debug_flag=True

import base64
import hmac
import secrets
import time
import traceback

import flask
from Application.Api.UserContext import UserContext

from Application.Util.ParamsBinder import bind_optional_params, bind_params
from Application.Api.ApiError import ApiError
from Application.App import App
from Crypto.Cipher import AES
import hashlib

#def make_audio_urls(audios:list):# optimize for many audios to avoid instantiation of AES multiple times
#    pass
AUDIO_URL_LIFETIME=1200

def check_audio_url(ip:str,url:str):
    key=bytes.fromhex(App.key)
    raw=b''
    url_i=url.replace('~','=')
    try:
        raw=base64.urlsafe_b64decode(url_i)
        if raw==b'':return False,'Invalid URL'
    except:
        return False,'Invalid URL'
    if len(raw)<(16+32+8):
        return False,'Invalid URL'
    nonce=raw[:16]
    mac=raw[16:16+32]
    b=raw[16+32:]
    cipher=AES.new(key,mode=AES.MODE_EAX,nonce=nonce)
    raw=cipher.decrypt(b)
    _mac=hmac.new(key,msg=nonce+b,digestmod='SHA256')
    pack_id=raw[:4]
    expires=raw[4:8]
    data=raw[8:]
    if not hmac.compare_digest(mac,_mac.digest()):
        return False,'Signature invalid'
    try:
        _ip,exp,_url='.'.join([str(x) for x in pack_id]),int.from_bytes(expires,'big'),base64.urlsafe_b64encode(data).decode().replace('=','')
        if _ip!=ip:
            return False,"Invalid ip"
        if exp<int(time.time()):
            return False,'URL Expired'
        return True,_url
    except:
        print(traceback.format_exc())
        return False,'Invalid URL'

def make_audio_url(ip:str,s:bytes,owner_id:int,audio_id:int,data_url:str):
    key=bytes.fromhex(App.key)
    #action_hashes=[hmac.new(key,msg="{}_{}_{}_{}".format(act,owner_id,audio_id,s.hex()).encode('utf-8'),digestmod='sha256').hexdigest() for act in actions]
    nonce=secrets.token_bytes(16)
    cipher=AES.new(key=key,mode=AES.MODE_EAX,nonce=nonce)
    data_raw=base64.urlsafe_b64decode(data_url)
    pack_ip=bytes([int(x) for x in ip.split('.')])
    ts=int(time.time()+AUDIO_URL_LIFETIME)
    expires=ts.to_bytes(4,'big')
    b=cipher.encrypt(pack_ip+expires+data_raw)
    mac=hmac.new(key,msg=nonce+b,digestmod="SHA256").digest()
    raw=nonce+mac+b
    return base64.urlsafe_b64encode(raw).decode().replace('=','~'),ts
def check_audio_hash(h:str,s:bytes,owner_id:int,audio_id:int):
    key=bytes.fromhex(App.key)
    exp,_h=h.split('_')
    sig=hmac.new(key,msg="ts={};id={}_{},s={};".format(expires,owner_id,audio_id,s.hex()).encode('utf-8'),digestmod='sha256').hexdigest()
    return hmac.compare_digest(_h,sig)

def make_audio_hash(s:bytes,owner_id:int,audio_id:int):
    key=bytes.fromhex(App.key)
    expires=int(time.time()+AUDIO_URL_LIFETIME)
    h="{}_{}".format(expires,hmac.new(key,msg="ts={};id={}_{},s={};".format(expires,owner_id,audio_id,s.hex()).encode('utf-8'),digestmod='sha256').hexdigest())
    return h

class Audios():
    def start_playback(args,user_context:UserContext):
        bind_params(args,{
            'id':str,
            'hash':str
            })
        owner_id,audio_id=args['id'].split('_')
        data=None
        with App.db.make_connection(False,20) as cur:
            cur.execute("""
            SELECT data_url
            FROM audios
            WHERE owner_id=? AND audio_id=?
            """,[int(owner_id),int(audio_id)])
            data=cur.fetchone()
        if not data:return {}
        data_url=data[0]
        s=user_context.session_id.binary
        url,expires=make_audio_url(str(flask.request.remote_addr),s,int(owner_id),int(audio_id),data_url)
        return {
        'url':'http://cdn.notvk.com/audios/'+url+'/128.mp3',
        'expires':expires
        }

    def search(args,user_context:UserContext):
        bind_params(args,{
            'q':str,
            'count':int,
            'offset':int,
        })
        bind_optional_params(args,{
            'name':str,
            'artist':str,
            'owner_id':int
        })
        data=[]
        audios=[]
        s=user_context.session_id.binary
        q=str(args['q']).strip()
        if len(q.strip())==0:
            return []
        count=args['count']
        offset=args['offset']
        where=''
        #_args=[q,'%{}%'.format(q),'%{}%'.format(q)]
        _args=[q]
        if 'owner_id' in args:
            owner_id=args['owner_id']
            where="owner_id=? AND"
            _args.append(owner_id)
        _args.append(count)
        _args.append(offset)
        #
        """
            WITH tempvar AS (SELECT ? AS q)
		    SELECT audios.id,audios.owner_id,audios.audio_id,audios.data_url,audios.duration,audios.artist,audios.name,
			instr(lower(audios.name),tempvar.q) AS npos,
			instr(lower(audios.artist),tempvar.q) AS apos
            FROM audios,tempvar
            WHERE {}  ( npos OR apos)
            ORDER BY MIN(npos,apos))
            LIMIT ?
            OFFSET ?
            """
        #
        with App.db.make_connection(False,20) as cur:
            cur.execute("""
            WITH tempvar AS (SELECT lower(?) AS q)
		    SELECT audios.id,audios.owner_id,audios.audio_id,audios.data_url,audios.duration,audios.artist,audios.name,audios.is_official,audios.thumbnail,audios.text,audios.explicit,audios.genre,
			instr(lower(audios.name),tempvar.q) AS npos,
			instr(lower(audios.artist),tempvar.q) AS apos
            FROM audios,tempvar
            WHERE   ( npos+apos)!=0
            ORDER BY  ( SELECT CASE WHEN npos==0 THEN apos WHEN apos==0 THEN npos ELSE MIN(apos,npos) END u)
            LIMIT ?
            OFFSET ?
            """.format(where),_args)
            data=cur.fetchall()
        if not data:
            return []
        for x in data:
            i,owner_id,audio_id,data_url,duration,artist,name,is_official,thumbnail,text,explicit,genre,unused1,unused2=x
            url,expires=make_audio_url(str(flask.request.remote_addr),s,int(owner_id),int(audio_id),data_url)
            audios.append({
                'duration':duration,
                'name':name,
                'artist':artist,
                'hash':make_audio_hash(s,owner_id,audio_id),
                'id':"{}_{}".format(owner_id,audio_id),
                'url':'http://cdn.notvk.com/audios/'+url+'/128.mp3',
                'expires':expires,
                'is_official':bool(is_official),
                'thumbnail':thumbnail,
                'text':text,
                'explicit':bool(explicit),
                'genre':genre
            })
        return audios
    def get(args,user_context:UserContext):
        bind_params(args,{
            'owner_id':int,
            'count':int,
            'offset':int
        })

        data=[]
        audios=[]
        s=user_context.session_id.binary
        owner_id=args['owner_id']
        count=args['count']
        offset=args['offset']
        with App.db.make_connection(False,20) as cur:
            cur.execute("""
            SELECT id,audio_id,data_url,duration,name,artist,is_official,thumbnail,text,explicit,genre
            FROM audios
            WHERE owner_id = ?
            ORDER BY audio_id DESC
            LIMIT ?
            OFFSET ?
            """,[owner_id,count,offset])
            data=cur.fetchall()
        if not data:
            return []
        for x in data:
            _id,audio_id,data_url,duration,name,artist,is_official,thumbnail,text,explicit,genre=x
            url,expires=make_audio_url(str(flask.request.remote_addr),s,int(owner_id),int(audio_id),data_url)
            audios.append({
                'duration':duration,
                'name':name,
                'artist':artist,
                'hash':make_audio_hash(s,owner_id,audio_id),
                'id':"{}_{}".format(owner_id,_id),
                'url':'http://cdn.notvk.com/audios/'+url+'/128.mp3',
                'expires':expires,
                'is_official':bool(is_official),
                'thumbnail':thumbnail,
                'text':text,
                'explicit':bool(explicit),
                'genre':genre

            })
        return audios


#!/usr/bin/env python

import argparse
import os
import subprocess

def main():

    # arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('-top_dir', help='top level directory of chromo grouped mafs', required=True)
    parser.add_argument('-ref', help='Reference species name', required=True)
    parser.add_argument('-chr_tag', help='ID for ref chromosome', type=int, required=True)
    parser.add_argument('-n_thou', default=0, type=int)
    args = parser.parse_args()

    # get chromo dir
    all_dirs = [args.top_dir + x + '/' for x in os.listdir(args.top_dir) if x.startswith('BrownTrout')]
    chr_index = (args.n_thou * 1000) + (args.chr_tag - 1)
    maf_dir = all_dirs[chr_index]
    mafs = maf_dir + '*.maf'

    out_dir = maf_dir + 'aligned/'
    out_maf = out_dir + maf_dir.split('/')[-2] + '.multiple.maf'

    if not os.path.isdir(out_dir):
        os.mkdir(out_dir)

    temp_dir = out_dir + 'roast_temp'
    if not os.path.isdir(temp_dir):
        os.mkdir(temp_dir)

    tree = ('"(((((BrownTrout AtlanticSalmon) (ArcticChar (RainbowTrout (CohoSalmon SockeyeSalmon)))) '
            'DanubeSalmon) EuropeanGrayling) NorthernPike)"')

    ref_name = maf_dir.split('/')[-2].split('.')[0]

    os.chdir(maf_dir)

    # construct and submit command line
    roast = ('roast + '
             'T=' + temp_dir + ' '
             'E=' + ref_name + ' ' +
             tree + ' ' +
             mafs + ' ' +
             out_maf)

    subprocess.call(roast, shell=True)

if __name__ == '__main__':
    main()


from relati.types import RELATI_RECEIVER, RELATI_REPEATER
from relati_perf.actions import placePiece
from relati_perf.rules import isPlaceable, isRelatiPlaceable, reEnablePieces

def isPlaceableOrReceiver(grid):
    return isPlaceable(grid) or grid.status == RELATI_RECEIVER

def getUnmergedPlaceableAreas(board):
    unmergedPlaceableAreas = []

    for grid in board.grids:
        if not isPlaceableOrReceiver(grid):
            continue

        isGridInArea = False

        for nearbyGrid in grid.nearbyGrids:
            if not isPlaceableOrReceiver(nearbyGrid):
                continue

            for placeableArea in unmergedPlaceableAreas:
                if nearbyGrid in placeableArea:
                    placeableArea.append(grid)
                    isGridInArea = True
                    break

            if isGridInArea:
                break

        if not isGridInArea:
            placeableArea = [grid]
            unmergedPlaceableAreas.append(placeableArea)

    return unmergedPlaceableAreas

def getPlaceableAreas(board):
    unmergedPlaceableAreas = getUnmergedPlaceableAreas(board)

    for placeableArea in unmergedPlaceableAreas:
        for otherPlaceableArea in unmergedPlaceableAreas:
            if otherPlaceableArea is placeableArea:
                continue

            isOtherPlaceableAreaMerged = False

            for grid in otherPlaceableArea:
                for nearbyGrid in grid.nearbyGrids:
                    if isPlaceableOrReceiver(nearbyGrid) and nearbyGrid in placeableArea:
                        placeableArea.extend(otherPlaceableArea)
                        otherPlaceableArea.clear()
                        isOtherPlaceableAreaMerged = True
                        break

                if isOtherPlaceableAreaMerged:
                    break

    placeableAreas = [
        placeableArea for placeableArea in unmergedPlaceableAreas if len(placeableArea) != 0
    ]

    return placeableAreas

def getPieceCode(board):
    return ''.join([
        str(0 if grid.symbol is None else (grid.symbol | grid.status) + 1)
        for grid in board.grids
    ])

