#!/usr/bin/env python
# This package
from robot_control.abstract_vehicle import AVehicle
# ROS packages
import rclpy
from rclpy.action import ActionServer, CancelResponse, ActionClient
from rclpy.time import Time
from rclpy.duration import Duration
from tf2_ros.transform_listener import TransformListener
from tf2_ros.buffer import Buffer
# ROS messages
from robot_control_interfaces.action import ArmTakeoff, Land
import numpy as np

class ADrone(AVehicle):
    def __init__(self, instance=0):
        super().__init__(instance=instance)

        # Actions
        self._server_arm_takeoff = ActionServer(self, ArmTakeoff, "arm_takeoff", self._handle_arm_takeoff_goal,
            cancel_callback=self._handle_arm_takeoff_cancel)
        self._server_land = ActionServer(self, Land, "land", self._handle_land_goal,
            cancel_callback=self._handle_land_cancel)
        self.get_logger().debug("ADrone initialized")

    def takeoff(self, alt: float):
        """Takes vehicle off from current location.

        Args:
            alt (float): altitude in meters

        Returns:
            bool: Flag indicating command was sent
        """
        raise NotImplementedError

    def land(self):
        """Lands vehicle at current location.

        Returns:
            bool: Flag indicating command was sent
        """
        raise NotImplementedError

    def is_landed(self):
        """Returns if vehicle has landed.

        Returns:
            bool: Whether the vehicle is landed
        """
        raise NotImplementedError

    #######################
    ## Actions
    #######################
    def _precheck_go_waypoint_goal(self):
        if not self.is_armed():
            self.get_logger().warn("GoWaypoint: aborted not armed")
            return False
        if self.is_landed():
            self.get_logger().warn("GoWaypoint: aborted not taken off")
            return False
        return True

    def _handle_arm_takeoff_goal(self, goal):
        """Action callback for arming and taking off vehicle.
        """
        self.get_logger().debug("ArmTakeoff: arming")
        self.arm()
        self.get_logger().debug(f"ArmTakeoff: sending {goal.request.altitude} m")
        if not self.takeoff(goal.request.altitude):
            self.get_logger().error("ArmTakeoff: could not send command")
            goal.abort()
            self._abort_arm_takeoff()
            return ArmTakeoff.Result()
        self.get_logger().debug("ArmTakeoff: waiting to reach altitude")
        feedback_msg = ArmTakeoff.Feedback()
        start_time = self.get_clock().now()
        init_position = self.position.copy()
        while True:
            distance = self.distance_to_target()
            reached = self.reached_target(distance=distance)
            if self.get_clock().now() - start_time > self._wait_moved and not self.has_moved(init_position):
                self.get_logger().error("ArmTakeoff: hasn't moved aborting")
                self.disarm()
                self._abort_arm_takeoff()
                goal.abort()
                return ArmTakeoff.Result()
            if distance is not None: #publish distance to target
                feedback_msg.distance = float(distance)
                goal.publish_feedback(feedback_msg)
            if goal.is_cancel_requested:
                self.land()
                self.get_logger().info(f'ArmTakeoff: cancelling...')
                while not self.is_landed():
                    continue
                self.disarm()
                self.get_logger().info(f'ArmTakeoff: cancelled!')
                goal.canceled() #handle cancel action
                self._abort_arm_takeoff()
                return ArmTakeoff.Result()
            if reached:
                self.get_logger().info("ArmTakeoff: reached destination")
                self._success_arm_takeoff()
                goal.succeed() #handle sucess
                return ArmTakeoff.Result()
            self._check_rate.sleep()

    def _handle_arm_takeoff_cancel(self, cancel):
        """Callback for cancelling arm_takeoff action. Must be used with ActionServer.
        """
        return CancelResponse.ACCEPT

    # FIXME: not necessary once landed state is fixed
    def _success_arm_takeoff(self):
        """Method that is ran after successful arm takeoff."""
        pass

    def _abort_arm_takeoff(self):
        """Method that is ran after failed arm takeoff."""
        pass

    def _handle_land_goal(self, goal):
        """Action callback to land vehicle.
        """
        self.get_logger().debug("Land: sent command")
        if not self.land():
            self.get_logger().error("Land: could not send command")
            goal.abort()
            return Land.Result()
        self.get_logger().debug("Land: waiting")
        start_time = self.get_clock().now()
        init_position = self.position.copy()
        while True:
            if self.get_clock().now() - start_time > self._wait_moved and not self.has_moved(init_position):
                self.get_logger().error("Land: hasn't moved aborting")
                goal.abort()
                return Land.Result()
            if goal.is_cancel_requested:
                self.get_logger().info('Land: cancelling...')
                self.halt()
                self.get_logger().info('Land: canceled!')
                goal.canceled()
                return Land.Result()
            if self.is_landed():
                if not self.disarm(): self.get_logger().warn("Land: could not disarm at end")
                self.get_logger().info("Land: success!")
                goal.succeed()
                return Land.Result()
            self._check_rate.sleep()

    def _handle_land_cancel(self, cancel):
        """Callback for cancelling land action. Must be used with ActionServer."""
        return CancelResponse.ACCEPT


import os.path
import sys
import math

import numpy

from Tool.CvTool import cv_imwrite

def CsvToPngRGBA( input_file ):
    filename, file_extension = os.path.splitext(input_file)
    output_file = filename + ".png"

    output_file = os.path.abspath(output_file)

    pixel_lines = []
    width = 0
    PIXEL_BYTE_COUNT = 1

    for line_index, l in enumerate(open(input_file)):
        line = l.replace("\n", "").strip()
        if line == "":
            continue

        if line_index == 0:
            #first line
            row_header = line.split(", ")
            width = (len(row_header)-1) // PIXEL_BYTE_COUNT
        else:
            # 加一行
            pixel_lines.append([None] * width)

            data_strs = line.split(", ")[1:]
            for row_index, float_strs in enumerate( (data_strs[i:i + PIXEL_BYTE_COUNT] for i in range(0, len(data_strs), PIXEL_BYTE_COUNT)) ):  # 列表生成式
                divs = (256.0**i for i in range(1, 1-4, -1))
                r_div, g_div, b_div, a_div = divs
                F32 = float(float_strs[0])
                remain = F32
                r = math.floor(remain / r_div )
                remain -= r * r_div
                g = math.floor(remain / g_div )
                remain -= g * g_div
                b = math.floor(remain / b_div )
                remain -= b * b_div
                a = math.floor(remain / a_div )
                remain -= a * a_div

                pixel_rgba = [b, g, r, a] # 颠倒的

                recover_F32 = r * r_div + g * g_div + b * b_div + a * a_div

                # pixel_rgba[3] = 255
                pixel_lines[-1][row_index] = tuple(pixel_rgba)
                # r, g, b, a = ( int(f"0x{v}",0) for v in rgba_strs )
                # print(f"{r},{g},{b},{a} | ", end="")

    # for i,v in enumerate(pixel_lines):
        # print(f"{i}\t{','.join((str(vv) for vv in v))}")

    img = numpy.array(pixel_lines)
    # print(img)
    # print("arr.shape", img.shape)
    # print("arr.dtype", img.dtype)

    cv_imwrite(output_file, img)

    print(f"Output: {output_file}")

if __name__ == "__main__":
    files = sys.argv[1:]
    # print(files)

    for i,v in enumerate(files):
        CsvToPngRGBA( v )


from functools import *
import math

def end(t,c):
  print('Case #' + str(t) + ': ', end='')
  print(c)

vowels = ['a', 'e', 'i', 'o', 'u']

def solve(name,n):
  subl = 0
  value = 0
  prevStart = -1
  ends = []
  for x in range(len(name)):
    if name[x] in vowels:
      subl = 0
    else:
      subl += 1
      if subl >= n:
        ends.append(x)
        start = x - n + 1
        pointsBefore = start - prevStart
        pointsAfter  = len(name) - x
        permsInside = pointsBefore * pointsAfter
        prevStart = start
        value += permsInside
  return value

testcases = int(input())
for tc in range(1, testcases + 1):
  name,n = [x for x in input().split()]
  n = int(n)
  prevStart = -1
  value = solve(name, n)
  end(tc,value)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.ticker as ticker

def plot_algebraic_problem_3D(expressions, domain=(0, 15), resolution=1, plot_intersection_only=False, save_fig=None,
                              hide_ticks=False, view_init=(30, -60)):

    """
    Plot approximations of (multiple) equations

    Args:
        expressions (list): A list of functions that take three arguments (x, y, z) and return a boolean value.
                          If you want to connect multiple conditions in one equation - use & instead of 'and' and
                          | instead of 'or'. This is needed, because x,y and z are going to be numpy matrices!
        domain (tuple): A tuple specifying a range [a,b] of the x, y, and z values to evaluate the functions on.
                        CAUTION: a and b have to be greater than 0!!!
        resolution (int): With the default resolution of 1 and a domain range of [a,b] (b-a)+1 values will be calculated
                          and plotted. If you want to have k times the amount, set resolution to k.
                          Example: If you specify a domain of (0,10) this method with resolution=1 would calculate
                          11 evenly spaced values for x, y and z. These values would be
                          [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].
                          With resolution=2 we would double the amount of evenly spaced calculated values
                          in the range [a,b].
        plot_intersection_only (bool): Whether to only plot the intersecting region. Otherwise, plot all inequalities.
        save_fig (str): If you want to save the generated plot, specify a path to the location where it should be saved
        hide_ticks (bool): If true, hide ticks on the axis.
        view_init (tuple): Tuple containing two numbers. Is used to set the viewing angle of a 3D plot in Matplotlib.
                           The first value of the tuple is the elev parameter which specifies the elevation angle
                           (i.e., the angle above the xy-plane) in degrees, while the second value specifies the
                           azimuth angle (i.e., the angle around the z-axis) in degrees.
    """

    # For the case that a user just wanted to plot one equation and forgot to put it into a list
    if not isinstance(expressions, list):
        expressions = [expressions]

    if domain[0] < 0 or domain[1] < 0:
        raise ValueError('The domain specifies a range [a,b] where a and b has to be greater than 0!'
                         + 'You have specified a domain with also negative value(s)')

    # Create a meshgrid that covers the specified domain.
    # The meshgrid is used to create a grid of points in the three-dimensional space that will be used to evaluate
    # the equations.
    x, y, z = np.meshgrid(
        np.linspace(domain[0], domain[1], resolution*((domain[1]-domain[0])+1)),
        np.linspace(domain[0], domain[1], resolution*((domain[1]-domain[0])+1)),
        np.linspace(domain[0], domain[1], resolution*((domain[1]-domain[0])+1)),
        indexing='ij'
    )

    colors = np.empty(x.shape, dtype=object)  # this matrix is going to say which equation will be which color
    possible_colors = mcolors.TABLEAU_COLORS  # We could specify other color palettes but these look alright
    # The list possible_colors_key is useful because I want to use the first color of the list for the first equation,
    # the second color for the second equation and so on
    possible_colors_keys = list(possible_colors.keys())
    if 'tab:red' in possible_colors:
        del possible_colors['tab:red']  # red should only be used for the intersection

    # iteratively the intersection matrix will get ones at the locations where several equations overlap
    intersection = np.ones_like(x)
    # iteratively we add the regions of the equations to the union matrix
    union = np.zeros_like(x)

    for i, func in enumerate(expressions):
        # func_result is a matrix containing the results for all the possible defined combinations of x, y and z
        func_result = func(x, y, z)

        # The matrix intersection is used to calculate the set of points that satisfy all equations.
        intersection = np.logical_and(intersection, func_result)

        # The matrix union is used to calculate the set of points that satisfy any of the equations .
        union = np.logical_or(union, func_result)

        # Let's color the equation with color number i
        colors[func_result] = possible_colors[possible_colors_keys[i]]

    # Now we color the intersection with the color red!
    colors[intersection] = 'tab:red'

    # Plotting stuff
    ax = plt.figure().add_subplot(projection='3d')
    ax.set_proj_type('ortho')

    if plot_intersection_only:
        ax.voxels(intersection, facecolors=colors)
    else:
        ax.voxels(union, facecolors=colors)

    ax.view_init(elev=view_init[0], azim=view_init[1])
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    ax.set_box_aspect((1, 1, 1))
    ax.set_xlim([0, union.shape[0]])
    ax.set_ylim([0, union.shape[1]])
    ax.set_zlim([0, union.shape[2]])

    if hide_ticks:
        ax.set_xticks([])
        ax.set_yticks([])
        ax.set_zticks([])
    else:
        ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x / resolution))
        ax.xaxis.set_major_formatter(ticks)
        ax.yaxis.set_major_formatter(ticks)
        ax.zaxis.set_major_formatter(ticks)

    if save_fig is not None:
        plt.savefig(save_fig)

    plt.show()


