from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse   #命令行参数选项解析模块
import tensorflow as tf

import lalala

parser= argparse.ArgumentParser()    #这是模块获取命令行的方法。得到一整个命令行
parser.add_argument('--batch_size',default=100,type=int,help='batch size')  #在获得的命令行上加 这一段参数
parser.add_argument('--train_steps',default=1000,type=int,help='number of training steps') #在获得的命令行上加这一段参数

def main(argv):
    args=parser.parse_args(argv[1:])   #因为启动时输入python do.py,然后又在命令行上加了两个参数，然后启动main函数时
                                       #一整个命令行都是argv。从argv拿到第二个参数到结尾，也就是batch_size和train_steps
    #此时 args就有属性了。args.batch_size是一个batch大小。args.train_steps是训练的步数。

    (train_x,train_y),(test_x,text_y)=lalala.load_data()

    #从train_x中获取特征列以供dnn分类器参数使用
    my_feature_columns=[]
    for key in train_x.keys():
        my_feature_columns.append(tf.feature_column.numeric_column(key=key))

    classifier=tf.estimator.DNNClassifier(
        feature_columns=my_feature_columns,
        hidden_units=[10,10],
        n_classes=3)  #定义分类器，输入特征列，隐藏层数，结果数

    classifier.train(input_fn=lambda:lalala.train_input_fn(train_x,train_y,args.batch_size),
                    steps=args.train_steps)

    eval_result=classifier.evaluate(input_fn=lambda:lalala.eval_input_fn(test_x,test_y,args.batch_size))

    print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))

    expected = ['Setosa', 'Versicolor', 'Virginica']
    predict_x = {
        'SepalLength': [5.1, 5.9, 6.9],
        'SepalWidth': [3.3, 3.0, 3.1],
        'PetalLength': [1.7, 4.2, 5.4],
        'PetalWidth': [0.5, 1.5, 2.1],
    }

    predictions = classifier.predict(
        input_fn=lambda:iris_data.eval_input_fn(predict_x,
                                                labels=None,
                                                batch_size=args.batch_size))

    template = ('\nPrediction is "{}" ({:.1f}%), expected "{}"')

    for pred_dict, expec in zip(predictions, expected):
        class_id = pred_dict['class_ids'][0]
        probability = pred_dict['probabilities'][class_id]

        print(template.format(iris_data.SPECIES[class_id],
                              100 * probability, expec))

if __name__ == '__main__':
    tf.logging.set_verbosity(tf.logging.INFO)
    tf.app.run(main)


# Copyright (c) 2019 The Boule Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
"""
Module for defining and setting the reference ellipsoid.
"""
from warnings import warn
import attr
import numpy as np

# Don't let ellipsoid parameters be changed to avoid messing up calculations
# accidentally.
@attr.s(frozen=True)
class Ellipsoid:
    """
    Reference oblate ellipsoid.

    The ellipsoid is oblate and spins around it's minor axis. It is defined by
    four parameters (semi-major axis, flattening, geocentric gravitational
    constant, and angular velocity) and offers other derived quantities.

    **All attributes of this class are read-only and cannot be changed after
    instantiation.**

    All parameters are in SI units.

    .. note::

        Use :class:`boule.Sphere` if you desire zero flattening because there
        are singularities for this particular case in the normal gravity
        calculations.

    Parameters
    ----------
    name : str
        A short name for the ellipsoid, for example ``'WGS84'``.
    semimajor_axis : float
        The semi-major axis of the ellipsoid (equatorial radius), usually
        represented by "a" [meters].
    flattening : float
        The flattening of the ellipsoid (f) [adimensional].
    geocentric_grav_const : float
        The geocentric gravitational constant (GM) [m^3 s^-2].
    angular_velocity : float
        The angular velocity of the rotating ellipsoid (omega) [rad s^-1].
    long_name : str or None
        A long name for the ellipsoid, for example ``"World Geodetic System
        1984"`` (optional).
    reference : str or None
        Citation for the ellipsoid parameter values (optional).

    Examples
    --------

    We can define an ellipsoid by setting the 4 key numerical parameters:

    >>> ellipsoid = Ellipsoid(
    ...     name="oblate-ellipsoid",
    ...     long_name="Oblate Ellipsoid",
    ...     semimajor_axis=1,
    ...     flattening=0.5,
    ...     geocentric_grav_const=1,
    ...     angular_velocity=0,
    ... )
    >>> print(ellipsoid) # doctest: +ELLIPSIS
    Ellipsoid(name='oblate-ellipsoid', ...)
    >>> print(ellipsoid.long_name)
    Oblate Ellipsoid

    The class defines several derived attributes based on the input parameters:

    >>> print("{:.2f}".format(ellipsoid.semiminor_axis))
    0.50
    >>> print("{:.2f}".format(ellipsoid.mean_radius))
    0.83
    >>> print("{:.2f}".format(ellipsoid.linear_eccentricity))
    0.87
    >>> print("{:.2f}".format(ellipsoid.first_eccentricity))
    0.87
    >>> print("{:.2f}".format(ellipsoid.second_eccentricity))
    1.73

    """

    name = attr.ib()
    semimajor_axis = attr.ib()
    flattening = attr.ib()
    geocentric_grav_const = attr.ib()
    angular_velocity = attr.ib()
    long_name = attr.ib(default=None)
    reference = attr.ib(default=None)

    @flattening.validator
    def _check_flattening(
        self, flattening, value
    ):  # pylint: disable=no-self-use,unused-argument
        """
        Check if flattening is valid
        """
        if value < 0 or value >= 1:
            raise ValueError(
                f"Invalid flattening '{value}'. "
                "Should be greater than zero and lower than 1."
            )
        if value == 0:
            raise ValueError(
                "Flattening equal to zero will lead to errors in normal gravity. "
                "Use boule.Sphere for representing ellipsoids with zero flattening."
            )
        if value < 1e-7:
            warn(
                f"Flattening is too close to zero ('{value}'). "
                "This may lead to inaccurate results and division by zero errors. "
                "Use boule.Sphere for representing ellipsoids with zero flattening."
            )

    @semimajor_axis.validator
    def _check_semimajor_axis(
        self, semimajor_axis, value
    ):  # pylint: disable=no-self-use,unused-argument
        """
        Check if semimajor_axis is positive
        """
        if not value > 0:
            raise ValueError(
                f"Invalid semi-major axis '{value}'. Should be greater than zero."
            )

    @geocentric_grav_const.validator
    def _check_geocentric_grav_const(
        self, geocentric_grav_const, value
    ):  # pylint: disable=no-self-use,unused-argument
        """
        Warn if geocentric_grav_const is negative
        """
        if value < 0:
            warn(f"The geocentric gravitational constant is negative: '{value}'")

    @property
    def semiminor_axis(self):
        "The small (polar) axis of the ellipsoid [meters]"
        return self.semimajor_axis * (1 - self.flattening)

    @property
    def linear_eccentricity(self):
        "The linear eccentricity [meters]"
        return np.sqrt(self.semimajor_axis ** 2 - self.semiminor_axis ** 2)

    @property
    def first_eccentricity(self):
        "The first eccentricity [adimensional]"
        return self.linear_eccentricity / self.semimajor_axis

    @property
    def second_eccentricity(self):
        "The second eccentricity [adimensional]"
        return self.linear_eccentricity / self.semiminor_axis

    @property
    def mean_radius(self):
        """
        The arithmetic mean radius :math:`R_1=(2a+b)/3` [Moritz1988]_ [meters]
        """
        return 1 / 3 * (2 * self.semimajor_axis + self.semiminor_axis)

    @property
    def emm(self):
        r"Auxiliary quantity :math:`m = \omega^2 a^2 b / (GM)`"
        return (
            self.angular_velocity ** 2
            * self.semimajor_axis ** 2
            * self.semiminor_axis
            / self.geocentric_grav_const
        )

    @property
    def gravity_equator(self):
        """
        The norm of the gravity vector on the ellipsoid at the equator [m/s²]
        """
        ratio = self.semiminor_axis / self.linear_eccentricity
        arctan = np.arctan2(self.linear_eccentricity, self.semiminor_axis)
        aux = (
            self.second_eccentricity
            * (3 * (1 + ratio ** 2) * (1 - ratio * arctan) - 1)
            / (3 * ((1 + 3 * ratio ** 2) * arctan - 3 * ratio))
        )
        axis_mul = self.semimajor_axis * self.semiminor_axis
        result = self.geocentric_grav_const * (1 - self.emm - self.emm * aux) / axis_mul
        return result

    @property
    def gravity_pole(self):
        "The norm of the gravity vector on the ellipsoid at the poles [m/s²]"
        ratio = self.semiminor_axis / self.linear_eccentricity
        arctan = np.arctan2(self.linear_eccentricity, self.semiminor_axis)
        aux = (
            self.second_eccentricity
            * (3 * (1 + ratio ** 2) * (1 - ratio * arctan) - 1)
            / (1.5 * ((1 + 3 * ratio ** 2) * arctan - 3 * ratio))
        )
        result = (
            self.geocentric_grav_const * (1 + self.emm * aux) / self.semimajor_axis ** 2
        )
        return result

    def geocentric_radius(self, latitude, geodetic=True):
        r"""
        Distance from the center of the ellipsoid to its surface.

        The geocentric radius and is a function of the geodetic latitude
        :math:`\phi` and the semi-major and semi-minor axis, a and b:

        .. math::

            R(\phi) = \sqrt{\dfrac{
                (a^2\cos\phi)^2 + (b^2\sin\phi)^2}{
                (a\cos\phi)^2 + (b\sin\phi)^2 }
            }

        See https://en.wikipedia.org/wiki/Earth_radius#Geocentric_radius

        The same could be achieved with
        :meth:`boule.Ellipsoid.geodetic_to_spherical` by passing any value for
        the longitudes and heights equal to zero. This method provides a
        simpler and possibly faster alternative.

        Alternatively, the geocentric radius can also be expressed in terms of
        the geocentric (spherical) latitude :math:`\theta`:

        .. math::

            R(\theta) = \sqrt{\dfrac{1}{
                (\frac{\cos\theta}{a})^2 + (\frac{\sin\theta}{b})^2 }
            }

        This can be useful if you already have the geocentric latitudes and
        need the geocentric radius of the ellipsoid (for example, in spherical
        harmonic analysis). In these cases, the coordinate conversion route is
        not possible since we need the radial coordinates to do that in the
        first place.

        .. note::

            No elevation is taken into account (the height is zero). If you
            need the geocentric radius at a height other than zero, use
            :meth:`boule.Ellipsoid.geodetic_to_spherical` instead.

        Parameters
        ----------
        latitude : float or array
            Latitude coordinates on geodetic coordinate system in degrees.
        geodetic : bool
            If True (default), will assume that latitudes are geodetic
            latitudes. Otherwise, will that they are geocentric spherical
            latitudes.

        Returns
        -------
        geocentric_radius : float or array
            The geocentric radius for the given latitude(s) in the same units
            as the ellipsoid axis.

        """
        latitude_rad = np.radians(latitude)
        coslat, sinlat = np.cos(latitude_rad), np.sin(latitude_rad)
        # Avoid doing this in favour of having the user do the conversions when
        # possible. It's not the case here, so we made an exception.
        if geodetic:
            radius = np.sqrt(
                (
                    (self.semimajor_axis ** 2 * coslat) ** 2
                    + (self.semiminor_axis ** 2 * sinlat) ** 2
                )
                / (
                    (self.semimajor_axis * coslat) ** 2
                    + (self.semiminor_axis * sinlat) ** 2
                )
            )
        else:
            radius = np.sqrt(
                1
                / (
                    (coslat / self.semimajor_axis) ** 2
                    + (sinlat / self.semiminor_axis) ** 2
                )
            )
        return radius

    def prime_vertical_radius(self, sinlat):
        r"""
        Calculate the prime vertical radius for a given geodetic latitude

        The prime vertical radius is defined as:

        .. math::

            N(\phi) = \frac{a}{\sqrt{1 - e^2 \sin^2(\phi)}}

        Where :math:`a` is the semi-major axis and :math:`e` is the first
        eccentricity.

        This function receives the sine of the latitude as input to avoid
        repeated computations of trigonometric functions.

        Parameters
        ----------
        sinlat : float or array-like
            Sine of the latitude angle.

        Returns
        -------
        prime_vertical_radius : float or array-like
            Prime vertical radius given in the same units as the semi-major
            axis

        """
        return self.semimajor_axis / np.sqrt(
            1 - self.first_eccentricity ** 2 * sinlat ** 2
        )

    def geodetic_to_spherical(self, longitude, latitude, height):
        """
        Convert from geodetic to geocentric spherical coordinates.

        The geodetic datum is defined by this ellipsoid. The coordinates are
        converted following [Vermeille2002]_.

        Parameters
        ----------
        longitude : array
            Longitude coordinates on geodetic coordinate system in degrees.
        latitude : array
            Latitude coordinates on geodetic coordinate system in degrees.
        height : array
            Ellipsoidal heights in meters.

        Returns
        -------
        longitude : array
            Longitude coordinates on geocentric spherical coordinate system in
            degrees.
            The longitude coordinates are not modified during this conversion.
        spherical_latitude : array
            Converted latitude coordinates on geocentric spherical coordinate
            system in degrees.
        radius : array
            Converted spherical radius coordinates in meters.

        """
        latitude_rad = np.radians(latitude)
        coslat, sinlat = np.cos(latitude_rad), np.sin(latitude_rad)
        prime_vertical_radius = self.prime_vertical_radius(sinlat)
        # Instead of computing X and Y, we only compute the projection on the
        # XY plane: xy_projection = sqrt( X**2 + Y**2 )
        xy_projection = (height + prime_vertical_radius) * coslat
        z_cartesian = (
            height + (1 - self.first_eccentricity ** 2) * prime_vertical_radius
        ) * sinlat
        radius = np.sqrt(xy_projection ** 2 + z_cartesian ** 2)
        spherical_latitude = np.degrees(np.arcsin(z_cartesian / radius))
        return longitude, spherical_latitude, radius

    def spherical_to_geodetic(self, longitude, spherical_latitude, radius):
        """
        Convert from geocentric spherical to geodetic coordinates.

        The geodetic datum is defined by this ellipsoid. The coordinates are
        converted following [Vermeille2002]_.

        Parameters
        ----------
        longitude : array
            Longitude coordinates on geocentric spherical coordinate system in
            degrees.
        spherical_latitude : array
            Latitude coordinates on geocentric spherical coordinate system in
            degrees.
        radius : array
            Spherical radius coordinates in meters.

        Returns
        -------
        longitude : array
            Longitude coordinates on geodetic coordinate system in degrees.
            The longitude coordinates are not modified during this conversion.
        latitude : array
            Converted latitude coordinates on geodetic coordinate system in
            degrees.
        height : array
            Converted ellipsoidal height coordinates in meters.

        """
        spherical_latitude = np.radians(spherical_latitude)
        k, big_z, big_d = self._spherical_to_geodetic_terms(spherical_latitude, radius)
        latitude = np.degrees(
            2 * np.arctan(big_z / (big_d + np.sqrt(big_d ** 2 + big_z ** 2)))
        )
        height = (
            (k + self.first_eccentricity ** 2 - 1)
            / k
            * np.sqrt(big_d ** 2 + big_z ** 2)
        )
        return longitude, latitude, height

    def _spherical_to_geodetic_terms(self, spherical_latitude, radius):
        "Calculate intermediate terms needed for the conversion."
        # Offload computation of these intermediate variables here to clean up
        # the main function body
        cos_latitude = np.cos(spherical_latitude)
        big_z = radius * np.sin(spherical_latitude)
        p_0 = radius ** 2 * cos_latitude ** 2 / self.semimajor_axis ** 2
        q_0 = (1 - self.first_eccentricity ** 2) / self.semimajor_axis ** 2 * big_z ** 2
        r_0 = (p_0 + q_0 - self.first_eccentricity ** 4) / 6
        s_0 = self.first_eccentricity ** 4 * p_0 * q_0 / 4 / r_0 ** 3
        t_0 = np.cbrt(1 + s_0 + np.sqrt(2 * s_0 + s_0 ** 2))
        u_0 = r_0 * (1 + t_0 + 1 / t_0)
        v_0 = np.sqrt(u_0 ** 2 + q_0 * self.first_eccentricity ** 4)
        w_0 = self.first_eccentricity ** 2 * (u_0 + v_0 - q_0) / 2 / v_0
        k = np.sqrt(u_0 + v_0 + w_0 ** 2) - w_0
        big_d = k * radius * cos_latitude / (k + self.first_eccentricity ** 2)
        return k, big_z, big_d

    def normal_gravity(
        self, latitude, height, si_units=False
    ):  # pylint: disable=too-many-locals
        """
        Calculate normal gravity at any latitude and height.

        Computes the magnitude of the gradient of the gravity potential
        (gravitational + centrifugal) generated by the ellipsoid at the given
        latitude and (geometric) height. Uses of a closed form expression of
        [LiGotze2001]_.

        Parameters
        ----------
        latitude : float or array
            The (geodetic) latitude where the normal gravity will be computed
            (in degrees).
        height : float or array
            The ellipsoidal (geometric) height of computation the point (in
            meters).
        si_units : bool
            Return the value in mGal (False, default) or SI units (True)

        Returns
        -------
        gamma : float or array
            The normal gravity in mGal.

        """
        # Warn if height is negative
        if np.any(height < 0):
            warn(
                "Formulas used are valid for points outside the ellipsoid."
                "Height must be greater than or equal to zero."
            )

        sinlat = np.sin(np.deg2rad(latitude))
        coslat = np.sqrt(1 - sinlat ** 2)
        # The terms below follow the variable names from Li and Goetze (2001)
        cosbeta_l2, sinbeta_l2, b_l, q_0, q_l, big_w = self._normal_gravity_terms(
            sinlat, coslat, height
        )
        # Put together gamma using 3 terms
        term1 = self.geocentric_grav_const / (b_l ** 2 + self.linear_eccentricity ** 2)
        term2 = (0.5 * sinbeta_l2 - 1 / 6) * (
            self.semimajor_axis ** 2
            * self.linear_eccentricity
            * q_l
            * self.angular_velocity ** 2
            / ((b_l ** 2 + self.linear_eccentricity ** 2) * q_0)
        )
        term3 = -cosbeta_l2 * b_l * self.angular_velocity ** 2
        gamma = (term1 + term2 + term3) / big_w
        if si_units:
            return gamma
        # Convert gamma from SI to mGal
        return gamma * 1e5

    def _normal_gravity_terms(self, sinlat, coslat, height):
        "Calculate intermediate terms needed for the calculations."
        # Offload computation of these intermediate variables here to clean up
        # the main function body
        beta = np.arctan2(self.semiminor_axis * sinlat, self.semimajor_axis * coslat)
        zl2 = (self.semiminor_axis * np.sin(beta) + height * sinlat) ** 2
        rl2 = (self.semimajor_axis * np.cos(beta) + height * coslat) ** 2
        big_d = (rl2 - zl2) / self.linear_eccentricity ** 2
        big_r = (rl2 + zl2) / self.linear_eccentricity ** 2
        cosbeta_l2 = 0.5 * (1 + big_r) - np.sqrt(0.25 * (1 + big_r ** 2) - 0.5 * big_d)
        sinbeta_l2 = 1 - cosbeta_l2
        b_l = np.sqrt(rl2 + zl2 - self.linear_eccentricity ** 2 * cosbeta_l2)
        q_0 = 0.5 * (
            (1 + 3 * (self.semiminor_axis / self.linear_eccentricity) ** 2)
            * np.arctan2(self.linear_eccentricity, self.semiminor_axis)
            - 3 * self.semiminor_axis / self.linear_eccentricity
        )
        q_l = (
            3
            * (1 + (b_l / self.linear_eccentricity) ** 2)
            * (
                1
                - b_l
                / self.linear_eccentricity
                * np.arctan2(self.linear_eccentricity, b_l)
            )
            - 1
        )
        big_w = np.sqrt(
            (b_l ** 2 + self.linear_eccentricity ** 2 * sinbeta_l2)
            / (b_l ** 2 + self.linear_eccentricity ** 2)
        )
        return cosbeta_l2, sinbeta_l2, b_l, q_0, q_l, big_w


# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.views.generic import ListView
from django.core.cache import caches
from .models import Article, Nav, Carousel
from dnglin_comments.models import Comment
from dnglin_system.models import Link
from django.conf import settings
import logging
# Create your views here.

# 缓存
try:
    cache=caches['memcache']
except ImportError as e:
    cache = caches['default']

# logger
logger = logging.getLogger(__name__)

class BaseMixin(object):
    def get_context_data(self, *args, **kwargs):
        context = super(BaseMixin, self).get_context_data(*args, **kwargs)
        try:
            # 网站标题等内容
            context['website_title'] = settings.WEBSITE_TITLE
            context['website_welcome'] = settings.WEBSITE_WELCOME
            # 热门文章
            context['hot_article_list']=Article.objects.order_by('-view_times')[0:10]
            # 导航条
            context['nav_list']=Nav.objects.filter(status=0)
            # 最新评论
            context['latest_comment_list']=Comment.objects.order_by('-create_time')[0:10]
            # 友情链接
            context['links']=Link.objects.order_by('create_time').all()
            colors=['primary','success', 'info', 'warning', 'danger']
            for index,link in enumerate(context['links']):
                link.color=colors[index % len(colors)]
            # 用户未读信息数
            user=self.request.user
            if user.is_authenticated():
                context['notification_count']=user.to_user_notification_set.filter(is_read=0).count()
        except Exception as e:
            logger.error(u'[BaseMixin]加载基本信息出错')
        return context

class IndexView(BaseMixin,ListView):
    template_name = 'blog/index.html'
    context_object_name = 'article_list'
    paginate_by = settings.PAGE_NUM # 分页--每页的数目

    def get_context_data(self, *args, **kwargs):
        # 轮播
        kwargs['carousel_page_list']=Carousel.objects.all()
        return super(IndexView,self).get_context_data(*args,**kwargs)

    def get_queryset(self):
        article_list=Article.objects.filter(status=0)
        return article_list


import pygame
from sys import exit
import random

class Bullet:
    def __init__(self):
        self.x=0
        self.y=-1
        self.image= pygame.image.load('bullet.png').convert_alpha()
        self.active=False

    def move(self):
        if self.active:
            self.y-=3
        if self.y<0:
            self.active=False

    def restart(self):
        mousex,mousey=pygame.mouse.get_pos()
        self.x=mousex-self.image.get_width()/2
        self.y=mousey-self.image.get_height()/2
        self.active=True

class Air:
    def __init__(self):
        self.x=225
        self.y=400
        self.image=pygame.image.load('air.png').convert_alpha()

    def Move(self):
        mousex,mousey=pygame.mouse.get_pos()
        self.x=mousex-self.image.get_width()/2
        self.y=mousey-self.image.get_height()/2

    def restart(self):
        self.x=225
        self.y=400
        self.image=pygame.image.load('air.png').convert_alpha()

class Enemy:
    def restart(self):
        self.x=random.uniform(30,420)
        self.y=random.uniform(-200,-50)

    def __init__(self):
        self.restart()
        self.image=pygame.image.load('enemy.png')
        self.speed=0.08

    def move(self):
        if self.y>608:
            self.speed+=0.01
            self.restart()

        else:
            self.y=self.y+self.speed

