#import csv
#import fileparse
#%%
import fileparse
def leer_camion(nombre_archivo_camion):
    '''
    LEE UN ARCHIVO Y ORDENA LOS DATOS DE CADA FRUTA

    PRE: DEBE INGRESAR LA RUTA DE UN ARCHIVO LEGIBLE
    POS: DEVUELVE UNA LISTA DE DICCIONARIOS CON LOS DATOS SELECCIONADOS
    '''
    with open(nombre_archivo_camion) as file:
        return fileparse.parse_csv(file, select = ['nombre','cajones','precio'], types = [str, int, float])

#nombre_archivo_camion = '../Data/camion.csv'
#camion = leer_camion(nombre_archivo_camion)

print('-------------------------------------------')
#print(camion)

#%%
def leer_precios(nombre_archivo_precios):
    '''
    LEE UN ARCHIVO, LO ABRE Y
   ORDENA EN UN DICCIONARIO {KEY: VALUE}
   LAS FRUTAS CON SU DATOS
    '''
    with open(nombre_archivo_precios) as file:
        return dict(fileparse.parse_csv(file, types = [str, float], has_headers = False, silence_errors = False))

#nombre_archivo_precios = '../Data/precios.csv'
#precios = leer_precios(nombre_archivo_precios)
print('-------------------------------------------')
#print(precios)
#%%
def hacer_informe(camion, precios):
    lista = []
    for lote in camion:
        precio_venta = precios[lote['nombre']]
        cambio = precio_venta - lote['precio']
        t = (lote['nombre'], lote['cajones'], precio_venta, cambio)
        lista.append(t)
    return lista
#%%

def imprimir_informe(camion, precios):
    '''
    TOMA DOS ARCHIVOS
    MUESTRA UN INFORME ORDENADO
    COMBINANDO LA LECTURA DE 2 ARCHIVOS
    '''

    informe = hacer_informe(camion, precios)
    print('    Nombre    Cajones     Precio     Cambio')
    print('---------- ---------- ---------- ----------')
    for nombre, cajones, precio, cambio in informe:
        precio = f'${precio}'
        print(f'{nombre:>10s} {cajones:>10d} {precio:>10s} {cambio:>10.2f}')
    print('---------- ---------- ---------- ----------')
    return informe

def f_principal(argv):
    if len(argv)!= 3:
        print('Uso inadecuado.')
        print(f'el uso correcto de {argv[0]} es con 2 argumentos más')
    else:
        camion = argv[1]
        precios = argv[2]
        informe = hacer_informe(camion, precios)
        imprimir_informe(informe)

if __name__ == '__main__':
    import sys
    f_principal(sys.argv)

#camion = leer_camion(nombre_archivo_camion)
#precios = leer_precios(nombre_archivo_precios)
#imprimir_informe(camion, precios)

#%%
#Ejercicio 6.10:
#import fileparse

#camion = fileparse.parse_csv('../Data/camion.csv', select = ['nombre', 'cajones', 'precio'], types = [str, int, float]) #Por defecto Headers = True
#lista_precios = fileparse.parse_csv('../Data/precios.csv', types = [str, float])

#precios = dict(lista_precios)

#6.11
#print(imprimir_informe(informe))

#%%
#Ejercicio 6.12:
#import costo_camion
#x = costo_camion.costo_camion('F:/Desktop/Ejercicios/ejercicios_python/Data/fecha_camion.csv')
#print(x)

07 - Diseño, especificación, documentación y estilo/informe_final.py


#Face and eye detection,
#also see: http://docs.opencv.org/trunk/doc/py_tutorials/py_objdetect/py_face_detection/py_face_detection.html
#Training:
#http://docs.opencv.org/doc/user_guide/ug_traincascade.html
#Gerald Schuller, Dec 2014

import numpy as np
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')

cap = cv2.VideoCapture(0)

while(True):
    [retval, frame] = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    print(faces)
    for (x,y,w,h) in faces:
       cv2.rectangle(gray,(x,y),(x+w,y+h),255,2)
       roi_gray = gray[y:y+h, x:x+w]

       eyes = eye_cascade.detectMultiScale(roi_gray)

       for (ex,ey,ew,eh) in eyes:
          cv2.rectangle(gray,(x+ex,y+ey),(x+ex+ew,y+ey+eh),255,2)

    cv2.imshow('Face and Eye Detection',gray)
    #Keep window open until key 'q' is pressed:
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


