#!/usr/bin/env python

import rospy
from sensor_msgs.msg import JointState, RegionOfInterest, CameraInfo
from dynamixel_controllers.srv import *
from std_msgs.msg import Float64
from math import radians
import thread
import random

class HeadTracker():
    def __init__(self):
        rospy.init_node("head_tracker")

        rospy.on_shutdown(self.shutdown)

        rate = rospy.get_param("~rate", 50)
        r = rospy.Rate(rate)
        tick = 1.0 / rate

        # Keep the speed updates below about 5 Hz; otherwise the servos
        # can behave erratically.
        speed_update_rate = rospy.get_param("~speed_update_rate", 10)
        speed_update_interval = 1.0 / speed_update_rate

        # How big a change do we need in speed before we push an update
        # to the servos?
        self.speed_update_threshold = rospy.get_param("~speed_update_threshold", 0.01)

        # What are the names of the pan and tilt joints in the list of dynamixels?
        self.head_pan_joint = rospy.get_param('~head_pan_joint', 'head_pan_joint')
        self.head_tilt_joint = rospy.get_param('~head_tilt_joint', 'head_tilt_joint')

        self.joints = [self.head_pan_joint, self.head_tilt_joint]

        # Joint speeds are given in radians per second
        self.default_joint_speed = rospy.get_param('~default_joint_speed', 1.0)
        self.max_joint_speed = rospy.get_param('~max_joint_speed', 2.0)

        # How far ahead or behind the target (in radians) should we aim for?
        self.lead_target_angle = rospy.get_param('~lead_target_angle', 1.0)

        # The pan/tilt thresholds indicate what percentage of the image window
        # the ROI needs to be off-center before we make a movement
        self.pan_threshold = rospy.get_param("~pan_threshold", 0.05)
        self.tilt_threshold = rospy.get_param("~tilt_threshold", 0.05)

        # The gain_pan and gain_tilt parameter determine how responsive the
        # servo movements are. If these are set too high, oscillation can result.
        self.gain_pan = rospy.get_param("~gain_pan", 1.0)
        self.gain_tilt = rospy.get_param("~gain_tilt", 1.0)

        # Set limits on the pan and tilt angles
        self.max_pan = rospy.get_param("~max_pan", radians(145))
        self.min_pan = rospy.get_param("~min_pan", radians(-145))
        self.max_tilt = rospy.get_param("~max_tilt", radians(90))
        self.min_tilt = rospy.get_param("~min_tilt", radians(-90))

        # How long we are willing to wait (in seconds) for a target before re-centering the servos?
        self.recenter_timeout = rospy.get_param('~recenter_timeout', 5)

        # Monitor the joint states of the pan and tilt servos
        self.joint_state = JointState()
        rospy.Subscriber('joint_states', JointState, self.update_joint_state, queue_size=1)

        # Wait until we actually have joint state values
        while self.joint_state == JointState():
            rospy.sleep(1)

        # Initialize the servo services and publishers
        self.init_servos()

        # Center the pan and tilt servos at the start
        self.center_head_servos()

        # Set a flag to indicate when the target has been lost
        self.target_visible = False

        # Set a timer to determine how long a target is no longer visible
        target_lost_timer = 0.0

        # Set a timer to track when we do a speed update
        speed_update_timer = 0.0

        # Initialize the pan and tilt speeds to zero
        pan_speed = tilt_speed = 0.0

        # Get a lock for updating the self.move_cmd values
        #self.lock = thread.allocate_lock()

        rospy.wait_for_message('joint_states', JointState)

        rospy.loginfo("Ready to track target.")

        while not rospy.is_shutdown():

            self.pan_speed=1.0
            self.tilt_speed=1.0

            random_pan=random.randint(-145, 145)
            random_pan=radians(random_pan)
            self.pan_position = random_pan;

            random_tilt=random.randint(-90, 90)
            random_tilt=radians(random_tilt)
            self.tilt_position = random_tilt

            self.set_servo_speed(self.head_pan_joint, self.pan_speed)
            self.set_servo_speed(self.head_tilt_joint, self.tilt_speed)

                    # Update the pan position
            if self.last_pan_position != self.pan_position:
               self.set_servo_position(self.head_pan_joint, self.pan_position)
               self.last_pan_position = self.pan_position

                    # Update the tilt position
            if self.last_tilt_position != self.tilt_position:
               self.set_servo_position(self.head_tilt_joint, self.tilt_position)
               self.last_tilt_position = self.tilt_position
            rospy.sleep(2.0)
            #r.sleep()

    def center_head_servos(self):
        rospy.loginfo("Centering servos.")

        self.servo_speed[self.head_pan_joint](self.default_joint_speed)
        self.servo_speed[self.head_tilt_joint](self.default_joint_speed)

        current_tilt = self.joint_state.position[self.joint_state.name.index(self.head_tilt_joint)]
        current_pan = self.joint_state.position[self.joint_state.name.index(self.head_pan_joint)]

        while abs(current_tilt) > 0.05 or abs(current_pan) > 0.05:
            self.servo_position[self.head_pan_joint].publish(0)
            self.servo_position[self.head_tilt_joint].publish(0)

            rospy.sleep(0.1)

            current_tilt = self.joint_state.position[self.joint_state.name.index(self.head_tilt_joint)]
            current_pan = self.joint_state.position[self.joint_state.name.index(self.head_pan_joint)]

        self.servo_speed[self.head_pan_joint](0.0)
        self.servo_speed[self.head_tilt_joint](0.0)

    def init_servos(self):
        # Create dictionaries to hold the speed, position and torque controllers
        self.servo_speed = dict()
        self.servo_position = dict()
        self.torque_enable = dict()

        # Connect to the set_speed services and define a position publisher for each servo
        rospy.loginfo("Waiting for joint controllers services...")

        for joint in sorted(self.joints):
            # The set_speed services
            set_speed_service = '/' + joint + '/set_speed'
            rospy.wait_for_service(set_speed_service)
            self.servo_speed[joint] = rospy.ServiceProxy(set_speed_service, SetSpeed, persistent=True)

            # Initialize the servo speed to the default_joint_speed
            self.servo_speed[joint](self.default_joint_speed)

            # The position controllers
            self.servo_position[joint] = rospy.Publisher('/' + joint + '/command', Float64, queue_size=5)

            # A service to enable/disable servo torque
            torque_enable = '/' + joint + '/torque_enable'
            rospy.wait_for_service(torque_enable)
            self.torque_enable[joint] = rospy.ServiceProxy(torque_enable, TorqueEnable)
            self.torque_enable[joint](False)

        self.pan_position = 0
        self.tilt_position = 0
        self.pan_speed = 0
        self.tilt_speed = 0

        self.last_pan_position = 0
        self.last_tilt_position = 0
        self.last_tilt_speed = 0
        self.last_pan_speed = 0

    def set_servo_speed(self, servo, speed):
        # Guard against a speed of exactly zero which means
        # "move as fast as you can" to a Dynamixel servo.
        if speed == 0:
            speed = 0.01
        self.servo_speed[servo](speed)

    def set_servo_position(self, servo, position):
        self.servo_position[servo].publish(position)

    def update_joint_state(self, msg):
        self.joint_state = msg

    def get_camera_info(self, msg):
        self.image_width = msg.width
        self.image_height = msg.height

    def shutdown(self):
        rospy.loginfo("Shutting down head tracking node.")

        # Turn off updates from the /roi subscriber
        try:
            self.roi_subscriber.unregister()
        except:
            pass

        # Center the servos
        self.center_head_servos()

        rospy.sleep(2)

        # Relax all servos to give them a rest.
        rospy.loginfo("Relaxing pan and tilt servos.")

        for servo in self.joints:
            self.torque_enable[servo](False)

if __name__ == '__main__':
    try:
        HeadTracker()
        rospy.spin()
    except rospy.ROSInterruptException:
        rospy.loginfo("Head tracking node terminated.")


from xai.brain.wordbase.verbs._blackball import _BLACKBALL

#calss header
class _BLACKBALLING(_BLACKBALL, ):
	def __init__(self,):
		_BLACKBALL.__init__(self)
		self.name = "BLACKBALLING"
		self.specie = 'verbs'
		self.basic = "blackball"
		self.jsondata = {}


class Solution(object):
    def minSubArrayLen(self, s, nums):
        """
        :type s: int
        :type nums: List[int]
        :rtype: int
        """
        # start coding at 8:32
        left = right = 0;
        sum = 0; ans = len(nums)+1;
        while right < len(nums):
            while sum < s and right < len(nums):
                sum += nums[right];
                right += 1;
            while sum >= s:
                ans = min(ans, right-left);
                sum -= nums[left];
                left += 1;
        return 0 if ans == len(nums)+1 else ans;
        # first submit at 8:38 and pass


#tilpro12
#testclass.py
#Program som testar sökfunktionen search utifrån testfall i en textfil
#Skrivet av Simon Johansson

#state 1 = objekt skapat
#state 2 = objekt skapt, vet vilken fil
#state 3 = läst in data från fil
#state 4 = testat data

class testclass:

    def __init__(self,filename = None):
        self.filename = filename
        self.testdata = None

        if filename != None:
            self.state = 2
        else:
            self.state = 1

    def setfile(self,filename):
        self.filename = filename
        self.state = 2

    def parsefile(self):
        if self.state == 1:
            return
        file = open(self.filename,"r")
        self.testdata = list()
        line = file.readline()
        while line != "":
            if line[0] == "#":
                    tmp = {}
                    tmp["quantity"] = file.readline().strip()
                    tmp["needle"] = file.readline().strip()
                    tmp["expected_result"] = file.readline().strip() == "True" and True or False
                    tmp["type"] = file.readline().strip()
                    if tmp["type"] == "matrix":
                        matrix = list()
                        line = file.readline().strip()
                        while line != "":
                            matrix.append(line.split())
                            line = file.readline()
                        tmp["haystack"] = matrix
                    else:
                        tmp["haystack"] = file.readline().strip()
                    self.testdata.append(tmp)
            line = file.readline()

        self.state = 3

    def execute(self):
        testdata = list()
        from functions import search
        for row in self.testdata:
            if row["type"] == "matrix":
                from matrix import matrix
                obj = matrix(row["haystack"])
                obj.createrows()
                obj.createcols()
                obj.creatediags()
                haystack = [obj.rows,obj.cols,obj.diags]
                row["matrix"] = obj.printmatrix()
            else:
                haystack = row["haystack"]
            row["result"] = search(row["needle"],haystack,row["quantity"])
            testdata.append(row)
        self.testdata = testdata
        self.state = 4

    def printresult(self):
        if self.state != 4:
            return;
        output = "Resultat:\n"
        for row in self.testdata:
            output += "Looking for "+row["quantity"]+" \""+row["needle"]+"\" in a row in the "
            if row["type"] == "matrix":
                output += "matrix :\n"+row["matrix"]
            else:
                output += "vector \""+row["haystack"]+"\"\n"
                output += "Expected result: "+str(row["expected_result"])+"\n"
                output += "Result: "+str(row["result"])+"\n"
        return output;

    def __str__(self):
        if self.state == 1:
            output = "Skapad, vet ännu inte vilken fil."
        elif self.state == 2:
            output = "Skapad, ska läsa in data från filen \""+self.filename+"\""
        elif self.state == 3:
            output = "Har läst in data:\n"
            output += str(self.testdata)
        elif self.state == 4:
            output = "Har utfört test med resultat:\n"
            output += self.printresult()
        return output;