pygame.init()
screen=pygame.display.set_mode((450,608))
pygame.display.set_caption('Star War')
background=pygame.image.load('background.png').convert()
interval_b=0
index_b=0
bullets=[]

for i in range(100):
    bullets.append(Bullet())

air=Air()
enemies=[]
for i in range(6):
    enemies.append(Enemy())

def checkHit(enemy, bullet):
    if (bullet.x > enemy.x and bullet.x < enemy.x + enemy.image.get_width())\
    and (bullet.y > enemy.y and bullet.y < enemy.y + enemy.image.get_height()):
        enemy.restart()
        bullet.active = False
        return True
    return False

def checkCrash(enemy, air):
    if (enemy.x + enemy.image.get_width() > 1.2*air.x and\
        enemy.x < air.x + 0.6*air.image.get_width())and\
        (enemy.y<air.y+air.image.get_height()and\
         enemy.y+enemy.image.get_height()>air.y):
        return True
    return False

score=0
font=pygame.font.Font(None,32)
gameover=False
start=False

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        if gameover and event.type==pygame.MOUSEBUTTONUP:
            air.restart()
            for e in enemies:
                e.restart()
            for b in bullets:
                b.restart()
            score=0
            gameover=False

        if event.type==pygame.MOUSEBUTTONDOWN:
            start=True
    screen.blit(background,(0,0))
    interval_b-=10
    if interval_b<0:
        bullets[index_b].restart()
        interval_b=100
        index_b=(1+index_b)%100

    if not gameover and start:
        for b in bullets:
            if b.active:
                for e in enemies:
                    if checkHit(e,b):
                        score+=100
                b.move()
                screen.blit(b.image,(b.x,b.y))

        for e in enemies:
            if checkCrash(e,air):

                gameover=True
                start=False
            e.move()
            screen.blit(e.image,(e.x,e.y))
        air.Move()
        screen.blit(air.image,(air.x,air.y))
        text=font.render('Score:%d' % score,1,(0,0,0))
        screen.blit(text,(0,0))

    if gameover:
        text=font.render('Score:%d' % score,1,(0,0,0))
        screen.blit(text,(160,150))
    if gameover==False and start==False:
        text=font.render('Click to Start Game!',1,(0,0,0))
        screen.blit(text,(100,150))

    pygame.display.update()


#!/usr/bin/env python3.7

# shared data can have possibly surprising effects with
# involving mutable objects such as lists and dictionaries

class Dog:
    tricks = []  # mistake : shared by all Dog instances

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

    def add_trick(self, trick):
        self.tricks.append(trick)

d = Dog('Fido')
e = Dog('Buddy')

d.add_trick('roll over')
e.add_trick('play dead')

print(d.tricks, e.tricks)

class CorrectDog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)

d = CorrectDog('Fido')
e = CorrectDog('Buddy')

d.add_trick('roll over')
e.add_trick('play dead')

print(d.tricks, e.tricks)


#!/usr/bin/env python
#-*- coding:utf-8 -*-

import xlrd
class Read_File:
    def read_xlsx(self,path):
        excel = xlrd.open_workbook(path)
        # count = len(excel.sheets())
        excel = excel.sheets()[0]
        # print(sheet.nrows)
        # print(sheet.row_values(0))
        # print(sheet)
        # print(count)
        # for sheet in excel.sheets():
        #     print(sheet.text())
        # return sheet
        # table = read_excel('3.xlsx',0)
        list1 = []
        for rownum in range(1, excel.nrows):  # 从第2行读取
            list = excel.row_values(rownum)  # 获取行数据，为列表形式
            # for i in list:
            #     print(i)


import numpy as np

def repeat(input_array, d2_length):
    output_array = []
    for i in range(len(input_array)-d2_length+1):
        new_array = np.array(input_array[i:i+d2_length]).flatten('F')
        output_array.append(new_array)
    return output_array

def normalize(input_array, to_normalize_columns):
    '''2d map to float and divide first n value by first value'''
    for i in range(len(input_array)):
        input_array[i] = list(map(lambda x: float(x), input_array[i]))
        normal_scale = input_array[i][0]
        for j in range(to_normalize_columns):
            input_array[i][j] = input_array[i][j]/normal_scale
    return input_array

def create_flatten_set(self, feature_length, label_length):
    '''create subsets of full data'''
    new_data = []
    for i in range(len(self.data) - feature_length - label_length + 1):
        new_data_subset = np.array(self.data[i:i+feature_length]).flatten()
        new_data.append(new_data_subset)
    return np.array(new_data)

def split_label(self, feature_length, label_length, label_column):
    '''split out hotmaxed arrays of 'length' day mean'''
    column = np.array(self.data)[:, label_column]
    label = []
    for i in range(feature_length - 1, len(column) - label_length):
        avg_change = (np.average(column[(i+1):(i+1)+(label_length-1)])-column[i])/column[i]
        label.append(avg_change)
    label = np.array(list(map(bucket, label)))
    return np.array(label)

if __name__=='__main__':
    a = [[1,2,3], [4,5,6], [7,8,9]]
    print(repeat(a,2))
    print(normalize(repeat(a,2), 3))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 21:12:14 2019