def finds(n):
    if n==1:
        return 1
    elif n==2:
        return 2
    else:
        for i in range(1,n):
            if i*i>n:
                tmp=i-1
                break
        if tmp*tmp==n:
                return 1
        res=[]
        for i in range(1,n//2+1):
            tmp=finds(i)+finds(n-i)
            res.append(tmp)
        res.sort()
        return res[0]
n=int(input())
print(finds(n))


import argparse
from datasets import load_dataset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def main(args):
    colname = ['Ground Truth', 'SFT', 'PPO']
    df = pd.read_csv(args.file_path)
    score_ar = np.array(df)[:,1:]
    score_ar = np.concatenate(np.hsplit(score_ar, args.n_question), axis = 0)

    avg_score = score_ar.mean(0).astype(float).round(1)
    print(avg_score)

    ratio = {}
    for i in range(2,len(colname)):
        odds_l = []
        for j in range(2):
            odds = (score_ar[:, i] > score_ar[:, j]).astype(float).mean().round(2)
            odds_l.append(odds)
        ratio[colname[i]] = odds_l
    print(ratio)

    if args.plot:
        barWidth = 0.35
        plt.bar(colname, avg_score, width=barWidth)
        plt.yticks(np.arange(0, 3.1, 1))
        plt.xlabel('Avg Score( Max 3 )', fontsize = 15)
        plt.ylabel('Score', fontsize = 15)
        plt.savefig('plot/ppo_avg_score.png',dpi=400)
        plt.close()

        barWidth = 0.2
        br1 = np.arange(len(colname[:2]))
        p1 = plt.bar(br1, ratio[colname[2]], label=colname[:2], width=barWidth)
        plt.axhline(y = 0.5, color = 'r', linestyle = '--')
        plt.xticks([r for r in range(len(colname[:2]))], colname[:2])
        plt.yticks(np.arange(0, 1.1, 0.2))
        plt.xlabel('Human Preference', fontsize = 15)
        plt.ylabel('Odds', fontsize = 15)
        plt.legend((p1[0],), ('PPO',))

        plt.savefig('plot/ppo_preference.png',dpi=400)
        plt.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--file_path', type=str, default='human_preference_ppo.csv')
    parser.add_argument('--n_question', type=int, default=3)
    parser.add_argument('--plot', type=bool, default=True)
    args = parser.parse_args()
    main(args)


class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        el = 0
        count = 0
        for num in nums:
            if count == 0:
                el = num
                count = 1
            elif el == num:
                count += 1
            else:
                count -= 1

        # total_current_count_in_nums = nums.count(count) Assuming that it will always have the largest value
        return el

169. Moore's voting Algo Majority Element.py


def all_to_int(x):
    for i in range(len(x)):
        x[i] = int(x[i])
    return x

def str_to_list(l, split):
    l0 = l[1: len(l)-1].split(split)
    return l0

def handle_each_use_case():
    n = int(input())
    num = input().split(" ")
    num = all_to_int(num)
    total = 0
    current = 1
    num.sort()
    for i in range(1, n):
        if num[i] - num[i-1] == 1:
            current += 1
        else:
            total = max(total, current)
            current = 1
    return total

num = int(input())
for i in range(num):
    res = handle_each_use_case()
    print(res)


class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        slen = len(s)
        plen = len(p)
        if slen == 0 and plen == 0:
            return False
        # initialization:
		# 1. M[0][0] = true, since empty string matches empty pattern
        dp = [[False]*(slen+1) for _ in range(plen+1)]
        dp[0][0] = True

		# 2. M[i][0] = false(which is default value of the boolean array) since empty pattern cannot match non-empty string
		# 3. M[0][j]: what pattern matches empty string ""? It should be #*#*#*#*..., or (#*)* if allow me to represent regex using regex :P,
		# and for this case we need to check manually:
        # as we can see, the length of pattern should be even && the character at the even position should be *,
		# thus for odd length, M[0][j] = false which is default. So we can just skip the odd position, i.e. j starts from 2, the interval of j is also 2.
		# and notice that the length of repeat sub-pattern #* is only 2, we can just make use of M[0][j - 2] rather than scanning j length each time
		# for checking if it matches #*#*#*#*.
        for i in range(2, plen + 1, 2):
            if p[i-1] == '*' and dp[i-2][0]:
                dp[i][0] = True
		# Induction rule is very similar to edit distance, where we also consider from the end. And it is based on what character in the pattern we meet.
        # 1. if p.charAt(j) == s.charAt(i), M[i][j] = M[i - 1][j - 1]
		#    ######a(i)
		#    ####a(j)
        # 2. if p.charAt(j) == '.', M[i][j] = M[i - 1][j - 1]
        # 	  #######a(i)
        #    ####.(j)
        # 3. if p.charAt(j) == '*':
        #    1. if p.charAt(j - 1) != '.' && p.charAt(j - 1) != s.charAt(i), then b* is counted as empty. M[i][j] = M[i][j - 2]
        #       #####a(i)
        #       ####b*(j)
        #    2.if p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i):
        #       ######a(i)
        #       ####.*(j)
		#
		# 	  	 #####a(i)
        #    	 ###a*(j)
        #      2.1 if p.charAt(j - 1) is counted as empty, then M[i][j] = M[i][j - 2]
        #      2.2 if counted as one, then M[i][j] = M[i - 1][j - 2]
        #      2.3 if counted as multiple, then M[i][j] = M[i - 1][j]

		# recap:
		# M[i][j] = M[i - 1][j - 1]
		# M[i][j] = M[i - 1][j - 1]
		# M[i][j] = M[i][j - 2]
		# M[i][j] = M[i][j - 2]
        # M[i][j] = M[i - 1][j - 2]
        # M[i][j] = M[i - 1][j]
		# Observation: from above, we can see to get M[i][j], we need to know previous elements in M, i.e. we need to compute them first.
		# which determines i goes from 1 to m - 1, j goes from 1 to n + 1
        for i in range(1, plen + 1):
            for j in range(1, slen + 1):
                pattern_char = p[i-1]
                str_char = s[j-1]
                if pattern_char == str_char or pattern_char == '.':
                    dp[i][j] = dp[i-1][j-1]
                elif pattern_char == '*':
                    prev_pattern_char = p[i-2]
                    if prev_pattern_char != '.' and prev_pattern_char != str_char:
                        dp[i][j] = dp[i-2][j]
                    else:
                        dp[i][j] = dp[i-2][j-1] or dp[i-2][j] or dp[i][j-1]

        return dp[plen][slen]


"""
Napisz program wypisujący wszystkie liczby od 0 do 100,
podzielne przez 3 lub podzielne przez 5. Wypisz także jak dużo
takich liczb wystąpiło w tym przedziale.

Liczby podzielne przez 3 lub 5:
0
3
5
...
96
99
100
W przedziale 0-100 jest 48 liczb podzielnych przez 3 lub 5
"""

# PEP8: https://peps.python.org/pep-0008/

ile = 0
for i in range(0, 101):
    if i % 3 == 0 or i % 5 == 0:
        ile += 1
        print(i)

print(f'W przedziale od 0-100 jest {ile} liczb podzielnych przez 3 lub 5')


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

from __future__ import absolute_import

from datetime import datetime

from box.account.model import Address
from box.ext import db
from box.product.model import Product

# 一次购买记录信息
class Order(db.Model):
    __tablename__ = 'order'

    # 钱包支付方式
    PAYED_CRASH = 'crash'

    # 微信支付方式
    PAYED_WECHAT = 'wechat'

    # todo 未付款状态?
    STATUS_PENDING = 0

    # # 账户付款 已付款状态
    # STATUS_PAID_BY_CRASH = 1
    # # 微信付款 已付款状态
    # STATUS_PAID_BY_WECHAT = 2

    # 已付款状态
    STATUS_PAYED = 1

    # 已发货状态
    STATUS_SHIPMENTS = 2

    # 取消订单
    STATUS_CANCEL = 3
    # 订单过期
    STATUS_EXPIRED = 4

    # 查询所有
    STATUS_ALL = 100

    id = db.Column(db.Integer, primary_key=True)

    # 哪个用户的订单
    user_id = db.Column(db.Integer, nullable=False)

    # # 箱子订单的初始化地址信息ID
    address_id = db.Column(db.Integer, nullable=False)

    # 用户姓名
    username = db.Column(db.String(32), nullable=False)

    # 手机
    mobile = db.Column(db.String(16), nullable=False)

    # 邮寄地址 初始化时通过 用户传过来的地址id进行填充
    address = db.Column(db.String(128), nullable=False)

    # 付款记录ID
    payment_id = db.Column(db.Integer, nullable=True)

    # 箱子的数目
    box_num = db.Column(db.Integer, nullable=False)

    # 纸箱费用 不懂就看微信公众号怎么下单的 看付费细节
    product_fee = db.Column(db.Integer, nullable=False)
    # 邮寄费用 好像还没用，下单的时候邮寄费用默认为0
    express_fee = db.Column(db.Integer, nullable=False)

    # 物流编号
    logistics_no = db.Column(db.String(128), default='')

    # todo 这个字段没有被使用过，不明白含义
    expire_at = db.Column(db.DateTime, default=None)

    # 订单当前的付款状态
    status = db.Column(db.Integer, index=True, default=STATUS_PENDING)

    # 付款方式
    payment_method = db.Column(db.String(32), default='')

    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow,
                           onupdate=datetime.utcnow)

    @classmethod
    def create(cls, user_id, address_id, product_fee, express_fee, box_num=1):
        obj = cls(user_id=user_id, address_id=address_id,
                  product_fee=product_fee, express_fee=express_fee, box_num=box_num)

        # 这里查询地址信息进行初始化
        address = Address.get(address_id)
        obj.address = address.province + address.city + address.location

        # 用户名
        obj.username = address.contact_name

        # 手机
        obj.mobile = address.contact_phone

        obj.save()
        return obj

    def save(self):
        """Proxy method of saving object to database"""
        db.session.add(self)
        db.session.commit()

    @classmethod
    def delete(cls, order_id):
        order = cls.query.get(order_id)
        if order is None:
            return False, u'订单不存在'
        db.session.delete(order)
        db.session.commit()

        return True, u'success'

    # 通过付款记录获得订单信息
    @classmethod
    def get_by_payment_id(cls, payment_id):
        return cls.query.filter_by(payment_id=payment_id).first()

    # 获得每个箱子的信息
    def get_items(self):
        return OrderItem.get_multi_by_order_id(self.id)

    # 根据不同的状态进行分页查询
    @classmethod
    def order_paginate(cls, page, status, size=10):
        query = cls.query

        # 判断是否需要进行分状态查询
        if hasattr(cls, 'status') and status != cls.STATUS_ALL:
            query = query.filter(cls.status == status)

        return query.paginate(page=page, per_page=size, error_out=False)

    # 获得列表信息
    @classmethod
    def get_order_list(cls, page, status, size=10):
        result_list = []

        item_list = cls.order_paginate(page, status, size=size).items
        if item_list is None:
            return result_list

        for item in item_list:
            box_item = list()
            result = {
                'id': item.id,
                'created_at': item.created_at.strftime('%Y-%m-%d %H:%I:%S'),
                'username': item.username,
                'mobile': item.mobile,
                'address': item.address,
                'box_num': item.box_num,
                'box_item': box_item,
                'status': item.status,
                'logistics_no': item.logistics_no,
            }
            box_item_list = OrderItem.get_multi_by_order_id(item.id)
            for b_item in box_item_list:
                box_item.append(b_item.item_id)

            result_list.append(result)
        return result_list

    # 查询订单数目
    @classmethod
    def get_order_num(cls, status):
        # 查询全部
        if status == cls.STATUS_ALL:
            return cls.query.count()

        return cls.query.filter_by(status=status).count()

    # 修改物流
    @classmethod
    def update_logistics(cls, order_id, logistics_no):

        if order_id is None or logistics_no is None:
            return False, u'参数错误: order_id = {} logistics_no = {}'.format(order_id, logistics_no)

        order = cls.query.get(order_id)
        if order is None:
            return False, u'订单不存在!'

        # 判断订单状态是否正确
        if order.status not in (cls.STATUS_PAYED, cls.STATUS_SHIPMENTS):
            return False, u'订单状态错误，无法修改物流信息: status = {}'.format(order.status)

        order.logistics_no = logistics_no
        order.save()
        return True, u'success'

    # 编辑订单
    @classmethod
    def update_user_info(cls, order_id, username, mobile, address):
        if order_id is None:
            return False, u'订单号错误: order_id = {}'.format(order_id)

        order = cls.query.get(order_id)
        if order is None:
            return False, u'订单不存在!'

        if username is not None:
            order.username = username
        if mobile is not None:
            order.mobile = mobile
        if address is not None:
            order.address = address

        order.save()
        return True, u'success'

    def as_resp(self):
        items = self.get_items()
        return {
            'id': self.id,
            'express_fee': self.express_fee,
            'product_fee': self.product_fee,
            'items': [each.as_resp() for each in items]
        }

