Archive

Archive for the ‘Linux & Programming’ Category

rsslibnotify – My very first python script

October 28th, 2010 6 comments

UPDATE: I included tante’s comments and extended the program. The config-file now allows you to define the checking interval and will be automatically created if nonexisting.

I noticed that gwibber removed their rss support for some reason. However, it would be really nice to have the option for libnotify to …well… notify you on gnome when there is something new on rss/atom feeds you find important. Since I always wanted to learn python anyway, I hacked together a small script, which does exactly that. Just create a config file in ~/.rsslibnotify with a number of rss/atom feeds separated by newlines and you will be informed every ten minutes via libnotify if there’s something new. (see update above)

feedparser and pynotify need to be installed prior. Btw. feedparser is giving me errors while installing, however seems to be working without a problem.

Of course this script is far from perfect. Keep in mind it’s my first python script and I worked at most one to two hours on it ;).

Available for download here: rsslibnotify.py

#!/usr/bin/python
# coding=utf-8
 
#
#    Copyright 2010 by Daniel Süpke
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
#
# rsslibnotify v0.3
#
 
import pynotify
import feedparser
import time
import os.path
import sys
 
config_file = os.path.expanduser('~/.rsslibnotify')
feeds = []
titles = []
 
try:
    file = open(config_file, 'r')
except:
    file = open(config_file, 'w')
    file.write('# amount of seconds to wait before checking for new items\n')
    file.write('interval 600\n\n')
    file.write('# feeds to check\n')
    file.write('feed https://suepke.net/feed/\n')
    file.write('feed http://rss.golem.de/rss.php?feed\x3dRSS1.0\x26ms\x3drss\n')
 
    print('Config file not found! Created example file at ' + config_file + '. Please edit.')
    sys.exit(0)
 
for line in file.readlines():
    config_line = line.rstrip().partition('#')[0] # Remove \n and comments
 
    if config_line.startswith('feed '):
        feeds.append(config_line.partition('feed ')[2])
    if config_line.startswith('interval '):
        interval = int(config_line.partition('interval ')[2])
 
    titles.append('')
 
file.close()
 
if not feeds:
    print('There were no feeds in your config file at ' + config_file + '. Exiting...')
    sys.exit(0)
 
if not interval:
    print('No check interval has been defined. Assuming ten minutes.')
    interval = 600
 
# Check for new feeds every interval seconds
while True:
    i = 0
 
    for feed in feeds:
        d = feedparser.parse(feed)
 
        # Assume new content if there is a new title
        if d.entries[0].title != titles[i]:
            titles[i] = d.entries[0].title
 
            if pynotify.init('rssnotify'):
                n = pynotify.Notification(d.feed.title, d.entries[0].title)
                n.show()
            else:
                print('there was a problem initializing the pynotify module')
        i += 1
 
    time.sleep(interval)

Uni Oldenburg VPN with ubuntu 10.04

May 11th, 2010 5 comments

Finally got the VPN of my university working. I will share how I got it working in case you study/work here and want to use it, too.

I found the VPN to be more stable when started from a shell:
sudo apt-get install vpnc
sudo nano /etc/vpnc/default.conf

Edit the config as following:
IPSec gateway 10.9.8.7
IPSec ID student
IPSec secret student
#IKE Authmode hybrid
Xauth username YOUR
Xauth password YOUR

Then just connect to the wlan and start the vpn with sudo vpnc.

If you want to use the network-manager, you need to install another package. However, I always get an error message about invalid secrets. If you have more luck, please let me know.
sudo apt-get install network-manager-vpnc
sudo service network-manager restart

Solving Sound Problems with Dosbox in Ubuntu 8.10 and 9.04

June 27th, 2009 No comments

Hey guys, since I get a lot of hits to this article, I’d really appreciate if you leave a short note when this helped you, so we can see if this is a general configuration problem. Thanks!