@author: karthikchowdary
"""
import pandas
from keras.models import Sequential
from keras.layers.core import Dense, Activation

# load dataset
from sklearn.model_selection import train_test_split

import pandas as pd

data = pd.read_csv("winequalityN.csv", sep = ",")
data.wine[data.wine == 'white'] = 1
data.wine[data.wine == 'red'] = 2
with open("winequalityN.csv",'r') as f:
    with open("updated_test.csv",'w') as f1:
        next(f) # skip header line
        for line in f:
            f1.write(line)

dataset = pd.read_csv("updated_test.csv", sep = ",").values

print(dataset)

import numpy as np
X_train, X_test, Y_train, Y_test = train_test_split(dataset[:,1:12], dataset[:,0],
                                                    test_size=0.25, random_state=87)

np.random.seed(155)

from tensorflow.python.framework import ops
ops.reset_default_graph()

my_first_nn = Sequential()
my_first_nn.add(Dense(105, input_dim=12, activation='relu'))

my_first_nn.add(Dense(125, input_dim=105, activation='relu'))
my_first_nn.add(Dense(1, activation='sigmoid'))
my_first_nn.compile(loss='binary_crossentropy', optimizer='adam')
my_first_nn_fitted = my_first_nn.fit(X_train, Y_train, epochs=100)
print(my_first_nn.summary())


# Title:        files.py
# Developer:    Christopher Corbett
# Description:  Creating, writing, and reading files

#setting variables
fileName = "test.csv"
write = 'w'
append = 'a'

#opening and writing a file
file = open(fileName, write)
firstName = input("Enter your first name: ")
lastName = input("Enter you last name: ")
dept = input("Enter your dept: ")

file.write(firstName + ',' + lastName + ',' + dept + ',\n')
file.close()

#Completetion notification
print("File write complete.")


import sys, os

sys.path.insert(0, os.path.abspath('./'))

from tools.deep_learning.cnn_utils import evaluate_prediction

possible_selection_metrics = ["best_loss", "best_balanced_accuracy", "last_checkpoint"]

def get_test_prediction(test_diagnosis_df, merged_df):
    import pandas as pd

    test_diagnosis_df=merged_df.merge(test_diagnosis_df, on=["participant_id"], how="right")
    test_diagnosis_df=dict(list(test_diagnosis_df.groupby("T1w_mri_field")))
    res_dict={}
    for key in [1.5, 3]:
        res_dict["test_%sT"%str(key)]=test_diagnosis_df[key]
    return res_dict

def load_test_and_separate(results_dict, args, cnn_classification_dir, selection_metric, mode,  fold, merged_df=None, stat_dict=None):
    import pandas as pd

    if args.bayesian:
        for test_mode, values_df in stat_dict[fold][selection_metric].groupby("mode"):
            if "test" in test_mode:
                prediction_column = "predicted_label_from_%s" % args.ba_inference_mode
                test_diagnosis_eval = evaluate_prediction(values_df[["true_label"]].values.astype(int),
                                                          values_df[[prediction_column]].values.astype(int))
                test_diagnosis_df = pd.DataFrame(test_diagnosis_eval, index=[0])
                test_diagnosis_df = test_diagnosis_df.assign(fold=fold,
                                                             mode=test_mode)

                results_dict[selection_metric] = pd.concat(
                    [results_dict[selection_metric], test_diagnosis_df],
                    axis=0)
    else:
        test_diagnosis_path = os.path.join(cnn_classification_dir, selection_metric,
                                           '%s_image_level_prediction.tsv' % (mode))
        test_diagnosis_df = pd.read_csv(test_diagnosis_path, sep='\t')
        prediction_column = "predicted_label"

        test_diagnosis_dict = get_test_prediction(test_diagnosis_df, merged_df)
        for test_mode in test_diagnosis_dict:
            test_diagnosis_eval = evaluate_prediction(test_diagnosis_dict[test_mode][["true_label"]].values.astype(int),
                                                      test_diagnosis_dict[test_mode][[prediction_column]].values.astype(int))
            test_diagnosis_df = pd.DataFrame(test_diagnosis_eval, index=[0])
            test_diagnosis_df = test_diagnosis_df.assign(fold=fold,
                                                         mode=test_mode)
            results_dict[selection_metric] = pd.concat(
                [results_dict[selection_metric], test_diagnosis_df],
                axis=0)
    return results_dict

def load_mode_results(results_dict, args, cnn_classification_dir, selection_metric, mode,  fold, load_from_ba_predictions=False,stat_dict=None):
    import pandas as pd
    if args.bayesian and load_from_ba_predictions:
        values_df = stat_dict[fold][selection_metric].groupby("mode").get_group(mode)
        prediction_column = "predicted_label_from_%s" % args.ba_inference_mode
        test_diagnosis_eval = evaluate_prediction(values_df[["true_label"]].values.astype(int),
                                                  values_df[[prediction_column]].values.astype(int))
        test_diagnosis_df = pd.DataFrame(test_diagnosis_eval, index=[0])
        test_diagnosis_df = test_diagnosis_df.assign(fold=fold,
                                                     mode=mode)

        results_dict[selection_metric] = pd.concat(
            [results_dict[selection_metric], test_diagnosis_df],
            axis=0)
    else:
        test_diagnosis_path = os.path.join(cnn_classification_dir, selection_metric,
                                           '%s_image_level_metrics.tsv' % (mode))
        if os.path.exists(test_diagnosis_path):
            test_diagnosis_df = pd.read_csv(test_diagnosis_path, sep='\t')
            test_diagnosis_df = test_diagnosis_df.assign(fold=fold,
                                                         mode=mode)
            test_diagnosis_df = test_diagnosis_df.drop(["total_loss", "image_id", ], axis=1)

            results_dict[selection_metric] = pd.concat([results_dict[selection_metric], test_diagnosis_df],
                                                       axis=0)
    return results_dict

def get_results(args, aggregation_type="average"):
    # aggregation_type=[average, separate, together]
    import pandas as pd
    import os
    import pathlib
    import numpy as np

    merged_df = None
    stat_dict = None
    if args.bayesian:
        stat_dict = get_uncertainty_distribution(args, aggregation_type="separate")
    else:
        if args.separate_by_MS:
            merged_df = pd.read_csv(args.merged_file, sep="\t")
            merged_df=merged_df[["participant_id", "T1w_mri_field"]]

    results_dict = {}
    currentDirectory = pathlib.Path(args.model_path)
    currentPattern = "fold-*"

    for fold_dir in currentDirectory.glob(currentPattern):
        fold = int(str(fold_dir).split("-")[-1])
        cnn_classification_dir = os.path.join(args.model_path, 'fold-%i' % fold, 'cnn_classification')
        if args.selection_metrics is None:
            selection_metrics = []
            for f in os.scandir(cnn_classification_dir):
                metric=os.path.basename(os.path.normpath(f.path))
                if metric in possible_selection_metrics:
                    selection_metrics.append(metric)
        else:
            selection_metrics=args.selection_metrics

        for selection_metric in selection_metrics:
            if not selection_metric in results_dict.keys():
                results_dict[selection_metric] = pd.DataFrame()
            modes = ['train', 'validation']
            for ms_el in args.MS_list:
                modes.append('test_' + ms_el)

            for mode in modes:
                if "test" in mode:
                    if args.separate_by_MS:
                        results_dict=load_test_and_separate(results_dict, args, cnn_classification_dir, selection_metric, mode,
                                               fold, merged_df, stat_dict=stat_dict)
                    else:
                        results_dict=load_mode_results(results_dict, args, cnn_classification_dir, selection_metric, mode,  fold, load_from_ba_predictions=True, stat_dict=stat_dict)

                else:
                    results_dict=load_mode_results(results_dict, args, cnn_classification_dir, selection_metric, mode, fold,
                                      load_from_ba_predictions=False, stat_dict=None)

    resulting_metrics_dict = {}
    if aggregation_type=="average":
        for key in results_dict.keys():
            res_df = results_dict[key].drop(["fold"], axis=1)
            resulting_metrics_dict[key] = res_df.groupby(["mode"], as_index=False, sort=False).agg(np.mean)
        resulting_metrics_dict = {aggregation_type: resulting_metrics_dict}

    elif aggregation_type=="separate":
        for key in results_dict.keys():
            metric_dict = dict(list(results_dict[key].groupby("fold")))
            for fold in metric_dict.keys():
                if fold not in resulting_metrics_dict.keys():
                    resulting_metrics_dict[fold] = {}
                resulting_metrics_dict[fold][key] = metric_dict[fold]
    else:
        resulting_metrics_dict={"all":results_dict}
    return resulting_metrics_dict

def get_uncertainty_distribution(args, aggregation_type="average"):
    import pandas as pd
    import os
    import pathlib
    import numpy as np

    if args.separate_by_MS:
        merged_df = pd.read_csv(args.merged_file, sep="\t")
        merged_df=merged_df[["participant_id", "T1w_mri_field"]]
    currentDirectory = pathlib.Path(args.model_path)
    currentPattern = "fold-*"
    stat_dict = {}
    for fold_dir in currentDirectory.glob(currentPattern):
        fold = int(str(fold_dir).split("-")[-1])
        cnn_classification_dir = os.path.join(args.model_path, 'fold-%i' % fold, 'cnn_classification')

        if args.selection_metrics is None:
            selection_metrics = []
            for f in os.scandir(cnn_classification_dir):
                metric=os.path.basename(os.path.normpath(f.path))
                if metric in possible_selection_metrics:
                    selection_metrics.append(metric)
        else:
            selection_metrics = args.selection_metrics

        for selection_metric in selection_metrics:
            if not selection_metric in stat_dict.keys():
                stat_dict[selection_metric] = pd.DataFrame()
            modes = ['test_' + ms_el for ms_el in args.MS_list]

            for mode in modes:
                test_diagnosis_path = os.path.join(cnn_classification_dir, selection_metric,
                                                   "bayesian_statistics", '%s_image_level_stats.tsv' % (mode))
                test_diagnosis_df = pd.read_csv(test_diagnosis_path, sep='\t')
                test_diagnosis_df["class_variance"] = test_diagnosis_df["class_variance"].apply(
                    lambda x: x[1:-1].split()).apply(lambda x: [float(i) for i in x])

                if "test" in mode and args.separate_by_MS:
                    test_diagnosis_dict = get_test_prediction(test_diagnosis_df, merged_df)
                    for key in test_diagnosis_dict:
                        test_diagnosis_dict[key] = test_diagnosis_dict[key].assign(fold=fold, mode=key)
                        stat_dict[selection_metric] = pd.concat([stat_dict[selection_metric], test_diagnosis_dict[key]],
                                                                axis=0)
                else:
                    test_diagnosis_df = test_diagnosis_df.assign(fold=fold, mode=mode)
                    stat_dict[selection_metric] = pd.concat([stat_dict[selection_metric], test_diagnosis_df], axis=0)
                # stat_dict[selection_metric].reset_index(inplace=True, drop=True)

    resulting_stat_dict = {}
    if aggregation_type=="average" or aggregation_type=="all":
        for key in stat_dict.keys():
            stat_df = stat_dict[key]
            additional_colums_df = stat_df[
                ["true_label", "predicted_label_from_mean", "predicted_label_from_mode", "mode", "participant_id"]]
            additional_colums_df = additional_colums_df.groupby(["mode", "participant_id"], as_index=False,
                                                                sort=False).agg(pd.Series.mode)
            stat_df = stat_df.drop(
                ["true_label", "predicted_label_from_mean", "predicted_label_from_mode", "fold"], axis=1)
            resulting_stat_dict[key] = stat_df.groupby(["mode", "participant_id"], as_index=False, sort=False).agg(np.mean)
            resulting_stat_dict[key]=resulting_stat_dict[key].merge(additional_colums_df, on=["mode", "participant_id"], how="right")
        resulting_stat_dict = {aggregation_type: resulting_stat_dict}

    elif aggregation_type == "separate":
        for key in stat_dict.keys():
            metric_dict = dict(list(stat_dict[key].groupby("fold")))
            for fold in metric_dict.keys():
                if fold not in resulting_stat_dict.keys():
                    resulting_stat_dict[fold] = {}
                resulting_stat_dict[fold][key] = metric_dict[fold]

    return resulting_stat_dict

def get_history(args, aggregation_type="average"):
    import pandas as pd
    import os
    import pathlib
    import numpy as np

    currentDirectory = pathlib.Path(args.model_path)
    currentPattern = "fold-*"
    history_df = pd.DataFrame()
    for fold_dir in currentDirectory.glob(currentPattern):
        fold = int(str(fold_dir).split("-")[-1])
        history = pd.read_csv(os.path.join(args.model_path, 'fold-%i' % fold, 'training.tsv'), sep='\t')
        history = history.assign(fold=fold)
        history_df = pd.concat([history_df, history], axis=0)
    if aggregation_type == "average":
        history_df = history_df[
            ["epoch", "balanced_accuracy_train", "loss_train", "balanced_accuracy_valid", "loss_valid"]]
        history_df = {aggregation_type: history_df.groupby("epoch", as_index=False).agg(np.mean)}

    elif aggregation_type == "all":
        history_df={aggregation_type:history_df}
    else:
        history_df = dict(list(history_df.groupby("fold")))
    return history_df

def reshape_dictionary(dict_sample):
    res = dict()
    for key, val in dict_sample.items():
        for key_in, val_in in val.items():
            if key_in not in res:
                temp = dict()
            else:
                temp = res[key_in]
            temp[key] = val_in
            res[key_in] = temp
    return res

def get_data_generic(args, reshape_dict=True):
    data = {}
    for data_type in args.data_types:
        data[data_type] = eval("get_%s" % data_type)(args, args.aggregation_type)
    #data is now in format {data_type: {fold_0:, ...fold_n etc}}

    #toDo: turn off this function?
    if reshape_dict:
        # reshape data to format  {fold_0: {data_type_1:, ...data_type_i etc}}
        data = reshape_dictionary(data)
    return data


from search import *
from action import Action

class LabProblem(Problem):
    goal_position: tuple = ()
    nb_explored_node: int = 0

    def goal_test(self, state):
        self.nb_explored_node += 1
        if self.goal_position == state.position_robot:
            return True
        return False

    def successor(self, state):
        sucess: list[tuple] = []
        action = Action(state)

        succ: tuple = action.up()  # Déplacer le smiley vers le haut
        if len(succ) != 0:  # si le déplcement est possible
            sucess.append(succ)  # Enregistrement de l'état et de l'action

        succ: tuple = action.down()  # Déplacer le smiley vers le bas
        if len(succ) != 0:
            sucess.append(succ)

        succ: tuple = action.right()  # Déplacer le smiley vers la droite
        if len(succ) != 0:
            sucess.append(succ)

        succ: tuple = action.left()  # Déplacer le smiley vers la gauche
        if len(succ) != 0:
            sucess.append(succ)

        return sucess

    def path_cost(self, c, state1, action, state2)->int:
        k, m = state2.position_robot  # Recupere position du S sur le state2
        grid_state1: list = state1.grid.copy()  # Etat de la grille

        #  Vérification de l'emplacement du smiley avant son déplacement
        if grid_state1[k][m] == ' ' or grid_state1[k][m] == '$':
            c += 1
        elif grid_state1[k][m] == 'H':
            c += 2
        return c


# 61. Rotate List
#

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def get_len(self, head):
        len = 0
        while (head):
            len += 1
            head = head.next
        return len

    def rotateRight(self, head: ListNode, k: int) -> ListNode:
        if head is None:
            return head
        len = Solution.get_len(self, head)
        k = k % len
        end = head
        for i in range(k):
            end = end.next
        start = head
        while (end.next):
            start = start.next
            end = end.next
        end.next = head
        head = start.next
        start.next = None

        return head

def prinLinedList(head):
    curNode = head
    while (curNode is not None):
        print(curNode.val)
        curNode = curNode.next

if __name__ == '__main__':
    s1 = ListNode(1)
    s2 = ListNode(2)
    s3 = ListNode(3)
    s4 = ListNode(4)
    s5 = ListNode(5)
    s6 = ListNode(6)
    s1.next = s2
    s2.next = s3
    s3.next = s4
    s4.next = s5
    s5.next = s6
    s = Solution()
    prinLinedList(s.rotateRight(s1, 20000000000000))


#%% Packages

import os
import sys

sys.path.append(
    os.path.join(os.path.join(os.path.dirname(__file__), os.pardir), os.pardir)
)

import csv
import pickle

import numpy as np

from homeostatic.definitions import level_position, level_states

#%% Data analysis

experiments = ["Hard", "Soft"]
scenarios = ["a", "b", "c", "d"]
starting_state = [4, 8, 8]

state_position = level_position(
    sum(starting_state), len(starting_state), starting_state
)
for i in range(len(starting_state), sum(starting_state)):
    state_position += len(level_states(i, 3))

with open("Results.csv", "a", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Established clonotypes"])
    writer.writerow(["Minimum", "Maximum", "Mean", "SD"])

    with open("Established/Data.bin", "rb") as data_file:
        data = pickle.load(data_file)
        row_data = [
            round(data.min(), 5),
            round(data.max(), 5),
            round(np.mean(data), 5),
            round(np.std(data), 5),
        ]
        writer.writerow(row_data)

    writer.writerow([""])

    writer.writerow(["3 Clonotypes"])
    writer.writerow(
        [
            "Niche",
            "Scenario",
            "Minimum",
            "Maximum",
            "Mean",
            "SD",
            f"n0 = ({starting_state[0]}, {starting_state[1]}, {starting_state[2]})",
        ]
    )

    for current_experiment in experiments:
        for current_matrix in range(4):
            with open(
                f"{current_experiment}/Matrix-{current_matrix}/Data.bin", "rb"
            ) as data_file:
                data = pickle.load(data_file)
                row_data = [
                    f"{current_experiment} niche",
                    scenarios[current_matrix],
                    round(data.min(), 5),
                    round(data.max(), 5),
                    round(np.mean(data), 5),
                    round(np.std(data), 5),
                    round(data[state_position], 5),
                ]
                writer.writerow(row_data)

Results/Mean time to extinction/MT-analysis.py


def craft():
    num = 1
    while num < n:
        num *= 2
    num *= 2
    tree = [0] * num
    return tree

def update(tree, i, x):
    v = len(tree) // 2 + i
    tree[v] = x
    while v > 1:
        v //= 2
        tree[v] = tree[2 * v] + tree[2 * v + 1]
    return tree

def get_sum(v, begin, end, left, right):
    if (right <= begin) or (left >= end):
        return 0
    if left >= begin and right <= end:
        return tree[v]
    mid = (left + right) // 2
    return \
        get_sum(v * 2, begin, end, left, mid) + \
        get_sum(v * 2 + 1, begin, end, mid, right)

sumrooks_in = open('sum-rooks.in', 'r')
sumrooks_out = open('sum-rooks.out', 'w')

# Читаем
n, k = map(int, sumrooks_in.readline().split())
tree = craft()
for i in range(k):
    request, first, second = map(str, sumrooks_in.readline().split())
    first = int(first)
    second = int(second)
    if request == 'A':
        tree = update(tree, first - 1, second)
    else:
        print(get_sum(1, first - 1, second, 0, (len(tree) // 2)),
              file=sumrooks_out)
sumrooks_in.close()

sumrooks_out.close()


for t in range(int(input())):
    input()
    l=[int(x) for x in input().split()]
    n=0
    for i in range(len(l)):
        if (l[i]==1) or (l[i]==0):
            continue
        for j in range(i+1,len(l)):
            try:
                l.index(l[i]*l[j])
            except:
                n=1
                break
        if n==1:
            break
    if n==0:
        print('yes')
    else:
        print('no')


# -*- coding: utf-8 -*-
'''Run a prediction for a comment through the reddit May 2015 hate speech model'''

from sklearn.feature_extraction.text import TfidfVectorizer
from string import punctuation
from nltk import word_tokenize
from nltk.stem import snowball
import xgboost as xgb
import cPickle as pickle
import numpy as np
import pandas as pd

stemmer = snowball.SnowballStemmer("english")

def stem_tokens(tokens, stemmer):
    '''Stem the tokens.'''
    stemmed = []
    for item in tokens:
        stemmed.append(stemmer.stem(item))
    return stemmed

def tokenize(text):
    '''Tokenize & stem. Stems automatically for now.
    Leaving "stemmer" out of function call, so it works with TfidfVectorizer'''
    tokens = word_tokenize(text)
    stems = stem_tokens(tokens, stemmer)
    return stems

def predict_comment(comment, classes, bst, vect):
    '''
    Where "comment" is the comment by the user, to be passed in.
    classes =
    '''
    comment_tfidf = vect.transform([comment])
    comment_xgb = xgb.DMatrix(comment_tfidf)
    yprob = bst.predict(comment_xgb).reshape(1, 5)  # hard coding -- only one comment at a time in this case.
    ylabel = classes[np.argmax(yprob, axis=1)]

    # print('The class is: {0} with probability {1}%'.format(ylabel, round(100 * np.max(yprob), 1)))

    return ylabel, round(100*np.max(yprob), 1), comment

def main():
    classes = ['Not Hate', 'Size Hate', 'Gender Hate', 'Race Hate', 'Religion Hate']

    # load saved xgboost model
    bst = xgb.Booster()
    bst.load_model('../FinalModel/modelv1/BuildModel/hatespeech.model')
    # load tf-idf matrix
    # tfidf_X = pickle.load(open('../FinalModel/BuildModel/tfidf_X.p', 'rb'))
    vect = pickle.load(open('../FinalModel/modelv1/BuildModel/vect.p', 'rb'))

    # get comment from user
    comment = raw_input('Enter comment: ')
    # predict class of comment
    predict_comment(comment, classes, bst, vect)

    predict = raw_input("Enter 'y' to get another prediction.")

    while predict == 'y':
        # get comment from user
        comment = raw_input('Enter comment: ')
        # predict class of comment
        predict_comment(comment, classes, bst, vect)
        predict = raw_input("Enter 'y' to get another prediction.")

if __name__ == "__main__":
    main()


import gym
import numpy as np
import matplotlib.pyplot as plt

num_images = 100
env = gym.make('Pong-v0')
env.reset()
done = False
path = 'env_images_test/'
for i in range(1000):
    # env.render()
    state, reward, done, _ = env.step(env.action_space.sample())
    state = state[35:195:2, ::2, 0]
    state[np.logical_or(state == 144, state == 109)] = 0
    state[state != 0] = 1
    state = state.astype(np.float)
    # state = np.expand_dims(state, axis=-1)
    if i>=500 and i<=500+num_images:
        plt.imsave(path+'{}.png'.format(i), state, cmap='gray')
    # print(state.shape)


def model_to_excel(model,name="model.xlsx"):
    import openpyxl
    wb = openpyxl.Workbook()
    sheet = wb.get_active_sheet()
    sheet.title = 'Metabolites'
    sheet['A1']="Metabolite id"
    sheet['B1']="Metabolite name"
    sheet['C1']="Metabolite compartment"
    sheet['D1']="Metabolite formula"
    for n, metabolite in enumerate(model.metabolites):
        nrow=n+2
        sheet['A'+str(nrow)]=metabolite.id
        sheet['B'+str(nrow)]=metabolite.name
        sheet['C'+str(nrow)]=metabolite.compartment
        #sheet['D'+str(nrow)]=metabolite.formula.id

    sheet=wb.create_sheet(title="Reactions")
    sheet['A1']="Reaction id"
    sheet['B1']="Reaction name"
    sheet['C1']="Reaction subsystem"
    sheet['D1']="Reaction"
    for n, reaction in enumerate(model.reactions):
        nrow=n+2
        sheet['A'+str(nrow)]=reaction.id
        sheet['B'+str(nrow)]=reaction.name
        sheet['C'+str(nrow)]=reaction.subsystem
        sheet['D'+str(nrow)]=reaction.reaction

    wb.save(name)


from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

classifier = Sequential()
classifier.add(Conv2D(32, (3, 3), input_shape = (64, 64, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
classifier.add(Flatten())
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,shear_range = 0.2,zoom_range = 0.2,horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
print(train_datagen.__doc__)
training_set = train_datagen.flow_from_directory('train',target_size = (64, 64),batch_size = 32,class_mode = 'binary')
test_set = test_datagen.flow_from_directory('train',target_size = (64, 64),batch_size = 32,class_mode = 'binary')
classifier.fit_generator(training_set,steps_per_epoch = 8,epochs = 1000,validation_data = test_set,validation_steps = 2000)

import numpy as np
from keras.preprocessing import image
test_image = image.load_img('/Users/saranshmittal/Development/Data-Science/Cat classification/train/cat/cat.100.jpg', target_size = (64, 64))
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict(test_image)
if result[0][0] == 1:
    prediction = 'dog'
    print(prediction)
else:
    prediction = 'cat'
    print(prediction)


# Default configuration for Cherry Py REST server

import cherrypy

config = {
    'global': {
        'server.thread_pool' : 30,  # Thread pool size (sys def = 10)
        'server.socket_host' : '0.0.0.0', # Current host
        'server.socket_port' : 8000,
        'server.max_request_body_size' : 400 * (1024 ** 2),  # N megabytes
        'engine.autoreload_on' : False,  # Restart when source files changed?
        'tools.gzip.on' : True,     # Support gzip compression
        'log.screen' : True,
        },
    '/': {
        'request.dispatch' : cherrypy.dispatch.MethodDispatcher(),
        # Let user see tracebacks.  Very useful for debugging, but
        # not typically considered good form as it exposes information
        # to users that could be exploited
        'request.show_tracebacks' : True,
        #change timeout duration
        'response.timeout' : 1080 #18 minutes
        }
    }


#!/usr/bin/python3

from random import random, choice, randint
from locale import getlocale
from os.path import exists, join
from datetime import datetime, timedelta
from math import floor

import sqlite3

MALE_FIRST_NAMES = 'maleFirstNames'

class DataSource:

    MALE_NAMES = 'maleNames'
    FEMALE_NAMES = 'femaleNames'
    LAST_NAMES = 'lastNames'

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

    def loadDataItems(self, localesDir, dataItems=None, locales=None):
        pass
        # if localesDir == None or len(localesDir.strip()) == 0:
            # raise Exception('localesDir not specified')
            #
        # if not exists(localesDir):
            # raise Exception("%s not found" % localesDir)
            #
        # self.localesDir = localesDir
        #
        # if dataItems == None or len(dataItems) == 0:
            # dataItems = DataSource.ALL_DATA_ITEMS
            #
        # if locales == None or len(locales) == 0:
            # locales = [getlocale()[0]]
        #
        # for dataItem in dataItems:
            # if dataItem not in DataSource.ALL_DATA_ITEMS:
                # raise Exception('unrecognized data item %s' % dataItem)
            # for locale in locales:
                # self.loadDataItem(dataItem, locale)

    def loadDataItem(self, dataItem, locale, *posArgs, **keywords):
        raise Exception('implement this method in subclass')

    def randomMaleName(self):
        return self.randomChoice(DataSource.MALE_NAMES)

    def randomFemaleName(self):
        return self.randomChoice(DataSource.FEMALE_NAMES)

    def randomLastName(self):
        return self.randomChoice(DataSource.LAST_NAMES)

class InMemoryDataSource(DataSource):

    def __init__(self):
        self.dataItems = {}

    def loadDataItem(self, dataItem, locale, *posArgs, **keywords):
        if 'values' not in keywords.keys():
            raise Exception('values not specified')

        self.dataItems[dataItem] = keywords['values']

    def randomChoice(self, dataItemName):
        if dataItemName not in self.dataItems.keys():
            raise Exception(dataItemName + " not present in data items")
        return choice(self.dataItems[dataItemName])

class SqliteDataSource(DataSource):

    def __init__(self):
        self.conn = None

    def open(self, dbFile):
        '''Opens an existing sqllite file if file exists.  Will create one if
        it does not exist'''

        self.conn = sqlite3.connect(dbFile)

    def loadDataItem(self, dataItem, locale):
        # Call base class method to validate that  files exist
        DataSource.loadDataItem(self, dataItem, locale)
        print('loadDataItem')

        cursor = self.conn.cursor()

        if not self.hasTable('nameControlTable'):
            cursor.execute(
                """create table if not exists maleFirstNames (
                    tableName text)""")

        if self.hasTable(dataItem):
            if self.hasRecords(dataItem):
                cursor.execute('delete maleFirstNames')
        else:
            cursor.execute(
                """create table if not exists maleFirstNames (
                    name text,
                    randSort integer)""")

        sourceFile = open(self.sourceFilePath, 'r')

        for line in sourceFile:
            line = line.strip()
            print(line)
            cursor.execute(
                "insert into maleFirstNames (name) values (?)",
                (line,))

        sourceFile.close()

    def hasTable(self, tableName):
        cursor = self.conn.cursor()
        cursor.execute(
            "select * from sqlite_master where tbl_name = ?",
            (tableName,))
        for row in cursor:
            return True
        return False

    def hasRecords(self, tableName):
        cursor = self.conn.cursor()
        cursor.execute(
            "select count(*) from %s" % tableName)
        for row in cursor:
            if row[0] == 0:
                return False
        return True

    def randomMaleName(self):
        pass

    def randomFemaleName(self):
        pass

    def close(self):
        if self.conn != None:
            self.conn.close()

    # def __init__(self):
        # self.conn = None
        #
    # def reLoad(self):
        # """opens an existing sqlite database"""
        # pass
        #
    # def load(self, localesDir, databaseFile, locales=None, dataItems=None):
        # """clears database and loads data into sqlite database from file."""
        # # check if localesDirectory exists
        #
        #
        #
        # if locales == None or len(locales) == 0:
            # locales = [getlocale()[0]]
        #
        # for locale in locales:
            # # do this in a cross platform way
            # localeDir = localesDir + '/' + locale
            # print(localeDir)
            #
    # def close(self):
        # self.conn.close()

class DataGenerationRule:
    def __init__(self):
        pass

class PersonAgeRule(DataGenerationRule):
    def getAge(self):
        return 90 * random()

class PersonSexRule(DataGenerationRule):
    def getSex(self):
        x = random()
        if x <= 0.495:
            return 'male'
        if x > 0.495 and x < 0.99:
            return 'female'
        return 'unknown'

class PersonContext:

    def __init__(self):
        self.currentDateTime = datetime.now()

        self.ageRule = PersonAgeRule()
        self.sexRule = PersonSexRule()

class Person:

    SEXES = ['male', 'female', 'unknown']

    def __init__(self, dataSource, context=None, **keywords):

        if context == None:
            context = PersonContext()

        if 'sex' in keywords.keys():
            self.sex = keywords['sex']
            if self.sex not in Person.SEXES:
                raise(ValueError())
        else:
            self.sex = context.sexRule.getSex()

        self.age = context.ageRule.getAge()

        self.dateOfBirth = datetime.today() - timedelta(self.age * 365.25)
        self.age = floor(self.age)

        self.firstName, tempSex = self.firstOrMiddleName(
            dataSource,
            self.sex,
            'firstName',
            **keywords)

        self.middleName, tempSex = self.firstOrMiddleName(
            dataSource,
            tempSex,
            'middleName',
            **keywords)

        self.lastName = dataSource.randomLastName()

    def firstOrMiddleName(self, dataSource, sex, nameType, **keywords):
        if nameType in keywords.keys():
            return keywords[nameType]
        if sex == 'male' or (sex == 'unknown' and random() < 0.5):
            return dataSource.randomMaleName(), 'male'
        return dataSource.randomFemaleName(), 'female'

    def __str__(self):
        array = {
            'sex': self.sex,
            'firstName': self.firstName,
            'middleName': self.middleName,
            'lastName': self.lastName,
            'dateOfBirth':self.dateOfBirth,
            'age':self.age}
        return str(array)

class Household:

    def __init__(self, dataSource, context=None, **keywords):
        numberOfAdults = randint(1,5)
        print("there are %d adults in the household")

        self.members = []

        if numberOfAdults > 1:
            if self.hasMarriedCouple():
                self.generateMarriedCouple(dataSource)

    def __str__(self):
        return str([str(x) for x in self.members])

    def hasMarriedCouple(self):
        return choice([True, False])

    def generateMarriedCouple(self, dataSource):
        spouse1 = Person(dataSource)
        self.members.append(spouse1)
        if self.isHomosexualCouple():
            pass

    def isHomosexualCouple(self):
        return randint(1,50) == 1
        # if 'middleName' in keywords.keys():
            # self.middleName = keywords['middleName']
        # else:
            # self.middleName = randomMiddleName(self.sex)
            #
        # if 'lastName' in keywords.keys():
            # self.lastName = keywords['lastName']
        # self.lastName = randomLastName(self.sex)
        #
        # if 'minAge' in keywords.keys():
            # minAge = keywords['minAge']
            # # add check to ensure minAge is numeric
        # else:
            # minAge = 0
            #
        # if 'maxAge' in keywords.keys():
            # maxAge = keywords['maxAge']
            # # add check to ensure maxAge is numeric
        # else:
            # maxAge = 110
            #
        # self.age = randint(minAge*100, maxAge*100)/100.0

# def randomCouple(**keywords):
    # """Will generate two random people who may or may not have the last name.
    # This function will override values for the sex and lastName keywords"""
    # if random() < 0.05:
        # # same - sex couple
        # keywords['sex'] = randomSex()
        # if random() < 0.33:
            # # share last_name
            # keywords['lastName'] = randomLastName()
            # return RandomPerson(**keywords), RandomPerson(**keywords)
        # return RandomPerson(**keywords), RandomPerson(**keywords)
