Thursday, March 31, 2011

Wordpress host IP changed.

Hi, I've got a Wordpress site on our home intranet that has run into trouble now that the IP address has changed - The index page loads, but not the CSS and I can't log in to the site administration panel.

Unfortunately I am a bit behind on backups. Is there a way to get Wordpress to refer to the new IP address?

From stackoverflow
  • What I'd do is dump its database, globally search and replace the old IP to the new IP, and load the database back in.

  • I ran into this problem once. Loginto your DB and check your wp_options (if wp_ is your table prefix) and then search for all records and replace your old ip with new.

    Possible columns to have the old ip would be 'permalinks' etc.. Sorry I cant see my blog's table structure now otherwise I would have posted the correct column name.

  • I ran into this problem before when I was migrating a site from test to production. Conveniently, MySQL has a string replace function.

    Try something like this:

    UPDATE wp_posts SET post_content = REPLACE(post_content,"http://localhost","http://www.myblog.com")
    
    cdmckay : Sorry, this is what you'd do to make all the links work... you need to fix your IP in the wp_options table to be able to login. Try scouring Google, there are many posts telling you how to do this.
  • You have to change the 'home' and 'siteurl' in the settings. Since you cannot open the admin side of wordpress, open the database in phpMyAdmin(or something similar).

    The options can be found in the 'wp_options' table(wp_ prefix might be different). Find the necessary setting using this query...

    SELECT * FROM `wp_options` WHERE `option_name` IN ('siteurl', 'home')
    

    Change the values of both the options to the new IP.

  • use hostnames!

  • You have two places to update this (well three, but we'll stick with the two).

    If you can still log into your admin section, type the following for your URI /wp-admin/options.php - so for example, if your site is http://localhost then your full URL will be http://localhost/wp-admin/options.php. Once you've logged into your site you should see two Fields (well you'll see a lot of fields), but you'll want to look for the two with URL's in them - the Site URL and the Blog URL (in WP 2.7 the fields are labeled "home" and "siteurl", not sure on the other versions).

    Or, you can log into MySQL database and run the following.

    Select * from wp_options where option_id = 1 OR option_id = 39;
    

    I just ran this today on one of my installs. If you're option_value is set to your localhost - you can then run the following:

    update wp_options set option_value='http://www.yourblogname.com' where option_id = 1;
    update wp_options set option_value='http://www.yourblogname.com' where option_id = 39;
    

    This should update your table structure.

Firefox extension with jquery 1.3+

I use jquery-1.2.6 within my Firefox extensions and it works great. Some days ago i wanted to update to the current version of jquery (1.31) but this does not seem to work anymore. Here is my technique to include jquery in my extensions:

$mb = jQuery.noConflict();
var doc = window.content.document
$mb("body", doc).slideToggle("slow");

I am aware of the technique described at this page, but that does not work either. So is there anybody here that uses a newer version than jquery-1.2.6 in Firefox extensions and can tell me how?

From stackoverflow
  • After window.content.document I don't see the semicolon, I think it's necessary.

    bizzy : No, jquery-1.3+ does not work even with the semicolon. As I said, it works perfekt with jquery-1.2.6 (even without any semicolon). There must another problem...
  • i found a solution for my problem!

    I will present it here so that others can use this as a reference. After a lot of searching and tearing my hair i found this bug report on the jquery bug tracker. You can download jquery 1.3.1 Revision: 6161 there which fixes the problem (the official 1.3.1 release is Revision: 6158).

    Another great trick a found out is including library's like jquery "on the fly" in firefox extensions. Just include the following within some javascript file within your extension:

    var jsLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
    jsLoader.loadSubScript("chrome://{appname}/content/jquery-1.3.1_6161.js");
    jQuery.noConflict();
    
    //use jquery
    var doc = window.content.document;
    alert(jQuery("body", doc).html());
    

    Update: Today version 1.3.2 was released and the problem seems to be solved!

How to sort varchar column (SQL) that contains number, chars, characters?

'Order by' returns this result below

05 05/1-1 05/1-2 05/1-3 05/1-4 05/1-5 05/1-6 05/1-7 05/1 05/2-1 05/2-2 05/2-3 05/2-4 05/2 05/3 05/4

and this order below is OK

05 05/1 05/1-1 05/1-2 05/1-3 05/1-4 05/1-5 05/1-6 05/1-7 05/2 05/2-1 05/2-2 05/2-3 05/2-4 05/3 05/4

Is there a way to do this?

From stackoverflow
  • If possible, try to split up the data, so that any numeric information is in its own field. String data and numeric data together in a field will always result in string type of data, so that 'A2' > 'A11'.

  • Hi,

    You need to cast/convert the varchar data to a numeric data type and then perform an order by sort on the data.

    You will likely need to split your data string also, so example order by caluse might be:

    order by 
    convert(int,left(columnName,2)) asc, 
    convert(int,subtring(columnName,4`,2))
    

    This will depend on which string elements represent which date components.

    Make sense?

  • Alter the table and add a compare column. Write a small program which reads the strings and converts them into a format which the database can convert. In your case, a DATE is a good candidate, I guess.

    In the general case, use a VARCHAR column and format all numbers to five (or more) digits (with leading zeroes/spaces, i.e. right aligned).

    After that, you can use the compare column to order the data.

  • If I were you I would order by a tricky expression. Let's assume that before a slash you have at most 2 or 3 digits. If you write

    order by case charindex('/', val)
               when 0 then convert(int, val)
               else convert(int, substr(val, 1, charindex('/', val) -1)
             end * 1000
               + case charindex('/', val)
                   when 0 then 0
                   else convert(float, replace(substring(val, 1 + charindex('/', val),
                                                         length(val)), '-', '.'))
                 end
    

    If I'm not mistyped anything, the following should convert 05 to 5000, 05/1 to 5001, 05/1-1 to 5001.1, and things should sort the way you want, assuming you always have a single digit at most after the hyphen. Otherwise you can probably work around it by splitting and left-padding with the suitable number of zeroes, but the expression would get much uglier ...

How can one number paragraphs in LaTeX?

Given a bunch of paragraphs:

Para. A ...

Para. B ...

Para. C ...

How can one have LaTeX automatically number them, i.e.

1. Para. A. ...

2. Para. B. ...

3. Para. C. ...

I've seen the following suggested:

\newcounter{parnum}
\newcommand{\N}{%
   \noindent\refstepcounter{parnum}%
    \makebox[\parindent][l]{\textbf{\arabic{parnum}.}}}
% Use a generous paragraph indent so numbers can be fit inside the
% indentation space.
\setlength{\parindent}{2em}

From here: comp.text.tex: Re: How do I number paragraphs in LaTeX?

Then use \N in front of every paragraph-to-be-numbered, i.e.

\N Para. A. ...

\N Para. B. ...

\N Para. C. ...

I've also seen references to Sarovar and numberpar, but both are referred to as "unstable" or "unpredictable", and things like "randomly breaks", which makes me wary.

I'd like some input on what may be the best course of action, here, and I think it's a topic worth some discussion.

Thank you for your interest and attention to this.

EDIT: I've tried the following

\begin{enumerate}
\item Para No. 1
\item Para No. 2
...
\end{enumerate}

However it results in typesetting problems, notably because I am interspersing section headings ala.

\begin{enumerate}
\item Para No. 1
\item Para No. 2
\section{Part II}
\item Para No. 5
\item Para No. 6
...
\end{enumerate}

and the section heading "Part II" will sometimes end up at the very bottom of the page (i.e. it doesn't keep with the following text).

From stackoverflow
  • I believe another option is the ledmac package. Here is a quote from the documentation:

    The normal \label, \ref and \label \pageref macros may be used within numbered text, and operate in the familiar fashion. As an example, here is one way of numbering paragraphs in numbered text, and then being able to refer to the paragraph numbers, in addition to line and page numbers.

    \newcounter{para} \setcounter{para}{0}
    \newcommand{\newpara}{%
      \refstepcounter{para}%
      \noindent\llap{\thepar. }\quad}
    \newcommand{\oldpara}[1]{%
      \noindent\llap{\ref{#1}. }\quad}
    

    The definitions of \newpara and \oldpara put the numbers in the left margin and the first line of the paragraph is indented. You can now write things like:

    \linenummargin{right}
    \beginnumbering
    \pstart
    \newpara\label{P1} A paragraph about \ldots
    \pend
      In paragraph~\ref{P1} the author \ldots
    \pstart
    \oldpara{P1} This has the same
                 \edtext{number}{\Afootnote{\ref{P1} is the paragraph, not line}}
      as the first paragraph.
    \pend
    \endnumbering
    

    I've never attempted this myself, however.

  • I think there are three possible solutions (at least!) which don't involve rolling your own or someone else's macro, depending on exactly what you are trying to do.

    1 If the numbering is required throughout the document, use \paragraph, which is a lower-level sectioning command (like \chapter, \section, \subsection, etc.)

    See the LaTeX wikibook for more information.

    \setcounter{secnumdepth}{5}
    ...
    \paragraph{If we want to} do something ...
    

    (You may find this overkill/ugly, because it needs a properly nested structure of sections and subsections not to be)

    Note that if your using the memoir document class (which I recommend unhesitatingly), the \setcounter line becomes \maxsecnumdepth{paragraph}

    2 If it's just a small piece, use a list:

    \begin{enumerate}
    \item Para No. 1
    \item Para No. 2
    ...
    \end{enumerate}
    

    3 Or a generalized list (\begin{list}...\end{list{}) if you want to tweak the formatting. I haven't immediately been able to find a good online reference for this, other than the piece in A Guide to LaTeX

    Brian M. Hunt : \setcounter{secnumdepth}{5} + \paragraph was the functionality I was looking for. Thanks!

What's the difference between Assert.AreNotEqual and Assert.AreNotSame?

In C#, what's the difference between

Assert.AreNotEqual

and

Assert.AreNotSame
From stackoverflow
  • Two things can be equal, but different objects. AreNotEqual checks the objects values via the equality test, while AreNotSame checks that they are not the same exact object.

    It is obvious why we would want to test that things AreNotEqual (we care about the values being tested); what about AreNotSame? The usefulness of this in testing is found when you have passed references around and want to make sure that after your shuffling is done that two references are still the same object.

    In a real world case, we use a lot of caching objects to mitigate round trips to the database. After an object has been handed off to the cache system, our unit tests ensure that in some cases we get back the same object (cache was valid) and in other cases we get back a fresh object (cache was invalidated). Note that AreNotEqual would not necessary suffice in this case. If the object had a new timestamp in the database, yet the data was not "different enough" to fail an equality test, AreNotEqual wouldn't notice that we refreshed the object.

  • AreNotSame does reference comparison, whereas AreNotEqual does an equality comparison.

  • AreNotSame uses reference equality (object.ReferenceEquals) - i.e. are they the same actual instance of an object; AreNotEqual uses conceptual equality (.Equals) - i.e. are they considered equal.

  • Isn't it so that AreNotEqual checks for the case where two objects are not equal in terms of Equals() method, whereas AreNotSame checks for the case where the two object references are not the same. So if x and y are two objects which are equal in terms of Equals() but have been separately allocated, AreNotEqual() would trigger failing assertion but the other not.

  • Assert.AreNotEqual asserts that two values are not equal to each other.

    Assert.AreNotSame asserts that two variables do not point to the same object.

    Example 1:

    int i = 1;
    int j = i;
    // The values are equal:
    Assert.AreEqual(i, j);
    // Two value types do *not* represent the same object:
    Assert.AreNotSame(i, j);
    

    Example 2:

    string s = "A";
    string t = s;
    // The values are equal:
    Assert.AreEqual(s, t);
    // Reference types *can* point to the same object:
    Assert.AreSame(s, t);
    
  • Almost all the answers given here are correct, but it's probably worth giving an example:

    public static string GetSecondWord(string text)
    {
        // Yes, an appalling implementation...
        return text.Split(' ')[1];
    }
    
    string expected = "world";
    string actual = GetSecondWord("hello world");
    
    // Good: the two strings should be *equal* as they have the same contents
    Assert.AreEqual(expected, actual);
    
    // Bad: the two string *references* won't be the same
    Assert.AreSame(expected, actual);
    

    AreNotEqual and AreNotSame are just inversions of AreEqual and AreSame of course.

    EDIT: A rebuttal to the currently accepted answer...

    If you use Assert.AreSame with value types, they are boxed. In other words, it's equivalent to doing:

    int firstNumber = 1;
    int secondNumber = 1;
    object boxedFirstNumber = firstNumber;
    object boxedSecondNumber = secondNumber;
    
    // There are overloads for AreEqual for various value types
    // (assuming NUnit here)
    Assert.AreEqual(firstNumber, secondNumber);
    
    // ... but not for AreSame, as it's not intended for use with value types
    Assert.AreSame(boxedFirstNumber, boxedSecondNumber);
    

    Neither firstNumber nor secondNumber has an object value, because int is a value type. The reason the AreSame call will fail is because in .NET, boxing a value creates a new box each time. (In Java it sometimes doesn't - this has caught me out before.)

    Basically you should never use AreSame when comparing value types. When you're comparing reference types, use AreSame if you want to check for identical references; use AreEqual to check for equivalence under Equals.

    The claim in the answer that:

    Using the example above changing the int to string, AreSame and AreEqual will return the same value.

    entirely depends on how the variables are initialized. If they use string literals, then yet, interning will take care of that. If, however, you use:

    string firstString = 1.ToString();
    string secondString = 1.ToString();
    

    then AreSame and AreEqual will almost certainly not return the same value.

    As for:

    The general rule of thumb is to use AreEqual on value types and AreSame on reference types.

    I almost never want to check for reference identity. It's rarely useful to me. I want to check for equivalence which is what AreEqual checks for. (I'm not saying that AreSame shouldn't be there - it's a useful method, just far more rarely than AreEqual.)

    Ilya Ryzhenkov : Shouldn't AreSame be generic method with class constraint?
    Jon Skeet : It would be now, if NUnit came out not caring about 1.1 support, I'm sure.
    Daniel Earwicker : All this confusion raises the question: why not just have a single Assert method?
    Jon Skeet : @Earwicker: Because you don't always want to check for the same thing. Yes, there could be Assert(bool) - but that couldn't give as much information when you pass it false as AreEqual etc do.
    Daniel Earwicker : Just a thought but how about Debug.Assert(() => x == y); i.e. pass a lambda of type Func. Then Assert can accept it as Expression>, so if it fails it can turn it into a string to include it in the test log.
    Jon Skeet : It's usually the values which are important, and the expression wouldn't show those.
    Daniel Earwicker : Challenge accepted! http://incrediblejourneysintotheknown.blogspot.com/2009/02/displaying-nested-evaluation-tree-from.html
    Jon Skeet : @Earwicker: Will take a closer look later. I doubt that you'll easily be able to *easily* do some of the nice things JUnit and NUnit can though, such as spotting that strings are different and doing a diff to make it easy to spot changes. Feasible I expect, but harder than having the extra method :)
    Daniel Earwicker : Yes, I should probably try making it into a wrapper around NUnit and see which nice facilities can be reproduced practically.

Limit of OpenGL displayList size

Does anyone know if putting too many OpenGL calls into a displaylist can cause it to fail? If so, does anyone have an estimate for how many calls might do this? Is it related to video memory?

I'm calling OpenGL from JOGL, but I don't think that's significant.

From stackoverflow
  • According to this documentation page if you try to compile a list that is too big you're supposed to get a GL_OUT_OF_MEMORY error message.
    make sure you call glGetError() before and after you create the list and process all the results until GL_NO_ERROR is returned.

    There doesn't seem to be a way to estimate the number of commands a list can contain. This is probably because every command takes a different size depending on its arguments and the device specific encoding used. The lists are kept in the video memory of the card so if you're using a relatively non-archaic card this should usually really not be a problem for any reasonably sized lists. If you do find this is indeed the problem you can probably use Vertex arrays or even VBOs

New to Javascript, can someone explain this code line by line?

I used this code to maintain scroll position and don't have a clue of what it means. If someone has the time, can you provide me with an step by step explanation of what it is doing. Here it is:

<script language="javascript"  type="text/javascript">
    var xPos, yPos;
    var prm = Sys.WebForms.PageRequestManager.getInstance();

        function BeginRequestHandler(sender, args) {

        if ($get('<%=lstAuctions.ClientID %>') != null) {

            xPos = $get('<%=lstAuctions.ClientID %>').scrollLeft;
            yPos = $get('<%=lstAuctions.ClientID %>').scrollTop;
        }
    }

    function EndRequestHandler(sender, args) {

        if ($get('<%=lstAuctions.ClientID %>') != null) {

            $get('<%=lstAuctions.ClientID %>').scrollLeft = xPos;
            $get('<%=lstAuctions.ClientID %>').scrollTop = yPos;
        }
    }

    prm.add_beginRequest(BeginRequestHandler);
    prm.add_endRequest(EndRequestHandler);

</script>
From stackoverflow
  • scrollLeft

    scrollTop

    Sys.WebForms.PageRequestManager Class

  • var xPos, yPos; // global variable declaration
    var prm = Sys.WebForms.PageRequestManager.getInstance(); // Some webforms javascript manager
    
    /*
    * Begin function with 2 arguments
    */
    function BeginRequestHandler(sender, args) {
    
        // check if the element generated by .net with id 'lstAuctions.ClientID' exists
        if ($get('<%=lstAuctions.ClientID %>') != null) {
    
            // get its scroll left and top position and
            // assign it to the global variables
            xPos = $get('<%=lstAuctions.ClientID %>').scrollLeft;
            yPos = $get('<%=lstAuctions.ClientID %>').scrollTop;
        }
    }
    
    /*
    * this method gets executed last, it uses the 
    * already set global variables to assign the old scrollpositions again
    */
    function EndRequestHandler(sender, args) {
    
        if ($get('<%=lstAuctions.ClientID %>') != null) {
            // assign the previous scroll positions
            $get('<%=lstAuctions.ClientID %>').scrollLeft = xPos;
            $get('<%=lstAuctions.ClientID %>').scrollTop = yPos;
        }
    }
    
    // first function gets executed on the beginning of a request
    prm.add_beginRequest(BeginRequestHandler);
    // second function gets executed on the end of the request
    prm.add_endRequest(EndRequestHandler);
    

    Ok the code highlighting is not working properly, no idea how to fix it but i guess you get the point :)

    Xaisoft : Very nice, thanks! What exactly is the beginRequest and endRequest? Is this similar to the Page_Load and Page_Unload in asp.net?
    Tomh : From MSDN, I never used it personally. beginRequest = Raised before processing of an asynchronous postback starts and the postback request is sent to the server. endRequest = Raised after an asynchronous postback is finished and control has been returned to the browser.
    jro : beginRequest and endRequest are (likely) DOM-based custom events. The prm object has some easy syntax to assign your function to be called. Based on the naming, beginRequest and endRequest sound like pre- and post- function calls in some AJAX request.
  • Sys.WebForms.PageRequestManager is an ASP.Net AJAX construct.

    Specifically in your code, there are some allocated variables (xPos,yPos,prm) and two defined functions (BeginRequestHandler,EndRequestHandler). At the end of the code are two function calls (prm.add_beginRequest,prm.add_endRequest) that are assigning those functions as event handlers.

    The $get calls are part of the library as a shortcut for getting data from the client-side. It's very much javascript under the covers, but it's just a syntactical implementation through the ASP.Net AJAX client-side library.

    Xaisoft : So instead of $get, what could I have used?
    Tomh : Use $get because the .net generated ID's are only known after page generation. With less crappy implementations of generated code (I really hate asp.net for those ID's) you can use document.getElementById();
    Xaisoft : ok, so I can either use $get or document.getElementById(). $get is just an microsoft shortcut, is this correct?
    jro : yes, $get() appears to be a shortcut to document.getElementById(). Pay heed to Tomh comment about generated Ids on the client-side.
    Tomh : $get is not a shortcut, .net generates ids like ctl_001_001_originalId if you use originalId as id in your aspx page. You do not know this prefix, thats why MS thought it was handy to build a function which does know that prefix so you can just use the id you assigned and the function adds the rest.
    Xaisoft : ok TomH, you are referring to naming containers, right?
    jro : tomH, are you sure $get() is not a shortcut? In this line of code: $get('<%=lstAuctions.ClientID %>') the clientID value will be rendered correctly at runtime, but I believe $get is written to the page. Thus, it should map to javascript routine in the JS client libs.
  • var xPos, yPos;

    **declares two global variables.


    function BeginRequestHandler(sender, args) {

    **declares a new function. This function is probably used for an event handler

    if ($get('<%=lstAuctions.ClientID %>') != null) {

    **this is a combination of inline ASP/ASP.NET code as defined in the <% %> pairing.

    xPos = $get('<%=lstAuctions.ClientID %>').scrollLeft;

    **captures the current scrolling position of the page into the local variable.

    yPos = $get('<%=lstAuctions.ClientID %>').scrollTop;

    **captures the current scrolling position of the page into the local variable.


    function EndRequestHandler(sender, args) {

    **declares a new function. This function is probably used for an event handler

    if ($get('<%=lstAuctions.ClientID %>') != null) {

    **this is a combination of inline ASP/ASP.NET code as defined in the <% %> pairing.

    $get('<%=lstAuctions.ClientID %>').scrollLeft = xPos;

    **sets the scrolling position of the page to the value of xPos.

    $get('<%=lstAuctions.ClientID %>').scrollTop = yPos;

    **sets the scrolling position of the page to the value of xPos.


    var prm = Sys.WebForms.PageRequestManager.getInstance();

    **declares and initializes a new variable to the PageRequestManager.

    prm.add_beginRequest(BeginRequestHandler);

    **adds the event handler defined above to the beginRequest of the current page.

    prm.add_endRequest(EndRequestHandler);

    **adds the event handler defined above to the endRequest of the current page.

  • You did ask...

    // declare 2 variables
    var xPos, yPos;
    // get an instance of the PageRequestManager - this looks like an MS ajax helper class
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    
    // declare a function
    function BeginRequestHandler(sender, args) {
    
        // get the ClientSide HTML DOM element which corresponds to the lstAuctions asp control on the serverside
        if ($get('<%=lstAuctions.ClientID %>') != null) {
            // if the element is not null (eg: page is not broken)
    
            // get the x Position of the object relative to what is displayed by the scrolled window (if you scroll sideways this value changes)
            xPos = $get('<%=lstAuctions.ClientID %>').scrollLeft;
            // get the y Position of the object relative to what is displayed by the scrolled window (if you scroll up/down this value changes)
            yPos = $get('<%=lstAuctions.ClientID %>').scrollTop;
        }
    }
    
    // declare a function
    function EndRequestHandler(sender, args) {
    
        // get the ClientSide HTML DOM element which corresponds to the lstAuctions asp control on the serverside
        if ($get('<%=lstAuctions.ClientID %>') != null) {
            // if the element is not null (eg: page is not broken)
    
            // set the x position of the object to what we got last time (horizontal scroll the page)
            $get('<%=lstAuctions.ClientID %>').scrollLeft = xPos;
    
            // set the y position of the object to what we got last time (vertical scroll the page)
            $get('<%=lstAuctions.ClientID %>').scrollTop = yPos;
        }
    }
    
    // tell the page request manager to call our BeginRequestHandler method when it begins it's request
    prm.add_beginRequest(BeginRequestHandler);
    
    // tell the page request manager to call our EndRequestHandler method when it ends it's request
    prm.add_endRequest(EndRequestHandler);
    

    Basically, it looks like the page is using the MS ajax library to display some dynamic content (probably replacing a list with another list), but preserving the place that the user has scrolled to so the page doesn't "jump" when the new content replaces the old content.

    Xaisoft : Thanks, what is the $get for and can the BeginRequestHandler and EndRequestHandler be named anything?

How do I get notified whenever a new editor is opened in Eclipse?

I have a view which would like to be notified about all the currently opened editors. Where can I add a listener to achieve this?

I was expecting WorkbenchPage or EditorManager to have some appropriate listener registry, but I couldn't find it.

From stackoverflow
  • I think you're on the right track. You need to listen to the IWorkbenchPage IPartService events:

    page.addPartListener(new IPartListener() {
        partOpened(IWorkbenchPart part) {
            ...
        }
    
        ...
    });
    
    Tirno : doesn't seem to do anything for me
    Tirno : ah... I was not reading your comment properly. I had added it to the page, not to the page's partService.
    Mike Houston : You probably didn't misread it - I thought you could just listen to the page directly. Apparently not.
  • Does your view uses a org.eclipse.ui.IPartListener2 ?

    That is what is using this EditorListener, whose job is to react, for a given view, to Editor events (including open and close)

    public class EditorListener implements ISelectionListener, IFileBufferListener,
    IPartListener2 {
        protected BytecodeOutlineView view;
    
        EditorListener(BytecodeOutlineView view){
            this.view = view;
        }
    
    [...] 
    
        /**
         * @see org.eclipse.ui.IPartListener2#partOpened(org.eclipse.ui.IWorkbenchPartReference)
         */
        public void partOpened(IWorkbenchPartReference partRef) {
            view.handlePartVisible(partRef.getPart(false));
        }
    


    Now if your ViewPart directly implements an IPartListener2, it can register itself to the various Editors, like this BytecodeReferenceView

    public class BytecodeReferenceView extends ViewPart implements IPartListener2, ISelectionListener {
    
        [...]
    
        public void createPartControl(Composite parent) {
            browser = new Browser(parent, SWT.BORDER);
            browser.setText(BytecodeOutlinePlugin.getResourceString(NLS_PREFIX
                + "empty.selection.text"));
            final IWorkbenchWindow workbenchWindow = getSite().getWorkbenchWindow();
            workbenchWindow.getPartService().addPartListener(this);
        [...]
    

How do you ensure .Net always searches for a namespace from the root of the namespace tree?

Is there a way to tell .Net to search for a namespace from the root of the namespace tree?

Say I have these two, completely independent, namespaces:

Apple.Orange.Banana
Orange.Grape.Peach

Assume they came from different programmers and the "Orange" in each one is completely coincidental.

If I'm inside "Apple.Orange.Banana" and I trying to import (or reference) "Orange.Grape.Peach," .Net things I'm trying to search from the "Orange" in "Apple.Orange.Banana".

How do I tell it, "Look from the root, not where I'm at now." This would be great:

~Orange.Grape.Peach

But, alas, that doesn't exist.

I know that some of you will say I should just plan namespaces better, but what happens when I'm using code from two places that come with namespaces predefined that I cannot change, and they conflict as I've noted above?

From stackoverflow
  • You could alias the root Orange like this:

    using RootOrange = Orange;
    

    Then you can do:

    RootOrange.Grape.Peach
    
  • Have you tried using the global:: resolution scope? For example, if you have the following:

    private global::Orange.Grape.Peach.classname x;
    

    Also, you get different resolution depending on whether namespaces are imported outside of a namespace declaration or inside, so

    using System.Linq;
    namespace MyLinq 
    {
       // ...
    }
    

    can provide different resolution rules than:

    namespace MyLinq 
    {
       using System.Linq;
    
       // ...
    }
    
    Deane : Excellent. Thank you.
    Scott Dorman : @Deane: You're welcome. Glad you were able to resolve the problem.

How do I properly handle a PreviewMouseDown event with a MessageBox confirmation?

Earlier I asked how to cancel a WPF TreeViewItem.Selected event.

The answerers suggested I instead handle the PreviewMouseDown event before the selection even takes place. That makes sense.

I've tried to do that...

XAML...

<TreeView Name="TreeViewThings"
    ...
    PreviewMouseDown="TreeViewThings_PreviewMouseDown"
    TreeViewItem.Expanded="TreeViewThings_Expanded"
    TreeViewItem.Selected="TreeViewThings_Selected" >

Visual Basic...

Sub TreeViewThings_PreviewMouseDown(...)
    If UnsavedChangesExist() Then
        e.Handled = UserCancelled()
    Else
        e.Handled = False
    End If
End Sub

Function UnsavedChangesExist() As Boolean
    ...
End Function

Function UserCancelled() As Boolean
    Return MessageBox.Show("Discard your unsaved changes?", _
                           "Unsaved Changes", _
                           MessageBoxButton.OKCancel, _
                           MessageBoxImage.Question) = MessageBoxResult.Cancel
End Function

This is only sort of working...

  • If there are no unsaved changes, then it proceeds just fine and executes TreeViewThings_Selected().

If there are unsaved changes, then I see the MessageBox...

MessageBox: Continue and discard your unsaved changes?  OK/Cancel

  • If I then choose Cancel, it cancels.

  • However, If I instead choose OK to discard my unsaved changes, then it just cancels anyway--even though e.Handled = False. It does not continue on and execute TreeViewThings_Selected().

I think the fact that there's a MessageBox screws it up somehow.

What am I doing wrong?

From stackoverflow
  • The problem is that the messagebox causes your tree to lose focus. Have you tried setting the focus back to the tree after the messagebox is dismissed?

Generic SOAP Debugging Tools

When you're programming against a SOAP Service, what tools do you use to explore/poke-at the API? I realize that Visual Studio/Eclipse likely have some sort of client built in (and please, do talk about them), but I'm more interested in information about stand-alone programs like Soap Client for OS X.

More specifically, does anyone have any experience with tools that work with the Magento API. SoapClient doesn't pickup the parameters for the login method, which makes it not-so-useful for my needs.

From stackoverflow

Handling enums in JSON

When I serialize an object of a class with a enum property to JSON, if the value is null, the resulting json string has a name value pair like this:

"controlType":"-2147483648"

This causes issues when I deserialize the string to a strongly typed object.

What's the best way of handling enums and nulls?

From stackoverflow
  • Consider:

    echo json_encode(array("test"=>null));
    

    This produces:

    {"test":null}
    

    The best way to handle enums is with a key,value array or an stdClass. Just bind your names to a set of unique integers. You can then bind the other direction as well:

    {"A":1, "B":2, "C":3, 1:"A", 2:"B", 3:"C"}

    This at least gives you bi-directionality.

  • the below code gives you json = '{"Name":"Test","Id":1,"MyEnum":3}', when you have a non-null value.

         public enum SerializeObjTestClassEnum
     {
      one = 1, two, three, four
     }
    
     [Serializable]
     public class SerializeObjTestClass
     {
      public string Name { get; set; }
      public int Id { get; set; }
      public SerializeObjTestClassEnum MyEnum{ get; set; }
     }
    
     public void SerializeObject_Test_Basic_Object()
     {
      var obj = new SerializeObjTestClass { Id = 1, Name = "Test", MyEnum = SerializeObjTestClassEnum.three };
      var json = (new JavaScriptSerializer()).Serialize(obj);
     }
    


    this code gives you json = '{"Name":"Test","Id":1,"MyEnum":0}'

        var obj = new SerializeObjTestClass { Id = 1, Name = "Test" };
    

    Notice how the enum, when not set, is serialized to a 0, while the enum itself starts out at 1. So this is how you code can know a NULL value was used for the enum.

    if you want the json to look like '{"Name":"Test","Id":1,"MyEnum":null}', then you're going to need to fake it out by using a class wrapper around the Enum.

    dbkk : The wrapper `is Nullable`, replace `MyEnum` with `MyEnum?`.

Syntax Error

What is wrong with the statement below? I keep getting the following error message.... Server: Msg 156, Level 15, State 1, Line 4 Incorrect syntax near the keyword 'THEN'.

update oildatasetstatus
set oildatasetstatusid = 
    case 
    WHEN 5 THEN 16        
    WHEN 6 THEN 17        
    WHEN 7 THEN 18        
    WHEN 8 THEN 18        
    WHEN 9 THEN 18        
    WHEN 10 THEN 19        
    WHEN 11 THEN 20    
    End
where oildatasetlabstatusid in 
(
                select oildatasetstatusid
                from OilDataSetStatus
                inner join OilDataSet on OilDataSet.OilDataSetID = 
                    OilDataSetStatus.OilDataSetID
                where SamplePointID in 
                (
                                select SamplePointID 
                                from SamplePoint
                                where CustomerSiteID in
                                (
                                                select CustomerSiteID
                                                from CustomerSite
                                                where CustomerID = 2
                                )
                )
)
From stackoverflow
  • Looks like your case statement needs to specify which column is being tested for the given value.

    For example:

     update  oildatasetstatus
        set     oildatasetstatusid = case WHEN oildatasetstatusid = 5 THEN 16
                                          WHEN oildatasetstatusid = 6 THEN 17
                                          WHEN oildatasetstatusid = 7 THEN 18
                                          WHEN oildatasetstatusid = 8 THEN 18
                                          WHEN oildatasetstatusid = 9 THEN 18
                                          WHEN oildatasetstatusid = 10 THEN 19
                                          WHEN oildatasetstatusid = 11 THEN 20
                                     End
        where   oildatasetlabstatusid in (
                select  oildatasetstatusid
                from    OilDataSetStatus
                        inner join OilDataSet on OilDataSet.OilDataSetID = OilDataSetStatus.OilDataSetID
                where   SamplePointID in (
                        select  SamplePointID
                        from    SamplePoint
                        where   CustomerSiteID in ( select  CustomerSiteID
                                                    from    CustomerSite
                                                    where   CustomerID = 2 ) ) )
    
  • I think you're missing the statement that you want to evaluate in the CASE statement.

    update oildatasetstatus set oildatasetstatusid =
    case oildatasetstatusid
     WHEN 5 THEN 16
     WHEN 6 THEN 17
     WHEN 7 THEN 18
     WHEN 8 THEN 18
     WHEN 9 THEN 18
     WHEN 10 THEN 19
     WHEN 11 THEN 20
    End
    where oildatasetlabstatusid in ( select oildatasetstatusid from OilDataSetStatus inner join OilDataSet on OilDataSet.OilDataSetID = OilDataSetStatus.OilDataSetID where SamplePointID in ( select SamplePointID from SamplePoint where CustomerSiteID in ( select CustomerSiteID from CustomerSite where CustomerID = 2 ) ) )
    

    Give that a shot?

  • Your case statement does not have an object to work on.

    You can do it 2 ways:

    set oildatasetstatusid = 
        case oildatasetstatusid
        WHEN 5 THEN 16        
        WHEN 6 THEN 17        
        WHEN 7 THEN 18        
        WHEN 8 THEN 18        
        WHEN 9 THEN 18        
        WHEN 10 THEN 19        
        WHEN 11 THEN 20    
        End
    

    or

    set oildatasetstatusid = 
        case 
        WHEN oildatasetstatusid = 5 THEN 16        
        WHEN oildatasetstatusid = 6 THEN 17        
        WHEN oildatasetstatusid = 7 THEN 18        
        WHEN oildatasetstatusid = 8 THEN 18        
        WHEN oildatasetstatusid = 9 THEN 18        
        WHEN oildatasetstatusid = 10 THEN 19        
        WHEN oildatasetstatusid = 11 THEN 20    
        End
    
  • The way you have your statement coded now will work (once you add the column reference to the case statement, as mentioned by other posts), however, to let the rest of your syntax go uncommented on would be a disservice to others in your situation.

    While you may only need to run this query once, I and others have run into similar situations where an Update to many rows also relies data 3 or 4 tables away from our source and has to be run many times (like in a report).

    By collapsing your sub selects into a single select statement and saving the results of that into a #Temp table or a @Table variable, you only have to do that lookup once, then select from the result set for your update.

    Here is a sample using a @table variable:

    declare @OilStatus table (oilDatasetStatusID int)
    insert into @OilStatus
        select odss.oildatasetstatusid
        from OildataSetStatus odss
        join oilDataSet ods on ods.OilDataSetID = odss.OilDataSetID
        join SamplePoint sp on sp.SamplePointID = odss.SamplePointID
        join CustomerSite cs on cs.CustomerSiteID = sp.CustomerSiteID
        where cs.CustomerID = 2
    
    update oildatasetstatus
    set oildatasetstatusid = 
     case oildatasetstatusid
      WHEN 5 THEN 16        
      WHEN 6 THEN 17        
      WHEN 7 THEN 18        
      WHEN 8 THEN 18        
      WHEN 9 THEN 18        
      WHEN 10 THEN 19        
      WHEN 11 THEN 20    
    end
    where oildatasetlabstatusid in ( select oilDatasetStatusID from @OilStatus )
    

    Since I do not have your exact schema, there may be errors when trying to implement the sample above but I think you will get the idea.

    Also, whenever multiple tables are used in a single statement try to preface every column name with an alias or the full table name. It helps keep both the sql engine and the people reading your code from getting lost.

How do I attach a remote debugger to a Python process?

I'm tired of inserting

import pdb; pdb.set_trace()

lines into my Python programs and debugging through the console. How do I connect a remote debugger and insert breakpoints from a civilized user interface?

From stackoverflow
  • Well, you can get something quite similar to that using a twisted manhole, which works like this:

    from twisted.internet import reactor
    from twisted.cred import portal, checkers 
    from twisted.conch import manhole, manhole_ssh 
    
    def getManholeFactory(namespace):
        realm = manhole_ssh.TerminalRealm()
        def getManhole(_): 
            return manhole.Manhole(namespace) 
        realm.chainedProtocolFactory.protocolFactory = getManhole
        p = portal.Portal(realm)
        p.registerChecker(
            checkers.InMemoryUsernamePassword DatabaseDontUse(admin='foobar'))
        f = manhole_ssh.ConchFactory(p)
        return f
    
    reactor.listenTCP(2222, getManholeFactory(globals()))
    reactor.run()
    

    Then you just login to the program over ssh;

    $ ssh admin@localhost -p 2222
    admin@localhost's password:
    

    Using foobar as the password.

    When you login you'll get a normal python prompt where you can just poke at the data. It's not quite the same as getting a traceback sent over to a host.

    Now, this might be tricky to integrate to a GUI program, in that case you might need to choose another reactor, for instance for gtk based programs used the gtk2reactor etc.

    If you want the actual traceback sent over you need to create a socket channel for both stderr, stdin and stdout which goes over the network instead of printing to your local host. Shouldn't be too hard to accomplish by using twisted.

  • use Winpdb. It is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.

    Features:

    • GPL license. Winpdb is Free Software.
    • Compatible with CPython 2.3 through 2.6 and Python 3000
    • Compatible with wxPython 2.6 through 2.8
    • Platform independent, and tested on Ubuntu Gutsy and Windows XP.
    • User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.

    Screenshot

Database change managing on software patch/update/upgrade

It's been few weeks I'm trying to find a more detailed explanation with examples how to manage my database change on software patch.

Situation:

  • I deploy wpf application release to user. App uses MSSQL data file for storing app's data (Deploying with Client Profile and SqlServer Compact 3.5 prerequisites)
  • In further development database schema changes I add some extra data too
  • I'm trying to run a patch/minor/major upgrade with Visual Studio 2008 publishing and msi

I want to update users app and database file, but not touch the data which was stored in that database. Seems easy, but i fail to find on web how to get this done with Visual Studio publishing

What I've collected so far are 2 choices:

  • Create sql update script for each release and try update database on 1st program launch after patching.
  • Create database setup project and try to script from there (no idea how to do this).

I'd be glad to hear what some of you are using or would use such case. Some link to examples/detailed explanation how todo would be awesome. I'm not very good at this deployment/database stuff...yet...:)

Thanks in advance.

From stackoverflow
  • This article on "Rails Style Database Migrations in .Net" might be useful. Since the rise of Rails there has been a lot of work on best practices for database migrations, which can be leveraged in other languages and platforms.

    Paul G. : I certainly haven't thought/knew of this, it's like moving whole database creation/changes to the code. What especially i'm interested is ability to use mysql db with same db creation code.
  • In my current project we use a technique called Continuous Database Integration.

    We collect all sql change scripts (that can be creating / altering tables, stored procedures, but also migrating data, etc...), into a c# project and deploy them at the same time as the rest of the software.

    Using this technique we can ensure that all developer databases are up-to-date as well, as it is integrated in the visual studio build system.

    We run this MSBuild script for local builds and for deployment. It checks a version number in the datebase, and runs any scripts with a higher number.

    I'm not so fond of MSBuild, but it gets the job done.

    Martin Fowler has an article on evolutionary database design which has some background on this.

    If you're using SQL Server management studio to make changes, you can use the "Generate Change Script" to let it script the changes for you.

  • If you add Installer class to your DLL or EXE it's Install method will be invoked during the setup (check our MSDN for details, VS can make a mini setup proj for you and then you can just copy the skeleton and attributes). Then you can run SQL commands against CE and backup existing CE files and even do a rollback if something goes wrong (Installer class has methods to follow full transnational steps on the level of the whole setup - the piece of mind thing :-)

How do I write a new Linux driver for an i2c device?

I have a usb device with some i2c control functions and I would like to add a userspace API for twiddling those bits. How do I add i2c support to my device's existing driver?

From stackoverflow
  • The excellent Linux Device Drivers book covers a lot of what it takes to write a Linux device driver, including USB specifics (see chapter 13).

SQL Functions and Recursion

Suppose you write a function in SQL Server that conditionally calls itself. If you are writing the function from scratch, finish it, and try to create it, SQL Server complains.

The complaint is that the function you call from your function doesn't exist. Of course it doesn't, it's recursive!

To actually make it work, you have to comment out the recursive call, create the function, uncomment the call, and alter the function. You have to go through this nonsense if you ever change what parameters the function accepts (in this case it complains there are too many or too few parameters in your new recursive call).

Is there any way around this?

From stackoverflow
  • For stored procedures you should get an error like this, that you can just ignore:

    Cannot add rows to sysdepends for the current object because it depends on the missing object 'sub_proc1'. The object will still be created.

    For user defined functions it is a little trickier, but it works (at least it did for me on SQL 2k8) if you fully qualify the function name in the recursive call.

    CREATE FUNCTION recursiveUDF () RETURNS int
    AS
    BEGIN
    
        DECLARE @X int
    
         --Fails with "recursiveUDF is not a recognized built-in function name."
        SET @X = recursiveUDF()          
    
         --works!
        SET @X = dbo.recursiveUDF()  
    
        RETURN 1
    END
    
    DJ : The create should still work - it's just a warning message that you can ignore
    colithium : That does the trick when Creating the function, however, Alter still fails. I think it's an annoyance I'm just going to have to live with.
    JohnFx : Why not just do an "if exists..drop" then "Create" instead of an alter? It is slightly more effort, but isn't so terrible.
  • [Edit] ignore my comment :)

What are good "real" programming examples for a beginning programmer?

I've been browsing Bjarne Stroustrup's new introductory programming book, Programming: Principles and Practice Using C++. It's meant for first-year university computer science and engineering students.

Early on in the book he works through an interesting extended example of creating a desktop calculator where he ends up implementing an arithmetic expression evaluator (that takes bracketed expressions and operator precedence into account) in a series of co-recursive functions based on a grammar.

This is a very interesting example, although arguably on the complex side for a lot of beginners.

I wonder what others thing of this particular example: would learning programming by seeing how to implement an expression parser excite and motivate you, or would it discourage you because of all the details and complexity?

Are there other good "real" programming examples for beginners?

From stackoverflow
  • Start small. Do examples that interest you. Stretch yourself just a little every time. Get comfortable with each step, to the point that you have confidence that you know what you're doing, and then try something a little harder the next time.

  • I think that any example program would help you learn a new language, but a beginner should try to work with something that is easy to understand in the real world, such as a mortgage calculator or something along those lines.

  • I think making tiny games like text version of Tetris will be a good way of getting into pragramming world.

  • I think the answer is that it would depend on the person who is learning how to program.

    One nice thing about something like an arithmetic expression evaluator is that it is a project that can start very small (make it work with just the format "X SYMBOL Y" where X and Y are single-digit numbers and SYMBOL must be a plus sign) and then you are slowly expanding the functionality to the point of a complicated system.

    However, it might not be a great starter project for someone who doesn't really understand the concept of computers (hard disk, memory, etc.)

    Try to think of something that you do on a computer that is repetitive, and could be easily automated. Then try to come up with how to make a program that automates that task for you. It can be anything, whether it's popping up a reminder every 15 minutes to stretch your legs or cleans up your temp directory on a regular basis.

  • The problem with this task is that it's conplex and not real life related. I don't need another calculator.

    But once I had a CD with scratched surface near its center and lots of valuable JPEG files inside. I dumped the data from the unscratched part of the disk but all the filesystem was surely lost. So I wrote a program which analysed the dump and separated it into files. It was not very simple but was a nice and exciting file IO programming exercise.

  • Examples can be more complex than something you try to write yourself. It's easier to follow someone else doing something than it is to do it yourself. A real-world example like this calculator may be a fine way to introduce someone to a language. For instance, Practical Common Lisp starts with an example of an in-memory database (for CDs I think) and uses that as the springboard to explore parts of the language.

    I prefer seeing a real example built up over time than just a lot of simple "Hello World" programs.

  • Board games are fun to design and code since they come in many shapes and difficulties

    from tic-tac-toe to checkers to monopoly, its reinventing the wheel for educational purposes!

    the best advice i can think of is to pick something from a field of interest you have because coding for the sake of coding might dim your resolve

  • When I was first learning to program, the best example I ever worked with was building a text adventure game from scratch. The basics just required knowing how to display text on the screen, receive input from the keyboard, and rudimentary flow control. But since text adventures always have room to add more features/puzzles/whatever, they can be easily adapted to explore aspects of whichever language you're learning.

    Of course, not everyone finds games more interesting than calculators. It really depends on the programmer.

    Shannon Nelson : +1 - yep, this is how I started as well. It doesn't even have to be a huge game, just a system to walk around your own house or your school.
  • I've always found that implementing a game of some sort is sufficient incentive to learn various features of a language. Card games, especially, because they generally have simple rule sets to implement, but are sufficiently complex from an abstract point of view.

    I would agree, though, with everyone else: find examples of things that interest you. Not everyone is a game fan, but something like a mortgage calculator would be far more interesting.

  • First, let me say that cognitive psychologists have proven in numerous studies that the most important factor in learning is desire to know.

    If you want to learn about programming, you need to find a domain that stokes your desire to understand. Find a challenge that can be solved with programming.

    I agree with the other folks when they suggest something that you are interested in. And games seem to be a common thread. As I reflect on my experience learning to program (too many years ago), math problems and a simple game was involved.

    However, I don't think I really understood the power of software until I created a useful small program that helped a business person solve a real problem. There was a tremendous amount of motivation for me because I had a "client". I wasn't getting paid, but the client needed this program. There was sincere pain (gotta get my job done quicker) related to this situation.

    So my advice is to talk to people you know and ask what small annoyance or computer-related obstacle to they have. Then try to fix it. It may be a simple web widget that reduces repetitive, manual tasks for an office worker.

    One of my best early works was helping a little printing shop (no software, circa 1985) that struggled with estimating jobs to produce proposals that weren't money-losers. I asked alot of questions of the sales lady and of the operations manager. There was obviously an intersection of a common pain point with a really easy calculation that I could automate. It took me a couple of days to learn Lotus 1-2-3 (spreadsheet for you young-uns) enough to write a few macros. I was motivated. I had passion. I saw where I could make a difference. And that, more than anything else, drove me to learn some simple programming.

    Having real people, real problems, and really simple solutions could be the inspiration you need as a beginning programmer. Don't try to write an accounting system. Just take one discreet piece of someone's frustration away. You can build on that success.

    So, I wouldn't focus on the technique (yet). Don't worry about, "Am I doing this the most efficient way?" The main objective for a beginner is to have success, no matter how small, and build confidence.

    BTW, that Lotus 1-2-3 set of macros grew into a full job tracking system. Very archaic, limited features, but made that little print shop much more profitable.

    Create your motivation, fuel your desire, and develop your passion for programming like an artist unveils the masterpiece in a blob of clay. And be persistent. Don't give up when challenged with a roadblock. We all get stumped sometimes. Those are some of the best learning moments because humans learn more from failure than success.

    Good luck.