cachedPlayersPoints = {}

def evaluatePlayersPoints(board):
    pieceCode = getPieceCode(board)

    if pieceCode in cachedPlayersPoints:
        return cachedPlayersPoints[pieceCode]

    placeableAreas = getPlaceableAreas(board)
    isPlaceableAreasForPlayers = [[False, False] for _ in placeableAreas]
    placeableGridsCountForPlayers = [0, 0]
    pointsForPlayers = [0, 0]

    for placeableAreaIndex in range(len(placeableAreas)):
        placeableArea = placeableAreas[placeableAreaIndex]

        for grid in placeableArea:
            for symbol in range(2):
                if isRelatiPlaceable(grid, symbol):
                    isPlaceableAreasForPlayers[placeableAreaIndex][symbol] = True
                    placeableGridsCountForPlayers[symbol] += 1

    for placeableAreaIndex in range(len(placeableAreas)):
        placeableArea = placeableAreas[placeableAreaIndex]
        isPlaceableAreaForPlayers = isPlaceableAreasForPlayers[placeableAreaIndex]

        if isPlaceableAreaForPlayers[0] and not isPlaceableAreaForPlayers[1]:
            pointsForPlayers[0] += len(placeableArea) * 9
        elif isPlaceableAreaForPlayers[1] and not isPlaceableAreaForPlayers[0]:
            pointsForPlayers[1] += len(placeableArea) * 9

    pointsForPlayers[0] += placeableGridsCountForPlayers[0]
    pointsForPlayers[1] += placeableGridsCountForPlayers[1]

    cachedPlayersPoints[pieceCode] = pointsForPlayers

    return pointsForPlayers

def evaluatePlayerPoints(board, symbol, depth, isPlayerTurn=True, alpha=-100000, beta=100000):
    [oPoints, xPoints] = evaluatePlayersPoints(board)

    if depth == 0:
        if symbol == 0:
            return oPoints - xPoints
        else:
            return xPoints - oPoints

    statusOfGrids = [
        grid.status
        for grid in board.grids
    ]

    if isPlayerTurn:
        maxPlayerPoints = -100000

        for grid in board.grids:
            if not isRelatiPlaceable(grid, symbol):
                continue

            grid.symbol = symbol
            grid.status = RELATI_REPEATER
            reEnablePieces(board)

            playerPoints = evaluatePlayerPoints(
                board, symbol, depth - 1, False, alpha, beta
            )

            maxPlayerPoints = max(maxPlayerPoints, playerPoints)
            alpha = max(alpha, maxPlayerPoints)

            grid.symbol = None

            for grid in board.grids:
                grid.status = statusOfGrids[grid.index]

            if beta <= alpha:
                break

        return maxPlayerPoints
    else:
        minPlayerPoints = 100000

        for grid in board.grids:
            if not isRelatiPlaceable(grid, (symbol + 1) % 2):
                continue

            grid.symbol = (symbol + 1) % 2
            grid.status = RELATI_REPEATER
            reEnablePieces(board)

            playerPoints = evaluatePlayerPoints(
                board, symbol, depth - 1, True, alpha, beta
            )

            minPlayerPoints = min(minPlayerPoints, playerPoints)
            beta = min(beta, minPlayerPoints)

            grid.symbol = None

            for grid in board.grids:
                grid.status = statusOfGrids[grid.index]

            if beta <= alpha:
                break

        return minPlayerPoints

def evaluatePlayerNextStep(board, symbol, depth):
    highestPoints = -100001
    gridOfHighestPoints = None

    statusOfGrids = [
        grid.status
        for grid in board.grids
    ]

    for grid in board.grids:
        if not isRelatiPlaceable(grid, symbol):
            continue

        grid.symbol = symbol
        grid.status = RELATI_REPEATER
        reEnablePieces(board)

        points = evaluatePlayerPoints(board, symbol, 2)

        if points > highestPoints:
            highestPoints = points
            gridOfHighestPoints = grid

        grid.symbol = None

        for grid in board.grids:
            grid.status = statusOfGrids[grid.index]

    return gridOfHighestPoints


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('contacts', '0004_auto_20151210_1426'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='region',
            options={'ordering': ['country', 'name']},
        ),
        migrations.AddField(
            model_name='contact',
            name='tax_code',
            field=models.CharField(help_text='Tax Code for Argentina, Brazil, Paraguay, Peru (CUIT/CPF/RUC)', max_length=20, verbose_name='Tax Code', blank=True),
        ),
    ]


# Import tensorflow library
# Reference it as tf for ease of calling
import tensorflow as tf

# Let's create two matrices, a 3x1 and another 1x3 matrix for multiplication
mat_a = tf.constant([[1., 3., 5.]], name='mat_a')
mat_b = tf.constant([[7.], [11.], [13.]], name='mat_b')

# Let's matrix multiply the two matrices
prod_op = tf.matmul(mat_a, mat_b)

# ---------------------------------------------------------------
# Create a session object to run our matrix multiplication
sess = tf.Session()

# Get the result by calling run on the session
# Returns an numpy ndarray object
mat_mul = sess.run(prod_op)

# Let's view the result
print(mat_mul)
# [[ 105.]]

# Remember to close the session when done, releases the resources
sess.close()

# ---------------------------------------------------------------
# Easier way to handle session objects is
# using the familiar 'with' block as follows
with tf.Session() as sess:
	mat_mul = sess.run(prod_op)
	print(mat_mul)
# [[ 105.]]

# ---------------------------------------------------------------
# If we want to run on multiple devices we do as follows
with tf.Session() as sess:
	with tf.device("/cpu:0"):
		mat_mul = sess.run(prod_op)
		print(mat_mul)


#!/usr/bin/env python
"""
Measure phase ghosts by taking the ratio of the phase background to the frequency background.
"""
import sys
import nibabel
import argparse
import labels
import _utilities as util
import numpy

def nii_4d(in_nii):
     pass

def cummean_nii(in_nii, scale=1, verbose=False):

     # Read in NIBABEL NIFTI object
     in_array = in_nii.get_data()

     # Perform cumulative sum
     out_array = scale * numpy.cumsum( in_array, axis=3)

     # Scale each sum by the number of volumes used in the summation to calculate the mean.
     for ii in range(0,out_array.shape[3]):
          out_array[...,ii] /= ii+1

     # Create nibabel NIFTI object
     out_nii = nibabel.Nifti1Image( out_array, None, in_nii.get_header())

     return out_nii

#
# Main Function
#

if __name__ == '__main__':

     ## Parsing Arguments

     usage = 'usage: %prog [options] arg1 arg2'

     parser = argparse.ArgumentParser(prog='sort_nii')

     parser.add_argument('in_nii',    help='Background labels')

     parser.add_argument('-o','--out_nii', help='Filename of NIFTI output label. (default = cumsum_nii.<in> ) ', default=None)

     parser.add_argument('-s','--scale', help='Multiply NIFTI output array by scale factor ', type=float, default=1.0)
     parser.add_argument('-v','--verbose',  help='Verbose flag',      action='store_true', default=False )

     inArgs = parser.parse_args()

     # Read NIFTI File
     in_nii = nibabel.load(inArgs.in_nii)

     out_nii = cummean_nii(in_nii, inArgs.scale)

     if inArgs.out_nii is None:
          out_nii_filename = util.add_prefix_to_filename( inArgs.in_nii, 'cumsum_nii.')
     else:
          out_nii_filename = inArgs.out_nii

     nibabel.save( out_nii, out_nii_filename)


'''
    date: 2019/10/28
    path: ../数组/11....md
    email: yiouejv@126.com
'''

class Solution(object):
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        # 题目的意思：两个数组元素的下标相减再乘以这两个数组元素的较小值。找出最大的值。
        # 方法一：暴力遍历
        #      求出所有的情况，取最大,
        #      时间复杂度 O(n**2)
        #      空间复杂度 O(1)
        #       超出时间限制，此方法不耐用
        # max = 0
        # for i in range(len(height)-1):
        #     for j in range(i+1, len(height)):
        #         r =  (j-i) * min(height[i], height[j])
        #         if r > max:
        #             max = r
        # return max
        # 方法二：
        #    双指针法，首尾两个指针保证了宽度由大到小，首位两个指针向中间靠拢。
        #    靠拢规则：指向较小数的指针王中间靠拢，直到尾指针小于等于首指针。保存之间最大的面积
        #    时间复杂度： O(n)
        #    空间复杂度： O(1)
        max = 0
        i = 0
        j = len(height) - 1
        while j > i:
            r = (j - i) * min(height[i], height[j])
            if r > max:
                max = r

            if height[i] < height[j]:
                i += 1
            else:
                j -= 1
        return max

print(Solution().maxArea([2,3,4,5,18,17,6]))


from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    MAN = "man"
    WOMEN = "women"
    SEX = [(MAN, MAN), (WOMEN, WOMEN)]

    sex = models.CharField(max_length=6, choices=SEX, default=MAN)

    class Meta:
        verbose_name = "Пользователь"
        verbose_name_plural = "Пользователи"
        ordering = ["username"]


import folium, pandas, ast
import json
# -*- coding: utf-8 -*-
locations_p = []
geos_p = []
files = 'tweets_#gopatriots.txt'
# get geo data only from rows with non-empty values
with open(files,'r') as ifile:
        for line in ifile.readlines():
            tweet = json.loads(line)
            if tweet['tweet']['geo'] is not None:
            	locations_p.append(tweet['tweet']['geo']['coordinates'])

ifile.close()

locations_h = []
files = 'tweets_#gohawks.txt'
with open(files,'r') as ifile:
        for line in ifile.readlines():
            tweet = json.loads(line)
            if tweet['tweet']['geo'] is not None:
            	locations_h.append(tweet['tweet']['geo']['coordinates'])

ifile.close()
# for location in locations:
#   # add to geos array an evaluated python literal syntax of the data
#  	geos.append(ast.literal_eval(location))

# initialize and create map
tweet_map= folium.Map(location=[52.8, -2], tiles='Mapbox Bright', zoom_start=7)

# add markers
for geo in locations_p:
	tweet_map.circle_marker(location=geo, radius=250, line_color='#E91616')

for geo in locations_h:
	tweet_map.circle_marker(location=geo, radius=250, line_color='#3186cc')

tweet_map.create_map(path='map.html')


# Example factorial with use recursive

# Let us to take famous example the factorial.

def factorial(x):
  if x == 1:
    return 1
  else:
    return x * factorial(x - 1)

 # call the function
factorial(5)  # output >>> 120


'''
pg. 31

Merge(A, p, q, r)
  n1 = q - p + 1
  n2 = r - q
  let L[1..n1 + 1] and R[1..n2+1] be new arrays
  for i = 1 to n1
    L[i] = A[p+i-1]
  for j = 1 to n2
    R[j] = A[q+j]
  L[n1+1] = infinity
  R[n2+1] = infinity
  i = 1
  j = 1
  for k = p to r
    if L[i] <= R[j]
      A[k] = L[i]
      i = i+1
    else A[k] = R[j]
      j = j+1
'''

# 25:00

def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left = arr[:mid]
        right = arr[mid:]
        merge_sort(left)
        merge_sort(right)

        i = 0
        j = 0
        k = 0

        while i < len(left) and j < len(right):
            if left[i] <= right[j]:
                arr[k] = left[i]
                i += 1
            elif left[i] > right[j]:
                arr[k] = right[j]
                j += 1
            k += 1

        if i == len(left):
            while j < len(right):
                arr[k] = right[j]
                i += 1
                j += 1
        elif j == len(right):
            while i < len(left):
                arr[k] = left[i]
                i += 1
                k += 1
    print(arr)

merge_sort([5,2,4,6,1,3])


from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent

class Twitter(BaseHelper):

    def __init__(self):
        BaseHelper.__init__(self)
        try:
            import twitter
            self.twitter = twitter
            import time
            self.time = time
            self._supported = True
        except ImportError:
            self._supported = False

    def _accept_account(self, account):
        return "twitter.com" in account.accountServiceHomepage

    def _handle_account(self, account):
        if account.accountName:
            username = account.accountName
        elif account.accountProfilePage:
            username = account.accountProfilePage.split("/")[-1]
        elif account.accountServiceHomepage:
            username = account.accountServiceHomepage.split("/")[-1]
        else:
            return []

        api = self.twitter.Api()
        tweets = []
        for tweet in api.GetUserTimeline(username):
            event = ActivityStreamEvent()
            event.type = "Twitter"
            event.detail = tweet.text
            event.link = "http://www.twitter.com/%s/status/%d" % (username, tweet.id)
            event.timestamp = self.time.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y")
            tweets.append(event)
        return tweets


#coding=utf8
#author : veritas501
from pwn import *

_IO_FILE_plus_size = {
	'i386':0x98,
	'amd64':0xe0
}
_IO_FILE_plus = {
	'i386':{
		0x0:'_flags',
		0x4:'_IO_read_ptr',
		0x8:'_IO_read_end',
		0xc:'_IO_read_base',
		0x10:'_IO_write_base',
		0x14:'_IO_write_ptr',
		0x18:'_IO_write_end',
		0x1c:'_IO_buf_base',
		0x20:'_IO_buf_end',
		0x24:'_IO_save_base',
		0x28:'_IO_backup_base',
		0x2c:'_IO_save_end',
		0x30:'_markers',
		0x34:'_chain',
		0x38:'_fileno',
		0x3c:'_flags2',
		0x40:'_old_offset',
		0x44:'_cur_column',
		0x46:'_vtable_offset',
		0x47:'_shortbuf',
		0x48:'_lock',
		0x4c:'_offset',
		0x54:'_codecvt',
		0x58:'_wide_data',
		0x5c:'_freeres_list',
		0x60:'_freeres_buf',
		0x64:'__pad5',
		0x68:'_mode',
		0x6c:'_unused2',
		0x94:'vtable'
	},

	'amd64':{
		0x0:'_flags',
		0x8:'_IO_read_ptr',
		0x10:'_IO_read_end',
		0x18:'_IO_read_base',
		0x20:'_IO_write_base',
		0x28:'_IO_write_ptr',
		0x30:'_IO_write_end',
		0x38:'_IO_buf_base',
		0x40:'_IO_buf_end',
		0x48:'_IO_save_base',
		0x50:'_IO_backup_base',
		0x58:'_IO_save_end',
		0x60:'_markers',
		0x68:'_chain',
		0x70:'_fileno',
		0x74:'_flags2',
		0x78:'_old_offset',
		0x80:'_cur_column',
		0x82:'_vtable_offset',
		0x83:'_shortbuf',
		0x88:'_lock',
		0x90:'_offset',
		0x98:'_codecvt',
		0xa0:'_wide_data',
		0xa8:'_freeres_list',
		0xb0:'_freeres_buf',
		0xb8:'__pad5',
		0xc0:'_mode',
		0xc4:'_unused2',
		0xd8:'vtable'
	}
}

class IO_FILE_plus_struct(dict):
	arch = None
	endian = None
	fake_file = None
	size  = 0
	FILE_struct = []

	@LocalContext
	def __init__(self):
		self.arch = context.arch
		self.endian = context.endian

		if self.arch != 'i386' and self.arch != 'amd64':
			log.error('architecture not supported!')
		success('arch: '+str(self.arch))

		self.FILE_struct = [_IO_FILE_plus[self.arch][i] for i  in sorted(_IO_FILE_plus[self.arch].keys())]
		self.update({r:0 for r in self.FILE_struct})
		self.size = _IO_FILE_plus_size[self.arch]

	def __setitem__(self, item, value):
		if item not in self.FILE_struct:
			log.error("Unknown item %r (not in %r)" % (item, self.FILE_struct))
		super(IO_FILE_plus_struct, self).__setitem__(item, value)

	def __setattr__(self, attr, value):
		if attr in IO_FILE_plus_struct.__dict__:
			super(IO_FILE_plus_struct, self).__setattr__(attr, value)
		else:
			self[attr]=value

	def __getattr__(self, attr):
		return self[attr]

	def __str__(self):
		fake_file = ""
		with context.local(arch=self.arch):
			for item_offset in sorted(self.item_offset):
				if len(fake_file) < item_offset:
					fake_file += "\x00"*(item_offset - len(fake_file))
				fake_file += pack(self[_IO_FILE_plus[self.arch][item_offset]],word_size='all')
			fake_file += "\x00"*(self.size - len(fake_file))
		return fake_file

	@property
	def item_offset(self):
		return _IO_FILE_plus[self.arch].keys()


# Type the name, age and height, so that the height number is 2 digits precised.

name = input()
age = int(input())
height = float(input())

height_format = '{:04.2f}'.format(height)

print(f"Hi, my name is {name}. My age is {age} and my height is {height_format}.")

print("Hi, my name is %s. My age is %d and my height is %.2f." % (name, age, height))


import h5py
import os
import shutil
import argparse
from genome import *

parser = argparse.ArgumentParser()
parser.add_argument("read_basedir", help="base directory of resquiggled fast5 files")
parser.add_argument("output_dir", help="directory to copy files to (must exist)")
parser.add_argument("reference", help="fasta file with reference genome")
parser.add_argument("begin", help="begining of interval (inclusive)")
parser.add_argument("end", help="end of interval (exclusive)")

args = parser.parse_args()

if args.read_basedir == args.output_dir:
  print("read_basedir and output_dir must be different")
  exit(1)

begin = int(args.begin)
end = int(args.end)
if end - begin <= 0:
  print("interval must have positive length")
  exit(1)

read_files = [file for file in os.listdir(args.read_basedir) if not os.path.isdir(os.path.join(args.read_basedir, file))]
read_files = filter(lambda x : x[-6:] == ".fast5", read_files)

reference = load_fasta(args.reference)[0].bases

for read_file in read_files:
  filename = os.path.join(args.read_basedir, read_file)
  good = False
  print(filename)
  try:
    with h5py.File(filename, "r") as f:
      read_id = list(f['Raw/Reads'].keys())[0]

      alignment_meta = f['Analyses/RawGenomeCorrected_000/BaseCalled_template/Alignment'].attrs
      start_in_reference = alignment_meta['mapped_start']
      end_in_reference = alignment_meta['mapped_end']
      strand = alignment_meta['mapped_strand'].decode('ascii')
      if strand == '-':
        start_in_reference, end_in_reference = len(reference) - end_in_reference, len(reference) - start_in_reference
      if min(end_in_reference, end) - max(start_in_reference, begin) > 0:
        good = True

  except KeyError:
    continue
  if good:
    copy_name = os.path.join(args.output_dir, read_file)
    print("copying {} to {}".format(filename, copy_name))
    shutil.copy2(filename, copy_name)


import numpy as np
import sys

def algo(s):
    s = list(s)
    convert_dict = {
        '0': 0,
        '1': 1,
        '2': 2,
        '3': 3,
        '4': 4,
        '5': 5,
        '6': 6,
        '7': 7,
        '8': 8,
        '9': 9,
        'a': 10,
        'b': 11,
        'c': 12,
        'd': 13,
        'e': 14,
        'f': 15
    }
    s = [convert_dict.get(i) for i in s]
    l = []
    count = 0
    for i in range(len(s)):
        for j in range(i+1,len(s)):
            for k in range(j+1,len(s)):
                l.append(16**2 * s[i] + 16 * s[j] + s[k])
    return np.min(l)

if __name__ == '__main__':
    for l in sys.stdin:
        result = algo(l.rstrip('\r\n'))
        print(result)


from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.functional import cached_property

from database.utils import translate_doc
from database.models.data_collections.data_collections import Collection

@translate_doc
class User(AbstractUser):
    help_text = _('''
    User Model

    People using irekua must be previously registered and should provide
    minimal personal information. This is to track contributions and to control
    access to data.

    Users can belong to collections (:model:`database.Collection`), possess
    devices (:model:`database.PhysicalDevice`), sign licences
    (:model:`database.Licence`), upload items (:model:`database.Item`),
    annotate data (:model:`database.Annotation`), and more.
    ''')

    institution = models.ForeignKey(
        'Institution',
        on_delete=models.PROTECT,
        db_column='institution_id',
        verbose_name=_('institution'),
        help_text=_('Institution to which user belongs'),
        blank=True,
        null=True)
    is_developer = models.BooleanField(
        db_column='is_developer',
        verbose_name=_('is developer'),
        help_text=_('Flag to indicate if user is a model developer'),
        blank=False,
        null=False,
        default=False)
    is_curator = models.BooleanField(
        db_column='is_curator',
        verbose_name=_('is curator'),
        help_text=_('Flag to indicate if user is a curator'),
        blank=False,
        null=False,
        default=False)
    is_model = models.BooleanField(
        db_column='is_model',
        verbose_name=_('is model'),
        help_text=_('Flag to indicate if user is an AI model'),
        blank=False,
        null=False,
        default=False)

    class Meta:
        verbose_name = _('User')
        verbose_name_plural = _('Users')
        unique_together = [
            ['email',],
        ]

    @property
    def is_special(self):
        return self.is_developer | self.is_curator | self.is_model | self.is_superuser

    @cached_property
    def is_collection_type_admin(self):
        return self.collectiontype_set.exists()

    @cached_property
    def managed_collections(self):
        queryset = Collection.objects.filter(
            collection_type__in=self.collectiontype_set.all())
        return queryset


#!/bin/python3

__author__ = "Adam Karl"
"""Starting with 1 and moving out in a spiral, that is the sum of the diagonals in an N x N spiral"""
#https://projecteuler.net/problem=28

#NOTES
#top right of nxn is n**2
#bottom left of nxn is (n**2 + (n-2)**2)/2 This is also the average of top left, bot left, and bot right
#therefore, ans(n by n) = ans(n-2 by n-2) + 4n**2 - 6n + 6 (after expansion)

def sumOfDiagonal(n):
    """Sum the diagonals of a n x n spiral (1 in the middle then spiralling out)"""
    sum1 = (n * (n + 1) * (2 * n + 1)) // 3
    sum2 = ((n - 1) * (n - 1)) //2
    return sum1 - sum2 - 1

def main():
    print("Sum the diagonals of a n x n spiral. n = ", end="")
    n = int(input())
    result = sumOfDiagonal(n)
    print("Sum = %d" % result)

if __name__ == "__main__":
    main()


# Activate
#   |- Linear
#   |- ReLU
#   |- Sigmoid
#   |- Softmax
#   |- Tanh
# Regularize
#   |- L2
#   |- Dropout
# Initialize (variance)
#   |- Constant
#   |- He
#   |- Xavier
# Optimize
#   |- EMA
#   |- RMSprop
#   |- Adam
# Normalization/ standardization
# Grad checking

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

class Activate:
    """
    Following activation functions are defined under this class
    (1) Linear
    (2) ReLU (Rectified Linear Unit)
    (3) Sigmoid
    (4) Softmax
    (5) Tanh (Hyperbolic tangent)
    """

    def linear(self, x):
        """
        Linear activation function (pass-through).
        Returns nothing but the the input vector itself.
        """
        return x

    def relu(self, x, max_value=None, threshold=0):
        """
        Rectified linear unit.
        With default values, it returns element-wise `max(x, 0)`.
        Otherwise:
        `relu(x) = max_value` for `x >= max_value`,
        `relu(x) = x` for `threshold <= x < max_value`,

        Parameters
        ----------
        x : ndarray
        max_value: float, default = None
        threshold : float, default = 0
        """

        output = np.maximum(x, threshold)
        output = np.minimum(output, max_value)

        return output

    def sigmoid(self, x):
        """
        Sigmoid activation function,
            `sigmoid(x) = 1 / (1 + exp(-x))`.

        The sigmoid function always returns a value between 0 and 1.

        For example:
            x = [-20, -1.0, 0.0, 1.0, 20]
            output = [2.06e-09, 2.689e-01, 5.00e-01, 7.31e-01, 1.0]
        """
        output = 1 / (1 + np.exp(-x))
        return output

    def softmax(self, x, axis=-1):
        """
        Softmax converts a vector of values to a probability distribution. It can
        be viewed as a higher-dimensional generalization of the sigmoid function.

        Parameters
        ----------
        x : ndarray of shape ()
        axis : int, default=-1
            axis along which the softmax normalization is applied.

        Returns
        -------
        output : ndarray of shape ()
            Output of softmax transformation (all values must be non-negative
            and sum to 1).
        """

        norm = np.sum(np.exp(x))
        output = np.exp(x)/norm

        # assert all the values are non-negative
        assert all(output > 0)
        # All the elements of the output vector sum to 1.
        assert np.sum(output) == 1.0

        return output

    def tanh(self, x):
        """
        Hyperbolic tangent activation function.

        Returns:
            ndarray of same shape and dtype as those of input `x`.
        """
        return np.tanh(x)

