input
stringlengths
51
42.3k
output
stringlengths
18
55k
prototype and jQuery peaceful co-existence? <p>I know very little about JavaScript but despite this I'm trying to cobble something together on my wordpress blog. It's not working, and I don't know how to resolve it, and hey, that's what StackOverflow is for, right?</p> <p>Firstly, the error message is:</p> <pre><code>Error: element.dispatchEvent is not a function Source File: http://.../wp-includes/js/prototype.js?ver=1.6 Line: 3936 </code></pre> <p>It happens on page load. My page load handler is registered thusly:</p> <pre><code>Event.observe(window, 'load', show_dates_as_local_time); </code></pre> <p>The error goes away if I disable some other plugins, and this (plus googling) led me to conclude that it was a conflict between prototype and jQuery (which is used by some of the other plugins).</p> <p>Secondly I'm following the wordpress recommended practice of using <a href="http://codex.wordpress.org/Function_Reference/wp_enqueue_script" rel="nofollow"><code>wp_enqeue_script</code></a> to add a dependency from my JavaScript to the Prototype library, as follows:</p> <pre><code>add_action( 'wp_print_scripts', 'depo_theme_add_javascript' ); function depo_theme_add_javascript() { wp_enqueue_script('friendly_dates', 'javascript/friendly_dates.js', array('prototype')); } </code></pre> <p>Now I'm also aware that there are some potential conflicts between jQuery and Prototype which are resolved using the jQuery <code>noConflicts</code> method. I've tried calling that from various places but no good. I don't <em>think</em> this is the problem because a) the <code>noConflict</code> function relates solely to the <code>$</code> variable, which doesn't seem to be the problem here, and b) I would <em>expect</em> wordpress to sort it out for me because it can...</p> <p>Lastly, using the Venkman debugger I've determined that the <code>element</code> referenced in the error message is indeed an <code>HTMLDocument</code> but also does lack a <code>dispatchEvent</code>. Not sure how this could happen, given it's a standard DOM method?</p>
<p>There is a nasty trick many libraries do that I've taken a distinct liking to, and it looks like prototype is one of these. </p> <p>Mootools does this, If I am right, and it involves overloading many of the prototypes on the basic classes, monkey patching them. </p> <p>And likewise, I similarly encountered strange behaviour when mootools and jQuery were present, usually jQuery dying because it was calling some object method which had been somehow overloaded/monkey patched by Mootools. </p> <p>Also, mysteriously, taking mootools out of the script usage list, resulted in <em>everything</em> running much faster, which I concluded was due to less object pollution. </p> <p>Now I could be wrong, but I concluded from my experience such libraries just simply don't like to co-exist with each other, and seeing how mootools code seemed to me to degrade speed at which normal things were done, I sucked up and ported all mootools based code to jQuery ( A time consuming deal I assure you ), and the result, was code that was <em>fast</em> <em>and</em> didn't have weird errors that were unexplainable. </p> <p>I recommend you consider migration as at least <strong>One</strong> of your options. </p> <p><strong>One More thing, when writing:</strong> </p> <p>I tend to use this syntax with all my jQuery driven code, for a bit of safe encapsulation in the event somebody breaks '$' somehow. </p> <p><strong>Runtime Code</strong> This waits for document.ready before executing: </p> <pre><code> jQuery(function($){ code_with_$_here; }); </code></pre> <p><strong>jQuery Plugins</strong></p> <pre><code>(function($){ code_with_$_here; })(jQuery); </code></pre> <p>Using these will make it easier for people <em>using</em> any jQuery you happen to write to be able to use it without much of a conflict issue. </p> <p>This will basically leave them to make sure their code isn't doing anything really magical. </p>
Regex Named Groups in Java <p>It is my understanding that the <code>java.regex</code> package does not have support for named groups (<a href="http://www.regular-expressions.info/named.html">http://www.regular-expressions.info/named.html</a>) so can anyone point me towards a third-party library that does?</p> <p>I've looked at <a href="http://jregex.sourceforge.net/">jregex</a> but its last release was in 2002 and it didn't work for me (admittedly I only tried briefly) under java5.</p>
<p>(<strong>Update</strong>: <strong>August 2011</strong>)</p> <p>As <a href="http://stackoverflow.com/users/50260/geofflane">geofflane</a> mentions in <a href="http://stackoverflow.com/questions/415580/regex-named-groups-in-java/7033467#7033467">his answer</a> (upvoted), <a href="http://download.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29">Java 7 now support named groups</a>.<br> <a href="http://stackoverflow.com/users/471272/tchrist">tchrist</a> points out in the comment that the support is limited.<br> He <strong>details the limitations in his great answer "<a href="http://stackoverflow.com/questions/5767627/java-regex-helper/5771326#5771326">Java Regex Helper</a>"</strong> </p> <p>Java 7 regex named group support was presented back in <a href="http://blogs.oracle.com/xuemingshen/entry/named_capturing_group_in_jdk7"><strong>September 2010</strong> in Oracle's blog</a>.</p> <p>In the official release of Java 7, the constructs to support the named capturing group are:</p> <blockquote> <ul> <li><code>(?&lt;name&gt;X)</code> to define a named group name"</li> <li><code>\k&lt;name&gt;</code> to backreference a named group "name"</li> <li><code>${name}</code> to reference to captured group in Matcher's replacement string</li> <li><a href="http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#group%28java.lang.String%29"><code>Matcher.group(String name)</code></a> to return the captured input subsequence by the given "named group".</li> </ul> </blockquote> <hr> <p><strong>Other alternatives for pre-Java 7</strong> were:</p> <ul> <li><a href="http://code.google.com/p/named-regexp/">Google named-regex</a> (see <a href="http://stackoverflow.com/users/134642/john-hardy">John Hardy</a>'s <a href="http://stackoverflow.com/questions/415580/regex-named-groups-in-java/1095737#1095737">answer</a>, upvoted)<br> <a href="http://stackoverflow.com/users/337621/gabor-liptak">Gábor Lipták</a> mentions (November 2012) that this project might not be active (with <a href="http://code.google.com/p/named-regexp/issues/list">several outstanding bugs</a>), and its <a href="https://github.com/tony19/named-regexp">GitHub fork</a> could be considered instead.</li> <li><a href="http://jregex.sourceforge.net/">jregex</a> (See <a href="http://stackoverflow.com/users/22982/brian-clozel">Brian Clozel</a>'s <a href="http://stackoverflow.com/questions/415580/regex-named-groups-in-java/3782345#3782345">answer</a>, upvoted)</li> </ul> <hr> <p>(<strong>Original answer</strong>: <strong>Jan 2009</strong>, with the next two links now broken)</p> <p>You can not refer to named group, unless you code your own version of Regex...</p> <p>That is precisely what <a href="http://x86.sun.com/thread.jspa?threadID=785370&amp;messageID=4463652">Gorbush2 did in this thread</a>.</p> <p><a href="http://gorbush.narod.ru/files/regex2.zip"><strong>Regex2</strong></a></p> <p>(limited implementation, as pointed out again by <a href="http://stackoverflow.com/users/471272/tchrist">tchrist</a>, as it looks only for ASCII identifiers. tchrist details the limitation as:</p> <blockquote> <p>only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.</p> </blockquote> <p>Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in <a href="http://www.perl.com/pub/2003/06/06/regexps.html">Regexp Power</a>, <a href="http://www.pcre.org/pcre.txt">PCRE specs</a> and <a href="http://perl.plover.com/yak/regex/samples/slide083.html">Matching Strings with Balanced Parentheses</a> slide)</p> <p>Example:</p> <p>String:</p> <pre><code>"TEST 123" </code></pre> <p>RegExp:</p> <pre><code>"(?&lt;login&gt;\\w+) (?&lt;id&gt;\\d+)" </code></pre> <p>Access</p> <pre><code>matcher.group(1) ==&gt; TEST matcher.group("login") ==&gt; TEST matcher.name(1) ==&gt; login </code></pre> <p>Replace</p> <pre><code>matcher.replaceAll("aaaaa_$1_sssss_$2____") ==&gt; aaaaa_TEST_sssss_123____ matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==&gt; aaaaa_TEST_sssss_123____ </code></pre> <hr> <p>(extract from the implementation)</p> <pre><code>public final class Pattern implements java.io.Serializable { [...] /** * Parses a group and returns the head node of a set of nodes that process * the group. Sometimes a double return system is used where the tail is * returned in root. */ private Node group0() { boolean capturingGroup = false; Node head = null; Node tail = null; int save = flags; root = null; int ch = next(); if (ch == '?') { ch = skip(); switch (ch) { case '&lt;': // (?&lt;xxx) look behind or group name ch = read(); int start = cursor; [...] // test forGroupName int startChar = ch; while(ASCII.isWord(ch) &amp;&amp; ch != '&gt;') ch=read(); if(ch == '&gt;'){ // valid group name int len = cursor-start; int[] newtemp = new int[2*(len) + 2]; //System.arraycopy(temp, start, newtemp, 0, len); StringBuilder name = new StringBuilder(); for(int i = start; i&lt; cursor; i++){ name.append((char)temp[i-1]); } // create Named group head = createGroup(false); ((GroupTail)root).name = name.toString(); capturingGroup = true; tail = root; head.next = expr(tail); break; } </code></pre>
Redirect console output to textbox in separate program <p>I'm developing an Windows Forms application that requires me to call a separate program to perform a task. The program is a console application and I need to redirect standard output from the console to a TextBox in my program. </p> <p>I have no problem executing the program from my application, but I don't know how to redirect the output to my application. I need to capture output while the program is running using events. </p> <p>The console program isn't meant to stop running until my application stops and the text changes constantly at random intervals. What I'm attempting to do is simply hook output from the console to trigger an event handler which can then be used to update the TextBox.</p> <p>I am using C# to code the program and using the .NET framework for development. The original application is not a .NET program.</p> <p>EDIT: Here's example code of what I'm trying to do. In my final app, I'll replace Console.WriteLine with code to update the TextBox. I tried to set a breakpoint in my event handler, and it isn't even reached.</p> <pre><code> void Method() { var p = new Process(); var path = @"C:\ConsoleApp.exe"; p.StartInfo.FileName = path; p.StartInfo.UseShellExecute = false; p.OutputDataReceived += p_OutputDataReceived; p.Start(); } static void p_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("&gt;&gt;&gt; {0}", e.Data); } </code></pre>
<p>This works for me:</p> <pre><code>void RunWithRedirect(string cmdPath) { var proc = new Process(); proc.StartInfo.FileName = cmdPath; // set up output redirection proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.EnableRaisingEvents = true; proc.StartInfo.CreateNoWindow = true; // see below for output handler proc.ErrorDataReceived += proc_DataReceived; proc.OutputDataReceived += proc_DataReceived; proc.Start(); proc.BeginErrorReadLine(); proc.BeginOutputReadLine(); proc.WaitForExit(); } void proc_DataReceived(object sender, DataReceivedEventArgs e) { // output will be in string e.Data } </code></pre>
FxCop rule that checks for NotImplementedExceptions <p>I'd like to have the nightly build check for how many NotImplementedExeptions there are in my .NET code so hopefully we can remove them all before releasing. My first thought is that FxCop might be a good tool to do this. Does anyone have a custom FxCop rule for this? How would I go about creating one myself?</p>
<p>Unit test like this will fail if more than 10 methods create NotImplementedException. On failing it will report all methods that create this exception.</p> <pre><code>var throwingMethods = codebase.Methods .Where(m =&gt; m .GetInstructions() .Exists(i =&gt; i.Creates&lt;NotImplementedException&gt;())) .ToArray(); if (throwingMethods.Length &gt; 10) CollectionAssert.IsEmpty(throwingMethods); </code></pre> <p>Where codebase is created like this:</p> <pre><code>var codebase = new Codebase("Assembly1.dll","Assembly2.dll"); </code></pre> <p>Snippet uses Lokad.Quality.dll from the <a href="https://github.com/Lokad/lokad-shared-libraries" rel="nofollow">Lokad Shared Libraries</a>.</p>
DataContext naming Best Practices <p>Are there any? Do you give the DataContext the name of the Database you are getting data from or..</p>
<p>Don't know if there are any established "best practices". I just name it with something that makes sense to me and lets me know immediately what it is. For me, that's to name it after the database. </p> <p>So with Northwind database I have NorthwindDataContext.</p>
Stubbing functions in simulations <p>I'm working on an embedded C project that depends on some external HW. I wish to stub out the code accessing these parts, so I can simulate the system without using any HW. Until now I have used some macros but this forces me to change a little on my production code, which I would like to avoid.</p> <h2>Example:</h2> <pre><code>stub.h #ifdef _STUB_HW #define STUB_HW(name) Stub_##name #else /*_STUB_HW*/ #define STUB_HW(name) name #endif /*_STUB_HW*/ my_hw.c WORD STUB_HW(clear_RX_TX)() { /* clear my rx/tx buffer on target HW */ } test_my_hw.c #ifdef _STUB_HW WORD clear_RX_TX() { /* simulate clear rx/tx buffer on target HW */ } </code></pre> <p>With this code I can turn on/off the stubbing with the preprocessor tag <code>_STUB_HW</code> <br><br> Is there a way to acomplish this without having to change my prod code, and avoiding a lot of ifdefs. And I won't mix prod and test code in the same file if I can avoid it. I don't care how the test code looks as long as I can keep as much as possible out of the production code.</p> <h2>Edit:</h2> <p>Would be nice if it was posible to select/rename functions without replacing the whole file. Like take all functions starting on <code>nRF_##</code> and giving then a new name and then inserting <code>test_nRF_##</code> to <code>nRF_##</code> if it is posible </p>
<p>I just make two files ActualDriver.c and StubDriver.c containing exactly the same function names. By making two builds linking the production code against the different objects there is no naming conflicts. This way the production code contains no testing or conditional code.</p>
Emacs and slime stopped cooperating for me <p>I'm trying to use slime from CVS (2009-01-05) but keep getting this error:</p> <pre> LOAD: A file with name /usr/share/common-lisp/source/slime/swank-loader.lisp does not exist </pre> <p>I've stripped my .emacs down to just:</p> <pre><code>(setq inferior-lisp-program "/usr/bin/clisp") (add-to-list 'load-path "/home/ssm/lisp/slime/") (require 'slime) (slime-setup) </code></pre> <p>I've deleted my ~/.slime directory, started with 'emacs -q' and eval'd the above code but I keep getting the LOAD error when I run slime (via M-x slime). Any ideas on how to fix this error?</p> <p>FWIW, I've tried to install slime via apt-get but I keep getting errors there too about cl-swank being broken. That's a whole different story.</p>
<p>Have you purged the slime pkg you installed via apt-get? It looks like emacs is still reading the old site-specific configuration setup by apt-get. Try starting emacs with the -Q option, which prevents loading of site-specific (as well as user specific) customization, and see if the problem still occur.</p>
SQL code import into Access 2007 <p>I basically need to know how to import SQL code into Access. I've tried one way but that requires me to do one table and one value at a time which takes a lot of time.</p> <p>Can anyone help?</p>
<p>If you are trying to import data, rather than SQL code (see Duffymo's response), there are two ways.</p> <p>One is to go where the data is and dump a .CSV file and import that, as Duffymo responded.</p> <p>The other is to create a table link from the Access database to a table in the source database. If the two databases will talk to each other this way, you can use the data in the remote table as if it were in the Access database.</p>
Modularising a C# Compact Framework 2.0 Application <p>We're currently developing a new piece of hand-held software. I cant discuss the nature of the application, so I'll use an example instead.</p> <p>We're designing hand-held software for managing a school. We want to modularise each aspect of the system so that different schools can use different features. </p> <p>Our system will start with a main menu and a login screen. I'd like this to be the base of the system and be where the modules will be added to. I.e. I'll have a project called SchoolPda.</p> <p>I then want to have different modules. I.e., I want a registration module that will handle student registrations. I want a classroom module for managing classroom cleanliness, etc.</p> <p>The way I'd possibly see this working is including/not including different dlls and having the base system's main menu expose buttons to access those modules if the dlls exist. That's just the kind of thing we're after.</p> <p>Does anyone have any experience doing something like this? What would be the best way of doing it? We don't need to worry about the database as the database will always be the full database, but aspects wont get populated if the associated modules do not exist.</p>
<p>I have been in projects that have done it two ways: </p> <ul> <li><p>In one project we did not deploy certain DLLs if the customers weren't licensed. That's what you are suggesting. It worked fine. Of course, there was no way to enable those modules without an additional install, but it made perfect sense for that app.</p></li> <li><p>In another project we deployed everything and only exposed to the end-users the menus, buttons, etc. for which the customer was licensed. We did that because then the user could easily add-on an extra module by adding a license for it. When the license was added, the stuff magically showed up on next login.</p></li> </ul> <p>So in my experience, I would say look at your licensing model as one big piece of your decision. Think about whether you would ever want to add those extra modules on the fly.</p>
AVM2 and ABC (Adobe's ActionScript bytecode format) spec licensing.. can I use it? <p>Google is failing me on this one.</p> <p>Let's say I have some ECMA script that I've compiled to an ABC bytecode file using the compiler in the Open Source Flex SDK.</p> <p>Is it within the terms of use (That I can't seem to find) for me to use the AVM2 specification from adobe to create a new interpreter for this file?</p> <p>The best I can manage is a sentence in wikipedia that says that the flash specification is available "without restriction". I'm not making a flash player though, and AFAIK the AVM2 spec is separate from the SWF spec.</p> <p>Does anyone know off-hand if my intentions are legal?</p>
<p>Adobe open sourced the ActionScript virtual machine as a Mozilla project named <a href="http://www.mozilla.org/projects/tamarin/" rel="nofollow">Tamarin</a> under an MPL/GPL/LGPL tri-license. If I remember correctly, this source code also includes documentation for ABC bytecode. With that in mind, it seems to me that you're free to build your own interpreter.</p>
Adding a License to your .Net Web Application <p>I am currently looking at adding some licensy type software which will protect my .net web application source code. Was wondering if you guys had any experience with this and knew perhaps any companies or sources which provide such utilities ?</p> <p>So my main aim is to protect the actual files</p> <p>i.e Default.aspx Default.aspx.cs .... being copied in the future without me being able to stop them from using it.</p> <p>Thanks</p> <p>EDIT : From reading the replies i seem to think obfuscator seems to be the way to go. Does a obfuscator program only work on exe or dll's or does it also work on individual pages ?</p>
<p>One step you can do is to release it as a Web Application rather than a Web Site.</p> <p><a href="http://weblogs.asp.net/anasghanem/archive/2008/07/13/differences-when-registering-httpmodules-and-httphandlers-for-web-application-projects-and-website-project.aspx" rel="nofollow">Differences here from asp.net</a></p> <p>As far as the Default.aspx, I don't know of a way to encrypt html pages that are served over standard web servers, and either way, the clients will all still be able to View Source, unless you write the entire page in JavaScript writes (horrible to manage).</p> <p>Your best bet is to not include any application logic code what-so-ever in the aspx and compile your binaries using an obfusicator.</p>
TFS shows some pending changes under my name, but I have not changed anything <p>TFS shows some pending changes under my name, but I have not changed anything. When I check in and see View Pending changes, I see some of the changes which I have never made, changes pending under some other user might be shown as my pending changes. When I unselect and check-in my changes, these are still locked under my name? Is this due to auto-checkout or any other reason? (TFS policy requires a compile before check-in)</p>
<p>This is probably due to the automatic checkout feature in TFS.</p> <p>TFS uses an atomic check-in process and is very careful about recording who did what. When you start editing a file (or the IDE edits one on your behalf, for example a .csproj or .vbproj file) then the file will show up in your pending changes list to show you that you have the file checked out with an edit pending.</p> <p>To see your pending changes list, go to View, Other Windows, Pending Changes in Visual Studio.</p> <p>To check-in any pending changes you can right click on the file in solution explorer or you can select it in the pending changes view. Only then will the change be committed into version control. From the pending changes view you can compare with the server version to see what changes you have made.</p> <p>To see the changes that have been committed to the server you can right click on a file or folder and select "View History".</p> <p>If you want to remove the pending change and restore the file to what it was before you edited it you can right click on the file and select "Undo Pending Changes".</p> <p>If you want to change the auto check-out behaviour to prompt you before it performs a check-out, then go to Tools, Options, Source Control, Environment and change the Checked-in items for Saving and Editing to "Prompt for check out" rather than the default which is "Check out automatically".</p> <p>Hope that helps,</p> <p>Martin. </p>
What is the best way to track memory management while testing my iPhone App? <p>While developing my app I have come to realize that the majority of my app crashes have arisen from poor memory management.</p> <p>I understand I can print or log retain counts through NSLog (@"retain count is:%d",[myInstance retainCount]);</p> <p>But isn't there a better, less manual method? Possibly a visual representation of your objects and instances?</p> <p><strong>answered. Cheers, Adam &amp; Jason. :-)</strong></p>
<p>Use the Leaks and Object Allocation tools through XCode.</p> <pre><code>Run &gt; Start with Performance Tool &gt; ... </code></pre>
Get image properties with Jython <p>I am using Jython to move images around and organise them. I would like to extract some information from the images like dimensions and file size.</p> <p>How would I go about doing this with Jython?</p> <p>Cheers</p>
<p><a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Image Library</a>.</p>
JavaScript detection of keypress context (form history selection vs. form submit) <p>I'm writing a semi-generic form plugin using jQuery in order to speed up the development of the project I'm working on.</p> <p>The plan is that a <a href="http://jtemplates.tpython.com/" rel="nofollow">jTemplates</a> template contains the fields, my plugin looks through the template to find any required multi-lingual resources, requests them from the server, and then packages everything up into a JavaScript object that is then passed to a custom function on "submit".</p> <p>Everything is working nicely, except the standard "when enter is pressed, submit the form" code that you need to do when you're faking a form:</p> <pre><code>opts.coreElement.find('input[type=text]').keypress(function(evt) { if ((evt.keyCode || evt.which) == 13) { opts.coreElement.find('.saveButton').click(); } }); </code></pre> <p>The issue is that in Firefox (at least; I haven't checked other browsers yet), if you've entered information in a similarly-named textbox before, you get your form history. If you then select one of those suggested values by hitting enter, it submits the form. Not great if you're on the first input on the page. Really rather annoying, actually.</p> <p>The obvious solution seems to be to insert a form element around the fields and stopping any possible submission of this dummy form via jQuery. Fortunately I have the luxury of doing this as I'm in ASP.NET MVC, but what if I wasn't? What if my plugin didn't know whether it was already inside a form and so had to keep itself to itself? What if I was in standard WebForms ASP.NET and I <em>had</em> to manually "target" each input's return key to the correct submit button?</p> <p>Is there a way, perhaps through the event object itself, to detect the context of the keypress, so I can filter out the selection of form history items?</p>
<p>I have found that in order to prevent the default action for an [enter] or [tab] key event you have to listen for the keydown event and handle/cancel it.<br> By the time keyup or keypress is triggered the default for keydown has already happened.</p>
How do I deny access to .dll files in a web site (on both IIS 6 and 7) <p>If I use an URL like <a href="http://mysite/myfolder/myfile.dll" rel="nofollow">http://mysite/myfolder/myfile.dll</a>, I get a dialog "Do you want to open or save this file". Of course, I don't want people to be able to download and disassembly our dll's. How can I deny people accessing such files directly ?</p>
<p>Usually this is disallowed by default. If you go into the IIS manager and edit the website, you need to uncheck 'script source access.' DLL should also be on the list of forbidden file extensions.</p>
Using API/Function calls or going for the Cron Job approach - An inquiry into dealing with transactions - How would you handle it? <p>I wanted to run something by you guys. I am starting a new project which is roughly the following:</p> <p>Important information: I am using PHP and MySQL</p> <p>Every minute I get a list of to-do transactions from an API from different users. </p> <p>Example: </p> <pre><code>user1 send $1 to user2 userx send $2 to usera userw send $0.50 to user2 etc.. </code></pre> <p>Lets say user1 wants to send $1 to user2. There are two posibilities, it's succesful or it's unsuccessful because there are insufficient funds or the user spelled the username wrong. If it's unsuccesfull I send out a message to the user.</p> <p>I am now facing several options - please bare with me through my thought process.</p> <p><strong>Option 1</strong></p> <p>Create a database table with transactions that need to be processed and use a cronjob that processes them every minute. The risk here is that the script could run against an error or a timeout and the other transactions would still show In Progress in the database table. So I would need a second script to check that against a timestamp.</p> <p><strong>Option 2</strong></p> <p>Create an API or Function which gets called for each transaction after I receive them and brings me a response. From which then I can call another API or Function to deal with that response or move on to the next transaction. However I would still have to put them in a database table since I can't risk losing them if the script stops executing. So it would work as follow: put all transactions in database table - start transaction - when finished transaction delete from table - start transaction 2.</p> <p><hr /></p> <p><em>Both options are flawed because you don't know how long the list of transactions will be. If it's long PHP is definitely not optimal to run for a long time - using set timeout to zero is risky. I am looking to create a solution that will scale with PHP. So I was thinking about an Option 3.</em></p> <p><hr /></p> <p><strong>Option 3 (Optimal solution?)</strong></p> <p>Use an API to return 10 transactions. </p> <p>In database set a flag to say they are sent to a script and timestamp to say when they were sent</p> <p>PHP script retreives 10 transactions from API - handles 10 transactions.</p> <p>Once transaction completed - delete it from this table and copy it to completed transaction table.</p> <p>Have a cronjob script check every 3 minutes if timesent is greater then X minutes (based on an upper bound of the execution time of 10 transactions). If it is greater - set them to not sent - so they can be sent out again.</p> <p><hr /></p> <p>As you can see I wrote down my whole thought process on this and am looking for input. There's bound to be stuff that I missed. Also please realize that these are not real financial transactions - it's just the best metafore I could use to make it clear.</p> <p>Thank you very much,</p> <p>Ice</p>
<p>If you want to do it using the bare minimum variance from your current technology stack you're on the right track. Essentially you're re-creating a bare bones MQ or job server.</p> <p>Minimum features you need for job/task/transaction queue are:</p> <ul> <li>the job (user1 send $2 to user2)</li> <li>the state (ready, out for processing, error, done)</li> </ul> <p>You're also probably going to want</p> <ul> <li>a last error string (so you can figure out what the hell happened)</li> <li>possibly a retry count (for tasks that should be retried before failing, anything that might fail due to transient errors)</li> </ul> <p>If you decide to parallelize your processing cron job, you'll want to track which instance of the script has a job out for processing, especially if you start operating on large batches. (and if you do that, you're going to want to watch to make sure any given transaction finishes fast, or you can effectively stall all the jobs behind a single slow job)</p> <p>Whether you fetch it from an API or straight from the database is 6 of one, half a dozen of the other.</p>
Fetch mail attachment into SQL Server 2005 using IMAP <p>I need to import data into my SQL Server 2005 from an e-mail datasource on an Exchange mail server. It means that when a mail is sent to a particular mail address I must retrieve the mail subject and the attached file and then I must import these data into my SQL Server 2005, using IMAP.</p> <p>Can I do this with SSIS, or do I have to write a Windows Service in C# ?</p> <p>Do I need to use an IMAP API library of some kind ?</p>
<p>In case anybody is interested: I solved the problem myself using an open source IMAP library which I included in a Windows Service. I did not use SSIS anyway because SSIS in SQL Server 2005 does not support the IMAP interface.</p> <p>The open source IMAP library is called "Koolwired.IMAP".</p> <p>Here are some links that I found useful:</p> <p><a href="http://koolwired.com/solutions/solutions.aspx?id=30" rel="nofollow">http://koolwired.com/solutions/solutions.aspx?id=30</a></p> <p><a href="http://sourceforge.net/projects/imapnet/" rel="nofollow">http://sourceforge.net/projects/imapnet/</a></p> <p><a href="http://www.codeplex.com/imapnet/Thread/List.aspx" rel="nofollow">http://www.codeplex.com/imapnet/Thread/List.aspx</a></p> <p><a href="http://www.imap.org/" rel="nofollow">http://www.imap.org/</a></p>
String Comparison : individual comparison Vs appended string comparison <p>I have six string variables say str11, str12, str13, str21, str21 and str23.</p> <p>I need to compare combination of these variables.</p> <p>The combinations I have to check is str11 -- str12 -- str13 as one group and str21 -- str22 -- str23 as other group. I have to compare these two groups.</p> <p>Now I'm in confusion which method should I use for comparison?</p> <p>Can I append strings of same group and compare, which is only one comparison say <code>( str11 append str12 append str13 ) eqauls ( str21 append str22 append str23 )</code></p> <p>Or</p> <p>Should I go for individual 3 comparisons?</p> <pre><code>if( str11 equals str21 ) { if( str12 equals str22 ) { if( str13 equals str23 ) { } } } </code></pre> <p>What is performance factor which costs me because of string length when I do string comparison? Lets us assume all strings are of same( approx ) length.</p>
<p>I’d test individually.</p> <p>Is “AB” “CD” “EF” equal to “ABC” “DE” “F”?</p> <p>Me thinks not.</p> <p>P.S. If it is, then it’s a VERY special case, and if you decide to code it that way (as a concatenated comparison) then comment the hell out of it.</p>
Java map with values limited by key's type parameter <p>Is there a way in Java to have a map where the type parameter of a value is tied to the type parameter of a key? What I want to write is something like the following:</p> <pre><code>public class Foo { // This declaration won't compile - what should it be? private static Map&lt;Class&lt;T&gt;, T&gt; defaultValues; // These two methods are just fine public static &lt;T&gt; void setDefaultValue(Class&lt;T&gt; clazz, T value) { defaultValues.put(clazz, value); } public static &lt;T&gt; T getDefaultValue(Class&lt;T&gt; clazz) { return defaultValues.get(clazz); } } </code></pre> <p>That is, I can store any default value against a Class object, provided the value's type matches that of the Class object. I don't see why this shouldn't be allowed since I can ensure when setting/getting values that the types are correct.</p> <p>EDIT: Thanks to cletus for his answer. I don't actually need the type parameters on the map itself since I can ensure consistency in the methods which get/set values, even if it means using some slightly ugly casts.</p>
<p>You're not trying to implement Joshua Bloch's typesafe hetereogeneous container pattern are you? Basically:</p> <pre><code>public class Favorites { private Map&lt;Class&lt;?&gt;, Object&gt; favorites = new HashMap&lt;Class&lt;?&gt;, Object&gt;(); public &lt;T&gt; void setFavorite(Class&lt;T&gt; klass, T thing) { favorites.put(klass, thing); } public &lt;T&gt; T getFavorite(Class&lt;T&gt; klass) { return klass.cast(favorites.get(klass)); } public static void main(String[] args) { Favorites f = new Favorites(); f.setFavorite(String.class, "Java"); f.setFavorite(Integer.class, 0xcafebabe); String s = f.getFavorite(String.class); int i = f.getFavorite(Integer.class); } } </code></pre> <p>From <a href="http://rads.stackoverflow.com/amzn/click/0321356683">Effective Java (2nd edition)</a> and <a href="http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf">this presentation</a>.</p>
On Windows XP, how do I enumerate all the windows displayed by the system (C#) <p>I would like to end up with a list (or array or whatever) of all the visible (including minimised) windows. </p> <p>I have found 2 similar questions, which don't <em>quite</em> give me what I'm looking for:<br /> - <a href="http://stackoverflow.com/questions/210504/enumerate-windows-like-alt-tab-does">Work out which windows go in the alt-tab list</a><br /> - <a href="http://stackoverflow.com/questions/308135/how-can-i-enumerate-the-open-windows-enumwindows-of-another-user-session">list windows in another user's session</a></p> <p>Thanks. </p>
<p>I think that the blog entry by Raymond Chen pointed to in the first link gives you an idea of where you want to go. Basically, you would call EnumWindows and then apply that algorithm, except that you would take note of every window handle that is visible.</p> <p>The question is a little vague, what is the purpose here (there might be a better way given more info).</p>
Problem with SQL Join <p>I have two tables, tblEntities and tblScheduling.</p> <p>tblEntities:</p> <pre><code>EntityID ShortName Active 1 Dirtville 1 2 Goldtown 1 3 Blackston 0 4 Cornfelt 1 5 Vick 1 </code></pre> <p>tblScheduling:</p> <pre><code>ScheduleID EntityID SchedulingYearID 1 1 20 2 1 21 3 2 20 4 3 19 5 5 20 </code></pre> <p>I need a query that will show <strong>ALL ACTIVE</strong> Entities and their schedule information for a particular ScheduleYearID.</p> <p>Output should look like (the desired SchedulingYearID in this case is 20):</p> <pre><code>EntityID ScheduleID 1 1 2 3 4 NULL 5 5 </code></pre> <p>The query that I have written so far is: </p> <pre><code>SELECT tblEntities.EntityID, tblEntities.ShortName, tblScheduling.ScheduleID FROM tblScheduling RIGHT OUTER JOIN tblEntities ON tblScheduling.EntityID = tblEntities.EntityID WHERE (tblScheduling.SchedulingYearID = @SchedulingYearID) AND (tblEntities.Active = 1) ORDER BY tblEntities.EntityID </code></pre> <p>My problem is that using this query it will not include active entities without schedule information (such as EntityID 4 in the example above). I can write the query to display all active entities and their schedule status fine, but once I start limiting it via the SchedulingYearID I lose those particular entities. </p> <p>Are there any solutions that I am obviously missing without having to resort to subqueries, cursors, etc.? If not it's not a big deal, I just feel like I am missing something simple here.</p>
<p>Try this... Join conditions are evaluated to produce the intermediate Join result set, and then, (for an outer join), all the rows from the "Outer" side are added back in before moving on... Where conditions are evaluated after all joins are done... </p> <pre><code>SELECT E.EntityID, E.ShortName, S.ScheduleID FROM tblEntities E Left Join tblScheduling S ON S.EntityID = E.EntityID And S.SchedulingYearID = @SchedulingYearID WHERE E.Active = 1 ORDER BY E.EntityID </code></pre> <p>I change your join order cause I prefer left joins... but it doesn't matter</p>
How to organize the controller of a MVC-based program with multiple screens/panels? <p>I'm currently working on a hobby project, written in Java, containing about two different JFrames with about 3-4 JPanels each. The problem I'm facing is that I'm not so sure how to handle the interaction with my controller and different view classes.</p> <p>For instance, I've an article by Sun on <a href="http://java.sun.com/developer/technicalArticles/javase/mvc/" rel="nofollow">Java App. design with MVC</a>, where they list the option to let all the communications between model and view go through the controller as the most modern one, a tactic I've been taught as well and should do just fine. However, it doesn't quite go as deep as to explain how to handle all the ActionListeners involved for all the elements and different panels. </p> <p>The 'way to go' I've been taught so far is to either use one controller and set the ActionListener to the various objects through getters and keep track of the active panel. The alternative my awesome Java book gives is to just stick to inner classes for each view class. Either method seems to result in pretty nasty code, while I'd prefer one or several controllers with as little bloat as possible.</p> <p>My question of course is; how would you assign the ActionListeners as neatly and efficiently as possible while keeping the controller(s) usable?</p>
<p>Even though Markus' solution remains the neatest I've seen so far, I've made some slight changes, which are hopefully improvements in the eyes of the original author as well ;).</p> <p>In case you add/remove an item of the list in response to an event, there is a chance of ending up with concurrent changes to the list; the event is handled, but the loop will continue in case there are more items after the one catching the event. </p> <p>Therefore it's required to use a slightly different approach. I've decided to use the ListIterator.add() method, as this one supports modifications to the list while walking through its items. Possibly there are more elegant solutions available, but this one does the job pretty decent. </p> <p>In case it will be of help to others; the modified code would similar be the following:</p> <pre><code>ListIterator&lt;ActionListener&gt; iterator = mActionListeners.listIterator(); public void actionPerformed(ActionEvent e) { iterator = mActionListeners.listIterator(); while (iterator.hasNext()) { ActionListener actionListener = (ActionListener)iterator.next(); actionListener.actionPerformed(e); } } public void addListener(ActionListener listener) { iterator.add(listener); } public void removeListener(ActionListener listener) { iterator.remove(listener); } </code></pre> <p>In case there are better solutions or improvements I'll be glad to hear those as well.</p>
Getting a Signature Mismatch Error when Compiling Even though it Matches in VS.NET 2005 <p>I changed a reference in my project from pointing to a specific hard-coded DLL to a project reference and now I'm getting an error telling me that the signature for some event handlers don't match even though they do.</p> <p>Here's one exact message:</p> <p>Method 'Private Sub ObjectsGrid_CellChange(sender As Object, e As Infragistics.Win.UltraWinGrid.CellEventArgs)' cannot handle Event 'Public Event CellChange(sender As Object, e As Infragistics.Win.UltraWinGrid.CellEventArgs)' because they do not have the same signature.</p> <p>What's also odd is if I drop the control in the GUI editor and have VS automatically create the handler, it still produces the same error.</p>
<p>Are the compiled dll, its respective project, and the user project all referencing the same version of the Infragistics assemblies? From what I've seen, any time you have a signature that appears to match, an error like this means you are referencing two different versions of an assembly and attempting to use one in place of the other.</p>
Can Hibernate return a collection of result objects OTHER than a List? <p>Does the Hibernate API support object result sets in the form of a collection other than a List? </p> <p>For example, I have process that runs hundreds of thousands of iterations in order to create some data for a client. This process uses records from a Value table (for example) in order to create this output for each iteration. </p> <p>With a List I would have to iterate through the entire list in order to find a certain value, which is expensive. I'd like to be able to return a TreeMap and specify a key programmatically so I can search the collection for the specific value I need. Can Hibernate do this for me?</p>
<p>If I understand correctly, you load a bunch of data from the database to memory and then use them locally by looking for certain objects in that list.</p> <p>If this is the case, I see 2 options.</p> <ol> <li>Dont load all the data, but for each iteration access the database with a query returning only the specific record that you need. This will make more database queries, so it will probably bu slower, but with much less memory consumption. This solution could easily be improved by adding cache, so that most used values will be gotten fast. It will of course need some performance measurement, but I usually favor a naive solution with good caching, as the cache can implemented as a cross-concern and be very transparent to the programmer.</li> <li>If you really want to load all your data in memory (which is actually a form of caching), the time to transform your data from a list to a TreeMap (or any other efficient structure) will probably be small compared to the full processing. So you could do the data transformation yourself.</li> </ol> <p>As I said, in the general case, I would favor a solution with caching ...</p>
XmlSerializer, sgen.exe and generics <p>I have a generic type:</p> <pre><code>public class Packet&lt;T&gt; where T : IContent { private int id; public int Id { get { return this.id; } } private T content; public T Content { get { return this.content; } } } </code></pre> <p>I want to deserialize/serialize instances of this type from/to XML. <code>IContent</code> is defined like that:</p> <pre><code>public interface IContent { XmlSerializer Serializer{get;} } </code></pre> <p>Basically, I would like the <code>Packet</code> to use the serializer provided by its content to serialize and deserialize its content member. This serializer is in fact an instance of a pre-compiled xml serializer generated by sgen.exe.</p> <p>Is it possible without making <code>Packet&lt;T&gt;</code> implementing <code>IXmlSerializable</code>?</p>
<p>Yes, you can implement a custom class directly with IXmlSerializable. <br/> For more information, see <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="nofollow">this</a> article.</p>
ASP.NET MVC - Mapping more than one query string parameter to a pretty url <p>I am a bit stuck on the design of my seo friendly urls for mvc....Take for example the following url: <a href="http://myapp/venues/resturants.aspx?location=central&amp;orderBy=top-rated" rel="nofollow">http://myapp/venues/resturants.aspx?location=central&amp;orderBy=top-rated</a></p> <p>With my mvc app i have mapped it as follows: <a href="http://myapp/venues/list/resturants/central/top-rated" rel="nofollow">http://myapp/venues/list/resturants/central/top-rated</a><br> {controller}/{action}/{category}/{location}/{order}</p> <p>Now the only problem is that location and order are optional...so it should be possible to submit a request like: <a href="http://myapp/venues/list/resturants/top-rated" rel="nofollow">http://myapp/venues/list/resturants/top-rated</a> . This proves to be a problem when the request hits the controller action, the location parameter has picked up "top-rated", naturally.</p> <p>Any suggestions? I' am considering using explicit querystrings to handle more than one parameter but this is really my last option as i dont want to sacrifice SEO too much.</p> <p>Has anyone eles run into such dilemmas? And how did you handle it?</p> <p>Thanks in advance!</p>
<p>Click on your <a href="http://stackoverflow.com/users/52065/wololo">profile link</a> and look at the URLs for Stats, Recent, Response, etc.</p> <p>Examples:</p> <ul> <li><a href="http://stackoverflow.com/users/52065?sort=recent#sort-top">http://stackoverflow.com/users/52065?sort=recent#sort-top</a></li> <li><a href="http://stackoverflow.com/users/52065?sort=stats#sort-top">http://stackoverflow.com/users/52065?sort=stats#sort-top</a></li> </ul> <p>with no sort it defaults to stats</p> <ul> <li><a href="http://stackoverflow.com/users/52065">http://stackoverflow.com/users/52065</a></li> </ul> <p><strong>Optional paramters should be query parameters</strong></p>
Can I Use a .NET DLL in "Delphi 2007 for Win32"? <p>Is it possible to use a .NET DLL in Delphi 2007 for Win32? I've tried to import the DLL in the same way I've done for an ActiveX component, but it doesn't appear to work (Component Menu -> Import Component -> Import .NET Assembly.</p> <p>Is it possible and if so what are the steps?</p>
<p>If you want a Delphi specific article on doing that:</p> <p><a href="http://dn.codegear.com/article/32754">Using a .NET Assembly via COM by Jim McKeeth</a> </p> <p>It is pretty straight forward once you have all the steps.</p>
Trigger and control inside DetailView <p>I have a DetailsView control with a LinkButton inside the TemplateField. </p> <p>I wrap the DetailsView inside the UpdatePanel and set trigger with the LinkButton inside the DetailsView . However, i got error saying it can't find the LinkButton. I tried to google on setting trigger that is inside DetailsView and GridView but I haven't come across any post regarding how to do it.</p> <p>Does anyone know how you can use the LinkButton inside it or DetailsView as trigger? </p>
<p>i find my answer. Basically set ChildrenAsTriggers to true in updatepanel. Any control inside the update panel will trigger it.</p>
Scaffolding ActiveRecord: two columns of the same data type <p>Another basic Rails question:</p> <p>I have a database table that needs to contain references to exactly two different records of a specific data type.</p> <p>Hypothetical example: I'm making a video game database. I have a table for "Companies." I want to have exactly one developer and exactly one publisher for each "Videogame" entry.</p> <p>I know that if I want to have one company, I can just do something like:</p> <pre><code>script/generate Videogame company:references </code></pre> <p>But I need to have both companies. I'd rather not use a join table, as there can only be exactly two of the given data type, and I need them to be distinct.</p> <p>It seems like the answer should be pretty obvious, but I can't find it anywhere on the Internet.</p>
<p>Just to tidy things up a bit, in your migration you can now also do:</p> <pre><code>create_table :videogames do |t| t.belongs_to :developer t.belongs_to :publisher end </code></pre> <p>And since you're calling the keys developer_id and publisher_id, the model should probably be:</p> <pre><code>belongs_to :developer, :class_name =&gt; "Company" belongs_to :publisher, :class_name =&gt; "Company" </code></pre> <p>It's not a major problem, but I find that as the number of associations with extra arguments get added, the less clear things become, so it's best to stick to the defaults whenever possible.</p>
HTML special code to ASCII <p>Hey, is there any built in functions or something like that in php that will allow me to turn HTML special code like: &lt;(;), >(;), Á(;) and ©(;) etc... into &lt;, >, Á and ©</p> <p>Lets say I have the value: </p> <pre><code>$fileName = "Gibt es eine schö(;)ne Offroadstrecke? (;)"; </code></pre> <p>And I want this:</p> <pre><code>$fileName = "Gibt es eine schöne Offroadstrecke? "; </code></pre> <p>Any easy way to do this with php? The first I though of was to make a function that hard codes replaceing all of the HTML, search each string for the codes and replace but that is a whole lot of code in the end. :) </p>
<p>I think you want <a href="http://uk3.php.net/manual/en/function.html-entity-decode.php" rel="nofollow">html_entity_decode</a> </p>
WatiN or Selenium? <p>I'm going to start building some automated tests of our presentation soon. It seems that everyone recommends <a href="http://watin.sourceforge.net/index.html">WatiN</a> and <a href="http://seleniumhq.org/">Selenium</a>. Which do you prefer for automated testing of ASP.NET web forms? Why did that product work better for you?</p> <p>As a side note, I noticed that WatiN 2.0 has been in CTP since March 2008, is that something to be concerned about?</p>
<p>Just want to say that I'm currently working hard on a beta release of WatiN 2.0 somewhere in Q1 of 2009. It will be a major upgrade to the current CTP 2.0 versions and will basically give you the same functionality to automate FireFox and IE as version 1.3.0 offers for automating IE.</p> <p>So no concerns there.</p> <p>Hope this helps in making your choice Jeroen van Menen Lead dev WatiN</p>
Why is the regex replace method not working? <p>In the following code I want to replace every occurrence of <code>"U.S.A"</code> with <code>"united states of America"</code> and every occurrence of <code>"uk"</code> with <code>"united kingdom"</code> in a string, but it does not seem to work. How do I fix it? </p> <pre><code>class Program { static void Main(string[] args) { string s = "the U.S.A love UK"; Console.WriteLine(replace(s)); } public static string replace(string s) { s = Regex.Replace(s, @"^U.S.A", " United state Of America"); s = Regex.Replace(s, @"^Uk", "United kingdom"); return s; } } </code></pre>
<p>Well, look at the search pattern in your regex.</p> <p>The <code>^</code> has a specific meaning. (as do the <code>.</code> but they won't actually fail in this case, but they aren't doing what you think they are)</p>
Install Shield 2009 - Shortcuts creation <p>Is it possible to create shortcuts in Install Shield 2009 based on user input? In essnes, a shortcut will be created (on the desktop) only if the user (who runs the installation) wants to do so</p>
<p>We have a screen that prompts the user to create desktop and quicklaunch shortcuts.</p> <p>The shortcuts are then each in individual components with a condition set to only install if the checkbox was selected.</p> <p>You also should store this response in the registry somewhere, and read it back during a reconfigure, upgrade, repair, etc. Otherwise if the checkboxes were on by default and that screen does not display to the user, the condition will evaluate to true (because the default property is true) and although the shortcut was not initially installed, it will be created during the repair if the components condition is reevaluated.</p>
Hide certain actions from Swing's undo manager <p>I am trying to write a JTextPane which supports some sort of coloring: as the user is typing the text, I am running some code that colors the text according to a certain algorithm. This works well.</p> <p>The problem is that the coloring operations is registered with the undo manager (a DefaultDocumentEvent with EventType.CHANGE). So when the user clicks undo the coloring disappears. Only at the second undo request the text itself is rolled back.</p> <p>(Note that the coloring algorithm is somewhat slow so I cannot color the text as it is being inserted).</p> <p>If I try to prevent the CHANGE events from reaching the undo manager I get an exception after several undo requests: this is because the document contents are not conforming to what the undoable-edit object expects.</p> <p>Any ideas?</p>
<p>How are you trying to prevent the CHANGE events from reaching the undo manager?</p> <p>Can you not send the UndoManager a lastEdit().die() call immediately after the CHANGE is queued?</p>
Edit HTML Meta Tag w/ ASP.NET <h3>Question</h3> <p><hr /> Hello All,</p> <p>I'm trying to build a quick and easy ASP.NET page that redirects a user to a new URL using a meta redirect. Only trouble is that I need to also pass along the GET values of the current request. I've found a way to do this programatically in the code behind using the HtmlMeta object. However, I'd like to avoid using the code behind and just put this code directly into the ASPX page.</p> <p>Here is what I have so far:</p> <pre> <code> &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head runat="server"&gt; &lt;title&gt;Untitled Page&lt;/title&gt; &lt;meta http-equiv="refresh" content='10;url=http://contact.test.net/main.aspx?&lt;%=Request.QueryString.ToString()%&gt;' /&gt; &lt;/head&gt; &lt;/html&gt; </code> </pre> <p><br /> ......However, this spits out the following meta tag: &lt;meta http-equiv="refresh" content="10;url=<a href="http://contact.test.net/main.aspx?&lt;%=Request.QueryString.ToString" rel="nofollow">http://contact.test.net/main.aspx?&lt;%=Request.QueryString.ToString</a>()%>" /></p> <p>So is there any way to escape the attribute so the ASP.NET code actually executes?</p> <p>Thank you in advance for your help.<br /><br /><br /></p> <h3>Solution 1</h3> <p><hr /> For the time being, I have fixed my problem by removing the quotes from the HTML attribute. Thus making the meta tag the following:</p> <pre> <code> &lt;meta http-equiv="refresh" content=10;url=http://contact.test.net/main.aspx?&lt;%=Request.QueryString.ToString()%&gt; /&gt; </code> </pre> <p><br /> Although this fixes the issue, I'd be curious if anyone knows of a more correct way to do it where I could escape the literal quotes of the HTML attribute. <br /><br /><br /></p> <h3>Solution 2 (Final Chosen Solution)</h3> <p><hr /> Per the much appreciated advise of Scott, I decided to go ahead and do this from the code behind. For anyone who is curious how this was implemented:</p> <pre> <code> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim nRef As String = Request.QueryString("n") Dim sRef As String = Request.QueryString("s") Dim contentAttrBuilder As New StringBuilder("0;http://contact.cableone.net/main.aspx") contentAttrBuilder.Append("?n=") contentAttrBuilder.Append(nRef) contentAttrBuilder.Append("&s=") contentAttrBuilder.Append(sRef) Dim metaRedirect As New HtmlMeta() metaRedirect.HttpEquiv = "refresh" metaRedirect.Content = contentAttrBuilder.ToString() Me.Header.Controls.Add(metaRedirect) End Sub </code> </pre> <p>Thanks,<br /> Chris</p>
<p>Maybe this code inside the head tag will be what you need:</p> <pre><code>&lt;%= string.Format("&lt;meta http-equiv='refresh' content='10;url=http://contact.test.net/main.aspx?{0}' /&gt;", Request.QueryString.ToString()) %&gt; </code></pre> <p><strong>However</strong>, I wouldn't advise you to do it this way. For example, this URL:</p> <pre><code>http:/mysite.with.metaredirect?&lt;script&gt;alert('hello!!!')&lt;/script&gt; </code></pre> <p>will throw an exception in asp.net if you haven't disabled its security features, and you never know if someone (or even yourself) will turn those off for some other reason.<br /> <br/> A code-behind <em>massage</em> of the querystring is <strong>strongly</strong> advised!</p>
jQuery UI Tabs - How to Select a Tab on Hover <p>Using the jQuery UI Tabs component, is it possible to select new tabs on hover instead of when clicking on them?</p> <p>I found an example <a href="http://stilbuero.de/jquery/tabs/mouseover.html" rel="nofollow">here</a>, but this does not seem to work with the latest (stable) versions of jQuery and jQuery UI tabs.</p> <p>Finally, one of the <a href="http://markmail.org/message/yymcisfniiyrf6ls#query:jquery%20tabs%20rollover+page:1+mid:w3kazcwusiyxahsz+state:results" rel="nofollow">developers mentions that this will be an option in Tabs 3</a>, which has since been released, but I cannot find any mention of it in the API.</p>
<p><a href="http://ui.jquery.com/demos/tabs#mouseover" rel="nofollow">demo here</a> Its running with 1.6rc4 which I consider as stable as any other of the ui releases!</p>
Abstract classes and methods in Java, Inheritance <p>I have class B, which inherits from class A. The superclass A is abstract, containing one abstract method. I don't want to implement the abstract method in class B, therefore I need to declare class B as abstract as well. Declaring class B abstract, two things are working for me (the programs compile and run correctly):</p> <p>1.) I don't declare any abstract methods in class B, even thought the class is abstract. This works, I assume, because the class inherits the abstract method of class A, and this is enough for the class to be declared as abstract: we don't need any other abstract methods directly declared in the class.</p> <p>2.) I do declare the same abstract method in class B as it is declared in class A. This is some kind of overriding (?), not in the same sense as overriding in java (using the same header, but providing different implementation), here I just use again the same header of the method.</p> <p>Both things are working, and I am not sure whether they are both Ok, and whether some of them is preferred (more correct) that the other. Are the two ways the same (do they mean the same to Java)? </p> <p>Here I give some example classes, so that what I mean is more clear for you:</p> <p>Case 1.):</p> <pre><code>public abstract class A { public abstract String giveSum(); } public abstract class B extends A { } </code></pre> <p>Case 2.):</p> <pre><code>public abstract class A { public abstract String giveSum(); } public abstract class B extends A { public abstract String giveSum(); } </code></pre> <p>Regards</p>
<p>In Java, the <code>abstract</code> class annotation indicates that the class cannot be directly instantiated. A class could be declared <code>abstract</code> simply because it should never be instantiated (perhaps it contains only static methods), or because its subclasses should be instantiated instead.</p> <p>It is <strong>not</strong> a requirement that <code>abstract</code> classes contain <code>abstract</code> methods (the inverse <strong>is</strong> true: a class containing one or more <code>abstract</code> methods must be <code>abstract</code>.)</p> <p>The question of whether you should duplicate the abstract method definition might be perceived as a style question - but I would be hard pressed to come up with an argument in favor of duplicating the definition (the only argument I can come up with is in the case where the class hierarchy might change the semantics or use of the method, and thus you'd like to provide an additional javadoc in class B.)</p> <p>The primary argument against re-definition of the <code>abstract</code> method is that duplicate code is bad - it makes refactoring more cumbersome and such (all the classic "don't duplicate code" arguments apply.)</p>
Classic ASP: Server.CreateObject not supported <p>When I call Server.CreateObject(), from my Classic ASP page, I get</p> <pre><code>Microsoft VBScript runtime (0x800A01B6) Object doesn't support this property or method </code></pre> <p>I've tried the following (separately):</p> <pre><code>Server.CreateObject("Microsoft.XMLHTTP") Server.CreateObject("MSXML2.XMLHTTP") Server.CreateObject("MSXML.DOMDocument") </code></pre> <p>I know the ActiveX objects are installed because the following javascript calls work</p> <pre><code>var test = new ActiveXObject("Microsoft.XMLHTTP"); var test = new ActiveXObject("MSXML2.XMLHTTP"); var test = new ActiveXObject("MSXML.DOMDocument"); </code></pre> <p>I'm calling it from my localhost IIS server. Any ideas how to troubleshoot this?</p>
<p>If you do the following:</p> <pre><code>Dim x: x = Server.CreateObject("My.ProgID.Here") </code></pre> <p>...VBScript creates the object and then attempts to access the default property for storing in 'x'. Since none of these objects have a default property defined (specifically an IDispatch-based property with [id(DISPID_VALUE)]), this fails with "Object doesn't support this property or method".</p> <p>What you actually want is this:</p> <pre><code>Dim x: Set x = Server.CreateObject("My.ProgID.Here") </code></pre>
How to right align a <p> tag? <p>I have a couple of <code>&lt;p&gt;</code> tags that I want to right align. Does anyone know how to do this?</p>
<p>CSS:</p> <pre><code>p { text-align: right; } </code></pre> <p>INLINE:</p> <pre><code>&lt;p style="text-align: right"&gt;Some Text&lt;/p&gt; </code></pre> <p>jQuery:</p> <pre><code>$('p').css('text-align', 'right'); </code></pre> <p>Javascript:</p> <pre><code>var aElements = document.getElementsByTagName('p'); for (var i = 0; i &lt; aElements.length; i++) { aElements[i].style.textAlign = 'right'; } </code></pre>
SVN export just the changed files from tags <p>Does anyone know how to export only the changed files from two tags using svn? </p> <p>Lets say I have tag 1.0 and then later fix bugs in the trunk. Next I am ready for a new patch release so I tag it 1.1. Now I want to export the changed files between tag 1.0 and 1.1. Is this possible? </p>
<p>svn diff --summarize url/to/tag1.0 url/to/tag1.1</p> <p>will give you a list of files that changed between those two tags. You should be able to parse that list in a script and export each file individually with either</p> <p>svn export url/to/file filepath</p> <p>or</p> <p>svn cat url/to/file > file</p> <p>If you're using TortoiseSVN:</p> <ul> <li>open the repository browser, browse to tag1.0, right-click, choose "mark for comparison"</li> <li>browse to tag1.1, right-click, choose "compare urls"</li> <li>in the file diff dialog, select all files/folders that changed between the tags (Ctrl+A)</li> <li>right-click, choose "export to..."</li> </ul>
What's your naming convention for helper functions? <p>In functional programming, it's often important to optimize any "looping" code to be tail recursive. Tail recursive algorithms are usually split between two functions, however - one which sets up the base case, and another that implements the actual loop. A good (albeit academic) example would be the reverse function.</p> <pre><code>reverse :: [a] -&gt; [a] reverse = reverse_helper [] reverse_helper :: [a] -&gt; [a] -&gt; [a] reverse_helper result [] = result reverse_helper result (x:xs) = reverse_helper (x:result) xs </code></pre> <p>"reverse_helper" isn't really a good, descriptive name. However, "reverse_recursive_part" is just awkward.</p> <p>What naming convention would you use for helper functions like this?</p>
<p>You can call the helper function anything you want, and it won't matter as long as you don't put the helper function in the "global" namespace. Simply adding a "prime" seems a common practice. :) E.g., in Haskell,</p> <pre><code>reverse :: [a] -&gt; [a] reverse = reverse' [] where reverse' :: [a] -&gt; [a] -&gt; [a] reverse' result [] = result reverse' result (x:xs) = reverse' (x:result) xs </code></pre>
What problems are easy to spot in a dependency graph? <p>What are the things I should be looking for when I produce a dependency graph?</p> <p>Or to put it another way, what are the characteristics of a good looking graph vs a bad one?</p> <p>Edit: The context here is my first look at my assemblies in NDepend.</p>
<p>a dependency graph of what? classes? stored procedures?</p> <p>cycles are bad...</p>
Implementing IInternetZoneManager in .NET <p>I'm trying to implement <a href="http://msdn.microsoft.com/en-us/library/ms537079(VS.85).aspx" rel="nofollow">IInternetZoneManager</a> in .NET with Webbrowser Control but I have no clue what to do.</p> <p>I couldn't find any managed code example about this implementation. I'm pretty bad about OLE stuff.</p> <p>Can anyone provide a sample on this? I spend about 2 days with no luck.</p>
<p>This is what I get when I convert it:</p> <pre><code>public class Constants { public const int MAX_PATH = 260; public const int MAX_ZONE_PATH = 260; public const int MAX_ZONE_DESCRIPTION = 200; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct ZONEATTRIBUTES { public uint cbSize; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] public string szDizplayName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_ZONE_DESCRIPTION)] public string szDescription; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Constants.MAX_PATH)] public string szIconPath; public uint dwTemplateMinLevel; public uint dwTemplateRecommended; public uint dwTemplateCurrentLevel; public uint dwFlags; } public enum URLZONEREG { URLZONEREG_DEFAULT = 0, URLZONEREG_HKLM, URLZONEREG_HKCU } [Guid("79eac9ef-baf9-11ce-8c82-00aa004ba90b")] [ComImport] public interface IInternetZoneManager { void CopyTemplatePoliciesToZone(uint dwTemplate, uint dwZone, uint dwReserved); void CreateZoneEnumerator(ref uint pdwEnum, ref uint pdwCount, uint dwFlags); void DestroyZoneEnumerator(uint dwEnum); void GetZoneActionPolicy(uint dwZone, uint dwAction, IntPtr pPolicy, uint cbPolicy, URLZONEREG urlZoneReg); void GetZoneAt(uint dwEnum, uint dwIndex, ref uint pdwZone); void GetZoneAttributes(uint dwZone, ref ZONEATTRIBUTES pZoneAttributes); void GetZoneCustomPolicy(uint dwZone, [In] ref Guid guidKey, ref IntPtr ppPolicy, ref uint pcbPolicy, URLZONEREG urlZoneReg); void LogAction(uint dwAction, [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [MarshalAs(UnmanagedType.LPWStr)] string pwszText, uint dwLogFlags); void PromptAction(uint dwAction, IntPtr hwndParent, [MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, [MarshalAs(UnmanagedType.LPWStr)] string pwszText, uint dwPromptFlags); void SetZoneActionPolicy(uint dwZone, uint dwAction, IntPtr pPolicy, uint cbPolicy, URLZONEREG urlZoneReg); void SetZoneAttributes(uint dwZone, ref ZONEATTRIBUTES pZoneAttributes); void SetZoneCustomPolicy(uint dwZone, [In] ref Guid guidKey, IntPtr pPolicy, uint pcbPolicy, URLZONEREG urlZoneReg); } </code></pre> <p>I've also posted the definition at <a href="http://www.pinvoke.net" rel="nofollow">pinvoke.net</a>:</p> <p><a href="http://www.pinvoke.net/default.aspx/Interfaces.IInternetZoneManager" rel="nofollow">http://www.pinvoke.net/default.aspx/Interfaces.IInternetZoneManager</a></p> <p>Generally, you should look there first for interop definitions (and contribute if it's not there).</p>
Practices to prevent/control image content <p>Dead code is easily recognised and eliminated by having code reviews, however, when it comes to images - unused images still get into our version control. Is there any clean way of organising graphic content so that a direct correlation exists between web pages and image files?</p> <p>In our current project, we use create master PNG files then export the required layers for development purpose. Recently I figured out that there is some bloat in the images folder. Doing a search for image names in code helps but it is very painful when it needs to be done for hundred odd images. So asking the forum for suggestions</p>
<p>You could walk the website with a crawler (like wget) and remove any image not touched (i.e. not listed in your logs.)</p> <p>A quicker way would be to just dump all the image file names found in your code.</p> <pre><code>grep -o -e \w*?\.png (caution: untested regex) </code></pre>
How to reverse lines of a text file? <p>I'm writing a small shell script that needs to reverse the lines of a text file. Is there a standard filter command to do this sort of thing?</p> <p>My specific application is that I'm getting a list of Git commit identifiers, and I want to process them in reverse order:</p> <pre><code>git log --pretty=oneline work...master | grep -v DEBUG: | cut -d' ' -f1 | reverse </code></pre> <p>The best I've come up with is to implement <code>reverse</code> like this:</p> <pre><code>... | cat -b | sort -rn | cut -f2- </code></pre> <p>This uses <code>cat</code> to number every line, then <code>sort</code> to sort them in descending numeric order (which ends up reversing the whole file), then <code>cut</code> to remove the unneeded line number.</p> <p>The above works for my application, but may fail in the general case because <code>cat -b</code> only numbers nonblank lines.</p> <p>Is there a better, more general way to do this?</p>
<p>In <a href="http://www.gnu.org/software/coreutils/">GNU coreutils</a>, there's <a href="http://www.gnu.org/software/coreutils/manual/coreutils.html#tac-invocation">tac(1)</a></p>
How "safe" are Anonymous Types and Reflection together? <p>I guess this could also be asked as to how long the created type name is attached to an anonymous type. Here's the issue:</p> <p>A blog had something like this:</p> <pre><code>var anonymousMagic = new {test.UserName}; lblShowText.Text = lblShowText .Text .Format("{UserName}", test); </code></pre> <p>As sort of a wish list and a couple ways to go at it. Being bored and adventurous I took to creating an string extension method that could handle this:</p> <pre><code>var anonymousMagic = new {test.UserName, test.UserID}; lblShowText.Text = "{UserName} is user number {UserID}" .FormatAdvanced(anonymousMagic); </code></pre> <p>With the idea that I would get the property info from the anonymous type and match that to the bracketted strings. Now with property info comes reflection, so I would want to save the property info the first time the type came through so that I wouldn't have to get it again. So I did something like this:</p> <pre><code> public static String FormatAdvanced(this String stringToFormat, Object source) { Dictionary&lt;String, PropertyInfo&gt; info; Type test; String typeName; // currentType = source.GetType(); typeName = currentType.Name; // //info list is a static list for the class holding this method if (infoList == null) { infoList = new Dictionary&lt;String, Dictionary&lt;String, PropertyInfo&gt;&gt;(); } // if (infoList.ContainsKey(typeName)) { info = infoList[typeName]; } else { info = test.GetProperties() .ToDictionary(item =&gt; item.Name); infoList.Add(typeName, info); } // foreach (var propertyInfoPair in info) { String currentKey; String replacement; replacement = propertyInfoPair.Value.GetValue(source, null).ToString(); currentKey = propertyInfoPair.Key; if (stringToFormat.Contains("{" + currentKey + "}")) { stringToFormat = stringToFormat .Replace("{" + currentKey + "}", replacement); } } // return stringToFormat; } </code></pre> <p>Now in testing, it seems to keep the name it created for the anonymous type so that the second time through it doesn't get the property info off the type but off the dictionary. </p> <p>If multiple people are hitting this method at the same time, is it pretty much going to work in a Session like fassion; IE the names of the types will be specific to each instance of the program? Or would it be even worse than that? At what point does that name get chucked and overwritten?</p>
<p>It never does. The type is generated at compile-time and you can consider it constant and unique throughout the life of the app-domain.</p> <p>I question the value of this function though. The obvious first reason is because you don't have much of the functionality of the Format method on the String class (no escape for brackets, no formatting of values in the brackets, etc, etc).</p> <p>The second is that it basically links the format string to the type being passed in, so they are not swapped out easily. If I had two classes which had the same conceptual value, but different properties naming it, I have to change my format string to display it with your method to compensate for the fact that the property name is embedded in the format string.</p>
Any drawbacks or gotchas to using Jinja2 templates in Django? <p>After reading the Jinja2 documentation, I'm interested in employing it in future Django projects. However, I'm wondering if anyone has encountered any drawbacks or gotchas when using Jinja2 templates with Django? If so, how did you work around them?</p> <p>I wouldn't mind hearing about positive experiences either, just to get a good cross section of the best and worst of Jinja2.</p>
<p>I use Jinja2 in some of my projects and love the extra expressiveness it gives me. I can keep my presentation logic and application logic separate, but I don't have to bend over backwards to call into a function/method I've designed specifically for my presentation layer.</p> <p>In addition to what's already been listed by other posters, here are some things that I've found:</p> <ul> <li>The Admin app is tightly coupled to Django templates</li> <li>The default views and decorators that come with the Auth app (and elsewhere) are coupled to Django templates, so you may have to duplicate the effort if you want to use your Jinja2 templates for login/logout/etc</li> </ul> <p>Behaviorally, Django templates will escape its output by default whereas Jinja2 will not. I think either approach has its own merits, but you have to keep this in mind if you are switching between the two.</p>
Transaction Scope <p>How does the transaction scope work? How does it know when there is another context being used already and how might I implement another kind of scope in my code.</p> <p>I'm primarily a vb.net developer but I can read the c# if you write in that.</p> <p>In case the above was too vague:</p> <p>I understand what system.transactions does and how to use it. What I want to know is how to create something similar, my own library that I can wrap around some code that can handle it in the same manner as the system.transactions scope does. I plan on using this with a caching model and it would greatly enhance it. I'm looking for details on how transaction scope knows for example that there is a parent scope and so it can attach to it and such, or that a commit then needs to take place at a higher level or in a higher contact.</p> <p>For example, if I have the following</p> <pre><code>using scope1 as new system.transactions.scope using scope2 as new system.transactions.scope using scope3 as new system.transactions.scope scope3.commit end using scope2.commit end using end using </code></pre> <p>Scope1 will not commit and so neither will scope2 or scope3 since the parent to them all is the context of scope1. I'd like to be able to set this up with my own libraries.</p>
<p>I suggest the article <a href="http://msdn.microsoft.com/en-us/library/ms973865.aspx">Introducing System.Transactions</a> by <a href="http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=3&amp;tabid=5">Juval Lowy</a></p>
Setting iso-8859-1 instead of utf-8 in oscommerce / sts template website? <p>In an oscommerce site I have the following:</p> <p>Server response = Content-type: text/html;charset=UTF-8</p> <p>and I want: Content-type: text/html;charset=ISO-8859-1</p> <p>How and where do I set this up. </p> <p><hr /></p> <p>Html looks like this on the page:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"&gt; &lt;html dir="LTR" lang="nl"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; </code></pre> <p>Changing it to: utf-8 doesnt solve the problem. </p>
<p>in an .htaccess file</p> <pre><code>AddDefaultCharset ISO-8859-1 </code></pre>
Subdirectories within an iOS application <p>Is there a way to have directories within an .app?</p> <p>At the moment if I add a file into Xcode, regardless of what Group hierarchy it is in, the file always lands in a flat filesystem within my application bundle.</p>
<p>If you just want to copy existing files into your application bundle's Resources folder (which on iPhone is just the inside of the .app bundle), do the following:</p> <ul> <li>Drag the folder you want copied into the Files and Folders listing of your xcode project.</li> <li>From the sheet that pops up asking you if you want to add the files to a target, change the radio button to "Create folder references for any added folders'.</li> </ul> <p>The folder you dragged in and all of its contents will be copied verbatim during building.</p>
All .cpp files depend on two .h files? <p>In a makefile, I have the following line:</p> <pre><code>helper.cpp: dtds.h </code></pre> <p>Which ensures that helper.cpp is rebuilt whenever dtds.h is changed. However, I want ALL files in the project to be rebuilt if either of two other header files change, kind like this:</p> <pre><code>*.cpp: h1.h h2.h </code></pre> <p>Obviously that won't work, but I don't know the right way to get nmake to do what I want. Can someone help? I don't want to have to manually specify that each individual file depends on h1.h and h2.h.</p> <p>Thanks. (I'm using nmake included with visual studio 2005.)</p>
<p>Try</p> <pre><code>%.cpp : h1.h h2.h </code></pre> <p>That works in GNU make - no idea if nmake is compatible...</p> <p><strong>Edit:</strong> And btw: shouldn't that be</p> <pre><code>helper.o : dtds.h %.o : h1.h h2.h </code></pre> <p>After all, you don't want to remake the <code>.cpp</code> file (how do you make a source file?), but recompile...</p> <p><strong>Edit2:</strong> Check the <a href="http://msdn.microsoft.com/en-us/library/dd9y37ha(VS.80).aspx" rel="nofollow">NMAKE Reference</a>. According to <a href="http://msdn.microsoft.com/en-us/library/x6bt6xe7(VS.80).aspx" rel="nofollow">this</a>, something like</p> <pre><code>.cpp.obj: h1.h h2.h </code></pre> <p>might work...</p>
What is a good openid selector control? <p>Now that <a href="http://www.idselector.com/">idselector</a> has been upgraded to <a href="http://rpxnow.com/">RPXNow</a> and you can't "just use" the selector code, what is a good replacement?</p> <p>I want to implement OpenId on a new website that I am using, but the users are going to be just dumb when it comes to logging in unless I provide an easy way for them to.</p> <p>As a reference, I will be using .Net Open Id for the background in an ASP.Net MVC web application.</p> <p><hr /></p> <p><strong>EDIT</strong></p> <p>After some cheap thought, what about using the <a href="http://code.google.com/p/rpxlib/">rpxlib</a>?</p>
<p><a href="http://jvance.com/pages/JQueryOpenIDPlugin.xhtml"><strong>Jarrett Vance</strong> </a> made a "version" of open-selector that is much more developer/designer friendly.</p> <blockquote> <p>This selector is different because <strong>it does not hide the markup details in javascript</strong>. Therefore, <strong>you can easily add new providers</strong> or rearrange the existing ones without digging into the javascript. The login form will still work for normal OpenID logins if javascript is disabled</p> </blockquote> <p>The best of all, is that it comes with documentation, demo, and lots of images both cropped and as raw <a href="http://www.getpaint.net/index.html">.pdn</a> files (<a href="http://www.getpaint.net/index.html">paint.net</a>)</p> <p>Jarrett Vance's <a href="http://jvance.com/pages/JQueryOpenIDPlugin.xhtml">openid-selector</a> <a href="http://jvance.com/pages/JQueryOpenIDPlugin.xhtml">can be found here</a></p> <p><a href="http://jvance.com/pages/JQueryOpenIDPlugin.xhtml"><img src="http://jvance.com/media/2009/02/10/JQueryOpenIdPluginUser%5Fthumb2.media" alt="alt text" /></a></p> <p><strong>PS: I would suggest reading <a href="http://blog.nerdbank.net/2009/01/why-using-rpxnow-is-bad-idea.html">this article</a> before implementing RPX.</strong></p>
cloning ExtJS components using JQuery <p>I'm trying to clone form components using JQuery's .clone() (actually, I'm cloning a collection of fields by cloning the container element). Everything worked out well except that the datefield, comboboxes are not working, even the validation for minLength, etc. is also not working.</p> <p>By the way, I'm just transforming an old html form fields to ext js form fields using applyTo</p>
<p>The problem is that jQuery clone() does not clone the event handlers associated with DOM elements. But even if you use clone(true), that does copy the event handlers, it still doesn't work, because you also need to clone the Ext object on the JavaScript side.</p> <p>You really need to use the tools provided by Ext to create many similar controls. A good start is to <a href="http://blog.extjs.eu/know-how/writing-a-big-application-in-ext/" rel="nofollow">create custom Ext components</a>, that you can then more easily instanciate multiple times.</p>
Managing and debugging SQL queries in MS Access <p>MS Access has limited capabilities to manage raw SQL queries: the editor is quite bad, no syntax highlighting, it reformats your raw SQL into a long string and you can't insert comments.</p> <p>Debugging complex SQL queries is a pain as well: either you have to split it into many smaller queries that become difficult to manage when your schema changes or you end-up with a giant query that is a nightmare to debug and update.</p> <p>How do you manage your complex SQL queries in MS Access and how do you debug them?</p> <p><strong>Edit</strong><br /> At the moment, I'm mostly just using <a href="http://notepad-plus.sourceforge.net/uk/site.htm">Notepad++</a> for some syntax colouring and <a href="http://www.wangz.net/">SQL Pretty Printer</a> for reformatting sensibly the raw SQL from Access.<br /> Using an external repository is useful but keeping there's always the risk of getting the two versions out of sync and you still have to remove comments before trying the query in Access...</p>
<p>For debugging, I edit them in a separate text editor that lets me format them sensibly. When I find I need to make changes, I edit the version in the text editor, and paste it back to Access, never editing the version in Access.</p> <p>Still a major PITA.</p>
Why doesn't CakePHP support a foreign key with multiple columns? <p>I searched in google for this without a good result. The only <a href="https://trac.cakephp.org/ticket/1923" rel="nofollow">topic</a> I found in the CakePHP trac, was closed without a "real" explanation. Since CakePHP is like one of the rails ports for php and rails does support this, I would like to know why it doesn't support this feature.</p> <hr> <p>ok. but I would like to decide how my db schema will be, in RoR you have the tool, if you wanna use it, you do it under your risk. btw: I don't know if symphony allow to do it also.</p>
<p>Only the CakePHP team would know for sure. One of the team, Nate Abdele, <a href="http://groups.google.com/group/cake-php/msg/255c641339eef6ac" rel="nofollow">said this</a> about multi-column primary keys back in February 2007:</p> <blockquote> <p>I could come up with a million other reasons why multi-column primary keys are a dumb idea, but I think the most important one for 2007 is that it breaks REST architecture on the web, as there is no single point of reference to a piece of data, and that data may now change up on you without you knowing it, so objects can no longer be consistently referenced from a single URI.</p> </blockquote> <p>I assume this would be his argument against multi-column foreign keys too.</p>
How to raise an exception on the version number of a module <p>How can you raise an exception when you import a module that is less or greater than a given value for its __version__?</p> <p>There are a lot of different ways you could do it, but I feel like there must be some really simple way that eludes me at the moment. In this case the version number is of the format x.x.x</p>
<p>Python comes with this inbuilt as part of distutils. The module is called <code>distutils.version</code> and is able to compare several different version number formats.</p> <pre><code>from distutils.version import StrictVersion print StrictVersion('1.2.2') &gt; StrictVersion('1.2.1') </code></pre> <p>For way more information than you need, see the documentation:</p> <pre><code>&gt;&gt;&gt; import distutils.version &gt;&gt;&gt; help(distutils.version) </code></pre>
How to get JavaScript function data into a PHP variable <p>I am using PHP and JavaScript. My JavaScript code contains a function, get_data():</p> <pre><code>function get_Data(){ var name; var job; ..... return buffer; } </code></pre> <p>Now I have PHP code with the following.</p> <pre><code>&lt;?php $i=0; $buffer_data; /* Here I need to get the value from JavaScript get_data() of buffer; and assign to variable $buffer_data. */ ?&gt; </code></pre> <p>How do I assign the JavaScript function data into the PHP variable?</p>
<p>Use jQuery to send a JavaScript variable to your PHP file:</p> <pre><code>$url = 'path/to/phpFile.php'; $.get($url, {name: get_name(), job: get_job()}); </code></pre> <p>In your PHP code, get your variables from <code>$_GET['name']</code> and <code>$_GET['job']</code> like this:</p> <pre><code>&lt;?php $buffer_data['name'] = $_GET['name']; $buffer_data['job'] = $_GET['job']; ?&gt; </code></pre>
Grabbing text from a webpage <p>I would like to write a program that will find bus stop times and update my personal webpage accordingly.</p> <p>If I were to do this manually I would </p> <ol> <li>Visit www.calgarytransit.com</li> <li>Enter a stop number. ie) 9510</li> <li>Click the button "next bus"</li> </ol> <p>The results may look like the following:</p> <blockquote> <p>10:16p Route 154 10:46p Route 154 11:32p Route 154</p> </blockquote> <p>Once I've grabbed the time and routes then I will update my webpage accordingly. </p> <p>I have no idea where to start. I know diddly squat about web programming but can write some C and Python. What are some topics/libraries I could look into?</p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Quick%20Start" rel="nofollow">Beautiful Soup</a> is a Python library designed for parsing web pages. Between it and <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> (<a href="http://docs.python.org/py3k/library/urllib.request" rel="nofollow">urllib.request</a> in Python 3) you should be able to figure out what you need.</p>
VS2008: Running xsd.exe on schema file gives XMLSchema:datetime is not declared <p>I have a an XSD that looks like this (roughly)</p> <pre><code>&lt;xs:schema id="Appointment" targetNamespace="http://tempuri.org/Record.xsd" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns="http://tempuri.org/Record.xsd" xmlns:mstns="http://tempuri.org/Record.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"&gt; &lt;xs:element name="Record" msdata:IsDataSet="true"&gt; &lt;xs:complexType&gt; &lt;xs:choice maxOccurs="unbounded"&gt; &lt;xs:element name="Record"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="ID" type="xs:string" minOccurs="0" /&gt; &lt;xs:element name="TimeStart" type="xs:datetime" minOccurs="0" /&gt; &lt;xs:element name="TimeEnd" type="xs:datetime" minOccurs="0" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; </code></pre> <p>When I try to generate classes from it using the xsd.exe from VS2008 I get string fields instead of date fields, and a warning that </p> <pre><code>Schema validation warning: Type 'http://www.w3.org/2001/XMLSchema:datetime' is not declared. Line 13, position 9. </code></pre> <p>Any clues?</p>
<p>Bah, nevermind. </p> <p>Was case sensitivity issue.</p> <p>The correct form to use was</p> <pre><code>xs:dateTime </code></pre> <p>instead of</p> <pre><code>xs:datetime </code></pre>
How do I get the number of rows per day between given dates? <p>I am having table in the below format. I need mysql query to get the no of rows perday when i give date between 2008-10-12 and 2008-10-13</p> <pre> Name | KW | KV | I | Date | ------+--------+------+------+---------------------+ UPS1 | 353.50 | NULL | NULL | 2008-10-12 00:54:36 | UPS1 | 352.50 | NULL | NULL | 2008-10-12 01:54:36 | UPS1 | 351.90 | NULL | NULL | 2008-10-12 02:54:36 | UPS1 | 351.60 | NULL | NULL | 2008-10-12 03:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 04:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 05:54:36 | UPS1 | 351.90 | NULL | NULL | 2008-10-12 06:54:36 | UPS1 | 352.50 | NULL | NULL | 2008-10-12 07:54:36 | UPS1 | 352.50 | NULL | NULL | 2008-10-12 08:54:36 | UPS1 | 353.20 | NULL | NULL | 2008-10-12 09:54:36 | UPS1 | 353.50 | NULL | NULL | 2008-10-12 10:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 11:54:36 | UPS1 | 352.50 | NULL | NULL | 2008-10-12 12:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 13:54:36 | UPS1 | 353.20 | NULL | NULL | 2008-10-12 14:54:36 | UPS1 | 353.50 | NULL | NULL | 2008-10-12 15:54:36 | UPS1 | 352.90 | NULL | NULL | 2008-10-12 16:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 17:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 18:54:36 | UPS1 | 352.90 | NULL | NULL | 2008-10-12 19:54:36 | UPS1 | 352.20 | NULL | NULL | 2008-10-12 20:54:36 | UPS1 | 352.50 | NULL | NULL | 2008-10-12 21:54:36 | UPS1 | 352.90 | NULL | NULL | 2008-10-12 22:54:36 | UPS1 | 353.20 | NULL | NULL | 2008-10-12 23:54:36 | UPS1 | 355.80 | NULL | NULL | 2008-10-13 00:54:36 | UPS1 | 358.40 | NULL | NULL | 2008-10-13 01:54:36 | UPS1 | 358.00 | NULL | NULL | 2008-10-13 02:54:36 | UPS1 | 359.00 | NULL | NULL | 2008-10-13 03:54:36 | UPS1 | 357.70 | NULL | NULL | 2008-10-13 04:54:36 | UPS1 | 357.40 | NULL | NULL | 2008-10-13 05:54:36 | UPS1 | 357.40 | NULL | NULL | 2008-10-13 06:54:36 | UPS1 | 359.00 | NULL | NULL | 2008-10-13 07:54:36 | UPS1 | 357.10 | NULL | NULL | 2008-10-13 08:54:36 | UPS1 | 359.00 | NULL | NULL | 2008-10-13 09:54:36 | UPS1 | 357.70 | NULL | NULL | 2008-10-13 10:54:36 | UPS1 | 357.40 | NULL | NULL | 2008-10-13 11:54:36 | UPS1 | 357.40 | NULL | NULL | 2008-10-13 12:54:36 | UPS1 | 359.00 | NULL | NULL | 2008-10-13 13:54:36 | UPS1 | 357.10 | NULL | NULL | 2008-10-13 14:54:36 | UPS1 | 358.00 | NULL | NULL | 2008-10-13 15:54:36 | UPS1 | 359.30 | NULL | NULL | 2008-10-13 16:54:36 | UPS1 | 357.10 | NULL | NULL | 2008-10-13 17:54:36 | UPS1 | 358.40 | NULL | NULL | 2008-10-13 18:54:36 | UPS1 | 357.70 | NULL | NULL | 2008-10-13 19:54:36 | UPS1 | 359.00 | NULL | NULL | 2008-10-13 20:54:36 | UPS1 | 358.70 | NULL | NULL | 2008-10-13 21:54:36 | UPS1 | 358.70 | NULL | NULL | 2008-10-13 22:54:36 | UPS1 | 358.40 | NULL | NULL | 2008-10-13 23:54:36 | </pre>
<p>I have changed the query so that Date column case matches exactly what you have in your query results.</p> <pre><code>select Date, count(Date) from TABLE where Date &gt;= '2008-10-12' and Date &lt;= '2008-10-13' group by Date </code></pre> <p>You will need to change TABLE in the from clause, but everything else should be correct for your table.</p> <p>edit:</p> <p>I have a table with a similar structure and I changed a date column to be named 'Date'. The following worked for me.</p> <pre><code>mysql&gt; select Date, count(Date) from calendar_items where date between '2008-12-12' and '2008-12-13' group by Date; +------------+-------------+ | Date | count(Date) | +------------+-------------+ | 2008-12-12 | 14 | | 2008-12-13 | 6 | +------------+-------------+ 2 rows in set (0.00 sec) mysql&gt; </code></pre>
Binary SMS in Symbian <p>I wonder if anyone has managed to create a working code for sending out binary messages (to configure Symbian phones) and have also some binary data sample. So far all the samples I have found fail to leave the Outbox or never return.</p> <pre><code>// Current entry is the Draft folder. iSmsMtm-&gt;SwitchCurrentEntryL( KMsvDraftEntryId ); // Create a new SMS message entry as a child of the current context. iSmsMtm-&gt;CreateMessageL( KUidMsgTypeSMS.iUid ); CMsvEntry&amp; serverEntry = iSmsMtm-&gt;Entry(); TMsvEntry entry( serverEntry.Entry() ); /* Send Binary SMS */ CSmsHeader &amp;hdr = iSmsMtm-&gt;SmsHeader(); CSmsMessage &amp;msg = hdr.Message(); CSmsPDU &amp;pdu = msg.SmsPDU(); CSmsUserData &amp;userdata = pdu.UserData(); // Set the DCS byte pdu.SetBits7To4(TSmsDataCodingScheme::ESmsDCSTextUncompressedWithNoClassInfo); pdu.SetAlphabet(TSmsDataCodingScheme::ESmsAlphabet8Bit); pdu.SetClass(ETrue, TSmsDataCodingScheme::ESmsClass2); char buf[]= {...}; //my binary data, 247 bytes long // Construct a dummy message HBufC8 * iMessage = HBufC8::NewL(300); TPtr8 TempUDHBufDesc((TUint8*)buf,247,247); iMessage-&gt;Des().Copy(TempUDHBufDesc); _LOGFENTRY1(_L("mess length %d"),iMessage-&gt;Des().Length()); userdata.SetBodyL(*iMessage); delete iMessage; // Message will be sent immediately. entry.SetSendingState( KMsvSendStateWaiting ); entry.iDate.UniversalTime(); // insert current time //Solution for HomeTime() // Set the SMS message settings for the message. CSmsHeader&amp; header = iSmsMtm-&gt;SmsHeader(); CSmsSettings* settings = CSmsSettings::NewL(); CleanupStack::PushL( settings ); settings-&gt;CopyL( iSmsMtm-&gt;ServiceSettings() ); // restore settings settings-&gt;SetDelivery( ESmsDeliveryImmediately ); // to be delivered immediately settings-&gt;SetDeliveryReport(EFalse); settings-&gt;SetCharacterSet(TSmsDataCodingScheme::ESmsAlphabet8Bit); // IMPORTANT! For sending binary SMS header.SetSmsSettingsL( *settings ); // new settings // Let's check if there is a service center address. if ( header.Message().ServiceCenterAddress().Length() == 0 ) { // No, there isn't. We assume there is at least one service center // number set and use the default service center number. CSmsSettings* serviceSettings = &amp;( iSmsMtm-&gt;ServiceSettings() ); // Check if number of service center addresses in the list is null. if ( !serviceSettings-&gt;ServiceCenterCount() ) { _LOGENTRY("No SC"); return ; // quit creating the message } else { CSmsNumber* smsCenter= CSmsNumber::NewL(); CleanupStack::PushL(smsCenter); smsCenter-&gt;SetAddressL((serviceSettings-&gt;GetServiceCenter( serviceSettings-&gt;DefaultServiceCenter())).Address()); header.Message().SetServiceCenterAddressL( smsCenter-&gt;Address() ); CleanupStack::PopAndDestroy(smsCenter); } } CleanupStack::PopAndDestroy( settings ); // Recipient number is displayed also as the recipient alias. entry.iDetails.Set( _L("+3725038xxx") ); iSmsMtm-&gt;AddAddresseeL( _L("+3725038xxx") , entry.iDetails ); // Validate message. if ( !ValidateL() ) { _LOGENTRY("Not valid"); return ; } entry.SetVisible( ETrue ); // set message as visible entry.SetInPreparation( EFalse ); // set together with the visibility flag serverEntry.ChangeL( entry ); // commit changes iSmsMtm-&gt;SaveMessageL(); // save message TMsvSelectionOrdering selection; CMsvEntry* parentEntry = CMsvEntry::NewL( iSmsMtm-&gt;Session(), KMsvDraftEntryId, selection ); CleanupStack::PushL( parentEntry ); // Move message to Outbox. iOperation =parentEntry-&gt;MoveL( entry.Id(), KMsvGlobalOutBoxIndexEntryId, iStatus ); CleanupStack::PopAndDestroy( parentEntry ); iState = EWaitingForMoving; SetActive(); </code></pre> <p>Mostly I'm not sure about the correct values for port and class . Also some correct binary string would be nice to have for testing. Now I'm not sure if thecode is bad or the data.</p>
<p>Use the JSR120 specification and the wireless toolkit. they contain java example code that will work for sure.</p> <p>These are implemented directly using RSocket objects in Symbian C++.</p> <p>If you really want to do it in C++, the simplest way is to copy your TMsvEntry to the entry of the sms service. In your code above, that means using "iSmsMtm->ServiceId()" instead of "KMsvGlobalOutBoxIndexEntryId". also, just copy the message to the service but do move it to the outbox after it has been successfully sent.</p> <p>shameless plug : <a href="http://www.quickrecipesonsymbianos.com" rel="nofollow">http://www.quickrecipesonsymbianos.com</a> will contain an explanation of the Symbian C++ messaging API will simple and reusable example code.</p>
How do I pan the image inside a UIImageView? <p>I have a <code>UIImageView</code> that is displaying an image that is wider and taller than the <code>UIImageView</code> is. I would like to pan the image within the view using an animation (so that the pan is nice and smooth).</p> <p>It seems to me that I should be able to just adjust the <code>bounds.origin</code> of the <code>UIImageView</code>, and the image should move (because the image should paint inside the view with that as <strong>its</strong> origin, right?) but that doesn't seem to work. The <code>bounds.origin</code> changes, but the image draws in the same location.</p> <p>What almost works is to change the <code>contentsRect</code> of the view's layer. But this begins as a unit square, even though the viewable area of the image is not the whole image. So I'm not sure how I would detect that the far edge of the image is being pulled into the viewable area (which I need to avoid, since it displays by stretching the edge out to infinity, which looks, well, sub-par).</p> <p>My view currently has its <code>contentsGravity</code> set to <code>kCAGravityTopLeft</code> via Interface Builder, if that makes a difference (Is it causing the image to move?). No other options seemed to be any better, though.</p> <p>UPDATE: to be clear, I want to move the image <strong>inside</strong> the view, while keeping the view in the same spot.</p>
<p>I'd highly recommend enclosing your <code>UIImageView</code> in a <code>UIScrollView</code>. Have the <code>UIImageView</code> display the full image, and set the contentSize on the <code>UIScrollView</code> to be the same as your <code>UIImageView's</code> size. Your <code>window</code> into the image will be the size of the <code>UIScrollView</code>, and by using <code>scrollRectToVisible:animated:</code> you can pan to particular areas on the image in an animated fashion.</p> <p>If you don't want scroll bars to appear, you can set the <code>showsHorizontalScrollIndicator</code> and <code>showsVerticalScrollIndicator</code>properties to <code>NO</code>. </p> <p><code>UIScrollView</code> also provides pinch-zooming functionality, which may or may not be useful to you.</p>
increase clarity of a graph <p>I am using jfreechart for plotting graphs. The problem is that if have more entries on the X-axis, then the X-axis parameters are not visible. How should I solve that?</p>
<p>Change the scale of the graph until you can see the parameters. </p>
What are the rules for file extensions in Windows and Unix? <p>i'm currently using File::Basename fileparse to separate out a file's directory, base file name and it's extension using something like this:</p> <pre><code>my($myfile_name,$mydirectory, $file_extension) = fileparse($$rhash_params{'storage_full_path_location'},'\..{1,4}'); </code></pre> <p>But see that there's a variation where you can actually provide a array of suffixes to the function, the array would contains all the known file extension.</p> <p>So i'm trying to find a safe way to do this as i've seen that i've got some strange file names to process, i.e. file.0f1.htm, etc.</p> <h2>Question:</h2> <ol> <li>Is there a list of commonly used extension for Windows and Unix systems? But in my case it's mainly for Windows. </li> <li>And is it safe to assume that all file names in Windows should have an extension ending with three letter characters?</li> </ol> <p>And if there's an even better way to do this, please share.</p> <p>Thanks.</p> <h2>Updates:</h2> <p>So obviously i must be drunk to forgot about those other extension. :) Thus i've updated the current regex to allow from 1-4chars.</p> <p>In this case, how should i change my regex line to properly match it? Or is it an even better idea to look for all those commonly used extension from google and put them into an array to be passed to the function instead? My users are usually either students or teachers.</p>
<blockquote> <p><code>1</code>. Is there a list of commonly used extension for Windows and Unix systems? But in my case it's mainly for Windows.</p> </blockquote> <p>Yes, loads, all over the internet: <a href="http://www.google.com/search?q=common+file+extensions" rel="nofollow">http://www.google.com/search?q=common+file+extensions</a></p> <blockquote> <p><code>2</code>. And is it safe to assume that all file names in Windows should have an extension ending with three letter characters?</p> </blockquote> <p>No, it's perfectly possible to use <code>'.c'</code>, <code>'.java'</code>, etc in Windows. </p>
Does location.replace() not do a conditional get if last-modified caching is in place? <p>Here's what I'm seeing: I have a conditional-get caching policy in place (cache-control: private, must-revalidate).</p> <p>It works fine if I'm on the page, then try to hit the browser's refresh button.</p> <p>However, in another part of my site, I use location.replace(url) to go to that page... if I do that, its not makign that check and always retrieving the cached version.</p> <p>Any tips on what might be wrong here?</p>
<p>you can force an uncached version by doing <code>location.replace(url + "?tid=" + Math.random())</code></p>
Digitally sign pdfs <p>My company has a web document management application and I have been assigned to find a way to sign pdf files with the user digital certificate.</p> <p>The pdfs can go from a few kb to over 100Mb, this is over the internet so the signature <strong><em>must</em></strong> take place at the web server.</p> <p>In order to do this i have built an activeX control that asks the user to choose the certificate, then uploads it to a webpage using WebClient.UploadData sending the certificate as a byte array.</p> <p>On the web page when i'm trying to sign the pdf document i am getting an error "Key does not exist". This comes to no surprise to me because when i was using the certificate directly over an https connection after i choose the proper certificate i would be prompt for the key. This is not happening with the activeX.</p> <p>This is how i'm getting the certificate from the user:</p> <pre><code>private static X509Certificate2 PickCertificate() { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); try { store.Open(OpenFlags.ReadOnly); // pick a certificate from the store X509Certificate2 cert = X509Certificate2UI.SelectFromCollection(store.Certificates, "Title", "Message", X509SelectionFlag.SingleSelection)[0]; // show certificate details dialog X509Certificate2UI.DisplayCertificate(cert); store.Close(); return cert; } finally { store.Close(); } } </code></pre> <p>How can I ask the user to provide the key i am missing?</p>
<p>You want the user to upload their certificate's private key to the webserver so that it may sign PDFs? If so, that's fundamentally broken from a security perspective.</p> <p>I think you may have missed the point that public certificate != private key. (Most of us are sloppy and use the word "certificate" to refer to either (or both) of those things, so that's not entirely suprising). Going from memory, the CryptoAPI only has a select set of methods that will allow you to access the key. There must be an "export as PFX" method amongst those, so you could make your design work if you really, really wanted to, but there's no way I'd recommend this. (Risk of sending private keys to webserver, broken non-repudiation, etc etc).</p> <p>If you really must do the signing on the server [I don't really understand your argument, signature should not add much data to the upload], then you should probably consider a multi-tiered architecture, and a key escrow mechanism. This way you can at least minimize some of the security concerns (but you'll still lose non-repudiation... and introduce other risks. No free lunch here).</p> <p>So... you probably need to consider re-architecting your application so that PDF signature occurs on the client (in your ActiveX control), before the PDF file is uploaded. I imagine you will need a 3rd-party library for the signature step as discussed in <a href="http://stackoverflow.com/questions/378247/how-to-digitally-sign-pdf-files">this SO thread</a>.</p>
Post from one controller action to another (not redirect) <p>I have an action which I need to post forward onto another action if it meets certain conditions, but I am unable to preserve the form data when passing through to the next action.</p> <p>The receiving action accepts a FormCollection, which the sending action </p> <p>Currently, I am doing a return RedirectToAction("action","controller", form). And I can determine that the form variable has keys before it redirects (form.HasKeys() = true).</p> <p>When the action is hit however, the FormCollection is empty (form.HasKeys() = false).</p> <p>Any ideas? Is there a 'PostToAction' method that I am missing?</p> <p>FYI: I am using ASP.NET MVC Beta. Many thanks!</p> <p><strong>Edit:</strong> For those who have this problem, please look into the <a href="http://en.wikipedia.org/wiki/Post/Redirect/Get" rel="nofollow">PRG Pattern</a>. This is the actual term of what I was looking to do which also enables pretty urls.</p>
<p>I would refactor the two controllers and put the common code into a helper or into a common base class. That way the actions in the two controllers can delegate to the common code.</p>
Java: Receive a multipart HTTP response <p>I'm writing a Java client application to receive live M-JPEG video from an IP camera. The video is sent by the camera as an endless multipart HTTP message where each part is a single JPEG frame. I need to process each of these frames as they arrive, so I'm hoping there's a way to make an HTTP request that asynchronously triggers an event as each message part/video frame is received.</p> <p>Is anyone aware of any libraries that can do this? All the examples I can find on Google won't work because they use blocking calls that only parse the response and break it up into parts after the entire response has finished being received (which obviously won't work for an endless response).</p> <p>I realise I could manually break up the data into parts as it arrives by searching for the message boundary but it just feels like I would be reinventing the wheel.</p>
<p>This project: <a href="http://fmj-sf.net/" rel="nofollow">http://fmj-sf.net</a>, does have a class to parse multipart/x-mixed-replace responses: <a href="http://fmj-sf.net/doc/fmj/net/sf/fmj/media/parser/MultipartMixedReplaceParser.html" rel="nofollow">http://fmj-sf.net/doc/fmj/net/sf/fmj/media/parser/MultipartMixedReplaceParser.html</a></p> <p>Searching google code with: multipart/x-mixed-replace lang:java</p> <p>I found some other examples like: <a href="http://www.google.com/codesearch?as_q=multipart%2Fx-mixed-replace&amp;btnG=Search+Code&amp;hl=en&amp;as_lang=java&amp;as_license_restrict=i&amp;as_license=&amp;as_package=&amp;as_filename=&amp;as_case=" rel="nofollow">http://www.google.com/codesearch?as_q=multipart%2Fx-mixed-replace&amp;btnG=Search+Code&amp;hl=en&amp;as_lang=java&amp;as_license_restrict=i&amp;as_license=&amp;as_package=&amp;as_filename=&amp;as_case=</a></p> <p><a href="http://www.google.com/codesearch/p?hl=en#FCmBlvKk1MA/cambozola-0.50/src/com/charliemouse/cambozola/shared/CamStream.java&amp;q=multipart/x-mixed-replace%20lang:java" rel="nofollow">http://www.google.com/codesearch/p?hl=en#FCmBlvKk1MA/cambozola-0.50/src/com/charliemouse/cambozola/shared/CamStream.java&amp;q=multipart/x-mixed-replace%20lang:java</a></p> <p><a href="http://www.google.com/codesearch/p?hl=en#Xnnd-VJLMBY/src/Grabber.java&amp;q=multipart/x-mixed-replace%20lang:java" rel="nofollow">http://www.google.com/codesearch/p?hl=en#Xnnd-VJLMBY/src/Grabber.java&amp;q=multipart/x-mixed-replace%20lang:java</a></p>
‘Remember Me’ Login in CodeIgniter <p>How do you implement this in CodeIgniter?</p>
<p><em>(This answer was a response to the original question)</em></p> <blockquote> <p><em>How would you do this ? Or, how would you create a session with a longer expiration date than the others ?</em></p> <p>*All created sessions would use the same $config['sess_expiration'] in the config file (default: 7200 seconds), is there a way to pass a custom value ?*</p> </blockquote> <p>Extending the expiration of a session cookie isn't going to work for a "remember me" feature, since the user will lose their session cookie when they close the browser. If Code Igniter doesn't have a native "remember feature", then you'll need to write something to drop a long-life cookie which contains information which will allow an automatic login when the server sees it again.</p> <p>There's a good article on <a href="http://fishbowl.pastiche.org/2004/01/19/persistent_login_cookie_best_practice/">Persistent Login Cookie Best Practice</a>, which can be summarized as:</p> <blockquote> <ol> <li>When the user successfully logs in with Remember Me checked, a login cookie is issued in addition to the standard session management cookie.[2]</li> <li>The login cookie contains the user's username and a random number (the "token" from here on) from a suitably large space. The username and token are stored as a pair in a database table.</li> <li>When a non-logged-in user visits the site and presents a login cookie, the username and token are looked up in the database. 1. If the pair is present, the user is considered authenticated. The used token is removed from the database. A new token is generated, stored in database with the username, and issued to the user via a new login cookie. 2. If the pair is not present, the login cookie is ignored.</li> <li>Users that are only authenticated via this mechanism are not permitted to access certain protected information or functions such as changing a password, viewing personally identifying information, or spending money. To perform those operations, the user must first successfully submit a normal username/password login form.</li> <li>Since this approach allows the user to have multiple remembered logins from different browsers or computers, a mechanism is provided for the user to erase all remembered logins in a single operation.</li> </ol> </blockquote> <p>Another article which builds more security onto those ideas in <a href="http://jaspan.com/improved_persistent_login_cookie_best_practice">Improved Persistent Login Cookie Best Practice</a></p> <p>If you follow the practices in those articles, you won't go far wrong!</p>
How to change the row position of virtual mode DataGridView? <p>How to change the row position of virtual mode DataGridView?</p> <p>I am using <a href="http://en.wikipedia.org/wiki/Windows%5FForms" rel="nofollow">Windows Forms</a>.</p>
<p>You have to clear the old position and set a new one</p> <p>The collection dataGridView1.SelectedRows has the current selected Rows. Depending on the MultiSelect property of the grid you may have to loop through all the rows in the SelectedRows and mark them as unselected. If you are single selection mode, just setting the new row as selected should clear the old selection.</p> <p>To select a particular row (in this case the one at index 0) you just add the line dataGridView1.Rows[0].Selected = true;</p>
Postback destroys user controls in my GridView columns <p>I have a ASP.NET GridView that uses template columns and user controls to allow me to dynamically construct the datagrid. Now I'm implementing the event handler for inserting a row. To do that, I create an array of default values and add it to the data table which is acting as a data source. However, when my OnLoad event is fired on postback, all my template columns no longer have the user controls. My gridview ends up just being all blank with nothing in it and my button column disappears as well (which contains the add row, delete row and save buttons).</p> <p>My row add event just does this:</p> <pre><code> public void AddDataGridRow() { List&lt;object&gt; defRow = new List&lt;object&gt;(); for (int i = 0; i &lt; fieldNames.Count; i++) { defRow.Add(GetDefaultValueFromDBType(types[i])); } dt.Rows.Add(defRow); } </code></pre> <p>It is fired from a button in a user control that's implement like this:</p> <pre><code> protected void Button1_Click(object sender, EventArgs e) { ((Scoresheet)(this.Page)).AddDataGridRow(); } </code></pre> <p>My on load event does a bunch of stuff on first run to set the GridView up but I don't run that again by using the IsPostBack property to tell.</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) Initialize(); } </code></pre> <p>Anyone have any hints as to why my user controls are vanishing?</p>
<p>You have to add the controls to the grid on every page_load, not just if it's (!Postback)</p>
How do I avoid unwanted log messages on java project? <p>On my java project, I have a bunch of strings externalized on a <code>messages.properties</code> file. On its respective <code>Messages.java</code> file I had the same number of public static String-typed attributes, so I could access those externalized texts. </p> <p>Then, I implemented a method called <code>getString</code>, which receives the name of the constant as its argument and returns the wanted text. This way, there is no need to declare all the public static Strings-typed attributes inside the <code>Messages.java</code> file.</p> <p>But after doing this my log became filled with "<em>NLS unused message</em>" messages.</p> <p>Do you know if there's a way to prevent those warning messages to be logged?</p> <p>Thanks in advance.</p>
<p>Your <code>Messages</code> class - it sounds like it extends <code>org.eclipse.osgi.util.NLS</code>.</p> <p>If this is the case, it is designed to fill the requirements:</p> <ul> <li>to provide compile time checking that a message exists.</li> <li>to avoid the memory usage of a map containing both keys and values (this would be the case in a resource bundle approach).</li> <li>good i18n support.</li> </ul> <p>i.e. NLS populates the value of the <code>Message.staticVariable</code> with the value of the <code>staticVariable</code> found in messages.properties. </p> <p>The warning logging provides information about a mismatch between the <code>Messages.java</code> and the <code>messages.properties</code> file.</p> <p>Your <code>getString()</code> method sounds like it does not use any of the advantages of NLS, so as others have suggested, you may be better off using a ResourceBundle. </p>
Loop through PageField in OLAP Cube [PivotTable] <p>I'm trying to write a VBA script that will draw buttons beside the <code>PageFields</code> in a Pivot Table, these buttons will loop through the values in the <code>PageField</code>. I had this working for a regular Pivot Table, but I've been asked to adapt it for an <code>OLAP Cube</code> (External Data Source) and I can't work out how to find the values for a Member using VBA (for an OLAP Cube).</p> <p>Can anyone help?</p> <p>Previously I had the following:</p> <pre><code>Public Function Next_page(row) Dim pivTable As PivotTable Dim pgField As PivotField Set pivTable = ActiveSheet.PivotTables(1) For Each pgField In pivTable.PageFields If pgField.DataRange.row = CInt(row) Then If pgField.CurrentPage.Name = "(All)" Then If pgField.PivotItems.Count &gt; 0 Then pgField.CurrentPage = pgField.PivotItems(1).Name End If Exit Function End If For j = 1 To pgField.PivotItems.Count Step 1 If pgField.PivotItems(j) = pgField.CurrentPage.Name Then If (j &lt; pgField.PivotItems.Count) Then pgField.CurrentPage = pgField.PivotItems(j + 1).Name Exit Function End If End If Next j Exit Function End If Next End Function </code></pre> <p>But because the <code>CurrentPage</code> doesn't exist, for an <code>OLAP Cube</code> it doesn't work.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/aa140054.aspx" rel="nofollow">This MSDN Link</a> (Extending OLAP Functionality) has quite a few VBA code snippets showing how to use the pivot table API.</p>
Lisp: Need help getting correct behaviour from SBCL when converting octet stream to EUC-JP with malformed bytes <p>The following does not work in this particular case, complaining that whatever you give it is not a character.</p> <pre><code>(handler-bind ((sb-int:character-coding-error #'(lambda (c) (invoke-restart 'use-value #\?)))) (sb-ext:octets-to-string *euc-jp* :external-format :euc-jp))</code></pre> <p>Where <code>*euc-jp*</code> is a variable containing binary of EUC-JP encoded text.</p> <p>I have tried <code>#\KATAKANA_LETTER_NI</code> as well, instead of #\? and also just "". Nothing has worked so far.</p> <p>Any help would be greatly appreciated!</p> <p>EDIT: To reproduce <code>*EUC-JP*</code>, fetch <a href="http://blogs.yahoo.co.jp/akira_w0325/27287392.html" rel="nofollow">http://blogs.yahoo.co.jp/akira_w0325/27287392.html</a> using drakma.</p>
<p>There's an expression in SBCL 1.0.18's <code>mb-util.lisp</code> that looks like this:</p> <pre><code>(if code (code-char code) (decoding-error array pos (+ pos bytes) ,format ',malformed pos)) </code></pre> <p>I'm not very familiar with SBCL's internals, but this looks like a bug. The consequent returns a character, while the alternative returns a string (no matter what you give to it via <code>USE-VALUE</code>, it's always converted into a string by way of the <code>STRING</code> function; see the definition of <code>DECODING-ERROR</code> in <code>octets.lisp</code>).</p>
Source for useful EC2 AMIs <p>Using Amazon's own <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=552&amp;categoryID=187" rel="nofollow">client libraries</a> (or <a href="http://code.google.com/p/typica/" rel="nofollow">alternatives</a>), you can get listings of available pre-packaged AMIs, but the interface is definitely designed for scriptability, not readability. <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=609" rel="nofollow">Elasticfox</a> is better, but still doesn't make it easy to see what an AMI <em>does</em>, allow for user rating, etc.</p> <p>Is there a centralised place for me to easily find AMIs for specific purposes? AMIs for Apache, OpenMQ, MySQL, that sort of thing?</p>
<p>This is a <a href="http://developer.amazonwebservices.com/connect/kbcategory.jspa?categoryID=101" rel="nofollow">list</a> of shared AMIs. I am afraid that you can't automatically search the list by a keyword in the title or the description.</p>
C++ ctor question (linux) <ul> <li><p>environment: linux, userspace-application created via g++ from a couple of C++ files (result is an ELF)</p></li> <li><p>there is a problem (SIGSEGV) when traversing the constructor list </p></li> </ul> <pre> ( __CTOR_LIST__ ) </pre> <p>(note: code called via this list is a kind of system initialisation for every class, <em>not</em> the constructor-code I wrote)</p> <ul> <li>when I understand correctly every compilation unit (every .o created from a .cpp) creates one entry in</li> </ul> <pre> __CTOR_LIST__ </pre> <ul> <li><p>the problem (SIGSEGV) does not exist when I step via GDB through the program</p></li> <li><p>for debugging this I'm looking for an way to add own code code <strong>before</strong> the call of </p></li> </ul> <pre> "_do_global_ctors_aux" </pre> <p>any hints for this ?</p> <p>thanks,</p> <p>Uwe</p>
<p>There are many possible reasons of this. Ranges from that you access objects not yet created (because order of creation of objects across different translation units is undefined) which i think is quite probable in this case, and ranges to an error on your build-environment. </p> <p>To make a own function be called before other constructor function, you have a <code>constructor (priority)</code> attribute described <a href="http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#index-pointer-arguments-2151" rel="nofollow">here</a>. GCC keeps a priority for each files' constructor input section. And it links them in order of those priorities. In the linker script of my linux system, that code looks like this (output it using <code>ld -verbose</code>):</p> <pre><code> .ctors : { /* gcc uses crtbegin.o to find the start of the constructors, so we make sure it is first. Because this is a wildcard, it doesn't matter if the user does not actually link against crtbegin.o; the linker won't look for a file to match a wildcard. The wildcard also means that it doesn't matter which directory crtbegin.o is in. */ KEEP (*crtbegin.o(.ctors)) KEEP (*crtbegin?.o(.ctors)) /* We don't want to include the .ctor section from the crtend.o file until after the sorted ctors. The .ctor section from the crtend file contains the end of ctors marker and it must be last */ KEEP (*(EXCLUDE_FILE (*crtend.o *crtend?.o ) .ctors)) KEEP (*(SORT(.ctors.*))) KEEP (*(.ctors)) } </code></pre> <p>You would want to give it a low priority to make it execute before other registered ctor functions having a higher priority number. However from the looks of it, it seems like constructors having no number will be executed first. Not sure entirely. Best you give it a try. If you want to have your function called even before _do_global_ctors_aux, you have to release the original <code>_init</code> function that is normally executed when your program is loaded by the ELF loader (look into the <code>-init</code> option of ld). It's been some time since i messed with it, but i remember it has to do some intimate details of initialization, so i wouldn't try to replace it. Try using the constructor attribute i linked to. However, be very careful. Your code will possibly be executed before other important objects like <code>cout</code> are constructed. </p> <p><strong>Update</strong>: I did a test, and it actually executes ctor functions in reverse. So ctor functions that are linked first are executed later. This code happens to be in crtstuff.c of the gcc source code:</p> <pre><code> func_ptr *p; for (p = __CTOR_END__ - 1; *p != (func_ptr) -1; p--) (*p) (); </code></pre> <p>I made a little test:</p> <pre><code>void dothat() { } struct f { f() { dothat(); } } f_; void doit() __attribute__((constructor (0))); void doit() { } int main() { } </code></pre> <p>Linking with <code>--print-map</code> yields, among others, this output:</p> <pre><code>.ctors 0x080494f4 0x10 *crtbegin.o(.ctors) .ctors 0x080494f4 0x4 /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/crtbegin.o *crtbegin?.o(.ctors) *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) .ctors 0x080494f8 0x4 /tmp/ccyzWBjs.o *(SORT(.ctors.*)) .ctors.65535 0x080494fc 0x4 /tmp/ccyzWBjs.o *(.ctors) .ctors 0x08049500 0x4 /usr/lib/gcc/i686-pc-linux-gnu/4.3.2/crtend.o </code></pre> <p>Notice how <code>.ctors.65535</code> is the section we implicitly created by our attribute priority <code>0</code>. Now, if you give it that priority, gcc warns and it's totally right :p</p> <blockquote> <p>test.cpp:7: warning: constructor priorities from 0 to 100 are reserved for the implementation</p> </blockquote> <p>I tested it by breaking on <code>doit</code> and <code>dothat</code>, and it called them in the order we expect. Have fun!</p>
Why do some URLs contain both numeric id and name? <p>I am wondering why the link to profile looks like: </p> <pre><code>http://stackoverflow.com/users/ID/NAME </code></pre> <p>not simply:</p> <pre><code>http://stackoverflow.com/users/ID </code></pre> <p>or even better:</p> <pre><code>http://stackoverflow.com/users/NAME </code></pre> <p>Can there be couple users with the same name? Or can one user have many names?</p>
<p>All SO-URLs are of the form id/description where the ID is unique and the description is optional. So <a href="http://stackoverflow.com/users/12890/arne.burmeister"><code>/users/12890/arne-burmeister</code></a> is the same as <a href="http://stackoverflow.com/users/12890/huhu"><code>/users/12890/huhu</code></a> and <a href="http://stackoverflow.com/questions/420380/why-does-the-link-to-the-user-profile-have-both-id-and-name"><code>/questions/420380/why-does-the-link-to-the-user-profile-have-both-id-and-name</code></a> is the same as <a href="http://stackoverflow.com/questions/420380/foo"><code>/questions/420380/foo</code></a>. The retrieval just uses the ID, but it is much better for google ranking, when the user/question/what-ever-should-be-found occurs in the URL (also for humans this is much more descriptive ;-).</p> <p>By the way, retrieval by ID is faster than by such a large text string. And of course, the URL remains valid if someone changes their user name or the question.</p>
How can I substitute regexp matches and map the substitutions in Perl? <p>I.e.:</p> <pre><code>echo H#97llo | MagicPerlCommand </code></pre> <p>Stdout:</p> <pre><code>Hallo </code></pre> <p>were MagicPerlCommand is something like </p> <pre><code>perl -pnle "s/#(\d+)/chr(\1)/ge" </code></pre> <p>(but that doesn't work).</p>
<p>Change <code>\1</code> to <code>$1</code> in your MagicPerlCommand. The <code>\digit</code> backreference style doesn't t work when the replacement expression is evaluated (i.e. <code>s///e</code>).</p> <p>That worked for me on Windows and Linux.</p>
Why did the designers of ColdFusion decide to index arrays from 1 rather than 0? <p>I'm just curious about this really, does anyone know why they broke convention on this one? </p> <p>Thanks, Ciaran</p>
<p>@Cory: You'd be surprised to know who lurking on StackOverflow. :-)</p> <p>You are very much right. The original design of CFML was to allow non-programmers to build complex web applications. ColdFusion\CFML was the first language designed specifically for building web applications. Back in 1995 the web was mostly static HTML and your typical 'web developer' wasn't doing too much programming. The language itself was designed to be as simple as possible which is why it's still one of the fastest/easiest languages to learn.</p> <p>It can lead to a bit of confusion, especially when ColdFusion code interacts directly with Java or .NET. However, it's just become one of those 'quirks'. The decision was revisited back in 2000/2001 when CF was rebuilt as a Java EE application, but backward compatibility prevented the change.</p>
SQL 2005: should I roll my own log shipping? <p>I'm looking into using log shipping for disaster recovery and I'm getting mixed messages about whether to use the built-in stuff or roll my own. Which do you recommend, please, and if you favour rolling your own what's wrong with the built-in stuff? If I'm going to reinvent the wheel I don't want to make the same mistakes! (We have the Workgroup edition.) Thanks in advance.</p>
<p>There's really two parts to your question:</p> <ol> <li><p>Is native log shipping good enough?</p></li> <li><p>If not, whose log shipping should I use?</p></li> </ol> <p>Here's my two cents, but like you're already discovering, a lot of this is based on opinions.</p> <p>About the first question - native log shipping is fine for small implementations - say, 1-2 servers, a handful of databases, and a full time DBA. In environments like this, the native log shipping's lack of monitoring, alerting, and management isn't a problem. If it breaks, you don't sweat bullets because it's relatively easy to repair. When would it break? For example, if someone accidentally deletes the transaction log backup file before it's restored on the disaster recovery server. (Happens all the time with automated processes.)</p> <p>When you grow beyond a couple of servers, the lack of management automation starts to become a problem. You want better automated email alerting, alerts when the log shipping gets more than X minutes/hours behind, alerts when the file copying is taking too long, easier handling of multiple secondary servers, etc. That's when people turn to alternate solutions.</p> <p>About the second question - I'll put it this way. I work for Quest Software, the makers of LiteSpeed, a SQL Server backup &amp; recovery product. I regularly talk to database administrators who use our product and other products like Idera SQLSafe and Red Gate SQL Backup to make their backup management easier. We build GUI tools to automate the log shipping process, give you a nice graphical dashboard showing exactly where your bottlenecks are, and help make sure your butt is covered when your primary datacenter goes down. We sell a lot of licenses. :-)</p> <p>If you roll your own scripts - and you certainly can - you will be completely alone when your datacenter goes down. You won't have a support line to call, you won't have tools to help you, and you won't be able to tell your coworkers, "Open this GUI and click here to fail over." You'll be trying to walk them through T-SQL scripts in the middle of a disaster. Expert DBAs who have a lot of time on their hands sometimes prefer writing their own scripts, and it does give you a lot of control, but you have to make sure you've got enough time to build them and test them before you bank your job on it.</p>
Guidelines for Using Brushes and Pens <p>How expensive is it to create gdi brushes and pens? Should I create them on an add needed basis and wrap them in a using so they are disposed quickly, or should I create a static class similar to System.Drawing.Brushes class?</p>
<p>IMO, they're efficient enough that you should usually not create long-lived instances that are used over several method calls, but inefficient enough that you should create each one only once within a particular method, instead of creating a new one each time you need to draw something.</p> <p>In other words, don't store a custom brush in your class that you use to paint your text on every <code>OnPaint</code> call, but also don't create a new brush for every line of text you draw within that OnPaint call, either.</p>
How to store IPv6-compatible address in a relational database <p>How do I do that?</p> <p>Right now, IPv6 will not be used, but I need to design the application to make it IPv6-ready. It is necessary to store IP addresses and CIDR blocks (also BGP NLRI, but this is another story) in a MySQL database. I've alway used an INT for IPv4 + a TINYINT for masklen, but IPv6 is 128 bit.</p> <p>What approach will be best for that? <code>2xBIGINT</code>? <code>CHAR(16)</code> for binary storage? <code>CHAR(39)</code> for text storage? <code>8xSMALLINT</code> in a dedicated table?</p> <p>What would you recommend?</p>
<p>I'm not sure which is the <em>right</em> answer for MySQL given that it doesn't yet support IPv6 address formats natively (although whilst "<a href="http://dev.mysql.com/worklog/task/?id=798" rel="nofollow">WL#798: MySQL IPv6 support</a>" suggests that it was going to be in MySQL v6.0, current documentation doesn't back that up).</p> <p>However of those you've proposed I'd suggest going for 2 * BIGINT, but make sure they're UNSIGNED. There's a sort of a natural split at the /64 address boundary in IPv6 (since a /64 is the smallest netblock size) which would align nicely with that.</p>
Primary servers in capistrano <p>I have a task in capistrano wherein I want just a single line to run only if the server is a marked as primary. Is there a variable or method that I can reference inside a task? 'primary?' or 'primary' doesn't seem to work.</p> <p>I've also tried something akin to the following:</p> <pre><code>after "deploy", "task1" after "deploy", "task2" after "deploy", "task3" task :task1, :roles =&gt; :app do *code* end task :task2, :roles =&gt; :app, :only =&gt; {:primary =&gt; true} do *code for just primary server* end task :task3, :roles =&gt; :app do *more code* end </code></pre> <p>But even this doesn't seem to work (all three tasks get run on every server).</p> <p>I've been working on this on and off for a few days and I'm having no luck with my searches. Thoughts?</p>
<p>I've solved the issue, but it wasn't pretty. The thing that I've found is that you need to use the 'primary => true' on a per-task basis. Looking at the code, it appears that capistrano generates a list of the servers that the task will be run on before the task is run.</p>
Superscript underline in IE <p>I'm going to be brief because I'm short on time, so I apologize if this isn't as detailed as I'd like it to be.</p> <p>I have some code:</p> <pre><code>print("&lt;a href='#'&gt;Some text&lt;sup&gt;&amp;reg;&lt;/sup&gt; some more text&lt;/a&gt;"); </code></pre> <p>In FF, this works like I would like, the link as a whole is underlined. However in IE, the link is underlined except under the &reg; where it looks like a symbol above a hyphen and is rather ridiculous looking. </p> <p>I've tried several suggestions I found on Google, but none of them are very helpful in achieving the desired effect. Adding a border to the bottom is not an option unfortunately. So far the best solution is to break the underline completely at the sup tag with CSS which still leaves it working fine in FF while still looking less silly in IE.</p> <p>If anyone could help with this it would be most appreciated, I'd rather not go through the site removing <code>&lt;sup&gt;</code> tags as I've been told I will have to do should I not solve this dilemma. </p> <p>UPDATE: Went with the sup {"text-decoration:none" } solution, it'll do for now. There are reg marks everywhere, so the whole site would've had to have been updated, which was more trouble than it was worth we all decided. Thanks to those who replied.</p>
<p>The <code>&lt;sup&gt;</code> tag isn't great for things like trademark and reg symbols.</p> <p>I prefer doing it with css:</p> <pre><code>&lt;span style='font-size:75%;vertical-align:super;text-decoration:none'&gt;&amp;reg&lt;/span&gt; </code></pre> <p>If you can set up a .reg class:</p> <pre><code>.reg { font-size:75%; vertical-align:super; text-decoration:none } </code></pre> <p>For:</p> <pre><code>&lt;span class='reg'&gt;&amp;reg;&lt;/span&gt; </code></pre>
Initialize multidimensional array <pre><code> Checkbox[,] checkArray = new Checkbox[2, 3]{{checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}}; </code></pre> <p>I am getting error . How do I initialize it? </p>
<p>OK, I think I see what's happening here. You're trying to initialize an array at a class level using this syntax, and one of the checkboxes is also a class level variable? Am I correct? </p> <p>You can't do that. You can only use static variables at that point. You need to move the init code into the constructor. At the class level do this:</p> <pre><code> CheckBox[,] checkArray; </code></pre> <p>Then in your constructor:</p> <pre><code>public Form1() { InitializeComponent(); checkArray = new CheckBox[2, 3] { { checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}}; } </code></pre>
Equivalent of java's ConcurrentHashMap in C#? <p>is there anything?</p>
<p>There is a generic Dictionary class for implementing associative arrays (aka hashtables). Recently MS came out with the ConcurrentDictionary class: <a href="http://msdn.microsoft.com/en-us/library/dd287191.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd287191.aspx</a> which is probably what you want. It's .Net 4+ though. :( </p>
How to convert a string to RegularTimePeriod in java? <p>I am using Jfreechart. I have the code like this:</p> <pre><code>TimeSeries t1 = new TimeSeries("EUR/GBP"); t1.add(new Day(4, MonthConstants.JANUARY, 2001), new Double(1.5807)); </code></pre> <p>But I get <code>String</code> from my SQL query. TimeSeries accepts only <code>RegularTimePeriod</code> or <code>TimeSeriesDataItem</code>.</p> <p>Please let me know how to convert a <code>String</code> into <code>RegularTimePeriod</code>.</p> <p>Thanks in Advance.</p>
<p>First you can get a Date object by parsing your mysql date string using a SimpleDateFormat, then create your RegularTimePeriod using the constructor with a Date arg.</p> <p>Basically (assuming mysqlDateStr is your string from mysql query) :</p> <pre><code>SimpleDateFormat standardDateFormat = new SimpleDateFormat("yyyy-MM-dd"); // (Define your formatter only once, then reuse) Date myDate = standardDateFormat.parse(mysqlDateStr); // (you may want to catch a ParseException) t1.add(new Day(myDate), new Double(1.5807)); </code></pre>
Why does IE7 when clearing a float result in a margin bug? <p>I have a very simple HTML page (validates as XHTML 1.0 Strict):</p> <pre><code>&lt;div class="news-result"&gt; &lt;h2&gt;&lt;a href="#"&gt;Title&lt;/a&gt;&lt;/h2&gt;&lt;span class="date"&gt;(1-1-2009)&lt;/span&gt; &lt;p&gt;Some text...&lt;/p&gt; &lt;/div&gt; </code></pre> <p>with the following CSS:</p> <pre><code>.news-result { overflow: hidden; padding: 30px 0 20px; } .news-result h2 { float: left; margin: 0 10px 0 0; } .news-result span.date { margin: 1px 0 0; float : left; } .news-result p { padding: 3px 0 0 0; clear: left; } </code></pre> <p>Rendering this page in IE6 or FF3 render perfectly (the title and the date on a single line, followed by the paragraph). In IE7 however, there is a large space between the title and date, and the paragraph.</p> <p>We have a simple reset that clears every margin and padding on every element.</p> <p>Dropping the float on the date element fixes this problem, as does setting <code>zoom: 1</code> on the paragraph or removing <code>overflow: hidden</code> on the container, but all are not ideal. Why does a float followed by a paragraph trigger this additional top margin, only on IE7?</p>
<p>Can I assume that you have a doc-type?</p> <p>However, change the h2 and span to display: inline; should also clear up your issue. </p> <p>Edit --- adding hasLayout</p> <p>Understanding that inline isn't always an option, here's an <a href="http://www.search-this.com/2007/09/05/lets-be-clear-about-this/" rel="nofollow">article explaining what's going on</a>.</p> <p>Essentially you have to give the <code>&lt;p></code> hasLayout. There are many ways to do this, and I don't like using <code>&lt;div class="clearall">&lt;/div></code> and prefer to use <code>overflow: hidden;</code> or <code>zoom: 1;</code></p>
python setup.py develop not updating easy_install.pth <p>According to <a href="http://peak.telecommunity.com/DevCenter/setuptools#development-mode" rel="nofollow">setuptools</a> documentation, setup.py develop is supposed to create the egg-link file and update easy_install.pth when installing into site-packages folder. However, in my case it's only creating the egg-link file. How does setuptools decide if it needs to update easy_install.pth?</p> <p>Some more info: It works when I have setuptools 0.6c7 installed as a folder under site-packages. But when I use setuptools 0.6c9 installed as a zipped egg, it does not work.</p>
<p>Reinstall setuptools with the command <code>easy_install --always-unzip --upgrade setuptools</code>. If that fixes it then the zipping was the problem.</p>
Is it possible to run custom actions during uninstall using InstallShield 2009 <p>I need to run a custom action during uninstallation of a ManagedCode which is a part of the installation (Before it is removed in the uninstall process) Is it possible in Install Shield 2009?</p>
<p>Yes you can run a ManagedCode custom action as part of the uninstall. You just need to sequences it in the Install Exec Sequence with a condition of REMOVE="ALL". InstallShield is just a wrapper around Microsoft's MSI technology, so many times it is best to go the MSDN for help understanding what you want to do. For example this entry should help you schedule your action, <a href="http://msdn.microsoft.com/en-us/library/aa371626(VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa371626(VS.85).aspx</a></p>
How do I find the caller of a method using stacktrace or reflection? <p>I need to find the caller of a method. Is it possible using stacktrace or reflection?</p>
<pre><code>StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace() </code></pre> <p>According to the Javadocs:</p> <blockquote> <p>The last element of the array represents the bottom of the stack, which is the least recent method invocation in the sequence. </p> </blockquote> <p>A <code>StackTraceElement</code> has <code>getClassName()</code>, <code>getFileName()</code>, <code>getLineNumber()</code> and <code>getMethodName()</code>.</p> <p>You will have to experiment to determine which index you want (probably <code>stackTraceElements[1]</code> or <code>[2]</code>).</p>
Access Non-Public members of a GridViewCommandEventArgs object <p>I have a gridview on my aspx page set up the OnRowCommand event using a series of ASP.NET LinkButton object to handle the logic using the CommandName property. I need to access the GridViewRow.RowIndex to retrieve values from the selected row and notice it is a non-public members of the GridViewCommandEventArgs object while debugging the application</p> <p>Is there a way I can access this property of is theere a better implementation?</p> <p>Here is my source code:</p> <p>aspx page:</p> <pre><code>&lt;asp:GridView ID="MyGridView" runat="server" OnRowCommand="MyGirdView_OnRowCommand"&gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton id="MyLinkButton" runat="server" CommandName="MyCommand" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>code behind</p> <pre><code>protected void MyGirdView_OnRowCommand(object sender, GridViewCommandEventArgs e) { //need to access row index here.... } </code></pre> <p><b>UPDATE:</b><br /> @brendan - I got the following compilation error on the following line of code:</p> <blockquote> <p>"Cannot convert type 'System.Web.UI.WebControls.GridViewCommandEventArgs' to 'System.Web.UI.WebControls.LinkButton'"</p> </blockquote> <pre><code>LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource); </code></pre> <p>I slightly modified the code and the following solution worked:</p> <pre><code>LinkButton lb = e.CommandSource as LinkButton; GridViewRow gvr = lb.Parent.Parent as GridViewRow; int gvr = gvr.RowIndex; </code></pre>
<p>Not the cleanest thing in the world but this is how I've done it in the past. Usually I'll make it all one line but I'll break it down here so it's more clear.</p> <pre><code>LinkButton lb = (LinkButton) ((GridViewCommandEventArgs)e.CommandSource); GridViewRow gr = (GridViewRow) lb.Parent.Parent; var id = gr.RowIndex; </code></pre> <p>Basically you get your button and move up the chain from button to cell, from cell to row.</p> <p>Here is the one row version:</p> <pre><code> var id = ((GridViewRow)((LinkButton)((GridViewCommandEventArgs)e).CommandSource).Parent.Parent).RowIndex; </code></pre>
What are some best practices to support multiple resolutions in a web application? <p>What are some best practices on enabling a web application to support multiple resolutions? Specifically resolutions that are wide-screen vs. normal aspect ratio.</p> <p>It doesn't seem like there is an easy answer - other than simply supporting a few fixed resolutions and using some absolute positioning to get the layout to work correctly.</p> <p>This of course gets even more difficult to make it cross browser.</p> <p>Does anyone have any good resources of this problem?</p>
<p>You can always try to use a <em>liquid layout</em> structure where the width of your elements are scaled proportionate to how wide their browser window is.</p> <p>here is a good article explaining different layouts including liquid layout.</p> <p><a href="http://www.maxdesign.com.au/presentation/liquid/" rel="nofollow">http://www.maxdesign.com.au/presentation/liquid/</a></p> <p>PS. the above mentioned site (maxdesign.com.au) is using liquid layout itself, so try and change the size of your browser when reading the article.</p>
Is endian conversion required for wchar_t data? <p>In C/C++, if a multi-byte wide character (wchar_t) value is transmitted from a big-endian system to a little-endian system (or vice-versa), will it come out the same value on the other side? Or will the bytes need to be swapped?</p>
<p>Yes you will need to swap them.<br> The bytes will be retrieved from the transport in the same order they were put in. Just at the other end the ordering of these bytes has a different meaning. So you need to convert them to the correct endian-ness (is that a word?).</p> <p>The tried and true method is to convert to network byte order before transport. Then convert back to host specific byte order (from network byte order) on receipt.</p> <p>A set of function to help with endian conversion:</p> <pre><code>ntohs Convert a 16-bit quantity from network byte order to host byte order ntohl Convert a 32-bit quantity from network byte order to host byte order htons Convert a 16-bit quantity from host byte order to network byte order htonl Convert a 32-bit quantity from host byte order to network byte order </code></pre> <p>Just to add another note of caution.<br> Different systems use different size for wchar_t so do not assume sizeof(wchar_t) == 2.</p> <p>Additionally each host may use a different representational format for wchar_t.<br> To help deal with this most systems convert the text to a known format for transport (UTF-8 or UTF-16 are good choices). The convert the text back to the host specific format at the other end.</p> <p>You could look at IBM's icu this has all this functionality. </p>
Is a glossy or matte LCD screen better for long coding sessions? <p>I'm looking at getting a new LCD monitor, but I'm concerned that a glossy monitor might cause more eye strain after a long day of work. I typically spend a lot of time in front of my monitor, so eye strain is definitely something I have thought about. Do you prefer the matte or glossy LCD screens and why?</p>
<p>Matte, because you get less reflections on it, which is good if your workplace is bright. I've worked with both, but especially if you have bright objects around your monitor, or windows at the side, you'll really want to have a matte one.</p> <p>Constantly having reflections in it is really annoying, and hurts the readability in the long run.</p>
How do you put a gradient background on ASP.NET menu items? <p>The boss wants the master page's menu to look nicer. I generated my gradient file with one of the tools available on the net, no problem there..</p> <p>I tried to make a CSS class for each menu item but when I use the background-image directive and the style builder, I get a line like:</p> <pre><code>background-image: url('file:///C:/Documents and Settings/Username/My Documents/Visual Studio 2008/WebSites/ThisSite/Images/Gradient.png') </code></pre> <p>...when what I <em>want</em> is</p> <pre><code>background-image: url('~/Images/Gradient.png') </code></pre> <p>The first url will, of course, only work when I'm debugging on my local machine - deploy this and I'm hosed. So many other ASP.NET objects work with "~/" to indicate the top-level directory of the website but my css file doesn't like it and I can't set a background image for the menu control or the menu items - seems like a GLARING omission when I can do it to so many other controls.</p> <p>What am I missing?</p>
<p>The url in your CSS needs to be an absolute (or relative) url and not use the tilde mapping as it is not a server-side component.</p> <pre><code> background-image: url( "/images/menu.jpg" ); </code></pre>
3ds max object to opengl <p>I am trying to assemble a scene in opengl, using already made objects. The problem is that the object are in .max format and have no external textures. How could I import my objects in opengl, without retexturing them. I am thinking about exporting them to 3ds and using a 3ds file loader. Could you recommend one, and of course it has to work only with the 3ds file itself, no external texture files.</p> <hr> <p>3ds max already allows me to export the file to obj. I have an object that has no external texture file, but it is already fully colored as a 3ds file. Is there any way to import in opengl and have the same colors, for the trunk, leaves?</p>
<p>You might want to check out <a href="http://www.lib3ds.org/">lib3ds</a> which will parse the 3ds binary format for you and give you access to all of the objects properties. I think Autodesk also has their own toolkit for doing this.</p>
How to copy a few chars from a char[] to a char* in C? <p>Yo!</p> <p>I'm trying to copy a few chars from a char[] to a char*. I just want the chars from index 6 to (message length - 9).</p> <p>Maybe the code example will explain my problem more:</p> <pre><code>char buffer[512] = "GET /testfile.htm HTTP/1.0"; char* filename; // I want *filename to hold only "/testfile.htm" msgLen = recv(connecting_socket, buffer, 512, 0); strncpy(filename, buffer+5, msgLen-9); </code></pre> <p>Any response would help alot!</p>
<p>I assume you meant...</p> <pre><code>strncpy(filename, buffer+5, msgLen-9); </code></pre> <p>The problem is you haven't allocated any memory to hold the characters you're copying. "filename" is a pointer, but it doesn't point at anything.</p> <p>Either just declare</p> <pre><code>char filename[512]; </code></pre> <p>or malloc some memory for the new name (and don't forget to free() it...)</p> <p>There are a few problems with the use of strncpy() in your code. </p> <ul> <li>buffer+5 points to the sixth character in string (the "T"), while you said you wanted the backslash. </li> <li>The last parameter is the maximum number of bytes to copy, so should probably be msglen-13.</li> <li>strncpy() won't null terminate the copied string, so you need to do that manually.</li> <li><p>Also, from a readabilty perspective, I prefer</p> <p>strncpy(filename, &amp;buffer[4], msgLen-(9 + 4));</p></li> </ul> <p>&amp;buffer[5] is the address of the character at the fifth position in the array. That's a personal thing, though.</p> <p>Also, worth pointing out that the result of "recv" could be one byte or 512 bytes. It won't just read a line. You should really loop calling recv until you have a complete line to work with.</p>
XML Deserialization - convert attribute value into class automatically (.net) <p>(vb.net/c#/etc)</p> <p>I am having trouble figuring out how to do a bit of deserialization magic. Currently the standard deserialization works fine, including the enums, but <em>now</em> I want to convert an attribute into a class. Oh! what was I <em>thinking</em>!</p> <p>My xml looks a bit like this:</p> <pre><code>.... &lt;review user="..." version="2.2"&gt;...&lt;/review&gt; </code></pre> <p>And this for my property/class:</p> <pre><code>[XmlAttribute("version")] public MyVersion Version { get; set; } class MyVersion { // equality overloaded // can ctype() from string to MyVersion // constructor that takes a single string, etc } </code></pre> <p>How can I help the serializer along, so that it can automatically deserialize my string property into this class? Do I need to modify the MyVersion class in some way, or change the definition of the property?</p> <ul> <li>I do <strong>not</strong> want to have to override any methods like OnDeserialized, etc. It is not worth it for this project.</li> </ul> <p>If this can't be done with the default xml deserializer, then that would be good enough to know. There are lots of things it isn't good for, so I won't be surprised.</p> <p>Thanks!</p>
<p>This is not supported in a declarative way. You will have to implement IXmlSerializable on the parent class (the one that is serialized to an element) and perform the conversion between the string and the MyValue type manually.</p>