# This script does the following:
#
# 1. Steps through all of the shapefiles associated with the aerial photos and
# determines whether the shapefile falls entirely within in the fjord. Photos
# that don't fall entirely within the fjord are excluded from analysis. A file
# titled 'input_files.npy' is created that contains the list of photos to be
# processed.
#
# 2. Steps through all of the photos in the 'input_files.npy' file and
# performs image segmentation. For each it produces a npz file that contains
# the total number of pixels (npixels), an array with the area of each
# individual iceberg (icebergArea), the pixel size (pixArea), and the edges
# of the icebergs (edges) for plotting purposes. It also produces a figure
# to show the results of the image segmentation.

import numpy as np
from matplotlib import pyplot as plt
import matplotlib

import cv2

import glob
import os

from scipy.ndimage.filters import gaussian_filter

import multiprocessing as mp
import timeit

import shapefile

from shapely.geometry import Polygon, Point

plt.ioff()
#%%

def findIcebergs(input_file):
    # https://machinelearningknowledge.ai/image-segmentation-in-python-opencv/

    print('Processing image ' + os.path.basename(input_file))

    img = cv2.imread(input_file)
    # use value
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    _, _, img = cv2.split(hsv)

    # smooth to remove small icebergs and whitecaps
    img = cv2.GaussianBlur(img,(11,11),0)

    npixels = img.shape[0]*img.shape[1] # store total number of pixels; later store number of pixels in each iceberg
    aspect_ratio = float(img.shape[0])/img.shape[1]

    with open(input_file[:-3] + 'jgw') as f:
        pixArea = f.readline().rstrip() # find area of pixel for each image
        pixArea = (np.array(pixArea,dtype='float32'))**2
    f.close()

    if np.max(img) > 200: # image contains icebergs!
        # enhance contrast by stretching the image PROBLEM IF NO ICEBERGS!!
        img = cv2.normalize(img, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F).astype('uint8')

        # add border to image to detect icebergs along the boundary
        bordersize=1
        img = cv2.copyMakeBorder(img, top=bordersize, bottom=bordersize,
                                   left=bordersize, right=bordersize, borderType=cv2.BORDER_CONSTANT, value=0 )

        # threshold image
        _, img_ = cv2.threshold(img, 170, 255, cv2.THRESH_BINARY)
        #_, img_ = cv2.threshold(img,40,255, cv2.THRESH_BINARY)

        ## segment using cluster detection, using canny edge detection
        # find edges
        edges = cv2.dilate(cv2.Canny(img_,0,255),None)

        # detect contours: only external contours, and keep all points along contours
        _, contours, _ = cv2.findContours(edges.copy(),cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

        # remove holes; this command no longer seems necessary?
        #contours = [contours[i] for i in range(len(contours)) if hierarchy[0][i][3] < 0]

        # fill contours on original image
        cv2.drawContours(img, contours, contourIdx=-1, color=(255,255,255),thickness=-1).astype('float32')

        # calculate area of icebergs
        icebergArea = np.zeros(len(contours))
        for k in range(len(icebergArea)):
            icebergArea[k] = cv2.contourArea(contours[k])

    else: # create empty arrays if no icebergs are found
        icebergArea = []
        edges = []

    photo_dir = os.path.dirname(input_file)
    processed_directory = photo_dir + '/processed/'

    np.savez(processed_directory + '/' +  os.path.basename(input_file)[:-4] + '_icebergs.npz', npixels=npixels, icebergArea=icebergArea, pixArea=pixArea, edges=edges)

    plt.figure(figsize=(15,15*aspect_ratio))
    ax = plt.axes([0,0,1,1])
    img = cv2.imread(input_file)
    RGB_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    ax.imshow(RGB_img)

    if np.sum(icebergArea)>0: # if contains icebergs, plot the edges using a map of the edges (instead of the vectors)
        edges_plot = edges[1:-1,1:-1].astype('float32')
        edges_plot[edges_plot==0] = np.nan
        ax.imshow(edges_plot)

    ax.axis('off')
    plt.savefig(processed_directory + '/' + os.path.basename(input_file)[:-4] + '_icebergs.jpg',format='jpg',dpi=300)
    plt.close()

#%%
def main():

    fjord = shapefile.Reader('./data/fjord_outline_copy.shp')
    fjord = fjord.shapeRecords()[0]
    fjord_polygon = Polygon(fjord.shape.points)

    campaign_shapefiles = sorted(glob.glob('../HARBORSEAL_' + year + '/footprints/*.shp'))

    input_files_all = [] # input files for all campaigns during the year

    for j in np.arange(0,len(campaign_shapefiles)):
        campaign = campaign_shapefiles[j][-22:-14]

        photo_dir = glob.glob('../HARBORSEAL_' + year + '/JHI/' + campaign + '/*' + campaign + '_photo/')[0]
        processed_directory = photo_dir + 'processed/'

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

        # footprints of all photos from that campaign
        footprints = shapefile.Reader(campaign_shapefiles[j])

        if os.path.exists(photo_dir + '/input_files.npy'):
            input_files = np.load(photo_dir + '/input_files.npy').tolist()

        else:

            input_files = []

            for k in np.arange(0,footprints.numRecords):
                photo = footprints.shapeRecords()[k] # extract footprint from individual photo

                if int(year)<2018:
                    photo_name = photo.record[1] # extract name of individual photo
                else:
                    photo_name = photo.record[0] # extract name of individual photo

                # seems to be different format for photo.record for older photos

                photo_polygon = Polygon(photo.shape.points) # get polygon boundary

                infjord = fjord_polygon.contains(photo_polygon) # is photo completely within the fjord?

                if infjord==True:
                    input_files = input_files + [photo_dir + photo_name]

            np.save(photo_dir + '/input_files.npy', input_files)

        input_files_all = input_files_all + input_files

    print('Number of files to process: ' + str(len(input_files_all)))

    pool = mp.Pool(mp.cpu_count()-1)
    pool.map(findIcebergs, input_files_all)

#%%
if __name__ == '__main__':

    start_time = timeit.default_timer()

    year = '2008' # only processes one year at a time

    main()

    elapsed = timeit.default_timer() - start_time

    print('Elapsed time: ' + str(elapsed/60) + ' min')


T = "I DO NOT LIKE SEVENTY SEV BUT SEVENTY SEVENTY SEVEN"
P = "SEVENTY SEVEN"
b = [None]*(len(P)+1)  # KMP back table

def kmpPreprocess():
    # initialization
    i = 0
    j = -1
    b[0] = -1
    # preprocess pattern
    while i < len(P):
        # different, reset j using b
        pi = P[i]
        pj = P[j]
        while j >= 0 and P[i] is not P[j]:
            bj = b[j]
            j = b[j]
        # if same, advance both pointers
        i += 1
        j += 1
        b[i] = j

def kmpSearch():
    # initialization
    i = 0
    j = 0
    # search through string T
    while i < len(T):
        # different, reset j using b
        while j >= 0 and T[i] is not P[j]:
            j = b[j]
        i += 1
        j += 1
        if j == len(P):
            print("P is found at index {} in T".format(i - j))
            j = b[j]

kmpPreprocess()
print(b)
kmpSearch()


with open("input.txt") as f:
    data = f.read().splitlines(keepends=False)

DISK_SPACE = 70_000_000
NEEDED_SPACE = 30_000_000

file_system = {}
total_sizes = {}

cd = []

def change_dir(dir):
    global cd
    if dir == "..":
        cd = cd[:-1]
    else:
        cd.append(dir)

def add_files():
    global file_system, cd, data
    path = "/".join(cd)
    dir_state = file_system.get(path, { "size": 0, "nested": [] })
    while len(data) > 0 and not data[0].startswith("$"):
        file = data.pop(0).split()
        if file[0] == "dir":
            dir_state["nested"].append(f"{path}/{file[1]}")
        else:
            dir_state["size"] += int(file[0])
    file_system[path] = dir_state

def calc_total_dir(dir):
    global file_system
    curr_dir = file_system[dir]
    return sum(calc_total_dir(nested) for nested in curr_dir["nested"]) + curr_dir["size"]

while len(data) > 0:
    line = data.pop(0)
    if line.startswith("$"):
        cmd = line.split()[1:]
        if cmd[0] == "cd":
            change_dir(cmd[1])
        elif cmd[0] == "ls":
            add_files()
    else:
        print("should never print")

for path in file_system.keys():
    total_sizes[path] = calc_total_dir(path)

used_space = total_sizes["/"]
free_space = DISK_SPACE - used_space
viable_directories = filter(lambda size: free_space + size > NEEDED_SPACE, total_sizes.values())

print(sorted(viable_directories)[0])


import base64
import json
import boto3
import uuid

from botocore.client import Config

def lambda_handler(event, context):
    config = Config(connect_timeout=15, retries={'max_attempts': 3})
    sqs = boto3.resource('sqs', config=config)
    queue = sqs.get_queue_by_name(
        QueueName='eks-notification-canada-cadelivery-receipts'
    )
    print("Queue {}".format(queue))
    print("Task has begun")
    for record in event["Records"]:
        task = {
            "task": "process-ses-result",
            "id": str(uuid.uuid4()),
            "args": [
                {
                    "Message": record["Sns"]["Message"]
                }
            ],
            "kwargs": {},
            "retries": 0,
            "eta": None,
            "expires": None,
            "utc": True,
            "callbacks": None,
            "errbacks": None,
            "timelimit": [
                None,
                None
            ],
            "taskset": None,
            "chord": None
        }
        envelope = {
            "body": base64.b64encode(bytes(json.dumps(task), 'utf-8')).decode("utf-8"),
            "content-encoding": "utf-8",
            "content-type": "application/json",
            "headers": {},
            "properties": {
                "reply_to": str(uuid.uuid4()),
                "correlation_id": str(uuid.uuid4()),
                "delivery_mode": 2,
                "delivery_info": {
                    "priority": 0,
                    "exchange": "default",
                    "routing_key": "delivery-receipts"
                },
                "body_encoding": "base64",
                "delivery_tag": str(uuid.uuid4())
            }
        }
        msg = base64.b64encode(bytes(json.dumps(envelope), 'utf-8')).decode("utf-8")
        queue.send_message(MessageBody=msg)
        print("Record has moved to call process-ses-result")
    print("Task has ended")

    return {
        'statusCode': 200
    }


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

from odoo import models, fields, api

class SaleOrder(models.Model):
    _inherit = "sale.order"

    @api.model_cr_context
    def _auto_init(self):
        cr = self._cr
        # Fonction à effacer : transition de many2one à many2many pour la relation sale_order - purchase_order
        cr.execute("SELECT 1 FROM information_schema.tables WHERE table_name = 'of_sale_order_purchase_order_rel'")
        existe_avant = bool(cr.fetchall())

        res = super(SaleOrder, self)._auto_init()

        if not existe_avant:
            cr.execute(
                "SELECT 1 FROM information_schema.columns "
                "WHERE table_name = 'sale_order' AND column_name = 'of_purchase_id'")
            if cr.fetchall():
                cr.execute(
                    "INSERT INTO of_sale_order_purchase_order_rel(sale_id,purchase_id) "
                    "SELECT id, of_purchase_id FROM sale_order WHERE of_purchase_id IS NOT NULL"
                )
        return res

    of_purchase_ids = fields.Many2many(
        'purchase.order', 'of_sale_order_purchase_order_rel', 'sale_id', 'purchase_id',
        string=u"Commandes fournisseur fusionnées", readonly=True, copy=False)

    @api.depends('purchase_ids', 'of_purchase_ids')
    def _compute_purchase_count(self):
        for sale_order in self:
            sale_order.purchase_count = len(sale_order.purchase_ids | sale_order.of_purchase_ids)

    @api.multi
    def action_view_achats(self):
        action = self.env.ref('of_purchase.of_purchase_open_achats').read()[0]
        action['domain'] = ['|', ('sale_order_id', 'in', self._ids), ('of_sale_order_ids', 'in', self._ids)]
        return action

class PurchaseOrderLine(models.Model):
    _inherit = "purchase.order.line"

    of_delivery_expected = fields.Char(string='Livraison attendue')
    of_customer_id = fields.Many2one('res.partner', string="Client")

    @api.multi
    def create(self, vals):
        purchase_order_obj = self.env['purchase.order']
        if vals.get('order_id'):
            order = purchase_order_obj.browse(vals.get('order_id'))
            if order.customer_id:
                vals['of_customer_id'] = order.customer_id.id
            if vals.get('delivery_expected'):
                vals['of_delivery_expected'] = order.delivery_expected
            if order.of_project_id:
                vals['account_analytic_id'] = order.of_project_id.id
        return super(PurchaseOrderLine, self).create(vals)

class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    of_sale_order_ids = fields.Many2many(
        'sale.order', 'of_sale_order_purchase_order_rel', 'purchase_id', 'sale_id',
        string=u"Commandes liées")
    of_fused = fields.Boolean(u'Commande fusionnée')
    of_sale_count = fields.Integer(compute='_compute_sale_count')

    @api.depends('of_sale_order_ids', 'sale_order_id')
    @api.multi
    def _compute_sale_count(self):
        for purchase_order in self:
            orders = purchase_order.of_sale_order_ids
            if purchase_order.sale_order_id not in orders:
                orders += purchase_order.sale_order_id
            purchase_order.of_sale_count = len(orders)

    @api.multi
    def action_view_ventes(self):
        action = self.env.ref('of_purchase_fusion.of_purchase_open_ventes').read()[0]
        action['domain'] = ['|', ('of_purchase_ids', 'in', self._ids), ('purchase_ids', 'in', self._ids)]
        return action

class StockPicking(models.Model):
    _inherit = 'stock.picking'

    @api.multi
    def _compute_of_purchase_ids(self):
        # Modification du calcul des achats associés au BL, champs du module of_sale_stock
        purchase_order_obj = self.env['purchase.order']
        sale_pickings = self.filtered('sale_id')
        for picking in sale_pickings:
            picking.of_purchase_ids = purchase_order_obj.search(
                ['|', ('sale_order_id', '=', picking.sale_id.id), ('of_sale_order_ids', 'in', picking.sale_id.id)])
            picking.of_purchase_count = len(picking.of_purchase_ids)
        super(StockPicking, self - sale_pickings)._compute_of_purchase_ids()

class StockMove(models.Model):
    _inherit = 'stock.move'

    of_customer_id = fields.Many2one('res.partner', related="move_dest_id.partner_id", string="Client")

class ResPartner(models.Model):
    _inherit = 'res.partner'

    def _compute_of_br_count(self):
        picking_obj = self.env['stock.picking']
        move_obj = self.env['stock.move']
        for partner in self:
            pickings = picking_obj.search([('of_customer_id', '=', partner.id), ('of_location_usage', '=', 'supplier')])
            pickings |= move_obj.search([('of_customer_id', '=', partner.id)]).mapped('picking_id')
            partner.of_br_count = len(pickings)

    @api.multi
    def action_view_picking(self):
        picking_obj = self.env['stock.picking']
        move_obj = self.env['stock.move']
        action = self.env.ref('of_purchase.of_purchase_open_picking').read()[0]
        pickings = self.env['stock.picking']
        for partner in self:
            pickings |= picking_obj.search(
                [('of_customer_id', '=', partner.id), ('of_location_usage', '=', 'supplier')])
            pickings |= move_obj.search([('of_customer_id', '=', partner.id)]).mapped('picking_id')
        action['domain'] = [('id', 'in', pickings._ids)]
        return action


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

# Python標準ライブラリ
import cv2
from cv_bridge import CvBridge, CvBridgeError

# Python追加ライブラリ
import mediapipe as mp

# ROSに関するライブラリ
import rospy
from sensor_msgs.msg import CompressedImage

class HandDetection():
    def __init__(self):
        # MediaPipeが提供しているhandsの値を読み込む
        self.mp_hands = mp.solutions.hands
        self.mp_drawing = mp.solutions.drawing_utils
        self.mesh_drawing_spec = self.mp_drawing.DrawingSpec(thickness=2, color=(0, 255, 0))
        self.mark_drawing_spec = self.mp_drawing.DrawingSpec(thickness=3, circle_radius=3, color=(0, 0, 255))
        self.cv_bridge = CvBridge()
        self.sub = rospy.Subscriber("/hsrb/head_rgbd_sensor/rgb/image_rect_color/compressed", CompressedImage, self.main)

    def main(self, msg):
        observed_img = self.cv_bridge.compressed_imgmsg_to_cv2(msg)
        image = cv2.resize(observed_img, dsize=None, fx=0.3, fy=0.3)
        # 色変換（BGR→RGB）
        rgb_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
        # リサイズ
        height = rgb_image.shape[0]
        width = rgb_image.shape[1]

        # 検出結果を別の画像名としてコピーして作成
        self.annotated_image = image.copy()

        # 認識する手の数と認識精度を設定する (手の数の上限、検出精度、ランドマーク検出)
        with self.mp_hands.Hands(max_num_hands=2, min_detection_confidence=0.5,
                                 static_image_mode=True) as hands_detection:

            # 顔検出の結果をresultsに
            results = hands_detection.process(rgb_image)

            for hand_landmarks in results.multi_hand_landmarks:
                self.mp_drawing.draw_landmarks(
                    image=self.annotated_image,
                    landmark_list=hand_landmarks,
                    connections=self.mp_hands.HAND_CONNECTIONS,
                    landmark_drawing_spec=self.mark_drawing_spec,
                    connection_drawing_spec=self.mesh_drawing_spec
                )
                self.save_data(self.annotated_image)
                cv2.imshow('Detection Result', self.annotated_image)
                cv2.waitKey(1)

    def save_data(self, img):
        cv2.imwrite('../data/result_ros.jpg', img)
        return

if __name__ == "__main__":
    rospy.init_node('mediapipe_ros')
    mediapipe_ros = HandDetection()
    rospy.spin()


# Big O
# Complexity

"""
To calculate Big O you need to go through every single (excutable)line of code and calculate how much time/space it takes.
- Calculate against number of items
- So no actual time (no seconds), and no actual space (no KBites)
- For lists, always call number of items (n) - but you can use n,m, etc.
"""

def compare(a, b):
    """
    This function compares the two arrays of things and returns the common vlaues in both arrays
    in a tuple format

    Input: Two lists of things
    Output: A tuple of common vlaues (things)
    """
    output = [] # 1 ops
    # Sol 1: O(n^2)
    for i in a: # n ops
        for j in b: # m ops
            if i==j:
                output.append(i)
                break

    # Sol 2: O(n^2)
    for i in a: # n ops
        if i in b: # m ops
            output.append(i) # 1 ops

    # Sol 3: O(n+m) = O(n)
    # convert the list into a set
    # Why? Searching a set is O(1)
    c = set(b) # m ops {7,9,12,True,'401','56'}
    for i in a: # n ops
        if i in c: # 1 ops
            output.append(i) # 1 ops

    # people = {'moh':25, 'Haia':23, 'Trad':24}
    # if 'Trad' in people:
    #     print(people['Trad'])

    return tuple(output) # n ops

if __name__=="__main__":
    a = ['56',4,5,7.8,'hi',False]
    b = [7,9,12,True,'401','56']
    output = compare(a,b)
    print(output)
    # ('56', True)


# -*- coding: utf-8 -*-
"""
Created on Wed Dec 16 20:47:36 2020

@author: mixmp
"""

import random
import math
import numpy as np
import mpmath

def nearest_neighbour_for_TPS(path):
    ###################function for reading the tps document########################33
    def read_tps(path):
     with open(path, 'r') as f:
    		content = f.read().splitlines()#content is a list whose every element contains every line
                                           #line of the txt document
    		cleaned = [x.lstrip() for x in content if x != ""]#The gaps that exist at the start of every element
                                                              #are removed
     for element in cleaned:#I find the line which strats with ΝΑΜΕ word and then
                            #I take the name of the problem
    		if element.startswith("NAME"):
    			 a=element
     if len(a.split())==2:#this happens when : is next to the word NAME
       name=a.split()[1]
     elif len(a.split())==3:#this happens when there is a gap between ΝΑΜΕ and :
       name=a.split()[2]
     i=0
     flag=False
     while flag==False:
         if cleaned[i]=="NODE_COORD_SECTION" or cleaned[i]=="DISPLAY_DATA_SECTION":
             loc=i#loc is the number of the row of the txt doument where it is written NODE_COORD_SECTION or
                  #NODE_COORD_SECTION and after this line there are the coordinates of the problem up to
                  #the line where it is written EOF
             flag=True
         i=i+1
     cleaned1=[]#A list where I save the lines of the txt document which contain the coordinates after
                #having applied split method to every line
     for i in range((loc+1),(len(cleaned)-1)):
        cleaned1.append(cleaned[i].split())
     for element in cleaned:#I find the line which strats with DIMENSION word and then
                            #I take the number after the DIMENSION
    		if element.startswith("DIMENSION"):
    			 a=element
     if len(a.split())==2:#this happens when : is next to the word DIMENSION
       dimension=int(a.split()[1])
     elif len(a.split())==3:#this happens when there is a gap between DIMENSION and :
       dimension=int(a.split()[2])
     for element in cleaned:
    		if element.startswith("EDGE_WEIGHT_TYPE"):
    			 a=element
     if len(a.split())==2:#this happens when : is next to EDGE_WEIGHT_TYPE
       EDGE_WEIGHT_TYPE=a.split()[1]
     elif len(a.split())==3:#this happens when there is a gap between EDGE_WEIGHT_TYPE   and :
        EDGE_WEIGHT_TYPE=a.split()[2]
     coordinates=[]
     coordinates1=[]
     for i in cleaned1:
         coordinates.append((int(i[0]),float(i[1]),float(i[2])))#coordinates is a list which contains the id
                                                                #number and dimensions of every point
         coordinates1.append((float(i[1]),float(i[2])))#coordinates is a list which contains
                                                       #the dimensions of every point
     #dimension=len(cleaned)-(loc+1)-1#A second way to find the dimensions of the problem

    ##########In the following lines I compute for every pair of points, the distance of them
    ##########and I create a nxn matrix which contains the distance of every 2 points of the problem
    ##########The type of the distance is given by the edge weight type

     if EDGE_WEIGHT_TYPE== "EUC_2D":
      ##EDGE_WEIGHT_TYPE : EUC_2D
      n=len(coordinates1)
      dist = np.zeros((n,n))
      for p in range(n):
       for q in range(p + 1, n):
          d = math.sqrt((coordinates1[p][0]-coordinates1[q][0])**2 + (coordinates1[p][1]-coordinates1[q][1])**2)
          dist[p][q] = d
          dist[q][p] = d

     if EDGE_WEIGHT_TYPE== "ATT":
      #EDGE_WEIGHT_TYPE : ATT
      ###ATT distance
      n=len(coordinates1)
      dist= np.zeros((n,n))
      for p in range(n):
        for q in range(p + 1, n):
          d1 = math.sqrt(((coordinates1[p][0]-coordinates1[q][0])**2 + (coordinates1[p][1]-coordinates1[q][1])**2)/10)
          d2=mpmath.nint(d1)
          if d2<d1:
              d=d2+1
          else:
              d=d2
          dist[p][q] = d
          dist[q][p] = d

     if EDGE_WEIGHT_TYPE== "GEO":
        #EDGE_WEIGHT_TYPE : GEO
      n=len(coordinates1)
      dist = np.zeros((n,n))
      for p in range(n):
       for q in range(p + 1, n):
          PI = math.pi;
          deg =mpmath.nint(coordinates1[p][0]);
          min = coordinates1[p][0] - deg;
          latitude_p= PI * (deg + 5.0 * min / 3.0 ) / 180.0
          deg = mpmath.nint( coordinates1[p][1] );
          min =  coordinates1[p][1] - deg;
          longitude_p = PI * (deg + 5.0 * min / 3.0 ) / 180.0
          deg = mpmath.nint(coordinates1[q][0]);
          min = coordinates1[q][0] - deg;
          latitude_q= PI * (deg + 5.0 * min / 3.0 ) / 180.0
          deg = mpmath.nint( coordinates1[q][1] );
          min =  coordinates1[q][1] - deg;
          longitude_q = PI * (deg + 5.0 * min / 3.0 ) / 180.0
          RRR = 6378.388;
          q1 = math.cos( longitude_p - longitude_q );
          q2 = math.cos( latitude_p - latitude_q );
          q3 = math.cos( latitude_p + latitude_q );
          d = int(( RRR * math.acos( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) ) + 1.0))
          dist[p][q] = d
          dist[q][p] = d

     return cleaned,cleaned1,dimension,coordinates1,coordinates,EDGE_WEIGHT_TYPE,dist,name
    ######################################################################################

    ##loading the tps document
    file_read=read_tps(path)
    coordinates=file_read[3]
    dimension=file_read[2]
    name=file_read[7]
    dist=file_read[6]
    ###############dist is the matrix which contains the distances between all the pairs of nodes
    EDGE_WEIGHT_TYPE=file_read[5]

    ############################Nearest Neighbor algorithm
    def nearest_neighbour(dist_matrix):
        n=dist_matrix.shape[0]#the total number of the nodes of the problem
        start=random.choice(list(range(n)))#random selection between all the nodes for the starting node
        not_visited=list(range(n))#at first all the nodes are not visited, so at first I create
        #the not_visited list as a sequence of all nodes of the problem
        path=[start]#the first node of the path is the initial node-start
        not_visited=[ele for ele in not_visited if ele not in path]#taking out from not_visited list
        #the elemnts of the path, beacause they are already visited
        cost=0
        #the repetition continues until the no_visited list is empty(its length is zero),
        #which means that every node of the problem is visited
        while len(not_visited)>0:
         last=path[-1]#last is the last visited node in the path
         next_loc_index=np.argmin(dist_matrix[last][not_visited])
         #the index for the next node that will be visited is computed by finding which node from the
         #nodes that are not visited has the minimum distance from the last visited node.
         #next_loc_index contains the index for that node
         next_loc=not_visited[next_loc_index]#next_loc is the next node that will be visited
         min_dist=dist_matrix[last][next_loc]#minimum distance from the previous visited node to the next
         #viisited node
         path.append(next_loc)#adding the current visited node to  the end of the path list
         not_visited=[ele for ele in not_visited if ele not in path]#taking out of the not_visited lsit
         #the node that is just visited and added to the path list
         cost+=min_dist#each time the minimum distance from the previous visited node to the next
         #viisited node is added to cost
        cost+=dist_matrix[path[-1]][start]# at the end the distance from the last visited node to the
        #initial node is added to the cost as the process is cyclical and we should
        #return to the start node
        path.append(start)
        return path, cost,start
    nn_alg=nearest_neighbour(dist)
    path=nn_alg[0]
    cost=nn_alg[1]
    start=nn_alg[2]
    print("The randomly chosen starting node is",start)
    print("\n")
    print("A short rout computed by nearest neighbour heuristic for",name,"TSP problem is:")
    print("\n")
    print(path)
    print("\n")
    print("The total cost of this rout is:",cost)
    return