#
    # if random() < 0.70 and 'lastName' not in keywords.keys():
        # keywords['lastName'] = randomLastName()
        #
    # keywords['sex'] = 'M'
    # person1 = RandomPerson(**keywords)
    #
    # keywords['sex'] = 'F'
    # person2 = RandomPerson(**keywords)
    # return person1, person2

if __name__ == '__main__':
    pass


from graphviz import Digraph

#We arrange the graph using Networkx and then paint it using Cytoscape.
G = Digraph(comment="Lung Cancer Experiment")
G.node('1', "Tobacco Use")
G.node('2', "Lung Cancer")
G.node('3', "Secondhand Smoke")
G.node('4', "Heavy Smoking")
G.node('5', "Complications")
G.node('6', "Death")
G.node('7', "Symptoms")
G.node('8', "Bone Pain")
G.node('9', "Treatable")
G.node('10',"Radiation Therapy")
G.node('11',"Bleeding")
G.node('12',"Chemical Imbalances")
G.node('13',"Pain")
G.node('14',"Speech Difficulties")
G.node('15',"Breathing Difficulties")
G.node('16',"Metastasize")
G.node('17',"Collect Fluid")
G.node('19',"Fatigue")
G.node('20',"Loss of appetite")
G.node('21',"Workplace")
G.node('22',"Radon Gas")
G.edge('1','2')
G.edge('3','2')
G.edge('4','2')
G.edge('2','5')
G.edge('2','5')
G.edge('2','6')
G.edge('2','7')
G.edge('2','8')
G.edge('2','9')
G.edge('2','10')
G.edge('2','11')
G.edge('2','12')
G.edge('2','13')
G.edge('2','14')
G.edge('2','15')
G.edge('2','16')
G.edge('2','17')
G.edge('9','19')
G.edge('9','20')
G.edge('21','2')
G.edge('22','2')
G.render("causal_graph")


