<commit_before>"""
This module contains the methods for the ``openxc-obd2scanner`` command line
program.

`main` is executed when ``openxc-obd2scanner`` is run, and all other callables in this
module are internal only.
"""

import argparse

from .common import device_options, configure_logging, select_device
import json

def scan(controller, bus=None):

    # TODO could read the response from the "PIDs supported" requests to see
    # what the vehicle reports that it *should* support.
    print("Beginning sequential scan of all OBD-II PIDs")
    for pid in range(0xd0ff, 0xd101):
        response = controller.create_diagnostic_request(0x7d0, mode=0x22, bus=bus,
                wait_for_first_response=True, pid=pid)
        if response is not None:
            no_response = True
            for item in response[1]:
                if 'success' in item:
                    no_response = False
                    print(("PID 0x%x responded with: %s" % (pid, item)))

            if (no_response == True):
                print(("PID 0x%x did not respond" % pid))

def parse_options():
    parser = argparse.ArgumentParser(description="Send requests for all "
                "OBD-II PIDs sequentially to see what actually responds",
            parents=[device_options()])
    parser.add_argument("--bus")

    return parser.parse_args()

def main():
    configure_logging()
    arguments = parse_options()

    controller_class, controller_kwargs = select_device(arguments)
    controller = controller_class(**controller_kwargs)
    controller.start()

    scan(controller, arguments.bus)
<commit_msg>fix for loop for obd2scanner.<commit_after>"""
This module contains the methods for the ``openxc-obd2scanner`` command line
program.

`main` is executed when ``openxc-obd2scanner`` is run, and all other callables in this
module are internal only.
"""

import argparse

from .common import device_options, configure_logging, select_device
import json

def scan(controller, bus=None):

    # TODO could read the response from the "PIDs supported" requests to see
    # what the vehicle reports that it *should* support.
    print("Beginning sequential scan of all OBD-II PIDs")
    for pid in range(0, 0x88):
            response = controller.create_diagnostic_request(0x7df, mode=0x1, bus=bus,
                    wait_for_first_response=True, pid=pid)
        if response is not None:
            no_response = True
            for item in response[1]:
                if 'success' in item:
                    no_response = False
                    print(("PID 0x%x responded with: %s" % (pid, item)))

            if (no_response == True):
                print(("PID 0x%x did not respond" % pid))

def parse_options():
    parser = argparse.ArgumentParser(description="Send requests for all "
                "OBD-II PIDs sequentially to see what actually responds",
            parents=[device_options()])
    parser.add_argument("--bus")

    return parser.parse_args()

def main():
    configure_logging()
    arguments = parse_options()

    controller_class, controller_kwargs = select_device(arguments)
    controller = controller_class(**controller_kwargs)
    controller.start()

    scan(controller, arguments.bus)
<|endoftext|>


<commit_before>import numpy
from numpy import unique
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.model_selection import cross_val_predict

class ConsciousClassifier():
    def __init__(self, inner, columns=None, weight=0, cv=10):
        self.inner = inner
        self.columns = columns
        self.cv = cv
        self.weight = weight

    def fit(self, X, Y):
        if self.columns is None:
            self.columns = set(X.columns.values)
        else:
            X = X[list(self.columns)]
        self.inner.fit(X, Y)
        yhat = cross_val_predict(self.inner, X, Y, cv=self.cv)
        self.recalls = {}
        self.precisions = {}
        if not self.weight:
            self.weight = accuracy_score(Y, yhat)
        for label in unique(Y):
            Y_binary = Y == label
            P_binary = yhat == label
            self.recalls[label] = recall_score(Y_binary, P_binary)
            self.precisions[label] = precision_score(Y_binary, P_binary)
        return self

    def predict(self, X, **kwargs):
        return self.inner.predict(X=X[list(self.columns)], **kwargs)

    def predict_proba(self, X, **kwargs):
        # if getattr(self.inner, 'predict_proba') is not None:
        #    return self.inner.predict_proba(X=X[list(self.columns)], **kwargs)
        out = []
        recall = 0
        for pred, rec in self.recalls.items():
            recall += rec
        for pred in self.predict(X):
            p = {}
            for prec_key in self.precisions:
                if pred == prec_key:
                    p[prec_key] = self.precisions[pred]
                else:
                    p[prec_key] = (1 - self.precisions[pred]) * (1 - self.recalls[prec_key]) / (
                        recall - (1 - self.recalls[pred]))
            out.append(list(p.values()))
        return out

    def supports(self, X):
        return set(X.columns.values).issuperset(self.columns)

class ProbabilityEnsemble(BaseEstimator):
    def __init__(self, classifiers, cv=10):
        self.classifiers = classifiers
        self.cv = cv

    def set_weights(self, weights):
        for i, weight in enumerate(weights):
            self.classifiers[i].weight = weight

    def fit(self, X, Y):
        for classifier in self.classifiers:
            classifier.fit(X, Y)
        return self

    def predict(self, X):
        combined = self.predict_proba(X)
        out = []
        for case in combined:
            out.append(numpy.argmax(case))
        return out

    def predict_proba(self, X):
        predictions = []
        weights = [cls.weight for cls in self.classifiers]
        for classifier in self.classifiers:
            if classifier.supports(X):
                predictions.append(classifier.predict_proba(X))
        combined = []
        for classifier in range(len(predictions)):
            for case in range(len(predictions[classifier])):
                predictions_for_x = weights[classifier] * numpy.array(predictions[classifier][case])
                if case < len(combined):
                    combined[case] = numpy.add(combined[case], predictions_for_x)
                else:
                    combined.append(predictions_for_x)
        combined = numpy.array(combined)
        return combined / combined.sum(axis=1)[:, numpy.newaxis]
<commit_msg>Experimental configuration<commit_after>import numpy
from numpy import unique
from sklearn.base import BaseEstimator
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.model_selection import cross_val_predict

class ConsciousClassifier():
    def __init__(self, inner, columns=None, weight=0, cv=10):
        self.inner = inner
        self.columns = columns
        self.cv = cv
        self.weight = weight

    def fit(self, X, Y):
        if self.columns is None:
            self.columns = set(X.columns.values)
        else:
            X = X[list(self.columns)]
        self.inner.fit(X, Y)
        yhat = cross_val_predict(self.inner, X, Y, cv=self.cv)
        self.recalls = {}
        self.precisions = {}
        if not self.weight:
            self.weight = accuracy_score(Y, yhat)
        for label in unique(Y):
            Y_binary = Y == label
            P_binary = yhat == label
            self.recalls[label] = recall_score(Y_binary, P_binary)
            self.precisions[label] = precision_score(Y_binary, P_binary)
        return self

    def predict(self, X, **kwargs):
        return self.inner.predict(X=X[list(self.columns)], **kwargs)

    def predict_proba(self, X, **kwargs):
        # if getattr(self.inner, 'predict_proba') is not None:
        #    return self.inner.predict_proba(X=X[list(self.columns)], **kwargs)
        out = []
        recall = 0
        for pred, rec in self.recalls.items():
            recall += rec
        for pred in self.predict(X):
            p = {}
            for prec_key in self.precisions:
                if pred == prec_key:
                    p[prec_key] = self.precisions[pred]
                else:
                    p[prec_key] = (1 - self.precisions[pred]) * (1 - self.recalls[prec_key]) / (recall - (1 - self.recalls[pred]))
            out.append(list(p.values()))
        return out

    def supports(self, X):
        return set(X.columns.values).issuperset(self.columns)

class ProbabilityEnsemble(BaseEstimator):
    def __init__(self, classifiers, cv=10):
        self.classifiers = classifiers
        self.cv = cv

    def set_weights(self, weights):
        for i, weight in enumerate(weights):
            self.classifiers[i].weight = weight

    def fit(self, X, Y):
        for classifier in self.classifiers:
            classifier.fit(X, Y)
        return self

    def predict(self, X):
        combined = self.predict_proba(X)
        out = []
        for case in combined:
            out.append(numpy.argmax(case))
        return out

    def predict_proba(self, X):
        predictions = []
        weights = [cls.weight for cls in self.classifiers]
        for classifier in self.classifiers:
            if classifier.supports(X):
                predictions.append(classifier.predict_proba(X))
        combined = []
        for classifier in range(len(predictions)):
            for case in range(len(predictions[classifier])):
                predictions_for_x = weights[classifier] * numpy.array(predictions[classifier][case])
                if case < len(combined):
                    combined[case] = numpy.add(combined[case], predictions_for_x)
                else:
                    combined.append(predictions_for_x)
        combined = numpy.array(combined)
        return combined / combined.sum(axis=1)[:, numpy.newaxis]
<|endoftext|>


<commit_before># coding=utf8
###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###

import urllib2
from BeautifulSoup import BeautifulSoup
import re
import string
import datetime
import time

import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring

_ = PluginInternationalization('Scores')