# 一次购买记录中不同箱子的信息
class OrderItem(db.Model):
    __tablename__ = 'order_item'

    id = db.Column(db.Integer, primary_key=True)

    # 箱子的编号！！！ 根据时间和用户信息生成的
    item_id = db.Column(db.String(128), nullable=True)

    # 购买的用户
    user_id = db.Column(db.Integer, nullable=False)
    # 属于哪一种产品
    product_id = db.Column(db.Integer, nullable=False)
    # 属于哪一个订单的
    order_id = db.Column(db.Integer, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow,
                           onupdate=datetime.utcnow)

    @classmethod
    def create(cls, user_id, product_id, order_id):
        obj = cls(user_id=user_id, product_id=product_id, order_id=order_id)
        db.session.add(obj)
        db.session.commit()
        return obj

    @classmethod
    def get_multi_by_order_id(cls, order_id):
        return cls.query.filter_by(order_id=order_id).all()

    def as_resp(self):
        product = Product.get(self.product_id)
        return {
            'id': self.id,
            'item_id': self.item_id,
            'product': product.as_resp(),
        }


# -*- coding: utf-8 -*-
"""
Created on Tue Mar 10 12:16:12 2020

@author: Nikhil
"""

# creating a list with tuples

a = (1,2)
b = (2,3)
c = (3,4)