import csv
import datetime
import os
from cStringIO import StringIO

from reversion import revisions as reversion

from django.conf import settings
from django.contrib.admin import helpers
from django.db import transaction
from django.db.models.query import QuerySet
from django.forms.models import model_to_dict
from django.http import HttpResponse
from django.template import Context, Template
from django.template.response import TemplateResponse
from django.utils import timezone
from django.utils.translation import ugettext as _
from django.utils.encoding import force_text
from reportlab.lib.units import cm #, mm
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet

from medlemssys.innhenting import mod10
from medlemssys.giro.models import GiroTemplate
from medlemssys.medlem.models import Giro

import admin # reversion
from .forms import GiroForm
from .forms import SuggestedLokallagForm

@transaction.atomic
def members_meld_ut(modeladmin, request, queryset):
    today = timezone.now().date()
    with reversion.create_revision():
        reversion.set_comment("Meld ut medlemar")
        reversion.set_user(request.user)
        for m in queryset:
            if not m.utmeldt_dato:
                m.utmeldt_dato = today
            if not m.fornamn.lower().startswith('utmeld'):
                m.fornamn = u'UTMELD ' + m.fornamn
            m.save()
members_meld_ut.short_description = "Meld ut"

def simple_member_list(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'filename=medlemer.csv'

    year = datetime.date.today().year
    dc = csv.writer(response, quoting=csv.QUOTE_ALL)
    dc.writerow(["Namn",
                 u"Fødd".encode('utf-8'),
                 "Heimeadresse",
                 "Postadresse",
                 "Poststad",
                 "Mobiltelefon",
                 "Epost",
                 "Lokallag",
                 "Medlemsnummer",
                 "Giro %d" % (year-1),
                 "Betalt",
                 u"Beløp".encode('utf-8'),
                 "KID"])
    def get_giro(year):
        giro = m.gjeldande_giro(year)
        if giro:
            return (giro.innbetalt_belop, giro.belop, giro.kid)
        return ('-', '-', '')
    for m in queryset:
        innbetalt, belop, kid = get_giro(year)
        ifjor = get_giro(year-1)
        postadr, poststad = '', ''
        adr = m.full_postadresse(namn=False, as_list=True)
        if len(adr) == 1:
            poststad = adr[0]
        elif len(adr) > 1:
            postadr = ', '.join(adr[:-1])
            poststad = adr[-1]
        a = [m,
             m.fodt,
             m.full_adresse(namn=False),
             postadr,
             poststad,
             m.mobnr,
             m.epost,
             m.lokallag_display(),
             m.id,
             "%s/%s (%s)" % ifjor,
             innbetalt,
             belop,
             kid]
        dc.writerow([unicode(s).encode('utf-8') for s in a])
    return response
simple_member_list.short_description = "Enkel medlemsliste"

def csv_list(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'filename=dataliste.csv'

    dc = csv.writer(response)
    dc.writerow(model_to_dict(queryset[0]).keys())
    for m in queryset:
        row = []
        for k, v in model_to_dict(m).items():
            if isinstance(v, QuerySet):
                v = ', '.join(force_text(k) for k in v)
            row.append(unicode(v).encode('utf-8'))
        dc.writerow(row)
    return response
csv_list.short_description = "Full dataliste"

def giro_list(modeladmin, request, queryset):
    response = HttpResponse(content_type='text/csv; charset=utf-8')
    response['Content-Disposition'] = 'filename=giroar.csv'

    dc = csv.writer(response, quoting=csv.QUOTE_ALL)
    dc.writerow(["Namn",
                 "Heimeadresse",
                 "Postadresse",
                 "Poststad",
                 "Betalt",
                 "Dato",
                 "Lokallag",
                 u"Fødd".encode('utf-8'),
                 "Epost",
                 "Mobnr",
                 u"For år".encode('utf-8'),
                 "Korleis",
                 "KID",
                 u"Beløp".encode('utf-8'),
                 "Medlem-ID",
                 "Giro-ID",
                 ])
    for g in queryset:
        postadr, poststad = '', ''
        adr = g.medlem.full_postadresse(namn=False, as_list=True)
        if len(adr) == 1:
            poststad = adr[0]
        elif len(adr) > 1:
            postadr = ', '.join(adr[:-1])
            poststad = adr[-1]

        a = [g.medlem,
             g.medlem.full_adresse(namn=False),
             postadr,
             poststad,
             g.innbetalt_belop,
             g.innbetalt,
             g.medlem.lokallag_display(),
             g.medlem.fodt,
             g.medlem.epost,
             g.medlem.mobnr,
             g.gjeldande_aar,
             g.konto,
             g.kid,
             g.belop,
             g.medlem.id,
             g.pk]

        dc.writerow([unicode(s).encode('utf-8') for s in a])

    return response
giro_list.short_description = "Enkel giroliste"

@transaction.atomic
def pdf_giro(modeladmin, request, queryset):
    # User has already written some text, make PDF
    if request.POST.get('post'):
        pdfmetrics.registerFont(TTFont('OCRB', os.path.dirname(__file__) + '/../giro/OCRB.ttf'))
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'filename=girosending.pdf'

        buf = StringIO()

        # Create the PDF object, using the StringIO object as its "file."
        pdf = canvas.Canvas(buf)

        if not request.POST.get('ink-utmeld'):
            queryset = queryset.filter(medlem__utmeldt_dato__isnull=True)
        if not request.POST.get('ink-betalt'):
            queryset = queryset.exclude(innbetalt__isnull=False)

        for giro in queryset:
            m = giro.medlem
            if not giro:
                continue
            context = Context({
                'medlem': m,
                'giro': giro,
                'host': settings.DEFAULT_HOST,
                'email': settings.DEFAULT_EMAIL,
            })
            if request.POST.get('pdf_type') == 'medlemskort':
                pdf = _giro(pdf, request, context)
                pdf = _medlemskort(pdf, request, context)
            elif request.POST.get('pdf_type') == 'giro':
                pdf = _giro_info(pdf, request, context)
                pdf = _giro(pdf, request, context)
            else:
                pdf = _giro_faktura(pdf, request, context)
            pdf.showPage()
            if request.POST.get('merk-postlagt'):
                giro.status = 'M'
                giro.save()

        # Close the PDF object cleanly.
        pdf.save()

        # Get the value of the StringIO buffer and write it to the response.
        pdf = buf.getvalue()
        buf.close()
        response.write(pdf)
        return response

    opts = modeladmin.model._meta
    app_label = opts.app_label
    n_utmelde = queryset.filter(medlem__utmeldt_dato__isnull=False).count()
    n_betalte = queryset.filter(innbetalt__isnull=False).count()
    g_frist = datetime.date.today() + datetime.timedelta(30)
    try:
        template = GiroTemplate.objects.get(trigger="medlemspengar-pdf")
        suggested_title = template.subject
        suggested_text = template.html_template
    except GiroTemplate.DoesNotExist:
        suggested_title = ""
        suggested_text = ""

    title = _("Lag giro-PDF-ar ({c} giroar)".format(c=queryset.count()))

    context = {
        "title": title,
        "queryset": queryset,
        "opts": opts,
        "app_label": app_label,
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
        "n_utmelde": n_utmelde,
        "n_betalte": n_betalte,
        "g_frist": g_frist,
        "suggested_title": suggested_title,
        "suggested_text": suggested_text,
    }

    request.current_app = modeladmin.admin_site.name
    return TemplateResponse(request, 'admin/pdf_giro.html', context)
pdf_giro.short_description = "Lag giro-PDF"

def _pdf_p(pdf, text, x, y, size_w=None, size_h=None):
    if not size_w:
        size_w = 19
    if not size_h:
        size_h = size_w

    style = getSampleStyleSheet()['BodyText']
    p = Paragraph(text, style)
    used_w, used_h = p.wrap(size_w*cm, size_h*cm)
    p.wrapOn(pdf, size_w*cm, size_h*cm)
    p.drawOn(pdf, x*cm, y*cm - used_h)

def _giro_faktura(pdf, request, context):
    giro = context['giro']
    m = context['medlem']

    title = Template(request.POST.get('title')).render(context)
    pdf.setFont('Helvetica', 16)
    pdf.drawString(1.0*cm, 16*cm, u"%s" % title)

    pdf.setFontSize(11)
    text = request.POST.get('text')
    text_content = Template(text).render(context).replace('\n', '
')
    _pdf_p(pdf, text_content, 1, 15.5, size_w=19, size_h=13)
    _pdf_p(pdf, m.full_betalingsadresse().replace('\n', '
\n'), 1, 26, size_w=8, size_h=6)
    _pdf_p(pdf, u"""\
        Kundenr: {m.pk}

        Fakturanr: {g.pk}

        Fakturadato: {now}

        Organisasjonsnr: {orgnr}

        Betalingsfrist: {frist}

        Til konto: {kontonr}

        KID-nummer: {g.kid}

        Å betala: {g.belop},00

        """.format(m=m,
                   g=giro,
                   kontonr=settings.KONTONUMMER,
                   orgnr=settings.ORGNUMMER,
                   now=datetime.date.today(),
                   frist=request.POST.get('frist')),
        15, 26, size_w=4, size_h=6)
    return pdf

def _medlemskort(pdf, request, context):
    giro = context['giro']
    m = context['medlem']

    # Medlemskort
    pdf.setFont('Helvetica', 12)
    pdf.drawString(13.0*cm, 14.9*cm, u"%s" % unicode(m))

    pdf.setFont('OCRB', 11)

    pdf.drawString(13.8*cm, 14.3*cm, u"%s" % m.pk)
    pdf.drawString(18.1*cm, 14.3*cm, u"%s" % giro.gjeldande_aar)
    pdf.drawString(13.0*cm, 12.7*cm, u"%s" % giro.belop)
    pdf.drawString(14.8*cm, 12.7*cm, u"%s" % '00')
    return pdf

def _giro_info(pdf, request, context):
    title = Template(request.POST.get('title')).render(context)

    pdf.setFont('OCRB', 11)
    pdf.drawString(1.2*cm, 8.3*cm, u"%s" % title)

    tekst = pdf.beginText(11.4*cm, 5.5*cm)
    for adrdel in settings.ORG_ADR.split('\n'):
        tekst.textLine(adrdel.strip())
    pdf.drawText(tekst)

    return pdf

def _giro(pdf, request, context):
    giro = context['giro']
    m = context['medlem']
    title = Template(request.POST.get('title')).render(context)

    pdf.setFont('Helvetica', 16)
    pdf.drawString(1.0*cm, 26*cm, u"%s" % title)
    pdf.setFontSize(12)

    text_template = Template(request.POST.get('text'))
    text_content = text_template.render(context).replace('\n', '
')

    _pdf_p(pdf, text_content, 1, 25.5, size_w=18, size_h=13)

    pdf.setFont('OCRB', 11)
    # Giro
    tekst = pdf.beginText(1.9*cm, 6.0*cm)
    for adrdel in m.full_betalingsadresse().split('\n'):
        tekst.textLine(adrdel.strip())
    pdf.drawText(tekst)
    if giro.betalt() or (giro.hensikt == 'P' and m.har_betalt()):
        pdf.drawString(18*cm, 12.8*cm, "BETALT")
        pdf.setFillColorRGB(0, 0, 0)
        pdf.rect(0,  5.3*cm, 26*cm, 0.2*cm, stroke=False, fill=True)
        pdf.rect(0, 4.85*cm, 26*cm, 0.2*cm, stroke=False, fill=True)
        pdf.rect(0,  1.9*cm, 26*cm, 0.2*cm, stroke=False, fill=True)
        pdf.rect(0, 1.45*cm, 26*cm, 0.2*cm, stroke=False, fill=True)
    else:
        pdf.drawString(16.8*cm, 9.5*cm, u"%s" % request.POST.get('frist'))
        pdf.drawString(5.0*cm,  2.08*cm, u"%s" % giro.kid)
        pdf.drawString(8.5*cm,  2.08*cm, u"%s" % giro.belop)
        pdf.drawString(10.6*cm, 2.08*cm, u"%s" % '00')
        pdf.drawString(11.9*cm, 2.08*cm,
                       u"%s" % mod10.mod10(unicode(giro.belop) + '00'))
        pdf.drawString(13.2*cm, 2.08*cm, u"%s" % settings.KONTONUMMER)

    return pdf

@transaction.atomic
def lag_giroar(modeladmin, request, queryset):
    year = datetime.date.today().year
    form = GiroForm(request.POST if 'post' in request.POST else None,
                    initial={'belop':70})
    if not request.POST.get('post') or not form.is_valid():
        opts = modeladmin.model._meta
        app_label = opts.app_label
        n_utmelde = queryset.filter(utmeldt_dato__isnull=False).count()
        n_allereie_giro = queryset.filter(giroar__gjeldande_aar=year).count()

        title = _("Lag giroar")

        context = {
            "title": title,
            "queryset": queryset,
            "form": form,
            "opts": opts,
            "app_label": app_label,
            "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
            "n_utmelde": n_utmelde,
            "n_allereie_giro": n_allereie_giro,
        }

        request.current_app = modeladmin.admin_site.name
        return TemplateResponse(request, "admin/lag_giroar.html", context)

    if not request.POST.get("ink-utmeld"):
        queryset = queryset.filter(utmeldt_dato__isnull=True)
    if not request.POST.get("ink-betalt"):
        queryset = queryset.exclude(giroar__gjeldande_aar=year)

    with reversion.create_revision():
        reversion.set_comment("Opprett giroar admin action")
        reversion.set_user(request.user)
        data = form.cleaned_data
        for m in queryset:
            g = Giro(belop=data['belop'], konto=data['konto'],
                     desc=data['desc'], hensikt=data['hensikt'],
                     medlem=m)
            g.save()
lag_giroar.short_description = "Opprett giroar"

def giro_status_ferdig(modeladmin, request, queryset):
    with reversion.create_revision():
        reversion.set_comment("Giro status ferdig admin action")
        reversion.set_user(request.user)
        today = datetime.date.today()
        for g in queryset:
            g.status='F'
            if not g.innbetalt_belop:
                g.innbetalt_belop = g.belop
            if not g.innbetalt:
                g.innbetalt = today
            g.save()
giro_status_ferdig.short_description = "Sett giro betalt"

def giro_status_postlagt(modeladmin, request, queryset):
    with reversion.create_revision():
        for g in queryset:
            g.status='M'
            g.save()
        reversion.set_comment("Giro status postlagt admin action")
        reversion.set_user(request.user)
giro_status_postlagt.short_description = "Sett girostatus 'Manuelt postlagt'"

def giro_status_ventar(modeladmin, request, queryset):
    with reversion.create_revision():
        for g in queryset:
            g.status='V'
            g.save()
        reversion.set_comment("Giro status ventar admin action")
        reversion.set_user(request.user)
giro_status_ventar.short_description = "Sett girostatus 'Ventar'"

def giro_status_ubetalt(modeladmin, request, queryset):
    with reversion.create_revision():
        for g in queryset:
            g.status='U'
            g.save()
        reversion.set_comment("Giro status 'utgått ubetalt' admin action")
        reversion.set_user(request.user)
giro_status_ubetalt.short_description = "Sett girostatus 'Utgått ubetalt'"

def giro_hensikt_gaave(modeladmin, request, queryset):
    with reversion.create_revision():
        for g in queryset:
            g.hensikt='G'
            g.save()
        reversion.set_comment("Giro hensikt 'gaave' admin action")
        reversion.set_user(request.user)
giro_hensikt_gaave.short_description = u"Sett hensikt 'Gåve'"

def giro_hensikt_medlemspengar(modeladmin, request, queryset):
    with reversion.create_revision():
        for g in queryset:
            g.hensikt='P'
            g.save()
        reversion.set_comment("Giro hensikt 'medlemspengar' admin action")
        reversion.set_user(request.user)
giro_hensikt_medlemspengar.short_description = u"Sett hensikt 'Medlemspengar'"

@transaction.atomic
def suggest_lokallag(modeladmin, request, queryset):
    if request.POST.get('post'):
        updated = []
        with reversion.create_revision():
            reversion.set_comment("Endra lokallag med suggest_lokallag")
            reversion.set_user(request.user)
            for m in queryset:
                pk = "lokallag_{0}".format(m.pk)
                if pk not in request.POST:
                    continue
                try:
                    new_lokallag_id = int(request.POST[pk])
                except ValueError:
                    continue
                if m.lokallag_id == new_lokallag_id:
                    continue
                m.lokallag_id = new_lokallag_id
                m.save()
                updated.append(m)
        modeladmin.message_user(
            request,
            "{} brukarar med oppdaterte lokallag".format(len(updated)))
        return None
    already_ok = []
    suggested_new = []
    totally_new = []
    nothing = []
    for m in queryset:
        m.prop = m.proposed_lokallag()
        if m.prop and m.lokallag == m.prop[0]:
            already_ok.append(m)
        elif m.lokallag in m.prop:
            suggested_new.append(m)
        elif m.prop:
            totally_new.append(m)
        else:
            nothing.append(m)

        choices = [(l.pk, l.namn) for l in m.prop]
        if m.lokallag and m.lokallag not in m.prop:
            choices.append((m.lokallag_id, m.lokallag.namn))
        elif not m.lokallag:
            choices.append(('', '(ingen)'))
        m.suggested = SuggestedLokallagForm(
                          auto_id='id_{}_%s'.format(m.pk),
                          initial={
                              'lokallag': m.lokallag_id,
                              'medlem': m.pk,
                          },
                          lokallag_choices=choices,
                          medlem_id=m.pk)

    title = _("Endra lokallag ({c} medlemar)".format(c=queryset.count()))
    opts = modeladmin.model._meta
    app_label = opts.app_label
    context = {
        "title": title,
        "queryset": queryset,
        "opts": opts,
        "app_label": app_label,
        "action": 'suggest_lokallag',
        "action_checkbox_name": helpers.ACTION_CHECKBOX_NAME,
        "already_ok": already_ok,
        "suggested_new": suggested_new,
        "totally_new": totally_new,
    }
    request.current_app = modeladmin.admin_site.name
    return TemplateResponse(request, "admin/proposed_lokallag.html",
              context)
suggest_lokallag.short_description = _(u"Foreslå lokallag")


#!/projects/trans_scratch/software/python/Python-2.7.3/bin/python

# Script to retrieve the merged BAM file for the given library name.

import argparse, glob, os, subprocess, sys, xmlrpclib
from gsc import getr2gbam

try:
    USERNAME = os.environ['USER']
except KeyError:
    print("ERROR: Cannot find USER in the environment!")
    exit(1)

try:
    PACKAGE_DIRECTORY = os.environ['TRANSABYSS_PATH']
except KeyError:
    print("ERROR: Cannot find TRANSABYSS_PATH in the environment!")
    exit(1)

BIOAPPS_API_SERVER = 'www.bcgsc.ca/data/sbs/viewer/api'

FAILED_MESSAGE = 'Failed to find anything =('
REFERENCE_CHECKER = '/projects/trans_scratch/validations/assembly_scripts/misc/get_reference_from_bam.sh'

def searchForBAMFiles(directory):
    """
    Search for BAM files in the given directory.

    @param directory - the directory to search for BAM files.

    @return True if at least one BAM file is found in the given directory.

    """
    found = False
    bam_files = glob.glob(os.path.join(directory, "*bam"))
    for bam_file in bam_files:
        bashCommand = REFERENCE_CHECKER + " " + bam_file
        process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
        output = process.communicate()[0].rstrip()
        print(output + " BAM file found: " + bam_file)
        index_file = bam_file + ".bai"
        if not "incomplete.bam" in index_file:
            if os.path.isfile(index_file):
                print("BAM index found: " + index_file)
            else:
                print("Missing BAM index file for: " + bam_file)
        found = True
    return found

def retrieveFastqFiles(api_fastq_result, production_only=False):
    target_number_of_lanes=api_fastq_result[0]['target_number_of_lanes']
    if target_number_of_lanes == None:
        return None
    data_paths = []
    for lane_info in api_fastq_result:
        for fastq in lane_info['fastq']:
            if production_only:
                if fastq['status'] != 'production':
                    continue
            data_path=fastq['data_path']
            if "chastity_passed" in data_path:
                data_paths.append(data_path)
    fastq_files=[]
    for path in data_paths:
        path_found = searchForFASTQFiles(path)
        if path_found == True:
            fastq_files.append(path)
    expected = target_number_of_lanes*2
    if len(fastq_files) > expected:
        print("WARNING: MORE FASTQ FILES WERE FOUND ON FILE SYSTEM THAN EXPECTED")
    elif len(fastq_files) < expected:
        print("WARNING: LESS FASTQ FILES WERE FOUND ON FILE SYSTEM THAN EXPECTED")
    else:
        print("ALL FASTQ FILES FOUND:")
    for i in fastq_files:
        print(i)
    return fastq_files

def searchForFASTQFiles(path):
    """
    Search for an existing fastq file given a file path

    @param path - the path to check for a fastq file.

    @return True if the FASTQ file is found.
    """
    return True if os.path.isfile(path) and os.path.getsize(path) > 0 else False

def get_fastq_read_lengths(api_fastq_result):
    sequence_len = []
    fastq_info = [i['fastq'] for i in api_fastq_result]
    for i in fastq_info:
        if len(i) == 0:
            continue
        else:
            for j in i:
                sequence_len.append(j['sequence_length'])
    return sequence_len

parser = argparse.ArgumentParser(description='Retrieve the filer path of the merged or repositioned BAM file for the given library name.',
                                 add_help=False)
required = parser.add_argument_group('POSITIONAL ARGUMENTS')
required.add_argument('library_name', metavar='LIBRARY_NAME', help='Library name of the merged or repositioned BAM file to retrieve, e.g. A10538.')
optional = parser.add_argument_group('OPTIONAL ARGUMENTS')
optional.add_argument('-h', '--help', action='help', help='show this help message and exit')
optional.add_argument('-q', '--qc',action='store_true', default='False', help='Do not Filter the fastq files that have not passed qc.')
optional.add_argument('-f', '--filter', action='store_true', default=False, help='Do not Filter the fastq files that are not marked as production.')
if len(sys.argv) == 1:
    parser.print_help()
    exit(2)

args = parser.parse_args()
library_name = args.library_name
ignore_qc = args.qc
production_only = not args.filter
try:
    bioapps_api = xmlrpclib.ServerProxy("http://%s:%s@%s" % (USERNAME, getr2gbam.getpassword(), BIOAPPS_API_SERVER), allow_none=True)
    api_fastq_results = bioapps_api.getFASTQInfo({'library':library_name,'ignore_qc':ignore_qc})
    if api_fastq_results:
        read_lengths = get_fastq_read_lengths(api_fastq_results)
        if len(read_lengths) == 0:
            print(FAILED_MESSAGE)
        for read_length in set(read_lengths):
            print("Retreiving fastqs for read length {}".format(read_length))
            filtered_api_fastq_result = bioapps_api.getFASTQInfo({'library':library_name,'ignore_qc':ignore_qc,'sequence_length':read_length})
            fastqs = retrieveFastqFiles(filtered_api_fastq_result,production_only)
    else:
        print(FAILED_MESSAGE)
except xmlrpclib.ProtocolError as error:
    print('ERROR: There appears to be an issue accessing the BIOAPPS database, "{0} {1}"'.format(error.errcode, error.errmsg))
    exit(1)


import datetime
import os
date = datetime.date.today()
hour = datetime.time(1,2,3)
#variables
print(hour)
temp0 = 50
tempF = 24
#Rutina para crear reporte de condiciones iniciales y finales
#datos relevantes
for i in range (3):
    cont = """se detectó un evento a las {hora}
    con fecha de {hoy}.
    La temperatura inicial fue {T0}
    La temperatura final fue de {Tf}""".format(hora = hour, hoy = date,T0 = temp0, Tf = tempF)
    os.mkdir('/home/pi/Documents/Event_{hoy}'.format(hoy = date, num = i))
    new_rute = ('/home/pi/Documents/Event_{hoy}/evento{num}.txt'.format(hoy = date, num = i)) #Creación de archivo con fecha

    archivo = open(new_rute, 'w') #w de write
    archivo.write(cont) #escribe archivo

    archivo.close()


import json
import urllib

import requests

telgramToken = ''
telefframDividendChatId = '-586722077'
URL = "https://api.telegram.org/bot{}/".format(telgramToken)

def get_url(url):
    response = requests.get(url)
    content = response.content.decode("utf8")
    return content

def send_message(text):
    payload = dict()
    payload['text'] = text
    payload['chat_id'] = telefframDividendChatId
    params = urllib.parse.urlencode(payload, quote_via=urllib.parse.quote)
    url = URL + "sendMessage"
    response = requests.get(url, params=params)
    #print(response)
    #get_url(url)


def speak_formation_futsal(*arguments, **keywords):
    for args in arguments:
        print(args)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for key in keys:
        print(key + ":" + keywords[key])

speak_formation_futsal("There will be 5 player.", "The coach chooses them.", "The team has to win.",
                       "Best formation is:", GK='A tall guy', ZB="Two big guys",
                       CM="A clever guy", LF="Two skilled guys")


#!/usr/bin/env python
import multiprocessing
import time
import numpy as np

class CV:
    MPH_TO_MS = 1.609 / 3.6
    MS_TO_MPH = 3.6 / 1.609
    KPH_TO_MS = 1. / 3.6
    MS_TO_KPH = 3.6
    MPH_TO_KPH = 1.609
    KPH_TO_MPH = 1. / 1.609
    KNOTS_TO_MS = 1 / 1.9438
    MS_TO_KNOTS = 1.9438

def scale_acceleration(speed):
    xp = [80*CV.KPH_TO_MS, 120*CV.KPH_TO_MS, 150*CV.KPH_TO_MS]
    yp = [1, 2, 3]
    acceleration_scale_factor = np.interp(speed, xp, yp)
    return acceleration_scale_factor

# function that returns the speed and acceleration of the ego vehicle
def car_plant(pos, speed=40, grade=-20, gas=1, brake=0):
    # vehicle parameters
    g = 9.81
    mass = 1700
    aero_cd = 0.3

    force_peak = mass * 3.
    force_brake_peak = -mass * 20.
    power_peak = 100000   # 100kW
    speed_base = power_peak / force_peak
    rolling_res = 0.01
    air_density = 1.225
    gas_to_peak_linear_slope = 3.33
    brake_to_peak_linear_slope = 0.2

    # *** longitudinal model ***
    # find speed where peak torque meets peak powertest_id_1.py -> import file and function... write test code and set excel data
    force_brake = brake * force_brake_peak * brake_to_peak_linear_slope #braking force
    if speed < speed_base:  # torque control
        force_gas = gas * force_peak * gas_to_peak_linear_slope #force due to throttle
    else:  # power control
        force_gas = gas * power_peak / speed * gas_to_peak_linear_slope

    force_grade = grade * mass  # positive grade means uphill

    force_resistance = -(rolling_res * mass * g + 0.5 *speed**2 * aero_cd * air_density) # negative force due to air resistance

    force = force_gas + force_brake + force_resistance + force_grade  #calculates the sum of all forces
    acceleration = (force / mass) * scale_acceleration(speed)

    return speed, acceleration
class CV:
    MPH_TO_MS = 1.609 / 3.6
    MS_TO_MPH = 3.6 / 1.609
    KPH_TO_MS = 1. / 3.6
    MS_TO_KPH = 3.6
    MPH_TO_KPH = 1.609
    KPH_TO_MPH = 1. / 1.609
    KNOTS_TO_MS = 1 / 1.9438
    MS_TO_KNOTS = 1.9438

# returns the current time
def sec_since_boot():
    return time.time()

# used to iterate the frame in visualised plot, depends on a given rate value.
class Ratekeeper(object):

    def __init__(self, rate):
        """Rate in Hz for ratekeeping. print_delay_threshold must be nonnegative."""
        self._interval = 1. / rate
        self._next_frame_time = sec_since_boot() + self._interval
        self._frame = 0

    @property
    def frame(self):
        return self._frame

    def monitor_time(self):
        self._next_frame_time += self._interval
        self._frame += 1

class Plant(object):

    def __init__(self, lead_relevancy=False, rate=100, speed=0.0, distance_lead=2.0, verbosity=0):
        self.rate = rate
        self.verbosity = verbosity
        self.distance, self.distance_prev = 0., 0.
        self.speed, self.speed_prev = speed, speed
        self.lead_relevancy = lead_relevancy

        # lead car
        self.distance_lead_prev = distance_lead

        self.rk = Ratekeeper(rate)
        self.ts = 1. / rate

    def current_time(self):
        return float(self.rk.frame) / self.rate

    def step(self, brake=0, gas=0, v_lead=0.0, grade=0.0):

        distance_lead = self.distance_lead_prev + v_lead * self.ts

        # ******** run the car ********
        speed, acceleration = car_plant(self.distance_prev, self.speed_prev, grade, gas, brake)
        distance = self.distance_prev + speed * self.ts + self.ts**2*acceleration*.5
        speed = self.speed_prev + self.ts * acceleration

        # ******** stop the car ********
        if speed <= 0:
            speed = 0
            acceleration = 0

        # *** radar model ***
        if self.lead_relevancy:
            d_rel = np.maximum(0., distance_lead - distance)
            v_rel = v_lead - speed
        else:
            d_rel = 200.
            v_rel = 0.

        # print at 5hz
        if True:
            msg_tmpl = ("%6.2f m  %6.2f m/s  %6.2f m/s2 "
                        "  gas: %.2f  brake: %.2f "
                        "  lead_rel: %6.2f m  %6.2f m/s")
            msg = msg_tmpl % (distance, speed, acceleration,
                              gas, brake, d_rel, v_rel)

            if self.verbosity > 2:
                print(msg)

        # ******** update prevs ********
        self.speed_prev = speed
        self.distance_prev = distance
        self.distance_lead_prev = distance_lead

        car_in_front = distance_lead - distance if self.lead_relevancy else 200.

        self.rk.monitor_time()
        return speed, acceleration, car_in_front


from pydantic import BaseModel, validator
from typing import Optional
from datetime import datetime, timedelta

from db.models import CurrencyCode

class FlightCreate(BaseModel):
    flight_guide_id: int
    departure_date: datetime
    arrival_date: datetime
    purchase_price: int
    price: int
    currency: CurrencyCode
    total_seats: int
    on_sale: datetime

    # region Validators
    @validator('currency')
    def currency_must_be_in_currency_code(cls, v):
        if v not in ['USD', 'EUR', 'RUB', 'UZS']:
            raise ValueError('currency must be in CurrencyCode[USD, EUR, RUB, UZS]')
        return v

    @validator('departure_date')
    def departure_date_must_be_greater_than_now(cls, v):
        if v < datetime.now():
            raise ValueError('departure_date must be greater than now')
        return v

    @validator('arrival_date')
    def arrival_date_must_be_greater_than_departure_date(cls, v, values):
        if v < values.get('departure_date'):
            raise ValueError('arrival_date must be greater than departure_date')
        return v

    @validator('price')
    def price_must_be_greater_than_0(cls, v):
        if v < 1:
            raise ValueError('price must be greater than 0')
        return v

    @validator('total_seats')
    def total_seats_must_be_greater_than_0(cls, v):
        if v < 1:
            raise ValueError('total_seats must be greater or equal than 0')
        return v

    # endregion

    class Config:
        schema_extra = {
            "example": {
                "flight_guide_id": 1,
                "departure_date": (datetime.now() + timedelta(hours=6)).strftime("%Y-%m-%d %H:%M"),
                "arrival_date": (datetime.now() + timedelta(hours=9)).strftime("%Y-%m-%d %H:%M"),
                "purchase_price": 1000,
                "price": 1500,
                "currency": "RUB",
                "total_seats": 30,
                "on_sale": (datetime.now() + timedelta(hours=2)).strftime("%Y-%m-%d %H:%M"),
            }
        }

class FlightUpdate(FlightCreate):
    flight_guide_id: Optional[int]
    departure_date: Optional[datetime]
    arrival_date: Optional[datetime]
    purchase_price: Optional[int]
    price: Optional[int]
    currency: Optional[str]
    total_seats: Optional[int]
    left_seats: Optional[int]
    on_sale: Optional[datetime]
    actor_id: Optional[int]

    class Config:
        schema_extra = {
            "example": {
                **FlightCreate.Config.schema_extra.get("example"),
                "left_seats": 100,
            }
        }

class Flight(FlightUpdate):
    id: int
    created_at: Optional[datetime]
    updated_at: Optional[datetime]
    deleted_at: Optional[datetime]
    tickets: list

    # price_history: list

    class Config:
        orm_mode = True
        schema_extra = {
            "example": {
                "id": 1,
                **FlightUpdate.Config.schema_extra.get("example"),
                "left_seats": 100,
                "created_at": "2021-07-01T10:00:00",
                "updated_at": "2021-07-01T10:00:00",
                "deleted_at": "2021-07-01T10:00:00",
                "tickets": [],
                # "price_history": []
            }
        }

# region FlightHistory

class FlightHistoryCreate(BaseModel):
    flight_id: int
    new_price: int
    currency: str
    comment: Optional[str]

    @validator('flight_id')
    def flight_id_gt_than_0(cls, v):
        if v < 1:
            raise ValueError('flight_id must be greater than 0')
        return v

    class Config:
        schema_extra = {
            "example": {
                "flight_id": 1,
                "new_price": 100000,
                "currency": "RUB",
                "comment": "Some comment",
            }
        }

class FlightHistory(FlightHistoryCreate):
    id: int
    created_at: Optional[datetime]

    class Config:
        orm_mode = True
        schema_extra = {
            "example": {
                "id": 1,
                **FlightHistoryCreate.Config.schema_extra.get("example"),
                "created_at": "2021-07-01T10:00:00",
            }
        }


from django.shortcuts import render
from .models import Cat
import requests
import secrets
from random import randint
from math import sin, cos, radians, degrees, acos

def home(request):
    # Landing page
    return render(request, 'cats/home.html')

def all(request):
    # Display all cats in the database
    cats = Cat.objects.all()
    for cat in cats:
        cat.distance = calc_dist(37.781975, -122.407448, float(cat.latitude), float(cat.longitude))
    context = {
        'cats': cats,
        'title': 'All Cats'
    }

    return render(request, 'cats/display.html', context)

def find(request):
    # Load all cats from database to be filtered by breed and age
    breeds = []
    cats = Cat.objects.all()
    for cat in cats:
        # Start distance is the location of Holberton SF campus
        cat.distance = calc_dist(37.781975, -122.407448, float(cat.latitude), float(cat.longitude))
        if cat.age <= 2:
            cat.age_range = '0'
        elif cat.age >= 3 and cat.age <= 5:
            cat.age_range = '3'
        elif cat.age >= 6 and cat.age <= 9:
            cat.age_range = '6'
        elif cat.age >= 10 and cat.age <= 12:
            cat.age_range = '10'
        elif cat.age >= 13 and cat.age <= 16:
            cat.age_range = '13'
        else:
            cat.age_range = '17'
        breeds.append(cat.breed)
    breeds = list(dict.fromkeys(breeds))
    breeds.sort()
    context = {
        'breeds': breeds,
        'cats': cats,
        'title': 'Find a Cat'
    }
    return render(request, 'cats/find.html', context)

def cat(request, cat_id):
    # Display info and a map with directions to a single cat
    cat = Cat.objects.get(id=cat_id)
    cat.distance = calc_dist(37.781975, -122.407448, float(cat.latitude), float(cat.longitude))
    # Give walking directions for cats under 1 mile away; driving directions otherwise
    if cat.distance > 1:
        cat.mode = 'driving'
    else:
        cat.mode = 'walking'
    context = {
        'cat': cat,
        'title': 'Borrow a Cat'
    }
    return render(request, 'cats/cat.html', context)

def about(request):
    # About page
    return render(request, 'cats/about.html', {'title': 'About'})

""" This function is taken from here: https://stackoverflow.com/questions/4716017/django-how-can-i-find-the-distance-between-two-locations/4716690#4716690 """
def calc_dist(lat_a, long_a, lat_b, long_b):
    # Calculate the distance in miles between two GPS coordinates
    lat_a = radians(lat_a)
    lat_b = radians(lat_b)
    long_diff = radians(long_a - long_b)
    distance = (sin(lat_a) * sin(lat_b) +
                cos(lat_a) * cos(lat_b) * cos(long_diff))
    resToMile = degrees(acos(distance)) * 69.09
    # resToMt = resToMile / 0.00062137119223733
    return resToMile

def random(request):
    # Get all breeds available on Cat API and randomly select and display one of each breed
    types = []

    breeds = requests.get('https://api.thecatapi.com/v1/breeds').json()
    # breeds = [{'id': 'abys'}]

    for breed in breeds:
        cat = requests.get('https://api.thecatapi.com/v1/images/search?breed_ids=' + breed.get('id')).json()[0]
        # cat = cat.get('url')
        types.append(cat)

    context = {
        'cats': types
    }
    return render(request, 'cats/random.html', context)

def add(request):
    # Add cats to the database for each GPS coordinate provided
    # Running this method in production (with more coordinates provided) generated the 1300+ cats currently in the database
    types = []

    coordinates = [
        {'latitude':37.7051,'longitude':-121.721},
        {'latitude':37.9978,'longitude':-121.721},
        {'latitude':37.7061,'longitude':-121.723},
        {'latitude':37.7092,'longitude':-121.724},
        {'latitude':37.7117,'longitude':-121.724},
        {'latitude':37.7183,'longitude':-121.724},
        {'latitude':37.9979,'longitude':-121.731},
        {'latitude':37.6966,'longitude':-121.735},
        {'latitude':37.9253,'longitude':-121.735},
        {'latitude':37.9617,'longitude':-121.743}

    ]

    breeds = requests.get('https://api.thecatapi.com/v1/breeds').json()
    # breeds = [{'id': 'abys'}]

    names = [
        'Aalaa',
        'Adekunle',
        'Afa',
        'Ahad',
        'Akeem',
        'Alex',
        'Alexa',
        'Alexandre',
        'Alexandro',
        'Alexis',
        'Alia',
        'Allison',
        'Amadriel',
        'Amber',
        'Amy',
        'Andres',
        'Andrew',
        'Angie',
        'Anne',
        'Anne-Sophie',
        'Anoop',
        'Anthony',
        'Ariana',
        'Arik',
        'Arthur',
        'Artur',
        'Athena',
        'Banu',
        'Becky',
        'Ben',
        'Bennett',
        'Bianca',
        'Bilal',
        'Binita',
        'Brendan',
        'Brennan',
        'Brent',
        'Bryan',
        'CaNese',
        'Cameron',
        'Carole',
        'Carrie',
        'Chandler',
        'Charles',
        'Christine',
        'Christopher',
        'Colton',
        'Constance',
        'Corbin',
        'Cuong',
        'Cynthia',
        'Damon',
        'Daniel',
        'Darnell',
        'David',
        'Debora',
        'Dennis',
        'Derek',
        'Derric',
        'Derrick',
        'Diva',
        'Domitille',
        'Dora',
        'Drew',
        'Edward',
        'Elaine',
        'Electra',
        'Elena',
        'Elizabeth',
        'Eric',
        'Erika',
        'Essence',
        'Ethan',
        'Evan',
        'Evdokiya',
        'Farrukh',
        'Felicia',
        'Fernando',
        'Florian',
        'Gaoqing',
        'George',
        'Germaine',
        'Grant',
        'Grayson',
        'Gregory',
        'Guillaume',
        'Hanh',
        'Heindrick',
        'Hemant',
        'Henry',
        'Holden',
        'Hongtu',
        'Hunter',
        'Ian',
        'Isaac',
        'Isaiah',
        'Jack',
        'Jacob',
        'James',
        'Jannis',
        'Jared',
        'Jason',
        'Jeffrey',
        'Jennifer',
        'Jerel',
        'Jeremy',
        'Jesse',
        'Jessica',
        'Jian',
        'Jianqin',
        'Jimmy',
        'Jinji',
        'Joan',
        'John',
        'Joseph',
        'Joshua',
        'Julien',
        'Julija',
        'Jun',
        'Juno',
        'Justin',
        'Katya',
        'Kenneth',
        'Kevan',
        'Kevin',
        'Kimberly',
        'Kiren',
        'Koome',
        'Kristen',
        'Kristine',
        'Kyle',
        'Laura',
        'Laurence',
        'Lee',
        'Leine',
        'Lindsey',
        'Lisa',
        'Madison',
        'Marc',
        'Marco',
        'Marine',
        'Marius',
        'Martin',
        'Mason',
        'Max',
        'Megha',
        'Michelle',
        'Mikaela',
        'Minhhuy',
        'Miranda',
        'Mitali',
        'Naomi',
        'Nathan',
        'Nehal',
        'Nga',
        'Niat',
        'Nicholas',
        'Nick',
        'Ntuj',
        'Olatope',
        'Omar',
        'Patrick',
        'Paul',
        'Pauline',
        'Peter',
        'Philip',
        'Phu',
        'Pierre',
        'Ramandeep',
        'Rashaad',
        'Raudo',
        'Rene',
        'Richard',
        'Rick',
        'Robert',
        'Rona',
        'Rui',
        'Ryuichi',
        'Samie',
        'Samuel',
        'Scout',
        'Sergii',
        'Sergio',
        'Shoji',
        'Sidney',
        'Sneha',
        'Sofia',
        'Sonia',
        'Sophie',
        'Spencer',
        'Sravanthi',
        'Stephen',
        'Steven',
        'Sumin',
        'Swati',
        'Sylvain',
        'Tabitha',
        'Tammy',
        'Tanya',
        'Tasneem',
        'Thomas',
        'Tiffany',
        'Tim',
        'Timothy',
        'Travis',
        'Trevor',
        'Tu',
        'Van',
        'Vasudha',
        'Veronica',
        'Victor',
        'Walton',
        'Wendy',
        'Yannis',
        'Yashar',
        'Yunju',
        'Zachary'
    ]

    for c in coordinates:
        breed = secrets.choice(breeds)
        cat = requests.get('https://api.thecatapi.com/v1/images/search?breed_ids=' + breed.get('id')).json()[0]
        cat['breed'] = cat['breeds'][0]['name']
        cat['latitude'] = c['latitude']
        cat['longitude'] = c['longitude']
        cat['age'] = randint(0,20)
        cat['name'] = secrets.choice(names)
        cat1 = Cat(name=cat['name'], photo=cat['url'], breed=cat['breed'], age=cat['age'], latitude=cat['latitude'], longitude=cat['longitude'])
        cat1.save()
        types.append(cat)

    context = {
        'cats': types,
    }
    return render(request, 'cats/random.html', context)


from datetime import datetime

from django import forms
from django.forms.widgets import SelectDateWidget

from core.models import Persona, Contacto

class PersonaForm(forms.ModelForm):

    class Meta:
        model = Persona
        fields = ('nombre', 'apellido', 'dni', 'fecha_nacimiento', 'genero', 'estado_civil',
                  'domicilio', 'profesion', 'imagen_perfil', )
        widgets = {
            'fecha_nacimiento': SelectDateWidget(years=range(1900, datetime.now().year))
        }

class ContactoForm(forms.ModelForm):

    class Meta:
        model = Contacto
        fields = ('telefono', 'celular', 'notificar_sms', 'email', 'horario')


from kivy.app import App
from kivy.config import Config
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.button import Label
from kivy.uix.popup import Popup
from kivy.lang.builder import Builder
from dateutil import parser
from datetime import datetime

import requests, json

Builder.load_file("torneio.kv")

class TorneioLayout(BoxLayout):

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

    id = -1

    def get(self):
        self.id = int(self.ids.tb_id.text)
        req = requests.get(f"http://localhost:8080/torneios/{self.id}")
        if req.status_code == 200:
            torneio = json.loads(req.text)
            data_inicio = parser.parse(torneio["data_inicio"])
            data_fim = parser.parse(torneio["data_fim"])
            self.ids.tb_nome.text = torneio["nome"]
            self.ids.tb_dt_fim.text = data_fim.strftime("%Y-%m-%d")
            self.ids.tb_dt_inicio.text = data_inicio.strftime("%Y-%m-%d")
            self.ids.tb_local.text = torneio["local"]
            self.ids.tb_nome.disabled = False
            self.ids.tb_dt_fim.disabled = False
            self.ids.tb_dt_inicio.disabled = False
            self.ids.tb_local.disabled = False
        else:
            self.ids.tb_nome.text = ""
            self.ids.tb_dt_fim.text = ""
            self.ids.tb_dt_inicio.text = ""
            self.ids.tb_local.text = ""
            # self.ids.tb_local.disabled = True
            # self.ids.tb_nome.disabled = True
            # self.ids.tb_dt_fim.disabled = True
            # self.ids.tb_dt_inicio.disabled = True

    def new(self):
        pass
    def update(self):
        upload = {}
        upload["nome"] = self.ids.tb_nome.text
        upload["data_fim"] = self.ids.tb_dt_fim.text
        upload["data_inicio"] = self.ids.tb_dt_inicio.text
        upload["local"] = self.ids.tb_local.text
        print(upload)
        response = requests.put(
            f"http://localhost:8080/torneios/{self.id}",
            data=json.dumps(upload),
            headers={"Content-Type": "application/json"})
        self.get()

    def delete(self):
        requests.delete(f"http://localhost:8080/torneios/{self.id}")
        self.get()


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
from typing import List

from langchain.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.indices.composability.graph import ComposableGraph
from llama_index.indices.empty.base import EmptyIndex
from llama_index.indices.list.base import ListIndex
from llama_index.indices.service_context import ServiceContext
from llama_index.indices.vector_store import VectorStoreIndex
from llama_index.llm_predictor.base import LLMPredictor
from llama_index.schema import Document
from llama_index.storage.storage_context import StorageContext

import project_settings as settings

DEFAULT_TEXT = """
我们是谁，我们在做什么
牛信云是一家专业提供CPaaS、SaaS等多种接入方式的国际云通信公司。
自成立以来，专注于云通信领域的技术研发，陆续推出了国际短信、国际语音、全球号码、WhatsApp Business、Viber Business等CPaaS服务，以及NXLink、NXCallbot、NXCC等SaaS服务。
目前，牛信云中国区总部坐落在深圳，并在宁波、上海、成都、厦门、香港设立分公司；
国际总部位于新加坡。深度合作客户有阿里巴巴、腾讯、小米、欢聚时代等头部互联网企业，旨在为出海企业提供一站式通信解决方案，帮助更多企业走向世界。
"""

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--query", default="牛信是做什么的?", type=str)
    parser.add_argument("--text_chunk", default=DEFAULT_TEXT, type=str)

    parser.add_argument(
        "--openai_api_key",
        default=settings.environment.get("openai_api_key", default=None, dtype=str),
        type=str
    )
    args = parser.parse_args()
    return args

def main():
    args = get_args()

    document = Document(
        text=args.text_chunk,
        metadata={
            "source": "metadata_source",
        }
    )
    documents: List[Document] = [document]

    storage_context: StorageContext = StorageContext.from_defaults()
    service_context: ServiceContext = ServiceContext.from_defaults(
        llm_predictor=LLMPredictor(
            llm=OpenAI(
                openai_api_key=args.openai_api_key
            )
        ),
        embed_model=OpenAIEmbedding(api_key=args.openai_api_key),
    )

    essay_index = VectorStoreIndex.from_documents(
        documents=documents,
        storage_context=storage_context,
        service_context=service_context,
    )
    essay_index_summary = "essay_index_summary"

    empty_index = EmptyIndex()
    empty_index_summary = "empty_index_summary"

    graph = ComposableGraph.from_indices(
        ListIndex,
        [essay_index, empty_index],
        index_summaries=[essay_index_summary, empty_index_summary],
        service_context=service_context,
        storage_context=storage_context,
    )
    print(graph.root_id)
    print(graph.all_indices)
    print(graph.root_index)
    print(graph.index_struct)
    print(graph.service_context)

    return

if __name__ == '__main__':
    main()


import argparse
import os
import sys
import time

import numpy as np
import torch
from torch.autograd import Variable
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms

import utils
from transformer_net import TransformerNet
from vgg16 import Vgg16

from tensorboardX import SummaryWriter
import io
import requests
from PIL import Image
from torchvision import models
from torch.nn import functional as F

#load the model for the cam map generation,here we use the squeezenet
model_id = 1
if model_id == 1:
    net = models.squeezenet1_1(pretrained=True).cuda()
    finalconv_name = 'features' # this is the last conv layer of the network
elif model_id == 2:
    net = models.resnet18(pretrained=True)
    finalconv_name = 'layer4'
elif model_id == 3:
    net = models.densenet161(pretrained=True)
    finalconv_name = 'features'

net.eval()

features_blobs = []
# hook the feature extractor
def hook_feature(module, input, output):
    #features_blobs.append(output.data.cpu().numpy())
    features_blobs.append(output)
net._modules.get(finalconv_name).register_forward_hook(hook_feature)

# get the softmax weight
params = list(net.parameters())
weight_softmax = torch.squeeze(params[-2])

# calculate and return the cam image through inner product operations
def returnCAM(feature_conv, weight_softmax, class_idx):
    # generate the class activation maps upsample to 256x256
    nc, h, w = feature_conv.shape
    cam = torch.matmul(weight_softmax[class_idx],feature_conv.view(nc, h*w))
    return cam

def train(args):
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)

    if args.cuda:
        torch.cuda.manual_seed(args.seed)
        kwargs = {'num_workers': 0, 'pin_memory': False}
    else:
        kwargs = {}

    transform = transforms.Compose([transforms.Scale(args.image_size),
                                    transforms.CenterCrop(args.image_size),
                                    transforms.ToTensor(),
                                    transforms.Lambda(lambda x: x.mul(255))])
    train_dataset = datasets.ImageFolder(args.dataset, transform)
    train_loader = DataLoader(train_dataset, batch_size=args.batch_size, **kwargs)

    transformer = TransformerNet()
    if (args.premodel != ""):
        transformer.load_state_dict(torch.load(args.premodel))
        print("load pretrain model:"+args.premodel)
    optimizer = Adam(transformer.parameters(), args.lr)
    mse_loss = torch.nn.MSELoss()

    vgg = Vgg16()
    utils.init_vgg16(args.vgg_model_dir)
    vgg.load_state_dict(torch.load(os.path.join(args.vgg_model_dir, "vgg16.weight")))

    if args.cuda:
        transformer.cuda()
        vgg.cuda()

    style = utils.tensor_load_rgbimage(args.style_image, size=args.style_size)
    style = style.repeat(args.batch_size, 1, 1, 1)
    style = utils.preprocess_batch(style)
    if args.cuda:
        style = style.cuda()
    style_v = Variable(style, volatile=True)
    style_v = utils.subtract_imagenet_mean_batch(style_v)
    features_style = vgg(style_v)
    gram_style = [utils.gram_matrix(y) for y in features_style]

    hori=0
    writer = SummaryWriter(args.logdir,comment=args.logdir)
    for e in range(args.epochs):
        transformer.train()
        agg_content_loss = 0.
        agg_style_loss = 0.
        agg_cate_loss = 0.
        agg_cam_loss = 0.
        count = 0
        for batch_id, (x, _) in enumerate(train_loader):
            n_batch = len(x)
            count += n_batch
            optimizer.zero_grad()
            x = Variable(utils.preprocess_batch(x))
            if args.cuda:
                x = x.cuda()
            y = transformer(x)
            xc = Variable(x.data.clone(), volatile=True)
            #print(y.size()) #(4L, 3L, 224L, 224L)

            # Calculate focus loss and category loss
            y_cam = utils.depreprocess_batch(y)
            y_cam = utils.subtract_mean_std_batch(y_cam)

            xc_cam = utils.depreprocess_batch(xc)
            xc_cam = utils.subtract_mean_std_batch(xc_cam)

            del features_blobs[:]
            logit_x = net(xc_cam)
            logit_y = net(y_cam)

            label=[]
            cam_loss = 0
            for i in range(len(xc_cam)):
                h_x = F.softmax(logit_x[i])
                probs_x, idx_x = h_x.data.sort(0, True)
                label.append(idx_x[0])

                h_y = F.softmax(logit_y[i])
                probs_y, idx_y = h_y.data.sort(0, True)

                x_cam = returnCAM(features_blobs[0][i], weight_softmax, idx_x[0])
                x_cam = Variable(x_cam.data,requires_grad = False)

                y_cam = returnCAM(features_blobs[1][i], weight_softmax, idx_y[0])

                cam_loss += mse_loss(y_cam, x_cam)

            #the focus loss
            cam_loss *= 80
            #the category loss
            label = Variable(torch.LongTensor(label),requires_grad = False).cuda()
            cate_loss = 10000 * torch.nn.CrossEntropyLoss()(logit_y,label)

            y = utils.subtract_imagenet_mean_batch(y)
            xc = utils.subtract_imagenet_mean_batch(xc)

            features_y = vgg(y)
            features_xc = vgg(xc)

            #f_xc_c = Variable(features_xc[1].data, requires_grad=False)
            #content_loss = args.content_weight * mse_loss(features_y[1], f_xc_c)

            f_xc_c = Variable(features_xc[2].data, requires_grad=False)
            content_loss = args.content_weight * mse_loss(features_y[2], f_xc_c)
            style_loss = 0.
            for m in range(len(features_y)):
                gram_s = Variable(gram_style[m].data, requires_grad=False)
                gram_y = utils.gram_matrix(features_y[m])
                style_loss += args.style_weight * mse_loss(gram_y, gram_s[:n_batch, :, :])
            #add the total four loss and backward
            total_loss = style_loss + content_loss  + cam_loss + cate_loss
            total_loss.backward()
            optimizer.step()

            #something for display
            agg_content_loss += content_loss.data[0]
            agg_style_loss += style_loss.data[0]
            agg_cate_loss += cate_loss.data[0]
            agg_cam_loss += cam_loss.data[0]

            writer.add_scalar("Loss_Cont", agg_content_loss / (batch_id + 1), hori)
            writer.add_scalar("Loss_Style", agg_style_loss / (batch_id + 1), hori)
            writer.add_scalar("Loss_CAM", agg_cam_loss / (batch_id + 1), hori)
            writer.add_scalar("Loss_Cate", agg_cate_loss / (batch_id + 1), hori)
            hori += 1

            if (batch_id + 1) % args.log_interval == 0:
               mesg = "{}Epoch{}:[{}/{}] content:{:.2f} style:{:.2f} cate:{:.2f} cam:{:.2f}  total:{:.2f}".format(
                    time.strftime("%a %H:%M:%S"),e + 1, count, len(train_dataset),
                                 agg_content_loss / (batch_id + 1),
                                 agg_style_loss / (batch_id + 1),
                                 agg_cate_loss / (batch_id + 1),
                                 agg_cam_loss / (batch_id + 1),
                                 (agg_content_loss + agg_style_loss + agg_cate_loss + agg_cam_loss ) / (batch_id + 1)
               )
               print(mesg)

            if (batch_id + 1) % 2500 == 0:
                transformer.eval()
                transformer.cpu()
                save_model_filename = "epoch_" + str(e+1) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str(
                    args.content_weight) + "_" + str(args.style_weight) + ".model"
                save_model_path = os.path.join(args.save_model_dir, save_model_filename)
                torch.save(transformer.state_dict(), save_model_path)
                transformer.cuda()
                transformer.train()
                print("saved at ",count)

    # save model
    transformer.eval()
    transformer.cpu()
    save_model_filename = "epoch_" + str(args.epochs) + "_" + str(time.ctime()).replace(' ', '_') + "_" + str(
        args.content_weight) + "_" + str(args.style_weight) + ".model"
    save_model_path = os.path.join(args.save_model_dir, save_model_filename)
    torch.save(transformer.state_dict(), save_model_path)

    writer.close()
    print("\nDone, trained model saved at", save_model_path)

def check_paths(args):
    try:
        if not os.path.exists(args.vgg_model_dir):
            os.makedirs(args.vgg_model_dir)
        if not os.path.exists(args.save_model_dir):
            os.makedirs(args.save_model_dir)
    except OSError as e:
        print(e)
        sys.exit(1)

def stylize(args):
    content_image = utils.tensor_load_rgbimage(args.content_image, scale=args.content_scale)
    content_image = content_image.unsqueeze(0)

    if args.cuda:
        content_image = content_image.cuda()
    content_image = Variable(utils.preprocess_batch(content_image), volatile=True)
    style_model = TransformerNet()
    style_model.load_state_dict(torch.load(args.model))

    if args.cuda:
        style_model.cuda()

    output = style_model(content_image)
    utils.tensor_save_bgrimage(output.data[0], args.output_image, args.cuda)

def main():
    main_arg_parser = argparse.ArgumentParser(description="parser for fast-neural-style")
    subparsers = main_arg_parser.add_subparsers(title="subcommands", dest="subcommand")

    train_arg_parser = subparsers.add_parser("train",
                                             help="parser for training arguments")
    train_arg_parser.add_argument("--epochs", type=int, default=2,
                                  help="number of training epochs, default is 2")
    train_arg_parser.add_argument("--premodel", type=str, default="",
                                  help="pretrain model")
    train_arg_parser.add_argument("--batch-size", type=int, default=4,
                                  help="batch size for training, default is 4")
    train_arg_parser.add_argument("--dataset", type=str, required=True,
                                  help="path to training dataset, the path should point to a folder "
                                       "containing another folder with all the training images")
    train_arg_parser.add_argument("--style-image", type=str, default="images/style-images/mosaic.jpg",
                                  help="path to style-image")
    train_arg_parser.add_argument("--vgg-model-dir", type=str, required=True,
                                  help="directory for vgg, if model is not present in the directory it is downloaded")
    train_arg_parser.add_argument("--save-model-dir", type=str, required=True,
                                  help="path to folder where trained model will be saved.")
    train_arg_parser.add_argument("--image-size", type=int, default=224,
                                  help="size of training images, default is 256 X 256")
    train_arg_parser.add_argument("--style-size", type=int, default=224,
                                  help="size of style-image, default is the original size of style image")
    train_arg_parser.add_argument("--cuda", type=int, required=True, help="set it to 1 for running on GPU, 0 for CPU")
    train_arg_parser.add_argument("--seed", type=int, default=42, help="random seed for training")
    train_arg_parser.add_argument("--content-weight", type=float, default=1.0,
                                  help="weight for content-loss, default is 1.0")
    train_arg_parser.add_argument("--style-weight", type=float, default=20.0,
                                  help="weight for style-loss, default is 5.0")
    train_arg_parser.add_argument("--lr", type=float, default=1e-3,
                                  help="learning rate, default is 0.001")
    train_arg_parser.add_argument("--log-interval", type=int, default=50,
                                  help="number of images after which the training loss is logged, default is 500")
    train_arg_parser.add_argument("--logdir", type=str, default="Logdir",help="")
    train_arg_parser.add_argument("--self", type=int, default=50,
                                  help="number of images after which the training loss is logged, default is 500")

    eval_arg_parser = subparsers.add_parser("eval", help="parser for evaluation/stylizing arguments")
    eval_arg_parser.add_argument("--content-image", type=str, required=True,
                                 help="path to content image you want to stylize")
    eval_arg_parser.add_argument("--content-scale", type=float, default=None,
                                 help="factor for scaling down the content image")
    eval_arg_parser.add_argument("--output-image", type=str, required=True,
                                 help="path for saving the output image")
    eval_arg_parser.add_argument("--model", type=str, required=True,
                                 help="saved model to be used for stylizing the image")
    eval_arg_parser.add_argument("--cuda", type=int, required=True,
                                 help="set it to 1 for running on GPU, 0 for CPU")

    args = main_arg_parser.parse_args()

    if args.subcommand is None:
        print("ERROR: specify either train or eval")
        sys.exit(1)

    if args.cuda and not torch.cuda.is_available():
        print("ERROR: cuda is not available, try running on CPU")
        sys.exit(1)

    if args.subcommand == "train":
        check_paths(args)
        train(args)
    else:
        stylize(args)

if __name__ == "__main__":
    main()


import random

random_num = random.randint(1,25)
lowercase_alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s', \
		  't','u','v','w','x','y','z']
punc = [' ', '.',',']
source_file = "test_file.txt"
am = "r"
output_file = "processed.txt"
encoding_type = "utf-8"
output_text = ""

myFile = open(source_file,am)
input_text = myFile.read()
# look at each character of the message
for i in range(len(input_text)):
	# if current char is punctuation
	# leave it alone-pass it through
	if input_text[i] in punc:
		# i=i+1 => i+=1
		output_text += output_text + input_text[i]
	else:
		alpha_index = lowercase_alphabet.index(input_text[i].lower())

		new_index = (alpha_index + random_num) % 26
		# maintain the case of the input message
		if input_text[i].upper() == input_text[i]:
			output_text += lowercase_alphabet[new_index].upper()
		else:
			output_text += lowercase_alphabet[new_index]

print(output_text)


from Crypto.Hash import SHA256
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
from Crypto.Random import get_random_bytes
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pss
from Crypto.PublicKey import RSA
import binascii

#def decode( filename, fkey, rsa_pub_sign, rsa_priv_cipher ):
def decode( filename, rsa_pub_sign, rsa_priv_cipher ):
	with open(filename, "rb") as f:
		content = f.read()

	# RSA sign cle pub
	rsa_pub_sign = RSA.import_key(open(rsa_pub_sign).read())
	sign_pub_key = pss.new(rsa_pub_sign)

	# RSA dechiffre cle priv
	rsa_priv_key = RSA.importKey(open(rsa_priv_cipher).read())
	cipher_priv_key = PKCS1_OAEP.new(rsa_priv_key)

	# Parsing IV, rsa_cipher, bmsgcipher, signature
	iv = content[0:16]
	rsa_cipher = content[16:272]
	bmsgcipher = content[272:288]
	signature = content[288:544]

	print ("iv = ", binascii.hexlify(iv), "\n")
	print ("rsa cipher = ", binascii.hexlify(rsa_cipher), "\n")
	print ("msg cipher = ", binascii.hexlify(bmsgcipher), "\n")
	print ("signature = ", binascii.hexlify(signature), "\n")

	# Recuperation de la cle master
	kc = cipher_priv_key.decrypt(rsa_cipher)

	# validation du hash
	sha256 = SHA256.new()
	sha256.update(iv)
	sha256.update(rsa_cipher)
	sha256.update(bmsgcipher)

	try:
		sign_pub_key.verify(sha256,signature)
		print("Le message est valide\nVous pouvez déchiffrer le message!\n")

	except ValueError:
		print("Le message a été compromis")

	# dechiffrement du message
	try:
		print("Déchiffrement en cours ...")
		cipher = AES.new(kc, AES.MODE_CBC, iv)
		decodemsg = unpad(cipher.decrypt(bmsgcipher),AES.block_size)
		print("Le message secret est : ",decodemsg.decode("utf-8"))

	except ValueError:
		print("Le déchiffrement n'a pas pu aboutir :/")

#decode("./testout", "./secretekey", "rsa_pub.pem", "rsa_priv.pem")
decode("./testout", "rsa_pub.pem", "rsa_priv.pem")


class vector2D:
    def __init__(self, x=0, y=0):
        self._x = x
        self._y = y

    def plus(self, other):
        return vector2D(self._x + other._x, self._y + other._y)

a = vector2D(2,2)
b = vector2D(-1,2)
c = a.plus(b)
print(c)
print(1, 2, 3, sep = ':')
N = 987654321
print(N % 10 ** 5 // 10 ** 2)


import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.layout import LAParams
import io
import pandas as pd

def pdfparser(data):

    fp = open(data, 'rb')
    rsrcmgr = PDFResourceManager()
    retstr = io.StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    # Create a PDF interpreter object.
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    # Process each page contained in the document.

    for page in PDFPage.get_pages(fp):
        interpreter.process_page(page)
        data =  retstr.getvalue()

    return data.split('\n\n')

def file_open(name):

    paras=pdfparser(name)
    title=paras.pop(0)
    #print(title)
    row=[title,paras]

    return row


import json
import matplotlib.pyplot as plt
from clustering import *
if __name__ == '__main__':

    # Load trajectories
    trajectories = None
    model_name = 'double_jump_labyrinth'
    with open("../arrays/{}.json".format("{}_trajectories".format(model_name))) as f:
        trajectories = json.load(f)

    print('Clustering')
    print(cluster_trajectories(list(trajectories.values())))


from email.policy import default
from enum import unique
from django.db import models
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from datetime import date, datetime

class Especialidade(models.Model):
    nome = models.CharField(max_length=100, null=False, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.nome

class Medico(models.Model):
    nome = models.CharField(max_length=100, null=False, blank=False)
    especialidade = models.ForeignKey(
        to=Especialidade,
        on_delete=models.SET_NULL,
        related_name="medicos",
        null=True,
        blank=False
    )
    crm = models.PositiveSmallIntegerField(
        null=False,
        blank=False,
        unique=True,
        validators=[
            MinValueValidator(1),
            MaxValueValidator(9999)
        ]
    )
    email = models.EmailField(max_length=255, null=False, blank=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.nome

class Horario(models.Model):
    horario = models.TimeField(
        auto_now=False, auto_now_add=False, unique=True,)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.horario)

class Agenda(models.Model):
    medico = models.ForeignKey(
        to=Medico,
        on_delete=models.CASCADE,
        related_name="agendas",
        null=False,
        blank=False
    )
    dia = models.DateField(
        null=False,
        blank=False
    )
    horarios = models.ManyToManyField(Horario, through='AgendaHorario',)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def clean(self):
        medico_conflitante = Agenda.objects.filter(
            dia=self.dia, medico_id=self.medico.id).last()

        if self.id is None and self.dia < date.today():
            raise ValidationError(
                "Não é possivel cadastrar uma agenda retroativamente.")

        if self.id is None and medico_conflitante is not None:
            raise ValidationError(
                "O medico selecionado já possui uma agenda cadastrada para o dia selecionado.")

class AgendaHorario(models.Model):
    agenda = models.ForeignKey(
        Agenda, on_delete=models.CASCADE, related_name='through_model')
    horario = models.ForeignKey(
        Horario, on_delete=models.CASCADE, related_name='through_model')
    _esta_ocupado = models.BooleanField(default=False)

    def clean(self):
        trought_table = self

        if self.id is None and trought_table.agenda.dia == date.today() and trought_table.horario.horario < datetime.now().time():
            raise ValidationError(
                "Não é possivel horario passado em uma agenda.")

class Consulta(models.Model):
    agenda = models.ForeignKey(
        to=Agenda,
        on_delete=models.CASCADE,
        related_name="consultas",
        null=False,
        blank=False
    )
    horario = models.ForeignKey(
        to=Horario,
        on_delete=models.CASCADE,
        related_name="consultas",
        null=False,
        blank=False
    )
    paciente = models.ForeignKey(
        to=User,
        on_delete=models.CASCADE,
        related_name="consultas",
        null=False,
        blank=False
    )
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)


import reflex as rx

# Import app components
from app.components.navbar import navbar
from app.components.chat import chat, action_bar

# Load overall application state
from app.config.state import State
from app.config import style

# Import Starcoder and use base chain
from app.utils.watsonxga import WatsonxLangchainLLM
from app.utils.watsonxworkbench import WatsonxWorkbenchLangchainLLM
from ibm_watson_machine_learning.foundation_models.utils.enums import ModelTypes
from ibm_watson_machine_learning.metanames import GenTextParamsMetaNames as GenParams

from app.config.state import State

config = rx.config.get_config()

if config.watsonx_type == "ga":
    # Create Starcoder chain
    llm = WatsonxLangchainLLM(
        model_id=ModelTypes.STARCODER.value,
        generate_params={
            GenParams.DECODING_METHOD: "greedy",
            GenParams.MAX_NEW_TOKENS: 200,
        },
    ).from_pretrained()

if config.watsonx_type == "workbench":
    llm = WatsonxWorkbenchLangchainLLM(
        model_id="codellama/codellama-34b-instruct",
        generate_params={
            GenParams.DECODING_METHOD: "greedy",
            GenParams.MAX_NEW_TOKENS: 200,
            "stream": True,
        },
    ).from_pretrained()

class CodeGenState(State):
    """The page state."""

    question: str = ""
    code_history: str
    chat_history: list[tuple[str, str]]

    async def answer(self):
        if config.watsonx_type == "ga":
            answer = llm(self.question)
            self.code_history += str(answer)
            self.chat_history.append((self.question, answer))
            self.question = ""

        if config.watsonx_type == "workbench":
            history = "\n ".join(
                [f"Q:{chat[0]} H:{chat[1]}" for chat in self.chat_history]
            )
            prompt = starcoder_template(history, self.question)
            self.chat_history.append((self.question, ""))
            answer = ""
            for response in llm.stream(prompt):
                answer += response
                self.code_history += str(response)
                self.chat_history[-1] = (self.question, answer)
                yield
            self.question = ""

    def run_prompt(self, prompt):
        self.question = prompt

    def clear_state(self):
        self.question = ""
        self.code_history = ""
        self.chat_history = []

def starcoder_template(history, prompt):
    return f"[inst]<sys>You are a coding assistant.</sys> This is a summary of the previous interactions. {history} Try to help answer the following:{prompt} [\inst]"

def codeblock() -> rx.Component:
    return rx.cond(
        CodeGenState.code_history,
        rx.code_block(
            CodeGenState.code_history, language="python", show_line_numbers=True
        ),
    )

@rx.page(route="/codegen", title="Code Generation - watsonx")
def index() -> rx.Component:
    return rx.box(
        navbar(),
        rx.hstack(
            rx.container(
                rx.text(
                    "Try out code generation below. Select one of the prompts e.g. Import Data then hit ask to generate code. Hit Clear once you're done.",
                    color="#342E5C",
                    font_size="0.9em",
                    font_family=style.SANS,
                    padding_top="1em",
                ),
                rx.hstack(
                    rx.button(
                        "Import Data",
                        on_click=lambda: CodeGenState.run_prompt(
                            "Import data from a file called data.csv and show the first five rows."
                        ),
                        style=style.PROMPT_BUTTON,
                    ),
                    rx.button(
                        "Build Linear Model",
                        on_click=lambda: CodeGenState.run_prompt(
                            "Build a linear model using scikit-learn."
                        ),
                        style=style.PROMPT_BUTTON,
                    ),
                    rx.button(
                        "Export to Joblib",
                        on_click=lambda: CodeGenState.run_prompt(
                            "Export the model using joblib"
                        ),
                        style=style.PROMPT_BUTTON,
                    ),
                    rx.button(
                        "Clear",
                        on_click=CodeGenState.clear_state,
                        style=style.CLEAR_BUTTON,
                    ),
                    style={"margin-top": "10px"},
                    position="sticky",
                    z_index="998",
                    top="0",
                ),
                rx.vstack(
                    chat(CodeGenState),
                    action_bar(CodeGenState),
                    height="100vh",
                    display="flex",
                    flex_direction="column",
                ),
                style={"min-width": "450px"},
            ),
            rx.container(
                rx.vstack(
                    rx.center(
                        rx.button(
                            "Copy to Clipboard",
                            on_click=rx.set_clipboard(CodeGenState.code_history),
                            style=style.ASK_BUTTON,
                        )
                    ),
                    codeblock(),
                    height="100vh",
                    display="inline-block",
                    # flex_direction="column",
                    style={
                        "inline-size": "800px",
                        "overflow-wrap": "break-word",
                    },
                ),
                style={"min-width": "1000px"},
            ),
        ),
    )


#!/usr/bin/python
import os, sys
from itertools import cycle
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import challenges as c

# c.mu2c => challenge no. 2 for mini urban race
s=c.mu2c
s1="Use Scytale Period 8"
m1=''.join(hex(ord(n))[2:].ljust(3,' ') for n in s1)

s2="Decode The Word Below And Use Its Opposite Color To Vigenere Decode"
s2=s2.replace(' ','')
m2=s2[0::7]+s2[1::7]+s2[2::7]+s2[3::7]+s2[4::7]+s2[5::7]+s2[6::7]

s3="BLACK"
m3=''.join([ (" {num:08b}".format(num=ord(c))+"\n") for c in s3])

s4="FilltheblankwithMUK"
key='WHITE'
alpha='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
plaintext=s4.upper().replace(' ','')
cycledkey=cycle(key)
m4=''.join(alpha[(alpha.index(next(cycledkey))+alpha.index(plaintext[i])) % 26] for i in range(len(s4)))

m5="http://crypto.cyberpdx.org/static/____.jpg"
ofile=open("mu2_final.txt","w+")
ofile.write(m1+"\n\n"+m2+"\n\n"+m3+"\n\n"+m4+"\n\n"+m5+"\n")
ofile.close()
command='exiftool -ImageDescription="'+s+'" static/MUK.jpg'
os.system(command)
command='exiftool -ImageDescription="'+s+'" static/muk.jpg'
os.system(command)


import json
import aioredis

async def get_redis_client():
    return aioredis.Redis(host='localhost', port=6379, db=0)

async def write_dict_to_redis(data: list):
    db: aioredis.Redis = await get_redis_client()

    for pk, football in enumerate(data):
        await db.set(pk, json.dumps(football))

async def get_all_date_from_redis():
    db: aioredis.Redis = await get_redis_client()

    finally_info = list()
    for key in await db.keys('*'):
        finally_info.append(await db.get(key))

    return finally_info


import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt

def get_P(DAY, data):
    P_zero = np.zeros((10,1))
    for idx, i in enumerate(range(-25,25,5)):
        if data[:,2][DAY] >  data[:,2][DAY+1]*i/100 and data[:,2][DAY] < data[:,2][DAY+1]*(i+5)/100:
            P_zero[idx] = 1
    return P_zero

def getProbabilities(data, DAY, preds=1, plot=False):
    prob = []
    for i in range(-25,25,5):
        prob_v = []
        for idx, v in enumerate(data[:,-2][:DAY]):
            if v >  data[:,2][idx+1]*i/100 and v < data[:,2][idx+1]*(i+5)/100:
                # print(v, data[:,2][idx]*i/100 , data[:,2][idx]*(i+5)/100, i)
                prob_v.append(abs(v))

        prob.append(sum(prob_v) / data[:,:DAY].shape[0])
    if plot:
        print(sum(prob))
        plt.bar( range(-100,100,5), prob)
        plt.show()

    Markov = np.array(prob).reshape(10,1).dot(np.array(prob).reshape(1,10))
    P_zero = get_P(DAY, data)
    Markov = np.linalg.matrix_power(Markov, preds)
    P_final = Markov.dot(P_zero)
    return P_final

data = [(i,pd.read_csv(f"../DATA/historical_prices/{i}", sep ="|")) for i in os.listdir("../DATA/historical_prices/")[1:25]]

for name, df in data:
    shift = df["OPEN"].shift(1)
    df["diff1"] =  df["OPEN"] - shift

    df["diff2"] =  df["diff1"].shift(-1)
    # df["diff3"] =  df["diff2"].shift(-1)

    df.dropna(inplace=True)

# data_t = data[0][1].values
# getProbabilities(data_t, 1000)
_ = plt.hist( data[0][1]["diff1"], bins=np.arange(-6, 6))
plt.show()
print("Done")
error = 0
for DAY in range(1000, 1500):
    for name, df in data:
        P_final = getProbabilities(df.values, DAY)
        P_true = get_P(DAY+30, df.values)
        P_final[np.where(P_final==np.max(P_final))] = 1
        P_final[np.where(P_final!=np.max(P_final))] = 0
        error += (P_true - P_final).T.dot((P_true - P_final))
        print(f"For {name} the probability is: \n{P_final} and {P_true}")

    print(f"Day={DAY}, error={error}")


from django.shortcuts import render,redirect
from .models import TodoItem
from todoApp.forms import TodoForm

# Create your views here.
def retrieve_view(request):
    todoitems = TodoItem.objects.all()
    context = {'todoitems':todoitems}
    return render(request,'todoApp/index.html',context)

def create_view(request):
    form = TodoForm()
    if request.method == 'POST':
        form = TodoForm(request.POST)
        if form.is_valid:
            form.save()
        return redirect('/')
    context = {'form':form }
    return render(request,'todoApp/create.html',context)

def update_view(request,id):
    todoitems = TodoItem.objects.get(id=id)

    form= TodoForm(instance=todoitems)
    if request.method == 'POST':
        form = TodoForm(request.POST,instance = todoitems)
        form.save()
        return redirect('/')
    return render(request,'todoApp/update.html',{'form':form})

def delete_view(request,id):
    todoitems = TodoItem.objects.get(id=id)
    if request.method == 'POST':
        todoitems.delete()
        return redirect('/')
    return render(request,'todoApp/delete.html',{'todoitems':todoitems})