##################applying nearest_neighbour_for_TPS function to TSP problems
nearest_neighbour_for_TPS("berlin52.txt")

nearest_neighbour_for_TPS("burma14.txt")

nearest_neighbour_for_TPS("pr144.txt")

nearest_neighbour_for_TPS("a280.txt")


# check if below string is a palindrome

city = 'cccco'

# way 1: this code is good but we end up comparing letters more than we need
for i in range(0, len(city)):
    if city[i] != city[(i+1) * -1]:
        is_palindrome1 = 'No'
        break
print(is_palindrome1)

# way 2: this code is longer but it is faster
stopper = ''
is_palindrome2 = 'Yes'
if len(city) // 2 == 0:
    stopper = len(city) // 2 - 1
else:
    stopper = len(city) // 2

for i in range(0, stopper):
    if city[i] != city[(i+1) * -1]:
        is_palindrome2 = 'No'
        break
print(is_palindrome2)


from django.http import HttpRequest
from djaveAllowed.models import Allowed
from djaveAllowed.credentials import UserCredentials
from djaveAPI.get_instance import get_instance
from djaveAPI.problem import Problem
from djaveClassMagic.find_models import model_from_name

def get_request_ajax_obj(request, model=None, pk=None):
  if not pk:
    # It's awfully confusing if I'm using id or pk, so I just make them both
    # work.
    pk = get_request_variable(request, 'id', required=False)
    if not pk:
      pk = get_request_variable(request, 'pk', required=True)
  model_name = None
  if model:
    model_name = model.__name__
  else:
    # It's awfully confusing if I'm using model or type, so I just make them
    # both work.
    model_name = get_request_variable(request.POST, 'model', required=False)
    if not model_name:
      model_name = get_request_variable(request.POST, 'type', required=True)
    # I'm very intentionally NOT using djaveAPI.get_publishable_model because
    # this is AJAX and you can do AJAX calls on objects that aren't necessarily
    # in the API. The only thing you actually need here is a model I can check
    # permission on.
    model = model_from_name(model_name, Allowed)
  credentials = UserCredentials(request.user)

  # model.live is really handy for pulling back a list of active objects. This
  # requires a single object and I don't want to outsmart myself, so I'm just
  # using model.objects
  return get_instance(model_name, model.objects, pk, credentials)