type(a)

dict1 = {1:a,2:b,3:c}
#      (or)
dict2 = {'a':a,'b':b,'c':c}

untitled3 creating dictionary with tuples.py


#!/usr/bin/env python
import rospy
from sensor_msgs.msg import CameraInfo

def callback(data):
    P = list(data.P);
    P[3] = P[3] * scale
    data.P = tuple(P);
    pub.publish(data)

if __name__ == '__main__':
    rospy.init_node('republish_camera_info', anonymous=True)
    pub = rospy.Publisher('camera_info_out', CameraInfo, queue_size=1)
    scale = rospy.get_param('~scale', 1.091664)
    rospy.Subscriber("camera_info_in", CameraInfo, callback)
    rospy.spin()


from django import forms
from django.contrib.admin.forms import AdminAuthenticationForm
from django.core.exceptions import ValidationError

class DateFilterForm(forms.Form):
    device_eui = forms.CharField(label='EUI', max_length = 50)
    datetime_ini = forms.DateTimeField(label='Data inicial')
    datetime_fin = forms.DateTimeField(label='Data final')

class WhiteTariffForm(forms.Form):
    # filtro relativo ao gráfico de consumo medido (gráfico 2)
    datetime_ref = forms.DateTimeField(label='Data')
    # filtro relativo à data inicial e à data final (navbar à esquerda)
    datetime_ini = forms.DateTimeField(label='Data inicial')
    datetime_fin = forms.DateTimeField(label='Data final')
    # filtro relativo à data inicial e à data final (campos ocultos)
    datetime_ini_hidden = forms.DateTimeField(label='Inicial')
    datetime_fin_hidden = forms.DateTimeField(label='Final')

class IcaroAdminAuthenticationForm(AdminAuthenticationForm):
    def confirm_login_allowed(self, user):
        # elimina a confirmação de is_staff rodando o mesmo código de AuthenticationForm
        if not user.is_active:
            raise ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

class NewUserForm(forms.Form):
    username = forms.CharField(label='username', max_length = 50)
    first_name = forms.CharField(label='first_name', max_length=50)
    last_name = forms.CharField(label='last_name', max_length=50)
    email = forms.CharField(label='email', max_length=50)


import pandas as pd
import numpy as np
from pathlib import Path
import os
from tqdm import tqdm

def cal_joint_angles(file=None, destination_path=None, encoder_type='CNN'):
    """
    Calculate the joint angles between body parts and returns a dataframe of distances
    for only one animal

    Expects to read h5 files. Doesn't work for csv files

    Parameters
    ----------
    file: the path to file with the tracked points.
    destination_path: the path to save tracked points.
    encoder_type: either SAE, VAE or ANT
    """

    destination_name = Path(file).stem
    destination_name = destination_name[:destination_name.find(encoder_type)]

    name = 'animal_1'
    if destination_path is None:
        destination_path = str(Path(file).parent)
        destination_file = f"{destination_path}/{destination_name}{name}_joint_angles.h5"
    else:
        destination_file = f"{destination_path}/{destination_name}{name}_joint_angles.h5"

    if os.path.exists(destination_file):
        return

    print(file)
    # Read file
    with pd.HDFStore(file) as df:
        animal_key = df.keys()[0][1:]
        h5 = df[animal_key]

    # Get scorer
    scorer = h5.columns.get_level_values('scorer').unique().item()

    # Get list of individuals
    individuals = h5.columns.get_level_values('individuals').unique()

    center = 'midBody'

    vector1_bodyparts = ['Nose', 'midHip']

    vector2_bodyparts = ['leftEar', 'betweenEars', 'rightEar', 'rightMidWaist',
                         'leftMidWaist', 'leftHip', 'rightHip', 'tailStart']

    animals_angles = pd.DataFrame()
    for it, ind in enumerate(individuals):

        ind_h5 = h5[scorer][ind]

        for vec1 in vector1_bodyparts:
            vector1 = ind_h5[center].sub(ind_h5[vec1])
            vector1 = vector1 / np.linalg.norm(vector1, axis=1)[:, np.newaxis]
            for vec2 in vector2_bodyparts:
                vector2 = ind_h5[center].sub(ind_h5[vec2])
                vector2 = vector2 / np.linalg.norm(vector2, axis=1)[:, np.newaxis]
                angle_data = np.zeros((vector2.shape[0], 1))
                for t in tqdm(range(vector2.shape[0])):
                    v1 = vector1.iloc[t]
                    v2 = vector2.iloc[t]
                    angle = np.arccos(np.dot(v1, v2)) * 180 / np.pi
                    angle_data[t] = angle
                animals_angles[f'{vec1}_{vec2}'] = angle_data.flatten()

        name = f'animal_{it + 1}'
        if destination_path is None:
            destination_path = file.rsplit('/', 1)[0]
            destination_file = f"{destination_path}/{destination_name}{name}_joint_angles.h5"
        else:
            destination_file = f"{destination_path}/{destination_name}{name}_joint_angles.h5"

        print(destination_file)
        animals_angles.fillna(method='bfill', inplace=True)
        animals_angles.to_hdf(destination_file, animal_key)

    return animals_angles


