input
stringlengths
51
42.3k
output
stringlengths
18
55k
Need tips on how to prioritize and schedule a bunch of work items <p>It took me some time, but I've finally managed to write down all the tasks that need to go into Version 1.0 of the software product I'm working on. </p> <p>The list is almost 1000 items long.</p> <p>We are a 3-person team, and we've somehow managed to get this far using MindMeister, Google Docs, @todos in the code etc. Now, I have everything neatly grouped by feature, but how do I prioritize all this and turn it into a schedule?</p> <p>Any advice would be greatly appreciated - I'm not looking for software recommendations, however - I'm seeking advice on how to take this enormous bag of tasks - ranging from bug-fixes to application modules - and find out in what order I should do them.</p>
<p>Prioritize ruthlessly. 1000 action items is a lot, and the odds are that as you go you'll modify some, toss others, and add new ones. Your list will not survive the things you learn by actually building the software, and if you don't do the most important stuff first, you'll end up with a mess.</p> <p>For every item or feature, you have to answer the question: Can the product be at all usable or useful without this? If yes, it can wait; everything else goes to the head of the queue.</p> <p>After that, I like to group milestones by focus: I'll do a features milestone (or multiple ones if there are natural small clusters of features), a UI milestone where I'll focus on AJAX/rich client interactivity, a performance milestone where I profile and do database &amp; server tuning, etc. Or break them up some other way - but definitely break them up. Work in smaller bites with specific focus for each iteration, and make sure each iteration is solid before moving on.</p>
Which C++ Library for CGI Programming? <p>I'm looking at doing some work (for fun) in a compiled language to run some simple tests and benchmarks against php.</p> <p>Basically I'd like to see what other people use for C++ CGI programming. (Including backend database, like mysql++ or something else)</p>
<p>I'm not sure exactly what you're looking for, but there is a C++ web framework called wt (pronounced "witty"). It's been kept pretty much up to date and if you want robust C++ server-side code, this is probably what you're looking for.</p> <p>You can check it out and read more at the <a href="http://www.webtoolkit.eu/wt/">wt homepage</a>.</p> <p>P.S. You may have some trouble installing wt if you don't have experience with *nix or C++ libraries. There are walkthroughs but since frameworks like these are the road less traveled, expect to hit a few bumps.</p>
What's the best way to expose multiple objects to a view in ASP.NET MVC? <p>I'm kind of new to ASP.NET MVC and to the MVC pattern in general but I'm really digging the concept and the rapidity with which I can compose an app. One thing that I'm struggling with is how to expose more than one object to a view. I use a lot of strongly typed views, which works well but what if my view relies on more than one object? Right now I'm doing something pretty hacky and passing a Dictionary to the view and then just keying the different objects. Is there a better pattern for this?</p>
<p>You have two primary options and either could work well depending on your application.</p> <p>1) Just put objects into the ViewData collecion. This works well if you have lots of different controllers that pass different data to different views. It also depends on how much boxing/unboxing you want from object as you cast objects to their correct types. This option is more flexible, but less type-safe and possibly more fragile.</p> <p>2) Create strongly-typed objects that contain other strongly-typed objects useful to a set of views. This works well if you tend to pass the same data to most of your views and you have fewer controllers.</p> <p>You could also consider passing an object that exposes an interface that can acquire different model objects (kind of a locator class), but that probably causes more problems than it does fix them.</p>
Is this a bug with PHP array accessing? <p>I ran into this bug where an element of an array, if its index is the string "0", is inaccessible. </p> <p>It's not a bug with unserialize, either, as this occurred in my code without invoking it.</p> <pre><code>$arr = unserialize('a:1:{s:1:"0";i:5;}'); var_dump($arr["0"]); //should be 5, but is NULL var_dump($arr[0]); //maybe this would work? no. NULL </code></pre> <p>Am I doing something wrong here? How do I access this element of the array?</p>
<p>Yes, it looks as though it is a bug, related to PHPs automatic conversion of strings to integers. More information is available here: <a href="http://bugs.php.net/bug.php?id=43614" rel="nofollow">http://bugs.php.net/bug.php?id=43614</a></p> <pre><code>var_dump( $arr ); // =&gt; array(1) { ["0"]=&gt; int(5) } $arr2["0"]=5; var_dump($arr2); // =&gt; array(1) { [0]=&gt; int(5) } print serialize($arr2); // a:1:{i:0;i:5;} </code></pre> <p>So it seems that older versions of PHP5 don't perform the string index to integer index conversion in unserialize.</p> <p>This bug was reported in PHP 5.2.5, and is fixed in PHP 5.2.6 (see <a href="http://www.php.net/ChangeLog-5.php#5.2.6" rel="nofollow">http://www.php.net/ChangeLog-5.php#5.2.6</a>).</p>
Can SQL Server Express be used to effectively administrate a SQL Server Standard/Enterprise installation? <p>We have a number of MS SQL Server 2005 installations (both Standard and Enterprise editions) on our webservers. From time to time I need to administrate them from home. Right now I'm using Remote Desktop to connect to my work machine, but I'd prefer to install SQL Server Management Studio on my home machine so that I can work more efficiently. I don't have a spare license, so I was wondering... if I installed MS SQL Server 2005 Express on my home machine, could I use it to effectively administrate the higher-end installations on our servers?</p>
<p>See this question:<br /> <a href="http://stackoverflow.com/questions/117347/whats-the-difference-between-sql-server-management-studio-and-the-express-versi">http://stackoverflow.com/questions/117347/whats-the-difference-between-sql-server-management-studio-and-the-express-versi</a></p> <p>Also, if you have any trouble doing anything from Managment Studio Express, there are third-party tools out there that have no trouble connecting to SQL Server.</p> <p>Personally, I've noticed a few things missing out of the box:</p> <ul> <li>Import/Export</li> <li>Activity Monitor</li> <li>Job monitor</li> </ul> <p>However, the question I linked to indicated you may be able to restore most of that for use when you connect to a full sql server edition.</p>
How safe is Greasemonkey? <p>I've never actually used greasemonkey, but I was considering using it. Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be? Can they steal my passwords? Look at my private data? Do things I didn't want to do? How safe is Greasemonkey?</p> <p>Thanks</p>
<p><em>Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be?</em></p> <p>It's as safe as you allow it to be - but you aren't very clear, so let's look at it from a few perspectives:</p> <h2>Web Developer</h2> <p>Greasemonkey can't do anything to your website that a person with telnet can't already do to your website. It automates things a bit, but other than that if greasemonkey is a security hole, then your website design is flawed - not greasemonkey.</p> <h2>Internet user with Greasemonkey loaded</h2> <p>Like anything else you load on your system, greasemonkey can be used against you. Don't load scripts onto your system unless you trust the source (in both meanings of the term 'source'). It's fairly limited and sandboxed, but that doesn't mean it's safe, merely that it's harder for someone to do something nefarious.</p> <h2>Internet user without Greasemonkey</h2> <p>If you do not load greasemonkey or any of its scripts, it cannot affect you in any way. Greasemonkey does not alter the websites you visit unless you've loaded it on your system.</p> <h2>Greasemonkey developer</h2> <p>There's not much you can do beyond what can already be done with XUL and javascript, but it is possible to trash your mozilla and/or firefox profile, and possibly other parts of your system. Unlikely, difficult to do on purpose or maliciously, but it's not a bulletproof utility. <em>Develop responsibly.</em></p>
Profiling Qt application that uses plugins <p>I have a medium sized application written in c++ using Qt. I wanted to profile things to see where my least performant code was so I compiled everything with <code>-pg</code>.</p> <p>However, my application makes use of a <em>lot</em> of plugins using the QTPlugin mechanism (boils down to a dlopen and a dlsym of a instance object per plugin). I've noticed that gprof doesn't seem to include functions from plugins.</p> <p>Yes, the plugins are also compiled with <code>-pg</code> and all that. Is there anything special I have to do get everything profiled? Or am I missing something simple?</p>
<p>If you can use it, I think <a href="http://valgrind.org/" rel="nofollow">Valgrind's</a> callgrind only needs debug symbols (-g) to profile code. I'm not sure if it works with dynamically linked objects, though.</p>
Is there a good NumPy clone for Jython? <p>I'm a relatively new convert to Python. I've written some code to grab/graph data from various sources to automate some weekly reports and forecasts. I've been intrigued by the Jython concept, and would like to port some Python code that I've written to Jython. In order to do this quickly, I need a NumPy clone for Jython (or Java). Is there anything like this out there?</p>
<p>I can't find anything that's a clone of numpy, but there's a long list of Java numerics packages <a href="http://math.nist.gov/javanumerics/">here</a> - these should all be usable from Jython. Which one meets your requirements depends on what you're doing with numpy, I guess.</p>
Is Flex ready for prime time? <p>I'm working on a project that currently has zero users but we would like to scale up to potentially hundreds. Currently we are running on a MySQL database with AMFPHP interacting with Flex. We used Flex because of its robust graphic features (important to this project) and because the initial developer (not me) already knew ActionScript. We are currently using AIR but might switch to web-based Flash at some point.</p> <p>My questions are:</p> <ol> <li>Is Flex a good tool for a project like this?</li> <li>What are the main limitations of Flex that we might encounter?</li> <li>What are other development platforms we might want to consider?</li> </ol> <p>Thanks. - Dave</p>
<p>Short answer, Yes. There are already many prime-time Apps using Flex as their UI development platform. If you go to the Adobe site they showcase quite a few.</p> <p>Speaking personally, I chose Flex for two reasons, first was that, although you probably can do much of what Flex does in HTML or with an appropriate toolkit, Flex is designed for attractive and compelling user experience and has available all of Flash. Plus the development environment and available widgets make it easy and fun to program. I don't want to spark a religious war about HTML vs. Flex, so I'll leave that there - it works for me and my application and customers.</p> <p>Second, and more important, was that it balances the processing load more towards the client which means my server architecture can be optimised just for serving the content and persisting the data. Most of my business logic has migrated across to the client. Having spent many years in classical architectures I think this is a huge step forward, but I can already her a chorus of disagreement about that too.</p> <p>My word of caution about Flex comes from needing to adopt the right architecture for your client code. It is pretty easy to create a huge and badly performing app with Flex if you get that wrong. Make everything event driven and apparently asynchronous and you should be OK ('apparently' because the Flash player is single threaded). And that is downside 1, the single threaded Flash player sometimes causes issues.</p> <p>Downside 2 is perhaps more serious and that is locked down desktops in corporate environments. Quite often your target audience won't have administrative rights to their computer and will have either the wrong flash player or none at all. This is particularly true in public sector organisations and the military, so if you are heading there I would test carefully the presence of Flash amongst your users.</p> <p>Other than that I heartily recommend Flex. It's also a great thing to have on your CV!</p> <p>HTH</p>
How to load viewController from a nib file <p>I have a Tab bar bases project (along with navigation control), inside a particular tab there is a tableViewLoaded , when i click on the table rows it shoud open another view , ie it pushes another controller , i have a view controller in the MainWindow.nib for this view also with some items like buttons labels , but whn i click it doesnt show up anythng only a blank page cums up , can any one help me out with this . </p>
<p>You should generally use one view controller-per-nib file; it makes things much easier. A few things to check:</p> <ol> <li>Is your view controller object being created (set a break point in its init, loadView, or viewDidLoad methods)</li> <li>Is your view being displayed (set a breakpoint in your viewWillAppear: or viewDidAppear: methods)</li> <li>Is your view properly hooked up (make sure the view outlet in IB is hooked up correctly; this is a common mistake)</li> </ol> <p>If your question is actually <i>how</i> to load a nib file that's paired with a UIViewController subclass, take a look at UIViewController's -initWithNibName:bundle: and -loadView methods.</p>
What is the meaning of "..::." in C#? <p>I saw this signature on the ListView class:</p> <pre><code>public ListView..::.ListViewItemCollection Items { get; } </code></pre> <p>When I saw that, "What?!"</p> <p>I searched "dot dot colon colon dot" and "..::." on Google with no result.</p> <p><img src="http://i.stack.imgur.com/av0FO.png" alt="alt text"></p>
<p>That's not C#; that's JScript. In C#, it would be:</p> <p>public ListView.ListViewItemCollection Items { get; }</p> <p>It's a little different because ListViewItemCollection is an inner class of ListView.</p> <p>I'm guessing that you saw this looking at <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.items.aspx">ListView.Items Property (System.Windows.Forms)</a>.</p> <p>If you look at the listing for all the other languages, they're all listed with the JScript syntax. You've found a documentation bug.</p>
XML Parsing <p>Hi All i want add the new node as parent node of the old nodes in XML using C#.for example node have the following XMl file</p> <pre><code>&lt;bookstore&gt; &lt;books&gt; &lt;author&gt; &lt;/author&gt; &lt;/books&gt; &lt;/bookstore&gt; </code></pre> <p>like that now i want add the new like below</p> <pre><code>&lt;bookstore&gt; &lt;newnode&gt; &lt;books&gt; &lt;author&gt; &lt;/author&gt; &lt;/books&gt; &lt;/newnode&gt; &lt;/bookstore&gt; </code></pre> <p>Thanks in Advance Sekar</p>
<p>Try this:-</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.Load("BookStore.xml"); XmlElement newNode = doc.CreateElement("newnode"); doc.DocumentElement.AppendChild(newNode); newNode.AppendChild(doc.SelectSingleNode("/bookstore/books")); doc.Save("BookStore.xml"); </code></pre>
How to count lines of code including sub-directories <p>Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:</p> <pre><code>cat * | wc -l </code></pre> <p>However, if there are sub-directories, this doesn't work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?</p>
<p>First you do not need to use <code>cat</code> to count lines. This is an <a href="http://en.wikipedia.org/wiki/Cat_%28Unix%29#Useless_use_of_cat">antipattern called Useless Use of Cat</a> (UUoC). To count lines in files in the current directory, use <a href="https://en.wikipedia.org/wiki/Wc_%28Unix%29"><code>wc</code></a>:</p> <pre><code>wc -l * </code></pre> <p>Then the <code>find</code> command recurses the sub-directories:</p> <pre><code>find . -name "*.c" -exec wc -l {} \; </code></pre> <ul> <li><p><code>.</code> is the name of the top directory to start searching from</p></li> <li><p><code>-name "*.c"</code> is the pattern of the file you're interested in </p></li> <li><p><code>-exec</code> gives a command to be executed</p></li> <li><p><code>{}</code> is the result of the find command to be passed to the command (here <code>wc-l</code>)</p></li> <li><p><code>\;</code> indicates the end of the command </p></li> </ul> <p>This command produces a list of all files found with their line count, if you want to have the sum for <strong>all</strong> the files found, you can use find to list the files (with the <code>-print</code> option) and than use xargs to pass this list as argument to wc-l.</p> <pre><code>find . -name "*.c" -print | xargs wc -l </code></pre> <p>EDIT to address Robert Gamble comment (thanks): if you have spaces or newlines (!) in file names, then you have to use <code>-print0</code> option instead of <code>-print</code> and <code>xargs -null</code> so that the list of file names are exchanged with null-terminated strings. </p> <pre><code>find . -name "*.c" -print0 | xargs -0 wc -l </code></pre> <p>The Unix philosophy is to have tools that do one thing only, and do it well.</p>
Adjusting XML config files from a script <p>I'm working on automating the configuration of several JBoss servers, which involves editing a substantial number of XML files.</p> <p>I'd like to script all these changes as much as possible. But the "standard" tools (sed, grep et al) do not work well with XML. Without necessarily resorting to a higher-level language, how can I script e.g. the insertion of a given XML snipper after a given XML element in a certain file?</p> <p>Say for instance that my jboss-log4j.xml looks like</p> <pre><code>&lt;!-- ====================== --&gt; &lt;!-- More Appender examples --&gt; &lt;!-- ====================== --&gt; &lt;!-- Buffer events and log them asynchronously --&gt; &lt;appender name="ASYNC" class="org.apache.log4j.AsyncAppender"&gt; &lt;errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/&gt; &lt;appender-ref ref="FILE"/&gt; &lt;!-- &lt;appender-ref ref="CONSOLE"/&gt; &lt;appender-ref ref="SMTP"/&gt; --&gt; &lt;/appender&gt; </code></pre> <p>and that I want to add a new appender-ref element. What's the easiest way to do that from a script?</p>
<p>You'll find more answers in my <a href="http://stackoverflow.com/questions/91791/grep-and-sed-equivalent-for-xml-command-line-processing" rel="nofollow" title="Grep and Sed Equivalent for XML">previous question</a>. <a href="http://xmlstar.sourceforge.net/" rel="nofollow" title="XMLStarlet tool collection">xmlstar</a> seems to be the most popular answer.</p>
Dynamically updated graphs on a web page - howto? <p>I need to understand a good way to design a web page with dynamically updated graphs. It should be something close to what stock market graphs look like (e.g. <a href="http://finance.google.com/finance?q=NASDAQ%3AGOOG" rel="nofollow">Google Finance</a>), although with a bit more complicated functionality, which is not the point. Naturally I am thinking of writing an ajaxy-style flash control, which would communicate with the server through, okay, something like XMLHttpRequest, but from within flash code, and draw things basing on data received. Is this doable with flash? Does security model allow such kind of client-server interaction? If yes, could you think of any references for me to get started (similar opensource projects, articles, whatever)? Or should I forget about flash and use a Java applet right away?</p> <p>An important thing to note: I don't think I can use Google charting API, because I need also to have user interaction. In the link above to Google Finance the user can drag the graph to and forth with the mouse, that's close to what I need (I will also need to implement some actions from the dropdown menu).</p> <p>Thanks for your answers and opinions!</p>
<p>Try this: <a href="http://code.google.com/p/flot/" rel="nofollow" title="JQuery Flot">JQuery Flot</a></p> <p> Flot is a JQuery plugin to plot graphs. You keep replotting in-place with the latest data at the desired frequency to generate a dynamically updated graph. It is based on the &lt;canvas&gt; tag. We use it successfully to generate pretty complex dynamically updated graphs in our applications. The updates are fetched via periodic AJAX calls. </p> <p>Another alternative is <a href="http://developer.yahoo.com/yui/charts/" rel="nofollow" title="YUI Charts">YUI Charts</a></p> <p> We did not explore this a lot but this uses Flash and AJAX like you wanted to do. </p> <p>/RS</p>
Schema for a multilanguage database <p>I'm developing a multilanguage software. As far as the application code goes, localizability is not an issue. We can use language specific resources and have all kinds of tools that work well with them.</p> <p>But what is the best approach in defining a multilanguage database schema? Let's say we have a lot of tables (100 or more), and each table can have multiple columns that can be localized (most of nvarchar columns should be localizable). For instance one of the tables might hold product information:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME NVARCHAR(50), DESCRIPTION NTEXT, PRICE NUMBER(18, 2) ) </code></pre> <p>I can think of three approaches to support multilingual text in NAME and DESCRIPTION columns:</p> <ol> <li><p>Separate column for each language</p> <p>When we add a new language to the system, we must create additional columns to store the translated text, like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_EN NVARCHAR(50), NAME_DE NVARCHAR(50), NAME_SP NVARCHAR(50), DESCRIPTION_EN NTEXT, DESCRIPTION_DE NTEXT, DESCRIPTION_SP NTEXT, PRICE NUMBER(18,2) ) </code></pre></li> <li><p>Translation table with columns for each language</p> <p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains a column for each language.</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_FK int, DESCRIPTION_FK int, PRICE NUMBER(18, 2) ) CREATE TABLE T_TRANSLATION ( TRANSLATION_ID, TEXT_EN NTEXT, TEXT_DE NTEXT, TEXT_SP NTEXT ) </code></pre></li> <li><p>Translation tables with rows for each language</p> <p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains only a key, and a separate table contains a row for each translation to a language.</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_FK int, DESCRIPTION_FK int, PRICE NUMBER(18, 2) ) CREATE TABLE T_TRANSLATION ( TRANSLATION_ID ) CREATE TABLE T_TRANSLATION_ENTRY ( TRANSLATION_FK, LANGUAGE_FK, TRANSLATED_TEXT NTEXT ) CREATE TABLE T_TRANSLATION_LANGUAGE ( LANGUAGE_ID, LANGUAGE_CODE CHAR(2) ) </code></pre></li> </ol> <p>There are pros and cons to each solution, and I would like to know what are your experiences with these approaches, what do you recommend and how would you go about designing a multilanguage database schema.</p>
<p>What do you think about having a related translation table for each translatable table?</p> <blockquote> <p>CREATE TABLE T_PRODUCT (pr_id int, PRICE NUMBER(18, 2))</p> <p>CREATE TABLE T_PRODUCT_tr (pr_id INT FK, languagecode varchar, pr_name text, pr_descr text)</p> </blockquote> <p>This way if you have multiple translatable column it would only require a single join to get it + since you are not autogenerating a translationid it may be easier to import items together with their related translations.</p> <p>The negative side of this is that if you have a complex language fallback mechanism you may need to implement that for each translation table - if you are relying on some stored procedure to do that. If you do that from the app this will probably not be a problem.</p> <p>Let me know what you think - I am also about to make a decision on this for our next application. So far we have used your 3rd type.</p>
Dynamic Id's in JSF/Seam <p>Got a little problem with a Seam application I'm working on and I was wondering if anyone knows a way round it. I've got a form in my application that uses AJAX to show certain input boxes depending on an item in a dropdown box. The code works fine except for setting the ID's in my input boxes. It looks like JSF doesn't let me set an ID via a variable. Other attributes like "for" in labels are fine. Here's some code explaining what I mean:</p> <pre><code>&lt;ui:repeat value="#{serviceHome.instance.serviceSettings}" var="currSetting" &gt; &lt;li&gt; &lt;!-- Imagine the below works out as "settingABC" --&gt; &lt;c:set var="labelKey" value="setting#{jsfUtils.removeWhitespace(currSetting.key.name)}" /&gt; &lt;!-- Labelkey is correctly added into this input so for = "settingABC" --&gt; &lt;h:outputLabel for="#{labelKey}" styleClass="required generated" value="#{currSetting.key.name}:"/&gt; &lt;s:decorate styleClass="errorwrapper"&gt; &lt;!-- Labelkey ISN'T correctly added into this input. Instead we just get "setting" --&gt; &lt;h:inputText id="#{labelKey}" value="#{currSetting.value}"/&gt; &lt;a4j:outputPanel ajaxRendered="true"&gt; &lt;h:message for="#{labelKey}" styleClass="errormessage" /&gt; &lt;/a4j:outputPanel&gt; &lt;/s:decorate&gt; &lt;/li&gt; &lt;/ui:repeat&gt; </code></pre> <p>Does anyone have any idea how I can get past this?</p>
<p>You see why they don't let you set the ID, right? JSF takes over id creation because you're in a repeated loop of components and, if they let you just set the id, you'd end up with duplicate IDs, which wouldn't help you anyway.</p> <p>Without knowing WHY you want to set the ID explicitly, it's hard to give you a workaround. If it's for JavaScript, you can do what Grant Wagner suggests, and let JSF give you what it put as the id. You can also take a peek at the generated HTML and see what format the id is in. JSF usually uses </p> <pre><code>"form_id:loop_id:loop_index:component_id" </code></pre> <p>as the id it generates for components in a form/repeat. You'd have to be sure and give id's to your form and ui:repeat tags to know what they were.</p> <p>Ok, you answered that you want to have an h:message tag for a specific inputText inside the loop, that's easy.</p> <pre><code>&lt;h:inputText id="myInput" .... /&gt; &lt;h:message for="myInput" ... /&gt; </code></pre> <p>Now, messages generated for the input will be displayed in the message, and JSF will mangle the "for" attribute (though that isn't generated to HTML) just like it will the "id" attribute in the inputText so they match.</p> <p>You can even make your OWN messages in your handler code to go to the specific h:message, but you'll need to use a call to clientId to get the target of the message, given the backing bean (not the value backing bean) of the component in question. </p>
How can I launch the default media player from a .NET application? <p>I need to launch a media file from a URL from within my c# .NET application. Is there any way to do this natively in .NET? I don't need an embedded player, I just need the default player to launch. I have tried </p> <pre><code>System.Diagnostics.Process.Start("File URL"); </code></pre> <p>but it launches the default browser and downloads the file, instead of attempting to play it in WMP/VLC/whatever the default media player is. Any ideas?</p>
<p>If you enter an URL it will be handled with the program registered to that URL format, in your case the default web browser.</p> <p>What format are the media in? You can get associated program for an extension and then run that program with the url as parameter. See: <a href="http://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension">http://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension</a></p> <p>So if your media is for example .MP3, then find the assoicated program for .MP3 (using the code in the link above) and pass the url as a parameter to that program.</p>
Drag'n'drop one or more mails from Outlook to C# WPF application <p>I'm working on a windows client written in WPF with C# on .Net 3.5 Sp1, where a requirement is that data from emails received by clients can be stored in the database. Right now the easiest way to handle this is to copy and paste the text, subject, contact information and time received manually using an arthritis-inducing amount of ctrl-c/ctrl-v.</p> <p>I thought that a simple way to handle this would be to allow the user to drag one or more emails from Outlook (they are all using Outlook 2007 currently) into the window, allowing my app to extract the necessary information and send it to the backend system for storage.</p> <p>However, a few hours googling for information on this seem to indicate a shocking lack of information about this seemingly basic task. I would think that something like this would be useful in a lot of different settings, but all I've been able to find so far have been half-baked non-solutions. </p> <p>Does anyone have any advice on how to do this? Since I am just going to read the mails and not send anything out or do anything evil, it would be nice with a solution that didn't involve the hated security pop ups, but anything beats not being able to do it at all.</p> <p>Basically, if I could get a list of all the mail items that were selected, dragged and dropped from Outlook, I will be able to handle the rest myself!</p> <p>Thanks!</p> <p>Rune</p>
<p>I found a great <a href="http://www.codeproject.com/KB/office/outlook%5Fdrag%5Fdrop%5Fin%5Fcs.aspx">article</a> that should do exactly what you need to. </p> <p><strong>UPDATE</strong></p> <p>I was able to get the code in that article working in WPF with a little tweaking, below are the changes you need to make.</p> <p>Change all references from System.Windows.Forms.IDataObject to System.Windows.IDataObject</p> <p>In the OutlookDataObject constructor, change</p> <pre><code>FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("innerData", BindingFlags.NonPublic | BindingFlags.Instance); </code></pre> <p>To</p> <pre><code>FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField("_innerData", BindingFlags.NonPublic | BindingFlags.Instance); </code></pre> <p>Change all DataFormats.GetFormat calls to DataFormats.GetDataFormat</p> <p>Change the SetData implementation from</p> <pre><code>public void SetData(string format, bool autoConvert, object data) { this.underlyingDataObject.SetData(format, autoConvert, data); } </code></pre> <p>TO</p> <pre><code>public void SetData(string format, object data, bool autoConvert) { this.underlyingDataObject.SetData(format, data, autoConvert); } </code></pre> <p>With those changes, I was able to get it to save the messages to files as the article did. Sorry for the formatting, but numbered/bulleted lists don't work well with code snippets.</p>
Threaded loading (waiting) screen <p>I'm looking for a generic method to implement a wait screen during long operations. I have used threading a few times before, but I have the feeling that I implemented it either very poorly, or with way too much hassle (and copy/pasting - the horror!).</p> <p>I want to keep this as generic and simple as possible, so I won't have to implement loads of <code>BackgroundWorker</code>s handling all kinds of crap, making things hard to maintain.</p> <p>Here's what I would like to do -- please note this might differ from what's actually possible/best practise/whatever -- using VB.NET, Framework 2.0 (so no anonymous methods):</p> <pre><code> Private Sub HandleBtnClick(sender as Object, e as EventArgs) Handles Button.Click LoadingScreen.Show() 'Do stuff here, this takes a while!' Dim Result as Object = DoSomethingTakingALongTime(SomeControl.SelectedObject) LoadingScreen.Hide() ProcessResults(Result) End Sub </code></pre> <p>The application is now completely single-threaded, so everything runs on the GUI thread. I need to be able to access objects in <code>DoSomethingTakingALongTime()</code> without getting cross-thread exceptions. The GUI thread waits for some method (which takes a long time) to complete, while the <code>LoadingScreen</code> Form should stay responsive (it's animated/has a progressbar/etc.).</p> <p>Is this a doable/good approach or am I seeing this way too simplistic? What is the best practise concerning this matter? And most importantly: how could I implement such a system? As I already mentioned, I have very little experience with threading, so be gentle please :-)</p>
<p>Your problem is that your getting a cross thread exception when your trying to pass your Worker thread data to your ui thread. what you need to do is check InvokeRequired and begininvoke before setting the controls on your ui so you don't get the error like so:</p> <pre><code>Private Sub work_CrossThreadEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles work.CrossThreadEvent If Me.InvokeRequired Then Me.BeginInvoke(New EventHandler(AddressOf work_CrossThreadEvent), New Object() {sender, e}) Return End If Me.Text = "Cross Thread" End Sub </code></pre> <p>just change the <code>New EventHandler</code> part to the event handler your using.</p> <p>Also i think using a background worker isn't a bad method for your worker classes, just create a class for your work and use the background worker to do the threading stuff a bit like this:</p> <pre><code>Public MustInherit Class Worker Protected WithEvents worker As BackgroundWorker Public Sub New() worker = New BackgroundWorker() worker.WorkerReportsProgress = True worker.WorkerSupportsCancellation = True End Sub Public Sub Start() If (Not worker.IsBusy AndAlso Not worker.CancellationPending) Then worker.RunWorkerAsync() End If End Sub Public Sub Cancel() If (worker.IsBusy AndAlso Not worker.CancellationPending) Then worker.CancelAsync() End If End Sub Protected MustOverride Sub Work() Private Sub OnDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles worker.DoWork Work() End Sub Public Event WorkCompelted As RunWorkerCompletedEventHandler Private Sub OnRunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles worker.RunWorkerCompleted OnRunWorkerCompleted(e) End Sub Protected Overridable Sub OnRunWorkerCompleted(ByVal e As RunWorkerCompletedEventArgs) RaiseEvent WorkCompelted(Me, e) End Sub Public Event ProgressChanged As ProgressChangedEventHandler Private Sub OnProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles worker.ProgressChanged OnProgressChanged(e) End Sub Protected Overridable Sub OnProgressChanged(ByVal e As ProgressChangedEventArgs) RaiseEvent ProgressChanged(Me, e) End Sub End Class Public Class ActualWork Inherits Worker Public Event CrossThreadEvent As EventHandler Protected Overrides Sub Work() 'do work here' WorkABit() worker.ReportProgress(25) WorkABit() worker.ReportProgress(50) WorkABit() worker.ReportProgress(75) WorkABit() worker.ReportProgress(100) End Sub Private Sub WorkABit() If worker.CancellationPending Then Return Thread.Sleep(1000) RaiseEvent CrossThreadEvent(Me, EventArgs.Empty) End Sub End Class </code></pre> <p><em>disclaimer.. bit rusty with vb but you should get the idea.</em></p>
Javascript: how do I determine if a link targets the same domain as the page it resides on? <p>For the purposes of tracking non-HTML documents via google analytics, I need the mentioned algorithm. It should:</p> <ul><li>not hard-code the domain</li> <li>ignore the protocol (i.e. http/https)</li> <li>not worry about the presence/absence of "www" (any absolute links WILL prefix with "www" and all pages WILL be served via "www")</li></ul> <p>This is complicated by the fact that I need to access it via a function called from the IE-only 'attachEvent'.</p> <p><strong>UPDATE</strong> Sorry, I've worded this question <em>really</em> badly. The real problem is getting this to work via an event, since IE has its own made-up world of event handling. Take the following:</p> <pre><code>function add_event(obj) { if (obj.addEventListener) obj.addEventListener('click', track_file, true); else if (obj.attachEvent) obj.attachEvent("on" + 'click', track_file); } function track_file(obj) { } </code></pre> <p>It seems as if the "obj" in track_file is not the same across browsers - how can I refer to what was clicked in IE?</p>
<p>I would like to point out that, if you're on so.com, the following links are URLs within the same domain:</p> <ul> <li><a href="http://test.so.com" rel="nofollow">http://test.so.com</a></li> <li><a href="http://so.com/index" rel="nofollow">http://so.com/index</a></li> <li>index</li> <li>/index</li> <li>#</li> <li>/#</li> <li>https://subdomain.so.com#hash</li> <li>mail.google.com</li> <li>mail.google.com/index.php?var=value#index</li> </ul> <p>(it may seem odd, but the last two ones are valid: if you're on <a href="http://so.com" rel="nofollow">http://so.com</a>, the last one would take you to <a href="http://so.com/mail.google.com/index.php?var=value" rel="nofollow">http://so.com/mail.google.com/index.php?var=value</a>, which is perfectly valid)</p> <p>This doesn't really answer the question but I hope it will guide the rest of the answers. If there's anything else weird enough, feel free to add it.</p>
Get dimensions of JPEG in C++ <p>I need to get at the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it, or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source libraries!</p> <p>Has anyone come across anything that might do the trick, or understand the JPEG file format (I think I probably mean the JFIF file format here) to tell me how I might go about rolling my own solution?</p> <p>Thanks,</p> <p>Dom</p>
<p>You have this <a href="http://carnage-melon.tom7.org/stuff/jpegsize.html" rel="nofollow">C function</a> which may extract the relevant data for you.</p> <blockquote> <p>This is a C routine but should compile fine with C++.<br> Pass it a normal FILE pointer (from fopen) to the beginning of a jpeg file and two int pointers to be set with the image height and width. </p> </blockquote> <p>Or you may find in the <a href="http://www.boost.org/doc/libs/1_35_0/boost/gil/extension/io/jpeg_io.hpp" rel="nofollow">Boost library</a> a jpeg class which has the right function (From <a href="http://www.adobe.com/technology/graphics/generic_image_library.html" rel="nofollow">Adobe</a> <a href="http://opensource.adobe.com/wiki/display/gil/Generic+Image+Library" rel="nofollow">Generic Image Library</a>).</p> <p><a href="http://stlab.adobe.com/gil/html/group___j_p_e_g___i_o.html#ga4" rel="nofollow">jpeg_read_dimensions</a> </p> <pre><code>boost::gil::jpeg_read_dimensions (const char *filename) </code></pre> <blockquote> <p>Returns the width and height of the JPEG file at the specified location. Throws std::ios_base::failure if the location does not correspond to a valid JPEG file. </p> </blockquote>
How can I change HTML attribute names with jQuery? <p>I would like to change all the names of the attributes where <code>class="testingCase"</code> throughout all my whole html document.</p> <p>e.g. Change:</p> <p><code>&lt;a class="testingCase" href="#" title="name of testing case"&gt;Blabla&lt;/a&gt;</code> <br/><code>&lt;a class="testingCase" href="#" title="name of another testing case"&gt;Bloo&lt;/a&gt;</code></p> <p>To this: </p> <p><code>&lt;a class="testingCase" href="#" newTitleName="name of testing case"&gt;Blabla&lt;/a&gt;</code> <br/><code>&lt;a class="testingCase" href="#" newTitleName="name of another testing case"&gt;Bloo&lt;/a&gt;</code></p> <p>I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?</p> <p>Thank you,</p> <p>Ice</p>
<p>I don't think you can "rename" an attribute, but you can create new attributes and remove other ones...</p> <pre><code>$('a.testingCase[title]').each(function() { var $t = $(this); $t .attr({ newTitleName : $t.attr('title'), }) .removeAttr('title') ; }); </code></pre> <p>Edit: added in the bit that makes it only select <code>a</code> elements with <code>class="testingCase"</code></p>
Using dates in the "where" clause of HQL query <p>I am using the <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a> database and have the following persistent class (simplified):</p> <pre><code>public class Project { public virtual int Id { get; set; } public virtual DateTime StartDate { get; set; } } </code></pre> <p>which is mapped to this table in the database:</p> <pre><code>CREATE TABLE projects ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, start_date DATETIME ) </code></pre> <p>Now I need to write a query that will select all the projects that have started in a given month.</p> <p>In SQL I could use:</p> <pre><code>SELECT id FROM projects WHERE strftime('%m', start_date) = '12' </code></pre> <p>What I dislike about this query is that it uses the database specific function "<a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow">strftime</a>".</p> <p>So the following HQL is dependent on the underlying database:</p> <pre><code>// Get all projects that started in December (no matter which year) var projects = session .CreateQuery( "from Project p " + "where strftime('%m', p.StartDate) = :month") .SetParameter("month", "12") .List&lt;Project&gt;(); </code></pre> <p>I have also tried "from Project p where p.StartDate.Month = 12" but it didn't work.</p> <p>So using HQL or criteria API is it possible to write such a query in a database agnostic way?</p>
<p>If you're regularly querying against months, days, years, you shouldn't really be storing your date as a DateTime column - it makes the queries incredibly inefficient. You could easily create a "Month" column and query against that (and your DBA would love you again)</p>
How can I create multidimensional arrays in Perl? <p>I am a bit new to Perl, but here is what I want to do: </p> <pre><code>my @array2d; while(&lt;FILE&gt;){ push(@array2d[$i], $_); } </code></pre> <p>It doesn't compile since <code>@array2d[$i]</code> is not an array but a scalar value.</p> <p>How should I declare @array2d as an array of array?</p> <p>Of course, I have no idea of how many rows I have.</p>
<p>To make an array of arrays, or more accurately an array of arrayrefs, try something like this: </p> <pre><code>my @array = (); foreach my $i ( 0 .. 10 ) { foreach my $j ( 0 .. 10 ) { push @{ $array[$i] }, $j; } } </code></pre> <p>It pushes the value onto a dereferenced arrayref for you. You should be able to access an entry like this: </p> <pre><code>print $array[3][2]; </code></pre>
Do i need to dispose of this Image instance? <p>I'm making a simple Image Debugger Visualizer. Code is below. I'm not sure if i need to manually dispose of the Image instance? Because i'm making a windows Form window and the PictureBox inside that contains my dynamic image .. do i need to add some special code when the form is terminating, to dispose of this? </p> <p>here's the code..</p> <pre><code>using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Microsoft.VisualStudio.DebuggerVisualizers; using DebuggerVisualizers; [assembly: DebuggerVisualizer( typeof (ImageDebuggerVisualizer), typeof (VisualizerObjectSource), Target = typeof (Image), Description = "Image Visualizer")] namespace DebuggerVisualizers { public class ImageDebuggerVisualizer : DialogDebuggerVisualizer { protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { Image image = (Image) objectProvider.GetObject(); Form form = new Form { Text = ("Image Visualizer - " + image.HorizontalResolution + " " + image.VerticalResolution), Width = image.Width, Height = image.Height }; PictureBox pictureBox = new PictureBox {Image = image, SizeMode = PictureBoxSizeMode.AutoSize}; form.Controls.Add(pictureBox); form.ShowDialog(); } } } </code></pre> <p>thanks for any help :)</p>
<p>Change your Show method to this:</p> <pre><code>protected override void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider) { Image image = (Image) objectProvider.GetObject(); using (Form form = new Form()) { PictureBox pictureBox = new PictureBox(); pictureBox.Image = image; form.Controls.Add(pictureBox); form.ShowDialog(); } } </code></pre> <p>The using(){} block will call Dispose on the form after it closes, which will dispose of everything on the form also.</p>
Why override operator()? <p>In the <a href="http://www.boost.org/doc/html/signals.html">Boost Signals</a> library, they are overloading the () operator.</p> <p>Is this a convention in C++? For callbacks, etc.?</p> <p>I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.</p> <p>Any insight as to the reason for this overload?</p>
<p>One of the primary goal when overloading operator() is to create a functor. A functor acts just like a function, but it has the advantages that it is stateful, meaning it can keep data reflecting its state between calls.</p> <p>Here is a simple functor example :</p> <pre><code>struct Accumulator { int counter = 0; int operator()(int i) { return counter += i; } } ... Accumulator acc; cout &lt;&lt; acc(10) &lt;&lt; endl; //prints "10" cout &lt;&lt; acc(20) &lt;&lt; endl; //prints "30" </code></pre> <p>Functors are heavily used with generic programming. Many STL algorithms are written in a very general way, so that you can plug-in your own function/functor into the algorithm. For example, the algorithm std::for_each allows you to apply an operation on each element of a range. It could be implemented something like that :</p> <pre><code>template &lt;typename InputIterator, typename Functor&gt; void for_each(InputIterator first, InputIterator last, Functor f) { while (first != last) f(*first++); } </code></pre> <p>You see that this algorithm is very generic since it is parametrized by a function. By using the operator(), this function lets you use either a functor or a function pointer. Here's an example showing both possibilities :</p> <pre><code>void print(int i) { std::cout &lt;&lt; i &lt;&lt; std::endl; } ... std::vector&lt;int&gt; vec; // Fill vec // Using a functor Accumulator acc; std::for_each(vec.begin(), vec.end(), acc); // acc.counter contains the sum of all elements of the vector // Using a function pointer std::for_each(vec.begin(), vec.end(), print); // prints all elements </code></pre> <hr> <p>Concerning your question about operator() overloading, well yes it is possible. You can perfectly write a functor that has several parentheses operator, as long as you respect the basic rules of method overloading (e.g. overloading only on the return type is not possible).</p>
Looking for network link speed determination algorithm <p>I'm looking for the best way to interpret the standard (well, standardish) Ethernet PHY registers, to determine the speed that an Ethernet link is actually running at. (e.g. 10/100/1000 and full/half-duplex)</p> <p>I daresay that this is to be found in the source of things like Linux, and I'm just off to look there now, but if anyone has a good reference I'd be interested.</p> <p>What I'm interested in is if it actually linked and what it linked at, rather than the vast sea of possibilities that each end has advertised at the outset.</p>
<p>Thanks for the answer. It's intended as a language and platform agnostic question, because pretty much all MII/GMII Ethernet PHYs have the same basic registers. I happen to be on an embedded platform.</p> <p>But I found a sensible sequence which was good enough for my restricted application by looking at various bits of Linux driver source - it's basically:</p> <p>Check for link-up in basic-status (0x1) If the link's up then check for negotiation-complete in basic status (0x1) If the negotiation's complete then check for 1G in the 1000M-status register (0xa) If you've not got 1G, then you've got 100M. (That's not a general rule, but it applies in this application)</p> <p>Maybe this was really a hardware question rather than a software one...</p>
phpmyadmin - save file to disk <p>when i point my browser to <code>http://localhost/phpmyadmin</code>, instead of showing me its front page, it comes up with save as dialog.</p> <p>I'm running: Apache/2.2.3 (Debian) PHP/5.2.0-8+etch13 Server </p> <p>I've reinstalled both apache2 and php5. After re-install i don't have httpd.conf file, how can i get it back? Is there a standard file which i can just copy into /etc/apache2?</p> <p>I did a locate httpd.conf and the only file i got was the empty file i have under /etc/apache2/ which i made.</p>
<p>Did you configure the php extension to send an http header?</p> <p>In httpd.conf: AddType application/x-httpd-php .php</p> <p>EDIT<br /> The file is not necessarily named <code>httpd.conf</code>, that's just the default name. Try searching for other configuration files in the Apache directory -- the extension probably is <code>.conf</code> but it might be something else... If you used apt-get on debian to install apache2, try <code>/etc/apache2/apche2.conf</code><br /> /EDIT</p>
prolog recursively find largest node <p>Just a simple binary tree and i want to find the the largest node. <br>example tree: t(t(t(nil,1,nil),2,t(nil,3,nil)),4,t(t(t(nil,8,nil),5,nil),6,t(nil,7,nil)))</p> <pre><code>int L(t,max) { if(t=null) return max; if(max&lt;t.root) max = t.root; LN(t,max); RN(t,max); return max; } L(tree,tree.root); </code></pre> <p>I just cant wrap my head around applying it to prolog. Here i display each node. Which i get, but i dont understand how to save the max value and keep it recursively.</p> <pre><code>tree(nil). tree(t(L,Root,R)) :- tree(L), tree(R), write(Root). </code></pre> <p>edit: It checks all the leaf nodes, but ignores the t(nil,8,nil)</p> <pre><code>tree(nil,0). tree(t(nil,Q,nil),Q) :- !. tree(t(nil,Q,_),Q). tree(t(_,Q,nil),Q). tree(t(L,_,R),Max) :- tree(L, LValue), tree(R, RValue), max(LValue,RValue,Max). </code></pre>
<p>Is this <a href="http://stackoverflow.com/questions/315944/prolog-problem-with-recursion">another homework assignment</a>?</p> <p>In any case, I'll try to let you do the thinking since you seem to be learning Prolog. Not to mention the fact that I don't actually have Prolog running on my computer, so I couldn't be sure my suggested solution would actually work.</p> <p>The fact that the 5 is the only node with only one subnode (i.e. the 8 it's ignoring) should tell you something. All the other nodes are either leaf nodes or have two subnodes.</p> <p>What exactly is it that you think these two rules do?</p> <pre><code>tree(t(nil,Q,_),Q). tree(t(_,Q,nil),Q). </code></pre>
How to get Url Hash (#) from server side <p>I know on client side (javascript) you can use windows.location.hash but could not find anyway to access from the server side.</p>
<p>We had a situation where we needed to persist the URL hash across ASP.Net post backs. As the browser does not send the hash to the server by default, the only way to do it is to use some Javascript:</p> <ol> <li><p>When the form submits, grab the hash (<code>window.location.hash</code>) and store it in a server-side hidden input field Put this in a DIV with an id of "<code>urlhash</code>" so we can find it easily later.</p></li> <li><p><strong>On the server</strong> you can use this value if you need to do something with it. You can even change it if you need to.</p></li> <li><p>On page load <strong>on the client</strong>, check the value of this this hidden field. You will want to find it by the DIV it is contained in as the auto-generated ID won't be known. <em>Yes, you could do some trickery here with .ClientID but we found it simpler to just use the wrapper DIV as it allows all this Javascript to live in an external file and be used in a generic fashion.</em></p></li> <li><p>If the hidden input field has a valid value, set that as the URL hash (<code>window.location.hash again</code>) and/or perform other actions.</p></li> </ol> <p>We used jQuery to simplify the selecting of the field, etc ... all in all it ends up being a few jQuery calls, one to save the value, and another to restore it.</p> <p><strong>Before submit:</strong></p> <pre><code>$("form").submit(function() { $("input", "#urlhash").val(window.location.hash); }); </code></pre> <p><strong>On page load:</strong></p> <pre><code>var hashVal = $("input", "#urlhash").val(); if (IsHashValid(hashVal)) { window.location.hash = hashVal; } </code></pre> <p><code>IsHashValid()</code> can check for "<code>undefined</code>" or other things you don't want to handle.</p> <p>Also, make sure you use <code>$(document).ready()</code> appropriately, of course.</p>
MySQL efficient "select id else insert" query <p>I have a MySQL table consisting of:</p> <pre><code>CREATE TABLE `url_list` ( `id` int(10) unsigned NOT NULL auto_increment, `crc32` int(10) unsigned NOT NULL, `url` varchar(512) NOT NULL, PRIMARY KEY (`id`), KEY `crc32` (`crc32`) ); </code></pre> <p>When inserting data into a related table I need to lookup the primary key from this table, and using the crc32 really speeds that up whilst allowing a small index. The URLs do need to be unique, but I'd like to avoid having more index than actual data.</p> <p>If the value isn't present I need to insert it, but using structures such as <code>INSERT IGNORE</code>, or ON <code>DUPLICATE KEY</code> either requires me to put a unique on the huge varchar, or don't take advantage of my index.</p> <p>How can I "SELECT id else INSERT", whilst preserving the lookup speed for the 80-90% of hits that are already in the table?</p>
<p>I would recommend ditching the <code>id</code> column and the <code>crc32</code> because they're not necessary.</p> <p>You can use an <code>MD5()</code> hash to provide a fixed-length, virtually unique value computed from the lengthy URL data, and then use that hash as the primary key.</p> <pre><code>CREATE TABLE `url_list` ( `url_hash` BINARY(16) NOT NULL PRIMARY KEY `url` VARCHAR(512) NOT NULL ); DELIM !! CREATE TRIGGER `url_ins` BEFORE INSERT ON `url_list` FOR EACH ROW BEGIN SET NEW.`url_hash` = UNHEX( MD5( NEW.`url` ) ); END!! </code></pre> <p>Then you can use <code>INSERT..ON DUPLICATE KEY UPDATE</code> because unlike <code>crc32</code>, the hash should have a very low chance of collision.</p> <p><strong>edit:</strong> See <a href="http://en.wikipedia.org/wiki/Birthday_attack" rel="nofollow">http://en.wikipedia.org/wiki/Birthday_attack</a>. If you log 1 million distinct URL's per day for 2,000 years, the MD5 hashes of these URL's are still less likely to include a collision than your hard disk is to have an uncorrectable bit error.</p>
Collection type for representing a hierarchial structure in .Net 3.5 <p>I been experimenting with the different methods for representing a hierarchical structures in memory that would allow for simple and efficient transversal both up and down to discover ancestor and descendant relationships. Does anyone have any suggestions or examples of the options that I have? Is there a collection type in .Net 3.5 that would help here? </p>
<p>So you want a <a href="http://en.wikipedia.org/wiki/Tree_%28data_structure%29" rel="nofollow">Tree</a>? <a href="http://www.google.co.uk/search?q=c%23+tree&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-GB:official&amp;client=firefox-a" rel="nofollow">FGI</a></p>
How am I supposed to use the TortoiseSVN merge tool (TortoiseMerge)? <p>How am I supposed to use merge with the latest version of Tortoise SVN? I'm an old <a href="http://en.wikipedia.org/wiki/IBM_Rational_ClearCase" rel="nofollow">ClearCase</a> guy, and I've never understood it. When I merge a branch back into the trunk, I just select range of revisions and then leave the version numbers blank and it starts spitting out all kinds of files that it's merging. It basically looks like it's adding and modifying everything.</p> <p>The funny thing is, when the merge is done, the only files that are actually touched are the files I updated, so it seems like everything worked fine (and after running a few tests, this seems to be the case). I just get scared by everything getting spit out of the merge log, it doesn't give me any indication of what's really happening.</p> <p>Should I put something in the version number box? TortoiseSVN seems to indicate that won't be necessary.</p> <hr> <p>So it seems like what I missing is the fact that the "Range of Revisions" should not be blank. To get functionality similar to what I was used to, I needed to put in the revision that created the branch-HEAD. So if revision 289 created my branch, then I needed to put 289-HEAD in the revisions to merge field and the results would match what I expected.</p>
<p>TortoiseSVN contains two notions of "merge":</p> <ol> <li>The TortoiseMerge tool, which is the graphical diffing tool that comes with TortoiseSVN</li> <li>Merging, as in "branching and merging", which is a Subversion concept (which is what you appear to be referring to)</li> </ol> <p>The latter is a classic source code control concept that differs between products. I know nothing about ClearCase, so I can't really attempt any conversion explanation, but I can point you in the direction of the <a href="http://svnbook.red-bean.com/" rel="nofollow">Subversion book</a>, which is an excellent guide, and which contains a really good explanation of how <a href="http://svnbook.red-bean.com/en/1.8/svn.branchmerge.html" rel="nofollow">branching and merging</a> work in the Subversion world.</p>
How do I reference a scalar in a hash reference in Perl? <p>Simple question:</p> <p>How do I do this on one line:</p> <pre><code>my $foo = $bar-&gt;{baz}; fizz(\$foo); </code></pre> <p>I've tried \$bar->{baz}, \${$bar->{baz}}, and numerous others. Is this even possible?</p> <p>-fREW</p> <p><strong>Update</strong>: Ok, the hashref is coming from DBI and I am passing the scalar ref into template toolkit. I guess now that I look more closely the issue is something to do with how TT does all of this. Effectively I want to say:</p> <pre><code>$template-&gt;process(\$row-&gt;{body}, $data); </code></pre> <p>But TT doesn't work that way, TT takes a scalar ref and puts the data there, so I'd have to do this:</p> <pre><code>$template-&gt;process(\$row-&gt;{body}, $shopdata, \$row-&gt;{data}); </code></pre> <p>Anyway, thanks for the help. I'll at least only have one reference instead of two.</p>
<pre><code>\$bar-&gt;{baz} </code></pre> <p>should work.</p> <p>E.g.:</p> <pre><code>my $foo; $foo-&gt;{bar} = 123; my $bar = \$foo-&gt;{bar}; $$bar = 456; print "$foo-&gt;{bar}\n"; # prints "456" </code></pre> <p>In answer to the update in the OP, you can do:</p> <pre><code>\@$row{qw(body data)}; </code></pre> <p>This is not the same as \@array, which would create one reference to an array. The above will distribute the reference and make a list of two references.</p>
What is the difference between the KeyCode and KeyData properties on the .NET WinForms key event argument objects? <p>The two key event argument classes <code>KeyEventArgs</code> and <code>PreviewKeyDownEventArgs</code> each have two properties, <code>KeyCode</code> and <code>KeyData</code>, which are both of the enumeration type Keys.</p> <p>What is the difference between these two properties? Do the values in them ever differ from each other? If so, when and why?</p>
<p><code>KeyCode</code> is an enumeration that represents all the possible keys on the keyboard. <code>KeyData</code> is the <code>KeyCode</code> combined with the modifiers (Ctrl, Alt and/or Shift).</p> <p>Use <code>KeyCode</code> when you don't care about the modifiers, <code>KeyData</code> when you do. </p>
Compare equality between two objects in NUnit <p>I'm trying to assert that one object is "equal" to another object. </p> <p>The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties?</p> <p>This is my current solution but I think there may be something better:</p> <pre><code>Assert.AreEqual(LeftObject.Property1, RightObject.Property1) Assert.AreEqual(LeftObject.Property2, RightObject.Property2) Assert.AreEqual(LeftObject.Property3, RightObject.Property3) ... Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN) </code></pre> <p>What I'm going for would be in the same spirit as the CollectionEquivalentConstraint wherein NUnit verifies that the contents of two collections are identical.</p>
<p>If you can't override Equals for any reason, you can build a helper method that iterates through public properties by reflection and assert each property. Something like this:</p> <pre class="lang-cs prettyprint-override"><code>public static class AssertEx { public static void PropertyValuesAreEquals(object actual, object expected) { PropertyInfo[] properties = expected.GetType().GetProperties(); foreach (PropertyInfo property in properties) { object expectedValue = property.GetValue(expected, null); object actualValue = property.GetValue(actual, null); if (actualValue is IList) AssertListsAreEquals(property, (IList)actualValue, (IList)expectedValue); else if (!Equals(expectedValue, actualValue)) Assert.Fail("Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } } private static void AssertListsAreEquals(PropertyInfo property, IList actualList, IList expectedList) { if (actualList.Count != expectedList.Count) Assert.Fail("Property {0}.{1} does not match. Expected IList containing {2} elements but was IList containing {3} elements", property.PropertyType.Name, property.Name, expectedList.Count, actualList.Count); for (int i = 0; i &lt; actualList.Count; i++) if (!Equals(actualList[i], expectedList[i])) Assert.Fail("Property {0}.{1} does not match. Expected IList with element {1} equals to {2} but was IList with element {1} equals to {3}", property.PropertyType.Name, property.Name, expectedList[i], actualList[i]); } } </code></pre>
Preparing a development tools machine <p>I am working on a small project with a few friends and need to set up a server to run our tools. I looked around at hosted solutions like <a href="http://unfuddle.com/" rel="nofollow">Unfuddle</a> but they don't provide a CI server.</p> <p>I am now considering buying a <a href="http://www.linode.com/" rel="nofollow">Linode</a> and running the following on it:</p> <ul> <li>Mail : <a href="http://james.apache.org/" rel="nofollow">Apache JAMES</a> </li> <li>CI : <a href="http://hudson-ci.org/" rel="nofollow">Hudson</a> </li> <li>Wiki/Tracker : <a href="http://trac.edgewall.org/" rel="nofollow">Trac</a> </li> <li>Project Management: <a href="http://studios.thoughtworks.com/mingle-agile-project-management" rel="nofollow">Mingle</a> </li> <li>VCS : <a href="http://subversion.tigris.org/" rel="nofollow">SVN</a></li> </ul> <p>I am a Linux server newbie, so does anyone have any writeups, advice etc about this? I am aware of <a href="http://buildix.thoughtworks.com/" rel="nofollow">Buildix</a>, but they don't provide the combination I need. </p>
<p>I'm not sure how much power you need, but what I've done in the past is grabbed an old desktop computer. Wiped the hard drive and installed an appropriate OS and then loaded my tools on that.</p> <p>I setup port forwarding on my router to send incoming requests to it. And I got my hands a dynamic IP address URL (there are free and pay-for ones) and setup tools to always update the current IP address on the URL.</p> <p>It worked great, was cheap and I learned a lot about server administration.</p> <p>Yes, setup is harder and it takes longer but if you run this project for 12 months and you are paying (say $30 a month) then you save yourself $360 plus you gained a whole lot of insight in to Admin-ing Linux(or the OS of your choice).</p> <p>Best Regards,<br> Frank</p>
Create a DSL vs. Embed an Existing Language <p>This often comes up: your application has gotten extensive enough that it's time to add some programmability into it to make it flexible. One example might be a finance application - you want to add a formula editor so that you can create your own custom formulas without having to re-compile the code.</p> <p>You have to make a choice: do you create your own tokenizer, parser, and interpreter/compiler chain, something which might take a long time and might be done incorrectly? Or do you just embed another scripting language, which has the problem that it'll likely bloat your code and expose your app to security vulnerabilities.</p> <p>How would you balance the trade-offs and make this decision?</p>
<p>There are no trades offs -- embed a throughly tested, well documented interpretor. Otherwise, you'll end up with an abomination like MAXScript.</p>
Running numpy from cygwin <p>I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy. </p> <p>This all works great when I run the Python (command line) tool that comes with Python.</p> <p>However, if I run cygwin and then run Python from within, it cannot find the numpy package.</p> <p>What environment variable do I need to set? What value should it be set to? </p>
<p>Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin.</p> <p>To test this, try opening a bash prompt in Cygwin and typing <code>which python</code> to see where the Python executable is located. If it says <code>/cygdrive/c/Python25/python.exe</code> or something similar then you'll know you're running the Windows executable. If you see <code>/usr/local/bin/python</code> or something like that, then you'll know that you're running the Cygwin version.</p> <p>I recommend opening a DOS prompt and running Python from there when you need interactive usage. This will keep your two Python installs nicely separate (it can be very useful to have both; I do this on my own machine). Also, you may have some problems running a program designed for Windows interactive console use from within a Cygwin shell.</p>
ApplicationVerifier is not detecting handle leaks, what do I do? <p>I did select the executable correctly, because I can get it to respond to certain things I do. But I can't get ApplicationVerifier to properly detect a handle leak.</p> <p>Here is an example:</p> <pre><code>int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { HANDLE hFile = CreateFile(_T("C:\\test.txt"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); return 0; } </code></pre> <p>ApplicationVerifier doesn't detect this.</p> <p>What can I do to detect the above problem?</p>
<p>Is your code only creating handles through CreateFile? If so you can just macro these methods out to versions that do custom implemented leak detection. It's a lot of work but it will get the job done.</p> <pre><code>#if DEBUG #define CreateFile DebugCreateFile #define CloseHandle DebugCloseHandle #endif // in another cpp file #undef CreateFile #undef CloseHandle HANDLE DebugCreateFile(...) { HANDLE real = ::CreateFile(...); TrackHandle(real); return real; } void DebugCloseHandle(HANDLE target) { if (IsTracked(target)) { Untrack(target); } ::CloseHandle(target); } void CheckForLeaks() { // Look for still registered handles } </code></pre> <p>At the end of your program you'd need to call CheckForLeaks. Like I said though, quite a bit of work but it may help with your scenairo. </p>
Is It Possible to Use a String as an Index? <p>In other languages you can use strings as keys -</p> <p>PHP:</p> <pre><code>$array['string'] = 50; $array['anotherstring'] = 150; </code></pre> <p>Is this possible in VBA?</p>
<p>In VBA you can create a Collection object. Items in the collection can be accessed by index (Long integer) or by a string key.</p>
Is it possible to initialise a New System.Collections.Generic.Dictionary with String key/value pairs? <p>Is it possible to create and initialise a <a href="http://msdn.microsoft.com/en-us/library/6918612z(VS.80).aspx"><code>System.Collections.Generic.Dictionary</code></a> object with String key/value pairs in one statement?</p> <p>I'm thinking along the lines of the constructor for an array of Strings..</p> <p>e.g.</p> <pre><code>Private mStringArray As String() = {"String1", "String2", "etc"} </code></pre> <p>In case this is turns out to be a <a href="http://en.wikipedia.org/wiki/Syntactic_sugar">syntactic sugar</a> kind of thing, I'd prefer an answer that I can use in .Net 2.0 (Visual Studio 2005), and Visual Basic - though I'm curious if it's possible at all so don't let that put you off ;o)</p>
<p>Like this:</p> <pre><code>Dim myDic As New Dictionary(Of String, String) From {{"1", "One"}, {"2", "Two"}} </code></pre>
How to close a system dialog on a BlackBerry? <p>I have a BlackBerry app running in the background that needs to know when a "Missed call" system dialog is brought up by the system, and programmatically close it without user intervention. How can I do that?</p> <p>I could actually almost know when the dialog is brought up, i.e. a little later I programmatically end the call...but how can I get a reference to the dialog, and close it?</p>
<p>Key press injection for device <em>Close</em> button looks like this: </p> <pre><code>KeyEvent inject = new KeyEvent(KeyEvent.KEY_DOWN, Characters.ESCAPE, 0); inject.post(); </code></pre> <p>Don't forget to set permissions for device release: Options => Advanced Options => Applications => [Your Application] =>Edit Default permissions =>Interactions =>key stroke Injection</p> <p>May be useful:<br /> <a href="http://stackoverflow.com/questions/1292896/blackberry-simulate-a-keypress-event/1298900#1298900">BlackBerry - Simulate a KeyPress event</a></p>
Object-oriented or sequential? <p>I'm refactoring a 500-lines of C++ code in main() for solving a differential equation. I'd like to encapsulate the big ideas of our solver into smaller functions (i.e. "SolvePotential(...)" instead of 50 lines of numerics code). </p> <p>Should I code this sequentially with a bunch of functions taking <strong>very long</strong> parameters lists, such as:</p> <pre><code>int main(int *argc, void **argv){ interpolate(x,y,z, x_interp, y_interp, z_interp, potential, &amp;newPotential); compute_flux(x,y,z, &amp;flux) compute_energy(x,y,z, &amp;eng) ... // 10 other high-level function calls with long parameter lists ... return 0; } </code></pre> <p>Or should I create a "SolvePotential" class that would be called like so:</p> <pre><code>int main(int *argc, void **argv){ potential = SolvePotential(nx, ny, nz, nOrder); potential.solve(); return 0; } </code></pre> <p>Where I would define functions in SolvePotential that uses member variables rather than long parameter lists, such as:</p> <pre><code>SolverPotential::solve(){ SolvePotential::interpolate() SolverPotential::compute_flux() SolverPotential::compute_energy() // ... // 10 other high-level function calls with NO parameter lists (just use private member variables) } </code></pre> <p>In either case, I doubt I'll re-use the code very much... really, I'm just refactoring to help with code clarity down the road.</p> <p>Maybe this is like arguing "Is it '12' or 'one dozen'?", but what do you think?</p>
<p>Write it sequentially and then refactor if there's something you think you can reuse or would make it clearer.</p> <p>Also, a SolvePotential class doesn't make a lot of sense since a class should be an Object with the method SolvePotential.</p>
Get real image width and height with JavaScript in Safari/Chrome? <p>I am creating a jQuery plugin.</p> <p>How do I get real image width and height with Javascript in Safari?</p> <p>Following works with Firefox 3, IE7 and Opera 9:</p> <pre><code>var pic = $("img") // need to remove these in of case img-element has set width and height pic.removeAttr("width"); pic.removeAttr("height"); var pic_real_width = pic.width(); var pic_real_height = pic.height(); </code></pre> <p>But in Webkit browsers like Safari and Google Chrome values are 0...</p> <p>Doing this on server side is not an option.</p>
<p>Webkit browsers set the height and width property after the image is loaded. Instead of using timeouts, I'd recommend using an image's onload event. Here's a quick example:</p> <pre><code>var img = $("img")[0]; // Get my img elem var pic_real_width, pic_real_height; $("&lt;img/&gt;") // Make in memory copy of image to avoid css issues .attr("src", $(img).attr("src")) .load(function() { pic_real_width = this.width; // Note: $(this).width() will not pic_real_height = this.height; // work for in memory images. }); </code></pre> <p>To avoid any of the effects CSS might have on the image's dimensions, the code above makes an in memory copy of the image. This is a very clever solution suggested by <a href="http://stackoverflow.com/questions/318630#3192577">FDisk</a>.</p>
BLAS Library Benchmark <p>Is there a benchmark that compares the different BLAS (Basic Linear Algebra Subprograms) libraries? I am especially interested in sparse matrix multiplication for single- and multi-core systems?</p>
<p>BLAS performance is very much system dependent, so you'll best do the benchmarks yourself on the very machine you want to use. Since there are only a few BLAS implementations, that is less work than it sounds (normally the <a href="http://www.netlib.org/blas/faq.html#5" rel="nofollow">hardware vendors implementation</a>, <a href="http://math-atlas.sourceforge.net/" rel="nofollow">ATLAS</a> and the <a href="http://www.tacc.utexas.edu/resources/software/software_downloads.php" rel="nofollow">GOTO BLAS</a>).</p> <p>But note that BLAS only covers dense matrices, so for sparse matrix multiplication you'll need Sparse-BLAS or some other code. Here performance will differ not only depending on hardware but also on the sparse format you want to use and even on the type of matrix you are working with (things like sparsity pattern, bandwidth etc. matter). So even more than in the dense case, if you need maximum performance you will need to do your own benchmarks. </p>
asp.net sql timeout when not using sql <p>Im in the process of learning asp.net 3.5, currently on webparts and co.</p> <p>Ive started a new project for webparts, not using a database with it, but when i go to view the website (dev server), i get an sql timeout??</p> <blockquote> <p>A network-related or instance-specific error occurred while establishing a connection to SQL Server.</p> </blockquote> <p>Just to be clear, there is no mention of sql anywhere in the project.<br /> Should i just start again?</p> <p><strong>Edit:</strong><br /> May be relevant</p> <blockquote> <p>(provider: Shared Memory Provider, error: 40 - Could not open a connection to SQL Server)</p> </blockquote>
<p>The webparts infrastructure talks to a database.</p>
Does anyone know where there is a recipe for serializing data and preserving its order in the output? <p>I am working with a set of data that I have converted to a list of dictionaries</p> <p>For example one item in my list is </p> <pre><code>{'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2005', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Bananas'} </code></pre> <p>Per request </p> <p>The second item in my list could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078099', 'columnLabel': u'2006', 'actionDate': u'C20070627', 'data': u'86,000', 'rowLabel': u'Sales of Bananas'} </code></pre> <p>The third item could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2005', 'actionDate': u'C20070627', 'data': u'116,000', 'rowLabel': u'Sales of Cherries'} </code></pre> <p>The fourth item could be:</p> <pre><code> {'reportDate': u'R20070501', 'idnum': u'1078100', 'columnLabel': u'Full Year 2006', 'actionDate': u'C20070627', 'data': u'76,000', 'rowLabel': u'Sales of Sales of Cherries'} </code></pre> <p>The reason I need to pickle this is because I need to find out all of the ways the columns were labeled before I consolidate the results and put them into a database. The first and second items will be one row in the results, the third and fourth would be the next line in the results (after someone decides what the uniform column header label should be)</p> <p>I tested pickle and was able to save and retrieve my data. However, I need to be able to preserve the order in the output. One idea I have is to add another key that would be a counter so I could retrieve my data and then sort by the counter. Is there a better way?</p> <p>I don't want to put this into a database because it is not permanent. </p> <p>I marked an answer down below. It is not what I am getting, so I need to figure out if the problem is somewhere else in my code.</p>
<p>So what's wrong with pickle? If you structure your data as a list of dicts, then everything should work as you want it to (if I understand your problem).</p> <pre><code>&gt;&gt;&gt; import pickle &gt;&gt;&gt; d1 = {1:'one', 2:'two', 3:'three'} &gt;&gt;&gt; d2 = {1:'eleven', 2:'twelve', 3:'thirteen'} &gt;&gt;&gt; d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'} &gt;&gt;&gt; data = [d1, d2, d3] &gt;&gt;&gt; out = open('data.pickle', 'wb') &gt;&gt;&gt; pickle.dump(data, out) &gt;&gt;&gt; out.close() &gt;&gt;&gt; input = open('data.pickle') &gt;&gt;&gt; data2 = pickle.load(input) &gt;&gt;&gt; data == data2 True </code></pre>
Private module methods in Ruby <p>I have a two part question</p> <p><strong>Best-Practice</strong></p> <ul> <li>I have an algorithm that performs some operation on a data structure using the public interface</li> <li>It is currently a module with numerous static methods, all private except for the one public interface method.</li> <li>There is one instance variable that needs to be shared among all the methods.</li> </ul> <p>These are the options I can see, which is the best?:</p> <ul> <li><strong>Module</strong> with static ('module' in ruby) methods </li> <li><strong>Class</strong> with static methods</li> <li><strong>Mixin</strong> module for inclusion into the data structure</li> <li><strong>Refactor</strong> out the part of the algorithm that modifies that data structure (very small) and make that a mixin that calls the static methods of the algorithm module</li> </ul> <p><strong>Technical part</strong></p> <p>Is there any way to make a <strong>private Module method</strong>?</p> <pre><code>module Thing def self.pub; puts "Public method"; end private def self.priv; puts "Private method"; end end </code></pre> <p><strong>The <code>private</code> in there doesn't seem to have any effect</strong>, I can still call <code>Thing.priv</code> without issue.</p>
<p>I think the best way (and mostly how existing libs are written) do this by making a class within the module that deals with all the logic, and the module just provides a convenient method, e.g.</p> <pre><code>module GTranslate class Translator def perform( text ); 'hola munda'; end end def self.translate( text ) t = Translator.new t.perform( text ) end end </code></pre>
Is there an easy way to determine the type of a file without knowing the file's extension? <p>I have a table with a binary column which stores files of a number of different possible filetypes (PDF, BMP, JPEG, WAV, MP3, DOC, MPEG, AVI etc.), but no columns that store either the name or the type of the original file. Is there any easy way for me to process these rows and determine the type of each file stored in the binary column? Preferably it would be a utility that only reads the file headers, so that I don't have to fully extract each file to determine its type.</p> <p><strong>Clarification</strong>: I know that the approach here involves reading just the beginning of each file. I'm looking for a good resource (aka links) that can do this for me without too much fuss. Thanks.</p> <p>Also, <strong>just C#/.NET on Windows, please</strong>. I'm not using Linux and can't use Cygwin (doesn't work on Windows CE, among other reasons).</p>
<p>you can use these tools to find the file format.</p> <p>File Analyser <a href="http://www.softpedia.com/get/Programming/Other-Programming-Files/File-Analyzer.shtml" rel="nofollow">http://www.softpedia.com/get/Programming/Other-Programming-Files/File-Analyzer.shtml</a></p> <p>What Format <a href="http://www.jozy.nl/whatfmt.html" rel="nofollow">http://www.jozy.nl/whatfmt.html</a></p> <p>PE file format analyser <a href="http://peid.has.it/" rel="nofollow">http://peid.has.it/</a></p> <p>This website may be helpful for you. <a href="http://mark0.net/onlinetrid.aspx" rel="nofollow">http://mark0.net/onlinetrid.aspx</a></p> <p>Note: i have included the download links to make sure that you are getting the right tool name and information.</p> <p>please verify the source before you download them.</p> <p>i have used a tool in the past i think it is File Analyser, which will tell you the closest match.</p> <p>happy tooling.</p>
Anyone seen good embedded help in a web application? <p>I have a pretty simple app on the web (written in Flex) which is very straightforward to use once it has data inside it. The steps to get data inside it are themselves also pretty simple, but not at all obvious to my audience when they first log into my app. </p> <p>I have been wrestling with how to communicate the data setup process to my users without referring them to a separate help. I also don't want to clog my lovely, elegant UI (which has uniformly been praised for its clarity from my current users and matches their processes very well) with wizards, or worse still an annoying animated paperclip.</p> <p>I have a very rich set of tools available for the web UI but I am looking for inspiration and wondered if anyone had experienced good web-based, intuitive, unobtrusive, genuinely helpful process/usage instructions embedded in an application and could point me to a link so I can take a look for myself.</p> <p>Failing that anyone got any bright ideas? There are about 5 steps involved each one visiting a different page of the existing app to enter/upload data.</p>
<p>Have you taken a look at: <a href="http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html" rel="nofollow">http://www.askthecssguy.com/2007/03/form_field_hints_with_css_and.html</a></p> <p>I believe there is a jquery or prototype or mootools or whatever framework that goes a couple steps beyond the above and walks a user through what to do. My google-fu isn't coming through right now so I can't seem to find it.</p>
Any tips on how to organize Eclipse environment on multiple monitors? <p>I can't find a good way of putting Eclipse windows on two monitors. Currently I just detached (clicked on a header and dragged) a few windows to a secondary monitor (package explorer, console, and outline) while leaving primary monitor with maximized source editing window. </p> <p>It works pretty well except few annoying issues. Detached windows are not in focus while you are editing your code. Which means that, for example, last build shortcut (<kbd>Alt</kbd>-<kbd>Shift</kbd>-<kbd>X</kbd>, <kbd>Q</kbd>) doesn't work because it can't find build file (because package explorer is not in focus). Also "Selected resources" option in a file search menu is not picking up current package selection.</p> <p>So I was wondering is detaching windows a right way to go? Do you have any better solutions so at least package explorer stays in focus?</p> <p>Thanks.</p> <p>PS. Btw "unable to find build" error started showing up only in 3.4 ver for some reason.</p>
<p>In the Eclipse Helios (currently 3.6.2) I found very useful the use of another window to bring up multiple documents in different screens. in the main menu, go:</p> <p>Window > New window, </p> <p>and drag it to the screen you prefer. Double click in the filename on the editor and will maximize the editor's window.</p> <p>I hope i helped.</p> <p>Kyr.</p> <p>PS: If you want to maintain both windows when you closing Eclipse, don't close them one by one. Instead go: File > Exit.</p>
How to create an element without hardcoding the name <p>I tried this but it does not seem to be valid syntax.</p> <pre><code>&lt;xsl:element name="$myElementName"&gt;&lt;/xsl:element&gt; </code></pre>
<p>You may need to surround it with <code>{}</code> to ensure the value is evaluated rather than used as a verbatim string, e.g.</p> <pre><code>&lt;xsl:element name="{$myElementName}"&gt;&lt;/xsl:element&gt; </code></pre>
How to access the layer of a view? <p>I would like to apply a transformation (rotation) to a <code>UIImageView</code>. I could just set the <code>transform</code> property of the view, but wouldn't setting the layer's <code>transform</code> make it faster? If so, how can I achieve this?</p> <p>Assuming I have a <code>UIImageView</code> initialized with an image, can anyone help? Wouldn't it be better to have a <code>UIVIew</code> with a <code>UIImageView</code> in it?</p>
<p>If you're doing a simple rotation, the speed difference is probably insignificant, but you can get access to a view's layer by doing:</p> <p><code>view.layer </code></p> <p>So, you can just use </p> <p><code>view.layer.affineTransform = newTranform; </code></p>
How do you use LINQ with Sqlite <p>Would someone explain how to get LINQ working with Sqlite.</p>
<p><a href="http://code.google.com/p/dblinq2007/">Here you have an SQL Linq provider for SQLite, and some other DBs</a></p>
Cascading to a auto completing text box <p>I have a web page where the user will enter their address. They will select their country and region in cascading drop down lists. I would like to provide an auto completing textbox for their city, but I want to be context sensitive to the country and region selections. I would have just used another cascading drop down list, however the number of cities exceeds the maximum number of list items. </p> <p>Any suggestions or cool code spinets out there that may help me out?</p>
<p>I just found the following <a href="http://blogs.technet.com/kirtid/archive/2007/05/17/cascading-autocomplete.aspx" rel="nofollow">blog</a> post that looks at least close to what you want.</p> <p>They manage it using the following javascript functions:</p> <pre><code> function initCascadingAutoComplete() { var moviesAutoComplete = $find('autoCompleteBehavior1'); var actorsAutoComplete = $find('autoCompleteBehavior2'); actorsAutoComplete.set_contextKey(moviesAutoComplete.get_element().value); moviesAutoComplete.add_itemSelected(cascade); // setup initial state of second flyout if (moviesAutoComplete.get_element().value) { actorsAutoComplete.get_element().disabled = false; } else { actorsAutoComplete.get_element().disabled = true; actorsAutoComplete.get_element().value = ""; } } function cascade(sender, ev) { var actorsAutoComplete = $find('autoCompleteBehavior2'); actorsAutoComplete.set_contextKey(ev.get_text()); actorsAutoComplete.get_element().value = ''; if (actorsAutoComplete.get_element().disabled) { actorsAutoComplete.get_element().disabled = false; } } Sys.Application.add_load(initCascadingAutoComplete); </code></pre> <p>Calling the cascade function on the add_itemSelected method of the parent control for the cascading behaviour.</p> <p>They cascade the contents of one auto complete extender into another, rather than taking a cascading drop down list, but hopefully you can reuse some of the ideas.</p>
Postgresql Concurrency <p>In a project that I'm working, there's a table with a "on update" trigger, that monitors if a boolean column has changed (ex.: false -> true = do some action). But this action can only be done once for a row.</p> <p>There will be multiple clients accessing the database, so I can suppose that eventually, multiple clients will try to update the same row column in parallel.</p> <p>Does the "update" trigger itself handle the concurrency itself, or I need to do it in a transaction and manually lock the table?</p>
<p>Triggers don't handle concurrency, and PostgreSQL should do the right thing whether or not you use explicit transactions.</p> <p>PostgreSQL uses <em>optimistic locking</em> which means the first person to actually update the row gets a lock on that row. If a second person tries to update the row, their update statement waits to see if the first commits their change or rolls back. </p> <p>If the first person commits, the second person gets an error, rather than their change going through and obliterating a change that might have been interesting to them.</p> <p>If the first person rolls back, the second person's update un-blocks, and goes through normally, because now it's not going to overwrite anything.</p> <p>The second person can also use the <code>NOWAIT</code> option, which makes the error happen immediately instead of blocking, if their update conflicts with an unresolved change.</p>
How many dimensions in an array with no value <p>I'm a little lost (still working with Ron Jeffries's book). Here's a simple class:</p> <pre><code>public class Model{ private String[] lines; public void myMethod(){ String[] newLines = new String[lines.length + 2]; for (i = 0, i &lt;= lines.length, i++) { newLines[i] = lines[i]; } } } </code></pre> <p>I have another class that initializes Model, and an empty array, by setting myModel = new String[0]. When I invoke myModel.myMethod(), I get a subscript out of range error. Looking at the debugger, what I see is that myModel.lines has zero dimensions and zero length. Shouldn't it have a dimension and length of 1? Granted the value of lines[0] is null, but the array itself shouldn't be, should it? </p> <p>Any thoughts truly appreciated. </p> <p>Randy</p>
<p>lines will be null, so lines.length will throw an exception.</p> <p>I believe your other class initializing "Model" won't help since Lines itself is private. In fact, whatever you are doing to Model is probably illegal in at least 30 states.</p>
RESTful Authentication <p>What does RESTful Authentication mean and how does it work? I can't find a good overview on Google. My only understanding is that you pass the session key (remeberal) in the URL, but this could be horribly wrong.</p>
<p>How to handle authentication in a RESTful Client-Server architecture is a matter of debate.</p> <p>Commonly, it can be achieved, in the SOA over HTTP world via:</p> <ul> <li>HTTP basic auth over HTTPS;</li> <li>Cookies and session management;</li> <li>Token in HTTP headers (e.g. <em>OAuth</em> 2.0);</li> <li>Query Authentication with additional signature parameters.</li> </ul> <p>You'll have to adapt, or even better mix those techniques, to match your software architecture at best.</p> <p>Each authentication scheme has its own PROs and CONs, depending on the purpose of your security policy and software architecture.</p> <p><strong>HTTP basic auth over HTTPS</strong></p> <p>This first solution, based on the standard HTTPS protocol, is used by most web services.</p> <pre><code>GET /spec.html HTTP/1.1 Host: www.example.org Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== </code></pre> <p>It's easy to implement, available by default on all browsers, but has some known draw-backs, like the awful authentication window displayed on the Browser, which will persist (there is no LogOut-like feature here), some server-side additional CPU consumption, and the fact that the user-name and password are transmitted (over HTTPS) into the Server (it should be more secure to let the password stay only on the client side, during keyboard entry, and be stored as secure hash on the Server).</p> <p>We may use <a href="http://tools.ietf.org/html/rfc2617">Digest Authentication</a>, but it requires also HTTPS, since it is vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">MiM</a> or <a href="http://en.wikipedia.org/wiki/Replay_attack">Replay</a> attacks, and is specific to HTTP.</p> <p><strong>Session via Cookies</strong></p> <p>To be honest, a session managed on the Server is not truly Stateless.</p> <p>One possibility could be to maintain all data within the cookie content. And, by design, the cookie is handled on the Server side (Client in fact does even not try to interpret this cookie data: it just hands it back to the server on each successive request). But this cookie data is application state data, so the client should manage it, not the server, in a pure Stateless world.</p> <pre><code>GET /spec.html HTTP/1.1 Host: www.example.org Cookie: theme=light; sessionToken=abc123 </code></pre> <p>The cookie technique itself is HTTP-linked, so it's not truly RESTful, which should be protocol-independent, IMHO. It is vulnerable to <a href="http://en.wikipedia.org/wiki/Man-in-the-middle_attack">MiM</a> or <a href="http://en.wikipedia.org/wiki/Replay_attack">Replay</a> attacks.</p> <p><strong>Granted via Token (OAuth2)</strong></p> <p>An alternative is to put a token within the HTTP headers, so that the request is authenticated. This is what <em>OAuth</em> 2.0 does, for instance. See <a href="https://tools.ietf.org/html/rfc6749#section-7">the RFC 6749</a>:</p> <pre><code> GET /resource/1 HTTP/1.1 Host: example.com Authorization: Bearer mF_9.B5f-4.1JqM </code></pre> <p>In short, this is very similar to a cookie, and suffers to the same issues: not stateless, relying on HTTP transmission details, and subject to <a href="https://tools.ietf.org/html/rfc6819">a lot of security weaknesses</a> - including MiM and Replay - so is to be used only over HTTPS.</p> <p><strong>Query Authentication</strong></p> <p>Query Authentication consists in signing each RESTful request via some additional parameters on the URI. See <a href="http://broadcast.oreilly.com/2009/12/principles-for-standardized-rest-authentication.html">this reference article</a>. </p> <p>It was defined as such in this article:</p> <blockquote> <p>All REST queries must be authenticated by signing the query parameters sorted in lower-case, alphabetical order using the private credential as the signing token. Signing should occur before URL encoding the query string.</p> </blockquote> <p>This technique is perhaps the more compatible with a Stateless architecture, and can also be implemented with a light session management (using in-memory sessions instead of DB persistence).</p> <p>For instance, here is a generic URI sample from the link above:</p> <pre><code>GET /object?apiKey=Qwerty2010 </code></pre> <p>should be transmitted as such:</p> <pre><code>GET /object?timestamp=1261496500&amp;apiKey=Qwerty2010&amp;signature=abcdef0123456789 </code></pre> <p>The string being signed is <code>/object?apikey=Qwerty2010&amp;timestamp=1261496500</code> and the signature is the SHA256 hash of that string using the private component of the API key.</p> <p>Server-side data caching can be always available. For instance, in our framework, we cache the responses at the SQL level, not at the URI level. So adding this extra parameter doesn't break the cache mechanism.</p> <p>See <a href="http://synopse.info/files/html/Synopse%20mORMot%20Framework%20SAD%201.18.html#TITL_98">this article</a> for some details about RESTful authentication in our client-server ORM/SOA/MVC framework, based on JSON and REST. Since we allow communication not only over HTTP/1.1, but also named pipes or GDI messages (locally), we tried to implement a truly RESTful authentication pattern, and not rely on HTTP specificity (like header or cookies).</p> <p>In practice, the upcoming <a href="https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-05">MAC Tokens Authentication for OAuth 2.0</a> may be a huge improvement in respect to the "Granted by Token" current scheme. But this is still a work in progress, and is tied to HTTP transmission.</p> <p><strong>Conclusion</strong></p> <p>It's worth concluding that REST is not only HTTP-based, even if, in practice, it's mostly implemented over HTTP. REST can use other communication layers. So a RESTful authentication is not just a synonym of HTTP authentication, whatever Google answers. It should even not use the HTTP mechanism at all, but shall be abstracted from the communication layer.</p>
PHP Shipping Calculator <p>Does anyone know of a freeware shipping calculator for PHP? I do not want anything too fancy, and it can be compatible with any of the major US domestic shipping services.</p> <p>If anyone knows of one that is a plugin for CodeIgniter that would be nice.</p> <p>Travis</p>
<p>Usually services like this are based on web services offered from the various couriers. You would send the weight and dimensions of the box you want to ship to their web service, and they would return a corresponding shipping price. Each couriers API would be different. I'm not sure if there are any libraries that aggregate all these services together, but I've never seen one. Since prices can change at any time, you pretty much have to use some kind of web service to access this information. That is, unless you are Amazon sized and have preexisting arrangements for pricing rates on shipping with the various couriers. Just from a quick lookup, here is some of the services that <a href="http://www.fedex.com/us/developer/product/basics.html" rel="nofollow">FedEx</a> offers.</p>
Postage Calculator for PHP <p>Could anyone point me in the right direction for a shipping calculator? I would like something simple and I don't want to sign up for too much stuff.</p> <p>EDIT: I do not want to deal with all the registering and stuff the API would require... I think I may just try to make one using the zone charts USPS provides.</p>
<p>The USPS has rate calculator APIs available for both domestic and international. You can learn more about them at the following site. Hope that helps.</p> <p><a href="https://www.usps.com/webtools/htm/Rate-Calculators-v1-3.htm" rel="nofollow">https://www.usps.com/webtools/htm/Rate-Calculators-v1-3.htm</a></p>
Escaping Bracket [ in a CONTAINS() clause? <p>How can I escape a bracket in a full-text SQL Server <code>contains()</code> query? I've tried all the following, <em>none</em> of which work:</p> <pre><code>CONTAINS(crev.RawText, 'arg[0]') CONTAINS(crev.RawText, 'arg[[0]]') CONTAINS(crev.RawText, 'arg\[0\]') </code></pre> <p>Using double quotes does work, but it <strong>forces the entire search to be a phrase</strong>, which is a showstopper for multiple word queries. </p> <pre><code>CONTAINS(crev.RawText, '"arg[0]"') </code></pre> <p>All I really want to do is escape the bracket, but I can't seem to do that..</p>
<p>You don't have to escape the [ as it has no special meaning in Full Text Search. If you do need to search for an exact match though, you can use "" marks. </p> <p>Further, you can use multiple "" inside the single quotes:</p> <pre><code>CONTAINS('"word1" or "word2" or "word3"') </code></pre> <p>This also works:</p> <pre><code>CONTAINS('"word1" and "word2" and "word3"') </code></pre> <p>Anything put inside the double quotes is treated as exact text. Thus if I were to do a search of the Description field of the Production.ProductDescription table in AdventureWorks, I could use</p> <pre><code>CONTAINS('shifting and "on or off-road"') </code></pre> <p>and it would find matches for the word shifting that also had the phrase "on or off-road". </p> <p>The only special symbol is the ~, it can be used in place of the NEAR command. </p> <pre><code>CONTAINS('shifting ~ smooth') </code></pre> <p>is the same as </p> <pre><code>CONTAINS('shifting NEAR smooth') </code></pre> <p>and will find matches where the words shifting and smooth are near each other. </p>
SQLite C/C++ API unsigned char * <p>Why does the SQLite C/C++ API return <code>unsigned char *</code>s for text values as opposed to the more de-facto <code>char *</code> type?</p> <p>This is somewhat related to <a href="http://stackoverflow.com/questions/75191/unsigned-char">the unsigned char</a> question, except that the SQLite API's decision seems opposite of the conventional <code>char *</code> advice given for string-like values.</p> <p>For example:</p> <pre><code>const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol); </code></pre>
<p>From the <a href="http://www.sqlite.org/capi3ref.html#sqlite3_column_blob">SQLite documentation</a>:</p> <blockquote> <p>(H13821) The sqlite3_column_text(S,N) interface converts the Nth column in the current row of the result set for the prepared statement S into a zero-terminated UTF-8 string and returns a pointer to that string.</p> </blockquote> <p>UTF-8 wants byte values ranging from 0x00 to 0xFF. char can range from -0x80 to 0x7F (signed) or 0x00 to 0xFF (unsigned). Forcing unsigned allows the proper encoding of a UTF-8 string.</p>
how to translate the SQL code "having" condition into LinqToSQL or LinqToEntites? <p>Could you tell me how to translate the following SQL code to Linq To SQL or Linq To Entites?</p> <p>The correct SQL code is: </p> <blockquote> <p>select CollectId,url,userid,pubtime from Collect group by url,collectid,userid,pubtime having pubtime >= (select max(pubtime) from collect d where d.url = collect.url ) order by Collect.pubtime desc</p> </blockquote> <p>The database table script is:</p> <blockquote> <p>if exists (select * from sysobjects where id = OBJECT_ID('[Collect]') and OBJECTPROPERTY(id, 'IsUserTable') = 1) DROP TABLE [Collect]</p> <p>CREATE TABLE [Collect] ( [CollectId] [int] IDENTITY (1, 1) NOT NULL, [Url] [nvarchar] (200) NULL, [UserId] [nvarchar] (50) NULL, [PubTime] [datetime] NULL)</p> <p>ALTER TABLE [Collect] WITH NOCHECK ADD CONSTRAINT [PK_Collect] PRIMARY KEY NONCLUSTERED ( [CollectId] ) SET IDENTITY_INSERT [Collect] ON</p> <p>INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 1,'www.sohu.com','Mike','2008-10-10 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 2,'www.echina365.com','Lily','2008-10-15 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 3,'www.php.com','Tom','2008-10-20 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 4,'www.echina365.com','YaoMing','2008-10-23 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 5,'www.echina365.com','Mike','2008-10-25 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 6,'www.sohu.com','Jack','2008-10-26 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 7,'www.echina365.com','Tracy','2008-11-2 0:00:00') INSERT [Collect] ([CollectId],[Url],[UserId],[PubTime]) VALUES ( 8,'www.php.com','YaoMing','2008-11-5 0:00:00')</p> <p>SET IDENTITY_INSERT [Collect] OFF</p> </blockquote>
<p>Since your "having" condition isn't actually on an aggregated column, couldn't you just use the "where" clause?</p> <pre><code>select distinct CollectId, url, userid, pubtime from Collect where pubtime &gt;= (select max(pubtime) from collect d where d.url = collect.url) order by Collect.pubtime desc </code></pre> <p>This gets the same result given the dataset you've supplied. The LINQ statement then becomes reasonably simple:</p> <pre><code>var rows = (from c in Collect where c.PubTime &gt;= ( from d in Collect where d.Url == c.Url select d.PubTime).Max() orderby c.PubTime descending select c).Distinct(); </code></pre> <p>I could be misinterpreting your intent though. Perhaps my version of the query doesn't do exactly what you want. If so, leave me a comment and I'll delete the answer so as not to confuse the issue.</p>
How do I effectively find duplicate blob rows in MySQL? <p>I have a table of the form </p> <pre><code>CREATE TABLE data { pk INT PRIMARY KEY AUTO_INCREMENT, dt BLOB }; </code></pre> <p>It has about 160,000 rows and about 2GB of data in the blob column (avg. 14kb per blob). Another table has foreign keys into this table.</p> <p>Something like 3000 of the blobs are identical. So what I want is a query that will give me a re map table that will allow me to remove the duplicates.</p> <p>The naive approach took about an hour on 30-40k rows:</p> <pre><code>SELECT a.pk, MIN(b.pk) FROM data AS a JOIN data AS b ON a.dt=b.dt WHERE b.pk &lt; a.pk GROUP BY a.pk; </code></pre> <p>I happen to have, for other reasons, a table that has the sizes of the blobs:</p> <pre><code>CREATE TABLE sizes ( fk INT, // note: non-unique sz INT // other cols ); </code></pre> <p>By building indexes for both fk and another for sz the direct query from that takes about 24 sec with 50k rows:</p> <pre><code>SELECT da.pk,MIN(db.pk) FROM data AS da JOIN data AS db JOIN sizes AS sa JOIN sizes AS sb ON sa.size=sb.size AND da.pk=sa.fk AND db.pk=sb.fk WHERE sb.fk&lt;sa.fk AND da.dt=db.dt GROUP BY da.pk; </code></pre> <p>However that is doing a full table scan on da (the data table). Given that the hit rate should be fairly low I'd think that an index scan would be better. With that in mind in added a 3rd copy of data as a 5th join to get that, and lost about 3 sec.</p> <p>OK so for the question: <em>Am I going to get much better than the second select?</em> If so, how?</p> <p>A bit of a corollary is: if I have a table where the key column's get very heavy use but the rest should only get rarely used, will I ever be better off adding another join of that table to encourage an index scan vs. a full table scan?</p> <p><hr /></p> <p>Xgc on #mysql@irc.freenode.net points out that the adding a utility table like sizes but with a unique constraint on <code>fk</code> might help a lot. Some fun with triggers and what not might make it even not to bad to keep up to date.</p>
<p>You can always use a hashing function (<a href="https://en.wikipedia.org/wiki/MD5" rel="nofollow">MD5</a> or <a href="https://en.wikipedia.org/wiki/SHA-1" rel="nofollow">SHA1</a>) for your data and then compare the hashes.</p> <p>The question is if you can save the hashes in your database?</p>
Is it possible to programmatically add a softkey shortcut to an application in Symbian <p>Is it possible for a Symbian S60 application to automatically add itself to one of the softkeys. The best would be if it could be done at installation time but if there is some API that can be used to add a shortcut the first time the application runs that would also be ok in our case.</p> <p>Does Symbian has some best practices around this. I can guess that some users may be upset if some application overwrites his settings if he/she has configured the softkey shortcuts to refer some other application, </p>
<p>I believe <a href="http://wiki.forum.nokia.com/index.php/ScShortcuts_Engine_Wrapper_API" rel="nofollow">this</a> is what you are looking for. I will not comment on Symbian best practices about that, but would like to say that were an application to override one of my defined shortcuts, I would be annoyed. If it is absolutely necessary, I for one would display a prompt during installation and request whether the user knowing that the application once installed will override one shortcut softkey would want to continue with the installation or not. In fact, when and if you choose to get your application Symbian signed, you may or may not be required to put such a confirmation box during installation.</p>
Integer division rounding with negatives in C++ <p>Suppose <code>a</code> and <code>b</code> are both of type <code>int</code>, and <code>b</code> is nonzero. Consider the result of performing <code>a/b</code> in the following cases:</p> <ol> <li><code>a</code> and <code>b</code> are both nonnegative.</li> <li><code>a</code> and <code>b</code> are both negative.</li> <li>Exactly one of them is negative.</li> </ol> <p>In Case 1 the result is rounded down to the nearest integer. But what does the standard say about Cases 2 and 3? An old draft I found floating on the Internet indicates that it is implementation dependent (yes, even case 2) but the committee is leaning toward making it always 'round toward zero.' Does anyone know what the (latest) standard says? Please answer only based on the standard, not what makes sense, or what particular compilers do.</p>
<p>According to the May 2008 revision,</p> <p>You're right:</p> <blockquote> <p>The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined75).</p> </blockquote> <p>Note 75 says:</p> <blockquote> <p>According to work underway toward the revision of ISO C, the preferred algorithm for integer division follows the rules defined in the ISO Fortran standard, ISO/IEC 1539:1991, in which the quotient is always rounded toward zero.</p> </blockquote> <p>Chances are that C++ will lag C in this respect. As it stands, it's undefined but they have an eye towards changing it.</p> <p>I work in the same department as Stroustrup and with a member of the committee. Things take AGES to get accomplished, and its endlessly political. If it seems silly, it probably is. </p>
What should I teach a beginning Perl programmer? <p>I am going to spend 30 minutes teaching Perl to an experienced programmer. The best way to learn Perl is by writing code. In addition to CPAN, what would you show a programmer so they would understand the expressiveness of Perl, the amount of functionality provided by CPAN, while keeping everything clean and tidy so they walk away comfortable with the language? I'll save the tricky stuff for another day. </p> <pre> use warnings; use strict; # use A_CPAN_LIB; sub example_func1 { # use the CPAN lib or demonstrate some basic feature of Perl } example_func1(); # ... __END__ </pre> <p><hr> Here's what I came up with...<br></p> <h2>Where to Start</h2> <p>Believe it or not, the man pages. Ok, we'll just use perldoc instead to be Windows friendly.</p> <p>The perldoc pages (or man pages on Unix/Mac) are excellent for Perl. You can type man perl or perldoc perl</p> <p><strong>perldoc perl</strong>; # Show an overview and dozens of tutorials; man perl is the same.<br></p> <p><strong>perldoc perlintro</strong>; # A Perl intro for beginners; man perlintro<br> <strong>perldoc perlrequick</strong>; # An example Perl regex tutoral<br></p> <p><strong>perldoc perlfunc</strong>; # Shows builtin Perl functions<br> <strong>perldoc perlre</strong>; # More Perl regex.<br></p> <h2>CPAN</h2> <p>There are thousands of libraries on the Perl library site CPAN.<br> <strong>perl -MCPAN -e 'install DateTime'</strong><br></p> <p>perldoc works for installed modules too: perldoc module<br></p> <p><strong>perldoc DateTime</strong><br> <strong>perldoc DBI</strong>; # Database API. If this doesn't work then install it:<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>perl -MCPAN -e 'install DBI'</strong></p> <h2>Recommended Modules</h2> <p><strong>perl -MCPAN -e 'install Moose'</strong>; # Perl does OOP<br> <strong>perldoc Moose</strong>; # Tell me more about the Moose<br> <strong>perl -MCPAN -e 'install CGI'</strong>; # Quick and dirty web pages<br> <strong>perl -MCPAN -e 'install Catalyst'</strong>; # Big web framework. Sometimes have problems installing. Google is your friend<br> <strong>perl -MCPAN -e 'install CGI::Application'</strong>; # Another web framework<br> <strong>perldoc CGI::Application</strong>; # Take a quick look at the docs<br> <br> A little Q&amp;A.<br> <br> Q: Why should I use Perl instead Ruby or Python?<br> A: More people use Perl. There are more libraries for Perl(way more). Perl is a really great GTD language.<br> <br> Q: Why do people hate Perl?<br> A: You can do some ugly stuff with it. Remember use warnings; use strict; in all of your code. You can check your code before running it. <strong>perl -c</strong> hello.pl<br></p> <p><br></p> <h2>Perl Topics</h2> <h3>Using Perl with Databases</h3> <p><a href="http://www.perl.com/pub/a/1999/10/DBI.html">http://www.perl.com/pub/a/1999/10/DBI.html <br></p> <h3>Using Perl for Web Development</h3> <p><a href="http://www.catalystframework.org">http://www.catalystframework.org <br></p> <h3>OO Perl</h3> <p><a href="http://www.iinteractive.com/moose">http://www.iinteractive.com/moose <br></p> <h3>Perl 1-Liners</h3> <p><a href="http://www.perlmonks.org/?node_id=470397">http://www.perlmonks.org/?node_id=470397<br> <a href="http://sial.org/howto/perl/one-liner">http://sial.org/howto/perl/one-liner</a> <br></p> <h3>Other Tutorials</h3> <p><a href="http://perlmonks.org/index.pl?node=Tutorials">http://perlmonks.org/index.pl?node=Tutorials</a></p> <h2>Books</h2> <p>There are dozens.<br> <a href="http://www.amazon.com/s/ref=nb%5Fss%5Fgw?url=search-alias%3Dstripbooks&amp;field-keywords=perl&amp;x=0&amp;y=0">http://www.amazon.com/s/ref=nb%5Fss%5Fgw?url=search-alias%3Dstripbooks&amp;field-keywords=perl&amp;x=0&amp;y=0</a><br> <br></p> <h2>Websites</h2> <p><a href="http://perlmonks.com">Perlmonks</a><br> <a href="http://www.perl.org">Perl.org</a><br> <a href="http://pleac.sourceforge.net">Pleac</a><br> <a href="http://stackoverflow.com/questions/161872/hidden-features-of-perl">StackOverFlow's Hidden Features of Perl</a><br> <a href="http://www.cpan.org/misc/cpan-faq.html">CPAN FAQ</a><br> <a href="http://www.stonehenge.com/merlyn/LinuxMag">Randall Schwartz's articles</a><br> <br> <br></p> <h2>Getting Help</h2> <p><a href="http://www.nabble.com/Perl-f13578.html">Perl Nabble Forum</a><br> IRC Channels: freenode, irc.perl.org. There are several:<br> <br> irc://irc.perl.org/perl</a><br> irc://irc.perl.org/catalyst</a><br> irc://irc.freenode.net/modperl</a><br> irc://irc.perl.org/perl6</a><br></p>
<p>We wrote a whole book on that called <a href="http://shop.oreilly.com/product/0636920018452.do" rel="nofollow">Learning Perl</a>. Check out the table of contents.</p> <p>This book is a product of teaching people Perl since 1995. It's not geared to any particular application, and shows people the parts of Perl that they'll use for 80% of their Perl programming. We updated it for Perl 5.10, and include sections on using CPAN.</p> <p>Good luck, :)</p>
create databases in ms-access, then delete a particular database. using any vb query or vb code <p>i want to create a number of databases in ms-access using a code or any option of ms-access, but i want delete databases also. Please help me</p>
<p>You could have an empty database named "db1.mdb", and then add this code inside a module <strong>in another</strong> Access database:</p> <pre><code> Set fso = CreateObject("scripting.filesystemobject") fso.CopyFile "c:\db.mdb", "c:\db_copy1.mdb", True fso.CopyFile "c:\db.mdb", "c:\db_copy2.mdb", True fso.CopyFile "c:\db.mdb", "c:\db_copy3.mdb", True fso.DeleteFile "c:\db.mdb" </code></pre>
anyone know of a shared To-do list plugin for eclipse <p>Does anyone know of shared TODO list plugin for Eclipse that allows users in a a development team to all view and edit the same list of tasks?</p>
<p><a href="http://www.eclipse.org/mylyn/" rel="nofollow">Mylyn</a> can be used to integrate issue tracking systems into the IDE.</p> <blockquote> <p>It does this by making tasks a first class part of Eclipse, and integrating rich and offline editing for repositories such as Bugzilla, Trac, and JIRA. </p> </blockquote> <p>If you are not looking for a lightweight solution, then you might give it a try.</p>
How do I divide an ordered list of integers into evenly sized sublists? <p>Does anyone have a good algorithm for taking an ordered list of integers, i.e.:<br /> [1, 3, 6, 7, 8, 10, 11, 13, 14, 17, 19, 23, 25, 27, 28]</p> <p>into a given number of evenly sized ordered sublists, i.e. for 4 it will be:<br /> [1, 3, 6] [7, 8, 10, 11] [13, 14, 17, 19] [23, 25, 27, 28]</p> <p>The requirement being that each of the sublists are ordered and as similar in size as possible. </p>
<p>Splitting the lists evenly means you will have two sizes of lists - size S and S+1.</p> <p>With N sublists, and X elements in the original, you would get:</p> <p>floor(X/N) number of elements in the smaller sublists (S), and X % N is the number of larger sublists (S+1).</p> <p>Then iterate over the original array, and (looking at your example) creating small lists firsts.</p> <p>Something like this maybe:</p> <pre><code> private static List&lt;Integer[]&gt; splitOrderedDurationsIntoIntervals(Integer[] durations, int numberOfIntervals) { int sizeOfSmallSublists = durations.length / numberOfIntervals; int sizeOfLargeSublists = sizeOfSmallSublists + 1; int numberOfLargeSublists = durations.length % numberOfIntervals; int numberOfSmallSublists = numberOfIntervals - numberOfLargeSublists; List&lt;Integer[]&gt; sublists = new ArrayList(numberOfIntervals); int numberOfElementsHandled = 0; for (int i = 0; i &lt; numberOfIntervals; i++) { int size = i &lt; numberOfSmallSublists ? sizeOfSmallSublists : sizeOfLargeSublists; Integer[] sublist = new Integer[size]; System.arraycopy(durations, numberOfElementsHandled, sublist, 0, size); sublists.add(sublist); numberOfElementsHandled += size; } return sublists; } </code></pre>
sql - Using aggregate functions (min/max) as part of select statement <p>I am trying to return the minimum and maximum prices for a villa booking system. I have a look up table that stores the price for each week for each villa. </p> <p>I am using the min and max functions to do this within the select but I'm having lots of problems. Can anyone explain where i'm going wrong? Heres the sp</p> <pre><code>ALTER PROCEDURE spVillaGet -- Add the parameters for the stored procedure here @accomodationTypeFK int = null, @regionFK int = null, @arrivalDate datetime = null, @numberOfNights int = null, @sleeps int = null, @priceFloor money = null, @priceCeil money = null </code></pre> <p>AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;</p> <pre><code>-- Insert statements for procedure here SELECT tblVillas.name, tblVillas.introduction, tblVillas.italian_introduction, tblVillas.uk_content, tblVillas.italian_content, tblVillas.sleeps, tblVillas.postcode, tblLkUpRegions.regionName, tblLkUpAccomodationTypes.accomodationType, MIN(price) As MinPrice, MAX(price) As MaxPrice FROM tblVillas LEFT JOIN tblLkUpRegions on tblVillas.regionFK = tblLkUpRegions.regionID LEFT JOIN tblLkUpAccomodationTypes on tblVillas.accomodationTypeFK = tblLkUpAccomodationTypes.accomodationId LEFT JOIN tblWeeklyPrices on tblWeeklyPrices.villaFK = tblVillas.villaId WHERE ((@accomodationTypeFK is null OR accomodationTypeFK = @accomodationTypeFK) AND (@regionFK is null OR regionFK = @regionFK) AND (@sleeps is null OR sleeps = @sleeps) AND tblVillas.deleted = 0) GROUP BY tblVillas.name </code></pre>
<p>You don't elaborate on <em>what</em> problems you are getting, but this is probably one: you need to specify <strong>all</strong> the non-aggregate columns in the GROUP BY clause i.e.:</p> <pre><code>GROUP BY tblVillas.name, tblVillas.introduction, tblVillas.italian_introduction, tblVillas.uk_content, tblVillas.italian_content, tblVillas.sleeps, tblVillas.postcode, tblLkUpRegions.regionName, tblLkUpAccomodationTypes.accomodationType </code></pre> <p>From your follow-up comment is appears that some of your columns are of a data type that can't be used in a GROUP BY clause. Try this instead:</p> <pre><code>SELECT tblVillas.name, tblVillas.introduction, tblVillas.italian_introduction, tblVillas.uk_content, tblVillas.italian_content, tblVillas.sleeps, tblVillas.postcode, tblLkUpRegions.regionName, tblLkUpAccomodationTypes.accomodationType, (SELECT MIN(price) FROM tblWeeklyPrices where tblWeeklyPrices.villaFK = tblVillas.villaId) As MinPrice, (SELECT MAX(price) FROM tblWeeklyPrices where tblWeeklyPrices.villaFK = tblVillas.villaId) As MaxPrice FROM tblVillas LEFT JOIN tblLkUpRegions on tblVillas.regionFK = tblLkUpRegions.regionID LEFT JOIN tblLkUpAccomodationTypes on tblVillas.accomodationTypeFK = tblLkUpAccomodationTypes.accomodationId WHERE ((@accomodationTypeFK is null OR accomodationTypeFK = @accomodationTypeFK) AND (@regionFK is null OR regionFK = @regionFK) AND (@sleeps is null OR sleeps = @sleeps) AND tblVillas.deleted = 0) </code></pre>
threadPool.SetMaxThreads returning false <p>My understanding of SetMaxThreads() in C# was that it can not be set to less than the number of processors.</p> <p>But in my code I am unable to set the number to less than 8, I have no idea why this is.</p> <p>If I set it to lower it returns false!</p> <p>(Running an Intel Core 2)</p>
<p>I think I have solved this problem now (kinda!), if SetMinThreads() is first set to the minimum number, so in my case 2, then we are able to set the max number of threads to a value less than 8.</p> <p>I am aware that this then ties of resources with idle threads, but for my purposes it is a suitable work around.</p>
How can I make log4perl output easier to read? <p>When using <a href="http://log4perl.sourceforge.net/" rel="nofollow">log4perl</a>, the debug log layout that I'm using is :</p> <pre><code>log4perl.appender.D10.layout=PatternLayout log4perl.appender.D10.layout.ConversionPattern=%d [pid=%P] %p %F{1} (%L) %M %m%n log4perl.appender.D10.Filter = DebugAndUp </code></pre> <p>This produces very verbose debug logs, for example:</p> <pre><code>2008/11/26 11:57:28 [pid=25485] DEBUG SomeModule.pm (331) functions::SomeModule::Test Test XXX was successfull 2008/11/26 11:57:29 [pid=25485] ERROR SomeOtherUnrelatedModule.pm (99999) functions::SomeModule::AnotherTest AnotherTest YYY has faled </code></pre> <p>This works great, and provides excellent debugging data.</p> <p>However, each line of the debug log contains different function names, pid length, etc. This makes each line layout differently, and makes reading debug logs much harder than it needs to be.</p> <p>Is there a way in log4perl to format the line so that the debugging metadata (everything up until the actual log message) be padded at the end with spaces/tabs, and have the actual message start at the same column of text?</p>
<p>You can pad the single fields that make up your entries. For example [pid=%5P] will always give you at least 5 characters for the PID. </p> <p>The <a href="http://search.cpan.org/~mschilli/Log-Log4perl-1.19/lib/Log/Log4perl/Layout/PatternLayout.pm#Quantify_placeholders">"Quantify Placeholders" section</a> in the docs for Log::Log4perl::Layout gives more details. </p>
Which is better apply two conditions in nested If or using single with And? <p>Nested If or single if with And operator, which is better approach?<br> <strong>Single If with And</strong> </p> <pre><code>if (txtPackage.Text != string.Empty &amp;&amp; txtPackage.Text == "abc") { // } </code></pre> <p><strong>Nested If</strong> </p> <pre><code>if (txtPackage.Text != string.Empty) { if (txtPackage.Text == "abc") { // } } </code></pre>
<p>Are you going to do something different in the 'nested if' example if, in fact, txtPackage.Text isn't empty but contains something other than "abc"?</p> <p>If you aren't, I'd ask why are you checking for string.empty at all? </p> <p>You could just write:</p> <pre><code>if (txtPackage.Text == "abc") { // } </code></pre> <p>and be done with it.</p> <p>Totally depends upon what you want to do in the end.</p>
How do I generate a compiled lambda with method calls? <p>I'm generating compiled getter methods at runtime for a given member. Right now, my code just assumes that the result of the getter method is a string (worked good for testing). However, I'd like to make this work with a custom converter class I've written, see below, "ConverterBase" reference that I've added.</p> <p>I can't figure out how to add the call to the converter class to my expression tree.</p> <pre><code> public Func&lt;U, string&gt; GetGetter&lt;U&gt;(MemberInfo info) { Type t = null; if (info is PropertyInfo) { t = ((PropertyInfo)info).PropertyType; } else if (info is FieldInfo) { t = ((FieldInfo)info).FieldType; } else { throw new Exception("Unknown member type"); } //TODO, replace with ability to specify in custom attribute ConverterBase typeConverter = new ConverterBase(); ParameterExpression target = Expression.Parameter(typeof(U), "target"); MemberExpression memberAccess = Expression.MakeMemberAccess(target, info); //TODO here, make the expression call "typeConverter.FieldToString(fieldValue)" LambdaExpression getter = Expression.Lambda(memberAccess, target); return (Func&lt;U, string&gt;)getter.Compile(); } </code></pre> <p>I'm looking for what to put in the second TODO area (I can handle the first :)).</p> <p>The resulting compiled lambda should take an instance of type U as a param, call the specified member access function, then call the converter's "FieldToString" method with the result, and return the resulting string.</p>
<p>Can you illustrate what (if it was regular C#) you want the expression to evaluate? I can write the expression easily enough - I just don't fully understand the question...</p> <p>(edit re comment) - in that case, it'll be something like:</p> <pre><code> ConverterBase typeConverter = new ConverterBase(); var target = Expression.Parameter(typeof(U), "target"); var getter = Expression.MakeMemberAccess(target, info); var converter = Expression.Constant(typeConverter, typeof(ConverterBase)); return Expression.Lambda&lt;Func&lt;U, string&gt;&gt;( Expression.Call(converter, typeof(ConverterBase).GetMethod("FieldToString"), getter), target).Compile(); </code></pre> <p>Or if the type refuses to bind, you'll need to inject a cast/convert:</p> <pre><code> MethodInfo method = typeof(ConverterBase).GetMethod("FieldToString"); return Expression.Lambda&lt;Func&lt;U, string&gt;&gt;( Expression.Call(converter, method, Expression.Convert(getter, method.GetParameters().Single().ParameterType)), target).Compile(); </code></pre>
Viewing contents of a .jar file <p>What would be the easiest way to view classes, methods, properties, etc. inside a jar file? I'm looking for something equivalent to the very useful <I> Lutz Roeder .NET Reflector </I> - for Java</p>
<p>Using the JDK, <code>jar tf</code> will list the files in the jar. <code>javap</code> will give you more details from a particular class file.</p>
Best nntp to web gateway? <p>My company uses usenet groups on an internal nntp server and I would like to add a web server to this that would allow the usual browsing and searching but in addition provide an archive of old messages that may have expired on the server. This is mainly for searching the archives so ability to post is not important.</p> <p>Can anyone recommend a piece of software the would act as such a gateway? Most of the stuff I found on Google appears to be either no longer maintained or doesn't offer the archive ability.</p>
<p>Gmane seems to be nice. You could also look into a NNTP -> Email thing and use any of the available email web archive software.</p>
Regexps in Elisp to include newlines <p>I'm trying to add a special markup to Python documentation strings in emacs (python-mode).</p> <p>Currently I'm able to extract a single line with:</p> <pre><code>(font-lock-add-keywords 'python-mode '(("\\(\"\\{3\\}\\.+\"\\{3\\}\\)" 1 font-lock-doc-face prepend))) </code></pre> <p>This works now:</p> <pre><code>"""Foo""" </code></pre> <p>But as soon there is a newline like:</p> <pre><code>""" Foo """ </code></pre> <p>It doesn't work anymore. This is logical, since <code>.</code> doesn't include newlines (<code>\n</code>). Should I use a character class?</p> <p>How can I correct this regular expression to include everything between <code>""" """</code>?</p> <p>Thanks in advance!</p>
<pre><code>"\\(\"\\{3\\}\\(.*\n?\\)*?\"\\{3\\}\\)" </code></pre> <p>The "*?" construct is the non-greedy version of "*".</p>
How to automatically create a file with the latest compile time and include it into a library? <p>I have a library consisting of approx 100 source files. I want one of the sources to be always rebuilt if any of the other files have been compiled but I don't want it built every time I run the make/build.</p> <p>Basically I want this file to have the last build date/time built into it so any application linking to the library can check the last build time/date. Is there any other way to do this?</p>
<p>Let the object file containing the build timestamp depend on all the other object files:</p> <pre><code>version.o: $(OBJECTS) </code></pre>
ASP.NET MVC Beta 1 - Will My Existing User Controls Work In My Views As-Is? <p>I understand that you can now create MVC-specific user controls, but will my existing standard ASCX user controls work in an MVC view? </p> <p>I understand that MVC pages have a completely different lifecycle but will, for example, a Page_Load method be invoked as normal when the control is sitting in a view?</p>
<p>If your standard ASCX controls do not have control events. There is no viewstate in MVC so that'll have to change.</p> <p>The normal page lifecycle is still executed. E.g. Page load, init, prerender, etc. The main thing is viewstate.</p>
What build tool do you use professionally? <p>At home, I use CTRL+SHIFT+B or F7 or whatever key sequence initiates the build for my build tool. At work, this doesn't quite cut it.</p> <p>At my first job (an internship) we used a product called Visual Build, which I have come to like very much. It's the best build tool I've ever worked with. The down side here is that it's not free.</p> <p>At my latest job, I came in knowing literally nothing about Ant. Now, unfortunately, I've become deeply involved in our build processes, and cannot extricate myself. It works, yes, but after coming from Visual build, it seems like it's fighting me every step of the way. Yes, it's free, but we're not trying to be a free-software-only development company or anything.</p> <p>I've never looked in to <code>make</code> or any other build tools, so I don't really know what else is out there.</p> <p>Has anybody ever seen or had experience with Visual Build? Mostly I'm fond of a few key things:</p> <ol> <li>it has a GUI</li> <li>it runs arbitrary VBScript without the need of a compiled class</li> <li>you can step through the build process, or start from anywhere in the middle.</li> </ol> <p>Are there any free build tools that have this? Is there any way to convince people that it's worth it to move on? It's 2008. We use IDEs to develop, why not (IBEs) to build?</p> <p><b>Edit: </b> I'm mostly looking for an answer to my last questions; Is there a solution with a built-in GUI that I can use for free?</p>
<p>Not very sophisticated, but we use a set of batch files. And that works great.</p>
The ';' character, hexadecimal value 0x3B, cannot be included in a name <p>I have seen the error "The ';' character, hexadecimal value 0x3B, cannot be included in a name." in my log files for an ASP.NET Web App. The url that's logged looks something like this:</p> <pre><code>mypage.aspx?paramone=one+two&amp;amp;paramtwo=zero+1 </code></pre> <p>So my first question is what type of system/browser is encoding the original query string? (This happens rarely)</p> <p>I've tried to address this problem with the following snippet of code in the Page_Load() event:</p> <pre><code>string rawUrl = Request.RawUrl; if (rawUrl.Contains(amp)) { rawUrl = rawUrl.Replace("&amp;amp;", "&amp;"); Server.Transfer(rawUrl, false); return; } </code></pre> <p>However when it transfers back to this page the <code>&amp;amp;</code> is back in the query string. So I'm guessing that the .Transfer() function encodes the first param.</p> <p>Suggestions about solving this problem?</p>
<ol> <li><p>Your web server should be able to log the "user agent" field from the HTTP Request, which should enable you to identify the culprit.</p></li> <li><p>Don't fix it - there's a very well defined set of legal syntaxes for URI parameters, and this ain't one of them.</p></li> </ol>
Steps in the memory allocation process for Java objects <p><strong>What happens in the memory when a class instantiates the following object?</strong> </p> <pre><code>public class SomeObject{ private String strSomeProperty; public SomeObject(String strSomeProperty){ this.strSomeProperty = strSomeProperty; } public void setSomeProperty(String strSomeProperty){ this.strSomeProperty = strSomeProperty; } public String getSomeProperty(){ return this.strSomeProperty; } } </code></pre> <p>In class <code>SomeClass1</code>:</p> <pre><code>SomeObject so1 = new SomeObject("some property value"); </code></pre> <p>In class <code>SomeClass2</code>:</p> <pre><code>SomeObject so2 = new SomeObject("another property value"); </code></pre> <p><strong>How is memory allocated to the newly instantiated object and its properties?</strong> </p>
<p>Let's step through it:</p> <pre><code>SomeObject so1 = new SomeObject("some property value"); </code></pre> <p>... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:</p> <pre><code>String tmp = new String("some property value"); SomeObject so1 = new SomeObject(tmp); // Not that you would normally write it in this way. </code></pre> <p>(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)</p> <p>So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called <code>tmp</code>; in your original form Java handles it without naming it.</p> <p>Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field, <code>strSomeProperty</code>.</p> <p>Bear in mind that <code>strSomeProperty</code> is just a reference to a String. For now, it'll be initialised to null.</p> <p>Next, the constructor is executed. </p> <pre><code>this.strSomeProperty = strSomeProperty; </code></pre> <p>All this does is copy the <em>reference</em> to the String, into your <code>strSomeProperty</code> field.</p> <p>Finally, space is allocated for the object reference <code>so1</code>. This is set with a reference to the SomeObject.</p> <p><code>so2</code> works in exactly the same way.</p>
What are the advantages of dynamic scoping? <p>I've learned that <a href="http://en.wikipedia.org/wiki/Static_scoping#Static_scoping_.28also_known_as_lexical_scoping.29" rel="nofollow">static scoping</a> is the only sane way to do things, and that <a href="http://en.wikipedia.org/wiki/Static_scoping#Dynamic_scoping" rel="nofollow">dynamic scoping</a> is the tool of the devil, and results only from poor implementations of interpreters/compilers. </p> <p>Then I saw this snippet from a <a href="http://community.schemewiki.org/?scheme-vs-common-lisp" rel="nofollow">Common Lisp vs. Scheme</a> article:</p> <pre> Both Lexically and Dynamically Lexical scope only, per the standard. scoped special vars. Common Dynamically scoped vars are provided Lisp just wins on this point. by some implementations as an extension but code using them is not portable. (I have heard the arguments about whether Dynamic scoping is or is not a Bad Idea in the first place. I don't care. I'm just noting that you can do things with it that you can't easily do without it.) </pre> <p>Why does Common Lisp "just win on this point"? What things are easier to do with dynamic scoping? I really can't justify ever needing it / seeing it as a good thing.</p>
<p>Like everything else, Dynamic Scoping is merely a tool. Used well it can make certain tasks easier. Used poorly it can introduce bugs and headaches.</p> <p>I can certainly see some uses for it. One can eliminate the need to pass variables to some functions.</p> <p>For instance, I might set the display up at the beginning of the program, and every graphic operation just assumes this display.</p> <p>If I want to set up a window inside that display, then I can 'add' that window to the variable stack that otherwise specifies the display, and any graphic operations performed while in this state will go to the window rather than the display as a whole.</p> <p>It's a contrived example that can be done equally well by passing parameters to functions, but when you look at some of the code this sort of task generates you realize that global variables are really a much easier way to go, and <strong>dynamic scoping gives you a lot of the sanity of global variables with the flexibility of function parameters</strong>.</p>
Putting JVM arguments in a file to be picked up at runtime <p>I'm building a jar of my current application, which required several JVM arguments to be set.</p> <p>Is there a way of setting these JVM arguments in a file rather than on the command line?</p> <p>I've done some hunting and it looks like I might be able to do something witha java.properties file, possibly by setting a java-args, but I can't find any reference to the format for doing this.</p> <p>Am I barking up the wrong tree?</p> <p>Is this possible and if so how?</p> <p>If not is there some other way to specify the JVM arguments?</p>
<p>You could of course write a batch script to execute the JVM. The batch script could look into the file and call with the appropriate parameters. This would be OS dependent though.</p>
How do I test database-related code with NUnit? <p>I want to write unit tests with NUnit that hit the database. I'd like to have the database in a consistent state for each test. I thought transactions would allow me to "undo" each test so I searched around and found several articles from 2004-05 on the topic:</p> <ul> <li><a href="http://weblogs.asp.net/rosherove/archive/2004/07/12/180189.aspx">http://weblogs.asp.net/rosherove/archive/2004/07/12/180189.aspx</a></li> <li><a href="http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx">http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx</a></li> <li><a href="http://davidhayden.com/blog/dave/archive/2004/07/12/365.aspx">http://davidhayden.com/blog/dave/archive/2004/07/12/365.aspx</a></li> <li><a href="http://davidhayden.com/blog/dave/archive/2004/07/12/365.aspx">http://haacked.com/archive/2005/12/28/11377.aspx</a></li> </ul> <p>These seem to resolve around implementing a custom attribute for NUnit which builds in the ability to rollback DB operations after each test executes.</p> <p>That's great but... </p> <ol> <li>Does this functionality exists somewhere in NUnit natively?</li> <li>Has this technique been improved upon in the last 4 years? </li> <li>Is this still the best way to test database-related code?</li> </ol> <p><hr /></p> <p>Edit: it's not that I want to test my DAL specifically, it's more that I want to test pieces of my code that interact with the database. For these tests to be "no-touch" and repeatable, it'd be awesome if I could reset the database after each one.</p> <p>Further, I want to ease this into an existing project that has no testing place at the moment. For that reason, I can't practically script up a database and data from scratch for each test.</p>
<p>NUnit now has a [Rollback] attribute, but I prefer to do it a different way. I use the <a href="http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx">TransactionScope</a> class. There are a couple of ways to use it.</p> <pre><code>[Test] public void YourTest() { using (TransactionScope scope = new TransactionScope()) { // your test code here } } </code></pre> <p>Since you didn't tell the TransactionScope to commit it will rollback automatically. It works even if an assertion fails or some other exception is thrown.</p> <p>The other way is to use the [SetUp] to create the TransactionScope and [TearDown] to call Dispose on it. It cuts out some code duplication, but accomplishes the same thing.</p> <pre><code>[TestFixture] public class YourFixture { private TransactionScope scope; [SetUp] public void SetUp() { scope = new TransactionScope(); } [TearDown] public void TearDown() { scope.Dispose(); } [Test] public void YourTest() { // your test code here } } </code></pre> <p>This is as safe as the using statement in an individual test because NUnit will guarantee that TearDown is called.</p> <p>Having said all that I do think that tests that hit the database are not really unit tests. I still write them, but I think of them as integration tests. I still see them as providing value. One place I use them often is in testing LINQ to SQL code. I don't use the designer. I hand write the DTO's and attributes. I've been known to get it wrong. The integration tests help catch my mistake.</p>
VS2008 Navigate to class definition add-in <p>I am looking for a Visual Studio add-in that would analyze the text around the cursor position and navigate to the corresponding class definition.</p> <p>For example I have this XML file that is currently open:</p> <pre><code>&lt;object id="abc" type="MyProject.Foo.Bar, MyProject"/&gt; </code></pre> <p>If I put the cursor somewhere between the double quotes on the <em>type</em> attribute the add-in should obtain the string <em>"MyProject.Foo.Bar, MyProject"</em> and search for all projects and project references in the current solution for the given type and if it finds one, it should navigate to the class definition (or metadata if the source code is not available in the current solution).</p> <p>If such add-in doesn't exist I would greatly appreciate some pointers that could help me writing one.</p>
<p>Well you could use the '<strong><a href="http://msdn.microsoft.com/en-us/library/f5yx24a6(VS.80).aspx" rel="nofollow">Code Definition Window</a></strong>' that comes with the VS2008 IDE. When you place your cursor, the Code Def window dynamically updates with the source code for that type. <em>Works with regular source files.. don't have the IDE at hand to verify with XAML/XML</em></p> <p>Also you could 'Jump to Symbol' key combo but you would need CodeRush Express add in for that. Shift+Ctrl+Q. More details <a href="http://madcoderspeak.blogspot.com/2008/11/ide-ninja-shortcuts-with-vs2008-and.html" rel="nofollow">here</a>.</p>
Drop down list box with dynamic month and year in Date Prompt in Cognos <p>I want to add the current month and the last 2 months for user to select in prompt. e.g. if this month is <code>2008 Nov</code>, then I wil see foowing in <code>ddlbox</code>:</p> <pre><code>112008 102008 092008 </code></pre> <p>May I know how to do it? </p>
<pre><code>&lt;asp:DropDownList ID="DropDownList1" runat="server"&gt; &lt;/asp:DropDownList&gt; for (int i = 0; i &lt; 3; i++) { ListItem item = new ListItem(string.Format("{0: MM/yyyy}", DateTime.Now.AddMonths(-i))); DropDownList1.Items.Add(item); } </code></pre> <p>Try this :)</p>
Recommendations for column-oriented database <p>I've found databases typically come in two flavors, your traditional row-oriented RDBMS or an object oriented database (OODBMS). However, in the mid 90s I remember, a new breed of databases showing up that were column oriented. Some of these were given the term 4GL, but I don't think it was a term that stuck.</p> <p>What I'd like to know is the following:</p> <ul> <li>What column oriented databases still exist?</li> <li>What are the performance characteristics of these databases?</li> <li>Are there any open source column oriented databases?</li> <li>What platforms do they interoperate with (.NET, Java, etc)</li> <li>What's been your general experience with them?</li> </ul> <p>The two column oriented databases that I remember working with are FAME and KDB.</p>
<p><a href="http://en.wikipedia.org/wiki/HBase">HBase</a> is an open-source column-oriented database system modelled on <a href="http://en.wikipedia.org/wiki/BigTable">Google's BigTable</a>.</p>
How can I convert a hex string to a byte array? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa-in-c">How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?</a> </p> </blockquote> <p>Can we convert a hex string to a byte array using a built-in function in C# or do I have to make a custom method for this?</p>
<p>Here's a nice fun LINQ example.</p> <pre><code>public static byte[] StringToByteArray(string hex) { return Enumerable.Range(0, hex.Length) .Where(x =&gt; x % 2 == 0) .Select(x =&gt; Convert.ToByte(hex.Substring(x, 2), 16)) .ToArray(); } </code></pre>
Unit Testing: Creating a 'mock' request to simulate a MVC page request <p>How do I go about creating a mock request for my asp.net-mvc application for unit-testing?</p> <p>What options do I have?</p> <p>I am using FormsCollection in my Actions so I can simulate form input data also.</p>
<p>You just have to create a new instance of FormCollection and add the data inside of it.</p> <p>So you can call something like this without mocking anything.</p> <pre><code>var result = controller.Create(new FormCollection { { "InvoiceId", "-1" } }) as RedirectToRouteResult; </code></pre> <p>Otherwise if your code calls something like Request or HttpContext you can use the following extension method (inspired from Scott Hanselman's <a href="http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx" rel="nofollow">example</a>)</p> <p>I am using RhinoMocks.</p> <pre><code>public static HttpContextBase SetHttpContext(this MockRepository mocks, Controller controller, HttpCookieCollection cookies) { cookies = cookies ?? new HttpCookieCollection(); var request = mocks.StrictMock&lt;HttpRequestBase&gt;(); var context = mocks.StrictMock&lt;HttpContextBase&gt;(); var response = mocks.StrictMock&lt;HttpResponseBase&gt;(); SetupResult.For(context.Request).Return(request); SetupResult.For(context.Response).Return(response); SetupResult.For(request.Cookies).Return(cookies); SetupResult.For(request.IsSecureConnection).Return(false); SetupResult.For(response.Cookies).Return(cookies); if (controller != null) { controller.ControllerContext = new ControllerContext(context, new RouteData(), controller); } if (!string.IsNullOrEmpty(requestUrl)) { request.SetupRequestUrl(requestUrl); SetupResult.For(response.ApplyAppPathModifier(null)).IgnoreArguments().Return(null); } return context; } </code></pre>
How do I set a field value in an C# Expression tree? <p>Given:</p> <pre><code>FieldInfo field = &lt;some valid string field on type T&gt;; ParameterExpression targetExp = Expression.Parameter(typeof(T), "target"); ParameterExpression valueExp = Expression.Parameter(typeof(string), "value"); </code></pre> <p>How do I compile a lambda expression to set the field on the "target" parameter to "value"?</p>
<p><strong>.Net 4.0</strong> : now that there's <code>Expression.Assign</code>, this is easy to do:</p> <pre><code>FieldInfo field = typeof(T).GetField("fieldName"); ParameterExpression targetExp = Expression.Parameter(typeof(T), "target"); ParameterExpression valueExp = Expression.Parameter(typeof(string), "value"); // Expression.Property can be used here as well MemberExpression fieldExp = Expression.Field(targetExp, field); BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp); var setter = Expression.Lambda&lt;Action&lt;T, string&gt;&gt; (assignExp, targetExp, valueExp).Compile(); setter(subject, "new value"); </code></pre> <p><strong>.Net 3.5</strong> : you can't, you'll have to use System.Reflection.Emit instead:</p> <pre><code>class Program { class MyObject { public int MyField; } static Action&lt;T,TValue&gt; MakeSetter&lt;T,TValue&gt;(FieldInfo field) { DynamicMethod m = new DynamicMethod( "setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(Program)); ILGenerator cg = m.GetILGenerator(); // arg0.&lt;field&gt; = arg1 cg.Emit(OpCodes.Ldarg_0); cg.Emit(OpCodes.Ldarg_1); cg.Emit(OpCodes.Stfld, field); cg.Emit(OpCodes.Ret); return (Action&lt;T,TValue&gt;) m.CreateDelegate(typeof(Action&lt;T,TValue&gt;)); } static void Main() { FieldInfo f = typeof(MyObject).GetField("MyField"); Action&lt;MyObject,int&gt; setter = MakeSetter&lt;MyObject,int&gt;(f); var obj = new MyObject(); obj.MyField = 10; setter(obj, 42); Console.WriteLine(obj.MyField); Console.ReadLine(); } } </code></pre>
Building a database driven menu with ASP.NET, JQuery and Suckerfish <p>I'm attempting at creating a menu from a table using the Suckerfish css menu and Jquery. I'm using this as my reference: <a href="http://www.aspcode.net/Suckerfish-menu-with-ASPNET-and-JQuery.aspx" rel="nofollow">Suckerfish menu with ASP.NET and JQuery</a> and I have it working with manually supplied links (much like in the article).</p> <p>Where I'm having issues is writing the recursive function to get the menu items from the database and create the new menu items in the proper hierarchy. My database table looks like so:</p> <p>Table Menu <hr /></p> <p>MenuID ParentID Link Text</p> <p>The idea being that if an item is a parent-level item the MenuID and ParentID are the same, if it's a child it will have the MenuID of it's parent in the ParentID field. I'm needing to create a function that can go through and find all of the children for the parents (could be a few levels) and have it replace manual entries like this:</p> <pre><code> Dim Foo As New MenuItem("#", "Foo", Me) Items.Add(Foo) Foo.Items.Add(New MenuItem("#", "1", Me)) Foo.Items.Add(New MenuItem("#", "2", Me)) Foo.Items.Add(New MenuItem("#", "3", Me)) Foo.Items.Add(New MenuItem("#", "4", Me)) </code></pre> <p>I'm open to changing the database table structure if necessary and basically doing anything else to get this going.</p> <p>Thanks for any input, it's much appreciated.</p>
<p>That method of representing hierarchical data is easy to understand for humans but difficult to extract data from, because it requires recursion to extract the full hierarchy. Some flavors of SQL have commands that will do this for you, but that is what is going on behind the scenes.</p> <p>I suggest you read <a href="http://www.sqlteam.com/article/more-trees-hierarchies-in-sql" rel="nofollow">More Trees &amp; Hierarchies in SQL</a>, and restructure your schema using the materialized path method that it explains. It is easy to query against and scales really well.</p>
Best practices for version control comments <p>There is a lot of conversation about commenting code, but how about commenting on check-ins?</p> <p>I found this blog post: <a href="http://redbitbluebit.com/subversion-check-in-comment-great-practices/" rel="nofollow">http://redbitbluebit.com/subversion-check-in-comment-great-practices/</a></p> <p>As the guy who is putting together the release notes, I am looking for ways to make that job easier.</p> <p>Currently we defined our own scheme with <code>&lt;Begin_Doc&gt;...&lt;End_Doc&gt;</code> for anything that should be published to our software customers. But even for the internal stuff, I'd like to know the "why" for every change.</p>
<p>Every feature has a ticket/issue/bugreport/task/whatever-you-call-it, and the ticket number is always referenced in the check-in comment. This gives context.</p>
How to remove elements from xml using xslt with stylesheet and xsltproc? <p>I have a lot of XML files which have something of the form:</p> <pre> &lt Element fruit="apple" animal="cat" /&gt </pre> <p>Which I want to be removed from the file.</p> <p>Using an XSLT stylesheet and the Linux command-line utility xsltproc, how could I do this?</p> <p>By this point in the script I already have the list of files containing the element I wish to remove, so the single file can be used as a parameter.</p> <p><hr /></p> <p><strong>EDIT:</strong> the question was originally lacking in intention.</p> <p>What I am trying to achieve is to remove the entire element "Element" where (fruit=="apple" &amp;&amp; animal=="cat"). In the same document there are many elements named "Element", I wish for these to remain. So</p> <pre> &lt Element fruit="orange" animal="dog" /&gt &lt Element fruit="apple" animal="cat" /&gt &lt Element fruit="pear" animal="wild three eyed mongoose of kentucky" /&gt </pre> <p>Would become:</p> <pre> &lt Element fruit="orange" animal="dog" /&gt &lt Element fruit="pear" animal="wild three eyed mongoose of kentucky" /&gt </pre>
<p>Using one of the most fundamental XSLT design patterns: "Overriding the <a href="http://www.w3.org/TR/xslt#copying"><strong>identity transformation</strong></a>" one will just write the following:</p> <pre> &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> &lt;xsl:output omit-xml-declaration="yes"/> &lt;xsl:template match="node()|@*"> &lt;xsl:copy> &lt;xsl:apply-templates select="node()|@*"/> &lt;/xsl:copy> &lt;/xsl:template> &lt;xsl:template match="Element[@fruit='apple' and @animal='cat']"/> &lt;/xsl:stylesheet> </pre> <p><strong>Do note</strong> how the second template overrides the identity (1st) template only for elements named "Element" that have an attribute "fruit" with value "apple" and attribute "animal" with value "cat". This template has empty body, which means that the matched element is simply ignored (nothing is produced when it is matched).</p> <p>When this transformation is applied on the following source XML document:</p> <pre> &lt;doc>... &lt;Element name="same">foo&lt;/Element>... &lt;Element fruit="apple" animal="cat" /> &lt;Element fruit="pear" animal="cat" /> &lt;Element name="same">baz&lt;/Element>... &lt;Element name="same">foobar&lt;/Element>... &lt;/doc> </pre> <p>the wanted result is produced:</p> <pre> &lt;doc>... &lt;Element name="same">foo&lt;/Element>... &lt;Element fruit="pear" animal="cat"/> &lt;Element name="same">baz&lt;/Element>... &lt;Element name="same">foobar&lt;/Element>... &lt;/doc> </pre> <p>More code snippets of using and overriding the identity template can be found <strong><a href="http://www.dpawson.co.uk/xsl/sect2/identity.html">here</a></strong>.</p>
CreateProcessAsUser not working correctly in my experiments <p>I am trying to do the following: 1. I am logged in as Administrator account in my XP with SP2 machine running VS.NET 2005 2. This machine also has another account user1 which is a guest account 3. I am running a program as Administrator, from this program i want to launch a notepad.exe process which will be running under the user1 security context 4. I specifically want to use CreateProcessasUser to do this..</p> <p>This is the code snipper which will explain what i have been trying..</p> <pre><code>const string GRANTED_ALL = "10000000"; const int LOGON32_LOGON_INTERACTIVE = 2; const int LOGON32_LOGON_NETWORK = 3; const int LOGON32_LOGON_BATCH = 4; const int LOGON32_LOGON_SERVICE = 5; const int LOGON32_LOGON_UNLOCK = 7; const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8; const int LOGON32_LOGON_NEW_CREDENTIALS = 9; const int LOGON32_PROVIDER_DEFAULT = 0; static IntPtr hToken = IntPtr.Zero; static IntPtr hTokenDuplicate = IntPtr.Zero; static void Main(string[] args) { int last_error = 0; if(LogonUser("user1",null,"#welcome123", LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out hToken)) { last_error = Marshal.GetLastWin32Error(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); STARTUPINFO si = new STARTUPINFO(); SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES(); last_error = 0; last_error = Marshal.GetLastWin32Error(); if(DuplicateTokenEx(hToken,UInt32.Parse(GRANTED_ALL,System.Globalization.NumberStyles.HexNumber), ref sa,SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary,out hTokenDuplicate)) { last_error = 0; last_error = Marshal.GetLastWin32Error(); CreateProcessAsUser(hTokenDuplicate, "d:\\san\\notepad.exe", null, ref sa, ref sa, false, 0, IntPtr.Zero, "d:\\san", ref si, out pi); last_error = 0; last_error = Marshal.GetLastWin32Error(); } } last_error = 0; last_error = Marshal.GetLastWin32Error(); if (hToken != IntPtr.Zero) CloseHandle(hToken); if (hTokenDuplicate != IntPtr.Zero) CloseHandle(hTokenDuplicate); } </code></pre> <p>}</p> <p>For some reason this is not working.. The DuplicateTokenEx function is returning as error code of 1305 and i cant seem to figure out why..</p> <p>Instead of DuplicateTokenEx i also used the DuplicateToken, now the CreateProcessAsUser is returning an error code of 1308.</p> <p>Could someone please throw light on this issue.. This appears to be an apparently very simple thing, but just cant get it right.. [Please note that I specifically want to LogonUser and then DuplicateToken and then CreateProcessAsUSer]</p> <p>Thanks Santhosh</p>
<p>See <a href="http://support.microsoft.com/kb/165194" rel="nofollow">CreateProcessAsUser() windowstations and desktops</a>.</p> <p>But I suggest to do it in managed way:</p> <pre><code>... using System.Diagnostics; using System.Security; ... ... string progPath = @"c:\WINNT\notepad.exe"; ProcessStartInfo startInfo = new ProcessStartInfo(progPath); startInfo.WindowStyle = ProcessWindowStyle.Normal; startInfo.UseShellExecute = false; startInfo.UserName = "SomeUser"; SecureString password = new SecureString(); #region setting password password.AppendChar('p'); password.AppendChar('a'); ... #endregion startInfo.Password = password; Process.Start(startInfo); ... ... </code></pre>
Powershell remoting with V1 <p>Do you know of any good remoting solutions using powershell V1 (I know the V2 stuff is awesome, but my organization doesn't like using pre-release software). I don't need anything spectactular, just a way to kick off powershell script on another box and get the results back when they're done. I'm considering using sysinternals PSEXEC and export-csv/import-csv and just making something that works. I'd rather have someone else do the work, though.</p>
<p>I think PrimalScript's Remote Script Execution Engine would do what you're after. It does require a small service to be installed on remote computers, but you get unlimited licenses for that when you buy PrimalScript (Enterprise edition).</p> <p>There's also a PSHRemoting project someone did.</p> <p>N Software's NetCmdlets also come with a "PowerShell Server" (<a href="http://nsoftware.com/powershell/" rel="nofollow">http://nsoftware.com/powershell/</a>) which enables remoting.</p>
Does Java work with PCF fonts? <p>I am trying to make IBM jre to use PCF fonts from default X11 installation on my linux box. In particular adobe-helvetica font. I have toyed to modify fontconfig.properties in jre/lib folder but no matter what I do Java seams to use some other fonts. I guess there is some algorithm how java VM tries to link java logical fonts to actual physical fonts in the system even in case when font specified in config could not be used. On Windows it is pretty straight forward, but on Linux I was unable to make it work with anything except TrueType fonts.<br> Anybody have experience with configuring fonts on IBM jre on Linux?</p>
<p>I've spent all morning learning about Java fonts. There's a lot of limitations, some of which are removed in Java 1.6. I don't have any answers, but here is some information I have that might be helpful.</p> <p>Java distinguishes internally between system fonts and created fonts. (News flash to Sun: it'd be nice to make that clear through subclassing!) The system fonts seem to be fonts installed in the JRE possibly plus some of the fonts installed on your system. But apparently not all of the fonts installed on your system; I, too, have adobe-helvetica on my Linux system but it doesn't seem to be accessible from Java under any name I can think of.</p> <p>Meanwhile, you can create fonts from a font file with the Font.createFont() method. You have to specify the font file type. The only constants I found to specify these types in the Font class are TRUETYPE_FONT and TYPE1_FONT. So it looks like if PCF fonts are available, it isn't made explicit through providing a constant to specify them. Maybe somebody else knows more. I did see some information online about using bitmap fonts in Java ME, so it must somehow be possible to use other types of fonts.</p> <p>Once you have a created font, you can add it to the JVM's concept of available fonts with the GraphicsEnvironment.registerFont() call, but that is only available on Java 1.6 and later.</p>