def get_request_variable(data, variable_name, required=True):
  """ data can be a dictionary such as request.POST, or it can just be a
  request. """
  if isinstance(data, HttpRequest):
    data = get_data_from_request(data)
  if variable_name not in data:
    if required:
      raise Problem(
          'This request doesn\'t specify a {}'.format(variable_name))
    return None
  variable = data[variable_name]
  if required and variable in [None, '']:
    raise Problem('The {} is required'.format(variable_name))
  return variable

def get_data_from_request(request):
  return request.POST or request.PUT or request.DELETE


import numpy as n
import matplotlib.pyplot as plt

v0 = float(input("Podaj V0: "))
katpierwszy = float(input("Podaj kat: ")) * n.pi / 180
kat = katpierwszy* n.pi / 180
time = 2 * v0 * n.sin(kat) / 9.81
hmax = v0**2 * n.sin(kat)**2 / (2 * 9.81)
zasieg = 2 * v0**2 * n.sin(kat)**2 / 9.81

punkty = 100
t = n.linspace(0, time, punkty)
vx = [v0 * n.cos(kat) for i in range(punkty)]
vy = v0 * n.sin(kat) - 9.81 * t
x = vx * t
y = v0 * t * n.sin(kat) - 9.81 * t * t / 2

print("Maksymalna wysokość: ",hmax)
print("Zasieg rzutu: ",zasieg)
print("Czas lotu: ",time)

plt.subplot(131, title="predkosc chwilowa")
plt.plot(t, vx, t, vy)
plt.subplot(132, title="polozenie funkcji w czasie")
plt.plot(t, x, t, y)
plt.subplot(133, title="tor ruchu w rzucie ukosnum ")
plt.plot(x, y)

plt.show()


"""
Split Raster's into tiles
"""

import os
from osgeo import gdal

def nrsts_fm_rst(rst, rows, cols, out_fld, bname):
    """
    Split raster into several rasters

    The number of new rasters will be determined by the extent of the
    raster and the maximum number of rows and cols that the new
    rasters could have.
    """

    from glass.prop.img import rst_epsg
    from glass.wt.rst   import ext_to_rst

    # Open Raster
    img = gdal.Open(rst, gdal.GA_ReadOnly)

    # Get EPSG
    epsg = rst_epsg(img)

    # Get raster cellsize
    tlx, csx, xr, tly, yr, csy = img.GetGeoTransform()

    # Get Raster cols and Rows
    rrows, rcols = img.RasterYSize, img.RasterXSize

    # Get Raster max X and min Y (bottom right)
    rmax_x = tlx + (rcols * csx)
    rmin_y = tly + (rrows * csy)

    # Get Number of rasters to be created
    nr_rows = int(rrows / rows)
    nr_rows = nr_rows if nr_rows == rrows / rows else nr_rows + 1
    nr_cols = int(rcols / cols)
    nr_cols = nr_cols if nr_cols == rcols / cols else nr_cols + 1

    # Create new rasters
    newrst = []
    for i in range(nr_rows):
        # TopLeft Y
        _tly = tly + ((rows * csy) * i)

        # BottomRight Y
        _bry = _tly + (csy * rows)

        # If fishnet min y is lesser than raster min_y
        # Use raster min_y
        if _bry < rmin_y:
            _bry = rmin_y

        for e in range(nr_cols):
            # TopLeft X
            _tlx = tlx + ((cols * csx) * e)

            # Bottom Right X
            _brx = _tlx + (csx * cols)

            # If fishnet max x is greater than raster max_x
            # Use raster max_x
            if _brx > rmax_x:
                _brx = rmax_x

            # Create Raster
            nrst = ext_to_rst(
                (_tlx, _tly), (_brx, _bry),
                os.path.join(out_fld, f"{bname}_{str(i)}{str(e)}.tif"),
                cellsize=csx, epsg=epsg, rstvalue=1
            )

            newrst.append(nrst)

    return newrst

def split_raster_by_window(rst, ntile_rows, ntile_cols, out_fld):
    """
    Split Raster By Spatial Window
    """

    from glass.pys     import execmd
    from glass.pys.oss import fprop
    from glass.prop.df import drv_name

    # Open Raster
    img = gdal.Open(rst, gdal.GA_ReadOnly)

    # Get Raster cols and Rows
    rrows, rcols = img.RasterYSize, img.RasterXSize

    # Driver
    drv = drv_name(rst)

    # Basename
    fp = fprop(rst, ['ff', 'fn'])
    fn, ff = fp['filename'], fp['fileformat']

    # Create new subrasters
    nc = 0
    res = []
    for c in range(0, rcols, ntile_cols):
        nr = 0
        for r in range(0, rrows, ntile_rows):
            outrst = os.path.join(
                out_fld,
                f'{fn}_r{str(nr)}c{str(nc)}{ff}'
            )
            cmd = (
                f'gdal_translate -of {drv} '
                f'-srcwin {str(c)} {str(r)} '
                f'{str(ntile_cols)} {str(ntile_rows)} '
                f'{rst} {outrst}'
            )

            rcmd = execmd(cmd)

            res.append(outrst)

            nr += 1

        nc += 1

    return res


from typing import Optional

from tornado.template import Loader