import matplotlib.pyplot as plt
import cv2 as cv
import numpy as np
from genetic_algorithm import GeneticAlgorithm
import utils
from individual import Individual
from gen_record import GenRecord

IMG_SIZE = 256

# read target image
img = cv.imread("face.png", cv.IMREAD_GRAYSCALE)
img = cv.resize(img, (IMG_SIZE, IMG_SIZE))

ga = GeneticAlgorithm(img, num_gens=1000000, init_pop=20, new_per_gen=10, mut_pct=0.001, checkpoints=100)
print(f'Best fitness {ga.max_fitness}')
input('Press any key to begin simulation...')
ga_results = ga.run_simulation()

# process GA results
imgs = []
for r in ga_results:
  img = chromosome2img(r.chromosome, (IMG_SIZE, IMG_SIZE))
  imgs.append(img)
  cv.imwrite(f'./output/img/best_{r.gen_number}.png', img)
# append target image
imgs = [img] + imgs

# show image results
cols = 5
rows = len(imgs) // cols
fig, axs = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 10))
for r in range(rows):
    for c in range(cols):
        axs[r][c].imshow(imgs[r + c], cmap='gray')
        axs[r][c].axis('off')
plt.tight_layout()
plt.show()

# show how fitness was improving
xs = [x.gen_number for x in ga_results]
ys = [x.fitness for x in ga_results]
fig, ax = plt.subplots()
ax.plot(xs, ys)
ax.set(xlabel='Número de Generación', ylabel='Fitness',
       title='Evolución de Fitness')
ax.grid()
fig.savefig("fitness.png")
plt.show()


"""Define two dimensional geometric entities."""

__author__ = "Daniel Ching, Doga Gursoy"
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
__docformat__ = 'restructuredtext en'
__all__ = [
    'Curve',
    'Circle',
    'Polygon',
    'RegularPolygon',
    'Triangle',
    'Rectangle',
    'Square',
    'Mesh',
]

from copy import deepcopy
import logging
import warnings

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
from cached_property import cached_property

from xdesign.geometry.entity import *
from xdesign.geometry.line import *
from xdesign.geometry.point import *

logger = logging.getLogger(__name__)

class Curve(Entity):
    """The base class for closed manifolds defined by a single equation. e.g.
    :class:`.Circle`, :class:`.Sphere`, or :class:`.Torus`.

    Attributes
    ----------
    center : Point
    """

    def __init__(self, center):
        if not isinstance(center, Point):
            raise TypeError("center must be a Point.")
        super(Curve, self).__init__()
        self.center = center

    def __repr__(self):
        return "{}(center={})".format(type(self).__name__, repr(self.center))

    def translate(self, vector):
        """Translates the Curve along a vector."""
        if not isinstance(vector, (Point, list, np.array)):
            raise TypeError("vector must be point, list, or array.")
        self.center.translate(vector)

    def rotate(self, theta, point=None, axis=None):
        """Rotates the Curve by theta radians around an axis which passes
        through a point radians."""
        self.center.rotate(theta, point, axis)

class Superellipse(Curve):
    """A Superellipse in 2D cartesian space.

    Attributes
    ----------
    center : Point
    a : scalar
    b : scalar
    n : scalar
    """

    def __init__(self, center, a, b, n):
        super(Superellipse, self).__init__(center)
        self.a = float(a)
        self.b = float(b)
        self.n = float(n)

    def __repr__(self):
        return "Superellipse(center={}, a={}, b={}, n={})".format(
            repr(self.center), repr(self.a), repr(self.b), repr(self.n)
        )

    @property
    def list(self):
        """Return list representation."""
        return [self.center.x, self.center.y, self.a, self.b, self.n]

    def scale(self, val):
        """Scale."""
        self.a *= val
        self.b *= val

class Ellipse(Superellipse):
    """Ellipse in 2-D cartesian space.

    Attributes
    ----------
    center : Point
    a : scalar
    b : scalar
    """

    def __init__(self, center, a, b):
        super(Ellipse, self).__init__(center, a, b, 2)

    def __repr__(self):
        return "Ellipse(center={}, a={}, b={})".format(
            repr(self.center), repr(self.a), repr(self.b)
        )

    @property
    def list(self):
        """Return list representation."""
        return [self.center.x, self.center.y, self.a, self.b]

    @property
    def area(self):
        """Return area."""
        return np.pi * self.a * self.b

    def scale(self, val):
        """Scale."""
        self.a *= val
        self.b *= val

class Circle(Curve):
    """Circle in 2D cartesian space.

    Attributes
    ----------
    center : Point
        The center point of the circle.
    radius : scalar
        The radius of the circle.
    sign : int (-1 or 1)
        The sign of the area
    """

    def __init__(self, center, radius, sign=1):
        super(Circle, self).__init__(center)
        self.radius = float(radius)
        self.sign = sign
        self._dim = 2

    def __repr__(self):
        return "Circle(center={}, radius={}, sign={})".format(
            repr(self.center), repr(self.radius), repr(self.sign)
        )

    def __str__(self):
        """Return the analytical equation."""
        return "(x-%s)^2 + (y-%s)^2 = %s^2" % (
            self.center.x, self.center.y, self.radius
        )

    def __eq__(self, circle):
        return ((self.x, self.y,
                 self.radius) == (circle.x, circle.y, circle.radius))

    def __neg__(self):
        copE = deepcopy(self)
        copE.sign = -copE.sign
        return copE

    @property
    def list(self):
        """Return list representation for saving to files."""
        return [self.center.x, self.center.y, self.radius]

    @property
    def circumference(self):
        """Returns the circumference."""
        return 2 * np.pi * self.radius

    @property
    def diameter(self):
        """Returns the diameter."""
        return 2 * self.radius

    @property
    def area(self):
        """Return the area."""
        return self.sign * np.pi * self.radius**2

    @property
    def patch(self):
        """Returns a matplotlib patch."""
        return plt.Circle((self.center.y, self.center.x), self.radius)

    @property
    def bounding_box(self):
        """Return the axis-aligned bounding box as two numpy vectors."""
        xmin = np.array(self.center._x - self.radius)
        xmax = np.array(self.center._x + self.radius)

        return xmin, xmax

    # def scale(self, val):
    #     """Scale."""
    #     raise NotImplementedError
    #     self.center.scale(val)
    #     self.rad *= val

    def contains(self, other):
        """Return whether `other` is a proper subset.

        Return one boolean for all geometric entities. Return an array of
        boolean for array input.
        """
        if isinstance(other, Point):
            x = other._x
        elif isinstance(other, np.ndarray):
            x = other
        elif isinstance(other, Mesh):
            for face in other.faces:
                if not self.contains(face) and face.sign == 1:
                    return False
            return True
        else:
            if self.sign == 1:
                if other.sign == -1:
                    # Closed shape cannot contain infinite one
                    return False
                else:
                    assert other.sign == 1
                    # other is within A
                    if isinstance(other, Circle):
                        return (
                            other.center.distance(self.center) + other.radius <
                            self.radius
                        )
                    elif isinstance(other, Polygon):
                        x = _points_to_array(other.vertices)
                        return np.all(self.contains(x))

            elif self.sign == -1:
                if other.sign == 1:
                    # other is outside A and not around
                    if isinstance(other, Circle):
                        return (
                            other.center.distance(self.center) - other.radius >
                            self.radius
                        )
                    elif isinstance(other, Polygon):
                        x = _points_to_array(other.vertices)
                        return (
                            np.all(self.contains(x))
                            and not other.contains(-self)
                        )

                else:
                    assert other.sign is -1
                    # other is around A
                    if isinstance(other, Circle):
                        return (
                            other.center.distance(self.center) + self.radius <
                            other.radius
                        )
                    elif isinstance(other, Polygon):
                        return (-other).contains(-self)

        x = np.atleast_2d(x)

        if self.sign == 1:
            return np.sum((x - self.center._x)**2, axis=1) < self.radius**2
        else:
            return np.sum((x - self.center._x)**2, axis=1) > self.radius**2

def _points_to_array(points):
    a = np.zeros((len(points), points[0].dim))

    for i in range(len(points)):
        a[i] = points[i]._x

    return np.atleast_2d(a)

