import math, time, statistics
from read_data import *
from q3 import *

''' Returns net entropy '''
def entropy(indices):
    arr_size = len(indices)
    ''' Creating dictionary for each distinct values in labels whose index is present in indices
    0 and 1 are labels
    d = {0: 20299, 1: 6701}
    '''
    d = {}
    for i in indices:
        if train_labels[i] in d:
            d[train_labels[i]] += 1
        else:
            d[train_labels[i]] = 1

    ent = 0
    for v in d.values():
        prob = float(v)/len(indices)
        ent += ( prob * math.log(prob) * (-1))

    return ent

''' Returns the list of information gain for each of the feature in the feature vecor '''
''' child_node_d contains all the indices corresponding to the values that the chosen feature can take '''
def highest_ig(indices, attr_list):
    h_y = entropy(indices)
    ig_max = 0
    d_max = None
    feature_index = None
    max_feature_med = None
    feature_med = None
    if sum(attr_list) == 0:
        return ig_max, feature_index, d_max, None
    for i in range(14):
        if attr_list[i] == 1:
            ''' Extracting ith feature column from the data '''
            feature = train_data[:,i]
            ''' d contains list of those indices which has same feature value '''
            d = {}

            ''' if the feature selected is a continuous feature '''
            if i in cont_list:
                ind_features = []
                for ind in indices:
                    ind_features.append( train_data[ind][i] )
                    #print (ind, train_data[ind][i])
                feature_med = statistics.median(ind_features)
                #print (i, feature_med)
                for ind in indices:
                    temp = (float(feature[ind]) >= feature_med)
                    if temp in d :
                        d[temp].append(ind)
                    else :
                        d[temp] = [ind]
            else:
                for ind in indices:
                    if feature[ind] in d :
                        d[feature[ind]].append(ind)
                    else :
                        d[feature[ind]] = [ind]

            if (d_max == None or feature_index == None):
                d_max = d
                feature_index = i

            net_ent = 0
            for v in d.values():
                prob_x = float(len(v))/len(indices)
                ''' Calculating entropy over all the values of dictonary creates '''
                ent = entropy (v)
                net_ent += (prob_x * ent)

            if ( ( h_y - net_ent ) > ig_max ):
                ig_max = ( h_y - net_ent )
                d_max = d
                feature_index = i
                max_feature_med = feature_med

        #print ("Information gain", data_attributes[i], (h_y - net_ent))
    #print ("Feature chosen:", data_attributes[feature_index])
    #print (ig_max)
    if feature_index in cont_list:
        return ig_max, feature_index, d_max, max_feature_med
    else:
        return ig_max, feature_index, d_max, None

#what value 0/1 is being predicted at this node, accuracy
def get_accuracy(indices):
    pos = 0
    for i in indices:
        if train_labels[i] == 1:
            pos += 1

    pos_per = 100.0 * float(pos) / len(indices)
    if ( pos_per > (100 - pos_per) ):
        return (1, pos_per)
    else:
        return (0, 100.0-pos_per)


import vtk

def make_clipper(plane,normals):
    """
    Returns a clipper filter, of type vtk.vtkClipPolyData()
    takes as input:
      * the cut plane, of type vtk.vtkPlane()
      * The normals to the polydata, of type  vtk.vtkPolyDataNormals()
    """
    # We clip with an implicit function. Here we use a plane positioned near
    # the center of the cow model and oriented at an arbitrary angle.

    # vtkClipPolyData requires an implicit function to define what it is to
    # clip with. Any implicit function, including complex boolean combinations
    # can be used. Notice that we can specify the value of the implicit function
    # with the SetValue method.
    clipper = vtk.vtkClipPolyData()    #clip filter ?
    clipper.SetInputConnection(normals.GetOutputPort())
    clipper.SetClipFunction(plane)
    clipper.GenerateClipScalarsOn()
    clipper.GenerateClippedOutputOn()
    clipper.SetValue(0.5)

    return clipper

def make_actors(plane,clipper,normals,color):
    """ Creates three actors for a given volume: clipActor,cutActor,restActor
    takes as input plane and normal (same as parameters for  make_clipper)
    and clipper (generated by  make_clipper)
    """
    clipMapper = vtk.vtkPolyDataMapper()   # Mapper
    clipMapper.SetInputConnection(clipper.GetOutputPort())
    clipMapper.ScalarVisibilityOff()

    #backProp = vtk.vtkProperty()
    #backProp.SetDiffuseColor(tomato)

    clipActor = vtk.vtkActor()      # Actor
    clipActor.SetMapper(clipMapper)
    clipActor.GetProperty().SetColor(color)
    clipActor.GetProperty().EdgeVisibilityOff()
    clipActor.GetProperty().SetOpacity(0.5)
    clipActor.GetProperty().SetInterpolationToGouraud()

    #clipActor.SetBackfaceProperty(backProp)

    # Here we are cutting the cow. Cutting creates lines where the cut
    # function intersects the model. (Clipping removes a portion of the
    # model but the dimension of the data does not change.)
    #
    # The reason we are cutting is to generate a closed polygon at the
    # boundary of the clipping process. The cutter generates line
    # segments, the stripper then puts them together into polylines. We
    # then pull a trick and define polygons using the closed line
    # segments that the stripper created.
    cutEdges = vtk.vtkCutter()
    cutEdges.SetInputConnection(normals.GetOutputPort())
    cutEdges.SetCutFunction(plane)
    cutEdges.GenerateCutScalarsOn()
    cutEdges.SetValue(0, 0.5)

    cutStrips = vtk.vtkStripper()
    cutStrips.SetInputConnection(cutEdges.GetOutputPort())
    cutStrips.Update()

    cutPoly = vtk.vtkPolyData()
    cutPoly.SetPoints(cutStrips.GetOutput().GetPoints())
    cutPoly.SetPolys(cutStrips.GetOutput().GetLines())

    # Triangle filter is robust enough to ignore the duplicate point at
    # the beginning and end of the polygons and triangulate them.
    cutTriangles = vtk.vtkTriangleFilter()
    cutTriangles.SetInputData(cutPoly)
    cutMapper = vtk.vtkPolyDataMapper()
    cutMapper.SetInputData(cutPoly)
    cutMapper.SetInputConnection(cutTriangles.GetOutputPort())
    cutActor = vtk.vtkActor()
    cutActor.SetMapper(cutMapper)
    cutActor.GetProperty().SetColor(color)

    # The clipped part of the cow is rendered wireframe.
    restMapper = vtk.vtkPolyDataMapper()
    restMapper.SetInputConnection(clipper.GetClippedOutputPort())
    restMapper.ScalarVisibilityOff()
    restActor = vtk.vtkActor()
    restActor.SetMapper(restMapper)
    restActor.GetProperty().SetColor(color)
    restActor.GetProperty().EdgeVisibilityOff()
    restActor.GetProperty().SetOpacity(0.1)
    restActor.GetProperty().SetInterpolationToGouraud()

    #restActor.GetProperty().SetRepresentationToWireframe()
    return clipActor,cutActor,restActor


from functools import cmp_to_key
from bisect import bisect_right, bisect_left

while True:
    n = int(input())
    if n == 0:
        break

    course = dict()

    students = [ tuple(sorted(list(map(int,input().split())))) for _ in range(n)]

    for student in students:
        course[student] = course[student]+1 if student in course else 1

    for index,student in enumerate(students):
        students[index] = course[student]

    students.sort()
    print(len(students) - bisect_left(students,students[-1]))


# encoding: utf-8
import csv
import numpy as np
import os
import pandas as pd
from matplotlib import pylab
import matplotlib.pyplot as plt
from matplotlib import font_manager
from mpl_toolkits.mplot3d import Axes3D
from sklearn.cluster import KMeans,MeanShift,estimate_bandwidth
from sklearn.ensemble import RandomForestClassifier,RandomForestRegressor
from sklearn.neural_network import MLPClassifier, MLPRegressor
from sklearn.metrics import precision_score, recall_score, classification_report, confusion_matrix,r2_score,euclidean_distances
from sklearn.metrics.pairwise import pairwise_distances
from sklearn import cross_validation
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.grid_search import GridSearchCV
from sklearn.preprocessing import scale
from sklearn import mixture
from x_means import XMeans
import multiprocessing
import functools
import funcs
import datetime
from sklearn.externals import joblib

##listにuidが存在するか確認
def find_userid(datalist,uid):
    for data in datalist:
        if uid == data[0]:
            return True
    return False

##入力データと入力ラベルに基づいてMSに最適なパラメータを探索
def tune_MS(data):
    mss = []
    range_max = 20
    bandwidth_range = 0.35 + (np.array(range(0, range_max+1))-(range_max/2))*0.001
    for bandwidth in bandwidth_range:
        ms = MeanShift(bandwidth=bandwidth, n_jobs=-2)
        ms.fit(data)
        mss.append(ms)

    metrics=['cityblock', 'cosine', 'euclidean', 'l1', 'l2', 'manhattan']
    distance_max = 0
    retms = mss[0]
    for metric in metrics:
        print(metric)
        print("-------------")
        for ms in mss:
            distance = pairwise_distances(ms.cluster_centers_,metric=metric,n_jobs=-2)
            print(np.mean(distance,axis=0))
            distance = np.mean(distance)
            if distance > distance_max:
                distance_max = distance
                retms = ms
        print("-------------")
    return retms

##入力データと入力ラベルに基づいてGMMに最適なパラメータを探索
def tune_GMM(data):
    lowest_bic = np.infty
    bic = []
    n_components_range = range(1, 7)
    cv_types = ['spherical', 'tied', 'diag', 'full']
    for cv_type in cv_types:
        for n_components in n_components_range:
            # Fit a mixture of Gaussians with EM
            gmm = mixture.GMM(n_components=n_components, covariance_type=cv_type, random_state=1)
            gmm.fit(data)
            bic.append(gmm.bic(data))
            if bic[-1] < lowest_bic:
                lowest_bic = bic[-1]
                best_gmm = gmm
    return best_gmm

##各列毎の平均値をとる
def get_average(tup):
    uid = tup[0]
    data = tup[1]
    speed_array = np.array(data['data']).astype(np.float)
##    nan要素をマスキングで計算に現れずにする
    masked_array = np.ma.masked_array(speed_array,np.isnan(speed_array))
    speed = np.mean(masked_array,axis=0)
    ##        np.nansumでnanを無視した合計を取ってくれる便利なヤツあり
##    maskした後mean取ると--になっているところを無視して平均取ってくれる
    return uid, speed,len(data['climbCategory'])

##keyに基づいてdicからデータを取得
##keyのなかでデータがないものがあれば省く
def make_onedata(dic,keys):
    data = []
    for key in keys:
        d = dic[key]