Since ubuntu 8.10 I was having stuttering sound with dosbox. I just made a fresh install of 9.04 and still was experiencing such problems (pulseaudio ftw again…). I searched the web, alas was unable to find a solution that was actually working. After trying a couple of things, I finally seem to have found a solution which is working (at least for me): I set the mixing rate within dosbox to match that of pulseaudio. To make it short, change your conf in ~/.dosbox/ to

[mixer]
#   nosound: Enable silent mode, sound is still emulated though.
#      rate: Mixer sample rate, setting any device's rate higher than this will probably lower their sound quality.
#            Possible values: 22050, 44100, 48000, 32000, 16000, 11025, 8000, 49716.
# blocksize: Mixer block size, larger blocks might help sound stuttering but sound will also be more lagged.
#            Possible values: 2048, 4096, 8192, 1024, 512, 256.
# prebuffer: How many milliseconds of data to keep on top of the blocksize.
nosound=false
#rate=22050
rate=44100      # Change this line
blocksize=2048
prebuffer=10

Also, to get rid of the initial midi warning I changed the following, though it may not be necessary:

[midi]
#     mpu401: Type of MPU-401 to emulate.
#             Possible values: intelligent, uart, none.
# mididevice: Device that will receive the MIDI data from MPU-401.
#             Possible values: default, win32, alsa, oss, coreaudio, coremidi, none.
# midiconfig: Special configuration options for the device driver. This is usually the id of the device you want to use. See README for details.
mpu401=intelligent
mididevice=default
midiconfig=128:0      # Change this line

Yet another pulseaudio problem solved.

Update: Also, setting output to opengl helps a lot, at least if you have compiz enabled.

Enabling Automatic Upgrades for Ubuntu

May 9th, 2009 No comments

Ubuntu allows you to install security updates automatically in the background (under Synaptic -> Repositories -> Updates), but there was only the option Install Security updates without notification, no option for just installing all updates. I searched for a way to automate it and found the solution in launchpad:

Just open /etc/apt/apt.conf.d/50unattended-upgrades and enable all updates, then you can have daily automatic upgrades without notification. No more need to confirm all the same upgrades on different computers again and again, neat!

Conditional Commenting in LaTeX

April 22nd, 2009 7 comments

In my Ph.D. thesis are quite a lot of comments/reminders for myself. I defined two commands for this, one for a red footnote and one for red bold text. But if someone else is to read parts of the document, he shouldn’t necessarily see all my comments, so I was searching for a method to suppress all comments with a single flag. I found the package ifthen and it’s exactly what I was looking for. If you need to use comments for yourself in a document you’re writing, consider using the following:

\usepackage{ifthen}
\usepackage{color}
...
\newboolean{showComments}
% If set to true, comments will be inserted, otherwise ignored
\setboolean{showComments}{true}
...
% Internal command
\newcommand{\todocmd}[1]{{\bf\textcolor{red}{#1}}}
 
% use \todo{text} for a comment within your page/section
\newcommand{\todo}[1]{\ifthenelse {\boolean{showComments}} {\todocmd{#1}} {}}
 
% use todof{text} for a footnote
\newcommand{\todof}[1]{\ifthenelse {\boolean{showComments}} {\footnote{\todocmd{#1}}} {}}
Categories: English, Linux & Programming Tags:

Embedding Windows in Linux with VirtualBox

February 10th, 2009 3 comments

I am obviously a big fan of Linux and use it at home as well as in my office. But in both places I still require Windows for two reason:

  • At home I require it for gaming. Wine is ok, but can still be a major pain in the ass with configuration and lesser known games.
  • In the office I am obliged to use Microsoft Office. I prefer LaTeX, but compared to OpenOffice the 2007 version of MsOffice is the big winner in my opinion.  But since working under Windows otherwise is out of question for me (I am way more productive with Linux/Gnome), a dual-boot like I use for gaming is no option.

So, in my office, I use VirtualBox to embed Windows inside my Linux desktop. Formerly I used VMware, which admittedly is more powerful, but provides a less appealing user interface and, at that time, did not provide the seamless mode, which I will make use of. To give an impression, here is a screenshot of my desktop:

Using VirtualBox to embed Windows inside Gnome

Using VirtualBox to embed Windows inside Gnome

I will not go through the installation process, as it’s pretty self-explanatory. But what VirtualBox additionally offers is the aforementioned seamless mode (default combination: Right-CTRL + L), which gives you the taskbar over your normal gnome panel. This is really nice, since it allows easy access and switching between Windows and Linux applications. While Alt-Tab is not used optimally (it only lets you access applications of one OS at a time), you can switch between Windows and Linux applications by pressing Right-CTRL before using Alt-Tab.

Another great feature is embedding any host folder (e.g. your home folder) directly inside the Windows explorer as seen on the screenshot. This is achieved by setting a shared folder in Devices->Shared Folders and then adding a network drive. This is as simple as right-clicking on My Computer (unsure about the name, I only have German Windows 😉 ) and adding the drive. From now it’s possible to modify and share files between host and virtual machine without any hassle.

Also, I configured cups to allow web access to the printers configured in Linux, so the Windows VM could easily print by using these. But I haven’t configured this yet since my last installation, so I cannot give a howto right now 😉 .

I hope you enjoy the progress of free VMs like VirtualBox as much as I do, as it allows Windows apps, that are sadly still required, to be used inside your Linux without a hassle and with nice integration. I hope that Alt-Tab is improved, then the whole thing would feel like a natural part of your Linux desktop. Additionally, VirtualBox now has Direct3D support (which I haven’t tested yet), so maybe one day we will be able to even do gaming inside our Linux distributions without any more need for a dual boot.

Update:

For all this, you need to install the Guest additions. You can find these in the menu devices.

A Java Wizard Toolkit

February 5th, 2009 No comments

Well, here goes my first post. This is a toolkit I started developing back in 2006. I am sure there are other, better implementations and I did not develop this small project any further, but I think it’s also a good example on how to program in OO (though I am sure there is much room for improvement, any flames appreciated 😉 ). So, here it goes:

Introduction

The Wizard Toolkit is a java framework / toolkit for the easy use and creation of wizards. This toolkit lets you focus on defining and validating input fields while the control flow and data storage is automated by the surrounding toolkit.

Wizards are a useful way to gather information for different purposes. They interact in form of dialogs, allowing step-by-step data input. Wizards can be used to gather information, for creating specific output or for setting preferences.

Tutorial

The following example serves as a step-by-step tutorial demonstrating the possibilities provided by the toolkit and how to implement a custom wizard based on it. It will consist of three parts, which will be found in most wizards:

  • A welcome dialog
  • Some input forms
  • A final dialog for checking / presenting all input

The toolkit provides two classes for implementing a wizard:

  • Wizard: The main class of any wizard, extending JDialog. Manages the control flow and displays the panels provided. After finishing the input process, it contains the data entered.
  • WizardPanel: An extension of JPanel. Every WizardPanel stands for one step in the dialog process. It may contain everything a JPanel can contain, usually text or input fields.

The welcome dialog

The first step in a dialog system should always be a welcoming screen, describing what needs to be done in the next steps. This way the user can get an overview of the data required or the process he is about to start. So we create a first class extending WizardPanel:

Note: All following sources are excerpts from the example files. For copyright issues look in the according java files.

public class Panel1 extends WizardPanel {
  public Panel1() {
    super(“Welcome”);
    add(new JLabel(“Welcome to the Wizard toolkit demonstration!));
  }
}

The title Welcome is set in the constructor. It is used for the header and for the menu. You might add further welcome information or for example add licence information here.

Theoretically one WizardPanel is sufficient to create the Wizard class, but in the next step we will add the skeleton of the other two panels and then create the Wizard.

Starting the Wizard

public class Panel2 extends WizardPanel {
  public Panel2() {
    super("Options");
  }
}
public class Panel3 extends WizardPanel {
  public Panel3() {
    super(“Finish”);
  }
}
public class WizardExample {
  public static void main(String[] args) {
    WizardPanel[] panels = new WizardPanel[] { new Panel1(),
        new Panel2(), new Panel3() };
    Wizard wizard = new Wizard((JFrame) null, “Wizard Example”, panels);
    wizard.setVisible (true);
    System.out.println(wizard.getProperties());
  }
}

The Wizard class needs three arguments: A parent dialog or frame (may be null), a title and an array with WizardPanels to display. The constructor automatically initializes everything needed for the process and starts after being set visible. When the user finished using the wizard, all data may be gathered via getProperties. With the WizardPanels implemented so far, calling the constructor will open the following dialog:

Welcoming Screen of the Wizard

Welcoming Screen of the Wizard

Menu, header and buttons are created and managed by the toolkit. Only the main panel / content panel needs to be implemented. Back and Finish cannot be selected, as there is no previous WizardPanel and this is not the last WizardPanel. The buttons behaviour may be modified. Selecting Next will display the next dialog, which will be further implemented now.

The options dialog

After the first dialog, the data input forms begin. In this tutorial a WizardPanel with some sample input fields will be implemented, including verification and storage of the data entered. At first, some input components will be added in the panel’s constructor:

public class Panel2 extends WizardPanel {
  private JCheckBox box1, box2;
  private JRadioButton rbutton1, rbutton2;
  private JTextField textField;
 
  public Panel2() {
    super("Options");
 
    box1 = new JCheckBox("Some option");
    box2 = new JCheckBox(
        "If this radio button is selected, you cannot select "next"");
    rbutton1 = new JRadioButton("Select me");
    rbutton2 = new JRadioButton(
        "If this button is selected, clicking "next" will open a Dialog Box.");
    textField = new JTextField(30);
 
    rbutton1.setSelected(true);
 
    setLayout(new GridBagLayout());
 
    GridBagConstraints gc = new GridBagConstraints();
    ButtonGroup rbuttons = new ButtonGroup();
 
    rbuttons.add(rbutton1);
    rbuttons.add(rbutton2);
 
    gc.gridx = gc.gridy = 0;
    gc.anchor = GridBagConstraints.NORTHWEST;
    add(new JLabel("Checkbox options:"), gc);
 
    gc.gridy++;
    add(box1, gc);
 
    // Add other Components
    // ...
  }

The toolkit enables the Back-Button as there is a previous dialog. But we do not want the user to go back, as there is only a welcome screen. On the other hand, we want to disable the forward button if box2 is selected (as described in its text). The toolkit’s control over the buttons may be overridden to implement panel-specific behaviour:

  protected boolean backButtonEnabled() {
    return false;
  }
 
  protected boolean nextButtonEnabled() {
    return !box2.isSelected();
  }

The Wizard toolkit must be specifically told when to refresh the buttons. Therefore it is necessary to add an ActionListener to the component and tell it to refresh the buttons upon selection:

public class Panel2 extends WizardPanel implements ActionListener {
  // ...
 
  public Panel2() {
    // ...
 
    // Refresh buttons upon selecting / deselecting this checkbox
    box2.addActionListener(this);
    box2.setActionCommand("box1");
 
    // ...
  }
 
  public void actionPerformed(ActionEvent e) {
    refreshButtons();
  }
}

If the second radio button is selected, a confirmation box will be opened upon clicking Next. This can be done via verification of the data input. To use this method, all data must be made available to the toolkit. Every information that needs to be stored must be added to a Property object. This data is gathered by the toolkit.

  protected Properties getProperties() {
    Properties properties = new Properties();
 
    properties.setProperty("box1", String.valueOf(box1.isSelected()));
    properties.setProperty("box2", String.valueOf(box2.isSelected()));
    properties.setProperty("rbutton1", String
        .valueOf(rbutton1.isSelected()));
    properties.setProperty("rbutton2", String
        .valueOf(rbutton2.isSelected()));
    properties.setProperty("textfield", textField.getText());
 
    return properties;
  }
 
  protected boolean verifyChanges(Properties properties) {
    if (Boolean.parseBoolean(properties.getProperty("rbutton2"))) {
      return JOptionPane
          .showConfirmDialog(
              this,
              "Are you sure you want to continue with radio button 2 selected?",
              "Please confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION;
    }
 
    return ALLOW;
  }

Every WizardPanel which gathers information must provide the getProperties method to store its data. Every WizardPanel that needs verification must provide the verifyChanges method. This method either returns ALLOW (true) or DENY (false). If DENY is returned, the toolkit will do nothing upon selecting Next or Finish. Note: The properties given as parameter here are not only the properties of this WizardPanel but the properties of all Panels. This way, data can be verified over multiple steps.

Second Dialog of the Wizard

Second Dialog of the Wizard

Confirmation before Advancing to the next Step

Confirmation before Advancing to the next Step

The finish dialog

On the last dialog we want to display all information entered by the user so far. Therefore we cannot use the constructor for initializing the components, as we do not know what the user has entered previously. Even worse, the user may use the back button and change the data. So we need a way to update all components upon displaying the WizardPanel. This is done via setComponents, which is called upon every display of the WizardPanel and is provided all properties so far:

public class Panel3 extends WizardPanel {
  public Panel3() {
    super("Finish");
 
    setLayout(new GridBagLayout());
  }
 
  protected void setComponents(Properties properties) {
    removeAll();
 
    GridBagConstraints gc = new GridBagConstraints();
 
    gc.gridx = gc.gridy = 0;
    add(new JLabel("All required information have been entered."), gc);
 
    gc.gridy++;
    add(new JLabel(" "), gc);
 
    gc.anchor = GridBagConstraints.NORTHWEST;
    gc.gridy++;
    add(new JLabel("Boxes selected:"), gc);
 
    if (Boolean.valueOf(properties.getProperty("box1"))) {
      gc.gridy++;
      add(new JLabel("Checkbox 1"), gc);
    }
 
    if (Boolean.valueOf(properties.getProperty("box2"))) {
      gc.gridy++;
      add(new JLabel("Checkbox 2"), gc);
    }
 
    if (Boolean.valueOf(properties.getProperty("rbutton1"))) {
      gc.gridy++;
      add(new JLabel("Radio button 1"), gc);
    }
 
    if (Boolean.valueOf(properties.getProperty("rbutton2"))) {
      gc.gridy++;
      add(new JLabel("Radio button 2"), gc);
    }
 
    gc.gridy++;
    add(new JLabel(" "), gc);
 
    gc.gridy++;
    add(new JLabel("Text entered: "), gc);
 
    gc.gridy++;
    add(new JLabel(properties.getProperty("textfield")), gc);
  }
}

Final Dialog of the Wizard, showing Summary

Final Dialog of the Wizard, showing Summary

Conclusion

With this step, all implementation for the example is finished, showing all possibilities this framework provides. You may verify data on the fly or after selecting buttons and override the button behaviour. The toolkit lets you specify custom behaviour when necessary and provides standard control flow when applicable, supporting a very easy and structured way to implement Wizards.

Source code (SVN)

Sorry, this outdated information, if you need the source code, download it from the section below.

This software is developed as open source under the general public licence. You may freely use or modify this software in terms specified by the GPL. The source code is accessible via Subversion with the repository lying at:

feanorscurse.dyndns.org/home/svn/toolkit

Please inform me before publishing any code changes.

Download

The current stable version is 0.2. You may download the toolkit as jar-files or access the source. If you are planning to use this toolkit, it would be nice to leave a comment 🙂 .

Wizard Toolkit v0.2

Wizard Toolkit v0.2 with example application

Categories: English, Linux & Programming Tags: ,