from web.controllers.utils.errors import handle_errors
from web.controllers.utils.validated import ValidatedFormRequestHandler
from web.schemas import template_schema
from web.services.email.abstract import AbstractEmailService
from web.validation import validate_template_schema

class BaseTemplateRequestHandler(ValidatedFormRequestHandler):
    def initialize(self, template_loader: Loader, email_service: AbstractEmailService):
        self.service = email_service
        self.loader = template_loader

class TemplatesHandler(BaseTemplateRequestHandler):
    schemas = {"post": template_schema}

    @handle_errors
    async def get(self):
        contacts = await self.service.list_email_templates()
        self.write(
            self.loader.load("templates/templates.html").generate(
                objects=contacts, columns=["id", "name"], url_base="/templates/"
            )
        )

    @handle_errors
    async def post(self):
        data = self.get_data("post")
        validate_template_schema(data)
        template = await self.service.create_email_template(data)
        self.redirect(f"/templates/{template['id']}")

class TemplateHandler(BaseTemplateRequestHandler):
    schemas = {"post": template_schema}

    @handle_errors
    async def get(self, template_id: str):
        template = await self.service.get_email_template(int(template_id))
        self.write(
            self.loader.load("templates/template.html").generate(template=template)
        )

    @handle_errors
    async def post(self, template_id: str):
        data = self.get_data("post")
        validate_template_schema(data)
        data["id"] = int(template_id)

        await self.service.update_email_template(data)
        await self.get(template_id)

class TemplateFormHandler(BaseTemplateRequestHandler):
    @handle_errors
    async def get(self, template_id: Optional[str] = None):
        if template_id:
            action = f"/templates/{template_id}"
            initial = await self.service.get_email_template(int(template_id))
        else:
            action = "/templates"
            initial = {}

        self.write(
            self.loader.load("templates/template_form.html").generate(
                action=action, initial=initial
            )
        )


import pdb
import unittest

from app import app as flickrlive_app

class FlickrLiveTestCase(unittest.TestCase):

    def setUp(self):
        flickrlive_app.config['TESTING'] = True
        self.app = flickrlive_app.test_client()

    def test_homepage_shows_initial_flickr_feed(self):
        """ The homepage should be able to display an initial
            set of public feed from Flickr as well as a search box.

        """
        response = self.app.get('/')
        self.assertEqual(response.status_code, 200)

        # Check if there are feed items are the page.
        self.assertIn('class="item"', response.data)

        # Check if the query search box in the page.
        self.assertIn('name="q"', response.data)

    def test_homepage_able_to_search_flickr_feed_via_tags(self):
        """ The homepage search box should be able to search Flickr's
            public feed via their tags and display the images.

        """
        search_term = 'dogs'

        # Check if we're able to perform a search.
        response = self.app.get('/?q=' + search_term)
        self.assertEqual(response.status_code, 200)

        # Check if there are feed items are the page.
        self.assertIn('class="result-item"', response.data)

        # Check if the search term is on the page.
        self.assertIn(search_term, response.data)

if __name__ == '__main__':
    unittest.main()


import discord
import logging
import os
from discord.ext import commands

logger = logging.getLogger('serverlinker')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

initial_extensions = [
    'plugins.commands',
    'plugins.handlers'
]

bot = commands.AutoShardedBot(command_prefix=commands.when_mentioned_or('$'))

logger.info("""
  _________                               .____    .__        __
 /   _____/ ______________  __ ___________|    |   |__| ____ |  | __ ___________
 \_____  \_/ __ \_  __ \  \/ // __ \_  __ \    |   |  |/    \|  |/ // __ \_  __ \\
 /        \  ___/|  | \/\   /\  ___/|  | \/    |___|  |   |  \    <\  ___/|  | \/
/_______  /\___  >__|    \_/  \___  >__|  |_______ \__|___|  /__|_ \\\\___  >__|
        \/     \/                 \/              \/       \/     \/    \/
""")

logger.info("Created by Kelwing#0001")

if __name__ == '__main__':
    for ext in initial_extensions:
        try:
            logger.info(f"Loading {ext}...")
            bot.load_extension(ext)
        except Exception as e:
            logger.exception(f'Failed to load extension {ext}.')

@bot.event
async def on_ready():
    game = discord.Game(f"Type $help "
                        f"| Serving {len(bot.guilds)} guilds on "
                        f"{bot.shard_count} shards")
    await bot.change_presence(activity=game)

    logger.info(f"{bot.user} is now online!")

bot.run(os.environ.get('TOKEN'), reconnect=True)


from bs4 import BeautifulSoup
#from requests import Session as R
import requests as R
import time
import random
import os
import json
from fake_useragent import UserAgent
from stem import Signal
from stem.control import Controller
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

class DATA(object):
        def __init__(self):
            self.file = {}
            self.csv = "";

        def parseCSV(self):
              with open(self.csv, 'r') as g:
                             for gh in g.readlines():
                                         gh = gh.split('\n')[0].split(';')
                                         try:
                                              list = self.file[gh[0]]
                                              if gh[1] != 'no_matching_images':
                                                  convRUC = [int(i) for i in gh[1].split(':')[1].split('/')]
                                                  list.append(convRUC)
                                                  self.file[gh[0]] = list
                                              else:
                                                  list.append([])
                                                  self.file[gh[0]] = list
                                         except KeyError:
                                              pass

        def parseIMG(self, dir_name, tp):
                path = "data/"+dir_name
                print ("PARSING",path)
                valid_images = [".jpg",".png"]
                for r, d, f in os.walk(path):
                    for ix, file in enumerate(f):
                        if valid_images[0] in file or valid_images[1] in file:
                          if int(tp) == 4:
                                   self.file[file.split(".")[0]] = [os.path.join(r, file)]
                          else:
                                   self.file[os.path.join(r, file)] = [os.path.join(r, file)]
                        if ".csv" in file:
                           self.csv = os.path.join(r, file)

path_img = "data_img/"
def create_dir(x):

   x = x.split("/")
   #try:
   x1 = path_img+x[2]
   try:
       os.mkdir(x1)
   except FileExistsError:
       pass
   x2 = x1+"/"+x[3]
   try:
       os.mkdir(x2)
   except FileExistsError:
       pass
   x3 = x2+"/"+x[4]
   try:
       os.mkdir(x3)
   except FileExistsError:
       pass
   #except:
   #print (x[2], x[3], x[4])
   return x3
   #os.mkdir(car_info.text)

#---------------------------------------_>
class RequestLib():
    def __init__(self):
        self.session = R.session()
        self.session.proxies = {}
        #self.session.proxies['http'] = 'socks5://127.0.0.1:9050'
        #self.session.proxies['https'] = 'socks5://127.0.0.1:9050'
        self.headers = {}
        self.headers['User-agent'] = UserAgent().random
        self.headers['Accept-Language'] = "en,en-US;q=0,5"
        self.headers['Content-Type'] = "application/x-www-form-urlencoded"
        self.headers['Connection'] = "keep-alive"
        self.headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
    def get(self, http):
        #print (http)
        self.headers['User-agent'] = UserAgent().random
        get_page = self.session.get(http, headers=self.headers)#, timeout=(10, 10))
        return get_page#.text
Sess = RequestLib()
#---------------------------------------_>
def my_proxy(PROXY_HOST,PROXY_PORT):
    fp = webdriver.FirefoxProfile()
    #fp.set_preference("network.proxy.type", 1)
    #fp.set_preference("network.proxy.socks",PROXY_HOST)
    #fp.set_preference("network.proxy.socks_port",int(PROXY_PORT))

    fp.update_preferences()
    options = Options()
    #options.add_argument('headless')
    options.add_argument("--headless")
    #options.headless = True
    return webdriver.Firefox(options=options, firefox_profile=fp)

def scroll():
    last_height = proxy.execute_script("return document.body.scrollHeight")
    w = last_height//100
    igg = 100
    for i in range(w):
        proxy.execute_script("window.scrollTo(0, {})".format(igg))
        time.sleep(0.3)
        igg += 100

proxy = my_proxy("127.0.0.1", 9050)

path = "data"

def func_(htt, dir_save):
                   #p_parse = Sess.get(htt)
                   #soup = BeautifulSoup(p_parse.text)
                   proxy.get(htt)
                   try:
                        #element = WebDriverWait(proxy, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "l-body")))

                        scroll()
                   finally:
                        pass
                   def PP():
                       html = proxy.page_source
                       soup = BeautifulSoup(html)

                       car_info = soup.find("span",{"class":"u-break-word"})
                       car_rate = soup.find("span",{"class":"r-button-unstyled c-round-num-block"})

                       car_rate = car_rate.find("strong")
                       user_info = soup.find("div",{"class":"c-user-card__info"})
                       user_link = soup.find("a",{"class":"c-link c-link--color00 c-username c-username--wrap"})
                       #print (user_link["href"])#(car_info.text, car_rate.text)#, user_info.text)

                       f_inf = open(dir_save+"/info.txt", "w")
                       f_inf.write(car_info.text+";"+car_rate.text+"\n")
                       f_inf.write(user_link["href"]+"\n")
                       f_inf.write(user_info.text+"\n")
                       f_inf.close()

                       cl = soup.find_all('div', {"class": "c-slideshow__hd"})

                       for K in cl:
                          Kcl = K.find("img")
                          #print (Kcl["src"], Kcl["src"].split("/")[-1])
                          response = Sess.get(htt)#R.get(Kcl["src"], headers=headers)
                          print (response)
                          if response.status_code == 200:
                              with open(dir_save+"/"+Kcl["src"].split("/")[-1], 'wb') as fli:
                                   fli.write(response.content)
                          #else:
                              #cl = PP() #func_(htt, dir_save)

                       SEC = random.choice([2,3,4,5,3,1,1.1,1.5, 0.7])
                       time.sleep(SEC)
                   PP()

dirn = os.walk(path)
ls = ["bmw","mercedes","audi","opel","landrover","mitsubishi","nissan","subaru","toyota","porsche","ferrari","lamborghini"]#"bmw",
for U in dirn:
   for P in U[2]:
       fl = [os.path.join(U[0], P)]
       #print (fl)
       OP = open(fl[0],"r")
       lS = OP.readlines()
       for st in lS:
           htt = "https://www.drive2.ru"+st.split("\n")[0]
           dir_save = create_dir(st.split("\n")[0])
           if st.split("/")[2] in ls:
                 print (htt, st.split("/")[-2])
                 func_(htt, dir_save)
           #try:
#           func_(htt, dir_save)
#                   p_parse = Sess.get(htt)
#                   soup = BeautifulSoup(p_parse.text)
#
#                   car_info = soup.find("span",{"class":"u-break-word"})
#                   car_rate = soup.find("span",{"class":"r-button-unstyled c-round-num-block"})
#
#                   car_rate = car_rate.find("strong")
#                   user_info = soup.find("div",{"class":"c-user-card__info"})
#                   user_link = soup.find("a",{"class":"c-link c-link--color00 c-username c-username--wrap"})
#                   #print (user_link["href"])#(car_info.text, car_rate.text)#, user_info.text)
#
#                   f_inf = open(dir_save+"/info.txt", "w")
#                   f_inf.write(car_info.text+";"+car_rate.text+"\n")
#                   f_inf.write(user_link["href"]+"\n")
#                   f_inf.write(user_info.text+"\n")
#                   f_inf.close()
#
#                   cl = soup.find_all('div', {"class": "c-slideshow__hd"})
#                   for K in cl:
#                      Kcl = K.find("img")
#                      print (Kcl["src"], Kcl["src"].split("/")[-1])
#                      response = R.get(Kcl["src"], headers=headers)
#                      print (response)
#                      if response.status_code == 200:
#                          with open(dir_save+"/"+Kcl["src"].split("/")[-1], 'wb') as fli:
#                               fli.write(response.content)