##        データが存在しない場合無視するためにNoneを代入
        if d == '-1':
            d = None
        data.append(d)
    return data,dic['userid'],dic['climbCategory']

##ユーザデータにラベルを付与
##現在は欠損値があるデータを削除している
def add_labels(tup,uids,labels):
    uid = tup[0]
    data = tup[1]

    if uid not in uids:
        return None
    data = np.array(data['data']).astype(np.float)
##    欠損値を削除
    data = data[~np.isnan(data).any(axis=1)]
    if len(data) == 0:
        print(uid)
        return None
    label = np.array([labels[uids.index(uid)]]*len(data))
    return np.c_[data,label]

##climbCategory毎の回数を記録
##pythonは引数で与えられた変数を直接弄る？
##dictだからメモリが引数として与えられている？
def update_climbCategory(dic,climbCategory):
    if climbCategory in dic.keys():
        dic[climbCategory] += 1
    else:
        dic[climbCategory] = 1
    return dic

##クラスタごとに色分けしてプロット
def plot_data_3D(data,classes):
    fig = plt.figure()
    ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
    ax.scatter(data[:,0], data[:,1], data[:,2], c=classes.astype(np.float))
    ax.w_xaxis.set_ticklabels([])
    ax.w_yaxis.set_ticklabels([])
    ax.w_zaxis.set_ticklabels([])
    ax.set_xlabel('Negative Grade')
    ax.set_ylabel('No Grade')
    ax.set_zlabel('Positive Grade')
    plt.show()

##クラスタごとに色分けしてプロット
def plot_data_2D(data,classes,components_label):
    fig = plt.figure()
    data_len = len(components_label)
    for x in range(data_len):
        for y in range(data_len):
            ax = fig.add_subplot(data_len,data_len,1+y+x*data_len)
            if x == y:
                ax.text(0,0,components_label[x])
            else:
                ax.scatter(data[:,x], data[:,y], c=classes.astype(np.float))
    plt.show()

##雑に時間を定義、季節によって変える必要あり
def get_hour(hour):
    key = ""
    if hour >= 6 and hour <= 9:
        key = "morning"
    elif hour >=10 and hour <= 18 :
        key = "noon"
    else:
        key = "night"

    return key

##季節を定義
def get_month(month):
    key = ""
    if month >= 3 and month <= 5:
        key = "spring"
    elif month >=6 and month <= 8 :
        key = "summer"
    elif month >=9 and month <= 11 :
        key = "autumn"
    else:
        key = "winter"

    return key

##セグメントのデータをファイルから作成
def makesegmentdata_from_files(path_labeled):
    keys = ['startDate','climbCategory','DISTANCE']
    ret_list = []
    for label in ['labeled','notlabeled']:
        files = os.listdir(os.path.join(path_labeled,label))
        for file in files:
            data = funcs.read_myjson(os.path.join(path_labeled,label,file),None,None)
            for d in data:
                temp_list = []
                for key in keys:
                    if key == 'DISTANCE':
                        temp_list.append(d[key][0])
                        temp_list.append(d[key][-1] - d[key][0])
                    elif key == 'startDate':
                        tdatetime = datetime.datetime.strptime(d[key], '%Y-%m-%dT%H:%M:%SZ')
                        temp_list.append(get_month(tdatetime.month))
                        temp_list.append(get_hour(tdatetime.hour))
                        temp_list.append(d[key])
                    else:
                        temp_list.append(d[key])
                ret_list.append(temp_list)
    try:
        f = funcs.get_fileobj('middata.csv','w',None)
        writer = csv.writer(f, lineterminator='\n')
        keys = ['month','hour','climbCategory','DISTANCE','consumed_dist']
        writer.writerow(keys)
        writer.writerows(ret_list)
    finally:
        f.close()

##--------------プログラム開始------------------
##マルチスレッド処理の為にこれが必要 http://matsulib.hatenablog.jp/entry/2014/06/19/001050
if __name__ == '__main__':
    funcs.start_program()
    filepath = funcs.get_filepath('middata.csv',None)
    if os.path.exists(filepath) is False:
        print("DATA FROM FILE!!!!!!!!!!!!!!!!!!!!!!!!!!!")
        data = makesegmentdata_from_files('results\\data_for_regression\\20160203_011146')
        print("RESTART")
        exit(-1)
    else:
        df = pd.read_csv(filepath)
        data = np.array(df).astype(np.float)

##    クラスタリング開始
    uids = data[:,0]
    data = data[:,2:5]
    scaled_data = scale(data)
##kmeansでクラスタリング
    kmeans_model = KMeans(n_clusters=9, random_state=1)
    kmeans_model.fit(scale(scaled_data))
    km_labels = np.array(kmeans_model.labels_)
##        plot_data_2D(data,labels,components_label)

##GMMでクラスタリング
##        GMMのチューニング
    gmm = tune_GMM(scaled_data)
    joblib.dump(gmm, funcs.get_filepath('gmmpred.pkl',gmmmodel))
    gm_labels = gmm.predict(scaled_data)
    plot_data_3D(data,gm_labels)

##MeanShiftでクラスタリング
##    ms_model = tune_MS(scaled_data)
    ms_model = MeanShift(bandwidth=0.35299999999999998)
    ms_model.fit(scaled_data)
    ms_labels = ms_model.labels_

    try:
        file = funcs.get_fileobj('labels.csv','w',None)
        writer = csv.writer(file, lineterminator='\n')
        writer.writerow(['uid','9-means','GMM','MeanShift'])
        writer.writerows(np.c_[uids,km_labels,gm_labels,ms_labels])
    finally:
        file.close()
##        kmeansの重心のプロット
##        centers = kmeans_model.cluster_centers_
##        plot_data_2D(centers,np.array(range(cluster_num)),components_label)
    funcs.end_program()


from builtins import enumerate

from django import template
from django.urls import reverse

from tapir.shifts.models import (
    Shift,
    ShiftTemplate,
    ShiftAttendanceTemplate,
    WEEKDAY_CHOICES,
)

register = template.Library()

@register.inclusion_tag("shifts/user_shifts_overview_tag.html", takes_context=True)
def user_shifts_overview(context, user):
    context["user"] = user
    return context

@register.inclusion_tag("shifts/shift_block_tag.html", takes_context=True)
def shift_block(context, shift: Shift, fill_parent=False):
    context["shift"] = shift_to_block_object(shift, fill_parent)
    return context

@register.inclusion_tag("shifts/shift_block_tag.html", takes_context=True)
def shift_template_block(context, shift_template: ShiftTemplate, fill_parent=False):
    context["shift"] = shift_template_to_block_object(shift_template, fill_parent)
    return context

def shift_to_block_object(shift: Shift, fill_parent: bool):
    attendances = ["empty" for _ in range(shift.num_slots)]
    for index, attendance in enumerate(shift.get_valid_attendances()):
        attendances[index] = "single"
        if (
            shift.shift_template is not None
            and ShiftAttendanceTemplate.objects.filter(
                shift_template=shift.shift_template, user=attendance.user
            ).count()
            > 0
        ):
            attendances[index] = "template"

    template_group = None
    if shift.shift_template is not None:
        template_group = template_group_name_to_character(
            shift.shift_template.group.name
        )

    background = "success"
    if shift.get_valid_attendances().count() == 0:
        background = "danger"
    elif shift.get_valid_attendances().count() < shift.num_slots:
        background = "warning"

    style = ""
    if fill_parent:
        style = "height:100%; width: 100%;"

    return {
        "attendances": attendances,
        "name": shift.name,
        "num_slots": shift.num_slots,
        "start_time": shift.start_time,
        "end_time": shift.end_time,
        "start_date": shift.start_time,
        "weekday": None,
        "template_group": template_group,
        "background": background,
        "style": style,
        "id": shift.id,
        "is_template": False,
    }

def shift_template_to_block_object(shift_template: ShiftTemplate, fill_parent: bool):
    attendances = ["empty" for _ in range(shift_template.num_slots)]
    attendance_templates = ShiftAttendanceTemplate.objects.filter(
        shift_template=shift_template
    )
    for index in range(attendance_templates.count()):
        attendances[index] = "template"

    background = "success"
    if attendance_templates.count() == 0:
        background = "danger"
    elif attendance_templates.count() < shift_template.num_slots:
        background = "warning"

    style = ""
    if fill_parent:
        style = "height:100%; width: 100%;"

    return {
        "attendances": attendances,
        "name": shift_template.name,
        "num_slots": shift_template.num_slots,
        "start_time": shift_template.start_time,
        "end_time": shift_template.end_time,
        "start_date": None,
        "weekday": WEEKDAY_CHOICES[shift_template.weekday][1],
        "template_group": template_group_name_to_character(shift_template.group.name),
        "background": background,
        "style": style,
        "id": shift_template.id,
        "is_template": True,
    }

def template_group_name_to_character(name: str):
    if name[-1] == "A":
        return "Ⓐ"
    if name[-1] == "B":
        return "Ⓑ"
    if name[-1] == "C":
        return "Ⓒ"
    if name[-1] == "D":
        return "Ⓓ"
    return None


import copy
import urllib
import requests
import functools

from .login import Salesforce

from .helpers import errors
from .helpers import parsers

from .helpers.report_filters import set_filters, set_period, set_logic

from .report import (
    get_excel,
    get_tabular_reports,
    get_summary_reports,
    get_matrix_reports,
)

URL = "https://{}/services/data/v{}/analytics/reports/"

