instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>My implementation of httpclient occasionally throws an exception when calling doGetConnection(). However, I have the following timeout set</p> <pre><code>_moHttpClient.setHttpConnectionFactoryTimeout(30000); </code></pre> <p>it looks almost like my timeout is not being picked up. Is there anywhere else I need to set a timeout to ensure this behaviour does not re-occur</p>
<pre><code> HttpConnectionManagerParams cmparams = new HttpConnectionManagerParams(); cmparams.setSoTimeout(10000); cmparams.setTcpNoDelay(true); HttpConnectionManager manager = new SimpleHttpConnectionManager(); manager.setParams(cmparams); params = new HttpClientParams(); params.setSoTimeout(5000); client = new HttpClient(params, manager); </code></pre> <p>I wonder why I have two different SoTimeouts set. Maybe I was trying to find out which one was actually active, as I had the same problems as you when I used it.</p> <p>The above is in live code at our place right now, but I cannot say whether it works because it's correct, or because providence is smiling down on me (and the other end is usually always available).</p>
<blockquote> <p>cmparams.setSoTimeout(10000);</p> </blockquote> <p>This one is for all HttpClient by default.</p> <blockquote> <p>params.setSoTimeout(5000);</p> </blockquote> <p>And this one is for a particular httpclient.</p>
16,045
<p>Does anyone know of a simple web app that supports running ant tasks? Alternatively it could run command line programs. I need to allow the user to choose parameters for running the ant task. I effectively want a web interface to run the ant task and provide any parameters.</p> <p>I can write one but this is generic enough that it seems like there should already be a few standard packages that do this.</p>
<p>You could give <a href="http://www.anthillpro.com/html/products/anthillos/download.html" rel="nofollow noreferrer">Anthill</a> a shot. They have an open source version. This will periodically check your source code repository, and run a specified ant task any time the code base changes. You can also manually trigger builds.</p>
<p>You could put this in a PHP-file:</p> <pre><code>echo shell_exec('ant'); </code></pre> <p>It would run ant and return the output to the browser. </p>
29,776
<p>I am looking for an efficient means to partially check the integrity of "large" data sets over a slow transfer medium. This seems like a common problem as file sizes grow out of proportion to transfer rates. </p> <p>For example, for concrete numbers, a terabyte of data over USB2. Checking that this data is still valid by reading every byte into a hash or checksum requires a day, and increases the risk of drive failure. </p> <p>Instead, this code would need to verify random pieces of data, and provide a probability of validity based on the time available. If allowed to run sufficiently long, all blocks would be verified (base case of reading entire data set). </p> <p>Usage "story":<br> -- Data stored in large encrypted containers (sizes 1TB .. 1GB).<br> -- Each container redundantly backed up on multiple sets of drives at different locations.<br> -- Verification check must be done without knowledge of underlying data or keys. </p> <p>What failure modes the approach needs to DETECT:<br> - Storage transport failures (eg, controller drops portions of the physical address) - Sector errors (no data returned for a particular block)<br> - Single bit errors (non-ECC memory or caches) </p> <p>When errors are detected, the data is recovered from redundant storage. The verification data probably must be stored seperately. </p> <p>Since the goal is data integrity, the techniques from file-sharing networks don't seem applicable -- a "hash tree" would require full storage of the hashes at each node, which seems to be more storage than is necessary for scenarios without active attackers. </p> <ul> <li>How can I determine the tradeoff between storage space versus time to read the relevant blocks of the file? </li> <li>If a hash-tree/hash-list is the best way, how safe is it to store partial values of the hashes? </li> <li>Would some checksum or error correcting code be a better choice than hashes for equivalent protection? </li> </ul>
<p>Transfers take place over USB2, right? Therefore you should know that:</p> <ul> <li>USB communication are in form of packets, with a payload up to 1024 bytes for high-speed transfers and a 16-bit CRC.</li> <li>Each packet is acknowledged and potentially retransmitted.</li> </ul> <p>You have to take into account these information to deploy an algorithm that add some warrantees over those provided by CRC, otherwise it would be futile. If I remember well a 16-bit CRC can detects any single error bursts not longer than 16 bit and a fraction of those longer. </p> <p>You can start from wikipedia: <a href="http://en.wikipedia.org/wiki/USB2" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/USB2</a> and <a href="http://en.wikipedia.org/wiki/Cyclic_redundancy_check" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Cyclic_redundancy_check</a>.</p>
<p>How about storing hash or checksum values for runs of data within the file? You would then only have to read in a restricted portion of the data for a limited validation of the file content.</p>
40,231
<p>I've got an app that my client wants to open a kiosk window to ie on startup that goes to their corporate internet. Vb isn't my thing but they wanted it integrated into their current program and I figured it would be easy so I've got</p> <pre><code>Shell ("explorer.exe http://www.corporateintranet.com") </code></pre> <p>and command line thing that needs to be passed is -k</p> <p>Can't figure out where in the hell to drop this to make it work. Thanks in advance! :)</p>
<p>If you would like to use -k, you will probably want to call <code>iexplore.exe</code> instead of <code>explorer.exe</code>.</p>
<p>You have it right now but I think you are missing the closing quote after iexplore.exe</p> <p>You may also want to take out the [space]-k, set the zoom level to what will work for you in kiosk mode and then put the [space]-k back in. I am guessing there is a parameter or argument as they call it to pass the opening zoom level to iexplore but don't know how to do that yet.</p>
20,669
<p>I have an ASP.Net application which as desired feature, users would like to be able to take a screenshot. While I know this can be simulated, it would be really great to have a way to take a URL (or the current rendered page), and turn it into an image which can be stored on the server.</p> <p>Is this crazy? Is there a way to do it? If so, any references?</p>
<p>I can tell you right now that there is no way to do it from inside the browser, <strong>nor should there be</strong>. Imagine that your page embeds GMail in an iframe. You could then steal a screenshot of the person's GMail inbox!</p> <p>This could be made safe by having the browser "black out" all iframes and embeds that would violate cross-domain restrictions.</p> <p>You could certainly write an extension to do this, but be aware of the security considerations outlined above.</p> <p><strong>Update:</strong> You can use a canvas utility function to get a screenshot of a page on the <em>same origin</em> as your code. There's even a lib to allow you to do this: <a href="http://experiments.hertzen.com/jsfeedback/" rel="nofollow noreferrer">http://experiments.hertzen.com/jsfeedback/</a></p> <p>You can find other possible answers here: <a href="https://stackoverflow.com/questions/4912092/using-html5-canvas-javascript-to-take-screenshots">Using HTML5/Canvas/JavaScript to take screenshots</a></p>
<p>You could try a browser plugin like <a href="http://www.ie7pro.com/" rel="nofollow noreferrer">IE7 Pro</a> for Internet Explorer which allows you to save a screenshot of the current site to a file on disk. I'm sure there is a comparable plugin for FireFox out there as well.</p>
27,151
<p>Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing</p> <pre><code>$result = mysql_query("SELECT id FROM table"); $total = mysql_num_rows($result) </code></pre> <p>I was told this was not very efficient or fast, if you have a lot of records in the table. </p>
<p>You were told correctly. mysql can do this count for you which is much more efficient.</p> <pre><code>$result = mysql_query( "select count(id) as num_rows from table" ); $row = mysql_fetch_object( $result ); $total = $row-&gt;num_rows; </code></pre>
<p>Just wanted to note that <code>SHOW TABLE STATUS</code> returns a <code>Rows</code> column, though I can't speak to its efficiency. Some light Googling turns up reports of slowness in MySQL 4 over two years ago. Might make for interesting time trials.</p> <p>Also note the <a href="http://dev.mysql.com/doc/refman/5.0/en/show-table-status.html" rel="nofollow noreferrer">InnoDB caveat</a> regarding inaccurate counts.</p>
14,232
<p>Looking for sites which offer templates for creating styled table-based web page forms. </p> <p>Similar to css-based forms at: <a href="http://www.smashingmagazine.com/2006/11/11/css-based-forms-modern-solutions/" rel="nofollow noreferrer">http://www.smashingmagazine.com/2006/11/11/css-based-forms-modern-solutions/</a></p> <p>(please no css is better than tables discussions)</p>
<p>This is like asking for an example of GOTO statement best practices. Your just asking for trouble, no matter the intent!</p>
<p>I don't know about sites which offer templates, but 37 Signals use tables with their forms. Like <a href="https://signup.37signals.com/basecamp/Max/signup/new?source=google-basecamp" rel="nofollow noreferrer">this one</a>.</p>
23,363
<p>I'd like to call methods of my DAOs by AJAX. I'm quite new in that so I would like to ask what is the best way to do that. Is it possible to publish my beans as web services and call them with e.g. jQuery? I think it is not possible :) I've also read about Direct Web Remoting but I don't know which way to go... </p> <p>As I see, there are lot of experienced guys here so I think you can show me direction.. thanks in advance</p>
<p>Rather than exposing your DAO beans directly, you should create some Spring MVC controller beans, and call those from the client-side (using AJAX). Ideally, the controllers should not call the DAOs directly, but should instead call service beans (and the service beans should call the DAOs). One advantage of this approach is that you can define your service methods to be transactional, i.e. whenever a service method begins a transaction is started, and whenever a service method returns (without an exception) the transaction is committed. If the boundaries of your transactions are your DAO methods then it is not possible to wrap several database calls in a single transaction.</p> <p>Of course there's no reason why you need to use Spring MVC - any web framework would suffice.</p>
<p>You have to expose your DAO's or beans by means of http. Typically you create a layer above the DAO layer to expose your services through HTTP, which are available to any AJAX framework such as jQuery. What jQuery and other frameworks ends up doing is using a special asynchronous request called XMLHttpRequest and then parse the server response (can be anything, pure HTML, JSON, XML, etc) and process it.</p> <p>Here's a link I found that shows Spring &amp; DWR with AJAX: <a href="http://bram.jteam.nl/index.php/2007/01/31/spring-dwr-ajax-made-easy/" rel="nofollow noreferrer">Bram Smeets Blog</a>.</p>
22,841
<p>I was reading a MS Excel help article about pivotcache and wonder what they mean by <em>OLE DB and ODBC sources</em></p> <blockquote> <p>...You should use the CommandText property instead of the SQL property, which now exists primarily for compatibility with earlier versions of Microsoft Excel. If you use both properties, the CommandText property’s value takes precedence.</p> <p>For <strong>OLE DB sources</strong>, the CommandType property describes the value of the CommandText property.</p> <p>For <strong>ODBC sources</strong>, the CommandText property functions exactly like the SQL property, and setting the property causes the data to be refreshed...</p> </blockquote> <p>I really appreciate your short answers.</p>
<p>According to <a href="https://books.google.ca/books?id=JTKX7OUqCEMC" rel="nofollow noreferrer"><em>ADO: ActiveX Data Objects</em>, a book by Jason T. Roff, published by O'Reilly Media in 2001</a> (excellent diagram here), he says precisely what MOZILLA said.</p> <p>(directly from page 7 of that book)</p> <blockquote> <ul> <li>ODBC provides access only to relational databases</li></li> </ul> </blockquote> <ul> <li>OLE DB provides the following features</li> <li>Access to data regardless of its format or location</li></li> <li>Full access to ODBC data sources and ODBC drivers</li></li> </ul> <p>So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.</p> <p><img src="https://bobobobo.files.wordpress.com/2009/07/db-full-diagram.png" alt="alt text" /></p> <p><em>I'm not 100% sure this image is correct.</em> The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in <a href="https://books.google.ca/books?id=JTKX7OUqCEMC&pg=PA22#v=onepage&q&f=false" rel="nofollow noreferrer">this diagram</a> the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).</p>
<p>To know why M$ invents OLEDB, you can't compare OLEDB with ODBC. Instead, you should compare OLEDB with DAO,RDO, or ADO. The latter largely relies on SQL. However, OLEDB relies on COM. But ODBC is already there many years, so there's a OLEDB-ODBC bridges to remedy this. I think there's a big picture when M$ invents OLEDB.</p>
12,872
<p>I am using TortoiseSVN for my Subversion repository held on a USB drive. When I move from one PC to another, is there a way to automatically identify that files are out of date (without using the Check for Modifications menu). It would be nice just to be able to see that the folder on my hard drive did not match that of the repository, rather than seeing the green tick.</p>
<p>Try creating a file called <a href="http://dailycupoftech.com/usb-drive-autoruninf-tweaking/" rel="nofollow noreferrer">"autorun.inf"</a> in the root directory of your USB key. Then fill it with the following lines:</p> <pre><code>[autorun] open=CheckForMods.bat </code></pre> <p>Then create a <code>CheckForMods.bat</code> batch file in the root directory that does an <code>svn status -u</code>.</p>
<p>Create a batch file which automatically update your local working copy when the USB key is connected.</p>
26,939
<p>My local library has a 3D printer (Lulzbot Mini) for patrons to use. The prints are limited to 4 hours and if I go after work I really only have two hours before the Library closes. The software at the Library will give an estimated time, but I would like to be able to estimate the time before I get there.</p> <p>Currently I have been creating my designs in TinkerCad and then I export the STL file. From the STL file I can find online estimators that will tell me how much material but nothing that says how long it will take to print.</p> <p>Is there a way of calculating the estimated printing time from a STL file for a given printer?</p>
<p>There is no way to estimate the print time of an STL file directly.</p> <p>The print time is based on the number of instructions in the g-code file plus the time it takes to move the effector (the hot end) around the build area. The only way to compute that is to know what settings their slicer is using and then slice your stl the way they will; and this is assuming that you have the same slicer software. If you manage to do that, then the slicer software will give you an estimate.</p> <p>Here is what you would need to do:</p> <ol> <li><p>Get access to the same slicing software, and obtain a copy of the profile that they use to slice with. The nozzle diameter, feed rate, layer height, and infill settings will affect the print time.</p></li> <li><p>Import your stl into the sofware and "slice it" There will usually be a large button that is used to generate the g-code. There are quite a few slicers that will output the print time into the text of the g-code. They may also show the print time on the UI during slicing.</p></li> </ol> <p>alternatively: Email the stl to the staff at the library, and them to generate an estimate for you. They might just do it.</p> <p>However, that estimate could be incorrect. It will depend on the printer itself. As an example: the time it takes to heat the bed and the hot end is never included in the time estimate the slicer gives.</p>
<p>There is no way to estimate the print time of an STL file directly.</p> <p>The print time is based on the number of instructions in the g-code file plus the time it takes to move the effector (the hot end) around the build area. The only way to compute that is to know what settings their slicer is using and then slice your stl the way they will; and this is assuming that you have the same slicer software. If you manage to do that, then the slicer software will give you an estimate.</p> <p>Here is what you would need to do:</p> <ol> <li><p>Get access to the same slicing software, and obtain a copy of the profile that they use to slice with. The nozzle diameter, feed rate, layer height, and infill settings will affect the print time.</p></li> <li><p>Import your stl into the sofware and "slice it" There will usually be a large button that is used to generate the g-code. There are quite a few slicers that will output the print time into the text of the g-code. They may also show the print time on the UI during slicing.</p></li> </ol> <p>alternatively: Email the stl to the staff at the library, and them to generate an estimate for you. They might just do it.</p> <p>However, that estimate could be incorrect. It will depend on the printer itself. As an example: the time it takes to heat the bed and the hot end is never included in the time estimate the slicer gives.</p>
1,427
<p>I am looking at depency injection, I can see the benefits but I am having problems with the syntax it creates. I have this example</p> <pre><code>public class BusinessProducts { IDataContext _dx; BusinessProducts(IDataContext dx) { _dx = dx; } public List&lt;Product&gt; GetProducts() { return dx.GetProducts(); } } </code></pre> <p>The problem is that I don't want to write </p> <pre><code>BusinessProducts bp = new BusinessProducts(dataContextImplementation); </code></pre> <p>I would continue to write </p> <pre><code>BusinessProducts bp = new BusinessProducts(); </code></pre> <p>because I feel the first alternative just feels unatural. I dont want to know what the BusinessProduct "depends" on to get the products, also I feel it makes my code more unreadable. </p> <p>Is there any alternatives to this approach as I would like to keep my original syntax for creating objects but I would like to still be able to fake the dependencies when unit testing or is it this dependecy injection frameworks can do for me?</p> <p>I am coding in c# but alternatives from other languages is welcome</p>
<p>I use a factory for my context and inject it, providing a suitable default if the provided factory is null. I do this for two reasons. First, I use the data context as a unit of work scoped object so I need to be able to create them when needed, not keep one around. Second, I'm primarily using DI to increase testability, with decoupling only a secondary consideration.</p> <p>So my business products class would look like:</p> <pre><code>public class BusinessProducts { private IDataContextFactory DataContextFactory { get; set; } // my interface public BusinessProducts() : this(null) {} public BusinessProducts( IDataContextFactory factory ) { this.DataContext = factory ?? new BusinessProductsDataContextFactory(); } public void DoSomething() { using (DataContext dc = this.DataContextFactory().CreateDataContext()) { ... } } </code></pre> <p>An alternative to this would be to make the factory property publicly settable and inject an alternate factory by setting the property. Either way if you want to keep the null constructor, you'll need to provide a default.</p>
<p>you can also look at <a href="http://www.castleproject.org/container/index.html" rel="nofollow noreferrer">windsor</a> for IoC .</p>
46,837
<p>So which is better. Do we start letting Tests design our code. Do we start introducing constructor injection for dependencies just to make code testable? or do we use the "override" protected method &amp; sub class the class under test.</p>
<p>I generally think that testable code is good code. For code to be testable, you need better decoupling so each component can be tested in isolation with a test harness. However, there shouldn't be code in the implementation that is just used by the unit tests. </p> <p>Also, keep in mind that what you need to test is the public API of an object, not it's protected/private methods. Finding bugs in private/protected method should be what logging/debuggers are for. After all, a bug in those will also propagate up to the public methods. So as long as the public methods fulfill tests, the protected methods will be covered too.</p> <p>If you are using java, and have package scoped classes that implement public interfaces in the same package, I would put the unit tests in the same package in a separate folder to test those classes. You can also put unit tests in the same package as the tested class to test protected methods.</p>
<p>I mostly agree with Staale, well-designed code should be testable.<br> I don't use constructor injection or derive classes for testing. I believe using 'service locators' is the right way to do dependency injection.</p>
22,566
<p>Imagine you homebrew a custom gui framework that <em>doesn't</em> use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.</p> <p>So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the <code>InitialiseComponent()</code> method?</p>
<pre><code>select * from information_schema.tables WHERE OBJECTPROPERTY(OBJECT_ID(table_name),'IsMSShipped') =0 </code></pre> <p>Will exclude dt_properties and system tables</p> <p>add </p> <pre><code>where table_type = 'view' </code></pre> <p>if you just want the view</p>
<pre><code>select * from information_schema.tables where table_type = 'view' </code></pre>
5,325
<p>After installing the F# September CTP (1.9.6.2), Visual Studio 2008 frequently gives an error "Microsoft Visual C# IntelliSense has stopped working" which promptly crashes all of Visual Studio. I tried the tips mentioned in a <a href="https://stackoverflow.com/questions/178846/visual-studio-intellisense-stopped-working">similar SO article</a> such as "devenv.exe /ResetSettings", deleting the ncb file (which actually didn't exist), and installing the latest service pack (SP1) but no luck. Also tried reinstalling F#, nothing. This specifically happens in a C# unit test project that references my F# project and when I start to type things like [TestMethod] or "= new Tuple&lt;List&lt;int>,int,int> { Item1 = ". That's why I'm guessing it's related to F#. Incidentally I have ReSharper installed but disabled. Anyway, wondering if anyone else has had this problem and/or solved it. Otherwise any thoughts/ideas would be much appreciated.</p>
<p>Edit after reading some more of the source:</p> <p>You still need to subclass PatternLayout, but the method you want to override is ignoresThrowable(): it should return false, which will prevent the appender from writing the Throwable (it assumes that the layout has done so already).</p> <p>No way to specify this in the configuration: PatternLayout has a hardcoded "return true".</p>
<p>If you can change the source code, then another option is available for consideration.</p> <p>In my applications, I always and only log FATAL messages from my applications entry point (e.g., "main()"), since I only know that they are fatal if I am about to exit the application because of them.</p> <p>Therefore, in this one place (or handful if you have multiple application entry points), instantiate a Log4j Logger with a special class or MDC of "syslog" or similar. Upon catching a soon-to-be-FATAL error, log it in the usual way (for your other log files and such), but also invoke the fatal() method on this new "syslog" Logger with only the precise message that you want (such as only the exception class and message but without the stack trace). Then configure Log4j to direct only this "syslog" class or MDC to a newly-configured Appender that targets the SysLog.</p> <p>Ta-dum!</p>
45,351
<p>I'm dealing with huge glassfish log files (in windows, eek!) and well ... Wordpad isn't cutting it. </p> <p>Are there any tools out there that can handle these log files in a more intelligent manner? Functionality that would be welcome:</p> <ul> <li>View all lines of a certain log level (info, warning, severe)</li> <li>Show logs between two timestamps</li> <li>Occurency counter (this exception was thrown 99 times between time x and time y)</li> </ul>
<p>On Windows I'd still go perl or awk. Download and install <a href="http://cygwin.com" rel="nofollow noreferrer">cygwin</a>, then use awk or whatever you are familiar with. awk has the time functions needed for filtering, and features such as <code>getline</code> for log file navigation.</p> <p>Ex: Exception occurency count - all time</p> <pre><code>$ awk '/^java.*:\W/ {print $1}' server.log* |sort|uniq -c|sort -nr 60 javax.ejb.EJBException: 45 java.rmi.ServerException: 2 javax.persistence.PersistenceException: 2 javax.ejb.ObjectNotFoundException: 1 java.lang.Error: </code></pre>
<p>I use Excel for parsing log files. If you use tab-delimited log files this can work great. The filtering and sorting features of Excel lend themselves well to logfile analysis.</p>
16,896
<p>I'm slowly moving from PHP5 to Python on some personal projects, and I'm currently loving the experience. Before choosing to go down the Python route I looked at Ruby. What I did notice from the ruby community was that monkey-patching was both common and highly-regarded. I also came across a <strong>lot</strong> of horror stories regarding the trials of debugging ruby s/w because someone included a relatively harmless library to do a little job but which patched some heavily used core object without telling anyone. </p> <p>I chose Python for (among other reasons) its cleaner syntax and the fact that it could do everything Ruby can. Python is making OO click much better than PHP ever has, and I'm reading more and more on OO principles to enhance this better understanding.</p> <p>This evening I've been reading about <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" rel="noreferrer">Robert Martin's SOLID</a> principles:</p> <ul> <li><strong>S</strong>ingle responsibility principle,</li> <li><strong>O</strong>pen/closed principle,</li> <li><strong>L</strong>iskov substitution principle,</li> <li><strong>I</strong>nterface segregation principle, and</li> <li><strong>D</strong>ependency inversion principle</li> </ul> <p>I'm currently up to <strong>O</strong>: <em>SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION</em>. </p> <p>My head's in a spin over the conflict between ensuring consistency in OO design and the whole monkey-patching thing. I understand that its possible to do monkey-patching in Python. I also understand that being "pythonic" is to follow common, well-tested, oop best-practices &amp; principles.</p> <p><strong>What I'd like to know is the community's opinion on the two opposing subjects;</strong> how they interoperate, when its best to use one over the other, whether the monkey-patching should be done at all... hopefully you can provide a resolution to the matter for me.</p>
<p>There's a difference between monkey-patching (overwriting or modifying pre-existing methods) and simple addition of new methods. I think the latter is perfectly fine, and the former should be looked at suspiciously, but I'm still in favour of keeping it.</p> <p>I've encountered quite a few those problems where a third party extension monkeypatches the core libraries and breaks things, and they really do suck. Unfortunately, they all invariably seem stem from the the third party extension developers taking the path of least resistance, rather than thinking about how to actually build their solutions properly.<br> This sucks, but it's no more the fault of monkey patching than it's the fault of knife makers that people sometimes cut themselves.</p> <p>The only times I've ever seen legitimate need for monkey patching is to work around bugs in third party or core libraries. For this alone, it's priceless, and I really would be disappointed if they removed the ability to do it.</p> <p>Timeline of a bug in a C# program we had:</p> <ol> <li>Read strange bug reports and trace problem to a minor bug in a CLR library.</li> <li><em>Invest days coming up with a workaround involving catching exceptions in strange places and lots of hacks which compromises the code a lot</em></li> <li><em>Spend days extricating hacky workaround when Microsoft release a service pack</em></li> </ol> <p>Timeline of a bug in a rails program we had:</p> <ol> <li>Read strange bug reports and trace problem to a minor bug in a ruby standard library</li> <li><em>Spend 15 minutes performing minor monkey-patch to remove bug from ruby library, and place guards around it to trip if it's run on the wrong version of ruby.</em></li> <li>Carry on with normal coding.</li> <li><em>Simply delete monkeypatch later when next version of ruby is released.</em></li> </ol> <p>The bugfixing process looks similar, except with monkeypatching, it's a 15 minute solution, and a 5-second 'extraction' whereas without it, pain and suffering ensues.</p> <p>PS: The following example is "technically" monkeypatching, but is it "morally" monkeypatching? I'm not changing any behaviour - this is more or less just doing AOP in ruby...</p> <pre><code>class SomeClass alias original_dostuff dostuff def dostuff # extra stuff, eg logging, opening a transaction, etc original_dostuff end end </code></pre>
<p>Monkey-patching is just plain <em>wrong</em>, IMHO. I've not come across the open/closed principle you mention before, but it's a principle I've long held myself, I agree with it 100%. I think of monkey-patching as a code-smell on a larger scale, a coding-philosophy-smell, as it were.</p>
37,421
<p>I have compression enabled within IIS7 and it works as expected on all responses except for those constructed by ASP.NET AJAX. I have a web service that provides data to the client. When the web service is called directly, it is properly compressed. However, when it is called via ASP.NET AJAX, the JSON response is not compressed.</p> <p>How can I get ASP.NET AJAX to send its JSON response with GZip compression?</p>
<p>IIS7 uses the content-encoding to decide whether to compress the response (assuming of course that the browser can accept gzip). They're set in applicationHost.config, and by default the list is</p> <pre><code>&lt;dynamicTypes&gt; &lt;add mimeType="text/*" enabled="true" /&gt; &lt;add mimeType="message/*" enabled="true" /&gt; &lt;add mimeType="application/x-javascript" enabled="true" /&gt; &lt;add mimeType="*/*" enabled="false" /&gt; &lt;/dynamicTypes&gt; </code></pre> <p>If you call the web service directly, the XML response has a content-type of <code>text/xml</code>, which gets compressed. When called by AJAX, the JSON response has a content type of <code>application/json</code>, so it isn't compressed. Adding the following to applicationHost.config should fix that...</p> <pre><code> &lt;add mimeType="application/json" enabled="true" /&gt; </code></pre>
<p>Last I checked, the gzipping was something that IIS does (when setup correctly) - and of course when the browser sends the required headers</p>
30,277
<p>Is there an easy way to discover a File's creation time with Java? The File class only has a method to get the "last modified" time. According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.</p> <p>The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time. I guess this works, I only need to support Windows, but it seems very error prone to me.</p> <p>Are there any third party libraries that provide the info I need?</p> <p><strong>Update:</strong> In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a good choice for anyone else that has this problem. </p>
<p>With the release of Java 7 there is a built-in way to do this:</p> <pre><code>Path path = Paths.get("path/to/file"); BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class); FileTime creationTime = attributes.creationTime(); </code></pre> <p>It is important to note that not all operating systems provide this information. I believe in those instances this returns the mtime which is the last modified time.</p> <p>Windows does provide creation time.</p>
<p>This is a basic example in <code>Java</code>, using <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/attribute/BasicFileAttributes.html" rel="nofollow"><strong><code>BasicFileAttributes</code></strong></a> class:</p> <pre><code> Path path = Paths.get("C:\\Users\\jorgesys\\workspaceJava\\myfile.txt"); BasicFileAttributes attr; try { attr = Files.readAttributes(path, BasicFileAttributes.class); System.out.println("File creation time: " + attr.creationTime()); } catch (IOException e) { System.out.println("oops un error! " + e.getMessage()); } </code></pre>
5,253
<p>I've got 2 remote databases as part of a query </p> <pre><code>select p.ID,p.ProjectCode_VC,p.Name_VC,v.* FROM [serverB].Projects.dbo.Projects_T p LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC = v.PROJ_CODE </code></pre> <p>The problem is that serverA uses collation <code>Latin1_General_BIN</code> and serverB uses <code>Latin1_General_CP1_CP_AS</code> and the query refuses to run. </p> <p>Both servers are SQL 2000 servers. Both databases are set in stone so I cannot change their collations, unfortunately. </p> <p>Is there anyway you guys know how to get this to work?</p> <p><strong>Update:</strong> I found an alternative solution. In the Linked Server Properties, you can specify the linked server's collation there.</p>
<p>Just add the collation to your select, like:</p> <pre><code>select p.ID, p.ProjectCode_VC, p.Name_VC, v.* FROM [serverB].Projects.dbo.Projects_T p LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC collate Latin1_General_Bin = v.PROJ_CODE </code></pre> <p>or the other way around. So "convert" one of the collations to the other.</p>
<p>Or you can use a more generic query like this:</p> <pre><code>select * from profile, userinfo where profile.custid collate database_default = userinfo.custid collate database_default </code></pre>
32,316
<p>I've downloaded the svntask for ant from tigris.org, so it is the "official" one.</p> <p>I have a simple task to update my entire project</p> <pre><code>&lt;target name="prepare"&gt; &lt;svn username="user" password="pass"&gt; &lt;update&gt; &lt;fileset dir="."/&gt; &lt;/update&gt; &lt;/svn&gt; &lt;/target&gt; </code></pre> <p>Running this task took about 2 hours.</p> <p>Running a <code>svn update</code> on the command line took about 5 seconds.</p> <p>(in both cases, there were no updates to bring down from the server)</p> <p>I've also tried chaning the method that svntask uses to interface with subversion, I've tried both the svnkit method and the command line method.</p> <p>Any ideas why this may be taking so long? Obviously this is unacceptably slow.</p> <p>Thanks</p>
<p>By using the nested <code>&lt;fileset&gt;</code> the command ends up calling <code>update</code> for every file in the current directory hierarchy. That's probably why it takes two hours.</p> <p>Try using the <code>dir</code> attribute of the <code>update</code> task:</p> <pre><code> &lt;svn username="user" password="pass"&gt; &lt;update dir="."/&gt; &lt;/svn&gt; </code></pre> <p>And, if that doesn't work, turn on <code>-verbose</code> or <code>-debug</code> and see if you can get more information about what is happening during the task.</p>
<p>So if you just run "ant prepare" it takes 2 hrs? Or is this 2 hr duration only under special conditions like your build machine?</p> <p>Have you tried using the task for comparison, to try and isolate if it is Ant vs. the particular task?</p>
49,520
<p>I'm looking to replace a couple of machines in the office with a more powerful multi-processor machine running either VMware or Microsoft's Hyper-V with a view to hosting a mix of Windows Server 2003, Windows Server 2008 and Linux operating systems. The machines are used mainly for testing ASP.Net or Perl web sites. I don't need advanced features like live migration of running systems but it would be useful to be able to restore a machine to a known state. Performance is not really a big issue either unless one is noticeable faster than the other.</p> <p>My question is: Should I play safe and go with VMware or is Hyper-V mature enough to be a candidate?</p>
<p>VMware did recently release a free version of ESXi recently.</p> <p>VMware has a few advantages:<br> 1. VMware virtual machines are portable across different types of hardware. IIRC, Hyper-V uses the drivers from the Host OS.<br> 2. VMware virtual machines are portable across different VMware products (although you may need to use their converter tool to go from some hosted virtual machines to ESX or ESXi).<br> 3. The VMware platforms have been in use much longer, and are quite mature products and generally better-known for troubleshooting.</p> <p>With VMware, you could develop and test a virtual machine on your local system using VMware Workstation, Fusion, Server, or Player, and then deploy it to a production server later. With Hyper-V, I believe you would have to build the virtual machine on the target box for best results. If performance isn't really that big of an issue, then VMware Server may be the best option, for it can run most .vmx machines directly and is generally a bit easier to manage; if performance becomes critical, you still have the ESX or ESXi upgrade option that you can use those same virtual machines with.</p> <p>This entry talks about how Virtual Server machines will not run on Hyper-V:<br> <a href="http://blogs.technet.com/jhoward/archive/2008/02/28/are-vhds-compatible-between-hyper-v-and-virtual-server-and-virtual-pc.aspx" rel="noreferrer">http://blogs.technet.com/jhoward/archive/2008/02/28/are-vhds-compatible-between-hyper-v-and-virtual-server-and-virtual-pc.aspx</a></p>
<p><em>Necros the thread</em> Just wanted to add my 2c since the last post has been a while.</p> <p>I have been using VMWare Server since version 1.6 all the way up to 2.0.</p> <p>Just out of curiosity, I tried out Hyper-V, and there's a real definitive performance gain. Hyper-V is plain faster.</p> <p>Switched over 2 months ago and never looked back.</p>
5,923
<p>I'm currently working on a project that depends on me providing a path to a file (eg. <code>C:\Path.pth</code>). Now, I had everything working yesterday by calling my <code>std::string</code> with:</p> <pre><code>std::string path(`"C:\\Path.pth`"); </code></pre> <p>But now it doesn't work. It throws a <code>bad_alloc</code>. Seems like the '<code>\</code>' character is the problem. I even tried using <code>\x5C</code> as the ascii-value of it instead, but same result.</p> <p>Now, my question is, is it possible that I have screwed up some <code>#define</code>, some compiler-option or something else "non-code" that could've caused this? I'm using VS 2005.</p> <p>Any help would be much appreciated</p> <hr> <p>PierreBdR</p> <p>.. That sounds very likely. Or at least, it have to :P</p> <p>Since no one have mentioned some kind of /SetStringCharSize:2bit-compiler option, I think it's safe to assume that my code has to mess something up, somewhere, and that it's not just a silly compiler-option (or similar) that's wrong..</p>
<p>As your error suggest, the problem is due to <strong>memory allocation</strong> (i.e. the bad_alloc exception).</p> <p>So either you have no more memory (unlikely) or you have a buffer overrun somewhere before (quite likely in my opinion) or some other memory issues like double free.</p> <p>In short, you do something that messes up the memory management layout (i.e. all these information in between allocated blocks). Check on what happens <strong>before</strong> this call.</p>
<p>Assuming your double-backslash is correct, I'd guess you're running on Vista?</p> <p>Vista won't let your write into the root directory of the C drive by default. Try one of the following:</p> <ul> <li>Turn off UAC, or</li> <li>Run your application as "Administrator", or</li> <li>Write into a subdirectory.</li> </ul>
21,414
<p>Does anyone have a suggestion for where to find archives or collections of everyday English text for use in a small corpus? I have been using Gutenberg Project books for a working prototype, and would like to incorporate more contemporary language. A <a href="https://stackoverflow.com/questions/122595/nlp-qualitatively-positive-vs-negative-sentence#126378">recent answer</a> here pointed indirectly to a great <a href="http://us.imdb.com/Reviews/" rel="nofollow noreferrer">archive of usenet movie reviews</a>, which hadn't occurred to me, and is very good. For this particular program technical usenet archives or programming mailing lists would tilt the results and be hard to analyze, but any kind of general blog text, or chat transcripts, or anything that may have been useful to others, would be very helpful. Also, a partial or downloadable research corpus that isn't too marked-up, or some heuristic for finding an appropriate subset of wikipedia articles, or any other idea, is very appreciated.</p> <p>(BTW, I am being a good citizen w/r/t downloading, using a deliberately slow script that is not demanding on servers hosting such material, in case you perceive a moral hazard in pointing me to something enormous.)</p> <p><strong>UPDATE</strong>: User S0rin points out that wikipedia requests no crawling and provides <a href="http://en.wikipedia.org/wiki/Special:Export" rel="nofollow noreferrer">this export tool</a> instead. Project Gutenberg has a policy specified <a href="http://www.gutenberg.org/wiki/Gutenberg:Information_About_Robot_Access_to_our_Pages" rel="nofollow noreferrer">here</a>, bottom line, try not to crawl, but if you need to: "Configure your robot to wait at least 2 seconds between requests."</p> <p><strong>UPDATE 2</strong> The wikpedia dumps are the way to go, thanks to the answerers who pointed them out. I ended up using the English version from here: <a href="http://download.wikimedia.org/enwiki/20090306/" rel="nofollow noreferrer">http://download.wikimedia.org/enwiki/20090306/</a> , and a Spanish dump about half the size. They are some work to clean up, but well worth it, and they contain a lot of useful data in the links.</p> <hr>
<ul> <li>Use the <a href="http://en.wikipedia.org/wiki/Wikipedia:Database_download" rel="noreferrer">Wikipedia dumps</a> <ul> <li>needs lots of cleanup</li> </ul></li> <li>See if anything in <a href="http://prdownloads.sourceforge.net/nltk/nltk-data-0.9.5.zip" rel="noreferrer">nltk-data</a> helps you <ul> <li>the corpora are usually quite small</li> </ul></li> <li>the <a href="http://wacky.sslmit.unibo.it/doku.php?id=start" rel="noreferrer">Wacky</a> people have some free corpora <ul> <li>tagged</li> <li>you can spider your own corpus using their toolkit</li> </ul></li> <li><a href="http://www.statmt.org/europarl/" rel="noreferrer">Europarl</a> is free and the basis of pretty much every academic MT system <ul> <li>spoken language, translated</li> </ul></li> <li>The <a href="http://trec.nist.gov/data/reuters/reuters.html" rel="noreferrer">Reuters Corpora</a> are free of charge, but only available on CD</li> </ul> <p>You can always get your own, but be warned: HTML pages often need heavy cleanup, so restrict yourself to RSS feeds.</p> <p>If you do this commercially, the <a href="http://www.ldc.upenn.edu/" rel="noreferrer">LDC</a> might be a viable alternative.</p>
<p>You've covered the obvious ones. The only other areas that I can think of too supplement:</p> <p>1) News articles / blogs.</p> <p>2) Magazines are posting a lot of free material online, and you can get a good cross section of topics.</p>
16,615
<p><a href="https://stackoverflow.com/questions/48496/how-to-teach-a-crash-course-on-c">This post</a> reference to the One Definition Rule.</p> <p><a href="http://en.wikipedia.org/wiki/One_Definition_Rule" rel="nofollow noreferrer">Wikipedia is pretty bad on explaining how to implement it</a></p> <p>Where can I find good ressources about guidelines to follow in C++ .NET?</p>
<p>The one definition rule basically means that a variable/function can only be located at one place in address space of the compiled executable. One way to think of it is while you compile, there is an array of memory to be used in the compiled program (object code), and a lookup table to reference variable/function locations. This is done on a per process level. Suppose that the following is a simple program: </p> <p>file1.cpp</p> <pre><code>int square(int x); // this is a declaration extern int someVariable; // this is a declration void square(int x) // this is a definition { return x * someVariable; } </code></pre> <p>file2.cpp</p> <pre><code>int square(int x); // this is a declaration int someVariable; // this is a definition void main() { someVariable = 12; someVariable = square(4); } </code></pre> <p>When the compiler starts compiling the object code, it reads in the declarations, and puts thing in its table. AT the end of compiling file1.cpp, it will end up with something like this:</p> <pre><code>declarations: square (XX): function that returns int, and takes a single int as parameter [4 bytes] someVariable (YY): integer [4 bytes] data: 12 34 56 78 aa XX XX XX XX ab cd definition: square: starts at address 0 </code></pre> <p>This assumes that the function gets compiled to those particular assembly instructions. At linker time, XX XX XX XX will get replaced by the address of someVariable.</p> <p>File2 ends up something like:</p> <pre><code>declarations: square (XX): function that returns int, and takes a single int as parameter [4 bytes] someVariable (YY): integer [4 bytes] data: 00 00 00 00 12 34 56 78 12 34 56 YY YY YY YY 23 21 definitions: someVariable: starts at address 0 main: starts at address 4 </code></pre> <p>And in this case, the YY will be replaced by the address of square.</p> <p>That's where the linker comes into play. The linker's job is to go through the list, and build up a table of where everything is in the address space of the program at compile time. However, there is a problem if two object files have the same definition of a variable when it tries to link. If there were two definitions of someVariable in the above example, then it wouldn't know what to replace YY with. Likewise, if there's <em>no</em> definition, then you get ugly linker errors.</p> <p>The "solution" to the rule is to partition your file such that you have definitions only in .cpp files, and have declarations of things in your .h files, so the example above would become:</p> <p>file1.cpp</p> <pre><code>#include "file2.h" void square(int x) // this is a definition { return x * someVariable; } </code></pre> <p>file1.h</p> <pre><code>int square(int x); // this is a declaration </code></pre> <p>file2.cpp</p> <pre><code>#include "file1.h" int someVariable; // this is a definition void main() { someVariable = 12; someVariable = square(4); } </code></pre> <p>file2.h</p> <pre><code>extern int someVariable; </code></pre> <p>Note that this is an incredibly simple example, and that it doesn't really apply in .NET since there isn't a concept of a distinction between a declaration and definition.</p>
<p>The easiest way to comply with the one definition rule is to put the definition in a .cpp file instead of the header.</p> <p>People sometimes put definitions into headers using macros and/or preprocessor conditionals to make the object or function defined only in one compilation unit. But it's easier usually (and certainly more understandable) to just put the definition in a .cpp file.</p>
49,781
<p>It's surprising how difficult it is to find a simple, concise answer to this question:</p> <ol> <li>I have a file, foo.zip, on my website</li> <li>What can I do to find out how many people have accessed this file?</li> <li>I could use Tomcat calls if necessary</li> </ol>
<p>Or you could parse the log file if you don't need the data in realtime.</p> <pre><code>grep foo.zip /path/to/access.log | grep 200 | wc -l </code></pre> <p>In reply to comment:</p> <p>The log file also contains bytes downloaded, but as someone else pointed out, this may not reflect the correct count if a user cancels the download on the client side.</p>
<p>Use the logs--each GET request for the file is another download (unless the visitor stopped the download partway through for some reason).</p>
19,113
<p>Everyone has this huge massively parallelized supercomputer on their desktop in the form of a graphics card GPU.</p> <ul> <li>What is the "hello world" equivalent of the GPU community?</li> <li>What do I do, where do I go, to get started programming the GPU for the major GPU vendors?</li> </ul> <p>-Adam</p>
<p>Check out CUDA by NVidia, IMO it's the easiest platform to do GPU programming. There are tons of cool materials to read. <a href="http://www.nvidia.com/object/cuda_home.html" rel="noreferrer">http://www.nvidia.com/object/cuda_home.html</a> <br /></p> <p>Hello world would be to do any kind of calculation using GPU.</p> <p>Hope that helps.</p>
<p>Try <a href="http://blog.beef.de/thesis/" rel="nofollow noreferrer">GPU++</a> and <a href="http://libsh.org/wiki/index.php/How_Sh_Works" rel="nofollow noreferrer">libSh</a></p> <p>LibSh link has a good description of how they bound the programming language to the graphics primitives (and obviously, the primitives themselves), and GPU++ describes what its all about, both with code examples.</p>
27,075
<p>I have an ASP.NET application which tracks statistics by creating and writing to custom performance counters. Occasionally, I see in the error logs that indicate that the counters have failed to open because they had already been used in the current process. I presume this is due to my .NET appdomain having been reset within the same w3wp.exe process. How can I avoid these errors and re-establish a connection to my performance counters when my app domain has been recycled?</p> <p>Counter construction:</p> <pre><code>PerformanceCounter pc = new PerformanceCounter(); pc.CategoryName = category_name; pc.CounterName = counter_name; pc.ReadOnly = false; pc.InstanceLifetime = PerformanceCounterInstanceLifetime.Process; pc.InstanceName = instance_name; </code></pre> <p>Counter usage:</p> <pre><code>pc.Increment() </code></pre> <p>[Update on 3/26/09] The error message received is:</p> <p>Instance '_lm_w3svc_1_root_myapp' already exists with a lifetime of Process. It cannot be recreated or reused until it has been removed or until the process using it has exited. already exists with a lifetime of Process.</p> <p>I tried to replicate the exception in a console application by initializing the performance counters and writing to one of them in a transient AppDomain. I then unload the AppDomain and do it again in a second Appdomain (same process). They both succeed. I'm unsure now exactly what the cause of this is, my assumption about AppDomain recycling in ASP.NET seems to be false.</p>
<p>IIRC, IIS will not make sure that your first AppDomain is closed before it starts the second, particularly when you are recyclying it manually or automatically. I believe that when a recycle is initiated, the second AppDomain is instantiated first, and once that succeeds, new incoming requests are directed towards it, and then IIS waits for the first AppDomain (the one being shut down) to finish process any requests it has.</p> <p>The upshot is that there's an overlap where two AppDomains are in existence, both with the same value for <code>instance_name</code>.</p> <p>However, not all is solved. I have corrected this problem in my code by including the process ID as part of the instance name. But it seems to have introduced another problem -- what I thought was a process-scoped performance counter never seems to go away without rebooting the computer. (That may be a bug on my part, so YMMV).</p> <p>This is the routine I have for creating an instance name:</p> <pre><code> private static string GetFriendlyInstanceName() { string friendlyName = AppDomain.CurrentDomain.FriendlyName; int dashPosition = friendlyName.IndexOf('-'); if (dashPosition &gt; 0) { friendlyName = friendlyName.Substring(0, dashPosition); } friendlyName = friendlyName.TrimStart('_'); string processID = Process.GetCurrentProcess().Id.ToString(); string processName = Process.GetCurrentProcess().ProcessName; string instanceName = processName + " " + processID + " " + friendlyName.Replace('/', '_').Trim('_').Trim(); return instanceName; } </code></pre>
<p>I am no expert with custom counters, but based on the info you provided, I think it is worth a shot considering the possibility of some code trying to use the counters when the add domain is about to be recycled. Look for the use of the counter in anything related to dispose or destructor.</p>
44,740
<p>I've been looking for some good genetic programming examples for C#. Anyone knows of good online/book resources? Wonder if there is a C# library out there for Evolutionary/Genetic programming?</p>
<p>After developing <a href="http://code.google.com/p/evo-lisa-clone/" rel="noreferrer">my own Genetic Programming didactic application</a>, I found a complete Genetic Programming Framework called <a href="http://code.google.com/p/aforge/source/browse/#svn/trunk/Sources/Genetic" rel="noreferrer">AForge.NET Genetics</a>. It's a part of the <a href="http://code.google.com/p/aforge/" rel="noreferrer">Aforge.NET library</a>. It's licensed under LGPL.</p>
<p>I maintain a port of ECJ in C#. It's great.</p>
3,488
<p>What's the shortest way to get an Iterator over a range of Integers in Java? In other words, implement the following:</p> <pre><code>/** * Returns an Iterator over the integers from first to first+count. */ Iterator&lt;Integer&gt; iterator(Integer first, Integer count); </code></pre> <p>Something like</p> <pre><code>(first..first+count).iterator() </code></pre>
<p>This implementation does not have a memory footprint.</p> <pre><code>/** * @param begin inclusive * @param end exclusive * @return list of integers from begin to end */ public static List&lt;Integer&gt; range(final int begin, final int end) { return new AbstractList&lt;Integer&gt;() { @Override public Integer get(int index) { return begin + index; } @Override public int size() { return end - begin; } }; } </code></pre> <h2>Edit:</h2> <p>In Java 8 and later you can simply say:</p> <pre><code>IntStream.range(begin, end).iterator() // returns PrimitiveIterator.OfInt </code></pre> <p>or if you need the boxed version:</p> <pre><code>IntStream.range(begin, end).boxed().iterator() // returns Iterator&lt;Integer&gt; </code></pre>
<p>It's generally considered good style to pass around <code>Collection</code> and friends instead of <code>Iterator</code> (see <a href="http://java.sun.com/j2se/1.4.2/docs/guide/collections/designfaq.html#8" rel="nofollow noreferrer">this FAQ entry</a>), so I'd recommend something like</p> <pre><code>public final class IntegerRange implements Set&lt;Integer&gt; { final LinkedHashSet&lt;Integer&gt; backingList; public IntegerRange(final int start, final int count) { backingList = new LinkedHashSet(count, 1.0f); for (int i=0; i &lt; count; i++) { backingList.set(i, start + i); } } /** Insert a bunch of delegation methods here */ } </code></pre> <p>and then just use <code>.iterator()</code> when you need to pass an <code>Iterator</code> to whatever framework you're using.</p> <p>UPDATE: Obviously, this code isn't lazy. If you can't afford the extra memory overhead of storing (potentially) 2^32-1 <code>Integer</code>s, you should use a different solution. Also, nothing about the type guarantees the range will be sorted (even though it is, based on the implementation). If you need to guarantee sorting, you could look into implementing <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/SortedSet.html" rel="nofollow noreferrer">SortedSet</a> and backing it with a <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/TreeSet.html" rel="nofollow noreferrer">TreeSet</a>, but it will take longer to build the range. Honestly, if you are that concerned with getting the details right, it might be worth your effort to look for a library. Tapestry has an <a href="http://tapestry.apache.org/tapestry5/apidocs/org/apache/tapestry5/internal/util/IntegerRange.html" rel="nofollow noreferrer">internal version</a>, for instance.</p>
48,485
<p>Sorry for the basic question - I'm a .NET developer and don't have much experience with LAMP setups.</p> <p>I have a PHP site that will allow uploads to a specific folder. I have been told that this folder needs to be owned by the webserver user for the upload process to work, so I created the folder and then set permissions as such:</p> <pre><code>chown apache:apache -R uploads/ chmod 755 -R uploads/ </code></pre> <p>The only problem now is that the FTP user can not modify the uploaded files at all.</p> <p>Is there a permission setting that will allow me to still upload files and then modify them later as a user other than the webserver user?</p>
<p>You can create a new group with both the apache user and FTP user as members and then make the permission on the upload folder 775. This should give both the apache and FTP users the ability to write to the files in the folder but keep everyone else from modifying them.</p>
<p>Based on the answer from <code>@Ryan Ahearn</code>, following is what I did on <code>Ubuntu</code> 16.04 to create a user <code>front</code> that only has permission for nginx's web dir <code>/var/www/html</code>.</p> <p><strong>Steps:</strong></p> <pre> * pre-steps: * basic prepare of server, * create user 'dev' which will be the owner of "/var/www/html", * * install nginx, * * * create user 'front' sudo useradd -d /home/front -s /bin/bash front sudo passwd front # create home folder, if not exists yet, sudo mkdir /home/front # set owner of new home folder, sudo chown -R front:front /home/front # switch to user, su - front # copy .bashrc, if not exists yet, cp /etc/skel/.bashrc ~front/ cp /etc/skel/.profile ~front/ # enable color, vi ~front/.bashrc # uncomment the line start with "force_color_prompt", # exit user exit * * add to group 'dev', sudo usermod -a -G dev front * change owner of web dir, sudo chown -R dev:dev /var/www * change permission of web dir, chmod 775 $(find /var/www/html -type d) chmod 664 $(find /var/www/html -type f) * * re-login as 'front' to make group take effect, * * test * * ok * </pre>
3,219
<p>I'm implementing a document server. Currently, if two users open the same document, then modify it and save the changes, the document's state will be undefined (either the first user's changes are saved permanently, or the second's). This is entirely unsatisfactory. I considered two possibilities to solve this problem:</p> <p>The first is to lock the document when it is opened by someone the first time, and unlock it when it is closed. But if the network connection to the server is suddenly interrupted, the document would stay in a forever-locked state. The obvious solution is to send regular pings to the server. If the server doesn't receive K pings in a row (K > 1) from a particular client, documents locked by this client are unlocked. If that client re-appears, documents are locked again, if someone hadn't already locked them. This could also help if the client application (running in web browser) is terminated unexpectedly, making it impossible to send a 'quitting, unlock my documents' signal to the server.</p> <p>The second is to store multiple versions of the same document saved by different users. If changes to the document are made in rapid succession, the system would offer either to merge versions or to select a preferred version. To optimize storage space, only document diffs should be kept (just like source control software).</p> <p>What method should I choose, taking into consideration that the connection to the server might <em>sometimes</em> be slow and unresponsive? How should the parameters (ping interval, rapid succession interval) be determined?</p> <p>P.S. Unfortunately, I can't store the documents in a database.</p>
<p>My suggestion would be something like your first one. When the first user (Bob) opens the document, he acquires a lock so that other users can only read the current document. If the user saves the document while he is using it, he keeps the lock. Only when he exits the document, it is unlocked and other people can edit it. </p> <p>If the second user (Kate) opens the document while Bob has the lock on it, Kate will get a message saying the document is uneditable but she can read it until it the lock has been released.</p> <p>So what happens when Bob acquires the lock, maybe saves the document once or twice but then exits the application leaving the lock hanging? </p> <p>As you said yourself, requiring the client with the lock to send pings at a certain frequency is probably the best option. If you don't get a ping from the client for a set amount of time, this effectively means his client is not responding anymore. If this is a web application you can use javascript for the pings. The document that was last saved releases its lock and Kate can now acquire it. </p> <p>A ping can contain the name of the document that the client has a lock on, and the server can calculate when the last ping for that document was received.</p>
<p>Currently documents are published by a limited group of people, each of them working on a separate subject. So, the inconvenience introduced by locks is minimized. People mostly extend existing documents and correct mistakes in them.</p> <p>Speaking about the pessimistic model, the 'left client connected for N days' scenario could be avoided by setting lock expire date to, say, one day before lock start date. Because documents edited are by no means mission critical, and are modified by multiple users quite rarely, that could be enough.</p> <p>Now consider the optimistic model. How should the differences be detected, if the documents have some regular (say, hierarchical) structure? If not? What are the chances of successful automatic merge in these cases?</p> <p>The situation becomes more complicated, because some of the documents (edited by the 'admins' user group) contain important configuration information (document global index, user roles, etc.). To my mind, locks are more advantageous for precisely this kind of information, because it's not changed on everyday basis. So some hybrid solution might be acceptable.</p> <p>What do you think?</p>
3,107
<p>I can find tutorials about mapping textures to polygons specifying vertices etc. but nothing regarding how to apply a texture to a cube (or other stuff) drawn with glut (glutSolidCube).</p> <p>I am doing something like:</p> <pre><code>glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, decal); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, nearest); glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, nearest); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, 4, myImageWidth, myImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, (GLvoid *)myImage); //... glEnable(GL_TEXTURE_2D); //now draw the cube glutSolidCube(N); </code></pre> <p>Doing this I get the texture to apply to the cube but the whole cube gets the color of the first byte in the texture!</p> <p>Is there any way of mapping a texture to a solid cube (and other solids) when using glutSolidCube?</p>
<p>No, since <code>glutSolidCube()</code> does not generate texture coordinates. Fortunately, though, <code>glutSolidCube()</code> is easy to implement yourself and add texture coordinates. Here's the source code to <code>glutSolidCube()</code> and associated functions, from <a href="http://www.opengl.org/resources/libraries/glut/" rel="noreferrer"><a href="http://www.opengl.org/resources/libraries/glut/" rel="noreferrer">http://www.opengl.org/resources/libraries/glut/</a></a>:</p> <pre><code>/* Copyright (c) Mark J. Kilgard, 1994, 1997. */ /** (c) Copyright 1993, Silicon Graphics, Inc. ALL RIGHTS RESERVED Permission to use, copy, modify, and distribute this software for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both the copyright notice and this permission notice appear in supporting documentation, and that the name of Silicon Graphics, Inc. not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. THE MATERIAL EMBODIED ON THIS SOFTWARE IS PROVIDED TO YOU "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON GRAPHICS, INC. BE LIABLE TO YOU OR ANYONE ELSE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER, INCLUDING WITHOUT LIMITATION, LOSS OF PROFIT, LOSS OF USE, SAVINGS OR REVENUE, OR THE CLAIMS OF THIRD PARTIES, WHETHER OR NOT SILICON GRAPHICS, INC. HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS, HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE POSSESSION, USE OR PERFORMANCE OF THIS SOFTWARE. US Government Users Restricted Rights Use, duplication, or disclosure by the Government is subject to restrictions set forth in FAR 52.227.19(c)(2) or subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 and/or in similar or successor clauses in the FAR or the DOD or NASA FAR Supplement. Unpublished-- rights reserved under the copyright laws of the United States. Contractor/manufacturer is Silicon Graphics, Inc., 2011 N. Shoreline Blvd., Mountain View, CA 94039-7311. OpenGL(TM) is a trademark of Silicon Graphics, Inc. */ static void drawBox(GLfloat size, GLenum type) { static GLfloat n[6][3] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static GLint faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v[8][3]; GLint i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -size / 2; v[4][0] = v[5][0] = v[6][0] = v[7][0] = size / 2; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -size / 2; v[2][1] = v[3][1] = v[6][1] = v[7][1] = size / 2; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -size / 2; v[1][2] = v[2][2] = v[5][2] = v[6][2] = size / 2; for (i = 5; i &gt;= 0; i--) { glBegin(type); glNormal3fv(&amp;n[i][0]); glVertex3fv(&amp;v[faces[i][0]][0]); glVertex3fv(&amp;v[faces[i][1]][0]); glVertex3fv(&amp;v[faces[i][2]][0]); glVertex3fv(&amp;v[faces[i][3]][0]); glEnd(); } } void APIENTRY glutSolidCube(GLdouble size) { drawBox(size, GL_QUADS); } </code></pre> <p>Just add in some calls to the <a href="http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texcoord.html" rel="noreferrer">glTexCoord*</a> family of functions. <a href="http://nehe.gamedev.net/data/lessons/lesson.asp?lesson=06" rel="noreferrer">NeHe</a> has a good tutorial on how to get started with texture mapping with OpenGL.</p>
<p>In case you want to avoid <code>glBegin\End</code> and <code>GL_TEXTURE_GEN_S\T</code> per modern design</p> <pre><code> void drawBox() { static glm::vec3 n[6] = { {-1.0, 0.0, 0.0}, {0.0, 1.0, 0.0}, {1.0, 0.0, 0.0}, {0.0, -1.0, 0.0}, {0.0, 0.0, 1.0}, {0.0, 0.0, -1.0} }; static int faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; glm::vec3 v[8]; int i; v[0][0] = v[1][0] = v[2][0] = v[3][0] = -1; v[4][0] = v[5][0] = v[6][0] = v[7][0] = 1; v[0][1] = v[1][1] = v[4][1] = v[5][1] = -1; v[2][1] = v[3][1] = v[6][1] = v[7][1] = 1; v[0][2] = v[3][2] = v[4][2] = v[7][2] = -1; v[1][2] = v[2][2] = v[5][2] = v[6][2] = 1; auto&amp; surface = surfaces[0]; for ( i = 0; i &lt; 6; i++ ) { for ( int j = 0; j &lt; 4; j++ ) surface.normals.push_back( n[i] ); auto i1 = i * 4; surface.indices.push_back( i1 + 0 ); surface.indices.push_back( i1 + 1 ); surface.indices.push_back( i1 + 3 ); surface.indices.push_back( i1 + 1 ); surface.indices.push_back( i1 + 2 ); surface.indices.push_back( i1 + 3 ); surface.vertices.push_back( v[faces[i][0]] ); surface.vertices.push_back( v[faces[i][1]] ); surface.vertices.push_back( v[faces[i][2]] ); surface.vertices.push_back( v[faces[i][3]] ); surface.texCoords.push_back( { 0, 0 } ); surface.texCoords.push_back( { 0, 1 } ); surface.texCoords.push_back( { 1, 0 } ); surface.texCoords.push_back( { 1, 1 } ); } } </code></pre>
42,371
<p>I guess it should be a common technique, However, I tried the following two options:</p> <p>1) Using my existing POP3 PHP client to access my local mail account. I am getting a "could not connect". Same code works if I run it with my localhost connecting to GoDaddy's pop3 server</p> <p>2) Parsing the local mbox file - I can't figure out if I can access it, seems like I can't.</p> <p>Any good ideas of which approach should be best here?</p>
<p>I'd go with the POP3 option. It should work once you get the right port/host etc.</p> <p>The other option will result in you duplicating a large part of the functionality already in the mail server, and its quite likely you'll have minor bugs in it resulting in emails not displaying properly, or worse, corruption in the mbox.</p> <p>If you do go with 2, try to find a library for doing the mbox bit!</p>
<p>Zend Framework has <a href="http://framework.zend.com/manual/en/zend.mail.read.html" rel="nofollow noreferrer">a mail component</a>, that allows you to read from various sources.</p>
42,580
<p>Given two colors and <em>n</em> steps, how can one calculate n colors including the two given colors that create a fade effect? </p> <p>If possible pseudo-code is preferred but this will probably be implemented in Java.</p> <p>Thanks!</p>
<p>Divide each colour into its RGB components and then calculate the individual steps required.</p> <pre><code>oldRed = 120; newRed = 200; steps = 10; redStepAmount = (newRed - oldRed) / steps; currentRed = oldRed; for (i = 0; i &lt; steps; i++) { currentRed += redStepAmount; } </code></pre> <p>Obviously extend that for green and blue.</p>
<p>How about <a href="https://stackoverflow.com/q/15757872/2012219">this answer</a></p> <pre><code>- (UIColor *)colorFromColor:(UIColor *)fromColor toColor:(UIColor *)toColor percent:(float)percent { float dec = percent / 100.f; CGFloat fRed, fBlue, fGreen, fAlpha; CGFloat tRed, tBlue, tGreen, tAlpha; CGFloat red, green, blue, alpha; if(CGColorGetNumberOfComponents(fromColor.CGColor) == 2) { [fromColor getWhite:&amp;fRed alpha:&amp;fAlpha]; fGreen = fRed; fBlue = fRed; } else { [fromColor getRed:&amp;fRed green:&amp;fGreen blue:&amp;fBlue alpha:&amp;fAlpha]; } if(CGColorGetNumberOfComponents(toColor.CGColor) == 2) { [toColor getWhite:&amp;tRed alpha:&amp;tAlpha]; tGreen = tRed; tBlue = tRed; } else { [toColor getRed:&amp;tRed green:&amp;tGreen blue:&amp;tBlue alpha:&amp;tAlpha]; } red = (dec * (tRed - fRed)) + fRed; green = (dec * (tGreen - fGreen)) + fGreen; blue = (dec * (tBlue - fBlue)) + fBlue; alpha = (dec * (tAlpha - fAlpha)) + fAlpha; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha]; } </code></pre>
41,326
<p>So I have this regex:</p> <pre><code>(^(\s+)?(?P&lt;NAME&gt;(\w)(\d{7}))((01f\.foo)|(\.bar|\.goo\.moo\.roo))$|(^(\s+)?(?P&lt;NAME2&gt;R1_\d{6}_\d{6}_)((01f\.foo)|(\.bar|\.goo\.moo\.roo))$)) </code></pre> <p>Now if I try and do a match against this:</p> <pre> B048661501f.foo </pre> <p>I get this error:</p> <pre> File "C:\Python25\lib\re.py", line 188, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression sre_constants.error: redefinition of group name 'NAME' as group 9; was group 3 </pre> <p>If I can't define the same group twice in the same regex expression for two different cases, what do I do?</p>
<p>No, you can't have two groups of the same name, this would somehow defy the purpose, wouldn't it?</p> <p>What you probably <em>really</em> want is this:</p> <pre><code>^\s*(?P&lt;NAME&gt;\w\d{7}|R1_(?:\d{6}_){2})(01f\.foo|\.(?:bar|goo|moo|roo))$ </code></pre> <p>I refactored your regex as far as possible. I made the following assumptions:</p> <p>You want to (correct me if I'm wrong):</p> <ul> <li>ignore white space at the start of the string</li> <li>match either of the following into a group named "NAME": <ul> <li>a letter followed by 7 digits, or</li> <li><code>"R1_"</code>, and two times (6 digits + <code>"_"</code>)</li> </ul></li> <li>followed by either: <ul> <li><code>"01f.foo"</code> or</li> <li><code>"."</code> and (<code>"bar"</code> or <code>"goo"</code> or <code>"moo"</code> or <code>"roo"</code>)</li> </ul></li> <li>followed by the end of the string</li> </ul> <hr> <p>You could also have meant:</p> <pre><code>^\s*(?P&lt;NAME&gt;\w\d{7}01f|R1_(?:\d{6}_){2})\.(?:foo|bar|goo|moo|roo)$ </code></pre> <p>Which is:</p> <ul> <li>ignore white space at the start of the string</li> <li>match either of the following into a group named "NAME": <ul> <li>a letter followed by 7 digits and "01f"</li> <li><code>"R1_"</code>, and two times (6 digits + <code>"_"</code>)</li> </ul></li> <li>a dot</li> <li><code>"foo"</code>, <code>"bar"</code>, <code>"goo"</code>, <code>"moo"</code> or <code>"roo"</code></li> <li>the end of the string</li> </ul>
<p>As mentioned <a href="https://stackoverflow.com/a/44463324/416988">here</a>, Python PyPi <code>regex</code> module supports a <em>branch reset feature</em>.</p>
47,411
<p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="noreferrer">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p> <pre><code>import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') </code></pre> <p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p> <pre><code>print d.toXML() </code></pre> <p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
<p>Appended is a not hugely-elegant, but working solution - it uses feedparser to parse the feed, you can then modify the entries, and it passes the data to PyRSS2Gen. It preserves <em>most</em> of the feed info (the important bits anyway, there are somethings that will need extra conversion, the parsed_feed['feed']['image'] element for example).</p> <p>I put this together as part of a <a href="http://github.com/dbr/pyfeedproc" rel="nofollow noreferrer">little feed-processing framework</a> I'm fiddling about with.. It may be of some use (it's pretty short - should be less than 100 lines of code in total when done..)</p> <pre><code>#!/usr/bin/env python import datetime # http://www.feedparser.org/ import feedparser # http://www.dalkescientific.com/Python/PyRSS2Gen.html import PyRSS2Gen # Get the data parsed_feed = feedparser.parse('http://reddit.com/.rss') # Modify the parsed_feed data here items = [ PyRSS2Gen.RSSItem( title = x.title, link = x.link, description = x.summary, guid = x.link, pubDate = datetime.datetime( x.modified_parsed[0], x.modified_parsed[1], x.modified_parsed[2], x.modified_parsed[3], x.modified_parsed[4], x.modified_parsed[5]) ) for x in parsed_feed.entries ] # make the RSS2 object # Try to grab the title, link, language etc from the orig feed rss = PyRSS2Gen.RSS2( title = parsed_feed['feed'].get("title"), link = parsed_feed['feed'].get("link"), description = parsed_feed['feed'].get("description"), language = parsed_feed['feed'].get("language"), copyright = parsed_feed['feed'].get("copyright"), managingEditor = parsed_feed['feed'].get("managingEditor"), webMaster = parsed_feed['feed'].get("webMaster"), pubDate = parsed_feed['feed'].get("pubDate"), lastBuildDate = parsed_feed['feed'].get("lastBuildDate"), categories = parsed_feed['feed'].get("categories"), generator = parsed_feed['feed'].get("generator"), docs = parsed_feed['feed'].get("docs"), items = items ) print rss.to_xml() </code></pre>
<pre><code>from xml.dom import minidom doc= minidom.parse('./your/file.xml') print doc.toxml() </code></pre> <p>The only problem is that it do not download feeds from the internet.</p>
21,956
<p>I want to take the url: <a href="http://www.mydomain.com/signup-12345" rel="nofollow noreferrer">http://www.mydomain.com/signup-12345</a></p> <p>And actually give them: <a href="http://www.mydomain.com/signup/?aff=12345" rel="nofollow noreferrer">http://www.mydomain.com/signup/?aff=12345</a></p> <p>I have NO history with mod_rewrite, HELP!</p>
<p>Try this : </p> <p>RewriteRule ^/signup-(\d+)/$ /signup/?aff=$1 [I]</p>
<p>As far i know, </p> <p><em>flag causes the RewriteCond to be ignored.</em> - for "Ignore case" - from <code>IsapiRewrite</code> version 2</p>
13,082
<h3>Summary</h3> <p>What's the best way to ensure a table cell cannot be less than a certain minimum width. </p> <h3>Example</h3> <p>I want to ensure that all cells in a table are at least 100px wide regards of the width of the tables container. If there is more available space the table cells should fill that space.</p> <h3>Browser compatibility</h3> <p>I possible I would like to find a solution that works in</p> <ul> <li>IE 6-8</li> <li>FF 2-3</li> <li>Safari</li> </ul> <p>In order of preference.</p>
<p>This CSS should suffice:</p> <pre><code>td { min-width: 100px; } </code></pre> <p>However, it's not always obeyed correctly (the min-width attribute) by all browsers (for example, IE6 dislikes it a great deal).</p> <p><strong>Edit:</strong> As for an IE6 (and before) solution, there isn't one that works reliably under all circumstances, as far as I know. Using the nowrap HTML attribute doesn't really achieve the desired result, as that just prevents line-breaks in the cell, rather than specifying a minimum width.</p> <p>However, if nowrap is used in conjunction with a regular cell width property (such as using width: 100px), the 100px will act <em>like</em> a minimum width and the cell will still expand with the text (due to the nowrap). This is a less-than-ideal solution, which cannot be fully applied using CSS and, as such, would be tedious to implement if you have many tables you wish to apply this to. (Of course, this entire alternative solution falls down if you want to have dynamic line-breaks in your cells, anyway).</p>
<p>IE6 handles width as min-width:</p> <pre><code>td { min-width: 100px; _width: 100px;/* IE6 hack */ } </code></pre> <p>If you want IE6 to handle width like normal browsers, give it an overflow:visible; (not the case here)</p>
8,067
<p>Can any one give me a scripts (HTML/CSS/Javascript) that can reproduce this error on <code>IE 7.0</code>? I am trying to fix this bug in my page where I get this warning but could not exactly found the problem. Line number does not match with the source either. </p> <p>I thought the better approach would be to create a bug and then work on it incrementally rather than making some wild guess!</p>
<p>As Shog said, that error will occur when you try to call a method on an object which doesn't have that method.</p> <p>This is most often caused by an object being null when you expect it to, well, not be null.</p> <pre><code>var myEl = document.getElementById('myElement'); myEl.appendChild(...) </code></pre> <p>The above example will cause that error if the "#myElement" element doesn't exist.</p> <p>If it's only happening on IE and not Firefox, chances are it's because you're using a method which IE doesn't support.</p> <p>The solution? You can try the Script Debugger, but I've never found that to be useful myself. The most reliable, yet painfully slow method is alert() debugging. At strategic points through your code, put in an alert with a unique message. At some point IE will throw an error, so you'll know that the error is somewhere between the last alert which you saw, and the next one which didn't.</p> <pre><code>function myFunc() { alert('a'); var myEl = document.getElementById('myElement'); myEl.appendChild(something); alert('b'); // more code } </code></pre> <p>if you ran that and you saw 'a' but not 'b' you know it's in between there somewhere. This is just the sad state of javascript in IE, I'm afraid.</p>
<p>For IE, download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=2f465be0-94fd-4569-b3c4-dffdf19ccd99&amp;displaylang=en" rel="nofollow noreferrer">Microsoft Script Debugger</a></p>
39,533
<p>I'm writing a Java game and I want to implement a power meter for how hard you are going to shoot something. </p> <p>I need to write a function that takes a int between 0 - 100, and based on how high that number is, it will return a color between Green (0 on the power scale) and Red (100 on the power scale).</p> <p>Similar to how volume controls work:<br> <img src="https://i.stack.imgur.com/uErDJ.png" alt="volume control"></p> <p>What operation do I need to do on the Red, Green, and Blue components of a color to generate the colors between Green and Red?</p> <p>So, I could run say, <code>getColor(80)</code> and it will return an orangish color (its values in R, G, B) or <code>getColor(10)</code> which will return a more Green/Yellow RGB value.</p> <p>I know I need to increase components of the R, G, B values for a new color, but I don't know specifically what goes up or down as the colors shift from Green-Red.</p> <hr> <p>Progress:</p> <p>I ended up using HSV/HSB color space because I liked the gradiant better (no dark browns in the middle).</p> <p>The function I used was:</p> <pre class="lang-java prettyprint-override"><code>public Color getColor(double power) { double H = power * 0.4; // Hue (note 0.4 = Green, see huge chart below) double S = 0.9; // Saturation double B = 0.9; // Brightness return Color.getHSBColor((float)H, (float)S, (float)B); } </code></pre> <p>Where "power" is a number between 0.0 and 1.0. 0.0 will return a bright red, 1.0 will return a bright green.</p> <p>Java Hue Chart:<br> <img src="https://i.stack.imgur.com/QphuU.png" alt="Java Hue Chart"></p>
<p>This should work - just linearly scale the red and green values. Assuming your max red/green/blue value is <code>255</code>, and <code>n</code> is in range <code>0 .. 100</code></p> <pre><code>R = (255 * n) / 100 G = (255 * (100 - n)) / 100 B = 0 </code></pre> <p><em>(Amended for integer maths, tip of the hat to Ferrucio)</em></p> <p>Another way to do would be to use a <a href="http://www.cs.rit.edu/~ncs/color/t_convert.html" rel="noreferrer">HSV colour model</a>, and cycle the hue from <code>0 degrees</code> (red) to <code>120 degrees</code> (green) with whatever saturation and value suited you. This should give a more pleasing gradient.</p> <p>Here's a demonstration of each technique - top gradient uses RGB, bottom uses HSV:</p> <p><img src="https://i.stack.imgur.com/ZkoHs.jpg" alt="http://i38.tinypic.com/29o0q4k.jpg"></p>
<p>Self contained example</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; //-------------------------------------------------------------------------- function gradient(left, mid, right) { var obj = {} var lt50 = {"r":(mid.r-left.r)/50.0, "g":(mid.g-left.g)/50.0, "b":(mid.b-left.b)/50.0} var gt50 = {"r":(right.r-mid.r)/50.0, "g":(right.g-mid.g)/50.0, "b":(right.b-mid.b)/50.0} obj.getColor = function(percent) { if (percent == 50.0) { return mid; } if (percent &lt; 50.0) { return "rgb("+Math.floor(left.r+lt50.r*percent+0.5)+","+ Math.floor(left.g+lt50.g*percent+0.5)+","+ Math.floor(left.b+lt50.b*percent+0.5)+")"; } var p2 = percent-50.0; return "rgb("+Math.floor(mid.r+gt50.r*p2+0.5)+","+ Math.floor(mid.g+gt50.g*p2+0.5)+","+ Math.floor(mid.b+gt50.b*p2+0.5)+")"; } return obj; } //-------------------------------------------------------------------------- var g_gradient = gradient( {"r":255, "g":20, "b":20}, // Left is red {"r":255, "g":255, "b":20}, // Middle is yellow {"r":20, "g":255, "b":20} ); // right is green //-------------------------------------------------------------------------- function updateColor() { var percent = document.getElementById('idtext').value.length; var oscore = document.getElementById('idscore'); if (percent &gt; 100.0) { percent = 100.0; } if (percent &lt; 0.0) { percent = 0.0; } var col = g_gradient.getColor(percent) oscore.style['background-color'] = col; oscore.innerHTML = percent + '%'; } &lt;/script&gt; &lt;/head&gt; &lt;body onLoad="updateColor()"&gt; &lt;input size='100' placeholder='type text here' id='idtext' type="text" oninput="updateColor()" /&gt; &lt;br /&gt; &lt;br /&gt; &lt;div id='idscore' style='text-align:center; width:200px; border-style:solid; border-color:black; border-width:1px; height:20px;'&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
44,192
<p>I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current <code>IQueryable</code> result instance has been executed or not.</p> <p>The debugger knows that my <code>IQueryable</code> has not been <em>'invoked'</em> because it tells me that expanding the Results property will <em>'enumerate'</em> it. Is there a way for me to programmatically identify that as well.</p> <p>I hope that makes sense :)</p>
<p>How about writing an IQueryable wrapper like this:</p> <pre><code>class QueryableWrapper&lt;T&gt; : IQueryable&lt;T&gt; { private IQueryable&lt;T&gt; _InnerQueryable; private bool _HasExecuted; public QueryableWrapper(IQueryable&lt;T&gt; innerQueryable) { _InnerQueryable = innerQueryable; } public bool HasExecuted { get { return _HasExecuted; } } public IEnumerator&lt;T&gt; GetEnumerator() { _HasExecuted = true; return _InnerQueryable.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public Type ElementType { get { return _InnerQueryable.ElementType; } } public System.Linq.Expressions.Expression Expression { get { return _InnerQueryable.Expression; } } public IQueryProvider Provider { get { return _InnerQueryable.Provider; } } } </code></pre> <p>Then you can use it like this:</p> <pre><code>var query = new QueryableWrapper&lt;string&gt;( from str in myDataSource select str); Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); foreach (string str in query) { Debug.WriteLine(str); } Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); </code></pre> <p>Output is:</p> <p>False<br/> String0<br/> String1<br/> ...<br/> True</p>
<p>I believe you can use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.data.linq.datacontext.log" rel="nofollow noreferrer">DataContext.Log</a> to log everything that is executed.</p>
7,966
<p>How do you perform the equivalent of Oracle's <code>DESCRIBE TABLE</code> in PostgreSQL (using the psql command)?</p>
<p>Try this (in the <code>psql</code> command-line tool):</p> <pre><code>\d+ tablename </code></pre> <p>See <a href="http://www.postgresql.org/docs/current/interactive/app-psql.html#APP-PSQL-META-COMMANDS" rel="noreferrer">the manual</a> for more info.</p>
<p>I worked out the following script for get table schema.</p> <pre><code>'CREATE TABLE ' || 'yourschema.yourtable' || E'\n(\n' || array_to_string( array_agg( ' ' || column_expr ) , E',\n' ) || E'\n);\n' from ( SELECT ' ' || column_name || ' ' || data_type || coalesce('(' || character_maximum_length || ')', '') || case when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr FROM information_schema.columns WHERE table_schema || '.' || table_name = 'yourschema.yourtable' ORDER BY ordinal_position ) column_list; </code></pre>
13,463
<p>Hmm. I'm trying to deploy a web service to a new server and there is no ASP.NET tab. I've tried running <code>aspnet_regiis</code> from ASP.NET 2.0 directory but this doesn't seem to work. Any ideas anyone?</p>
<p>If you've had (or have...) VMware Server installed on this particular machine, the following steps will most likely fix the issue with minimal pain:</p> <ol> <li>Stop the IISAdmin service (and its dependencies)</li> <li>Open <code>%windir%\system32\inetsrv\MetaBase.xml</code> in a text editor</li> <li>Delete the line that reads <code>Enable32BitAppOnWin64="TRUE"</code></li> <li>Restart your services using <code>iisreset /start</code></li> </ol>
<p>reinstall IIS</p>
27,451
<p>Some files are uploaded with a reported MIME type:</p> <pre><code>image/x-citrix-pjpeg </code></pre> <p>They are valid jpeg files and I accept them as such.</p> <p>I was wondering however: why is the MIME type different?<br> Is there any difference in the format? or was this mimetype invented by some light bulb at citrix for no apparent reason?</p>
<p><strong>Update:</strong><br> Ok, I did some more searching and testing on this question, and it turns out they're all lying about MIME-type (never trust <em>any</em> info send by the client, I know).<br> I've checked a bunch of files with different encodings (created with libjpeg)</p> <p><code>Official</code> MIME type for jpeg files: <code>image/jpeg</code></p> <p>But some applications (most notably MS Internet Explores but also Yahoo! mail) send jpeg files as <code>image/pjpeg</code> </p> <blockquote> <p>I thought I knew that pjpeg stood for 'progressive' jpeg. It turns out that progressive/standard encoding has nothing to do with it.</p> </blockquote> <p>MS Internet explorer send out <em>all</em> jpeg files as pjpeg regardless of the contents of the file.</p> <p>The same goes for citrix: <em>all</em> jpeg files send from a citrix client are reported as the <code>image/x-citrix-pjpeg</code> MIME type.</p> <p>The files themselves are untouched (identical before and after upload). So it turns out that difference in MIME type is only an indication the software used to send the file?</p> <p>Why would people invent a new MIME type if there is no differences to the file contents?</p>
<p>From what I recall the Progressive JPG format is the one that would allow the image to be shown with progressively higher resolution as the download of the file progressed. I am not entirely aware of the details, but if you remember back in the days of dial up, some files would show blurry, then better and eventually complete as they were downloaded. For this to work the data needs to be sent in a different order than a JPEG would typically be sent. </p> <p>The actual data, once you view it, is identical it is just sent in a different order. The JPEG encoding itself may very well group pixels differently, I forget.</p>
24,525
<p>I'm on a team that uses scrum for our development process. We are currently trying to revamp certain aspects of our process to address some of the problems we've noticed lately. In doing so, we are exploring what it is that we like about the scrum process in general as well as what we don't like in order to help us identify what we as a team values in our work. We figure that if we can identify what we value, then we can come up with implementations that revolve around the values to help new solutions stick within the team. </p> <p>With that said, I'm really interested in how other people view the scrum process. What was it that you really like about it? What was it that was frustrating and felt like it was too much overhead or non-productive? Specific examples of successes and failures are fine, but I'm interested in a much larger view where discussion revolves around pitfalls of scrum or where scrum really shines. </p> <p>Thoughts?</p>
<p>I don't like when managers implement scrum process as just quick release cycle, with all other aspects the same or worse as waterfall.</p>
<p>This is a pretty broad question! Here's my take.</p> <p>I think what Scrum is really good at is teaching organizations to love agile / iterative / incremental / lean software development. For a company that's used to a command and control hierarchy of project management, the empowerment necessary for teams to succeed at being truly adaptive to their customers' needs is a massive cultural shift. Scrum makes all this approachable for organizations, with clearly defined roles and processes.</p> <p>Basically, to me, it buys a team of programmers the space they need within all the politics and bureaucracy of a big company to get on with doing XP.</p> <p>However with this empowerment comes responsibility. Scrum does not mandate any of the XP engineering practices, but without core practices like CI, TDD and refactoring, any scrum team will splutter to a halt after a few iterations. I personally think it is quite irresponsible for this not to be explicit in scrum's 'rules', and that would be one of my criticisms.</p> <p>My other criticism is with task cards and task planning. I have yet to see a team where this was really effective: usually there's a very tiring day where you try to think through everything you'll do on the whole iteration, then you get going and find you actually needed to do something different. Measuring progress through task burn-downs feels like a good way to get teams to collaborate and bond (especially if you disavow task ownership) but ultimately it isn't a reliable way to track the progress of a team.</p> <p>I place a lot more emphasis on <strong>burn-up</strong> of value or story points, and these days usually get the team to do a daily update a big <a href="http://bdn1.borland.com/borcon2004/article/paper/0,1963,32096,00.html" rel="nofollow noreferrer">Cumulative Flow Diagram</a> chart of where we're at with that instead. The tasks stay on people's to do lists, but they don't go on the board or get managed by anyone.</p> <p>The key practice, of course, is retrospectives. Mike Cohn's counter-argument to my earlier point about the XP practices is that with retrospectives, teams will end up inventing / adopting XP anyway, and this does have some validity. Certainly regular introspection is the best way of all to make sure your team is and continues to be as effective as it possibly can.</p>
39,356
<pre><code>Pattern pattern = Pattern.compile("^[a-z]+$"); String string = "abc-def"; assertTrue( pattern.matcher(string).matches() ); // obviously fails </code></pre> <p>Is it possible to have the character class match a "-" ?</p>
<p>Don't put the minus sign between characters.</p> <pre><code>"[a-z-]" </code></pre>
<p>This works for me</p> <pre><code> Pattern p = Pattern.compile("^[a-z\\-]+$"); String line = "abc-def"; Matcher matcher = p.matcher(line); System.out.println(matcher.matches()); // true </code></pre>
18,610
<p>We have a WinForms application written in C# that uses the AxAcroPDFLib.AxAcroPDF component to load and print a PDF file. Has been working without any problems in Windows XP. I have moved my development environment to Vista 64 bit and now the application will not run (on Vista 64) unless I remove the AxAcroPDF component. I get the following error when the application runs:</p> <p>"System.Runtime.InteropServices.COMException: Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))." </p> <p>I have been advised on the Adobe Forums that the reason for the error is that they do not have a 64 bit version of the AxAcroPDF ActiveX control. </p> <p>Is there some way around this problem? For example can I convert the 32bit ActiveX control to a 64bit control myself?</p>
<p>You can't convert Adobe's ActiveX control to 64bit yourself, but you can force your application to run in 32bit mode by setting the platform target to x86.</p> <p>For instructions for your version of Visual Studio, see section 1.44 of <a href="http://msdn.microsoft.com/en-gb/vstudio/aa718685.aspx" rel="noreferrer">Issues When Using Microsoft Visual Studio 2005</a></p>
<p>Use DLL isolation, works with every 32bit COM+ application. See more at: <a href="http://support.microsoft.com/kb/281335" rel="nofollow noreferrer">http://support.microsoft.com/kb/281335</a></p> <p>With this solution you can isolate your 32 bit COM+ application into a separate 32bit process.</p> <p>64bit applications search installed COM+ objects at: HKLM\Software\Classes, but 32bit applications use HKLM\Software\WOW6432\Classes</p>
9,275
<p>Normally, the method of passing workflow parameters to the workflow happens in the call to RunWorkflow. However, with the WorkflowServiceHost, there is no such method call involved. You simply call the Open() method on the instance. Any ideas?</p> <p>Of course, the implication is that I add more parameters to the service contract, but these parameters are not relevant for the consumers of the service. They are more like configuration values. </p>
<p>Here is my complete code. I hope this will help.</p> <p>The xaml code:</p> <pre><code>&lt;Window x:Class="DataGridSort.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:dg="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" xmlns:System="clr-namespace:System;assembly=mscorlib" Title="Window1" Height="413" Width="727" x:Name="_this"&gt; &lt;Window.Resources&gt; &lt;ObjectDataProvider ObjectInstance="_this.DataContext" MethodName="GetFromDate" x:Key="odp"&gt; &lt;ObjectDataProvider.MethodParameters&gt; &lt;System:DateTime&gt;2008-01-01&lt;/System:DateTime&gt; &lt;/ObjectDataProvider.MethodParameters&gt; &lt;/ObjectDataProvider&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;dg:DatePicker Grid.Row="0" x:Name="dtpSource" &gt; &lt;dg:DatePicker.SelectedDate&gt; &lt;Binding Source="{StaticResource odp}" Path="MethodParameters[0]" BindsDirectlyToSource="True" Mode="OneWayToSource"/&gt; &lt;/dg:DatePicker.SelectedDate&gt; &lt;/dg:DatePicker&gt; &lt;dg:DataGrid x:Name="dtgGrid" ItemsSource="{Binding Source={StaticResource odp}}" AutoGenerateColumns="True" Grid.Row="1"/&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>The code behind:</p> <pre><code>public partial class Window1 : Window { public Window1() { InitializeComponent(); LoadData(); } protected void LoadData() { DataContext = new Data(); ObjectDataProvider odp = this.Resources["odp"] as ObjectDataProvider; odp.ObjectInstance = DataContext; } } </code></pre> <p>and the business object:</p> <pre><code>public class DataItem { public string Name { get; set; } public int BirthYear { get; set; } } public class Data { private readonly List&lt;DataItem&gt; data; public Data() { data = new List&lt;DataItem&gt;(); data.Add(new DataItem { Name = "John", BirthYear = 2007 }); data.Add(new DataItem { Name = "Mike", BirthYear = 2007 }); data.Add(new DataItem { Name = "Aaron", BirthYear = 2006 }); data.Add(new DataItem { Name = "Bill", BirthYear = 2006 }); data.Add(new DataItem { Name = "Steven", BirthYear = 2005 }); data.Add(new DataItem { Name = "George", BirthYear = 2004 }); data.Add(new DataItem { Name = "Britany", BirthYear = 2004 }); } public List&lt;DataItem&gt; GetFromDate(DateTime dt) { return this.data.Where(d =&gt; d.BirthYear == dt.Year).ToList(); } } </code></pre>
<p>If you build your class with INotifyPropertyChanged like this:</p> <pre><code>public class MyDataObject : INotifyPropertyChanged { private DateTime _SelectedDate; public DateTime SelectedDate { get { return _SelectedDate; } set { _SelectedDate = value; NotifyPropertyChanged("SelectedDate"); GetDataForDate(); } } private ObservableCollection&lt;YourDataType&gt; _Data; public ObservableCollection&lt;YourDataType&gt; Data { get { return _Data; } set { _Data = value; NotifyPropertyChanged("Data"); } } public void GetDataForDate() { // Your code here to fill the Data object with your data } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (this.PropertyChanged != null) this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } #endregion } </code></pre> <p>Then you can create your ObjectDataProvider in XAML and bind directly to it. In your resources:</p> <pre><code>&lt;ObjectDataProvider x:Key="MyDataSource" ObjectType="{x:Type local:MyDataObject}" /&gt; </code></pre> <p>And then bind:</p> <pre><code>&lt;DockPanel&gt; &lt;toolkit:DatePicker SelectedDate="{Binding Path=SelectedDate, Mode=Default, Source={StaticResource MyDataSource}}"/&gt; &lt;toolkit:DataGrid ItemsSource="{Binding Path=Data, Mode=Default, Source={StaticResource MyDataSource}}"/&gt; &lt;/DockPanel&gt; </code></pre>
37,998
<p>Any suggestions on how to write repeatable unit tests for code that may be susceptible to deadlocks and race conditions?</p> <p>Right now I'm leaning towards skipping unit tests and focusing on stress tests. The problem with that is you can run a stress test 5 times and see five different results.</p> <p>EDIT: I know its probably just a dream, but if there were a way to control individual threads and cause them to execute one instruction at a time then I might get somewhere.</p>
<p>Take a look at <a href="http://www.typemock.com/typemock-racer-product/" rel="nofollow noreferrer">TypeMock</a> Racer (it's in Beta)</p> <p>edit: actually Alpha</p> <p><a href="http://www.typemock.com/Typemock_software_development_tools.html" rel="nofollow noreferrer">http://www.typemock.com/Typemock_software_development_tools.html</a></p>
<p>I have previously used artificial delays in the code that are triggered by some parameters in the request. For example one request tells the server to delay write between two writes and another to do them with no delay in between. </p> <p>A Mark Bessey writes, this is only useful for creating repro, not for discovering the problem.</p>
21,276
<p>I am working with a larger than average sqlite database (for use on both on windows and linux) and am looking to maximize the performance I get out of it. The database is to be installed on commodity hardware along with an sqlite gui. The users I am delivering this to are sql savvy but are unlikely to undertake their own optimizations (creation of indexes, setting of pragma etc.) so I am keen to get as much out of the box performance as possible (to ensure maximum usage of the data).</p> <p>One issue Windows seems to throttle the execution of queries much more than Linux and another is that I am less familiar with sqlite's approach to indexing (compared to other databases such as postgres).</p>
<p>Have you read the <a href="http://web.utk.edu/~jplyon/sqlite/SQLite_optimization_FAQ.html" rel="nofollow noreferrer">SQLite Optimization FAQ</a> (a few years old, but still seems useful)?</p> <p>I don't think 1gb is particularly large, even for SQLite. It can certainly handle much larger databases stably.</p>
<p>You should have a look at "scheduled tasks" and a script to "optimize tables" every night, perhaps even re-recreate your indexes. Doing so on a regular basis can save you a ton of time and manual labour.</p>
27,792
<p>I wish to send a header to my Apache server on a Linux box. How can I achieve this via a cURL call?</p>
<p><a href="https://curl.haxx.se/docs/manpage.html" rel="noreferrer"><code>man curl</code></a>:</p> <pre><code> -H/--header &lt;header&gt; (HTTP) Extra header to use when getting a web page. You may specify any number of extra headers. Note that if you should add a custom header that has the same name as one of the internal ones curl would use, your externally set header will be used instead of the internal one. This allows you to make even trickier stuff than curl would normally do. You should not replace internally set headers without knowing perfectly well what you're doing. Remove an internal header by giving a replacement without content on the right side of the colon, as in: -H &quot;Host:&quot;. curl will make sure that each header you add/replace get sent with the proper end of line marker, you should thus not add that as a part of the header content: do not add newlines or carriage returns they will only mess things up for you. See also the -A/--user-agent and -e/--referer options. This option can be used multiple times to add/replace/remove multi- ple headers. </code></pre> <h1>Example 1: Single Header</h1> <pre><code>curl --header &quot;X-MyHeader: 123&quot; www.google.com </code></pre> <h1>Example 2: Multiple Headers</h1> <pre><code>curl --header &quot;Accept: text/javascript&quot; --header &quot;X-Test: hello&quot; -v www.google.com </code></pre> <p>You can see the request that curl sent by adding the <code>-v</code> option.</p>
<p>Here are the some curl commands for most common http methods.</p> <p>Domain Object considered here is</p> <pre><code>@Data @NoArgsConstructor @AllArgsConstructor @Document @Validated public class Movie { @Id private String id; private String name; @NotNull private Integer year; @NotNull private List&lt;String&gt; cast; private LocalDate release_date; } </code></pre> <h2>POST-CREATE-MOVIE</h2> <pre><code>curl -i \ -d '{&quot;id&quot;:1, &quot;name&quot;: &quot;Dhoom&quot;, &quot;year&quot;:2004,&quot;cast&quot;:[&quot;John Abraham&quot;, &quot;Abhishek Bachan&quot;],&quot;release_date&quot;: &quot;2004-06-15&quot;}' \ -H &quot;Content-Type: application/json&quot; \ -X POST http://localhost:8080/v1/movies </code></pre> <h2>GET-ALL-MOVIES</h2> <pre><code>curl -i http://localhost:8080/v1/movies </code></pre> <h2>GET-MOVIE-BY-ID</h2> <pre><code>curl -i http://localhost:8080/v1/movies/1 </code></pre> <h2>PUT-UPDATE-MOVIE</h2> <pre><code>curl -i \ -d '{&quot;id&quot;:1, &quot;name&quot;: &quot;Dhoom&quot;, &quot;year&quot;:2005,&quot;cast&quot;:[&quot;John Abhraham&quot;, &quot;Abhishek Bachhan&quot;, &quot;Uday Chopra&quot;, &quot;Isha Deol&quot;],&quot;release_date&quot;: &quot;2005-03-25&quot;}' \ -H &quot;Content-Type: application/json&quot; \ -X PUT http://localhost:8080/v1/movies/1 </code></pre> <h2>DELETE-MOVIE</h2> <pre><code>curl -i -X DELETE http://localhost:8080/v1/movies/1 </code></pre>
46,512
<p>I'm wondering if there are any applications, preferably freeware, that can take a database configuration, and, with as little hassle as possible, create web forms for inserting data easily. </p> <p>I'm finding it hard to express exactly what it is I'm after. Maybe I can talk a bit about what I need.</p> <p>I have a configuration database that, at least usually, contains "the truth" about the servers in our system. It contains stuff like zone names, hostnames, different configuration items, etc, over multiple tables. Right now we're using simple INSERTs directly when adding new servers or other stuff, handling the keys and IDs ourselves. The crux is, they don't want us to develop a simple web form thingy to handle this, instead they want a tool that can generate the web form thingy. Did that make sense?</p> <p>I'm not sure if anything like this exists or is reliable, but, I thought that if anyone knew, it's this community. Thanks!</p>
<p>As many have already stated, it depends on what technology you're working with:</p> <ul> <li>.Net 3.5 - Dynamic Data or Subsonic's Scaffolding control</li> <li>.Net 2.0 - Subsonic's Scaffolding control </li> <li>PHP - CakePHP </li> <li>Ruby - Rail's Scaffolding component</li> </ul>
<p>You can try <a href="http://www.adminer.org/en/editor/" rel="nofollow">Adminer Editor</a></p> <blockquote> <p>Adminer Editor is both easy-to-use and user-friendly database editing tool written in PHP. It is suitable for common users, as it provides high-level data manipulation.</p> </blockquote>
41,015
<p>I have no experience with web services. Historically I've built client-server systems using proprietary communication protocols (even they happen to be XML). I just spent a few hours looking over Axis2 and it sent a shudder down my spine. The learning curve of WS scares me, and seeing all that XML surround so little functionality makes me wonder if it's worth the trouble.</p> <p>How do you decide whether you need to use Web Services or a custom communication protocol? What are the advantages/disadvantages of each approach and what use-cases are they best suited for?</p> <p><strong>Please post a clear guideline, not an opinion piece :)</strong></p>
<p>Build RESTful web APIs; then you get a lot of automatic caching and etc benefits that you don't get if you use other methods (SOAP, XML-RPC, etc)</p> <p>See <a href="https://stackoverflow.com/questions/106546/performance-of-soap-vs-xml-rpc-or-rest#106701">this post</a> for more details</p> <p>Another benefit is that if you build a RESTful API for your code to use, you can potentially let your users take advantage of it too - they often have uses for your product that you never dreamed of.</p>
<p>I have recently broken my custom protocol habit. I am now using Apache on the server side and libCurl plus libxml2 to load and parse the XML on the client which is written in C++.</p> <p>The server side can be either PHP or a CGI written in a more serious language. Depends what you want to do.</p>
15,167
<p>I am setting up Apache server with TortoiseSVN for a local source code repository. I have observed that if someone deletes a file using TortoiseSVN it will get deleted from everyone's view and the only log will be their in log history. I feel it is dangerous that any user can delete a file if they have read/write rights (accidentally or intentionally, and though the file remains on the server it is risky and can create panic in others).</p> <p>Is there a way that only admins can add or delete files?</p>
<p>One of the beauties of source control is that it doesn't matter if someone deletes a file. If they delete a file and check it in and it should not have been deleted, just revert their revision. Simple as that.</p>
<p>I would recommend that you read a book about version control, preferably the <a href="http://svnbook.red-bean.com/" rel="nofollow noreferrer" title="Version Control with Subversion">Version Control with Subversion</a>. What you describe is not a problem, this is how version control works.</p>
14,269
<p>I need to match something in the form </p> <pre><code>&lt;a href="pic/5" id="piclink"&gt;&lt;img src="thumb/5" /&gt;&lt;/a&gt; </code></pre> <p>to find the number, in this case 5, using JavaScript. I have no idea how to use regexes, so I was wondering if anyone here could help out.</p>
<p>Just to make sure you know what's going on, the pattern you posted in your own answer will match exactly <strong>one</strong> digit between 0 and 9.</p> <p>If you want to match integers with one or more digits, you might try the pattern</p> <pre><code>/[0-9]+/ </code></pre> <p>Check out <a href="http://en.wikipedia.org/wiki/Regular_expressions" rel="nofollow noreferrer">Wikipedia's article on Regular Expressions</a> for a great overview. Regular Expressions can seem overwhelming if you're just starting out, but once you get a handle on the basic syntax, they're incredibly useful and powerful.</p>
<p>Nevermind, I solved it with a simple </p> <pre><code>'&lt;a href="pic/5" id="piclink"&gt;&lt;img src="thumb/5" /&gt;&lt;/a&gt;'.match(/[0-9]/); </code></pre>
23,898
<p>I have a MySQL query structured as follows:</p> <pre><code>SELECT time(c.start_time), time(c.end_time), time(c.end_time) - time(c.start_time) as 'opening_hours' FROM my_shop c; </code></pre> <p>The data in start and end time is 1970-01-01 07:00:00 and 1970-01-01 19:00:00 respectively.</p> <p>On my local machine this this query returns:</p> <pre><code>| 07:00:00 | 19:00:00 | 12 | </code></pre> <p>However on a remote machine (production) it is returning</p> <pre><code>| 07:00:00 | 19:00:00 | 120000 | </code></pre> <p>Any ideas as to why this might be happening and how to fix it? </p> <p>Both sets of data are identical and too the best of my knowledge both MySQL installations are identical.</p> <p>Any help is much appreciated.</p> <p>Update: </p> <p>It would seem that the versions of MySQL are slightly different: 5.0.27-community-nt versus 5.0.51b-community-nt. This is most probably the reason why.</p> <p>djt has raised a good point in that Bill's solution does not take into account minutes. As well as this djt's solution is not quite what i need. </p> <p>So i guess the question has morphed into how to subtract two times including minutes such that:</p> <pre><code>1970-01-01 19:00:00 - 1970-01-01 07:00:00 = 12 1970-01-01 19:00:00 - 1970-01-01 07:30:00 = 11.5 1970-01-01 19:00:00 - 1970-01-01 07:45:00 = 11.25 </code></pre> <p>etc.</p>
<p>I'd do it this way:</p> <pre><code>SELECT TIME(c.start_time), TIME(c.end_time), EXTRACT(HOUR FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time))) AS 'opening_hours' FROM my_shop c; </code></pre>
<p>Is there a better solution than this:</p> <pre><code>SELECT EXTRACT(HOUR FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time))) + ((EXTRACT(MINUTE FROM TIMEDIFF(TIME(c.end_time), TIME(c.start_time))))/60) FROM my_shop c; </code></pre>
47,169
<p>Is there a way with SVN to check out from a remote repository to another remote location rather than my local file system? Something like:</p> <pre><code>svn co http://myrepository/svn/project ssh me@otherlocation.net:/var/www/project </code></pre>
<p>I think you could do:</p> <pre><code>ssh me@other.net 'svn co http://repository/svn/project /var/www/project' </code></pre> <p>This takes advantage of the fact that ssh lets you execute a command remotely.</p>
<p>You could use Subversion with <a href="http://fuse.sourceforge.net/sshfs.html" rel="nofollow noreferrer" title="SSHFS">SSHFS</a>.</p>
19,254
<p>Please don't answer the obvious, but what are the limit signs that tell us a problem should not be solved using regular expressions?</p> <p>For example: Why is a complete email validation too complex for a regular expression?</p>
<p>When you need to parse an expression that's not defined by a <a href="http://en.wikipedia.org/wiki/Regular_language" rel="noreferrer">regular language</a>.</p>
<p>My limit is a Regex pattern that's about 30-50 characters long (varying depending on how much is fixed text and how much is regex commands)</p>
28,535
<p>What's your opinion on whether one should write an application for a specific platform or use a cross platform approach and reach more potential clients?</p> <p>It would be a GUI based application and I'm thinking of using Java.</p> <p>Most of the applications that I've used built on Java don't run as smooth as the native applications on the respective platforms.</p> <p>The two platforms I'm thinking of are windows and macs.</p> <p>If I was creating the app just for my own use, and I had to choose one system, I would choose to focus on the mac. </p> <p>I would like to hear your thoughts.</p>
<p>I would use Qt and yes, definitely target Cross Platform...</p> <p>The major reason isn't in fact what you think it is (being cross platform by itself) but actually that by targeting multiple platforms your code by some freaking weird magical reasons tends to end up with far better code quality. I've seen this happen countless times in my own projects. Every time I add a new platform the quality of the code increases and the code becomes more clean...</p> <p>Also every serious app should have as few "dependencies" as possible, being cross platform means you have less dependencies... ;)</p> <p>Then as a "bonus" you get to your app to run on multiple platforms...</p>
<p>Why don't you consider Web Application.</p> <p>You can build rich UI Web site running in browser which runs everywhere and all platforms, If you are familiar with Java, you can try GWT for the 'Weblication' Check out the <a href="http://gwt.google.com/samples/Showcase/Showcase.html" rel="nofollow noreferrer">demo page of GWT</a></p>
40,772
<p>Any time I try to publish my Portal project on a Websphere Portal 6.1 Server, I get the following error message:</p> <pre><code>Portal project publishing is not supported on WebSphere Portal v6.1 Server </code></pre> <p>Is that really true or have I done something wrong?</p> <p>I'm trying to deploy a portal project, with the underlying goal of publishing a new theme.</p> <p>Unfortunately, any time I try to deploy, I get the error message listed above from the IDE and no errors in the console.</p> <p>The RAD version is 7.0.0.7.</p>
<p>Not sure this will help, but:</p> <blockquote> <p>Limitation: Although the WebSphere Portal installer contains an advanced option to install an empty portal, Portal Designer relies on administration portlets for setting access control; therefore, publishing a portal project to an empty portal is not supported.</p> </blockquote> <p>Are you trying to deploy a portlet or an entire portal project? What version of RAD are you using? Any other information in the error log? (Both within RAD &amp; on WP server) Is the error message posted verbatim?</p>
<p>It is possible to deploy such a project to a WebSphere Portal. I use v6.2 and deploy portlets, which are parts of a big Portal project, every day. I'm only a starter in such a stuff, but I can say that WebSphere is really buggy. You know, it is a big difference to run a deployed app "locally, in a workspace" or "on a server". I suggest you to work out with server options - administrative console.</p>
18,331
<p>I am trying to use <code>ActiveRecord::Base.transaction</code>. I figured that rollback doesn't work by default using Rails 1.2.6 and mysql 5.0. Playing with it a little bit more I found out that <code>autocommit</code> is not set to 0 in mysql connection.</p> <p><strong>Questions:</strong></p> <p>1) How do I disable autocommit in rails for all connections?</p> <p>2) Will it have some negative impact on the other code that doesn't have to be transactional?</p>
<p>If you have a mix of code that needs explicit transactions and code that can rely on autocommit, perhaps you shouldn't disable autocommit for all connections. You're on the right track wondering if this will impact other code. If you disable autocommit, but the other code doesn't know it has to commit to have its work committed, then that'll be a problem. Uncommitted work is rolled back when the connection closes.</p> <p>You should be aware that the default storage engine for MySQL is <a href="http://dev.mysql.com/doc/refman/5.0/en/myisam-storage-engine.html" rel="noreferrer">MyISAM</a>, which doesn't support transactions at all. When you make changes to a table that uses MyISAM, the changes are effectively committed immediately, regardless of your explicit requests to begin and finish transactions, and regardless of the state of autocommit. So you won't be able to roll back no matter what, unless you created your tables using the <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb.html" rel="noreferrer">InnoDB</a> storage engine (or other transaction-safe storage engines such as <a href="http://dev.mysql.com/doc/refman/5.0/en/bdb-storage-engine.html" rel="noreferrer">BDB</a>).</p> <p>It's <a href="http://dev.rubyonrails.org/ticket/4" rel="noreferrer">unnecessary</a> to disable autocommit mode to use transactions in MySQL. Simply begin a transaction explicitly. The following SQL statements will be part of a transaction until you commit or rollback that transaction, regardless of the value of autocommit on your current connection.</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/commit.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/commit.html</a> says:</p> <blockquote> <p>With START TRANSACTION, autocommit remains disabled until you end the transaction with COMMIT or ROLLBACK. The autocommit mode then reverts to its previous state.</p> </blockquote>
<p>Not that I have any specifically not transactional code - it is mostly all ActiveRecord objects, I just want to have rollback behavior if one of my methods fails. </p> <p>I will explore more , you seem to be right - I can confirm your answer in mysql console. However in my Rails application I have to do connection.execute("set autocommit = 0") to get rollback working. </p>
44,776
<p>How would I set an image to come from a theme directory (my theme changes so I don't want to directly reference) I am sure this is possible but every example I find doesn't seem to work. They are usually along the lines of:</p> <p>asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg" /</p> <p>where Web would be a sub directory in my themes folder. Suggesting the theme directory would be added at runtime.</p>
<p>If you are wanting to reference an Image in your Theme folder, then I suggesting using a SkinId. Inside the skin file of each Theme Folder you would define something like this</p> <pre><code>&lt;asp:Image runat="server" SkinId="HomeImage" ImageUrl="Images/HomeImage.gif" /&gt; </code></pre> <p>When you go to use the image in your code you do something like this...</p> <pre><code>&lt;asp:Image runat="server" SkinId="HomeImage" /&gt; </code></pre> <p>Depending on the theme your application has picked it will pick up the correct image from the correct Theme folder.</p> <pre><code>MyWebSite App_Themes Theme1 Default.skin Default.css Images HomeImage.gif Theme2 Default.skin Default.css Images HomeImage.gif </code></pre> <p>Here is a <a href="http://www.odetocode.com/articles/423.aspx" rel="noreferrer">good article</a> explaining how to use themes, skins, and to set the theme several different ways.</p>
<p>Not sure if I understood your question right, but if you have an image in a skin file, such as the following, it will come by default from the theme folder:</p> <pre><code>&lt;asp:Image runat="server" ImageUrl="filename.ext" /&gt; </code></pre> <p>If you want it to come from a subfolder Web of the theme folder, use a relative path:</p> <pre><code>&lt;asp:Image runat="server" ImageUrl="Web/filename.ext" /&gt; </code></pre> <p>Your example specifies a subfolder of the application root directory:</p> <pre><code>&lt;asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg"/&gt; </code></pre> <p>See <a href="http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx" rel="nofollow noreferrer">the MSDN page on themes and skins</a>.</p>
24,463
<p>It seems</p> <pre><code>import Queue Queue.Queue().get(timeout=10) </code></pre> <p>is keyboard interruptible (ctrl-c) whereas</p> <pre><code>import Queue Queue.Queue().get() </code></pre> <p>is not. I could always create a loop;</p> <pre><code>import Queue q = Queue() while True: try: q.get(timeout=1000) except Queue.Empty: pass </code></pre> <p>but this seems like a strange thing to do.</p> <p>So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?</p>
<p><code>Queue</code> objects have this behavior because they lock using <code>Condition</code> objects form the <code>threading</code> module. So your solution is really the only way to go.</p> <p>However, if you really want a <code>Queue</code> method that does this, you can monkeypatch the <code>Queue</code> class. For example:</p> <pre><code>def interruptable_get(self): while True: try: return self.get(timeout=1000) except Queue.Empty: pass Queue.interruptable_get = interruptable_get </code></pre> <p>This would let you say</p> <pre><code>q.interruptable_get() </code></pre> <p>instead of</p> <pre><code>interruptable_get(q) </code></pre> <p>although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.</p>
<p>This may not apply to your use case at all. But I've successfully used this pattern in several cases: (sketchy and likely buggy, but you get the point).</p> <pre><code>STOP = object() def consumer(q): while True: x = q.get() if x is STOP: return consume(x) def main() q = Queue() c=threading.Thread(target=consumer,args=[q]) try: run_producer(q) except KeybordInterrupt: q.enqueue(STOP) c.join() </code></pre>
26,152
<p>Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where <em>only</em> the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is. The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008" Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ? thanks, Ian</p>
<p>You could create a struct Date that provides access to the details you want/need, like:</p> <pre><code>public struct Date { public int Month; //or string instead of int public int Day; public int Year; } </code></pre> <p>This is lightweight, flexible and gives you full control.</p>
<p>You can send it as UTC Time</p> <p>dateTime1.ToUniversalTime()</p>
10,518
<p><strong>Update:</strong> This turned into a blog post, with updated links and code, over at my blog: <a href="https://egilhansen.com/2008/12/01/how-to-take-control-of-style-sheets-in-asp-net-themes-with-the-styleplaceholder-and-style-control/" rel="nofollow noreferrer">https://egilhansen.com/2008/12/01/how-to-take-control-of-style-sheets-in-asp-net-themes-with-the-styleplaceholder-and-style-control/</a></p> <hr> <p>The problem is pretty simple. When using ASP.NET Themes you do not have much say in how your style sheets are rendered to the page.</p> <p>The render engine adds all the style sheets you have in your themes folder in alphabetic order, using the &lt;link href=”...” notation.</p> <p>We all know the order of the style sheets are important, luckily asp.nets shortcomings can be circumvented by prefixing the style sheets with 01, 02, ... , 99, and thus forcing the order you want (see Rusty Swayne <a href="http://rustyswayne.com/post.aspx?id=cba116ea-b672-4c90-9f4e-18b70ca2f50a" rel="nofollow noreferrer">blog post</a> on the technique for more information).</p> <p>This is especially important if you use a reset style sheet, which I highly recommend; it makes it much easier to style a site in a consistent form across browsers (take a look at <a href="http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/" rel="nofollow noreferrer">Reset Reloaded from Eric Meyer</a>).</p> <p>You also miss out of the possibility to specify a media type (e.g. screen, print, projection, braille, speech). And if you prefer to include style sheets using the @import method, you are also left out in the cold.</p> <p>Another missing option is Conditional Comment, which is especially useful if you use an “ie-fix.css” style sheet.</p> <p>Before I explain how the StylePlaceholder and Style control resolve the above issues, credit where credit is due, my solution is inspired by <a href="http://www.dentaku.com/2007/01/take-control-over-stylesheet-order-and-media-when-using-asp-net-2-0-themes.aspx" rel="nofollow noreferrer">Per Zimmerman’s blog post</a> on the subject.</p> <p>The StylePlaceHolder control is placed in the header section of your master page or page. It can host one or more Style controls, and will remove styles added by the render engine by default, and add its own (it will only remove styles added from the current active theme).</p> <p>The Style control can both host inline styles in-between it’s opening and closing tags and a reference to a external style sheet file through its CssUrl property. With other properties you control how the style sheet it renders to the page.</p> <p>Let me show an example. Consider a simple web site project with a master page and a theme with three style sheets – 01reset.css, 02style.css, 99iefix.cs. Note: I have named them using prefixing technique described earlier, as it makes for a better design time experience. Also, the tag prefix of the custom controls is “ass:”.</p> <p>In the master page’s header section, add:</p> <pre><code>&lt;ass:StylePlaceHolder ID="StylePlaceHolder1" runat="server" SkinID="ThemeStyles" /&gt; </code></pre> <p>In your theme directory, add a skin file (e.g. Styles.skin) and add the following content:</p> <pre><code>&lt;ass:StylePlaceHolder1runat="server" SkinId="ThemeStyles"&gt; &lt;ass:Style CssUrl="~/App_Themes/Default/01reset.css" /&gt; &lt;ass:Style CssUrl="~/App_Themes/Default/02style.css" /&gt; &lt;ass:Style CssUrl="~/App_Themes/Default/99iefix.css" ConditionCommentExpression="[if IE]" /&gt; &lt;/ass:StylePlaceHolder1&gt; </code></pre> <p>That is basically it. There are a more properties on the Style control that can be used to control the rendering, but this is the basic setup. With that in place, you can easily add another theme and replace all the styles, since you only need to include a different skin file.</p> <p>Now to the code that makes it all happen. I must admit that the design time experience have some quirks. It is probably due to the fact that I am not very proficient in writing custom controls (in fact, these two are my first attempts), so I would very much like input on the following. In a current WCAB/WCSF based project I am developing, I am seeing errors like this in Visual Studios design view, and I have no idea why. The site compiles and everything works online.</p> <p><a href="http://www.egil.dk/wp-content/styleplaceholder-error.jpg" rel="nofollow noreferrer">Example of design time error in Visual Studio http://www.egil.dk/wp-content/styleplaceholder-error.jpg</a></p> <p>The following is the code for the StylePlaceHolder control:</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; [assembly: TagPrefix("Assimilated.Extensions.Web.Controls", "ass")] namespace Assimilated.WebControls.Stylesheet { [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] [DefaultProperty("SkinID")] [ToolboxData("&lt;{0}:StylePlaceHolder runat=\"server\" SkinID=\"ThemeStyles\"&gt;&lt;/{0}:StylePlaceHolder&gt;")] [ParseChildren(true, "Styles")] [Themeable(true)] [PersistChildren(false)] public class StylePlaceHolder : Control { private List&lt;Style&gt; _styles; [Browsable(true)] [Category("Behavior")] [DefaultValue("ThemeStyles")] public override string SkinID { get; set; } [Browsable(false)] public List&lt;Style&gt; Styles { get { if (_styles == null) _styles = new List&lt;Style&gt;(); return _styles; } } protected override void CreateChildControls() { if (_styles == null) return; // add child controls Styles.ForEach(Controls.Add); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // get notified when page has finished its load stage Page.LoadComplete += Page_LoadComplete; } void Page_LoadComplete(object sender, EventArgs e) { // only remove if the page is actually using themes if (!string.IsNullOrEmpty(Page.StyleSheetTheme) || !string.IsNullOrEmpty(Page.Theme)) { // Make sure only to remove style sheets from the added by // the runtime form the current theme. var themePath = string.Format("~/App_Themes/{0}", !string.IsNullOrEmpty(Page.StyleSheetTheme) ? Page.StyleSheetTheme : Page.Theme); // find all existing stylesheets in header var removeCandidate = Page.Header.Controls.OfType&lt;HtmlLink&gt;() .Where(link =&gt; link.Href.StartsWith(themePath)).ToList(); // remove the automatically added style sheets removeCandidate.ForEach(Page.Header.Controls.Remove); } } protected override void AddParsedSubObject(object obj) { // only add Style controls if (obj is Style) base.AddParsedSubObject(obj); } } } </code></pre> <p>And the code for the Style control:</p> <pre><code>using System.ComponentModel; using System.Security.Permissions; using System.Web; using System.Web.UI; [assembly: TagPrefix("Assimilated.Extensions.Web.Controls", "ass")] namespace Assimilated.WebControls.Stylesheet { [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)] [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)] [DefaultProperty("CssUrl")] [ParseChildren(true, "InlineStyle")] [PersistChildren(false)] [ToolboxData("&lt;{0}:Style runat=\"server\"&gt;&lt;/{0}:Style&gt;")] [Themeable(true)] public class Style : Control { public Style() { // set default value... for some reason the DefaultValue attribute do // not set this as I would have expected. TargetMedia = "All"; } #region Properties [Browsable(true)] [Category("Style sheet")] [DefaultValue("")] [Description("The url to the style sheet.")] [UrlProperty("*.css")] public string CssUrl { get; set; } [Browsable(true)] [Category("Style sheet")] [DefaultValue("All")] [Description("The target media(s) of the style sheet. See http://www.w3.org/TR/REC-CSS2/media.html for more information.")] public string TargetMedia { get; set; } [Browsable(true)] [Category("Style sheet")] [DefaultValue(EmbedType.Link)] [Description("Specify how to embed the style sheet on the page.")] public EmbedType Type { get; set; } [Browsable(false)] [PersistenceMode(PersistenceMode.InnerDefaultProperty)] public string InlineStyle { get; set; } [Browsable(true)] [Category("Conditional comment")] [DefaultValue("")] [Description("Specifies a conditional comment expression to wrap the style sheet in. See http://msdn.microsoft.com/en-us/library/ms537512.aspx")] public string ConditionalCommentExpression { get; set; } [Browsable(true)] [Category("Conditional comment")] [DefaultValue(CommentType.DownlevelHidden)] [Description("Whether to reveal the conditional comment expression to downlevel browsers. Default is to hide. See http://msdn.microsoft.com/en-us/library/ms537512.aspx")] public CommentType ConditionalCommentType { get; set; } [Browsable(true)] [Category("Behavior")] public override string SkinID { get; set; } #endregion protected override void Render(HtmlTextWriter writer) { // add empty line to make output pretty writer.WriteLine(); // prints out begin condition comment tag if (!string.IsNullOrEmpty(ConditionalCommentExpression)) writer.WriteLine(ConditionalCommentType == CommentType.DownlevelRevealed ? "&lt;!{0}&gt;" : "&lt;!--{0}&gt;", ConditionalCommentExpression); if (!string.IsNullOrEmpty(CssUrl)) { // add shared attribute writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); // render either import or link tag if (Type == EmbedType.Link) { // &lt;link href=\"{0}\" type=\"text/css\" rel=\"stylesheet\" media=\"{1}\" /&gt; writer.AddAttribute(HtmlTextWriterAttribute.Href, ResolveUrl(CssUrl)); writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet"); writer.AddAttribute("media", TargetMedia); writer.RenderBeginTag(HtmlTextWriterTag.Link); writer.RenderEndTag(); } else { // &lt;style type="text/css"&gt;@import "modern.css" screen;&lt;/style&gt; writer.RenderBeginTag(HtmlTextWriterTag.Style); writer.Write("@import \"{0}\" {1};", ResolveUrl(CssUrl), TargetMedia); writer.RenderEndTag(); } } if(!string.IsNullOrEmpty(InlineStyle)) { // &lt;style type="text/css"&gt;... inline style ... &lt;/style&gt; writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css"); writer.RenderBeginTag(HtmlTextWriterTag.Style); writer.Write(InlineStyle); writer.RenderEndTag(); } // prints out end condition comment tag if (!string.IsNullOrEmpty(ConditionalCommentExpression)) { // add empty line to make output pretty writer.WriteLine(); writer.WriteLine(ConditionalCommentType == CommentType.DownlevelRevealed ? "&lt;![endif]&gt;" : "&lt;![endif]--&gt;"); } } } public enum EmbedType { Link = 0, Import = 1, } public enum CommentType { DownlevelHidden = 0, DownlevelRevealed = 1 } } </code></pre> <p>So what do you guys think? Is this a good solution to the asp.net theme problem? And what about the code? I would really like some input on it, especially in regards to the design time experience.</p> <p>I uploaded a <a href="http://egilhansen.com/sites/default/files/node/9/assimilatedwebcontrols.zip" rel="nofollow noreferrer">zipped version of the Visual Studio solution</a> that contains the project, in case anyone is interested.</p> <p>Best regards, Egil.</p>
<p>Found the answer to my own question.</p> <p>The reason for the rendering errors I am getting in design mode, is an apparent bug in Visual Studio SP1, <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=361826" rel="nofollow noreferrer">which Microsoft has yet to fix</a>.</p> <p>So the above code works as expected, also in design mode, as long as you just include the custom controls in a pre compiled assembly, and not through another project in the same solution.</p> <p>See the link above for a more detailed explanation of how and why. </p>
<p>Works very smoothly.</p> <p>For those like me that never remember syntax of &lt;% tags here's what you need to add to the top of the master page definition and the skin file to register the namespace.</p> <pre><code>&lt;%@ Register TagPrefix="ass" Namespace="Assimilated.WebControls.Stylesheet" %&gt; </code></pre> <p>I'm not sure I want that much 'ass' all over my code, but otherwise I like it.</p> <p>Oh and if this is really your first custom control great job. I know it was inspired by someone else's code but it at least <strong>appears</strong> to have all the right attributes and interfaces.</p>
42,596
<p>If you have a situation where you need to know where a boolean value wasn't set (for example if that unset value should inherit from a parent value) the Java boolean primitive (and the equivalent in other languages) is clearly not adequate.</p> <p>What's the best practice to achieve this? Define a new simple class that is capable of expressing all three states or use the Java Boolean class and use null to indicate the unset state?</p>
<pre><code>Boolean a = true; Boolean b = false; Boolean c = null; </code></pre> <p>I would use that. It's the most straight-forward.</p> <p>Another way is to use an enumeration. Maybe that's even better and faster, since no boxing is required:</p> <pre><code>public enum ThreeState { TRUE, FALSE, TRALSE }; </code></pre> <p>There is the advantage of the first that users of your class doesn't need to care about your three-state boolean. They can still pass <code>true</code> and <code>false</code>. If you don't like the <code>null</code>, since it's telling rather little about its meaning here, you can still make a <code>public static final Boolean tralse = null;</code> in your class.</p>
<p>java.lang.Boolean does this for you. There are static constants Boolean.TRUE, Boolean.False. </p> <p>private Boolean myBoolean;</p> <p>should be all you need.Note that Boolean.TRUE will pass an equivalence test but is distinct from "true" (which gets autoboxed to TRUE). </p>
40,637
<p>Our application has a file format similar to the OpenDocument file format (see <a href="http://en.wikipedia.org/wiki/OpenDocument" rel="noreferrer">http://en.wikipedia.org/wiki/OpenDocument</a>) - i.e. zipped with a manifest file, a thumbnail image, etc.</p> <p>I notice that OpenOffice files have a preview image of the Open Office file as their icons, both in Windows and in Linux. Is there some way to accomplish this for our files: i.e. I want a dynamic icon based on the internal thumbnail.png?</p> <p><strong>Edit 1</strong> Wow, thanks for all the quick answers. <a href="http://library.gnome.org/devel/integration-guide/stable/thumbnailer.html.en" rel="noreferrer">Thumbnailer</a> looks great for the GNOME world. Windows I'll be looking into those links, thanks. As for the comment question: programmatically OR via our installer.</p> <p><strong>Edit 2</strong> Oh, forgot Mac. How about on the Mac? (Sorry Mac lovers!) Also are there any links or info for how OpenOffice does their IconHandler stuff - since ours would be very similar?</p>
<h2>Windows</h2> <p>What you need is an <a href="http://msdn.microsoft.com/en-us/library/bb776857(VS.85).aspx" rel="nofollow noreferrer">Icon Handler</a>, also known as a Thumbnail Handler. Here is an example written as an <a href="http://www.shellplus.com/examples/thumbnail-image-handler-example.html" rel="nofollow noreferrer">active x control</a>.</p> <p>Another resource is to look up <a href="http://blogs.msdn.com/benkaras/archive/2007/01/21/what-do-property-handlers-accomplish.aspx" rel="nofollow noreferrer">Property Handlers</a>, which should also point to you to the latest and greatest way of having dynamic meta data handled correctly in windows.</p> <p>These are <em>dynamic</em> solutions - they aren't needed if you just want an icon associated with all your files - they are only used when you want windows explorer to display an icon based on what's in the file, not just the extension, and when the file changes the icon is updated to reflect the changes. It doesn't have to be an image of the file itself, either, the thumbnail handler can generate any image based on the file contents.</p> <p>The property handler updates other metadata, such as song or video length, so you can use all the metadata Windows Explorer supports.</p> <p>Regarding MAC support, <a href="http://blogs.adobe.com/indesignchannel/2007/10/thumbnail_icons.html" rel="nofollow noreferrer">this page</a> says, "The Mac and Windows operating systems have different methods of enabling this type of thumbnail, and in the case of the Mac OS, this support has been inconsistent from version to version so it hasn't been pursued [for Adobe InDesign]."</p> <h2>OS X</h2> <p>Icons for Mac OSX are determined by the <a href="http://developer.apple.com/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCConcepts/chapter_2_section_4.html" rel="nofollow noreferrer">Launch Services Database</a>. However, it refers to a static icon file for all files handled by a registered application (it's not based on extension - each file has meta data attached that determines the application to which it belongs, although extensions give hints when the meta data doesn't exist, such as getting the file from a different OS or file system)</p> <p>It appears that the dynamic icon functionality in OSX is provided by Finder, but searches aren't bringing up any easy pointers in this direction. Since Finder keeps changing over time, I can see why this target is hard to hit...</p> <h2>Gnome</h2> <p>For Gnome you use a <a href="http://library.gnome.org/devel/integration-guide/stable/thumbnailer.html.en" rel="nofollow noreferrer">thumbnailer</a>. (thanks <a href="https://stackoverflow.com/questions/120865/how-do-i-get-files-in-my-own-file-format-to-have-its-own-dynamic-icon#120887">Dorward</a>)</p> <p>This is an extraordinarily simple program you write, which has 3 command line arguments:</p> <ul> <li>input file name, the file you are describing with the thumbnail (or URI if you accept those instead)</li> <li>output file name, where you need to write the PNG</li> <li>size, a number, in pixels, that describes the maximum square image size you should produce (128 --> 128x128 or smaller)</li> </ul> <p>I wish all systems were this simple. On the other hand this doesn't support animation and a few other features that are provided by more difficult to implement plugins on other systems.</p> <h2>KDE</h2> <p>I'm a bit uncertain, but there are a few pointers that should get you started. First is that Konqueror is the file manager and displays the icons - it supports dynamic icons for some inbuilt types, but I don't know if these are hardcoded, or plugins you can write. Check out the <a href="http://konqueror.kde.org/componentstutorial/" rel="nofollow noreferrer">Embedded Components Tutorial</a> for a starting point.</p> <p>There's a new (ish?) feature (or planned feature...) called Plasma which has a great deal to do with icons and icon functionality. Check out <a href="http://liquidat.wordpress.com/2007/06/20/kde-4-news-plasma-icons-solid-information-and-taskbar-mockups/" rel="nofollow noreferrer">this announcment</a> and <a href="http://blog.ruphy.org/?p=11" rel="nofollow noreferrer">this initial implementation</a>.</p> <p>You may need to dig into the source of Konqueror and check out how they did this for text files and others already implemented.</p> <p>-Adam</p>
<p>This is up to the operating system as far as I know, it will be based on the file extension. </p>
14,697
<p>What is the most efficient way to remove duplicate items from an array under the constraint that axillary memory usage must be to a minimum, preferably small enough to not even require any heap allocations? Sorting seems like the obvious choice, but this is clearly not asymptotically efficient. Is there a better algorithm that can be done in place or close to in place? If sorting is the best choice, what kind of sort would be best for something like this?</p>
<p>I'll answer my own question since, after posting, I came up with a really clever algorithm to do this. It uses hashing, building something like a hash set in place. It's guaranteed to be O(1) in axillary space (the recursion is a tail call), and is typically O(N) time complexity. The algorithm is as follows:</p> <ol> <li>Take the first element of the array, this will be the <strong>sentinel</strong>.</li> <li>Reorder the rest of the array, as much as possible, such that each element is in the position corresponding to its hash. As this step is completed, duplicates will be discovered. Set them equal to sentinel.</li> <li>Move all elements for which the index is equal to the hash to the beginning of the array.</li> <li>Move all elements that are equal to sentinel, except the first element of the array, to the end of the array.</li> <li>What's left between the properly hashed elements and the duplicate elements will be the elements that couldn't be placed in the index corresponding to their hash because of a collision. Recurse to deal with these elements.</li> </ol> <p>This can be shown to be O(N) provided no pathological scenario in the hashing: Even if there are no duplicates, approximately 2/3 of the elements will be eliminated at each recursion. Each level of recursion is O(n) where small n is the amount of elements left. The only problem is that, in practice, it's slower than a quick sort when there are few duplicates, i.e. lots of collisions. However, when there are huge amounts of duplicates, it's amazingly fast.</p> <p>Edit: In current implementations of D, hash_t is 32 bits. Everything about this algorithm assumes that there will be very few, if any, hash collisions in full 32-bit space. Collisions may, however, occur frequently in the modulus space. However, this assumption will in all likelihood be true for any reasonably sized data set. If the key is less than or equal to 32 bits, it can be its own hash, meaning that a collision in full 32-bit space is impossible. If it is larger, you simply can't fit enough of them into 32-bit memory address space for it to be a problem. I assume hash_t will be increased to 64 bits in 64-bit implementations of D, where datasets can be larger. Furthermore, if this ever did prove to be a problem, one could change the hash function at each level of recursion.</p> <p>Here's an implementation in the D programming language:</p> <pre><code>void uniqueInPlace(T)(ref T[] dataIn) { uniqueInPlaceImpl(dataIn, 0); } void uniqueInPlaceImpl(T)(ref T[] dataIn, size_t start) { if(dataIn.length - start &lt; 2) return; invariant T sentinel = dataIn[start]; T[] data = dataIn[start + 1..$]; static hash_t getHash(T elem) { static if(is(T == uint) || is(T == int)) { return cast(hash_t) elem; } else static if(__traits(compiles, elem.toHash)) { return elem.toHash; } else { static auto ti = typeid(typeof(elem)); return ti.getHash(&amp;elem); } } for(size_t index = 0; index &lt; data.length;) { if(data[index] == sentinel) { index++; continue; } auto hash = getHash(data[index]) % data.length; if(index == hash) { index++; continue; } if(data[index] == data[hash]) { data[index] = sentinel; index++; continue; } if(data[hash] == sentinel) { swap(data[hash], data[index]); index++; continue; } auto hashHash = getHash(data[hash]) % data.length; if(hashHash != hash) { swap(data[index], data[hash]); if(hash &lt; index) index++; } else { index++; } } size_t swapPos = 0; foreach(i; 0..data.length) { if(data[i] != sentinel &amp;&amp; i == getHash(data[i]) % data.length) { swap(data[i], data[swapPos++]); } } size_t sentinelPos = data.length; for(size_t i = swapPos; i &lt; sentinelPos;) { if(data[i] == sentinel) { swap(data[i], data[--sentinelPos]); } else { i++; } } dataIn = dataIn[0..sentinelPos + start + 1]; uniqueInPlaceImpl(dataIn, start + swapPos + 1); } </code></pre>
<p>If you sort the array, you will still need another pass to remove duplicates, so the complexity is O(N<em>N) in the worst case (assuming Quicksort), or O(N</em>sqrt(N)) using Shellsort.</p> <p>You can achieve O(N*N) by simply scanning the array for each element removing duplicates as you go.</p> <p>Here is an example in Lua:</p> <pre><code>function removedups (t) local result = {} local count = 0 local found for i,v in ipairs(t) do found = false if count &gt; 0 then for j = 1,count do if v == result[j] then found = true; break end end end if not found then count = count + 1 result[count] = v end end return result, count end </code></pre>
46,701
<p>I am trying to write out a png file from a java.awt.image.BufferedImage. Everything works fine but the resulting png is a 32-bit file.</p> <p>Is there a way to make the png file be 8-bit? The image is grayscale, but I do need transparency as this is an overlay image. I am using java 6, and I would prefer to return an OutputStream so that I can have the calling class deal with writing out the file to disk/db.</p> <p>Here is the relevant portion of the code:</p> <pre><code> public static ByteArrayOutputStream createImage(InputStream originalStream) throws IOException { ByteArrayOutputStream oStream = null; java.awt.Image newImg = javax.imageio.ImageIO.read(originalStream); int imgWidth = newImg.getWidth(null); int imgHeight = newImg.getHeight(null); java.awt.image.BufferedImage bim = new java.awt.image.BufferedImage(imgWidth, imgHeight, java.awt.image.BufferedImage.TYPE_INT_ARGB); Color bckgrndColor = new Color(0x80, 0x80, 0x80); Graphics2D gf = (Graphics2D)bim.getGraphics(); // set transparency for fill image gf.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f)); gf.setColor(bckgrndColor); gf.fillRect(0, 0, imgWidth, imgHeight); oStream = new ByteArrayOutputStream(); javax.imageio.ImageIO.write(bim, "png", oStream); oStream.close(); return oStream; } </code></pre>
<p>The build in imageio png writer will write 32bit png files on all the platforms I have used it on, no matter what the source image is. You should also be aware that many people have complained that the resulting compression is much lower than what is possible with the png format. There are several independent <a href="http://www.catcode.com/pngencoder/" rel="nofollow noreferrer">png libraries</a> available that allow you to specify the exact format, but I don't actually have any experience with any of them.</p>
<p>Thanks for responding, I was going to try an <code>TYPE_BYTE_INDEXED</code> with an IndexColorModel and may still but if ImageIO writes out 32-bit regardless it appears that I may be wasting my time there. </p> <p>The image I am trying to write out can be very large (up to 8000x4000) but is just a simple mask for the image underneath, so will only have a ~30% transparent gray and a 100% transparent cutout. I would use a GIF but IE6 seems to have trouble with displaying one that large. </p> <p>It only gets generated once and in an internal set-up type screen, so performance isn't an issue either, but it does have to be done within the java code and not by an offline utility.</p> <p>The libraries that you specified might be used to transform it while writing... I am going to go check that out.</p> <p>If anyone has a better way, please let me know!! </p> <p>Thanks!</p>
33,410
<p>I am opening a XML file using .NET XmlReader and saving the file in another filename and it seems that the DOCTYPE declaration changes between the two files. While the newly saved file is still valid XML, I was wondering why it insisted on changing original tags.</p> <pre><code>Dim oXmlSettings As Xml.XmlReaderSettings = New Xml.XmlReaderSettings() oXmlSettings.XmlResolver = Nothing oXmlSettings.CheckCharacters = False oXmlSettings.ProhibitDtd = False oXmlSettings.IgnoreWhitespace = True Dim oXmlDoc As XmlReader = XmlReader.Create(pathToOriginalXml, oXmlSettings) Dim oDoc As XmlDocument = New XmlDocument() oDoc.Load(oXmlDoc) oDoc.Save(pathToNewXml) </code></pre> <p>The following (in the original document):</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"&gt; </code></pre> <p>becomes (notice the [ ] characters at the end): </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd"[]&gt; </code></pre>
<p>There is a bug in System.Xml when you set XmlDocument.XmlResolver = null. The workaround is to create a custom XmlTextWriter:</p> <pre><code> private class NullSubsetXmlTextWriter : XmlTextWriter { public NullSubsetXmlTextWriter(String inputFileName, Encoding encoding) : base(inputFileName, encoding) { } public override void WriteDocType(string name, string pubid, string sysid, string subset) { if (subset == String.Empty) { subset = null; } base.WriteDocType(name, pubid, sysid, subset); } } </code></pre> <p>In your code, create a new NullSubsetXmlTextWriter(pathToNewXml, Encoding.UTF8) and pass that object to the oDoc.Save() method.</p> <p>Here is the <a href="http://www.vistax64.com/net-general/215921-xmldocument-save-null-xmlresolver-modifies-doctype-tag.html" rel="noreferrer">Microsoft support case</a> where you can read about the workaround (it describes the workaround but doesn't provide the code).</p>
<p>This is best solution for you:</p> <pre><code>writer.WriteDocType("Name", Nothing, "http://xml.cxml.org/schemas/cXML/1.2.033/Fulfill.dtd", Nothing) </code></pre> <p>If you use <code>Nothing</code> you will not get [] or "" etc</p>
36,082
<p>We have a case where clients seem to be eternally caching versions of applets. We're making use of the <code>&lt;param name="cache_version"&gt;</code> tag correctly within our <code>&lt;object&gt;</code> tag, or so we think. We went from a version string of <code>7.1.0.40</code> to <code>7.1.0.42</code> and this triggered a download for only about half of our clients.</p> <p>It doesn't seem to matter which version of the JRE the client is running. We've seen people have this problem on 1.4, 1.5 and 1.6.</p> <p>Does anybody have experience with explicit cache versions? Does it work more reliably (ignoring speed) to instead rely on the <code>cache_archive</code>'s "Last-Modified" and/or "Content-Length" values (as per <a href="http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/applet_caching.html" rel="noreferrer">Sun's Site</a>)?</p> <p>FYI, object block looks like this:</p> <pre><code>&lt;object&gt; &lt;param name="ARCHIVE" value="foo.jar"&gt; &lt;param name="CODE" value="com.foo.class"&gt; &lt;param name="CODEBASE" value="."&gt; &lt;param name="cache_archive" value="foo.jar"&gt; &lt;param name="cache_version" value="7.1.0.40"&gt; &lt;param name="NAME" value="FooApplet"&gt; &lt;param name="type" value="application/x-java-applet;jpi-version=1.4.2_13"&gt; &lt;param name="scriptable" value="true"&gt; &lt;param name="progressbar" value="true"/&gt; &lt;param name="boxmessage" value="Loading Web Worksheet Applet..."/&gt; &lt;/object&gt; </code></pre>
<p>Unfortunately, different versions of the Java Plug-In have different caching behaviors. Setting your Cache-Control and Last-Modified HTTP headers is the ideal solution, but it only works under <a href="http://java.sun.com/javase/6/docs/technotes/guides/deployment/enhancements.html" rel="noreferrer">the most recent versions</a> of the JRE. </p> <p>The only solution GUARANTEED to work is to rename your application jars when their versions change (we've seen strange caching behavior when trying other tricks like adding query strings based on file dates). This isn't so difficult to do if you have a properly automated deployment system. </p>
<p>As per <a href="http://docs.oracle.com/javase/1.3/docs/guide/misc/appletcaching.html" rel="nofollow">this link</a> , same jar file should not be listed int "archive" and "cache_archive" params. In that case, the JAR file is cached using the native browser cache.</p>
9,241
<p>I want to create a Silverlight 2 control that has two content areas. A Title and a MainContent. So the control would be:</p> <pre><code>&lt;StackPanel&gt; &lt;TextBlock Text=" CONTENT1 "/&gt; &lt;Content with CONTENT2 "/&gt; &lt;/StackPanel&gt; </code></pre> <p>When I use the control I should just be able to use:</p> <pre><code>&lt;MyControl Text="somecontent"&gt;main content &lt;/MyControl&gt; </code></pre> <p>How can I create such a control?</p>
<p>You can do that easily with the <a href="http://msdn.microsoft.com/en-us/library/system.windows.markup.contentpropertyattribute.aspx" rel="nofollow noreferrer">ContentProperty</a> attribute.</p> <p>Then you can define your code behind as:</p> <pre><code>[ContentProperty("Child")] public partial class MyControl: UserControl { public static readonly DependencyProperty ChildProperty = DependencyProperty.Register("Child", typeof(UIElement), typeof(MyControl), null); public UIElement Child { get { return (UIElement)this.GetValue(ChildProperty); } set { this.SetValue(ChildProperty, value); this.content.Content = value; } } </code></pre> <p>What that will do is any default content within your tags (<code>&lt;MyControl Text="somecontent"&gt;main content &lt;/MyControl&gt;</code>) - will be set as the Child property on your class. Then once it's been set you can assign it to any control you like.</p> <p><strong>Edit:</strong></p> <p>You can have as many contents as you like, but you can only have 1 auto-content (which is designated via the ContentProperty attribute). If you want two you could do:</p> <pre><code>&lt;MyControl&gt; &lt;MyControl.Content1&gt;Hello World&lt;/MyControl.Content1&gt; &lt;MyControl.Content2&gt;Goodbye World&lt;/MyControl.Content2&gt; &lt;/MyControl&gt; </code></pre> <p>All you have to do is make sure you have the matching dependency properties in your code. Then when the property is set, just assign it to a parent content control in your XAML.</p>
<p>What you wanted is a Silverlight version of the WPF HeaderedContentControl You can find a try here. <a href="http://leeontech.wordpress.com/2008/03/11/headeredcontentcontrol-sample/" rel="nofollow noreferrer">http://leeontech.wordpress.com/2008/03/11/headeredcontentcontrol-sample/</a></p>
25,480
<p>I have a need to open a popup detail window from a gridview (VS 2005 / 2008). What I am trying to do is in the markup for my TemplateColumn have an asp:Button control, sort of like this:</p> <pre><code>&lt;asp:Button ID="btnShowDetails" runat="server" CausesValidation="false" CommandName="Details" Text="Order Details" onClientClick="window.open('PubsOrderDetails.aspx?OrderId=&lt;%# Eval("order_id") %&gt;', '','scrollbars=yes,resizable=yes, width=350, height=550');" </code></pre> <p>Of course, what isn't working is the appending of the &lt;%# Eval...%> section to set the query string variable.</p> <p>Any suggestions? Or is there a far better way of achieving the same result?</p>
<p>I believe the way to do it is</p> <blockquote> <pre><code>onClientClick=&lt;%# string.Format("window.open('PubsOrderDetails.aspx?OrderId={0}',scrollbars=yes,resizable=yes, width=350, height=550);", Eval("order_id")) %&gt; </code></pre> </blockquote>
<p>I like @<a href="https://stackoverflow.com/questions/102343/including-eval-bind-values-in-onclientclick-code#102373">AviewAnew</a>'s suggestion, though you can also just write that from the code-behind by wiring up and event to the grid views ItemDataBound event. You'd then use the FindControl method on the event args you get to grab a reference to your button, and set the <em>onclick</em> attribute to your window.open statement.</p>
12,788
<p>I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.</p> <p>I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table.</p> <p>The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK"</p> <p>What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like:</p> <pre><code>ID NAME SPECIALTYPE 1 Red Dragon Archfiend Synchro 1 Red Dragon Archfiend DARK 1 Red Dragon Archfiend Effect </code></pre> <p>and I could tally my results that way.</p> <p>I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like:</p> <pre><code>1 Red Dragon Archfiend Synchro/DARK/Effect </code></pre> <p>..but I don't know if that's feasible.</p> <p>Help me stackoverflow Kenobi! You're my only hope.</p>
<p>Is this for SQL server?</p> <p>If yes then</p> <p><a href="http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column" rel="nofollow noreferrer">Concatenate Values From Multiple Rows Into One Column (2000)</a><br> <a href="http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column_Ordered" rel="nofollow noreferrer">Concatenate Values From Multiple Rows Into One Column Ordered (2005+)</a></p>
<p>Don't collapse by concatenation for storage of related records in your database. Its not exactly best practices. </p> <p>What you're describing is a pivot table. Pivot tables are <em>hard</em>. I'd suggest avoiding them if at all possible. </p> <p>Why not just read in your related rows and process them in memory? It doesn't sound like you're going to spend too many milliseconds doing this...</p>
3,881
<p>I'm working on a free software (bsd license) project with others. We're searching for a system that check out our source code (svn) and build it also as test it (unit tests with Check / other tools).</p> <p>It should have a webbased interface and generate reports.</p> <p>I hope we don't have to write such a system from null by ourselves...</p>
<p>You surely do not have to code this yourself - there are a lot of <a href="http://en.wikipedia.org/wiki/Continuous_integration" rel="nofollow noreferrer">continuous integration</a> systems which are able to check out source code from systems such as SVN and they are generally easy to extend with your own tasks, so running custom test scripts/programs should not be a problem.</p> <p>While these CI systems are probably not written in C, this does not matter, since they just need to be able to access and compile your source code, for which they will use an external compiler anyways.</p> <p>Just to list some of the well known CI tools:</p> <ul> <li><a href="http://cruisecontrol.sourceforge.net/" rel="nofollow noreferrer">CruiseControl</a></li> <li><a href="http://hudson-ci.org/" rel="nofollow noreferrer">Hudson</a></li> <li><a href="http://www.jetbrains.com/teamcity/" rel="nofollow noreferrer">TeamCity</a></li> </ul> <p>You might also be interested in other <a href="https://stackoverflow.com/questions/tagged/continuous-integration">questions on Stack Overflow tagged as continuous-integration</a>. :)</p>
<p>Check out <a href="http://buildbot.net/trac" rel="nofollow noreferrer">buildbot</a></p>
22,112
<p>Do you have any tricks for generating SQL statements, mainly INSERTs, in Excel for various data import scenarios?</p> <p>I'm really getting tired of writing formulas with like </p> <p><code>="INSERT INTO Table (ID, Name) VALUES (" &amp; C2 &amp; ", '" &amp; D2 &amp; "')"</code></p>
<p>The semi-colon needs to be inside the last double quote with a closing paren. When adding single quotes around a string, remember to add them outside your selected cell. </p> <p>(spaces added for visibility - remove before inserting)</p> <p><code>=CONCATENATE("insert into table (id, name) values (",C2,",' ",D2," ');")</code></p> <p>Here is another view:</p> <p><code>=CONCATENATE("insert into table (id, date, price) values (",C3,",'",D3,"',",B3,");")</code></p>
<p>I was doing this yesterday, and yes, it's annoying to get the quotes right. One thing I did was have a named cell that just contained a single quote. Type into A1 <code>="'"</code> (equals, double quote, single quote, double quote) and then name this cell "QUOTE" by typing that in the box on the left of the lowest toolbar.</p>
40,728
<p>I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.</p> <p>But if I try to do a redirect or simply do an 'alert' on the link array element I get: </p> <blockquote> <p>function(){return JSON.encode(this);}</p> </blockquote> <p>As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.</p> <p>After following some suggestions I've run <code>eval('(' + jsonObject + ')')</code> but it still returns the same output.</p> <p>So how's this done ? </p>
<pre><code>var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" ); </code></pre> <p><a href="http://api.jquery.com/jQuery.parseJSON/" rel="noreferrer">See the jQuery API</a>.</p>
<p>I decode JSON this way:</p> <pre><code>eval( 'var from_json_object = ' + my_json_str + ';' ); </code></pre>
22,044
<p>For example:</p> <pre><code>&gt;&gt;&gt; x = [1, 1, 2, 'a', 'a', 3] &gt;&gt;&gt; unique(x) [1, 2, 'a', 3] </code></pre> <p>Assume list elements are hashable.</p> <p><strong>Clarification:</strong> The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].</p>
<pre><code>def unique(items): found = set() keep = [] for item in items: if item not in found: found.add(item) keep.append(item) return keep print unique([1, 1, 2, 'a', 'a', 3]) </code></pre>
<p>I haven't done any tests, but one possible algorithm might be to create a second list, and iterate through the first list. If an item is not in the second list, add it to the second list.</p> <pre><code>x = [1, 1, 2, 'a', 'a', 3] y = [] for each in x: if each not in y: y.append(each) </code></pre>
11,474
<p>I can only think of Peek() and ReadNoAdvance() atm, but I wonder if there are better or standard options.</p> <p>Thanks.</p>
<p>peek is the standard name, present in various languages.</p>
<p>When writing parsers I've often also used <code>lookahead</code>.</p>
40,935
<p>Explain why a nullable int can't be assigned the value of null e.g</p> <pre><code>int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr)); </code></pre> <p>What's wrong with that code?</p>
<p>The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:</p> <pre><code>int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr)); </code></pre>
<p>Similarly I did for long:</p> <pre><code>myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null; </code></pre>
42,809
<p>What is the maximum size for a MySQL table? Is it 2 million at 50GB? 5 million at 80GB?</p> <p>At the higher end of the size scale, do I need to think about compressing the data? Or perhaps splitting the table if it grew too big?</p>
<p>I once worked with a very large (Terabyte+) MySQL database. The largest table we had was literally over a billion rows. </p> <p>It worked. MySQL processed the data correctly most of the time. It was extremely unwieldy though. </p> <p>Just backing up and storing the data was a challenge. It would take days to restore the table if we needed to.</p> <p>We had numerous tables in the 10-100 million row range. Any significant joins to the tables were too time consuming and would take forever. So we wrote stored procedures to 'walk' the tables and process joins against ranges of 'id's. In this way we'd process the data 10-100,000 rows at a time (Join against id's 1-100,000 then 100,001-200,000, etc). This was significantly faster than joining against the entire table.</p> <p>Using indexes on very large tables that aren't based on the primary key is also much more difficult. Mysql stores indexes in two pieces -- it stores indexes (other than the primary index) as indexes to the primary key values. So indexed lookups are done in two parts: First MySQL goes to an index and pulls from it the primary key values that it needs to find, then it does a second lookup on the primary key index to find where those values are. </p> <p>The net of this is that for very large tables (1-200 Million plus rows) indexing against tables is more restrictive. You need fewer, simpler indexes. And doing even simple select statements that are not directly on an index may never come back. Where clauses <em>must</em> hit indexes or forget about it.</p> <p>But all that being said, things did actually work. We were able to use MySQL with these very large tables and do calculations and get answers that were correct.</p>
<p>About your first question, the effective maximum size for the <em>database</em> is usually determined by operating system, specifically the file size MySQL Server will be able to create, not by MySQL Server itself. Those limits play a big role in <em>table</em> size limits. And MyISAM works differently from InnoDB. So any tables will be dependent on those limits.</p> <p>If you use InnoDB you will have more options on manipulating table sizes, resizing the tablespace is an option in this case, so if you plan to resize it, this is the way to go. Give a look at <a href="http://dev.mysql.com/doc/refman/5.0/en/full-table.html" rel="nofollow noreferrer">The table is full</a> error page.</p> <p>I am not sure the real record quantity of each table given all necessary information (OS, Table type, Columns, data type and size of each and etc...) And I am not sure if this info is easy to calculate, but I've seen simple table with around 1bi records in a couple cases and MySQL didn't gave up.</p>
7,110
<p>Char's are great because they are fixed size and thus make for a faster table. They are however limited to 255 characters. I want to hold 500 characters but a blob is variable length and that's not what I want.</p> <p>Is there some way to have a fixed length field of 500 characters in MySQL or am I going to have to use 2 char fields?</p>
<p>I would suggest using a varchar(500). Even though varchar isn't a fixed length, the database should reserve the correct amount of space. You shouldn't notice any performance difference using varchar(500) over 2xchar(255).</p> <p>You're also probably going to cause extra overhead by joining two char fields together.</p>
<p>You're worrying too much about internal implementation details. Don't pre-optimize. </p> <p>Go with <code>VARCHAR(500)</code></p>
2,705
<p>I've have searched on this and it seems to be a catch all, unfortunately everything I've read doesn't help figure it out. Here is the class:</p> <pre><code>public interface IMockInterface { MockClass MockedMethod(); MockClass MockThis(); } public class MockClass : IMockInterface { public virtual MockClass MockedMethod() { MockClass returnValue; returnValue = new MockClass(); returnValue.SomeMessage = "Not mocked"; return returnValue; } public MockClass MockThis() { MockClass mock; MockClass returnValue; mock = new MockClass(); return mock.MockedMethod(); } } </code></pre> <p>And the test:</p> <pre><code>public void MockTest_Internal() { MockClass mainClass; MockClass returnedClass; IMockInterface mockProvider; mainClass = new MockClass(); mockProvider = repository.StrictMock&lt;IMockInterface&gt;(); Expect.Call(mockProvider.MockedMethod()) .Return(new MockClass { SomeMessage = "Mocked" }); repository.ReplayAll(); returnedClass = mainClass.MockThis(); provider.AssertWasCalled(item =&gt; item.MockedMethod()); Assert.IsTrue(returnedClass.SomeMessage == "Mocked"); } </code></pre> <p><strong>And have also tried and doesn't work</strong></p> <p>But I keep getting this exception:</p> <p>Rhino.Mocks.Exceptions.ExpectationViolationException:<br> IMockInterface.MockedMethod(); Expected #1, Actual #0</p> <p>Now from what I've read this would suggest either the method was called with different than expected parameters OR the method was never called but was expected to be called. This isn't the case for the test.</p> <p>Side Note: This is my first time really using Rhino.Mocks without some in house code so I am basically picking it up as I go. There could be something really stupid here...</p> <p><strong>This was the old test commented on, but is not what I should have been using:</strong></p> <pre><code>public void MockTest_Internal() { MockClass mainClass; MockClass returnedClass; IMockInterface mockProvider; mainClass = new MockClass(); var provider = MockRepository.GenerateStub&lt;IMockInterface&gt;(); provider.Stub(item =&gt; item.MockedMethod()) .Return(new MockClass { SomeMessage = "Mocked" }); returnedClass = mainClass.MockThis(); provider.AssertWasCalled(item =&gt; item.MockedMethod()); Assert.IsTrue(returnedClass.SomeMessage == "Mocked"); } </code></pre>
<p>You're telling the mock framework to stub the MockedMethod class on the provider object, but you never inject the provider into the mainClass object to be used. It's not clear to me what you are trying to accomplish but if you want the mocked method to be called then it has to be called on the object on which the stub was set up.</p> <p>If you define <code>MockThis</code> as below, I think you will find that it will work.</p> <pre><code>public MockClass MockThis(IMockInterface provider) { return provider.MockMethod(); } </code></pre> <p>The bottom line is that you get the exception because the method was never called on the provider, only on the mainClass object.</p> <p><strong>EDIT</strong>: Example</p> <pre><code>public class ClassUnderTest { private ProviderClass provider { get; set; } public ClassUnderTest( ProviderClass provider ) { this.Provider = provider; } public int DoOperation() { return this.Provider.ProviderOperation(); } } public class ProviderClass { private int value = 42; public ProviderClass() { } public virtual int ProviderOperation() { return this.value; } } [TestMethod] public void DoOperationTest() { ProviderClass mockProvider = MockRepository.GenerateMock&lt;ProviderClass&gt;(); mockProvider.Expect( mp =&gt; mp.ProviderOperation() ).Return( -1 ); ClassUnderTest target = new ClassUnderTest( mockProvider ); int expectedValue = -1; int value = target.DoOperation(); Assert.AreEqual( expectedValue, value ); mockProvider.VerifyAllExpectations(); } </code></pre> <p>Normally the ProviderClass object would return 42 from the ProviderOperation method, but we've mocked it out and told it to return -1. When the ClassUnderTest DoOperation method is called, the mock provider object's ProviderOperation method is invoked and returns the mocked value of -1.</p> <p>Hope this helps.</p>
<p>I usually get this error when a stubbed method is called with an object argument that I build in the test and in the tested code the object is built before calling that method. The solution is to use the <code>Rhino.Mocks Matches()</code>. </p> <p>Ex: </p> <pre><code>Arg&lt;string&gt;.Matches(s =&gt; s.Contains("some substring")) </code></pre>
48,298
<p>I have a table which has roughly 10 cells, 4 different types. I subclassed UITextViewCell because I wanted to have an IBOutlet to a label and to a UITextField. Not sure if that was the best way of handling it, but it works thus far. Next, I had a cell for gender, so I figured instead of subclassing UITableViewCell, I took my already subclassed cell with a UILabel and UITextField, and wrote the following code:</p> <pre><code>NSArray *buttonNames = [NSArray arrayWithObjects:@"Male", @"Female", nil]; UISegmentedControl* segmentedControl = [[UISegmentedControl alloc] initWithItems:buttonNames]; segmentedControl.momentary = YES; segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth; segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar; segmentedControl.frame = CGRectMake(75, 5, 130, 30); [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged]; for (UIView *oneView in cell.contentView.subviews) { if ([oneView isMemberOfClass:[UITextField class]]) { [cell.contentView insertSubview:segmentedControl aboveSubview:oneView]; [oneView removeFromSuperview]; } } [segmentedControl release]; </code></pre> <p>How horrible is that for going about this? Should I be subclassing UITableViewCell 5 times for one complex tableView? Is handling it in edge cases such as the following OK?</p>
<p>I'd actually go for subclassing. Subclassing is cheap. The cells have different types, and what you're doing now is iterating through all the subviews and checking each view for membership of a class - this is slow! A subclass will clean up your code and make it faster at the same time. Don't try to shoe-horn too many things into one container, as it were.</p>
<p>You could always just add the control to your subclass but have it hidden. Then, depending on the row, set the cell's "mode". The mode setter can hide / unhide the controls that pertain to that row. If performance is an issue, maybe use multiple cell IDs so that the views are cached.</p>
44,510
<p>I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore.</p> <p>Example:</p> <pre><code>input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] </code></pre> <p>I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.</p> <p>Any help would be greatly appreciated!</p>
<pre><code>var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); </code></pre> <p>... returns the array you're looking for.<br> Note, however:</p> <ul> <li>Bounding quotes are included, so can be removed with <code>replace(/^"([^"]+)"$/,"$1")</code> on the results.</li> <li>Spaces between the quotes will stay intact. So, if there are three spaces between <code>lorem</code> and <code>ipsum</code>, they'll be in the result. You can fix this by running <code>replace(/\s+/," ")</code> on the results.</li> <li>If there's no closing <code>"</code> after <code>ipsum</code> (i.e. an incorrectly-quoted phrase) you'll end up with: <code>['foo', 'bar', 'lorem', 'ipsum', 'baz']</code></li> </ul>
<p>One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like </p> <p><code>"hello my name is 'jon delaware smith fred' I have a 'long name'"</code>....</p> <p>A bit like the answer by AC but a bit neater...</p> <pre><code>function split(input, delimiter, joiner){ var output = []; var joint = []; input.split(delimiter).forEach(function(element){ if (joint.length &gt; 0 &amp;&amp; element.indexOf(joiner) === element.length - 1) { output.push(joint.join(delimiter) + delimiter + element); joint = []; } if (joint.length &gt; 0 || element.indexOf(joiner) === 0) { joint.push(element); } if (joint.length === 0 &amp;&amp; element.indexOf(joiner) !== element.length - 1) { output.push(element); joint = []; } }); return output; } </code></pre>
9,057
<p>It could be part of the model because it's part of the business logic of the game.</p> <p>It could be part of the controller because it could be seen as simulating player input, which would be considered part of the controller, right? Or would it?</p> <p>What about a normal enemy, like a goomba in Mario?</p> <p>UPDATE: Wow, that's really not the answer I was expecting. As far as I could tell, A.I. is an internal part of the autonomous game system, hence model. I'm still not convinced.</p>
<p>Remember that MVC was originally purely a GUI architectural pattern. So it is of no surprise that it doesn't map well to AI, networking, or whatever. But there are still some benefits to using it here. But what the code achieves is not as important as where it sits in the chain. Just because something looks like it's internal, doesn't mean that it is, and therefore shouldn't be counted as such.</p> <p>eg. If you're writing a bot, chances are high that you will essentially just be writing scripts to manipulate the characters. So in that sense, the script interface is the pre-existing Controller, and your scripts are completely external to that. You don't even go anywhere near the Model to write that high level AI..</p> <p>Now if you were the original programmer, who had to write low level AI functionality, which is triggered off either by player interaction (eg. clicking somewhere to start walking there) or by a bot-style script, then you would have been writing that into the Model.</p> <p>It may seem unintuitive to have any single concept such as 'AI' span all the way from model, through controller, and right out to whoever or whatever manipulates the controller, but that's how it goes when you attempt to map 2 very different concepts onto each other. It is obvious when you look at it from the perspective of a developer trying to present the same interfaces for non-player characters as they do for player-characters - ultimately the AI has to comprise both the high level decision making that an actor outside of the system would make, in addition to the low level implementation that typically exists for both players and non-players within the system.</p>
<p>Neither. I would program an AI as an independant agent communicating with the model via the controller. Or if you like, the AI is <em>A</em> model, but not <em>the</em> model.</p>
46,523
<p>Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:</p> <pre><code>var theControl = document.getElementById("txtEditBox"); </code></pre> <p>Then just set the control's Visible property to true/false. It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false. How can I do that? Also, is that the best way to hide/show a ASP.NET control from a Javascript function?</p> <p>Thanks, Jeff </p>
<p>The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.</p> <p>So, you cannot, technically, set that property of the control.</p> <p>That said, if the control <em>is</em> rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:</p> <pre><code>var theControl = document.getElementById("txtEditBox"); theControl.style.display = "none"; // to show it again: theControl.style.display = ""; </code></pre> <p>That assumes that the control's <code>id</code> attribute really is "txtEditBox" on the client and that it is already visible.</p> <blockquote> <p>Also, is that the best way to hide/show a ASP.NET control from a Javascript function?</p> </blockquote> <p>There is not necessarily a "best" way, although one better approach is to use CSS class definitions:</p> <pre><code>.invisible { display: none; } </code></pre> <p>When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose <code>display</code> value starts off as <code>block</code>.</p>
<p>I think the best solution is to put your ASP control inside a div and set the property display to the div element.</p> <pre><code>&lt;div id="divTest"&gt; &lt;asp:TextBox ID="txtTest" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; SIN JQuery document.getElementById('divTest').style.display = "none"; CON JQuery $('#divTest').hide(); &lt;/script&gt; </code></pre>
33,508
<p>Deep down in WinDef.h there's this relic from the segmented memory era:</p> <pre><code>#define far #define near </code></pre> <p>This obviously causes problems if you attempt to use near or far as variable names. Any clean workarounds? Other then renaming my variables?</p>
<p>You can safely undefine them, contrary to claims from others. The reason is that they're just macros's. They only affect the preprocessor between their definition and their undefinition. In your case, that will be from early in windows.h to the last line of windows.h. If you need extra windows headers, you'd include them after windows.h and before the #undef. In your code, the preprocessor will simply leave the symbols unchanged, as intended. </p> <p>The comment about older code is irrelevant. That code will be in a separate library, compiled independently. Only at link time will these be connected, when macros are long gone.</p>
<p>Best not to. They are defined for backwards compatibility with older code - if you got rid of them somehow and then later needed to use some of that old code you'd be broken.</p>
14,460
<p>I use an Ender 3, with cheap Amazon "Eryone PLA", which states a range from 190-220&nbsp;&deg;C, 1.75&nbsp;mm dia. I have had this for about a year.</p> <p>I use the rough build plate, not the glass. I have tried my best to level the bed but I am an amateur</p> <p>I was originally getting poor adhesion so I cleaned the bed, levelled it, increased filament temp to 196&nbsp;&deg;C and heated the bed to 40&nbsp;&deg;C, with no fans in a house around 20&nbsp;&deg;C with not much airflow.</p> <p>This helped adhesion, but my layers are very messy - the first perimeter may adhere correctly, but subsequent layers curl off, meaning the inner passes lift off the build plate. Attempting to persevere, pulling out these regions causes the blobby, ridged mess shown below. This is still the first layer. </p> <p>I have noticed the extruder makes a knocking noise every so often, and the edges of prints can be so thin they are translucent.</p> <p>I've browsed the web for common 3D printing errors but nothing I've found or tried has helped.</p> <p><a href="https://i.stack.imgur.com/tOT5H.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tOT5H.jpg" alt="print"></a></p>
<p>This is clearly overextrusion relative to the volume the material is being deposited into, but that doesn't necessarily mean your extrusion rate is wrong. It could be:</p> <ul> <li>Nozzle smashed down into the bed (bed way too high) but somehow still extruding</li> <li>Problem in Z axis movement preventing the head from moving up the right amount for each layer (possibly not moving up at all?)</li> <li>Extrusion (flow) increased significantly above 100% in slicer</li> <li>Wrong extruder steps/mm setting (usually controlled on printer not slicer, though you can send a setting in the start gcode)</li> <li>Misconfigued filament diameter (unlikely since there's no common setting smaller than 1.75 mm; larger setting would under-extrude)</li> </ul>
<p>Bad filament is my answer. I bought PRLine and both print terrible like your picture. Suspect 2 factors, one is that the line is less than 1.75, so they underextrude and so you see those lines and in some cases gaps, second is the material itself is slippery suggesting to me that it has florinated additives.</p>
1,621
<p>I got a web application, the problem is that the text in the label will not update on the first click, I need to click the button twice, I debugged to code, and I found out that the label does not recive the data until after the second click,</p> <p>Here is my code:</p> <pre><code>System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(); System.Data.SqlClient.SqlConnection connection; string CommandText; string game; string modtype; bool filter; protected void Page_Load(object sender, EventArgs e) { labDownloadList.Text = null; //Session variables: if (Session["Game"] != null) { game = Convert.ToString(Session["Game"]); } if (Session["ModType"] != null) { modtype = Convert.ToString(Session["ModType"]); } if (Session["FilterBool"] != null) { filter = Convert.ToBoolean(Session["FilterBool"]); } string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\inetpub\\wwwroot\\stian\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True"; connection = new System.Data.SqlClient.SqlConnection(ConnectionString); System.Data.SqlClient.SqlDataReader reader; command = connection.CreateCommand(); connection.Open(); CommandText = "SELECT * FROM Command"; if (filter) { CommandText = "SELECT * FROM Command WHERE Game='" + game + "' AND Type='" + modtype + "'"; } command.CommandText = CommandText; reader = command.ExecuteReader(); labDownloadList.Text = ""; while (reader.Read()) { string game = reader.GetString(1); string author = reader.GetString(2); string downloadlink = reader.GetString(3); string size = reader.GetString(4); string description = reader.GetString(5); string version = reader.GetString(6); string screenshotlink = reader.GetString(7); Int64 AmountDownloaded = reader.GetInt64(8); labDownloadList.Text += "Game: " + game + "&lt;br&gt;"; labDownloadList.Text += "Author: " + author + "&lt;br&gt;"; labDownloadList.Text += "Size: " + size + "&lt;br&gt;"; labDownloadList.Text += "Description: " + description + "&lt;br&gt;"; labDownloadList.Text += "Version: " + version + "&lt;br&gt;"; labDownloadList.Text += "&lt;img src='" + screenshotlink + " /&gt;&lt;br&gt;"; labDownloadList.Text += "Downloaded: " + AmountDownloaded + " times&lt;br&gt;&lt;hr&gt;"; labDownloadList.Text += "&lt;a href='" + downloadlink + "'&gt;Download&lt;/a&gt;&lt;br&gt;"; } } protected void Page_UnLoad(object sender, EventArgs e) { Session["Game"] = game; Session["ModType"] = modtype; Session["FilterBool"] = filter; connection.Close(); } protected void btnFilter_Click(object sender, EventArgs e) { game = lstGames.SelectedValue; modtype = lstTypeMod.SelectedValue; filter = true; } </code></pre>
<p>To be very clear. The button click event happens after the Page_Load event meaning that the filtering does not get applied on the first postback. It has been updated on the second postback and you see the filtering. The simplest change to get your code to work is to move all the code in your Page_Load event into OnPreRender so the reload happens after the button click event. </p> <p>A cleaner solution however is probably to move it into a LoadData function and call that on PageLoad when it is not a postback and also call it on the button click event after updating your filters. That will prevent a call to the database on any postback page cycles that do not need to reload the data:</p> <pre> <code> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LoadData() } } private void LoadData() { labDownloadList.Text = null; //Session variables: if (Session["Game"] != null) ... } protected void btnFilter_Click(object sender, EventArgs e) { game = lstGames.SelectedValue; modtype = lstTypeMod.SelectedValue; filter = true; LoadData(); } </code> </pre> <p>A last piece of quick advice for a budding ASP.Net developer is to thoroughly learn the page lifecycle. Knowing the sequence of events on a page is essential. Good Luck.</p>
<p>I was stuck on this for about a week. Finally, I've put the code behind for the <code>Button_Click</code> event in the <code>TextChanged</code> event and it worked. Pressing the button makes the focus leave the <code>TextBox</code> so that event fires when the <code>Button_click</code> event doesn't. Very kludgy. I don't like it. </p> <p>I came across an interesting article that didn't actually work for me, but I'm glad I read it anyway: <a href="https://web.archive.org/web/20210125133120/https://www.4guysfromrolla.com/articles/060805-1.aspx" rel="nofollow">Enter and the Button Click Event</a></p> <p>That might work in other situations.</p>
38,020
<p>I am very new to Java. My assignment is to create my own method and then create a class to test it in. My question, do I create the method separate of the class, or within the class? If it is separate of the class, how do I get the class to access my method?</p> <p>(Are they saved as two separate files?)</p> <p>This is what I have so far, but I am getting an error that I have to initialize KILOWATT in class DWindmill. I thought I did already in the method??? Any suggestions?</p> <pre><code>//This is the method Windmill import java.util.*; import static java.lang.Math.*; class DWindmill { public static void Windmill(){ //create the method for the Windmill class int miles = 50; //int miles = 200; //int miles = 250; int KILOWATT = (miles / 50);} static Scanner console = new Scanner(System.in); { System.out.println("Enter miles per hour:"); miles = console.nextInt(); Windmill(); System.out.println(+ KILOWATT + "kilowatts"); } } </code></pre>
<p>For a simple assignment such as this, you can probably create your method in the same class as your class. Create a class with a static main method, which will be your programs starting point, and then create your method which will be called.</p> <p>Seems like you are quite new to programming I would take advantage of any tutorials that are offered in your program. They are usually taught by junior, senior, or grad level students, and are meant to give you a good introduction to the material, as well as give you time outside class to ask questions. Make sure you go to class, and try to read the textbook you were supposed to buy for the course. The information can often be found there.</p>
<p>OR you can create like follows</p> <pre><code>public class MyClass { public int myMethod() { ,,,,, } } public class myTest { public void testMyMethod() { MyClass testClass = new MyClass(); int output = testClass.myMethod(); . . } } </code></pre> <p>In Java, all methods need to be inside a class. You can have a separate test class or test it in the same class.</p> <p>Things can get more complicated if you use something like jUnit(www.junit.org) for unit testing your methods.</p>
28,242
<p>I'd like to write a Ruby snippet that gets run when my Gem is first installed via <code>[sudo ]gem install mygem</code>. Can it be done?</p>
<p>It doesn't look like it's really supported. I found a "post_install_message" attribute that you should be able to set in the gem spec, but that won't execute code.</p> <p>You may be able to do it by packaging your on-install code as an extension in your gem (as if it were a native extension), and providing a Rakefile to "build" the extension (i.e. call your code).</p>
<p>You can try to do this using call of OS commands. I'll quote eample from irb but you can do same in your scripts too.</p> <pre><code>irb(main):001:0&gt; system 'gem list | grep rails' rails (2.1.1, 2.1.0) =&gt; true irb(main):002:0&gt; system 'gem list | grep railssssss' =&gt; false </code></pre> <p>You can use result of this command as the condition of your snippet execution.</p>
27,545
<p>I am displaying a scrolled data table in a web page. This table has several thousands of dynamic rows, so it is loaded from the server (via AJAX).</p> <p>The user can scroll up and down, so what I need is to <strong>detect when the user reaches the end of the scrollbar</strong> (that is, the last row at the bottom of the table) in order to request and show more data.</p> <p>You can find this effect in google reader, when you scroll down to the last post in a given feed, google requests and shows new posts in a transparent way, but I can't figure out how they achieve it.</p> <p>By the way, right now I am using a <a href="http://developer.yahoo.com/yui/datatable/" rel="noreferrer">YUI Datatable</a></p>
<p>Thank you for your answers. That's my final working code (inspired by Greg and <a href="http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery" rel="nofollow noreferrer">ajaxian.com</a>), that uses some jQuery functions and works with the <a href="http://developer.yahoo.com/yui/datatable/" rel="nofollow noreferrer">YUI DataTable</a>.</p> <pre><code>$(".yui-dt-bd").scroll(load_more); function load_more() { if ($(this).scrollend()) { alert("SCROLL END REACHED !"); // TODO load more data } } $.fn.scrollend = function() { return this[0].scrollHeight - this[0].scrollTop - this.height() &lt;= 0; } </code></pre> <p>My next step is to implement my own <a href="http://developer.yahoo.com/yui/paginator/" rel="nofollow noreferrer">YUI Paginator</a> to achieve a complete integration with YUI components :)</p>
<p>There is a property I noticed while reading through DOM properties in Firebug today called <code>scrollY</code> (in Firebug under the DOM tab go to <code>content</code> > <code>scrollY</code>) which appears to be the amount of pixels left to scroll on the window. Try seeing if this is also created for scrollable elements. Then you can use Yuval's function to load new data.</p>
26,625
<p>I need to simulate a low bandwidth, high latency connection to a server in order to emulate the conditions of a VPN at a remote site. The bandwidth and latency should be tweakable so I can discover the best combination in order to run our software package.</p>
<p>For <strong>macOS</strong>, there is the <em>Network Link Conditioner</em> that simulates configurable bandwidth, latency, and packet loss. It is contained in the <a href="https://developer.apple.com/download/more/?q=Additional%20Tools%20for%20Xcode" rel="nofollow noreferrer">Additional Tools for Xcode</a> package. <img src="https://i.stack.imgur.com/FjgqM.png" alt="Screenshot"></p>
<p>LANforge ICE is a <a href="http://www.candelatech.com/emulate.php" rel="nofollow">network emulator</a> with an emphasis on virtual routing, jitter, corruption and delay. Projects have used it to emulate satellite link, cable and modem connections, and high-speed (10Gbit) wan emulation. You can use a Java GUI to build your virtual networks and generate very detailed reports of the traffic flow. The LANforge products also provide traffic generation features: frame, ethernet, layer-3 and stateful traffic (NFS, http). Recent editions for LANforge have sophisticated WiFi testing features as well.</p>
15,831
<p>I need to implement a <a href="http://en.wikipedia.org/wiki/Wavetable" rel="nofollow noreferrer">wavetable synthesizer</a> in an ARM Cortex-M3 core. I'm looking for any code or tools to help me get started.</p> <p>I'm aware of <a href="http://elm-chan.org/works/mxb/report.html" rel="nofollow noreferrer">this AVR implementation</a>. I actually converted it to a PIC a while back. Now I am looking for something similar, but a little better sounding.</p> <p>ANSI C code would be great. Any code snippets (C or C++), samples, tools, or just general information would be greatly appreciated.</p> <p>Thanks.</p>
<p>The Synthesis Toolkit (STK) is excellent, but it is C++ only:</p> <p><a href="http://ccrma.stanford.edu/software/stk/" rel="noreferrer">http://ccrma.stanford.edu/software/stk/</a></p> <p>You may be able to extract the wavetable synthesizer code from the STK though.</p>
<p>Any ARM synth, the best ones, can be changed to wavescanner in less than a day. Scanning the wave from files or generating them mathematically is nearly the same thing audio wise, WT provides massive banks of waveforms at zero processing cost, you need the waves, the WT oscillator code itself is 20 lines. so change your waveform knob from 3 to 100 to indicate which WAV you are reading, use a ramp/counter to read the WAV files(as arrays). WT fixed. </p> <p>From 7 years of Synth experience, i'd recommend to change 20 lines of the oscillator function of your favorite synth to adapt it to read wave arrays. The WT only uses 20 lines of logic, the rest of the synthesizer is more important: LFO's, Filters, input parameters, preset memory... Use your favorite synth instead and find a WT wave library as WAV files and folders, and replace your fav synth oscillators with WT functions, it will sound almost the same, only lower processing costs. </p> <p>A synth normally uses Sin, Sqr, Saw, Antialiased OSC functions for the wave... </p> <p>A wavetable synth uses about 20 lines of code at it's base, and 10/20/100ds of waves, each wave sampled at every octave ideally. If you can get a wavetable sound library, the synth just loops, pitch shifts, the sounds, and pro synths can also have multiple octave to mix the octaves. </p> <p>WTfunction = </p> <ul> <li>load WAV files into N arrays</li> <li>change waveform = select waveform array from WAV list</li> <li>read waveform array at desired Hz </li> </ul> <p>wavescanner function =</p> <ul> <li>crossfade between 2 waves and assign xfade to LFO, i.e. sine and xfade.</li> </ul> <p>The envelope, filter, amplitude, all other functions are independent from the wave generation function in all synths. </p> <p>remember the the most powerful psychoacoustic tool for synthesizers is deviation from the digital tone of the notes, it's called unison detune, sonic character of synthesizers mostly comes from chorus and unison detune. </p> <p>WT's are either single periods of waves of longer sections, in more advanced synths. the single period stuff is super easy to write into code. the advanced WT's are sampled per octave with waves lasting N periods, even 2-3 seconds, i.e. piano, and that means that they change sound quality through the octaves, so the complex WT's are crossfaded every octave with multiple octave recordings. </p>
4,935
<p>I have a linq to sql database. Very simplified we have 3 tables, Projects and Users. There is a joining table called User_Projects which joins them together. </p> <p>I already have a working method of getting <code>IEnumberable&lt;Project&gt;</code> for a given user. </p> <pre><code>from up in User_Projects select up.Project; </code></pre> <p>Now I want to get the projects the user <em>isn't</em> involved with. I figured the except method of IEnumerable would be pretty good here:</p> <pre><code>return db.Projects.Except(GetProjects()); </code></pre> <p>That compiles, however I get a runtime error: "Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator."</p> <p>Is there any way to get around this?</p> <hr> <h2>Update:</h2> <p>A few views but no answers :p</p> <p>I have tried this: </p> <pre><code> IEnumerable&lt;Project&gt; allProjects = db.Projects; IEnumerable&lt;Project&gt; userProjects = GetProjects(); return allProjects.Except(GetProjects()); </code></pre> <p>I know it's essentially the same as the original statement - but now i dont get a runtime error. Unfortunately, it doesn't really do the except part and just returns all the projects, for some reason</p>
<p>Linq to Sql doesn't understand how to work with an arbitrary in-memory sequence of objects. You need to express this in relational terms, which works on IDs:</p> <pre><code>var userProjectIds = from project in GetProjects() select project.ProjectId; var nonUserProjects = from project in db.Projects where !userProjectIds.Contains(project.ProjectId) select project; </code></pre>
<p>try this:</p> <pre><code>var userProjects = GetProjects(); return db.Projects.Except(userProjects.ToArray()); </code></pre> <p>The ToArray should force evaluation of the sequence (if I'm understanding the issue right) and allow the operation to succeed.</p>
42,928
<p>C#: How do you tell which item index is selected in ListView?</p>
<pre><code>ListView mylistv = new ListView(); var index = mylistv.SelectedIndices(); </code></pre> <p>That should do it.</p>
<p>Use the SelectedIndex property of the class.</p>
36,730
<p>How do I escape '&lt;' and '>' character in sed.</p> <p>I have some xml files which needs some text between the tags to be replaced. How do I escape the '>' and '&lt;' characters.</p> <p>The problem with > and &lt; is it has special meaning in the shell to redirect the output to a file. So backslash doesn't work.</p>
<p>Ok. Found out by myself. Use quotes.</p> <pre><code>$ sed -i "s/&gt;foo&lt;/&gt;bar&lt;/g" file </code></pre>
<p>Escape them with backslash</p>
18,471
<p>What is the recommended way to embed PDF in HTML?</p> <ul> <li>iFrame? </li> <li>Object? </li> <li>Embed?</li> </ul> <p>What does Adobe say itself about it?</p> <p>In my case, the PDF is generated on the fly, so it can't be uploaded to a third-party solution prior to flushing it.</p>
<p>Probably the best approach is to use the <a href="https://mozilla.github.io/pdf.js/" rel="noreferrer">PDF.JS</a> library. It's a pure <a href="https://en.wikipedia.org/wiki/HTML5" rel="noreferrer">HTML5</a>/<a href="https://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> renderer for PDF documents without any third-party plugins.</p> <p>Online demo: <a href="https://mozilla.github.io/pdf.js/web/viewer.html" rel="noreferrer">https://mozilla.github.io/pdf.js/web/viewer.html</a></p> <p>GitHub: <a href="https://github.com/mozilla/pdf.js" rel="noreferrer">https://github.com/mozilla/pdf.js</a></p>
<p>If you don't want to host PDF.JS on your own, you could try <a href="https://www.docdroid.net" rel="nofollow noreferrer">DocDroid</a>. It is similar to the Google Drive PDF viewer but allows custom branding. </p>
37,220