class Polygon(Entity):
    """A convex polygon in 2D cartesian space.

    It is defined by a number of distinct vertices of class :class:`.Point`.
    Superclasses include :class:`.Square`, :class:`.Triangle`, etc.

    Attributes
    ----------
    vertices : List of Points
    sign : int (-1 or 1)
        The sign of the area

    Raises
    ------
    ValueError : If the number of vertices is less than three.
    """

    def __init__(self, vertices, sign=1):
        for v in vertices:
            if not isinstance(v, Point):
                raise TypeError("vertices must be of type Point.")
        if len(vertices) < 3:
            raise ValueError("A Polygon has at least three vertices.")
        super(Polygon, self).__init__()
        self.vertices = vertices
        self._dim = vertices[0].dim
        self.sign = sign

    def __repr__(self):
        return "Polygon(vertices={}, sign={})".format(
            repr(self.vertices), repr(self.sign)
        )

    def __str__(self):
        return "{}({})".format(type(self).__name__, str(self.numpy))

    def __neg__(self):
        copE = deepcopy(self)
        copE.sign = -copE.sign
        return copE

    @property
    def numverts(self):
        return len(self.vertices)

    @property
    def list(self):
        """Return list representation."""
        lst = []
        for m in range(self.numverts):
            lst.append(self.vertices[m].list)
        return lst

    @property
    def numpy(self):
        """Return Numpy representation."""
        return _points_to_array(self.vertices)

    @property
    def patch(self):
        """Returns a matplotlib patch."""
        points = self.vertices
        a = np.zeros((len(points), points[0].dim))
        for i in range(len(points)):
            a[i] = np.flip(points[i]._x, 0)
        return plt.Polygon(a)

    # Cached Properties
    @property
    def bounds(self):
        """Returns a 4-tuple (xmin, ymin, xmax, ymax) representing the
        bounding rectangle for the Polygon.
        """
        warnings.warn(
            "Polygon.bounds is deprecated; use Polygon.bounding_box instead.",
            DeprecationWarning)
        xs = [p.x for p in self.vertices]
        ys = [p.y for p in self.vertices]
        return (min(xs), min(ys), max(xs), max(ys))

    @property
    def bounding_box(self):
        """Return the axis-aligned bounding box as two numpy vectors."""
        xs = [p.x for p in self.vertices]
        ys = [p.y for p in self.vertices]
        return np.array([min(xs), min(ys)]), np.array([max(xs), max(ys)])

    @property
    def edges(self):
        """Return a list of lines connecting the points of the Polygon."""
        edges = []

        for i in range(self.numverts):
            edges.append(
                Segment(
                    self.vertices[i], self.vertices[(i + 1) % self.numverts]
                )
            )

        return edges

    @cached_property
    def area(self):
        """Return the area of the Polygon.

        References
        ----------
        https://en.wikipedia.org/wiki/Shoelace_formula
        https://stackoverflow.com/a/30408825
        """
        a = _points_to_array(self.vertices)
        x = a[:, 0]
        y = a[:, 1]
        return 0.5 * np.abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))

    @cached_property
    def perimeter(self):
        """Return the perimeter of the Polygon."""
        perimeter = 0
        verts = self.vertices
        points = verts + [verts[0]]
        for m in range(self.numverts):
            perimeter += points[m].distance(points[m + 1])
        return perimeter

    @cached_property
    def center(self):
        """The center of the bounding circle."""
        center = Point(np.zeros(self._dim))
        for v in self.vertices:
            center += v
        return center / self.numverts

    @cached_property
    def radius(self):
        """The radius of the bounding circle."""
        r = 0
        c = self.center
        for m in range(self.numverts):
            r = max(r, self.vertices[m].distance(c))
        return r

    @cached_property
    def half_space(self):
        """Returns the half space polytope respresentation of the polygon."""
        assert (self.dim > 0), self.dim
        A = np.ndarray((self.numverts, self.dim))
        B = np.ndarray(self.numverts)

        for i in range(0, self.numverts):
            edge = Line(
                self.vertices[i], self.vertices[(i + 1) % self.numverts]
            )
            A[i, :], B[i] = edge.standard

            # test for positive or negative side of line
            if self.center._x.dot(A[i, :]) > B[i]:
                A[i, :] = -A[i, :]
                B[i] = -B[i]

        return A, B

    # Methods
    def translate(self, vector):
        """Translates the polygon by a vector."""
        for v in self.vertices:
            v.translate(vector)

        if 'center' in self.__dict__:
            self.center.translate(vector)

        # if 'bounds' in self.__dict__:
        #     self.bounds.translate(vector)

        if 'half_space' in self.__dict__:
            self.half_space = self.half_space.translation(vector)

    def rotate(self, theta, point=None, axis=None):
        """Rotates the Polygon around an axis which passes through a point by
        theta radians."""
        for v in self.vertices:
            v.rotate(theta, point, axis)

        if 'center' in self.__dict__:
            self.center.rotate(theta, point, axis)

        # if 'bounds' in self.__dict__:
        #     self.bounds.rotate(theta, point, axis)

        if 'half_space' in self.__dict__:
            if point is None:
                d = 0
            else:
                d = point._x
            self.half_space = self.half_space.translation(-d)
            self.half_space = self.half_space.rotation(0, 1, theta)
            self.half_space = self.half_space.translation(d)

    def contains(self, other):
        """Return whether this Polygon contains the other."""

        if isinstance(other, Point):
            x = other._x
        elif isinstance(other, np.ndarray):
            x = other
        elif isinstance(other, Mesh):
            for face in other.faces:
                if not self.contains(face) and face.sign == 1:
                    return False
            return True
        else:
            if self.sign == 1:
                if other.sign == -1:
                    # Closed shape cannot contain infinite one
                    return False
                else:
                    assert other.sign == 1
                    # other is within A
                    if isinstance(other, Circle):
                        if self.contains(other.center):
                            for edge in self.edges:
                                if other.center.distance(edge) < other.radius:
                                    return False
                            return True
                        return False
                    elif isinstance(other, Polygon):
                        x = _points_to_array(other.vertices)
                        return np.all(self.contains(x))

            elif self.sign == -1:
                if other.sign == 1:
                    # other is outside A and not around
                    if isinstance(other, Circle):
                        if self.contains(other.center):
                            for edge in self.edges:
                                if other.center.distance(edge) < other.radius:
                                    return False
                            return True and not other.contains(-self)
                        return False
                    elif isinstance(other, Polygon):
                        x = _points_to_array(other.vertices)
                        return (
                            np.all(self.contains(x))
                            and not other.contains(-self)
                        )

                else:
                    assert other.sign is -1
                    # other is around A
                    if isinstance(other, Circle) or isinstance(other, Polygon):
                        return (-other).contains(-self)

        border = Path(self.numpy)

        if self.sign == 1:
            return border.contains_points(np.atleast_2d(x))
        else:
            return np.logical_not(border.contains_points(np.atleast_2d(x)))

class RegularPolygon(Polygon):
    """A regular polygon in 2D cartesian space.

    It is defined by the polynomial center, order, and radius.

    By default (i.e. when the ``angle`` parameter is zero), the regular
    polygon is oriented so that one of the vertices is at coordinates
    :math:`(x + r, x)` where :math:`x` is the x-coordinate of
    ``center`` and :math:`r` = ``radius``. The ``angle`` parameter is
    only meaningful modulo :math:`2\pi /` ``order`` since rotation by
    :math:`2\pi /` ``order`` gives a result equivalent to no rotation.

    Parameters
    ----------
    center : :class:`Point`
        The center of the polygon
    radius : float
        Distance from polygon center to vertices
    order : int
        Order of the polygon (e.g. order 6 is a hexagon).
    angle : float
        Optional rotation angle in radians.
    sign : int (-1 or 1)
        Optional sign of the area (see :class:`Polygon`)
    """

    def __init__(self, center, radius, order, angle=0, sign=1):
        vertex_angles = (np.linspace(0, 2 * np.pi, order, endpoint=False) +
                         angle)
        vertices = [
            Point([radius * np.cos(theta), radius * np.sin(theta)]) + center
            for theta in vertex_angles
        ]
        super(RegularPolygon, self).__init__(vertices, sign=sign)

class Triangle(Polygon):
    """Triangle in 2D cartesian space.

    It is defined by three distinct points.
    """

    def __init__(self, p1, p2, p3):
        super(Triangle, self).__init__([p1, p2, p3])

    def __repr__(self):
        return "Triangle({}, {}, {})".format(
            self.vertices[0], self.vertices[1], self.vertices[2]
        )

    @cached_property
    def center(self):
        center = Point([0, 0])
        for v in self.vertices:
            center += v
        return center / 3

    @cached_property
    def area(self):
        A = self.vertices[0] - self.vertices[1]
        B = self.vertices[0] - self.vertices[2]
        return self.sign * 1 / 2 * np.abs(np.cross([A.x, A.y], [B.x, B.y]))

class Rectangle(Polygon):
    """Rectangle in 2D cartesian space.

    Defined by a point and a vector to enforce perpendicular sides.

    Parameters
    ----------
    side_lengths : array
        The lengths of the sides
    """

    def __init__(self, center, side_lengths):

        s = np.array(side_lengths) / 2
        self.side_lengths = np.array(side_lengths)

        p1 = Point([center.x + s[0], center.y + s[1]])
        p2 = Point([center.x - s[0], center.y + s[1]])
        p3 = Point([center.x - s[0], center.y - s[1]])
        p4 = Point([center.x + s[0], center.y - s[1]])

        super(Rectangle, self).__init__([p1, p2, p3, p4])

    def __repr__(self):
        return "Rectangle({}, {})".format(
            repr(self.center), repr(self.side_lengths.tolist())
        )

    @cached_property
    def area(self):
        return self.sign * (
            self.vertices[0].distance(self.vertices[1]) *
            self.vertices[1].distance(self.vertices[2])
        )

class Square(Rectangle):
    """Square in 2D cartesian space.

    Defined by a point and a length to enforce perpendicular sides.
    """

    def __init__(self, center, side_length=None, radius=None):

        if radius is not None:
            # side_length = np.sqrt(2) * radius
            side_length = 2 * radius

        side_lengths = [side_length] * 2

        super(Square, self).__init__(center, side_lengths)