class Reportforce(Salesforce):
    """Class to interact with the Salesforce Analytics API.

    Attributes
    ----------
    url : str
        Salesforce instance/server URL.

    session : requests.Session
        Session used for making http requests.

    Methods
    -------
    get_report : pandas.DataFrame
        Get a report as a DataFrame.

    get_total : int, float
        Get the grand total of a report.

    get_metadata : dict
        Get a report metadata.
    """

    session = requests.Session()
    session.hooks["response"].append(errors.handle_error)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.url = URL.format(self.instance_url, self.version)

        self.session.headers.update(self.headers)

    def get_report(
        self,
        report_id,
        id_column=None,
        date_column=None,
        start=None,
        end=None,
        filters=[],
        logic=None,
        excel=None,
        **kwargs
    ):
        """Function to get a Salesforce report into a DataFrame.

        Parameters
        ----------
        report_id : str
            A report unique identifier.

        id_column : str (optional)
            Column name which has unique values for each row. This is needed as
            a workaround to the Analytics API's 2000 row limitation.

        date_column : str (optional)
            Date column name.

        start : str (optional)
            Initial date string, passed into dateutil.parser.parse. Must start with
            the day.

        end : str (optional)
            End date string, passed into dateutil.parser.parse. Must start with
            the day.

        filters : list (optional)
            List of tuples, each of which represents a filter:
            [("column", ">=", "value")].

        logic : str (optional)
            Logical filter. This is commonly needed if the report already has a
            report filter, but it can also be useful in case you add more filters.

        excel : bool, str (optional)
            Whether or not you want to save the report in a Excel file. If a
            non-empty string is passed, it will be used as the filename. If True,
            the workbook will be automatically named.

        Returns
        -------
        DataFrame
            A DataFrame contaning the records from the report.

        Raises
        ------
        ReportError
            If there is an error-like JSON string in the reponse body.
        """
        self.metadata = copy.deepcopy(self.get_metadata(report_id))

        if start or end:
            set_period(start, end, date_column, self.metadata)
        if logic:
            set_logic(logic, self.metadata)
        if filters:
            set_filters(filters, self.metadata)

        if excel:
            return get_excel(report_id, excel, self.metadata, self, **kwargs)

        report_format = self.metadata["reportMetadata"]["reportFormat"]

        args = (report_id, id_column, self.metadata, self)

        if report_format == "TABULAR":
            return get_tabular_reports(*args, **kwargs)
        elif report_format == "SUMMARY":
            return get_summary_reports(*args, **kwargs)
        else:
            return get_matrix_reports(*args, **kwargs)

    def get_total(self, report_id):
        """Get a report grand total."""
        url = urllib.parse.urljoin(self.url, report_id)
        report = self.session.get(url, params={"includeDetails": "false"}).json()

        return parsers.get_report_total(report)

    @functools.lru_cache(maxsize=8)
    def get_metadata(self, report_id):
        """Get a report metadata, used to manipulate reports."""
        url = urllib.parse.urljoin(self.url, report_id + "/describe")

        return self.session.get(url).json()


import telepot
import traceback

class TelegramTutorial(telepot.Bot):
    def __init__(self, token):
        super(TelegramTutorial, self).__init__(token)

    def handle_message(self, msg):
        if 'text' not in msg:
            return

        if msg['text'].startswith('/'):
            self.handle_command(msg)

    def handle_start(self, msg):
        self.sendMessage(msg['chat']['id'], "Bem-vindo ao Bot :D")

    def handle_command(self, msg):

        method = 'handle_' + msg['text'][1:]

        if hasattr(self, method):
            getattr(self, method)(msg)

    def runBot(self):
        last_offset = 0
        print('Ouvindo...')

        while True:
            try:
                updates = self.getUpdates(timeout=60, offset=last_offset)

                if updates:
                    for u in updates:
                        self.handle_message(u['message'])

                    last_offset = updates[-1]['update_id'] + 1

            except KeyboardInterrupt:
                break
            except:
                traceback.print_exc()

bot = TelegramTutorial('178525461:AAGZXbGAK1Z1l0e39TbyJhklHC3NAdD91pU')
bot.runBot()


from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.shortcuts import render,get_object_or_404
from .models import Course, Step, Category
import datetime
# Create your views here.

def category_list(request, category):
    courses = Course.objects.order_by('-pub_date').filter(category = category_id )
    paginator = Paginator(courses, 9)
    page = request.GET.get('page')
    paged_courses = paginator.get_page(page)
    category = Category.objects.all()
    context = {
       'courses':courses,
       'courses':paged_courses,
       'category':category
    }
    return render(request,'courses/course_list.html',context)

def course_list(request):
    courses = Course.objects.order_by('-pub_date').filter(is_published=True)
    paginator = Paginator(courses, 9)
    page = request.GET.get('page')
    paged_courses = paginator.get_page(page)
    category = Category.objects.all()
    context = {
       'courses':courses,
       'courses':paged_courses,
       'category':category
    }
    return render(request,'courses/course_list.html',context)

def  detail_view(request, course_id):
    course = get_object_or_404(Course,pk=course_id)
    context = {
        'course':course
    }
    return render(request, 'courses/course_detail.html',context)

def step_detail(request,course_pk, step_pk):
    step = get_object_or_404(Step,Course_id=course_pk,pk=step_pk)
    context ={
        'step':step
    }
    return render(request, 'courses/step_detail.html',context)

def search(request):
    context = {

    }
    return render(request, 'courses/search.html',context)


'''
https://report.amap.com/ajax/roadRank.do?roadType=0&timeType=0&cityCode=110000
'''
import requests
import re
import random
from lxml import etree
import xlsxwriter
# 创建文件，添加一个工作表
def header():
    agent1 = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
    agent2 = "Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3"
    agent3 = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0"
    agent4 = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727"
    list = [agent1, agent2, agent3, agent4]
    agent = random.choice(list)
    header = {"User-Agent": agent}
    return header
if __name__ == '__main__':
    header = header()
    url = "https://report.amap.com/ajax/roadRank.do?roadType=0&timeType=0&cityCode=110000"
    response = requests.get(url,headers = header).content.decode()
    pat = re.compile(r',"delayTime":(.*?),"')
    pat1 = re.compile(r',"dir":"(.*?)","')
    pat2 = re.compile(r',"id":(.*?),"')
    pat3 = re.compile(r',"index":(.*?),"')
    pat4 = re.compile(r'"length":(.*?),"')
    pat5= re.compile(r',"name":"(.*?)",')
    pat6= re.compile(r',"number":(.*?),"')
    pat7 = re.compile(r',"speed":(.*?),"')
    pat8 = re.compile(r',"travelTime":(.*?)}')
    print('延迟时间',pat.findall(response))
    print('方向',pat1.findall(response))
    print('道路号码',pat2.findall(response))
    print('拥堵延时指数',pat3.findall(response))
    print('路长',pat4.findall(response))
    print('路名',pat5.findall(response))
    print('路编号',pat6.findall(response))
    print('速度',pat7.findall(response))
    print('运行时间',pat8.findall(response))
    workbook = xlsxwriter.Workbook('demo.xlsx')
    worksheet = workbook.add_worksheet()
    for i in range(len(pat.findall(response))):
        worksheet.write("A"+str(i+1),pat.findall(response)[i])
    workbook.close()

python网络爬虫/个人做的爬虫练习/爬车速.py