"""
Give the Host and Gene name to print the express gene names
"""
import argparse
import re
import sys
from assignment5 import my_io
from assignment5 import config

def main():
    """
    Main function
    :return: Prints out Expressed genes in Mammal in STD.OUT format
    """
    args = get_cli_args()
    # function to check for passed arguments
    temp_host, gene = check_passed_args(args)
    # getting scientific name
    host = modify_host_name(temp_host)
    # file name and absolute path
    file = "/".join((config.get_unigene_directory(),
                     host, gene + "." + config.get_unigene_extension()))
    # checking if file exist in directory or not
    _check_file_exist(file, host, gene)
    # List of expressed genes sorted alphabetically
    tissue_strig = get_gene_data(file)
    # Print output on STD.OUT
    print_ouput(temp_host, gene, tissue_strig)

def print_ouput(host, gene, tissue_string):
    """
    Print Expressed gene name on STD OUT
    :param host: Name of the host
    :param gene: Name of the gene passed
    :param tissue_string: sorted list of expressed genes
    :return: None
    """
    print(f"In {host}, There are {len(tissue_string)} "
          f"tissues that {gene} is expressed in:\n")

    for i, value in enumerate(tissue_string, start=1):
        print(f"{i}. {value.title()}")

def get_gene_data(gene_file):
    """
    Get Epressed gene names from host file.
    :param gene_file: Absolute path to gene file of host
    :return: Sorted list of expresssed genes in host
    """
    fh_in = my_io.get_fh(gene_file, "r")

    tissue_strig = []

    for line in fh_in:
        if re.search("EXPRESS", line):
            line = line.replace("\n", "")
            line = re.sub('[A-Z]', "", line)
            tissue_strig = line.split("|")
            tissue_strig = [x.strip(' ') for x in tissue_strig]

    my_io.get_fh(fh_in, "close")

    return sorted(tissue_strig)

def _check_file_exist(file, temp_host, gene):
    # check for the existence of file
    if my_io.is_valid_gene_file_name(file):
        # using f-strings
        print(f"\nFound Gene {gene} for {temp_host}")
    else:
        print("Not found")
        print(f"Gene {gene} does not exist for {temp_host}. "
              f"exiting now...", file=sys.stderr)
        sys.exit()

def modify_host_name(host_name):
    """
    Get Scientific name from dictionary exist in config file
    if name with "_" is passed it can be treated as scientifc name
    :param host_name: Argument passed in CLI otions
    :return: Scientific name for Host
    """
    scientific_name = ""

    if "_" in host_name:
        scientific_name = host_name
    else:
        if host_name.lower() in list(config.get_host_keywords().keys()):
            scientific_name = config.get_host_keywords()[host_name.lower()]
        else:
            _print_host_directories()
            scientific_name = host_name

    return scientific_name

def _print_host_directories():
    """
    Internal function to print the name of valid Hosts data available
    in directory scientific and non-scientific both (case-insensitive)
    :return: NONE exits the program
    """

    print("\nEither the Host Name you are searching for is not in the database"
          "\nor If you are trying to use the scientific name please "
          "put the name in double quotes:\n"
          "\n\"Scientific name\"\n"
          "\nHere is a (non-case sensitive) list of available Hosts by scientific name\n")

    for i, value in enumerate(set(list(config.get_host_keywords().values())), start=1):
        print(f"{i}. {value}")

    print("\nHere is a (non-case sensitive) list of available Hosts by common name\n")

    for i, key in enumerate(list(config.get_host_keywords().keys()), start=1):
        print(f"{i}. {key.title()}")

def check_passed_args(args):
    """
    Check how many arguments passed, if NONE: return
    default file options
    :param args: Argparse file arguments, passed in CLI
    :return: Names of the files to open
    """

    host = "Homo_sapiens"
    gene = "TGM1"
    args_to_return1 = ""
    args_to_return2 = ""

    if len(sys.argv) > 2:
        args_to_return1 = args.HOST
        args_to_return2 = args.GENE
    else:
        args_to_return1 = host
        args_to_return2 = gene

    return args_to_return1, args_to_return2

def get_cli_args():
    """
    Get Command Line Argument function to read arguments from command
    line using argparse
    :return: Argument Parser object with all the required options
    """
    parser = argparse.ArgumentParser(description="Give the Host and Gene name")

    parser.add_argument("-host",
                        dest="HOST",
                        type=str,
                        help="Name of Host",
                        required=False)

    parser.add_argument("-gene",
                        dest="GENE",
                        type=str,
                        help="Name of Gene",
                        required=False)

    return parser.parse_args()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-

"""Utilities for building paths."""

import logging
import os
import tarfile
from typing import Optional
from urllib.parse import urlparse
from urllib.request import urlretrieve

import pandas as pd

from .constants import PYOBO_HOME

__all__ = [
    'get_prefix_directory',
    'prefix_directory_join',
    'get_prefix_obo_path',
    'get_url_filename',
    'ensure_path',
    'ensure_df',
    'ensure_excel',
    'ensure_tar_df',
]

logger = logging.getLogger(__name__)

def get_prefix_directory(prefix: str, *, version: Optional[str] = None) -> str:
    """Get the directory."""
    if version:
        directory = os.path.abspath(os.path.join(PYOBO_HOME, prefix, version))
    else:
        directory = os.path.abspath(os.path.join(PYOBO_HOME, prefix))
    os.makedirs(directory, exist_ok=True)
    return directory

def prefix_directory_join(prefix: str, *parts: str, version: Optional[str] = None) -> str:
    """Join the parts onto the prefix directory."""
    rv = os.path.join(get_prefix_directory(prefix, version=version), *parts)
    os.makedirs(os.path.dirname(rv), exist_ok=True)
    return rv

def get_prefix_obo_path(prefix: str) -> str:
    """Get the canonical path to the OBO file."""
    return prefix_directory_join(prefix, f"{prefix}.obo")

def get_url_filename(url: str) -> str:
    """Get the filename from the end of the URL."""
    parse_result = urlparse(url)
    return os.path.basename(parse_result.path)