class Mesh(Entity):
    """A collection of Entities

    Attributes
    ----------
    faces : :py:obj:`list`
        A list of the Entities
    area : float
        The total area of the Entities
    population : int
        The number entities in the Mesh
    radius : float
        The radius of a bounding circle

    """

    def __init__(self, obj=None, faces=[]):
        self.faces = []
        self.area = 0
        self.population = 0
        self.radius = 0
        self._dim = 2

        if obj is not None:
            assert not faces
            self.import_triangle(obj)
        else:
            assert obj is None
            for face in faces:
                self.append(face)

    def __str__(self):
        return "Mesh(" + str(self.center) + ")"

    def __repr__(self):
        return "Mesh(faces={})".format(repr(self.faces))

    def import_triangle(self, obj):
        """Loads mesh data from a Python Triangle dict.
        """
        for face in obj['triangles']:
            p0 = Point(obj['vertices'][face[0], 0], obj['vertices'][face[0], 1])
            p1 = Point(obj['vertices'][face[1], 0], obj['vertices'][face[1], 1])
            p2 = Point(obj['vertices'][face[2], 0], obj['vertices'][face[2], 1])
            t = Triangle(p0, p1, p2)
            self.append(t)

    @property
    def center(self):
        center = Point([0, 0])
        if self.area > 0:
            for f in self.faces:
                center += f.center * f.area
            center /= self.area
        return center

    @property
    def bounding_box(self):
        """Return the axis-aligned bounding box as two numpy vectors."""
        xmin = np.full(self.dim, np.nan)
        xmax = np.full(self.dim, np.nan)

        for f in self.faces:
            fmin, fmax = f.bounding_box
            with np.errstate(invalid='ignore'):
                xmin = np.fmin(xmin, fmin)
                xmax = np.fmax(xmax, fmax)

        return xmin, xmax

    def append(self, t):
        """Add a triangle to the mesh."""
        self.population += 1
        # self.center = ((self.center * self.area + t.center * t.area) /
        #                (self.area + t.area))
        self.area += t.area

        if isinstance(t, Polygon):
            for v in t.vertices:
                self.radius = max(self.radius, self.center.distance(v))
        else:
            self.radius = max(
                self.radius,
                self.center.distance(t.center) + t.radius
            )

        self.faces.append(t)

    def pop(self, i=-1):
        """Pop i-th triangle from the mesh."""
        self.population -= 1
        self.area -= self.faces[i].area
        try:
            del self.__dict__['center']
        except KeyError:
            pass
        return self.faces.pop(i)

    def translate(self, vector):
        """Translate entity."""
        for t in self.faces:
            t.translate(vector)

    def rotate(self, theta, point=None, axis=None):
        """Rotate entity around an axis which passes through a point by theta
        radians."""
        for t in self.faces:
            t.rotate(theta, point, axis)

    def scale(self, vector):
        """Scale entity."""
        for t in self.faces:
            t.scale(vector)

    def contains(self, other):
        """Return whether this Mesh contains other.

        FOR ALL `x`,
        THERE EXISTS a face of the Mesh that contains `x`
        AND (ALL cut outs that contain `x` or THERE DOES NOT EXIST a cut out).
        """
        if isinstance(other, Point):
            x = other._x
        elif isinstance(other, np.ndarray):
            x = other
        elif isinstance(other, Polygon):
            x = _points_to_array(other.vertices)
            return np.all(self.contains(x))
        elif isinstance(other, Circle):
            warnings.warn("Didn't check that Mesh contains Circle.")
            return True
        else:
            raise NotImplementedError("Mesh.contains({})".format(type(other)))

        x = np.atleast_2d(x)

        # keep track of whether each point is contained in a face
        x_in_face = np.zeros(x.shape[0], dtype=bool)
        x_in_cut = np.zeros(x.shape[0], dtype=bool)
        has_cuts = False

        for f in self.faces:
            if f.sign < 0:
                has_cuts = True
                x_in_cut = np.logical_or(x_in_cut, f.contains(x))
            else:
                x_in_face = np.logical_or(x_in_face, f.contains(x))

        if has_cuts:
            return np.logical_and(x_in_face, x_in_cut)
        else:
            return x_in_face

    @property
    def patch(self):
        patches = []
        for f in self.faces:
            patches.append(f.patch)
        return patches


#!/home/mlfrantz/miniconda2/bin/python3.6

"""
I messed up when running constraint testing and accidenttilly added a string to the score.
This script just fixes that mistake.
"""
import sys
import pandas as pd
import pdb

dataPath = '/home/mlfrantz/Documents/MIP_Research/mip_research/data/'

assert type(sys.argv[1]) is str, "File name must be a string"

df = pd.read_csv(dataPath + sys.argv[1])

for index, row in df.iterrows():
    # pdb.set_trace()
    try:
        if row["Constraints"][0] == '_':
            df["Constraints"][index] = row["Constraints"][1:]
            # continue
            # print(index, row['Score'][7:])
            # print(index, df['Score'][index][7:])
    except TypeError:
        df.at['Constraints',index] = 'none'
    # if row['Score'] == '_no_solution':
    #     df['Score'][index] = 0

print(df['Constraints'].tail())

df.to_csv(dataPath + sys.argv[1], index=False)


from crypto import paillier
from crypto import znp
import Crypto.Util.number as pycrypto
import sys

class Voter:
    def __init__(self, voter_id, registrar, tallier, election):
        self.voter_id = voter_id
        self.registrar = registrar
        self.tallier = tallier
        self.election = election
        self.evote = None
        self.r = None
        self.proof = None

    def vote(self, evote, proof):
        self.evote = int(evote)
        self.proof = [list(map(int, proof[0])), list(map(int, proof[1])), list(map(int, proof[2])), list(map(int, proof[3])), int(proof[4])]
        if self.registrar.add_voter(self.election.election_id, self.voter_id, self.evote):
            if self.tallier.send_vote(self.voter_id, self.election.election_id, self.evote, self.proof):
                return True
        return False


from Member_List import Member_List
from operator import itemgetter
from collections import Counter

def GetAllResult(logfile):
    result_all = dict()
    with open(logfile) as f:
        for line in f:
            tmp = line.strip().split(', ')
            if tmp[2] in list(Member_List.keys()):
                key = Member_List[tmp[2]]
                val = tmp[1]
                result_all[key] = val

    result_all = sorted(result_all.items(), key=itemgetter(0))

    for idx,i in enumerate(result_all):
        if '取消今日點餐' in i:
            result_all.pop(idx)

    return result_all

def GetSummary(result_all):
    result_all = {i[0]:i[1] for i in result_all}

    Summary = list(result_all.values())
    Summary = Counter(Summary)
    Summary = sorted(Summary.items(), key=itemgetter(0))

    return Summary

##AllResult = GetAllResult()
##Summary = GetSummary(AllResult)
##
##print(AllResult)
##print(Summary)
##print(type(AllResult))
##print(type(AllResult[0]))
##print(type(Summary))
##print(type(Summary[0]))


import torch

from ..box_heads.box_utils import (
    pairwise_iou,
    xywha_to_xyxy,
    xyxy_to_xywha,
)

def encode(boxes, priors, variances):
    """Encode the variances from the priorbox layers into the ground truth boxes
    we have boxes (based on jaccard overlap) with the prior boxes.
    Args:
        boxes (tensor): [num_priors, 4] coords of ground truth for each prior in XYXY_REL BoxMode
        priors (tensor): [num_priors, 4] prior boxes in XYWHA_REL BoxMode
        variances (list[float]): variances of prior boxes
    Return:
        encoded boxes (tensor) [num_priors, 4]
    """
    boxes = xyxy_to_xywha(boxes)
    locations = boxes_to_locations(boxes, priors, variances)
    return locations

# Adapted from https://github.com/Hakuyume/chainer-ssd
def decode(locations, priors, variances):
    """Decode locations from predictions using priors to undo
    the encoding we did for offset regression at train time.
    Args:
        locations (tensor): [num_priors, 4] location predictions for locations layers
        priors (tensor): [num_priors, 4] prior boxes in XYWHA_REL BoxMode
        variances (list[float]): variances of prior boxes
    Return:
        decoded bounding box predictions
    """

    boxes = locations_to_boxes(locations, priors, variances)
    boxes = xywha_to_xyxy(boxes)
    return boxes

def boxes_to_locations(boxes, priors, variances):
    r"""Convert boxes into regressional location results of SSD
    Args:
        boxes (Tensor): [num_targets, 4] in XYWHA_REL BoxMode
        priors (Tensor): [num_targets] in XYWHA_REL BoxMode
        variances (list(float)): used to change the scale of center.
            change of scale of size.
    """
    # priors can have one dimension less
    if priors.dim() + 1 == boxes.dim():
        priors = priors.unsqueeze(0)
    return torch.cat([
        (boxes[..., :2] - priors[..., :2]) / priors[..., 2:] / variances[0],
        torch.log(boxes[..., 2:] / priors[..., 2:]) / variances[1],
    ], dim=boxes.dim() - 1)

def locations_to_boxes(locations, priors, variances):
    r"""Convert regressional location results of SSD into boxes in XYWHA_REL BoxMode
    The conversion:
        $$predicted\_center \times variance_center =
            \frac{real\_center - prior\_center}{prior\_hw}$$
        $$\exp(predicted\_hw \times variance_size) = \frac{real\_hw}{prior\_hw}$$
    We do it in the inverse direction here.
    Args:
        locations (Tensor): [batch_size, num_priors, 4] the regression output of SSD.
            It will contain the outputs as well.
        priors (Tensor): [num_priors, 4] or [batch_size, num_priors, 4] prior boxes.
        variances (list(float)): used to change the scale of center and
            change of scale of size.
    Returns:
        boxes: priors (Tensor): converted XYWHA_REL BoxMode. All the values
            are relative to the image size.
    """
    # priors can have one dimension less.
    if priors.dim() + 1 == locations.dim():
        priors = priors.unsqueeze(0)
    return torch.cat([
        locations[..., :2] * variances[0] * priors[..., 2:] + priors[..., :2],
        torch.exp(locations[..., 2:] * variances[1]) * priors[..., 2:],
    ], dim=locations.dim() - 1)

def assign_priors(gt_boxes, gt_labels, priors, iou_threshold):
    """Assign ground truth boxes and targets to priors.
    Args:
        gt_boxes (Tensor): [num_targets, 4]: ground truth boxes
        gt_labels (Tensor): [num_targets,]: labels of targets
        priors (Tensor): [num_priors, 4]: XYXY_REL BoxMode
        iou_threshold (float): iou threshold
    Returns:
        boxes (Tensor): [num_priors, 4] real values for priors.
        labels (Tensor): [num_priros] labels for priors.
    """
    ious = pairwise_iou(gt_boxes.unsqueeze(0), priors.unsqueeze(1))  # num_priors x num_targets
    best_target_per_prior, best_target_per_prior_index = ious.max(1)  # num_priors
    best_prior_per_target, best_prior_per_target_index = ious.max(0)  # num_targets

    for target_index, prior_index in enumerate(best_prior_per_target_index):
        best_target_per_prior_index[prior_index] = target_index
    # 2.0 is used to make sure every target has a prior assigned
    best_target_per_prior.index_fill_(0, best_prior_per_target_index, 2)

    labels = gt_labels[best_target_per_prior_index]  # num_priors
    labels[best_target_per_prior < iou_threshold] = 0  # the backgound id
    boxes = gt_boxes[best_target_per_prior_index]
    return boxes, labels


