Category: Uncategorized

  • Blog moved to subdomain and folder

    Due to little activity on the blog, I’ve decided to move the blog to the subdomain blog.lovholm.net and the corresponding path lovholm.net/blog. For those places this causes trouble with links I apologize.

    I hope to be able to write more in the years to come, although I know this blog is mostly for my own thoughts and there aren’t many readers.

    If you come across this, thank you for visiting, and let me know. It’s fun to know whether anyone checks in.

  • Programming Philips Hue

    Programming Philips Hue

    Phillips’ smart light system Hue has for long been synonymous with smart IoT light bulbs, and although they recently have received competition from IKEA Trådfri and Osram Lightify (and many more), it’s still the dominant platform for smart lighting.

    Basically Phillips Hue consists of the light bulbs, lamps or light strips which can be either white, white ambience or full colour, as well as the Hue Hub. In addition Phillips also sells buttons and sensors that can be used with the Hue lamps.

    As the bulbs are communicating through the Zigbee protocol the Hub acts as a gateway where you, or your apps, or even smarts hubs can connect and speak with the bulbs. This is done through an API endpoint exposed by the hub.

    Find the Hub and the API-endpoint

    Once you get your Hue system up and running, your Hue Hub is connected to your home router over Ethernet. There are several ways of finding the hub. Given that you have access to the web interface of your router (usually found at the address 192.168.1.1 or similar), the easiest way is to find it under connected devices. Do you see a host named “Philips-hue” there? Bingo! If you don’t have access to the router, you could use nmap, arp or other funky tool to find the hub on your local network. Once you find the right IP-address you will be greeted by a page listing license information among other things .

    Once you have the IP-address to the Hue Hub on your local network, let’s find the API-endpoint at http://the-ip-address/api.

    For easier access to the API, you can also use the supplied debug client. It can be found at http://the-ip-address/debug/clip.html

    Obtain a key

    If you start running commands against the API-endpoint you will soon discover that you need to be authorized before you can do anything. To obtain such a key. Do a POST-request to /api with the following JSON-body. You will also have to click the physical button on the Hue Hub to be granted a token.

    {“devicetype”:”the_hue_app#test”}

    Software libraries

    The API for the Philips Hue is not enormous, but using an already existing library with the API implementation in your programming language of choice saves you the hassle of creating the data-objects. Q42 has compiled a pretty good list over the available Hue libraries available. You can find the documentation of the API on Hues developer pages, but for the official documentation you will need to create a free account.

    Control the lights

    Depending on the library you chose (or if you have to create HTTP-clients on top of the model) you are now ready to create an application that can talk with your Philips Hue lights.

  • Into the exclusion zone

    Into the exclusion zone

    I was born in 1986, and one of the names always being associated with this year is Chernobyl. Yesterday I had the ambivalent “pleasure” to visit parts of exclusion zone: the buffer zone, the Pripyat zone and the 10K zone in which the reactor is located. Towards the end of 2017 a new shelter, or sarcophagus, was put in place over the reactor. This, together with the old shelter and the work of 500.000 liquidators after the catastrophy, makes the zone a safe place to visit for a shorter timespan, and today it’s grown an industry around taking people into the zone and show them around.

    Following a test run on the reactor on 26th April reactor 4 at the Chernobyl power plant exploded sending a huge amount of radioactivity into the sky. The cloud created by the accident first blew north and then westward increasing radioactivity levels throughout the Soviet union and the rest of Europe. The accident became known in the West as radioactivity levels were picked up outside the Soviet union, but within Soviet it was kept as a secret and the consequences were played down. In fact, already on the 1st of May, a few days later, the mayday celebration in Kiev, a few hours by car to the south, went uninterrupted.

    At the same time, a huge operation were initiated to get control over the fire and constant radiation being spread by the accident. At first fire men tried to take out the fire without any protective gear. At this point any direct exposure was lethal. Later helicopters were used to throw sand, clay and later lead into the fire. Still this job was leathal. Much was done; water was drained from under the reactor to avoid a fatal reaction which would leave large parts of Europe uninhabitable, in the area around the reactor villages were emptied and buildings demolished, Pripyat of around 50.000 people were evacuated and people were to never move back. Above the reactor a sarcophagus was erected. First by robots as the radiation was leathal from as little as 20 seconds exposure, but as some of the robots malfunctioned humans were used as well; bio-robots covered in makeshift protective gear. The human tragedies, still continuing to our day, was and are immense. About 500.000 people were involved in the clean up, many exposed to large amounts of radiation.

    The first sarcphagous was built to last for around 30 years, the new will last for another 100 years, but this area will stay uninhabitable for thousands of years.

  • Push your code onto your EC2 instance with Git

    Push your code onto your EC2 instance with Git

    Here is a little thing that has saved me a lot of work, and which I find quite neat.

    I use the EC2 as my cloud computer. This page (lovholm.net) is hosted on a shared host, but sometimes it’s nice to have the flexibility to run things that are not supported by shared hosts, such as custom software and all that jazz. When I try out different web-things that are not only front-end or PHP I usually create a subdomain and place the code on an EC2-instance after initial development on localhost.

    Since I now use different environments for development I have found this neat way of pushing code  from my local computer to the server. This is a lot easier than using FTP, and is more flexible than deploying to Heroku (which is – by the way – a brilliant super-easy way of hosting and deploying).

    The idea is very similar to that used by Heroku, except that the setup is more complex and the good terminal tool is lacking. On the other hand it gives you greater flexibility to run your own instance and it may also be more affordable if you plan to make your code into a business with much traffic.

    Don’t know what git is, or don’t have git installed. Github has some great documentation on installation and Git on what git is.

    Setting up the Git-repositories

    Locally I initialise a git repository in the folder I am working.

    local $ cd the-amazing-test-project
    local $ git init

    Then I use SSH to connect to my cloud computer where I have a folder for remote git repositories (I store these in a sibling-folder to the root folders of my projects.)

    remote $ cd git-repos
    remote $ mkdir testrepo.git
    remote $ cd testrepo.git
    remote $ git init --bare

    When this is done, we need to create a remote-link from the local repository, and create a post-update hook at the remote repository. This will make you able to push the code from the local git-repo onto the server and from there unpack the code and do other neat things like logging and restarting of servers (if necessary).

    The cloud instance as remote repository

    So now you have a local repository on which you work, commit and track your local files, and you have a bare repository in the cloud. Let’s make the bridge.

    local $ git remote add web ssh://ec2-user@yourwebserver.cloud.org/home/www/git-repos/testrepo.git

    Create an empty file in the local directory, use

    git add .

    to add this file to repository, commit the changes to the git repository:

    git commit -am "Initial test"

    Now you could push the repository to the clouds using:

    git push web master

    If you get an error message. Make sure that you have added the keys used to connect to the remote host to your ssh-keys. If not, you could use ssh-add to do this. Call the command ssh-add with the key as the only argument.

    If you still experience problems. Enter the local repository with your terminal and then change to the .ssh directory where you will find a file named config. This content of the file should be something similar to this:

    [core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = false
    [remote “web”]
    url = ssh://ec2-user@yourwebserver.cloud.org/home/www/git-repos/testrepo.git
    fetch = +refs/heads/*:refs/remotes/origin/*

    Add a hook for deployment

    Once you have a connection between the local and remote repository, we need to make a way for the remote repository to deploy our code and not just keep it safe and sound. Connect through ssh to the terminal of your remote computer and change into the git-repos directory and your testrepo.git folder.

    Within this folder you should have a folder with hooks, and it is here we are going to add the last pieces of code to get our system up and running. We will utilize the server-side hook post-update to deploy our code and do other tasks needed. The post-update hook is a shell script which git executes after receiving a push. Add to this the following code:

    #!/bin/sh
    GIT_WORK_TREE=/home/www/amazing_web git checkout -f
    
    echo "the_amazing_web_project checkin at: <$(date)> " >> /home/www/logs/updates_log

    The second line in this code excerpt will extract the data (when adapting this snippet, make sure the path after the equal sign is created), and the fourth line will add to a logfile the name of the project and the date.

    You can now commit code to your remote server easy, and if you need to do any changes like rebooting the web-server you can add the code to the post-update script.

  • Facebooksider som RSS

    RSS er super-praktiskt. Enten om du bruker laptop, tablet eller mobil så er aggregerte kilder gull verdt. Hvor digg er det ikke å kunne samle alt du ønsker å lese i en leser (f.eks Google Reader) eller til og med automatisk oppdatere nettbrettet ditt med de nyeste sakene fra dine favorittkilder?

    Her er en liten oppskrift på hvordan du kan gjøre dette på facebook sider du følger. Det er ikke alltid at social feed plukker opp disse, og dessuten er det fint å kunne lagre oppdateringer for ettertiden.

    Det første du trenger er denne URL strengen:

    https://www.facebook.com/feeds/page.php?format=atom10&id=241453889260137
    

    Denne ganske ordinære URL strengen som parses som to argumenter av webserveren [:format =>  “atom”, :id => “241453889260137”] (ruby hash syntax), et voila, du får en atom formatert RSS side tilbake. Det du gjør her er å bytte ut id fra URLen ovenfor med iden fra siden du ønsker å følge.

    Men hva om det ikke er noe ID i side URLen på Facebook? Som f.eks i bildet under (tatt fra siden til Løvholm Digitale Medier – mitt forholdsvis nye enkeltmannsforetak).

    Screen Shot 2013-01-30 at 11.50.14 PM

    Her blir det litt mer komplisert.Dersom du forsøker å laste inn atom RSS-feeden fra dette navnet vil du kun få en side med en feilmelding.

    Vår vei til målet går igjennom fantastiske Open Graph, teknologien Facebook bruker for å organisere sine tjenester og sin verden, og dens API.

    http://graph.facebook.com/lovdigmed

    Her kan du bruke navnet som oppslag og få tilbake en JSON-formatert tekststreng med det du trenger å vite

    Screen Shot 2013-01-30 at 11.56.36 PM

    Nå trenger du kun å gå tilbake til den første URLen vi hadde, og benytte IDen til siden (merk: ikke cover_id) for å få tilgang til RSS-feeden.

    Nå kan du lese Facebook sideoppdateringer i din yndlingsleser sammen med alt annet interessant du abonnerer på

    Screen Shot 2013-01-31 at 12.00.10 AM

  • The Gathering 2012

    Godt plantet i en stol på Universitetet i Oslos stand på The Gathering i Hamar har jeg god utsikt utover et lyshav a LCD-skjermer og strålende datamaskiner. I en rus av energidrikk, manglende søvn, pulserende musikk og varm frossen-pizza har 5500 personer boltret seg fast i Vikingskipet på Hamar. Etter et par runder rundt i lokalet har jeg observert at spill er den mest populære aktiviteten og på en skjerm i ene enden av lokalet vises spillturneringer på storskjerm. UiO ved Institutt for Informatikk er i år en av hovedsponsorene for arrangementet og er derfor sterkt representert i hva som må være norges mest høyteknologiske lokale denne påskeferien. I løpet av datafestivalen, eller LANet om du vil, har UiO etablert Campus TG, et konsept der deltagerne får være med på mange faglige foredrag hvor de har mulighet til å lære om alt fra papirfly, forskjellige Linux-distribusjoner til spillprogrammering og sampling med Arduino. I tillegg er det arrangert workshops i lodding og demonstrasjoner av forskjellige roboter.

    Mens musikken fra hovedscenen er fylt med sampling fra jingler kjent fra 8-bit Nintendo og enkelte deltagere løper rundt ikled kostymer som forestiller creepers fra Minecraft eller Pikachu fra Pokemon løses rubiks kuber og kruttsterk kaffe drikkes. I tillegg er det laget et webside hvor deltagerne kan skru av og på en lampe på UiO-standen ved hjelp av et web-interface eller delta i en krevende hacking-oppgave som involverer mange skills fra charset, cæsars-kode til nivåer jeg ennå ikke har kommet til 😛

    Fra et musikkperspektiv er det morsomt å observere en tilnærmet tredeling av hvordan deltagerne hører på musikk. Fra hovedscene drønner bassen fra egenkombinerte sanger fra kreative konkurranser og fra kjente DJer (fra nesten bare elektroniske sjangere), i gruppene spilles det gamle klassikere for hverandre (om ikke GAMLE, så iallefall sommerhits fra et par år tilbake) og individuelt brukes det headset hvor flere blander alle lydene som måtte komme fra aktivitene de driver med, enten om det er spill, filmer, YouTube, programmering eller gamle episoder av Derrick. Jeg tror nok i de fleste tilfellene at musikken mer opptrer i bakgrunnen enn aktiv lytting, men med en så stor og mangfoldig gruppe er det vanskelig å si noe sikkert. Uansett, det er veldig spennende og interessant å være på denne arenaen som nå etterhvert begynner å få den oppmerksomheten den fortjener (for å si det sånn, jeg tror flere ungdommer er interessert i internett, gaming og data enn skirenn i Holmenkollen og skøyteløp i, ja, Vikingskipet). Artikler fra Vikingskipet finnes i de fleste riksmedier og fornyingsminister Åsland var med på åpningen (som du kan lese mer om på Morten Dæhlen sin blogg).

    Her er utklipp fra en liten video jeg filmet i nærheten av UiO-standen.

    [youtube]http://www.youtube.com/watch?v=5AUYHUxYa4U[/youtube]

  • Mining the Social Web

    Social network sites and interpersonal web communication is big business and plays an ever increasing part of peoples lives. From being mainly a tools for communication has now other life-world domains been conquered by the digital forum for exchange of virtual and real-life information. Both the explicit, and more recently, implicit data footprint produced by acts in the virtual and real world is aggregated, analysed and shared. A member of Facebook sending a wall-post to a friend, a Twitter user retweeting a post by someone he or she follows. These are apparent, but what about the meta-data. Who is connected to whom? From where is a message sent and what does it contain?

    To look closer on the social web I have recently bought the book with the self explanatory title Mining the Social Web, I have also established a GitHub repository in which I will try to publish some of my scripts. Please have a look, clone and come with feedback.

     

     

  • Behind the Scenes: A CSS3 page in the making

    In today’s post we’ll be creating a little page with some graphics. The purpose of this little session is to create a web site which takes advantage of some of the new features in HTML5 and CSS3. Lots have happened to web technology the last years, and my little toe tells me more is in the making. Let us make a little page and style it with some of the cool new stuff as well as adding some elements to make it more human friendly. This text is written with an emphasis on users who know some web-design, but who are not experts. Regardless of your skill competency I am interested to hear what you think of the demonstration, and also how your practices are different from mine. I think peer-review provides an excellent foundation for learning and improvement, so please, criticise my approach (constructively).

    To do this little project we’ll need a text editor and a browser to preview the result while we are working. Since we’re not going to apply some server magic in this project we won’t need to install a server, but we need somewhere to write our stuff and somewhere to display it. To display the project we need a web browser. I guess you already have one (and if you are the average Joe visiting my page you are using Chrome on Windows), but you need to make sure it’s up to date. For a long time i preferred Firefox, but lately I have spent more time working with browser using the webkit-based browsers Google Chrome and Apple Safari. I will exclusively be using Chrome while working on this project so I recommend you to use the same. I will, however, also include the moz prefix support where CSS3 support is limited to vendor specific implementation.

    Text editors are available in all shapes and colours. What you don’t need is a word processor, you will need a program that writes plain text to a file. If you are working on the Mac I will recommend TextMate or the free version TextWrangler. Lately, I have tried out an Integrated Development Enviroment built on Eclipse named Aptana Studio. This was also very good and comes with more advance features, but is not as lightweight. If you are working on Windows I recommend Notepad+.

    The Final Result

    We need some idea of how our web-page should look like. Before we start to prototype we need to establish some really fundamental concepts of what we’ll need. If we look at the new HTML5 syntax as an indicator of popular practices we can see that HTML5 includes some new elements named header, footer, nav and article. Let us use them to structure a basic HTML document. A rather conventional structure which makes the design coherent at larger screen sizes is to wrap the content of a page within an element, and to do this we can use the div element. Newer practices takes advantage of screen real-estate through media queries, but for this little project we are not going to do so, instead we make a wrapper with the width of 1000 pixels. This is going to render as a “page inside the browser window” on most modern computers. We wil also be placing two columns for the main content area one with the content and another with a local menu. A global menu we place in the header element. For the footer we are also creating two columns: one with some information about the page and one with links. To get a better idea you can take a sneak peak at the final result here: projects 206.

    To create the documents we need I like to first go into the root folder of my web projects using the terminal and create a new folder with mkdir, then I go into the folder and create the following files index.html, style.css and script.js with the touch command. If it’s a bigger project I would use a more advance structure, but for our little mockup this would be more than enough.

    We can leave the style.css and script.js files empty for now and type or copy the following into the index.html:

    [sourcecode language=”html”]
    <!DOCTYPE html>
    <html>
    <head>
    <title>Webpage</title>
    <link type="text/css" rel="stylesheet" href="style.css" />
    <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
    <div id="wrapper">
    <header>
    <h1 id="main_title">Christmas</h1>
    <nav id="top_menu">
    <ul>
    <li><a href="#">Literature</a></li>
    <li><a href="#">Tradition</a></li>
    <li><a href="#">Recipes</a></li>
    <li><a href="#">Songs</a></li>
    </ul>
    </nav>
    </header>
    <div id="main">
    <nav id="left_menu">
    <ul>
    <li><a href="#">A Christmas Carol</a></li>
    <li><a href="#">Three nuts to Cinderella</a></li>
    <li><a href="#">A Christmas Story</a></li>
    <li><a href="#">Nightmare before Christmas</a></li>
    </ul>
    </nav>
    <article>
    <h2>A christmas story</h2>
    <p>Some text</p>
    </article>
    </div><!– End of main –>
    <footer>
    <div id="footer_about">
    <p>This is some footer text</p>
    </div><!– End of footer_about –>
    <div id="footer_links">
    <ul>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    <li><a href="#">Link</a></li>
    </ul>
    </div><!– End of footer_links –>
    <p id="footer_bottom">Legal information and a link to my <a href="http://www.lovholm.net">blog</a></p>
    </footer>
    </div> <!– End of wrapper –>
    </body>
    </html>

    [/sourcecode]

    The HTML markup above differs a bit from the HTML in the final version, but only in the sense that the “about” text in the footer and the main text is changed with shorter versions. The rest of the markup is the same. As you can see this is pretty conventional stuff. The header element contains links to the css and javascript file we created earlier so we can take advantage of these and at the same time keep them separate from the content. The body-elements consists of one child element, the wrapper, which further is divided into three elements: header, main and footer. The first and the last of these take advantage of the HTML5 semantic markup for their function within a page, the main element is a div-tag with an ID of “main”. All the main sections contain a link list and these are located within unordered lists. For convenience I use HTML-comments after closing a div-tags to make nesting easier. If you copy this HTML or the HTML of the final version into a document and open this in the browser the result will however be without styling. To keep content and presentation separated is a good practice: it makes it easier to update each of them in the future, re-use them or provide separate versions to accomodate different user scenarios. In another post we are going to make our little page dynamic, and then this rule of thumb will prove useful.

    The text used in the finished version is an excerpt from the beginning of Charles Dickens famous book A Christmas Carol. I copied it from the Gutenberg Project, a service that provides loads of books where the copyright is no longer valid. Please support this project, it is a really good resource for gaining example texts not to mention the gigantic cultural value it makes available for free.

    The Style

    Here is the CCS modifying the HTML above. The css is the content of the style.css file:

    [sourcecode language=”css”]

    body {
    background: url(‘bg_thick_red.png’);
    background-repeat: repeat-both;
    }

    #wrapper {
    margin: 20px auto 20px;
    width:1000px;
    background-color: #FFF;
    background-color: rgba(255,255,255,.92);
    box-shadow:2px 2px 15px #000;
    border-radius:4px;
    }

    header {
    padding:5px;

    background-image: linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -o-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -moz-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -webkit-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -ms-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0.04, rgba(244,250,240,.3)),
    color-stop(0.52, rgba(102,168,204,.3)),
    color-stop(0.76, rgba(92,131,209,.3))
    );
    }

    header h1{
    text-align:center;
    color: #888;
    text-shadow: 0 1px 0 #FFF;
    font-size:3em;
    text-transform:uppercase;
    font-family: helvetica, sans-serif;
    }

    header nav {
    text-align:center;
    }

    header nav ul {
    list-style: none;
    }

    header nav ul li {
    display:inline;
    }

    header nav ul li a{
    background-color: green ;
    text-align:center;
    padding:5px 20px 5px;
    margin:0 2px 0;
    text-decoration:none;
    color:white;
    font-size:1.5em;
    border-radius: 4px;
    }

    #main {
    margin: 0;
    padding: 0;

    }

    #main nav {
    float:left;
    width:215px;
    margin: 20px 5px 0 20px;
    background-color: #FFF;
    background-color: rgba(255,255,255,0.2);
    border-radius:4px;

    }

    #main nav ul {
    list-style:none;
    margin: 0;
    padding: 0;
    }
    #main nav ul li a{
    display: inline-block;
    font-size: 1.2em;
    background-color: #DDD;
    border-radius:4px;
    margin: 5px 0 10px 0;
    padding: 5px;
    width:100%;
    text-decoration:none;
    color: green;

    }
    #main article {
    background-color:#FFF;
    border-radius:4px;
    float:right;
    width:680px;
    padding:10px;
    margin:15px;
    }

    footer {
    clear: both;
    background-color: #D4C4AD;
    padding:10px;
    border-top: 3px solid #000;
    font-size:0.9em;
    }

    #footer_about {
    width:450px;
    float:left;

    }

    #footer_links {
    width:450px;
    float:right;
    }

    #footer_links ul {
    list-style:none;
    margin: 0;
    padding: 0;
    background-image: url(‘post_service.png’);
    background-repeat:no-repeat;
    background-position:right top;
    height:130px;
    padding-top:15px;
    }

    #footer_bottom {
    border-top: 1px solid #333;
    padding-top:4px;
    clear:both;
    text-align:center;
    font-family:monospace;
    }

    nav ul li a:hover{
    padding-top:10px;
    padding-bottom:10px;
    box-shadow: 0 0 30px #FEE100;
    }

    nav ul li a {
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    -ms-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    }

    [/sourcecode]

    This is where the magic happens. It’s amazing how much some lines of CSS can change how the HTML is styled within the browser. As you may see, I have tried to keep the CSS in somewhat same structure as HTML in the sense of the place in the document. I’ve added some global rules at the bottom that applies to all links within a nav-element list. If you been working with CSS before you probably recognise the techniques chosen. I will now comment on some of the choices I made while authoring this stylesheet.

    For this project I thought it could be cool with some stripes in the background, this really emphasises the transparency in the alpha layering supported by the new rgba and hsla tags. To get stripes as a background I chose to repeat the basic structure of the background using the background-repeat property. I crated the image used at Stripegenerator. For colours I prefer to use Adobe Kuler.

    The new CSS3 features I have used includes: gradients, border-radius, transition, shadows and the new colour tags. CSS3 is not yet a fully implemented standard and many of the functions are only available through vendor prefixes (such as -moz- or -webkit-) but why wait for the future? Most of the CSS3 modules are working and not likely to go through major changes, other things are still in blueprints. The stuff I’m been using here seems to be widely adapted and let alone the gradients are all using simliar syntax across browsers. An important argument for adapting and using new standards you are also playing an active role in defining how these can be used and their popularity, so you can in fact be a part of defining your own future.

    Gradients

    The gradients as you can see are here located within the background image. The syntax diverge between webkit-browsers (e.g Safari and Chrome) and non-webkit-browsers. The most commonly used syntax includes the type of gradient in the title, while webkit takes it as an argument. Webkit does also needs clearly defined start and stop position while other syntax just need the defined start location. In the code here I have used the rgba elements (which we will return to later) and colour stops. When these are defined will they work as absolute stops which the browser interpolates between. The percentage defines where the stops will be. I am only applying gradients to the header, but if I chose a higher element the gradients would be equally distributed. For this example I have also changed the version without a vendor-prefix to the bottom, this may be a good idea as the browsers will drop prefixes as the function becomes a standard, the browsers adapts the rule last defined and will skip the rules without the prefixes for the specific browser. The syntax can be a little hard to type with many parentesis and commas so to save time and worries I can recommend you to use a CSS3 gradient generator.

    [sourcecode language=”css”]

    background-image: -o-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);

    background-image: -moz-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);

    background-image: -webkit-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -ms-linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);
    background-image: -webkit-gradient(
    linear,
    left bottom,
    left top,
    color-stop(0.04, rgba(244,250,240,.3)),
    color-stop(0.52, rgba(102,168,204,.3)),
    color-stop(0.76, rgba(92,131,209,.3))
    );

    background-image: linear-gradient(bottom, rgba(244,250,240,.3) 4%, rgba(102,168,204,.8) 52%, rgba(92,131,209,.8) 76%);

    [/sourcecode]

    The vendor prefixes are o for Opera, moz for mozilla which Firefox is the most known in the family, webkit is used by webkit browsers which have gained popularity trough Chrome and Safari. The built-in browser on iOS and Android devices are also built on the webkit engine. Ms is short for Microsoft and is the vendor prefix for the widely used Internet Explorer browser. IE is supposedly getting better in newer versions so let hope that users upgrade.

    New Colour Tags

    Traditionally colours have been expressed with three or six hexadecimal numbers or name constants. Opacity has been available since CSS2 through the opacity function, but it is all brought together in the rgb, hsl, rgba and hsla tags. The two first takes three values and the two latter four. The RGB colours (Red, Green, Blue) constitutes the additive colour model, while the HSL (Hue, Saturation, Lightness ) makes up the colour wheel variables. To use of the models call either of the rules with the appropriate number of argument such as:

    [sourcecode language=”css”]

    background-color: #FFF;
    background-color: rgba(255,255,255,.92);

    [/sourcecode]

    In the excerpt above the first background-color tag is sent the three hexadecimals as a concatenation of the six hexadecimal version #FFFFFF. This can also be expressed as rbg(255, 255, 255) and if you’re into maths you may see why. The first two ‘F’s correspond to 255 and the same goes for the subsequent. The range between  0 and 255 corresponds to what can be distinguished in a byte. The HSL version has another range. Since it is based on the colour wheel the first argument corresponds to the degree or the circular point on the wheel; the accepted range leads from this and is somewhere between 0 and 360. The second and third arguments are stated in percentage (and the syntax is a number between 0 and 100 followed by the percentage sign). If you choose to add some transparency you add an a to hsl or rgb so it becomes hsla and rgba. In addition you will need to add a fourth argument which takes a number between 0 and 1 where 0 is totally transparent.

    Border-radius

    Boxes in the web browsers may seem a bit hard from time to time, so to make them more visually friendly you can round the angles using the border-radius rule. This is easy to use either if you want to create a subtle visual effect or going wild with round boxes. I like to add this feature to buttons in order to make them more click friendly but I also think it looks good on boxes. In the little code above I have used a 4 pixel border radius on buttons and also on the wrapper.

    [sourcecode language=”css”]

    border-radius: 4px;

    [/sourcecode]

    Shadows

    You have probably noticed the heavily use of shadows in various graphical user interface the last years. Shadows make a subtle three dimensional feel on the screen, adding depth and give visual cues of what information should stand out. There are two shadows I have applied to this little page: box and text shadows. In the header h1 element I add a text shadow to make the text a bit more crispy:

    [sourcecode language=”css”]

    text-shadow: 0 1px 0 #FFF;

    [/sourcecode]

    In this example I keep the x-axis of the light source straight on the text, but I move the y-axis one pixel down. I do not want to blur the shadow, and I set its colour to  white.

    I use the box shadow function in more sections. Perhaps the most apparent shadow is the one applied to the wrapper, but also on the link elements are shadows used for an effect. When the user  hover an anchor tag in the nav section is a subtle box shadow applied. Here are the two examples in the CSS markup:

    [sourcecode language=”css”]

    box-shadow:2px 2px 15px #000;

    box-shadow: 0 0 30px #FEE100;

    [/sourcecode]

    The first line is the box-shadow from the wrapper element, and the second is from the light effect I try to emulate applied to the buttons when the user is hovering them. The idea is for the light to look like the radiation around a light source hidden by the button. These two implementations of the same function are just a little example on all the effects which can be accomplished using the new shadow functions.

    Animation

    The last piece of code I want to comment upon is the animation. This is a new element providing visual effects without having to apply Javascript.

    [sourcecode language=”css”]

    nav ul li a {
    -webkit-transition: all 0.2s ease-in-out;
    -moz-transition: all 0.2s ease-in-out;
    -o-transition: all 0.2s ease-in-out;
    -ms-transition: all 0.2s ease-in-out;
    transition: all 0.2s ease-in-out;
    }
    [/sourcecode]

    For all the a tags used in a unordered list within a nav section (pretty much all navigational links) I apply a transition element. This is used to interpolate an animation when the visual state of the element is changed. The code excerpt above is quite long due to the vendor-prefixes, but one line will, in the future, be enough. The syntax as you can see is three arguments: the first is a selector for what should be included in this rule. I choose to include all. In a case where you a using CSS transformations  you can here choose which of the transformations it should apply to, which is great in case you plan to make something advance. The second and third argument is the timing and interpolation approach. I choose a rather short time 0.2 seconds from the animation starts until it is finished, I also choose an ease-in-out interpolation. A short demonstration of the various interpolation approaches can be found here.

    I hope this post has been useful and perhaps provided you with some new knowledge or ideas. Please tell if anything is unclear or if you would have chosen another approach. At a later point I hope to take this page, or a similar one, and apply some Javascript magic and a little back-end providing some text or data. Well, until next time.

  • Graduation

    The 23rd of November mom, Jules and I went to Scotland to attend my graduation at the University of Edinburgh. In McEwan Hall I meet with most of my old study colleagues and we were in turn hit by the hat which graduates us and bestow our academic titles upon us. This could have been a nice introduction to John Searle and his speech acts, but I will save that for later.

    Anyhow, this marks the end of my second round of formal education, and the start of a new era in which I hope to bring with me the ideals and inspiration I’ve accumulated through five years at universities in Oslo, Stuttgart and Edinburgh. It’s been five interesting years, and I meet a good deal of great people which I hope I will be lucky enough to work with at a later occasion.

    I try to keep my blog semi-professional and I try to write more about various topics than about myself. However, as I use this little place as a way of keeping track of what I think, care about and do from year to year I think I should mention my newest little achievement. On the continuous line of life, which is dived into past and future by the razor-thin present I think it’s important to think back and hopefully this can be a little personal milestone for future me.

    I do hope that I can put my studies to use, and that I can still learn and develop my skills and thoughts. Learning is not just formal degrees, nor a profession, or an intrest, it is a life-long process which enrich me, and hopefully you as well. There are still big questions to be explored, questions to be answered and arguments to be presented. I look forward to the next challenge

     

  • Visuell programmering i Processing

    I dag holdt jeg en liten innledning og workshop om visuell programmering hos Norsk Telemuseum på Kjelsås. Jeg ønsket å vise fram programmeringsmiljøet rundt Processing og var også innom forskjellige emner jeg mener er viktig i dagens IT-landskap. I hovedsak orienterte dette seg om data og interfaces, eller data og dingser som jeg kalte det. En artikkel på det kontekstuelle kommer snart, men inntil videre kan du forsøke deg på oppgavesettet jeg lagde til den praktiske gjennomføringen av kurset. Jeg tror denne praktiske delen godt også kan fungere som en del 1 i serien “lær programmering med processing”.

     

    Et enkelt program:
    Syntaks introdusert: Kommentarer, print(), println(), size().

    + Start opp processing
    + Skriv en åpningskommentar på toppen av programmet ved å sette inn //. Alt som følger etter disse tegnene fram til linjeskift vil ikke bli prosessert. Dersom du ønsker flere linjer med kommentarer kan du bruke /* i begynnelsen av kommentarblokken og avslutte med */
    + Klikk på play-knappen for å åpne sketsjen. Hva dukket opp. Klikk på x-symbolet i vinduet som åpnet.

    +Skriv kommandoen size(x,y) i programmet. Denne kommandoen tar to parametere. X angir bredden og y angir høyden i pixler. Erstatt x og y med nummere. Forsøk forskjellige tall og se resultatet ved å klikke på play etter å ha endret et av tallene. Normalt sett skal variblene være mellom 1 og 1200, avhengig av oppløsningen støttet av datamaskinen. Du må avslutte en kommando med et semikolon.

    + Skriv ut en tekst til terminalen ved å bruke kommandoen print() og println(). Dette kan være en tekststreng, et nummer eller tegn. Tegn og tekststrenger må termineres, dette gjøres ved å sette et hermetegn i hver ende.

    Resultat:

    //Dette er en kommentar
    /* Vi kan også kommentere
    over flere linjer med kode */
    
    size(200,300);
    print(“Dette er en commando fra programmet”);
    println(“Hello World!”);
    print(“Dette skal komme på en ny linje”);

    Variabler
    Syntaks introdusert: int, float, String, char, boolean, +, -, /, *
    + Nå har du laget ditt eget lille program. Forsøk nå å bytt ut nummerene fra size med variabler. Variablene skriver du ved å først initialisere dem med datatype og navn for deretter å sette en verdi til dem. Variabler er plassholdere for verdier.

    int x = 200;

     int y = 500; 

    + Opprette et par nye int-variabler. Velg navn selv, men følg
    navnekonvensjonene som bestemmer at en variabel skal begynne med liten bokstav og ikke ha mellomrom. Sett disse til forskjellige tall og forsøk og opprett nye variabler ved å utføre matematiske funksjoner på eksistrerende variabler inn i nye.

    + Opprett en variabel for en tekststreng og skriv en velkomstmelding til denne (Bruk type String i stedet for int). Deklarer variablene på toppen av dokumentet og referer til det nedover. Bruk regneartene til å legge verdier inn i nye variabler. Eksempel:

    int i = 10;

    String k = “Dette er en tekststreng”; 

    int j = 5;

    int k = i* j;

    println(k);

    Vi har hittil benyttes oss int og String (String skrives med stor forbokstav, mens alle andre datatyper vi bruker her skrives med små bokstaver). int er kort for integer (heltall), og String er en tekststreng, som også kan være tall som ikke kan regnes på. I tillegg bruker vi float som er flyttall (eks 1.2), char som er enkelttegn og boolean som true eller false. Forsøk å utfør følgende kode, og gjett hva du får:

    int a = 3;

    int b = 2; 

    int c = a / b; 

    println(c);

    + Forsøk å endre a eller b og c til float. Hvilket svar får du nå.
    + Opprett en variabel boolean og sett denne til false eller true. Hva skjer? Skriv denne ut.

    Resultat:

    // Variabler for size-kommandoen

    int x = 200;

    int y = 500;

    // Tekst

    String tekst = “Dette er en hilsen”

    boolean test = false;

    println(test);

    //Variabler for å teste verdier

    int i = 10;

    int j = 5

    int k = i* j;

    println(k);

    //Variabler for å teste heltall og flyttallsdivisjon

    int a = 3;

    float b = 2;

    float c = a / b;

    println(c);

    //Dette er en kommentar

    /* Vi kan også kommentere over

    flere linjer med kode */

    size(x,y);

    print(“Dette er en commando fra programmet”);

    println(tekst);

    print(“Dette skal komme på en ny linje”);

     

    Punkter, linjer og firkanter i Processing
    Syntaks introdusert: point(), line(), rect().

    Nå som du har kjennskap til variabler og funksjonskall i programmering kan vi begynne å more oss med funksjonaliteten i Proessing. Funksjonene point(), line(), og rect() tegner det de heter. Point tar to verdier, x og y som blir punktets koordinater på lerretet. Line tar fire argumenter, de to første er x og y for utgangspunktet og de to siste er x og y for sluttpunktet. Rect tar også fire argumenter: x, y, bredde og høyde.

    size(500,500);

    rect(10,10,50,50);

    rect(20,60,200,100);

    rect(200,400,70,70);

    line(0,0,500,500);

    line(0,500,500,0);

    I denne introduksjonen tar vi bare for oss en 2D kontekst. I denne konteksten refererer vi til posisjoner som i et kartesiansk rom. Utgangspunktet for koordinatene er øvre venstre hjørne. Derfor vil høyere tall på x aksen bevege objektet mot høyre, og høyere tall på y aksen nedover. Dette kan du selv forsøke ved å endre på nummerene i koden ovenfor. Fra dette eksempelet kan du også se hvordan objektene blir tegnet til lerretet. Dersom et objekt er tegnet og et nytt objekt seinere skal være i samme område blir det siste tegnet over det første.

    For å skape en kode det er lettere å endre (selv om Processing programmer aldri burde bli så lange at all oversikt blir borte) kan du bruke height og width, som er konstanter satt av programmet. Disse er også reserverte ord i programmet. La oss teste dette ved å endre på koden for de to siste linjene i eksempelet over.

    line(0,0,width,height);

    line(0,height,width,0);

    Å tegne punkter er ganske kjedelig på dette tidspunktet, men frykt ikke, om litt kommer du til å kunne tegne punkter på en annen måte, noe som gjør det mye morsommere.

     

    Variabler og if/else
    Syntaks introdusert: if, else, blokker.
    + Nå begynner det å bli en del kode, så nå kan du enten opprette en ny fil eller fjerne all teksten ved å markere koden du allerede har og fjerne denne på samme måte som i en tekstbehandler.
    +Opprett en if-blokk. Den ser omtrent ut som dette:

    if(logisk spørring) {

    // Gjør noe dersom logisk spørring er tilfelle

    } else {

    // Gjør noe annet dersom det ikke er tilfelle

    }

    En logisk spørring resulterer i en boolean verdi som kan være enten true eller false. For enkelhetsskyld opprett en boolean variabel og sett denne til true. Referer til denne i if(variabel). Disse logiske spørringene etterfølges av en blokk. Tenk på denne blokken som en inndeling av kode som gjennomføres. Du kan gjøre så mye du ønsker i blokken, og denne kan bestå av en kommando eller hundre, men husk å start og slutt blokken med krøllparanteser.

    boolean test = false;

    if(test) { 

    print(“Denne kommer ikke til skrives ut ”); 

    println(“Kan du finne ut hvorfor?”);

    Det hele blir mer interessant når du kan teste på verdier i de logiske spørringene. Typiske spørringer for tall er ==,eller en kombinasjon av disse.
     int i = 50; 
     if(i == 20 ){  
     println(“Hvordan kan du få skrevet ut dette?”); 
     } 

    Her kan du se at = og == er to forskjellige. Den første setter er verdi til en variabel og den andre tester om to verdier er de samme.

    + Forsøk nå å lage en egen if-else forgrening der du skriver ut noe dersom en verdi er sann og noe annet dersom dette ikke er tilfelle.

     

    Løkker
    Syntaks introdusert: for, while.

    Løkker er et nyttig redskap for å gjøre en handling mange ganger. De består gjerne av en logisk spørring, en blokk og en endring. Den enkleste løkka er while(), som til norsk kan oversettes til mens. Så for å oversette den syntaktiske meningen kan du si at en while løkke går mens spørringen er sann.

    //setter variabelen i 
    int i = 0; 
    //mens i er mindre enn tusen 
    while(i < 1000){ 
    //Denne har du ikke sett ennå, men her skriver vi ut 
    //verdien av i 
    println(i++); 
    // i++ er kortform for i = i+1 
    } 

    + Hvis du vil være litt vågal kan du nå forsøke å endre i++ til i. Gjett hva som skjer først og deretter test det. Litt av moroa med å programmere er at uansett hvor mange feil du gjør skjer det ikke noe veldig alvorlig.

    Den andre formen for løkker er for()-løkker. Disse er litt mer avanserte enn while, og ser typisk slik ut:

    for(int i = 0; i < 100; i++ ){ }

    Hvis du tenker på hva slags funksjoner som en løkke typisk inneholder, er alle disse implementert i en for-løkke. Vi kan forstå en for-løkke som for(startvariabel; utgangskriterie; inkrement) { blokk }. Når en variabel blir opprettet innenfor en blokk er den usynlig utenfor. Deklarer derfor variabler du ønsker å aksessere igjennom hele programmet utenfor en løkke, eller funksjon. I eksempelet ovenfor ser du at i blir deklarert i den logiske spørringen.
    + Forsøk å skriv ut verdien av i nedenfor den siste krøllparantesen. Hva skjer? Hva skjer dersom du deklarerer i ovenfor for-løkka?

    + Tegn et stort antall geometriske gjenstander i Processing ved hjelp av løkker. Forsøk å endre noen av parameterene ved å trekke inn iteratoren i løkka i tegnefunksjonene.

     

    Funksjoner
    Syntaks introdusert: funksjoner, void

    Å kunne skrive kode er vel og bra, men når koden blir lengre oppstår det et behov for å abstrahere vekk alle detaljer. Hvis du bruker, som vi har gjort tidligere i heftet, bokstaver som variabelnavn kommer du ganske raskt til å gå tom, dessuten kan det være vanskelig å huske mange navn. En annen fordel ved å lage metoder er at disse kan kalles fra hvilket som helst sted i programmet. Dette gjør det enkelt å hoppe fram og tilbake i koden.

    Metoder deklareres med
    returtype navn(argument1, argument2, argumentN){
    //Her skriver du innmaten
    }

    Returtyper kan være alle datatyper, eller ingenting. Dersom du bruker en datatype må du bruke utrykket return samt en verdi eller variabel som inneholder data av typen oppgitt.
    Denne funksjonen tar to argumenter av typen heltall og returnerer et heltall med summen av disse to tallene.

    int plusser(int tall1, int tall2){ return tall1 + tall2; }

    Denne funksjonen returnerer en sannhetsverdi av et heltall om hvorvidt dette tallet er et partall. Denne funksjonen introduserer et nytt tegn % – modulo – Dette utrykket returnerer rest ved divisjon. Premisset er at et partall som deles på to ikke skal returnere en rest. If grenen tester om dette er sant og returnerer true hvis dette er tilfelle.

    boolean isPartall(int tall){

    if(tall %2 == 0){

    return true;

    } else {

    return false;

    }

     

    setup() og draw()
    Syntaks introdusert: setup(), draw(), noLoop().

    Processing har to funksjoner du som programmerer skriver. Disse heter setup() og draw(). Selv om du kan lage et program uten disse, kan det være en fordel å stykke programmets funksjonalitetet, som ikke allerede har sin egen funksjon, inn i disse blokkene. I setup() skriver du kode som eksekveres en gang i begynnelsen av programmet. Her kan du plassere size() metoden samt andre definisjoner og kall som ikke trengs å være en del av draw()-loopen.

    I draw() skriver du all funksjonalitetet som kjøres for å tegne. Skal du lage geometriske figurerer er det lurt å gjøre dette her. Denne funksjonen kjører helt til du kaller noLoop(). Du kan også kalle noLoop() i setup() for å la programmet kjøre kun en gang.

    Verken setup() eller draw() returnerer en verdi og tar derfor returneringstypen void.

    Et godt utgangspunkt kan se slik ut:

    void setup {

    size(200,200);

    noLoop();

    }

     

    void draw() {

    point(width/2, height/2);

    }

    Dette lille programmet setter en prikk midt på skjermen.

     

    Farger
    Syntaks introdusert: color(), background(), fill(), stroke(), noFill(), noStroke()

    Farger kan få prosjektet til å se mye flottere ut, og kan også være en effektiv måte å gruppere forskjellig informasjon. Processing støtter forskjellige typer farger, men her bruker vi RGB-baserte farger hvor hver av verdiene settes til et tall mellom 0 og 255.

    color() brukes for å sette en farge til en variabel av typen color. F.eks
    color c1 = color(0,0,255);
    Dette gjør det enkelt å referere til farger senere i programmet og slik gjøre det enkelt å holde en fargeplan. Du kan bruke fargevariabler eller fargeverdier igjennom programmet
    background() tar en farge og setter denne til bakgrunnen. For å lage en applikasjon der ting skrevet til lerretet ikke blir der i neste runde av draw() må du kalle background() i draw. Det kan være lurt å la background være det første som blir kalt i draw().

    Objektene du tegner på skjermen i Processing er litt som ting i Photoshop og andre steder, de har en linje som følger formen og innmat. Du kan sette hvilken farge disse har ved å kalle fill() og/eller stroke() før du tegner en form. Fargene du setter med disse metodene vil være der til du setter de på nytt.

    Siden vi allererede har vært igjennom blokker og løkker la oss tegne noen farger. Denne lille kodesnutten kommer til å tegne rødt, grønt og blått i steg fra svart (0) til full farge (255)

    /* Skriver ut fargene i RGB-fargebånd. Går i steg på 2px per verdi fra 0 til 255, 

    skriver ut hver farge i 50 pixler brede remser. */ 

     

    void setup() { 

    size(3*50, 3*255); 

    // Setter størrelsen til antall bånd 

    //* 3 og antall steg *3. 

    noStroke(); 

    //Bruker ikke rand-farging 

    background(255); 

    //I utgangspunktet hvit farge 

    noLoop(); 

    // Programmet eksekverer og stopper. Draw kun kalt en gang. 

    
    
     // Tegner rødt
     void draw() { 
     for(int r = 0; r < 255; r++){
     fill(r,0,0); 
     rect(0,r*3,50,3); 
    
    
     // Tegner grønt 
     for(int g = 0; g < 255; g++){
     fill(0,g,0); 
     rect(50,g*3,50,3); 
    
    
    // Tegner blått 
    for(int b = 0; b < 255; b++){
     fill(0,0,b); 
     rect(100,b*3,50,3); 
    } 

     

    Mus

    La oss returnere til punktene. Disse ønsket vi å ikke tegne selv siden de er veldig små, og du først ser morsomme resultater når du har mange av dem.

    + Skriv en setup() funksjon som setter størrelsen til 500×500 pixler. Husk å ikke ta med kallet til noLoop(). Ta deretter å skriv en draw() funksjon som plasserer en prikk midt på skjermen. Bytt nå ut prikkens x-koordinat med mouseX og prikkens y-koordinat med mouseY. Beveg musepekeren rundt på skjermen.

    + Forsøk å skrive bakground(155) i begynnelsen av draw() funksjonen. Hva skjer? Ta den vekk. Hva skjer nå?

     

    Arrays og online ressurser

    Et annet viktig element innen programmering er arrays. Denne kan være av alle datatyper og er en organisert samling av data. Gå inn på processing.org og se etter array i dokumentasjonen.

    + Forsøk å opprett en array med 10 forskjellige tekststrenger. Skriv deretter ut verdien av hver av disse ved hjelp av en for-løkke og println. NB: Dette er vanskelig. Se om du finner ut hvordan du kan gjøre dette ved hjelp av google, eller kontakt meg.

     

    Jeg håper å komme tilbake med mer Processing-kode snart, men i mellomtiden anbefaler jeg tutorialene som ligger ute på Processing.org. Temaer jeg ønsker å dekke neste gang inkluderer å lese til og fra fil, XML og objektorientering.

     

    Bildet er tatt fra Flickr brukeren blprnt. Det er lisensiert under en Creative Commons lisens.