input
stringlengths
51
42.3k
output
stringlengths
18
55k
Query to find all the tables with date columns in it <p>Can anybody let me know the query to find all the tables that has a date columns on it.</p> <p>Thanks</p>
<p>This should do the trick, just add in additional types if you need them:</p> <pre><code>select so.name table_name ,sc.name column_name ,st.name data_type from sysobjects so inner join syscolumns sc on (so.id = sc.id) inner join systypes st on (st.type = sc.type) where so.type = 'U' and st.name IN ('DATETIME', 'DATE', 'TIME') </code></pre> <p><strong><em>edit:</strong> this also works in Sybase and any other T-SQL variants.</em></p>
Django FormWizard with dynamic forms <p>I want to implement a simple 2 part FormWizard. Form 1 will by dynamically generated something like this:</p> <pre><code>class BuyAppleForm(forms.Form): creditcard = forms.ChoiceField(widget = forms.RadioSelect) type = forms.ChoiceField(widget = forms.RadioSelect) def __init__(self,*args, **kwargs): user = kwargs['user'] del kwargs['user'] super(BuyAppleForm, self).__init__(*args, **kwargs) credit_cards = get_credit_cards(user) self.fields['creditcard'].choices = [(card.id,str(card)) for card in credit_cards] apple_types= get_types_packages() self.fields['type'].choices = [(type.id,str(type)) for type in apple_types] </code></pre> <p>This will dynamically create a form with lists of available choices.</p> <p>My second form, I actually want no input. I just want to display a confirmation screen containing the credit card info, apple info, and money amounts (total, tax, shipping). Once user clicks OK, I want the apple purchase to commence.</p> <p>I was able to implement the single form way by passing in the request.user object in the kwargs. However, with the FormWizard, I cannot figure this out.</p> <p>Am I approaching the problem wrong and is the FormWizard not the proper way to do this? If it is, how can the Form <code>__init__</code> method access the user object from the HTTP request? </p>
<p>When I was trying to figure out FormWizard, I searched all over and found responses such as most of these that just say don't use it. FormPreview would work fine since OP is only interested in a one-level form, but the question is still valid in how to use FormWizard.</p> <p>Even though this question is so old, I think it is valuable to answer here because this question is asked on so many sites and I see no cohesive response to it, nor a clear solution in the docs.</p> <p>I think in terms of the OPs question, overriding process_step is the way to go. The trick is in creating the form (or view) within this method that will receive the data from the first form.</p> <p>I added this form_setup to my forms.py as a utility wrapper (think constructor):</p> <pre><code>def form_setup(**kwargs): def makeform(data, prefix=None, initial=None): form = FormLev2(data, prefix, initial) for k, v in kwargs.items(): if k == 'some_list': form.fields['some_list'].choices = v ... return form return makeform </code></pre> <p>Then override process_step as follows:</p> <pre><code>def process_step(self, request, process, step): if step == 1 if form.is_valid(): #form from step 1 objs = Table.objects.filter(...) #based on last form self.form_list[1] = form_setup(some_list=[(o.id,o.name) for o in objs]) #(*) ... </code></pre> <p>That way, you are able to dynamically modify form_list(*), in the sense that you modify the form_list in the FormWizard instance, rather than the form definitions themselves. The wrapper function is essential for this functionality, as it returns a function that will instantiate a new Form object, which is then used within FormWizard to be called with the data for the next form, and allows you to use the data from the previous one. </p> <p>Edit: for Erik's comment, and to clarify the last part.</p> <p>Also note that process_step will be called with step [0,n] after step n.</p>
base64 encode in MySQL <p>I want to select a blob col from one table, base64 encode it and insert it into another tables. Is there any way to do this without round tripping the data out of the DB and through my app?</p>
<p>I was looking for the same thing and I've just seen that MySQL 5.6 has a couple of new string functions supporting this functionality: <a href="http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_to-base64">TO_BASE64</a> and <a href="http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_from-base64">FROM_BASE64</a>.</p>
How to Search date in SQL? <p>I am having an Event Management System in which i want,</p> <p>If an event is registered for 5 days (21 jan 2009 to 26 Jan 2009) Then if another person wants to register an event between 22 jan 2009 to 24 jan 2009 then it will not allow to register. I want to check this using SQL query, so please tell me how can i do this.</p>
<p>Just a to complete other answers, you have a good article on <strong><a href="http://www.devarticles.com/c/a/SQL-Server/Date-and-Time-Values-Using-SQL-Server-2000/" rel="nofollow">How to Search for Date and Time Values Using SQL Server 2000</a></strong> </p> <p>It reminds you about how date/time values are stored (two date/time data types: datetime and smalldatetime)</p> <p>It also points out Datetime and smalldatetime are like the floating-point data types, float and real, in that they’re approximate numerics. That means the value retrieved from SQL Server may be different from the value that was originally stored.</p> <p>Plus, it warns about Database designers who don’t always use date/time columns appropriately. At the time the database is designed, each date/time column should be identified as to whether it will store both dates and times, dates only, or times only.</p> <p>It closes with <a href="http://www.devarticles.com/c/a/SQL-Server/Date-and-Time-Values-Using-SQL-Server-2000/6/" rel="nofollow">practical queries on data/time</a>.</p> <p>You also have a good description of <a href="http://searchsqlserver.techtarget.com/tip/0,289483,sid87_gci1333669,00.html#" rel="nofollow">DATEADD and DATEDIFF here</a>.</p>
How to install a windows service programmatically in C#? <p>I have 3 projects in my VS solution. 1 is a web app, the other is a windows service and the last one a setup project for my web app. </p> <p>What i want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that i have the location of the assembly by then.</p> <p>Thanks for all the help in advance.</p>
<p>Ok, here is what REALLY worked for me, it has been tested on multiple machines with different OS ( Vista, XP, Win2k, Win2003 server )</p> <p>The code has been taken from <a href="http://www.tech-archive.net/Archive/VB/microsoft.public.vb.winapi/2006-08/msg00238.html">here</a> so full credit goes to whoever wrote this piece of code.</p> <p>You can find the source file <a href="http://dl.getdropbox.com/u/152585/ServiceInstaller.cs">here</a> or you may as well grab <a href="http://dl.getdropbox.com/u/152585/ServiceTools.dll">this</a> dll that i prepared for you.</p> <p>Once you add the dll or source file into your project make sure to add the ServiceTools namespace and then you have access to some very handy functionality such as...</p> <pre><code>//Installs and starts the service ServiceInstaller.InstallAndStart("MyServiceName", "MyServiceDisplayName", "C:\PathToServiceFile.exe"); //Removes the service ServiceInstaller.Uninstall("MyServiceName"); //Checks the status of the service ServiceInstaller.GetServiceStatus("MyServiceName"); //Starts the service ServiceInstaller.StartService("MyServiceName"); //Stops the service ServiceInstaller.StopService("MyServiceName"); //Check if service is installed ServiceInstaller.ServiceIsInstalled("MyServiceName"); </code></pre> <p>I hope this helps.</p> <p>-Konstantinos</p>
auto-check radio-button using struts <p>I have a jsp page with two radio tags. </p> <p>The page contains a struts2 form. When I submit the form one of two radio must be automatically checked.</p> <p>Is it possible to do that?</p>
<p>One of the features of a radio input is that an item in a radio set once selected cannot be deselected except by another member of the set being selected (unlike a checkbox "set"). i.e. if you initialise the page with a selection you can guarantee you will have a value. Does a default value exist you can do this for? Then you can just set <code>checked="checked"</code> on that item.</p> <p>Alternatively you'll just have to add another validation rule in JS and/or the server side.</p>
When adding new items to a database with foreign keys, should I use SQL triggers to create the related rows in other tables? <p>I am implementing a database design that has a vehicle table, vehicle engine and vehicle gear table with SQL 2005.</p> <p>Each table has an ID that is a SQL identity number, and each engine and gear has a relation with the vehicle ID. So before I create a vehicle I must create an engine and gear.</p> <p>How could I know the vehicle identity number when creating the engine and gear? The vehicle row hasn't yet been created because of the foreign key constraint with the engine and gear tables?</p> <p>Should I implement an automatic trigger that on a creation of a vehicle creates an empty row for the engine and gear linked to the vehicle? But again how could I know the vehicle ID?</p>
<p>Whichever, there's no need to create rows in any of the tables for which you don't have data. It's fine to, for instance, have an engine row that is unmatched to a vehicle. You can add what's missing when you find it.</p> <p>I think I understand the design. Each vehicle can have one engine and one transmission. But you may record the transmission or engine before you find the vehicle.</p> <p>They really are separate entities, so treat them as such. You may easily end up with engines and transmissions which you never match to a vehicle.</p> <p>Another more interesting question is whether you might end up with a transmission matched to an engine, but no vehicle. One often sees an engine and tramsission bolted together with no vehicle in sight. And they'll often be sold together as well.</p> <p>In fact, you can imagine any of the three existing alone, or matched to one or two of the other entities.</p> <p>Triggers have no role here. If used at all, triggers should be restricted to fine-grained referential integrity rules about the schema structure - not for business rules like this. There are no mandatory constraints - every foreign key is optional (nullable). And there are several different ways to set the FK fields up.</p>
JQuery Loop over JQueryObjects <p>I have a method, which will accept a parameter of a JQuery Object and will calculate totals for a section. So if you give it a JQuery Object of a div containing the section it will calculate a total for it</p> <p>so you can do this:</p> <p>var $totalcompletion = CalculateSectionCompletion(jQuery("#Section1"));</p> <p>Now I have multiple divs with the class of section container. I want to be able to call the above method on any div with that class.</p> <p>I'm doing this:</p> <p>jQuery("div.SectionContainer").each( function(i, valueOfElement){<br /> CalculateSectionCompletion(valueOfElement);<br /> });</p> <p>The problem is the valueOfElement is actually the DOM object and not the JQuery Object, so I can't pass this in to my method.</p> <p>Is there anyway I can loop through all JQuery Objects selected by a query, without writing some dirty code to extract the Id from the DOM object, and call JQuery(valueOfElement.id) and pass it in?</p>
<p>You can wrap any DOM element in $(..), as you do with $(document).</p> <p>So I think you should be able to </p> <pre><code>jQuery("div.SectionContainer").each( function(i, valueOfElement){ CalculateSectionCompletion($(valueOfElement)); }); </code></pre>
Best way to make an expandable/collapsible subTable with rich:dataTable <p>I've recently ported an application from JSF 1.1 to JSF 1.2. In the process we removed tomahawk and decided to use rich instead.</p> <p>Now I need a way to make an expandable/collapsible detailViev for each row in the table. </p> <p>The only thing I can think of is something along these lines (adapted from documentation at docs.jboss.com):</p> <pre><code>&lt;rich:dataTable value="#{capitalsBean.capitals}" var="capitals"&gt; &lt;rich:column&gt; ... &lt;/rich:column&gt; &lt;rich:subTable value="#{capitals.details}" var="detail" ajaxKeys="#{bean.ajaxSet}" binding="#{bean.subtable}" id="subtable" rendered="detail.detailOpened"&gt; &lt;rich:column&gt; ... &lt;/rich:column&gt; &lt;/rich:subTable&gt; &lt;/rich:dataTable&gt; </code></pre> <p>I guess something like that would work. The problem is that I either have to add a getDetailOpened and a setDetailOpened to the objects I use, or wrap each object in another object that provides those two methods.</p> <p>Anybody knows a better way, or how it is supposed to be done?</p>
<p>I've often added methods to my beans (or wrapper beans) which contain those properties as a way of working around JSF. It's not pretty but it works.</p> <p>The only other option I can think of at the moment is to use a JavaScript function to toggle the state of the details view. That wouldn't be ideal for a number of reasons but it would save you having to keep state server-side.</p>
How do I implement Advanced combobox in CakePHP? <p>I have implemented combobox in cakephp using following statement - </p> <pre><code>echo $form-&gt;select('brand_id',array($brands),null,array(),'Choose Brand'); </code></pre> <p>for brand and input form for category - </p> <pre><code>echo $form-&gt;input('category_id',array('type'=&gt;'select',$categories,'empty'=&gt;'Choose Category')); </code></pre> <p>but none of above option allows me to add my text input to brand or category, like say I want to add an input which is not there in the combobox, how should i go about it. </p> <p>Like a link in the combobox or textbox in combobox?</p> <p>-skr</p>
<p>Have 2 "other" fields:</p> <pre><code>echo $form-&gt;input('brand_other'); echo $form-&gt;input('category_other'); </code></pre> <p>You'll either need 2 more fields in your database table for the model of this form, or logic in your controller that adds values posted in these "other" fields to your brands and categories tables, then add the inserted IDs to $this->data brand_id and category_id before saving this model.</p> <p>Also, you can use the $form->input() method for both select boxes, and you don't need to explicitly send it $brands or $categories vars, if they are available in your view the form helper will detect this and print a select box automatically.</p>
Why do I get an error using moveTo in JavaScript? <p>I am opening a new window from a button using var myWindow = window.open(...). I then want to move that window to the correct location on the screen. I use myWindow.moveTo(10,10) to do this but I get an Access Denied error.</p> <p>The window I open contains information from another server to the one I am executing on. When it isn't, the window moves correctly. Is this the limitation and is there a way around it?</p> <p>I am using IE7. (The work is for an existing Intranet that includes lots of ActiveX so all users use IE7)</p>
<p>You could try to put the information from the other site in an iframe located on the same host that runs the window.open JavaScript. Or maybe even better, get the information server-side and present it directly from your site. Iframes can be trouble.</p>
error C2065: 'CoInitializeEx' : undeclared identifier <p>I get the following error while trying to use <code>hres = CoInitializeEx(0, COINIT_MULTITHREADED);</code></p> <blockquote> <p>error C2065: 'CoInitializeEx' : undeclared identifier</p> </blockquote> <p>I have already included:</p> <pre><code>#define _WIN32_DCOM #include &lt;iostream&gt; using namespace std; #include &lt;comdef.h&gt; #include &lt;Wbemidl.h&gt; </code></pre> <p>in my cpp file.</p> <p>Kindly help.</p> <p>Thanks, Neha</p>
<p>Try placing the following line at the beginning of your precompiled header(<em>stdafx.h</em>).</p> <pre><code>#define _WIN32_WINNT 0x0400 </code></pre>
Batch how to end an for-loop properly <p>for testing purposes i need an recursive directory with some files, that comes to maximum path-length.</p> <p>The Script used for the creation consists only of two for-loops, as followed:</p> <pre><code>for /L %%a in (1 1 255) do @( mkdir %%a &amp;&amp; cd %%a &amp;&amp; for /L %%b in (1 1 %random%) do @( echo %%b &gt;&gt; %%a.txt ) ) </code></pre> <p>Now I would like to embed this script as part of another script, since more is to be done, but I can not add any other commands around it or it refuses working. I use this under windows vista, if this is useful to you.</p> <p>Nor it works if i write <code>"@ECHO OFF</code>" in first line, neither with "<code>echo done</code>" on the last line.</p> <p>output on commandline is:</p> <pre><code>X:\Scripte&gt;recursive.cmd OFFfor /L %a in (1 1 255) do @( mkdir %a The system cannot find the path specified. </code></pre> <p>EDIT: Seems to be a problem with layer 8, the problem seems to be in the command shell used, if used the bare cmd.exe, it works, with visual studio 2008 command shell it does not work, like stated above.</p> <p>anyway, thank you.</p>
<p>I don't understand how to add a little comment below an answer, so I'll just do it here.</p> <p>The @ sign in front of the open parenthesis is needed only if echo is not already off. In that case, what would happen without the @ sign is that every command in the FOR loop would be echoed.</p> <p>And, yes, the reason for needing &amp;&amp; is that the text editor is putting it all on one line. But no one posted a solution. Just copy and paste into Notepad, and then separate the lines as necessary.</p>
Specifying attribute values as CDATA <p>Can one specify XML attribute values as CDATA ? If yes - what would be the schema for the same. If not - why is this limitation not addressed in XML ?</p>
<p>No you cannot do this.</p> <p>There's a very fine line (and a very large debate) between what constitutes an attribute and what constitutes a child element. See <a href="http://stackoverflow.com/questions/152313/xml-attributes-vs-elements">here</a> for example. </p> <p>That given, the "limitation" isn't addressed in XML because it doesn't exist. You always have the ability to put this data in a child element, and in fact I would go so far as to say that if you even have to think about this, an element is the correct structure.</p> <p>Edit: More reading material</p> <ul> <li><a href="http://xmleverywhere.com/newsletters/20000525.htm" rel="nofollow">The Attribute/Text Conundrum</a></li> <li><a href="http://www.ibm.com/developerworks/xml/library/x-eleatt.html" rel="nofollow">Principles of XML design: When to use elements versus attributesl</a></li> <li><a href="http://www.w3schools.com/DTD/dtd_el_vs_attr.asp" rel="nofollow">w3schools take</a></li> </ul>
How to get the FxCop custom dictionary to work? <p>How is it possible to get the FxCop custom dictionary to work correctly?</p> <p>I have tried adding words to be recognised to the file 'CustomDictionary.xml', which is kept in the same folder as the FxCop project file. This does not seem to work, as I still get the 'Identifiers should be spelled correctly' FxCop message, even after reloading and re-running FxCop. Using version 1.36.</p>
<p>If you use it inside Visual Studio...</p> <p>From <a href="http://blogs.msdn.com/fxcop/archive/2007/08/20/new-for-visual-studio-2008-custom-dictionaries.aspx">Visual Studio Code Analysis Team Blog</a></p> <blockquote> <p>To add a custom dictionary to a C# and Visual Basic project is simple:</p> <ol> <li>In Solution Explorer, right-click on the project and choose Add -> New Item...</li> <li>Under Templates, select XML File, enter a name for the dictionary, such as CodeAnalysisDictionary.xml and click Add</li> <li>In Solution Explorer, right-click on the XML file and choose Properties</li> <li>In the Properties tool window, under Build Action choose CodeAnalysisDictionary</li> <li>In Solution Explorer, double-click on the newly created dictionary to open it</li> <li><p>In the XML editor, paste the following, replacing "productname" and "companyname" with your team's equivalents:</p> <pre><code>&lt;Dictionary&gt; &lt;Words&gt; &lt;Recognized&gt; &lt;Word&gt;"productname"&lt;/Word&gt; &lt;Word&gt;"companyname"&lt;/Word&gt; &lt;/Recognized&gt; &lt;/Words&gt; &lt;/Dictionary&gt; </code></pre></li> </ol> <p>You are now ready to start entering your own custom words. Simply add a new element for each word in your project that does not exist in the dictionary. Each word is case-insensitive, so any casing of the word will be recognized. Code Analysis will automatically pick up the custom dictionary the next time it is run.</p> </blockquote>
Creating a delegate type inside a method <p>I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.</p> <p>For Example :</p> <pre><code> public void MyMethod(){ delegate int Sum(int a, int b); Sum mySumImplementation=delegate (int a, int b) {return a+b;} Console.WriteLine(mySumImplementation(1,1).ToString()); } </code></pre> <p>Unfortunately, I cannot do it in .NET 2.0 and C# 2.0.</p>
<p>Why do you want to create the delegate type within the method? What's wrong with declaring it outside the method? Basically, you can't do this - you can't declare a <em>type</em> (any kind of type) within a method.</p> <p>One alternative would be to declare all the Func/Action generic delegates which are present in .NET 3.5 - then you could just do:</p> <pre><code>public void MyMethod(){ Func&lt;int, int, int&gt; mySumImplementation = delegate (int a, int b) { return a+b; }; Console.WriteLine(mySumImplementation(1,1).ToString()); } </code></pre> <p>The declarations are on my <a href="http://csharpindepth.com/Articles/Chapter1/Versions.aspx">C#/.NET Versions page</a>.</p>
path name and arguments of running processes using java code <p>I want to get the path name and arguments of running processes using java code. Is there any solution?</p>
<p>For instance, on Windows, one possibility is to encapsulate the <a href="http://www.rgagnon.com/javadetails/java-0593.html" rel="nofollow">system call to <code>TASKLIST.EXE</code></a> </p> <p>Extract from the code:</p> <pre><code>Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh"); BufferedReader input = new BufferedReader (new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { if (!line.trim().equals("")) { // keep only the process name line = line.substring(1); processes.add(line.substring(0, line.indexOf("""))); } } </code></pre> <p>You should use <code>tasklist /V</code> though, since it comes with the parameters of the processes.</p>
Oxite or S#arp Architecture for new Asp.net CMS site <p>I'd like to build a CMS site based on Asp.Net Mvc and I want to choose my starting point.</p> <p>I have seen that there is a lot of interest in the new Microsoft Oxite project also if it seems to be pretty early to adopt it in a production project.<br /> I've also looked at S#arp Architecture but it does not properly compare to Oxite as is just a starting point for general Asp.Net Mvc sites.</p> <p>For me S#arp Architecture has some advantages over Oxite as is far less complex and it uses Nhibernate for the data access layer.<br /> Oxite code uses Linq2Sql for it's DAL and has already a project in the solution that requires the DB version for VS2008.<br /> Oxite seems to me more blog oriented than CMS oriented but I haven’t looked the code deeply.</p> <p>Here are some of the choices that would point me to S#arp Ar. for starting.</p> <ul> <li>Simple clean architecture</li> <li>Nhibernate Dal</li> <li>Community supported</li> </ul> <p>Oxite:</p> <ul> <li>Microsoft project </li> <li>Potential huge community </li> <li>Early stages but very good code quality </li> <li>Provider model that permits to easily switch the DAL </li> </ul> <p>If anyone has looked at the code of these two projects please advice on your opinions.</p> <p>Thanks</p>
<p>Oxite might be feature rich, but the code quality is very low.</p> <p>I was very surprised when I checkout the code and found controller actions with 100+ lines of very unclean code, tagsoup views, no unit tests, etc.</p> <p>The criticism has been well summed up in these blog posts:</p> <p><a href="http://blog.wekeroad.com/blog/some-thoughts-on-oxite/" rel="nofollow">http://blog.wekeroad.com/blog/some-thoughts-on-oxite/</a></p> <p><a href="http://codebetter.com/blogs/karlseguin/archive/2008/12/15/oxite-oh-dear-lord-why.aspx" rel="nofollow">http://codebetter.com/blogs/karlseguin/archive/2008/12/15/oxite-oh-dear-lord-why.aspx</a></p>
Cocoa equivalent of .NET's Environment.SpecialFolder for saving preferences/settings? <p>How do I get the reference to a folder for storing per-user-per-application settings when writing an Objective-C Cocoa app in Xcode?</p> <p>In .NET I would use the <code>Environment.SpecialFolder</code> enumeration:</p> <pre><code>Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); </code></pre> <p>What's the Cocoa equivalent?</p>
<p>In Mac OSX application preferences are stored automatically through NSUserDefaults, which saves them to a .plist file <code>~/Library/Preferences/</code>. You shouldn't need to do anything with this file, NSUserDefaults will handle everything for you.</p> <p>If you have a data file in a non-document based application (such as AddressBook.app), you should store it in <code>~/Library/Application Support/Your App Name/</code>. There's no built-in method to find or create this folder, you'll need to do it yourself. Here's an example from one of my own applications, if you look at some of the Xcode project templates, you'll see a similar method.</p> <pre><code>+ (NSString *)applicationSupportFolder; { // Find this application's Application Support Folder, creating it if // needed. NSString *appName, *supportPath = nil; NSArray *paths = NSSearchPathForDirectoriesInDomains( NSApplicationSupportDirectory, NSUserDomainMask, YES ); if ( [paths count] &gt; 0) { appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"]; supportPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:appName]; if ( ![[NSFileManager defaultManager] fileExistsAtPath:supportPath] ) if ( ![[NSFileManager defaultManager] createDirectoryAtPath:supportPath attributes:nil] ) supportPath = nil; } return supportPath; } </code></pre> <p>Keep in mind that if your app is popular you'll probably get requests to be able to have multiple library files for different users sharing the same account. If you want to support this, the convention is to prompt for a path to use when the application is started holding down the alt/option key.</p>
Getting started with Tomcat docs <p>Are there any <em>good</em> "Getting started with Tomcat" documents/tutorials/sites?</p> <p>The official docs are horribly written and jump from the intricacies of compiling Tomcat to how you should lay out your site on disk.</p> <p>Specifically I want to get Tomcat serving through Apache httpd.</p>
<p>The best source I've found for deep understanding is a book called <em>How Tomcat Works</em>. There's also an O'Reilly title <em>Tomcat: The Definitive Guide</em> for more of a "how to" approach.</p>
Spring-WS: how to use WebserviceTemplate with pre-generated SOAP-envelope <p>Can you use a Spring-WS WebserviceTemplate for calling a webservice and avoid that it generates a SOAP-envelope? That is, the message already contains an SOAP-Envelope and I don't want that the WebserviceTemplate wraps another one around it. :-)</p> <p>The reason I want this is that I'd like to call a webservice that uses ws-security and do not want to put the ws-security stuff into the WebserviceTemplate, but just want to feed it a message with pre-generated ws-security information in the SOAP-envelope. I tried calling the method <a href="http://static.springsource.org/spring-ws/sites/1.5/apidocs/org/springframework/ws/client/core/WebServiceTemplate.html#sendSourceAndReceiveToResult(java.lang.String,%20javax.xml.transform.Source,%20javax.xml.transform.Result)" rel="nofollow">sendSourceAndReceiveToResult</a> with a Source already contains a Soap-Envelope with the WS-Security stuff and the webservice template wraps around another Soap-Envelope and thus destroys the message.</p>
<p>You're using ws-security in a strange way... I guess that you're trying to avoid ws-security dependancy by using pre-generated messages - for simple client might make sense, although it's definitely not by-the-book.</p> <p>You can configure WebServiceTemplate to use plain XML without SOAP by setting messageFactory on WebServiceTemplate to this bean:</p> <pre><code>&lt;bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate"&gt; &lt;property name="messageFactory" ref="poxMessageFactory" /&gt; &lt;/bean&gt; &lt;bean id="poxMessageFactory" class="org.springframework.ws.pox.dom.DomPoxMessageFactory" /&gt; </code></pre>
How can I get the value data out of an MSXML::IXMLDOMElement <p>I have an xml string </p> <pre><code>&lt;grandparent&gt; &lt;parent&gt; &lt;child&gt;dave&lt;/child&gt; &lt;child&gt;laurie&lt;/child&gt; &lt;child&gt;gabrielle&lt;/child&gt; &lt;/parent&gt; &lt;/grandparrent&gt; </code></pre> <p>What I want to get is the data raw xml that's inside the parent. I'm using MSXML </p> <pre><code>iXMLElm-&gt;get_xml(&amp;bStr); </code></pre> <p>is returning</p> <pre><code>&lt;parent&gt; &lt;child&gt;dave&lt;/child&gt; &lt;child&gt;laurie&lt;/child&gt; &lt;child&gt;gabrielle&lt;/child&gt; &lt;/parent&gt; </code></pre> <p>.</p> <pre><code>iXMLElm-&gt;get_text(&amp;bStr); </code></pre> <p>returns davelauriegabrielle</p> <p><strong>What function do I use if I want to get?</strong> </p> <pre><code>&lt;child&gt;dave&lt;/child&gt; &lt;child&gt;laurie&lt;/child&gt; &lt;child&gt;gabrielle&lt;/child&gt; </code></pre> <p>Is anyone aware of some good documentation on these functions? Everything I've seen is a linked nightmare. </p>
<p>Iterate over the child nodes and build the string manually.</p>
How can I force the PropertyGrid to show a custom dialog for a specific property? <p>I have a class with a string property, having both a getter and a setter, that is often so long that the PropertyGrid truncates the string value. How can I force the PropertyGrid to show an ellipsis and then launch a dialog that contains a multiline textbox for easy editing of the property? I know I probably have to set some kind of attribute on the property, but what attribute and how? Does my dialog have to implement some special designer interface?</p> <p><strong>Update:</strong> <a href="http://stackoverflow.com/questions/130032/multi-line-string-in-a-propertygrid">This</a> is probably the answer to my question, but I could not find it by searching. My question is more general, and its answer can be used to build any type of custom editor.</p>
<p>You need to set an <code>[Editor(...)]</code> for the property, giving it a <code>UITypeEditor</code> that does the edit; like so (with your own editor...)</p> <pre><code>using System; using System.ComponentModel; using System.Drawing.Design; using System.Windows.Forms; using System.Windows.Forms.Design; static class Program { static void Main() { Application.Run(new Form { Controls = { new PropertyGrid { SelectedObject = new Foo() } } }); } } class Foo { [Editor(typeof(StringEditor), typeof(UITypeEditor))] public string Bar { get; set; } } class StringEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { return UITypeEditorEditStyle.Modal; } public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IWindowsFormsEditorService svc = (IWindowsFormsEditorService) provider.GetService(typeof(IWindowsFormsEditorService)); if (svc != null) { svc.ShowDialog(new Form()); // update etc } return value; } } </code></pre> <p>You might be ablt to track down an existing Editor by looking at existing properties that behave like you want.</p>
How can I add a big flash banner to the top of my Wordpress blog? <p>I don't know if it is possible to add a Flash banner into a Wordpress theme... Ideally, this banner would be in the header of the site always. Any ideas on how I might accomplish this?</p>
<p>Yes, it's very much possible. What I would recommend is to use <a href="http://code.google.com/p/swfobject/" rel="nofollow">swfobject</a> to replace the your current header with a Flash movie. This way it will degrade gracefully for everyone that lacks a proper flash player, and also you get the benefit of proper google indexing. </p>
Delete All Emails in a Highrise App <p>How do I delete all the emails in my <a href="http://highrisehq.com/" rel="nofollow">highrise</a> app? I don't want to delete the entire thing and start over, I've got companies and tags and metadata. What's the easiest way?</p> <p>This question paraphrased from <a href="http://getsatisfaction.com/people/tiborholoda" rel="nofollow">Tibor Holoda</a>'s <a href="http://getsatisfaction.com/37signals/topics/can_you_help_me_deleting_all_emails_and_start_again_please" rel="nofollow">question</a> on <a href="http://getsatisfaction.com" rel="nofollow">GetSatisfaction</a></p>
<p>It looks like this is available through the <a href="http://developer.37signals.com/highrise" rel="nofollow">API</a>, and should be easy with the <a href="http://developer.37signals.com/highrise/highrise.rb" rel="nofollow">ruby bindings</a>:</p> <pre><code>#!/usr/bin/env ruby ENV['SITE'] = "http://passkey:X@my.hirisehq.com" require 'highrise' Highrise::Person.each do |person| person.emails.each {|email| email.destroy } end </code></pre>
Get a file system handle to a bluetooth mapped folder <p>Is there any way to get code level access to a bluetooth mapped drive? The simple use case is I have a bluetooth folder in Explorer that looks something like:</p> <p>"My Bluetooth Places\Entire Bluetooth Neighborhood\DEV1\OBEX File Transfer\E:\" </p> <p>which maps to a device root, and I want to be able to read/write to the file system by treating it as a standard directory.</p> <p>Is this possible?</p>
<p>This is not possible. The way to achieve this is to open a Bluetooth serial connection to the device in question, and traverse its file system using the <a href="https://obex4j.dev.java.net/files/documents/2519/9269/OBEX13.pdf" rel="nofollow">OBEX File Transfer profile</a>.</p>
What are pitfalls for agile development methodologies? <p>What are pitfalls for agile development methodologies?</p>
<p>The <a href="http://en.wikipedia.org/wiki/Agile_software_development">common criticisms</a> include:</p> <ul> <li>Lack of structure and necessary documentation</li> <li>Only works with senior-level developers</li> <li>Incorporates insufficient software design</li> <li>Requires too much cultural change to adopt</li> <li>Can lead to more difficult contractual negotiations</li> <li>Can be very inefficient — if the requirements for one area of code change through various iterations, the same programming may need to be done several times over. Whereas if a plan were there to be followed, a single area of code is expected to be written once.</li> <li>Impossible to develop realistic estimates of work effort needed to provide a quote, because at the beginning of the project no one knows the entire scope/requirements</li> <li>Can increase the risk of scope creep due to the lack of detailed requirements documentation</li> <li>Agile is feature driven, non-functional quality attributes are hard to be placed as user stories</li> </ul>
Localizing system generated status messages <p>I am working in a .NET environment where the system occasionally generates log entries for a customer. Messages are then appended to a customer log which can be reviewed at a later time.</p> <p>For example, if a customer is subscribing to a new service, or a customer has a failed payment attempt, these messages gets appended to the customer log.</p> <p>At the moment, all messages are hardcoded into the code, e.g "Customer failed to finish payment of XX".</p> <p>The problem is now that these messages need to be localized in a smart way, such that when a English user reviews the customer log, he gets the messages in English, and when a foreign user reviews the log, he gets them in his language.</p> <p>What would be the best way to handle this scenario?</p>
<ul> <li>Log event identifiers rather than messages.</li> <li>Capture event specific data along with the event identifier.</li> <li>When a user views the log, localize the event message based on the unique identifier.</li> </ul> <p>The problem you'll run into is if you try to insert dynamic data into the messages in a conversational fashion. For example, if you have to write "No messages found" vs. "One message found" vs. "X messages found" is problematic - in English we have different pluralities for zero, one, and more than one... but it's not necessarily like that in other languages. Things like numbers or dates are less problematic to insert in String.Format form, but you don't want to get in the business of trying to dynamically generate real language in a localized fashion.</p> <p>I'd recommend following a pattern a lot like the Windows Event Log where you output an event ID, a localized message based on the event ID, and then capturing certain "fields" where you'll localize the field name and the display format of the field, like "Amount: $2.00" or whatever. It may not be the prettiest way to go, but unless you've got a full-time linguist dedicated to this and you intend on accounting for all the little nuances of every language, I'd punt and go with a simpler log output format.</p> <p>In your given example, you'd separate the log message from the data, like:</p> <p>Customer failed to finish payment.<br/> Amount: XX</p> <p>You'd log a message ID, like "13579" might be the unique ID for the event when a customer fails to finish a payment. Finally, you could store the value as a separate field.</p> <p>How you go about figuring out how many fields to allocate to an event or how to store the data is... well, an exercise best left to the reader.</p>
How do I set up MySQL to work with C#? <p>I have been tasked with creating a new frontend for a legacy website.</p> <p>It is written in php (pre-oo), and uses a MySQL database. The hosting provides a .Net package, but does not offer Ms Sql Server. </p> <p>This is fine, as the database is working fine, but I really want to use Asp.net for the pages. However, most tutorials I've seen on connecting to MySQL from C# require installing an ODBC Driver specifically for MySQL. Not controlling the hosting env, I doubt I'll be able to do just that :)</p> <p>Have you got any insight to share on this issue?</p>
<p>MySql does have <a href="http://dev.mysql.com/downloads/connector/net/5.2.html" rel="nofollow">connector</a> for .Net. You do not need to use ODBC,</p> <p>MySql Connector will let you interact with your MySql database and is fully managed ADO.Net provider. You have the binary (dll) or the source code if you desire. It's pretty simple, once you have imported the dll you just need a connexion string (username,password,location) and you will be setup!</p> <p>Here is a sample of code (ref: <a href="http://bitdaddys.com/MySQL-ConnectorNet.html" rel="nofollow">bitdaddy.com</a>):</p> <pre><code>string MyConString = "SERVER=localhost;" + "DATABASE=mydatabase;" + "UID=testuser;" + "PASSWORD=testpassword;"; MySqlConnection connection = new MySqlConnection(MyConString); MySqlCommand command = connection.CreateCommand(); MySqlDataReader Reader; command.CommandText = "select * from mycustomers"; connection.Open(); Reader = command.ExecuteReader(); while (Reader.Read()) { string thisrow = ""; for (int i= 0;i&lt;Reader.FieldCount;i++) thisrow+=Reader.GetValue(i).ToString() + ","; listBox1.Items.Add(thisrow); } connection.Close(); </code></pre> <p>I suggest you to do not put your code and persistance in the same place and to place your connexion string in you App.Config, but I think this show you how to do it.</p>
How good is Apache POI word support? <p>On the web page, it looks like there is no current development in the old style .doc.</p> <ul> <li>Is it good enough to create complex documents? </li> <li>Can it read all .docs without crashing?</li> <li>What features do (not) work?</li> </ul> <p>I am not currently interested in the XML based formats, as I don't control the client side. </p> <p>The excel support seems to be much better.</p>
<p>If you are looking for programmatically reading or writing doc files, I believe you're better of with remoting OpenOffice or StarOffice. We've done this at a former company, even though it's a pretty heavy solution, it worked quite well. OpenOffice has (right after Word) a very good doc-Support. For remoting it's a lot better than Word itself. At said company we (earlier) used to remotecontrol Word with frequent problems because Word (on saving a document) insisted on displaying a warning dialog from time to time. Bad idea on a server deep down in some datacenter with nobody close to it.</p> <p>As this was a Java shop, the very good OpenOffice support for Java came in handy. In fact, they even used to bundle the commercial version StarOffice and had some very good contacts at and help from Sun.</p> <p>Disclaimer: As andHapp and alepuzio said, POI is very good in Excel support and I'm using it with big success. Last time I've seen the doc support, I didn't dare using it in production (for customers). I haven't looked at doc support for at least two years.</p>
Set Variable from an Array directly into a List of Variables in Java <p>I have a Java method which returns an array of doubles. I would then like to store these values in individual variables in the calling function. Is there an elegant way of doing this in Java.</p> <p>I could write it as this:</p> <pre><code>double[] returnValues = calculateSomeDoubles(); double firstVar = returnValues[0]; double secondVar = returnValues[1]; </code></pre> <p>I was just wondering if there was some way of compressing this down to a single line? Something like:</p> <pre><code>(firstVar, secondVar) = calculateSomeDoubles(); </code></pre> <p>This type of thing is quite easy when scripting, but the stronger typing of Java means it probably isn't possible.</p>
<p>Basically no, this isn't possible.</p> <p>You'll have to return an object that contains the values.</p> <pre><code>MyObject myObject = calculateMyObject(); </code></pre>
Which is faster, Hash lookup or Binary search? <p>When given a static set of objects (static in the sense that once loaded it seldom if ever changes) into which repeated concurrent lookups are needed with optimal performance, which is better, a <code>HashMap</code> or an array with a binary search using some custom comparator?</p> <p>Is the answer a function of object or struct type? Hash and/or Equal function performance? Hash uniqueness? List size? <code>Hashset</code> size/set size?</p> <p>The size of the set that I'm looking at can be anywhere from 500k to 10m - incase that information is useful.</p> <p>While I'm looking for a C# answer, I think the true mathematical answer lies not in the language, so I'm not including that tag. However, if there are C# specific things to be aware of, that information is desired.</p>
<p>A binary search is going to be O(log n), whereas a hash lookup will be O(1), amortized. You would have to have a pretty terrible hash function to get worse performance than a binary search.</p> <p><strong>EDIT:</strong> When I say "terrible hash", I mean something like:</p> <pre><code>hashCode() { return 0; } </code></pre> <p>Yeah, it's blazing fast itself, but causes your hash map to become a linked list.</p>
Mixing Qt and Boost <p>I'm looking at starting a project in C++ using the Qt 4 framework (a cross-platform GUI is required). I've heard great things about the Boost libraries from friends and online. I've started reading up on both and wanted to ask a cursory question before I got too deep: Are these two development "systems" mutually exclusive? </p> <p>My initial searching and reading shows some overlap in the signal handling, custom build systems, and other low-level primitives.</p> <p>Does it make sense to use them both in the same project?</p>
<p>Yes it makes perfect sense. I would generally prefer using the boost/stdlib functions where possible rather than their Qt alternatives. </p> <p>It makes the code easier to port to the next framework.<br> It makes is easier for new non-Qt programmers to get upto speed.<br> Boost has some great functionality and is getting more all the time. </p> <p>note: strings to/from widgets are probably the main exception - inside the GUI I would use Qt strings to save confusing casts everywhere.</p>
Multi core programming <p>I want to get into multi core programming (not language specific) and wondered what hardware could be recommended for exploring this field. My aim is to upgrade my existing desktop.</p>
<p>If at all possible, I would suggest getting a dual-socket machine, preferably with quad-core chips. You can certainly get a single-socket machine, but dual-socket would let you start seeing some of the effects of NUMA memory that are going to be exacerbated as the core counts get higher and higher.</p> <p>Why do you care? There are two huge problems facing multi-core developers right now:</p> <ol> <li><p><strong>The programming model</strong> Parallel programming is hard, and there is (currently) no getting around this. A quad-core system will let you start playing around with real concurrency and all of the popular paradigms (threads, UPC, MPI, OpenMP, etc).</p></li> <li><p><strong>Memory</strong> Whenever you start having multiple threads, there is going to be contention for resources, and the memory wall is growing larger and larger. A <a href="http://arstechnica.com/news.ars/post/20081207-analysis-more-than-16-cores-may-well-be-pointless.html" rel="nofollow">recent article at arstechnica</a> outlines some (very preliminary) research at Sandia that shows just how bad this might become if current trends continue. Multicore machines are going to have to keep everything fed, and this will require that people be intimately familiar with their memory system. Dual-socket adds NUMA to the mix (at least on AMD machines), which should get you started down this difficult road.</p></li> </ol> <p>If you're interested in more info on performance inconsistencies with multi-socket machines, you might also check out <a href="http://www.renci.org/publications/techreports/TR-08-07.pdf" rel="nofollow">this technical report</a> on the subject.</p> <p>Also, others have suggested getting a system with a CUDA-capable GPU, which I think is also a great way to get into multithreaded programming. It's lower level than the stuff I mentioned above, but throw one of those on your machine if you can. The new Portland Group compilers have <a href="http://www.pgroup.com/resources/accel.htm" rel="nofollow">provisional support for optimizing loops with CUDA</a>, so you could play around with your GPU even if you don't want to learn CUDA yourself.</p>
ISO 9797-1 Algorithm 1 [CBC-MAC] in C# <p>It seems that there're 6 variations to CBC-MAC algorithm. I've been trying to match the MAC algorithm on the PINPad 1000SE [which per manual is ISO 9797-1 Algorithm 1].</p> <p>I got an excellent start from <a href="http://bytes.com/topic/net/answers/654069-iso-iec-9797-1-cbc-mac-using-vb-net" rel="nofollow">here</a>.</p> <p>And I coded the algorithm as below:</p> <pre><code>public static byte[] CalculateMAC(this IPinPad pinpad, byte[] message, byte[] key) { //Divide the key with Key1[ first 64 bits] and key2 [last 64 bits] var key1 = new byte[8]; Array.Copy(key, 0, key1, 0, 8); var key2 = new byte[8]; Array.Copy(key, 8, key2, 0, 8); //64 bits //divide the message into 8 bytes blocks //pad the last block with "80" and "00","00","00" until it reaches 8 bytes //if the message already can be divided by 8, then add //another block "80 00 00 00 00 00 00 00" Action&lt;byte[], int&gt; prepArray = (bArr, offset) =&gt; { bArr[offset] = 0; //80 for (var i = offset + 1; i &lt; bArr.Length; i++) bArr[i] = 0; }; var length = message.Length; var mod = length &gt; 8? length % 8: length - 8; var newLength = length + ((mod &lt; 0) ? -mod : (mod &gt; 0) ? 8 - mod : 0); //var newLength = length + ((mod &lt; 0) ? -mod : (mod &gt; 0) ? 8 - mod : 8); Debug.Assert(newLength % 8 == 0); var arr = new byte[newLength]; Array.Copy(message, 0, arr, 0, length); //Encoding.ASCII.GetBytes(message, 0, length, arr, 0); prepArray(arr, length); //use initial vector {0,0,0,0,0,0,0,0} var vector = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; //encrypt by DES CBC algorith with the first key KEY 1 var des = new DESCryptoServiceProvider { Mode = CipherMode.CBC }; var cryptor = des.CreateEncryptor(key1, vector); var outputBuffer = new byte[arr.Length]; cryptor.TransformBlock(arr, 0, arr.Length, outputBuffer, 0); //Decrypt the result by DES ECB with the second key KEY2 [Original suggestion] //Now I'm Encrypting var decOutputBuffer = new byte[outputBuffer.Length]; des.Mode = CipherMode.ECB; var decryptor = des.CreateEncryptor(key2, vector); //var decryptor = des.CreateDecryptor(key2, vector); decryptor.TransformBlock(outputBuffer, 0, outputBuffer.Length, decOutputBuffer, 0); //Encrypt the result by DES ECB with the first key KEY1 var finalOutputBuffer = new byte[decOutputBuffer.Length]; var cryptor2 = des.CreateEncryptor(key1, vector); cryptor2.TransformBlock(decOutputBuffer, 0, decOutputBuffer.Length, finalOutputBuffer, 0); //take the first 4 bytes as the MAC var rval = new byte[4]; Array.Copy(finalOutputBuffer, 0, rval, 0, 4); return rval; } </code></pre> <p>Then I discovered there're 3 padding schemes and the one that gave me a start may not necessarily be right. The manual came to my rescue again. It seems the device only pads with 0s. Additional block is also nowhere mentioned so I made the below changes:</p> <pre><code> Action&lt;byte[], int&gt; prepArray = (bArr, offset) =&gt; { bArr[offset] = 0; ... } </code></pre> <p>No additional block (if mod 0 [divisible by 8] do not change array length)</p> <pre><code>var newLength = length + ((mod &lt; 0) ? -mod : (mod &gt; 0) ? 8 - mod : 0); </code></pre> <p>The original suggestion wanted me to decrypt at the second step... but Valery <a href="http://www.derkeiler.com/Newsgroups/microsoft.public.dotnet.security/2005-04/0180.html" rel="nofollow">here</a> suggests that it's encrypt all the way. So I changed Decrypt to Encrypt. But still I'm unable to get the requisite MAC...</p> <p>Manual says for key "6AC292FAA1315B4D8234B3A3D7D5933A" [since the key should be 16 bytes, I figured the key here's hex string so I took byte values of 6A, C2, 92, FA... new byte[] { 106, 194, 146, ...] the MAC should be 7B,40,BA,95 [4 bytes] if the message is [0x1a + byte array of MENTERODOMETER]</p> <p>Can someone help? Please?</p> <p><hr /></p> <p>Since Pinpad requires that the first character in message is a 0x1a...</p> <pre><code>public static byte[] CalculateAugmentedMAC(this IPinPad pinpad, string message, byte[] key) { var arr = new byte[message.Length + 1]; var source = Encoding.ASCII.GetBytes(message); arr[0] = 0x1a; //ClearScreenIndicator Array.Copy(source, 0, arr, 1, source.Length); return CalculateMAC(pinpad, arr, key); } </code></pre> <p>I'm calling the code above with this input:</p> <pre><code>var result = pad.CalculateAugmentedMAC("MENTERODOMETER", new byte[] { 106, 194, 146, 250, 161, 49, 91, 77, 130, 52, 179, 163, 215, 213, 147, 58 }); </code></pre>
<p>Most CBC MAC algorithms are implemented in <a href="http://www.bouncycastle.org" rel="nofollow">BouncyCastle</a>'s JCE provider.</p> <p>Look at: <a href="http://bouncycastle.org/viewcvs/viewcvs.cgi/java/crypto/src/org/bouncycastle/jce/provider/BouncyCastleProvider.java?rev=1.83&amp;content-type=text/vnd.viewcvs-markup" rel="nofollow">BouncyCastleProvider.java</a></p> <p>You're probably looking for <code>DESEDEISO9797ALG1MACWITHISO7816-4PADDING</code>, which is an alias for <code>DESEDEMAC64WITHISO7816-4PADDING</code>, implemented here (well, it's a specific configuration of CBCBlockCipherMac using the DESedeEngine and ISO7816d4Padding, you'll have to jump between some classes to get the full picture): <a href="http://bouncycastle.org/viewcvs/viewcvs.cgi/java/crypto/src/org/bouncycastle/jce/provider/JCEMac.java?rev=1.5&amp;content-type=text/vnd.viewcvs-markup" rel="nofollow">JCEMac.java</a></p> <p>Also, have a look at jPos:</p> <p><a href="http://jpos.svn.sourceforge.net/svnroot/jpos/trunk/jpos6/modules/security/src/org/jpos/security/jceadapter/JCESecurityModule.java" rel="nofollow">JCESecurityModule.java</a></p> <p>and their contributed retail MAC algorithm implementation:</p> <p><a href="http://jpos.svn.sourceforge.net/svnroot/jpos/trunk/incoming/retail-mac-contributed-by-vsalaman.zip" rel="nofollow">retail-mac-contributed-by-vsalaman.zip</a></p>
SQL Server 2005 -Seeing SPs executing inside SPs <p>I am wondering if it is possible to see stored procs that are being executed by other stored procs in Sql Server Profiler, is it possible, and if so how?</p>
<p>If you profile using the SP::Starting event, you can see all the stored procedures that are executed. You want to make sure to get a couple of the profile columns included:</p> <p>NestLevel - This shows the nesting level of SPs calling each other - so if Test calls EmbeddedTest then the SP::Starting event for Test wil show NestLevel=1 and the event for EmbeddedTest will show NestLevel=2</p> <p>ObjectName - This shows the name of the stored procedure being executed</p> <p>SPID - Session ID for the connection</p> <p>So to find a calling sequence you need to look for an event with NestLevel greater then 1 and then look for the NestLevel=1 on the same SPID that preceeded the call. Of course this works for deeper nesting levels as well.</p>
Unit testing with Spring Security <p>My company has been evaluating Spring MVC to determine if we should use it in one of our next projects. So far I love what I've seen, and right now I'm taking a look at the Spring Security module to determine if it's something we can/should use. </p> <p>Our security requirements are pretty basic; a user just needs to be able to provide a username and password to be able to access certain parts of the site (such as to get info about their account); and there are a handful of pages on the site (FAQs, Support, etc) where an anonymous user should be given access.</p> <p>In the prototype I've been creating, I have been storing a "LoginCredentials" object (which just contains username and password) in Session for an authenticated user; some of the controllers check to see if this object is in session to get a reference to the logged-in username, for example. I'm looking to replace this home-grown logic with Spring Security instead, which would have the nice benefit of removing any sort of "how do we track logged in users?" and "how do we authenticate users?" from my controller/business code. </p> <p>It seems like Spring Security provides a (per-thread) "context" object to be able to access the username/principal info from anywhere in your app...</p> <pre><code>Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); </code></pre> <p>... which seems very un-Spring like as this object is a (global) singleton, in a way.</p> <p>My question is this: if this is the standard way to access information about the authenticated user in Spring Security, what is the accepted way to inject an Authentication object into the SecurityContext so that it is available for my unit tests when the unit tests require an authenticated user?</p> <p>Do I need to wire this up in the initialization method of each test case?</p> <pre><code>protected void setUp() throws Exception { ... SecurityContextHolder.getContext().setAuthentication( new UsernamePasswordAuthenticationToken(testUser.getLogin(), testUser.getPassword())); ... } </code></pre> <p>This seems overly verbose. Is there an easier way? </p> <p>The <code>SecurityContextHolder</code> object itself seems very un-Spring-like...</p>
<p>Just do it the usual way and then insert it using <code>SecurityContextHolder.setContext()</code> in your test class, for example:</p> <p>Controller:</p> <pre><code>Authentication a = SecurityContextHolder.getContext().getAuthentication(); </code></pre> <p>Test:</p> <pre><code>Authentication authentication = Mockito.mock(Authentication.class); // Mockito.whens() for your authorization object SecurityContext securityContext = Mockito.mock(SecurityContext.class); Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); SecurityContextHolder.setContext(securityContext); </code></pre>
Eclipse PDT HTML attribute assignment operator colour? <p>I would like to know how to change the colour of the equality sign and double quotes for html documents in the eclipse PDT IDE. I can change most colours in Preferences -> Web &amp; XML -> HTML Files -> syntax coloring, but can't change the characters <code>=</code> or <code>"</code> e.g. in an anchor tag <code>&lt;a href=""&gt;</code>.</p> <p>How to change these colours?</p>
<p>It was the only remaining element being overridden by the default <em>Foreground color</em> in the general text editors options.</p>
LinkageError: loader constraints violated when linking javax/xml/namespace/QName in Websphere6.1 using resteasy <p>I am getting this error when making a web services call. I couldn't figure out a workround for this. ANy help is greatly appreciated.</p> <p>related library I have is: axis-1.3.jar<br /> axis-jaxrpc-1.3.jar<br /> axis-saaj-1.3.jar<br /> axis-wsdl4j-1.5.1.jar </p> <p>jaxb-api-2.1.jar jaxb-impl-2.1.8.jar jaxen-1.1-beta-9.jar jaxrs-api-1.0-beta-9.jar</p> <p>In websphere 61 admin setting is the following: Enterprise Application -> WAR Classloader Mode : PARENT_LAST * Web Module : -> ClassLoader Mode : application_FIRST</p> <p>Caused by: java.lang.LinkageError: loader constraints violated when linking javax/xml/namespace/QName class at com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl.(RuntimeBuiltinLeafInfoImpl.java:224) at com.sun.xml.bind.v2.model.impl.RuntimeTypeInfoSetImpl.(RuntimeTypeInfoSetImpl.java:61) at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createTypeInfoSet(RuntimeModelBuilder.java:127) at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.createTypeInfoSet(RuntimeModelBuilder.java:79) at com.sun.xml.bind.v2.model.impl.ModelBuilder.(ModelBuilder.java:152) at com.sun.xml.bind.v2.model.impl.RuntimeModelBuilder.(RuntimeModelBuilder.java:87) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:432) at com.sun.xml.bind.v2.runtime.JAXBContextImpl.(JAXBContextImpl.java:297) at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:139) at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:117) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:211) at javax.xml.bind.ContextFinder.find(ContextFinder.java:372) at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:574) at org.jboss.resteasy.plugins.providers.jaxb.JAXBContextWrapper.(JAXBContextWrapper.java:74) at org.jboss.resteasy.plugins.providers.jaxb.JAXBContextWrapper.(JAXBContextWrapper.java:99) at org.jboss.resteasy.plugins.providers.jaxb.XmlJAXBContextFinder.createContextObject(XmlJAXBContextFinder.java:48) at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBContextFinder.createContext(AbstractJAXBContextFinder.java:114) at org.jboss.resteasy.plugins.providers.jaxb.XmlJAXBContextFinder.findCachedContext(XmlJAXBContextFinder.java:39) at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.findJAXBContext(AbstractJAXBProvider.java:49) at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.getMarshaller(AbstractJAXBProvider.java:112) at org.jboss.resteasy.plugins.providers.jaxb.AbstractJAXBProvider.writeTo(AbstractJAXBProvider.java:88) at org.jboss.resteasy.client.core.MessageBodyParameterMarshaller$ClientRequestEntity.(MessageBodyParameterMarshaller.java:88) at org.jboss.resteasy.client.core.MessageBodyParameterMarshaller.buildRequest(MessageBodyParameterMarshaller.java:51) at org.jboss.resteasy.client.core.ClientInvoker.invoke(ClientInvoker.java:197) at org.jboss.resteasy.client.core.ClientProxy.invoke(ClientProxy.java:46) at $Proxy51.updateAccount(Unknown Source) at com.amg.brides.wedsimple.client.WedSimpleClientImpl.updateAccount(WedSimpleClientImpl.java:72) at com.amg.brides.wedsimple.web.WedSimpleUpdateAccountEvent.invokeClient(WedSimpleUpdateAccountEvent.java:24) at com.amg.brides.wedsimple.web.AbstractWedSimpleAccountEvent.execute(AbstractWedSimpleAccountEvent.java:35) at com.amg.brides.util.WebEventProcessor.processEvents(WebEventProcessor.java:29)</p>
<p>The basic problem is that you're loading one or more class files related to xml from an incorrect jar. Your application server does not permit you to change these libraries, because it has already loaded most of the parser from a different implementation. I tried to inspect the content of the jar files looking for javax/xml/namespace but stopped halfway. If you find it there's a good chance you can get one without the offending classes. People have been known to manually remove such files from external jars.</p> <p>You can probably turn on som vm options to log classloading while the container is running. This is the java -verbose:class option.</p> <p>I'm sorry I cant pinpoint the exact problem ;)</p>
Regular Expressions in unicode strings <p>I have some unicode text that I want to clean up using regular expressions. For example I have cases where u'(2'. This exists because for formatting reasons the closing paren ends up in an adjacent html cell. My initial solution to this problem was to look ahead at the contents of the next cell and using a string function determine if it held the closing paren. I knew this was not a great solution but it worked. Now I want to fix it but I can't seem to make the regular expression work. </p> <pre><code>missingParen=re.compile(r"^\(\d[^\)]$") </code></pre> <p>My understanding of what I think I am doing:<br /> ^ at the beginning of the string I want to find<br /> ( an open paren, the paren has to be backslashed because it is a special character<br /> \d I also want to find a single digit<br /> [ I am creating a special character class<br /> ^ I don't want to find what follows<br /> ) which is a close paren<br /> $ at the end of the string </p> <p>And of course the plot thickens I made a silly assumption that because I placed a \d I would not find (33 but I am wrong so I added a {1} to my regular expression and that did not help, it matched (3333, so my problem is more complicated than I thought. I want the string to be only an open paren and a single digit. Is this the more clever approach </p> <pre><code>missingParen=re.compile(r"^\(\d$") </code></pre> <p>And note S Lott _I already tagged it beginner so you can't pick up any cheap points Not that I don't appreciate your insights I keep meaning to read your book, it probably has the answer</p>
<p>Okay sorry for using this a a stream of consciousness thinking stimulator but it appears that writing out my original question got me on the path. It seems to me that this is a solution for what I am trying to do:</p> <pre><code> missingParen=re.compile(r"^\(\d$") </code></pre>
How to save objects when approval is needed to actually make changes? <p>So I have an object graph, let's just say it's an order. You have the order class, line item class, tracking number class, payment class. You get the idea.</p> <p>Now the business requirement is any user can change the order, but order changes must be approved by the manager. Until the manger approves nothing changes. Managers can change anything, at any time, without approval. </p> <p>What are the best practices for dealing with situations like this? Saving the many (possible) different states of the order object and eventually approving or rejecting the changes.</p> <p>i'm using C# and Nhibernate.</p> <p>Thanks, Kyle.</p>
<p>I would create a transaction table. It would have a record for each pending change. It would reference the order table.</p> <p>So an order would get created but have a pending change; a record would be inserted into the orders table, with a status column of pending, and a record would be insterted into the OrderTransaction table.</p> <p>For every change another record would get inserted into the OrderTransaction table.</p> <p>I would also set up a RequestedChanges table with all the possible requested changes.</p>
SQL Server to Excel 2007 - New Lines <p>I'm trying to retrieve data from an SQL Server 2000 server, and place into Excel. Which sounds simple I know. I'm currently Copying, and Pasting into Excel, from Management Studio</p> <p>The problem is one of the columns is an address, and it’s not retaining the newlines. These new lines have to stay in the same cell in excel, I.E cannot take up 3 rows, for 3 lines of an address.</p> <p>In the SQL Data CHAR(10) and CHAR(13) are included, and other software pick up on these correctly.</p> <p>EDIT: Sorry I forgot to metion, I want the lines to be present in the cell, but not span multiple cells.</p>
<p>Try running this macro on the worksheet. (Right click the worksheet tab and click "View Code" to summon the VB IDE.)</p> <pre><code>Sub FixNewlines() For Each Cell In UsedRange Cell.FormulaR1C1 = Replace(Cell.FormulaR1C1, Chr(13), "") Next Cell End Sub </code></pre>
What is domain logic? <p>What is domain logic? The Wikipedia page for domain logic redirects to business logic. Are they the same thing, and, if not, how do they differ?</p>
<p>Domain is the world your application lives in. So if you are working on say a flight reservation system, the application domain would be flight reservations.</p> <p>Business Logic on the other hand is a more discrete block of the entire Application Domain. Business Logic is usually a chuck of code built to perform one specific business process. So you would have business logic to take a reservation. An other bit of business logic would be code to refund canceled tickets.</p> <p>The objects that support your business process then become your business objects!</p>
Sending data from one page to another server. Language agnostic <p>I'll try to keep this short and simple. I haven't begun writing the code for this project yet, but I'm trying to work out the pre-coding logistics as of right now.</p> <p>What I am looking to do, is create a method of sending data from one/any site, to another remote server, which would generate a response for the user requesting the data be sent.</p> <p>Specifically, a web designer should be able to take a snippet of code I would have available on my website, implement it into their own page(s), and when a user browses their page(s), my service would be available.</p> <p>A specific example, a web designer with a website (<code>helloworld.com</code>) could implement my code into their page (<code>helloworld.com/index.html</code>). When a user is viewing the page (<code>/index.html</code>), the user hovers the mouse over a text word (lemonade) for a couple seconds, a small dialog box pops up beside it, providing the user with some options specific to the text (example of an option would be "Define 'lemonade' at Dictionary.com") that if selected, would be processed at, and a response would be returned from my remote server (<code>myremoteserver.com</code>)</p> <p>Obviously, I would want the code that designers would be using to be as lightweight and standalone as possible. Any ideas as to how I could execute this? Resources I should study, and methods I could implement?</p>
<p>Please do not create another one of those services that annoyingly double-underlines words in web site content and then pops up a ugly, slow-to-load ad over the content if I accidentally mouse over the word. Because that sounds like what you're doing.</p> <p>If you're going to do it anyway, then what the "remote server" will be will probably actually be a bit of client-side JavaScript, in which case <a href="http://json.org/" rel="nofollow">JSON</a> is probably your best bet. XML could also work, but even when JavaScript isn't on the other side, I rather like JSON as a <a href="http://en.wikipedia.org/wiki/Serialization" rel="nofollow">serialization</a> technique due to its compactness and readability.</p>
Correct way to handle 2D z-indexing in a 3D scene (DirectX) <p>I need to achieve the following:</p> <p>Two 2D quads appear as though they are stacked one on top of the other (like two halves of the same texture) but are in fact seperated on the z axis by n coordinates. So that if a 3D object passes between them one half appears in front of the object and the other behind.</p> <p>Could i achieve this by applying orthogonal projection to the two quads and then normal perspective to the rest of the 3d data? Will this lose depth data?</p> <p>I hope my example isn't too misleading!</p>
<p>The simple answer is yes,if you have z write turned on while rendering your quads. Your z data is never discarded unless you do it explicitly.</p> <p>Getting orthagonal depths to play nicely with projection depths may be tricky, however. (I've never tried, but I imagine it's not going to line up nicely.) In that case it would be best to do one of the following:</p> <ul> <li>Render all geometry in a perspective view</li> <li>Render all geometry in an othogonal view</li> <li>Render orthogonal geometry in non-z-tested sorted layers (back to front), rendering you perspective geometry in between.</li> </ul> <p>I'm assuming you will already know the downsides to the first two methods, so it's up to you if that's acceptable. I think the third method is the most traditional. </p>
Datamart vs. reporting Cube, what are the differences? <p>The terms are used all over the place, and I don't know of crisp definitions. I'm pretty sure I know what a data mart is. And I've created reporting cubes with tools like Business Objects and Cognos.</p> <p>I've also had folks tell me that a datamart is more than just a collection of cubes.</p> <p>I've also had people tell me that a datamart is a reporting cube, nothing more.</p> <p>What are the distinctions you understand?</p>
<p><a href="http://en.wikipedia.org/wiki/Olap_cube">Cube</a> can (and arguably should) mean something quite specific - OLAP artifacts presented through an <a href="http://en.wikipedia.org/wiki/MOLAP">OLAP server</a> such as <a href="http://msdn.microsoft.com/en-us/library/ms175609(SQL.90).aspx">MS Analysis Services</a> or Oracle (nee Hyperion) <a href="http://www.oracle.com/appserver/business-intelligence/essbase.html">Essbase</a>. However, it also gets used much more loosely. OLAP cubes of this sort use cube-aware query tools which use a different API to a standard relational database. Typically OLAP servers maintain their own optimised data structures (known as <a href="http://en.wikipedia.org/wiki/MOLAP">MOLAP</a>), although they can be implemented as a front-end to a relational data source (known as <a href="http://en.wikipedia.org/wiki/ROLAP">ROLAP</a>) or in various hybrid modes (known as <a href="http://en.wikipedia.org/wiki/HOLAP">HOLAP</a>)</p> <p>I try to be specific and use 'cube' specifically to refer to cubes on OLAP servers such as SSAS. </p> <p><a href="http://www.businessobjects.com/">Business Objects</a> works by querying data through one or more sources (which could be relational databases, OLAP cubes, or flat files) and creating an in-memory data structure called a <a href="http://olapreport.com/purchase/snapshot/BusinessObjects.htm">MicroCube</a> which it uses to support interactive slice-and-dice activities. Analysis Services and MSQuery can make a <a href="http://office.microsoft.com/en-us/excel/HP052479081033.aspx">cube (.cub) file</a> which can be opened by the AS client software or Excel and sliced-and-diced in a similar manner. IIRC Recent versions of Business Objects can also open .cub files. </p> <p>To be pedantic I think Business Objects sits in a 'semi-structured reporting' space somewhere between a true OLAP system such as ProClarity and ad-hoc reporting tool such as <a href="http://msdn.microsoft.com/en-us/library/ms155933.aspx">Report Builder</a>, <a href="http://www.oracle.com/technology/products/discoverer/index.html">Oracle Discoverer</a> or <a href="http://www.oracle.com/technology/products/bi/interactive-reporting/index.html">Brio</a>. Round trips to the Query Panel make it somewhat clunky as a pure stream-of-thought OLAP tool but it does offer a level of interactivity that traditional reports don't. I see the sweet spot of Business Objects as sitting in two places: ad-hoc reporting by staff not necessarily familiar with SQL and provding a scheduled report delivered in an interactive format that allows some drill-down into the data.</p> <p><a href="http://en.wikipedia.org/wiki/Datamart">'Data Mart'</a> is also a fairly loosely used term and can mean any user-facing data access medium for a data warehouse system. The definition may or may not include the reporting tools and metadata layers, reporting layer tables or other items such as Cubes or other analytic systems.</p> <p>I tend to think of a data mart as the database from which the reporting is done, particularly if it is a readily definable subsystem of the overall data warehouse architecture. However it is quite reasonable to think of it as the user facing reporting layer, particularly if there are ad-hoc reporting tools such as Business Objects or OLAP systems that allow end-users to get at the data directly.</p>
SQL Sorting and hyphens <p>Is there a way to easily sort in SQL Server 2005 while ignoring hyphens in a string field? Currently I have to do a REPLACE(fieldname,'-','') or a function to remove the hyphen in the sort clause. I was hoping there was a flag I could set at the top of the stored procedure or something.</p> <p>Access and the GridView default sorting seems to ignore the hypen in strings.</p>
<p>I learned something new, just like you as well</p> <p>I believe the difference is between a "<strong>String Sort</strong>" vs a "<strong>Word Sort</strong>" (ignores hyphen)</p> <p>Sample difference between WORD sort and STRING sort <a href="http://andrusdevelopment.blogspot.com/2007/10/string-sort-vs-word-sort-in-net.html">http://andrusdevelopment.blogspot.com/2007/10/string-sort-vs-word-sort-in-net.html</a></p> <p>From Microsoft <a href="http://support.microsoft.com/kb/322112">http://support.microsoft.com/kb/322112</a></p> <blockquote> <p>For example, if you are using the SQL collation "SQL_Latin1_General_CP1_CI_AS", the non-Unicode string 'a-c' is less than the string 'ab' because the hyphen ("-") is sorted as a separate character that comes before "b". However, if you convert these strings to Unicode and you perform the same comparison, the Unicode string N'a-c' is considered to be greater than N'ab' because the Unicode sorting rules use a "word sort" that ignores the hyphen.</p> </blockquote> <p>I did some sample code you can also play with the COLLATE to find the one to work with your sorting</p> <pre><code>DECLARE @test TABLE (string VARCHAR(50)) INSERT INTO @test SELECT 'co-op' INSERT INTO @test SELECT 'co op' INSERT INTO @test SELECT 'co_op' SELECT * FROM @test ORDER BY string --COLLATE SQL_Latin1_General_Cp1_CI_AS --co op --co-op --co_op SELECT * FROM @test ORDER BY CAST(string AS NVARCHAR(50)) --COLLATE SQL_Latin1_General_Cp1_CI_AS --co op --co_op --co-op </code></pre>
How detect whether running under valgrind in make file or shell script? <p>I need to detect whether my Makefile is running under valgrind (indirectly, using valgrind --trace-children=yes), I know how to do it from C but I have not found a way to do it from a script,</p> <p>The earlier answers works on Linux only. For Mac OS X I am an going to grep for VALGRIND_STARTUP_PWD in the environment, unless someone has a better idea.</p>
<p>from a shell:</p> <p><code>grep -q '/valgrind' /proc/$$/maps &amp;&amp; echo "valgrindage"</code></p> <p>This determines if the valgrind preloaded libraries are present in address map of the process. This is <em>reasonably</em> effective, but if you happen to have a non-valgrind related library that shares the '/valgrind' moniker then you will get a false positive (unlikely).</p> <p>[I changed the grep pattern from vg_preload to /valgrind, as testing on Debian/Ubuntu revealed that the library name was different, while a directory match of valgrind is most likely to succeed.]</p>
How would I get the column names from a Model LINQ? <p>I am looking to get a list of the column names returned from a Model. Anyone know how this would be done, any help would be greatly appreciated.</p> <p>Example Code:</p> <pre><code>var project = db.Projects.Single(p =&gt; p.ProjectID.Equals(Id)); </code></pre> <p>This code would return the Projects object, how would I get a list of all the column names in this Model.</p> <p>Thanks</p>
<p>This would be nice to have as an extension method:</p> <pre><code>public static class LinqExtensions { public static ReadOnlyCollection&lt;MetaDataMember&gt; ColumnNames&lt;TEntity&gt; (this DataContext source) { return source.Mapping.MappingSource.GetModel (typeof (DataContext)).GetMetaType (typeof (TEntity)).DataMembers; } } </code></pre> <p>example:</p> <pre><code>var columnNames = myDataContext.ColumnNames&lt;Orders&gt; (); </code></pre>
Representing sparse integer sets? <p>What is a good way to represent sparse set of integers (really C memory addresses) in a compact and fast way. I already know about the obvious things like bit-vectors and run-length encoding. but I want something much more compact than one word per set element. I need to add and remove elements and test for membership. I do not need other set operations, like union.</p> <p>I read about one such library many years ago but have since forgotten its name. I think it was released as open source by HP and had a womans name.</p>
<p>You are referring to a judy array. It was a HP project. I think they are used in ruby and are available in c. Very interesting data structure. Making use of the fact that allocations are (at least) word aligned, having separate structures for dense and sparse ranges.</p> <p><a href="http://judy.sourceforge.net/index.html">http://judy.sourceforge.net/index.html</a></p>
Excel 2002 Add-In not loading when the application opens <p>Good afternoon,</p> <p>I created an Excel .xla addin for Excel 2002. This weird behavior I am seeing from it happens only on my machine, but not on my coworkers. I would like to understand why.</p> <p>The add-in has a UDF function that gets called from many, many spreadsheets.</p> <ul> <li><p>My Add-in is set to open when Excel opens. When I open a blank spreadsheet it works fine.</p></li> <li><p>If I double-click on an .XLS that references the add-in, Excel fails to load the VBA project, and I get #NAME!. However, if I open Excel and then the spreadsheet, it works fine.</p></li> </ul> <p>I've checked the blacklist "disabled items" under the help menu. There's nothing there. This has been working for a long time now; I can't find out what changed. I've tried nuking all Registry entries with my add-in's name and trying again. Still doesn't work.</p> <p>Any ideas? Thanks. -Alan.</p>
<p>Eventually I figured out that all the problematic spreadsheets had RTD/DDE links in them, and it turns out that the data source process is never really running on my machine. As soon as I went to Edit-Links and removed those links everything worked fine.</p>
Get selected text and selected nodes on a page? <p>When selecting a block of text (possibly spanning across many DOM nodes), is it possible to extract the selected text and nodes using Javascript?</p> <p>Imagine this HTML code:</p> <pre><code>&lt;h1&gt;Hello World&lt;/h1&gt;&lt;p&gt;Hi &lt;b&gt;there!&lt;/b&gt;&lt;/p&gt; </code></pre> <p>If the user initiated a mouseDown event starting at "World..." and then a mouseUp even right after "there!", I'm hoping it would return:</p> <pre><code>Text : { selectedText: "WorldHi there!" }, Nodes: [ { node: "h1", offset: 6, length: 5 }, { node: "p", offset: 0, length: 16 }, { node: "p &gt; b", offset: 0, length: 6 } ] </code></pre> <p>I've tried putting the HTML into a textarea but that will only get me the selectedText. I haven't tried the <code>&lt;canvas&gt;</code> element but that may be another option.</p> <p>If not JavaScript, is there a way this is possible using a Firefox extension? </p>
<p>You are in for a bumpy ride, but this is quite possible. The main problem is that IE and W3C expose completely different interfaces to selections so if you want cross browser functionality then you basically have to write the whole thing twice. Also, some basic functionality is missing from both interfaces.</p> <p>Mozilla developer connection has the story on <a href="https://developer.mozilla.org/en/DOM/window.getSelection">W3C selections</a>. Microsoft have their system <a href="http://msdn.microsoft.com/en-us/library/ms535869%28VS.85%29.aspx">documented on MSDN</a>. I recommend starting at PPK's <a href="http://www.quirksmode.org/dom/range%5Fintro.html">introduction to ranges</a>.</p> <p>Here are some basic functions that I believe work: </p> <pre><code>// selection objects will differ between browsers function getSelection () { return ( msie ) ? document.selection : ( window.getSelection || document.getSelection )(); } // range objects will differ between browsers function getRange () { return ( msie ) ? getSelection().createRange() : getSelection().getRangeAt( 0 ) } // abstract getting a parent container from a range function parentContainer ( range ) { return ( msie ) ? range.parentElement() : range.commonAncestorContainer; } </code></pre>
HowTo Multicast a Stream Captured with DirectShow? <p>I have a requirement to build a very simple streaming server. It needs to be able to capture video from a device and then stream that video via multicast to several clients on a LAN. </p> <p>The capture part of this is pretty easy (in C#) thanks to a library someone wrote with DirectShow.Net (<a href="http://www.codeproject.com/KB/directx/directxcapture.aspx" rel="nofollow">http://www.codeproject.com/KB/directx/directxcapture.aspx</a>). </p> <p>The question I have now is how to multicast this? This is the part I'm stuck on. I'm not sure what to do next, or what steps to take. </p>
<p>There are no filters available that you can plug and use.</p> <p>You need to do three things here:</p> <ol> <li>Compress the video into MPEG2 or MPEG4</li> <li>Mux it into MPEG Transport Stream</li> <li>Broadcast it</li> </ol> <p>There are lots of codecs available for part 1, and some devices can even output compressed video.</p> <p>The part 3 is quite simple too.</p> <p>Main problem goes with part 2, as MPEG Transport Stream is patented. It is licensed so that you cannot develop free software based on it (VLC and FFMPEG violate that license), and you have to pay several hundred dollars just to obtain a copy of specification.</p> <p>If you have to develop it, you need to:</p> <ul> <li>Obtain a copy of ISO/IEC 13818-1-2000 (you may download it as PDF from their site), it describes MPEG Transport Stream</li> <li>Develop a renderer filter that takes MPEG Elementary Streams and muxes them into Transport Stream</li> </ul> <p>It has to be a renderer as Transport Stream is not a transform filter. There are some kind of outband data (program allocation tables and reference clocks) that need to be sent on a regular basis, and you need to keep a worker thread to do that.</p>
SSE4 instructions in VS2005? <p>I need to use the popcnt instruction in a project that is compiled using Visual Stdio 2005<br /> The intrinsic <code>__popcnt()</code> only works with VS2008 and the compiler doesn't seem to recognize the instruction even when I write in a <code>__asm {}</code> block.</p> <p>Is there any way to do this?</p>
<p>Okay, this is a wild guess thing but ... assuming you've set up VS2005 like <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/3e24f203-c516-41e2-a7bf-325452157336/" rel="nofollow">this</a> to do assembly language, then you could get a hold of the <a href="http://www.developers.net/filestore2/download/2550" rel="nofollow">SSE4.1 manual</a> from Intel and code a macro for each SSE4.1 opcode that you needed as per this <a href="http://www.masm32.com/board/index.php?topic=973.0" rel="nofollow">thread</a> at masm32.com (which discusses a similar issue w.r.t. SSE2.)</p> <p>For example, here's some code out of one of the downloads from the masm32 link:</p> <pre><code>;SSE2 macros for MASM 6.14 by daydreamer aka Magnus Svensson ADDPD MACRO M1,M2 db 066h ADDPS M1,M2 ENDM ADDSD MACRO M1,M2 DB 0F2H ADDPS M1,M2 ENDM </code></pre>
Increase number of characters in filename field of GetOpenFileName file selection dialog <p>Our app allows multiple files to be selected in a file selection dialog which is shown via the GetOpenFileName function (this question also applies to folks using CFileDialog, etc...)</p> <p>There appears to be a limit to the number of characters that can be typed into the filename field (259 seems to be the magic number - not sure why).</p> <p>We have tried changing the following members of the <a href="http://msdn.microsoft.com/en-us/library/ms646839(VS.85).aspx" rel="nofollow">OPENFILENAME</a> structure:</p> <p>lpstrFile - point to our own buffer, sized at 4K bytes nMaxFile - set to the size of lpstrFile (we are compiling ANSI, so this is effectively 4000</p> <p>But these values appear to not increase the input width of the filename field in the dialog.</p> <p>I am going to experiment with sending a EM_SETLIMITTEXT message to the control, but wanted to know if anyone else has a solution.</p> <p>EDIT - solved this myself: <a href="http://stackoverflow.com/questions/361350/increase-number-of-characters-in-filename-field-of-getopenfilename-file-selecti#394443">solution</a> I can't accept out my own answer, but here it is for posterity. If anyone else has a better solution, please post it - or feel free to mod up my solution so future searchers will find it at the top.</p>
<p>Turns out that the edit control (At least in my development environment) is a combo box, so <code>EM_SETLIMITTEXT</code> isn't appropriate. </p> <p>Instead, I tracked down the combo box using <code>GetDlgCtrl</code> on the parent of the file open dialog (I do this in the <code>OnInitDialog</code> handler), cast it to <code>CComboBox*</code>, then call <code>LimitText()</code> to set the limit. </p> <p>This could also be done by sending a <code>CB_LIMITTEXT</code> message to the control for those of you who are not working with <code>CFileDialog</code>. The appropriate value here is most likely the <code>OPENFIILENAME.nMaxFile</code> value that is passed in.</p>
Can I hide a directory/path from Launch Services? <p>I would like to be able to build test applications (e.g. the nightly Minefield/Firefox) without Launch Services deciding that they're the best way to open their assigned file types.</p> <p>Is there a way to hide my ~/src directory from Launch Services, so that Finder won't register applications in that folder?</p>
<p>I don't know of a way to do that hiding, but you <em>can</em> change the bundle ID of your development apps so that they don't get treated as the preferred app for that content type/URI scheme by LaunchServices.</p>
Silverlight 2 Error Code: 4004 <p>Hey guys/gals. I have a silverlight 2 app that has an ObservableCollection of a class from a separate assem/lib. When I set my ListBox.ItemsSource on that collection, and run it, I get the error code: 4004 "System.ArgumentException: Value does not fall within the expected range." Here is part of the code:</p> <pre><code>public partial class Page : UserControl { ObservableCollection&lt;Some.Lib.Owner&gt; ooc; public Page() { ooc = new ObservableCollection&lt;Some.Lib.Owner&gt;(); Some.Lib.Owner o1 = new Some.Lib.Owner() { FirstName = "test1" }; Some.Lib.Owner o2 = new Some.Lib.Owner() { FirstName = "test2" }; Some.Lib.Owner o3 = new Some.Lib.Owner() { FirstName = "test3" }; ooc.Add(o1); ooc.Add(o2); ooc.Add(o3); InitializeComponent(); lb1.ItemsSource = ooc; } } </code></pre> <p>But when I create the Owner class within this same project, everything works fine. Is there some security things going on behind the scenes? Also, I'm using the generate a html page option and not the aspx option, when I created this Silverlight 2 app.</p>
<p>Are you trying to use a standard class library or a "Silverlight Class Library"?</p> <p>Because Silverlight 2 uses a subset of the CLR it cannot access standard class libraries that were compiled using the full CLR. To use an external assembly you must create it as a "Silverlight Class Library". This will create a project that only includes the namespaces available to Silverlight and will allow you to reference the assembly within your Silverlight project.</p> <p>Check out the MSDN article <a href="http://msdn.microsoft.com/en-us/library/cc838194(VS.95).aspx" rel="nofollow">".NET Framework Class Library for Silverlight"</a> for more info.</p>
initializing std::string from char* without copy <p>I have a situation where I need to process large (many GB's) amounts of data as such:</p> <ol> <li>build a large string by appending many smaller (C char*) strings</li> <li>trim the string</li> <li>convert the string into a C++ const std::string for processing (read only)</li> <li>repeat</li> </ol> <p>The data in each iteration are independent.</p> <p>My question is, I'd like to minimise (if possible eliminate) heap allocated memory usage, as it at the moment is my largest performance problem.</p> <p>Is there a way to convert a C string (char*) into a stl C++ string (std::string) without requiring std::string to internally alloc/copy the data?</p> <p>Alternatively, could I use stringstreams or something similar to re-use a large buffer?</p> <p><strong>Edit:</strong> Thanks for the answers, for clarity, I think a revised question would be:</p> <p><em>How can I build (via multiple appends) a stl C++ string efficiently. And if performing this action in a loop, where each loop is totally independant, how can I re-use thisallocated space.</em></p>
<p>You can't actually form a std::string without copying the data. A stringstream would probably reuse the memory from pass to pass (though I think the standard is silent on whether it actually has to), but it still wouldn't avoid the copying.</p> <p>A common approach to this sort of problem is to write the code which processes the data in step 3 to use a begin/end iterator pair; then it can easily process either a std::string, a vector of chars, a pair of raw pointers, etc. Unlike passing it a container type like std::string, it would no longer know or care how the memory was allocated, since it would still belong to the caller. Carrying this idea to its logical conclusion is <a href="http://www.boost.org/doc/libs/1_37_0/libs/range/index.html" rel="nofollow">boost::range</a>, which adds all the overloaded constructors to still let the caller just pass a string/vector/list/any sort of container with .begin() and .end(), or separate iterators.</p> <p>Having written your processing code to work on an arbitrary iterator range, you could then even write a custom iterator (not as hard as it sounds, basically just an object with some standard typedefs, and operator ++/*/=/==/!= overloaded to get a forward-only iterator) that takes care of advancing to the next fragment each time it hit the end of the one it's working on, skipping over whitespace (I assume that's what you meant by trim). That you never had to assemble the whole string contiguously at all. Whether or not this would be a win depends on how many fragments/how large of fragments you have. This is essentially what the SGI rope mentioned by Martin York is: a string where append forms a linked list of fragments instead of a contiguous buffer, which is thus suitable for much longer values.</p>
Reading an XML File using FileInputStream (for Java)? <p>here's the deal.</p> <p>For my project I have to serialize and deserialize a random tree using Java and XStream. My teacher made the Tree/RandomTree algorithms, so I don't have to worry about that. What I don't know how to do is this: I am using FileInputStream to read/write the xml file that I serialized and deserialized, but when I deserialize, I do not know the method used to read the file. After I read the file I should be able to convert it from XML and then print it out as a string. Here's what I have so far. (I imported everything correctly, just didn't add it to my code segment). </p> <pre><code>FileInputStream fin; try { // Open an input stream fin = new FileInputStream ("/Users/Pat/programs/randomtree.xml"); //I don't know what to put below this, to read FileInpuStream object fin String dexml = (String)xstream.fromXML(fin); System.out.println(dexml); // Close our input stream fin.close(); System.out.println(dexml); // Close our input stream fin.close(); } // Catches any error conditions catch (IOException e) { System.err.println ("Unable to read from file"); System.exit(-1); } </code></pre> <p><hr /></p> <p><strong>Edit:</strong> Hey guys, thanks for the help, I figured it out; I don't think I have to print it as a string, I just needed to make a benchmarking framework to time it and such, but thanks again!</p>
<p>The <code>xstream.fromXML()</code> method will do the reading from the input stream for you. I think the problem is that you are casting the return value from <code>xstream.fromXML(fin)</code> into a String when it should be cast to the type of object you originally serialized (<code>RandomTree</code> I assume). So the code would look like this:</p> <pre><code>RandomTree tree = (RandomTree)xstream.fromXML(fin); </code></pre> <p>EDIT: after clarification in comments, the author's goal is to first read into a String so the XML contents can be printed before deserialization. With that goal in mind, I recommend taking a look at the IOUtils library mentioned in <a href="http://stackoverflow.com/questions/326390/is-there-an-alternative-to-this-way-of-read-file-to-a-string-in-java#326413">this thread</a></p>
ASP.NET MVC vs WebForms for First Page Load Speed for Big Projects <p>We have a pretty big ASP.NET WebForm (web application) project with a lot of references to other libraries, other projects etc and most of the time after a compilation, the first time we load a page it takes a LONG time before rendering anything... Disk IO is the main problem. For small projects it's nearly instantaneous, but once your project gets large, it can really slow development and remove fun from programming.</p> <p>My question: Is first page load time after a compilation as long in ASP.NET MVC as it is in ASP.NET Webforms for big projects?</p>
<p>MVC still uses the same ASP.NET framework as Web Forms, so you are probably going to see similar behavior, regardless. </p> <p>The long first load time is because your project's build output is still just IL code that needs to be compiled into native code by the JIT compiler before executing. Any code changes that you make will cause the previously cached native code for your app to be discarded, so the JIT has to recompile. Naturally, the larger your project, the longer it's going to take for the JIT to process it.</p>
VS2008 binary 3x times slower than VS2005? <p>I've just upgraded a native C++ project from VS2005-SP1 to VS2008-SP1<br /> The first thing I tested was a very basic functionality test of the application and the first thing I noticed is that the main number-crunching algorithm performs three times slower in the VS2008 binary.<br /> I tested again the VS2005 binary to make sure there isn't any other difference and it still performed as it did before.<br /> Did anyone stumble into this?</p>
<p>Strangest. Thing. Ever. </p> <p>It seems that the project upgrade wizard of vs2008 simply doesn't copy the '<code>Optimization="2"</code>' property so the new project is left with no optimization in release. </p> <p>The fix was to go to the properties dialog, change optimization to 1 and then back to 2. compile again and everything works it should.</p> <p>I couldn't find any official reference for this only <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/fb32033b-7bad-439b-a94c-943a17f0cbb2/" rel="nofollow">this obscure reference</a> in an MSDN forum.</p>
Get last MySQL binary log entry <p>I'm using MySQL replication, and I'd like a status script running on the slave to report the last statement that was replicated over to the slave.</p> <p>I can use "SHOW SLAVE STATUS" to get the current read and execute positions. But how do I use that information with mysqlbinlog to read the last entry? Assuming the slave is caught up with the master, the following statement returns nothing useful:</p> <pre><code>mysqlbinlog.exe -R --start-position=&lt;READ_MASTER_LOG_POS&gt; &lt;MASTER_LOG_FILE&gt; -h &lt;MASTER_HOST&gt; </code></pre> <p>I can't seem to minus one from the log position to get the previous statement, and I don't see any way to give a negative offset meaning to read from the end in reverse order. Is there any way to do this?</p> <p>Thanks!</p>
<p>Are you after the last statement that was sent to the slave, or the last statement that was executed on the slave? You mention that you're assuming the slave is caught up with the master, in which case you simply need to read the last statement in the relay log instead, with the information available in SHOW SLAVE STATUS:</p> <pre><code>mysqlbinlog.exe --start-position=&lt;RELAY_LOG_POS&gt; &lt;RELAY_LOG_FILE&gt; </code></pre>
Drupal 6 : CCK : Views2 : What ways would you substitute an image for a view-field <p><strong>Background:</strong> Customer X has a CCK-based Content Type (vendorxxentry) and is using Views2 to generate a listing of all the vendorxxentry nodes in a simple table. </p> <p>One of the fields in vendorxxentry is called "vendorxxattitude", which appears as one of the following enumerated possible values:</p> <ul> <li>happy</li> <li>sleepy</li> <li>dopey</li> <li>grumpy</li> </ul> <p>Customer X has four custom-made 16x16 images that correspond to these enumerated values. He wants to have them display in the generated view, so instead of seeing "happy" in the generated view, the user would see the image happy.png in its place. Customer X would like to accomplish this without breaking the ability to sort individual columns as can be currently done with Views2 in table output mode.</p> <p><strong>Question:</strong> What methods would you use in order to substitute the text with the associated images? Assume that the images should only be substituted in one or more specific views (e.g., vendorxxsummary, vendorxxbyxxdate, vendorxxbyxxindustry), but not in the individual node views themselves.</p>
<p>You can change the 'mood' from a simple data field to a taxonomy vocabulary, with each mood being a term in the vocabulary. Then use <a href="http://drupal.org/project/taxonomy_image" rel="nofollow">Taxonomy Image</a> module to substitute an image for each mood in any way you like.</p>
Recovering from an unfortunate "svn copy" <p>This afternoon, upon noticing a broken build and the fact that some files looked like very old versions (about 2 weeks old), I checked the svn log. Apparently just this afternoon, 1 of the developers did an "svn copy" of a directory from an older revision to the same directory. Thus it appears that the latest version "i.e. head" of all the files in that directory are really old, and all the history "i.e. log" is even older.</p> <p>However, I think I can recover by using another "svn copy" (i.e. the disease is the cure). What I am considering doing is finding the revision where the bad "svn copy" was done (say rev 1234) , subtracting 1 (1233) and doing:</p> <pre><code>svn copy -r 1233 file://path/to/messed/up/dir file://path/to/messed/up/dir </code></pre> <p>That <em>should</em> restore the latest version, as well as get back all my history. Am I right about this?</p>
<p>According to <a href="http://svnbook.red-bean.com/" rel="nofollow">the SVN book</a>,</p> <pre><code>svn merge -c -1234 </code></pre> <p>should do the trick.</p> <p>There's a whole <a href="http://svnbook.red-bean.com/en/1.5/svn.branchmerge.basicmerging.html#svn.branchmerge.basicmerging.undo" rel="nofollow">section</a> about this in the book.</p> <p>The verbose explanation: <code>-c -1234</code> translates into <code>-r 1234:1233</code>, which reverts the change from revision 1234.</p>
Is a keyframed transition possible in Core Animation? <p>I know that keyframed transitions are possible in Core Animation via setting the <code>path</code> property on the <code>CAAnimation</code> instance. However, <code>CATransition</code> does not seem to have this functionality. Does anyone know any other ways to control the transition apart from setting the timing function?</p>
<p>The answer seems to be no. If you want to do this sort of thing, you have to add the CAAnimation yourself rather than depending on transitions. The transitions probably depend on some deep workings of CoreAnimation, because they don't work the same way normal animations do (they don't move the object in question, they control how the new content of the object replaces the old).</p>
Is there any native way in ASP.NET to do a "success message"? <p>Say you have something like an ASP.NET ASP:DetailsView to show and edit a single record in a database.</p> <p>It's simple to record the error cases... you add validation and a validation summary. When your update form fails validation it naturally makes noise: it shows the validation message and/or the validation summary. Not a single code behind is required.</p> <p>But then, you pass validation, and it makes your update completely silently. There's no sense that anything happened, and there doesn't seem to be any default settings to make a success message without code-behinds.</p> <p>But, even code-behinds are confusing. What event should show the success message? onItemUpdate, right? Fine, but then let's say you make another change and get a validation error? Your success message stays. I wasn't able to find an event that would reliably turn off an existing success message if there were a validation error. </p> <p>This should be web development 101! Why is it so hard?</p> <p><strong>EDIT:</strong></p> <p>Someone suggested using the ItemCommand event... I tried this and many other events, but that success message just won't disappear. Here's some code.</p> <p>My message in ASP.NET</p> <pre><code>&lt;label id="successMessage" class="successMessage" runat="server"&gt;&lt;/label&gt; </code></pre> <p>And my DataView tag (simplified):</p> <pre><code> &lt;asp:DetailsView Id="EditClient" DataKeyNames="LicenseID" DataSourceID="MySource" runat="server" OnItemUpdated="SuccessfulClientUpdate" OnItemCommand="ClearMessages"&gt; </code></pre> <p>And, my code-behind:</p> <pre><code>protected void SuccessfulClientUpdate(object sender, DetailsViewUpdatedEventArgs e) { successMessage.InnerText = string.Format("Your changes were saved."); successMessage.Visible = true; } protected void ClearMessages(object sender, DetailsViewCommandEventArgs e) { successMessage.InnerText = string.Empty; successMessage.Visible = false; } </code></pre> <p>Once I do a successful update, however, nothing seems to make that message disappear, not even failed validation.</p> <p><strong>2nd EDIT:</strong></p> <p>Just want to be clear that I did try putting the ClearMessages code in Page_Load. However, nothing seems to make that successMessage label disappear when I hit update a 2nd time WITH a validation error. Can anyone suggest any other troubleshooting tips?</p>
<p>As far as I know, there is no native way of doing this. You may rant about it, maybe Microsoft will hear it :).</p> <p>Resetting the "success message" on Page_Load, or wherever in your code-behind, won't work. This is because ASP.NET validation is usually done both client and server-side. This means for every validation control you put on the page, ASP.NET generates some client-side Javascript that does the validation and renders the error on the client, <strong>without</strong> going back to the server. So you're stuck with both the success message and the error message at the same time.</p> <p>What you can do about it:</p> <ul> <li>place a <code>&lt;div&gt;</code> control on your page, that would show up the success message (as already suggested by others above). Whenever you update something (in server-side code), show up the control and set a meaningful "Successful!" message text.</li> <li>register a custom Javascript function that would lookup the <code>&lt;div&gt;</code> and hide it on every page submit. Be aware that the function needs to be called before the autogenerated client script that does the validation.</li> </ul> <p>If you look at the client source of an ASP.NET page (with validators on it), here's what you can find:</p> <p><code>&lt;form name="aspnetForm" method="post" action="MyPage.aspx" onsubmit="javascript:return WebForm_OnSubmit();id="aspnetForm"&gt;</code></p> <p>The WebForm_OnSubmit is generated by ASP.NET and calls the javascript that does the validation. Sample:</p> <pre><code>function WebForm_OnSubmit() { if (typeof(ValidatorOnSubmit) == "function" &amp;&amp; ValidatorOnSubmit() == false) return false; return true; } </code></pre> <p>To register your custom code that hides the success message, you should place (in your code-behind) something along these lines:</p> <pre><code>if (!Page.ClientScript.IsOnSubmitStatementRegistered("ClearMessage")) { string script = @"document.getElementById('" + yourDivControl.ClientID + "').style.display='none'"; Page.ClientScript.RegisterOnSubmitStatement(Page.GetType(), "ClearMessage", script); } </code></pre> <p>This will turn your page's autogenerated WebForm_OnSubmit into the following:</p> <pre><code>function WebForm_OnSubmit() { document.getElementById('ctl00_yourDivControl').style.display='none'; if (typeof(ValidatorOnSubmit) == "function" &amp;&amp; ValidatorOnSubmit() == false) return false; return true; } </code></pre> <p>The effect: On every postback (e.g. when ItemCommand is triggered, or when some Save button is clicked, or anything else), you will show up the div control with the "success" message. On the next postback, just before submitting the page to the server, this message is cleared. Of course, if this postback also triggers a "success", the message is shown again by the code-behind on the server. And so on and so forth.</p> <p>I hope the above is helpful. It's not the full-blown solution, but it gives sufficient hints to point you in the right direction.</p>
How do sites like Hubspot track inbound links? <p>Are all these types of sites just illegally scraping Google or another search engine?<br /> As far as I can tell ther is no 'legal' way to get this data for a commercial site.. The Yahoo! api ( <a href="http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html" rel="nofollow">http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html</a> ) is only for noncommercial use, Yahoo! Boss does not allow automated queries etc.<br /> Any ideas?</p>
<p>For example, if you wanted to find all the links to Google's homepage, search for</p> <pre><code>link:http://www.google.com </code></pre> <p>So if you want to find all the inbound links, you can simply traverse your website's tree, and for each item it finds, build a URL. Then query Google for:</p> <pre><code>link:URL </code></pre> <p>And you'll get a collection of all the links that Google has from other websites into your website.</p> <p>As for the legality of such harvesting, I'm sure it's not-exactly-legal to make a profit from it, but that's never stopped anyone before, has it? </p> <p>(So I wouldn't bother wondering whether they did it or not. Just assume they do.)</p>
How can I extract or change links in HTML with Perl? <p>I have this input text:</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;meta http-equiv="content-type" content="text/html; charset=utf-8"&gt;&lt;/head&gt;&lt;body&gt;&lt;table cellspacing="0" cellpadding="0" border="0" align="center" width="603"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td&gt;&lt;table cellspacing="0" cellpadding="0" border="0" width="603"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td width="314"&gt;&lt;img height="61" width="330" src="/Elearning_Platform/dp_templates/dp-template-images/awards-title.jpg" alt="" /&gt;&lt;/td&gt; &lt;td width="273"&gt;&lt;img height="61" width="273" src="/Elearning_Platform/dp_templates/dp-template-images/awards.jpg" alt="" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;table cellspacing="0" cellpadding="0" border="0" align="center" width="603"&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td colspan="3"&gt;&lt;img height="45" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/top-bar.gif" alt="" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td background="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" width="12"&gt;&lt;img height="1" width="12" src="/Elearning_Platform/dp_templates/dp-template-images/left-bar-bg.gif" alt="" /&gt;&lt;/td&gt; &lt;td width="580"&gt;&lt;p&gt;&amp;nbsp;what y all heard?&lt;/p&gt;&lt;p&gt;i'm shark oysters.&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/td&gt; &lt;td background="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" width="11"&gt;&lt;img height="1" width="11" src="/Elearning_Platform/dp_templates/dp-template-images/right-bar-bg.gif" alt="" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;img height="31" width="603" src="/Elearning_Platform/dp_templates/dp-template-images/bottom-bar.gif" alt="" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt;&lt;/table&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt; </code></pre> <p>As you can see, there's no newline in this chunk of HTML text, and I need to look for all image links inside, copy them out to a directory, and change the line inside the text to something like <code>./images/file_name</code>. </p> <p>Currently, the Perl code that I'm using looks like this:</p> <pre><code>my ($old_src,$new_src,$folder_name); foreach my $record (@readfile) { ## so the if else case for the url replacement block below will be correct $old_src = ""; $new_src = ""; if ($record =~ /\&lt;img(.+)/){ if($1=~/src=\"((\w|_|\\|-|\/|\.|:)+)\"/){ $old_src = $1; my @tmp = split(/\/Elearning/,$old_src); $new_src = "/media/www/vprimary/Elearning".$tmp[-1]; push (@images, $new_src); $folder_name = "images"; }## end if } elsif($record =~ /background=\"(.+\.jpg)/){ $old_src = $1; my @tmp = split(/\/Elearning/,$old_src); $new_src = "/media/www/vprimary/Elearning".$tmp[-1]; push (@images, $new_src); $folder_name = "images"; } elsif($record=~/\&lt;iframe(.+)/){ if($1=~/src=\"((\w|_|\\|\?|=|-|\/|\.|:)+)\"/){ $old_src = $1; my @tmp = split(/\/Elearning/,$old_src); $new_src = "/media/www/vprimary/Elearning".$tmp[-1]; ## remove the ?rand behind the html file name if($new_src=~/\?rand/){ my ($fname,$rand) = split(/\?/,$new_src); $new_src = $fname; my ($fname,$rand) = split(/\?/,$old_src); $old_src = $fname."\\?".$rand; } print "old_src::$old_src\n"; ##s7test print "new_src::$new_src\n\n"; ##s7test push (@iframes, $new_src); $folder_name = "iframes"; }## end if }## end if my $new_record = $record; if($old_src &amp;&amp; $new_src){ $new_record =~ s/$old_src/$new_src/ ; print "new_record:$new_record\n"; ##s7test my @tmp = split(/\//,$new_src); $new_record =~ s/$new_src/\.\\$folder_name\\$tmp[-1]/; ## print "new_record2:$new_record\n\n"; ##s7test }## end if print WRITEFILE $new_record; } # foreach </code></pre> <p>This is only sufficient to handle HTML text with newlines in them. I thought only looping the regex statement, but then i would have to change the matching line to some other text.</p> <p>Do you have any idea if there an elegant Perl way to do this? Or maybe I'm just too dumb to see the obvious way of doing it, plus I know putting global option doesn't work.</p> <p>thanks. ~steve</p>
<p>There are excellent HTML parsers for Perl, learn to use them and stick with that. HTML is complex, allows > in attributes, heavily use nesting, etc. Using regexes to parse it, beyond very simple tasks (or machine generated code), is prone to problems.</p>
FontFamily question <p>Why the FontFamily param of the Font object is a string and not an enum?</p>
<p>FontFamily refers to the name of the Font. While you could use "monospace" or "serif" I wouldn't think it would be supported by .Net.</p> <p>Remember, using a enum would be impossible. A enum is a static compile-time feature, which means that it can't "generate" a enum dynamically from fonts on your system. Indeed, including anything this specific in a language would probably be a poor idea. Even if this was supported, the user's machine wouldn't have the same fonts as yours - some fonts would be incorrectly included in the list and some excluded (because once compiled an enum becomes 'final'). </p> <p>Enums are a convenient store of integral constants and NOTHING else. Each item in a enum has a convenient name and a value, even if you don't specify it. The following two enums are the same.</p> <pre><code>public enum MyEnum { A = 1, B = 2 } public enum FooEnum { A, B } </code></pre> <p>And there are two other problems, enum names can not contain spaces, where font names can. Getting the fields from an enum is not a trivial task (it requires a lot of reflection code).</p> <p>The following code will get you a list of fonts (you will need to add System.Drawing as a reference):</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing.Text; using System.Drawing; namespace ConsoleApplication19 { class Program { static void Main(string[] args) { InstalledFontCollection ifc = new InstalledFontCollection(); foreach (FontFamily o in ifc.Families) { Console.WriteLine(o.Name); } Console.ReadLine(); } } } </code></pre>
Literature and tutorials for writing a ray tracer <p>I am interested in finding recommendations on books on writing a raytracer, simple and clear implementations of ray tracing that can be seen on the web, and online resources on introductory ray tracing.</p> <p>Ideally, the approach would be incremental and tutorial in style, and explain both the programming techniques and underyling mathematics, starting from the basics.</p>
<p>"Ray Tracing from the Ground Up" by Kevin Suffern for getting started.</p> <p>"Physically Based Rendering" by Matt Pharr and Greg Humphreys for a more advanced take on it when you've gotten comfortable with the basics.</p> <p>And if you get really into it, the <a href="http://tog.acm.org/resources/RTNews/html/" rel="nofollow">Ray Tracing News</a> archives are a good read. Also, a lot of ray tracing enthusiast hang out at the <a href="http://ompf2.com/" rel="nofollow">ompf2.com forum</a>.</p>
How to read list of string <p>I have this:</p> <p>Public stringList As New List(Of String)</p> <p>I need to read the whole list using For each statement, what is the best way to do so using VB.net syntax?</p> <p>Thanks,</p>
<p>It sounds like it would be worth you reading <a href="http://msdn.microsoft.com/en-us/library/5ebk1751.aspx" rel="nofollow">the MSDN documentation for the For Each ... Next statement</a>.</p> <p>For example:</p> <pre><code>For Each x As String In stringList Console.WriteLine(x) Next </code></pre> <p>If that's not what you're after, please give more details in your question.</p>
Thread safety and `const` <p>How does <code>const</code> (pointers, references and member functions) help with thread safety in C++?</p>
<p>Any immutable (that is, unchangable) data is inherently thread safe - there's no risk for multiple threads concurrently reading the same read-only data because it's never going to change!</p> <p>Marking a variable as const in C++ makes it read-only and thus thread safe.</p>
How to abstract out 2 different implementations of cache <p>I plan to use a distributed cache in my load-balanced webapp. So I'm going to try to abstract out the common functions between apache ehcache and memcached.</p> <p>My goal is to be able to make a simple configuration switch to select the caching solution to use. Should I go the SPI route e.g. like how XML parsers are wired in ?</p>
<p>After fixing the interface, this is really a creational pattern problem. Dependency Injection is my favourite, if the cache-selection strategy is dynamic you can use spring bean factories to decide at runtime. Spring has support for "session" scopes on web-applications meaning you can let the factory decide per session if you want to.</p> <p>Otherwise a simple service locator should also do the trick.</p> <p><a href="http://en.wikipedia.org/wiki/Service_locator_pattern" rel="nofollow">http://en.wikipedia.org/wiki/Service_locator_pattern</a></p>
UITextField input issue <p>In my application there have two Outlet, one is UItextfield and another is UIWebview, textfield used to get the url request by the user and shown it in webview, but I met a problem is when finish the typing in my textfield, and click GO button(return) in the keyboard, that is nothing happen in my webview, my source code as shown in below:</p> <pre><code>- (BOOL)textFieldShouldReturn:(UITextField *)textField { NSLog(@"clicked"); [textField resignFirstResponder]; [mywebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[textField text]]]]; return YES; } </code></pre> <p>What is the problem?</p>
<p>Have you set the delegate of the textfield to be the class with the textFieldShouldReturn: method?</p>
Image resize in Grails <p>I am developing a Web Album using Grails and for image processing, I am using grails-image-tools plugin. I need a functionality to resize the images if the uploaded images size is too big (for eg: more than 600 * 840 ) . In this case I need to resize this image to 600 * 840). What is the most efficient way to do this? Thanks a lot.</p>
<p>In <code>BuildConfig.groovy</code> add a dependency to <a href="http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/">imgscalr</a></p> <pre><code>dependencies { compile 'org.imgscalr:imgscalr-lib:4.1' } </code></pre> <p>Then resizing images becomes a one-liner:</p> <pre><code>BufferedImage thumbnail = Scalr.resize(image, 150); </code></pre>
What is the best practice for persistence right now? <p>I come from a java background.</p> <p>But I would like a cross-platform perspective on what is considered best practice for persisting objects.</p> <p>The way I see it, there are 3 camps:</p> <ul> <li>ORM camp</li> <li>direct query camp e.g. JDBC/DAO, iBatis</li> <li>LINQ camp</li> </ul> <p>Do people still handcode queries (bypassing ORM) ? Why, considering the options available via JPA, Django, Rails.</p>
<p>There is no one best practice for persistence (although the number of people screaming that ORM is best practice might lead you to believe otherwise). The only best practice is to use the method that is most appropriate for your team and your project.</p> <p>We use ADO.NET and stored procedures for data access (though we do have some helpers that make it very fast to write such as SP class wrapper generators, an IDataRecord to object translator, and some higher order procedures encapsulating common patterns and error handling).</p> <p>There are a bunch of reasons for this which I won't go into here, but suffice to say that they are decisions that work for our team and that our team agrees with. Which, at the end of the day, is what matters.</p>
Updating from Java 1.4.2 to Java 6 (both Sun VMs) results in slower performance <p>I've just upgraded some old Java source which has been running on a Sun Java 1.4.2 VM to Sun Java (JRE) 6 VM. More or less the only thing I had to change was to add explicit datatypes for some abstract objects (Hashmap's, Vector's and so on). The code itself it quite memory intensive, using up to 1G of heap memory (using -Xmx1024m as a parameter to start the VM).</p> <p>Since I read alot about better performance on newer Java VM's, this was one of the reasons I did this upgrade.</p> <ol> <li>Can anyone think of a reason why the performance is worse in my case now (just in general, of course, since you can't take a look at the code)?</li> <li>Has anyone some advice for a non Java guru what to look for if I wanted to optimize (speed wise) existing code? Any hints, recommended docs, tools?</li> </ol> <p>Thanks.</p>
<p>Not much information here. But here are a couple of things you might want to explore:</p> <ul> <li><p>Start the VM with Xmx and Xms as the same value (in your case 1024M)</p></li> <li><p>Ensure that the server jvm dll is being used to start the virtual machine.</p></li> <li><p>Run a profiler to see what objects are hogging memory or what objects are not being garbage collected</p></li> <li><p>Hook up your VM with the jconsole and trace through the objects</p></li> </ul>
How do I detect the DLLs required by an application? <p>In a nutshell: I want to do the same thing "Dependency Walker" does.</p> <p>Is there any Win32 API function which can enumerate the dependencies of a EXE and/or DLL file?</p> <p>And is there any safe way to detect dependencies on ActiveX classes? (I doubt it is possible, but who knows ...)</p> <p><strong>EDIT:</strong> I'm aware of available tools which provide the same core functionality (Dependency Walker, ProcessExplorer, AQTime, ...) but I want to create my own program which dumps a text file containing the required modules. </p>
<p>The following commands dumps the direct dependencies of some.exe :</p> <pre><code>dumpbin /imports some.exe </code></pre> <p>It works on DLLs too.</p> <p>This won't list dependencies such as plugins loaded at application launch (via LoadLibrary calls). Same for COM dependencies since they work the same way (as far as I know).</p> <p>If you need to know all the DLLs used by a running program, use ProcessExplorer.</p>
Carbide / Symbian C++ - Change Application Icon <p>I am using Carbide (just upgraded to 2.0) to develop an S60 3rd Edition application.</p> <p>I would like to know the easiest way to change the icon (both the application icon on the device menu <strong>and</strong> the icon at the top left of the main view) because I have the need to skin my application in many different ways as easily as possible.</p> <p>All my efforts with messing around with .mif files have so far failed. I have a 44x44 .svg icon I made with Illustrator, could someone please help me in the right direction?</p> <p>Thanks!</p>
<p>To change the app icon when you run your app use (in the status bar):</p> <pre><code>CEikStatusPane* sp=iEikonEnv-&gt;AppUiFactory()-&gt;StatusPane(); CAknContextPane* cp=(CAknContextPane *)sp-&gt;ControlL(TUid::Uid(EEikStatusPaneUidContext)); _LIT(KContextBitMapFile, "my_bitmap_file.mbm"); CFbsBitmap* bitmap = iEikonEnv-&gt;CreateBitmapL(KContextBitMapFile, EMbmBitmap); CleanupStack::PushL(bitmap); CFbsBitmap* bitmapmask = iEikonEnv-&gt;CreateBitmapL(KContextBitMapFile, EMbmBitmapMask); CleanupStack::PushL(bitmapmask); cp-&gt;SetPicture(bitmap, bitmapmask); CleanupStack::Pop(); // bitmapmask CleanupStack::Pop(); // bitmap DrawNow(); </code></pre> <p>I'm not aware of any possibility of changing the app icon in the menu list programmatically, other than reinstalling the app with different mif file.</p>
How can I get an ListView item from the (X,Y) position? <p>I am dropping something in a ListView in WPF. I need to know the item in the (X,Y) position I am dropping. How can I do this?</p> <hr> <p>The WPF ListView doesn't have GetItemAt. I return to my original problem.</p>
<p>Done! Thanks to this article <a href="http://www.codeproject.com/KB/WPF/WPF_Drag_And_Drop_Sample.aspx">http://www.codeproject.com/KB/WPF/WPF_Drag_And_Drop_Sample.aspx</a></p> <pre><code>private int GetCurrentIndex(GetPositionDelegate getPosition) { int index = -1; for (int i = 0; i &lt; clasesListView.Items.Count; ++i) { ListViewItem item = GetListViewItem(i); if (this.IsMouseOverTarget(item, getPosition)) { index = i; break; } } return index; } private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition) { Rect bounds = VisualTreeHelper.GetDescendantBounds(target); Point mousePos = getPosition((IInputElement)target); return bounds.Contains(mousePos); } delegate Point GetPositionDelegate(IInputElement element); ListViewItem GetListViewItem(int index) { if (clasesListView.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return null; return clasesListView.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem; } </code></pre>
Are iframes considered 'bad practice'? <p>Somewhere along the line I picked up the notion that using iframes is 'bad practice'. </p> <p>Is this true? What are the pros/cons of using them?</p>
<p>As with all technologies, it has its ups and downs. If you are using an iframe to get around a properly developed site, then of course it is bad practice. However sometimes an iframe is acceptable. </p> <p>One of the main problems with an iframe has to do with bookmarks and navigation. If you are using it to simply embed a page inside your content, I think that is fine. That is what an iframe is for.</p> <p>However I've seen iframes abused as well. It should never be used as an integral part of your site, but as a piece of content within a site.</p> <p>Usually, if you can do it without an iframe, that is a better option. I'm sure others here may have more information or more specific examples, it all comes down to the problem you are trying to solve.</p> <p>With that said, if you are limited to HTML and have no access to a backend like PHP or ASP.NET etc, sometimes an iframe is your only option.</p>
Java memory model - can someone explain it? <p>For years and years, I've tried to understand the <a href="http://java.sun.com/docs/books/jls/third_edition/html/memory.html#17.4">part</a> of Java specification that deals with memory model and concurrency. I have to admit that I've failed miserably. Yes' I understand about locks and "synchronized" and wait() and notify(). And I can use them just fine, thank you. I even have a vague idea about what "volatile" does. But all of that was not derived from the language spec - rather from general experience.</p> <p>Here are two sample questions that I am asking. I am not so much interested in particular answers, as I need to understand how the answers are derived from the spec (or may be how I conclude that the spec has no answer).</p> <ul> <li>What does "volatile" do, exactly?</li> <li>Are writes to variable atomic? Does it depend on variable's type?</li> </ul>
<p>I'm not going to attempt to actually answer your questions here - instead I'll redirect you to the book which I seeing recommended for advice on this topic: <a href="http://rads.stackoverflow.com/amzn/click/0321349601">Java Concurrency in Practice</a>.</p> <p>One word of warning: if there <em>are</em> answers here, expect quite a few of them to be wrong. One of the reasons I'm not going to post details is because I'm pretty sure <em>I'd</em> get it wrong in at least some respects. I mean no disrespect whatsoever to the community when I say that the chances of everyone who thinks they can answer this question actually having enough rigour to get it right is practically zero. (Joe Duffy recently found a bit of the .NET memory model that was surprised by. If he can get it wrong, so can mortals like us.)</p> <p><hr /></p> <p>I will offer some insight on just one aspect, because it's often misunderstood:</p> <p>There's a difference between volatility and atomicity. People often think that an atomic write is volatile (i.e. you don't need to worry about the memory model if the write is atomic). That's not true.</p> <p>Volatility is about whether one thread performing a read (logically, in the source code) will "see" changes made by another thread.</p> <p>Atomicity is about whether there is any chance that if a change <em>is</em> seen, only part of the change will be seen.</p> <p>For instance, take writing to an integer field. That is guaranteed to be atomic, but not volatile. That means that if we have (starting at foo.x = 0):</p> <pre><code>Thread 1: foo.x = 257; Thread 2: int y = foo.x; </code></pre> <p>It's possible for <code>y</code> to be 0 or 257. It won't be any other value, (e.g. 256 or 1) due to the atomicity constraint. However, even if you know that in "wall time" the code in thread 2 executed after the code in thread 1, there could be odd caching, memory accesses "moving" etc. Making the variable <code>x</code> volatile will fix this.</p> <p>I'll leave the rest up to real honest-to-goodness experts.</p>
How do realloc and memcpy work? <p>Dear all, Here are my questions...</p> <p>1- Do realloc and memcpy copy the entries in an array to another in a way faster than just iterating on each element O(N) ? If the answer is yes then what do you think is its complexity ?</p> <p>2- If the size allocated is smaller than the original size, does realloc copy the entries to somewhere else or just leave them as they are decreasing the size of the array ?</p> <p>Thanks so much.</p>
<p>1 - No. They copy a block at a time. See <a href="http://www.embedded.com/design/configurable-systems/4024961/Optimizing-Memcpy-improves-speed" rel="nofollow">http://www.embedded.com/design/configurable-systems/4024961/Optimizing-Memcpy-improves-speed</a> for a pretty good analysis.</p> <p>2 - This is implementation dependent. See <a href="http://www.gnu.org/software/libtool/manual/libc/Changing-Block-Size.html" rel="nofollow">http://www.gnu.org/software/libtool/manual/libc/Changing-Block-Size.html</a> for glibc details. "In several allocation implementations, making a block smaller sometimes necessitates copying it"</p>
Should an interface that is inherited from base-class be implemented explicitly in subclass? <p>My question is, if an interface that is implemented implicitly by extending a class that already implements it, should be explicitly implemented by the class, if the class wants to advertise the fact, that it fulfills the contract of that interface. </p> <p>For instance, if you want to write a class, that fulfills the contract of the interface <code>java.util.List</code>. You implement this, extending the class <code>java.util.AbstractList</code>, that already implements the interface <code>List</code>. Do you explicitly declare, that you implement List?</p> <pre><code>public class MyList extends AbstractList implements List </code></pre> <p>Or do you save typing by using the implicit way?</p> <pre><code>public class MyList extends AbstractList </code></pre> <p>Which way is considered better style? What reasons do you have to prefer one way or another? In which situations you would prefer way 1 or way 2?</p>
<p>Avoid redundancy. Use method 2.</p> <p>Use @Override for overrides.</p>
What is the best way to determine application root directory? <p>I need to get all dlls in my application root directory. What is the best way to do that?</p> <pre><code>string root = Application.StartupPath; </code></pre> <p>Or,</p> <pre><code>string root = new FileInfo(Assembly.GetExecutingAssembly().Location).FullName; </code></pre> <p>And after that,</p> <pre><code>Directory.GetFiles(root, "*.dll"); </code></pre> <p>Which way is better? Are there better ways?</p>
<p><code>AppDomain.CurrentDomain.BaseDirectory</code> is my go to way of doing so.</p> <p>However:</p> <p><code>Application.StartupPath</code> gets the directory of your executable</p> <p><code>AppDomain.BaseDirectory</code> gets the directory used to resolve assemblies</p> <p>Since they can be different, perhaps you want to use Application.StartupPath, unless you care about assembly resolution.</p>
MFC AfxParseURL reverse function? <p>Is there reverse function to MFC AfxParseURL (which creates URL from service type, port and so on)?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/cs1z60t6.aspx" rel="nofollow">AfxParseURL</a> is a wrapper around the <a href="http://msdn.microsoft.com/en-us/library/aa384376.aspx" rel="nofollow">InternetCrackUrl </a> function in <code>&lt;wininet.h&gt;</code>. The reverse function is <a href="http://msdn.microsoft.com/en-us/library/aa384473.aspx" rel="nofollow">InternetCreateUrl</a>, but MFC does not provide a wrapper for this.</p> <p>You could either use <code>InternetCreateUrl</code> directly or create your own wrapper function that takes <code>CString</code> objects as input, initialises a <code>URL_COMPONENTS</code> structure, calls <code>InternetCreateUrl</code>, and returns the result as a <code>CString</code>.</p>
circular dependencies between dlls with visual studio <p>I have a circular dependency between two functions. I would like each of these functions to reside in its own dll. Is it possible to build this with visual studio?</p> <pre><code>foo(int i) { if (i &gt; 0) bar(i -i); } </code></pre> <p>-> should compile into foo.dll</p> <pre><code>bar(int i) { if (i &gt; 0) foo(i - i); } </code></pre> <p>-> should compile into bar.dll</p> <p>I have created two projects in visual studio, one for foo and one for bar. By playing with the 'References' and compiling a few times, I managed to get the dll's that I want. I would like to know however whether visual studio offers a way to do this in a clean way.</p> <p>If foo changes, bar does not need to be recompiled, because I only depend on the signature of bar, not on the implementation of bar. If both dll's have the lib present, I can recompile new functionality into either of the two and the whole system still works.</p> <p>The reason I am trying this is that I have a legacy system with circular dependencies, which is currently statically linked. We want to move towards dll's for various reasons. We don't want to wait until we clean up all the circular dependencies. I was thinking about solutions and tried out some things with gcc on linux and there it is possible to do what I suggest. So you can have two shared libraries that depend on each other and can be built independent of each other.</p> <p>I know that circular dependencies are not a good thing to have, but that is not the discussion I want to have.</p>
<p>The reason it works on Unix-like systems is because they perform actual linking resolution at load time. A shared library does not know where its function definition will come from until it's loaded into a process. The downside of this is that you don't know either. A library can find and call functions in any other library (or even the main binary that launched the process in the first place). Also by default everything in a shared library is exported.</p> <p>Windows doesn't work like that at all. Only explicitly exported things are exported, and all imports must be resolved at library link-time, by which point the identity of the DLL that will supply each imported function has been determined. This requires an import library to link against.</p> <p>However, you can (with some extra work) get around this. Use <code>LoadLibrary</code> to open any DLL you like, and then use <code>GetProcAddress</code> to locate the functions you want to call. This way, there are no restrictions. But the restrictions in the normal method are there for a reason.</p> <p>As you want to transition from static libraries to DLLs, it sounds like you're assuming that you should make each static library into a DLL. That's not your only option. Why not start moving code into DLLs only when you identify it as a self-contained module that fits into a layered design with no circularity? That way you can begin the process now but still attack it a piece at a time.</p>
How long before the line of business app in F# becomes the norm? <p>With the recent news about F# being included with Visual Studio 2010, I got to thinking ... how soon before I see functional programming take hold in the usual "line of business app" space?</p>
<p>I would add the subjective tag to that one ;)</p> <p>Personally, I don't think it will become the norm although it will be used in areas where it is well suited.</p> <p>I don't think it will become the norm because it is best suited to certain layers of the application, but isn't well suited to other layers like UI.</p> <p>Because of this, development of several layers will continue in C# or VB. From a company's perspective, even if F# is the better tool for one part of the application, they will tend to write it in C# or VB anyway to maintain consistency, because their programmers will be more adept in those languages and so that future hires will be easier to find.</p>
jRails vs. Prototype <p>I am not trying to make this a preference question, I am really wondering what people's experiences are with using jQuery and Rails or jRails for development. Most rails users including myself up to now have been using Prototype. However, I am mixing in a lot of jQuery plugins since they are so easy to use and extend.</p> <p>I am now thinking about moving from Prototype to jQuery for a new Rails project. However, I love the Power of Prototype. Protoype is almost a new language that sites ontop of JS whereas I find that jQuery is like a great scripting language with lots of syntax sugar and chaining.</p> <p>Anyway, your thoughts would be much appreciated.</p>
<p>In Rails it really all comes down to the helper methods. Are you using any prototype helper methods? If so then you must use jRails to switch to jQuery. But if not then it really does not matter. They are both great. I used prototype a lot before and it is great. But I prefer the selector way of doing things with jQuery so I have switched. Another good reason to not use the helper methods is unobtrusive javascript. The rails helper methods creates messy inline code.</p>
In WPF, how can I determine what column/row in a grid a control is in? <p>I am building a grid dynamically and putting buttons in one of the columns. When I click a button, I want to know what row of my grid it's in. How can I find this?</p>
<p>In the Click event handler for the button you say:</p> <pre><code>int row; Button btn = sender as Button; if (btn != null) { row = Grid.GetRow(btn); // And you have the row number... } else { // A nasty error occurred... } </code></pre>
How do I set the ideal QPixmapCache::cacheLimit? <p>I have just started using QPixmapCache and I was wondering, since there is not much documentation, about how to adjust the size based on the system the application is running on.</p> <p>Some users might have lots of free memory while others have very little. I have no idea what the best setting would be. </p> <p>What would be the best way to detect the system (free) RAM and adjust the cache size to fit?</p> <p><a href="http://doc.trolltech.com/4.4/qpixmapcache.html#setCacheLimit" rel="nofollow">http://doc.trolltech.com/4.4/qpixmapcache.html#setCacheLimit</a></p>
<p>To detect free RAM in Windows, you can use the <a href="http://msdn.microsoft.com/en-us/library/aa366586.aspx" rel="nofollow">GlobalMemoryStatus</a> function.</p> <p>I'm not sure if this will help you size the pixmap cache; perhaps you will need to do some performance measurements and create a lookup table.</p>
How to avoid XML injection <p>I have input field value from that is used for forming XPath query. What symbols in input string should I check to minimise possibility of XML injection?</p>
<p>This <a href="http://packetstormsecurity.org/papers/bypass/Blind_XPath_Injection_20040518.pdf" rel="nofollow"><strong>document</strong></a> describes in detail the concept of "Blind XPath Injection".</p> <p>It provides concrete examples of XPath injections and discusses ways of preventing such.</p> <p>In the section "<strong>Defending against XPath Injection</strong>" it is said:</p> <p>"<em>Defending against XPath Injection is essentially similar to defending against SQL injection. The application must sanitize user input. Specifically, the single and double quote characters should be disallowed. This can be done either in the application itself, or in a third party product (e.g. application firewall.) Testing application susceptibility to XPath Injection can be easily performed by injecting a single quote or a double quote, and inspecting the response. If an error has occurred, then it’s likely that an XPath Injection is possible</em>."</p> <p>As others have said, one should also pay attention to using of axes and the // abbreviation. If <a href="http://www.w3.org/TR/xpath20/" rel="nofollow"><strong>XPath 2.0</strong></a> is being used, then the <a href="http://www.w3.org/TR/xpath-functions/#func-doc" rel="nofollow"><strong><code>doc</code></strong>()</a> function should not be allowed, as it gives access to any document with known URI (or filename).</p> <p>It is advisable to use an API which precompiles an XPath expression but leaves the possibility that it works with dynamically defined parameters or variables. Then the user input will define the contents of these parameters only and will never be treated as a modification of the already compiled expression.</p>
Is it possible to sort numbers in a QTreeWidget column? <p>I have a QTreeWidget with a column filled with some numbers, how can I sort them?</p> <p>If I use setSortingEnabled(true); I can sort correctly only strings, so my column is sorted:</p> <p>1 10 100 2 20 200</p> <p>but this is not the thing I want! Suggestions?</p>
<p>You can sort overriding the &lt; operator and changing sort condiction like this.</p> <pre><code>class TreeWidgetItem : public QTreeWidgetItem { public: TreeWidgetItem(QTreeWidget* parent):QTreeWidgetItem(parent){} private: bool operator&lt;(const QTreeWidgetItem &amp;other)const { int column = treeWidget()-&gt;sortColumn(); return text(column).toLower() &lt; other.text(column).toLower(); } }; </code></pre> <p>In this example it ignore the real case, confronting fields in lowercase mode.</p>
Bind an ObjectDataSource to an existing method in my Data access layer <p>I've seen the designer code, and I have seen code which builds the ObjectDataSource in the code-behind, however both methods communicate directly with the database via either text commands or stored procs. This seems like unnecessary code duplication to me since my data access layer has a method already which returns a datatable with the data I need for this report. </p> <p>How can I programmatically build and link the ODS to my data access layer's method?</p> <p>EDIT: </p> <p>Thanks to everyone who answered. This was very poorly phrased on my part. There was too much that I did not understand when I wrote this question originally. What I should have asked is: </p> <p>How do I programmatically bind a .Net Reporting Services Report (*.rdlc) to a method in my Data Access Layer instead of an ADO.Net DataSet.</p> <p>See my answer below. </p>
<p>In order to use a standard .Net DataSet as an DataSource for a Reporting Services Report I had to:</p> <ol> <li><p>Create an ADO DataSet which uses the same stored procedure as the DAL method</p></li> <li><p>Use the ADO DataSet to populate the fields in the Report in the designer</p></li> <li><p>In the aspx page, use the following:</p> <pre class="lang-html prettyprint-override"><code>&lt;rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" Height="655px" Width="980px"&gt; &lt;ServerReport ReportServerUrl="" /&gt; &lt;LocalReport&gt; &lt;/LocalReport&gt; &lt;/rsweb:ReportViewer&gt; </code></pre> <p>And in the code-behind:</p> <pre><code>ReportViewer1.ProcessingMode = ProcessingMode.Local Dim report As LocalReport = ReportViewer1.LocalReport report.ReportPath = "&lt;your report path&gt;" report.DataSources.Clear() Dim rds As New ReportDataSource() rds.Name = "&lt;dataset name&gt;_&lt;stored proc name&gt;" rds.Value = &lt;your DAL method ()&gt; report.DataSources.Add(rds) report.Refresh() </code></pre></li> <li><p>Once you have tested this and are comfortable with the report you get, you can safely exclude the ADO DataSet from your project.</p></li> </ol> <p>Notes: This is far from ideal and there are likely steps I did which are unnecessary or something I missed.<br> One thing that gave me a real headache was that the XML in the RDLC contained definitions for old ADO datasets that were no longer relevant. To strip those out, right click the rdlc file in your Solution Explorer and select "Open With" then XML Editor in the next menu. </p>
Browsing for SQL Servers <p>I'm writing a database application that connects to SQL server. I'd like to implement a similar connection dialog box like the one in SQL Management Studio. I've already found a way to get the list of databases on a server, but I'd really like to get the list of available servers on the network so end users won't have to type in the name/IP of the server.</p>
<p>If you are developing your program in .Net you can use the SMO objects to do this. Use the Microsoft.SqlServer.Management.Smo.SmoApplication.EnumAvailableSqlServers method to get a list of all sql servers running in your local network.<br /> The scanning taKes a few seconds, but its not very slow.</p>
Visual Studio Web Design <p>I'm using visual studio 2005 and have been building asp.net applications. Mostly just departmental level apps for reporting and data maintenance. They work and they look ok but they don't look great. I don't have any other tools like Dreamweaver or Expression. Can anyone name any books or resources for making better looking web pages in Visual Studio.</p> <p>Thanks,</p> <p>Billy </p>
<p>Honestly, the IDE does a fairly good job at design work. We are transitioning our designers from Dreamweaver to Visual Studio 2008, and they definitely like the tools.</p> <p>Don't take this the wrong way, but some people just can't make a page look good, no matter what tool it is. I am one of those people. I can code all day long, but if I need to put a page together, it is going to look like something right of of the 90's.</p> <p>I'd recommend looking for some HTML templates, and adapting them to your product. There are open source templates out there, and ones that can be bought for relatively little money.</p>
How can I make a Table of Contents frame in XSL? <p>I have an XML file that I am creating an XSL stylesheet for.</p> <p>What I would like is to have two frames and do two passes on the data, the first would create a Table of Contents in the left frame, and the second would have the body of data in the right.</p> <p>I can do the two passes, the problem is putting them in separate frames. The frame HTML element takes in a source; I can't put my source directly in there.</p> <p>I can think of a few ways to get around this, none of which I'm thrilled with, so I wanted to see if anyone had found a way to do this.</p>
<p>If you want to use frames you need three separate files.</p> <ol> <li>The frame file. This is just a strict HTML file</li> <li>A file for your table of contents</li> <li>A file for your content</li> </ol> <p>The first one is as specified just an HTML file. The second two are XSL files that will eventually turn into HTML. A good tutorial on frames is <a href="http://www.w3schools.com/HTML/html_frames.asp" rel="nofollow">here at W3Schools</a>.</p> <p><strong>EDIT</strong>: The more I think about this, the more I dislike the solution. It requires the XSL parser to be run twice for each time the initial page is served</p> <p>Have you thought about using CSS or tables to do your layout? There are some really good <a href="http://www.oswd.org/" rel="nofollow">open source CSS templates</a> flying about here on the interwebs.</p>
How To Update Data With Linq By Attach Method <p>I have a update method in my data layer such this:</p> <pre><code>public clacc datalayerSec_User private objUIData as new UIData Public Function Update(ByVal objUser As SEC_USER) As Boolean Try objUIData.SEC_USERs.Attach(objUser) objUIData.Refresh(RefreshMode.KeepCurrentValues, objUser) objUIData.SubmitChanges(ConflictMode.ContinueOnConflict) Return True Catch ex As Exception Throw ex End Try End Function end class </code></pre> <p>And I write this code to update my data:</p> <pre><code>Dim tmpUser As New UI_Class.BAL.Security.cls_SEC_USER Dim tblUser = tmpUser.GetAll.SingleOrDefault(Function(x) x.DS_OPENID = pOpenID) tblUser.DT_LAST_LOGIN = DateTime.Now tmpUser.Update(tblUser) </code></pre> <p>When I run it, I have this error message: Cannot attach an entity that already exists.</p> <p>How can it be fixed?</p>
<p>The easiest way to get around this issue is to use the same DataContext when retrieving the user object and updating.</p> <p>In general, a DataContext should be kept alive for a "unit of work", in other words, you use it to retrieve whatever object you want to change, then change its properties, and then just do SubmitChanges() on the DataContext. No need to reattach the entity to the DataContext, since it already has a reference to it.</p> <p>My VB skills are none existing, but something like this should work (note: very crude pseudo code coming up, things like properly disposing of the DataContext is recommended):</p> <pre><code>class cls_SEC_USER { private _UIData = new UIData(); public User SingleOrDefault(int x) { return _UIData.Users.SingleOrDefault(y =&gt; y.UserId == x); } public void Update(User u) { _UIData.SubmitChanges(); } } // .......... cls_SEC_USER tmpUser = new cls_SEC_USER(); User u = tmpUser.SingleOrDefault(4); if(u != null) { u.DT_LAST_LOGIN = DateTime.Now; tmpUser.Update(u); } </code></pre> <p><a href="http://borrell.parivedasolutions.com/2008/02/linq-to-sql-updating-in-aspnet-right.html" rel="nofollow">Brian Orrell has a pretty good run-down</a> of the issues that you are experiencing, if you want to dig in deeper. </p>
Good way to stretch object over multiple classes <p>I have a collection of orders. I would like to hit the database once, retrieve the orders, store them and then be able to access this collection over multiple forms. I know in asp.net, you can use things like Application Object or Session Object but how do you do it in a win form app? I was thinking of creating a static collection that could be accessed through multiple forms, classes, or wherever. Does this sound right and is it even feasible?</p> <p>thanks</p>
<p>The fundamental difference in WebForms &amp; WinForms is that WinForms are stateful. In other words, you can ensure the objects you load once are available till the program is shutdown. The same is not true for WebForms as HTTP is stateless and ASP.Net weaves lots of "magic" [ViewState, Server session, Cookies, Hidden fields etc.] to glue together pages of a web application.</p> <p>With this basic concept of the way, it's easy to make an object globally available in WinForms. Use a Singleton / Static class and assign its members. You could always say .Instance.. [in case of static classes / classes with static properties] to retrieve values from any Form.</p> <p>One Gottcha is "thread-safety"... aka.. multiple Forms reading / writing to the static property at the same time. If you can take care of this, rest is a breeze.</p> <p>For your above problem:</p> <p>You could have your own Singleton Cache class that will cache records. The Cache class will be a custom collection implementation. You need to make sure that it's thread-safe [or make sure your application only Loads once and reads from then on]... You may need to consider a full-fledged ORM if you want changes to the database reflected in your entity objects.</p> <p><code> CacheList.OrderCache[orderNo].Customer.Address.City = "Las Vegas";</p> <p>class static CacheList { public static Cache OrderCache {get; internal set;}</p> <p>}</p> <p>public class Cache : CollectionBase where T : Entity { .....</p> <p>} </code></p>
StringBuilder for string concatenation throws OutOfMemoryException <p>We mostly tend to following the above best practice.</p> <p>Have a look at <a href="http://stackoverflow.com/questions/73883/string-vs-stringbuilder">String vs StringBuilder</a></p> <p>But StringBuilder could throw <strong>OutOfMemoryException even when there is sufficient memory available</strong>. It throws OOM exception because it needs "continuous block of memory".</p> <p>Some links for reference <a href="http://bytes.com/groups/net-c/501231-stringbuilder-outofmemory">StringBuilder OutOfMemoryException</a></p> <p>and there are many more.....</p> <p>How many of you faced this problem or aware and what did you do to resolve it?</p> <p>Is there anything I am missing?</p> <p><strong>P.S: I wasn't aware of this.</strong></p> <p>I have rephrased the question.</p> <p>*** The same thing worked with manual concatenation(I'll verify this and update SO). The other thing that caused me concern was that there is enough memory in the system. That's the reason I raised this question here to check whether any one faced this problem or there was something drastically wrong with the code. </p>
<p>The underyling string you create will also need a contiguous block of memory because it is represented as an array of chars (arrays require contiguous memory) . If the StringBuilder throws an OOM exception you woludn't be able to build the underlying without it.</p> <p>If creating a string causes an OOM, there is likely a more serious issue in your application.</p> <p>Edit in response to clarification:</p> <p>There is a small subset of cases where building a string with a StringBuilder will fail when manual concatenation succeeds. Manual concatenation will use the exact length required in order to combine two strings while a StringBuilder has a different algorithmn for allocating memory. It's more aggressive and will likely allocate more memory than is actually needed for the string. </p> <p>Using a StringBuilder will also result in a temporary doubling of the memory required since the string will be present in a System.String form and StringBuilder simultaneously for a short time. </p> <p>But if one way is causing an OOM and the other is not, it still likely points to a more serious issue in your program. </p>