#                   SEC = random.choice([2,3,4,5,3,1,1.1,1.5, 0.7])
#                   time.sleep(SEC)
           #except:
                   #print (htt)
                   #pass
                   #func_(htt, dir_save)
#print (dirn)


from torch import nn
import torch

class OrderPredictor(nn.Module):
    def __init__(self, model_dim):
        super().__init__()
        self.disc_linear = nn.ModuleList([
            nn.Linear(2 * model_dim, model_dim) for _ in range(3)
        ])
        self.final_linear = nn.Linear(3 * model_dim, 6)

    def forward(self, features):
        # features in (batch_size * sampled_num, 3, dim)
        res_01 = self.disc_linear[0](torch.cat((features[:, 0], features[:, 1]), dim=-1))
        res_02 = self.disc_linear[1](torch.cat((features[:, 0], features[:, 2]), dim=-1))
        res_12 = self.disc_linear[2](torch.cat((features[:, 1], features[:, 2]), dim=-1))
        res = torch.cat((res_01, res_02, res_12), dim=-1)
        return self.final_linear(res)  # in (bs * sampled_num, 6)

def order2target(order):
    return {'012': 0, '021': 1, '102': 2, '120': 3, '201': 4, '210': 5}[str(order[0]) + str(order[1]) + str(order[2])]


demo_config_data = {
    'num_epochs': 30,
    'num_train_iter': 400,
    'num_val_iter': 60,
    'start_save': 2,
    'save_freq': 10,
    'eval_freq': 5,
    'batch_size': 32,
    'batch_size_val': 16,
    'learning_rate': 1e-4,
    'num_fourier_comp': 3,
    'img_size': (224, 224),
    'mlp_layers': [256]*2,
    'random_seed': 44,
    'warmup_steps': 40,
    'num_train_queries': 2**12,
    'dataset': "tabletop",
    'backbone': "convnext_tiny",
    'backbone_layer': 1,
    'occlusion': False,
    'full_img': False,
    'full_eval': True,
    'length': 15000,
    'material': True
}


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

"""
Lib to manage toolbars which appear on mousedown and stay visible a few seconds
"""
from PyQt4.QtGui import *
from PyQt4.QtCore import *

from ...basic.utils.toolbar import ToolbarManager as BasicToolbarManager

class ToolbarManager(BasicToolbarManager):

    def __init__(self, *args, **kwargs):
        super(ToolbarManager, self).__init__(*args, **kwargs)
        self.max_delay = 1500.0 # ms (don't forget ".0")
        self.event_target.installEventFilter(self)

    def eventFilter(self, obj, e):
        if e.type() == QEvent.HoverMove:
            if self.delay and self.delay < 500:
                self.display()
            elif (not self.delay):
                self.display()
        return False

    def move_cursor_away_of_toolbar(self):
        QCursor.setPos(self.parent().mapToGlobal(self.parent().pos()))


def power(x, n):
    # calculate x^n
    if n == 1:
        return x
    else:
        return x * power(x, n-1)

