<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>dennogumi.org &#187; python</title>
	<atom:link href="http://www.dennogumi.org/tag/python/feed" rel="self" type="application/rss+xml" />
	<link>http://www.dennogumi.org</link>
	<description>On the web since 1999</description>
	<lastBuildDate>Fri, 06 Jan 2012 14:56:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>PyKDE4: Queries with Nepomuk</title>
		<link>http://www.dennogumi.org/2011/06/pykde4-queries-with-nepomuk</link>
		<comments>http://www.dennogumi.org/2011/06/pykde4-queries-with-nepomuk#comments</comments>
		<pubDate>Wed, 29 Jun 2011 19:27:42 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[pykde]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=924</guid>
		<description><![CDATA[In one of my previous blog posts I dealt with tagging files and resources with Nepomuk. But Nepomuk is not only about storing metadata, it is also about retrieving&#160;and interrogating data. Normally, this would mean querying the metadata database directly, &#8230; <a href="http://www.dennogumi.org/2011/06/pykde4-queries-with-nepomuk">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In one of my previous blog posts I dealt with <a href="http://www.dennogumi.org/2010/10/pykde4-tag-and-annotate-files-using-nepomuk">tagging files and resources with Nepomuk</a>. But Nepomuk is not only about storing metadata, it is also about <i>retrieving</i>&nbsp;and <i>interrogating </i>data. Normally, this would mean querying the metadata database directly, using queries written in SPARQL. But this is not intuitive, can be inefficient (if you do things the wrong way) and error prone (oops, I messed up a parameter!).&nbsp;
<p>Fortunately, the Nepomuk developers have come up with a high level API to query already stored metadata, and today&#8217;s post will deal with querying tags in Nepomuk. As per the past tutorials, the full source code is available <a href="https://projects.kde.org/projects/kde/kdeexamples/repository/revisions/master/changes/bindings/python/nepomuk/nepomuk_tag_query_example.py">in the kdeexamples module</a>.</p>
<p>Let&#8217;s start off with the basic imports:</p>
<pre class="brush: python; title: ; notranslate">
import sys

import PyQt4.QtCore as QtCore

import PyKDE4.kdecore as kdecore
import PyKDE4.kdeui as kdeui
from PyKDE4.kio import KIO
from PyKDE4.nepomuk import Nepomuk
from PyKDE4.soprano import Soprano
</pre>
<p>Then let&#8217;s create a simple class that wil be used for the rest of this exercise:</p>
<pre class="brush: python; title: ; notranslate">
class NepomukTagQueryExample(QtCore.QObject):

    def __init__(self, parent=None):

        super(NepomukTagQueryExample, self).__init__(parent)
</pre>
<p>__init__ is just used to construct the instance, nothing more. The bulk of the work is in the query_tag() function, which we&#8217;ll take a look at in parts.</p>
<pre class="brush: python; title: ; notranslate">
    def query_tag(self, tag):

        &quot;&quot;&quot;Query for a specific tag.&quot;&quot;&quot;

        tag = Nepomuk.Tag(tag)
</pre>
<p>First of all we convert the tag we want to query into a proper Nepomuk.Tag() instance. Of course we should use an already existing tag: even if Nepomuk.Tag() automatically creates new tags, it makes little sense to query for a newly created tag, doesn&#8217;t it?</p>
<p>For our job, we need to use <i>properties</i>&nbsp;which define the terms of our query. As we&#8217;re looking for tags, we&#8217;ll use Soprano.Vocabulary.NAO.hasTag():</p>
<pre class="brush: python; title: ; notranslate">
        soprano_term_uri = Soprano.Vocabulary.NAO.hasTag()
        nepomuk_property = Nepomuk.Types.Property(soprano_term_uri)
</pre>
<p>The first call generates an URI pointing to a specific RDF resource for this specific term, which is then wrapped as a Nepomuk.Types.Property in the second call. While the C++ API docs don&#8217;t show this, I found it to be necessary, or the Python interpreter would raise a TypeError. Notice that this is not the only term we can use: aside for tags, there are a lot of other URIs we can use for querying, <a href="http://api.kde.org/kdesupport-api/kdesupport-apidocs/soprano/html/namespaceSoprano_1_1Vocabulary_1_1NAO.html">listed in the Soprano API docs</a>.</p>
<p>Once we have our property set up, it&#8217;s time to define which kind of query we&#8217;re going to use. In this case, since we want to check for the presence of tags, we use a Nepomuk.Query.ComparisonTerm, which is a query term used to match values of specific properties (in our case, tags):</p>
<pre class="brush: python; title: ; notranslate">
        comparison_term = Nepomuk.Query.ComparisonTerm(nepomuk_property,
                Nepomuk.Query.ResourceTerm(tag))
</pre>
<p>Our tag is wrapped in a ResourceTerm, which is used exactly for the purpose. Now we make the proper query: in this specific case, we want to look up <i>files </i>tagged, so we use a FileQuery. We could also get other items, such as mails (in Akonadi): in that case we could use a a Nepomuk.Query.Query():</p>
<pre class="brush: python; title: ; notranslate">
        query = Nepomuk.Query.FileQuery(comparison_term)
</pre>
<p>Lastly, we want to get some <i>results</i> out of this query. There are different methods, but for this tutorial we&#8217;ll use the tried-and-tested KIO technology:</p>
<pre class="brush: python; title: ; notranslate">
        search_url = query.toSearchUrl()
        search_job = KIO.listDir(kdecore.KUrl(search_url))
        search_job.entries.connect(self.search_slot)
        search_job.result.connect(search_job.entries.disconnect)
</pre>
<p>First we convert the query to a nepomuksearch:// url, which then we pass to KIO.listDir, to list the entries. Unlike <a href="http://www.dennogumi.org/2011/01/pykde4-retrieve-data-using-kio">my previous post on KIO</a>, this job emits entries() every time one is found, so we connect the signal to our search_slot method. We also connect the job&#8217;s result() signal in a way that it will disconnect the job once it&#8217;s over.</p>
<p>Finally, let&#8217;s take a look at the search_slot function:</p>
<pre class="brush: python; title: ; notranslate">
    def search_slot(self, job, data):

        # We may get invalid entries, so skip those
        if not data:
            return

        for item in data:
            print item.stringValue(KIO.UDSEntry.UDS_DISPLAY_NAME)
</pre>
<p>Entries are emitted as <a href="http://api.kde.org/4.x-api/kdelibs-apidocs/kio/html/classKIO_1_1UDSEntry.html">UDSEntries</a>: to get something at least understandable, we turn them into the file name, which is obtained by the stringValue() call using KIO.UDSEntry.UDS_DISPLAY_NAME.</p>
<p>That&#8217;s it. As you can see, it was pretty easy. Of course there&#8217;s more than that. For further reading, take a look at <a href="http://api.kde.org/4.x-api/kdelibs-apidocs/nepomuk/html/namespaceNepomuk_1_1Query.html">Nepomuk&#8217;s Query API docs</a>, and <a href="http://api.kde.org/4.x-api/kdelibs-apidocs/nepomuk/html/examples.html#examples_query">Query Examples</a>. Bear in mind however that to the best of my knowledge, the &#8220;fancy operators&#8221; mentioned there will not work with Python.</p>
<p>Happy Nepomuk querying!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2011/06/pykde4-queries-with-nepomuk/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Multiscale bootstrap clustering with Python and R</title>
		<link>http://www.dennogumi.org/2011/05/multiscale-bootstrap-clustering-with-python-and-r</link>
		<comments>http://www.dennogumi.org/2011/05/multiscale-bootstrap-clustering-with-python-and-r#comments</comments>
		<pubDate>Sun, 29 May 2011 12:11:40 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[Science]]></category>
		<category><![CDATA[clustering]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=906</guid>
		<description><![CDATA[While reading the statistics for my blog, I noticed that a number of searches looked for hierarchical clustering with Python, which I covered quite a while ago. Today I&#8217;d like to present an updated version which uses more robust techniques. &#8230; <a href="http://www.dennogumi.org/2011/05/multiscale-bootstrap-clustering-with-python-and-r">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>While reading the statistics for my blog, I noticed that a number of searches looked for hierarchical clustering with Python, which <a href="http://www.dennogumi.org/2007/11/data-clustering-with-python">I covered quite a while ago</a>. Today I&#8217;d like to present an updated version which uses more robust techniques.</p>
<p><span id="more-906"></span></p>
<h2>Defining the problem</h2>
<p>Since Eisen&#8217;s original paper on clustering, this form of analysis has been widely used by a lot of researchers. However, as it is known, such systems may be susceptible to an ordering bias: in other words, the order of the samples and/or genes might influence the final result. That&#8217;s why popular software such as <a href="http://www.tm4.org/mev/">TMeV</a> offers alternative approaches, based on <i>bootstrapping</i>.&nbsp;</p>
<p>In this specific form of bootstrapping, the samples and/or genes are randomly shuffled a number of times (1000 or more iterations are a good starting point) and the resulting dendrograms checked for consistency and robustness of partitioning. In other words, a p-value is calculated, our null hypothesis being that the arrangement of samples/genes is merely due by chance. Depending on the software, this value might be expressed either in form of p-value or percentage (TMeV calls it <i>support</i>).&nbsp;</p>
<p>In the past years, I found <a href="http://www.is.titech.ac.jp/~shimo/prog/pvclust/">an interesting method developed by Hidetoshi Shimodaira</a>: the technique, called <i>multiscale bootstrap resampling</i>, aims at determining more accurate p-values out of the bootstrapping. Shimodaira calls the resulting p-value an <i>AU</i>&nbsp;value, where AU stands for &#8220;approximately unbiased&#8221;, a more precise p-value than the one obtained through bootstrapping alone.</p>
<p>In addition to this nice algorithm, a R package was also provided, named <i>pvclust </i>(it&#8217;s available on your favorite CRAN mirror). And that&#8217;s exactly what we&#8217;ll use for this exercise.</p>
<h2>Prerequisites</h2>
<p>Some of the readers of this blog might remember my disdain of R: while I need to use it for Bioconductor, I&#8217;m often annoyed by its weird syntax, and difficult to understand error messages. Luckily, thanks to the hard work of Laurent Gautier and contributors, there&#8217;s <a href="http://rpy.sourceforge.net">rpy2</a>, a nice R-to-Python bridge. All the examples here require this package, version 2.1 or newer (I&#8217;d recommend the release candidate of 2.2, it&#8217;s really nice). Unfortunately, this means that Windows users are out of luck as there&#8217;s no version of rpy2 2.1 or 2.2 available for that platform..</p>
<p>Also, don&#8217;t forget to have the pvclust package installed in R.</p>
<h2>Loading and preparing the data</h2>
<div>Let&#8217;s start first by importing the necessary bits:</div>
<div></div>
<div>
<pre class="brush: python; title: ; notranslate">
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
</pre>
</div>
<div>The second line is important, because it&#8217;ll let us play with R libraries as they were packages. Case in point, we&#8217;ll get the &#8220;base&#8221; and &#8220;pvclust&#8221; libraries loaded:</div>
<pre class="brush: python; title: ; notranslate">
base = importr(&quot;base&quot;)
pvclust = importr(&quot;pvclust&quot;)
</pre>
<div>Now we can manipulate them as if they were modules, and (most) of R&#8217;s dotted functions have been converted to underscores, as the dot is the namespace operator in Python. Example: as.data.frame becomes as_data_frame.&nbsp;</div>
<div>Next, we&#8217;ll load the data in a data.frame. rpy2 conveniently gives us the <i>DataFrame </i>class, which is a no-nonsense wrapper to R&#8217;s data.frames. For this exercise, we&#8217;ll load a set of normalized data from <a href="http://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE4984">GSE4984</a>, a microarray experiment with dendritic cells expoosed to different stimuli. It&#8217;s just a matter of downloading the data from <a href="http://www.ebi.ac.uk/arrayexpress/files/E-GEOD-4984/E-GEOD-4984.processed.1.zip">Array Express</a>&nbsp;(if you ask why from AE and not GEO: the latter doesn&#8217;t have a clearly-identified link for normalized data)&nbsp;and then loading it in a data.frame as:</div>
<pre class="brush: python; title: ; notranslate">
dataframe = robjects.DataFrame.from_csvfile(&quot;GSE4984.txt&quot;, sep=&quot;\t &quot;, row_names=1)
</pre>
<div>The resulting Python object has all the attributes of a R data.frame but with added Python goodness. We can use the <i>colnames</i>&nbsp;and <i>rownames</i>&nbsp;attributes to access the row names (if set) and column names of the object, and likewise we can use <i>nrow</i>&nbsp;and <i>ncol</i>&nbsp;to quickly glance at the rows/columns.</p>
<div>Since a full array has a lot of genes, we&#8217;re going to choose only the first 500 genes:</p>
<pre class="brush: python; title: ; notranslate">
rows = robjects.IntVector(range(1,501))
subset = dataframe.rx(rows, True)
</pre>
<div>An <i>IntVector</i>&nbsp;is a rpy2 object which replicates R&#8217;s vectors of integers: there are variants for strings, floats, integers, lists (R lists, not the Python type) and factors. rx is an <i>accessor</i>&nbsp;that mimicks R&#8217;s item access: in short, it&#8217;s equivalent to</p>
<pre class="brush: r; title: ; notranslate">
subset &lt;- dataframe[rows, ]
</pre>
<div>rpy2 has another accessor, <i>rx2,</i>&nbsp;which mimicks the [[ ]] access in data.frames.</div>
<h2>Clustering</h2>
<p>Once we have the data, it&#8217;s time to do some serious clustering on it:</p>
<pre class="brush: python; title: ; notranslate">
result = pvclust.pvclust(subset, nboot=100, method_dist=&quot;correlation&quot;, method_hclust=&quot;average&quot;)
</pre>
<p>We&#8217;re using a small number of permutations (100) because the computation times are long. You can change the distance metric and the linkage types using <i>method_dist</i>&nbsp;and <i>method_hclust</i>. Internally the data.frame is converted to a matrix, so ensure you have valid data (i.e. numeric) prior to proceeding.</p>
<p>Notice that this will just cluster the columns by default. If we want to cluster genes, we have to transpose the data.frame. In this case we have to first convert it to a matrix, then transpose it:</p>
<pre class="brush: python; title: ; notranslate">
matrix = base.as_matrix(subset)
subset_transposed = matrix.transpose()
result_rows = pvclust(subset_tranposed, nboot=100, method_dist=&quot;correlation&quot;, method_hclust=&quot;average&quot;)
</pre>
<p>Once the computation is done, we have a <i>pvclust</i>&nbsp;object which holds information on the results. What we&#8217;re most interested in is the <i>hclust</i>&nbsp;attribute, as it holds a dendrogram object we can use for plotting (either standalone or via a heat map). We can also manipulate the object with the <i>pvpick</i>&nbsp;function, for example to color the trees of the dendrogam basing on their AU values.</p>
<p>To get a fast representation, we can just dump the object as it is to a dendrogram which will show AU and BP values for each element of the cluster:</p>
<pre class="brush: python; title: ; notranslate">
graphics = importr(&quot;graphics&quot;)
graphics.plot(result)
</pre>
<div>Or we can do the same, but to a PDF:</div>
<pre class="brush: python; title: ; notranslate">
graphics = importr(&quot;graphics&quot;)
grdevices = importr(&quot;grDevices&quot;)
grdevices.pdf(&quot;myresult.pdf&quot;, paper=&quot;a4&quot;)
graphics.plot(result)
grdevices.dev_off()</pre>
<div>Of course, we might want a heat map (<b>everyone</b>&nbsp;wants pretty heat maps, right?). In that case we extract both dendrograms and use something like gplots&#8217; <i>heatmap.2 </i>&nbsp;function to represent it (you will need the <i>gplots</i>&nbsp;package installed in order for the following to work):</div>
<pre class="brush: python; title: ; notranslate">
gplots = importr(&quot;gplots&quot;)
row_dendrogram = result_rows.rx2(&quot;hclust&quot;)
column_dendrogram = result.rx2(&quot;hclust&quot;)
gplots.heatmap_2(subset, Rowv=row_dendrogram, Colv=column_dendrogram, col=gplots.greenred(255), density_info=&quot;none&quot;)
</pre>
<div>You can add the <i>grdevices</i>&nbsp;lines like above to make a PDF of the plot. &nbsp;If you notice we have used the <i>rx2</i>&nbsp;accessors here, just as I wrote above, to access the <i>hclust</i>&nbsp;attribute of the pvclust object.&nbsp;</div>
<h2>Moving further</h2>
<p>pvclust as-is it&#8217;s quite slow. There&#8217;s however a parallelized version, called <i>parPvclust</i>, which uses <i>snow</i>&nbsp;to parallelize the clustering, either through multiple machines or using multiple cores. Setting snow properly up is beyond the scope of this tutorial, but it may be worth investing if you cluster a lot of data.</p>
</div>
</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2011/05/multiscale-bootstrap-clustering-with-python-and-r/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Taking video snapshots quickly: KDE VLC Snapper</title>
		<link>http://www.dennogumi.org/2011/04/taking-video-snapshots-quickly-kde-vlc-snapper</link>
		<comments>http://www.dennogumi.org/2011/04/taking-video-snapshots-quickly-kde-vlc-snapper#comments</comments>
		<pubDate>Sun, 10 Apr 2011 12:40:26 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[Anime]]></category>
		<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[vlc]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=823</guid>
		<description><![CDATA[Some of the oldest readers of this blog are well aware of a certain hobby of mine. Over the years I&#8217;ve always wanted to write more about that, including the stuff I&#8217;m viewing nowadays, but I found a hassle to &#8230; <a href="http://www.dennogumi.org/2011/04/taking-video-snapshots-quickly-kde-vlc-snapper">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Some of the oldest readers of this blog are well aware of <a href="http://www.dennogumi.org/category/anime">a certain hobby of mine</a>. Over the years I&#8217;ve always wanted to write more about that, including the stuff I&#8217;m viewing nowadays, but I found a hassle to collect snapshots from videos / DVDs, selecting them, and so on.&nbsp;
<div>Recently I learnt that VLC has <a href="http://wiki.videolan.org/Python_bindings">some rather complete Python bindings</a>, and I thought, <i>why not make the process automated?</i>&nbsp;Yesterday I had some free time on my hands and a quick session of hacking brought some results already.</div>
<div>As the stuff is somewhat past prototypal stage, I thought I would push somewhere for others to use. &nbsp;Lo and behold, here I present you <i>KDE VLC Snapper</i>.</div>
<div></div>
<div style="text-align: center;"><img width="300" height="313" src="http://www.dennogumi.org/wp-content/uploads/2011/04/vlcsnapper_resized.png?cda6c1"/></div>
<div style="text-align: left;">As you can see, it&#8217;s a minimal dialog: just select your source video file (any file supported by VLC will do), the number of screencaps, the destination directory, and the program will do the rest. Currently it works <i>somewhat</i>&nbsp;OK (see caveats below) and is good enough for my use cases.</div>
<h2>How do I get it?</h2>
<div>Just clone this repository:
<pre class="brush: plain; title: ; notranslate">git clone http://git.gitorious.org/kde-vlc-snapper/kde-vlc-snapper.git</pre>
<p> followed by
<pre class="brush: bash; title: ; notranslate">sudo python setup.py install</pre>
<p> You can then invoke the program with
<pre class="brush: plain; title: ; notranslate">kdevlcsnapper</pre>
</div>
<div></div>
<div><b>Requirements</b>&nbsp;include PyKDE4 (tested on KDE Dev Platform 4.6), numpy (just for its &#8220;linspace&#8221; function, alternatives are welcome) and VLC installed (you don&#8217;t need the bindings, however: I provide a local copy).</div>
<div>What about <b>bugs</b>? Well, currently there are two issues that I&#8217;m unsure on how to fix: the first is a crash on exit, the second is that certain media files make VLC crash in the background when called from the bindings.</div>
<div>In any case, if you try it out, let me know what you think in the comments!</div>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2011/04/taking-video-snapshots-quickly-kde-vlc-snapper/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>PyKDE4: Retrieve data using KIO</title>
		<link>http://www.dennogumi.org/2011/01/pykde4-retrieve-data-using-kio</link>
		<comments>http://www.dennogumi.org/2011/01/pykde4-retrieve-data-using-kio#comments</comments>
		<pubDate>Sat, 01 Jan 2011 21:09:26 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[pykde]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=810</guid>
		<description><![CDATA[One of the greatest strengths of KDE is undoubtedly the asynchronous and network-transparent I/O access, employed by the so-called &#8220;I/O&#8221; slaves, part of the KIO class. If you are developing an application that requires file or network access, those classes &#8230; <a href="http://www.dennogumi.org/2011/01/pykde4-retrieve-data-using-kio">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the greatest strengths of KDE is undoubtedly the asynchronous and network-transparent I/O access, employed by the so-called &#8220;I/O&#8221; slaves, part of the KIO class. If you are developing an application that requires file or network access, those classes make things incredibly simple to do, and they don&#8217;t freeze your GUI when you are in the middle of a process.
<div></div>
<div>In this post I&#8217;ll show how to use KIO to retrieve files from network resources using PyKDE4. The whole example is also available <a href="http://websvn.kde.org/trunk/KDE/kdeexamples/bindings/python/kio/">in the kdeexamples module</a>.</p>
<p>Our first step is to create a simple UI to show how KIO works. It will be a text edit along with two buttons to retrieve and clear items. Here&#8217;s how it looks in Designer (the ui file and its compiled Python version are available at the above link):</p>
<div style="text-align: center;"><img width="400" height="300" title="Example form" src="http://www.dennogumi.org/wp-content/uploads/2011/01/kio_tutorial.png?cda6c1" alt="Image of the example form"/></div>
<p>Once this is done, we turn our attention to code. We start customary imports:</p>
<pre class="brush: python; title: ; notranslate">
#!/usr/bin/env python
import sys
import PyQt4.QtCore as QtCore
import PyQt4.QtGui as QtGui
import PyKDE4.kdecore as kdecore
import PyKDE4.kdeui as kdeui
from PyKDE4.kio import KIO</pre>
<p>These will provide for everything we need. Then we set up our widget:</p>
<pre class="brush: python; title: ; notranslate">

from ui_textbrowser import Ui_Form

class TextArea(QtGui.QWidget, Ui_Form):

    &quot;&quot;&quot;Example class used to show how KIO works.&quot;&quot;&quot;

    def __init__(self, parent=None):

        super(TextArea, self).__init__(parent)
        self.setupUi(self)

        self.downloadButton.clicked.connect(self.start_download)
        self.clearButton.clicked.connect(self.textWidget.clear)
</pre>
<p>Nothing strange in the initializer here. We simply make two connections, one to the clear() slot of the clear button, and the other to start the KIO process, that is the retrieval of the index from www.kde.org. Let&#8217;s take a look at the start_download slot:</p>
<pre class="brush: python; title: ; notranslate">
    def start_download(self):
        kdeui.KMessageBox.information(self.parent(),
                                      &quot;Now data will be retrieved from &quot;
                                      &quot;www.kde.org using KIO&quot;)

        # KIO wants KUrls
        data_url = kdecore.KUrl(&quot;http://www.kde.org&quot;)
        retrieve_job = KIO.storedGet(data_url, KIO.NoReload, KIO.HideProgressInfo)
        retrieve_job.result.connect(self.handle_download)
</pre>
<p>What do we do here? We show a KMessageBox, just for informational purposes. Once this is done, we prepare the actual KIO &nbsp;job. KIO wants KUrls so we first of all wrap the URL we want to download from in that. Then we create the actual job: in this case it&#8217;s KIO.storedGet, that is we retrieve the data in full from our URL and store it in a QByteArray. This is a common use case, but you have to keep in mind that for large files this may be impractical. In such a case, we would be better off using KIO.get followed by a connection to the &#8220;data&#8221; signal, to get the data in chunks.</p>
<p>A KIO job can have many flags: here we set to remove the progress information, so that you won&#8217;t get a notification in the Plasma notifier. For small operations, this should be always present. For longer downloads, it&#8217;s likely not a good idea. More information are available in the <a href="http://api.kde.org/4.5-api/kdelibs-apidocs/kio/html/namespaceKIO.html">KIO namespace page (C++ version).</a></p>
<p>As a last step, we connect the result signal (emitted when the job is complete) to a slot to handle the download. This is what makes KIO useful, because it&#8217;s asynchronous, so you can perform long downloads without blocking the user interface of your program</p>
<p>Lastly, we see the &#8220;handle_download&#8221; slot:</p>
<pre class="brush: python; title: ; notranslate">

    def handle_download(self, job):

        # Bail out in case of errors
        if job.error():
            return

        print &quot;This slot has been called. The job has finished its operation.&quot;

        data = job.data()
        self.textWidget.setPlainText(QtCore.QString(data))
</pre>
<p>This slot&#8217;s signature include a KJob instance, that is what we&#8217;ll use to get the data. In fact, using the data() function we can obtain the QByteArray containing what we have retrieved. Then, in this case we simply use setPlainText to put the downloaded data into the text edit.</p>
<p>What if something goes wrong? We can check for errors if job.error() returns True: in that case we can perform recovery, or simply tell our user that something went wrong. Especially with networked resources, this should always be present in your code.</p>
<p>So that&#8217;s all for now. As you can see, it was pretty simple, and also very effective.</p></div>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2011/01/pykde4-retrieve-data-using-kio/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>PyKDE4: Tag and annotate files using Nepomuk</title>
		<link>http://www.dennogumi.org/2010/10/pykde4-tag-and-annotate-files-using-nepomuk</link>
		<comments>http://www.dennogumi.org/2010/10/pykde4-tag-and-annotate-files-using-nepomuk#comments</comments>
		<pubDate>Tue, 26 Oct 2010 19:37:16 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[semantic desktop]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=803</guid>
		<description><![CDATA[Some time has passed since I last blogged&#8230; this was not only due to lack of time but also due to motivation (writing long texts can be discouraging at times). In any case, I&#8217;d like to rectify for that. In &#8230; <a href="http://www.dennogumi.org/2010/10/pykde4-tag-and-annotate-files-using-nepomuk">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Some time has passed since I last blogged&#8230; this was not only due to lack of time but also due to motivation (writing long texts can be discouraging at times). In any case, I&#8217;d like to rectify for that. In this post, I&#8217;ll talk about Nepomuk, and in particular how to use it to tag and annotate arbitrary files using its API in PyKDE4.</p>
<p>Before starting, let me say that creating this tutorial was only possible thanks to the help of Sebastian Trueg, who helped me by pointing out some mistakes I was doing.</p>
<p>The example here is not showing the extra methods to set up a KApplication, etc.:  the full code for this tutorial<a href="http://websvn.kde.org/trunk/KDE/kdeexamples/bindings/python/nepomuk/" title="WebSVN link"> is available in the kdeexamples module</a>. </p>
<p>Let&#8217;s start with the basics.</p>
<pre class="brush: python; title: ; notranslate">import sys
from PyQt4 import QtCore
from PyKDE4 import kdecore
from PyKDE4 import kdeui
from PyKDE4.nepomuk import Nepomuk</pre>
<p>This will import all the bits needed to test our experiment. As a second step, we&#8217;ll create a dummy empty file.</p>
<pre class="brush: python; title: ; notranslate">dummy_file = open(&quot;dummy.txt&quot;, &quot;w&quot;)
dummy_file.write(&quot;Some text\n&quot;)
dummy_file.close()</pre>
<p>Or, if we have Python 2.6+ (as pointed out in the comments):</p>
<pre class="brush: python; title: ; notranslate">
with open(&quot;dummy.txt&quot;, &quot;w&quot;) as handle:
    handle.write(&quot;Some text\n&quot;)
</pre>
<p>Now that we have our file, it&#8217;s time to do something productive with it. But first and foremost, we have to ensure that Nepomuk is running. To do so, we make a simple check (EDIT: fixed the syntax):</p>
<pre class="brush: python; title: ; notranslate">result = Nepomuk.ResourceManager.instance().init()
if result != 0:
     return</pre>
<p>Neomuk.instance().init() must return 0 if Nepomuk is properly set up. Once this is taken care of, we can manipulate the semantic information of our file. Thus, Nepomuk needs to be made aware of it: this is done by creating a <em>resource</em> that points to the actual file:</p>
<pre class="brush: python; title: ; notranslate">file_info = QtCore.QFileInfo(&quot;dummy.txt&quot;)
absolute_path = file_info.absoluteFilePath()
resource = Nepomuk.Resource(kdecore.KUrl(absolute_path)</pre>
<p>Notice that we <strong>must</strong> use an absolute file path, or the resource will be not created properly and although no errors will happen when tagging, changes will not be made. Let&#8217;s now create a tag, which is done by simply constructing a Nepomuk.Tag instance:</p>
<pre class="brush: python; title: ; notranslate">tag = Nepomuk.Tag(&quot;test_example&quot;)
tag.setLabel(&quot;test_example&quot;)</pre>
<p>In the first line we create the tag, then we associate it with a label, so that it will be displayed in applications such as Dolphin. The nice thing is that if the Tag already exists, it will be recycled: no duplicates will occur. A simple call to addTag to the resource we created earlier will now tag it:</p>
<pre class="brush: python; title: ; notranslate">resource.addTag(tag)</pre>
<p>We can also add comments that can show up in Dolphin as well by using the setDescription method:</p>
<pre class="brush: python; title: ; notranslate">resource.setDescription(&quot;This is an example comment.&quot;)</pre>
<p>What if we want to remove tags and descriptions? To wipe them all, we can use the remove() method of the Resource, otherwise we can strip elements by using removeProperty along with the tagUri() or descriptionUri() methods of the resource:</p>
<pre class="brush: python; title: ; notranslate">resource.remove() # strip everything
resource.removeProperty(resource.descriptionUri()) # remove comment
resource.removeProperty(resource.tagUri()) # remove tags
</pre>
<p>That&#8217;s it. As you can see, adding semantic information from PyKDE4 isn&#8217;t that hard. Sooner or later I&#8217;ll try my hand at queries and report back my findings.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/10/pykde4-tag-and-annotate-files-using-nepomuk/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>What this might ever be?</title>
		<link>http://www.dennogumi.org/2010/07/what-this-might-ever-be</link>
		<comments>http://www.dennogumi.org/2010/07/what-this-might-ever-be#comments</comments>
		<pubDate>Tue, 27 Jul 2010 22:41:14 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=790</guid>
		<description><![CDATA[The rest is up to you to figure out.]]></description>
			<content:encoded><![CDATA[<p align="center"><img src="http://imagebin.ca/img/V-7GlD.png" /></p>
<p align="left">The rest is up to you to figure out.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/07/what-this-might-ever-be/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>OCS and KDE Forums &#8211; work continues</title>
		<link>http://www.dennogumi.org/2010/07/ocs-and-kde-forums-work-continues</link>
		<comments>http://www.dennogumi.org/2010/07/ocs-and-kde-forums-work-continues#comments</comments>
		<pubDate>Sun, 25 Jul 2010 18:49:22 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[OCS]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=787</guid>
		<description><![CDATA[With my last entry, I announced the start of the work for an OCS library for the KDE Community Forums. Today I&#8217;d like to blog again about the recent developments. First of all, now there isn&#8217;t one, but two Python &#8230; <a href="http://www.dennogumi.org/2010/07/ocs-and-kde-forums-work-continues">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>With my last entry, I announced the start of the work for an OCS library for the KDE Community Forums. Today I&#8217;d like to blog again about the recent developments. </p>
<p>First of all, now there isn&#8217;t one, but <em>two</em> Python modules:</p>
<ul>
<li><em>ocslib, </em> a pure Python module that can be used to interface with OCS-based forum systems;</li>
<li><em>ocslibkde</em>, a PyKDE4 based module that can be used to interface with OCS-based forum system in KDE applications.</li>
</ul>
<p>Currently ocslib supports reading and posting, while ocslibkde only reading (as of now). Both can be retrieved from the <a href="http://gitorious.org/kde-forum-mods" title="Gitorious.org repository">kde-forum-mods repository</a> under the <em>ocs-client</em> subdirectory. The Python lib needs unit-testing, then I&#8217;ll be able to push a tarball soon for people to test (but you can always check out the Git repository). With regards to the PyKDE4 library, I plan on making a proof-of-concept plasmoid soon that shows how to use the API.</p>
<p>Speaking of API, here are some examples using ocslib:</p>
</p>
<pre class="brush: python; title: ; notranslate">
&gt;&gt;&gt; from ocslib import service# Connect to OCS
&gt;&gt;&gt; ocs_service = ocslib.service.OCService(&quot;http://www.example.com&quot;)
#Retrieve all forums
&gt;&gt;&gt; forums = ocs_service.list_forums()
# Elements have attributes for name, posts, etc.
&gt;&gt;&gt; print forums[0].name
&quot;Test forum&quot;
#Retrieve threads for forum 15
&gt;&gt;&gt; threads = ocs_service.list_forum_threads(forum_id=15)
# Retrieve thread 8945 from forum 15
&gt;&gt;&gt; messages = ocs_service.show_thread(forum_id=15, topic_id=8945)
&gt;&gt;&gt; print messages[0].text
&quot;Hello world!
#Post to a forum - requires authentication
&gt;&gt;&gt; ocs_service = service.OCService(&quot;http://www.example.com&quot;, username=&quot;foo&quot;, password=&quot;bar&quot;)
&gt;&gt;&gt; message = &quot;Hello, KDE people!&quot;
&gt;&gt;&gt; subject = &quot;Test message&quot;
&gt;&gt;&gt; ocs_service.post(forum_id=15, subject=subject, message=message)
True # Return code of operation
</pre>
<p>Feedback (especially on the API) welcome!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/07/ocs-and-kde-forums-work-continues/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Open Collaboration Services and KDE Forums</title>
		<link>http://www.dennogumi.org/2010/07/open-collaboration-services-and-kde-forums</link>
		<comments>http://www.dennogumi.org/2010/07/open-collaboration-services-and-kde-forums#comments</comments>
		<pubDate>Sun, 18 Jul 2010 10:00:39 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[forums]]></category>
		<category><![CDATA[OCS]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=785</guid>
		<description><![CDATA[For KDE developers, web-based forums are often uncommon workflows. Indeed, for communication among developers mailing lists are much better tools, especially since you can handle everything inside a client (most of the time), compared to forums where you have to &#8230; <a href="http://www.dennogumi.org/2010/07/open-collaboration-services-and-kde-forums">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>For KDE developers, web-based forums are often uncommon workflows. Indeed, for communication among developers mailing lists are much better tools, especially since you can handle everything inside a client (most of the time), compared to forums where you have to use a web browser. The ways of reading, replying and interacting with posters are dramatically different. And that is why some developers find themselves uncomfortable with the <a href="http://forum.kde.org" title="KDE Community Forums">KDE Community Forums</a>.</p>
<p>A dedicated application would be usually much better than a browser, because you can work around the intrinsic limitations of the browser itself. The problem is that you can&#8217;t really access a forum with anything else than a browser. That is, it <em>used to be</em> like this, but now things are changing.</p>
<p>In the past months fellow administrator bcooksley has been working quite hard implementing the <a href="http://freedesktop.org/wiki/Specifications/open-collaboration-services" title="OCS specification">Open Collaboration Services (OCS) specification</a> in the KDE Community Forums. For the uninformed, it&#8217;s the same API that powers <a href="http://opendesktop.org" title="OpenDesktop.org">OpenDesktop.org</a> and related web pages. This means that you could access the forum contents programmatically using a REST API and parsing the XML that is returned by the service. </p>
<p>Unfortunately, bcooksley had no time to implement a client that would make use of this newly-made service.</p>
<p>That&#8217;s where I stepped in. This morning <a href="http://gitorious.org/kde-forum-mods/phpbb/commit/471f6f7b4135d004be040c2bbd552b12451badfe" title="OCS commit">I committed in the kde-forum-mods repository</a> the first implementation of a backend to access the forums&#8217; OCS service. Currently it&#8217;s extremely basic &#8211; just a few classes to wrap the XML responses into decent data representation, and a basic class to perform reading requests: that means that technically it is possible to request forum listings, thread listing, and posts. I&#8217;m still working on the ability of replying and posting messages.</p>
<p>Being a Pythonista, the backend is written entirely in Python: currently it uses the standard library plus <a href="http://labix.org/python-dateutil" title="Python-dateutil"><em>dateutil</em></a> and <a href="http://codespeak.net/lxml/" title="lxml home page"><em>lxml</em></a> to do its bidding, but the next steps would be to turn it into a PyKDE4 library to access all the KDE related goodness (hello, KIO!). Bear in mind that currently there is no application using this: I merely completed (part of) the backend. </p>
<p>If you&#8217;re interested, the code can be found on gitorious.org, in the <em>ocs-client</em> directory, branch <em>experimental</em>,  inside the <a href="http://gitorious.org/kde-forum-mods" title="Gitorious.org repository">kde-forum-mods repository</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/07/open-collaboration-services-and-kde-forums/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>PyKDE4: new style signals and slots</title>
		<link>http://www.dennogumi.org/2010/03/pykde4-new-style-signals-and-slots</link>
		<comments>http://www.dennogumi.org/2010/03/pykde4-new-style-signals-and-slots#comments</comments>
		<pubDate>Sat, 06 Mar 2010 09:04:48 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=763</guid>
		<description><![CDATA[Those who use PyQt and PyKDE4 are certainly familiar with the syntax used to connect signals and slots: The main advantage of this syntax is that it&#8217;s very close to the C++ equivalent, and so you can translate easily from &#8230; <a href="http://www.dennogumi.org/2010/03/pykde4-new-style-signals-and-slots">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Those who use PyQt and PyKDE4 are certainly familiar with the syntax used to connect signals and slots:</p>
<pre class="brush: python; title: ; notranslate">
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyKDE4 import kdeui

class MyGUI(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyGUI, self).__init__(parent)
        self.pushbutton = kdeui.KPushButton()
        self.pushbutton.setText(&quot;Push me!&quot;)

        QObject.connect(self.pushbutton, QtCore.SIGNAL(&quot;clicked()&quot;),
                               self.button_pushed)

    def button_pushed(self):
        print &quot;Button clicked&quot;
</pre>
<p>The main advantage of this syntax is that it&#8217;s very close to the C++ equivalent, and so you can translate easily from C++ to Python. Unfortunately the advantages of this syntax end here. The disadvantages, at least from a Python coding perspective, outweigh the advantages:</p>
<ul>
<li>It&#8217;s <em>extremely</em> error-prone: make a typo, and not only your signal won&#8217;t be connected, but you won&#8217;t even get a warning, your program will simply do nothing;</li>
<li>In case you have overloaded signals, you have to type the exact signature, going back to the first problem;</li>
<li>It&#8217;s not Pythonic at all.</li>
</ul>
<p>So, in recent PyQt versions (and thus also in PyKDE4) a <em>new style</em> approach was introduced (although the old style is always present should it be the need to). Using the new style, the signals become a property of the object that emits them. and then you use the connect function of that property. Here&#8217;s the example using the new style-signals:</p>
<pre class="brush: python; title: ; notranslate">
from PyQt4 import QtCore
from PyQt4 import QtGui
from PyKDE4 import kdeui

class MyGUI(QtGui.QWidget):

    def __init__(self, parent=None):
        super(MyGUI, self).__init__(parent)
        self.pushbutton = kdeui.KPushButton()
        self.pushbutton.setText(&quot;Push me!&quot;)
        # New style
        self.pushbutton.clicked.connect(self.button_pushed)

    def button_pushed(self):
        print &quot;Button clicked&quot;
</pre>
<p>As you can see it&#8217;s much clearer, and much more Pythonic. Also, typos  <strong>will</strong> trigger an AttributeError, which means you&#8217;ll be able to track where the problem is.  </p>
<p>What about overloaded signals? Normally the first defined is the default, but you can use a dictionary-like syntax to access other overloads (signal names are completely made up here):</p>
<pre class="brush: python; title: ; notranslate">
# One signal is without arguments, the other has a bool

# Signal without arguments
self.my_widget.connected.connect(self.handle_errors)
# Signal with a book
self.my_widget.connected[bool].connect(self.handle_errors)
</pre>
<p>Signals are emitted with the emit() function and disconnected with the disconnect() function:</p>
<pre class="brush: python; title: ; notranslate">
# Emit a signal
self.pushbutton.clicked.emit()
# Emit a signal with a value (an int)
self.my_widget.valueChanged.emit(int)
# Disconnect another
self.my_tabwidget.currentIndexChanged.disconnect()
</pre>
<p>To define new signals, you can use the <em>pyqtSignal</em> function, specifying which values will the signal take (if any): just define that as a class constant (like in the example) and then you can access them like the wrapped ones:</p>
<pre class="brush: python; title: ; notranslate">

class MyWidget(QWidget):

    # Signal with no arguments
    operationPerformed = QtCore.pyqtSignal()

    # Signal that takes arguments
    valueChanged = QtCore.pyqtSignal(int)
</pre>
<p>I merely scratched the surface with this. For more information, check out <a href="http://riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html" title="PyQt4 Reference Manual">PyQt&#8217;s reference manual</a>, which also covers other cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/03/pykde4-new-style-signals-and-slots/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>The world of KIO metadata &#8211; checking the HTTP response from a server</title>
		<link>http://www.dennogumi.org/2010/02/the-world-of-kio-metadata-checking-the-http-response-from-a-server</link>
		<comments>http://www.dennogumi.org/2010/02/the-world-of-kio-metadata-checking-the-http-response-from-a-server#comments</comments>
		<pubDate>Thu, 18 Feb 2010 21:42:46 +0000</pubDate>
		<dc:creator>Einar</dc:creator>
				<category><![CDATA[KDE]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[python]]></category>

		<guid isPermaLink="false">http://www.dennogumi.org/?p=753</guid>
		<description><![CDATA[Recently, I investigated how to perform some checks on web addresses using KIO for Danbooru Client. My old code was synchronous, so it blocked the application while checking, thus causing all sort of troubles (UI freezing, etc.). Therefore, making the &#8230; <a href="http://www.dennogumi.org/2010/02/the-world-of-kio-metadata-checking-the-http-response-from-a-server">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Recently, I investigated how to perform some checks on web addresses using KIO for <a href="http://kde-apps.org/content/show.php/Danbooru+Client?action=content&#038;content=114343" title="kde-apps page">Danbooru Client</a>. My old code was synchronous, so it blocked the application while checking, thus causing all sort of troubles (UI freezing, etc.). Therefore, making the switch to KIO was the best solution. However, I had one problem: <em>how could I check the HTTP response?</em></p>
<p>I knew already that the various ioslaves can store metadata, consisting of key-value pairs which are specific on the slave used. Normally you can get the whole map by accessing the <a href="http://api.kde.org/4.4-api/kdelibs-apidocs/kio/html/classKIO_1_1Job.html#a631cbc61c70e512ad91b2cf2c23ef029" title="API docs on metaData()"><em>metaData</em></a> function of the job you have used, in the slot connected from the <em>result</em> signal.  For some reason, however, in PyKDE4 calling metaData() triggers an assert in SIP, which ends in a crash (at least in my application; I stil need to debug further).  KIO  jobs have also the <a href="http://api.kde.org/4.4-api/kdelibs-apidocs/kio/html/classKIO_1_1Job.html#aafd31b4d9643bffb4cd75f3a31242bd4" title="API docs on queryMetaData"><em>queryMetaData</em></a> function, which returns the value of the key you have queried. Unfortunately, there was no way I could find the name.</p>
<p>Thus began my search for the right key. Googling didn&#8217;t help, and on IRC I got the first answers I needed but not enough to reach the goal. Until I saw a commit by David Faure in trunk/kdelibs/kio/ which touched a file called <a href="http://websvn.kde.org/branches/KDE/4.4/kdelibs/kio/DESIGN.metadata?revision=1070858&#038;view=markup" title="Link to the branch version">DESIGN.metadata</a> (link is for the branch version). After checking with webSVN, that was exactly the thing I was looking for! It lists all the keys for the metadata, indicating also to which ioslave they begin.  After that, the solution was easy.</p>
<p>Of course I&#8217;m not leaving you hanging there and now I&#8217;ll show you how, in PyKDE4, you can quickly check for the server response:</p>
<pre class="brush: python; title: ; notranslate">
from PyKDE4.kio import KIO
from PyQt4.QtCore import SIGNAL
[...]

class my_widget(QWidget):
[...]

    def check_address(self, url):

        # You can add optional flags such as KIO.HideProgressInfo
        job = KIO.get(KUrl(url))
        self.connect(job, SIGNAL(&quot;result (KJob *)&quot;), self.slot_result)

    def slot_result(self, job):

        if job.error():
            # Bail out if there's an error
            return    

        # Get the HTTP response through queryMetaData
        http_response = job.queryMetaData(&quot;responsecode&quot;)
        print &quot;Got response: %s&quot; % unicode(http_response)
</pre>
<p>This snippet does a few things. Firstly, it gets the specified URL, using KIO.get (KIO.stat doesn&#8217;t set the required metadata). Notice that the call is not wrapped in the  new-style PyQt API because <em>result (KJob *)</em> isn&#8217;t wrapped like that (<a href="https://bugs.kde.org/show_bug.cgi?id=211070" title="Bug 211070">there&#8217;s a bug open for that</a>). In any case, the signal passes to the connecting slot (slot_result) where we first check if there&#8217;s an error (perhaps the address didn&#8217;t exist?) and then we use <em>queryMetaData(&quot;responsecode&quot;)</em> to get the actual response code. </p>
<p>If you want to do error checking basing on the result, bear in mind that KIO operates asynchronously, so you should use a signal to tell your application that the result is what it expected or not.</p>
<p>I wonder if this should be documented in Techbase&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.dennogumi.org/2010/02/the-world-of-kio-metadata-checking-the-http-response-from-a-server/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using xcache (Feed is rejected)
Page Caching using xcache
Database Caching 1/31 queries in 0.021 seconds using xcache
Object Caching 774/838 objects using xcache

Served from: www.dennogumi.org @ 2012-02-05 06:10:50 -->