# ----- Methods useful for Convolutional Neural Networks (CNN) ---- #
def conv_dims(dim: int, f: int, pad: int, stride: int):
    """
    Arguments:
        dim -- int; dim of the input image
        f -- int; dim of the filter/ weight (square) matrix
        pad -- int; padding level
        stride -- int; stride parameter

    Returns:
        dim -- dim of the output layer after convolution
    """

    dim = 1 + int((dim - f + 2 * pad) / stride)

    return dim

def zero_pad(image, pad: int, demo=False):
    """
    Pad the images with zeros

    Parameters:
        image -- ndarray; of shape (m, nH, nW, nc) representing a vector of m images
        pad -- int; amount of padding around height, width dimensions of each image
        demo -- bool; show the image pixels before and after padding

    Returns:
        im_pad -- padded image of shape (m, nH + 2*pad, nW + 2*pad, nc)

    Raises:
        ValueError -- Input dimension must be (m, nH, nW, nc)
    """

    # Check the input format
    if len(image.shape) < 4:
        raise ValueError("Input dimensions not of the form (m, nh, nw, nc).")

    im_pad = np.pad(image, ((0, 0), (pad, pad), (pad, pad), (0, 0)),
                    mode='constant', constant_values=(0, 0))

    # If 'demo' requested then show image before & after padding
    if demo:
        fig, ax = plt.subplots(1, 2)
        ax[0].set_title('Original Image')
        ax[0].imshow(image[0, :, :, 0])
        ax[1].set_title('Padded Image')
        ax[1].imshow(im_pad[0, :, :, 0])
        plt.show()

    return im_pad

def conv_block(im_block, kernel, bias):
    """
    Convolve the filter with a single block matrix of the same size.

    Parameters:
        im_block -- ndarray, slice of input image of shape (f, f, nC_prev)
        kernel -- ndarray, Weight parameters of the filter matrix of shape (f, f, nC_prev)
        bias -- float, Bias parameters - matrix of shape (1, 1, 1)

    Returns:
        conv_im -- float, result of convolution with (kernel, bias)
    """

    # Element-wise product between im_block and kernel.
    s = np.multiply(im_block, kernel)
    # Sum over all entries of the volume s and add the bias term.
    conv_im = np.sum(s) + float(bias)

    return conv_im

def conv_full(image, kernel, bias, stride, pad, demo=False):
    """
    Implements the convolution operation on the full input image. This is done
    by repeating 'conv_block' method on the entire image.

    Arguments:
        image -- output activations of the previous layer,
            ndarray of shape (m, nH_prev, nW_prev, nC_prev)
        kernel -- Weights, ndarray of shape (f, f, nC_prev, nC)
        bias -- Biases, ndarray of shape (1, 1, 1, nC)
        stride -- int; stride parameter
        pad -- int; padding parameter
        demo -- bool; show the image pixels before and after convolution

    Returns:
        im_out -- convolved output, numpy array of shape (m, nH, nW, nC)
    """

    # Retrieve the shapes of the matrices
    (m, nh_prev, nw_prev, nc_prev) = image.shape
    # nc = num channels in the output layer = num filters
    (f, f, nc_prev, nc) = kernel.shape

    # Compute the number of dims in height and width of the output
    nh = conv_dims(nh_prev, f, pad, stride)
    nw = conv_dims(nw_prev, f, pad, stride)

    # The convolved output image is initialized by zeros
    im_out = np.zeros(shape=(m, nh, nw, nc))

    # Pad the input image before convolution begins and overwrite
    image = zero_pad(image, pad, demo=False)

    for i in range(m):  # loop over the training examples
        im_i = image[i, :, :, :]

        for h in range(nh):  # loop over the vertical axis of the matrix
            top = h * stride
            bottom = top + f

            for w in range(nw):  # loop over the horizontal axis of the matrix
                left = w * stride
                right = left + f

                for c in range(nc):  # loop over the channels
                    im_block = im_i[top:bottom, left:right, :]
                    weights = kernel[:, :, :, c]
                    biases = bias[:, :, :, c]
                    # Convolve the image block
                    im_out[i, h, w, c] = conv_block(im_block, weights, biases)

    # Making sure the output shape is correct
    assert (im_out.shape == (m, nh, nw, nc))

    # If 'demo' requested then show image before & after convolution
    if demo:
        fig, ax = plt.subplots(1, 2)
        ax[0].set_title('Original Image (%ix%ix%i)'
                        % (nh_prev + 2 * pad, nw_prev + 2 * pad, nc_prev))
        ax[0].imshow(image[0, :, :, 0])
        ax[1].set_title('Convolved Image (%ix%ix%i)' % (nh, nw, nc))
        ax[1].imshow(im_out[0, :, :, 0])
        plt.show()

    # if input matrix is large enough it's good to deallocate memory
    del image
    gc.collect()

    return im_out

def pooling(image, f: int, stride: int, mode='max', demo=False):
    """
    Implements the convolution operation on the full input image. This is done
    by repeating 'conv_block' method on the entire image.

    Arguments:
        image -- output activations of the previous layer,
            ndarray of shape (m, nH_prev, nW_prev, nC_prev)
        f -- int; dim of the filter/ weight (square) matrix
        stride -- int; stride parameter
        mode -- 'max' for max pooling; 'avg' for average pooling
        demo -- bool; show the image pixels before and after pooling

    Returns:
        im_out -- pooled output, ndarray of shape (m, nH, nW, nC)

    Exceptions:
        KeyError -- raised if 'mode' key is incorrectly specified.
    """

    # Retrieve the shapes of the input
    (m, nh_prev, nw_prev, nc_prev) = image.shape

    # Compute the number of dims in height and width of the output
    nh = conv_dims(nh_prev, f, 0, stride)  # pooling doesn't need padding
    nw = conv_dims(nw_prev, f, 0, stride)
    nc = nc_prev

    # The convolved output image is initialized by zeros
    im_out = np.zeros(shape=(m, nh, nw, nc))

    for i in range(m):  # loop over the training examples
        im_i = image[i, :, :, :]

        for h in range(nh):  # loop over the vertical axis of the matrix
            top = h * stride
            bottom = top + f

            for w in range(nw):  # loop over the horizontal axis of the matrix
                left = w * stride
                right = left + f

                for c in range(nc):  # loop over the channels
                    im_block = im_i[top:bottom, left:right, c]

                    if mode == 'max':
                        im_out[i, h, w, c] = np.max(im_block)
                    elif mode == "avg":
                        im_out[i, h, w, c] = np.mean(im_block)
                    else:
                        raise KeyError("'mode' key unrecognized, use 'avg' or 'max'.")

    # Making sure the output shape is correct
    assert (im_out.shape == (m, nh, nw, nc))

    # If 'demo' requested then show image before & after convolution
    if demo:
        fig, ax = plt.subplots(1, 2)
        ax[0].set_title('Original Image')
        ax[0].imshow(image[0, :, :, 0])
        ax[1].set_title('%s-pooled Image' % mode)
        ax[1].imshow(im_out[0, :, :, 0])
        plt.show()

    del image
    gc.collect()

    return im_out

# def forward_prop(self, X):
#   CONV2D -> RELU -> MAX_POOL -> CONV2D -> RELU -> MAX_POOL -> FLATTEN -> FULLY_CONNECTED
#   CONV2D: stride of 1, padding 'SAME'
#     Z1 = None
#     # RELU
#     A1 = None
#     # MAX_POOL: window 8x8, stride 8, padding 'SAME'
#     P1 = None
#     # CONV2D: filters W2, stride 1, padding 'SAME'
#     Z2 = None
#     # RELU
#     A2 = None
#     # MAX_POOL: window 4x4, stride 4, padding 'SAME'
#     P2 = None
#     # FLATTEN
#     F = None
#     # FULLY-CONNECTED without non-linear activation function (not not call softmax).
#     # 6 neurons in output layer. Hint: one of the arguments should be "activation_fn=None"
#     Z3 = None --> return Z3 (a linear unit) as a 'self' object.

# ----- Speeding methods for Artificial Neural Networks (ANN) ---- #

#
# def init_var_scale(num_hidden_units, key, const=0.01):
#     # Good for ReLU
#     if key == 'He':
#         # pass the number of hidden units in the previous layer
#         return np.sqrt(2. / num_hidden_units)
#
#     # Good for Sigmoid or Tanh
#     elif key == 'Xavier':
#         # pass the number of hidden units in the previous layer
#         return np.sqrt(1. / num_hidden_units)
#
#     # If not sure, just use a constant variance
#     else:
#         return const
#
#
# def accuracy(y_orig, y_pred):
#     return round(np.mean(y_orig == y_pred) * 100, 4)
#
#
# def activate(x, key):
#
#     if key == 'sigmoid':
#         a_func = 1 / (1 + np.exp(-x))
#         a_grad = np.multiply(a_func, 1-a_func)
#
#     elif key == 'tanh':
#         a_func = np.tanh(x)
#         a_grad = 1 - np.power(a_func, 2)
#
#     elif key == 'ReLU':
#         a_func = np.maximum(0, x)
#         a_grad = np.heaviside(x, 0)  # x==0 returns 0
#
#     else:
#         raise KeyError("Invalid activation key. "
#                        "Choose from 'tanh', 'sigmoid', 'ReLU'")
#
#     return a_func, a_grad
#
#
# def train_test(A, B, test_size=0.2):
#
#     nums = A.shape[1]
#     frac = round(nums * (1 - test_size))
#
#     # Shuffle the index array and then map that to X, Y
#     idx = np.arange(nums)
#     np.random.shuffle(idx)
#     A = A[:, idx]
#     B = B[:, idx]
#
#     return A[:, :frac], A[:, frac:], B[:, :frac], B[:, frac:]
#
#
# def set_bias_as_weight(shape):
#     return shape[0] + 1, shape[1]
#
#
# def add_bias(vector):
#     return np.hstack([vector, np.ones((vector.shape[0], 1))])
#
#
# def sigmoid(z):
#     return 1 / (1 + np.exp(-z))
#
#
# def shuffle_vectors(x, y):
#     rd = np.arange(len(x))
#     np.random.shuffle(rd)
#     x = x[rd]
#     y = y[rd]
#     return x, y
#
#
# def _stable_clip(x):
#     """Used to avoid numerical inestability when"""
#     return np.clip(x, 1e-7, 1 - 1e-7)
#
#
# def mean_squared_error(ypred, ytrue):
#     return (ypred - ytrue) * ypred * (1 - ypred)
#
#
# def cross_entropy(ypred, ytrue, binary=True):
#     # return -ytrue * np.log(_stable_clip(ypred)) -\
#     #         (1 - ytrue) * np.log(1 - _stable_clip(ypred))
#     return _stable_clip(ypred) - ytrue


"""
Python3.6+ only
"""
import re
from pathlib import Path

from pie import *

