Uncategorized

Manually resize a SD card for your Raspberry Pi (version2)

0

Warning, use these instructions on your own risk.

 

When I tried to resize the 16GB SD card in the raspberry pi version 2 I got a corrupted file system and all other kinds
of nastiness.

So I decided to try to resize the thing manually.

First “dd” the image to the SD card.

Leave the card in the reader/writer and issue the following comands, replace the device for you own device
and use the units for your card.

 

$ sudo parted /dev/sdd
 GNU Parted 2.3
 Using /dev/sdd
 Welcome to GNU Parted! Type 'help' to view a list of commands.

 (parted) print
 Model: Generic- SD/MMC (scsi)
 Disk /dev/sdd: 16,1GB
 Sector size (logical/physical): 512B/512B
 Partition Table: msdos
Number Start End Size Type File system Flags
 1 4194kB 62,9MB 58,7MB primary fat16 lba
 2 62,9MB 3277MB 3214MB primary ext4

(parted) unit chs
 (parted) print
 Model: Generic- SD/MMC (scsi)
 Disk /dev/sdd: 1955,244,16
 Sector size (logical/physical): 512B/512B
 BIOS cylinder,head,sector geometry: 1955,255,63. Each cylinder is 8225kB.
 Partition Table: msdos
Number Start End Type File system Flags
 1 0,130,2 7,165,29 primary fat16 lba
 2 7,165,30 398,97,18 primary ext4

(parted) rm 2
 (parted) mkpart primary 7,165,30 1955,244,16
 (parted) quit

 Information: You may need to update /etc/fstab.

$ sudo e2fsck -f /dev/sdd2
 e2fsck 1.42.9 (4-Feb-2014)
 Pass 1: Checking inodes, blocks, and sizes
 Pass 2: Checking directory structure
 Pass 3: Checking directory connectivity
 Pass 4: Checking reference counts
 Pass 5: Checking group summary information
 /dev/sdd2: 86233/196224 files (0.1% non-contiguous), 630146/784640 blocks

 $ sudo resize2fs /dev/sdd2
 resize2fs 1.42.9 (4-Feb-2014)
 Resizing the filesystem on /dev/sdd2 to 3912448 (4k) blocks.
 The filesystem on /dev/sdd2 is now 3912448 blocks long.

$ sudo parted /dev/sdd
 GNU Parted 2.3
 Using /dev/sdd
 Welcome to GNU Parted! Type 'help' to view a list of commands.
 (parted) print
 Model: Generic- SD/MMC (scsi)
 Disk /dev/sdd: 16,1GB
 Sector size (logical/physical): 512B/512B
 Partition Table: msdos
Number Start End Size Type File system Flags
 1 4194kB 62,9MB 58,7MB primary fat16 lba
 2 62,9MB 16,1GB 16,0GB primary ext4
(parted) quit
 $

 

And of course, don’t choose ‘resize’ when the rspi first boots 🙂

OSX enable hibernate

0

As I don’t use my OSX machine very often I like to have it hibernate iso suspend to RAM.

But as the “geniuses” didn’t enable it by default it has to be enabled manually:

sudo pmset hibernatemode 25

Now when you choose “sleep” it will hibernate.

To reset it back to suspend:

sudo pmset hibernatemode 3

 

Get a Logitec unifying USB dongle to accept devices in Linux

0

When I bought a Logitec M570 wireless trackball I had trouble connecting it to my Logitec unifying USB dongle from my keyboard  under Linux.

I could just plug in a second USB dongle but that’s not the way to go.

Luckily there are free-software engineers who don’t fear to fight the beast 🙂

A nice fellow named  binky734 dived in and came up with a solution:
I just found an extremely simple way of getting your Unifying Receiver to function on Linux without having to bother with pairing it on Windows first. In fact, I tried pairing my M570 with Windows first, and that did not work.

 

  1. Download this small C program.
  2. Ctrl+Alt+T to open a command line and cd to your download directory
  3. $ gcc -o unifying_pair unifying_pair.c
  4. Unplug your Unifying Receiver and head to /dev
  5. Plug in your Unifying Receiver and wait for it to show up in /dev/. Mine was hidraw0.
  6. $ sudo ./unifying_pair /dev/X where X is which ever device name was in your /dev/ directory for your receiver.
  7. If your mouse is not already on, switch it on now. You might have to do the whole ‘turn it off and back on’ thing, but mine connected right away.

 

