Vim: Stop Vim from reading standard input

wnguyen@europa:~$ d | vim -
Vim: Warning: Output is not to a terminal
Vim: Reading from stdin...

Ahh shit, I hate it when you accidently type something and then lock up the terminal.

Usually, pressing CTRL+C will unlock the console but sometimes it doesn't work.

Press CTRL+Z to get back to the console and then kill the processes manually.

Bash: List and kill a process

To list the processes you're running in the current terminal, type "ps".

Figure out which processes from the list you want to kill and select the process IDs (PIDs).

wnguyen@europa:~$ ps
  PID TTY          TIME CMD
22452 pts/16   00:00:00 bash
18595 pts/16   00:00:00 vim
18596 pts/16   00:00:00 vim
20490 pts/16   00:00:00 ps

wnguyen@europa:~$ kill -9 18595 18596

That will kill off both vim processes. Type ps again to make sure they're dead.

image
Dead like this.

Computing Inception

I was bored the other day and decided to see how many levels deep I could go...

inception

Would throw in a few Inception meme pics but that'd be side tracking too much =P

Win7: How to change back to XP style taskbar

Wow I can't believe I've missed this simple write-up.

The superbar is pretty neat, but it isn't for everyone. Someone asked me today how to change it back to the more familiar XP-style layout, with text and without the gayish OS X task grouping.

So, right click on the taskbar to bring up the menu. Select "Properties" to bring up this screen.

image

Enable "Use small icons" and change the taskbar buttons to "Never combine".

Thanks Microsoft for adding this in for people like us =)

Firefox 4: Stop tabs from appearing as separate Win7 Aero peek previews

I like the Aero peek previews, but when programs abuse them it becomes really difficult to see what you're doing.

I really like Firefox 4 so far. It's fast, looks nice and it's all about the little things that make it better. Except when I hovered over the task item and saw ...

image  
Oh the horror!

Now you're probably thinking... what's the big deal, right? Well each browser window will add more previews, and with my insane super-nerd 5x browser with 20x tabs in each browsing habits, that'll equate to a lot of previews.

Luckily, there's a nice little option to disable it (unlike Chromium).

Click on the Firefox button in the top left corner and select "Options".

Select "Show tab previews in the Windows taskbar".

image

That's it, you're done!

image
Now you're normal again.

Django: Creating custom tag and endtag type template tags

A single tag is normally sufficient when it comes to template based operations.

However, sometimes you'll need to capture the contents of the template before choosing what to do with it.

For example, the built-in template tag "if" and "endif".

The tag captures anything between the if/endif tags and then does something with it.

The example below is straight from Django docs.

{% upper %}{{ name }} will appear in uppercase.{% endupper %}

The usage of the template tag seems simple enough. Uppercase all the text between the tags.

The creation of the custom tag is below.

def do_upper(parser, token):
nodelist = parser.parse(('endupper',))
parser.delete_first_token()

return UpperNode(nodelist)

class UpperNode(template.Node):
def __init__(self, nodelist):
self.nodelist = nodelist

def render(self, context):
output = self.nodelist.render(context)
return output.upper()

The magic line there is self.nodelist.render(context), which pulls out all the content in between and renders it properly before performing the upper-casing operation.

[ Source ]

WinXP: Windows logs out straight after entering user details

When upon fixing a computer, I had trouble getting back into Windows after deleting the malware files.

The reason was that the malware had slipped itself into the login process by changing the file which Windows expects, redirecting the initialisation process to a dirty file.

When the file is removed, Windows doesn't know what to do with the login process and boots you back to the login screen.

Many places suggest this solution:

cd %WINDOWS%\system32
copy userinit.exe wsaupdater.exe

Personally, I don't like this. Although it solves the problem, this solution will not work if Windows is expecting a file other than "wsaupdater.exe".

To fix it properly, boot up the computer using the Windows XP setup disc or BartPE. (See this guide)

Once you've got the Registry Editor open:

  • Select "HKEY_USERS"
  • Click File > Load Hive
  • Open up "C:\Windows\System32\Config\SOFTWARE" (SOFTWARE is the filename)
  • Give it a name. For this example I'll call it "LOGOUT"
  • Now navigate to: HKEY_USERS\LOGOUT\Microsoft\Windows NT\CurrentVersion\Winlogon
  • Now find "Userinit" on the right panel and double click to edit.
  • It should point to: "C:\Windows\System32\userinit.exe,"

    Note: that red comma it HAS to be there or else this fix wont work.
  • Navigate back and select "HKEY_USERS\LOGOUT"
  • Click on File > Unload Hive.

Now it is pointing back to "userinit.exe", the correct file.