class env(env):
    @classmethod
    def _parse_lines(cls,ls):
        """Parses lines and returns a dict."""
        d={}
        for i,l in enumerate(ls,1):
            l=l.strip()
            # skip blank lines and comments
            if not l or l.startswith('#'): continue
            # ignore `set` and `export` and split into pre and post `=` parts
            mo=re.match(r'^(set\s+|export\s+)?(?P<key>[^=\s]+)\s*=(?P<value>.*)',l)
            if mo:
                d[mo.group('key')]=mo.group('value')
            else:
                raise Exception(f'Failed to parse line {i}: "{l}"')
        return d

    @classmethod
    def from_files(cls,*files):
        d={}
        # turn files into Path objects
        env_files=[Path(f) for f in files]
        # and filter out files that don't exist
        existing_env_files=[]
        for ef in env_files:
            if ef.exists():
                existing_env_files.append(ef)
            else:
                print(f'INFO: {ef} not found')
        # parse all existing files in order
        for p in existing_env_files:
            with p.open('r',encoding='utf-8') as fin:
                file_d=cls._parse_lines(fin.readlines())
                d.update(file_d)
        return cls(d)

    @classmethod
    def dump_env(cls):
        import os
        for k in sorted(os.environ.keys()):
            v=os.environ[k]
            print(f'{k}={v}')


# Linked Lists (with a tail reference) + relevant primary methods

# Node Class
class Node:
    def __init__(self, value = None):
        self.value = value
        self.next = None

    # Method which returns the value of a node
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def getValue(self):
        return self.value

    # Method which returns the next node
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def getNext(self):
        return self.next

    # Method which set a new value to the current node value
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def setValue(self, newval):
        self.value = newval

    # Method which set the next node value to a new value
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def setNext(self, newval):
        self.next = newval

# Linked List class
class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    # Method returning the head node
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def headNode(self):
        if self.head == None:
            return None
        else:
            return self.head.getValue()

    # Method returning the tail node
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def tailNode(self):
        if self.tail == None:
            return None
        else:
            return self.tail.getValue()

    # Method checking whether the linked list is empty or not
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def isEmpty(self):
        return self.head == None

    # Method returning all the nodes within the Linked List
    # Time Complexity => O(n) because the worst case implies traversing each elements depending on the size of the linked list
    # Space Complexity => O(n) because it stores the nodes into a list values which can be n size
    def __str__(self):
        values = []

        currentNode = self.head
        while currentNode:
            values.append(currentNode.value)
            currentNode = currentNode.getNext()
        return " => ".join(map(str, values))

    # Method transforming the value as the head and the current head as the 2nd node
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def prepend(self, value):
        newNode = Node(value)
        currentNode = self.head

        if self.head == None:
            self.head = newNode
        else:
            newNode.setNext(self.head)
            self.head = newNode

    # Method transforming the value as the tail and the current tail become the 2nd last node
    # Time Complexity => O(n) since we don't know the previous node, it needs to traverse through each node
    # Space Complexity => O(1)
    def append(self, value):
        newNode = Node(value)

        if self.head == None:
            self.head = newNode
            return

        current = self.head
        while current.next:
            current = current.next

        current.next = newNode
        self.tail = newNode

    # Method transforming the 2nd node to become the head
    # Time Complexity => O(1)
    # Space Complexity => O(1)
    def popFirst(self):
        currentHead = self.head
        self.head = currentHead.getNext()

    # Method transforming the 2nd last node to become the tail
    # Time Complexity => O(n) since the previous node is now know, it has to traverse until it reaches the tail
    # Space Complexity => O(1)
    def pop(self):
        previousNode = None
        currentNode = self.head
        while currentNode.next:
            previousNode = currentNode
            currentNode = currentNode.next
        self.tail = previousNode

        previousNode.next = None
        currentNode = None

    # Method returning the size of the Linked List
    # Time Complexity => O(n) because it has to traverse untill it reaches the tail
    # Space Complexity => O(1) because it is only a simple variable
    def size(self):
        currentNode = self.head
        size = 0
        while currentNode != None:
            size += 1
            currentNode = currentNode.getNext()

        return size

    # Method accessing the value of a specific index in the Linked List
    # Time Complexity => O(n) if the index is out of reach
    # Space Complexity => O(1)
    def index(self, index):
        currentNode = self.head
        count = 0

        while currentNode:
            count += 1
            if count == index:
                return currentNode.getValue()
            else:
                currentNode = currentNode.getNext()

    # Method checking wether a value is in the Linked List or not, returning True if found, false otherwise
    # Iterative Method
    # Time Complexity => O(n) if the node is not in the linked list
    # Space Complexity => O(1)
    def search(self, value):
        currentNode = self.head
        found = False

        while currentNode is not None and not found:
            if currentNode.getValue() == value:
                found = True
                return found
            else:
                currentNode = currentNode.getNext()
        if not found:
            return 'Value not present in the List'

    # Method checking wether a value is in the Linked List or not, returning True if found, false otherwise
    # Recursive Method
    # Time Complexity => O(n)
    # Space Complexity => O(n)
    def searchR(self, head, value):
        if head == None:
            return False

        elif head.getValue() == value:
            return True

        return self.searchR(head.next, value)

    # Method inserting a value at a specific index
    # Time Complexity => O(n) if it has to traverse until the tail and we do not know about the previous Node
    # Space Complexity => O(1)
    def insert(self, value, index):
        newNode = Node(value)
        currentNode = self.head
        previousNode = None
        count = 0

        if self.head == None:
            self.head = newNode

        elif index == 0 or index == 1:
            newNode.setNext(self.head)
            self.head = newNode

        else:
            while currentNode:
                count += 1

                if count == index - 1:
                    previousNode = currentNode
                    nextNode = previousNode.next
                    currentNode.next = newNode
                    newNode.next = nextNode
                    return count
                else:
                    currentNode = currentNode.getNext()

    # Method deleting a value in the Linked List
    # Time Complexity => O(n) since the previous Node is unknown, it has to traverse through the linked list
    # Space Complexity => O(1)
    def delete(self, value):
        currentNode = self.head
        previousNode = None
        found = False

        while not found:
            if currentNode.getValue() == value:
                found = True
            else:
                previousNode = currentNode
                currentNode = currentNode.getNext()

        if previousNode == None:
            self.head = currentNode.getNext()
        else:
            previousNode.setNext(currentNode.getNext())


import sublime
import sublime_plugin

import re

class ReactExpanderAutocomplete(sublime_plugin.EventListener):
	def on_query_completions(self, view, prefix, locations):
		sn = view.scope_name(locations[0])

		is_ok = False
		if "meta.block.tsx" in sn or "meta.block.jsx" in sn:
			is_ok = True
		if not is_ok:
			return None

		p = prefix.strip()

		return [
			[
				"{P}\t<{P}><{P}/>".format(P=p),
				"<%s>\n\t$1\n</%s>" % (p, p)
			],
			[
				"{P}\t<{P}/>".format(P=p),
				"<%s $1 />" % (p)
			],
		]


import common, sql
import os, json
import subprocess, shlex
from dateutil import parser as dt
import dateutil
import requests, json
import logging, coloredlogs
coloredlogs.install()
ecosystem = 'Composer'
from packaging import version as PythonVersion

def isValidVersion(v):
    try:
        v = PythonVersion.Version(v)
        return True
    except:
        logging.info(v)
        return False

def version_sorting(vers):
    temp=[]
    for v in vers:
        if isValidVersion(v):
            temp.append(v)
    vers=temp

    #https://stackoverflow.com/a/58035970/1445015
    return sorted(vers, key=lambda x: PythonVersion.Version(x))

def get_repository_url(package):
    repository = None
    assert package.count('/') == 1

    try:
        url = 'https://repo.packagist.org/p2/{}.json'.format(package)
        page = requests.get(url)
        data = json.loads(page.content)
        data = data['packages'][package][0]
        data = data['source']['url']
        assert data.endswith('.git')
        repository = data[:-len('.git')]

        # if 'source_code_uri' in data:
        #     repository = data['source_code_uri']
        if not repository:
            repository = common.search_for_github_repo(package, data)
    except Exception as e:
        logging.info(e)

    print(package, repository)
    if repository:
        return repository
    else:
        return common.norepo

def get_release_info(package, version):
    #composer api sends release as properly sorted: https://packagist.org/packages/drupal/core
    release_date = prior_release = None

    url = 'https://repo.packagist.org/p2/{}.json'.format(package)
    print(url)
    page = requests.get(url)
    if page.status_code == 200:
        data = json.loads(page.content)
        assert 'packages' in data and package in data['packages']

        releases = data['packages'][package]
        versions = []
        for item in releases:
            cur = item['version']
            if cur.startswith('v'):
                cur =  cur[1:]
            versions.append(cur)
            if version == cur:
                if 'time' in item:
                    release_date = dt.parse(item['time']).astimezone(dateutil.tz.tzutc())

        if version in versions:
            idx = versions.index(version)
            if idx < len(versions) - 1: #oldest
                prior_release = versions[idx+1] #sorted from recent to oldest
        else:
            logging.info(version)

    return release_date, prior_release

if __name__=='__main__':
    #get repository remote url of packages
    packages = common.getPackagesToSearchRepository(ecosystem)
    for item in packages:
        id, repo = item['id'], get_repository_url(item['name'])
        sql.execute('update package set repository_url=%s where id = %s',(repo,id))

    #get release info (publish date and prior release) for each fixing release
    packages = common.getPackagesToProcessRelease(ecosystem)
    for item in packages:
        package_id, package, version = item['package_id'], item['package'], item['version']
        publish_date, prior_release = get_release_info(package,version)

        print(package, package_id, version, publish_date, prior_release)
        sql.execute('insert into release_info values(null,%s,%s,%s,%s)',(package_id, version, publish_date, prior_release))


from selenium.webdriver.common.by import By
from behave import given, when, then
from selenium.webdriver.support import expected_conditions as EC
from time import sleep

ADD_TO_CART = (By.CSS_SELECTOR, "button[type='submit'].product-form__submit.button.button--secondary")
ADD_TO_CART_CONFIRM = (By.CSS_SELECTOR, "h3.label")
VIEW_CART = (By.CSS_SELECTOR, "div.button-container a[href='/cart']")

@when('Click to add product to cart')
def add_to_cart(context):
    context.app.product_detail_page.add_to_cart()
    sleep(5)

    #context.driver.find_element(*ADD_TO_CART).click()

@when("Click View my cart")
def click_view_cart(context):
    context.app.product_detail_page.click_view_cart()
    # context.driver.wait.until(EC.element_to_be_clickable(VIEW_CART)).click()
    # sleep(3)

@then('Verify that the Subtotal is shown for confirmation')
def verify_add_to_cart_confirm(context):
    context.app.product_detail_page.verify_add_to_cart_confirm()
    # expected_text = 'Subtotal'
    # actual_text = context.driver.find_element(*ADD_TO_CART_CONFIRM).text
    # assert actual_text == expected_text, f'Expected {expected_text} but got {actual_text}'


# 迪菲-赫尔曼密钥交换流程
import random

def eve(func):
    def _func(*args):
        ans = []
        for i in args:
            if type(i) == int:
                ans.append(i)
        print("eve knows", *ans)
        return func(*args)

    return _func

class Peer:

    def __init__(self):
        self.secret = -1
        self.send_number = -1
        self.recv_number = -1

    def send(self, other, number):
        self.send_number = number
        self.solve()
        other.recv(pow(g, number, p))

    @eve
    def recv(self, number):
        self.recv_number = number
        self.solve()

    def solve(self):
        if self.send_number != -1 and self.recv_number != -1:
            self.secret = pow(self.recv_number, self.send_number, p)

p = int(1e9) + 7
g = 1665161446161321

Alice = Peer()
Bob = Peer()

Alice.send(Bob, random.randint(1, 48516168476161986476984))
Bob.send(Alice, random.randint(1, 48516168476161986476984))

print("alice secret is", Alice.secret)
print("bob secret is", Bob.secret)


# Install Python Packages
#!pip install openai tiktoken

# Import Python Packages
import platform
import os
import openai
import tiktoken
import time

print('Python: ', platform.python_version())

# Count the Number of Tokens
def count_tokens(filename):
    encoding = tiktoken.get_encoding("gpt2")
    with open(filename, 'r') as f:
        text = f.read()

    input_ids = encoding.encode(text)
    num_tokens = len(input_ids)
    return num_tokens

# Count the Number of Tokens in a String
def count_tokens_in_string(text):
    encoding = tiktoken.get_encoding("gpt2")
    input_ids = encoding.encode(text)
    num_tokens = len(input_ids)
    return num_tokens

filename = "inputFile.txt"
num_tokens = count_tokens(filename=filename)
print("Number of tokens:  ", num_tokens)

# Break up text into chunks of 2000 tokens with an overlap of 100 tokens
def break_up_file_to_chunks(filename, chunk_size=2000, overlap=100):
    encoding = tiktoken.get_encoding("gpt2")
    with open(filename, 'r') as f:
        text = f.read()

    tokens = encoding.encode(text)
    num_tokens = len(tokens)

    chunks = []
    for i in range(0, num_tokens, chunk_size - overlap):
        chunk = tokens[i:i + chunk_size]
        chunks.append(chunk)

    return chunks

# Modified the function break_up_file_to_chunks to work with a list of strings
def break_up_text_to_chunks(text_list, chunk_size=2000, overlap=100):
    encoding = tiktoken.get_encoding("gpt2")

    tokens = [encoding.encode(text) for text in text_list]
    tokens = [token for sublist in tokens for token in sublist]  # Flatten the list
    num_tokens = len(tokens)

    chunks = []
    for i in range(0, num_tokens, chunk_size - overlap):
        chunk = tokens[i:i + chunk_size]
        chunks.append(chunk)

    return chunks

chunks = break_up_file_to_chunks(filename)
for i, chunk in enumerate(chunks):
    print(f"Chunk {i}: {len(chunk)} tokens")

# Set OpenAI API Key
os.environ["OPENAI_API_KEY"] = 'OPENAI_API_KEY goes HERE'
openai.api_key = os.getenv("OPENAI_API_KEY")

# Recursive function to handle API rate limits and large texts
def summarize_text(text_list, max_tokens):
    if count_tokens_in_string(str(text_list)) > max_tokens:
        text_list = break_up_text_to_chunks(text_list)

        summary_list = []
        for text_chunk in text_list:
            prompt_request = "Summarize this long summary section: " + encoding.decode(text_chunk)

            try:
                response = openai.Completion.create(
                    model="text-davinci-003",
                    prompt=prompt_request,
                    temperature=.5,
                    max_tokens=max_tokens,
                    top_p=1,
                    frequency_penalty=0,
                    presence_penalty=0
                )
                summary_list.append(response["choices"][0]["text"].strip())
                time.sleep(1)  # Add a delay between each API request to avoid hitting rate limits
            except openai.api_resources.completion.CompletionError as e:
                if e.args[0]['error']['message'] == 'Rate limit exceeded':
                    print('Rate limit exceeded. Waiting for 60 seconds.')
                    time.sleep(60)
                    return summarize_text(text_list, max_tokens)
                elif e.args[0]['error']['message'] == 'Token limit exceeded':
                    print('Token limit exceeded. Breaking the text into smaller chunks.')
                    text_chunks = break_up_text_to_chunks([text_list])
                    summarized_text = []
                    for chunk in text_chunks:
                        summarized_text.append(summarize_text(encoding.decode(chunk), max_tokens))
                    return ' '.join(summarized_text)

        return summarize_text(summary_list, max_tokens)  # Recursive call to handle the case where the summarized text still exceeds the maximum token limit
    else:
        prompt_request = "Consolidate these paper summaries: " + str(text_list)

        try:
            response = openai.Completion.create(
                model="text-davinci-003",
                prompt=prompt_request,
                temperature=.5,
                max_tokens=max_tokens,
                top_p=1,
                frequency_penalty=0,
                presence_penalty=0
            )
            return response["choices"][0]["text"].strip()
        except openai.api_resources.completion.CompletionError as e:
            if e.args[0]['error']['message'] == 'Rate limit exceeded':
                print('Rate limit exceeded. Waiting for 60 seconds.')
                time.sleep(60)
                return summarize_text(text_list, max_tokens)
            elif e.args[0]['error']['message'] == 'Token limit exceeded':
                print('Token limit exceeded. Breaking the text into smaller chunks.')
                text_chunks = break_up_text_to_chunks([text_list])
                summarized_text = []
                for chunk in text_chunks:
                    summarized_text.append(summarize_text(encoding.decode(chunk), max_tokens))
                return ' '.join(summarized_text)

# Summarize the text one chunk at a time
prompt_response = []
encoding = tiktoken.get_encoding("gpt2")
chunks = break_up_file_to_chunks(filename)

for i, chunk in enumerate(chunks):
    prompt_request = "Summarize this partial section of a paper: " + encoding.decode(chunks[i])
    summary = summarize_text(prompt_request, 2000)
    prompt_response.append(summary)

    #Print to the user the partial section summaries
    print("Summary of each part ",i,": ",summary)

#print("These are the aggregated chunk summaries:\n")
#print(prompt_response)

# Consolidate the summaries
prompt_request = "Consolidate these paper summaries: " + ' '.join(prompt_response)
paper_summary = summarize_text(prompt_request, 2000)

# Summary of Summaries
print("This is the final overall summary: \n")
print(paper_summary)


# Author: Xinshuo Weng
# email: xinshuo.weng@gmail.com
import numpy as np, os, matplotlib.pyplot as plt, colorsys, random, matplotlib.patches as patches
import matplotlib.collections as plycollections
from matplotlib.patches import Ellipse
from skimage.measure import find_contours
# from scipy.stats import norm, chi2

# import matplotlib as mpl; mpl.use('Agg')
# import warnings
# warnings.filterwarnings("ignore", message="numpy.dtype size changed")
# warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
# from warnings import catch_warnings, simplefilter
# with catch_warnings(record=True):
    # simplefilter('ignore', FutureWarning)
from .private import save_vis_close_helper, get_fig_ax_helper
from xinshuo_math.private import safe_2dptsarray, safe_bbox
from xinshuo_math import pts_euclidean, bbox_TLBR2TLWH, bboxcheck_TLBR
from xinshuo_miscellaneous import islogical, islist, isstring, is2dptsarray_confidence, is2dptsarray_occlusion, is2dptsarray, isdict, list_reorder, list2tuple, islistofstring, ifconfscalar, isscalar, isnparray
from xinshuo_io import mkdir_if_missing, save_image

color_set = ['r', 'b', 'g', 'c', 'm', 'y', 'k', 'w', 'lime', 'cyan', 'aqua']
color_set_big = ['aqua', 'azure', 'red', 'black', 'blue', 'brown', 'cyan', 'darkblue', 'fuchsia', 'gold', 'green', 'grey', 'indigo', 'magenta', 'lime', 'yellow', 'white', 'tomato', 'salmon']
marker_set = ['o', 'v', '^', '<', '>', '1', '2', '3', '4', '8', 's', 'p', '*', 'h', 'H', '+', 'x', 'D', 'd']
hatch_set = [None, 'o', '/', '\\', '|', '-', '+', '*', 'x', 'O', '.']
linestyle_set = ['-', '--', '-.', ':', None, ' ', 'solid', 'dashed']
dpi = 80

def visualize_bbox(input_bbox, linewidth=0.5, edge_color_index=15, scores=None, threshold=0.0, textsize=8,
    fig=None, ax=None, save_path=None, vis=False, warning=True, debug=True, closefig=True):
    '''
    visualize a set of bounding box

    parameters:
        input_bbox:     a list of 4 elements, a listoflist of 4 elements: e.g., [[1,2,3,4], [5,6,7,8]],
                        a numpy array with shape or (N, 4) or (4, )
                        TLBR format
        scores:         a list of floating numbers representing the confidences
    '''
    if islist(input_bbox) and len(input_bbox) == 0:
        return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig)
    elif isnparray(input_bbox) and input_bbox.size == 0:
        return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig)

    np_bboxes = safe_bbox(input_bbox, warning=warning, debug=debug)
    if debug: assert bboxcheck_TLBR(np_bboxes, warning=warning, debug=debug), 'input bounding boxes are not correct'
    edge_color = color_set_big[edge_color_index % len(color_set_big)]

    np_bboxes = bbox_TLBR2TLWH(np_bboxes, warning=warning, debug=debug)              # convert TLBR format to TLWH format
    for bbox_index in range(np_bboxes.shape[0]):
        bbox_tmp = np_bboxes[bbox_index, :]
        if scores is not None:
            score = float(scores[bbox_index])
            if score < threshold: continue
            caption = '{:.2f}'.format(score)

            # score = str(scores[bbox_index])
            # caption = '%s' % (score)

            ax.text(bbox_tmp[0], bbox_tmp[1] + textsize, caption, color='r', size=textsize, backgroundcolor='none')

        ax.add_patch(plt.Rectangle((bbox_tmp[0], bbox_tmp[1]), bbox_tmp[2], bbox_tmp[3], fill=False, edgecolor=edge_color, linewidth=linewidth))
    return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig)

def visualize_pts_array(input_pts, color_index=0, pts_size=20, label=False, label_list=None, label_size=20, vis_threshold=0.3,
    covariance=False, plot_occl=False, xlim=None, ylim=None,
    fig=None, ax=None, save_path=None, vis=False, warning=True, debug=True, closefig=True):
    '''
    plot keypoints with covariance ellipse

    parameters:
        pts_array:      2(3) x num_pts numpy array, the third channel could be confidence or occlusion
    '''
    # obtain the points
    try: pts_array = safe_2dptsarray(input_pts, homogeneous=True, warning=warning, debug=debug)
    except AssertionError: pts_array = safe_2dptsarray(input_pts, homogeneous=False, warning=warning, debug=debug)
    if debug: assert is2dptsarray(pts_array) or is2dptsarray_occlusion(pts_array) or is2dptsarray_confidence(pts_array), 'input points are not correct'
    num_pts = pts_array.shape[1]

    # obtain a label list if required but not provided
    if debug: assert islogical(label), 'label flag is not correct'
    if label and (label_list is None): label_list = [str(i) for i in xrange(num_pts)]
    if label_list is not None and debug: assert islistofstring(label_list), 'labels are not correct'

    # obtain the color index
    if islist(color_index):
        if debug: assert not (plot_occl or covariance) , 'the occlusion or covariance are not compatible with plotting different colors during scattering'
        color_tmp = [color_set_big[index_tmp] for index_tmp in color_index]
    else: color_tmp = color_set_big[color_index % len(color_set_big)]

    fig, ax = get_fig_ax_helper(fig=fig, ax=ax)
    std, conf = None, 0.95
    if is2dptsarray(pts_array):             # only 2d points without third rows
        if debug and islist(color_tmp): assert len(color_tmp) == num_pts, 'number of points to plot is not equal to number of colors provided'
        ax.scatter(pts_array[0, :], pts_array[1, :], color=color_tmp, s=pts_size)
        pts_visible_index = range(pts_array.shape[1])
        pts_ignore_index = []
        pts_invisible_index = []
    else:
        # automatically justify if the third row is confidence or occlusion flag
        num_float_elements = np.where(np.logical_and(pts_array[2, :] != -1, np.logical_and(pts_array[2, :] != 0, pts_array[2, :] != 1)))[0].tolist()
        if len(num_float_elements) > 0: type_3row = 'conf'
        else: type_3row = 'occu'

        if type_3row == 'occu':
            pts_visible_index   = np.where(pts_array[2, :] == 1)[0].tolist()              # plot visible points in red color
            pts_ignore_index    = np.where(pts_array[2, :] == -1)[0].tolist()             # do not plot points with annotation, usually visible, but not annotated
            pts_invisible_index = np.where(pts_array[2, :] == 0)[0].tolist()              # plot invisible points in blue color
        else:
            pts_visible_index   = np.where(pts_array[2, :] > vis_threshold)[0].tolist()
            pts_invisible_index    = np.where(pts_array[2, :] <= vis_threshold)[0].tolist()
            pts_ignore_index = []

        if debug and islist(color_tmp): assert len(color_tmp) == len(pts_visible_index), 'number of points to plot is not equal to number of colors provided'
        ax.scatter(pts_array[0, pts_visible_index], pts_array[1, pts_visible_index], color=color_tmp, s=pts_size)
        if plot_occl: ax.scatter(pts_array[0, pts_invisible_index], pts_array[1, pts_invisible_index], color=color_set_big[(color_index+1) % len(color_set_big)], s=pts_size)
        if covariance: visualize_pts_covariance(pts_array[0:2, :], std=std, conf=conf, fig=fig, ax=ax, debug=debug, color=color_tmp)

    if plot_occl: not_plot_index = pts_ignore_index
    else: not_plot_index = pts_ignore_index + pts_invisible_index
    if label_list is not None:
        for pts_index in xrange(num_pts):
            label_tmp = label_list[pts_index]
            if pts_index in not_plot_index: continue
            else:
                # note that the annotation is based on the coordinate instead of the order of plotting the points, so the orider in pts_index does not matter
                if islist(color_index): plt.annotate(label_tmp, xy=(pts_array[0, pts_index], pts_array[1, pts_index]), xytext=(-1, 1), color=color_set_big[(color_index[pts_index]+5) % len(color_set_big)], textcoords='offset points', ha='right', va='bottom', fontsize=label_size)
                else: plt.annotate(label_tmp, xy=(pts_array[0, pts_index], pts_array[1, pts_index]), xytext=(-1, 1), color=color_set_big[(color_index+5) % len(color_set_big)], textcoords='offset points', ha='right', va='bottom', fontsize=label_size)

    # set axis
    if xlim is not None:
        if debug: assert islist(xlim) and len(xlim) == 2, 'the x lim is not correct'
        plt.xlim(xlim[0], xlim[1])
    if ylim is not None:
        if debug: assert islist(ylim) and len(ylim) == 2, 'the y lim is not correct'
        plt.ylim(ylim[0], ylim[1])

    return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig, transparent=False)