@internationalizeDocstring
class Scores(callbacks.Plugin):
    """Add the help for "@plugin help Scores" here
    This should describe *how* to use this plugin."""
    threaded = True

    def _validate(self, date, format):
        """Return true or false for valid date based on format."""
        try:
            datetime.datetime.strptime(date, format) # format = "%m/%d/%Y"
            return True
        except ValueError:
            return False

    def _b64decode(self, string):
        """Returns base64 encoded string."""
        import base64
        return base64.b64decode(string)

    def _dateFmt(self, string):
        """Return a short date string from a full date string."""
        return time.strftime('%m/%d', time.strptime(string, '%A, %B %d'))

    def _fetch(self, optargs):
        """Internal function to fetch what we need."""

        url = self._b64decode('aHR0cDovL20uZXNwbi5nby5jb20v') + '%s&wjb=' % optargs

        #self.log.info(url)

        try:
            req = urllib2.Request(url)
            html = (urllib2.urlopen(req)).read()
            return html
        except:
            return None

    ###########################
    # start public functions. #
    ###########################

    def cfb(self, irc, msg, args, optconf):
        """<conference>
        Display CFB scores.
        """

        validconfs = { 'top25':'999', 'acc':'1', 'bigeast':'10', 'bigsouth':'40', 'big10':'5', 'big12':'4',
                'bigsky':'20', 'caa':'48', 'c-usa':'12', 'independent':'18',
                'ivy':'22', 'mac':'15', 'meac':'24', 'mvc':'21', 'i-a':'80',
                'i-aa':'81', 'pac12':'9', 'southern':'29', 'sec':'8',
                'sunbelt':'37', 'wac':'16'
        }

        if optconf:
            optconf = optconf.lower()
            if optconf not in validconfs:
                irc.reply("Conference must be one of: %s" % validconfs.keys())
                return

        url = 'ncf/scoreboard?'
        if not optconf:
            url += 'groupId=%s' % validconfs['top25']
        else:
            url += 'groupId=%s' % validconfs[optconf]

        html = self._fetch(url)

        if html == 'None':
            irc.reply("Cannot fetch NFL scores.")
            return

        html = html.replace(', ESPN','').replace(', BIG10','').replace(', ABC','').replace(', FOX','')
        html = html.replace(', CBS','').replace(', FX','').replace(', CSTV','').replace(', ESP2','').replace(', ESPU','')

        soup = BeautifulSoup(html)
        divs = soup.findAll('div', attrs={'id':re.compile('^game.*?')})

        append_list = []

        for div in divs:
            rows = div.findAll('a')
            for row in rows:
                game = row.text.strip()

                # rz/pos display
                if row.findParent('div').findParent('div').find('b', attrs={'class':'red'}):
                    game = game.replace('*', ircutils.mircColor('<RZ>','red'))
                else:
                    game = game.replace('*', ircutils.mircColor('<>','red'))

                if " at " not in game:
                    gamesplit = game.split(' ')
                    awayteam = gamesplit[0]
                    awayscore = gamesplit[1]
                    hometeam = gamesplit[2]
                    homescore = gamesplit[3]
                    time = gamesplit[4:]
                    time = " ".join(time)

                    if int(awayscore) > int(homescore):
                        awayteam = ircutils.bold(awayteam)
                        awayscore = ircutils.bold(awayscore)
                    elif int(homescore) > int(awayscore):
                        hometeam = ircutils.bold(hometeam)
                        homescore = ircutils.bold(homescore)

                    game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " " + time)

                append_list.append(game)

        allgames = string.join([item for item in append_list], " | ")

        irc.reply(allgames)

    cfb = wrap(cfb, [optional('somethingWithoutSpaces')])

    def nfl(self, irc, msg, args):
        """
        Display NFL scores.
        """

        url = 'nfl/scoreboard?'
        html = self._fetch(url)

        if html == 'None':
            irc.reply("Cannot fetch NFL scores.")
            return

        html = html.replace('class="ind alt', 'class="ind')

        if "No games" in html:
            irc.reply("No games on today.")
            return

        soup = BeautifulSoup(html)
        divs = soup.findAll('div', attrs={'id':re.compile('game.*?')})

        object_list = []

        for div in divs:
            rows = div.findAll('a')
            for row in rows:
                game = row.text.strip()
                game = game.replace(', NFL','').replace(', ESPN', '').replace(', FOX','').replace(', CBS','').replace(', NBC','')
                if row.findParent('div').findParent('div').find('b', attrs={'class':'red'}):
                    game = game.replace('*', ircutils.mircColor('<RZ>','red'))
                else:
                    game = game.replace('*', ircutils.mircColor('<>','red'))
                game = game.replace('Half', ircutils.mircColor('H', 'yellow'))
                game = game.replace('Final', ircutils.mircColor('F', 'red'))
                game = game.replace('1st', ircutils.mircColor('1st', 'green'))
                game = game.replace('2nd', ircutils.mircColor('2nd', 'green'))
                game = game.replace('3rd', ircutils.mircColor('3rd', 'green'))
                game = game.replace('4th', ircutils.mircColor('4th', 'green'))

                if " at " not in game:
                    gamesplit = game.split(' ')
                    awayteam = gamesplit[0]
                    awayscore = gamesplit[1]
                    hometeam = gamesplit[2]
                    homescore = gamesplit[3]
                    time = gamesplit[4:]
                    time = " ".join(time)

                    # bold the leader
                    if int(awayscore) > int(homescore):
                        awayteam = ircutils.bold(awayteam)
                        awayscore = ircutils.bold(awayscore)
                    elif int(homescore) > int(awayscore):
                        hometeam = ircutils.bold(hometeam)
                        homescore = ircutils.bold(homescore)

                    game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " " + time)

                object_list.append(game)

        allgames = string.join([item for item in object_list], " | ")

        irc.reply(allgames)

    nfl = wrap(nfl)

    def mlb(self, irc, msg, args, optdate):
        """
        Display MLB scores.
        """

        if optdate:
            testdate = self._validate(optdate, '%Y%m%d')
            if not testdate:
                irc.reply("Invalid year. Must be YYYYmmdd.")
                return
        #else:
        #    optdate = datetime.datetime.now().strftime("%Y%m%d")

        url = 'mlb/scoreboard?'

        if optdate:
            url += 'date=%s' % optdate

        html = self._fetch(url)
        if html == 'None':
            irc.reply("Cannot fetch mlb scores.")
            return

        html = html.replace('class="ind alt', 'class="ind')

        if "No games" in html:
            irc.reply("No games on today.")
            return

        soup = BeautifulSoup(html)
        rows = soup.findAll('div', attrs={'class':'ind', 'style':'white-space: nowrap;'})

        object_list = []

        for row in rows:
            game = row.find('a').text.strip()
            game = game.replace('SDG', 'SD').replace('SFO', 'SF').replace('TAM', 'TB').replace('WAS', 'WSH').replace('KAN', 'KC').replace('CHW', 'CWS') # teams.
            game = game.replace(', ESPN', '').replace(', MLBN', '').replace(', TBS', '').replace(' PM','').replace(' AM','').replace(', ESP2', '')
            game = game.replace('Del:', ircutils.mircColor('DLY', 'yellow')).replace('PPD',ircutils.mircColor('PPD', 'yellow')).replace('Del', ircutils.mircColor('DLY', 'yellow')

            if " at " not in game:
                game = game.replace('Bot ','B').replace('Top ','T').replace('Mid ','M').replace('End ','E') # innings
                game = game.replace('st','').replace('th','').replace('rd','').replace('nd','') # abbr
                gamesplit = game.split(' ')
                awayteam = gamesplit[0]
                awayscore = gamesplit[1]
                hometeam = gamesplit[2]
                homescore = gamesplit[3]
                innings = gamesplit[4]

                if int(awayscore) > int(homescore):
                    awayteam = ircutils.bold(awayteam)
                    awayscore = ircutils.bold(awayscore)
                elif int(homescore) > int(awayscore):
                    hometeam = ircutils.bold(hometeam)
                    homescore = ircutils.bold(homescore)

                game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " ")
                if innings.startswith('F'):
                    innings = innings.replace('Final','F')
                    game += ircutils.mircColor(innings, 'red')
                else:
                    game += ircutils.mircColor(innings, 'green')

            object_list.append(game)

        allgames = string.join([item for item in object_list], " | ")

        irc.reply(allgames)

    mlb = wrap(mlb, [optional('somethingWithoutSpaces')])

Class = Scores

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=250:
<commit_msg>Missed a closing )<commit_after># coding=utf8
###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###

import urllib2
from BeautifulSoup import BeautifulSoup
import re
import string
import datetime
import time

import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring

_ = PluginInternationalization('Scores')