def ensure_path(
    prefix: str,
    url: str,
    *,
    version: Optional[str] = None,
    path: Optional[str] = None,
) -> str:
    """Download a file if it doesn't exist."""
    if path is None:
        path = get_url_filename(url)

    if version:
        path = prefix_directory_join(prefix, path, version=version)
    else:
        path = prefix_directory_join(prefix, path)

    if not os.path.exists(path):
        logger.info('[%s] downloading OBO from %s', prefix, url)
        urlretrieve(url, path)

    return path

def ensure_df(
    prefix: str,
    url: str,
    *,
    version: Optional[str] = None,
    path: Optional[str] = None,
    sep: str = '\t',
    **kwargs,
) -> pd.DataFrame:
    """Download a file and open as a dataframe."""
    path = ensure_path(prefix, url, version=version, path=path)
    return pd.read_csv(path, sep=sep, **kwargs)

def ensure_excel(
    prefix: str,
    url: str,
    *,
    version: Optional[str] = None,
    path: Optional[str] = None,
    **kwargs,
) -> pd.DataFrame:
    """Download an excel file and open as a dataframe."""
    path = ensure_path(prefix, url, version=version, path=path)
    return pd.read_excel(path, **kwargs)

def ensure_tar_df(
    prefix: str,
    url: str,
    inner_path: str,
    *,
    version: Optional[str] = None,
    path: Optional[str] = None,
    **kwargs,
) -> pd.DataFrame:
    """Download a tar file and open as a dataframe."""
    path = ensure_path(prefix, url, version=version, path=path)
    with tarfile.open(path) as tar_file:
        with tar_file.extractfile(inner_path) as file:
            return pd.read_csv(file, **kwargs)


from sklearn.neighbors import KNeighborsClassifier, NearestNeighbors
import numpy as np
from lmnn import LargeMarginNearestNeighbor as LMNN

class imls():
    def __init__(self, k=3, mu=0.5, coef=5, randomState=np.random):
        self.coef = coef
        self.k = k
        self.mu = mu
        self.randomState = randomState

    def fitPredict(self, Xtrain, ytrain, Xtest):
        while self.coef*self.k > Xtrain.shape[0]:
            self.coef -= 1
        nn = NearestNeighbors(n_neighbors=self.coef*self.k)
        nn.fit(Xtrain)
        nearestNeighbors = nn.kneighbors(Xtest, return_distance=False)
        lmnn = LMNN(k=self.k,randomState=self.randomState, mu=self.mu)
        lmnn.fit(Xtrain, ytrain)
        Xtrain = lmnn.transform(Xtrain)
        Xtest = lmnn.transform(Xtest)
        nn = NearestNeighbors(n_neighbors=self.coef*self.k)
        nn.fit(Xtrain)
        newNearestNeighbors = nn.kneighbors(Xtest, return_distance=False)
        matching = np.array([len(np.intersect1d(
               nearestNeighbors[i],newNearestNeighbors[i]))>=int(self.coef*0.8)
                             for i in range(len(nearestNeighbors))])
        while matching.all() == False:
            nearestNeighbors = newNearestNeighbors.copy()
            lmnn = LMNN(k=self.k,randomState=self.randomState, mu=self.mu)
            lmnn.fit(Xtrain, ytrain)
            Xtrain = lmnn.transform(Xtrain)
            Xtest = lmnn.transform(Xtest)
            nn = NearestNeighbors(n_neighbors=self.coef*self.k)
            nn.fit(Xtrain)
            newNearestNeighbors = nn.kneighbors(Xtest, return_distance=False)
            matching = np.array([len(np.intersect1d(
              nearestNeighbors[i], newNearestNeighbors[i]))>=int(self.coef*0.8)
                                 for i in range(len(nearestNeighbors))])
        knc = KNeighborsClassifier(n_neighbors=self.k)
        knc.fit(Xtrain, ytrain)
        return knc.predict(Xtest)


from xai.brain.wordbase.verbs._reincarnate import _REINCARNATE

#calss header
class _REINCARNATES(_REINCARNATE, ):
	def __init__(self,):
		_REINCARNATE.__init__(self)
		self.name = "REINCARNATES"
		self.specie = 'verbs'
		self.basic = "reincarnate"
		self.jsondata = {}


#!/usr/bin/python3
""" states.py objects that handle all default API actions
    using GET, POST, DELETE"""
from models import storage
from models.state import State
from flask import jsonify, abort, request
from api.v1.views import app_views

@app_views.route('/states', methods=['GET'], strict_slashes=False)
@app_views.route('/states/<state_id>', methods=['GET'], strict_slashes=False)
def get_state_id(state_id=None):
    """ returns the state dictionary """
    if state_id is None:
        obj_list = []
        objs = storage.all("State")
        for obj in objs.values():
            obj_list.append(obj.to_dict())
        return jsonify(obj_list)
    obj = storage.get("State", state_id)
    if obj is None:
        abort(404)
    return jsonify(obj.to_dict())

@app_views.route('/states/<state_id>', methods=['DELETE'],
                 strict_slashes=False)
def delete_state(state_id=None):
    """ returns the state id """
    obj = storage.get("State", state_id)
    if obj is None:
        abort(404)
    storage.delete(obj)
    storage.save()
    return jsonify({}), 200

@app_views.route('/states', methods=['POST'], strict_slashes=False)
def new_state():
    """ creates a new state """
    if request.get_json() is None:
        abort(400, "Not a JSON")
    dic = request.get_json()
    if 'name' not in dic:
        abort(400, "Missing name")
    obj = State(**dic)
    storage.new(obj)
    storage.save()
    return jsonify(obj.to_dict()), 201

@app_views.route('/states/<state_id>', methods=['PUT'], strict_slashes=False)
def update_state(state_id=None):
    """ Updates the states """
    if request.get_json() is None:
        abort(400, "Not a JSON")
    obj = storage.get("State", state_id)
    if obj is None:
        abort(404)
    dic = request.get_json()
    dic.pop('created_at', None)
    dic.pop('updated_at', None)
    dic.pop('id', None)
    for key, value in dic.items():
        setattr(obj, key, value)
    obj.save()
    return jsonify(obj.to_dict()), 200


import pymcell as m

# Make a model
model = m.create_model()

# Set timestep
model.dt = 0.1

###
# Cylinder
###

# Create a cylinder
cylinder = model.create_simple_object(name="My Cylinder", type="CYLINDER", center=[0,0,0], radius=[0.1,0.1,100])

###
# To release the mols, also make a thin box
###

# Create a box
box = model.create_simple_object(name="My Box", type="CUBE", center=[0,0,0], radius=[0.1,0.1,0.01])

###
# Species
###

# Create a species
mol_A = model.create_species(name="A",dc=1) # Volume mol by default

###
# Release molecules at the intersection of the box with the cylinder
###

list_of_mols_to_release = [mol_A]
number_of_each_to_release = [100]
model.release_mols(list_of_mols_to_release,
	nrel = number_of_each_to_release,
	loc = "%o[ALL] * %o[ALL]" % (cylinder,box))

###
# Run the simulation
###

n_iter = 100
model.run(n_iter)


#A program to print n number of even numbers, taking input to n

n = int(input('Enter the number of terms:')) #taking input

total_terms = 0                     #to check the no. of even numbers printed
number = 0
while total_terms <= n:             #checking if no. of printed numbers is still less than n
    if number % 2 == 0:             #checking if the number is an even number
        print(number)
        total_terms += 1
    number += 1


import logging
from unittest.mock import patch

from django.test import override_settings

import pytest

from thenewboston_node.business_logic.blockchain.base import BlockchainBase
from thenewboston_node.business_logic.blockchain.memory_blockchain import MemoryBlockchain
from thenewboston_node.business_logic.blockchain.mock_blockchain import MockBlockchain
from thenewboston_node.business_logic.tests.factories import add_blocks_to_blockchain
from thenewboston_node.business_logic.tests.mocks.storage_mock import StorageMock
from thenewboston_node.business_logic.utils.iter import get_generator

logger = logging.getLogger(__name__)

LARGE_MEMORY_BLOCKCHAIN_SIZE = 100

MEMORY_BLOCKCHAIN_CLASS = 'thenewboston_node.business_logic.blockchain.memory_blockchain.MemoryBlockchain'
FILE_BLOCKCHAIN_CLASS = 'thenewboston_node.business_logic.blockchain.file_blockchain.FileBlockchain'
MOCK_BLOCKCHAIN_CLASS = 'thenewboston_node.business_logic.blockchain.mock_blockchain.MockBlockchain'

@pytest.fixture
def get_head_block_mock():
    with patch.object(MockBlockchain, 'get_head_block', return_value=None) as mock:
        yield mock

@pytest.fixture
def get_next_block_number_mock():
    with patch.object(MockBlockchain, 'get_next_block_number', return_value=0) as mock:
        yield mock

@pytest.fixture
def get_next_block_identifier_mock():
    with patch.object(MockBlockchain, 'get_next_block_identifier', return_value='next-block-identifier') as mock:
        yield mock

@pytest.fixture
def get_account_state_mock():
    with patch.object(MockBlockchain, 'get_account_balance', return_value=430) as mock:
        yield mock

@pytest.fixture
def get_account_lock_mock():
    with patch.object(MockBlockchain, 'get_account_balance_lock', return_value='fake-balance-lock') as mock:
        yield mock

def yield_forced_blockchain(class_, class_kwargs=None):
    blockchain_settings = {'class': class_, 'kwargs': class_kwargs or {}}

    BlockchainBase.clear_instance_cache()
    with override_settings(BLOCKCHAIN=blockchain_settings):
        blockchain = BlockchainBase.get_instance()
        yield blockchain
    BlockchainBase.clear_instance_cache()

def yield_and_init_forced_blockchain(class_, blockchain_genesis_state, class_kwargs=None):
    blockchain = next(yield_forced_blockchain(class_, class_kwargs))
    blockchain.add_blockchain_state(blockchain_genesis_state)
    blockchain.validate()
    yield blockchain

@pytest.fixture
def memory_blockchain(blockchain_genesis_state):
    blockchain = MemoryBlockchain()
    blockchain.add_blockchain_state(blockchain_genesis_state)
    blockchain.validate()
    yield blockchain

@pytest.fixture
def forced_memory_blockchain(blockchain_genesis_state):
    yield from yield_and_init_forced_blockchain(MEMORY_BLOCKCHAIN_CLASS, blockchain_genesis_state)

@pytest.fixture
def forced_file_blockchain(blockchain_genesis_state, blockchain_directory):
    yield from yield_and_init_forced_blockchain(
        FILE_BLOCKCHAIN_CLASS, blockchain_genesis_state, class_kwargs={'base_directory': blockchain_directory}
    )

@pytest.fixture(autouse=True)  # Autouse for safety reasons
def forced_mock_blockchain(blockchain_genesis_state):
    yield from yield_and_init_forced_blockchain(MOCK_BLOCKCHAIN_CLASS, blockchain_genesis_state)

@pytest.fixture
def large_blockchain(treasury_account_key_pair):
    blockchain = BlockchainBase.get_instance()

    accounts = blockchain.get_first_blockchain_state().account_states
    assert len(accounts) == 1
    treasury_account, account_state = list(accounts.items())[0]
    assert treasury_account_key_pair.public == treasury_account
    assert account_state.balance > 10000000000  # tons of money present

    add_blocks_to_blockchain(blockchain, 100, treasury_account_key_pair.private)
    yield blockchain

@pytest.fixture
def file_blockchain_w_memory_storage(
    forced_file_blockchain, blockchain_genesis_state, forced_mock_network, get_primary_validator_mock,
    get_preferred_node_mock
):
    block_storage_mock = patch.object(forced_file_blockchain, 'block_storage', StorageMock())
    arf_storage_mock = patch.object(forced_file_blockchain, 'account_root_files_storage', StorageMock())

    with block_storage_mock, arf_storage_mock:
        forced_file_blockchain.add_blockchain_state(blockchain_genesis_state)
        forced_file_blockchain.validate()
        yield forced_file_blockchain

