<commit_before>"""Classes to configure and launch jobs from a wmt-exe environment."""

import os
import sys
import stat
import subprocess
from types import StringTypes

class Launcher(object):
    """Job launcher for a wmt-exe environment.

    Parameters
    ----------
    sim_id : str
        A unique UUID for the job.

    Attributes
    ----------
    launch_dir : str
        The working directory from which the job is started.
    script_path : str
        Path to launch script.
    sim_id : str
        A unique UUID for the job.

    """
    launch_dir = '~/.wmt'
    _script = "{slave_command}"
    _extra_args = []

    def __init__(self, sim_id):
        self.sim_id = sim_id
        self.script_path = os.path.expanduser(
            os.path.join(self.launch_dir,
                         '%s.sh' % self.sim_id))

    def before_launch(self, **kwds):
        """Perform actions before launching job.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        with open(self.script_path, 'w') as f:
            f.write(self.script(**kwds))
        os.chmod(self.script_path, stat.S_IXUSR|stat.S_IWUSR|stat.S_IRUSR)

    def after_launch(self, **kwds):
        """Perform actions after launching job.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        pass

    def after_success(self, **kwds):
        """Perform actions after job completes.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        pass

    def run(self, **kwds):
        """Perform job setup, launch, and teardown actions.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        self.before_launch(**kwds)

        try:
            self.launch(**kwds)
        except subprocess.CalledProcessError:
            raise
        else:
            self.after_success(**kwds)
        finally:
            self.after_launch(**kwds)

    def launch(self, **kwds):
        """Launch job with launch command.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        subprocess.check_output(self.launch_command(**kwds), env={})

    def launch_command(self, **kwds):
        """Path to launch script.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch command to execute.

        """
        return self.script_path

    def slave_command(self, extra_args=None):
        """Create the `wmt-slave` command.

        Parameters
        ----------
        extra_args : str, optional
            Additional arguments.

        Returns
        -------
        str
            The slave command to execute.

        """
        import shlex
        from pipes import quote

        wmt_slave = os.path.join(sys.prefix, 'bin', 'wmt-slave')
        command = [wmt_slave, quote(self.sim_id)] + self._extra_args

        if extra_args:
            if isinstance(extra_args, StringTypes):
                extra_args = shlex.split(extra_args)
            command += [quote(arg) for arg in extra_args]

        return ' '.join(command)

    def script(self, **kwds):
        """Generate the launch script.

        Parameters
        ----------
        *kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch script to be written to a file.

        """
        return self._script.format(slave_command=self.slave_command(**kwds))

class QsubLauncher(Launcher):
    """WMT job launcher for a PBS scheduler."""
    _script = """
#! /bin/bash
#PBS -q debug
#PBS -l mem=10gb
#PBS -j oe
#PBS -k oe

cd $TMPDIR

{slave_command}
""".strip()
    _extra_args = ['--exec-dir=$TMPDIR',
                   '--server-url=https://csdms.colorado.edu/wmt/api-testing']

    def launch_command(self, **kwds):
        """Path to launch script.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch command to execute.

        """
        return ['/opt/torque/bin/qsub', '-o', self.launch_dir,
                self.script_path]

class BashLauncher(Launcher):
    """WMT job launcher for a bash environment."""
    _script = """
#! /bin/bash

export PATH={wmt_path}

{slave_command}
""".strip()
    _extra_args = ['--server-url=https://csdms.colorado.edu/wmt/api-testing']

    def prepend_path(self):
        """Places the `bin` directory of executor at the front of the path."""
        return os.pathsep.join([os.path.join(sys.prefix, 'bin'),
                                os.environ['PATH']])

    def script(self, **kwds):
        """Generate the launch script.

        Parameters
        ----------
        *kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch script to be written to a file.

        """
        return self._script.format(wmt_path=self.prepend_path(),
                                   slave_command=self.slave_command(**kwds))
<commit_msg>Add serverl_url attribute to Launcher class<commit_after>"""Classes to configure and launch jobs from a wmt-exe environment."""

import os
import sys
import stat
import subprocess
from types import StringTypes

class Launcher(object):
    """Job launcher for a wmt-exe environment.

    Parameters
    ----------
    sim_id : str
        A unique UUID for the job.
    server_url : str or None, optional
        The URL of the WMT API server from which the job was submitted.

    Attributes
    ----------
    launch_dir : str
        The working directory from which the job is started.
    script_path : str
        Path to launch script.
    sim_id : str
        A unique UUID for the job.
    server_url : str or None
        The URL of the WMT API server from which the job was submitted.

    """
    launch_dir = '~/.wmt'
    _script = "{slave_command}"
    _extra_args = []

    def __init__(self, sim_id, server_url=None):
        self.sim_id = sim_id
        self.server_url = server_url
        self.script_path = os.path.expanduser(
            os.path.join(self.launch_dir,
                         '%s.sh' % self.sim_id))

    def before_launch(self, **kwds):
        """Perform actions before launching job.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        with open(self.script_path, 'w') as f:
            f.write(self.script(**kwds))
        os.chmod(self.script_path, stat.S_IXUSR|stat.S_IWUSR|stat.S_IRUSR)

    def after_launch(self, **kwds):
        """Perform actions after launching job.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        pass

    def after_success(self, **kwds):
        """Perform actions after job completes.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        pass

    def run(self, **kwds):
        """Perform job setup, launch, and teardown actions.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        self.before_launch(**kwds)

        try:
            self.launch(**kwds)
        except subprocess.CalledProcessError:
            raise
        else:
            self.after_success(**kwds)
        finally:
            self.after_launch(**kwds)

    def launch(self, **kwds):
        """Launch job with launch command.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        """
        subprocess.check_output(self.launch_command(**kwds), env={})

    def launch_command(self, **kwds):
        """Path to launch script.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch command to execute.

        """
        return self.script_path

    def slave_command(self, extra_args=None):
        """Create the `wmt-slave` command.

        Parameters
        ----------
        extra_args : str, optional
            Additional arguments.

        Returns
        -------
        str
            The slave command to execute.

        """
        import shlex
        from pipes import quote

        wmt_slave = os.path.join(sys.prefix, 'bin', 'wmt-slave')
        command = [wmt_slave, quote(self.sim_id)] + self._extra_args

        if self.server_url:
            command += ['--server-url={}'.format(self.server_url)]

        if extra_args:
            if isinstance(extra_args, StringTypes):
                extra_args = shlex.split(extra_args)
            command += [quote(arg) for arg in extra_args]

        return ' '.join(command)

    def script(self, **kwds):
        """Generate the launch script.

        Parameters
        ----------
        *kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch script to be written to a file.

        """
        return self._script.format(slave_command=self.slave_command(**kwds))

class QsubLauncher(Launcher):
    """WMT job launcher for a PBS scheduler."""
    _script = """
#! /bin/bash
#PBS -q debug
#PBS -l mem=10gb
#PBS -j oe
#PBS -k oe

cd $TMPDIR

{slave_command}
""".strip()
    _extra_args = ['--exec-dir=$TMPDIR']

    def launch_command(self, **kwds):
        """Path to launch script.

        Parameters
        ----------
        **kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch command to execute.

        """
        return ['/opt/torque/bin/qsub', '-o', self.launch_dir,
                self.script_path]

class BashLauncher(Launcher):
    """WMT job launcher for a bash environment."""
    _script = """
#! /bin/bash

export PATH={wmt_path}

{slave_command}
""".strip()

    def prepend_path(self):
        """Places the `bin` directory of executor at the front of the path."""
        return os.pathsep.join([os.path.join(sys.prefix, 'bin'),
                                os.environ['PATH']])

    def script(self, **kwds):
        """Generate the launch script.

        Parameters
        ----------
        *kwds
            Arbitrary keyword arguments.

        Returns
        -------
        str
            The launch script to be written to a file.

        """
        return self._script.format(wmt_path=self.prepend_path(),
                                   slave_command=self.slave_command(**kwds))
<|endoftext|>


<commit_before># coding=utf-8
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('Enter text, i shall print it in reversed order, ctrl-d to stop')
#         lines.append(line)
#     except (EOFError):
#         for l in range(len(lines) - 1, -1, -1):
#             print(lines[l])
#             done = True

# C-1.22
# Write a short Python program that takes two arrays a and b of length n storing int values,
# and returns the dot product of a and b. That is, it returns an array c of length n such that
# c[i] = a[i]·b[i],
# for i = 0,...,n−1.

first = [1, 2, 3, 4]
second = [1, 2, 3, 4]

def dot_product(a, b):
    # assume n is the same for both
    c = []
    for k in range(0, len(a)):
        c.append(a[k] + b[k])
    return c

third = dot_product(first, second)

print(third)

# C-1.23
# Give an example of a Python code fragment that attempts
# to write an ele- ment to a list based on an index that may be out of bounds.
# If that index is out of bounds, the program should
# catch the exception that results, and print the following error message:
# “Don’t try buffer overflow attacks in Python!”

a_list = [1, 2, 3, 4]

try:
    a_list[4] = 5
except IndexError:
    print("Don't try buffer overflow attacks in Python")

# C-1.24
# Write a short Python function that counts the number of vowels in a given
# character string.
#
given_string = "There are 9 vowels in this string"
count = 0

for c in given_string:
    if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == "u":
        count += 1

print(count)

<commit_msg>Update primer.py<commit_after># coding=utf-8
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('Enter text, i shall print it in reversed order, ctrl-d to stop')
#         lines.append(line)
#     except (EOFError):
#         for l in range(len(lines) - 1, -1, -1):
#             print(lines[l])
#             done = True

# C-1.22
# Write a short Python program that takes two arrays a and b of length n storing int values,
# and returns the dot product of a and b. That is, it returns an array c of length n such that
# c[i] = a[i]·b[i],
# for i = 0,...,n−1.

first = [1, 2, 3, 4]
second = [1, 2, 3, 4]

def dot_product(a, b):
    # assume n is the same for both
    c = []
    for k in range(0, len(a)):
        c.append(a[k] + b[k])
    return c

third = dot_product(first, second)

print(third)

# C-1.23
# Give an example of a Python code fragment that attempts
# to write an ele- ment to a list based on an index that may be out of bounds.
# If that index is out of bounds, the program should
# catch the exception that results, and print the following error message:
# “Don’t try buffer overflow attacks in Python!”

a_list = [1, 2, 3, 4]

try:
    a_list[4] = 5
except IndexError:
    print("Don't try buffer overflow attacks in Python")

# C-1.24
# Write a short Python function that counts the number of vowels in a given
# character string.
#
given_string = "There are 9 vowels in this string"
count = 0

for c in given_string:
    if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == "u":
        count += 1

print(count)

# C-1.25
#WriteashortPython function thattakes astrings,representing asentence,
#and returns a copy of the string with all punctuation removed. For example,
#if given the string "Let s try, Mike.", this function would return "Lets try Mike".
#
given_string = 'Let\'s try, Mike.'

punctuations = ''''~!@#$%^*()_-{}[]|\:'";<>,./'''  # Take help of your keyboard to remember this.

newstring = ''
for i in given_string:
    if i not in punctuations:
        newstring += i

print(newstring)

<|endoftext|>


<commit_before>###########################################
# Suppress matplotlib user warnings
# Necessary for newer version of matplotlib
import warnings
warnings.filterwarnings("ignore", category = UserWarning, module = "matplotlib")
#
# Display inline matplotlib plots with IPython
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
###########################################

import matplotlib.pyplot as pl
import matplotlib.patches as mpatches
import numpy as np
import pandas as pd
from time import time
from sklearn.metrics import f1_score, accuracy_score

def distribution(data, transformed = False):
    """
    Visualization code for displaying skewed distributions of features
    """

    # Create figure
    fig = pl.figure(figsize = (11,5));

    # Skewed feature plotting
    for i, feature in enumerate(['capital-gain','capital-loss']):
        ax = fig.add_subplot(1, 2, i+1)
        ax.hist(data[feature], bins = 25, color = '#00A0A0')
        ax.set_title("'%s' Feature Distribution"%(feature), fontsize = 14)
        ax.set_xlabel("Value")
        ax.set_ylabel("Number of Records")
        ax.set_ylim((0, 2000))
        ax.set_yticks([0, 500, 1000, 1500, 2000])
        ax.set_yticklabels([0, 500, 1000, 1500, ">2000"])

    # Plot aesthetics
    if transformed:
        fig.suptitle("Log-transformed Distributions of Continuous Census Data Features", \
            fontsize = 16, y = 1.03)
    else:
        fig.suptitle("Skewed Distributions of Continuous Census Data Features", \
            fontsize = 16, y = 1.03)

    fig.tight_layout()
    fig.show()

def evaluate(results, accuracy, f1):
    """
    Visualization code to display results of various learners.

    inputs:
      - learners: a list of supervised learners
      - stats: a list of dictionaries of the statistic results from 'train_predict()'
      - accuracy: The score for the naive predictor
      - f1: The score for the naive predictor
    """

    # Create figure
    fig, ax = pl.subplots(2, 3, figsize = (11,7))

    # Constants
    bar_width = 0.3
    colors = ['#A00000','#00A0A0','#00A000','#000000','838FA2']

    # Super loop to plot four panels of data
    for k, learner in enumerate(results.keys()):
        for j, metric in enumerate(['train_time', 'acc_train', 'f_train', 'pred_time', 'acc_test', 'f_test']):
            for i in np.arange(3):

                # Creative plot code
                ax[j/3, j%3].bar(i+k*bar_width, results[learner][i][metric], width = bar_width, color = colors[k])
                ax[j/3, j%3].set_xticks([0.45, 1.45, 2.45])
                ax[j/3, j%3].set_xticklabels(["1%", "10%", "100%"])
                ax[j/3, j%3].set_xlabel("Training Set Size")
                ax[j/3, j%3].set_xlim((-0.1, 3.0))

    # Add unique y-labels
    ax[0, 0].set_ylabel("Time (in seconds)")
    ax[0, 1].set_ylabel("Accuracy Score")
    ax[0, 2].set_ylabel("F-score")
    ax[1, 0].set_ylabel("Time (in seconds)")
    ax[1, 1].set_ylabel("Accuracy Score")
    ax[1, 2].set_ylabel("F-score")

    # Add titles
    ax[0, 0].set_title("Model Training")
    ax[0, 1].set_title("Accuracy Score on Training Subset")
    ax[0, 2].set_title("F-score on Training Subset")
    ax[1, 0].set_title("Model Predicting")
    ax[1, 1].set_title("Accuracy Score on Testing Set")
    ax[1, 2].set_title("F-score on Testing Set")

    # Add horizontal lines for naive predictors
    ax[0, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[1, 1].axhline(y = accuracy, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[0, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')
    ax[1, 2].axhline(y = f1, xmin = -0.1, xmax = 3.0, linewidth = 1, color = 'k', linestyle = 'dashed')

    # Set y-limits for score panels
    ax[0, 1].set_ylim((0, 1))
    ax[0, 2].set_ylim((0, 1))
    ax[1, 1].set_ylim((0, 1))
    ax[1, 2].set_ylim((0, 1))

    # Create patches for the legend
    patches = []
    for i, learner in enumerate(results.keys()):
        patches.append(mpatches.Patch(color = colors[i], label = learner))
    pl.legend(handles = patches, bbox_to_anchor = (-.80, 2.53), \
               loc = 'upper center', borderaxespad = 0., ncol = 3, fontsize = 'x-large')

    # Aesthetics
    pl.suptitle("Performance Metrics for Three Supervised Learning Models", fontsize = 16, y = 1.10)
    pl.tight_layout()
    pl.show()

def feature_plot(importances, X_train, y_train):

    # Display the five most important features
    indices = np.argsort(importances)[::-1]
    columns = X_train.columns.values[indices[:5]]
    values = importances[indices][:5]

    # Creat the plot
    fig = pl.figure(figsize = (9,5))
    pl.title("Normalized Weights for First Five Most Predictive Features", fontsize = 16)
    pl.bar(np.arange(5), values, width = 0.6, align="center", color = '#00A000', \
          label = "Feature Weight")
    pl.bar(np.arange(5) - 0.3, np.cumsum(values), width = 0.2, align = "center", color = '#00A0A0', \
          label = "Cumulative Feature Weight")
    pl.xticks(np.arange(5), columns)
    pl.xlim((-0.5, 4.5))
    pl.ylabel("Weight", fontsize = 12)
    pl.xlabel("Feature", fontsize = 12)

    pl.legend(loc = 'upper center')
    pl.tight_layout()
    pl.show()
<commit_msg>Delete visuals.py<commit_after><|endoftext|>


<commit_before>"""The util module contains a variety of utility functions."""
import configparser
import sys

def read_cfg_file(filename):
    """Read and parse the experiment configuration file with configparser."""

    config = configparser.ConfigParser(inline_comment_prefixes=("#", ";"))
    config.optionxform = str

    try:
        out = config.read(str(filename))

        if not out and filename is not None:
            exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n")

    except configparser.MissingSectionHeaderError:
        exit(f"\nERROR: You are missing a section heading in {filename:s}\n")

    except configparser.ParsingError:
        exit(
            "\nERROR: Having trouble reading your parameter file, did you"
            " forget '=' signs?\n{:s}".format(sys.exc_info()[1])
        )

    return config

def normalize_path(working_dir, filename):
    """Normalize the path of a filename relative to a specific directory."""

    path = filename

    if not path.is_absolute():
        path = working_dir / path

    return path.resolve()

def header1(string):
    """Print a formatted heading."""
    print(("\n".join(["", "", string, "=" * len(string), ""])))

def header2(string):
    """Print a formatted subheading."""
    print(("\n".join(["", string, "-" * len(string), ""])))
<commit_msg>Update settings for reading config files<commit_after>"""The util module contains a variety of utility functions."""
import configparser
import sys

def listfloat(text):
    return [float(val) for val in text.strip("[]").split(",")]

def read_cfg_file(filename=None):
    """Read and parse the experiment configuration file with configparser."""

    config = configparser.ConfigParser(
        comment_prefixes="#", inline_comment_prefixes="#", converters=listfloat
    )
    config.optionxform = str

    try:
        result = config.read(str(filename))

        if not result and filename is not None:
            exit(f"\nERROR: The file '{filename}' is empty or does not exist!\n")

    except configparser.MissingSectionHeaderError:
        exit(f"\nERROR: You are missing a section heading in {filename:s}\n")

    except configparser.ParsingError:
        exit(
            "\nERROR: Having trouble reading your parameter file, did you"
            " forget '=' signs?\n{:s}".format(sys.exc_info()[1])
        )

    return config

def normalize_path(working_dir, filename):
    """Normalize the path of a filename relative to a specific directory."""

    path = filename

    if not path.is_absolute():
        path = working_dir / path

    return path.resolve()

def header1(string):
    """Print a formatted heading."""
    print(("\n".join(["", "", string, "=" * len(string), ""])))

def header2(string):
    """Print a formatted subheading."""
    print(("\n".join(["", string, "-" * len(string), ""])))
<|endoftext|>


<commit_before># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------

import numpy
import matplotlib.pyplot as plt
from excite_function_base import ExciteFunctionBase

class LogisticExciteFunction(ExciteFunctionBase):
  """
  Implementation of a logistic activation function for activation updating.
  Specifically, the function has the following form:

  f(x) = (maxValue - minValue) / (1 + exp(-steepness * (x - xMidpoint) ) ) + minValue

  Note: The excitation rate is linear. The activation function is
  logistic.
  """

  def __init__(self, xMidpoint=5, minValue=10, maxValue=20, steepness=1):
    """
    @param xMidpoint: Controls where function output is half of 'maxValue,'
                      i.e. f(xMidpoint) = maxValue / 2
    @param minValue: Minimum value of the function
    @param maxValue: Controls the maximum value of the function's range
    @param steepness: Controls the steepness of the "middle" part of the
                      curve where output values begin changing rapidly.
                      Must be a non-zero value.
    """
    assert steepness != 0

    self._xMidpoint = xMidpoint
    self._maxValue = maxValue
    self._minValue = minValue
    self._steepness = steepness

  def excite(self, currentActivation, inputs):
    """
    Increases current activation by amount.
    @param currentActivation (numpy array) Current activation levels for each cell
    @param inputs            (numpy array) inputs for each cell
    """

    currentActivation += self._minValue + (self._maxValue - self._minValue) / \
                                          (1 + numpy.exp(-self._steepness * (inputs - self._xMidpoint)))

    return currentActivation

  def plot(self):
    """
    plot the activation function
    """
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
    plt.title('Sigmoid Activation Function')

class FixedExciteFunction(ExciteFunctionBase):
  """
  Implementation of a simple fixed excite function
  The function reset the activation level to a fixed amount
  """

  def __init__(self, targetExcLevel=10.0):
    """
    """
    self._targetExcLevel = targetExcLevel

  def excite(self, currentActivation, inputs):
    """
    Increases current activation by a fixed amount.
    @param currentActivation (numpy array) Current activation levels for each cell
    @param inputs            (numpy array) inputs for each cell
    """

    currentActivation += self._targetExcLevel

    return currentActivation

  def plot(self):
    """
    plot the activation function
    """
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
<commit_msg>update union pooler excitation rule<commit_after># ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2015, Numenta, Inc.  Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------

import numpy
import matplotlib.pyplot as plt
from excite_function_base import ExciteFunctionBase

class LogisticExciteFunction(ExciteFunctionBase):
  """
  Implementation of a logistic activation function for activation updating.
  Specifically, the function has the following form:

  f(x) = (maxValue - minValue) / (1 + exp(-steepness * (x - xMidpoint) ) ) + minValue

  Note: The excitation rate is linear. The activation function is
  logistic.
  """

  def __init__(self, xMidpoint=5, minValue=10, maxValue=20, steepness=1):
    """
    @param xMidpoint: Controls where function output is half of 'maxValue,'
                      i.e. f(xMidpoint) = maxValue / 2
    @param minValue: Minimum value of the function
    @param maxValue: Controls the maximum value of the function's range
    @param steepness: Controls the steepness of the "middle" part of the
                      curve where output values begin changing rapidly.
                      Must be a non-zero value.
    """
    assert steepness != 0

    self._xMidpoint = xMidpoint
    self._maxValue = maxValue
    self._minValue = minValue
    self._steepness = steepness

  def excite(self, currentActivation, inputs):
    """
    Increases current activation by amount.
    @param currentActivation (numpy array) Current activation levels for each cell
    @param inputs            (numpy array) inputs for each cell
    """

    currentActivation = self._minValue + (self._maxValue - self._minValue) / \
                                          (1 + numpy.exp(-self._steepness * (inputs - self._xMidpoint)))

    return currentActivation

  def plot(self):
    """
    plot the activation function
    """
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
    plt.title('Sigmoid Activation Function')

class FixedExciteFunction(ExciteFunctionBase):
  """
  Implementation of a simple fixed excite function
  The function reset the activation level to a fixed amount
  """

  def __init__(self, targetExcLevel=10.0):
    """
    """
    self._targetExcLevel = targetExcLevel

  def excite(self, currentActivation, inputs):
    """
    Increases current activation by a fixed amount.
    @param currentActivation (numpy array) Current activation levels for each cell
    @param inputs            (numpy array) inputs for each cell
    """

    currentActivation = self._targetExcLevel

    return currentActivation

  def plot(self):
    """
    plot the activation function
    """
    plt.ion()
    plt.show()
    x = numpy.linspace(0, 15, 100)
    y = numpy.zeros(x.shape)
    y = self.excite(y, x)
    plt.plot(x, y)
    plt.xlabel('Input')
    plt.ylabel('Persistence')
<|endoftext|>


<commit_before>#!/usr/bin/python
import pygame
import os
import copy
from pygame.locals import *
from enum import Enum

# TODO: move to commons (confirm)
SCREEN_TITLE = 'Chess'
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
BOARD_SIZE = 640
IMAGES_FOLDER_PATH = 'assets/images'

# TODO: comment this and color_board after integration (as docs)
board = [
    ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'], # 8
    ['p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'], # 7
    ['.', '.', '.', '.', '.', '.', '.', '.'], # 6
    ['.', '.', '.', '.', '.', '.', '.', '.'], # 5
    ['.', '.', '.', '.', '.', '.', '.', '.'], # 4
    ['.', '.', '.', '.', '.', '.', '.', '.'], # 3
    ['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'], # 2
    ['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'], # 1
    # a    b    c    d    e    f    g    h
]
color_board = [
    [1, 2, 1, 0, 1, 0, 1, 0], # 8
    [0, 1, 0, 1, 0, 1, 0, 1], # 7
    [1, 3, 1, 0, 1, 0, 1, 0], # 6
    [0, 1, 0, 1, 0, 1, 0, 1], # 5
    [1, 0, 1, 0, 1, 0, 1, 0], # 4
    [0, 1, 0, 1, 0, 1, 0, 1], # 3
    [1, 0, 1, 0, 1, 0, 1, 0], # 2
    [0, 1, 0, 1, 0, 1, 0, 1], # 1
    #a  b  c  d  e  f  g  h
]

class Color(Enum):
    BLACK = (100, 100, 100)
    WHITE = (230, 230, 230)
    GREEN = (50, 200, 50)
    RED = (200, 50, 50)

    def get_rgb(code):
        if code == 0:
            return Color.BLACK.value
        if code == 1:
            return Color.WHITE.value
        if code == 2:
            return Color.GREEN.value
        if code == 3:
            return  Color.RED.value

def load_png(file_name):
    """ Load image and return image object"""
    """
        Não precisa se preocupar com essa função, ela é só uma função auxiliar para garantir que
        as imagens sejam carregadas no formato certo
    """
    fullname = os.path.join(IMAGES_FOLDER_PATH, file_name + '.png')
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except (pygame.error):
        print('Error loading image', fullname)
        raise(pygame.error('a'))
    return image

class ChessPiece(pygame.sprite.Sprite):
    """"
    Não precisa se preocupar muito com essa classe também, é apenas uma 'imagem'
    """
    def __init__(self, name, image_surface, rect):
        pygame.sprite.Sprite.__init__(self)
        self.name = name
        self.image = image_surface
        self.rect = pygame.Rect(rect)
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()

    def was_clicked(self, click_position):
        return self.rect.collidepoint(click_position)

def create_chess_piece(piece_code, cell_size, cell_rect):
    """
    Uma factory de peças simplesmente
    :returns ChessPiece
    """
    piece_image = None
    if piece_code == 'P':
        piece_image = WHITE_PAWN_IMAGE
        name = 'white pawn'
    elif piece_code == 'R':
        piece_image = WHITE_ROOK_IMAGE
        name = 'white rook'
    elif piece_code == 'N':
        piece_image = WHITE_KNIGHT_IMAGE
        name = 'white knight'
    elif piece_code == 'B':
        piece_image = WHITE_BISHOP_IMAGE
        name = 'white bishop'
    elif piece_code == 'Q':
        piece_image = WHITE_QUEEN_IMAGE
        name = 'white queen'
    elif piece_code == 'K':
        piece_image = WHITE_KING_IMAGE
        name = 'white king'
    elif piece_code == 'p':
        piece_image = BLACK_PAWN_IMAGE
        name = 'black pawn'
    elif piece_code == 'r':
        piece_image = BLACK_ROOK_IMAGE
        name = 'black rook'
    elif piece_code == 'n':
        piece_image = BLACK_KNIGHT_IMAGE
        name = 'black knight'
    elif piece_code == 'b':
        piece_image = BLACK_BISHOP_IMAGE
        name = 'black bishop'
    elif piece_code == 'q':
        piece_image = BLACK_QUEEN_IMAGE
        name = 'black queen'
    elif piece_code == 'k':
        piece_image = BLACK_KING_IMAGE
        name = 'black king'

    chess_piece = None
    if piece_image is not None:
        chess_piece_image = pygame.transform.scale(
            piece_image, (int(cell_size), int(cell_size)))
        chess_piece = ChessPiece(name, chess_piece_image, cell_rect)

    return chess_piece

def setup_board(board, color_board):
    """
    Recebe um board e um color_board (ambos são matrizes)
    A partir deles, monta um tabuleiro com as respectivas peças e cores de cada célula
    """
    # Surface é a classe que representa uma imagem, basicamente, a qual pode ser pintada na tela
    board_surface = pygame.Surface((BOARD_SIZE, BOARD_SIZE)).convert()
    chess_pieces = []
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell_rect = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_color = Color.get_rgb(color_board[row][col])
            board_surface.fill(cell_color, cell_rect)
            cell_code = board[row][col]
            chess_piece = create_chess_piece(cell_code, cell_size, cell_rect)
            if chess_piece is not None:
                chess_pieces.append(chess_piece)

    return board_surface, chess_pieces

def get_cell_by_position(position, board):
    """
    Pega a posição de uma célula dentro do board (0..7)x(0..7)
    de acordo com a position
    """
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_rect = pygame.Rect(cell)
            if cell_rect.collidepoint(position):
                return (row, col)

if __name__ == '__main__':
    # Initialise screen
    # Necessário para "rodar" o joguinho
    pygame.init()
    # A janela do jogo em si, com tamanho WIDTHxHEIGHT (lá em cima setados)
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    # Título da janela
    pygame.display.set_caption(SCREEN_TITLE)

    # Load sprites
    # Ainda vou pensar em como tirar isso daqui e carregar em outro lugar hehe
    WHITE_PAWN_IMAGE = load_png('chess-pieces/white-pawn')
    WHITE_BISHOP_IMAGE = load_png('chess-pieces/white-bishop')
    WHITE_KING_IMAGE = load_png('chess-pieces/white-king')
    WHITE_KNIGHT_IMAGE = load_png('chess-pieces/white-knight')
    WHITE_QUEEN_IMAGE = load_png('chess-pieces/white-queen')
    WHITE_ROOK_IMAGE = load_png('chess-pieces/white-rook')
    BLACK_PAWN_IMAGE = load_png('chess-pieces/black-pawn')
    BLACK_BISHOP_IMAGE = load_png('chess-pieces/black-bishop')
    BLACK_KING_IMAGE = load_png('chess-pieces/black-king')
    BLACK_KNIGHT_IMAGE = load_png('chess-pieces/black-knight')
    BLACK_QUEEN_IMAGE = load_png('chess-pieces/black-queen')
    BLACK_ROOK_IMAGE = load_png('chess-pieces/black-rook')

    # Events loop
    running = True
    # Posição da última peça clicada
    last_held_piece_pos = None

    while running:
        # Pinta a tela de preto
        screen.fill((0,0,0))
        # Pega posição (x,y) do mouse
        mouse_position = pygame.mouse.get_pos()
        # Pega a posição das células (a partir da posição do mouse)
        cell_x, cell_y = get_cell_by_position(mouse_position, board)
        # Para cada evento que ocorreu (cliques, teclas, etc.)
        for event in pygame.event.get():
            # Se clicou para fechar a janela
            if event.type == QUIT:
                running = False
###### Início da lógica de movimentação #######
            # Se apartou algum botão do mouse (ainda vou adicionar restrição para apenas o botão esquerdo)
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If wasn't holding a piece before AND clicked on a piece (that is, board value != '.')
                if last_held_piece_pos is None \
                        and board[cell_x][cell_y] != '.':
                    # Hold the piece
                    last_held_piece_pos = cell_x, cell_y
                    print("Clicked on cell: {} which contains a {}".format(
                        last_held_piece_pos, board[cell_x][cell_y]))
            # Se soltou algum botão do mouse E estava segurando alguma peça
            elif event.type == pygame.MOUSEBUTTONUP \
                    and last_held_piece_pos is not None:
                # Substitui o valor do board na célula destino pelo valor da célula de origem
                # Pega a posição de origem (para fazer swap)
                origin_piece_x = last_held_piece_pos[0]
                origin_piece_y = last_held_piece_pos[1]
                # Pega o valor da posição de origem (letra da peça)
                origin_piece = board[origin_piece_x][origin_piece_y]
                # Remove peça de origem do tabuleiro (substitui por '.')
                board[origin_piece_x][origin_piece_y] = '.'
                # Substitui peça na célula de destino
                board[cell_x][cell_y] = origin_piece
                # "solta" a peça
                last_held_piece_pos = None
##### Fim da lógica de movimentação ######

        # give it a margin if board is smaller than screen
        # somente por estética, pode ignorar
        board_position = (
            (SCREEN_WIDTH - BOARD_SIZE) / 2,
            (SCREEN_HEIGHT - BOARD_SIZE) / 2,
        )

        # Pega nova surface atualizada pelas linhas acima
        board_surface, chess_pieces = setup_board(board, color_board)
        # Blitting => drawing updates to the screen
        # pinta o tabuleiro
        screen.blit(board_surface, board_position)
        # pinta cada peça em sua respectiva nova posição
        for chess_piece in chess_pieces:
            screen.blit(chess_piece.image, chess_piece.rect)

        # updating everything (necessary)
        pygame.display.update()
<commit_msg>:memo: Use models.py/utils.py instead of hard-coded features<commit_after>#!/usr/bin/python
import pygame
import os

from pygame.locals import *

from chess.core.models import Coordinate, Color, Piece
from chess.core.utils import INITIAL_BOARD, TEST_COLORED_BOARD

# TODO: move to commons (confirm)
SCREEN_TITLE = 'Chess'
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
BOARD_SIZE = 640
IMAGES_FOLDER_PATH = 'assets/images'

colored_board = TEST_COLORED_BOARD

def load_png(file_name):
    """ Load image and return image object"""
    fullname = os.path.join(IMAGES_FOLDER_PATH, file_name + '.png')
    try:
        image = pygame.image.load(fullname)
        if image.get_alpha() is None:
            image = image.convert()
        else:
            image = image.convert_alpha()
    except pygame.error:
        print('Error loading image', fullname)
        raise(pygame.error('a'))
    return image

class ChessPiece(pygame.sprite.Sprite):
    def __init__(self, name, image_surface, rect):
        pygame.sprite.Sprite.__init__(self)
        self.name = name
        self.image = image_surface
        self.rect = pygame.Rect(rect)
        self.screen = pygame.display.get_surface()
        self.area = screen.get_rect()

    def was_clicked(self, click_position):
        return self.rect.collidepoint(click_position)

def create_chess_piece(piece, cell_size, cell_rect):
    piece_image = None
    if piece == Piece.WHITE_PAWN:
        piece_image = WHITE_PAWN_IMAGE
        name = 'white pawn'
    elif piece == Piece.WHITE_ROOK:
        piece_image = WHITE_ROOK_IMAGE
        name = 'white rook'
    elif piece == Piece.WHITE_KNIGHT:
        piece_image = WHITE_KNIGHT_IMAGE
        name = 'white knight'
    elif piece == Piece.WHITE_BISHOP:
        piece_image = WHITE_BISHOP_IMAGE
        name = 'white bishop'
    elif piece == Piece.WHITE_QUEEN:
        piece_image = WHITE_QUEEN_IMAGE
        name = 'white queen'
    elif piece == Piece.WHITE_KING:
        piece_image = WHITE_KING_IMAGE
        name = 'white king'
    elif piece == Piece.BLACK_PAWN:
        piece_image = BLACK_PAWN_IMAGE
        name = 'black pawn'
    elif piece == Piece.BLACK_ROOK:
        piece_image = BLACK_ROOK_IMAGE
        name = 'black rook'
    elif piece == Piece.BLACK_KNIGHT:
        piece_image = BLACK_KNIGHT_IMAGE
        name = 'black knight'
    elif piece == Piece.BLACK_BISHOP:
        piece_image = BLACK_BISHOP_IMAGE
        name = 'black bishop'
    elif piece == Piece.BLACK_QUEEN:
        piece_image = BLACK_QUEEN_IMAGE
        name = 'black queen'
    elif piece == Piece.BLACK_KING:
        piece_image = BLACK_KING_IMAGE
        name = 'black king'

    chess_piece = None
    if piece_image is not None:
        chess_piece_image = pygame.transform.scale(
            piece_image, (int(cell_size), int(cell_size)))
        chess_piece = ChessPiece(name, chess_piece_image, cell_rect)

    return chess_piece

def setup_board(board, color_board):
    board_surface = pygame.Surface((BOARD_SIZE, BOARD_SIZE)).convert()
    chess_pieces = []
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell_rect = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_color = Color.get_rgb(color_board[row][col])
            board_surface.fill(cell_color, cell_rect)
            cell_value = board[row][col]
            chess_piece = create_chess_piece(cell_value, cell_size, cell_rect)
            if chess_piece is not None:
                chess_pieces.append(chess_piece)

    return board_surface, chess_pieces

def get_cell_by_position(position, board):
    num_of_cells = len(board)
    cell_size = BOARD_SIZE / num_of_cells
    for row in range(num_of_cells):
        for col in range(num_of_cells):
            cell = (col * cell_size, row * cell_size, cell_size, cell_size)
            cell_rect = pygame.Rect(cell)
            if cell_rect.collidepoint(position):
                return row, col

if __name__ == '__main__':
    chess_board = INITIAL_BOARD
    # Initialise screen
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption(SCREEN_TITLE)

    # Load sprites
    WHITE_PAWN_IMAGE = load_png('chess-pieces/white-pawn')
    WHITE_BISHOP_IMAGE = load_png('chess-pieces/white-bishop')
    WHITE_KING_IMAGE = load_png('chess-pieces/white-king')
    WHITE_KNIGHT_IMAGE = load_png('chess-pieces/white-knight')
    WHITE_QUEEN_IMAGE = load_png('chess-pieces/white-queen')
    WHITE_ROOK_IMAGE = load_png('chess-pieces/white-rook')
    BLACK_PAWN_IMAGE = load_png('chess-pieces/black-pawn')
    BLACK_BISHOP_IMAGE = load_png('chess-pieces/black-bishop')
    BLACK_KING_IMAGE = load_png('chess-pieces/black-king')
    BLACK_KNIGHT_IMAGE = load_png('chess-pieces/black-knight')
    BLACK_QUEEN_IMAGE = load_png('chess-pieces/black-queen')
    BLACK_ROOK_IMAGE = load_png('chess-pieces/black-rook')

    # Game Loop
    running = True
    last_held_piece_pos = None
    while running:
        screen.fill((0,0,0))
        mouse_position = pygame.mouse.get_pos()
        cell_x, cell_y = get_cell_by_position(mouse_position, chess_board)
        for event in pygame.event.get():
            if event.type == QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN:
                # If wasn't holding a piece before AND clicked on a piece (that is, board value != '.')
                if last_held_piece_pos is None \
                        and chess_board[cell_x][cell_y] != Piece.NONE:
                    # Hold the piece
                    last_held_piece_pos = cell_x, cell_y
                    print("Clicked on cell: {} which contains a {}".format(
                        last_held_piece_pos, chess_board[cell_x][cell_y]))
            elif event.type == pygame.MOUSEBUTTONUP \
                    and last_held_piece_pos is not None:
                origin_piece_x = last_held_piece_pos[0]
                origin_piece_y = last_held_piece_pos[1]
                origin_piece = chess_board[origin_piece_x][origin_piece_y]
                chess_board[origin_piece_x][origin_piece_y] = Piece.NONE
                chess_board[cell_x][cell_y] = origin_piece
                last_held_piece_pos = None

        # give it a margin if board is smaller than screen
        # somente por estética, pode ignorar
        board_position = (
            (SCREEN_WIDTH - BOARD_SIZE) / 2,
            (SCREEN_HEIGHT - BOARD_SIZE) / 2,
        )

        # Pega nova surface atualizada pelas linhas acima
        board_surface, chess_pieces = setup_board(chess_board, colored_board)
        # Blitting => drawing updates to the screen
        # pinta o tabuleiro
        screen.blit(board_surface, board_position)
        # pinta cada peça em sua respectiva nova posição
        for chess_piece in chess_pieces:
            screen.blit(chess_piece.image, chess_piece.rect)

        # updating everything (necessary)
        pygame.display.update()
<|endoftext|>


<commit_before># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from pycontrail import exceptions
import pycontrail.types as types
import pytest

def _get_ipam_refs(network):
    for ipam_ref in network.get_network_ipam_refs() or []:
        yield ipam_ref

def _get_subnets(network):
    for ipam_ref in _get_ipam_refs(network):
        for subnet in ipam_ref['attr'].ipam_subnets:
            yield subnet

@pytest.fixture
def contrail_create_subnet(contrail_api_client, contrail_default_ipam):
    """Callable fixture to create subnet and delete it after test."""

    networks = []

    def _contrail_create_subnet(network,
                                ipam=None,
                                ip_prefix='10.0.0.0',
                                ip_prefix_len=24):
        # Refresh network data
        network = contrail_api_client.virtual_network_read(id=network.uuid)
        ipam = ipam or contrail_default_ipam

        ipam_subnets = []
        update_exists = False
        for ipam_ref in _get_ipam_refs(network):
            if ipam_ref['uuid'] == ipam.uuid:
                ipam_subnets = ipam_ref['attr'].ipam_subnets
                update_exists = True

        # Store subnet uuids before adding new
        subnet_uuids = {
            x.subnet_uuid
            for x in _get_subnets(network) if x.subnet_uuid is not None
        }

        networks.append((network, ipam))

        subnet_type = types.SubnetType(
            ip_prefix=ip_prefix, ip_prefix_len=ip_prefix_len)
        ipam_subnets.append(types.IpamSubnetType(subnet=subnet_type))
        vn_sub = types.VnSubnetsType(ipam_subnets=ipam_subnets)
        if update_exists:
            network.set_network_ipam(ipam, vn_sub)
        else:
            network.add_network_ipam(ipam, vn_sub)
        contrail_api_client.virtual_network_update(network)

        # Reread network data after update
        network = contrail_api_client.virtual_network_read(id=network.uuid)
        for subnet in _get_subnets(network):
            if subnet.subnet_uuid not in subnet_uuids:
                break
        return subnet

    yield _contrail_create_subnet

    for network, ipam in networks:
        try:
            network = contrail_api_client.virtual_network_read(id=network.uuid)
            ipam = contrail_api_client.network_ipam_read(id=ipam.uuid)
        except exceptions.NoIdError:
            continue
        network.del_network_ipam(ipam)
        contrail_api_client.virtual_network_update(network)

@pytest.fixture
def contrail_subnet(contrail_create_subnet, contrail_default_ipam,
                    contrail_network):
    return contrail_create_subnet(contrail_network, contrail_default_ipam)
<commit_msg>Add Google DNS to subnet<commit_after># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from pycontrail import exceptions
import pycontrail.types as types
import pytest
from stepler import config as stepler_config

def _get_ipam_refs(network):
    for ipam_ref in network.get_network_ipam_refs() or []:
        yield ipam_ref

def _get_subnets(network):
    for ipam_ref in _get_ipam_refs(network):
        for subnet in ipam_ref['attr'].ipam_subnets:
            yield subnet

@pytest.fixture
def contrail_create_subnet(contrail_api_client, contrail_default_ipam):
    """Callable fixture to create subnet and delete it after test."""

    networks = []

    def _contrail_create_subnet(network,
                                ipam=None,
                                ip_prefix='10.0.0.0',
                                ip_prefix_len=24,
                                dns_server_address=None):
        dns_server_address = dns_server_address or stepler_config.GOOGLE_DNS_IP

        # Refresh network data
        network = contrail_api_client.virtual_network_read(id=network.uuid)
        ipam = ipam or contrail_default_ipam

        ipam_subnets = []
        update_exists = False
        for ipam_ref in _get_ipam_refs(network):
            if ipam_ref['uuid'] == ipam.uuid:
                ipam_subnets = ipam_ref['attr'].ipam_subnets
                update_exists = True

        # Store subnet uuids before adding new
        subnet_uuids = {
            x.subnet_uuid
            for x in _get_subnets(network) if x.subnet_uuid is not None
        }

        networks.append((network, ipam))

        subnet_type = types.SubnetType(
            ip_prefix=ip_prefix, ip_prefix_len=ip_prefix_len)
        ipam_subnets.append(
            types.IpamSubnetType(
                subnet=subnet_type,
                dhcp_option_list={
                    'dhcp_option': [{
                        'dhcp_option_value': dns_server_address,
                        'dhcp_option_name': '6'
                    }]
                }))
        vn_sub = types.VnSubnetsType(ipam_subnets=ipam_subnets)
        if update_exists:
            network.set_network_ipam(ipam, vn_sub)
        else:
            network.add_network_ipam(ipam, vn_sub)
        contrail_api_client.virtual_network_update(network)

        # Reread network data after update
        network = contrail_api_client.virtual_network_read(id=network.uuid)
        for subnet in _get_subnets(network):
            if subnet.subnet_uuid not in subnet_uuids:
                break
        return subnet

    yield _contrail_create_subnet

    for network, ipam in networks:
        try:
            network = contrail_api_client.virtual_network_read(id=network.uuid)
            ipam = contrail_api_client.network_ipam_read(id=ipam.uuid)
        except exceptions.NoIdError:
            continue
        network.del_network_ipam(ipam)
        contrail_api_client.virtual_network_update(network)

@pytest.fixture
def contrail_subnet(contrail_create_subnet, contrail_default_ipam,
                    contrail_network):
    return contrail_create_subnet(contrail_network, contrail_default_ipam)
<|endoftext|>


<commit_before># Time:  O(n^2)
# Space: O(n)

# Given a set of distinct positive integers,
# find the largest subset such that every pair (Si, Sj) of
# elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
#
# If there are multiple solutions, return any subset is fine.
#
# Example 1:
#
# nums: [1,2,3]
#
# Result: [1,2] (of course, [1,3] will also be ok)
# Example 2:
#
# nums: [1,2,4,8]
#
# Result: [1,2,4,8]

class Solution(object):
    def largestDivisibleSubset(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []

        nums.sort()
        dp = [1] * (len(nums) + 1)
        prev = [-1] * len(nums)
        largest_idx = 1
        for i in xrange(1, len(nums)+1):
            for j in xrange(1, i):
                if nums[i-1] % nums[j-1] == 0:
                    if dp[i] < dp[j] + 1:
                        dp[i] = dp[j] + 1
                        prev[i-1] = j-1
                        if dp[largest_idx] < dp[i]:
                            largest_idx = i
        result = []
        i = largest_idx - 1
        while i != -1:
            result.append(nums[i])
            i = prev[i]
        return result[::-1]
<commit_msg>Update largest-divisible-subset.py<commit_after># Time:  O(n^2)
# Space: O(n)

# Given a set of distinct positive integers,
# find the largest subset such that every pair (Si, Sj) of
# elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
#
# If there are multiple solutions, return any subset is fine.
#
# Example 1:
#
# nums: [1,2,3]
#
# Result: [1,2] (of course, [1,3] will also be ok)
# Example 2:
#
# nums: [1,2,4,8]
#
# Result: [1,2,4,8]

class Solution(object):
    def largestDivisibleSubset(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        if not nums:
            return []

        nums.sort()
        dp = [1] * len(nums)
        prev = [-1] * len(nums)
        largest_idx = 0
        for i in xrange(len(nums)):
            for j in xrange(i):
                if nums[i] % nums[j] == 0:
                    if dp[i] < dp[j] + 1:
                        dp[i] = dp[j] + 1
                        prev[i] = j
                        if dp[largest_idx] < dp[i]:
                            largest_idx = i
        result = []
        i = largest_idx
        while i != -1:
            result.append(nums[i])
            i = prev[i]
        return result[::-1]
<|endoftext|>


<commit_before>
from django import forms

from workshift.models import Semester, WorkshiftPool, WorkshiftType, \
	TimeBlock, WorkshiftRating, PoolHours, WorkshiftProfile, \
	RegularWorkshift, ShiftLogEntry, InstanceInfo, WorkshiftInstance

class SemesterForm(forms.ModelForm):
	class Meta:
		model = Semester
		exclude = ["workshift_managers", "preferences_open", "current"]

	def save(self, *args, **kwargs):
		semester = super(SemesterForm, self).save(*args, **kwargs)

		# Set current to false for previous semesters
		for semester in Semester.objects.all():
			semester.current = False
			semester.save()

		semester.current = True
		semester.preferences_open = True
		semeseter.save(*args, **kwargs)

		# TODO Copy workshift and pools over from previous semester?

		# TODO Create this semester's workshift profiles

		return semester

class RegularWorkshiftForm(forms.ModelForm):
	class Meta:
		model = RegularWorkshift
		fields = "__all__"

class WorkshiftInstanceForm(forms.ModelForm):
	class Meta:
		model = WorkshiftInstance
		exclude = ["weekly_workshift", "info", "intended_hours", "log"]

	title = forms.CharField(
		max_length=255,
		help_text="The title for this workshift",
		)
	description = forms.CharField(
		widget=forms.Textarea(),
		help_text="Description of the shift.",
		)
	pool = forms.ModelChoiceField(
		queryset=WorkshiftPool.objects.filter(semester__current=True),
		help_text="The workshift pool for this shift.",
		)
	start_time = forms.TimeField(
		required=False,
		help_text="The earliest time this shift should be started.",
		)
	end_time = forms.TimeField(
		required=False,
		help_text="The latest time this shift should be completed.",
		)

	info_fields = ["title", "description", "pool", "start_time", "end_time"]

	def __init__(self, *args, **kwargs):
		if "instance" in kwargs:
			instance = kwargs["instance"]
			initial = kwargs.get("initial", {})

			# Django ModelForms don't play nicely with foreign fields, so we
			# will just manually pre-fill them if an instance is available.
			for field in self.info_fields:
				initial.setdefault(field, getattr(instance, field))

			kwargs["initial"] = initial

			super(WorkshiftInstanceForm, self).__init__(*args, **kwargs)

			# If this is a regular workshift, disable title, description, etc
			# from being edited
			if instance.weekly_workshift:
				for field in self.info_fields:
					self.fields[field].widget.attrs['readonly'] = True
		else:
			super(WorkshiftInstanceForm, self).__init__(*args, **kwargs)

		# Move the forms for title, description, etc to the top
		keys = self.fields.keyOrder
		for field in reversed(self.info_fields):
			keys.remove(field)
			keys.insert(0, field)

	def save(self, *args, **kwargs):
		instance = super(WorkshiftInstanceForm, self).save(*args, **kwargs)
		if instance.info:
			for field in self.info_fields:
				setattr(instance.info, field, self.cleaned_data[field])
		return instance

class WorkshiftTypeForm(forms.ModelForm):
	class Meta:
		model = WorkshiftType
		fields = "__all__"

class InteractShiftForm(forms.Form):
	pk = forms.IntegerField(widget=forms.HiddenInput())

	def __init__(self, *args, **kwargs):
		self.profile = kwargs.pop("profile")
		super(InteractShiftForm, self).__init__(*args, **kwargs)

	def clean_pk(self):
		pk = self.cleaned_data["pk"]
		try:
			shift = WorkshiftInstance.objects.get(pk=pk)
		except WorkshiftInstance.DoesNotExist:
			raise forms.ValidationError("Workshift does not exist.")
		if shift.closed:
			raise forms.ValidationError("Workshift has been closed.")
		return shift

# TODO: SellShiftForm

class VerifyShiftForm(InteractShiftForm):
	title_short = "V"
	title_long = "Verify"
	action_name = "verify_shift"

	def clean_pk(self):
		shift = super(VerifyShiftForm, self).clean_pk()

		if not shift.workshifter:
			raise forms.ValidationError("Workshift is not filled.")
		if not shift.pool.self_verify and shift.workshifter == self.profile:
			raise forms.ValidationError("Workshifter cannot verify self.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.VERIFY,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.verifier = self.profile
		instance.closed = True
		instance.log.add(entry)
		instance.save()

		pool_hours = instance.workshifter.pool_hours \
		  .get(pool=instance.get_info().pool)
		pool_hours.standing += instance.hours
		pool_hours.save()

class BlownShiftForm(InteractShiftForm):
	title_short = "B"
	title_long = "Blown"
	action_name = "blown_shift"

	def clean_pk(self):
		shift = super(BlownShiftForm, self).clean_pk()

		if not shift.workshifter:
			raise forms.ValidationError("Workshift is not filled.")
		pool = shift.pool
		if not pool.any_blown and \
		  pool.managers.filter(incumbent__user=self.profile.user).count() == 0:
			raise forms.ValidationError("You are not a workshift manager.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.BLOWN,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.blown = True
		instance.closed = True
		instance.log.add(entry)
		instance.save()

		pool_hours = instance.workshifter.pool_hours \
		  .get(pool=instance.get_info().pool)
		pool_hours.standing -= instance.hours
		pool_hours.save()

class SignInForm(InteractShiftForm):
	title_short = "I"
	title_long = "Sign In"
	action_name = "sign_in"

	def clean_pk(self):
		shift = super(SignInForm, self).clean_pk()

		if shift.workshifter:
			raise forms.ValidationError("Workshift is currently filled.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.SIGNIN,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.workshifter = self.profile
		instance.log.add(entry)
		instance.save()

class SignOutForm(InteractShiftForm):
	title_short = "O"
	title_long = "Sign Out"
	action_name = "sign_out"

	def clean_pk(self):
		shift = super(SignOutForm, self).clean_pk()

		if shift.workshifter != self.profile:
			raise forms.ValidationError("Cannot sign out of others' workshift.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.SIGNOUT,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.workshifter = None
		instance.log.add(entry)
		instance.save()
<commit_msg>Fixed a typo<commit_after>
from django import forms

from workshift.models import Semester, WorkshiftPool, WorkshiftType, \
	TimeBlock, WorkshiftRating, PoolHours, WorkshiftProfile, \
	RegularWorkshift, ShiftLogEntry, InstanceInfo, WorkshiftInstance

class SemesterForm(forms.ModelForm):
	class Meta:
		model = Semester
		exclude = ["workshift_managers", "preferences_open", "current"]

	def save(self, *args, **kwargs):
		semester = super(SemesterForm, self).save(*args, **kwargs)

		# Set current to false for previous semesters
		for semester in Semester.objects.all():
			semester.current = False
			semester.save()

		semester.current = True
		semester.preferences_open = True
		semester.save(*args, **kwargs)

		# TODO Copy workshift and pools over from previous semester?

		# TODO Create this semester's workshift profiles

		return semester

class RegularWorkshiftForm(forms.ModelForm):
	class Meta:
		model = RegularWorkshift
		fields = "__all__"

class WorkshiftInstanceForm(forms.ModelForm):
	class Meta:
		model = WorkshiftInstance
		exclude = ["weekly_workshift", "info", "intended_hours", "log"]

	title = forms.CharField(
		max_length=255,
		help_text="The title for this workshift",
		)
	description = forms.CharField(
		widget=forms.Textarea(),
		help_text="Description of the shift.",
		)
	pool = forms.ModelChoiceField(
		queryset=WorkshiftPool.objects.filter(semester__current=True),
		help_text="The workshift pool for this shift.",
		)
	start_time = forms.TimeField(
		required=False,
		help_text="The earliest time this shift should be started.",
		)
	end_time = forms.TimeField(
		required=False,
		help_text="The latest time this shift should be completed.",
		)

	info_fields = ["title", "description", "pool", "start_time", "end_time"]

	def __init__(self, *args, **kwargs):
		if "instance" in kwargs:
			instance = kwargs["instance"]
			initial = kwargs.get("initial", {})

			# Django ModelForms don't play nicely with foreign fields, so we
			# will just manually pre-fill them if an instance is available.
			for field in self.info_fields:
				initial.setdefault(field, getattr(instance, field))

			kwargs["initial"] = initial

			super(WorkshiftInstanceForm, self).__init__(*args, **kwargs)

			# If this is a regular workshift, disable title, description, etc
			# from being edited
			if instance.weekly_workshift:
				for field in self.info_fields:
					self.fields[field].widget.attrs['readonly'] = True
		else:
			super(WorkshiftInstanceForm, self).__init__(*args, **kwargs)

		# Move the forms for title, description, etc to the top
		keys = self.fields.keyOrder
		for field in reversed(self.info_fields):
			keys.remove(field)
			keys.insert(0, field)

	def save(self, *args, **kwargs):
		instance = super(WorkshiftInstanceForm, self).save(*args, **kwargs)
		if instance.info:
			for field in self.info_fields:
				setattr(instance.info, field, self.cleaned_data[field])
		return instance

class WorkshiftTypeForm(forms.ModelForm):
	class Meta:
		model = WorkshiftType
		fields = "__all__"

class InteractShiftForm(forms.Form):
	pk = forms.IntegerField(widget=forms.HiddenInput())

	def __init__(self, *args, **kwargs):
		self.profile = kwargs.pop("profile")
		super(InteractShiftForm, self).__init__(*args, **kwargs)

	def clean_pk(self):
		pk = self.cleaned_data["pk"]
		try:
			shift = WorkshiftInstance.objects.get(pk=pk)
		except WorkshiftInstance.DoesNotExist:
			raise forms.ValidationError("Workshift does not exist.")
		if shift.closed:
			raise forms.ValidationError("Workshift has been closed.")
		return shift

# TODO: SellShiftForm

class VerifyShiftForm(InteractShiftForm):
	title_short = "V"
	title_long = "Verify"
	action_name = "verify_shift"

	def clean_pk(self):
		shift = super(VerifyShiftForm, self).clean_pk()

		if not shift.workshifter:
			raise forms.ValidationError("Workshift is not filled.")
		if not shift.pool.self_verify and shift.workshifter == self.profile:
			raise forms.ValidationError("Workshifter cannot verify self.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.VERIFY,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.verifier = self.profile
		instance.closed = True
		instance.log.add(entry)
		instance.save()

		pool_hours = instance.workshifter.pool_hours \
		  .get(pool=instance.get_info().pool)
		pool_hours.standing += instance.hours
		pool_hours.save()

class BlownShiftForm(InteractShiftForm):
	title_short = "B"
	title_long = "Blown"
	action_name = "blown_shift"

	def clean_pk(self):
		shift = super(BlownShiftForm, self).clean_pk()

		if not shift.workshifter:
			raise forms.ValidationError("Workshift is not filled.")
		pool = shift.pool
		if not pool.any_blown and \
		  pool.managers.filter(incumbent__user=self.profile.user).count() == 0:
			raise forms.ValidationError("You are not a workshift manager.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.BLOWN,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.blown = True
		instance.closed = True
		instance.log.add(entry)
		instance.save()

		pool_hours = instance.workshifter.pool_hours \
		  .get(pool=instance.get_info().pool)
		pool_hours.standing -= instance.hours
		pool_hours.save()

class SignInForm(InteractShiftForm):
	title_short = "I"
	title_long = "Sign In"
	action_name = "sign_in"

	def clean_pk(self):
		shift = super(SignInForm, self).clean_pk()

		if shift.workshifter:
			raise forms.ValidationError("Workshift is currently filled.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.SIGNIN,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.workshifter = self.profile
		instance.log.add(entry)
		instance.save()

class SignOutForm(InteractShiftForm):
	title_short = "O"
	title_long = "Sign Out"
	action_name = "sign_out"

	def clean_pk(self):
		shift = super(SignOutForm, self).clean_pk()

		if shift.workshifter != self.profile:
			raise forms.ValidationError("Cannot sign out of others' workshift.")

		return shift

	def save(self):
		entry = ShiftLogEntry(
			person=self.profile,
			entry_type=ShiftLogEntry.SIGNOUT,
			)
		entry.save()

		instance = self.cleaned_data["pk"]
		instance.workshifter = None
		instance.log.add(entry)
		instance.save()
<|endoftext|>


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

import random

ENGINES = ["🚂"]
CARS = ["🚃","🚋"]
SCENES = ["desert","forest","beach"]

ORBS = ["🌕","🌙","☀","☁"]
DESERT_TILES = ["🌵","🌵","🌴","🌴","🐪","🐢","🐎"]
FOREST_TILES = ["🌲","🌲","🌲","🌲","🐇","🌳","🌳"]
BEACH_TILES = ["🌴","🌴","🍍","🐢","🗿"]
SEA_TILES =["🐬","🐳","🐙"]

def maketrain():
    scene = random.choice(SCENES)
    sky = make_sky()
    if scene == "desert":
        landscape, train = make_desert()
    elif scene == "forest":
        landscape, train = make_forest()
    elif scene == "beach":
        landscape, train = make_beach()
    mise_en_scene = (
    sky + "\n" + \
    landscape[0] + "\n" + \
    landscape[1] + "\n" + \
    train + "\n" + \
    landscape[2] + "\n" + \
    landscape[3])
    return mise_en_scene

def make_desert():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = DESERT_TILES
    for row in range(4):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    return landscape, train

def make_forest():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = FOREST_TILES
    for row in range(4):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    return landscape, train

def make_beach():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = BEACH_TILES
    for row in range(3):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    tileset = SEA_TILES
    lastrow = ""
    for spot in range(12):
        tile = random.randint(0,1000)
        if tile%10 == 0:
            lastrow += random.choice(tileset)
        else:
            lastrow += "🌊"
    landscape.append(lastrow)
    return landscape, train

def make_sky():
    sky = ""
    orb = random.choice(ORBS)
# It appears most clients don't let tweets lead with whitespace.
# This commented out code would have put arbitrary whitespace in the sky
# But for now we'll just put the sun or moon or cloud on the far left
#    for _ in range(20):
#        sky += " "
#    orb_placement = random.randint(0,len(sky)-1)
#    sky = sky[:orb_placement] + orb + sky[orb_placement:]
    sky = orb
    return sky

def pick_engine():
    leading_spaces = random.randint(0,9)
    engine = ""
    for _ in range(leading_spaces):
        engine += " "
    engine += random.choice(ENGINES)
    return engine

def pick_body():
    body = ""
    cars = random.randint(1,10)
    for _ in range(cars):
        body += random.choice(CARS)
    return body

if __name__ == "__main__":
    maketrain()
<commit_msg>fixed merge conflict<commit_after>#!/usr/bin/env python3

import random

ENGINES = ["🚂"]
CARS = ["🚃","🚋"]
SCENES = ["desert","forest","beach"]

ORBS = ["🌕","🌙","☀","☁"]
DESERT_TILES = ["🌵","🌵","🌴","🌴","🐪","🐢","🐎"]
FOREST_TILES = ["🌲","🌲","🌲","🌲","🐇","🌳","🌳"]
BEACH_TILES = ["🌴","🌴","🍍","🐢","🗿"]
SEA_TILES =["🐬","🐳","🐙"]
CITY_TILES = [""]

def maketrain():
    scene = random.choice(SCENES)
    sky = make_sky()
    if scene == "desert":
        landscape, train = make_desert()
    elif scene == "forest":
        landscape, train = make_forest()
    elif scene == "beach":
        landscape, train = make_beach()
#    elif scene == "city":
#        landscape, train = make_city(sky)
    mise_en_scene = (
    sky + "\n" + \
    landscape[0] + "\n" + \
    landscape[1] + "\n" + \
    train + "\n" + \
    landscape[2] + "\n" + \
    landscape[3])
    return mise_en_scene

def make_desert():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = DESERT_TILES
    for row in range(4):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    return landscape, train

def make_forest():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = FOREST_TILES
    for row in range(4):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    return landscape, train

def make_beach():
    train = pick_engine() + pick_body()
    landscape = []
    tileset = BEACH_TILES
    for row in range(3):
        row = ""
        for spot in range(20):
            tile = random.randint(0,1000)
            if tile%10 == 0:
                row += random.choice(tileset)
            else:
                row += " "
        landscape.append(row)
    tileset = SEA_TILES
    lastrow = ""
    for spot in range(12):
        tile = random.randint(0,1000)
        if tile%10 == 0:
            lastrow += random.choice(tileset)
        else:
            lastrow += "🌊"
    landscape.append(lastrow)
    return landscape, train

def make_city():
    train = "🚅" + pick_body()
    # TODO: make the rest of this city

def make_sky():
    sky = ""
    orb = random.choice(ORBS)
# It appears most clients don't let tweets lead with whitespace.
# This commented out code would have put arbitrary whitespace in the sky
# But for now we'll just put the sun or moon or cloud on the far left
#    for _ in range(20):
#        sky += " "
#    orb_placement = random.randint(0,len(sky)-1)
#    sky = sky[:orb_placement] + orb + sky[orb_placement:]
    sky = orb
    return sky

def pick_engine():
    leading_spaces = random.randint(0,9)
    engine = ""
    for _ in range(leading_spaces):
        engine += " "
    engine += random.choice(ENGINES)
    return engine

def pick_body():
    body = ""
    cars = random.randint(1,8)
    for _ in range(cars):
        body += random.choice(CARS)
    body += "💨"
    return body

if __name__ == "__main__":
    maketrain()
<|endoftext|>


<commit_before>#
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#

try:
    # The mod_python version is more efficient, so try importing it first.
    from mod_python.util import parse_qsl
except ImportError:
    from cgi import parse_qsl

from django import http
from django.core.handlers import modpython

class MintDjangoRequest(modpython.ModPythonRequest):

    def __init__(self, req):
        modpython.ModPythonRequest.__init__(self, req)

        questionParams = parse_qsl(req.args)

        if ';' in self.path:
            self.path, semiColonParams = self.path.split(';', 1)
            self.path_info = self.path
            semiColonParams = parse_qsl(semiColonParams)
        else:
            semiColonParams = []

        params = questionParams + semiColonParams
        self.params = ['%s=%s' % (k, v) for k, v in params]
        self.params = ';'.join(self.params)

    def _get_get(self):
        if not hasattr(self, '_get'):
            self._get = http.QueryDict(self.params, encoding=self._encoding)
        return self._get

    def _set_get(self, *args, **kwargs):
        return modpython.ModPythonRequest._set_get(self, *args, **kwargs)

    GET = property(_get_get, _set_get)

class MintDjangoHandler(modpython.ModPythonHandler):
    request_class = MintDjangoRequest

def handler(req):
    # mod_python hooks into this function.
    return MintDjangoHandler()(req)
<commit_msg>tell pyflakes to ignore<commit_after>#
# Copyright (c) 2010 rPath, Inc.
#
# All Rights Reserved
#

try:
    # The mod_python version is more efficient, so try importing it first.
    from mod_python.util import parse_qsl
except ImportError:
    from cgi import parse_qsl #pyflakes=ignore

from django import http
from django.core.handlers import modpython

class MintDjangoRequest(modpython.ModPythonRequest):

    def __init__(self, req):
        modpython.ModPythonRequest.__init__(self, req)

        questionParams = parse_qsl(req.args)

        if ';' in self.path:
            self.path, semiColonParams = self.path.split(';', 1)
            self.path_info = self.path
            semiColonParams = parse_qsl(semiColonParams)
        else:
            semiColonParams = []

        params = questionParams + semiColonParams
        self.params = ['%s=%s' % (k, v) for k, v in params]
        self.params = ';'.join(self.params)

    def _get_get(self):
        if not hasattr(self, '_get'):
            self._get = http.QueryDict(self.params, encoding=self._encoding)
        return self._get

    def _set_get(self, *args, **kwargs):
        return modpython.ModPythonRequest._set_get(self, *args, **kwargs)

    GET = property(_get_get, _set_get)

class MintDjangoHandler(modpython.ModPythonHandler):
    request_class = MintDjangoRequest

def handler(req):
    # mod_python hooks into this function.
    return MintDjangoHandler()(req)
<|endoftext|>