@internationalizeDocstring
class Scores(callbacks.Plugin):
    """Add the help for "@plugin help Scores" here
    This should describe *how* to use this plugin."""
    threaded = True

    def _validate(self, date, format):
        """Return true or false for valid date based on format."""
        try:
            datetime.datetime.strptime(date, format) # format = "%m/%d/%Y"
            return True
        except ValueError:
            return False

    def _b64decode(self, string):
        """Returns base64 encoded string."""
        import base64
        return base64.b64decode(string)

    def _dateFmt(self, string):
        """Return a short date string from a full date string."""
        return time.strftime('%m/%d', time.strptime(string, '%A, %B %d'))

    def _fetch(self, optargs):
        """Internal function to fetch what we need."""

        url = self._b64decode('aHR0cDovL20uZXNwbi5nby5jb20v') + '%s&wjb=' % optargs

        #self.log.info(url)

        try:
            req = urllib2.Request(url)
            html = (urllib2.urlopen(req)).read()
            return html
        except:
            return None

    ###########################
    # start public functions. #
    ###########################

    def cfb(self, irc, msg, args, optconf):
        """<conference>
        Display CFB scores.
        """

        validconfs = { 'top25':'999', 'acc':'1', 'bigeast':'10', 'bigsouth':'40', 'big10':'5', 'big12':'4',
                'bigsky':'20', 'caa':'48', 'c-usa':'12', 'independent':'18',
                'ivy':'22', 'mac':'15', 'meac':'24', 'mvc':'21', 'i-a':'80',
                'i-aa':'81', 'pac12':'9', 'southern':'29', 'sec':'8',
                'sunbelt':'37', 'wac':'16'
        }

        if optconf:
            optconf = optconf.lower()
            if optconf not in validconfs:
                irc.reply("Conference must be one of: %s" % validconfs.keys())
                return

        url = 'ncf/scoreboard?'
        if not optconf:
            url += 'groupId=%s' % validconfs['top25']
        else:
            url += 'groupId=%s' % validconfs[optconf]

        html = self._fetch(url)

        if html == 'None':
            irc.reply("Cannot fetch NFL scores.")
            return

        html = html.replace(', ESPN','').replace(', BIG10','').replace(', ABC','').replace(', FOX','')
        html = html.replace(', CBS','').replace(', FX','').replace(', CSTV','').replace(', ESP2','').replace(', ESPU','')

        soup = BeautifulSoup(html)
        divs = soup.findAll('div', attrs={'id':re.compile('^game.*?')})

        append_list = []

        for div in divs:
            rows = div.findAll('a')
            for row in rows:
                game = row.text.strip()

                # rz/pos display
                if row.findParent('div').findParent('div').find('b', attrs={'class':'red'}):
                    game = game.replace('*', ircutils.mircColor('<RZ>','red'))
                else:
                    game = game.replace('*', ircutils.mircColor('<>','red'))

                if " at " not in game:
                    gamesplit = game.split(' ')
                    awayteam = gamesplit[0]
                    awayscore = gamesplit[1]
                    hometeam = gamesplit[2]
                    homescore = gamesplit[3]
                    time = gamesplit[4:]
                    time = " ".join(time)

                    if int(awayscore) > int(homescore):
                        awayteam = ircutils.bold(awayteam)
                        awayscore = ircutils.bold(awayscore)
                    elif int(homescore) > int(awayscore):
                        hometeam = ircutils.bold(hometeam)
                        homescore = ircutils.bold(homescore)

                    game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " " + time)

                append_list.append(game)

        allgames = string.join([item for item in append_list], " | ")

        irc.reply(allgames)

    cfb = wrap(cfb, [optional('somethingWithoutSpaces')])

    def nfl(self, irc, msg, args):
        """
        Display NFL scores.
        """

        url = 'nfl/scoreboard?'
        html = self._fetch(url)

        if html == 'None':
            irc.reply("Cannot fetch NFL scores.")
            return

        html = html.replace('class="ind alt', 'class="ind')

        if "No games" in html:
            irc.reply("No games on today.")
            return

        soup = BeautifulSoup(html)
        divs = soup.findAll('div', attrs={'id':re.compile('game.*?')})

        object_list = []

        for div in divs:
            rows = div.findAll('a')
            for row in rows:
                game = row.text.strip()
                game = game.replace(', NFL','').replace(', ESPN', '').replace(', FOX','').replace(', CBS','').replace(', NBC','')
                if row.findParent('div').findParent('div').find('b', attrs={'class':'red'}):
                    game = game.replace('*', ircutils.mircColor('<RZ>','red'))
                else:
                    game = game.replace('*', ircutils.mircColor('<>','red'))
                game = game.replace('Half', ircutils.mircColor('H', 'yellow'))
                game = game.replace('Final', ircutils.mircColor('F', 'red'))
                game = game.replace('1st', ircutils.mircColor('1st', 'green'))
                game = game.replace('2nd', ircutils.mircColor('2nd', 'green'))
                game = game.replace('3rd', ircutils.mircColor('3rd', 'green'))
                game = game.replace('4th', ircutils.mircColor('4th', 'green'))

                if " at " not in game:
                    gamesplit = game.split(' ')
                    awayteam = gamesplit[0]
                    awayscore = gamesplit[1]
                    hometeam = gamesplit[2]
                    homescore = gamesplit[3]
                    time = gamesplit[4:]
                    time = " ".join(time)

                    # bold the leader
                    if int(awayscore) > int(homescore):
                        awayteam = ircutils.bold(awayteam)
                        awayscore = ircutils.bold(awayscore)
                    elif int(homescore) > int(awayscore):
                        hometeam = ircutils.bold(hometeam)
                        homescore = ircutils.bold(homescore)

                    game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " " + time)

                object_list.append(game)

        allgames = string.join([item for item in object_list], " | ")

        irc.reply(allgames)

    nfl = wrap(nfl)

    def mlb(self, irc, msg, args, optdate):
        """
        Display MLB scores.
        """

        if optdate:
            testdate = self._validate(optdate, '%Y%m%d')
            if not testdate:
                irc.reply("Invalid year. Must be YYYYmmdd.")
                return
        #else:
        #    optdate = datetime.datetime.now().strftime("%Y%m%d")

        url = 'mlb/scoreboard?'

        if optdate:
            url += 'date=%s' % optdate

        html = self._fetch(url)
        if html == 'None':
            irc.reply("Cannot fetch mlb scores.")
            return

        html = html.replace('class="ind alt', 'class="ind')

        if "No games" in html:
            irc.reply("No games on today.")
            return

        soup = BeautifulSoup(html)
        rows = soup.findAll('div', attrs={'class':'ind', 'style':'white-space: nowrap;'})

        object_list = []

        for row in rows:
            game = row.find('a').text.strip()
            game = game.replace('SDG', 'SD').replace('SFO', 'SF').replace('TAM', 'TB').replace('WAS', 'WSH').replace('KAN', 'KC').replace('CHW', 'CWS') # teams.
            game = game.replace(', ESPN', '').replace(', MLBN', '').replace(', TBS', '').replace(' PM','').replace(' AM','').replace(', ESP2', '')
            game = game.replace('Del:', ircutils.mircColor('DLY', 'yellow')).replace('PPD',ircutils.mircColor('PPD', 'yellow')).replace('Del', ircutils.mircColor('DLY', 'yellow'))

            if " at " not in game:
                game = game.replace('Bot ','B').replace('Top ','T').replace('Mid ','M').replace('End ','E') # innings
                game = game.replace('st','').replace('th','').replace('rd','').replace('nd','') # abbr
                gamesplit = game.split(' ')
                awayteam = gamesplit[0]
                awayscore = gamesplit[1]
                hometeam = gamesplit[2]
                homescore = gamesplit[3]
                innings = gamesplit[4]

                if int(awayscore) > int(homescore):
                    awayteam = ircutils.bold(awayteam)
                    awayscore = ircutils.bold(awayscore)
                elif int(homescore) > int(awayscore):
                    hometeam = ircutils.bold(hometeam)
                    homescore = ircutils.bold(homescore)

                game = str(awayteam + " " + awayscore + " " + hometeam + " " + homescore + " ")
                if innings.startswith('F'):
                    innings = innings.replace('Final','F')
                    game += ircutils.mircColor(innings, 'red')
                else:
                    game += ircutils.mircColor(innings, 'green')

            object_list.append(game)

        allgames = string.join([item for item in object_list], " | ")

        irc.reply(allgames)

    mlb = wrap(mlb, [optional('somethingWithoutSpaces')])

Class = Scores

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=250:
<|endoftext|>


<commit_before>import os
import re
import plistlib
from timeit import default_timer as timer

import sublime
import sublime_plugin

__version__ = "0.12.0"
__version_info__ = (0, 12, 0)

if os.getenv('SUBLIME_COLOR_SCHEME_UNIT_DEBUG'):
    def debug_message(message):
        print('DEBUG color_scheme_unit: %s' % str(message))
else:
    def debug_message(message):
        pass

COLOR_TEST_PARAMS_COMPILED_PATTERN = re.compile('^(?:(?:\<\?php )?(?://|#|\/\*|\<\!--)\s*)?COLOR(?P<keyword> SCHEME)? TEST "(?P<color_scheme>[^"]+)" "(?P<syntax_name>[^"]+)"(?:\s*(?:--\>|\?\>|\*\/))?\n')
COLOR_TEST_ASSERTION_COMPILED_PATTERN = re.compile('^(//|#|\/\*|\<\!--)\s*(?P<repeat>\^+)(?: fg=(?P<fg>[^ ]+)?)?(?: bg=(?P<bg>[^ ]+)?)?(?: fs=(?P<fs>[^=]*)?)?$')

class _color_scheme_unit_test_view_set_content(sublime_plugin.TextCommand):

    """
    Helper view command for TestView#set_content()
    TODO is there a way to avoid needing this superfluous text command?
    """

    def run(self, edit, content):
        self.view.erase(edit, sublime.Region(0, self.view.size()))
        self.view.insert(edit, 0, content)

class TestView():
    def __init__(self, name, window):
        self.name = name + '_test_view'
        self.window = window

    def setUp(self):
        self.view = self.window.create_output_panel(self.name, unlisted=True)

    def tearDown(self):
        if self.view:
            self.view.close()

    def set_content(self, content):
        self.view.run_command('_color_scheme_unit_test_view_set_content', {
            'content': content
        })

    def get_content(self):
        return self.view.substr(sublime.Region(0, self.view.size()))

class TestOutputPanel():
    def __init__(self, name, window):
        self.view = window.create_output_panel(name)

        settings = self.view.settings()
        settings.set('result_file_regex', '^(.+):([0-9]+):([0-9]+)$')
        settings.set('word_wrap', False)
        settings.set('line_numbers', False)
        settings.set('gutter', False)
        settings.set('rulers', [])
        settings.set('scroll_past_end', False)

        self.view.assign_syntax('Packages/color_scheme_unit/test_output_panel.sublime-syntax')

        # Assign panel with color scheme of active view
        active_view = window.active_view()
        if active_view:
            active_color_scheme = active_view.settings().get('color_scheme')
            if active_color_scheme:
                settings.set('color_scheme', active_color_scheme)

        window.run_command('show_panel', { 'panel': 'output.' + name })

    def write(self, text):
        self.view.run_command('append', { 'characters': text, 'scroll_to_end': True })

class ColorSchemeStyle():

    def __init__(self, view):
        self.view = view

        color_scheme = self.view.settings().get('color_scheme')
        color_scheme_resource = sublime.load_resource(color_scheme)
        color_scheme_plist = plistlib.readPlistFromBytes(bytes(color_scheme_resource, 'UTF-8'))
        self.color_scheme_plist_settings = color_scheme_plist['settings']

        self.default_style = dict()
        for color_scheme_plist_dict in self.color_scheme_plist_settings:
            if 'scope' not in color_scheme_plist_dict:
                self.default_style.update(color_scheme_plist_dict['settings'])

    def at_point(self, point):
        scope = self.view.scope_name(point).strip()

        last_selector_score = -1
        style = self.default_style.copy()
        for color_scheme_definition in self.color_scheme_plist_settings:
            if 'scope' in color_scheme_definition:
                score = sublime.score_selector(scope, color_scheme_definition['scope'])
                if score and score >= last_selector_score:
                    last_selector_score = score
                    style.update(color_scheme_definition['settings'])

        return style

def run_color_scheme_test(test, window, output):
    debug_message('running color scheme test: %s' % test)

    error = False
    failures = []
    assertion_count = 0

    test_view = TestView('color_scheme_unit', window)
    test_view.setUp()

    try:
        test_content = sublime.load_resource(test)

        color_test_params = COLOR_TEST_PARAMS_COMPILED_PATTERN.match(test_content)

        # TODO remove this deprecated behaviour in v1.0.0
        if not color_test_params.group('keyword'):
            output.write("\n")
            output.write("DEPRECATED: \"COLOR TEST\" in %s:0\n" % test)
            output.write("  Use 'COLOR SCHEME TEST ...' instead; see https://github.com/gerardroche/sublime_color_scheme_unit/issues/7\n\n")

        if not color_test_params:
            error = {
                'message': 'Invalid color test',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        syntaxes = sublime.find_resources(color_test_params.group('syntax_name') + '.sublime-syntax')

        if len(syntaxes) > 1:
            error = {
                'message': 'Too many syntaxes found',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        if len(syntaxes) is not 1:
            error = {
                'message': 'Syntaxes not found',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        # TODO remove this deprecated behaviour in v1.0.0
        color_scheme = 'Packages/' + color_test_params.group('color_scheme')
        if 'Packages/Packages/' in color_scheme:
            color_scheme = re.sub('Packages/Packages/', 'Packages/', color_scheme)
            output.write("\n")
            output.write("DEPRECATED: \"Packages/...\" in %s:0\n" % test)
            output.write(" Rename '%s'\n     to          '%s'\n" % (color_scheme, color_scheme[9:]))
            output.write(" See https://github.com/gerardroche/sublime_color_scheme_unit/issues/6\n\n")

        test_view.view.settings().set('color_scheme', color_scheme)
        test_view.view.assign_syntax(syntaxes[0])
        test_view.set_content(test_content)

        color_scheme_style = ColorSchemeStyle(test_view.view)

        consecutive_test_lines = 0
        for line_number, line in enumerate(test_content.splitlines()):
            assertion_params = COLOR_TEST_ASSERTION_COMPILED_PATTERN.match(line.lower().rstrip(' -->').rstrip(' */'))
            if not assertion_params:
                consecutive_test_lines = 0
                continue

            consecutive_test_lines += 1

            assertion = assertion_params.group(0)
            assertion_row = line_number - consecutive_test_lines
            assertion_begin = line.find('^')
            assertion_end = assertion_begin + len(assertion_params.group('repeat'))
            expected_styles = {}
            if assertion_params.group('fg') is not None:
                expected_styles['foreground'] = assertion_params.group('fg')
            if assertion_params.group('bg') is not None:
                expected_styles['background'] = assertion_params.group('bg')
            if assertion_params.group('fs') is not None:
                expected_styles['fontStyle'] = assertion_params.group('fs')

            for col in range(assertion_begin, assertion_end):
                assertion_count += 1
                assertion_point = test_view.view.text_point(assertion_row, col)
                actual_styles_at_point = color_scheme_style.at_point(assertion_point)

                actual_styles = {}
                for style in expected_styles:
                    if style in actual_styles_at_point:
                        if actual_styles_at_point[style]:
                            actual_styles[style] = actual_styles_at_point[style].lower()
                        else:
                            actual_styles[style] = actual_styles_at_point[style]
                    else:
                        actual_styles[style] = ''

                progress_character='.'
                if actual_styles != expected_styles:
                    progress_character='F'

                    failure_trace = {
                        'assertion': assertion,
                        'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                        'row': assertion_row + 1,
                        'col': col + 1,
                        'actual': actual_styles,
                        'expected': expected_styles,
                    }

                    debug_message('----- Assertion FAILED! -----')
                    debug_message('Trace: %s' % str(failure_trace))

                    failures.append(failure_trace)

                output.write(progress_character)
                if assertion_count % 80 == 0:
                    output.write("\n")

        output.write("\n")
    except Exception as e:
        test_view.tearDown()
        if not error:
            output.write(str(e))
            output.write("\n")

    test_view.tearDown()

    return {
        'error': error,
        'failures': failures,
        'assertions': assertion_count
    }

class RunColorSchemeTestCommand(sublime_plugin.WindowCommand):

    def run(self):
        if self.is_enabled():
            self.window.run_command(
                'run_color_scheme_tests', {
                    'test_file': self.test_file
                }
            )

    def is_enabled(self):
        view = self.window.active_view()
        if not view:
            return False

        file_name = view.file_name()
        if not file_name:
            return False

        if not re.match('^.+/color_scheme_test.*\.[a-z]+$', file_name):
            return False

        self.test_file = file_name

        return True

class RunColorSchemeTestsCommand(sublime_plugin.WindowCommand):

    def run(self, test_file = None):
        sublime.set_timeout_async(lambda: self.run_async(test_file))

    def run_async(self, test_file):
        view = self.window.active_view()
        if not view:
            return

        file_name = view.file_name()
        if not file_name:
            return

        tests = []
        for resource in sublime.find_resources('color_scheme_test*'):
            package = resource.split(os.sep)[1]
            package_path = os.path.join(sublime.packages_path(), package)
            if file_name.startswith(package_path):
                tests_package_name = package
                if test_file:
                    resource_file = os.path.join(os.path.dirname(sublime.packages_path()), resource)
                    if test_file == resource_file:
                        tests.append(resource)
                else:
                    tests.append(resource)

        if not len(tests):
            return

        output = TestOutputPanel('color_scheme_unit', self.window)
        output.write("ColorSchemeUnit %s\n\n" % __version__)
        output.write("Runtime: %s build %s\n" % (sublime.platform(), sublime.version()))
        output.write("Package: %s\n" % tests_package_name)
        if test_file:
            output.write("File:    %s\n" % test_file)
        output.write("\n")

        errors = []
        failures = []
        total_assertions = 0

        start = timer()
        for test in tests:
            test_result = run_color_scheme_test(test, self.window, output)
            if test_result['error']:
                errors += [test_result['error']]
            failures += test_result['failures']
            total_assertions += test_result['assertions']
        elapsed = timer() - start
        output.write("\n")

        output.write("Time: %.2f secs\n" % (elapsed))
        output.write("\n")

        if len(errors) > 0:
            output.write("There were %s errors:\n" % len(errors))
            output.write("\n")
            for i, error in enumerate(errors, start=1):
                output.write("%d) %s\n" % (i, error['message']))
                output.write("%s:%d:%d\n" % (error['file'], error['row'], error['col']))
                output.write("\n")

        if len(failures) > 0:
            output.write("There were %s failures:\n\n" % len(failures))
            for i, failure in enumerate(failures, start=1):
                output.write("%d) %s\n" % (i, failure['assertion']))
                output.write("Failed asserting %s equals %s\n" % (str(failure['actual']), str(failure['expected'])))
                # TODO failure diff
                # output.write("--- Expected\n")
                # output.write("+++ Actual\n")
                # output.write("@@ @@\n")
                # output.write("{{diff}}\n\n")
                output.write("%s:%d:%d\n" % (failure['file'], failure['row'], failure['col']))
                output.write("\n")

        if len(errors) == 0 and len(failures) == 0:
            output.write("OK (%d tests, %d assertions)\n" % (len(tests), total_assertions))
        else:
            output.write("FAILURES!\n")
            output.write("Tests: %d, Assertions: %d" % (len(tests), total_assertions))
            if len(errors) > 0:
                output.write(", Errors: %d" % (len(errors)))
            output.write(", Failures: %d" % (len(failures)))
            output.write(".")
            output.write("\n")

if os.getenv('SUBLIME_COLOR_SCHEME_UNIT_DEBUG'):

    def copy(view, text):
        sublime.set_clipboard(text)
        view.hide_popup()
        sublime.status_message('Scope name copied to clipboard')

    class ShowScopeNameAndStylesCommand(sublime_plugin.TextCommand):

        def run(self, edit):
            scope = self.view.scope_name(self.view.sel()[-1].b)
            style = ColorSchemeStyle(self.view).at_point(self.view.sel()[-1].b)

            style_html = '
'
            if 'foreground' in style:
                style_html += "
foreground: {0}
".format(style['foreground'])
                del style['foreground']
            if 'background' in style:
                style_html += "
background: {0}
".format(style['background'])
                del style['background']
            if 'fontStyle' in style:
                style_html += "
fontStyle: {0}
".format(style['fontStyle'])
                del style['fontStyle']
            for x in sorted(style):
                style_html += "
{0}: {1}
".format(x, style[x])
            style_html += '
';

            html = """

%s

                    Copy
                    %s

            """ % (scope.replace(' ', '
'), scope.rstrip(), style_html)

            self.view.show_popup(html, max_width=512, on_navigate=lambda x: copy(self.view, x))

    class SetColorSchemeOnLoad(sublime_plugin.EventListener):

        def on_load_async(self, view):
            file_name = view.file_name()
            if file_name:
                if not re.match('.*color_scheme_test[a-zA-Z0-9_]+.[a-zA-Z0-9]+$', file_name):
                    return

            color_scheme_test = COLOR_TEST_PARAMS_COMPILED_PATTERN.match(view.substr(sublime.Region(0, view.size())))
            if color_scheme_test:
                view.settings().set('color_scheme', color_scheme_test.group('color_scheme'))
<commit_msg>:sparkles:<commit_after>
__version__ = "0.12.0"
__version_info__ = (0, 12, 0)

import os
import re
import plistlib
from timeit import default_timer as timer

import sublime
import sublime_plugin

if os.getenv('SUBLIME_COLOR_SCHEME_UNIT_DEBUG'):
    def debug_message(message):
        print('DEBUG color_scheme_unit: %s' % str(message))
else:
    def debug_message(message):
        pass

COLOR_TEST_PARAMS_COMPILED_PATTERN = re.compile('^(?:(?:\<\?php )?(?://|#|\/\*|\<\!--)\s*)?COLOR(?P<keyword> SCHEME)? TEST "(?P<color_scheme>[^"]+)" "(?P<syntax_name>[^"]+)"(?:\s*(?:--\>|\?\>|\*\/))?\n')
COLOR_TEST_ASSERTION_COMPILED_PATTERN = re.compile('^(//|#|\/\*|\<\!--)\s*(?P<repeat>\^+)(?: fg=(?P<fg>[^ ]+)?)?(?: bg=(?P<bg>[^ ]+)?)?(?: fs=(?P<fs>[^=]*)?)?$')

class _color_scheme_unit_test_view_set_content(sublime_plugin.TextCommand):

    """
    Helper view command for TestView#set_content()
    TODO is there a way to avoid needing this superfluous text command?
    """

    def run(self, edit, content):
        self.view.erase(edit, sublime.Region(0, self.view.size()))
        self.view.insert(edit, 0, content)

class TestView():
    def __init__(self, name, window):
        self.name = name + '_test_view'
        self.window = window

    def setUp(self):
        self.view = self.window.create_output_panel(self.name, unlisted=True)

    def tearDown(self):
        if self.view:
            self.view.close()

    def set_content(self, content):
        self.view.run_command('_color_scheme_unit_test_view_set_content', {
            'content': content
        })

    def get_content(self):
        return self.view.substr(sublime.Region(0, self.view.size()))

class TestOutputPanel():
    def __init__(self, name, window):
        self.view = window.create_output_panel(name)

        settings = self.view.settings()
        settings.set('result_file_regex', '^(.+):([0-9]+):([0-9]+)$')
        settings.set('word_wrap', False)
        settings.set('line_numbers', False)
        settings.set('gutter', False)
        settings.set('rulers', [])
        settings.set('scroll_past_end', False)

        self.view.assign_syntax('Packages/color_scheme_unit/test_output_panel.sublime-syntax')

        # Assign panel with color scheme of active view
        active_view = window.active_view()
        if active_view:
            active_color_scheme = active_view.settings().get('color_scheme')
            if active_color_scheme:
                settings.set('color_scheme', active_color_scheme)

        window.run_command('show_panel', { 'panel': 'output.' + name })

    def write(self, text):
        self.view.run_command('append', { 'characters': text, 'scroll_to_end': True })

class ColorSchemeStyle():

    def __init__(self, view):
        self.view = view

        color_scheme = self.view.settings().get('color_scheme')
        color_scheme_resource = sublime.load_resource(color_scheme)
        color_scheme_plist = plistlib.readPlistFromBytes(bytes(color_scheme_resource, 'UTF-8'))
        self.color_scheme_plist_settings = color_scheme_plist['settings']

        self.default_style = dict()
        for color_scheme_plist_dict in self.color_scheme_plist_settings:
            if 'scope' not in color_scheme_plist_dict:
                self.default_style.update(color_scheme_plist_dict['settings'])

    def at_point(self, point):
        scope = self.view.scope_name(point).strip()

        last_selector_score = -1
        style = self.default_style.copy()
        for color_scheme_definition in self.color_scheme_plist_settings:
            if 'scope' in color_scheme_definition:
                score = sublime.score_selector(scope, color_scheme_definition['scope'])
                if score and score >= last_selector_score:
                    last_selector_score = score
                    style.update(color_scheme_definition['settings'])

        return style

def run_color_scheme_test(test, window, output):
    debug_message('running color scheme test: %s' % test)

    error = False
    failures = []
    assertion_count = 0

    test_view = TestView('color_scheme_unit', window)
    test_view.setUp()

    try:
        test_content = sublime.load_resource(test)

        color_test_params = COLOR_TEST_PARAMS_COMPILED_PATTERN.match(test_content)

        # TODO remove this deprecated behaviour in v1.0.0
        if not color_test_params.group('keyword'):
            output.write("\n")
            output.write("DEPRECATED: \"COLOR TEST\" in %s:0\n" % test)
            output.write("  Use 'COLOR SCHEME TEST ...' instead; see https://github.com/gerardroche/sublime_color_scheme_unit/issues/7\n\n")

        if not color_test_params:
            error = {
                'message': 'Invalid color test',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        syntaxes = sublime.find_resources(color_test_params.group('syntax_name') + '.sublime-syntax')

        if len(syntaxes) > 1:
            error = {
                'message': 'Too many syntaxes found',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        if len(syntaxes) is not 1:
            error = {
                'message': 'Syntaxes not found',
                'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                'row': 0,
                'col': 0
            }
            raise RuntimeError(error['message'])

        # TODO remove this deprecated behaviour in v1.0.0
        color_scheme = 'Packages/' + color_test_params.group('color_scheme')
        if 'Packages/Packages/' in color_scheme:
            color_scheme = re.sub('Packages/Packages/', 'Packages/', color_scheme)
            output.write("\n")
            output.write("DEPRECATED: \"Packages/...\" in %s:0\n" % test)
            output.write(" Rename '%s'\n     to          '%s'\n" % (color_scheme, color_scheme[9:]))
            output.write(" See https://github.com/gerardroche/sublime_color_scheme_unit/issues/6\n\n")

        test_view.view.settings().set('color_scheme', color_scheme)
        test_view.view.assign_syntax(syntaxes[0])
        test_view.set_content(test_content)

        color_scheme_style = ColorSchemeStyle(test_view.view)

        consecutive_test_lines = 0
        for line_number, line in enumerate(test_content.splitlines()):
            assertion_params = COLOR_TEST_ASSERTION_COMPILED_PATTERN.match(line.lower().rstrip(' -->').rstrip(' */'))
            if not assertion_params:
                consecutive_test_lines = 0
                continue

            consecutive_test_lines += 1

            assertion = assertion_params.group(0)
            assertion_row = line_number - consecutive_test_lines
            assertion_begin = line.find('^')
            assertion_end = assertion_begin + len(assertion_params.group('repeat'))
            expected_styles = {}
            if assertion_params.group('fg') is not None:
                expected_styles['foreground'] = assertion_params.group('fg')
            if assertion_params.group('bg') is not None:
                expected_styles['background'] = assertion_params.group('bg')
            if assertion_params.group('fs') is not None:
                expected_styles['fontStyle'] = assertion_params.group('fs')

            for col in range(assertion_begin, assertion_end):
                assertion_count += 1
                assertion_point = test_view.view.text_point(assertion_row, col)
                actual_styles_at_point = color_scheme_style.at_point(assertion_point)

                actual_styles = {}
                for style in expected_styles:
                    if style in actual_styles_at_point:
                        if actual_styles_at_point[style]:
                            actual_styles[style] = actual_styles_at_point[style].lower()
                        else:
                            actual_styles[style] = actual_styles_at_point[style]
                    else:
                        actual_styles[style] = ''

                progress_character='.'
                if actual_styles != expected_styles:
                    progress_character='F'

                    failure_trace = {
                        'assertion': assertion,
                        'file': os.path.join(os.path.dirname(sublime.packages_path()), test),
                        'row': assertion_row + 1,
                        'col': col + 1,
                        'actual': actual_styles,
                        'expected': expected_styles,
                    }

                    debug_message('----- Assertion FAILED! -----')
                    debug_message('Trace: %s' % str(failure_trace))

                    failures.append(failure_trace)

                output.write(progress_character)
                if assertion_count % 80 == 0:
                    output.write("\n")

        output.write("\n")
    except Exception as e:
        test_view.tearDown()
        if not error:
            output.write(str(e))
            output.write("\n")

    test_view.tearDown()

    return {
        'error': error,
        'failures': failures,
        'assertions': assertion_count
    }

class RunColorSchemeTestCommand(sublime_plugin.WindowCommand):

    def run(self):
        if self.is_enabled():
            self.window.run_command(
                'run_color_scheme_tests', {
                    'test_file': self.test_file
                }
            )

    def is_enabled(self):
        view = self.window.active_view()
        if not view:
            return False

        file_name = view.file_name()
        if not file_name:
            return False

        if not re.match('^.+/color_scheme_test.*\.[a-z]+$', file_name):
            return False

        self.test_file = file_name

        return True

class RunColorSchemeTestsCommand(sublime_plugin.WindowCommand):

    def run(self, test_file = None):
        sublime.set_timeout_async(lambda: self.run_async(test_file))

    def run_async(self, test_file):
        view = self.window.active_view()
        if not view:
            return

        file_name = view.file_name()
        if not file_name:
            return

        tests = []
        for resource in sublime.find_resources('color_scheme_test*'):
            package = resource.split(os.sep)[1]
            package_path = os.path.join(sublime.packages_path(), package)
            if file_name.startswith(package_path):
                tests_package_name = package
                if test_file:
                    resource_file = os.path.join(os.path.dirname(sublime.packages_path()), resource)
                    if test_file == resource_file:
                        tests.append(resource)
                else:
                    tests.append(resource)

        if not len(tests):
            return

        output = TestOutputPanel('color_scheme_unit', self.window)
        output.write("ColorSchemeUnit %s\n\n" % __version__)
        output.write("Runtime: %s build %s\n" % (sublime.platform(), sublime.version()))
        output.write("Package: %s\n" % tests_package_name)
        if test_file:
            output.write("File:    %s\n" % test_file)
        output.write("\n")

        errors = []
        failures = []
        total_assertions = 0

        start = timer()
        for test in tests:
            test_result = run_color_scheme_test(test, self.window, output)
            if test_result['error']:
                errors += [test_result['error']]
            failures += test_result['failures']
            total_assertions += test_result['assertions']
        elapsed = timer() - start
        output.write("\n")

        output.write("Time: %.2f secs\n" % (elapsed))
        output.write("\n")

        if len(errors) > 0:
            output.write("There were %s errors:\n" % len(errors))
            output.write("\n")
            for i, error in enumerate(errors, start=1):
                output.write("%d) %s\n" % (i, error['message']))
                output.write("%s:%d:%d\n" % (error['file'], error['row'], error['col']))
                output.write("\n")

        if len(failures) > 0:
            output.write("There were %s failures:\n\n" % len(failures))
            for i, failure in enumerate(failures, start=1):
                output.write("%d) %s\n" % (i, failure['assertion']))
                output.write("Failed asserting %s equals %s\n" % (str(failure['actual']), str(failure['expected'])))
                # TODO failure diff
                # output.write("--- Expected\n")
                # output.write("+++ Actual\n")
                # output.write("@@ @@\n")
                # output.write("{{diff}}\n\n")
                output.write("%s:%d:%d\n" % (failure['file'], failure['row'], failure['col']))
                output.write("\n")

        if len(errors) == 0 and len(failures) == 0:
            output.write("OK (%d tests, %d assertions)\n" % (len(tests), total_assertions))
        else:
            output.write("FAILURES!\n")
            output.write("Tests: %d, Assertions: %d" % (len(tests), total_assertions))
            if len(errors) > 0:
                output.write(", Errors: %d" % (len(errors)))
            output.write(", Failures: %d" % (len(failures)))
            output.write(".")
            output.write("\n")

if os.getenv('SUBLIME_COLOR_SCHEME_UNIT_DEBUG'):

    def copy(view, text):
        sublime.set_clipboard(text)
        view.hide_popup()
        sublime.status_message('Scope name copied to clipboard')

    class ShowScopeNameAndStylesCommand(sublime_plugin.TextCommand):

        def run(self, edit):
            scope = self.view.scope_name(self.view.sel()[-1].b)
            style = ColorSchemeStyle(self.view).at_point(self.view.sel()[-1].b)

            style_html = '
'
            if 'foreground' in style:
                style_html += "
foreground: {0}
".format(style['foreground'])
                del style['foreground']
            if 'background' in style:
                style_html += "
background: {0}
".format(style['background'])
                del style['background']
            if 'fontStyle' in style:
                style_html += "
fontStyle: {0}
".format(style['fontStyle'])
                del style['fontStyle']
            for x in sorted(style):
                style_html += "
{0}: {1}
".format(x, style[x])
            style_html += '
';

            html = """

%s

                    Copy
                    %s

            """ % (scope.replace(' ', '
'), scope.rstrip(), style_html)

            self.view.show_popup(html, max_width=512, on_navigate=lambda x: copy(self.view, x))

    class SetColorSchemeOnLoad(sublime_plugin.EventListener):

        def on_load_async(self, view):
            file_name = view.file_name()
            if file_name:
                if not re.match('.*color_scheme_test[a-zA-Z0-9_]+.[a-zA-Z0-9]+$', file_name):
                    return

            color_scheme_test = COLOR_TEST_PARAMS_COMPILED_PATTERN.match(view.substr(sublime.Region(0, view.size())))
            if color_scheme_test:
                view.settings().set('color_scheme', color_scheme_test.group('color_scheme'))
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Orangetool IP functions."""
from .orangetool_system import restart as restart_func
from .orangetool_params import IP_PATTERN, GLOBAL_IP_API_1, GENERAL_ERROR_MESSAGE
import subprocess as sub
import socket
import os
import requests
import re
import platform

def internet(host="8.8.8.8", port=53, timeout=3, debug=False):
    """
    Check internet connections.

    :param  host: the host that check connection to
    :type host:str
    :param  port: port that check connection with
    :type port:int
    :param  timeout: times that check the connection
    :type timeout:int
    :param debug:flag for using debug Mode
    :type debug:bool
    :return bool: True if Connection is Stable
    >>> internet() # if there is stable internet connection
    True
    >>> internet() # if there is no stable internet connection
    False
    """
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception as e:
        if debug:
            print(str(e))
        return False

def local_ip(debug=False):
    """
    Return local ip of computer in windows by socket module and in unix with hostname command in shell.

    :param debug:flag for using debug Mode
    :type debug:bool
    :return: local ip as string
    """
    try:
        ip = socket.gethostbyname(socket.gethostname())
        if ip != "127.0.0.1":
            return ip
        if platform.system() != "Windows":
            command = sub.Popen(["hostname",
                                 "-I"],
                                stdout=sub.PIPE,
                                stderr=sub.PIPE,
                                stdin=sub.PIPE,
                                shell=False)
            response = list(command.communicate())
            if len(response[0]) > 0:
                return str(response[0])[2:-4]
            return GENERAL_ERROR_MESSAGE
        return GENERAL_ERROR_MESSAGE

    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def global_ip(debug=False):
    """
    Return ip with by http://ipinfo.io/ip api.

    :param debug:flag for using debug mode
    :type debug:bool
    :return: global ip as string
    """
    try:
        new_session = requests.session()
        response = new_session.get(GLOBAL_IP_API_1)
        ip_list = re.findall(IP_PATTERN, response.text)
        new_session.close()
        return ip_list[0]
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def set_ip(ip, restart=False, device="eth0", debug=False):
    """
    Set static ip in interfaces file (need sudo).

    :param ip: static ip
    :type ip :str
    :param restart : restart flag
    :type restart : bool
    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful
    """
    static_string = '''
    auto lo device
iface lo inet loopback
iface device inet static
        address ip
        netmask 255.255.255.0
        gateway 192.168.1.1
        dns-nameservers 8.8.8.8 8.8.4.4
    '''
    try:
        if not bool(re.match(IP_PATTERN, ip)) or ip.find(
                "192.168.") == -1 or device not in mac().keys():
            raise Exception("IP Formation Error")
        static_string = static_string.replace("ip", ip)
        static_string = static_string.replace("device", device)
        file = open("/etc/network/interfaces", "w")
        file.write(static_string)
        file.close()
        sub.Popen(["ifdown", device, "&&", "ifup", device],
                  stderr=sub.PIPE, stdin=sub.PIPE, stdout=sub.PIPE)
        if restart:
            restart_func()
        return True
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def ping(ip, packet_number=3, debug=False):
    """
    Ping ip and return True if this ip is available and False otherwise.

    :param ip: target ip
    :type ip :str
    :param packet_number: number of packet to size
    :type packet_number:int
    :param debug: flag for using debug mode
    :type debug:bool
    :return: a boolean value (True if ip is available and False otherwise)
    """
    try:
        if not re.match(IP_PATTERN, ip):
            raise Exception("IP Formation Error")
        output = str(list(sub.Popen(["ping",
                                     ip,
                                     "-c",
                                     str(packet_number)],
                                    stdout=sub.PIPE,
                                    stderr=sub.PIPE).communicate())[0])
        if output.find("Unreachable") == -1:
            return True
        return False
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def mac(debug=False):
    """
    Return mac addresses of net devices.

    :param debug: flag for using debug mode
    :type debug:bool
    :return: return mac addresses as dict with name as keys and mac addresses as values
    """
    try:
        net_dir = "/sys/class/net"
        mac_list = []
        dir_list = os.listdir(net_dir)
        for item in dir_list:
            mac_addr = open(net_dir + "/" + item + "/address", "r")
            mac_list.append(mac_addr.read()[:-1])
            mac_addr.close()
        return dict(zip(dir_list, mac_list))
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def network_control(command, device="eth0", debug=False):
    """
    Control network adaptor.

    :param command: input command
    :type command: str
    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    try:
        cmd = "up"
        if command == "down":
            cmd = "down"
        cmd_out = sub.Popen(["ifconfig", device, cmd],
                           stderr=sub.PIPE, stdin=sub.PIPE, stdout=sub.PIPE)
        output = list(cmd_out.communicate())
        if len(output[0]) == 0 and len(output[1]) == 0:
            return True
        return False
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def network_enable(device="eth0", debug=False):
    """
    Shortcut to enable network adaptor.

    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    return network_control("up", device=device, debug=debug)

def network_disable(device="eth0", debug=False):
    """
    Shortcut to disable network adaptor.

    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    return network_control("down", device=device, debug=debug)
<commit_msg>doc : minor edits in docstrings<commit_after># -*- coding: utf-8 -*-
"""Orangetool IP functions."""
from .orangetool_system import restart as restart_func
from .orangetool_params import IP_PATTERN, GLOBAL_IP_API_1, GENERAL_ERROR_MESSAGE
import subprocess as sub
import socket
import os
import requests
import re
import platform

def internet(host="8.8.8.8", port=53, timeout=3, debug=False):
    """
    Check internet connections.

    :param host: the host that check connection to
    :type host:str
    :param port: port that check connection with
    :type port:int
    :param timeout: times that check the connection
    :type timeout:int
    :param debug:flag for using debug mode
    :type debug:bool
    :return bool: True if connection is stable
    >>> internet() # if there is stable internet connection
    True
    >>> internet() # if there is no stable internet connection
    False
    """
    try:
        socket.setdefaulttimeout(timeout)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception as e:
        if debug:
            print(str(e))
        return False

def local_ip(debug=False):
    """
    Return local ip of computer in windows by socket module and in unix with hostname command in shell.

    :param debug:flag for using debug mode
    :type debug:bool
    :return: local ip as string
    """
    try:
        ip = socket.gethostbyname(socket.gethostname())
        if ip != "127.0.0.1":
            return ip
        if platform.system() != "Windows":
            command = sub.Popen(["hostname",
                                 "-I"],
                                stdout=sub.PIPE,
                                stderr=sub.PIPE,
                                stdin=sub.PIPE,
                                shell=False)
            response = list(command.communicate())
            if len(response[0]) > 0:
                return str(response[0])[2:-4]
            return GENERAL_ERROR_MESSAGE
        return GENERAL_ERROR_MESSAGE

    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def global_ip(debug=False):
    """
    Return ip with by http://ipinfo.io/ip api.

    :param debug:flag for using debug mode
    :type debug:bool
    :return: global ip as string
    """
    try:
        new_session = requests.session()
        response = new_session.get(GLOBAL_IP_API_1)
        ip_list = re.findall(IP_PATTERN, response.text)
        new_session.close()
        return ip_list[0]
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def set_ip(ip, restart=False, device="eth0", debug=False):
    """
    Set static ip in interfaces file (need sudo).

    :param ip: static ip
    :type ip :str
    :param restart : restart flag
    :type restart : bool
    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful
    """
    static_string = '''
    auto lo device
iface lo inet loopback
iface device inet static
        address ip
        netmask 255.255.255.0
        gateway 192.168.1.1
        dns-nameservers 8.8.8.8 8.8.4.4
    '''
    try:
        if not bool(re.match(IP_PATTERN, ip)) or ip.find(
                "192.168.") == -1 or device not in mac().keys():
            raise Exception("IP Formation Error")
        static_string = static_string.replace("ip", ip)
        static_string = static_string.replace("device", device)
        file = open("/etc/network/interfaces", "w")
        file.write(static_string)
        file.close()
        sub.Popen(["ifdown", device, "&&", "ifup", device],
                  stderr=sub.PIPE, stdin=sub.PIPE, stdout=sub.PIPE)
        if restart:
            restart_func()
        return True
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def ping(ip, packet_number=3, debug=False):
    """
    Ping ip and return True if this ip is available and False otherwise.

    :param ip: target ip
    :type ip :str
    :param packet_number: number of packet to size
    :type packet_number:int
    :param debug: flag for using debug mode
    :type debug:bool
    :return: a boolean value (True if ip is available and False otherwise)
    """
    try:
        if not re.match(IP_PATTERN, ip):
            raise Exception("IP Formation Error")
        output = str(list(sub.Popen(["ping",
                                     ip,
                                     "-c",
                                     str(packet_number)],
                                    stdout=sub.PIPE,
                                    stderr=sub.PIPE).communicate())[0])
        if output.find("Unreachable") == -1:
            return True
        return False
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def mac(debug=False):
    """
    Return mac addresses of net devices.

    :param debug: flag for using debug mode
    :type debug:bool
    :return: return mac addresses as dict with name as keys and mac addresses as values
    """
    try:
        net_dir = "/sys/class/net"
        mac_list = []
        dir_list = os.listdir(net_dir)
        for item in dir_list:
            mac_addr = open(net_dir + "/" + item + "/address", "r")
            mac_list.append(mac_addr.read()[:-1])
            mac_addr.close()
        return dict(zip(dir_list, mac_list))
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def network_control(command, device="eth0", debug=False):
    """
    Control network adaptor.

    :param command: input command
    :type command: str
    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    try:
        cmd = "up"
        if command == "down":
            cmd = "down"
        cmd_out = sub.Popen(["ifconfig", device, cmd],
                           stderr=sub.PIPE, stdin=sub.PIPE, stdout=sub.PIPE)
        output = list(cmd_out.communicate())
        if len(output[0]) == 0 and len(output[1]) == 0:
            return True
        return False
    except Exception as e:
        if debug:
            print(str(e))
        return GENERAL_ERROR_MESSAGE

def network_enable(device="eth0", debug=False):
    """
    Shortcut to enable network adaptor.

    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    return network_control("up", device=device, debug=debug)

def network_disable(device="eth0", debug=False):
    """
    Shortcut to disable network adaptor.

    :param device: network device name
    :type device:str
    :param debug: flag for using debug mode
    :type debug:bool
    :return: True in successful and False otherwise
    """
    return network_control("down", device=device, debug=debug)
<|endoftext|>


<commit_before>""" OrderPortal: Dump the database into a tar file.
The settings file may be given as the first command line argument,
otherwise it is obtained as usual.
The dump file will be called 'dump_{ISO date}.tar.gz' using today's date.
Create the dump file in the directory specified by BACKUP_DIR variable
in the settings, otherwise in the current working directory.
"""

from __future__ import print_function, absolute_import

import cStringIO
import json
import os
import tarfile
import time

import couchdb

from orderportal import constants
from orderportal import settings
from orderportal import utils

def get_command_line_parser():
    parser = utils.get_command_line_parser(description=
        'Dump all data into a tar file.')
    parser.add_option('-d', '--dumpfile',
                      action='store', dest='dumpfile',
                      metavar='DUMPFILE', help='name of dump file')
    return parser

def dump(db, filepath, verbose=False):
    """Dump contents of the database to a tar file, optionally gzip compressed.
    Only entities with IUID key as name are dumped; all others are ignored.
    """
    count_items = 0
    count_files = 0
    if filepath.endswith('.gz'):
        mode = 'w:gz'
    else:
        mode = 'w'
    outfile = tarfile.open(filepath, mode=mode)
    for key in db:
        doc = db[key]
        # Only documents that explicitly belong to the application
        if doc.get(constants.DOCTYPE) is None: continue
        del doc['_rev']
        info = tarfile.TarInfo(doc['_id'])
        data = json.dumps(doc)
        info.size = len(data)
        outfile.addfile(info, cStringIO.StringIO(data))
        count_items += 1
        for attname in doc.get('_attachments', dict()):
            info = tarfile.TarInfo("{0}_att/{1}".format(doc['_id'], attname))
            attfile = db.get_attachment(doc, attname)
            if attfile is None:
                data = ''
            else:
                data = attfile.read()
                attfile.close()
            info.size = len(data)
            outfile.addfile(info, cStringIO.StringIO(data))
            count_files += 1
    outfile.close()
    if verbose:
        print('dumped', count_items, 'items and',
              count_files, 'files to', filepath, file=sys.stderr)

def undump(db, filepath, verbose=False):
    """Reverse of dump; load all items from a tar file.
    Items are just added to the database, ignoring existing items.
    """
    count_items = 0
    count_files = 0
    attachments = dict()
    infile = tarfile.open(filepath, mode='r')
    for item in infile:
        itemfile = infile.extractfile(item)
        itemdata = itemfile.read()
        itemfile.close()
        if item.name in attachments:
            # This relies on an attachment being after its item in the tarfile.
            db.put_attachment(doc, itemdata, **attachments.pop(item.name))
            count_files += 1
        else:
            doc = json.loads(itemdata)
            # If the email already exists, do not load document.
            if doc[constants.DOCTYPE] == constants.ACCOUNT:
                rows = db.view('account/email', key=doc['email'])
                if len(list(rows)) != 0: continue
            atts = doc.pop('_attachments', dict())
            # Overwrite meta documents
            if doc[constants.DOCTYPE] == constants.META:
                try:
                    doc2 = db[doc['_id']]
                except couchdb.ResourceNotFound:
                    pass
                else:
                    doc2.update(doc)
                    doc = doc2
            db.save(doc)
            count_items += 1
            for attname, attinfo in atts.items():
                key = "{0}_att/{1}".format(doc['_id'], attname)
                attachments[key] = dict(filename=attname,
                                        content_type=attinfo['content_type'])
    infile.close()
    if verbose:
        print('undumped', count_items, 'items and',
              count_files, 'files from', filepath, file=sys.stderr)

if __name__ == '__main__':
    parser = get_command_line_parser()
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings,
                        verbose=options.verbose)
    db = utils.get_db()
    if options.dumpfile:
        filepath = options.dumpfile
    else:
        filepath = "dump_{0}.tar.gz".format(time.strftime("%Y-%m-%d"))
    try:
        filepath = os.path.join(settings['BACKUP_DIR'], filepath)
    except KeyError:
        pass
    dump(db, filepath, verbose=options.verbose)
<commit_msg>Fixed bug in dump.py: import sys.<commit_after>""" OrderPortal: Dump the database into a tar file.
The settings file may be given as the first command line argument,
otherwise it is obtained as usual.
The dump file will be called 'dump_{ISO date}.tar.gz' using today's date.
Create the dump file in the directory specified by BACKUP_DIR variable
in the settings, otherwise in the current working directory.
"""

from __future__ import print_function, absolute_import

import cStringIO
import json
import os
import sys
import tarfile
import time

import couchdb

from orderportal import constants
from orderportal import settings
from orderportal import utils

def get_command_line_parser():
    parser = utils.get_command_line_parser(description=
        'Dump all data into a tar file.')
    parser.add_option('-d', '--dumpfile',
                      action='store', dest='dumpfile',
                      metavar='DUMPFILE', help='name of dump file')
    return parser

def dump(db, filepath, verbose=False):
    """Dump contents of the database to a tar file, optionally gzip compressed.
    Only entities with IUID key as name are dumped; all others are ignored.
    """
    count_items = 0
    count_files = 0
    if filepath.endswith('.gz'):
        mode = 'w:gz'
    else:
        mode = 'w'
    outfile = tarfile.open(filepath, mode=mode)
    for key in db:
        doc = db[key]
        # Only documents that explicitly belong to the application
        if doc.get(constants.DOCTYPE) is None: continue
        del doc['_rev']
        info = tarfile.TarInfo(doc['_id'])
        data = json.dumps(doc)
        info.size = len(data)
        outfile.addfile(info, cStringIO.StringIO(data))
        count_items += 1
        for attname in doc.get('_attachments', dict()):
            info = tarfile.TarInfo("{0}_att/{1}".format(doc['_id'], attname))
            attfile = db.get_attachment(doc, attname)
            if attfile is None:
                data = ''
            else:
                data = attfile.read()
                attfile.close()
            info.size = len(data)
            outfile.addfile(info, cStringIO.StringIO(data))
            count_files += 1
    outfile.close()
    if verbose:
        print('dumped', count_items, 'items and',
              count_files, 'files to', filepath, file=sys.stderr)

def undump(db, filepath, verbose=False):
    """Reverse of dump; load all items from a tar file.
    Items are just added to the database, ignoring existing items.
    """
    count_items = 0
    count_files = 0
    attachments = dict()
    infile = tarfile.open(filepath, mode='r')
    for item in infile:
        itemfile = infile.extractfile(item)
        itemdata = itemfile.read()
        itemfile.close()
        if item.name in attachments:
            # This relies on an attachment being after its item in the tarfile.
            db.put_attachment(doc, itemdata, **attachments.pop(item.name))
            count_files += 1
        else:
            doc = json.loads(itemdata)
            # If the email already exists, do not load document.
            if doc[constants.DOCTYPE] == constants.ACCOUNT:
                rows = db.view('account/email', key=doc['email'])
                if len(list(rows)) != 0: continue
            atts = doc.pop('_attachments', dict())
            # Overwrite meta documents
            if doc[constants.DOCTYPE] == constants.META:
                try:
                    doc2 = db[doc['_id']]
                except couchdb.ResourceNotFound:
                    pass
                else:
                    doc2.update(doc)
                    doc = doc2
            db.save(doc)
            count_items += 1
            for attname, attinfo in atts.items():
                key = "{0}_att/{1}".format(doc['_id'], attname)
                attachments[key] = dict(filename=attname,
                                        content_type=attinfo['content_type'])
    infile.close()
    if verbose:
        print('undumped', count_items, 'items and',
              count_files, 'files from', filepath, file=sys.stderr)

if __name__ == '__main__':
    parser = get_command_line_parser()
    (options, args) = parser.parse_args()
    utils.load_settings(filepath=options.settings,
                        verbose=options.verbose)
    db = utils.get_db()
    if options.dumpfile:
        filepath = options.dumpfile
    else:
        filepath = "dump_{0}.tar.gz".format(time.strftime("%Y-%m-%d"))
    try:
        filepath = os.path.join(settings['BACKUP_DIR'], filepath)
    except KeyError:
        pass
    dump(db, filepath, verbose=options.verbose)
<|endoftext|>


<commit_before>import random

# R-1.1
# Write a short Python function, is multiple(n, m), that takes two integer values and returns
# True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise.

def is_multiple(m, n):
    return True if m % n == 0 else False

print(is_multiple(10, 3))
print(is_multiple(10, 2))

# R-1.2
# Write a short Python function, is even(k), that takes an integer value and returns True if k is even,
# and False otherwise. However, your function cannot use the multiplication, modulo, or division operators.

def is_even(k):
    return False if k & 1 else True

print(is_even(2))
print(is_even(3))

# R-1.3
#Write a short Python function, minmax(data), that takes a sequence of one or more numbers,
# and returns the smallest and largest numbers, in the form of a tuple of length two.
# Do not use the built-in functions min or max in implementing your solution.

def minmax(data):
    largest = data[0]
    smallest = data[0]
    for item in data:
        if item > largest:
            largest = item
        elif item < smallest:
            smallest = item
    return smallest, largest

alpha = [2, 2, 3, 4, 5, 6, 7, 8, 99]

print(minmax(alpha))

# R-1.4
# Write a short Python function that takes a positive integer n and returns the sum of the squares
#  of all the positive integers smaller than n.

def sum_of_squares(n):
    n -= 1
    total = 0
    while n > 0:
        total += n * n
        n -= 1
    return total

print('sum of squares')
print(sum_of_squares(4))

# R-1.5
# give a single command that computes the sum from exercise r-1.4, relying on python's comprehension syntax and built in sum function

def sum_of_squares2(n):
    return sum([k * k for k in range(0, n)])

print(sum_of_squares2(4))

# R-1.6
#Write a short Python function that takes a positive integer n and returns the sum of the squares
# of all the odd positive integers smaller than n.

def sum_of_squares_odd(n):
    n -= 1
    total = 0
    while n > 0:
        if n % 2 != 0:
            total += n * n
        n -= 1
    return total

print('sum of squares odd')
print(sum_of_squares_odd(4))
# R-1.7

# give a single command that computes the sum from r-1.6, relying on python's comprehension syntax and built in sum function

def sum_of_squares_odd2(n):
    return sum([k * k for k in range(0, n) if k % 2 != 0])

print(sum_of_squares_odd2(4))

# R-1.8
# Python allows negative integers to be used as indices into a sequence,
# such as a string. If string s has length n, and expression s[k] is used
# for index -n <= k < 0, what is the equivalent index j >= 0 such that s[j]
# references the same element?

s = "pythonstring"
n = len(s)

for k in range(-n, 0):
    print(s[k])

for j in range(-n, 0):
    print(s[j + n])

# R-1.9
# What parameters should be sent to the range constructor, to produce a range with values 50, 60, 70, 80?

print(range(50, 90, +10))

# R-1.10
# what parameters should be sent to the range constructor to produce a range with values
# 8, 6, 4, 2, 0, -2, -4, -6, -8

print(range(8, -10, -2))

# R-1.11
# Demonstrate how to use Python's list comprehension syntax to produce the list
# [1, 2, 4, 8, 16, 32, 64, 128, 256].

print([pow(2, k) for k in range(0, 9, +1)])

# R-1.12

# Python's random module includes a function choice(data) that returns a random element
# from a non-empty sequence. The random module in- cludes a more basic function randrange,
# with parameterization similar to the built-in range function, that return a random choice
# from the given range. Using only the randrange function, implement your own version of the choice function.

def my_choice(data):
    return data[random.randrange(0, len(data) - 1)]

print(my_choice(alpha))

# C-1.13

# Write a pseudo-code description of a function that reverses a list of n integers,
# so that the numbers are listed in the opposite order than they were before, and compare
# this method to an equivalent Python function for doing the same thing.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def reverse(data):
    temp = []
    n = len(data) - 1
    for thing in range(n, -1, -1):
        temp.append(data[thing])
    return temp

print(my_list)

print(reverse(my_list))

# C-1.14
# Write a short Python function that takes a sequence of integer values and determines
# if there is a distinct pair of numbers in the sequence whose product is odd.

def odd_pair(data):
    count = 0
    for k in range(0, len(data) - 1):
        if k % 2 != 0:
            count += 1
    return True if count >= 2 else False

evens = [2, 4, 6, 8]
print(odd_pair(my_list))
print(odd_pair(evens))

# C-1.15
# Write a Python function that takes a sequence of numbers and determines
# if all the numbers are different from each other (that is, they are distinct).

def are_distinct(data):
    count = 0
    for k in data:
        for j in range(1, len(data) - 1):
            if k == j:
                count += 1
                if count == 2:
                    return False
    return True

print(are_distinct(evens))
print(are_distinct(alpha))

# C-1.18
# Demo list comprehension to create the following
# list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].

print([k * (k - 1) for k in range(1, 11)])

# C-1.19
# Demonstrate how to use python's
# list comprehension syntax to produce
# the list [ a , b , c ,..., z ],without typing  characters literally.

print([chr(k) for k in range(97, 123)])

# print(chr(ord('A') + 1))
print(chr(97))<commit_msg>C-1.21<commit_after>import random

# R-1.1
# Write a short Python function, is multiple(n, m), that takes two integer values and returns
# True if n is a multiple of m, that is, n = mi for some integer i, and False otherwise.

def is_multiple(m, n):
    return True if m % n == 0 else False

print(is_multiple(10, 3))
print(is_multiple(10, 2))

# R-1.2
# Write a short Python function, is even(k), that takes an integer value and returns True if k is even,
# and False otherwise. However, your function cannot use the multiplication, modulo, or division operators.

def is_even(k):
    return False if k & 1 else True

print(is_even(2))
print(is_even(3))

# R-1.3
#Write a short Python function, minmax(data), that takes a sequence of one or more numbers,
# and returns the smallest and largest numbers, in the form of a tuple of length two.
# Do not use the built-in functions min or max in implementing your solution.

def minmax(data):
    largest = data[0]
    smallest = data[0]
    for item in data:
        if item > largest:
            largest = item
        elif item < smallest:
            smallest = item
    return smallest, largest

alpha = [2, 2, 3, 4, 5, 6, 7, 8, 99]

print(minmax(alpha))

# R-1.4
# Write a short Python function that takes a positive integer n and returns the sum of the squares
#  of all the positive integers smaller than n.

def sum_of_squares(n):
    n -= 1
    total = 0
    while n > 0:
        total += n * n
        n -= 1
    return total

print('sum of squares')
print(sum_of_squares(4))

# R-1.5
# give a single command that computes the sum from exercise r-1.4, relying on python's comprehension syntax and built in sum function

def sum_of_squares2(n):
    return sum([k * k for k in range(0, n)])

print(sum_of_squares2(4))

# R-1.6
#Write a short Python function that takes a positive integer n and returns the sum of the squares
# of all the odd positive integers smaller than n.

def sum_of_squares_odd(n):
    n -= 1
    total = 0
    while n > 0:
        if n % 2 != 0:
            total += n * n
        n -= 1
    return total

print('sum of squares odd')
print(sum_of_squares_odd(4))
# R-1.7

# give a single command that computes the sum from r-1.6, relying on python's comprehension syntax and built in sum function

def sum_of_squares_odd2(n):
    return sum([k * k for k in range(0, n) if k % 2 != 0])

print(sum_of_squares_odd2(4))

# R-1.8
# Python allows negative integers to be used as indices into a sequence,
# such as a string. If string s has length n, and expression s[k] is used
# for index -n <= k < 0, what is the equivalent index j >= 0 such that s[j]
# references the same element?

s = "pythonstring"
n = len(s)

for k in range(-n, 0):
    print(s[k])

for j in range(-n, 0):
    print(s[j + n])

# R-1.9
# What parameters should be sent to the range constructor, to produce a range with values 50, 60, 70, 80?

print(range(50, 90, +10))

# R-1.10
# what parameters should be sent to the range constructor to produce a range with values
# 8, 6, 4, 2, 0, -2, -4, -6, -8

print(range(8, -10, -2))

# R-1.11
# Demonstrate how to use Python's list comprehension syntax to produce the list
# [1, 2, 4, 8, 16, 32, 64, 128, 256].

print([pow(2, k) for k in range(0, 9, +1)])

# R-1.12

# Python's random module includes a function choice(data) that returns a random element
# from a non-empty sequence. The random module in- cludes a more basic function randrange,
# with parameterization similar to the built-in range function, that return a random choice
# from the given range. Using only the randrange function, implement your own version of the choice function.

def my_choice(data):
    return data[random.randrange(0, len(data) - 1)]

print(my_choice(alpha))

# C-1.13

# Write a pseudo-code description of a function that reverses a list of n integers,
# so that the numbers are listed in the opposite order than they were before, and compare
# this method to an equivalent Python function for doing the same thing.

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def reverse(data):
    temp = []
    n = len(data) - 1
    for thing in range(n, -1, -1):
        temp.append(data[thing])
    return temp

print(my_list)

print(reverse(my_list))

# C-1.14
# Write a short Python function that takes a sequence of integer values and determines
# if there is a distinct pair of numbers in the sequence whose product is odd.

def odd_pair(data):
    count = 0
    for k in range(0, len(data) - 1):
        if k % 2 != 0:
            count += 1
    return True if count >= 2 else False

evens = [2, 4, 6, 8]
print(odd_pair(my_list))
print(odd_pair(evens))

# C-1.15
# Write a Python function that takes a sequence of numbers and determines
# if all the numbers are different from each other (that is, they are distinct).

def are_distinct(data):
    count = 0
    for k in data:
        for j in range(1, len(data) - 1):
            if k == j:
                count += 1
                if count == 2:
                    return False
    return True

print(are_distinct(evens))
print(are_distinct(alpha))

# C-1.18
# Demo list comprehension to create the following
# list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90].

print([k * (k - 1) for k in range(1, 11)])

# C-1.19
# Demonstrate how to use python's
# list comprehension syntax to produce
# the list [ a , b , c ,..., z ],without typing  characters literally.

print([chr(k) for k in range(97, 123)])

# C-1.20
# python's random module includes a function shuffle(data) that accepts a list
# of elements and randomly reorders the elements so that each possible order
# occurs with equal probability. The random module includes a more basic function
#  randint(a, b) that returns a uniformly random integer from a to b
# (including both endpoints). Using only the randint function,
#  implement your own version of the shuffle function.

def shufl(data):
    for k in range(0, len(data)):
        random_index = random.randint(0, k)
        tmp = data[random_index]
        data[random_index] = data[k]
        data[k] = tmp

shufl(alpha)
print(alpha)

# C-1.21
# Write a Python program that repeatedly reads lines from standard input until an EOFError
# is raised, and then outputs those lines in reverse order
#  (a user can indicate end of input by typing ctrl-D).

done = False
lines = []

while not done:
    try:
        line = raw_input()
        lines.append(line)
    except (EOFError):
        for l in range(len(lines) - 1, -1, -1):
            print(lines[l])
            done = True
<|endoftext|>