@pytest.fixture
def blockchain_base(blockchain_genesis_state):
    blockchain = BlockchainBase()
    with patch.object(blockchain, 'yield_blockchain_states', get_generator([blockchain_genesis_state])):
        yield blockchain


from __future__ import absolute_import
import traceback
import thundra.constants as constants
from urllib.parse import urlparse
from thundra.integrations.base_integration import BaseIntegration

class RequestsIntegration(BaseIntegration):
    CLASS_TYPE = 'http'

    def __init__(self):
        pass

    def get_operation_name(self):
        return 'http_call'

    def inject_span_info(self, scope, wrapped, instance, args, kwargs, response, exception):
        prepared_request = args[0]
        method = prepared_request.method
        url = prepared_request.url
        parsed_url = urlparse(url)
        path = parsed_url.path
        query = parsed_url.query
        host = parsed_url.netloc
        span = scope.span

        span.operation_name = url
        span.domain_name =  constants.DomainNames['API']
        span.class_name =  constants.ClassNames['HTTP']

        ## ADDING TAGS ##

        tags = {
            constants.SpanTags['SPAN_TYPE']: constants.SpanTypes['HTTP'],
            constants.SpanTags['OPERATION_TYPE']: 'CALL',
            constants.HttpTags['HTTP_METHOD']: method,
            constants.HttpTags['HTTP_URL']: url,
            constants.HttpTags['HTTP_PATH']: path,
            constants.HttpTags['HTTP_HOST']: host,
            constants.HttpTags['QUERY_PARAMS']: query,
        }

        span.tags = tags

        if exception is not None:
            self.set_exception(exception, traceback.format_exc(), span)

        if response is not None:
            self.set_response(response, span)

    def set_exception(self, exception, traceback_data, span):
        span.set_tag('error.stack', traceback_data)
        span.set_error_to_tag(exception)

    def set_response(self, response, span):
        statusCode = response.status_code
        span.set_tag(constants.HttpTags['HTTP_STATUS'], statusCode)


import pandas as pd
from pandas.api.types import CategoricalDtype
import numpy as np
import matplotlib.pyplot as plt

def main():

    dtype_dict = {
        "key": "string",
        "utility": "category",
        "usability": "float",
        "interface": "float",
        "relevance": CategoricalDtype(
            categories=["Low", "Medium", "High"], ordered=True),
        "response_time": CategoricalDtype(
            categories=["Slow", "Neutral", "Fast"], ordered=True),
        "quality": CategoricalDtype(categories=["Bad", "Average", "Good"], ordered=True),
        "use?": CategoricalDtype(categories=["No", "Yes"], ordered=True),
        "recommend?": CategoricalDtype(categories=["No", "Yes"], ordered=True),
        "overall": "float",
        "num_liked": "float"
    }

    df = pd.read_csv("./feedback.csv", dtype=dtype_dict)
    cat_cols = df.select_dtypes(["category"]).columns
    df[cat_cols] = df[cat_cols].apply(lambda x: x.cat.codes)
    print(df)

    for column in df.columns:
        if column in ["key", "utility"]:
            continue
        x = ["MovieRecommender", "PickAMovie", "SuggestMeMovie"]
        means = []
        for site in df["utility"].unique():
            sitedf = df.loc[df["utility"] == site]
            means.append(sitedf[column].mean())
        x_pos = [i for i, _ in enumerate(x)]

        plt.clf()
        plt.bar(x_pos, means)
        plt.xlabel("website")
        plt.ylabel("Mean {}".format(column))
        plt.title("Website vs mean {}".format(column))
        plt.xticks(x_pos, x)

        plt.savefig("./plots/{}.png".format(column))

if __name__ == "__main__":
    main()


import numpy, scipy, sklearn.feature_selection, sys, pandas, scipy.stats
sys.path.append("/Users/pwangel/Gene_Analysis")
from ga_utils import *
from scipy import optimize

def transform_distribution(dataframe, scale_parameter):

    for i_col in dataframe.columns:

        col_range  = dataframe[i_col].max()-dataframe[i_col].min()
        n_bins     = int(col_range/dataframe[i_col].std()/scale_parameter)+2
        starting_point = dataframe[i_col].mean() + 0.5*dataframe[i_col].std()*scale_parameter
        minimum    = dataframe[i_col].min()
        maximum    = dataframe[i_col].max()

        upper_bins = numpy.array([dataframe[i_col].std()*scale_parameter*pos+starting_point for pos in range(n_bins//2+1)])
        lower_bins = numpy.array([-dataframe[i_col].std()*scale_parameter*pos+starting_point for pos in range(n_bins//2+1)])
        all_bins   = numpy.concatenate((lower_bins[::-1], upper_bins[1:]))
        sel        = (all_bins >= minimum) & (all_bins <= maximum)
        all_bins   = all_bins[sel]
        labels     = numpy.concatenate((numpy.arange(start =-len(lower_bins[lower_bins>=minimum])+2, stop=0), numpy.arange(start=0, stop=len(upper_bins[upper_bins <= maximum]))))
        dataframe[i_col] = pandas.cut(dataframe[i_col], bins=all_bins, labels=labels)

    return dataframe

'''Finds common genes between a group of RNASeq and Microarray datasets.'''
'''Then plots 2d Histogram comparing measure correlation coefficients between Microarray and RNASeq'''

sample_threshold  = 20

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from plotly.graph_objs import *
import plotly.figure_factory as ff

# Read in data

RNASeq_data, labels = read_file_lists.smash_into_matrix('/Users/pwangel/Data/ensembl_hg19_v69_mm9_v67/', 'RNASeq', sample_threshold, 'TMM RPKM (Log2)', 'ENSG', False)
Microarray_data, labels = read_file_lists.smash_into_matrix('/Users/pwangel/Data/ensembl_hg19_v69_mm9_v67/', 'Microarray', sample_threshold, None, 'ENSG', False)

print("Comparing RNASeq and Microarray gene content")

RNASeq_data        = RNASeq_data.loc[(RNASeq_data.count(axis=1).values > len(RNASeq_data.columns)/2)]
Microarray_data    = Microarray_data.loc[(Microarray_data.count(axis=1).values > len(Microarray_data.columns)/2)]

common_genes       = numpy.intersect1d(RNASeq_data.index.values, Microarray_data.index.values)

print("Kept %d common genes" %len(common_genes))
iu = numpy.triu_indices(len(common_genes),1)

df_gene_list       = pandas.DataFrame(index=common_genes)

RNASeq_data        = df_gene_list.merge(RNASeq_data, how='left', left_index=True, right_index=True, validate='1:1')
Microarray_data    = df_gene_list.merge(Microarray_data, how='left', left_index=True, right_index=True, validate='1:1').sample(frac=0.5, replace=False, axis=1)

print("Have dataframes of size:")

print(RNASeq_data.shape)
print(Microarray_data.shape)

# Let's do an experimental transform
#bins = 100
#labels = numpy.linspace(start=0.0, stop=1.0, num=bins+1)
#labels = labels[:-1]+0.5*(labels[1]-labels[0])
#labels = scipy.stats.lognorm.ppf(labels, s=0.75)

#for i_col in RNASeq_data.columns:
#	RNASeq_data[i_col] = pandas.qcut(RNASeq_data[i_col], q=bins, labels =labels , retbins=False).astype(float)

#for i_col in Microarray_data.columns:
#	Microarray_data[i_col] = pandas.qcut(Microarray_data[i_col], q=bins, labels =labels , retbins=False).astype(float)

#RNASeq_correlation_array      = run_parallel.parallelized_correlation(RNASeq_data.sort_index()).as_matrix()[iu].astype(float)
#non_parRNASeq_correlation_array      = RNASeq_data.sort_index().transpose().corr(method='pearson', min_periods=10).as_matrix()[iu]
#print(len(RNASeq_correlation_array[RNASeq_correlation_array!= non_parRNASeq_correlation_array]))

print("Completed RNASeq correlations")

#Microarray_correlation_array  = Microarray_data.sample(n=1000, axis=1, replace =False).sort_index().transpose().corr(method='pearson', min_periods=10).as_matrix()[iu]
#Microarray_correlation_array   = run_parallel.parallelized_correlation(Microarray_data.sort_index()).as_matrix()[iu].astype(float)
print("Completed Microarray correlations")

sel = (~numpy.isnan(Microarray_correlation_array)) & (~numpy.isnan(RNASeq_correlation_array))
heat, x_bins, y_bins = numpy.histogram2d(x=Microarray_correlation_array[sel], y=RNASeq_correlation_array[sel], bins=200)
heat                 = numpy.power(heat, 1.0) #shows the trend more clearly, i hope

fitfunc = lambda p, x: p[0]+ p[1]*x # target function
errfunc = lambda p, x, y, weight: (fitfunc(p, x) - y)/weight # distance to the target function
p0 = [0.1, 0.5] # initial guess for the parameters

weights   = []
y_plot    = []
for i_col in range(len(x_bins)-1):
    weights.append(1.0/scipy.stats.norm.fit(heat[:,i_col])[1])
    y_plot.append(y_bins[numpy.argmax(heat[:,i_col])])

p1, success = optimize.leastsq(errfunc, p0[:], args=(x_bins[:-1], y_plot, weights))

data_to_plot = [Heatmap(z=heat, x=x_bins, y=y_bins)]
data_to_plot.append(Scatter(x=[-0.9, 0.9], y=[-0.9, 0.9], mode='lines', name='1:1', \
                            line=dict(color = 'black', width=2, dash='dash')))
data_to_plot.append(Scatter(x=x_bins, y=fitfunc(p1, x_bins[:-1]), mode='lines', name='y=%.2f x +%.2f' %(p1[1], p1[0]), \
                            line=dict(color = 'k', width=2, dash='dash')))
data_to_plot.append(Scatter(x=x_bins, y=y_plot, mode='lines', name='Max density', \
                            line=dict(color = 'white', width=2, dash='dash')))

fig = Figure(data=data_to_plot,
        layout=Layout(title='p(pearson)', xaxis=dict(title='micorarray correlation coefficient'), yaxis=dict(title='rnaseq correlation coefficient')) )
plot(fig, auto_open=False, filename='/users/pwangel/plotlyworkspace/transformed_Microarray_vs_RNASeq_pearson.html')


#!/usr/bin/env python3

# Copyright (c) 2018 Anki, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License in the file LICENSE.txt or at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Play animations on Vector

Play an animation using a trigger, and then another animation by name.
"""
import sys,getopt, anki_vector
#import asyncio, threading, time

def main():

    #conn.run_coroutine(play_animation()).result()
    #loop = asyncio.get_event_loop()

    try:
        opts, args = getopt.getopt(sys.argv[1:], "s:i:c:")
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    action = "anim_holiday_hny_fireworks_01"
    serial = None
    config = None
    ip=None
    for o, a in opts:
        if o == "-s":
            serial = a.strip()
        elif o == "-a":
            action = a.strip()
        elif o == '-c':
            config  = {"cert": a.strip()}
        elif o == '-i':
            ip = a.strip()
        else:
            action = "anim_holiday_hny_fireworks_01"
           # assert False, "unhandled option"

    # Connect to your Vector
    # config = { "cert": "/home/ddevine/.anki_vector/Vector-P9H1-006037af.cert", "name" : "Vector-P9H1",
    #   "192.168.1.7:443", , "cVFCZLc3R/aDVIP5tk9q8Q==")
    # conn.connect(20)

    # Close the connectionanim_pounce_success_02anim_holiday_hny_fireworks_01

    #args2 = anki_vector.util.parse_command_args()
    #print(res)

    with anki_vector.Robot(serial = serial, config = config, ip=ip) as robot:
        print("Playing animation by name: " + action)
        robot.anim.play_animation(action)

if __name__ == "__main__":
    main()