def power2(x, n):
    if n == 1:
        return x
    else:
        partial = power2(x, n//2)
        result = partial * partial
        if n % 2 == 1: result *= x

        return result


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

import torch
import torch.nn as nn
import torch.nn.functional as F
from core.modules import RNNCell, SequenceWise, ConvLayer

def im2col(x, K, P):
    N, C, H, W = x.shape
    L = N * H * W
    CK2 = C * K ** 2
    xcol = F.unfold(x, kernel_size=K, padding=P)
    xcol = xcol.permute(0, 2, 1).reshape(L, CK2)
    return xcol

def outer_conv(xcol, y):
    N, C, H, W = y.shape
    L, CK2 = xcol.shape
    y = hide_spatial(y) # [L, C]

    # [L, CK2, 1] x [L, 1, C] = [L, CK2, C]
    delta = torch.bmm(xcol.unsqueeze(2), y.unsqueeze(1))
    return delta

def local_convolution(self, xcol, w, out_shape):
    L, CK2 = xcol.shape
    N, C, H, W = out_shape
    y = torch.bmm(xcol.unsqueeze(1), w)
    return y

def show_spatial(x, N, H, W, C):
    return x.reshape(N, H, W, C).permute(0, 3, 1, 2).contiguous()

def hide_spatial(x):
    N, C, H, W = x.shape
    L = N*H*W
    return x.permute(0, 2, 3, 1).reshape(L, C)

def convolutions(x, weights, padding=1):
    return torch.cat([F.conv2d(x[i:i+1], weights[i], bias=None, padding=padding)  for i in range(len(x))])

class ConvPlastic(RNNCell):
    r"""ConvPlasticCell module, applies sequential part of ConvRNNPlastic.

    a convolutional derivation of https://arxiv.org/pdf/1804.02464.pdf

    the module learns weights by applying hebbian rule convolutionally.

    V1: the plastic weights are accumulated accross the receptive field (only global convolutions)
    """
    def __init__(self, in_channels, hidden_dim, kernel_size=3, hard=False, local=False):
        super(ConvPlastic, self).__init__(hard)
        self.hidden_dim = hidden_dim

        self.conv_x2h = SequenceWise(ConvLayer(in_channels, hidden_dim,
                                             kernel_size=5,
                                             stride=2,
                                             dilation=1,
                                             padding=2,
                                             activation='Identity'))

        self.K = kernel_size
        self.P = kernel_size//2
        self.C = hidden_dim
        self.CK2 = self.C * self.K**2

        # fixed part of weights
        self.fixed_weights = nn.Parameter(.01 * torch.randn(self.C, self.C, self.K, self.K).float())

        # fixed modulation of plastic weights
        self.alpha = nn.Parameter(.01 * torch.randn(self.C, self.C, self.K, self.K).float())

        self.eta = nn.Parameter( .01 * torch.ones(1).float() )
        self.reset()

    def forward(self, xi):
        xi = self.conv_x2h(xi)
        xiseq = xi.split(1, 0)  # t,n,c,h,w

        T, N, C, H, W = xi.shape
        L = N*H*W

        if self.prev_h is not None:
            self.hebb = self.hebb.detach()
            self.prev_h = self.prev_h.detach()
        else:
            self.prev_h = torch.zeros(N, C, H, W).float().to(xi)
            self.hebb = torch.zeros(N, self.C, self.C, self.K, self.K).float().to(xi)

        result = []
        for t, xt in enumerate(xiseq):
            xt = xt.squeeze(0)
            self.prev_h, self.hebb = self.forward_t(xt, self.prev_h, self.hebb)
            result.append(self.prev_h.unsqueeze(0))

        res = torch.cat(result, dim=0)
        return res

    def forward_t(self, xt, hin, hebb):
        weights = hebb * self.alpha.unsqueeze(0) + self.fixed_weights
        hout = torch.tanh(convolutions(hin, weights) + xt)
        hebb = self.update_hebbian(hin, hout, hebb)
        return hout, hebb

    def update_hebbian(self, hin, hout, hebb):
        N, C, H, W = hout.shape
        hin_col = im2col(hin, self.K, self.P)
        delta = outer_conv(hin_col, hout)
        delta = delta.reshape(N, H*W, self.CK2, C).mean(dim=1) # [N, CK2, C]
        delta = delta.reshape(N, C,  self.K, self.K, self.C).permute(0, 1, 4, 2, 3) # [N, C, C, K, K]
        hebb = (hebb + self.eta * delta).clamp_(-1, 1)
        return hebb

    def reset(self):
        self.prev_h = None
        self.hebb = None

if __name__ == '__main__':
    x = torch.rand(10, 5, 7, 16, 16)

    net = ConvPlasticCell(7)
    y = net(x)
    print(y.shape)


from command.control_commands.control_command import ControlCommand
from terminal.confirm import Confirm

class QuitCommand(ControlCommand):
    def __init__(self):
        super().__init__()
        self.__confirm = Confirm()

    def execute(self, *args):
        sequences = self.get_all_sequences()
        modified_num = 0
        new_num = 0
        for seq in sequences:
            if seq.get_status() == "modified":
                modified_num += 1
            elif seq.get_status() == "new":
                new_num += 1
        if modified_num != 0 or new_num != 0:
            if modified_num == 0:
                message = "There are {} new sequences. Are you sure you want to quit?".format(new_num)
            elif new_num == 0:
                message = "There are {} modified sequences. Are you sure you want to quit?".format(modified_num)
            else:
                message = "There are {} modified and {} new sequences. Are you sure you want to quit?".format(
                    modified_num, new_num)
            user_confirm = self.__confirm.run(message)
            if not user_confirm:
                return "Quit cancelled"
        return "Thank you for using Dnalanyzer."


import argparse
import os
import time
import gym
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from PPO import PPO
from unity_wrapper_zzy import UnityWrapper

parser = argparse.ArgumentParser(description='Train or test neural net motor controller.')
parser.add_argument('--train', dest='train', action='store_true', default=True)
parser.add_argument('--test', dest='test', action='store_true', default=False)
args = parser.parse_args()

#####################  hyper parameters  ####################

ENV_ID = 'CarVerification-2'  # environment id
RANDOM_SEED = 1  # random seed
RENDER = True  # render while training

ALG_NAME = 'PPO'
TRAIN_EPISODES = 3000  # total number of episodes for training
TEST_EPISODES = 10  # total number of episodes for testing
MAX_STEPS = 200  # total number of steps for each episode
# GAMMA = 0.9  # reward discount
# LR_A = 0.00001  # learning rate for actor0.00001
# LR_C = 0.00002  # learning rate for critic0.0005
BATCH_SIZE = 32  # update batch size
# ACTOR_UPDATE_STEPS = 10  # actor update steps
# CRITIC_UPDATE_STEPS = 10  # critic update steps
#
# # ppo-penalty parameters
# KL_TARGET = 0.01
# LAM = 0.5
#
# # ppo-clip parameters
# EPSILON = 0.2

LogDir = os.path.join("logs/"+ENV_ID)

if __name__ == '__main__':
    if RENDER:  # 流畅渲染，看训练效果
        env = UnityWrapper(train_mode=False, base_port=5004)
    else:
        env = UnityWrapper(train_mode=True, base_port=5004)
    obs_shape_list, d_action_dim, c_action_dim = env.init()
    print("obs_shape_list", obs_shape_list)
    print("d_action_dim:", d_action_dim)
    print("c_action_dim:", c_action_dim)

    agent = PPO(obs_shape_list[0], d_action_dim, c_action_dim, 1)

    t0 = time.time()
    if args.train:
        summary_writer = tf.summary.create_file_writer(LogDir)
        all_episode_reward = []
        for episode in range(TRAIN_EPISODES):
            obs_list = env.reset()
            state = obs_list[0][0]
            # print("state:", state)
            # print("state_dim:", state.shape)
            # print("type_state:", type(state))
            n_agents = obs_list[0].shape[0]
            # print("n_agent:", n_agents)
            episode_reward = 0
            for step in range(MAX_STEPS):  # in one episode
                if d_action_dim != 0:  # 离散动作
                    d_action = agent.get_action(state, d_action_dim)
                    # print("d_action:", d_action)  # d_action: [3]
                    d_action_to_unity = np.eye(d_action_dim, dtype=np.int32)[d_action]
                    # print("d_action_toUnity:", d_action_to_unity)
                    obs_list, reward, done, max_step = env.step(d_action_to_unity, None)
                    agent.store_transition(state, d_action, reward)
                else:  # 连续动作
                    c_action = agent.get_action(state, d_action_dim)
                    # print("c_action:", c_action)  # c_action: [1. 1.]
                    # print("type_c_action:", type(c_action))
                    c_action_to_unity = c_action[np.newaxis, :]
                    # print("c_action_to_unity", c_action_to_unity)
                    obs_list, reward, done, max_step = env.step(None, c_action_to_unity)
                    # print("obs_list", obs_list)
                    # print("reward:", reward)  # [0.]
                    agent.store_transition(state, c_action, reward)

                # print("state_buffer:", agent.state_buffer)
                # print("length:", len(agent.state_buffer))
                # print("action_buffer:", agent.action_buffer)
                # print("len:", len(agent.action_buffer))
                # print("reward_buffer:", agent.reward_buffer)
                # print("len:", len(agent.reward_buffer))

                state = obs_list[0][0]  # state=state_
                episode_reward += reward[0]

                # update ppo
                if len(agent.state_buffer) >= BATCH_SIZE:
                    agent.finish_path(obs_list[0][0], done)
                    agent.update(d_action_dim)
                if done:
                    break
            agent.finish_path(obs_list[0][0], done)
            print(
                'Training  | Episode: {}/{}  | Episode Reward: {:.4f}  | Running Time: {:.4f}'.format(
                    episode + 1, TRAIN_EPISODES, episode_reward, time.time() - t0)
            )
            if episode == 0:
                all_episode_reward.append(episode_reward)
            else:
                all_episode_reward.append(all_episode_reward[-1] * 0.9 + episode_reward * 0.1)

            with summary_writer.as_default():  # 希望使用的记录器
                tf.summary.scalar('reward', episode_reward, step=episode)
        agent.save(ALG_NAME, ENV_ID)

        plt.plot(all_episode_reward)
        if not os.path.exists('image'):
            os.makedirs('image')
        plt.savefig(os.path.join('image', '_'.join([ALG_NAME, ENV_ID])))

    if args.test:
        # test
        agent.load(ALG_NAME, ENV_ID)
        average_success_rate = 0
        for episode in range(TEST_EPISODES):
            obs_list = env.reset()
            state = obs_list[0][0]
            # print("state:", state)
            # print("state_dim:", state.shape)
            n_agents = obs_list[0].shape[0]
            episode_reward = 0
            success_tag = 0
            for step in range(MAX_STEPS):
                if d_action_dim != 0:  # 离散动作
                    d_action = agent.get_action(state, d_action_dim)
                    # print("d_action:", d_action)  # d_action: [3]
                    d_action_to_unity = np.eye(d_action_dim, dtype=np.int32)[d_action]
                    # print("d_action_toUnity:", d_action_to_unity)
                    obs_list, reward, done, max_step = env.step(d_action_to_unity, None)
                    if done:
                        success_tag += 1
                    state = obs_list[0][0]
                    episode_reward += reward[0]
                else:  # 连续动作
                    c_action = agent.get_action(state, d_action_dim)
                    # print("c_action:", c_action)  # c_action: [1. 1.]
                    # print("type_c_action:", type(c_action))
                    c_action_to_unity = c_action[np.newaxis, :]
                    # print("c_action_to_unity", c_action_to_unity)
                    obs_list, reward, done, max_step = env.step(None, c_action_to_unity)
                    if done:
                        success_tag += 1
                state = obs_list[0][0]  # state=state_
                episode_reward += reward[0]
                if done:
                    break
            print("success:", success_tag)
            average_success_rate += success_tag
            print(
                'Testing  | Episode: {}/{}  | Episode Reward: {:.4f}  | Running Time: {:.4f}'.format(
                    episode + 1, TEST_EPISODES, episode_reward,
                    time.time() - t0))
        print('Testing  | Average Success Rate: {}'.format(
                    average_success_rate/TEST_EPISODES))


from .base import (
    ScraperModel,
    Price,
    Title,
    Description,
    Tags,
    Longitude,
    Latitude,
    PictureURL,
    PostTime,
    PostID
)
from ...shared.models.furniture import FurnitureDAO

class FurnitureScraperModel(ScraperModel):

    DB_MODEL = FurnitureDAO

    def __init__(self, soup, url):
        self.url = url
        self._id = PostID(soup)
        self._price = Price(soup)
        self._title = Title(soup)
        self._description = Description(soup)
        self._tags = Tags(soup)
        self._longitude = Longitude(soup)
        self._latitude = Latitude(soup)
        self._picture_url = PictureURL(soup)
        self._post_time = PostTime(soup)
        super().__init__(soup)

    def to_dict(self):
        res = super().to_dict()
        res['_id'] = res['id']
        res['url'] = self.url
        del res['id']
        return res


"""Module test user information reource."""
import json
from unittest import mock

from flask import Response

from .base_test import BaseTestCase, Center, Cohort, Society
from api.utils.marshmallow_schemas import basic_info_schema

def info_mock(status_code, society=None, location=None, cohort=None, data=None):
    """Mock reponses from api calls to ANDELA API."""
    data = {} if not data else data
    api_response = Response()
    api_response.json = lambda: data
    api_response.status_code = status_code
    return cohort, location, api_response

class UserInformationTestCase(BaseTestCase):
    """Test get user information reource."""

    def setUp(self):
        """Set up patch information for every test."""
        BaseTestCase.setUp(self)
        self.nairobi.save()
        self.cohort_12_Ke.save()
        self.successops_role.save()
        self.society = Society(name="iStelle")
        self.society.cohorts.append(self.cohort_12_Ke)
        self.society.save()
        self.successops_token = {"Authorization":
                                 self.generate_token(
                                  self.test_successops_payload)}

        cohort = self.cohort_12_Ke
        self.patcher = mock.patch('api.services.auth.helpers.add_extra_user_info',
                                  return_value=info_mock(200,
                                                         location=self.nairobi,
                                                         cohort=cohort,
                                                         society=self.society))
        self.patcher.start()

    def test_get_user_info_saved_in_DB(self):
        """Test retrive saved information sucesfully."""
        self.cohort_1_Nig.save()
        self.phoenix.cohorts.append(self.cohort_1_Nig)
        self.phoenix.save()
        self.test_user.save()

        response = self.client.get('/api/v1/users/-KdQsMt2U0ixIy_-yWTSZ',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response.status_code, 200)
        response1 = self.client.get('/api/v1/users/all',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response1.status_code, 401)
        response2 = self.client.get('/api/v1/users/all',
                                   headers=self.successops_token,
                                   content_type='application/json')
        self.assertEqual(response2.status_code, 200)

        response_data = json.loads(response.data)

        expected_location_data, _ = basic_info_schema.dump(self.lagos)
        self.assertDictEqual(response_data.get('data').get('location'),
                             expected_location_data)
        expected_society_data, _ = basic_info_schema.dump(self.phoenix)
        self.assertDictEqual(response_data.get('data').get('society'),
                             expected_society_data)
        expected_cohort_data, _ = basic_info_schema.dump(self.cohort_1_Nig)
        self.assertDictEqual(response_data.get('data').get('cohort'),
                             expected_cohort_data)

    def test_get_user_info_not_saved_in_DB(self):
        """Test retrive user info from ANDELA API sucesfully."""
        mock_location = Center(name='Mock-location')
        mock_location.save()
        mock_cohort = Cohort(name="mock_cohort", center=mock_location)
        mock_cohort.save()
        mock_society = Society(name="Mock-society")
        mock_society.cohorts.append(mock_cohort)
        mock_society.save()

        # build mock reponse
        user_mock_response = {
            'email': "mock.user.societies@andela.com",
            'first_name': "mock_user",
            'id': "-Krwrwahorgt-mock-user-id",
            'last_name': "mock_user",
            'picture': "https://www.link.com/picture_id",
            'location': {'id': mock_location.uuid},
            'cohort': {'id': mock_cohort.uuid},
            'roles': {
                "Andelan": "-Ktest_andelan_id",
                "Fellow": "-KXGy1EB1oimjQgFim6C"
            }
        }

        patcher = mock.patch('api.endpoints.users.users.add_extra_user_info',
                             return_value=info_mock(200,
                                                    society=mock_society,
                                                    location=mock_location,
                                                    cohort=mock_cohort,
                                                    data=user_mock_response))
        patcher.start()

        response = self.client.get('/api/v1/users/-Krwrwahorgt-mock-user-id',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response.status_code, 200)
        response_data = json.loads(response.data)

        expected_location_data, _ = basic_info_schema.dump(mock_location)
        self.assertDictEqual(response_data.get('data').get('location'),
                             expected_location_data)

        expected_society_data, _ = basic_info_schema.dump(mock_society)
        self.assertDictEqual(response_data.get('data').get('society'),
                             expected_society_data)

        expected_cohort_data, _ = basic_info_schema.dump(mock_cohort)
        self.assertDictEqual(response_data.get('data').get('cohort'),
                             expected_cohort_data)

        patcher.stop()

    @mock.patch('api.endpoints.users.users.add_extra_user_info',
                return_value=info_mock(404, data={"error": "user not found"}))
    def test_get_user_info_404(self, mocked_func):
        """Test handles user not found."""
        response = self.client.get('/api/v1/users/-KoJA5HXKK5nVeIdc2Sv',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response.status_code, 404)
        response_data = json.loads(response.data)
        self.assertDictEqual(response_data, {"error": "user not found"})

    @mock.patch('api.endpoints.users.users.add_extra_user_info',
                return_value=info_mock(503, data={"Error": "Network Error"}))
    def test_get_user_info_503(self, mocked_func):
        """Test handles failed network connection correctly."""
        response = self.client.get('/api/v1/users/-KoJA5HXKK5nVeIdc2Sv',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response.status_code, 503)
        response_data = json.loads(response.data)
        self.assertDictEqual(response_data, {"Error": "Network Error"})

    @mock.patch('api.endpoints.users.users.add_extra_user_info',
                return_value=info_mock(500,
                                       data={"Error": "Something went wrong"}))
    def test_get_user_info_500(self, mocked_func):
        """Test handles unexpected API issues correctly."""
        response = self.client.get('/api/v1/users/-KoJA5HXKK5nVeIdc2Sv',
                                   headers=self.header,
                                   content_type='application/json')
        self.assertEqual(response.status_code, 500)
        response_data = json.loads(response.data)
        self.assertDictEqual(response_data, {"Error": "Something went wrong"})


from typing import Type, TypeVar, MutableMapping, Any, Iterable

from datapipelines import (
    DataSource,
    PipelineContext,
    Query,
    NotFoundError,
    validate_query,
)
from .common import RiotAPIService, APINotFoundError
from ...data import Platform, Region
from ...dto.staticdata.version import VersionListDto
from ...dto.spectator import CurrentGameInfoDto, FeaturedGamesDto
from ..uniquekeys import convert_region_to_platform

T = TypeVar("T")

def _get_default_version(
    query: MutableMapping[str, Any], context: PipelineContext
) -> str:
    pipeline = context[PipelineContext.Keys.PIPELINE]
    versions = pipeline.get(VersionListDto, {"platform": query["platform"]})
    return versions["versions"][0]

def _get_default_locale(
    query: MutableMapping[str, Any], context: PipelineContext
) -> str:
    return query["platform"].default_locale

class SpectatorAPI(RiotAPIService):
    @DataSource.dispatch
    def get(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> T:
        pass

    @DataSource.dispatch
    def get_many(
        self,
        type: Type[T],
        query: MutableMapping[str, Any],
        context: PipelineContext = None,
    ) -> Iterable[T]:
        pass

    ################
    # Current Game #
    ################

    _validate_get_current_game_query = (
        Query.has("platform").as_(Platform).also.has("summoner.id").as_(str)
    )

    @get.register(CurrentGameInfoDto)
    @validate_query(_validate_get_current_game_query, convert_region_to_platform)
    def get_current_game(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> CurrentGameInfoDto:
        url = "https://{platform}.api.riotgames.com/lol/spectator/v4/active-games/by-summoner/{id}".format(
            platform=query["platform"].value.lower(), id=query["summoner.id"]
        )
        try:
            app_limiter, method_limiter = self._get_rate_limiter(
                query["platform"], "spectator/active-games/by-summoner"
            )
            data = self._get(
                url, {}, app_limiter=app_limiter, method_limiter=method_limiter
            )
        except APINotFoundError as error:
            raise NotFoundError(str(error)) from error

        data["region"] = query["platform"].region.value
        data["summonerId"] = query["summoner.id"]
        return CurrentGameInfoDto(data)

    #################
    # Featured Game #
    #################

    _validate_get_featured_game_query = Query.has("platform").as_(Platform)

    @get.register(FeaturedGamesDto)
    @validate_query(_validate_get_featured_game_query, convert_region_to_platform)
    def get_featured_games(
        self, query: MutableMapping[str, Any], context: PipelineContext = None
    ) -> FeaturedGamesDto:
        url = "https://{platform}.api.riotgames.com/lol/spectator/v4/featured-games".format(
            platform=query["platform"].value.lower()
        )
        try:
            app_limiter, method_limiter = self._get_rate_limiter(
                query["platform"], "featured-games"
            )
            data = self._get(
                url, {}, app_limiter=app_limiter, method_limiter=method_limiter
            )
        except APINotFoundError as error:
            raise NotFoundError(str(error)) from error

        data["region"] = query["platform"].region.value
        for game in data["gameList"]:
            game["region"] = data["region"]
        return FeaturedGamesDto(data)


'''

||||||||||||||||||||                                             | n_flanges_top
||||||||||||||||||||                                             | h_flange
    ||||    ||||
    ||||    ||||        ------------------- centroidal axis                         | n_webs
    ||||    ||||                                                                    | h_web
    ||||    ||||                                                                    | b_webs
||||||||||||||||||||    __________________ datum                 | n_flanges_bot

'''

import math as m

class Beam:
    def __init__(self, n_webs = 0, n_flanges_top = 0, n_flanges_bot = 0, b_web = 0, b_flange = 0, h_web = 0, h_flange = 0):
        self.n_webs = n_webs
        self.n_flanges_top = n_flanges_top
        self.n_flanges_bot = n_flanges_bot
        self.b_web = b_web
        self.b_flange = b_flange
        self.h_web = h_web
        self.h_flange = h_flange

    def calc_Centroid(self):

        bot_A = self.n_flanges_bot * self.h_flange * self.b_flange
        bot_y = (self.n_flanges_bot* self.h_flange)/2

        mid_A = self.n_webs * self.h_web * self.b_web
        mid_y = (self.h_web/2) + (self.n_flanges_bot * self.h_flange)

        top_A = self.n_flanges_top * self.h_flange * self.b_flange
        top_y = (self.n_flanges_top * self.h_flange)/2 + (self.h_web) + (self.n_flanges_bot * self.h_flange)

        Y = (top_A * top_y + mid_A * mid_y + bot_A * bot_y)/ (top_A + mid_A + bot_A)

        return Y

    def calc_I(self):

        Y = self.calc_Centroid()

        bot_A = self.n_flanges_bot * self.h_flange * self.b_flange
        bot_y_b = abs(Y - ( (self.n_flanges_bot * self.h_flange)/2 ))
        #After || axis
        bot_I = (self.b_flange * (self.n_flanges_bot * self.h_flange)**3)/12 + (bot_A * (bot_y_b**2))

        mid_A = self.n_webs * self.h_web * self.b_web
        mid_y_b = abs( Y - ((self.h_web/2) + (self.n_flanges_bot * self.h_flange)) )
        #After || axis
        mid_I = self.n_webs*(self.b_web * (self.h_web)**3)/12 + (mid_A * (mid_y_b**2))

        top_A = self.n_flanges_top * self.h_flange * self.b_flange
        top_y_b = abs(Y - (self.n_flanges_top * self.h_flange)/2 + (self.h_web) + (self.n_flanges_bot * self.h_flange))
        #After || axis
        top_I = (self.b_flange * (self.n_flanges_top * self.h_flange)**3)/12 + (top_A * (top_y_b**2))

        I = bot_I + mid_I + top_I

        return I

    def calc_Q(self):
        Y = self.calc_Centroid()

        Q_glue = (self.n_flanges_top* self.h_flange * self.b_flange)  *  abs(Y - (self.n_flanges_top * self.h_flange)/2 + (self.h_web) + (self.n_flanges_bot * self.h_flange))
        Q_section = (self.n_flanges_top* self.h_flange * self.b_flange + (self.n_webs * self.b_web * self.h_web/2) )  *  abs( Y - ((self.h_web/2) + (self.n_flanges_bot * self.h_flange)) )

        return (Q_glue, Q_section)

    #Failure P Checks:

    def calc_P_Flex(self):
        '''
        check for (t and c) at both (190 and 166) mark i.e. 4 values
        '''

        I = self.calc_I()
        Y = self.calc_Centroid()

        Pc_166 = (6 * I)/ (166 * ((self.n_flanges_bot * self.h_flange + self.h_web + self.n_flanges_top * self.h_flange)-Y))
        Pt_166 = (30 * I)/ (166 * (Y))

        Pc_190 = (6 * I)/ (166 * Y)
        Pt_190 = (30 * I)/ (166 * ((self.n_flanges_bot * self.h_flange + self.h_web + self.n_flanges_top * self.h_flange)-Y))

        Pc_f = min(Pc_166, Pc_190)
        Pt_f = min(Pt_166, Pt_190)

        return (Pt_f, Pc_f)

    def calc_P_Shear(self):
        # Check for Shear both at Glue and Section
        I = self.calc_I()
        Q = self.calc_Q()
        Ps = 6 * I * (self.b_web * self.n_webs)/ Q[1]
        Pg = 2 * I * (self.b_web * self.n_webs)/ Q[0]

        return (Pg, Ps)

    def calc_P_Plate(self):
        I = self.calc_I()
        Y = self.calc_Centroid()
        Q = self.calc_Q()

        t = (self.n_flanges_top * self.h_flange)
        h = self.h_web
        a = 530

        # Stress eqn 1
        S_t = (4 * (math.pi**2)* 4000 * (t)**2 ) / ( 12 * 0.96 * (self.b_flange**2))

        Pc_166_st = (6 * I)/ (166 * ((self.n_flanges_bot * self.h_flange + self.h_web + self.n_flanges_top * self.h_flange)-Y))
        Pc_190_st = (6 * I)/ (166 * Y)

        Pt_f = min(Pc_166, Pc_190)

        # Stress eqn 3
        S_w = (0.425 * (math.pi**2)* 4000 * (t)**2 ) / ( 12 * 0.96 * (self.b_flange**2))

        Pc_166_sw = (6 * I)/ (166 * ((self.n_flanges_bot * self.h_flange + self.h_web + self.n_flanges_top * self.h_flange)-Y))
        Pc_190_sw = (6 * I)/ (166 * Y)

        Pw_f = min(Pc_166, Pc_190)

        # Shear eqn 4
        Tau =  (  (5 * (math.pi**2)* 4000 * (self.h_flange)**2 )  *  ((t/h)**2 + (t/a)**2)  ) / ( 12 * 0.96)

        PTau_f = Tau * I * (self.b_web * self.n_webs)/ Q[1]
        return(Pt_f, Pw_f, PTau_f)

if __name__ == "__main__":
    n_webs = 2
    n_flanges_top = 1
    n_flanges_bot = 1
    b_web = 1.27
    b_flange = 100
    h_web = 150
    h_flange = 1.27

    Volume = 1275 * ( h_flange * b_flange * (n_flanges_top + n_flanges_bot) + (n_webs * b_web * h_web) )

    if Volume <= 825000:
        B = Beam(n_webs, n_flanges_top , n_flanges_bot, b_web, b_flange, h_web, h_flange)
        print(B.calc_P_Flex())
        print(B.calc_P_Shear())
        print(B.calc_P_Plate())

    else:
        print("Try Again")


from multiprocessing import Process,Queue,Pipe
from slave import serialize
import time

def timer(*args, f=None):
    before = time.time()
    f(*args)
    after = time.time()
    return after - before

big_str = ' '.join(['abcdeftghijklmnopq\n' for y in range(1000000)]) + ' '
print(len(big_str))

parent_conn,child_conn = Pipe()
p = Process(target=serialize, args=(child_conn,big_str))

def run(proc, conn):
    proc.start()
    conn.recv()

print(timer(p, parent_conn, f=run))


import sys
import os

from npbgpp.npbgplusplus.modeling.refiner.unet import RefinerUNet

from pytorch3d.io import load_obj, load_ply, save_obj
import cv2
import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import trimesh
import yaml

from .quad_rasterizer import QuadRasterizer

from NeuS.models.dataset import load_K_Rt_from_P
from src.utils.util import tensor2image
from src.utils.geometry import project_orient_to_camera, soft_interpolate, hard_interpolate

class Renderer(nn.Module):
    def __init__(
        self,
        config,
        device='cuda',
        save_dir='strands_rasterizer'
    ):
        super(Renderer, self).__init__()

        self.image_size = config.get('image_size', 512)
        self.out_channels = config.get('out_channels', -1)
        self.logging_freq = config.get('logging_freq', 5000)
        self.feat_size = config.get('feat_size', -1)
        self.num_strands = config.get('num_strands', -1)
        self.use_orients_cond = config.get('use_orients_cond', False)
        self.use_silh = config.get('use_silh', False)
        self.device = device

         # Load head mesh for occlusion
        if config.get('mesh_path', -1).split('.')[-1] == 'obj':
            verts, faces, _ = load_obj(config.get('mesh_path', -1))
            occlusion_faces = faces.verts_idx
        else:
            verts, faces = load_ply(config.get('mesh_path', -1))
            occlusion_faces = faces

        verts = verts.to(self.device)
        occlusion_faces = occlusion_faces.to(self.device)

        # Init rasterizers and renderers
        self.rasterizer = QuadRasterizer(
                                    render_size=self.image_size,
                                    feats_dim=self.feat_size + self.use_silh,
                                    head_mesh=(verts, occlusion_faces),
                                    use_silh=self.use_silh,
                                    use_orients_cond=self.use_orients_cond,
                                ).to(self.device)

        self.refiner_unet = RefinerUNet(
            conv_block='gated',
            num_input_channels=self.feat_size + 4 * self.use_orients_cond ,
            feature_scale=4,
            num_output_channels=self.out_channels
        ).to(self.device)

        self.save_dir = os.path.join(save_dir, 'strands_rasterizers')
        os.makedirs(self.save_dir, exist_ok=True)

    def forward(self, strands_origins, z_app, raster_dict, iter):

        rasterized = self.rasterizer(
            strands_origins,
            torch.cat((z_app, torch.ones(self.num_strands, 1).cuda()), dim=1),
            raster_dict['cam_extr'],
            raster_dict['cam_intr']
        )

        rasterized_features = rasterized[:, : self.feat_size, :, :]
        raster_dict['rasterized_img'] = rasterized_features[0]

        if self.use_orients_cond:
            raster_idxs = rasterized[0, self.feat_size + 1:, :, :]
            rasterized = rasterized[:, :self.feat_size + 1, :, :]

            orients = torch.zeros_like(strands_origins)
            orients[:, :orients.shape[1] - 1] = (strands_origins[:, 1:] - strands_origins[:, :-1])
            orients[:, orients.shape[1] - 1: ] = orients[:, orients.shape[1] - 2: orients.shape[1] - 1]
            orients = orients.reshape(-1, 3)

            r = raster_idxs
            r[r == 0] = -1
            valid_pixels = r[r != -1]

            strands_origins = soft_interpolate(valid_pixels.cuda(), strands_origins.view(-1, 3))

            # Hard rasterize orientations
            hard_orients = hard_interpolate(valid_pixels.cuda(), orients)

            # Project orients and points from 3d to 2d with camera
            projected_orients = project_orient_to_camera(hard_orients.unsqueeze(1), strands_origins, cam_intr=raster_dict['cam_intr'],  cam_extr=raster_dict['cam_extr'])

            plane_orients = torch.zeros(self.image_size, self.image_size, 1, device=hard_orients.device)
            plane_orients[r[0]!=-1, :] = projected_orients
            raster_dict['pred_orients'] = plane_orients.permute(2, 0, 1)

            orient_cos_fine = plane_orients.cos()
            orient_fine_cam = torch.cat(
                [
                    orient_cos_fine * (orient_cos_fine >= 0),
                    plane_orients.sin(),
                    orient_cos_fine.abs() * (orient_cos_fine < 0)
                ],
                dim=-1
            )
            raster_dict['visual_pred_orients'] = (orient_fine_cam.detach().cpu().numpy() * 255).clip(0, 255)

        raster_dict['pred_silh'] = rasterized[0, self.feat_size:, :, :]
        # Inpaint holes with unet
        inp = [rasterized_features]
        if self.use_orients_cond:
            inp.append(plane_orients.permute(2, 0, 1)[None])
            inp.append(orient_fine_cam.permute(2, 0, 1)[None])
        inp = torch.cat(inp, dim=1)

        rgb_hair_image = self.refiner_unet([inp]) #[1, 3, 512, 512]
        raster_dict['pred_rgb'] = rgb_hair_image[0, :3]
        return raster_dict

    def calculate_losses(self, raster_dict, iter):
        losses = {}

        color_strands_error = (raster_dict['pred_rgb'] - raster_dict['gt_rgb']) * raster_dict['gt_silh']

        losses['l1'] = F.l1_loss(
            color_strands_error,
            torch.zeros_like(color_strands_error), reduction='sum'
        ) / (raster_dict['gt_silh'].sum() + 1e-5)

        losses['silh'] = ((raster_dict['pred_silh'] - raster_dict['gt_silh']).abs()).mean()

        if iter % self.logging_freq == 0:
            self.visualize(raster_dict, iter)

        return losses

    def visualize(self, visuals, iter):
        cv2.imwrite(os.path.join(self.save_dir, f'rasterize_{iter}_resol_512.png'), tensor2image(visuals['rasterized_img'][:3, :, :]))

        cv2.imwrite(os.path.join(self.save_dir, f'pred_silh_{iter}_resol_512.png'), tensor2image(visuals['pred_silh'][:3, :, :]))
        cv2.imwrite(os.path.join(self.save_dir, f'gt_silh_{iter}_resol_512.png'), tensor2image(visuals['gt_silh'][:3, :, :]))

        cv2.imwrite(
            os.path.join(self.save_dir, f'pred_hair_strands_{iter}.png'),
            tensor2image(visuals['pred_rgb'][:3, :, :] * visuals['gt_silh'] + 1 - visuals['gt_silh'])
        )
        cv2.imwrite(
            os.path.join(self.save_dir, f'gt_hair_strands_{iter}.png'),
            tensor2image(visuals['gt_rgb'][:3, :, :] * visuals['gt_silh'] + 1 - visuals['gt_silh'])
        )

        if self.use_orients_cond or self.use_gabor_loss:
            cv2.imwrite(os.path.join(self.save_dir, f'pred_hair_or_{iter}.png'), visuals['visual_pred_orients'])
            cv2.imwrite(os.path.join(self.save_dir, f'gt_hair_or_{iter}.png'), visuals['visual_gt_orients'])


# encoding=utf-8

# encoding=utf-8
import data_input
import tensorflow as tf
import numpy as np
import sequence_model
from sklearn import metrics
import warnings

warnings.filterwarnings("ignore")

filename = "../Data/29_1.txt"
train_eval_split_line = 0.9
batch_size = 9600
show_step = 200
filemark = ""  # "" default test all file
master = data_input.DataMaster(train_mode=False, test_file=filemark)

model = sequence_model.SeqModel()

dataset = []
with open(filename, "r") as file:
    for url in file.readlines():
        url = url.strip()
        dataset.append(url)

saver = tf.train.Saver()

y_pred = []
with tf.Session() as sess:
    saver.restore(sess, '../Cache/sequence_model')
    sess.run(tf.local_variables_initializer())
    for step, index in enumerate(range(0, len(dataset), batch_size)):
        batch_xs, batch_lens = master.mapping(dataset[index:index + batch_size])
        predictions = sess.run(model.prediction,
                               feed_dict={model.x: batch_xs,
                                          model.batch_lens: batch_lens})
        y_pred.extend(predictions.tolist())

print(y_pred)

with open(filename, "r") as file, open(filename[:-4] + "_pred.txt", "w") as fileWriter:
    for i, url in enumerate(file.readlines()):
        url = url.strip()
        mark = "malicious" if y_pred[i] else "benign"
        fileWriter.write(url + "\t" + mark + "\n")
    print("%s write done!" % (filename[:-4] + "pred.txt"))


# Author: Ranjodh Singh

import requests
from bs4 import BeautifulSoup as bs
import os

url = "http://www.thehindu.com/archive/"
html = requests.get(url)
soup = bs(html.__dict__['_content'], "html5lib")
container = soup.select("#archiveTodayContainer")

for link in container[0].find_all("a"):
    resp = requests.get(link['href'])
    soup = bs(resp.__dict__['_content'], "html5lib")
    daily_links = soup.select("[class~=ui-state-default]")
    for l in daily_links:
        web_link = l['href']
        new_dir = "/".join(web_link.split("/")[-4:-1])
        os.makedirs(new_dir)
        s = bs(requests.get(web_link).__dict__['_content'], "html5lib")
        news_links = s.find_all('tr')[3].find_all('td')[-2].find_all("a")
        news_links = [i for i in news_links if "stories" in i['href']]
        print("Fetching news from ", web_link)
        for n in range(len(news_links)):
            news = bs(requests.get(web_link + news_links[n]['href']).__dict__['_content'], "html5lib")
            try:
                headline = news.find("h3").get_text()
            except:
                headline = ""
            with open(new_dir + "/" + str(n) + ".txt", "w") as f:
                f.write(headline)
                for x in news.find_all('p')[:-4]:
                    f.write(x.get_text())


import numpy as np

class Stack:
    def __init__(self):
        self.arr = np.array([0] * 2, dtype="<U10")
        self.end = 0
        self.capacity = 2

    def push(self, a):
        self.arr[self.end] = a
        self.end += 1
        if self.end == self.capacity:
            self.resize(self.capacity * 2)
            print("resize")

    def pop(self):
        if self.end == 0:
            print("Stack is empty")
            return
        self.end -= 1
        return self.arr[self.end]

    def resize(self, n):
        temp = np.array([0] * n, dtype="<U10")
        for i in range(self.end):
            temp[i] = self.arr[i]
        del self.arr
        self.arr = temp
        self.capacity = n

def do_op(a, b, opr):
    switcher = {
        '+': b + a,
        '-': b - a,
        '*': b * a,
        '/': b / a,
        '^': b ^ a,
    }
    return switcher[opr]

exp = input("Enter the Expression: ")
exp = list(exp.split(" "))
op = Stack()
val = Stack()
for i in exp:
    if i.isdigit():
        val.push(int(i))
    elif i == "(":
        pass
    elif i == ")":
        res = do_op(int(val.pop()), int(val.pop()), op.pop())
        val.push(str(res))
    else:
        op.push(i)

print(val.pop())

python/Stack Queue/Shunting Yard Algorithm.py


connected_nodes = [[0, 2], [0, 3], [1, 2], [1, 4], [2, 3], [2, 5], [3, 4], [4, 5]]
num_nodes = 6  # max(max(x) for x in connected_nodes) + 1
nodes = list(range(num_nodes))

# This is wrong. see:
# https://docs.python.org/2/faq/programming.html#how-do-i-create-a-multidimensional-list
# matrix = [[0]*num_nodes]*num_nodes

matrix = [[0] * num_nodes for _ in range(num_nodes)]

print(matrix)
print(connected_nodes)

for x in connected_nodes:
    matrix[x[0]][x[1]] = 1

print(matrix)


class TST(object):
    class Node(object):
        def __init__(self, c):
            self.value = None
            self.c = c
            self.left = None
            self.middle = None
            self.right = None

    def __init__(self):
        self.__root = None

    def put(self, key, value):
        self.__root = self.__put(self.__root, key, value, 0)

    def __put(self, x, key, value, d):
        c = self.__char_at(key, d)
        if x is None:
            x = self.Node(c)

        if c < x.c:
            x.left = self.__put(x.left, key, value, d)
        elif c > x.c:
            x.right = self.__put(x.right, key, value, d)
        elif d < len(key) - 1:
            x.middle = self.__put(x.middle, key, value, d + 1)
        else:
            x.value = value

        return x

    def get(self, key):
        x = self.__get(self.__root, key, 0)
        return x.value if x is not None else None

    def __get(self, x, key, d):
        if x is None:
            return None

        c = self.__char_at(key, d)

        if c < x.c:
            return self.__get(x.left, key, d)
        elif c > x.c:
            return self.__get(x.right, key, d)
        elif d < len(key) - 1:
            return self.__get(x.middle, key, d + 1)
        else:
            return x

    def contains(self, key):
        return self.get(key) is not None

    def delete(self, key):
        x = self.__get(self.__root, key, 0)
        x.value = None

    def keys(self):
        result = []
        self.__collect(self.__root, "", result)
        return result

    def __collect(self, node, prefix, result):
        if node is None:
            return

        if node.value is not None:
            result.append(prefix + node.c)

        self.__collect(node.left, prefix, result)
        self.__collect(node.middle, prefix+node.c, result)
        self.__collect(node.right, prefix, result)

    def keys_with_prefix(self, prefix):
        result = []
        self.__collect(self.__get(self.__root, prefix, 0), prefix[:-1], result)
        return result

    def longest_prefix_of(self, target):
        pos = self.__get_prefix_pos(self.__root, target, 0, 0)
        return target[:pos+1]

    def __get_prefix_pos(self, x, key, d, length):
        if x is None:
            return length

        if len(key) == d:
            return d

        c = self.__char_at(key, d)

        if c < x.c:
            return self.__get_prefix_pos(x.left, key, d, length)
        elif c > x.c:
            return self.__get_prefix_pos(x.right, key, d, length)
        else:
            if x.value is not None:
                length = d
            if d < len(key) - 1:
                return self.__get_prefix_pos(x.middle, key, d + 1, length)
            else:
                return length

    @staticmethod
    def __char_at(s, d):
        return s[d] if d < len(s) else -1