#
# @lc app=leetcode id=485 lang=python
#
# [485] Max Consecutive Ones
#
# https://leetcode.com/problems/max-consecutive-ones/description/
#
# algorithms
# Easy (54.51%)
# Likes:    364
# Dislikes: 312
# Total Accepted:    138.6K
# Total Submissions: 251.7K
# Testcase Example:  '[1,0,1,1,0,1]'
#
# Given a binary array, find the maximum number of consecutive 1s in this
# array.
#
# Example 1:
#
# Input: [1,1,0,1,1,1]
# Output: 3
# Explanation: The first two digits or the last three digits are consecutive
# 1s.
#    The maximum number of consecutive 1s is 3.
#
#
#
# Note:
#
# The input array will only contain 0 and 1.
# The length of input array is a positive integer and will not exceed 10,000
#
#
#
class Solution(object):
    def _findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = longest = 0
        for num in nums:
            if num == 1:
                length += 1
            else:
                longest = longest if longest > length else length
                length = 0
        return longest if longest > length else length

    def findMaxConsecutiveOnes(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = longest = 0
        for num in nums:
            if num == 1:
                length += 1
            else:
                longest = max(longest, length)
                length = 0
        return max(longest, length)

# if __name__ == "__main__":
#     s = Solution()
#     print s.findMaxConsecutiveOnes([1,1,0,1,1,1])


import datetime
from bnw.core.base import get_webui_base

formatters = {
    'comment': None,
    'message': None,
    'recommendation': None,
    'message_with_replies': None,
    'messages': None,
}

def format_message(request, msg):
    result = '+++ [%s] %s:\n' % (
        datetime.datetime.utcfromtimestamp(
            msg['date']).strftime('%d.%m.%Y %H:%M:%S'),
        msg['user'],)
    if msg['tags']:
        result += 'Tags: %s\n' % (', '.join(msg['tags']),)
    if msg['clubs']:
        result += 'Clubs: %s\n' % (', '.join(msg['clubs']),)
    result += '\n%s\n' % (msg['text'],)
    result += '--- %(id)s (%(rc)d) %(base_url)s/p/%(id)s' % {
        'base_url': get_webui_base(request.user),
        'id': msg['id'].upper(),
        'rc': msg['replycount'],
    }
    return result

def format_comment(request, msg, short=False):
    args = {'id': msg['id'].split('/')[1].upper(),
            'author': msg['user'],
            'message': msg['message'].upper(),
            'replyto': None if msg['replyto'] is None else msg['replyto'].upper(),
            'replytotext': msg['replytotext'],
            'text': msg['text'],
            'num': msg.get('num', -1),
            'date': datetime.datetime.utcfromtimestamp(msg['date']).strftime('%d.%m.%Y %H:%M:%S'),
            'web': get_webui_base(request.user),
            }
    formatstring = '+++ [ %(date)s ] %(author)s'
    if msg['replyto']:
        formatstring += ' (in reply to %(replyto)s):\n'
    else:
        formatstring += ' (in reply to %(message)s):\n'
    if not short:
        formatstring += '>%(replytotext)s\n'
    formatstring += '\n%(text)s\n--- %(message)s/%(id)s (%(num)d) %(web)s/p/%(message)s#%(id)s'
    return formatstring % args

def formatter_messages(request, result):
    return 'Search results:\n' + '\n'.join((format_message(request, msg) for msg in result['messages']))

def formatter_message_with_replies(request, result):
    return format_message(request, result['message']) + '\n' + \
        '\n'.join(
        (format_comment(request, c, True) for c in result['replies']))

def formatter_search(request, search_result):
    estimated = search_result['estimated']
    results = search_result['results']
    results.reverse()  # Most relevant items should be at the bottom
    if not results:
        return 'No results found.'
    info = 'Found %d results' % estimated
    if estimated > 20:
        info += ' (displaying first 20)'
    out = [info + ':']
    for res in results:
        out.append('@%s: %s (%s%%)\n%s\n\n#%s %s/p/%s' % (
            res['user'], res['tags_info'], res['percent'], res['text'],
            res['id'], get_webui_base(request.user),
            res['id'].replace('/', '#')))
    return '\n\n'.join(out)

def formatter_subscriptions(request, result):
    return 'Your subscriptions:\n' + '\n'.join(
        (s['type'][4:].ljust(5) + s['target'].rjust(10) + ' ' + s.get('from', '')
         for s in result['subscriptions']))

def formatter_blacklist(request, result):
    return 'Your blacklist:\n' + '\n'.join(
        (s[0].ljust(5) + s[1].rjust(10)
         for s in result['blacklist']))

def formatter_message(request, result):
    return '\n' + format_message(request, result['message'])

def formatter_recommendation(request, result):
    return '\nRecommended by @%s: %s\n' % (result['recommender'], result['recocomment']) + \
        format_message(request, result['message'])

def formatter_comment(request, result):
    return '\n' + format_comment(request, result['comment'])

def formatter_userlist(request, result):
    if not result['users']:
        return 'No more users.'
    return ' ' + ' '.join(
        '@' + u['name'].ljust(10) + ('\n' if i % 5 == 4 else '')
        for i, u in enumerate(result['users'])) + '\nuserlist -p ' + str(result['page'] + 1) + ' -- next page.'

def formatter_settings(request, result):
    return ('Current settings:\n' +
            '\n'.join('%s\t%s' % (k, v) for k, v in result['settings'].iteritems()))

def formatter_clubs(request, result):
    return ' ' + ' '.join(
        '' + u['_id'].ljust(
            15) + ' ' + str(int(u['value'])).ljust(3) + ('\n' if i % 5 == 4 else '')
        for i, u in enumerate(result['clubs']))

def formatter_jids(request, result):
    res = 'JIDs:\n' + ' '.join(u for u in result['jids'])
    if result['pending_jids']:
        res += '\n\nPending JIDs:\n' + ' '.join(u for u in result[
                                                'pending_jids'])
    res += '\n\nActive JID: ' + result['jid']
    return res


from keras.models import load_model
from src.TokenSelector import TokenSelector
from src.Tokenization import Tokenization

import numpy as np
import os
import json

class CheckModel():

    def __init__(self, model_path, tokenization_path, tokenSelector_path):

        raisePathNotExists(model_path)
        raisePathNotExists(tokenization_path)
        raisePathNotExists(tokenSelector_path)

        with open(tokenization_path) as f:
            self.tokenization_params = json.load(f)

        self.model = load_model(model_path)

        with open(tokenSelector_path) as f:
            self.tokenSelector_params = json.load(f)

        self.tokenSelector = TokenSelector(final_char= self.tokenSelector_params["final_char"],
                                           inter_char= self.tokenSelector_params["inter_char"],
                                           signs_to_ignore= self.tokenSelector_params["signs_to_ignore"],
                                           words_to_ignore= self.tokenSelector_params["words_to_ignore"],
                                           map_punctuation= self.tokenSelector_params["map_punctuation"],
                                           letters= "".join(self.tokenSelector_params["letters"]),
                                           sign_not_syllable= self.tokenSelector_params["sign_not_syllable"]
                                           )

        self.tokenSelector.set_params(self.tokenSelector_params)

        self.map_punctuation_inv = dict()
        for key, value in self.tokenSelector_params["map_punctuation"]:
            self.map_punctuation_inv[value] = key

    def predict_word(self, sentence, temperature):

        next_token = ""
        generated = []
        while next_token not in self.tokenSelector_params["index_ends"]:
            x_pred = np.zeros((1, self.tokenization_params["lprime"]))
            for t, token in enumerate(sentence):
                x_pred[0, t] = self.tokenization_params["token_to_index"][token]
            preds = self.model.predict(x_pred, verbose=0)[0]
            next_index = sample(preds, temperature)
            next_token = self.tokenization_params["index_to_token"][str(next_index + 1)]
            generated += [next_token]
            sentence = sentence[1:] + [next_token]

        word = ""
        for token in generated:
            if token in self.map_punctuation_inv:
                word += self.map_punctuation_inv[token]+ " "
            else:
                token = token.replace(self.tokenSelector_params["final_char"], " ")
                token = token.replace(self.tokenSelector_params["inter_char"], "")
                word += token

        return word, generated

    def predict_text(self,
                     seed = "declaro",
                     nwords = 10,
                     temperature = 1.0):

        seed_array = seed.lower().split()

        sentence = []
        text = ""

        for word in seed_array:
            sentence = self.tokenSelector.select(word, sentence)

        for i in range(nwords):
            word, generated = self.predict_word(sentence, temperature)
            text += word
            sentence += generated

        return text

    def get_probability_token(self, token, sentence):
        x_pred = np.zeros((1, self.tokenization_params["lprime"]))
        for t, tk in enumerate(sentence):
            x_pred[0, t] = self.tokenization_params["token_to_index"][tk]
        preds = self.model.predict(x_pred, verbose=0)[0]

        return preds[token]

    def perplexity(self, path_to_test):

        tokenization = Tokenization(path_to_file=None,
                                    final_char=self.tokenSelector_params["final_char"],
                                    final_punc=self.tokenSelector_params["final_punc"],
                                    inter_char=self.tokenSelector_params["inter_char"],
                                    signs_to_ignore=self.tokenSelector_params["signs_to_ignore"],
                                    words_to_ignore=self.tokenSelector_params["words_to_ignore"],
                                    map_punctuation=self.tokenSelector_params["map_punctuation"],
                                    letters=self.tokenSelector_params["letters"],
                                    sign_not_syllable=self.tokenSelector_params["sign_not_syllable"],
                                    )
        tokenization.set_params_experiment(self.tokenization_params)
        max_len = self.tokenization_params["lprime"]
        test_selected = tokenization.select_tokens(path_to_test)

        sentence = []
        token_word = []
        ppl = 0
        qw = 0

        for i,token in enumerate(test_selected):
            token_word += token
            if token[-1] in [self.tokenSelector_params["final_char"], self.tokenSelector_params["final_punc"]]:
                if len(sentence) < 1:
                    sentence += token_word
                    token_word = []
                    continue

                seed = sentence
                probs_word = 1
                ## Calculo la probabilidad de la palabra
                for tok in token_word:
                    probs_word *= self.get_probability_token(tok, seed)
                    seed += [tok]

                ## sumo la probabilidad a la del resto
                ppl += np.log2(probs_word)

                sentence += token_word
                qw += 1
                token_word = []
                if len(sentence) > max_len:
                    sentence = sentence[-max_len:]

        return - ppl / qw

def sample(pred, temperature=1.0):
    pred = np.asarray(pred).astype('float64')
    pred = np.log(pred) / temperature
    exp_pred = np.exp(pred)
    pred = exp_pred / np.sum(exp_pred)
    prob = np.random.multinomial(1, pred, 1)

    return np.argmax(prob)

def raisePathNotExists(path_to_file):
    if not os.path.exists(path= path_to_file):
        raise FileNotFoundError("Path doesn't exists, '{}'".format(path_to_file))


def solution(N, A):
    counters = [0] * N
    maxCounter = 0
    for op in A:
        if op == N+1:
            counters = [maxCounter] * N
        else:
            counters[op-1] += 1
            maxCounter = max(counters[op-1], maxCounter)

    return counters


import os

import tensorflow as tf
from tensorflow import keras
import pandas as pd

from AI4Water import Model
from AI4Water.utils.datasets import load_nasdaq

class CustomModel(keras.Model):
    def train_step(self, data):
        print('custom train_step')
        # Unpack the data. Its structure depends on your model and
        # on what you pass to `fit()`.
        x, y = data

        with tf.GradientTape() as tape:
            y_pred = self(x, training=True)  # Forward pass
            # Compute the loss value
            # (the loss function is configured in `compile()`)
            loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)

        # Compute gradients
        trainable_vars = self.trainable_variables
        gradients = tape.gradient(loss, trainable_vars)
        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))
        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}

df = load_nasdaq()

model = Model(
    batch_size=32,
    lookback=1,
    lr=8.95e-5,
    data=df
)

model.KModel = CustomModel

history = model.fit(indices='random')

y, obs = model.predict()


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

dtst = pd.read_csv(r'vem amor bate n para com o DB na minha cara - Form Responses 1.csv')
dtst1 = dtst.iloc[:, :15]
# ---------------------
dtst1.iloc[:5, 2:9]
pers_data = pd.crosstab([dtst1["Sexo"], dtst1["Idade"]],
                        [dtst1["Orientação sexual"], dtst1["Cor pele"]])
sns.heatmap(pers_data, fmt="d", annot=True)
# ---------------------
sns.countplot(x='Cor pele', data=dtst1)
plt.show()

dtst1.loc[:, ["Sexo", "Idade", "Orientação sexual", "Cor pele"]].plot()
# ---------------------
test1 = pd.crosstab(dtst1['Sexo'], dtst1[("Quantidade que jogou "
                                          "League of Legends no último mês?")])

test2 = pd.crosstab(dtst1['Sexo'], dtst1[("Percebeu alguma opressão ou discriminação em "
                                          "qualquer tela neste último mês?")])
# ---------------------
tips = sns.load_dataset("tips")
tips.head()
# ---------------------
sns.heatmap(test1, fmt="d", annot=True)
plt.xticks(rotation=30)
plt.show()
sns.heatmap(test2, fmt="d", annot=True)
plt.show()


from time import sleep
from os import system
import math
import datetime

def ask_number(txt):
    try:
        global number
        number = input(txt)
        number = int(number)
    except:
        print(f">>>{number}" + " no es un numero\n")
        ask_number(txt)
    return number

def find_age():
    system('cls')
    print("""
************************************************************
PROGRAMA QUE ACEPTA LA FECHA DE NACIMIENTO Y MUESTRE LA EDAD
*************************************************************
\n""")

    date = datetime.datetime.now()
    get_day = date.day
    get_month = date.month
    get_year = date.year

    day = ask_number('Escribe tu dia de naciento: ')
    month = ask_number('Escribe tu mes de naciento: ')
    year = ask_number('Escribe el año de tu naciento: ')

    if year > get_year or day > 31 or month > 12:
        print(f'\nEs imposible que naciera el {day}/{month}/{year}')
        sleep(2)
        return find_age()
    if year == get_year and month > get_month:
        print(f'\nEs imposible que naciera el {day}/{month}/{year}')
        sleep(2)
        return find_age()
    if year == get_year and day > get_day:
        print(f'\nEs imposible que naciera el {day}/{month}/{year}')
        sleep(2)
        return find_age()

    age = get_year - year

    if month == get_month and day <= get_day and age >= 1:
        age = age
        print(f"Tu edad es: {age} años")

    elif month == get_month and day > get_day and age >= 1:
        age = age - 1
        print(f"Tu edad es: {age} años")

    elif month > get_month and age >= 1:
        age = age - 1
        print(f"Tu edad es: {age} años")

    elif month < get_month and age >= 1:
        age = age
        print(f"Tu edad es: {age} años")

    elif month < get_month and age == 0:
        age = get_month - month
        print(f"Tu edad es: {age} Mes/Meses")
    elif month == get_month and day <= get_day and age == 0:
        age = get_day - day
        print(f"Tu edad es: {age} dia/s")

    sleep(1)
    print('\nQUIERES PROBAR DE NUEVOO ? \n 1) SI \n 2) NO')
    option = ask_number('RESPUESTA: ')

    if option == 1:
        find_age()
    else:
        print('\nGRACIAS POR UTILIZARME!')

find_age()