Hope this helped!

 

Rotate video 90 degrees clockwise

1

I’ve have a video shot with a phone and for some reason the maker thought it would be a good idea to keep the phone upright while filming.
So now I’m forced to view the video with my head turned 90 degrees.
It’s uncomfortable so lets turn this video 90 degrees clockwise.

avconv -i inputvideo.mp4 -c:a copy -q 1 -r 23.967 -vf "transpose=1" outputvideo.mp4

Python xmlrpcserver with HTTPS support and basic authentication

6

For a project I’m working on at Formatics.nl I needed a Python based multithreaded xmlrpcserver with HTTPS support, HTTP basic authentication and capable of running on any port. After looking into solutions which required some sort of server for the HTTPS and basic autentication parts I decided to go for a better solution to try to add the HTTPS support and basic authentication to the Python xmlrpsserver itself. That way we would have a simple and fast solution which could run from any box on any port. Looking around on the net I found various solutions for every requirement but nothing which combined it all into one solution. So after combining various bits and pieces I came up with a Python xmlrpcserver with HTTPS and basic authentication support.

As the code used came from various free-software projects and locations I decided to share the server with the world so that it might benefit others.

For the HTTPS you need OpenSSL certificates, use your existing PEM formatted one or just create one yourself.

$ openssl genrsa -out privkey.pem 2048
$ openssl req -new -key privkey.pem -out cert.csr
$ openssl req -new -x509 -key privkey.pem -out cacert.pem -days 1095

And here’s the server

from SocketServer import ThreadingMixIn, BaseServer
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler, SimpleXMLRPCDispatcher
import socket
from OpenSSL import SSL
from base64 import b64decode

from threading import Thread, Condition
from thread import start_new_thread

import traceback
import time

# static stuff
DEFAULTKEYFILE = 'privkey.pem'  # Replace with your PEM formatted key file
DEFAULTCERTFILE = 'cacert.pem'  # Replace with your PEM formatted certificate file

class Services:
    def give_me_time(self):
        return time.asctime()

class CustomThreadingMixIn:
    """Mix-in class to handle each request in a new thread."""
    # Decides how threads will act upon termination of the main process
    daemon_threads = True

    def process_request_thread(self, request, client_address):
        """Same as in BaseServer but as a thread.
        In addition, exception handling is done here.
        """
        try:
            self.finish_request(request, client_address)
            self.close_request(request)
        except (socket.error, SSL.SysCallError), why:
            print 'socket.error finishing request from "%s"; Error: %s' % (client_address, str(why))
            self.close_request(request)
        except:
            self.handle_error(request, client_address)
            self.close_request(request)

    def process_request(self, request, client_address):
        """Start a new thread to process the request."""
        t = Thread(target=self.process_request_thread, args=(request, client_address))
        if self.daemon_threads:
            t.setDaemon(1)
        t.start()