[ Source ]

WinXP: Fix Mixa trojan/virus

I have no idea how people do it, but yet another relative has managed to break their computer by doing something stupid and has brought the computer over, asking me to spend a day fixing their computer. "Sure, I'd love to waste a nice sunny day off to do that!"

Anyway, before I become bitter and hateful, I quickly discovered that one of their many problems was that they were infected with a trojan called "Trojan.Mixa.A" or "W32/Autorun-DH".

It probably goes by a few other names, but the following information should be enough to identify it.

It's located at:

  • %WINDOWS%\Mixa.exe
  • C:\Mixa_i.exe (And the root path of any other writable drives or USB devices)
  • %WINDOWS%\System32\mixa.exe
  • %WINDOWS%\System32\systemio.exe

File information:

  • Mixa_i.exe
  • Filesize: 988kb
  • Version: v1.0.0.2
  • Company: Puppy
  • Product Name: Milk DHA
  • image

It is fairly difficult to remove using normal means, as you can't delete the files as they're in use. Trying to kill the task using the task manager will not work because it will log you out whenever it detects the Task Manager.

It also slips itself in as a fake system shell application, which makes Windows load it everytime you log in. To remove it, you will have to do it before Windows loads.

Using the Windows XP setup disc

Use this method if you have access to the Administrator account. If not, use the other method.

Load up the computer with the setup disc and select "Recovery Console" by pressing R once its ready.