#  -*- mode: python; coding: utf-8; -*-
#
#    Contributors: Asier Aguirre
#
#    All rights reserved. Use of this source code is governed by a
#    BSD-style license that can be found in the LICENSE.txt file.

class Coord:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def rel(self, c):
        self.x += float(c[0])
        self.y += float(c[1])

    def abs(self, c):
        self.x = float(c[0])
        self.y = float(c[1])

class SvgPath:

    def __init__(self):
        self.out = ''
        self.xscale = self.yscale = 1.0
        self.xtrans = self.ytrans = 0.0

    def setXScale(self, v):
        self.xscale = v

    def setYScale(self, v):
        self.yscale = v

    def setXTranslate(self, v):
        self.xtrans = v

    def setYTranslate(self, v):
        self.ytrans = v

    def transform(self, x, y):
        return ((x + self.xtrans) * self.xscale, (y + self.ytrans) * self.yscale)

    def coordDump(self, coord, rel, pair):
        if rel:
            return '%.3f, %.3f' % self.transform(coord.x + float(pair[0]), coord.y + float(pair[1]))
        else:
            return '%.3f, %.3f' % self.transform(float(pair[0]), float(pair[1]))

    def dump(self, command, coord, rel, values):
        if not self.out:
            self.out += 'beginPath()'
        self.out += ',\n'
        self.out += command + '('
        self.out += ', '.join([self.coordDump(coord, rel, pair) for pair in zip(values[0::2], values[1::2])])
        self.out += ')'
        if values:
            if rel:
                coord.rel(values[-2:])
            else:
                coord.abs(values[-2:])
        return coord

    def add(self, path):
        path = path.replace(',', ' ')
        cs = path.split() # commands
        coord = Coord(0, 0)
        command = 'error'
        rel = True

        i = 0
        while i < len(cs):
            c = cs[i]
            if c == 'm' or c == 'M':
                rel = c.islower()
                command = c == 'm' and 'l' or 'L'
                coord = self.dump('moveto', coord, rel, cs[i + 1 : i + 3])
                i += 2
            elif c == 'l' or c == 'L':
                rel = c.islower()
                command = c
                coord = self.dump('lineto', coord, rel, cs[i + 1 : i + 3])
                i += 2
            elif c == 'c' or c == 'C':
                rel = c.islower()
                command = c
                coord = self.dump('bezierto', coord, rel, cs[i + 1 : i + 7])
                i += 6
            elif c == 'z' or c == 'Z':
                rel = c.islower()
                command = 'error'
                self.dump('closePath', coord, rel, [])
            else:
                assert False, 'unhandled command: ' + str(c)

            i += 1
            if i < len(cs) and not cs[i].isalpha():
                assert command != 'error', 'no command for values'
                i -= 1
                cs[i] = command

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print(sys.argv[0], '<svg path> <scale X> <scale Y> <translate X> <translate Y>')
    else:
        svg = SvgPath()
        if len(sys.argv) > 2: svg.setXScale(float(sys.argv[2]))
        if len(sys.argv) > 3: svg.setYScale(float(sys.argv[3]))
        if len(sys.argv) > 4: svg.setXTranslate(float(sys.argv[4]))
        if len(sys.argv) > 5: svg.setYTranslate(float(sys.argv[5]))
        svg.add(sys.argv[1])
        print(svg.out)


import logging
import os
from typing import Optional

from cookiecutter.main import cookiecutter

import seedfarmer.errors
from seedfarmer import config

_logger: logging.Logger = logging.getLogger(__name__)

def create_module_dir(
    module_name: str, group_name: Optional[str], module_type: Optional[str], template_url: Optional[str]
) -> None:
    """Initializes a directory for a new module.

    Creates a new directory that contains files that will aid in setting up a development environment

    Parameters
    ----------
    group_name : Optional[str],
        Nmae of the group where the module will reside. If group is a nested dir, use `/` as a delimiter
    module_name : str
        Name of the module. The initialization will include project files pulled from the template_url
    module_type: Optional[str]
        They type of code the module deploys with, adding more boilerplate code
        -- only cdkv2 is supported here
    template_url : Optional[List[str]]
        A URL, for example a Github repo, that is or contains templating for the initialization
    """
    module_root = os.path.join(config.OPS_ROOT, "modules")
    module_path = os.path.join(module_root, module_name)
    output_dir = module_root

    if group_name:
        module_path = os.path.join(module_root, group_name, module_name)
        output_dir = os.path.join(module_root, group_name)

        if not os.path.exists(output_dir):
            _logger.info("Creating group dir: %s", output_dir)
            os.makedirs(output_dir)

    if os.path.exists(module_path):
        raise seedfarmer.errors.InvalidPathError(f"The module {module_name} already exists under {output_dir}.")

    if template_url == "https://github.com/awslabs/seed-farmer.git":
        checkout_branch = "init-module-cdkv2" if module_type == "cdkv2" else "init-module"

    _logger.info("New module will be created in the following dir: %s", output_dir)
    cookiecutter(
        template=template_url,
        checkout=checkout_branch,
        no_input=True,
        extra_context={"project_name": module_name, "module_name": module_name},
        output_dir=output_dir,
    )