"""
Randomized Search Example.
"""

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import RandomizedSearchCV

# Loading data
iris = load_iris()
X = iris.data[:,2:]
y = iris.target

# Splitting data in training and test set
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify = y,
                                                    random_state = 7)

# Instantiate nearest neighbors classifier
knn_clf = KNeighborsClassifier()

# Prepare parameter distribution for randomized grid search
param_dist = {'n_neighbors': list(range(3,50,1))}

# Instantiate a randomized search using 10-fold cross validation
rs = RandomizedSearchCV(knn_clf, param_dist, cv=10, n_iter=15)

# Fit the randomized grid search estimator
rs.fit(X_train, y_train)

# Print the results
print("Best parameters:", rs.best_params_)
print("\nResults overview:")
for result in zip(rs.cv_results_['params'], rs.cv_results_['mean_test_score']):
    print(result)


import random
import prompt

def welcome_user():
    name = prompt.string('May I have your name?')
    print('Hello, ', name, '!')
    print('Answer "yes" if the number is even, otherwise answer "no".')
    return name

def even_odd(number):
    if number % 2 == 0:
        return 'even'
    else:
        return 'odd'

def check_answer(name):
    i = 3
    while i > 0:
        i = i - 1
        question = random.randint(1, 1000)
        print('Question: ', question)
        answer = prompt.string('Your answer: ')
        if (even_odd(question) == 'even' and answer == 'yes') or (even_odd(question) == 'odd' and answer == 'no'):
            print('Correct!')
        else:
            if even_odd(question) == 'even':
                print("'", answer, "'", " is wrong answer ;(. Correct answer was 'yes'.")
                break
            else:
                print("'", answer, "'", " is wrong answer ;(. Correct answer was 'no'.")
                break
    else:
        print('Congratulations, ', name)


import machine, system
from defines import *

def _cb(pin):
	if disable:
		return

	position = _pins.index(pin)
	gpio = _gpios[position]
	callback = button_mappings[-1][gpio]
	if callback and callable(callback):
		callback(not pin.value())

disable = False
_gpios     = [BTN_A, BTN_B, BTN_UP, BTN_DOWN, BTN_LEFT, BTN_RIGHT]
_pins      = [
	machine.Pin(BTN_A, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
	machine.Pin(BTN_B, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
	machine.Pin(BTN_UP, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
	machine.Pin(BTN_DOWN, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
	machine.Pin(BTN_LEFT, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
	machine.Pin(BTN_RIGHT, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=200, acttime=200),
]

button_mappings = []

def init_button_mapping():
	global button_mappings
	button_mappings.append(_default_button_mapping())
	return True

def clear_button_mapping():
	global button_mappings
	if len(button_mappings) > 1:
		button_mappings = button_mappings[:-1]
	return True

def assign(gpio, action = None):
	global button_mappings
	button_mappings[-1][gpio] = action
	return True

def unassign(gpio):
	return assign(gpio, None)

def _register(gpio):
	if gpio in _gpios:
		return False
	pin = machine.Pin(gpio, machine.Pin.IN, handler=_cb, trigger=machine.Pin.IRQ_ANYEDGE, debounce=100, acttime=100)
	_gpios.append(gpio)
	_pins.append(pin)
	return True

def _default_B_action(pressed):
	if pressed:
		# Make apps reboot when B is pressed, unless they rebind it
		print('Exit by B button')
		system.reboot()

def _default_button_mapping():
	return {
		BTN_UP: None,
		BTN_DOWN: None,
		BTN_LEFT: None,
		BTN_RIGHT: None,
		BTN_A: None,
		BTN_B: _default_B_action
	}

def __disable__():
	global disable
	disable = True

def __enable__():
	global disable
	disable = False

register = assign
init_button_mapping()


# This file is part of AltCanvas.
#
# http://code.google.com/p/altcanvas
#
# AltCanvas is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# AltCanvas is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with AltCanvas.  If not, see <http://www.gnu.org/licenses/>.

import gtk
import cairo
from math import pi as PI
import libpub
from libpub.prime.widget import Widget
import libpub.prime.mask as mask
from libpub.prime import utils
from libpub.prime.utils import RGBA

WALLPAPER_PATH = libpub.IMAGE_DIR+'/altpublishr.png'

class Pad(Widget):
    (RECT,ROUNDED_RECT) = range(2)
    (PLAIN,GRAD_EXPLOSION,WALLPAPER) = range(3)

    def __init__(self,w,h,color=RGBA(0,0,0,1),texture=PLAIN,shape=RECT):
        Widget.__init__(self,w,h)
        self.surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,w,h)
        ctx = cairo.Context(self.surface)

        if texture == self.GRAD_EXPLOSION:
            BORDER = int(min(w,h)*0.25)
            border_surface = utils.draw_grad_rect(
                                inner=(BORDER/2,BORDER/2,w-BORDER,h-BORDER),
                                border=BORDER,color=color)

            ctx.set_source_surface(border_surface)
            ctx.paint()

            ctx.set_source_rgba(color.r,color.g,color.b,color.a)
            ctx.rectangle(BORDER/2,BORDER/2,w-BORDER,h-BORDER)
            ctx.fill()

        elif texture == self.PLAIN and shape == self.RECT:
            ctx.set_source_rgba(color.r,color.g,color.b,color.a)
            ctx.rectangle(0,0,w,h)
            ctx.fill()

        elif texture == self.PLAIN and shape == self.ROUNDED_RECT:
            ctx.set_source_rgba(color.r,color.g,color.b,color.a)
            utils.draw_rounded_rect(ctx, 0, 0, w, h)
            '''
            x0 = 0
            y0 = 0
            x1 = x0+w
            y1 = y0+h
            vr = int(min(w,h)/10)

            ctx.set_source_rgba(color.r,color.g,color.b,color.a)

            ctx.move_to(x0+vr,y0)
            ctx.line_to(x1-vr,y0)
            ctx.arc(x1-vr,y0+vr,vr,3*PI/2,0)
            ctx.line_to(x1,y1-vr)
            ctx.arc(x1-vr,y1-vr,vr,0,PI/2)
            ctx.line_to(x0+vr,y1)
            ctx.arc(x0+vr,y1-vr,vr,PI/2,PI)
            ctx.line_to(x0,y0+vr)
            ctx.arc(x0+vr,y0+vr,vr,PI,3*PI/2)

            ctx.fill()
            '''

        elif texture == self.WALLPAPER:
            wpSurface = cairo.ImageSurface.create_from_png(WALLPAPER_PATH)
            ctx.set_source_surface(wpSurface,0,0)
            ctx.paint()


import random
import math, numpy
import json
import time

from PySide2 import QtCore, QtGui, QtWidgets

from human import Human, Head
from robot import Robot
from midPoint import MidPoint
from regularobject import RegularObject
from irregularobject import IrregularObject
from room import Room
from interaction import Interaction

MAX_GENERATION_WAIT = 1.

class WorldGenerator(QtWidgets.QGraphicsScene):
    available_identifier = 0

    def __init__(self, data=None):
        super(WorldGenerator, self).__init__()
        self.setSceneRect(-400, -400, 800 - 2, 800 - 2)
        self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex)

        if data is None:
            self.generateRandomWorld()
        else:
            self.generateFromData(data)

    def generateFromData(self, raw_data):
        data = json.loads(raw_data)
        idMap = dict()
        self.clear()

        self.ds_identifier = int(data['identifier'].split()[0])

        self.room = Room(data['room'])
        self.addItem(self.room)

        self.humans = []
        for raw_human in data['humans']:
            human = Human.from_json(raw_human)
            self.addItem(human)
            self.humans.append(human)
            idMap[raw_human['id']] = human

        self.heads = []
        for raw_head in data['heads']:
            head = Head.from_json(raw_head)
            self.addItem(head)
            self.heads.append(head)
            idMap[raw_head['id']] = head

        self.objects = []
        for raw_object in data['objects']:
            obj = RegularObject.from_json(raw_object)
            self.addItem(obj)
            self.objects.append(obj)
            idMap[raw_object['id']] = obj

        self.interactions = []
        interactions_done = []
        for interaction_raw in data['links']:
            if not [interaction_raw[1], interaction_raw[0], interaction_raw[2]] in interactions_done:
                interactions_done.append(interaction_raw)
                human = idMap[interaction_raw[0]]
                other = idMap[interaction_raw[1]]
                interaction = Interaction(human, other)
                self.interactions.append(interaction)
                self.addItem(interaction)

        #self.irregularobjects = []
        #for raw_irregularobjects in data['irregularobjects']:
            #obj = IrregularObject.from_json(raw_irregularobjects)
            #self.addItem(obj)
            #self.irregularobjects.append(obj)
            #idMap[raw_irregularobjects['id']] = obj

        self.robot = Robot()
        self.robot.setPos(0, 0)
        self.addItem(self.robot)

    def generateRandomWorld(self):
        done = False
        self.ds_identifier = WorldGenerator.available_identifier
        WorldGenerator.available_identifier += 1
        while not done:
            try:
                self.generation_time = time.time()
                self.generate()
                done = True
                # print(time.time()-self.generation_time)
            except RuntimeError:
                pass

    @staticmethod
    def distanceTo(something):
        return int(math.sqrt(something.xPos*something.xPos + something.yPos*something.yPos))

    @staticmethod
    def angleTo(something):
        angle = int(int(180.*math.atan2(something.yPos, something.xPos)/math.pi)+90.)
        if angle > 180.: angle = -360.+angle
        return angle

    def serialize(self, score=-1):
        structure = dict()
        structure['identifier'] = str(self.ds_identifier).zfill(5) + ' A'
        structure['score'] = 0
        if score > 0:
            structure['score'] = score
        structure['robot'] = {'id': 0}

        humansList = []
        for human in self.humans:
            h = dict()
            h['id'] = human.id
            h['xPos'] = +human.xPos
            h['yPos'] = +human.yPos
            h['orientation'] = +human.angle
            h['head_orientation'] = +human.angleHead
            humansList.append(h)
        structure['humans'] = humansList

        headsList = []
        for head in self.heads:
            h = dict()
            h['id'] = head.id
            h['xPos'] = +head.xPos
            h['yPos'] = +head.yPos
            h['orientation'] = +head.angle
            headsList.append(h)
        structure['heads'] = headsList

        objectsList = []
        for object in self.objects:
            o = dict()
            o['id'] = object.id
            o['xPos'] = +object.xPos
            o['yPos'] = +object.yPos
            o['orientation'] = +object.angle
            objectsList.append(o)
        structure['objects'] = objectsList

        structure['links'] = []
        for interaction in self.interactions:
            structure['links'].append( [interaction.a.id, interaction.b.id, 'interact'] )
            if type(interaction.b) is Human:
                structure['links'].append( [interaction.b.id, interaction.a.id, 'interact'] )

        #irregularObjectsList = []
        #for object in self.irregularobjects:
            #o = dict()
            #o['id'] = object.id
            #o['xPos'] = +object.xPos
            #o['yPos'] = +object.yPos
            #o['w'] = +object.w
            #o['h'] = +object.h
            #o['orientation'] = +object.angle
            #irregularObjectsList.append(o)
        #structure['irregularobjects'] = irregularObjectsList

        structure['room'] = [ [+point.x(), point.y()] for point in self.room.poly ]

        if score >= 0:
            print(json.dumps(structure))

        return structure

    def generateHuman(self, availableId):
        human = None
        while human is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            if QtCore.qrand() % 3 == 0:
                xx = int(random.normalvariate(0, 150))
                yy = int(random.normalvariate(0, 150))
            else:
                xx = QtCore.qrand()%800-400
                yy = QtCore.qrand()%800-400

            angleHuman = (QtCore.qrand()%360)-180
            angleHead = angleHuman + random.choice([-1,1])*QtCore.qrand()%100
            human = Human(availableId, xx, yy, angleHuman, angleHead)
            if not self.room.containsPolygon(human.polygon()):
                human = None
        return human

    def generateComplementaryHuman(self, human, availableId):
        a = math.pi*human.angle/180.
        dist = float(QtCore.qrand()%300+50)
        human2 = None
        while human2 is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            xPos = human.xPos+dist*math.sin(a)
            yPos = human.yPos-dist*math.cos(a)
            human2 = Human(availableId, xPos, yPos, human.angle+180)
            if not self.room.containsPolygon(human2.polygon()):
                dist -= 5
                if dist < 20:
                    human.setAngle(human.angle+180)
                    a = math.pi*human.angle/180.
                    dist = float(QtCore.qrand()%300+50)
                human2 = None
        return human2

    #def generateHumanHead(self, human):
        #head = None
        #while head is None:
            ##print ("human.angle", human.angle)
            #angle = human.angle + random.choice([-1,1])*QtCore.qrand()%100
            #if angle > 180.: angle = -360. + angle
            #if angle < -180.: angle = angle + 360
            #head = Head(human.id, human.xPos, human.yPos, angle)
            ##if -180 <= a <= 180:
        #return head

    def generateComplementaryObject(self, human, availableId):
        a = math.pi*human.angle/180.
        dist = float(QtCore.qrand()%250+50)
        obj = None
        while obj is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            xPos = human.xPos+dist*math.sin(a)
            yPos = human.yPos-dist*math.cos(a)
            obj = RegularObject(availableId, xPos, yPos, (human.angle+180)%360)
            if not self.room.containsPolygon(obj.polygon()):
                dist -= 5
                if dist <= 5:
                    obj.setAngle(human.angle+180)
                    a = math.pi*human.angle/180.
                    dist = float(QtCore.qrand()%300+50)
                obj = None
        return obj

    def generateInteractuatorHuman(self, human, availableId):
        a = math.pi*human.angle/180. #a radianes
        dist = float(QtCore.qrand()%300+50)
        human2 = None
        while human2 is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            xPos = human.xPos+dist*math.sin(a)
            yPos = human.yPos-dist*math.cos(a)
            l = [1,-1]
            option = random.choice (l)
            angle = human.angle+180 + (option*QtCore.qrand()%25)
            # print('angle human2:', angle)
            if angle > 180.: angle = -360. + angle
            # print('angle human2 normalize:', angle)
            angleHead = angle + random.choice([-1,1])*QtCore.qrand()%100
            human2 = Human(availableId, xPos, yPos, angle,angleHead)
            if not self.room.containsPolygon(human2.polygon()):
                dist -= 5
                if dist < 20:
                     human.setAngle(human.angle+180)
                     a = math.pi*human.angle/180.
                     dist = float(QtCore.qrand()%300+50)
                human2 = None
        return human2

    def generateObject(self, availableId):
        object = None
        while object is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            if QtCore.qrand() % 3 == 0:
                xx = int(random.normalvariate(0, 150))
                yy = int(random.normalvariate(0, 150))
            else:
                xx = QtCore.qrand()%800-400
                yy = QtCore.qrand()%800-400
            object = RegularObject(availableId, xx, yy, (QtCore.qrand()%360)-180)
            if not self.room.containsPolygon(object.polygon()):
                object = None

        return object

    def generateIrregularObject(self, availableId):
        object = None
        while object is None:
            if time.time() - self.generation_time > MAX_GENERATION_WAIT:
                raise RuntimeError('MAX_GENERATION_ATTEMPTS')
            if QtCore.qrand() % 3 == 0:
                xx = int(random.normalvariate(0, 150))
                yy = int(random.normalvariate(0, 150))
                ww = int(random.normalvariate(20, 50))
                hh = int(random.normalvariate(20, 50))
            else:
                xx = QtCore.qrand()%800-400
                yy = QtCore.qrand()%800-400
                ww = QtCore.qrand()%800/4-400/4
                hh = QtCore.qrand()%800/4-400/4
            if (ww>10 and hh>10):
                object = IrregularObject(availableId, xx, yy, ww, hh, (QtCore.qrand()%360)-180)
            if object is not None:
                if not self.room.containsPolygon(object.polygon()):
                    object = None

        return object

    def generate(self):
        regenerateScene = True
        while regenerateScene:

            availableId = 1
            regenerateScene = False
            self.clear()
            self.humans = []
            self.heads = []
            self.objects = []
            self.interactions = []
            #self.irregularobjects =[]

            self.room = Room()
            self.addItem(self.room)

            #ONLY TWO HUMAN BEINGS
            human = self.generateHuman(availableId)
            head = Head (human.id, human.xPos, human.yPos, human.angleHead )
            #head = self.generateHumanHead(human)
            availableId += 1
            self.addItem(human)
            self.humans.append(human)

            #heads
            self.addItem(head)
            #self.heads.append(head)

            human2 = None
            while human2 is None:
                if QtCore.qrand()%2 == 0:
                    human2 = self.generateInteractuatorHuman(human, availableId)
                    #CHECK necesito crear interaccion?
                    # interaction = Interaction(human, human2)
                    # self.interactions.append(interaction)
                    # self.addItem(interaction)
                else:
                    human2 = self.generateHuman(availableId)
                if human.polygon().intersects(human2.polygon()):
                    human2=None

            head2 = Head (human2.id, human2.xPos, human2.yPos, human2.angleHead )
            #head2 = self.generateHumanHead(human2)
            #print ("-----")
            availableId += 1
            self.addItem(human2)
            self.humans.append(human2)
            #heads
            self.addItem(head2)
            #self.heads.append(head2)

            # Calculamos el punto medio de los dos humanos. Adri
            x1 = human.xPos
            y1 = human.yPos
            x2 = human2.xPos
            y2 = human2.yPos
            x_pm = (x1 + x2)/2
            y_pm = (y1 + y2)/2
            punto_medio = QtCore.QPointF(x_pm, y_pm) # Coordenada x e y.
            punto_human = QtCore.QPointF(x1, y1) # Coordenada humano 1
            punto_human2 = QtCore.QPointF(x2, y2) # Coordenada humano 2.

            a = numpy.array((x1 ,y1))
            b = numpy.array((x2, y2))
            dist = numpy.linalg.norm(a-b)

            self.midPoint = MidPoint()
            self.midPoint.setHumansPoints(punto_human,punto_human2)
            self.midPoint.setMidPoint(punto_medio)
            self.midPoint.setDist(dist)
            self.addItem(self.midPoint)

            #genero objetos  regulares
            # objectCount = int(abs(random.normalvariate(1, 4))) % 5
            # #print ("objectCount",objectCount)
            # if objectCount == 0:
            #     objectCount = QtCore.qrand() % 3
            # for i in range(objectCount):
            #     # print (i)
            #     object = self.generateObject(availableId)
            #     #Chequeo sino intersecta con otro objeto ya creado
            #     if any (object.polygon().intersects(x.polygon()) for x in self.objects):
            #         continue
            #     #check is colide with human beings
            #     if any (object.polygon().intersects(x.polygon()) for x in self.humans):
            #         continue

            #     availableId += 1
            #     self.addItem(object)
            #     self.objects.append(object)

            #genero objetos IRREGULARES
            #objectCount = int(abs(random.normalvariate(1, 4))) % 15
            ## print ("irregular objects",objectCount)
            #if objectCount == 0:
                #objectCount = QtCore.qrand() % 3

            #for i in range(objectCount):
                ## print (i)
                #object = self.generateIrregularObject(availableId)
                ###check if intersect with regular IRREGULARobjects
                #if any (object.polygon().intersects(x.polygon()) for x in self.irregularobjects):
                    #continue
                ##check if intersect with humans
                #if any (object.polygon().intersects(x.polygon()) for x in self.humans):
                    #continue
                ##check if intersect with regular objects
                #if any (object.polygon().intersects(x.polygon()) for x in self.objects):
                    #continue

                #availableId += 1
                #self.addItem(object)
                #self.irregularobjects.append(object)

            #print ("----Sel.irregularobjets: len", len(self.irregularobjects))
            #print ("----Self.objects: len", len(self.objects))
            self.robot = Robot()
            self.robot.setPos(0, 0)
            self.addItem(self.robot)

        #self.text = 'Humans:' + str(len(self.humans)) + ' ' + 'Objects:' + str(len(self.objects))+ ' ' + 'Irregular Objects:' + str(len(self.irregularobjects))


#!/usr/bin/env python
# ~*~ encoding: utf-8 ~*~
"""setup.py for affirm addresses."""

# import built-in
from __future__ import absolute_import
import os

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))

def read_file(file_name):
    file_path = os.path.join(here, file_name)
    return open(file_path, encoding='utf-8').read().strip()

setup(
    name='eks-rolling-update',
    version='1.0.0',
    description='EKS Rolling Update is a utility for updating the launch configuration or template of worker nodes in an EKS cluster.',
    long_description=read_file('README.md'),
    author='Craig Huber, Nicolas Bélanger, Sam Weston & contributors',
    author_email='ch@hellofresh.com',
    maintainer='Craig Huber & contributors',
    maintainer_email='ch@hellofresh.com',
    url='https://github.com/gregsterin/eks-rolling-update',
    license_file='LICENSE',
    licence='Apache License, Version 2.0',
    packages=find_packages(exclude=["tests"]),
    include_package_data=True,
    zip_safe=False,
    install_requires=[
        "boto3>=1.9.246",
        "kubernetes>=10.0.1",
        "python-dotenv>=0.10.2"
    ],
    python_requires = ">=3.7",
    entry_points={
        # -*- Entry points -*-
        'console_scripts': ['eks_rolling_update.py=eksrollup.cli:main']
    },
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8"
    ],
)


class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        graph = defaultdict()
        for index, (source, destination) in enumerate(equations):
            if source not in graph:
                graph[source] = defaultdict(int)
            graph[source][destination] = float(values[index])
            if destination not in graph:
                graph[destination] = defaultdict(int)
            graph[destination][source] = float(1 / values[index])
        def dfs(source, destination, currentValue, visitedSet):
            nonlocal graph
            if source in visitedSet:
                return
            visitedSet.add(source)
            if source == destination:
                self.currentResult = currentValue
                return
            for neighbour, value in graph[source].items():
                dfs(neighbour, destination, currentValue * value, visitedSet)
        result = []
        for source, destination in queries:
            if source not in graph or destination not in graph:
                result.append(-1.0)
            elif source == destination:
                result.append(1.0)
            elif destination in graph[source]:
                result.append(graph[source][destination])
            else:
                self.currentResult = -1.0
                dfs(source, destination, 1.0, set())
                result.append(self.currentResult)
        return result

LeetCode/Google Interview Questions/Evaluate Division.py


# coding: UTF-8
import json
import re
import urllib

def results(fields, original_query):
  twq = fields['~twitterquery']
  quotedquery = urllib.quote_plus(twq.encode('utf_8'))

  reptn = r".*(?=\s)"
  rechk = re.match(reptn , original_query)
  if rechk:
    searchtype = rechk.group()

  if searchtype.startswith("tw"):
    titlestr = u"'{0}'をTwitterで検索".format(twq)
    searchurl = "https://twitter.com/search?q={0}".format(quotedquery)
    useragent = "Mozilla/5.0 (Nintendo 3DS; U; ; ja) Version/1.7498.JP"
  elif searchtype.startswith("ytw"):
  	titlestr = u"'{0}'をYahoo!リアルタイム検索".format(twq)
  	searchurl = "http://realtime.search.yahoo.co.jp/search?p={0}".format(quotedquery)
  	useragent = "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A365 Safari/600.1.4P"
  elif searchtype.startswith("tvch"):
  	titlestr = u"{0}chのテレビ放送のツイート（東京）".format(twq)
  	searchurl = "http://realtime.search.yahoo.co.jp/search?lz=1&ei=UTF-8&rkf=1&ch={0}".format(quotedquery)
  	useragent = "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12A365 Safari/600.1.4P"

  return {
  	"title": titlestr,
  	"run_args": [searchurl],
  	"html": (u"<script>"
		u"var url = '{0}';".format(searchurl)
		+ u"setTimeout(function(){window.location=url},800)"
		+ u"</script>"),
	"webview_user_agent": useragent,
	"webview_links_open_in_browser": True
  }

def run(link):
  import os
  os.system('open "{0}"'.format(link).encode('utf_8'))


'''
  Simple Flask app
'''
import json
import os
from pathlib import Path
import flask

# Templates
# In a proper Flask application all these templates should be in indepent files
STYLE = """
body {
  background-color: silver;
  font-family: "Helvetica Neue",Helvetica,"Liberation Sans",Arial,sans-serif;
  font-size: 14px;
  padding: 10%;
}
img {
  width: 90%;
}
"""

PAGE = """
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <title>{{ student }}</title>

This is the photo gallery from {{ student }}

{% for kitten in kittens %}

 {{ kitten }}

    {% endfor %}

"""

# Default configuration
defaults = {
    "student": "??????",
    "debug": False}

config = {}

# Flask app object
app = flask.Flask(__name__,
                  static_url_path='/static',
                  static_folder='/static')

# Routes
@app.route("/", methods=['GET'])
def home():
    '''
      Hello page, shows photos in the /static folder
    '''
    kittens = Path('/static/').rglob('*.jpg')
    return flask.render_template_string(
        PAGE,
        student=config["student"],
        kittens=kittens)

# Entry function
def main():
    '''
      Main entry function
    '''

    # Load student name from file
    global config
    try:
        with open('/etc/flask/config.json') as custom_config_file:
            config = json.load(custom_config_file)
    except FileNotFoundError:
        config = defaults

    try:
        if os.environ['DEBUG']:
            config["debug"] = True
    except KeyError:
        pass

    print('Configuration:')
    print(json.dumps(config))

    app.run(debug=config["debug"],
            port=8080,
            host='0.0.0.0')

if __name__ == "__main__":
    main()


#file = open('rosalind_ini5.txt', 'r')
#text = file.read()
#text = text.split('\n')
#text = ['Bravely bold Sir Robin rode forth from Camelot',
#'Yes, brave Sir Robin turned about',
#'He was not afraid to die, O brave Sir Robin',
#'And gallantly he chickened out',
#'He was not at all afraid to be killed in nasty ways',
#'Bravely talking to his feet',
#'Brave, brave, brave, brave Sir Robin',
#'He beat a very brave retreat']
inp = []
with open('rosalind_ini5.txt', 'r') as g:
	text = g.read()
	text = text.split('\n')
	for i in range(1, len(text)):
		if i % 2 == 0:
			inp.append(text[i-1])

print('\n'.join(inp))


#이미지 Gradient를 이용한 경계선 찾기
#OpenCV 경계선 찾기 : Sobel, Scharr, Laplacian
#Sobel, Scharr 미분 : Sobel오퍼레이터는 가우스스무딩과 미분 연산을 결합한 형태
#cv2.Sobel(src,ddepth,dx,dy,ksize)
#src : Sobel 미분을 적용할 원본 이미지
#ddepth : 결과 이미지 데이터타입
#dx, dy : x방향 y방향으로의 미분 차수
#ksize : 확장 Sobel커널의 크기 (1,3,5,7)중 선택 / -1로 설정하면 3x3 Scharr필터를 적용하게 됨

import numpy as np
import cv2
import matplotlib.pyplot as plt
'''
    미분 : 어느 한 지점에서 변화율을 구하는 수학적 방법
    x방향으로 미분한다 : x방향을 따라 값의 변화가 있다면 변화율이 감지된다 = 미분값이 존재한다
    x방향으로 변화율은 세로줄, y방향으로 변화율은 가로줄

    *주의
    Sobel알고리즘은 이미지가 검정에서 흰색으로 변할때 양수값을 취하고,
                 이미지가 흰색에서 검정색으로 변할때 음수값을 취한다
    만약 데이터 타입을 양수만 취급하는 np.unit8 또는 cv2.CV_8U로 지정하면
    흰색에서 검정색으로 변할때 취한 음수값을 모두 0으로 만들어버려 경계를 찾지 못함
    참고 np.absolute()

    cv2.Sobel()함수를 사용할떄, 인자로 입력되는 데이터 타입은 결과물에 영향을 미치는 요소
'''
def grad():
    img = cv2.imread('image.png',cv2.IMREAD_GRAYSCALE)
    #결과 데이터 타입 cv2.CV_64F로 정의
    #Laplacian은 x방향 편미분 결과와 y방향 편미분 결과를 더한 형태의 결과 (가로 세로선 모두 나타남 )
    #SobelX는 세로선이 두드러지게, SobelY는 가로선이 두드러지게
    laplacian = cv2.Laplacian(img,cv2.CV_64F)
    sobelx = cv2.Sobel(img,cv2.CV_64F, 1, 0, ksize=3)
    sobely = cv2.Sobel(img,cv2.CV_64F, 0, 1, ksize=3)

    plt.subplot(2,2,1), plt.imshow(img, cmap='gray')
    plt.title('original'), plt.xticks([]),plt.yticks([])

    plt.subplot(2,2,2), plt.imshow(laplacian, cmap='gray')
    plt.title('Laplacian'),plt.xticks([]), plt.yticks([])

    plt.subplot(2,2,4), plt.imshow(sobely, cmap='gray')
    plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])

    plt.show()

grad()


from datetime import date
from kivy.app import App
from kivy.uix.button import Button

class MainApplication(App):
    def build(self):
        button = Button(text='Weclome to my app!',
                        size_hint=(0.5, 0.5),
                        pos_hint={'center_x': 0.5, 'center_y': 0.5})
        # calling button bind and link to on_press_button event
        button.bind(on_press=self.on_press_button)

        return button

    def on_press_button(self, instance):
        date_now = str(date.today())
        print(f'You pressed the button!\non the date {date_now}')

        # Prints message to standard streams/ stdout (command line)
if __name__ == '__main__':
    app = MainApplication()
    app.run()


# coding:utf-8
import time  #时间
import pywifi  #破解wifi
from pywifi import const  #引用一些定义
from asyncio.tasks import sleep
import sys
import time

m=[chr(x) for x in range(ord('a'), ord('z') + 1)]

wifi = pywifi.PyWiFi()  # 创建一个wifi对象
ifaces = wifi.interfaces()[0]  # 取第一个无限网卡
print(ifaces.name())  # 输出无线网卡名称
def deswifi(findStr):
   # wifi = pywifi.PyWiFi()  # 创建一个wifi对象
   # ifaces = wifi.interfaces()[0]  # 取第一个无限网卡
   # print(ifaces.name())  # 输出无线网卡名称
   # ifaces.disconnect()  # 断开网卡连接
    #time.sleep(3)  # 缓冲3秒

    profile = pywifi.Profile()  # 配置文件
    profile.ssid = "acer"  # wifi名称
    profile.auth = const.AUTH_ALG_OPEN  # 需要密码
    profile.akm.append(const.AKM_TYPE_WPA2PSK)  # 加密类型
    profile.cipher = const.CIPHER_TYPE_CCMP  # 加密单元
    profile.key = findStr  # 密码
   # ifaces.remove_all_network_profiles()  # 删除其他配置文件
    tmp_profile = ifaces.add_network_profile(profile)  # 加载配置文件

    ifaces.connect(tmp_profile)  # 连接
    time.sleep(0.5)  # 尝试10秒能否成功连接
    isok = True
    if ifaces.status() == const.IFACE_CONNECTED:
        print("成功连接"+findStr)
    else:
        print("失败"+findStr)
   # ifaces.disconnect()  # 断开连接
   # time.sleep(1)
    return isok
str='88888888'
deswifi(str)

def bies():
    wifi=pywifi.PyWiFi()#创建一个无限对象
    ifaces=wifi.interfaces()[0]#取一个无限网卡
    ifaces.scan()#扫描
    bessis=ifaces.scan_results()
    print(bessis)
    for data in bessis:
        print(data.ssid)#输出wifi名称
#bies()

def bies():
    wifi = pywifi.PyWiFi()
    iface = wifi.interfaces()[0]
    iface.scan()  # 扫描
    bessis = iface.scan_results()
    print('bessis=',bessis)
    list = []
    for data in bessis:

        list.append((data.ssid, data.signal))
    return len(list), sorted(list, key=lambda st: st[1], reverse=True)