def visualize_lines(lines_array, color_index=0, line_width=3, fig=None, ax=None, vis=True, save_path=None, debug=True, closefig=True):
    '''
    plot lines

    parameters:
        lines_array:            4 x num_lines, each column denotes (x1, y1, x2, y2)
    '''
    if debug: assert islinesarray(lines_array), 'input array of lines are not correct'
    fig, ax = get_fig_ax_helper(fig=fig, ax=ax)

    # plot lines
    num_lines = lines_array.shape[1]
    lines_all = []
    for line_index in range(num_lines):
        line_tmp = lines_array[:, line_index]
        lines_all.append([tuple([line_tmp[0], line_tmp[1]]), tuple([line_tmp[2], line_tmp[3]])])

    line_col = plycollections.LineCollection(lines_all, linewidths=line_width, colors=color_set[color_index])
    ax.add_collection(line_col)
        # ax.plot([line_tmp[0], line_tmp[2]], [line_tmp[1], line_tmp[3]], color=color_set[color_index], linewidth=line_width)

    return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig)

def visualize_pts_line(pts_array, line_index_list, method=2, seed=0, alpha=0.5,
    vis_threshold=0.3, pts_size=20, line_size=10, line_color_index=0,
    fig=None, ax=None, save_path=None, vis=False, warning=True, debug=True, closefig=True):
    '''
    given a list of index, and a point array, to plot a set of points with line on it

    parameters:
        pts_array:          2(3) x num_pts
        line_index_list:    a list of index
        method:             1: all points are connected, if some points are missing in the middle, just ignore that point and connect the two nearby points
                            2: if some points are missing in the middle of a line, the line is decomposed to sub-lines
        vis_threshold:      confidence to draw the points

    '''
    if debug:
        assert is2dptsarray(pts_array) or is2dptsarray_occlusion(pts_array) or is2dptsarray_confidence(pts_array), 'input points are not correct'
        assert islist(line_index_list), 'the list of index is not correct'
        assert method in [1, 2], 'the plot method is not correct'

    num_pts = pts_array.shape[1]
    # expand the pts_array to 3 rows if the confidence row is not provided
    if pts_array.shape[0] == 2: pts_array = np.vstack((pts_array, np.ones((1, num_pts))))
    fig, ax = get_fig_ax_helper(fig=fig, ax=ax)
    np.random.seed(seed)
    color_option = 'hsv'

    if color_option == 'rgb': color_set_random = np.random.rand(3, num_pts)
    elif color_option == 'hsv':
        h_random = np.random.rand(num_pts, )
        color_set_random = np.zeros((3, num_pts), dtype='float32')
        for pts_index in range(num_pts): color_set_random[:, pts_index] = colorsys.hsv_to_rgb(h_random[pts_index], 1, 1)

    line_color = color_set[line_color_index]
    pts_line = pts_array[:, line_index_list]

    if method == 1:
        valid_pts_list = np.where(pts_line[2, :] > vis_threshold)[0].tolist()
        pts_line_tmp = pts_line[:, valid_pts_list]
        ax.plot(pts_line_tmp[0, :], pts_line_tmp[1, :], lw=line_size, color=line_color, alpha=alpha)      # plot all lines

        # plot all points
        for pts_index in valid_pts_list:
            pts_index_original = line_index_list[pts_index]
            # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)
            ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], marker='o', ms=pts_size, lw=line_size, color=color_set_random[:, pts_index], alpha=alpha)
    else:
        not_valid_pts_list = np.where(pts_line[2, :] < vis_threshold)[0].tolist()
        if len(not_valid_pts_list) == 0:            # all valid
            ax.plot(pts_line[0, :], pts_line[1, :], lw=line_size, color=line_color, alpha=alpha)

            # plot points
            for pts_index in line_index_list:
                # ax.plot(pts_array[0, pts_index], pts_array[1, pts_index], 'o', color=color_set_big[pts_index % len(color_set_big)], alpha=alpha)
                ax.plot(pts_array[0, pts_index], pts_array[1, pts_index], marker='o', ms=pts_size, lw=line_size, color=color_set_random[:, pts_index], alpha=alpha)
        else:
            prev_index = 0
            for not_valid_index in not_valid_pts_list:
                plot_list = range(prev_index, not_valid_index)
                pts_line_tmp = pts_line[:, plot_list]
                ax.plot(pts_line_tmp[0, :], pts_line_tmp[1, :], lw=line_size, color=line_color, alpha=alpha)

                # plot points
                for pts_index in plot_list:
                    pts_index_original = line_index_list[pts_index]
                    ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], marker='o', ms=pts_size, lw=line_size, color=color_set_random[:, pts_index_original], alpha=alpha)
                    # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)

                prev_index = not_valid_index + 1

            pts_line_tmp = pts_line[:, prev_index:]
            ax.plot(pts_line_tmp[0, :], pts_line_tmp[1, :], lw=line_size, color=line_color, alpha=alpha)      # plot last line

            # plot last points
            for pts_index in range(prev_index, pts_line.shape[1]):
                pts_index_original = line_index_list[pts_index]
                # ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], 'o', color=color_set_big[pts_index_original % len(color_set_big)], alpha=alpha)
                ax.plot(pts_array[0, pts_index_original], pts_array[1, pts_index_original], marker='o', ms=pts_size, lw=line_size, color=color_set_random[:, pts_index_original], alpha=alpha)

    return save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig)

def visualize_pts_covariance(pts_array, conf=None, std=None, fig=None, ax=None, debug=True, **kwargs):
    """
    Plots an `nstd` sigma ellipse based on the mean and covariance of a point
    "cloud" (points, an Nx2 array).

    Parameters
    ----------
        pts_array       : 2 x N numpy array of the data points.
        std            : The radius of the ellipse in numbers of standard deviations.
            Defaults to 2 standard deviations.
        ax : The axis that the ellipse will be plotted on. Defaults to the
            current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
    -------
        A matplotlib ellipse artist
    """
    if debug:
        assert is2dptsarray(pts_array), 'input points are not correct: (2, num_pts) vs %s' % print_np_shape(pts_array)
        if conf is not None: assert ifconfscalar(conf), 'the confidence is not in a good range'
        if std is not None: assert ispositiveinteger(std), 'the number of standard deviation should be a positive integer'

    pts_array = np.transpose(pts_array)
    center = pts_array.mean(axis=0)
    covariance = np.cov(pts_array, rowvar=False)
    return visualize_covariance_ellipse(covariance=covariance, center=center, conf=conf, std=std, fig=fig, ax=ax, debug=debug, **kwargs), np.sqrt(covariance[0, 0]**2 + covariance[1, 1]**2)

def visualize_covariance_ellipse(covariance, center, conf=None, std=None, fig=None, ax=None, debug=True, **kwargs):
    """
    Plots an `nstd` sigma error ellipse based on the specified covariance
    matrix (`cov`). Additional keyword arguments are passed on to the
    ellipse patch artist.

    Parameters
        covariance      : The 2x2 covariance matrix to base the ellipse on
        center          : The location of the center of the ellipse. Expects a 2-element sequence of [x0, y0].
        conf            : a floating number between [0, 1]
        std             : The radius of the ellipse in numbers of standard deviations. Defaults to 2 standard deviations.
        ax              : The axis that the ellipse will be plotted on. Defaults to the current axis.
        Additional keyword arguments are pass on to the ellipse patch.

    Returns
        A covariance ellipse
    """
    if debug:
        if conf is not None: assert isscalar(conf) and conf >= 0 and conf <= 1, 'the confidence is not in a good range'
        if std is not None: assert ispositiveinteger(std), 'the number of standard deviation should be a positive integer'
    fig, ax = get_fig_ax_helper(fig=fig, ax=ax)

    def eigsorted(covariance):
        vals, vecs = np.linalg.eigh(covariance)
        # order = vals.argsort()[::-1]
        # return vals[order], vecs[:,order]
        return vals, vecs

    if conf is not None: conf = np.asarray(conf)
    elif std is not None: conf = 2 * norm.cdf(std) - 1
    else: raise ValueError('One of `conf` and `std` should be specified.')
    r2 = chi2.ppf(conf, 2)
    vals, vecs = eigsorted(covariance)
    theta = np.degrees(np.arctan2(*vecs[:,0][::-1]))
    # theta = np.degrees(np.arctan2(*vecs[::-1, 0]))
    # Width and height are "full" widths, not radius
    # width, height = 2 * std * np.sqrt(vals)
    width, height = 2 * np.sqrt(np.sqrt(vals) * r2)
    # width, height = 2 * np.sqrt(vals[:, None] * r2)
    ellipse = Ellipse(xy=center, width=width, height=height, angle=theta, **kwargs)
    ellipse.set_facecolor('none')

    ax.add_artist(ellipse)
    return ellipse