import pandas as pd
from pandas.io.html import read_html
read.html('http://www.atpworldtour.com/Rankings/Singles.aspx')
df= _[0]
df
read_html
read_html('http://www.atpworldtour.com/Rankings/Singles.aspx', infer_type=FALSE, col_header=0)

from datetime import datetime, timedelta

start_date = datetime("23.08.1973")

def generate_url(date, start_range=1):
	return "http://www.atpworldtour.com/Rankings/Singles.aspx?d=%s&r=%d&c="(_format_date(date))

def format_date(date):
	return date.strftime('%d.%m.%Y')

def weekly_dates():
	date = start_date
	today = datetime.today()
	while date < today:
		yield date
		date += timedelta(weeks=1)

def run():
	output = open("tennisrankings.csv", "a")
	for date in weekly_dates():
		print("date")
		url = generate.url(date)
		df = read_html(url, infer_types=False, header=0)[0]
		df = clean_table(df)

def clean_table(df):
	"""
	Produces Name, Rank, Nationality
	"""
	df['Rank'] = df['Rank, Name & Nationality'].apply(lambda r: r.split()[0])
	df['Name'] = df['Rank, Name & Nationality'].apply(lambda r: r.split()[1:-1])
	df['Nationality'] = df['Rank, Name & Nationality'].apply(lambda r: r.split()[-1].strip("()"))
	del df["Rank, Name & Nationality"]
	return df


class Solution(object):
    def containsDuplicate(self,nums):
        numDict = {}
        for num in nums:
            #complexity is O(1)
            if num in numDict:
                return True
            numDict[num]=1
        return False
        """
        #time limit exceeded
        for num in nums:
            if nums.count(num)>1:
                return True
        return False
        """

#tuple:()
#list:[]
#set, dict: {}
nums=[1,2,3]
s = Solution()
print (s.containsDuplicate(nums))


import unicodedata

GUESS_ENCODINGS_SEQUENCE = (
    'UTF-8',
    'CP1250',
    'ISO-8859-2',
)

def guess_decode(s, fallback_method='replace'):
    for enc in GUESS_ENCODINGS_SEQUENCE:
        try:
            return s.decode(enc)
        except UnicodeDecodeError:
            pass
    return s.decode('UTF-8', fallback_method)

def strip_accents(unistr):
    """
    Return the accent-stripped str for the given unistr (unicode is required).
    """
    return unicodedata.normalize('NFKD', unistr).encode('ascii', 'ignore').decode('ascii')

def encoded_stream(stream, into='UTF-8'):
    import codecs

    if (stream.encoding or '').upper() != into.upper():
        stream = codecs.getwriter(into)(stream)

    return stream

def auto_encode_stdout_stderr(into='UTF-8'):
    """
    Call this on the top of your program to avoid the need of encoding each printed
    unicode object when the output encoding is not known such as during shell redirection.
    """
    import sys

    sys.stdout = encoded_stream(sys.stdout, into)
    sys.stderr = encoded_stream(sys.stderr, into)


import os
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import utils
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
from sklearn.utils import shuffle

def build_train_data(data):
    # 处理数据
    train_data=data.groupby(by=['buyer_admin_id','item_id']).size()
    train_data.name='item_counts'
    train_data=train_data.reset_index()

    temp=data.groupby(by=['buyer_admin_id']).size()
    temp.name='counts'
    temp=temp.reset_index()

    train_data=train_data.join(temp.set_index('buyer_admin_id'),on='buyer_admin_id')
    train_data['item_ratio']=train_data['item_counts']/train_data['counts']

    # 对id编码
    le_buyer = preprocessing.LabelEncoder()
    le_buyer.fit(data.buyer_admin_id.unique())
    le_item = preprocessing.LabelEncoder()
    le_item.fit(data.item_id.unique())
    train_data['buyerid_le']=le_buyer.transform(train_data.buyer_admin_id.values)
    train_data['itemid_le']=le_item.transform(train_data.item_id.values)
    return train_data, le_buyer, le_item

def batch_generator(data,batch_size,is_shuffle=True):
    '''批数据生成器'''
    if is_shuffle:
        data = shuffle(data)
    batch_count=0
    check=1
    while check:
        start = batch_count * batch_size
        end = start + batch_size
        if end > len(data):
            yield data.iloc[start:]
            check=0
        else:
            yield data.iloc[start:end]
            batch_count += 1

def mse(y, y_pred):
    """Returns the mean squared error between
    ground truths and predictions.
    """
    return np.mean((y - y_pred) ** 2)

def rmse(y, y_pred):
    """Returns the root mean squared error between
    ground truths and predictions.
    """
    return np.sqrt(mse(y, y_pred))

def mae(y, y_pred):
    """Returns mean absolute error between
    ground truths and predictions.
    """
    return np.mean(np.fabs(y - y_pred))

# SVD模型
class SVD():
    """Collaborative filtering model based on SVD algorithm.
    """

    def __init__(self, num_users, num_items, num_factors, sess):
        self.num_users = num_users
        self.num_items = num_items
        self.num_factors = num_factors
        self._sess = sess

        self.reg_b_u = 0.0001
        self.reg_b_i = 0.0001
        self.reg_p_u = 0.005
        self.reg_q_i = 0.005
        self.reg_y_u = 0.005
        self.reg_g_i = 0.005
        self._built=False

    def _create_placeholders(self):
        """Returns the placeholders.
        """
        with tf.variable_scope('placeholder'):
            users = tf.placeholder(tf.int32, shape=[None, ], name='users')
            items = tf.placeholder(tf.int32, shape=[None, ], name='items')
            ratings = tf.placeholder(tf.float32, shape=[None, ], name='ratings')
        return users, items, ratings

    def _create_constants(self, mu):
        """Returns the constants.
        """
        with tf.variable_scope('constant'):
            _mu = tf.constant(mu, shape=[], dtype=tf.float32)
        return _mu

    def _create_user_terms(self, users):
        """Returns the tensors related to users.
        """
        num_users = self.num_users
        num_factors = self.num_factors

        with tf.variable_scope('user', reuse=tf.AUTO_REUSE):
            self.user_embeddings = tf.get_variable(
                name='embedding',
                shape=[num_users, num_factors],
                initializer=tf.contrib.layers.xavier_initializer(),
                regularizer=tf.contrib.layers.l2_regularizer(self.reg_p_u))

            self.user_bias = tf.get_variable(
                name='bias',
                shape=[num_users, ],
                initializer=tf.contrib.layers.xavier_initializer(),
                regularizer=tf.contrib.layers.l2_regularizer(self.reg_b_u))

            p_u = tf.nn.embedding_lookup(self.user_embeddings, users, name='p_u')
            b_u = tf.nn.embedding_lookup(self.user_bias, users, name='b_u')
        return p_u, b_u

    def _create_item_terms(self, items):
        """Returns the tensors related to items.
        """
        num_items = self.num_items
        num_factors = self.num_factors

        with tf.variable_scope('item', reuse=tf.AUTO_REUSE):
            self.item_embeddings = tf.get_variable(
                name='embedding',
                shape=[num_items, num_factors],
                initializer=tf.contrib.layers.xavier_initializer(),
                regularizer=tf.contrib.layers.l2_regularizer(self.reg_q_i))

            self.item_bias = tf.get_variable(
                name='bias',
                shape=[num_items, ],
                initializer=tf.contrib.layers.xavier_initializer(),
                regularizer=tf.contrib.layers.l2_regularizer(self.reg_b_i))

            q_i = tf.nn.embedding_lookup(self.item_embeddings, items, name='q_i')
            b_i = tf.nn.embedding_lookup(self.item_bias, items, name='b_i')
        return q_i, b_i

    def _get_item_terms(self):
        """Returns the tensors related to items.
        """
        import pickle
        item_embeddings = self.item_embeddings.eval()
        with open('./model/item_embeddings.pkl', 'wb') as fw:
            pickle.dump({'embeddings': item_embeddings}, fw)

    def _create_prediction(self, mu, b_u, b_i, p_u, q_i):
        """Returns the tensor of prediction.

           Note that the prediction
            r_hat = \mu + b_u + b_i + p_u * q_i
        """
        with tf.variable_scope('prediction'):
            pred = tf.reduce_sum(tf.multiply(p_u, q_i),axis=1)
            pred = tf.add_n([b_u, b_i, pred])
            pred = tf.add(pred, mu, name='pred')

        return pred

    def _create_loss(self, pred, ratings):
        """Returns the L2 loss of the difference between
            ground truths and predictions.

           The formula is here:
            L2 = sum((r - r_hat) ** 2) / 2
        """
        with tf.variable_scope('loss'):
            loss = tf.nn.l2_loss(tf.subtract(ratings, pred), name='loss')

        return loss

    def _create_optimizer(self, loss):
        """Returns the optimizer.

           The objective function is defined as the sum of
            loss and regularizers' losses.
        """
        with tf.variable_scope('optimizer', reuse=tf.AUTO_REUSE):
            objective = tf.add(
                loss,
                tf.add_n(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)),
                name='objective'
            )

            try:
                optimizer = tf.contrib.keras.optimizers.Nadam().minimize(objective, name='optimizer')
            except:
                optimizer = tf.train.AdamOptimizer().minimize(objective, name='optimizer')

        return optimizer

    def _build_graph(self, mu):
        _mu = self._create_constants(mu)
        self._users, self._items, self._ratings = self._create_placeholders()
        p_u, b_u = self._create_user_terms(self._users)
        q_i, b_i = self._create_item_terms(self._items)
        self._pred = self._create_prediction(_mu, b_u, b_i, p_u, q_i)
        loss = self._create_loss(self._ratings, self._pred)
        self._optimizer = self._create_optimizer(loss)
        self._built = True

    def _run_train(self, data, epochs, batch_size, validation_data):

        steps_per_epoch = np.ceil(len(data) / batch_size).astype(int)

        self._sess.run(tf.global_variables_initializer())
        for e in range(1, epochs + 1):
            print('Epoch {}/{}'.format(e, epochs))
            # 批数据生成器，默认打乱
            data_gen = batch_generator(data, batch_size)
            pbar = utils.Progbar(steps_per_epoch,stateful_metrics=['rmse','mae','val_rmse','val_mae'])
            step = 0
            for batch_data in data_gen:
                step += 1
                users = batch_data['buyerid_le'].values
                items = batch_data['itemid_le'].values
                ratings = batch_data['item_ratio'].values

                self._sess.run(
                    self._optimizer,
                    feed_dict={
                        self._users: users,
                        self._items: items,
                        self._ratings: ratings
                    })

                pred = self.predict(batch_data[['buyerid_le','itemid_le']])

                update_values = [
                    ('rmse', rmse(ratings, pred)),
                    ('mae', mae(ratings, pred))
                ]
                # 进度条更新
                pbar.update(step, values=update_values)

            if validation_data is not None:
                valid_x = validation_data[['buyerid_le','itemid_le']]
                valid_y = validation_data['item_ratio']
                valid_pred = self.predict(valid_x)

                update_values += [
                    ('val_rmse', rmse(valid_y, valid_pred)),
                    ('val_mae', mae(valid_y, valid_pred))
                ]
                # 进度条更新
                pbar.update(step, values=update_values)

    def train(self, data, epochs=10, batch_size=1024, validation_data=None):
        if not self._built:
            self._build_graph(np.mean(data.item_ratio.values))
        self._run_train(data, epochs, batch_size, validation_data)
        # self._get_item_terms()

    def predict(self, x):
        if not self._built:
            return 'The model must be trained before prediction.'

        if x.shape[1] != 2:
            raise ValueError('The shape of x should be (samples, 2)')

        pred = self._sess.run(
            self._pred,
            feed_dict={
                self._users: x['buyerid_le'].values,
                self._items: x['itemid_le'].values
            })

        return pred

    def save_model(self,model_dir):
        self._saver = tf.train.Saver()
        model_name = type(self).__name__
        if not os.path.exists(model_dir):
            os.makedirs(model_dir)
        model_path = os.path.join(model_dir, model_name)
        print(model_dir)
        print(model_name)
        self._saver.save(self._sess, model_path)

    def load_model(self,model_dir):
        ckpt = tf.train.get_checkpoint_state(model_dir)
        self._saver = tf.train.import_meta_graph(ckpt.model_checkpoint_path +'.meta')  # 加载图结构
        gragh = tf.get_default_graph()
        tensor_name_list = [tensor.name for tensor in gragh.as_graph_def().node]
        self._users=gragh.get_tensor_by_name('placeholder/users:0')
        self._items=gragh.get_tensor_by_name('placeholder/items:0')
        self._pred=gragh.get_tensor_by_name('prediction/pred:0')
        self._saver.restore(self._sess, tf.train.latest_checkpoint(model_dir))
        self._built=True