#bies()


from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APITestCase, APIClient
from rest_framework.views import status
from .models import Interviewer, Candidate, TimeSlot_Candidate, TimeSlot_Interviewer
from .serializers import InterviewerSerializer, CandidateSerializer

START_DATE = '2018-08-20'
END_DATE = '2018-08-24'

# tests for views
class BaseViewTest(APITestCase):
    client = APIClient()

    @staticmethod
    def create_interviewer(first_name = "", last_name= "", email = ""):

        if first_name and last_name and email:
            Interviewer.objects.create(first_name = first_name, last_name = last_name, email = email)

    @staticmethod
    def create_candidate(first_name = "", last_name= "", email = ""):

        if first_name and last_name and email:
            Candidate.objects.create(first_name = first_name, last_name = last_name, email = email)

    @staticmethod
    def create_interviewer_timeslot(interviewer = "", start_date= "", end_date = ""):

        if interviewer and start_date and end_date:
            TimeSlot_Interviewer.objects.create(interviewer = interviewer, start_date = start_date, end_date = end_date)

    @staticmethod
    def create_candidate_timeslot(candidate = "", start_date= "", end_date = ""):

        if candidate and start_date and end_date:
            TimeSlot_Candidate.objects.create(candidate = candidate, start_date = start_date, end_date = end_date)

    def setUp(self):
        # add test data
        self.create_interviewer("Anton", "Ivanov", "an@gmail.com")
        self.create_interviewer("Peter", "Molodec", "pe@gmail.com")
        self.create_interviewer("Sergej", "Muller", "se@gmail.com")
        self.create_interviewer("Laura", "Peter", "la@gmail.com")

        self.create_candidate("Mike", "Trinogiy", "mi@gmail.com")
        self.create_candidate("Peter", "Jackson", "ajck@gmail.com")
        self.create_candidate("Ukrop", "Volosyans", "uik@gmail.com")
        self.create_candidate("Kat", "Man", "kat@gmail.com")

class GetAllInterviewersTest(BaseViewTest):

    def test_get_all_interviewers(self):

        # hit the API endpoint
        response = self.client.get(
            reverse("interviewers-all", kwargs={})
        )

        # fetch the data from db
        expected = Interviewer.objects.all()
        serialized = InterviewerSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

class GetAllCandidatesTest(BaseViewTest):

    def test_get_all_candidates(self):

        # hit the API endpoint
        response = self.client.get(
            reverse("candidates-all", kwargs={})
        )
        # fetch the data from db
        expected = Candidate.objects.all()
        serialized = CandidateSerializer(expected, many=True)
        self.assertEqual(response.data, serialized.data)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

class AddInterviwewersAddCandidateAddTimeslotsCheckMatchesTests(APITestCase):
    def test_create_timeslots_and_check(self):

        base_url = 'http://127.0.0.1:8000/api/'
        interviewer_url = reverse("interviewers-all", kwargs={})
        candidate_url = reverse("candidates-all", kwargs={})

        data_interviewer_1 = []
        data_interviewer_2 = []
        data_candidate = []

        #Add interviewers timeslots
        interviewer_1 = {
            "first_name": "Peter",
            "last_name": "Parker",
            "email": "spider@gmail.com"
        }

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-20 09:00",
            "end_date": "2018-08-20 16:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-21T09:10:00",
            "end_date": "2018-08-21T10:10:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-21T13:30:00",
            "end_date": "2018-08-21T14:00:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-21T15:00:00",
            "end_date": "2018-08-21T16:00:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-22T09:30:00",
            "end_date": "2018-08-22T10:30:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-22T11:30:00",
            "end_date": "2018-08-22T12:30:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-22T14:30:00",
            "end_date": "2018-08-22T16:00:00"
        })

        data_interviewer_1.append({
            "interviewer": "1",
            "start_date": "2018-08-23T09:00:00",
            "end_date": "2018-08-23T16:00:00"
        })

        interviewer_2 = {
            "first_name": "Johnson",
            "last_name": "James",
            "email": "whereisphotospider@gmail.com"
        }

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-20T09:30:00",
            "end_date": "2018-08-20T10:30:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-20T11:30:00",
            "end_date": "2018-08-20T13:30:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-20T14:30:00",
            "end_date": "2018-08-20T15:30:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-21T09:30:00",
            "end_date": "2018-08-21T10:30:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-21T13:00:00",
            "end_date": "2018-08-21T14:00:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-23T09:00:00",
            "end_date": "2018-08-23T10:00:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-23T11:00:00",
            "end_date": "2018-08-23T12:00:00"
        })

        data_interviewer_2.append({
            "interviewer": '2',
            "start_date": "2018-08-23T13:00:00",
            "end_date": "2018-08-23T14:00:00"
        })

        candidate = {
            "first_name": "Tom",
            "last_name": "Hardy",
            "email": "tom@gmail.com"
        }

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-20T09:00:00",
            "end_date": "2018-08-20T12:00:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-20T13:15:00",
            "end_date": "2018-08-20T15:15:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-21T09:00:00",
            "end_date": "2018-08-21T11:00:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-21T12:00:00",
            "end_date": "2018-08-21T14:30:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-21T14:45:00",
            "end_date": "2018-08-21T16:00:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-22T10:00:00",
            "end_date": "2018-08-22T12:00:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-22T14:00:00",
            "end_date": "2018-08-22T16:00:00"
        })

        data_candidate.append({
            "candidate": '1',
            "start_date": "2018-08-23T09:00:00",
            "end_date": "2018-08-23T16:00:00"
        })

        #test interviwewers are added
        response = self.client.post(interviewer_url, interviewer_1, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        response = self.client.post(interviewer_url, interviewer_2, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        #test candidate is added
        response = self.client.post(candidate_url, candidate, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        #check interviewers timeslots are added
        for data_el in data_interviewer_1:
            response = self.client.post(base_url + 'timeslots/interviewers/1', data_el, format='json')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        for data_el in data_interviewer_2:
            response = self.client.post(base_url + 'timeslots/interviewers/2', data_el, format='json')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        #check candidates timeslots are added
        for data_el in data_candidate:
            response = self.client.post(base_url + 'timeslots/candidates/1', data_el, format='json')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        #check timeslots in that case = 15
        response = self.client.get(base_url +
        'timeslots/candidates/1/interviewers/?ids=1,2&start_date=' + START_DATE + '&end_date=' + END_DATE +'&smcheck=0')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 15)

        #check timeslots simultaneously for given interviewers = 6
        response = self.client.get(base_url +
        'timeslots/candidates/1/interviewers/?ids=1,2&start_date=' + START_DATE + '&end_date=' + END_DATE +'&smcheck=1')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(len(response.data), 6)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#   Author: Yoge
#   Time: 2018/06/14

class Solution(object):
    def numJewelsInStones(self, J, S):
        """
        :type J: str
        :type S: str
        :rtype: int
        """
        i = 0
        for s in S:
            if s in J:
                i += 1
        return i


from django.shortcuts import render
from django.http import HttpResponse

import json
import time

from rest.models import UserProgress

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def update(req):

	try:
		if "update" in req.POST:
			data = json.loads(req.POST["update"])
			if(	"key" not in data["update"] or
				"assignment" not in data["update"] or
				"progress" not in data["update"] ):
				raise KeyError

			#Check if a progress row already exists for this user+assignment pair
			prog = UserProgress.objects.filter(key=data["update"]["key"]).filter(assignment=data["update"]["assignment"])

			if(len(prog)==0):
				#No progress has been reported so far, so create a new row
				new_prog = UserProgress(
					key = data["update"]["key"],
					assignment = data["update"]["assignment"],
					progress = data["update"]["progress"]
				)
				new_prog.save()
			else:
				prog[0].progress = data["update"]["progress"]
				prog[0].save()

			return HttpResponse(json.dumps({"success": True}), status=200, content_type="application/json")

	except:
		pass

	return HttpResponse(json.dumps({"success": False}), status=400, content_type="application/json")

def histogram(req, assignment):

	#Number of histogram bars
	step_size = 5

	if(assignment is not None and len(assignment) >= 1):

		histo = []
		for x in range(step_size):
			histo.append(0)

		progs = UserProgress.objects.filter(assignment=assignment)
		for p in progs:
			histo[p.progress/(100/step_size)] += 1

		return HttpResponse(json.dumps({"success":True, "steps": step_size, "histogram": histo}), status=200, content_type="application/json")

	return HttpResponse(json.dumps({"success": False}), status=400, content_type="application/json")


# -*- coding: utf-8 -*-
"""
Created on Sun Nov  4 20:29:34 2018

@author: liyang
"""

import numpy as np  # 引入numpy
np.random.seed(314)
N=100
alpha_real=2.5
beta_real=[0.9,1.5]
eps_real=np.random.normal(0,0.5,size=N)
X=np.array([np.random.normal(i,j,N) for i,j in zip([10,2],[1,1.5])])
X_mean=X.mean(axis=1,keepdims=True)
X_centered=X-X_mean
y=alpha_real+np.dot(beta_real,X)+eps_real

import matplotlib.pyplot as plt
def scatter_plot(x,y):
    plt.figure(figsize=(10,10))
    for idx,x_i in enumerate(x):
        plt.subplot(2,2,idx+1)
        plt.scatter(x_i,y)
        plt.xlabel('$x_{}$'.format(idx),fontsize=16)
        plt.ylabel('$y$',rotation=0,fontsize=16)
    plt.subplot(2,2,idx+2)
    plt.scatter(x[0],x[1])
    plt.xlabel('$x_{}$'.format(idx-1),fontsize=16)
    plt.ylabel('$x_{}$'.format(idx),rotation=0,fontsize=16)
scatter_plot(X_centered,y)


import KratosMultiphysics
import KratosMultiphysics.RANSApplication

from KratosMultiphysics.RANSApplication.evm_k_epsilon_configuration import TurbulenceKEpsilonConfiguration

def Factory(model_part, settings):
    if (not isinstance(settings, KratosMultiphysics.Parameters)):
        raise Exception(
            "expected input shall be a Parameters object, encapsulating a json string"
        )
    if (not isinstance(model_part, KratosMultiphysics.ModelPart)):
        raise Exception("expected input shall be a Model object")
    turbulence_models_list = ["k_epsilon"]

    model_type = settings["model_type"].GetString()
    if not model_type in turbulence_models_list:
        msg = "Unknown turbulence \"model_type\" name : \"" + model_type
        msg += "\".\nSupported \"model_type\" names:"
        msg += "\n\t".join(turbulence_models_list)
        raise Exception(msg)

    if model_type == "k_epsilon":
        turbulence_model = TurbulenceKEpsilonConfiguration(model_part, settings)
        return turbulence_model