Navigate around the console and delete the files if they exist in the given locations. Use the "delete" command to delete files.

  • delete %WINDOWS%\Mixa.exe
  • delete C:\Mixa_i.exe
  • delete %WINDOWS%\System32\mixa.exe
  • delete %WINDOWS%\System32\systemio.exe
  • See link below for the next step.

    Set up a BartPE startup disc

    This will give you access to the harddrive so you can remove the files. See this guide to create the BartPE disc.

    Once you've loaded up the computer with BartPE:

    • Click "Go"
    • Command Prompt (CMD)
    • Use the Recovery Console steps above

    OR

    • Click "Go"
    • Programs
    • A43 File Management Utility
    • Use the program to delete the files

    See next step below.

    Fix login screen

    Since we've deleted the files, this ensures that the malware can't reinstall itself after we log in.

    At this point, I thought it was all fixed and rebooted the machine. However, you should not reboot it yet! The system is still in a broken state!

    Windows still expects the missing files to be there and you will not be able to log in properly. To fix the login screen, stay in the command prompt and type "regedit". This will being up the Registry Editor.

    I've written the tutorial in another post as it is a common problem when fixing virus/trojan related issues.

    Once you've reverted the "Userinit" filename you can reboot and log in as usual.

    [ Source, Microsoft KB 892893 More information about the trojan ]

    Facebook: How to cancel friend request

    A long time ago I requested to be friends with someone... well, that I now don't want to be friends with. I totally forgot about it until I saw their profile appear on the suggested friends list.

    Annoyingly, Facebook doesn't really have a place to let you cancel it anymore.

    Luckily, after some poking around and experimenting I found a way to do it.

    • Open up your Privacy settings page under Accounts.
      image
       
    • Scroll to the bottom and find the "Block lists" option
      image
    • In there, enter in either the name or email of the person you want to cancel.
      image
    • Block them.
    • Now remove them from the block list.
    • View their profile.
    • It should now give you the option of "Add as friends".

    jQuery UI: Slider with mouse scrolling tutorial

    If you haven't discovered already, jQueryUI allows you to use jQuery in a way which recreates several very useful user interface elements. It also provides additional animation effects to make life easier.

    You'll need:

    One of which is the slider, which works quite well when dragging the bar but lacks a bit of support for mouse scrolling over the actual element being scrolled.

    image

    Now the slider will work as normal. When the slider is dragged, the content will scroll accordingly.

    To set up the slider:

    $(document).ready(function() {
    //scrollpane parts
    var scrollPane = $('#scroll-pane');
    var scrollContent = $('#scroll-content');

    //build slider
    var slide_handler = function(e, ui) {

    if (scrollContent.height() > scrollPane.height()) {
    scrollContent.css('margin-top', Math.round(((100 - ui.value) / 100) * (scrollPane.height() - scrollContent.height())) + 'px');
    }
    else {
    scrollContent.css('margin-top', 0);
    }
    };

    var scrollbar = $("#scroll-bar").slider({
    orientation: "vertical",
    value: 100, // Sets the value to the top
    slide: slide_handler
    });
    });

    This will set up the scrollbar, but when you scroll the mouse over the panel it wont register the events. This is because you'll need to set up the mouse-wheel extension.

    Within the document ready event, add:

    scrollPane.mousewheel(function(event, delta) {
    var value = scrollbar.slider('option', 'value');

    if (delta > 0) { value += 10; }
    else if (delta < 0) { value -= 10; }

    // Ensure that its limited between 0 and 100
    value = Math.max(0, Math.min(100, value));
    scrollbar.slider('option', 'value', value);
    event.preventDefault();
    });

    This will change the slider value, depending on whether you scrolled up or down.

    Infuriatingly, the change in slider value will not update the scrolling panel. This took me a while to figure out, but you'll also have to add another event handler called the "change" event.

    You can simply reuse the handler when initialising the slider:

    var scrollbar = $("#scroll-bar").slider({
    orientation: "vertical",
    value: 100,
    slide: slide_handler,
    change: slide_handler
    });

    Now when you scroll your mouse over the scroll pane, it'll also change the value of the slider. When the "change" event is triggered, it'll scroll the content.

    [ Slider documentation ]

    Python: How to parse XML

    In a sample XML string such as:

    <?xml version="1.0" encoding="utf-8" ?>
    <YourRoot>
    <Group Found="1000">
    <Item ID="1">
    <Title>Something silly</Title>
    <Summary><![CDATA[Blah blah blah...]]></Summary>
    <Location>
    <Country>Australia</Country>
    <State>NSW</State>
    <City>Sydney</City>
    <PostalCode>2002</PostalCode>
    </Location>
    </Item>
    <Item ID="2">
    ...
    </Item>
    <Item ID="3">
    ...
    </Item>
    </Group>
    </YourRoot>

    Reading the data

    Using ElementTree, you can either read directly from the file or load it into a string first. Include the following import.

    from xml.etree.ElementTree import ElementTree
    from xml.parsers.expat import ExpatError

    If you are using a string:

    from xml.etree.ElementTree import fromstring

    try:
    tree = fromstring(xml_data)
    except ExpatData:
    print "Unable to parse XML data from string"

    Otherwise, to load it directly:

    try:
    tree = ElementTree(file = "filename")
    except ExpatData:
    print "Unable to parse XML from file"

    Once you have the tree initialised, you can begin parsing the information.

    As ElementTree is quite versatile, there are a few options for parsing the data. You can choose between being lazy or specific.

    Being lazy and get all "Item" elements from XML

    For simple XML data like RSS feeds, this is usually enough to get by.

    def parse_results(self, tree):
    results = []

    for item in tree.getiterator('Item'):
    location = element.find('Location')

    results.append({ 'id': element.get('ID'),
    'title': element.find('Title').text,
    'summary': element.find('Summary').text,
    'location': {
    'country': location.find('Country').text if location.find('Country') is not None else '',
    'state': location.find('State').text if location.find('State') is not None else '',
    'city': location.find('City').text if location.find('City') is not None else '',
    'postcode': location.find('PostalCode').text if location.find('PostalCode') is not None else '',
    },
    })

    From the example, element.get('ID') reads the element attribute and element.find('Title').text returns the element value.

    The code checks for information within location before reading from it, otherwise it defaults to an empty string.

    Being picky and navigating the XML paths manually

    Depending on how complex the XML structure is, you may have to navigate some of it manually.

    def parse_results(self, tree):
    results = []
    group = tree.find("YourRoot/Group")

    for item in group.getiterator('Item'):
    location = element.find('Location')

    results.append({
    # Exactly the same as above...
    },
    })

    This time we navigate the tree a little by using tree.find("YourRoot/Group") to tell ElementTree that we want the specific element.

    Then we iterate all "Item" elements in "Group" as per usual.

    [ ElementTree Documentation, Source ]

    Fix Sansa c200/c240/c250 random song selection

    I've been using my Sansa c250 every once in a while for the past year or so but only recently noticed that the songs aren't selected randomly, even though shuffle mode is on.

    For example, the player starts up with the last song it was playing. When you hit next, it'll play "Song A". It'll then play a couple of random songs (eg. Song F, P, C, T, etc). When you turn it off (or allow it to auto power-off) it'll stay on the last song you played, "Song Z".

    Now the next time you start it up, it'll start on song Z, but when it goes to the next track... it'll pick song A, F, P, C, T, etc.

    I've looked online and found quite a few people had the same issue, but there were no definite fixes.
    The firmware I had was v3.02.04A and its been a while since there had been an update. A quick search showed that v3.02.05A out. Unfortunately, there was no change log available.
    Taking the risk I installed it and, as luck would have it, the random song selection problem was solved!

    *edit - 6/1/2011*
    I'm afraid the firmware update doesn't actually fix it but forgot to update this post.
    Contacted Sansa about it, awaiting reply.

    Notes

    I have the v2 of the player. If you have a v1 player, the steps will vary a little so the you'll have to check what version you have prior to upgrading.
    Installing the wrong version may cause it to stop turning on.
    To check, go to "Settings" > "System Info". If the version starts with 1, you have a v1 player. See here for the firmware downloads.
    At time of writing, v3.02.05 is the latest version and I'm using the "American & Asia Pacific Region" release.

    Upgrade

    • Download the latest firmware here (link to v2 firmware) for your region.
    • Turn off your Sansa C250.
    • Put it on hold.
      IMG_0390
    • Now hold the rewind button.
      IMG_0393
    • As you hold the rewind button, connect the cable.
    • Keep holding the rewind button until the logo goes away and it says "Connecting".
    • Now it should be connected like a USB drive and show up as a new drive with the label "Sansa C250".
    • (There is another drive that appears but just ignore it)
    • Extract the file(s) from the file you downloaded and put them into the new drive.
    • Once its finished, take it off "hold".
    • Unplug the cable.
    • It should now automatically install the firmware and turn off.
    Just check the system info again to make sure it installed properly.
    [ Source, Downloads ]

    Starcraft 2: Fix overheating bug

    Its been reported that the out of game menus in Starcraft II will make your graphics card work harder than it should.

    For reasons unknown, the menu screens (such as when you're signing in and selecting between single or multiplayer) are not frame limited.

    This will make your graphics card feel like a fat kid in a candy store, feeling it can eat everything but ultimately becoming so obese.

    Solution

    Until it is fixed, I don't want to experience how much damage first hand a melting video card can do to my computer (or wallet).

    • Make sure SC2 isn't running
    • Open up "My Documents" (or "Documents" in Windows Vista/Win7)
    • Go into the "Starcraft II" folder
    • Open up "Variables.txt"
    • Add the following lines at the end

    frameratecapglue=30

    frameratecap=60

    • Save

    Now it should apply the framerate limits the next time you run it.

    [ Source ]

    If you're having problems ALT+Tabbing, see here.

    Starcraft 2: Delay when ALT+Tabbing back into the game

    I've noticed a few times when I go back into the Starcraft II, it freezes for a good 10 seconds or so even if I'm in game or in menu. For a few people, its worse.

    Not sure why, but it seems to mainly affect ATI cards. It doesn't seem to matter how high your details levels are either.

    Solution

    By default, the SC2 uses the "Fullscreen" mode in the graphics setting. Change this to "Windowed (Fullscreen)" and it'll ALT+Tab like a charm!

    image

    [ Source ]

    While you're out of the game, Blizzard has confirmed a bug that causes the videocard to overheat. See here to prevent your video card from self destructing.

    Django: Delete all objects in Model

    To clear all the data from a django table, simply call:

    ModelName.objects.all().delete()

    Encoding: Convert between character sets with iconv

    Using a linux shell command called iconv you can convert content of a file from one encoding to another.

    If you know exactly what format its in:

    iconv --from-code=LATIN1 --to-code=UTF8 -c --output=~/test/xml/input_clean.xml ~/test/xml/input.xml

    The "-c" option tells the program to omit unmappable characters. Otherwise it will stop at the first unmappable character it encounters.

    Peerblock: Unblock Steam and Blizzard domains

    By default, PeerBlock will block Blizzard and Steam servers.

    This will kill off your access to Starcraft II, World of Warcraft and Left 4 Dead! Not acceptable!

    To prevent that, add then to the whitelist.

    Repeat the process for the Steam list: http://list.iblocklist.com/?list=steam

    Starcraft 2: Association Required Fix

    I installed SC2 earlier today before I had to go out. I come home at 1am in the morning to fire it up and it spends 15 minutes downloading and patching some stupid shit 3x over.

    When its finally ready, the play button glows and taunts me to start.

    image 
    "This Battle.net account does not include an associated copy of Starcraft II. Please log into Battle.net account management and add the game to your account."

    Now comes 2am and I'm finally about to cry. WHAT THE FUCK?

    Problem

    Apparently Blizzard doesn't like it when you use a distributed release from torrents.

    Well I'm fucking sorry Activision! The DVD is slow to install from and your digital distribution server is even slower because of the God-forsaken primitive internet we have in Australia.

    All I wanted was to pre-download the game and play it when I get the chance... Now I have to go through the damn installation again :(

    Solution

    • Uninstall (but keep your saves).
    • Install from the DVD or the digital distribution from your account and region (SEA, US, etc)
    • Now it should work.
     
    Copyright © Twig's Tech Tips
    Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog