<commit_before>"""
Space game
Ryan Kynor
Checklist:
fixed star field
~~Sun sprite~~
at least one player
muliple players or multplie inanimate objects to avoid
animated rocket thrust
collisions destroy ship
moving ships
rotating ships
Source:
lines 23 - 27 based off of orininal space game code
lines 123 and 124 taken from idea in original code
"""

#key list starts a line 1067 in ggame.py file

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import cos, sin
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class Sun(Sprite):
    """
    The Sun on the Screen
    """

    asset =  ImageAsset("images/sun.png")
    height = 80
    width = 80

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Starfield(Sprite):
    """
    The Starfield
    """

    asset = ImageAsset("images/starfield.jpg")
    #height = SCREEN_HEIGHT
    #width = SCREEN_WIDTH

    def __init__(self, position):
        super().__init__(Starfield.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

#spaceship spawn movement
    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.rotateRight = 0
        self.rotateLeft = 0
        self.forward = 0
        self.explode3 = 0

        #Thrust detection
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)

        #Rotation detection

        SpaceGame.listenKeyEvent("keydown", "w", self.moveForwardOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.moveForwardOff)
        """
        SpaceGame.listenKeyEvent("keydown", "s", self.moveBackOn)
        SpaceGame.listenKeyEvent("keyup", "s", self.moveBackOff)
        """

        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeftOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.rotateLeftOff)

        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRightOn)
        SpaceGame.listenKeyEvent("keyup", "d", self.rotateRightOff)
        #Rotation animation

        #SpaceGame.listenKeyEvent("keydown", "w",
        self.fxcenter = self.fycenter = 0.5

#display of thrust
    def step(self):
        if self.explode3 == 1:
            asset = ImageAsset("images/explosion2.png", Frame(0,0,128,128), 10, "horrizontal")
        if (self.y > 200) and (self.y < 250) and (self.x > 200) and (self.x < 250):
            self.explode3 = 1
            self.vy = 0
            self.vx = 0
            self.vr = 0
            SpaceGame.listenKeyEvent("keydown", "w", self.moveForwardOff)
            print(self.explode3)
        else:
            self.explode3 = 0
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vy = self.vy -0.001
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

        #if self.collision(self.app.sun) == true:
        #    self.explode()

#rotation
        if self.rotateRight == 1:
            self.vr = self.vr -0.001
        if self.rotateLeft == 1:
            self.vr = self.vr +0.001
        self.rotation += self.vr   # <<<< change rotation!
        if self.forward == 1:  # <<<< forward
            self.vy+=(-cos(self.rotation))
            self.vx+=(-sin(self.rotation))

#thrust
    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
#explode
    def explode(self):
        print("explode")
        self.explosion(self.position)
        self.destroy()

#movement
    def moveForwardOn(self,event):
        self.forward = 1
    def moveForwardOff(self,event):
        self.forward = 0

    def moveRightOn(self,event):
        self.right = 1
    def moveRightOff(self,event):
        self.right = 0

    def moveLeftOn(self,event):
        self.left = 1
    def moveLeftOff(self,event):
        self.left = 0

    def moveBackOn(self,event):
        self.back = 1
    def moveBackOff(self,event):
        self.back = 0

#rotation
    def rotateRightOn(self,event):
        self.rotateRight = 1
    def rotateRightOff(self,event):
        self.rotateRight = 0

    def rotateLeftOn(self,event):
        self.rotateLeft = 1
    def rotateLeftOff(self,event):
        self.rotateLeft = 0

#explosion image
class explosion(Sprite):

    asset = ImageAsset ("images/explosion2.png", Frame(0,0,128,128), 10, "horrizontal")
    def __init__(self,position):
        super().__init__(explosion.asset, position)
        #self.center = (0.5,0.5)
        self.Frame = 0
        self.eSpeed = 0
    def step(self):
        self.setImage(self.Frame)
        self.eSpeed += 0.3
        #self.Frame = init(self.eSpeed)
        self.Frame += 2
        if self.Frame == 10:
            self.destroy()   # <<< self.destroy() ??