def knn_recommend(pkl_path, le_item):
    import pickle
    from sklearn.neighbors import NearestNeighbors

    with open(pkl_path,'rb') as f:
        item_emb = pickle.load(f)
    item_emb=item_emb['embeddings']
    nbrs = NearestNeighbors(n_neighbors=31, algorithm='ball_tree').fit(item_emb)
    print('KNN fit')

    # 读取测试集
    test=pd.read_csv('./Antai_AE_round1_test_20190626.csv')
    test_irank_min = test.groupby(['buyer_admin_id']).apply(lambda t: t[t.irank == t.irank.min()]).reset_index(
        drop=True)
    test_irank_max = test.groupby(['buyer_admin_id']).apply(lambda t: t[t.irank == t.irank.max()]).reset_index(
        drop=True)
    buyer_item = test_irank_min.append(test_irank_max)
    buyer_item = buyer_item[['buyer_admin_id','item_id']].drop_duplicates().reset_index(drop=True)
    buyer_item['item_le'] = le_item.transform(buyer_item.item_id.values)
    # embedding
    test_item_emb = []
    for idx in range(len(buyer_item)):
        item_le = buyer_item.iloc[idx]['item_le']
        test_item_emb.append(item_emb[item_le])
    print('embedding finish')

    distances, indices = nbrs.kneighbors(test_item_emb)
    with open('./model/kneighbors_distances.pkl', 'wb') as f:
        pickle.dump(distances, f)
    with open('./model/kneighbors_indices.pkl', 'wb') as f:
        pickle.dump(indices, f)
    print('kneighbors finish')

    indices_inversed = le_item.inverse_transform(indices)
    for i in range(indices_inversed.shape[1]):
        buyer_item['recomend_' + str(i)] = indices_inversed[:, i]
    buyer_item.to_csv('./Data/knn_rec.csv', index=False)
    print('finish')

if __name__=='__main__':
    datayy = pd.read_csv('./Data/round1_data.csv')
    datayy = datayy.loc[datayy.buyer_country_id == 'yy']

    train_data, le_buyer, le_item = build_train_data(datayy)
    num_users = train_data.buyer_admin_id.nunique()
    num_items = train_data.item_id.nunique()
    num_factors = 100

    # ---------------------------KNN----推荐-------------------------------------------
    # del(datayy)
    # del(train_data)
    # knn_recommend('./model/item_embeddings_100.pkl', le_item)
    #----------------------------训-------练-------------------------------------------
    # 随机取样 90%训练 10%测试
    train_data = train_data[['buyerid_le', 'itemid_le', 'item_ratio']]
    traindf,validdf=train_test_split(train_data, test_size = 0.1)

    with tf.Session() as sess:
        model=SVD(num_users,num_items,num_factors,sess)
        model.train(traindf,epochs=5,batch_size=1024,validation_data=validdf)
        # model.load_model('./model/')

        y_pred = model.predict(validdf[['buyerid_le', 'itemid_le']])
        print('rmse: {}, mae: {}'.format(rmse(validdf['item_ratio'], y_pred), mae(validdf['item_ratio'], y_pred)))

        # Save model
        # model.save_model('./model/')


from django.shortcuts import render, render_to_response
from .models import Client_detail, Post_detail, New_articles
import requests, bs4
from django.http import HttpResponse, JsonResponse
import os
from urllib.parse import urlparse

def get_ln_articles(request):
	matching_key = 'Guest Service,Guest Experience,Customer Experience,CX,Customer Experience Management,Operational Policy,Operational Execution,Operational Consistency,Learning and Development,Learning Management Systems,LMS,Voice of the Customer,VOC,Voice of the Guest,OSAT,NPS,Customer Recovery,Guest Recovery,Customer Relations,Guest Relations, Employee Relations,customerservice,guestrelations'
	matching_key_list = matching_key.split(',')

	# matched_key = ['Data Quality', 'data entry', 'Forecast difficulties', 'SC Planning', 'collaboration']
	client_info = list(Client_detail.objects.filter(client_id=request.POST.get('client_id')).values())

	headers = {
    "User-Agent":
        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
	}

	dir_path = os.path.dirname(os.path.realpath(__file__))
	for client_data in client_info:
		data = requests.get(client_data['blog_url'], headers=headers)
		html = bs4.BeautifulSoup(data.text, 'html.parser')
		all_articles_div = html.findAll(class_='article-card')
		ln_article_url = []
		login_data = open(dir_path+'/static/shared-files/LinkedIn_Files/'+client_data['ln_username'].strip()+'.html', 'r').read()
		login_html = bs4.BeautifulSoup(login_data, 'html.parser')
		# login_html_data1 = login_html.findAll(class_='feed-shared-update-v2 mh0 Elevation-2dp relative full-height feed-shared-update-v2--e2e feed-shared-update--chat-ui feed-shared-update-v2--minimal-padding ember-view')
		# login_html_data = login_html.findAll('div', attrs={'class':'feed-shared-update-v2 mh0 Elevation-2dp relative full-height feed-shared-update--chat-ui feed-shared-update-v2--minimal-padding ember-view'})
		login_html_data = login_html.findAll('div', attrs={'class':'feed-shared-update-v2__description-wrapper'})
		post_data = login_html.findAll('div', attrs={'class':'feed-shared-text__text-view feed-shared-text-view white-space-pre-wrap break-words ember-view'})
		# for data in post_data:
		# 	post = data.find('span', attrs={'class':'ember-view'})
		# 	post_url = data.find('a', attrs={'class':'ember-view'})['href']
		# 	hash_tag = data.find('span', attrs={'class':'hashtag-a11y__name'}).text
		# 	print(post.text)
		# 	print(post_url)
		# 	print(hash_tag)
		# 	exit()
		login_article_urls = []
		for activity in login_html_data:
			# print(activity)
			# exit()
			# social_count = activity.find('ul',attrs={'class':'social-details-social-counts'})
			# print(social_count)
			# exit()

			# article_data = activity.find('div', attrs={'class':'feed-shared-article__description-container'})
			post_data = activity.find('div', attrs={'class':'feed-shared-update-v2__description-wrapper '})
			try:
				post_text = post_data.find('span').text
			except:
				post_text = ''
			if post_text == '':
				try:
					post_data = activity.find('div', attrs={'class':'feed-shared-update-v2__description feed-shared-inline-show-more-text ember-view'})
					post_text = post_data.find('div', attrs={'class':'feed-shared-text__text-view feed-shared-text-view white-space-pre-wrap break-words ember-view'}).find('span').text
				except:
					post_text = ''
			try:
				post_short_url = post_data.find('a', attrs={'class':'ember-view'})['href']
			except:
				post_short_url = ''
			try:
				hash_tag = post_data.find('span', attrs={'class':'hashtag-a11y__name'}).text
			except:
				hash_tag = ''

			try:
				article_url_login = activity.find('a', attrs={'class':'feed-shared-article__meta'})['href']
			except:
				article_url_login = ''
			# article_login = requests.get(article_url_login, headers=headers)
			# article_data_login = bs4.BeautifulSoup(article_login.text, 'html.parser')
			likes = None
			comments = None
			shares = None
			author_name = ''
			if article_url_login != '':
				if 'linkedin.com' in article_url_login:
					# try:
						# author_name = article_data_login.find('a', attrs={'class':'mini-card__title-link'}).text
					# except:
						# author_name = ''
					# article_login_title = article_data_login.find('title').text
					# article_login_description = article_data_login.find('meta',attrs={'name':'description'})['content']
					# com_like_share_login = article_data_login.findAll('li', attrs = {'class':'social-ctas__list-item'})
					# likes = com_like_share_login[0].find(class_='social-ctas__number').text
					# comments = com_like_share_login[1].find(class_='social-ctas__number').text
					# shares = com_like_share_login[2].find(class_='social-ctas__number').text
					get_source = 'LinkedIn|Pulse'
				else:
					# if 'nytimes.com' in article_url_login:
					# 	author_name = article_data_login.find('span', attrs={'class':'css-1baulvz'}).text
					# elif 'forbes' in article_url_login:
					# 	author_name = article_data_login.find('meta', attrs={'name':'author'})['content'].strip()

					# elif 'cnbc.com' in article_url_login:
					# 	author_name = article_data_login.find('meta', attrs={'name':'author'})['content']

					# try:
					# 	article_login_title = article_data_login.find('meta',attrs={'property':'og:title'})['content']
					# except:
					# 	article_login_title = ''
					# try:
					# 	article_login_description = article_data_login.find('meta',attrs={'property':'og:description'})['content']
					# except:
					# 	article_login_description = ''
					get_source = get_domain_name(article_url_login)
			else:
				get_source = ''
			meta_tags = ''
			try:
				meta_tags = article_data_login.find('meta',attrs={'name':'news_keywords'})['content']
			except:
				meta_tags = ''
			post_url = Post_detail.objects.filter(client_id=request.POST.get('client_id'), post_url=article_url_login).all()
			# if post_url:
				# Post_detail.objects.filter(client_id=request.POST.get('client_id'), post_url=article_url_login).update(client_id = request.POST.get('client_id'), client_name = client_data['name'], post_url = article_url_login, comment = comments, like = likes, share = shares, activity = '', source = get_source, meta_tags = meta_tags, found_keys='', author_name=author_name, hash_tag=hash_tag, post_text=post_text, post_short_url=post_short_url)
			# else:
			Post_detail(client_id = request.POST.get('client_id'), client_name = client_data['name'], post_url = article_url_login, comment = comments, like = likes, share = shares, activity = '', source = get_source, meta_tags = meta_tags, found_keys='', author_name=author_name, hash_tag=hash_tag, post_text=post_text, post_short_url=post_short_url).save()

		for articles in all_articles_div:
			ln_article_url.append('https://www.linkedin.com'+articles.find(class_='article-card__title--link')['href'])
		for url in ln_article_url:
			author_name = client_data['name']
			article = requests.get(url, headers=headers)
			article_data = bs4.BeautifulSoup(article.text, 'html.parser')
			article_title = article_data.find('title').text
			article_description = article_data.find('meta',attrs={'name':'description'})['content']
			try:
				article_full_content = article_data.find('section', attrs={'class':'article-body'}).text
			except:
				article_full_content = ''
			article_content = article_title+' '+article_description+' '+article_full_content
			post_url = Post_detail.objects.filter(client_id=request.POST.get('client_id'), post_url=url).all()
			com_like_share = article_data.findAll('li', attrs = {'class':'social-ctas__list-item'})
			meta_tags = ''
			likes = com_like_share[0].find(class_='social-ctas__number').text
			comments = com_like_share[1].find(class_='social-ctas__number').text
			shares = com_like_share[2].find(class_='social-ctas__number').text
			found_keys = []
			matched_tags = ['social selling','influence','immigrant', 'Children']

			for search_keys in matched_tags:
				if search_keys in article_content:
					found_keys.append(search_keys)
			if not found_keys:
				found_keywords = 'Not Found'
			else:
				found_keywords = ", ".join(found_keys)
			if post_url:
				Post_detail.objects.filter(client_id=request.POST.get('client_id'), post_url=url).update(client_id = request.POST.get('client_id'), client_name = client_data['name'], post_url = url, comment = comments, like = likes, share = shares, activity = '', source = 'LinkedIn|Pulse', meta_tags = meta_tags, found_keys=found_keywords, author_name=author_name)
			else:
				Post_detail(client_id = request.POST.get('client_id'), client_name = client_data['name'], post_url = url, comment = comments, like = likes, share = shares, activity = '', source = 'LinkedIn|Pulse', meta_tags = meta_tags, found_keys=found_keywords, author_name=author_name).save()

	results = {}
	get_all_articles = Post_detail.objects.filter(client_id = request.POST.get('client_id')).all()
	results['articles'] = get_all_articles

	return render_to_response('load_articles.html', results)

def get_domain_name(value):
	parsed_uri = urlparse(value)
	result = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
	if 'www' in value:
		value = value.replace('www.','')
	try:
		domain = urlparse(value).hostname.split('.')[0].upper()
	except:
		value = value.replace('.com','').upper()
		return value

	return domain

def get_new_articles(request):
	results = {}
	get_all_articles = New_articles.objects.all()
	results['articles'] = get_all_articles
	return render(request, 'admin/get_new_articles.html', results)


#change to appropriate directory with unix commands or with 'preferences'

#1 plot generation

#add data
import pandas
import numpy
#Columns in final array: 1st is time, 2nd is MSU score, 3rd is UW score
UWvMSU = pandas.read_csv("UWvMSU_1-22-13.txt",header=0,sep="\t") #read original file with scores, tabs are delimeter
scorearray = numpy.zeros((51,3)) #this is the new array that I am going to populate with data, there is an extra row at the top so time zero is zero score
for row in range(0,len(UWvMSU),1): #starting with row zero through the length of the original file (UWvMSU), counting by 1, variable is "row"
    scorearray[row+1,0] = UWvMSU.iloc[row,0] #in row+1 (starting with second row b/c first row is zero), populate column 1 of scorearray (index zero) with times from column 1 in UWvMSU data
    if UWvMSU.iloc[row,1] == "MSU": #read through rows in column 2 (index 1) in UWvMSU, see if it reads MSU
        scorearray[row+1,1] = scorearray[row,1] + UWvMSU.iloc[row,2] #populate the scorearray with row+1(the next row, in column 2,(index 1) and add the score from UWvMSU file with row and score from UWvMSU
        #part above is for adding cumulative score for MSU
        scorearray[row+1,2] = scorearray[row,2] #populate the third column (index 2) of scorearray with the score from column 3 (index 2) without adding to the score
        #cumulative score for UW above, doesn't add to score when MSU is found
    else: #this assumes no errors and that anything besides MSU will be UW
        scorearray[row+1,2] = scorearray[row,2] + UWvMSU.iloc[row,2] #in reverse of the first part of the if statement, add to the culmulative score for UW
        scorearray[row+1,1] = scorearray[row,1] #don't add to the score for MSU, move the last score down to the next row
#print(scorearray) #a print step for checking the array for cumulative scores, hashed out when not using
time = scorearray[:,0]
MSUscore = scorearray[:,1] #define a subset of the array as MSU score for plotting
#print(MSUscore) #checking print step
UWscore = scorearray[:,2] #define a subset of array as UW score for plotting
#print(UWscore) #checking print step
import matplotlib.pyplot as plt #import package for graphing
plt.plot(time,UWscore,'r-',time,MSUscore,'g-') #plots UWscore in red and MSUscore in green against time

#2 GAME: GUESS MY Number Vs 1
#add packages
import numpy as np
#select code from here to break to run game
#make array from 1:100
numbers=range(1,101,1)
#computer assigns random numbers
random=np.random.choice(numbers)
#set number outside of range so that the first loop works
guess=0
print("I'm thinking of a number between 1-100. Try to guess it.")
while guess != random:
    guess=raw_input('Guess:') #gives prompt
    guess=int(guess) #converts guess to integer
    if guess < random: #if guess is too low
        print('Guess:' + str(guess))
        print("Higher")
    elif guess > random: #if guess is too high
       print('Guess:'+ str(guess))
       print("Lower")
    else: #if guess is correct
        print('Guess:'+ str(guess))
        print("Correct! " + str(guess))
        break #ends the loop

#GAME Guess my Number Vers. 2.0 (also asks name and says number of guesses)
#select all of the following text and run it
#add packages
import numpy as np
#how many guesses taken, will be added to
guessesTaken = 0
#make array from 1:100
numbers=range(1,101,1)
#computer assigns random numbers
random=np.random.choice(numbers)
#program asks user name
print('Hello! What is your name?')
myName = raw_input() #user supplies name
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')#let the games begin
while guessesTaken < 100: #runs for 100 guesses, then will terminate
    print('Take a guess.')
    guess = raw_input() #takes user's first guess
    guess = int(guess)

    guessesTaken = guessesTaken + 1 #adds one for each guess

    if guess < random: #user's guess too low
        print('Your guess, ' + str(guess) + ', is too low.')

    if guess > random: #user's guess too high
        print('Your guess, ' + str(guess) + ', is too high.')

    if guess == random: #user's guess correct
        break
if guess == random: #once correct it lets the user know they were correct
    guessesTaken = str(guessesTaken)
    print('Good job, ' + myName + '! You guessed my number, ' + str(guess) + ', in ' + guessesTaken + ' guesses!')
#game complete at this point


import asyncio
import contextlib
import discord
import itertools

from discord.ext import commands
from random import choice

from .cards import Suit, Deck, images as card_images
from .manager import SessionManager

from ..utils.misc import emoji_url

__schema__ = """
    CREATE TABLE IF NOT EXISTS hilo_games (
        id SERIAL PRIMARY KEY,
        guild_id BIGINT NOT NULL,
        player_id BIGINT NOT NULL,
        played_at TIMESTAMP NOT NULL,
        points INTEGER NOT NULL
    );
"""

def _cmp(a, b):
    return (a > b) - (a < b)

EMOJI_CMPS = {
    '\N{UP-POINTING SMALL RED TRIANGLE}': 1,
    '\N{LEFT RIGHT ARROW}': 0,
    '\N{DOWN-POINTING SMALL RED TRIANGLE}': -1,
}
SUIT_EMOJI_URLS = [emoji_url(s.emoji) for s in Suit]

class HiloSession:
    def __init__(self, ctx):
        self.ctx = ctx
        self._deck = Deck()
        self._message = None
        self._display = (discord.Embed(colour=ctx.bot.colour)
                         .set_author(name='Points: 0', icon_url=ctx.author.avatar_url)
                         )

    async def _get_cmp(self):
        def check(reaction, user):
            return (reaction.message.id == self._message.id
                    and user.id == self.ctx.author.id
                    and str(reaction.emoji) in EMOJI_CMPS)

        reaction, user = await self.ctx.bot.wait_for('reaction_add', timeout=7, check=check)

        with contextlib.suppress(discord.HTTPException):
            await self._message.remove_reaction(reaction, user)

        return EMOJI_CMPS[reaction.emoji]

    async def _get_ending_text(self, points, *, default):
        connection = await self.ctx.acquire()

        # Check if it's a world record
        query = 'SELECT MAX(points) FROM hilo_games;'
        wr = await connection.fetchval(query)

        if wr is None or points > wr:
            return "World Record!"

        # Check if it's a personal best
        query = 'SELECT MAX(points) FROM hilo_games WHERE player_id = $1;'
        pb = await connection.fetchval(query, self.ctx.author.id)

        if pb is None or points > pb:
            return "New Personal Best!"

        return default

    def _display_card(self, card):
        image_url = card_images.get_card_image_url(card)
        if image_url:
            self._display.set_image(url=image_url)

    async def _loop(self):
        display = self._display
        current = self._deck.draw_one()

        self._display_card(current)
        self._message = message = await self.ctx.send(embed=display)

        for e in EMOJI_CMPS:
            await message.add_reaction(e)

        for i in itertools.count():
            try:
                success = False

                try:
                    user_cmp = await self._get_cmp()
                except asyncio.TimeoutError:
                    display.title = await self._get_ending_text(i, default="Time's up!")
                    display.colour = 0x9E9E9E
                    return i

                old, current = current, self._deck.draw_one(fill=True)
                result = _cmp(current.rank.value, old.rank.value)

                success = result == user_cmp

                if not success:
                    display.title = await self._get_ending_text(i, default="Game Over!")
                    display.colour = 0xF44336
                    return i
            finally:
                display.set_author(name=f'Points: {i + success}', icon_url=display.author.icon_url)
                self._display_card(current)

                await message.edit(embed=display)

    async def run(self):
        await self.ctx.release()
        return await self._loop()

class HigherOrLower:
    """The classic game of Higher or Lower.

    See if the next card will be... well higher or lower than the current one.
    """
    def __init__(self, bot):
        self.bot = bot
        self.channel_sessions = SessionManager()  # because only one game per channel
        self.user_sessions = SessionManager()     # because only one game per user

    @commands.group(invoke_without_command=True)
    @commands.bot_has_permissions(embed_links=True, add_reactions=True)
    async def hilo(self, ctx):
        """Starts a game of Higher or Lower"""
        if self.channel_sessions.session_exists(ctx.channel.id):
            return await ctx.send('A game is in progress in this channel. Please wait...')
        if self.user_sessions.session_exists(ctx.author.id):
            return await ctx.send('You already have a game in progress...')

        inst = HiloSession(ctx)
        with self.channel_sessions.temp_session(ctx.channel.id, inst), \
             self.user_sessions.temp_session(ctx.author.id, inst):
            score = await inst.run()

        query = """INSERT INTO hilo_games (guild_id, player_id, played_at, points)
                   VALUES ($1, $2, $3, $4);
                """
        await ctx.db.execute(query, ctx.guild.id, ctx.author.id, ctx.message.created_at, score)

    @hilo.command(name='leaderboard', aliases=['lb'])
    async def hilo_leaderboard(self, ctx):
        """Shows the 10 highest scores in Higher or Lower"""
        query = """SELECT player_id, points
                   FROM hilo_games
                   ORDER BY points DESC
                   LIMIT 10;
                """
        records = await ctx.db.fetch(query)

        lb = '\n'.join(
            '\\' + f'\u2b50 <@{player_id}>: {points} points '
            for player_id, points in records
        )

        embed = (discord.Embed(colour=ctx.bot.colour, description=lb)
                 .set_author(name='Higher or Lower Leaderboard', icon_url=choice(SUIT_EMOJI_URLS))
                 )
        await ctx.send(embed=embed)

def setup(bot):
    bot.add_cog(HigherOrLower(bot))


from pydicom.dataset import Dataset

from pynetdicom import AE, evt, StoragePresentationContexts, debug_logger
from pynetdicom.sop_class import PatientRootQueryRetrieveInformationModelMove

debug_logger()

def handle_store(event):
    """Handle a C-STORE service request"""
    return 0x0000

handlers = [(evt.EVT_C_STORE, handle_store)]

ae = AE()
ae.add_requested_context(PatientRootQueryRetrieveInformationModelMove)
ae.supported_contexts = StoragePresentationContexts

# Start our Storage SCP in non-blocking mode, listening on port 11120
ae.ae_title = b'OUR_STORE_SCP'
scp = ae.start_server(('', 11120), block=False, evt_handlers=handlers)

# Create out identifier (query) dataset
ds = Dataset()
ds.PatientID = '188'
ds.PatientName = '==문흥진'
ds.QueryRetrieveLevel = 'STUDY'

# Associate with peer AE at IP 127.0.0.1 and port 11112
assoc = ae.associate('127.0.0.1', 11112)

if assoc.is_established:
    # Use the C-MOVE service to send the identifier
    responses = assoc.send_c_move(ds, b'OUR_STORE_SCP', PatientRootQueryRetrieveInformationModelMove)

    for (status, identifier) in responses:
        if status:
            print('C-MOVE query status: 0x{0:04x}'.format(status.Status))
        else:
            print('Connection timed out, was aborted or received invalid response')

    # Release the association
    assoc.release()
else:
    print('Association rejected, aborted or never connected')

# Stop our Storage SCP
scp.shutdown()


#!/usr/bin/env python
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('mpg', type=float)
parser.add_argument('cost_per_litre', type=float)
args = parser.parse_args()

LITRES_IN_GAL = 4.55

cost_per_gallon = args.cost_per_litre * LITRES_IN_GAL
print(f"{args.mpg:.0f}mpg at £{args.cost_per_litre:.2f}/l => £{cost_per_gallon / args.mpg:.2f}/mi")


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

from django.contrib import admin
from .models import Campeonato
# Register your models here.

class Campeonatos (admin.ModelAdmin):
	raw_id_fields = ('pais',)
	list_display = ['Nombre_Campeonato','Region','pais','Tipo_Campeonato', 'Total_Fechas', 'Semestre', 'Fecha_Inicio', 'Fecha_Final']

	class Meta:
		model = Campeonato

admin.site.register(Campeonato, Campeonatos)


import hashlib

read_file = open("infile.txt", 'r')
read_lines = read_file.readlines()
read_file.close()

write_file = open("outfile.txt", 'w')

for line in read_lines:
    string = line.strip()
    encoded_string = string.encode()
    print(hashlib.md5(encoded_string).hexdigest(), "//MD5 for", string, file = write_file)
    print(hashlib.sha1(encoded_string).hexdigest(), "//SHA1 for", string, file = write_file)

write_file.close()

2020-2021/CST 466 - Embedded System Security/Assignment 3/hash_stuff.py


import datetime
import os

from emiproc.hourly_emissions import speciation as spec

model = 'cosmo-ghg'

path_emi = os.path.join('outputs', 'offline','all_emissions.nc')

output_path = os.path.join('outputs', 'offline','hourly')
output_name = "emis_"
prof_path = os.path.join('outputs', 'profiles')

start_date = datetime.date(2019, 1, 1)
end_date = datetime.date(2019, 1, 8)  # included

var_list = ['CO2_ALL_E']

contribution_list = None

catlist = [
    [
        'CO2_A_TNO',
        'CO2_B_TNO',
        'CO2_C_TNO',
        'CO2_F1_TNO',
        'CO2_F2_TNO',
        'CO2_F3_TNO',
        'CO2_D_TNO',
        'CO2_E_TNO',
        'CO2_G_TNO',
        'CO2_H_TNO',
        'CO2_I_TNO',
        'CO2_J_TNO',
        'CO2_K_TNO',
        'CO2_L_TNO',
        'CO2_B_Carbocount',
        'CO2_C_Carbocount',
        'CO2_J_Carbocount',
        'CO2_L_Carbocount',
        'CO2_F_Carbocount',
    ],
]

tplist = [
    [
        'GNFR_A_TNO',
        'GNFR_B_TNO',
        'GNFR_C_TNO',
        'GNFR_F_TNO',
        'GNFR_F_TNO',
        'GNFR_F_TNO',
        'GNFR_D_TNO',
        'GNFR_E_TNO',
        'GNFR_G_TNO',
        'GNFR_H_TNO',
        'GNFR_I_TNO',
        'GNFR_J_TNO',
        'GNFR_K_TNO',
        'GNFR_L_TNO',
        'GNFR_B_Carbocount',
        'GNFR_C_Carbocount',
        'GNFR_J_Carbocount',
        'GNFR_L_Carbocount',
        'GNFR_F_Carbocount',
    ],
]

""" All emissions are applied on the floor in fact"""
vplist = [['GNFR_area_sources']]
vplist[0] *= len(tplist[0])


import numpy as np
import pickle
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn import grid_search
import time

trainData  = []
trainLable = []
with open('ministTrainDataPy.pkl', 'rb') as pkl_file:
    data = pickle.load(pkl_file)
    for i in data:
        trainData.append(i[0])
        trainLable.append(i[1])

# convert to numpy array
for i in range(len(trainData)):
    trainData[i] = trainData[i].astype('float')/255 #归一化
trainLable = np.array(trainLable)
trainLable = trainLable.ravel()

# ####parameter chose using CV
# parameters = {'nu': (0.05, 0.02, 0.1, 0.03), 'gamma': [3e-2, 1e-1, 2e-3]}
# gsClf = grid_search.GridSearchCV(svcClf, parameters, n_jobs=1, verbose=True)
# gsClf.fit(trainData[0:2000], trainLable[0:2000])
# for params, mean_score, scores in gsClf.grid_scores_:
#     print("%0.3f (+/-%0.03f) for %r"  % (mean_score, scores.std() * 2, params))

# ######using NuSvm
svcClf = svm.NuSVC(nu=0.02, kernel='rbf', gamma=0.03, verbose=True)
svcClf.fit(trainData[0:2000], trainLable[0:2000])
# testdata
testData  = []
testLable = []
with open('ministTestDataPy.pkl', 'rb') as pkl_file:
    data = pickle.load(pkl_file)
    for i in data:
        testData.append(i[0])
        testLable.append(i[1])
rightNum = 0
wrongNum = 0
# convert to numpy array
for i in range(len(testData)):
    testData[i] = testData[i].astype('float')/255 #归一化
testLable = np.array(testLable)
testLable = testLable.ravel()

for i in range(200):
    if(svcClf.predict(testData[i].reshape(1, -1)) == testLable[i]):
        rightNum += 1
    else:
        wrongNum += 1

print('rate = ', str((rightNum/(rightNum+wrongNum))))