class MyXMLRPCServer(CustomThreadingMixIn, SimpleXMLRPCServer):
    def __init__(self, ip, port, keyFile=DEFAULTKEYFILE, certFile=DEFAULTCERTFILE, logRequests=True):
        self.logRequests = logRequests
        class VerifyingRequestHandler(SimpleXMLRPCRequestHandler):

            def setup(myself):
                myself.connection = myself.request
                myself.rfile = socket._fileobject(myself.request, "rb", myself.rbufsize)
                myself.wfile = socket._fileobject(myself.request, "wb", myself.wbufsize)

            def address_string(myself):
                "getting 'FQDN' from host seems to stall on some ip addresses, so... just (quickly!) return raw host address"
                host, port = myself.client_address
                #return socket.getfqdn(host)
                return host

            def do_POST(myself):
                """Handles the HTTPS POST request.
                It was copied out from SimpleXMLRPCServer.py and modified to shutdown the socket cleanly.
                """
                try:
                    # get arguments
                    data = myself.rfile.read(int(myself.headers["content-length"]))
                    # In previous versions of SimpleXMLRPCServer, _dispatch
                    # could be overridden in this class, instead of in
                    # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
                    # check to see if a subclass implements _dispatch and dispatch
                    # using that method if present.
                    response = myself.server._marshaled_dispatch(data, getattr(myself, '_dispatch', None))
                except Exception, info: # This should only happen if the module is buggy
                    print "ERROR do_POST: ", info
                    print "Traceback follows:", traceback.print_exc()

                    # internal error, report as HTTP server error
                    myself.send_response(500)
                    myself.end_headers()
                else:
                    # got a valid XML RPC response
                    myself.send_response(200)
                    myself.send_header("Content-type", "text/xml")
                    myself.send_header("Content-length", str(len(response)))
                    myself.end_headers()
                    myself.wfile.write(response)

                    # shut down the connection
                    myself.wfile.flush()
                    myself.connection.shutdown() # Modified here!

            def do_GET(myself):
                """Handles the HTTP GET request.

                Interpret all HTTP GET requests as requests for server
                documentation.
                """
                # Check that the path is legal
                if not myself.is_rpc_path_valid():
                    myself.report_404()
                    return

                response = myself.server.generate_html_documentation()
                myself.send_response(200)
                myself.send_header("Content-type", "text/html")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)

                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown() # Modified here!

            def report_404(myself):
                # Report a 404 error
                myself.send_response(404)
                response = 'No such page'
                myself.send_header("Content-type", "text/plain")
                myself.send_header("Content-length", str(len(response)))
                myself.end_headers()
                myself.wfile.write(response)
                # shut down the connection
                myself.wfile.flush()
                myself.connection.shutdown() # Modified here!

            def parse_request(myself):
                if SimpleXMLRPCRequestHandler.parse_request(myself):
                    basic, foo, encoded = myself.headers.get('Authorization').partition(' ')
                    username, foo, password = b64decode(encoded).partition(':')
                    #print username, foo, password
                    if username == 'admin':
                        return True
                    else:
                        myself.send_error(401, 'Authentication failed')
                        return False
        SimpleXMLRPCDispatcher.__init__(self, False, None)
        BaseServer.__init__(self, (ip, port), VerifyingRequestHandler)

        # SSL socket stuff
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file(keyFile)
        ctx.use_certificate_file(certFile)
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.server_bind()
        self.server_activate()

        self.funcs = {}
        self.register_introspection_functions()
        self.register_instance(Services())

        # requests count and condition, to allow for keyboard quit via CTL-C
        self.requests = 0
        self.rCondition = Condition()

    def startup(self):
        #run until quit signaled from keyboard
        print 'server starting; hit CTRL-C to quit...'
        while True:
            try:
                self.rCondition.acquire()
                start_new_thread(self.handle_request, ()) # we do this async, because handle_request blocks!
                while not self.requests:
                    self.rCondition.wait(timeout=3.0)
                if self.requests:
                    self.requests -= 1
                self.rCondition.release()
            except KeyboardInterrupt:
                print "quit signaled, i'm done."
                return

    def get_request(self):
        request, client_address = self.socket.accept()
        self.rCondition.acquire()
        self.requests += 1
        self.rCondition.notifyAll()
        self.rCondition.release()
        return (request, client_address)

    def listMethods(self):
        """return list of method names (strings)"""
        methodNames = self.funcs.keys()
        methodNames.sort()
        return methodNames

    def methodHelp(self, methodName):
        """method help"""
        if methodName in self.funcs:
            return self.funcs[methodName].__doc__
        else:
            raise Exception('method "%s" is not supported' % methodName)

if __name__ == '__main__':
    import sys
    if len(sys.argv) == 3:
        host = sys.argv[1]
        port = int(sys.argv[2])
    else:
        host = 'localhost'
        port = 8111

    server = MyXMLRPCServer(host, port, logRequests=True)
    # Run the server's main loop
    sa = server.socket.getsockname()
    print "Serving HTTPS on", sa[0], "port", sa[1]

    server.startup()

For a client use someting like this

from xmlrpclib import ServerProxy

user = 'stas'
pas = 'stas'
p = ServerProxy('https://%s:%s@localhost:8111' % (user, pas))
print p.give_me_time()

Eclipse change the tooltip colors on Ubuntu 12.04

0

Found an excellent post on ‘Ask Ubuntu’:
http://askubuntu.com/questions/70599/how-to-change-tooltip-background-color-in-unity

And in addition to the tip in the above post I copied the whole Ambiance theme into my home directory as I also have eclipse installed in my home directory which lives on a external HD so I have always a proper theme “with me” 🙂

Fix media keys in debian mate/mint

0

Start mateconf-editor and set the key /desktop/mate/sound/default_mixer_device to alsamixer:default

First post

0

This will become the online  place where I can keep my stuff.

Go to Top