"""
if (y > 200) and (y < 250):
    if (x > 200) and (x < 250):
        explode3 = 1
else:
    explode3 = 0
"""
class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(width, height, noline, black)
        bg = Sprite(bg_asset, (0,0))

        Starfield((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        SpaceShip((190,240))
        #SpaceShip((150,150))
        #SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        for explode in self.getSpritesbyClass(explosion):
            explode.step()

#Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

#self rotation will give you the current angle of rotation in radians<commit_msg>Updated from Brython Server: 1/5/2016 2:17:50 PM<commit_after>"""
Space game
Ryan Kynor
Checklist:
fixed star field
~~Sun sprite~~
at least one player
muliple players or multplie inanimate objects to avoid
animated rocket thrust
collisions destroy ship
moving ships
rotating ships
Source:
lines 23 - 27 based off of orininal space game code
lines 123 and 124 taken from idea in original code
"""

#key list starts a line 1067 in ggame.py file

from ggame import App, RectangleAsset, ImageAsset, Sprite, LineStyle, Color, Frame
from math import cos, sin
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class Sun(Sprite):
    """
    The Sun on the Screen
    """

    asset =  ImageAsset("images/sun.png")
    height = 80
    width = 80

    def __init__(self, position):
        super().__init__(Sun.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class Starfield(Sprite):
    """
    The Starfield
    """

    asset = ImageAsset("images/starfield.jpg")
    #height = SCREEN_HEIGHT
    #width = SCREEN_WIDTH

    def __init__(self, position):
        super().__init__(Starfield.asset, position)
        self.weight = 1
        self.fxcenter = 0.5
        self.fycenter = 0.5

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

#spaceship spawn movement
    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.vx = 0
        self.vy = 0
        self.vr = 0.00
        self.thrust = 0
        self.thrustframe = 1
        self.rotateRight = 0
        self.rotateLeft = 0
        self.forward = 0
        self.explode3 = 0

        #Thrust detection
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)

        #Rotation detection

        SpaceGame.listenKeyEvent("keydown", "w", self.moveForwardOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.moveForwardOff)
        """
        SpaceGame.listenKeyEvent("keydown", "s", self.moveBackOn)
        SpaceGame.listenKeyEvent("keyup", "s", self.moveBackOff)
        """

        SpaceGame.listenKeyEvent("keydown", "a", self.rotateLeftOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.rotateLeftOff)

        SpaceGame.listenKeyEvent("keydown", "d", self.rotateRightOn)
        SpaceGame.listenKeyEvent("keyup", "d", self.rotateRightOff)
        #Rotation animation

        #SpaceGame.listenKeyEvent("keydown", "w",
        self.fxcenter = self.fycenter = 0.5

#display of thrust
    def step(self):
        if self.explode3 == 1:
            asset = ImageAsset("images/explosion2.png", Frame(0,0,128,128), 10, "horrizontal")
        if (self.y > 200) and (self.y < 250) and (self.x > 200) and (self.x < 250):
            self.explode3 = 1
            self.visible = False

        else:
            self.explode3 = 0
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vy = self.vy -0.001
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)

        #if self.collision(self.app.sun) == true:
        #    self.explode()

#rotation
        if self.rotateRight == 1:
            self.vr = self.vr -0.001
        if self.rotateLeft == 1:
            self.vr = self.vr +0.001
        self.rotation += self.vr   # <<<< change rotation!
        if self.forward == 1:  # <<<< forward
            self.vy+=(-cos(self.rotation))
            self.vx+=(-sin(self.rotation))

#thrust
    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
#explode
    def explode(self):
        print("explode")
        self.explosion(self.position)
        self.destroy()

#movement
    def moveForwardOn(self,event):
        self.forward = 1
    def moveForwardOff(self,event):
        self.forward = 0

    def moveRightOn(self,event):
        self.right = 1
    def moveRightOff(self,event):
        self.right = 0

    def moveLeftOn(self,event):
        self.left = 1
    def moveLeftOff(self,event):
        self.left = 0

    def moveBackOn(self,event):
        self.back = 1
    def moveBackOff(self,event):
        self.back = 0

#rotation
    def rotateRightOn(self,event):
        self.rotateRight = 1
    def rotateRightOff(self,event):
        self.rotateRight = 0

    def rotateLeftOn(self,event):
        self.rotateLeft = 1
    def rotateLeftOff(self,event):
        self.rotateLeft = 0

#explosion image
class explosion(Sprite):

    asset = ImageAsset ("images/explosion2.png", Frame(0,0,128,128), 10, "horrizontal")
    def __init__(self,position):
        super().__init__(explosion.asset, position)
        #self.center = (0.5,0.5)
        self.Frame = 0
        self.eSpeed = 0
    def step(self):
        self.setImage(self.Frame)
        self.eSpeed += 0.3
        #self.Frame = init(self.eSpeed)
        self.Frame += 2
        if self.Frame == 10:
            self.destroy()   # <<< self.destroy() ??

"""
if (y > 200) and (y < 250):
    if (x > 200) and (x < 250):
        explode3 = 1
else:
    explode3 = 0
"""
class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = RectangleAsset(width, height, noline, black)
        bg = Sprite(bg_asset, (0,0))

        Starfield((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
        SpaceShip((190,240))
        #SpaceShip((150,150))
        #SpaceShip((200,50))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        for explode in self.getSpritesbyClass(explosion):
            explode.step()

#Sun((SCREEN_WIDTH/2,SCREEN_HEIGHT/2))

myapp = SpaceGame(SCREEN_WIDTH, SCREEN_HEIGHT)
myapp.run()

#self rotation will give you the current angle of rotation in radians<|endoftext|>


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

import argparse
import os
import logging
import datetime

import mpmath
from sympy import (nsolve, symbols, Mul, Add, chebyshevt, exp, simplify,
    chebyshevt_root, Tuple, diff, N, solve, together, Poly, lambdify)

from sympy.utilities.decorator import conserve_mpmath_dps

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
# Change INFO to DEBUG for more output
logger.setLevel(logging.INFO)

t = symbols('t')

def general_rat_func(d, x, chebyshev=False):
    """
    Return a general rational function with numerator and denominator degree d

    Returns a tuple, (rational function, numerator coefficients, denominator coefficients)

    The constant coefficient in the denominator is always 1.
    """
    num_coeffs = symbols('p:%s' % (d+1))
    den_coeffs = symbols('q:%s' % (d+1))[1:]
    if chebyshev:
        num = Add(*(Mul(c, chebyshevt(i, x)) for i, c in enumerate(num_coeffs)))
        den = Add(*(Mul(c, chebyshevt(i, x)) for i, c in enumerate([1, *den_coeffs])))
        rat_func = num/den
    else:
        rat_func = Poly(reversed(num_coeffs), x)/Poly([*reversed(den_coeffs), 1], x)
    return rat_func, num_coeffs, den_coeffs

def nsolve_intervals(expr, bounds, division=30, solver='bisect', scale=True, **kwargs):
    """
    Divide bounds into division intervals and nsolve in each one
    """
    roots = []
    L = bounds[1] - bounds[0]
    for i in range(division):
        interval = [bounds[0] + i*L/division, bounds[0] + (i + 1)*L/division]
        try:
            logger.debug("Solving in interval %s", interval)
            if scale:
                val = expr.evalf(kwargs['prec'], subs={t:interval[0]})
                logger.debug("Scaling by %s", val)
                expr /= val
            root = nsolve(expr, interval, solver=solver, **kwargs)
        except ValueError as e:
            logger.debug("No solution found: %s", e)
            continue
        else:
            if interval[0] < root < interval[1]:
                logger.debug("Solution found: %s", root)
                roots.append(root)
            else:
                logger.warn("%s is not in %s, discarding", root, interval)

    return roots

def nsolve_points(expr, bounds, division=200, scale=True, **kwargs):
    """
    Divide bounds into division points and nsolve near each one
    """
    roots = []
    L = bounds[1] - bounds[0]
    for i in range(division):
        point = bounds[0] + i*L/division
        try:
            logger.debug("Solving near point %s", point)
            if scale:
                val = expr.evalf(kwargs['prec'], subs={t:point})
                logger.debug("Scaling by %s", val)
                expr /= val
            root = nsolve(expr, point, **kwargs)
        except ValueError as e:
            logger.debug("No solution found: %s", e)
            continue
        else:
            if root not in roots:
                logger.debug("Solution found: %s", root)
                roots.append(root)
            else:
                logger.debug("%s already found, discarding", root)

    return sorted(roots)

def plot_in_terminal(expr, *args, logname=None, **kwargs):
    """
    Run plot() but show in terminal if possible
    """
    from mpmath import plot
    f = lambdify(t, expr, mpmath)
    try:
        from iterm2_tools.images import display_image_bytes
    except ImportError:
        if logname:
            os.makedirs('plots', exist_ok=True)
            file = 'plots/%s.png' % logname
        else:
            file = None
        plot(f, *args, file=file, **kwargs)
    else:
        from io import BytesIO
        b = BytesIO()
        plot(f, *args, **kwargs, file=b)
        if logname:
            os.makedirs('plots', exist_ok=True)
            with open('plots/%s.png' % logname, 'wb') as f:
                f.write(b.getvalue())
        print(display_image_bytes(b.getvalue()))

def _get_log_file_name(locals_dict):
    d = locals_dict.copy()
    kwargs = d.pop('kwargs')
    d.update(kwargs)
    d.setdefault('maxsteps')
    d.setdefault('division')
    degree = d.pop('degree')
    prec = d.pop('prec')
    info = 'degree=%s prec=%s ' % (degree, prec)
    info += ' '.join('%s=%s' % (i, d[i]) for i in sorted(d))
    return info

# This decorator is actually not needed any more, but we leave it in as it
# will fail early if we are not running in SymPy master.
@conserve_mpmath_dps
def CRAM_exp(degree, prec=128, *, max_loops=10, c=None, maxsteps=None,
    tol=None, nsolve_type='intervals', D_scale=1, **kwargs):
    """
    Compute the CRAM approximation of exp(-t) from t in [0, oo) of the given degree

    The Remez algorithm is used.

    degree is the degree of the numerator and denominator of the
    approximation.

    prec is the precision of the floats used in the calculation. Note that, as
    of now, the result may not be accurate to prec digits.

    max_loops is the number of loops to run the Remez algorithm before giving
    up (default 10).

    c is the coefficient of the transformation c*(t + 1)/(t - 1) that is
    applied to exp(-t) to translate it to the interval [-1, 1]. It should be
    chosen so that the maximal errors of the approximation are equally spaced
    in that interval. The default is 0.6*degree.

    maxsteps is the argument passed to the mpmath bisection solver. The
    default is 1.7*prec. See also
    https://github.com/fredrik-johansson/mpmath/issues/339.

    tol is the tolerance passed to nsolve.

    nsolve_type can be 'points' or 'intervals'.

    D_scale is a factor used to scale the derivative before root finding.

    Additional keyword arguments are passed to nsolve_intervals, such as
    division and scale.

    The SymPy master branch is required for this to work.

    """
    logger.info("CRAM_exp with arguments %s", locals())

    if kwargs.get('log', True):
        os.makedirs('logs', exist_ok=True)
        logname = _get_log_file_name(locals())
        logger.addHandler(logging.FileHandler('logs/%s.log' % logname))
        logger.info("Logging to file 'logs/%s.log'", logname)
    else:
        logname = None

    epsilon, t, i, y = symbols("epsilon t i y")

    c = c or 0.6*degree
    maxsteps = int(maxsteps or 1.7*prec)
    if nsolve_type == 'points':
        nsolve_func = nsolve_points
    elif nsolve_type == 'intervals':
        nsolve_func = nsolve_intervals
    else:
        raise ValueError("nsolve_type must be 'points' or 'intervals'")

    r, num_coeffs, den_coeffs = general_rat_func(degree, t, chebyshev=True)
    E = exp(c*(t + 1)/(t - 1)) - r
    expr = E + (-1)**i*epsilon
    expr = expr*r.as_numer_denom()[1]
    expr = simplify(expr)

    points = [chebyshevt_root(2*(degree + 1) + 1, 2*(degree + 1) - j) for j in range(1, 2*(degree + 1) + 1)]
    points = [i.evalf(prec) for i in points]
    for iteration in range(max_loops):
        logger.info('-'*80)
        logger.info("Iteration %s:", iteration)
        system = Tuple(*[expr.subs({i: j, t: points[j]}) for j in range(2*degree + 1)])
        system = system + Tuple(expr.replace(exp, lambda i: 0).subs({i: 2*degree + 1, t: 1}))
        logger.debug('system: %s', system)
        logger.debug('[*num_coeffs, *den_coeffs, epsilon]: %s', [*num_coeffs, *den_coeffs, epsilon])
        sol = dict(zip([*num_coeffs, *den_coeffs, epsilon], nsolve(system,
            [*num_coeffs, *den_coeffs, epsilon], [*[1]*(2*(degree + 1) - 1), 0],
            prec=prec, maxsteps=maxsteps)))
        logger.info('sol: %s', sol)
        logger.info('system.subs(sol): %s', [i.evalf() for i in system.subs(sol)])
        D = diff(E.subs(sol), t)
        plot_in_terminal(E.subs(sol), (-1, 0.999), logname=logname + 'iteration=%s' % iteration, points=1000)
        logger.info('E.subs(sol): %s', E.subs(sol))

        D *= D_scale
        # we can't use 1 because of the singularity
        points = [-1, *nsolve_func(D, [-1, 0.999999], prec=prec, tol=tol, maxsteps=maxsteps, **kwargs), 1]
        logger.debug('points: %s', points)
        logger.info('D: %s', D)
        logger.info('[(i, D.subs(t, i)) for i in points]: %s', [(i, D.subs(t, i)) for i in points])
        if not len(points) == 2*(degree + 1):
            logger.error("ERROR: len(points) is (%s), not 2*(degree + 1) (%s)",
                len(points), 2*(degree + 1))
            raise RuntimeError
        Evals = [E.evalf(prec, subs={**sol, t: point}) for point in points[:-1]] + [-r.evalf(prec, subs={**sol, t: 1})]
        logger.info('Evals: %s', Evals)
        maxmin = N(max(map(abs, Evals)) - min(map(abs, Evals)))
        logger.info('max - min: %s', maxmin)
        logger.info('epsilon: %s', N(sol[epsilon]))
        # if maxmin < 10**-prec:
        #     logger.info("Converged in %d iterations.", iteration + 1)
        #     break
    else:
        logger.warn("!!!WARNING: DID NOT CONVERGE AFTER %d ITERATIONS!!!", max_loops)

    inv = solve(-c*(t + 1)/(t - 1) - y, t)[0].subs(y, t)
    n, d = together(r.subs(sol).subs(t, inv)).as_numer_denom() # simplify/cancel here will add degree to the numerator and denominator
    rat_func = (Poly(n)/Poly(d).TC())/(Poly(d)/Poly(d).TC())
    return rat_func.evalf(prec)

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('degree', type=int)
    parser.add_argument('prec', type=int)
    parser.add_argument('--division', type=int)
    parser.add_argument('--c', type=float)
    parser.add_argument('--maxsteps', type=int)
    parser.add_argument('--max-loops', type=int)
    parser.add_argument('--tol', type=mpmath.mpf)
    parser.add_argument('--nsolve-type', default=None, choices=['points',
        'intervals'])
    parser.add_argument('--solver', default=None)
    parser.add_argument('--D-scale', default=None, type=float)
    parser.add_argument('--scale', default=None, type=bool)
    parser.add_argument('--log-level', default=None, choices=['debug', 'info',
        'warning', 'error', 'critical'])
    try:
        import argcomplete
        argcomplete.autocomplete(parser)
    except ImportError:
        pass
    args = parser.parse_args()

    arguments = args.__dict__.copy()
    for i in arguments.copy():
        if not arguments[i]:
           del arguments[i]
    if args.log_level:
        logger.setLevel(getattr(logging, args.log_level.upper()))
        del arguments['log_level']

    logger.info("Start time: %s", datetime.datetime.now())
    try:
        rat_func = CRAM_exp(**arguments)
    except BaseException as e:
        logger.error("Exception raised", exc_info=True)
        raise
    finally:
        logger.info("End time: %s", datetime.datetime.now())

    logger.info('rat_func: %s', rat_func)
    # TODO: log this plot
    plot_in_terminal(rat_func - exp(-t), (0, 100), points=1000)

if __name__ == '__main__':
    main()
<commit_msg>Revert "Try not breaking on the convergence condition"<commit_after>#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK

import argparse
import os
import logging
import datetime

import mpmath
from sympy import (nsolve, symbols, Mul, Add, chebyshevt, exp, simplify,
    chebyshevt_root, Tuple, diff, N, solve, together, Poly, lambdify)

from sympy.utilities.decorator import conserve_mpmath_dps

logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
# Change INFO to DEBUG for more output
logger.setLevel(logging.INFO)

t = symbols('t')

def general_rat_func(d, x, chebyshev=False):
    """
    Return a general rational function with numerator and denominator degree d

    Returns a tuple, (rational function, numerator coefficients, denominator coefficients)

    The constant coefficient in the denominator is always 1.
    """
    num_coeffs = symbols('p:%s' % (d+1))
    den_coeffs = symbols('q:%s' % (d+1))[1:]
    if chebyshev:
        num = Add(*(Mul(c, chebyshevt(i, x)) for i, c in enumerate(num_coeffs)))
        den = Add(*(Mul(c, chebyshevt(i, x)) for i, c in enumerate([1, *den_coeffs])))
        rat_func = num/den
    else:
        rat_func = Poly(reversed(num_coeffs), x)/Poly([*reversed(den_coeffs), 1], x)
    return rat_func, num_coeffs, den_coeffs

def nsolve_intervals(expr, bounds, division=30, solver='bisect', scale=True, **kwargs):
    """
    Divide bounds into division intervals and nsolve in each one
    """
    roots = []
    L = bounds[1] - bounds[0]
    for i in range(division):
        interval = [bounds[0] + i*L/division, bounds[0] + (i + 1)*L/division]
        try:
            logger.debug("Solving in interval %s", interval)
            if scale:
                val = expr.evalf(kwargs['prec'], subs={t:interval[0]})
                logger.debug("Scaling by %s", val)
                expr /= val
            root = nsolve(expr, interval, solver=solver, **kwargs)
        except ValueError as e:
            logger.debug("No solution found: %s", e)
            continue
        else:
            if interval[0] < root < interval[1]:
                logger.debug("Solution found: %s", root)
                roots.append(root)
            else:
                logger.warn("%s is not in %s, discarding", root, interval)

    return roots

def nsolve_points(expr, bounds, division=200, scale=True, **kwargs):
    """
    Divide bounds into division points and nsolve near each one
    """
    roots = []
    L = bounds[1] - bounds[0]
    for i in range(division):
        point = bounds[0] + i*L/division
        try:
            logger.debug("Solving near point %s", point)
            if scale:
                val = expr.evalf(kwargs['prec'], subs={t:point})
                logger.debug("Scaling by %s", val)
                expr /= val
            root = nsolve(expr, point, **kwargs)
        except ValueError as e:
            logger.debug("No solution found: %s", e)
            continue
        else:
            if root not in roots:
                logger.debug("Solution found: %s", root)
                roots.append(root)
            else:
                logger.debug("%s already found, discarding", root)

    return sorted(roots)

def plot_in_terminal(expr, *args, logname=None, **kwargs):
    """
    Run plot() but show in terminal if possible
    """
    from mpmath import plot
    f = lambdify(t, expr, mpmath)
    try:
        from iterm2_tools.images import display_image_bytes
    except ImportError:
        if logname:
            os.makedirs('plots', exist_ok=True)
            file = 'plots/%s.png' % logname
        else:
            file = None
        plot(f, *args, file=file, **kwargs)
    else:
        from io import BytesIO
        b = BytesIO()
        plot(f, *args, **kwargs, file=b)
        if logname:
            os.makedirs('plots', exist_ok=True)
            with open('plots/%s.png' % logname, 'wb') as f:
                f.write(b.getvalue())
        print(display_image_bytes(b.getvalue()))

def _get_log_file_name(locals_dict):
    d = locals_dict.copy()
    kwargs = d.pop('kwargs')
    d.update(kwargs)
    d.setdefault('maxsteps')
    d.setdefault('division')
    degree = d.pop('degree')
    prec = d.pop('prec')
    info = 'degree=%s prec=%s ' % (degree, prec)
    info += ' '.join('%s=%s' % (i, d[i]) for i in sorted(d))
    return info

# This decorator is actually not needed any more, but we leave it in as it
# will fail early if we are not running in SymPy master.
@conserve_mpmath_dps
def CRAM_exp(degree, prec=128, *, max_loops=10, c=None, maxsteps=None,
    tol=None, nsolve_type='intervals', D_scale=1, **kwargs):
    """
    Compute the CRAM approximation of exp(-t) from t in [0, oo) of the given degree

    The Remez algorithm is used.

    degree is the degree of the numerator and denominator of the
    approximation.

    prec is the precision of the floats used in the calculation. Note that, as
    of now, the result may not be accurate to prec digits.

    max_loops is the number of loops to run the Remez algorithm before giving
    up (default 10).

    c is the coefficient of the transformation c*(t + 1)/(t - 1) that is
    applied to exp(-t) to translate it to the interval [-1, 1]. It should be
    chosen so that the maximal errors of the approximation are equally spaced
    in that interval. The default is 0.6*degree.

    maxsteps is the argument passed to the mpmath bisection solver. The
    default is 1.7*prec. See also
    https://github.com/fredrik-johansson/mpmath/issues/339.

    tol is the tolerance passed to nsolve.

    nsolve_type can be 'points' or 'intervals'.

    D_scale is a factor used to scale the derivative before root finding.

    Additional keyword arguments are passed to nsolve_intervals, such as
    division and scale.

    The SymPy master branch is required for this to work.

    """
    logger.info("CRAM_exp with arguments %s", locals())

    if kwargs.get('log', True):
        os.makedirs('logs', exist_ok=True)
        logname = _get_log_file_name(locals())
        logger.addHandler(logging.FileHandler('logs/%s.log' % logname))
        logger.info("Logging to file 'logs/%s.log'", logname)
    else:
        logname = None

    epsilon, t, i, y = symbols("epsilon t i y")

    c = c or 0.6*degree
    maxsteps = int(maxsteps or 1.7*prec)
    if nsolve_type == 'points':
        nsolve_func = nsolve_points
    elif nsolve_type == 'intervals':
        nsolve_func = nsolve_intervals
    else:
        raise ValueError("nsolve_type must be 'points' or 'intervals'")

    r, num_coeffs, den_coeffs = general_rat_func(degree, t, chebyshev=True)
    E = exp(c*(t + 1)/(t - 1)) - r
    expr = E + (-1)**i*epsilon
    expr = expr*r.as_numer_denom()[1]
    expr = simplify(expr)

    points = [chebyshevt_root(2*(degree + 1) + 1, 2*(degree + 1) - j) for j in range(1, 2*(degree + 1) + 1)]
    points = [i.evalf(prec) for i in points]
    for iteration in range(max_loops):
        logger.info('-'*80)
        logger.info("Iteration %s:", iteration)
        system = Tuple(*[expr.subs({i: j, t: points[j]}) for j in range(2*degree + 1)])
        system = system + Tuple(expr.replace(exp, lambda i: 0).subs({i: 2*degree + 1, t: 1}))
        logger.debug('system: %s', system)
        logger.debug('[*num_coeffs, *den_coeffs, epsilon]: %s', [*num_coeffs, *den_coeffs, epsilon])
        sol = dict(zip([*num_coeffs, *den_coeffs, epsilon], nsolve(system,
            [*num_coeffs, *den_coeffs, epsilon], [*[1]*(2*(degree + 1) - 1), 0],
            prec=prec, maxsteps=maxsteps)))
        logger.info('sol: %s', sol)
        logger.info('system.subs(sol): %s', [i.evalf() for i in system.subs(sol)])
        D = diff(E.subs(sol), t)
        plot_in_terminal(E.subs(sol), (-1, 0.999), logname=logname + 'iteration=%s' % iteration, points=1000)
        logger.info('E.subs(sol): %s', E.subs(sol))

        D *= D_scale
        # we can't use 1 because of the singularity
        points = [-1, *nsolve_func(D, [-1, 0.999999], prec=prec, tol=tol, maxsteps=maxsteps, **kwargs), 1]
        logger.debug('points: %s', points)
        logger.info('D: %s', D)
        logger.info('[(i, D.subs(t, i)) for i in points]: %s', [(i, D.subs(t, i)) for i in points])
        if not len(points) == 2*(degree + 1):
            logger.error("ERROR: len(points) is (%s), not 2*(degree + 1) (%s)",
                len(points), 2*(degree + 1))
            raise RuntimeError
        Evals = [E.evalf(prec, subs={**sol, t: point}) for point in points[:-1]] + [-r.evalf(prec, subs={**sol, t: 1})]
        logger.info('Evals: %s', Evals)
        maxmin = N(max(map(abs, Evals)) - min(map(abs, Evals)))
        logger.info('max - min: %s', maxmin)
        logger.info('epsilon: %s', N(sol[epsilon]))
        if maxmin < 10**-prec:
            logger.info("Converged in %d iterations.", iteration + 1)
            break
    else:
        logger.warn("!!!WARNING: DID NOT CONVERGE AFTER %d ITERATIONS!!!", max_loops)

    inv = solve(-c*(t + 1)/(t - 1) - y, t)[0].subs(y, t)
    n, d = together(r.subs(sol).subs(t, inv)).as_numer_denom() # simplify/cancel here will add degree to the numerator and denominator
    rat_func = (Poly(n)/Poly(d).TC())/(Poly(d)/Poly(d).TC())
    return rat_func.evalf(prec)

def main():
    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('degree', type=int)
    parser.add_argument('prec', type=int)
    parser.add_argument('--division', type=int)
    parser.add_argument('--c', type=float)
    parser.add_argument('--maxsteps', type=int)
    parser.add_argument('--max-loops', type=int)
    parser.add_argument('--tol', type=mpmath.mpf)
    parser.add_argument('--nsolve-type', default=None, choices=['points',
        'intervals'])
    parser.add_argument('--solver', default=None)
    parser.add_argument('--D-scale', default=None, type=float)
    parser.add_argument('--scale', default=None, type=bool)
    parser.add_argument('--log-level', default=None, choices=['debug', 'info',
        'warning', 'error', 'critical'])
    try:
        import argcomplete
        argcomplete.autocomplete(parser)
    except ImportError:
        pass
    args = parser.parse_args()

    arguments = args.__dict__.copy()
    for i in arguments.copy():
        if not arguments[i]:
           del arguments[i]
    if args.log_level:
        logger.setLevel(getattr(logging, args.log_level.upper()))
        del arguments['log_level']

    logger.info("Start time: %s", datetime.datetime.now())
    try:
        rat_func = CRAM_exp(**arguments)
    except BaseException as e:
        logger.error("Exception raised", exc_info=True)
        raise
    finally:
        logger.info("End time: %s", datetime.datetime.now())

    logger.info('rat_func: %s', rat_func)
    # TODO: log this plot
    plot_in_terminal(rat_func - exp(-t), (0, 100), points=1000)

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


<commit_before>from feed.models import Post, Author, Comment, Friend
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from feed.models import Author
from django.contrib.auth.models import User
import urllib2, base64
import requests
import json

@login_required
# Create your views here.
def friends(request):
	user_object = User.objects.get(username = request.user.username)
	author_object = Author.objects.get(email = user_object)
	# gets
	followed_by = Friend.objects.filter(followed_id=author_object.id)
	following = Friend.objects.filter(follower_id=author_object.id)

	all_authors = Author.objects.all()

	friend_requests = list()
	my_friends = list()

	# Get all friends if they're local
	for i in followed_by:
		# if the followed_id == the use id, then add them to our list
		if (author_object.id == i.followed_id):
			req = urllib2.Request("http://ditto-test.herokuapp.com/api/friends/%s/%s" % (str(i.follower_id), str(i.followed_id)))

			base64string = base64.encodestring('%s:%s' % ("admin", "pass")).replace('\n', '')
			req.add_header("Authorization", "Basic %s" % base64string)

			response = urllib2.urlopen(req).read()
			loaded = json.loads(response)
			print "did ditto-test request"
			# friend is local
			try:
				friend = Author.objects.get(id=i.follower_id)
				print "Friend:"
				print friend
			# friend is foreign
			except:
				print i.follower_id
				print i.followed_id
				url = "http://mighty-cliffs-82717.herokuapp.com/api/author/%s" % str(i.follower_id)
				req = urllib2.Request("http://mighty-cliffs-82717.herokuapp.com/api/author/%s" % str(i.follower_id))
				print "attempting mighty request"
				response = urllib2.urlopen(req).read()
				print "Response: "
				print response
				loaded = json.loads(response)
				#print loaded['id']
				friend = loaded

			if friend.id != author_object.id and not loaded.get('friends'):
				friend_requests.append(friend)
			else:
				my_friends.append(friend)

	# For host in hosts:
		# Grab all authors on their server
			# If an author id matches the follower_id in one of our friend requests
				# Append that person to friend_requests

	# send request to other servers to load their friends
	foreign_authors = {'authors':[]}
	try:
		r = requests.get('http://mighty-cliffs-82717.herokuapp.com/api/authors')
		#print r.text

		#r = requests.get('http://localhost:8001/api/authors', auth=("admin", "pass"))

		foreign_authors = json.loads(r.text)
	except Exception as e:
		print e
		pass

	context = {
		'authors': all_authors,
		'current_author': author_object,
		'friends': my_friends,
		'friend_requests': friend_requests,
		'foreign_authors': foreign_authors['authors'],
	}

	return render(request, 'friends.html', context)
<commit_msg>sdhfjksdf<commit_after>from feed.models import Post, Author, Comment, Friend
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from feed.models import Author
from django.contrib.auth.models import User
import urllib2, base64
import requests
import json

@login_required
# Create your views here.
def friends(request):
	user_object = User.objects.get(username = request.user.username)
	author_object = Author.objects.get(email = user_object)
	# gets
	followed_by = Friend.objects.filter(followed_id=author_object.id)
	following = Friend.objects.filter(follower_id=author_object.id)

	all_authors = Author.objects.all()

	friend_requests = list()
	my_friends = list()

	# Get all friends if they're local
	for i in followed_by:
		# if the followed_id == the use id, then add them to our list
		if (author_object.id == i.followed_id):
			req = urllib2.Request("http://ditto-test.herokuapp.com/api/friends/%s/%s" % (str(i.follower_id), str(i.followed_id)))

			base64string = base64.encodestring('%s:%s' % ("admin", "pass")).replace('\n', '')
			req.add_header("Authorization", "Basic %s" % base64string)

			response = urllib2.urlopen(req).read()
			loaded = json.loads(response)
			print "did ditto-test request"
			# friend is local
			try:
				friend = Author.objects.get(id=i.follower_id)
				print "Friend:"
				print friend
			# friend is foreign
			except:
				print i.follower_id
				print i.followed_id
				url = "http://mighty-cliffs-82717.herokuapp.com/api/author/%s" % str(i.follower_id)
				req = urllib2.Request("http://mighty-cliffs-82717.herokuapp.com/api/author/%s" % str(i.follower_id))
				print "attempting mighty request"
				response = urllib2.urlopen(req).read()
				print "Response: "
				print response
				loaded = json.loads(response)
				#print loaded['id']
				friend = loaded

			if type(friend) == type({}):
				if friend['id'] != author_object.id and not loaded.get('friends'):
					friend_requests.append(friend)
				else:
					my_friends.append(friend)

			else:
				if friend.id != author_object.id and not loaded.get('friends'):
					friend_requests.append(friend)
				else:
					my_friends.append(friend)

	# For host in hosts:
		# Grab all authors on their server
			# If an author id matches the follower_id in one of our friend requests
				# Append that person to friend_requests

	# send request to other servers to load their friends
	foreign_authors = {'authors':[]}
	try:
		r = requests.get('http://mighty-cliffs-82717.herokuapp.com/api/authors')
		#print r.text

		#r = requests.get('http://localhost:8001/api/authors', auth=("admin", "pass"))

		foreign_authors = json.loads(r.text)
	except Exception as e:
		print e
		pass

	context = {
		'authors': all_authors,
		'current_author': author_object,
		'friends': my_friends,
		'friend_requests': friend_requests,
		'foreign_authors': foreign_authors['authors'],
	}

	return render(request, 'friends.html', context)
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.thrustDecel)
        SpaceGame.listenKeyEvent("keyup", "s", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if 0 <= self.rotation and self.rotation <= math.pi/4:
                self.vx = -.5
                self.vy = -1.5
            elif math.pi/4 <= self.rotation and self.rotation <= math.pi/2:
                self.vx = -1.5
                self.vy = -.5
            elif math.pi/2 <= self.rotation and self.rotation <= 3*math.pi/4:
                self.vx = -1.5
                self.vy =.5
            elif 3*math.pi/4 <= self.rotation and self.rotation <= math.pi:
                self.vx=-.5
                self.vy=1.5
            elif  math.pi <= self.rotation and self.rotation <= 5*math.pi/4:
                self.vx=.5
                self.vy=1.5
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.thrust == -1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx=self.vx+.01
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr==.1:
            self.rotation =self.rotation+.0001
        if self.vr==-.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def explode(self):
        self.visible =False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<commit_msg>Updated from Brython Server: 3/21/2016 2:55:31 PM<commit_after>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "s", self.thrustDecel)
        SpaceGame.listenKeyEvent("keyup", "s", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            if 0 <= self.rotation and self.rotation <= math.pi/4:
                self.vx = -.5
                self.vy = -1.5
            elif math.pi/4 <= self.rotation and self.rotation <= math.pi/2:
                self.vx = -1.5
                self.vy = -.5
            elif math.pi/2 <= self.rotation and self.rotation <= 3*math.pi/4:
                self.vx = -1.5
                self.vy =.5
            elif 3*math.pi/4 <= self.rotation and self.rotation <= math.pi:
                self.vx=-.5
                self.vy=1.5
            elif math.pi <= self.rotation and self.rotation <= 5*math.pi/4:
                self.vx=.5
                self.vy=1.5
            elif 5*math.pi/4 <= self.rotation and self.rotation <= 3*math.pi/2:
                self.vx =1.5
                self.vy=.5
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.thrust == -1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx=self.vx+.01
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr==.1:
            self.rotation =self.rotation+.0001
        if self.vr==-.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def explode(self):
        self.visible =False
        self.ExplosionSmall

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//2)  # slow it down
        self.image += 1
        if self.image == 20:
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

    def step(self):
            for ship in self.getSpritesbyClass(SpaceShip):
                ship.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<|endoftext|>


<commit_before>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel, Payton, Ethan

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "r", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "r", self.restartOn)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx = self.vx + .05*math.cos((self.rotation+math.pi/2))
            self.vy = self.vy + .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation = self.rotation+.0001
        if self.vr == -.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode()

        if self.reset == 1:
            self.x = 0
            self.y = 0
        elif self.reset == 0:
            self.vy = self.vy
            self.vx = self.vx

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.vx = 0
        self.vy = 0
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//5)  # slow it down
        self.image += 1
        self.boom.play()
        if self.image == 50:
            self.visible = False
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<commit_msg>Updated from Brython Server: 3/25/2016 2:16:10 PM<commit_after>"""
spaceshooter.py
Author: Avery Wallis
Credit: Original Spacewar Code, Daniel, Payton, Ethan

Assignment:
Write and submit a program that implements the spacewar game:
https://github.com/HHS-IntroProgramming/Spacewar
"""
from ggame import App, ImageAsset, RectangleAsset, SoundAsset, Frame
from ggame import LineStyle, Sprite, Sound, Color
import math

SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480

class SpaceShip(Sprite):
    """
    Animated space ship
    """
    asset = ImageAsset("images/four_spaceship_by_albertov_with_thrust.png",
        Frame(227,0,292-227,125), 4, 'vertical')

    def __init__(self, position):
        super().__init__(SpaceShip.asset, position)
        self.visible=True
        self.vx = 0
        self.vy = 0
        self.vr = 0
        self.rotation = 0
        self.thrust = 0
        self.reset = 0
        self.thrustframe = 1
        SpaceGame.listenKeyEvent("keydown", "w", self.thrustOn)
        SpaceGame.listenKeyEvent("keyup", "w", self.thrustOff)
        SpaceGame.listenKeyEvent("keydown", "a" , self.CCOn)
        SpaceGame.listenKeyEvent("keyup", "a", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "d" , self.CCthing)
        SpaceGame.listenKeyEvent("keyup", "d", self.CCOff)
        SpaceGame.listenKeyEvent("keydown", "r", self.restartOn)
        SpaceGame.listenKeyEvent("keyup", "r", self.restartOn)
        self.fxcenter = self.fycenter = 0.5

    def step(self):
        self.x += self.vx
        self.y += self.vy
        self.rotation += self.vr
        if self.thrust == 1:
            self.setImage(self.thrustframe)
            self.thrustframe += 1
            self.vx = self.vx + .05*math.cos((self.rotation+math.pi/2))
            self.vy = self.vy + .05*math.sin((self.rotation-math.pi/2))
            if self.thrustframe == 4:
                self.thrustframe = 1
            else:
                self.setImage(0)
        if self.vr == .1:
            self.rotation = self.rotation+.0001
        if self.vr == -.1:
            self.rotation =self.rotation-.0001
        if self.vr==0:
            self.rotation=self.rotation

        col= self.collidingWithSprites(Sunthing)
        if col:
            self.explode()

        if self.reset == 1:
            self.x = 0
            self.y = 0
        elif self.reset == 0:
            self.vy = self.vy
            self.vx = self.vx

    def thrustOn(self, event):
        self.thrust = 1
    def thrustOff(self, event):
        self.thrust = 0
    def thrustDecel(self, event):
        self.thrust=-1

    def CCOn(self, event):
        self.vr=.1
    def CCOff(self, event):
        self.vr=0
    def CCthing(self, event):
        self.vr=-.1

    def restartOn(self,event):
        self.reset = 1

    def restartOff(self, event):
        self.reset = 0

    def explode(self):
        self.visible = False
        self.vx = 0
        self.vy = 0
        ExplosionSmall(self.position)

class ExplosionSmall(Sprite):

    asset = ImageAsset("images/explosion1.png", Frame(0,0,128,128), 10)
    boomasset = SoundAsset("sounds/explosion1.mp3")

    def __init__(self, position):
        super().__init__(ExplosionSmall.asset, position)
        self.image = 0
        self.center = (0.5, 0.5)
        self.vx = 0
        self.vy = 0
        self.boom = Sound(ExplosionSmall.boomasset)
        self.boom.play()

    def step(self):
        self.setImage(self.image//5)  # slow it down
        self.image += 1
        self.boom.play()
        if self.image == 50:
            self.visible = False
            self.destroy()

class Sunthing(Sprite):
    asset=ImageAsset("images/sun.png")
    width=80
    length=76
    def __init__(self, position):
        super().__init__(Sunthing.asset, position)
        self.mass = 30*1000
        self.fxcenter = 0.5
        self.fycenter = 0.5
        self.circularCollisionModel()

class SpaceGame(App):
    """
    Tutorial4 space game example.
    """
    def __init__(self, width, height):
        super().__init__(width, height)
        black = Color(0, 1)
        noline = LineStyle(0, black)
        bg_asset = ImageAsset("images/starfield.jpg")
        star0 = Sprite(bg_asset, (0,0))
        star1= Sprite(bg_asset, (512,0))
        star2= Sprite(bg_asset, (0,512))
        star3= Sprite(bg_asset, (512, 512))
        Sunthing((500,360))
        SpaceShip((300,300))

    def step(self):
        for ship in self.getSpritesbyClass(SpaceShip):
            ship.step()
        explosions = self.getSpritesbyClass(ExplosionSmall)
        for explosion in explosions:
            explosion.step()

myapp = SpaceGame(SCREEN_WIDTH*1.5, SCREEN_HEIGHT*1.5)
myapp.run()
<|endoftext|>


<commit_before>import textwrap
from .AttributeNodes import ATTRIBUTE_NODES  # noqa: I201
from .AvailabilityNodes import AVAILABILITY_NODES  # noqa: I201
from . import Classification  # noqa: I201
from .CommonNodes import COMMON_NODES  # noqa: I201
from .DeclNodes import DECL_NODES  # noqa: I201
from .ExprNodes import EXPR_NODES  # noqa: I201
from .GenericNodes import GENERIC_NODES  # noqa: I201

from . import Token

from .NodeSerializationCodes import SYNTAX_NODE_SERIALIZATION_CODES, \
    get_serialization_code, \
    verify_syntax_node_serialization_codes

from .PatternNodes import PATTERN_NODES  # noqa: I201
from .StmtNodes import STMT_NODES  # noqa: I201

from .Trivia import TRIVIAS  # noqa: I201
from .TypeNodes import TYPE_NODES  # noqa: I201

# Re-export global constants
SYNTAX_NODES = COMMON_NODES + EXPR_NODES + DECL_NODES + ATTRIBUTE_NODES + \
    STMT_NODES + GENERIC_NODES + TYPE_NODES + PATTERN_NODES + \
    AVAILABILITY_NODES
SYNTAX_TOKENS = Token.SYNTAX_TOKENS
SYNTAX_TOKEN_MAP = Token.SYNTAX_TOKEN_MAP
SYNTAX_CLASSIFICATIONS = Classification.SYNTAX_CLASSIFICATIONS

verify_syntax_node_serialization_codes(SYNTAX_NODES,
                                       SYNTAX_NODE_SERIALIZATION_CODES)

def make_missing_child(child):
    """
    Generates a C++ call to make the raw syntax for a given Child object.
    """
    if child.is_token():
        token = child.main_token()
        tok_kind = token.kind if token else "unknown"
        tok_text = token.text if token else ""
        return \
            'RawSyntax::missing(tok::%s, OwnedString::makeUnowned("%s"))' % \
            (tok_kind, tok_text)
    else:
        missing_kind = "Unknown" if child.syntax_kind == "Syntax" \
                       else child.syntax_kind
        if child.node_choices:
            return make_missing_child(child.node_choices[0])
        return 'RawSyntax::missing(SyntaxKind::%s)' % missing_kind

def check_child_condition_raw(child):
    """
    Generates a C++ closure to check whether a given raw syntax node can
    satisfy the requirements of child.
    """
    result = '[](const RC<RawSyntax> &Raw) {\n'
    result += ' // check %s\n' % child.name
    if child.token_choices:
        result += 'if (!Raw->isToken()) return false;\n'
        result += 'auto TokKind = Raw->getTokenKind();\n'
        tok_checks = []
        for choice in child.token_choices:
            tok_checks.append("TokKind == tok::%s" % choice.kind)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.text_choices:
        result += 'if (!Raw->isToken()) return false;\n'
        result += 'auto Text = Raw->getTokenText();\n'
        tok_checks = []
        for choice in child.text_choices:
            tok_checks.append('Text == "%s"' % choice)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.node_choices:
        node_checks = []
        for choice in child.node_choices:
            node_checks.append(check_child_condition_raw(choice) + '(Raw)')
        result += 'return %s;\n' % ((' || ').join(node_checks))
    else:
        result += 'return %s::kindof(Raw->getKind());' % child.type_name
    result += '}'
    return result

def check_parsed_child_condition_raw(child):
    """
    Generates a C++ closure to check whether a given raw syntax node can
    satisfy the requirements of child.
    """
    result = '[](const ParsedRawSyntaxNode &Raw) {\n'
    result += ' // check %s\n' % child.name
    if child.token_choices:
        result += 'if (!Raw.isToken()) return false;\n'
        result += 'auto TokKind = Raw.getTokenKind();\n'
        tok_checks = []
        for choice in child.token_choices:
            tok_checks.append("TokKind == tok::%s" % choice.kind)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.text_choices:
        result += 'return Raw.isToken();\n'
    elif child.node_choices:
        node_checks = []
        for choice in child.node_choices:
            node_checks.append(
                check_parsed_child_condition_raw(choice) + '(Raw)')
        result += 'return %s;\n' % ((' || ').join(node_checks))
    else:
        result += 'return Parsed%s::kindof(Raw.getKind());' % child.type_name
    result += '}'
    return result

def make_missing_swift_child(child):
    """
    Generates a Swift call to make the raw syntax for a given Child object.
    """
    if child.is_token():
        token = child.main_token()
        tok_kind = token.swift_kind() if token else "unknown"
        if not token or not token.text:
            tok_kind += '("")'
        return 'RawSyntax.missingToken(TokenKind.%s)' % tok_kind
    else:
        missing_kind = "unknown" if child.syntax_kind == "Syntax" \
                       else child.swift_syntax_kind
        return 'RawSyntax.missing(SyntaxKind.%s)' % missing_kind

def create_node_map():
    """
    Creates a lookup table to find nodes by their kind.
    """
    return {node.syntax_kind: node for node in SYNTAX_NODES}

def is_visitable(node):
    return not node.is_base()

def dedented_lines(description):
    """
    Each line of the provided string with leading whitespace stripped.
    """
    if not description:
        return []
    return textwrap.dedent(description).split('\n')

def hash_syntax_node(node):
    # Hash into the syntax name and serialization code
    result = hash((node.name, get_serialization_code(node.syntax_kind)))
    for child in node.children:
        # Hash into the expected child syntax
        result = hash((result, child.syntax_kind))
        # Hash into the child name
        result = hash((result, child.name))
        # Hash into whether the child is optional
        result = hash((result, child.is_optional))
    return result

def hash_token_syntax(token):
    # Hash into the token name and serialization code
    return hash((token.name, token.serialization_code))

def hash_trivia(trivia):
    return hash((trivia.name, trivia.serialization_code, trivia.characters))

def calculate_node_hash():
    result = 0
    for node in SYNTAX_NODES:
        result = hash((result, hash_syntax_node(node)))
    for token in SYNTAX_TOKENS:
        result = hash((result, hash_token_syntax(token)))
    for trivia in TRIVIAS:
        result = hash((result, hash_trivia(trivia)))
    return result
<commit_msg>gyb: clean up some linter warnings<commit_after>import textwrap
from . import Classification  # noqa: I201
from . import Token
from .AttributeNodes import ATTRIBUTE_NODES  # noqa: I201
from .AvailabilityNodes import AVAILABILITY_NODES  # noqa: I201
from .CommonNodes import COMMON_NODES  # noqa: I201
from .DeclNodes import DECL_NODES  # noqa: I201
from .ExprNodes import EXPR_NODES  # noqa: I201
from .GenericNodes import GENERIC_NODES  # noqa: I201
from .NodeSerializationCodes import SYNTAX_NODE_SERIALIZATION_CODES, \
    get_serialization_code, \
    verify_syntax_node_serialization_codes
from .PatternNodes import PATTERN_NODES  # noqa: I201
from .StmtNodes import STMT_NODES  # noqa: I201
from .Trivia import TRIVIAS  # noqa: I201
from .TypeNodes import TYPE_NODES  # noqa: I201

# Re-export global constants
SYNTAX_NODES = COMMON_NODES + EXPR_NODES + DECL_NODES + ATTRIBUTE_NODES + \
    STMT_NODES + GENERIC_NODES + TYPE_NODES + PATTERN_NODES + \
    AVAILABILITY_NODES
SYNTAX_TOKENS = Token.SYNTAX_TOKENS
SYNTAX_TOKEN_MAP = Token.SYNTAX_TOKEN_MAP
SYNTAX_CLASSIFICATIONS = Classification.SYNTAX_CLASSIFICATIONS

verify_syntax_node_serialization_codes(SYNTAX_NODES,
                                       SYNTAX_NODE_SERIALIZATION_CODES)

def make_missing_child(child):
    """
    Generates a C++ call to make the raw syntax for a given Child object.
    """
    if child.is_token():
        token = child.main_token()
        tok_kind = token.kind if token else "unknown"
        tok_text = token.text if token else ""
        return \
            'RawSyntax::missing(tok::%s, OwnedString::makeUnowned("%s"))' % \
            (tok_kind, tok_text)
    else:
        missing_kind = "Unknown" if child.syntax_kind == "Syntax" \
                       else child.syntax_kind
        if child.node_choices:
            return make_missing_child(child.node_choices[0])
        return 'RawSyntax::missing(SyntaxKind::%s)' % missing_kind

def check_child_condition_raw(child):
    """
    Generates a C++ closure to check whether a given raw syntax node can
    satisfy the requirements of child.
    """
    result = '[](const RC<RawSyntax> &Raw) {\n'
    result += ' // check %s\n' % child.name
    if child.token_choices:
        result += 'if (!Raw->isToken()) return false;\n'
        result += 'auto TokKind = Raw->getTokenKind();\n'
        tok_checks = []
        for choice in child.token_choices:
            tok_checks.append("TokKind == tok::%s" % choice.kind)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.text_choices:
        result += 'if (!Raw->isToken()) return false;\n'
        result += 'auto Text = Raw->getTokenText();\n'
        tok_checks = []
        for choice in child.text_choices:
            tok_checks.append('Text == "%s"' % choice)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.node_choices:
        node_checks = []
        for choice in child.node_choices:
            node_checks.append(check_child_condition_raw(choice) + '(Raw)')
        result += 'return %s;\n' % ((' || ').join(node_checks))
    else:
        result += 'return %s::kindof(Raw->getKind());' % child.type_name
    result += '}'
    return result

def check_parsed_child_condition_raw(child):
    """
    Generates a C++ closure to check whether a given raw syntax node can
    satisfy the requirements of child.
    """
    result = '[](const ParsedRawSyntaxNode &Raw) {\n'
    result += ' // check %s\n' % child.name
    if child.token_choices:
        result += 'if (!Raw.isToken()) return false;\n'
        result += 'auto TokKind = Raw.getTokenKind();\n'
        tok_checks = []
        for choice in child.token_choices:
            tok_checks.append("TokKind == tok::%s" % choice.kind)
        result += 'return %s;\n' % (' || '.join(tok_checks))
    elif child.text_choices:
        result += 'return Raw.isToken();\n'
    elif child.node_choices:
        node_checks = []
        for choice in child.node_choices:
            node_checks.append(
                check_parsed_child_condition_raw(choice) + '(Raw)')
        result += 'return %s;\n' % ((' || ').join(node_checks))
    else:
        result += 'return Parsed%s::kindof(Raw.getKind());' % child.type_name
    result += '}'
    return result

def make_missing_swift_child(child):
    """
    Generates a Swift call to make the raw syntax for a given Child object.
    """
    if child.is_token():
        token = child.main_token()
        tok_kind = token.swift_kind() if token else "unknown"
        if not token or not token.text:
            tok_kind += '("")'
        return 'RawSyntax.missingToken(TokenKind.%s)' % tok_kind
    else:
        missing_kind = "unknown" if child.syntax_kind == "Syntax" \
                       else child.swift_syntax_kind
        return 'RawSyntax.missing(SyntaxKind.%s)' % missing_kind

def create_node_map():
    """
    Creates a lookup table to find nodes by their kind.
    """
    return {node.syntax_kind: node for node in SYNTAX_NODES}

def is_visitable(node):
    return not node.is_base()

def dedented_lines(description):
    """
    Each line of the provided string with leading whitespace stripped.
    """
    if not description:
        return []
    return textwrap.dedent(description).split('\n')

def hash_syntax_node(node):
    # Hash into the syntax name and serialization code
    result = hash((node.name, get_serialization_code(node.syntax_kind)))
    for child in node.children:
        # Hash into the expected child syntax
        result = hash((result, child.syntax_kind))
        # Hash into the child name
        result = hash((result, child.name))
        # Hash into whether the child is optional
        result = hash((result, child.is_optional))
    return result

def hash_token_syntax(token):
    # Hash into the token name and serialization code
    return hash((token.name, token.serialization_code))

def hash_trivia(trivia):
    return hash((trivia.name, trivia.serialization_code, trivia.characters))

def calculate_node_hash():
    result = 0
    for node in SYNTAX_NODES:
        result = hash((result, hash_syntax_node(node)))
    for token in SYNTAX_TOKENS:
        result = hash((result, hash_token_syntax(token)))
    for trivia in TRIVIAS:
        result = hash((result, hash_trivia(trivia)))
    return result
<|endoftext|>


<commit_before># coding=utf-8
import sys
import random
import findspam
import datahandling
import chatcommunicate
from globalvars import GlobalVars
from datetime import datetime, timedelta
import regex
import parsing
import metasmoke
import excepthook
from classes import Post, PostParseError
from helpers import log, escape_format
from parsing import to_metasmoke_link
from tasks import Tasks

# noinspection PyMissingTypeHints
def should_whitelist_prevent_alert(user_url, reasons):
    is_whitelisted = datahandling.is_whitelisted_user(parsing.get_user_from_url(user_url))
    if not is_whitelisted:
        return False
    return not any(r for r in set(reasons) if "username" not in r)

def sum_weight(reasons: list):
    if not GlobalVars.reason_weights:
        datahandling.update_reason_weights()
    now = datetime.utcnow() - timedelta(minutes=15)
    if 'last_updated' not in GlobalVars.reason_weights or \
            (now.date() != GlobalVars.reason_weights['last_updated'] and now.hour >= 1):
        Tasks.do(datahandling.update_reason_weights)
    s = 0
    weights = GlobalVars.reason_weights
    for r in reasons:
        try:
            if "(" in r:
                r = regex.sub(r"\s*\(.*$", "", r)
            s += weights[r.lower()]
        except KeyError:
            pass  # s += 0
    return s

# noinspection PyMissingTypeHints
def check_if_spam(post):
    test, why = findspam.FindSpam.test_post(post)
    if datahandling.is_blacklisted_user(parsing.get_user_from_url(post.user_url)):
        test.append("blacklisted user")
        blacklisted_user_data = datahandling.get_blacklisted_user_data(parsing.get_user_from_url(post.user_url))
        if len(blacklisted_user_data) > 1:
            if blacklisted_user_data[1] == "metasmoke":
                blacklisted_by = "the metasmoke API"
            else:
                blacklisted_by = blacklisted_user_data[1]
            blacklisted_post_url = blacklisted_user_data[2]
            if why and why[-1] == "\n":
                why = why[:-1]
            if blacklisted_post_url:
                rel_url = blacklisted_post_url.replace("http:", "", 1)
                ms_url = datahandling.resolve_ms_link(rel_url) or to_metasmoke_link(rel_url)
                why += "\nBlacklisted user - blacklisted for {} ({}) by {}".format(
                    blacklisted_post_url, ms_url, blacklisted_by)
            else:
                why += "\n" + u"Blacklisted user - blacklisted by {}".format(blacklisted_by)
    if test:
        result = None
        if datahandling.has_already_been_posted(post.post_site, post.post_id, post.title):
            result = "post has already been reported"
        elif datahandling.is_false_positive((post.post_id, post.post_site)):
            result = "post is marked as false positive"
        elif should_whitelist_prevent_alert(post.user_url, test):
            result = "user is whitelisted"
        elif datahandling.is_ignored_post((post.post_id, post.post_site)):
            result = "post is ignored"
        elif datahandling.is_auto_ignored_post((post.post_id, post.post_site)):
            result = "post is automatically ignored"
        elif datahandling.has_community_bumped_post(post.post_url, post.body):
            result = "post is bumped by Community \u2666\uFE0F"
        # Dirty approach
        if result is None:  # Post not ignored
            return True, test, why
        else:
            return False, (test, why), result

    return False, None, ""
    # Return value: (True, reasons, why) if post is spam
    #               (False, None, "") if post is not spam
    #               (False, (reasons, why), ignore_info) if post is spam but ignored
    # This is required because !!/report will check for 3rd tuple item to decide if it's not spam or spam but ignored

# noinspection PyMissingTypeHints
def check_if_spam_json(json_data):
    try:
        post = Post(json_data=json_data)
    except PostParseError as err:
        log('error', 'Parse error {0} when parsing json_data {1!r}'.format(
            err, json_data))
        return False, '', ''
    is_spam, reason, why = check_if_spam(post)
    return is_spam, reason, why

# noinspection PyBroadException,PyProtectedMember
def handle_spam(post, reasons, why):
    datahandling.append_to_latest_questions(post.post_site, post.post_id, post.title if not post.is_answer else "")

    if len(reasons) == 1 and ("all-caps title" in reasons or
                              "repeating characters in title" in reasons or
                              "repeating characters in body" in reasons or
                              "repeating characters in answer" in reasons or
                              "repeating words in title" in reasons or
                              "repeating words in body" in reasons or
                              "repeating words in answer" in reasons):
        datahandling.add_auto_ignored_post((post.post_id, post.post_site, datetime.utcnow()))

    if why is not None and why != "":
        datahandling.add_why(post.post_site, post.post_id, why)

    if post.is_answer and post.post_id is not None and post.post_id != "":
        datahandling.add_post_site_id_link((post.post_id, post.post_site, "answer"), post.parent.post_id)

    try:
        post_url = parsing.to_protocol_relative(parsing.url_to_shortlink(post.post_url))
        poster_url = parsing.to_protocol_relative(parsing.user_url_to_shortlink(post.user_url))
        if not post.user_name.strip() or (not poster_url or poster_url.strip() == ""):
            username = ""
        else:
            username = post.user_name.strip()

        Tasks.do(metasmoke.Metasmoke.send_stats_on_post,
                 post.title_ignore_type, post_url, reasons, post.body, post.markdown,
                 username, post.user_link, why, post.owner_rep, post.post_score,
                 post.up_vote_count, post.down_vote_count)

        offensive_mask = 'offensive title detected' in reasons
        message = build_message(post, reasons)
        if offensive_mask:
            post.title = "(potentially offensive title -- see MS for details)"
            clean_message = build_message(post, reasons)

        log('debug', GlobalVars.parser.unescape(message).encode('ascii', errors='replace'))
        GlobalVars.deletion_watcher.subscribe(post_url)

        without_roles = tuple(["no-" + reason for reason in reasons]) + ("site-no-" + post.post_site,)

        if set(reasons) - GlobalVars.experimental_reasons == set() and \
                not why.startswith("Post manually "):
            chatcommunicate.tell_rooms(message, ("experimental-all-sites", "experimental-site-" + post.post_site),
                                       without_roles, notify_site=post.post_site, report_data=(post_url, poster_url))
        else:
            if offensive_mask:
                chatcommunicate.tell_rooms(message, ("all-sites", "site-" + post.post_site),
                                           without_roles + ("offensive-mask",), notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
                chatcommunicate.tell_rooms(clean_message, ("all-sites", "site-" + post.post_site),
                                           without_roles + ("no-offensive-mask",), notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
            else:
                chatcommunicate.tell_rooms(message, ("all-sites", "site-" + post.post_site),
                                           without_roles, notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
    except Exception as e:
        excepthook.uncaught_exception(*sys.exc_info())

def build_message(post, reasons):
    # This is the main report format. Username and user link are deliberately not separated as with title and post
    # link, because we may want to use "by a deleted user" rather than a username+link.
    message_format = "{prefix_ms} {{reasons}} ({reason_weight}): **[{title}\u202D]({post_url})** by {user} on `{site}`"

    # Post URL, user URL, and site details are all easy - just data from the post object, transformed a bit
    # via datahandling.
    post_url = parsing.to_protocol_relative(parsing.url_to_shortlink(post.post_url))
    poster_url = parsing.to_protocol_relative(parsing.user_url_to_shortlink(post.user_url))
    shortened_site = post.post_site.replace("stackexchange.com", "SE")  # site.stackexchange.com -> site.SE

    # Message prefix. There's always a link to SmokeDetector; if we have a metasmoke key, there's also a link to the
    # post's MS record. If we *don't* have a MS key, it's a fair assumption that the post won't be in metasmoke as
    # we didn't have a key to create a record for it.
    prefix = u"[ [SmokeDetector](//git.io/vyDZv) ]"
    if GlobalVars.metasmoke_key:
        prefix = u"[ [SmokeDetector](//git.io/vyDZv) | [MS]({}) ]".format(
            to_metasmoke_link(post_url, protocol=False))

    # If we have reason weights cached (GlobalVars.reason_weights) we can calculate total weight for this report;
    # likewise, if we have a MS key, we can fetch the weights and then calculate. If we have neither, tough luck.
    if GlobalVars.reason_weights or GlobalVars.metasmoke_key:
        reason_weight = sum_weight(reasons)
        if reason_weight >= 1000:
            reason_weight = "**{}**".format(reason_weight)
        else:
            reason_weight = "{}".format(reason_weight)
    else:
        reason_weight = ""

    # If the post is an answer, it doesn't have a title, so we use the question's title instead. Either way, we
    # make sure it's escaped. We also add the edited indicator here.
    sanitized_title = parsing.sanitize_title(post.title if not post.is_answer else post.parent.title)
    sanitized_title = escape_format(sanitized_title).strip()
    if post.edited:  # Append a pencil emoji for edited posts
        sanitized_title += ' \u270F\uFE0F'

    # If we have user details available, we'll linkify the username. If we don't, we call it a deleted user.
    if not post.user_name.strip() or (not poster_url or poster_url.strip() == ""):
        user = "a deleted user"
    else:
        username = post.user_name.strip()
        escaped_username = escape_format(parsing.escape_markdown(username))
        user = "[{}\u202D]({})".format(escaped_username, poster_url)

    # Build the main body of the message. The next step is to insert the reason list while keeping the message
    # under 500 characters long.
    message = message_format.format(prefix_ms=prefix, reason_weight=reason_weight, title=sanitized_title,
                                    post_url=post_url, user=user, site=shortened_site)

    for reason_count in range(5, 0, -1):
        reason = ", ".join(reasons[:reason_count])
        if len(reasons) > reason_count:
            reason += ", +{} more".format(len(reasons) - reason_count)
        reason = reason.capitalize()
        attempt = message.format(reasons=reason)
        if len(attempt) <= 500:
            message = attempt
            break

    # If the message is still longer than 500 chars after trying to reduce the reason list, we're out of options,
    # so just cut the end of the message off.
    if len(message) > 500:
        message = message[:500]

    return message
<commit_msg>Revert "Bold post title in chat report messages"<commit_after># coding=utf-8
import sys
import random
import findspam
import datahandling
import chatcommunicate
from globalvars import GlobalVars
from datetime import datetime, timedelta
import regex
import parsing
import metasmoke
import excepthook
from classes import Post, PostParseError
from helpers import log, escape_format
from parsing import to_metasmoke_link
from tasks import Tasks

# noinspection PyMissingTypeHints
def should_whitelist_prevent_alert(user_url, reasons):
    is_whitelisted = datahandling.is_whitelisted_user(parsing.get_user_from_url(user_url))
    if not is_whitelisted:
        return False
    return not any(r for r in set(reasons) if "username" not in r)

def sum_weight(reasons: list):
    if not GlobalVars.reason_weights:
        datahandling.update_reason_weights()
    now = datetime.utcnow() - timedelta(minutes=15)
    if 'last_updated' not in GlobalVars.reason_weights or \
            (now.date() != GlobalVars.reason_weights['last_updated'] and now.hour >= 1):
        Tasks.do(datahandling.update_reason_weights)
    s = 0
    weights = GlobalVars.reason_weights
    for r in reasons:
        try:
            if "(" in r:
                r = regex.sub(r"\s*\(.*$", "", r)
            s += weights[r.lower()]
        except KeyError:
            pass  # s += 0
    return s

# noinspection PyMissingTypeHints
def check_if_spam(post):
    test, why = findspam.FindSpam.test_post(post)
    if datahandling.is_blacklisted_user(parsing.get_user_from_url(post.user_url)):
        test.append("blacklisted user")
        blacklisted_user_data = datahandling.get_blacklisted_user_data(parsing.get_user_from_url(post.user_url))
        if len(blacklisted_user_data) > 1:
            if blacklisted_user_data[1] == "metasmoke":
                blacklisted_by = "the metasmoke API"
            else:
                blacklisted_by = blacklisted_user_data[1]
            blacklisted_post_url = blacklisted_user_data[2]
            if why and why[-1] == "\n":
                why = why[:-1]
            if blacklisted_post_url:
                rel_url = blacklisted_post_url.replace("http:", "", 1)
                ms_url = datahandling.resolve_ms_link(rel_url) or to_metasmoke_link(rel_url)
                why += "\nBlacklisted user - blacklisted for {} ({}) by {}".format(
                    blacklisted_post_url, ms_url, blacklisted_by)
            else:
                why += "\n" + u"Blacklisted user - blacklisted by {}".format(blacklisted_by)
    if test:
        result = None
        if datahandling.has_already_been_posted(post.post_site, post.post_id, post.title):
            result = "post has already been reported"
        elif datahandling.is_false_positive((post.post_id, post.post_site)):
            result = "post is marked as false positive"
        elif should_whitelist_prevent_alert(post.user_url, test):
            result = "user is whitelisted"
        elif datahandling.is_ignored_post((post.post_id, post.post_site)):
            result = "post is ignored"
        elif datahandling.is_auto_ignored_post((post.post_id, post.post_site)):
            result = "post is automatically ignored"
        elif datahandling.has_community_bumped_post(post.post_url, post.body):
            result = "post is bumped by Community \u2666\uFE0F"
        # Dirty approach
        if result is None:  # Post not ignored
            return True, test, why
        else:
            return False, (test, why), result

    return False, None, ""
    # Return value: (True, reasons, why) if post is spam
    #               (False, None, "") if post is not spam
    #               (False, (reasons, why), ignore_info) if post is spam but ignored
    # This is required because !!/report will check for 3rd tuple item to decide if it's not spam or spam but ignored

# noinspection PyMissingTypeHints
def check_if_spam_json(json_data):
    try:
        post = Post(json_data=json_data)
    except PostParseError as err:
        log('error', 'Parse error {0} when parsing json_data {1!r}'.format(
            err, json_data))
        return False, '', ''
    is_spam, reason, why = check_if_spam(post)
    return is_spam, reason, why

# noinspection PyBroadException,PyProtectedMember
def handle_spam(post, reasons, why):
    datahandling.append_to_latest_questions(post.post_site, post.post_id, post.title if not post.is_answer else "")

    if len(reasons) == 1 and ("all-caps title" in reasons or
                              "repeating characters in title" in reasons or
                              "repeating characters in body" in reasons or
                              "repeating characters in answer" in reasons or
                              "repeating words in title" in reasons or
                              "repeating words in body" in reasons or
                              "repeating words in answer" in reasons):
        datahandling.add_auto_ignored_post((post.post_id, post.post_site, datetime.utcnow()))

    if why is not None and why != "":
        datahandling.add_why(post.post_site, post.post_id, why)

    if post.is_answer and post.post_id is not None and post.post_id != "":
        datahandling.add_post_site_id_link((post.post_id, post.post_site, "answer"), post.parent.post_id)

    try:
        post_url = parsing.to_protocol_relative(parsing.url_to_shortlink(post.post_url))
        poster_url = parsing.to_protocol_relative(parsing.user_url_to_shortlink(post.user_url))
        if not post.user_name.strip() or (not poster_url or poster_url.strip() == ""):
            username = ""
        else:
            username = post.user_name.strip()

        Tasks.do(metasmoke.Metasmoke.send_stats_on_post,
                 post.title_ignore_type, post_url, reasons, post.body, post.markdown,
                 username, post.user_link, why, post.owner_rep, post.post_score,
                 post.up_vote_count, post.down_vote_count)

        offensive_mask = 'offensive title detected' in reasons
        message = build_message(post, reasons)
        if offensive_mask:
            post.title = "(potentially offensive title -- see MS for details)"
            clean_message = build_message(post, reasons)

        log('debug', GlobalVars.parser.unescape(message).encode('ascii', errors='replace'))
        GlobalVars.deletion_watcher.subscribe(post_url)

        without_roles = tuple(["no-" + reason for reason in reasons]) + ("site-no-" + post.post_site,)

        if set(reasons) - GlobalVars.experimental_reasons == set() and \
                not why.startswith("Post manually "):
            chatcommunicate.tell_rooms(message, ("experimental-all-sites", "experimental-site-" + post.post_site),
                                       without_roles, notify_site=post.post_site, report_data=(post_url, poster_url))
        else:
            if offensive_mask:
                chatcommunicate.tell_rooms(message, ("all-sites", "site-" + post.post_site),
                                           without_roles + ("offensive-mask",), notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
                chatcommunicate.tell_rooms(clean_message, ("all-sites", "site-" + post.post_site),
                                           without_roles + ("no-offensive-mask",), notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
            else:
                chatcommunicate.tell_rooms(message, ("all-sites", "site-" + post.post_site),
                                           without_roles, notify_site=post.post_site,
                                           report_data=(post_url, poster_url))
    except Exception as e:
        excepthook.uncaught_exception(*sys.exc_info())

def build_message(post, reasons):
    # This is the main report format. Username and user link are deliberately not separated as with title and post
    # link, because we may want to use "by a deleted user" rather than a username+link.
    message_format = "{prefix_ms} {{reasons}} ({reason_weight}): [{title}\u202D]({post_url}) by {user} on `{site}`"

    # Post URL, user URL, and site details are all easy - just data from the post object, transformed a bit
    # via datahandling.
    post_url = parsing.to_protocol_relative(parsing.url_to_shortlink(post.post_url))
    poster_url = parsing.to_protocol_relative(parsing.user_url_to_shortlink(post.user_url))
    shortened_site = post.post_site.replace("stackexchange.com", "SE")  # site.stackexchange.com -> site.SE

    # Message prefix. There's always a link to SmokeDetector; if we have a metasmoke key, there's also a link to the
    # post's MS record. If we *don't* have a MS key, it's a fair assumption that the post won't be in metasmoke as
    # we didn't have a key to create a record for it.
    prefix = u"[ [SmokeDetector](//git.io/vyDZv) ]"
    if GlobalVars.metasmoke_key:
        prefix = u"[ [SmokeDetector](//git.io/vyDZv) | [MS]({}) ]".format(
            to_metasmoke_link(post_url, protocol=False))

    # If we have reason weights cached (GlobalVars.reason_weights) we can calculate total weight for this report;
    # likewise, if we have a MS key, we can fetch the weights and then calculate. If we have neither, tough luck.
    if GlobalVars.reason_weights or GlobalVars.metasmoke_key:
        reason_weight = sum_weight(reasons)
        if reason_weight >= 1000:
            reason_weight = "**{}**".format(reason_weight)
        else:
            reason_weight = "{}".format(reason_weight)
    else:
        reason_weight = ""

    # If the post is an answer, it doesn't have a title, so we use the question's title instead. Either way, we
    # make sure it's escaped. We also add the edited indicator here.
    sanitized_title = parsing.sanitize_title(post.title if not post.is_answer else post.parent.title)
    sanitized_title = escape_format(sanitized_title).strip()
    if post.edited:  # Append a pencil emoji for edited posts
        sanitized_title += ' \u270F\uFE0F'

    # If we have user details available, we'll linkify the username. If we don't, we call it a deleted user.
    if not post.user_name.strip() or (not poster_url or poster_url.strip() == ""):
        user = "a deleted user"
    else:
        username = post.user_name.strip()
        escaped_username = escape_format(parsing.escape_markdown(username))
        user = "[{}\u202D]({})".format(escaped_username, poster_url)

    # Build the main body of the message. The next step is to insert the reason list while keeping the message
    # under 500 characters long.
    message = message_format.format(prefix_ms=prefix, reason_weight=reason_weight, title=sanitized_title,
                                    post_url=post_url, user=user, site=shortened_site)

    for reason_count in range(5, 0, -1):
        reason = ", ".join(reasons[:reason_count])
        if len(reasons) > reason_count:
            reason += ", +{} more".format(len(reasons) - reason_count)
        reason = reason.capitalize()
        attempt = message.format(reasons=reason)
        if len(attempt) <= 500:
            message = attempt
            break

    # If the message is still longer than 500 chars after trying to reduce the reason list, we're out of options,
    # so just cut the end of the message off.
    if len(message) > 500:
        message = message[:500]

    return message
<|endoftext|>