def create_project(template_url: Optional[str]) -> None:
    """Initializes a new project directory.

    Creates a new directory that contains files that will aid in setting up a development environment

    Parameters
    ----------
    project_name : str
        Name of the project. The initialization will include project files pulled from the template_url
    template_url : Optional[List[str]]
        A URL, for example a Github repo, that is or contains templating for the initialization
    """

    checkout_branch = "init-project" if template_url == "https://github.com/awslabs/seed-farmer.git" else None
    _logger.info(" New project will be created in the following dir: %s", os.path.join(config.OPS_ROOT, config.PROJECT))
    cookiecutter(
        template=template_url,
        checkout=checkout_branch,
        no_input=True,
        extra_context={"project_name": config.PROJECT},
        output_dir=config.OPS_ROOT,
    )
    os.replace(
        os.path.join(config.OPS_ROOT, config.CONFIG_FILE),
        os.path.join(config.OPS_ROOT, config.PROJECT, config.CONFIG_FILE),
    )


import pandas as pd
import csv

## If you want to render an actual CSV
csv_file = 'crisis.csv'

## Edit sharing positions to anyone can view for access without OAuth
## Give the SheetID for the spreadsheet
googleSheetID = '1z5nVHhYdW_GGspZUPWNtXzZsz5_YIvS3eh3SaexlO0s'
## Choose a specific sheet from the spreadsheet
## This is the number after the edit#gid=
worksheetName = '300334505'

class Organization:
    """
    This class cleans up the information found in a physical CSV file.
    """
    def __init__(self, name, contact, email, phone, address, website, state,
                 crisis, counseling, peer, health, addiction, homelessness,
                 advocacy, medication, other, notes, etc):
        self.name = name
        self.contact = contact
        self.email = email
        self.phone = phone
        self.address = address
        self.website = website
        self.state = state
        self.crisis = crisis
        self.counseling = counseling
        self.peer = peer
        self.health = health
        self.addiction = addiction
        self.homelessness = homelessness
        self.advocacy = advocacy
        self.medication = medication
        self.other = other
        self.notes = notes
        self.etc = etc

    def to_dict(self):
        return {
            'name': self.name,
            'contact': self.contact,
            'email': self.email,
            'phone': self.phone,
            'address': self.address,
            'website': self.website,
            'state': self.state,
            'crisis': self.crisis,
            'counseling': self.counseling,
            'peer': self.peer,
            'health': self.health,
            'addiction': self.addiction,
            'homelessness': self.homelessness,
            'advocacy': self.advocacy,
            'medication': self.medication,
            'other': self.other,
            'notes': self.notes,
            'etc': self.etc,
            }

def csv_approach(csv_file):
    """
    Reads and processes a CSV, giving them appropriate names.

    Parameters
    ----------
    csv_file : str
        The path to the input CSV file.

    Returns
    -------
    df : pd.DataFrame
        A pandas dataframe.
    """
    orglist=[]
    with open(csv_file) as f:
        reader = csv.reader(f)
        next(reader, None)
        for a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r in reader:
            orglist.append(Organization(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r))

    df = pd.DataFrame.from_records([s.to_dict() for s in orglist])
    return df

def read_from_sheets(googleSheetID, worksheetName):
    """
    This function is based on the code at:
    https://kanoki.org/2018/12/25/read-google-spreadsheet-data-into-pandas-dataframe/

    It uses pandas to read a CSV from a public Google Sheet.

    Parameters
    ----------
    googleSheetID : str
        The specific ID of the Google Sheet link.
    worksheetName : str
        The GID for the specific sheet of the Google Sheet.

    Returns
    -------
    df : pd.DataFrame
        A pandas dataframe.
    """

    ## Export the Sheet as a CSV for Reading
    URL = 'https://docs.google.com/spreadsheets/d/{0}/export?format=csv&gid{1}'.format(
        googleSheetID,
        worksheetName
    )

    ## Read in the Google Sheet
    df = pd.read_csv(URL)
    return df

def setup_HTML():
    """
    Based on: https://stackoverflow.com/questions/50807744/apply-css-class-to-pandas-dataframe-using-to-html
    Set up the minimum HTML required for a JS DataTable in an iFrame,
    including jQuery. Add the Font Awesome CDN and oSTEM Favicon source.
    With Python, you need to double the braces for the correct rendering of
    javascript functions and CSS.

    {fa_key} : The font-awesome key (if there is one)
    {table} : the output of to_html

    Returns
    -------
    html_string : string
        A string of the relevant HTML elements needed to generate a standalone
        DataTables that works in an iFrame.
    """

    html_string = '''

     <link rel="shortcut icon" href='https://clubrunner.blob.core.windows.net/00000305556/Favicon/favicon.ico?time=637407227082223373' />
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">

      <link href="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css">

    <title class="hidden">Crisis Resource Table</title>

 {fa_key}

        {table}

    '''
    return html_string

def update_colnames(df):
    """
    Replace the Spreadsheet column names with shorter names based on their
    known order.

    Parameters
    ----------
    df : pd.DataFrame
        A pandas dataframe containing the spreadsheet data.

    Returns
    -------
    df : pd.DataFrame
        The cleaned pandas dataframe.
    """

    ## Get list of column names
    current_col_names = df.columns.tolist()

    ## Decide new column names
    new_col_names = ['name','contact', 'email', 'phone', 'address', 'website',\
     'state', 'crisis', 'counseling', 'peer', 'health', 'addiction', \
     'homelessness','advocacy', 'medication', 'other', 'notes', 'etc']

    ## Rename the columns
    df = df.rename(columns=dict(zip(current_col_names, new_col_names)))

    return df

def write_html(filename, html_string, df, fa_key=""):
    """
    Save the dataframe as an HTML table with customized style. In this case,
    "display" is a data.tables default with striped rows.
    You don't need table_id, but it might be helpful for other iFrame approaches.
    """

    with open(filename, 'w') as f:
        f.write(html_string.format(table=df.to_html(index=False, \
         classes='display', escape=False, table_id="CRtable", na_rep=''),
         fa_key=fa_key))
        f.close()

def symbol_key(df):
    """
    Replace the current form categories with shorter, normal symbols.

    Replacements
    ------------
    Accessible physical location [wheelchair and mobility aid accessible]: APL
    Age specific limitations: Age
    Firm costs: $
    Free: Free
    LGBTQ Competent: LGBTQ
    Member only: MO
    No insurance required: NI
    Other: ???
    Remote/Online access: OTI
    Sliding Scale: SS

    Parameters
    ----------
    df: pd.DataFrame
        A pandas dataframe containing the cleaned spreadsheet data.
    Returns
    -------
    sym_key : str
        A string with the HTML required for a key of the symbols that are
        used instead of the original data.
    df : pd.DataFrame
        The cleaned pandas dataframe after string replacement.
    """

    ## Deal with categories
    form_categories = [
     'Accessible physical location [wheelchair and mobility aid accessible]', \
     'Age specific limitations', 'Firm costs', 'Free', 'LGBTQ Competent', \
     'Member only', 'No insurance required', 'Other', 'Remote/Online access', \
     'Sliding Scale'
     ]

    ## Key of categories replaced with Font Awesome
    ## DO NOT include escapes for brackets -- \[ -- for Python here!
    sym_key = '''

Accessible physical location [wheelchair and mobility aid accessible]: APL

Age specific limitations: Age

Firm costs: $

Free: Free

LGBTQ Competent: LGBTQ

Member only: MO

No insurance required: NI

Other: ???

Remote/Online access: OTI

Sliding Scale: SS

     '''

    ## Columns to replace values in
    c2r = ['crisis', 'counseling', 'peer', 'health', 'addiction', \
     'homelessness', 'advocacy', 'medication', 'other']

    for i in range(len(c2r)):
        df[c2r[i]] = df[c2r[i]].replace('Accessible physical location \[wheelchair and mobility aid accessible\]', 'APL', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Age specific limitations', 'Age', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Firm costs', '\$', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Free', 'Free', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('LGBTQ Competent', 'LGBTQ', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Member only', 'MO', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('No insurance required', 'NI', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Other', '???', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Remote/Online access', 'OTI', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Sliding Scale', 'SS', regex=True)
        df[c2r[i]] = df[c2r[i]].replace(',', ' ', regex=True)

    ## Replace newlines with HTML breaks
    df = df.replace({'\n': '
'}, regex=True)

    return sym_key, df

def awesomeify(df):
    """
    Add in font awesome capability if you so choose.

    Replacements
    ------------
    Accessible physical location [wheelchair and mobility aid accessible]: fab fa-accessible-icon
    Age specific limitations: fas fa-child
    Firm costs: fas fa-comment-dollar
    Free: fas fa-money-bill-wave
    LGBTQ Competent: fas fa-rainbow
    Member only: fas fa-lock
    No insurance required: fas fa-notes-medical
    Other: far fa-plus-square
    Remote/Online access: fas fa-globe
    Sliding Scale: fas fa-balance-scale

    Parameters
    ----------
    df: pd.DataFrame
        A pandas dataframe containing the cleaned spreadsheet data.

    Returns
    -------
    fa_key : str
        A string with the HTML required for a key of the Font Awesome symbols
        that are used instead of the original data.
    df : pd.DataFrame
        The cleaned pandas dataframe after string replacement.
    """

    ## Deal with categories
    form_categories = [
     'Accessible physical location [wheelchair and mobility aid accessible]', \
     'Age specific limitations', 'Firm costs', 'Free', 'LGBTQ Competent', \
     'Member only', 'No insurance required', 'Other', 'Remote/Online access', \
     'Sliding Scale'
     ]

    ## Key of categories replaced with Font Awesome
    ## DO NOT include escapes for brackets -- \[ -- for Python here!
    fa_key = '''

Accessible physical location [wheelchair and mobility aid accessible]:

Age specific limitations:

Firm costs:

Free:

LGBTQ Competent:

Member only:

No insurance required:

Other:

Remote/Online access:

Sliding Scale:

     '''

    ## Columns to replace values in
    c2r = ['crisis', 'counseling', 'peer', 'health', 'addiction',  \
     'homelessness', 'advocacy', 'medication', 'other']

    for i in range(len(c2r)):
        df[c2r[i]] = df[c2r[i]].replace('Accessible physical location [wheelchair and mobility aid accessible]', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Age specific limitations', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Firm costs', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Free', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('LGBTQ Competent', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Member only', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('No insurance required', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Other', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Remote/Online access', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace('Sliding Scale', '', regex=True)
        df[c2r[i]] = df[c2r[i]].replace(',', ' ', regex=True)

    ## Replace newlines with HTML breaks
    df = df.replace({'\n': '
'}, regex=True)

    return fa_key, df

### Actual Run Code
if __name__ == "__main__":
    ## Render the HTML string
    html_string = setup_HTML()

    ## CSV approach
    csv_df = csv_approach(csv_file)
    ## Write a version based on CSV
    write_html('docs/CRDT-csv.html', html_string, csv_df)

    ## Google sheets approach
    gs_df = read_from_sheets(googleSheetID, worksheetName)
    gs_df = update_colnames(gs_df)
    ## Write a copy after cleaning the column names
    write_html('docs/CRDT-sheets.html', html_string, gs_df)

    ## Google sheets + Normal Symbols
    sym_gs_df = read_from_sheets(googleSheetID, worksheetName)
    sym_gs_df = update_colnames(sym_gs_df)
    sym_key, sym_gs_df = symbol_key(sym_gs_df)
    write_html('docs/CRDT-sheets-NFA.html', html_string, sym_gs_df, sym_key)

    ## Google sheets + Font Awesome
    fa_gs_df = read_from_sheets(googleSheetID, worksheetName)
    fa_gs_df = update_colnames(fa_gs_df)
    fa_key, fa_gs_df = awesomeify(gs_df)
    ## Write a copy after the Font Awesome substitutions
    write_html('docs/CRDT-sheets-FA.html', html_string, fa_gs_df, fa_key)


def find():
    for k in range(0,len(arr)):
        time=size-k
        temp=0
        for item in arr:
            if item>time:
                temp+=1
        if temp==time:
            return temp
if __name__ == '__main__':
    arr = eval(input())
    size = len(arr)
    print(find())


import scrapy
import re

class CathoJobSpider(scrapy.Spider):
    name = "geekhunter"

    def start_requests(self):
        urls = [
            "https://www.geekhunter.com.br/vagas",
        ]

        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = 1
        for job in response.css("ul li article article div div h2"):

            yield {
                "url": job.css("a::attr(href)").get(),
                "title": job.css("a::text").get(),
                "job_id": int(re.findall(r"\d+", job.css("a::attr(href)").get())[0]),
            }
            page += 1
            next_page = "&page={}".format(page)

            response.urljoin(next_page)
            yield response.follow(next_page, callback=self.parse)
            # next_page = response.urljoin(next_page)
            # print("PAgina: {page}")
            # yield scrapy.Request(next_page, callback=self.parse)


def moveTo(position, fast=True):
    if (hero.isReady("jump") and hero.distanceTo > 10 and fast):
        hero.jumpTo(position)
    else:
        hero.move(position)

# pickup coin
def pickUpNearestItem(items):
    nearestItem = hero.findNearest(items)
    if nearestItem:
        moveTo(nearestItem.pos)

# add soldier
summonTypes = ['griffin-rider', 'soldier', 'archer']

def summonTroops():
    type = summonTypes[len(hero.built) % len(summonTypes)]
    if hero.gold > hero.costOf(type):
        hero.summon(type)

def findNearest(index):
    top = False
    left = False
    if (index == 0):
        top = True
        left = True
    elif (index == 1):
        top = True
    elif (index == 3):
        left = True
    items = hero.findItems()
    for item in items:
        if (item.pos.y > 66 and top and left and item.pos.x < 76):
            return item
        elif (item.pos.y < 66 and not top and left and item.pos.x < 76):
            return item
        elif (item.pos.y > 66 and top and not left and item.pos.x > 76):
            return item
        elif (item.pos.y < 66 and not top and not left and item.pos.x > 76):
            return item
    return None

# commands attack
def commandTroops():
    index = 0
    for friend in hero.findFriends():
        if friend.type == 'peasant':
            item = findNearest(index)
            index += 1
            if item:
                hero.command(friend, 'move', item.pos)
        else:
            enemy = hero.findNearestEnemy()
            if enemy:
                hero.command(friend, "attack", enemy)

def attack(target):
    if target:
        if (hero.distanceTo(target) > 10):
            moveTo(enemy.pos)
        elif (hero.isReady("bash")):
            hero.bash(enemy)
        elif (hero.isReady("power-up")):
            hero.powerUp()
            hero.attack(enemy)
        elif (hero.isReady("cleave")):
            hero.cleave(enemy)
        else:
            hero.attack(enemy)

while True:
    summonTroops()
    commandTroops()
    enemy = hero.findNearestEnemy()
    attack(enemy)


import requests, re, pprint, json
import numpy as np
from bs4 import BeautifulSoup

with open("ZCL.html") as zip_code:
    zip_code_dat = BeautifulSoup(zip_code, "html.parser") #opens static file
    zip_code_dat_parsed = zip_code_dat.find_all(class_="inner_table")[0] #pulls table with zipcodes
    zip_code_dat_parsed = zip_code_dat_parsed.find_all("td")[5:] #finds tr (table row) tags. ignores first 5 b/c they hold useless info.
    zip_code_txt = [c.text for c in zip_code_dat_parsed] #turns trs into text
    #print(len(zip_code_txt))
    zip_code_txt = [zip_code_txt[x:x+4] for x in range(0, len(zip_code_txt), 4)] #creates a list of lists. each list is split in to [zip code, city, county, random text]
    #print(zip_code_txt)
    #print(zip_code_text_list)
    city_to_county = {}
    counrty_to_city = {}
    for line in zip_code_txt: #iterates thru list
        #print(line)
        city = line[1]
        county = line[2]
        #print(city)
        #print(county)
        #print(city, county)

    #there's two dictionaries being created here. one is for use in another folder (city_to_county), the other is to check for cities that
    #exist in 2+ counties. this is to deal with a double-counting error in 'Opioid_parser.py'

        if county not in city_to_county: #if not in dictionary, add to dictionary
            city_to_county[county] = []
            city_to_county[county].append(city)
        else: #if already in dictionary, append
            if city not in city_to_county[county]:
                city_to_county[county].append(city)

        if city not in counrty_to_city: #if not in dictionary, add to dictionary
            counrty_to_city[city] = []
            counrty_to_city[city].append(county)
        else: #if already in dictionary, append
            if county not in counrty_to_city[city]:
                counrty_to_city[city].append(county)
    #pprint.pprint(city_to_county)
    #pprint.pprint(counrty_to_city)
    json.dump(city_to_county, open("zip_codes.json", "w")) #write to json file