def visualize_pts(pts, title=None, fig=None, ax=None, display_range=False, xlim=[-100, 100], ylim=[-100, 100], display_list=None, covariance=False, mse=False, mse_value=None, vis=True, save_path=None, debug=True, closefig=True):
    '''
    visualize point scatter plot

    parameter:
        pts:            2 x num_pts numpy array or a dictionary containing 2 x num_pts numpy array
    '''

    if debug:
        if isdict(pts):
            for pts_tmp in pts.values(): assert is2dptsarray(pts_tmp) , 'input points within dictionary are not correct: (2, num_pts) vs %s' % print_np_shape(pts_tmp)
            if display_list is not None:
                assert islist(display_list) and len(display_list) == len(pts), 'the input display list is not correct'
                assert CHECK_EQ_LIST_UNORDERED(display_list, pts.keys(), debug=debug), 'the input display list does not match the points key list'
            else: display_list = pts.keys()
        else: assert is2dptsarray(pts), 'input points are not correct: (2, num_pts) vs %s' % print_np_shape(pts)
        if title is not None: assert isstring(title), 'title is not correct'
        else: title = 'Point Error Vector Distribution Map'
        assert islogical(display_range), 'the flag determine if to display in a specific range should be logical value'
        if display_range:
            assert islist(xlim) and islist(ylim) and len(xlim) == 2 and len(ylim) == 2, 'the input range for x and y is not correct'
            assert xlim[1] > xlim[0] and ylim[1] > ylim[0], 'the input range for x and y is not correct'

    # figure setting
    width, height = 1024, 1024
    fig, _ = get_fig_ax_helper(fig=fig, ax=ax, width=width, height=height)
    if ax is None:
        plt.title(title, fontsize=20)
        if isdict(pts):
            num_pts_all = pts.values()[0].shape[1]
            if all(pts_tmp.shape[1] == num_pts_all for pts_tmp in pts.values()):
                plt.xlabel('x coordinate (%d points)' % pts.values()[0].shape[1], fontsize=16)
                plt.ylabel('y coordinate (%d points)' % pts.values()[0].shape[1], fontsize=16)
            else:
                print('number of points is different across different methods')
                plt.xlabel('x coordinate', fontsize=16)
                plt.ylabel('y coordinate', fontsize=16)
        else:
            plt.xlabel('x coordinate (%d points)' % pts.shape[1], fontsize=16)
            plt.ylabel('y coordinate (%d points)' % pts.shape[1], fontsize=16)
        plt.axis('equal')
        ax = plt.gca()
        ax.grid()

    # internal parameters
    pts_size = 5
    std = None
    conf = 0.98
    color_index = 0
    marker_index = 0
    hatch_index = 0
    alpha = 0.2
    legend_fontsize = 10
    scale_distance = 48.8
    linewidth = 2

    # plot points
    handle_dict = dict()    # for legend
    if isdict(pts):
        num_methods = len(pts)
        assert len(color_set) * len(marker_set) >= num_methods and len(color_set) * len(hatch_set) >= num_methods, 'color in color set is not enough to use, please use different markers'
        mse_return = dict()
        for method_name, pts_tmp in pts.items():
            color_tmp = color_set[color_index]
            marker_tmp = marker_set[marker_index]
            hatch_tmp = hatch_set[hatch_index]

            # plot covariance ellipse
            if covariance: _, covariance_number = visualize_pts_covariance(pts_tmp[0:2, :], std=std, conf=conf, ax=ax, debug=debug, color=color_tmp, hatch=hatch_tmp, linewidth=linewidth)
            handle_tmp = ax.scatter(pts_tmp[0, :], pts_tmp[1, :], color=color_tmp, marker=marker_tmp, s=pts_size, alpha=alpha)
            if mse:
                if mse_value is None:
                    num_pts = pts_tmp.shape[1]
                    mse_tmp, _ = pts_euclidean(pts_tmp[0:2, :], np.zeros((2, num_pts), dtype='float32'), debug=debug)
                else:
                    mse_tmp = mse_value[method_name]
                display_string = '%s, MSE: %.1f (%.1f um), Covariance: %.1f' % (method_name, mse_tmp, mse_tmp * scale_distance, covariance_number)
                mse_return[method_name] = mse_tmp
            else: display_string = method_name
            handle_dict[display_string] = handle_tmp
            color_index += 1
            if color_index / len(color_set) == 1:
                marker_index += 1
                hatch_index += 1
                color_index = color_index % len(color_set)

        # reorder the handle before plot
        handle_key_list = handle_dict.keys()
        handle_value_list = handle_dict.values()
        order_index_list = [display_list.index(method_name_tmp.split(', ')[0]) for method_name_tmp in handle_dict.keys()]
        ordered_handle_key_list = list_reorder(handle_key_list, order_index_list, debug=debug)
        ordered_handle_value_list = list_reorder(handle_value_list, order_index_list, debug=debug)
        plt.legend(list2tuple(ordered_handle_value_list), list2tuple(ordered_handle_key_list), scatterpoints=1, markerscale=4, loc='lower left', fontsize=legend_fontsize)

    else:
        color_tmp = color_set[color_index]
        marker_tmp = marker_set[marker_index]
        hatch_tmp = hatch_set[hatch_index]
        handle_tmp = ax.scatter(pts[0, :], pts[1, :], color=color_tmp, marker=marker_tmp, s=pts_size, alpha=alpha)

        # plot covariance ellipse
        if covariance: _, covariance_number = visualize_pts_covariance(pts[0:2, :], std=std, conf=conf, ax=ax, debug=debug, color=color_tmp, hatch=hatch_tmp, linewidth=linewidth)

        if mse:
            if mse_value is None:
                num_pts = pts.shape[1]
                mse_tmp, _ = pts_euclidean(pts[0:2, :], np.zeros((2, num_pts), dtype='float32'), debug=debug)
                display_string = 'MSE: %.1f (%.1f um), Covariance: %.1f' % (mse_tmp, mse_tmp * scale_distance, covariance_number)
                mse_return = mse_tmp
            else:
                display_string = 'MSE: %.1f (%.1f um), Covariance: %.1f' % (mse_value, mse_value * scale_distance, covariance_number)
                mse_return = mse_value
            handle_dict[display_string] = handle_tmp
            plt.legend(list2tuple(handle_dict.values()), list2tuple(handle_dict.keys()), scatterpoints=1, markerscale=4, loc='lower left', fontsize=legend_fontsize)

    # display only specific range
    if display_range:
        axis_bin = 10 * 2
        interval_x = (xlim[1] - xlim[0]) / axis_bin
        interval_y = (ylim[1] - ylim[0]) / axis_bin
        plt.xlim(xlim[0], xlim[1])
        plt.ylim(ylim[0], ylim[1])
        plt.xticks(np.arange(xlim[0], xlim[1] + interval_x, interval_x))
        plt.yticks(np.arange(ylim[0], ylim[1] + interval_y, interval_y))
    plt.grid()

    save_vis_close_helper(fig=fig, ax=ax, vis=vis, save_path=save_path, warning=warning, debug=debug, closefig=closefig, transparent=False)
    return mse_return

def random_colors(N, bright=True):
    """
    Generate random colors.
    To get visually distinct colors, generate them in HSV space then
    convert to RGB.
    """
    brightness = 1.0 if bright else 0.7
    hsv = [(i / float(N), 1, brightness) for i in range(N)]
    colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
    # random.shuffle(colors)
    return colors

def apply_mask(image, mask, color, alpha=0.5):
    """Apply the given mask to the image.
    """
    for c in range(3):
        image[:, :, c] = np.where(mask == 1, image[:, :, c] * (1 - alpha) + alpha * color[c] * 255, image[:, :, c])
    return image

def visualize_image_with_bbox_mask(image, boxes, masks, class_ids, class_names, class_to_plot=None, scores=None, alpha=0.7, fig=None, ax=None, color_list=None, title='Mask & Bounding Box Visualization'):
    """
    visualize the image with bbox and mask (and text and score)

    parameters:
        boxes: [num_instance, (x1, y1, x2, y2, class_id)] in image coordinates.
        masks: [height, width, num_instances], numpy images, range in [0, 1]
        class_ids: [num_instances]
        class_names: list of class names of the dataset
        scores: (optional) confidence scores for each box
        class_to_plot:     list of class index in the class_names to plot
        title:
    """
    max_numinstances = 20
    if class_to_plot is None: class_to_plot = range(len(class_names))
    num_instances = boxes.shape[0]          # Number of instances
    if not num_instances: print("\n*** No instances to display *** \n")
    else: assert boxes.shape[0] == masks.shape[-1] == class_ids.shape[0]
    colors = random_colors(max_numinstances)       # Generate random colors
    if color_list is None: color_list = range(num_instances)

    height, width = image.shape[:2]
    # print(height)
    # print(width)
    # zxc

    fig, _ = get_fig_ax_helper(fig=fig, ax=ax, width=width, height=height)
    ax = fig.add_axes([0, 0, 1, 1])
    ax.axis('off')

    # if not ax: fig = plt.figure(figsize=(16, 16))
    # ax = fig.add_axes([0, 0, 1, 0.5])

    # ax.axis('off')
    ax.set_title(title)
    masked_image = image.astype(np.uint8).copy()
    # print(masked_image.shape)
    # save_image(masked_image, '/home/xinshuo/test.jpg')
    # tmp_dir = '/home/xinshuo/Workspace/junk/vis_individual'

    for instance_index in range(num_instances):
        color = colors[color_list[instance_index] % max_numinstances]
        # print(color)
        # zxc

        # skip to visualize the class we do not care
        class_id = class_ids[instance_index]
        if not (class_id in class_to_plot): continue

        # zxc

        # visualize the bbox
        if not np.any(boxes[instance_index]): continue           # Skip this instance. Has no bbox. Likely lost in image cropping.
        x1, y1, x2, y2 = boxes[instance_index]
        # print(x1)
        # print(y1)
        # print(x2)
        # print(y2)
        p = patches.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, alpha=alpha, edgecolor=color, facecolor='none')
        ax.add_patch(p)

        # add the text and score
        score = scores[instance_index] if scores is not None else None
        label = class_names[class_id]
        x = random.randint(x1, (x1 + x2) // 2)
        caption = "{} {:.2f}".format(label, score) if score else label
        ax.text(x1, y1 + 8, caption, color='w', size=8, backgroundcolor='none')

        # add the mask
        mask = masks[:, :, instance_index]
        # print(np.max(mask))
        # print(np.min(mask))
        # save_image(mask, '/home/xinshuo/test.jpg')
        # zxc
        masked_image = apply_mask(masked_image, mask, color)
        # save_image(masked_image, '/home/xinshuo/test%d.jpg' % instance_index)
        # zxc

        # save the individual mask one by one
        # save_tmp_dir = os.path.join(tmp_dir, 'instance_%04d.jpg' % instance_index); mkdir_if_missing(save_tmp_dir)
        # save_image(masked_image.astype('uint8'), save_path=save_tmp_dir)

        # add the contour of the mask
        padded_mask = np.zeros((mask.shape[0] + 2, mask.shape[1] + 2), dtype=np.uint8)
        padded_mask[1:-1, 1:-1] = mask
        contours = find_contours(padded_mask, 0.5)
        for verts in contours:
            verts = np.fliplr(verts) - 1            # Subtract the padding and flip (y, x) to (x, y)
            p = patches.Polygon(verts, facecolor="none", edgecolor=color, alpha=alpha)
            ax.add_patch(p)

    # zxc
    # print(masked_image.shape)
    # zxc
    ax.imshow(masked_image.astype(np.uint8))
    ax.set(xlim=[0, width], ylim=[height, 0], aspect=1)
    return fig, ax


from flask import Flask
from flask_restful import Api
import logging as log

from api.config.apiconf import config

from api.views import VRStats,VRTopPlaces,\
    VRClassifPlaces,VRClassifPlacesAccuracy,VRTop10Places

app = Flask(__name__)
ap = Api(app)

ap.add_resource(VRStats,                    '/api/stats')
ap.add_resource(VRTopPlaces,                '/api/top_places/<string:inp_number>')
ap.add_resource(VRTop10Places,              '/api/top_places')
ap.add_resource(VRClassifPlaces,            '/api/classify')
ap.add_resource(VRClassifPlacesAccuracy,    '/api/classif_accuracy')

if __name__ == '__main__':

    log.basicConfig(filename=config['log']['file'], level=log.DEBUG)

    app.run(debug   = bool(config['flask']['debug']),
            host    = config['flask']['host'],
            port    = int(config['flask']['port'])
            )

    log.info("Flask Restful server is started ...")


import os, signal, time

def traitant(s, _):
    print("signal", s, "capté")

signal.signal(signal.SIGINT, traitant)
print(os.getpid())
#time.sleep(30)
signal.pause()

# signal.pause(): à la réception d'un signal: termine.
# time.sleep(n):
# - Python 3.4- : à la reception d'un signal: termine => on n'est jamais
# assuré de dormir n secondes.
# - Python 3.5+ : à la reception d'un signal, exécute le traitant associé et
# poursuit son sommeil => on est assuré de dormir au moins n secondes.


""" Documentation checker

A command-line tool for checking source code documentation requirements.

Authors:
  - Ogunniyi Owamamwen
  - Sheyla Norton
  -
"""
from tictactoe import player_control, create_player_board, player_winner, player_draw, display_board, start_tictactoe

# The main function call other functions to run
# This mean one entry point

def main():
    print("-------------------------------------------\nThe grid with integer values is an example\nplease choose from number\n-------------------------------------------")
    player = player_control("")
    board = create_player_board()
    while not (player_winner(board) or player_draw(board)):
        display_board(board)
        start_tictactoe(player, board)
        player = player_control(player)
    display_board(board)
    print("Winner of the game with three point")

if __name__ == "__main__":
    main()