'''
QR Code PDF Label Maker
v1.01 December 2021
Tom Howard

Updates:
Minor additions to comments.

Notes:
I had a bunch of 6-per page, 3 1/3" x 4" labels (Avery: 94215, 5164, and many others)
I also had a bunch of 30-per page, 1" x 2 5/8" labels (Avery: 5160, 8460 and others)

I wanted to create QR Codes to label moving boxes so I could use them with the 'QRbox' app for my phone.
That app allows you to bring your own codes

Requirements: qrcode, fpdf
Install with: pip install qrcode && pip install fpdf
'''

import qrcode
from fpdf import FPDF
import os

##################################################################################################
#                                                                                #
#         Make Changes to these variables below                                                  #
#                                                                                #
#         5164 is 6-per page, 3 1/3" x 4" labels (Avery: 94215, 5164, and many others)           #
#         5160 is 30-per page, 1" x 2 5/8" labels (Avery: 5160, 8460 and others)                 #
##################################################################################################
paper = 5164                # Options are 5164 (6-per page) or 5160 (30 per page, 10 unique qr codes duplicated in each column)
line1 = "PROJECT"           # Make sure your app of choice can handle this part of the QRCode before wasting a print.
line2 = "(555) 459-2222"    # I used my phone number in case the boxes were lost
num_sheets = 10             # The number of sheets you want to print
start_num = 1               # Start label count at this number
##################################################################################################
##################################################################################################

pdf = FPDF('P','mm','Letter')
pdf.set_font('Arial')
pdf.set_font_size(14)

def select_sheet():
    if paper == 5164:
        labels_per_sheet = 6
    elif paper == 5160:
        labels_per_sheet = 10
    return labels_per_sheet

def place_tag(page_count,count,code):
        cimg = (f'{count}.png')
        if paper == 5164:
            if page_count == 1:         # First row, top left
                x = -5                  # Starting at 0 was still too far to the right so I started at -5.
                y = 20                  # All in mm
            elif page_count == 2:       # First row top right
                x = 110
                y = 20
            elif page_count == 3:       # 2nd row left
                x = -5
                y = 110
            elif page_count == 4:       # 2nd row right
                x = 110
                y = 110
            elif page_count == 5:       # 3rd row left
                x = -5
                y = 200
            elif page_count == 6:       # 3rd row right
                x = 110
                y = 200

            pdf.image(cimg,x,y-14,60,60,'PNG')
            pdf.text(x+60,y,code)       # print line1 + current count number (actual text of QR Code)
            pdf.text(x+60,y+10,line2)   # print line2
        elif paper == 5160:
            columns = 3
            x = 2
            y = (page_count * 27) - 12

            for i in range(columns):
                pdf.image(cimg,x,y-6,20,20,'PNG')
                pdf.text(x+20,y,code)       # print line1 + current count number (actual text of QR Code)
                pdf.text(x+20,y+10,line2)   # print line2
                x +=75

def main():
    count = start_num
    labels_per_sheet = select_sheet()
    for i in range(num_sheets):
        pdf.add_page()
        page_count = 1

        for i in range(labels_per_sheet):
            code = (f'{line1}_{count:04d}')
            print(f'Generated: {code}')
            img = qrcode.make(code)
            img.save(f'{count}.png')
            place_tag(page_count,count,code)
            os.remove(f'{count}.png')           # remove QR code PNG so it doesn't clutter up your folder.
            count += 1
            page_count += 1
    outfile = (f'labels_{line1}_{start_num:04d}-{count-1:04d}.pdf')
    pdf.output(outfile, 'F')
    print(f'Completed generating {num_sheets} sheets with a total of {count-1} labels.\n File saved as: {outfile}.')

if __name__ == "__main__":
    main()


from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'users'

urlpatterns = [
	path('profilechange',views.profilechange,name='profilechange'),
	path('<str:userreq>',views.profile,name='profile'),
	path('<str:issueid>/<str:usertype>/reportuser',views.reportuser,name="reportuser"),
	path('<str:reporteduser>/<str:reportingadmin>/removereport',views.removereport,name="removereport"),
	path('',views.home,name = 'home'),
	path('<str:userreq>/deleteconfirm',views.deleteconfirm,name='deleteconfirm'),
	path('<str:userreq>/delete',views.delete,name="delete"),
	path('<str:userreq>/<str:itemreq>',views.profileredirect,name='profileredirect'),
	path('<str:reporteduser>/<str:reportingadmin>/checkuser',views.checkuser,name='checkuser'),
	path('<str:banneduser>/<str:banningadmin>/<str:reporttype>/banuser',views.banuser,name='banuser'),
]+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)


import subprocess
from config.settings import BASE_DIR, S_TOKEN
from telegram import Bot

def dumpDataScript():
    working_directory = BASE_DIR

    # command = 'python manage.py dumpdata > data.json'

    command = 'python manage.py dumpdata --exclude admin_interface --exclude contenttypes > fixtures/data.json'

    # Run the command and wait for it to finish
    subprocess.run(command, cwd=working_directory, shell=True)
    subprocess.run(command, shell=True)

    bot = Bot(token=S_TOKEN)
    bot.send_document(chat_id=779890968, document=open('data.json', 'rb'))

if __name__ == '__main__':
    dumpDataScript()


import time, traceback
import pandas as pd

from SeleniumCore import interaction, action

from Search_Register import Search_Register as SEARCH

from traceback_formatted import traceback_formatted

class Scheduling_Services:

    def __init__(self, driver):
        self.driver = driver
        self.scheduling_sheet = 'sheets/Scheduling_Services.xlsx'

    def scheduling_verify(self):

        driver = self.driver

        try:

            ## Attendances
            interaction(driver, 'click', '/html/body/div/div[4]/div[5]/i')

            attend_list = interaction(driver, 'selector', 'div[class="list_dados"]')

            attend_body = interaction(attend_list, 'selector_all', 'div[class="corpo"]')

            services = []

            for attendance in attend_body:

                time.sleep(1)

                customer_name = attendance.text.split('\n')[0]
                tags = attendance.text.split('\n')[2]

                if 'Agendar Visita' in tags:

                    interaction(driver, 'click', attendance)

                    customer_id = interaction(driver, 'text', '/html/body/div/div[6]/div[2]/div[4]/span')

                    notes = interaction(driver, 'text', '/html/body/div/div[6]/div[2]/div[12]/div/div[2]/div[1]').split(' # ')

                    subject = notes[0]
                    date = notes[1]
                    period = notes[2]

                    hours = period.split('-')

                    if hours[0] == '09:00' and hours[1] < '18:00':
                        description = f'*Até às {hours[1]}* '

                    if hours[0] > '09:00' and hours[1] == '18:00':
                        description = f'*Após às {hours[0]}* '

                    if hours[0] == '09:00' and hours[1] == '13:00':
                        description = '*Manhã* '

                    if hours[0] == '13:00' and hours[1] == '18:00':
                        description = '*Tarde* '

                    if hours[0] == '09:00' and hours[1] == '18:00':
                        description = ''

                    data = [int(customer_id), customer_name , int(subject), date, period, description]

                    services.append(data)

            df_services = pd.DataFrame(services, columns=['ID', 'Customer', 'Subject', 'Date', 'Period', 'Description'])

            df_services.to_excel(self.scheduling_sheet, index = False, header=True)

            return ['success', ' Customers with services to be schedule listed!']

        except:

            return ['error', traceback_formatted(traceback.format_exc())]

    def scheduling_execute(self):

        driver = self.driver

        try:

            ## Search
            interaction(driver, 'click', '/html/body/div[1]/div[3]/div/div[1]/div[2]/ul/li[1]/a')

            schedulings = pd.read_excel(self.scheduling_sheet)

            for _, row in schedulings.iterrows():

                customer_id = row['ID']
                name = row['Customer']
                subject = row['Subject']
                date = row['Date']
                period = row['Period'].split('-')
                description = row['Description']

                SEARCH.open_register_search(self, 'id', customer_id)

                ## Service and OS created
                if subject == 0:

                    ## OS
                    interaction(driver, 'click', '/html/body/form[2]/div[3]/ul/li[11]/a')

                    ## Description?
                    if not pd.isna(description):

                        ## Edit
                        interaction(driver, 'click', '/html/body/form/div[3]/div[11]/dl/div/div/div[2]/div[1]/button[3]')

                        time.sleep(1)

                        ## Description
                        message = '/html/body/form[3]/div[3]/div[1]/dl[28]/dd/textarea'
                        interaction(driver, 'click', message)
                        for _ in range(15): action(driver, 'up')
                        interaction(driver, 'click', message, description)

                        time.sleep(2)

                        ## Save
                        interaction(driver, 'click', '/html/body/form[2]/div[2]/button[2]')

                        action(driver, 'esc')

                    time.sleep(2)

                    ## Actions
                    actions_btn = interaction(driver, 'click', '/html/body/form[2]/div[3]/div[11]/dl/div/div/div[2]/div[1]/nav[3]/div/span')

                    time.sleep(1)

                    ## Schedule Button
                    interaction(driver, 'click', '/html/body/form[2]/div[3]/div[11]/dl/div/div/div[2]/div[1]/nav[3]/ul/li[4]')

                    ## Dates
                    date1 = '/html/body/form[3]/div[3]/div/dl[3]/dd/input'
                    interaction(driver, 'click', date1)
                    interaction(driver, 'send_keys', date1, date + ' 09:00:00')

                    date2 = '/html/body/form[3]/div[3]/div/dl[4]/dd/input'
                    interaction(driver, 'click', date2)
                    interaction(driver, 'send_keys', date2, date + ' 18:00:00')

                    ## Message
                    interaction(driver, 'send_keys', '/html/body/form[3]/div[3]/div/dl[6]/dd/textarea', 'Agendado.')

                    ## Collaborator
                    interaction(driver, 'send_keys', '/html/body/form[3]/div[3]/div/dl[7]/dd/input', '21')

                    action(driver, 'tab')

                    time.sleep(1)

                    ## Save
                    interaction(driver, 'selector', r'#\33 _form > div.tDiv > button:nth-child(1)')

                ## Create Service and OS
                else:

                    ## Service Tab
                    interaction(driver, 'click', '/html/body/form[2]/div[3]/ul/li[10]/a')

                    time.sleep(2)

                    ## New Service #--> CORRIGIR: ele pega o botão de criar novo cliente
                    interaction(driver, 'click --e', interaction(driver, 'selector', 'button[name="novo"]'))

                    time.sleep(1)

                    ## Subject
                    interaction(driver, 'send_keys', '/html/body/form[3]/div[3]/div[1]/dl[10]/dd/input', subject)

                    ## Department
                    interaction(driver, 'send_keys', '/html/body/form[3]/div[3]/div[1]/dl[18]/dd/input[1]', '2')

                    action(driver, 'tab')

                    ## Description
                    interaction(driver, 'send_keys', '/html/body/form[3]/div[3]/div[1]/dl[28]/dd/textarea', description)

                    time.sleep(2)

                    ## Save Service
                    interaction(driver, 'click', '/html/body/form[3]/div[2]/button[2]')

                    time.sleep(2)

                    ## OS Tab
                    interaction(driver, 'click', '/html/body/form[3]/div[2]/button[5]')

                    time.sleep(2)

                    ## Sector
                    interaction(driver, 'send_keys', '/html/body/form[4]/div[3]/div[1]/dl[17]/dd/input', '1')

                    ## Collaborator
                    interaction(driver, 'clear', '/html/body/form[4]/div[3]/div[1]/dl[18]/dd/input')
                    interaction(driver, 'send_keys', '/html/body/form[4]/div[3]/div[1]/dl[18]/dd/input', '21')

                    time.sleep(1)

                    ## DateTimes
                    interaction(driver, 'click', '/html/body/form[4]/div[3]/ul/li[3]/a')

                    time.sleep(1)

                    ## Initial DateTime
                    interaction(driver, 'click', '/html/body/form[4]/div[3]/div[3]/dl[4]/dd/input')
                    interaction(driver, 'send_keys', '/html/body/form[4]/div[3]/div[3]/dl[4]/dd/input', f'{date} {period[0]}:00')

                    time.sleep(2)

                    ## Final DateTime
                    interaction(driver, 'click', '/html/body/form[4]/div[3]/div[3]/dl[5]/dd/input')
                    interaction(driver, 'send_keys', '/html/body/form[4]/div[3]/div[3]/dl[5]/dd/input', f'{date} {period[1]}:00')

                    time.sleep(1)

                    ## Save OS
                    interaction(driver, 'click', '/html/body/form[4]/div[2]/button[2]')

                    time.sleep(2)

                    for _ in range(2):
                        action(driver, 'esc')

                action(driver, 'esc')

                ## Clear Input Name
                clear = interaction(driver, 'selector', r'#\31 _grid > div > div.sDiv > div > div:nth-child(2) > span > i')
                interaction(driver, 'click', clear)

            action(driver, 'esc')

            return ['success', ' Successfully services scheduled!']

        except:

            return ['error', traceback_formatted(traceback.format_exc())]


# -*- coding: utf-8 *-*
from django.contrib.auth.forms import UserCreationForm
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse

def register(request):
    if request.method == 'POST':  # Si ya se hizo submit del form
        form = UserCreationForm(request.POST)  # un enlace a la POST-data
        if form.is_valid(): # Si pasa la validación
#            new_user = form.save() # Se puede procesar los datos acá
            form.save()
            return HttpResponseRedirect(reverse('home'))  # Redirect
    else:
        form = UserCreationForm()  # un form sin enlazar para rellenar
    return TemplateResponse(
        request, "registration/register.html", {'form': form})


# Databricks notebook source
from pyspark.sql.functions import *
from pyspark.sql.types import *
import json

# COMMAND ----------

exampleJSON = """
{
  "a": "{\\"b\\":{\\"x\\":1,\\"y\\":{\\"z\\":2}}}"
}
"""

dfExampleJSON = spark.read.json(sc.parallelize([exampleJSON]))
display(dfExampleJSON)

# COMMAND ----------

def get_json_schema(df, jsonColumnName):
  firstRecordString = df.where(col(jsonColumnName).isNotNull()).first()[jsonColumnName]
  firstRecordRDD = sc.parallelize([firstRecordString])
  dfJSON = spark.read.json(firstRecordRDD)
  schema = dfJSON.schema.json()
  dictionary = json.loads(schema)

  return StructType.fromJson(dictionary)

# COMMAND ----------

schema = get_json_schema(dfExampleJSON, "a")
dfExampleStruct = dfExampleJSON.withColumn("a", from_json("a", schema))

display(dfExampleStruct)


"""OUI API module. Implements OUI sync logic"""
__author__ = "Zacharias El Banna"
__add_globals__ = lambda x: globals().update(x)
__type__ = "INFO"

from urllib.request import urlopen, Request
from urllib.error import HTTPError

#
#
def list(aRT, aArgs):
 """Function returns a list of OUI:s

 Args:

 Output:
  - data
 """
 ret = {}
 with aRT.db as db:
  db.query("SELECT LPAD(HEX(oui),6,0) AS oui, company FROM oui")
  ret['data'] = db.get_rows()
 return ret

def info(aRT, aArgs):
 """ Function retrieves OUI info from database

 Args:
  - oui (required). string, e.g. "AABB00"

 Output:
  - status
  - data
 """
 ret = {}
 try:
  oui = int(aArgs['oui'].translate(str.maketrans({":":"","-":""}))[:6],16)
  with aRT.db as db:
   ret['data']= db.get_row() if db.query("SELECT LPAD(HEX(oui),6,0) AS oui, company FROM oui WHERE oui = %s"%oui) else {'oui':'NOT_FOUND','company':'NOT_FOUND'}
   ret['status'] = 'OK' if ret['data']['oui'] != 'NOT_FOUND' else 'NOT_FOUND'
 except Exception as e:
  ret = {'status':'NOT_OK','info':repr(e),'data':{'oui':None,'company':''}}
 return ret

#########################################################################3
#
#
def status(aRT, aArgs):
 """Function docstring for status. No OP

 Args:
  - type (required)

 Output:
  - data
 """
 return {'data':None, 'status':'OK' }

#
#
def sync(aRT, aArgs):
 """ Function fetch and populate OUI table

 Args:
  - id (required). Server id on master node
  - clear (optional). Bool. Clear database before populating if true. Defaults to false

 Output:
  - code. (error code, optional)
  - output. (output from command)
  - status. (operation result)
 """
 ret = {'output':0,'status':'NOT_OK'}
 try:
  req = Request(aRT.config['services']['oui']['location'])
  sock = urlopen(req, timeout = 120)
  data = sock.read().decode()
  sock.close()
 except HTTPError as h:
  ret.update({'status':'HTTPError', 'code':h.code, 'info':dict(h.info())})
 except Exception as e:
  ret.update({ 'status':type(e).__name__, 'code':590, 'error':repr(e)})
 else:
  with aRT.db as db:
   if aArgs.get('clear') is True:
    db.execute("TRUNCATE oui")
   for line in data.split('\n'):
    if line:
     parts = line.split()
     if len(parts) > 3 and parts[1] == '(base' and parts[2] == '16)':
      oui = int(parts[0].upper(),16)
      company = (" ".join(parts[3:]).replace("'",''))[0:60]
      ret['output'] += db.execute("INSERT INTO oui(oui,company) VALUES(%d,'%s') ON DUPLICATE KEY UPDATE company = '%s'"%(oui,company,company))
   ret['status'] = 'OK'
 return ret

#
#
def restart(aRT, aArgs):
 """Function provides restart capabilities of service

 Args:

 Output:
  - code
  - output
  - result 'OK'/'NOT_OK'
 """
 return {'status':'OK','code':0,'output':""}

#
#
def parameters(aRT, aArgs):
 """ Function provides parameter mapping of anticipated config vs actual

 Args:

 Output:
  - status
  - parameters
 """
 settings = aRT.config['services'].get('oui',{})
 params = ['location']
 return {'status':'OK' if all(p in settings for p in params) else 'NOT_OK','parameters':{p:settings.get(p) for p in params}}

#
#
def start(aRT, aArgs):
 """ Function provides start behavior

 Args:

 Output:
  - status
 """
 return {'status':'NO OP'}

#
#
def stop(aRT, aArgs):
 """ Function provides stop behavior

 Args:

 Output:
  - status
 """
 return {'status':'NO OP'}

#
#
def close(aRT, aArgs):
 """ Function provides closing behavior, wrapping up data and file handlers before closing

 Args:

 Output:
  - status
 """
 return {'status':'NO OP'}


def getMax(inList, tgList):
    res = [0] * len(tgList)
    for i in range(len(inList)):
        befNum = inList[i]
        for j in range(2):
            res[i+j] = max(res[i+j], befNum + tgList[i+j])
    return res

def solution(triangle):
    answer = 0
    for i in range(len(triangle)):
        garo = triangle[i]
        if i == 0:
            res = [garo[0]]
        else:
            res = getMax(res, garo)
    answer = max(res)
    return answer


from flask import Flask, Response
from opentelemetry import metrics, trace
from opentelemetry.sdk.trace import TracerProvider
import logging, speedtest, threading, redis, time, os

provider = TracerProvider()
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
app = Flask(__name__)

r = redis.Redis(host='localhost', port=6379, db=0, charset="utf-8", decode_responses=True)

## Logging configuration
FORMAT = ('%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] [trace_id=%(otelTraceID)s span_id=%(otelSpanID)s resource.service.name=%(otelServiceName)s trace_sampled=%(otelTraceSampled)s] - %(message)s')

werkzeug = logging.getLogger('werkzeug')
if len(werkzeug.handlers) == 1:
    formatter = logging.Formatter(FORMAT)
    werkzeug.handlers[0].setFormatter(formatter)

if (os.environ.get('LOG_TO_FILE') == 'true'):
    logging.basicConfig(filename="/code/out.log",
					format=FORMAT,
					filemode='w')
    print('logging to file')
else:
    logging.basicConfig(format=FORMAT)

log = logging.getLogger(__name__)
log.level = logging.INFO

### Metric setup

meter = metrics.get_meter("speedtest")

upload_histogram = meter.create_histogram(
    name="speedtest.upload.histogram",
    description="TODO",
    unit="",
    )

download_histogram = meter.create_histogram(
    name="speedtest.download.histogram",
    description="TODO",
    unit="",
    )
###

def measure_speeds():
    while True:
        with tracer.start_as_current_span("get_speed"):
            span = trace.get_current_span()
            st = speedtest.Speedtest()
            best_serv=st.get_best_server()
            log.info(best_serv)
            download=round((st.download()*0.000001),2)
            upload=round((st.upload()*0.000001),2)
            span.add_event( "log", {
                "speed.upload": upload,
                "speed.download": download,
            })
            r.set('upload', upload)
            r.set('download', download)
            download_histogram.record(download, attributes={"attr1": "value1"})
            upload_histogram.record(upload, attributes={"attr1": "value1"})
        time.sleep(300)

def start_scheduling():
    speedtest_thread = threading.Thread(target=measure_speeds, name="speedtester")
    speedtest_thread.start()

start_scheduling()

###### Endpoints

@app.route("/upload")
def upload():
    upload = str(r.get('upload'))
    log.info('Upload route hit: ' + upload + "MB/s")
    return Response(upload, status=200)

@app.route("/download")
def download():
    download = str(r.get('download'))
    log.info('Download route hit: ' + download + "MB/s")
    return Response(download, status=200)

@app.route("/best_serv")
def best_serv():
    best_serv = r.get('best_serv')
    log.info('best server details: ' + best_serv)
    return Response(best_serv, status=200)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8888)


#Test while

opcion = 0

while opcion <10:

    opcion += 1
    if opcion == 5:
        print('Estas en el ', opcion)
        continue
    print(opcion)

    if opcion == 7:
        break

else:
    print('Termino el siclo while')


import numpy as np
import os

import time
import data_utils

def load_calibration_file(calibration_file):
    with open(calibration_file, 'r') as fh:

        mapping = {}

        for line in fh.readlines():
            parts = line.split()
            path = parts[0].split(".")[0]
            energy = parts[-1]
            mapping[path] = float(energy)

        return mapping

class DataLoader():

    def __init__(self, use_fitted, batch_size=1024):
        """
        Helper class used to load various datasets.
        """
        self.batch_size = batch_size
        self.use_fitted = use_fitted

        if self.use_fitted:
            raise Exception("using fitted parameters is not supported right now")

    def load_gdb8(self,
        data_dir,
        calibration_file=None,
        ff_train_dirs=None):

        gdb_files = [
            os.path.join(data_dir, "ani_gdb_s01.h5"),
            os.path.join(data_dir, "ani_gdb_s02.h5"),
            os.path.join(data_dir, "ani_gdb_s03.h5"),
            # os.path.join(data_dir, "ani_gdb_s04.h5"),
            # os.path.join(data_dir, "ani_gdb_s05.h5"),
            # os.path.join(data_dir, "ani_gdb_s06.h5"),
            # os.path.join(data_dir, "ani_gdb_s07.h5"),
            # os.path.join(data_dir, "ani_gdb_s08.h5"),
        ]

        if calibration_file:
            cal_map = load_calibration_file(calibration_file)
        else:
            cal_map = None

        Xs, ys = data_utils.load_hdf5_files(
            gdb_files,
            calibration_map=cal_map,
            use_fitted=self.use_fitted)

        if ff_train_dirs:
            for train_dir in ff_train_dirs:
                ff_train_Xs, ff_train_ys, _ = data_utils.load_ff_files(train_dir, use_fitted=self.use_fitted)
                Xs.extend(ff_train_Xs)
                ys.extend(ff_train_ys)

        return Xs, ys

    def load_gdb11(self,
        data_dir,
        calibration_file=None,
        use_fitted=False):

        if calibration_file:
            cal_map = load_calibration_file(calibration_file)
        else:
            cal_map = None

        X_gdb11, y_gdb11 = data_utils.load_hdf5_files([
            os.path.join(data_dir, "ani1_gdb10_ts.h5"),
        ],
        calibration_map=cal_map,
        use_fitted=self.use_fitted)

        return X_gdb11, y_gdb11

    def load_ff(self, data_dir):
        ff_test_Xs, ff_test_ys, ff_groups = data_utils.load_ff_files(data_dir, use_fitted=self.use_fitted)

        return ff_test_Xs, ff_test_ys, ff_groups


#!/usr/bin/env python

"""The setup script."""

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = ['Click>=7.0', ]

test_requirements = ['pytest>=3', ]

setup(
    author="Carsten Stahl",
    author_email='carstenstahl122@gmail.com',
    python_requires='>=3.6',
    classifiers=[
        'Development Status :: 2 - Pre-Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    description="Just a practice package, that bundles all the basic knowledge of algorithms and data-structures.",
    entry_points={
        'console_scripts': [
            'the_simple_package=the_simple_package.cli:main',
        ],
    },
    install_requires=requirements,
    license="MIT license",
    long_description=readme + '\n\n' + history,
    include_package_data=True,
    keywords='the_simple_package',
    name='the_simple_package',
    packages=find_packages(include=['the_simple_package', 'the_simple_package.*']),
    test_suite='tests',
    tests_require=test_requirements,
    url='https://github.com/Carsten134/the_simple_package',
    version='0.1.0',
    zip_safe=False,
)


from django.urls import path,include
from lokalhood_api import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('user', views.UserProfileViewSet)
router.register('shop', views.ShopViewSet)
router.register('request', views.RequestViewSet)

urlpatterns = [
    path('login/', views.UserLoginAPIView.as_view()),
    path('', include(router.urls))
]


#--coding:utf-8--

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

# 相当于开辟了2个新链表
class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        dummy_1, dummy_2 = ListNode(-1), ListNode(-1)
        tmp_d1, tmp_d2 = dummy_1, dummy_2
        while head:
            if head.val < x:
                tmp_d1.next = head
                tmp_d1 = tmp_d1.next
            else:
                tmp_d2.next = head
                tmp_d2 = tmp_d2.next
            head = head.next
        tmp_d2.next = None
        tmp_d1.next = dummy_2.next
        return dummy_1.next

# 不开辟新链表的做法
class Solution:
    def partition(self, head: ListNode, x: int) -> ListNode:
        dummy = ListNode(-1, head)
        back = dummy
        cur = head
        while cur and cur.val<x:
            back = cur
            cur = cur.next
        if cur == None:
            return head
        new_back = cur
        new_cur = cur.next
        while new_cur:
            if new_cur.val<x:
                new_back.next = new_cur.next
                # 把当前节点插到前面末尾
                new_cur.next = cur
                back.next = new_cur
                back = new_cur
                new_cur = new_back.next
            else:
                new_back = new_cur
                new_cur = new_cur.next
        return dummy.next


"""Given an array of integers arr, return true if the number of occurrences of each value in the array is unique,
or false otherwise.
eg:
Input: arr = [1,2,2,1,1,3]
Output: true
Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.

"""
arr = list(map(int,input().split()))
nums_dict = {}
for num in arr:
    if num not in nums_dict:
        nums_dict[num] = 1
    else:
        nums_dict[num] += 1
if (len(nums_dict)) != (len(set(nums_dict.values()))):
    print(False)
else:
    print(True)


#!/usr/bin/env python
#coding:utf8

#celery配置文件

BROKER_URL = 'redis://taiops@127.0.0.1:6379/9'
CELERY_RESULT_BACKEND = 'redis://taiops@127.0.0.1:6379/10'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT=['json']
CELERY_TIMEZONE = 'Europe/Oslo'
CELERY_ENABLE_UTC = True

CELERY_ANNOTATIONS = {
    'app.worker.tasks.asset_import': {'rate_limit': '1/m'},
    'app.worker.tasks.site_crawler':{'rate_limit':'4/m'},
    'app.worker.tasks.port_crawler':{'rate_limit':'1/m'},
}

CELERY_IMPORTS = ("app.worker.tasks")


import random
import string

from Words import words

def valid(Words):
    word = random.choice(Words) # randomly chooses a word from Words.py
    while '-' in word or ' ' in word: # While condition to take out words with space and dash
        word = random.choice(Words)
    return word.upper()

def hangman():
    word = valid(words)
    word_letters = set(word) # letters in word
    alphabet = set(string.ascii_uppercase)
    used_letters = set() # what the user guessed

    lives = 6

    # getting user input
    while len(word_letters) > 0 and lives > 0:

        # Display used letters
        print('You have', lives, 'lives left and you have used the letters: ', ' '.join(used_letters))

        # what current word is (ie W - R D)
        word_list = [letter if letter in used_letters else '-' for letter in word]
        print('Current word: ', ' '.join(word_list))

        user_letter = input('Guess a letter: ').upper()
        print('---------------------------------------------------------')
        if user_letter in alphabet - used_letters:
            used_letters.add(user_letter)
            if user_letter in word_letters:
                word_letters.remove(user_letter)

            else:
                lives = lives - 1 # Takes away one life from a failed attempt
                print('Letter is not in word. Try again.')

        elif user_letter in used_letters:
            print("Already guessed the letter. Type a letter you did not used.")

        else:
            print("Invalid character. Try again.")

    # gets here when len(word_letters == 0 or when lives == 0
    if lives == 0:
        print('No more lives, you lose')
        print('Your word:',word,)
    else:
        print('You have guessed the word',word,)
        print('You won')

hangman()


import tkinter as tk

class TampilanAntarmuka:
    def _init_(self) -> None:
        self.root = tk.Tk()

        self.title_program = tk.Label(
            self.root, text="Sistem Deteksi Hoax", font=("Arial", 28)
        )
        self.title_program.pack()

        self.input_label = tk.Label(
            self.root, text="silahkan masukan judul berita anda"
        )
        self.input_label.pack()
        self.input_judul = tk.Entry(self.root)
        self.input_judul.pack()

        self.label_hasil = tk.Label(self.root, text="berita anda adalah")
        self.label_hasil.pack()

        self.cek_button = tk.Button(self.root, text="Cek")
        self.cek_button.pack()
        self.reset_button = tk.Button(self.root, text="Reset")
        self.reset_button.pack()

        self.root.mainloop()

    def cek_judul(self):
        print(self.input_judul.get())

def main():
    TampilanAntarmuka()

if __name__ == "__main__":
    main()


from django.urls import path
from . import views

app_name='student'

urlpatterns = [
    path('course/enroll/',views.student_enroll_view,name='student_enroll_view'),
    path('course/details/<slug:slug>/',views.student_course_detail_view,name='student_course_detail_view'),
    path('module/details/<int:course_pk>/<slug:course_slug>/module/<int:order>/<slug:slug>/',views.student_module_detail_view,name='student_module_detail_view'),
    path('course/bookmark/',views.course_bookmark_view,name='course_bookmark_view'),
    path('module/completed/',views.module_complete_view,name='module_complete_view'),
]


# 짜증나네;; 내가 이해한게 맞는지 아닌지 몰겄ㄸ음;;

import sys

def dp(answer,true,party,n,m,now):
    if(now == m):
        return 0
    tmp1,tmp2 = 0,0
    if(same(true,party[now])): # 없다면 구라가능
        tmp1 = 1 + dp(answer,true,party,n,m,now+1)
    else:
        tmp = true[:] # 얕은 복사
        true.extend(party[now])
        true = list(set(true))
        true.sort()
        tmp1 = dp(answer,true,party,n,m,now+1)
        # true = tmp[:]

    return tmp1

def same(l,s): # 항상 소트된 상태로 들어온다고 가정
    for i in range(len(l)):
        for j in range(len(s)):
            if(l[i] == s[j]):
                return False
    return True

n,m = input().split(" ")
n = int(n)
m = int(m)
true = list(map(int, sys.stdin.readline().split()))
true = true[1:]
party = [0]*m
for i in range(m):
    a  = list(map(int, sys.stdin.readline().split()))
    party[i] = a[1:]

answer = []
ans = dp(answer,true,party,n,m,0)
print(ans)


from App.ProblemBuilder.Region import Region
from App.ProblemBuilder.Boundary import Boundary
from App.ProblemBuilder.Cell import Cell
from App.ProblemBuilder.CellBoundary import CellBoundary
from App.THSolver.FlowChannel import FlowChannel
from Materials.MaterialBase import MaterialBase

class Problem:

    regions: list[Region]
    boundaries: list[Boundary]
    cells: list[Cell]
    cellBoundaries: dict

    numOfProcesses: int
    numOfParticles: int
    inactiveBatches: int
    activeBatches: int

    flowChannels: list[FlowChannel]

    def __init__(self):
        self.numOfProcesses = 1
        self.numOfParticles = 1000
        self.inactiveBatches = 1
        self.activeBatches = 1

        self.regions = []
        self.boundaries = []
        self.cells = []
        self.flowChannels = []
        self.cellBoundaries = {}

    def GetRegion(self, name: str) -> Region:
        for region in self.regions:
            if(region.name == name):
                return region

        return None

    def GetBoundary(self, name: str) -> Boundary:
        for boundary in self.boundaries:
            if(boundary.name == name):
                return boundary

        return None

    def GetCell(self, id: int) -> Cell:
        for cell in self.cells:
            if(cell.id == id):
                return cell

    def SetBatches(self, inactiveBatches: int, activeBatches: int):
        self.inactiveBatches = inactiveBatches
        self.activeBatches = activeBatches

    def SetConstantTempThermalBC(self, name: str, T: float):
        boundary = self.GetBoundary(name)

        for cellBoundary in boundary.cellBoundaries:
            cellBoundary.SetConstantTempThermalBC(T)

    def SetMaterial(self, name: str, material: MaterialBase):
        region = self.GetRegion(name)

        for cell in region.cells:
            cell.material = material

    def InsertFlowChannel(self, regionName: str, boundaryName: str, flowChannel: FlowChannel):
        flowChannel.regionName = regionName

        region = self.GetRegion(regionName)
        boundary = self.GetBoundary(boundaryName)

        for cell in region.cells:
            for cellBoundary in cell.cellBoundaries:
                cellBoundary.SetAdiabaticThermalBC()

        for cellBoundary in boundary.cellBoundaries:
            for cell in cellBoundary.cells:
                if(cell not in region.cells):
                    cellBoundary.SetConvectionToFlowChannelThermalBC(cell, flowChannel)

        self.flowChannels.append(flowChannel)


#!/usr/bin/python3
# ==============================================================
# Elegant region style
# Now can we have a more brilliant way to represent the point cloud
# ==============================================================
import numpy as np
import triangle
import sys

sys.path.append('/home/andy/Documents/gitHub/DashCam_python/module')  # use the module under 'module'
import file_process
import google_parse
import glumpy_setting

sleIndex = 3
createSV = True
needMatchInfo3d = True
needVisual = True
needGround = True
mapType = '_trajectory'

# Create dashCamFileProcess and load 50 top Dashcam
dashCamFileProcess = file_process.DashCamFileProcessor()
"""
Process the select file
"""
for fileIndex in range(sleIndex, sleIndex+1):
    fileID = str(dashCamFileProcess.list50[fileIndex][1])
    print(fileID, fileIndex)

    """
    Create the global metric point cloud,
    then set the region anchor
    """
    # anchor is sorted and pick the first one
    # now load the anchor that had been stored
    anchor = dashCamFileProcess.get_trajectory_anchor(fileID)
    fileID += mapType
    sv3DRegion = google_parse.StreetView3DRegion(fileID)
    sv3DRegion.init_region(anchor=anchor)
    # why QQ?
    # because the map didn't query the anchor file
    if sv3DRegion.QQ:
        continue

    if createSV:
        index = 0
        sv3DRegion.create_topoloy()
        sv3DRegion.create_single()
        #sv3DRegion.create_region()
        for sv3D_id, sv3D in sorted(sv3DRegion.sv3D_Dict.items()):
            sv3D.apply_global_adjustment()  # Absolute position on earth (lat, lon, yaw)
            sv3D.apply_local_adjustment()  # Relative position according to anchor (anchor's lat,lon)

            if index == 0:
                 data = sv3D.ptCLoudData
                 dataGnd = sv3D.ptCLoudDataGnd
            else:
                 data = np.concatenate((data, sv3D.ptCLoudData), axis=0)
                 dataGnd = np.concatenate((data, sv3D.ptCLoudDataGnd), axis=0)

            index += 1

        programSV3DRegion = glumpy_setting.ProgramSV3DRegion(
            data=data, name='ProgramSV3DRegion',
            anchor_matrix=sv3DRegion.anchorMatrix, anchor_yaw=sv3DRegion.anchorYaw)
        programSV3DRegionGnd = glumpy_setting.ProgramSV3DRegion(
            data=dataGnd, name='ProgramSV3DRegion',
            anchor_matrix=sv3DRegion.anchorMatrix, anchor_yaw=sv3DRegion.anchorYaw)
        programSV3DTopology = glumpy_setting.ProgramSV3DTopology(
            data=sv3DRegion.topologyData, name='ProgramSV3DRegion',
            anchor_matrix=sv3DRegion.anchorMatrix, anchor_yaw=sv3DRegion.anchorYaw)

        if needMatchInfo3d:
            # This rotate the SV3D for matching x-y plane
            # Actually we build the point cloud on x-y plane
            # So we just multiply the inverse matrix of anchor
            programSV3DRegion.apply_anchor_flip()
            programSV3DRegionGnd.apply_anchor_flip()
            programSV3DTopology.apply_anchor_flip()

"""
For Visualize
"""
if needVisual:
    gpyWindow = glumpy_setting.GpyWindow()

    if createSV:
        gpyWindow.add_program(programSV3DRegion)
        gpyWindow.add_program(programSV3DTopology)
        if needGround:
            gpyWindow.add_program(programSV3DRegionGnd)

    programAxis = glumpy_setting.ProgramAxis(line_length=5)
    gpyWindow.add_program(programAxis)

    gpyWindow.run()


from django.urls import path
from . import views

urlpatterns = [
    path('',views.index, name='index' ),
    path('home',views.home, name='home' ),
    path('signup',views.signup, name='signup' ),
    path('user_login',views.user_login, name='user_login'),
    path('signin',views.signin, name='signin' ),
    path('withdraw',views.withdraw, name='withdraw' ),
    path('deposit',views.deposit, name='deposit' ),
    path('transfer',views.transfer, name='transfer' ),
    path('dashboard',views.dashboard, name='dashboard' ),
    path('airtime',views.airtime, name='airtime' ),
    path('history',views.history, name='history' ),
    path('electricity',views.electricity, name='electricity' ),
    path('admindashboard/', views.admin_dashboard, name='admin_dashboard'),
    path('admindash',views.admindash, name='admindash' ),
    path('suspend_user/<int:user_id>/', views.suspend_user, name='suspend_user'),
    path('unsuspend_user/<int:user_id>/', views.unsuspend_user, name='unsuspend_user'),
    path('loan/', views.apply_loan, name='loan'),
    path('loan-requests/', views.loan_requests, name='loan_requests'),
    path('approve-loan/<int:loan_id>/', views.approve_loan, name='approve_loan'),
    path('reject-loan/<int:loan_id>/', views.reject_loan, name='reject_loan'),
    path('loans/pending-repayment/', views.pending_repayment, name='pending_repayment'),
    path('repay-loan/<int:loan_id>/', views.repay_loan, name='repay_loan'),
    path('base', views.base, name='base'),
    path('more_services', views.more_services, name='more_services'),
    path('userprofile', views.userprofile, name='userprofile'),
    # path('transaction_pin/', views.transaction_pin, name='transaction_pin'),
    path('set-transaction-pin/', views.set_transaction_pin, name='set_transaction_pin'),
    path('reset-transaction-pin/', views.reset_transaction_pin, name='reset_transaction_pin'),
    path('contactus',views.contact, name='contactus' ),
    path('success',views.success, name='success' ),
]


content = ''
suffix = '.ht'
if suffix == '.htm':
    content = 'text/html'
elif suffix == '.jpg':
    content = 'image/jpeg'
elif suffix == '.png':
    content = 'image/png'
else:
    content = 'none'
    raise RuntimeError('Содержимое неизвестного типа')

print(content)


#!/usr/bin/env python2.7
from __future__ import division

import re
import sys
import os.path
import argparse
from datetime import datetime

sink_id = 1

# Firefly addresses
addr_id_map = {
    "f7:9c":  1, "d9:76":  2, "f3:84":  3, "f3:ee":  4, "f7:92":  5,
    "f3:9a":  6, "de:21":  7, "f2:a1":  8, "d8:b5":  9, "f2:1e": 10,
    "d9:5f": 11, "f2:33": 12, "de:0c": 13, "f2:0e": 14, "d9:49": 15,
    "f3:dc": 16, "d9:23": 17, "f3:8b": 18, "f3:c2": 19, "f3:b7": 20,
    "de:e4": 21, "f3:88": 22, "f7:9a": 23, "f7:e7": 24, "f2:85": 25,
    "f2:27": 26, "f2:64": 27, "f3:d3": 28, "f3:8d": 29, "f7:e1": 30,
    "de:af": 31, "f2:91": 32, "f2:d7": 33, "f3:a3": 34, "f2:d9": 35,
    "d9:9f": 36, "f3:90": 50, "f2:3d": 51, "f7:ab": 52, "f7:c9": 53,
    "f2:6c": 54, "f2:fc": 56, "f1:f6": 57, "f3:cf": 62, "f3:c3": 63,
    "f7:d6": 64, "f7:b6": 65, "f7:b7": 70, "f3:f3": 71, "f1:f3": 72,
    "f2:48": 73, "f3:db": 74, "f3:fa": 75, "f3:83": 76, "f2:b4": 77
}

def parse_file(log_file, testbed=False):
    # Print some basic information for the user
    print(f"Logfile: {log_file}")
    print(f"{'Cooja simulation' if not testbed else 'Testbed experiment'}")

    # Create CSV output files
    fpath = os.path.dirname(log_file)
    fname_common = os.path.splitext(os.path.basename(log_file))[0]
    frecv_name = os.path.join(fpath, f"{fname_common}-recv.csv")
    fsent_name = os.path.join(fpath, f"{fname_common}-sent.csv")
    frecv = open(frecv_name, 'w')
    fsent = open(fsent_name, 'w')

    # Write CSV headers
    frecv.write("time\tdest\tsrc\tseqn\thops\n")
    fsent.write("time\tdest\tsrc\tseqn\n")

    if testbed:
        # Regex for testbed experiments
        testbed_record_pattern = r"\[(?P<time>.{23})\] INFO:firefly\.(?P<self_id>\d+): \d+\.firefly < b"
        regex_node = re.compile(r"{}'Rime configured with address "
                                r"(?P<src1>\d+).(?P<src2>\d+)'".format(testbed_record_pattern))
        regex_recv = re.compile(r"{}'App: Recv from (?P<src1>\w+):(?P<src2>\w+) "
                                r"seqn (?P<seqn>\d+) hops (?P<hops>\d+)'".format(testbed_record_pattern))
        regex_sent = re.compile(r"{}'App: Send seqn (?P<seqn>\d+)'".format(
            testbed_record_pattern))
    else:
        # Regular expressions --- different for COOJA w/o GUI
        record_pattern = r"(?P<time>[\w:.]+)\s+ID:(?P<self_id>\d+)\s+"
        regex_node = re.compile(r"{}Rime started with address "
                                r"(?P<src1>\d+).(?P<src2>\d+)".format(record_pattern))
        regex_recv = re.compile(r"{}App: Recv from (?P<src1>\w+):(?P<src2>\w+) "
                                r"seqn (?P<seqn>\d+) hops (?P<hops>\d+)".format(record_pattern))
        regex_sent = re.compile(r"{}App: Send seqn (?P<seqn>\d+)".format(
            record_pattern))

    # Node list and dictionaries for later processing
    nodes = []
    drecv = {}
    dsent = {}

    # Parse log file and add data to CSV files
    with open(log_file, 'r') as f:
        for line in f:
            # Node boot
            m = regex_node.match(line)
            if m:
                # Get dictionary with data
                d = m.groupdict()
                node_id = int(d["self_id"])
                # Save data in the nodes list
                if node_id not in nodes:
                    nodes.append(node_id)
                # Continue with the following line
                continue

            # RECV
            m = regex_recv.match(line)
            if m:
                # Get dictionary with data
                d = m.groupdict()
                if testbed:
                    ts = datetime.strptime(d["time"], '%Y-%m-%d %H:%M:%S,%f')
                    ts = ts.timestamp()
                    src_addr = "{}:{}".format(d["src1"], d["src2"])
                    try:
                        src = addr_id_map[src_addr]
                    except KeyError as e:
                        print("KeyError Exception: key {} not found in "
                              "addr_id_map".format(src_addr))

                else:
                    ts = d["time"]
                    # Discard second byte and convert to decimal
                    src = int(d["src1"], 16)
                dest = int(d["self_id"])
                seqn = int(d["seqn"])
                hops = int(d["hops"])
                # Write to CSV file
                frecv.write("{}\t{}\t{}\t{}\t{}\n".format(
                    ts, dest, src, seqn, hops))
                # Save data in the drecv dictionary for later processing
                if dest == sink_id:
                    drecv.setdefault(src, {})[seqn] = ts
                # Continue with the following line
                continue

            # SENT
            m = regex_sent.match(line)
            if m:
                d = m.groupdict()
                if testbed:
                    ts = datetime.strptime(d["time"], '%Y-%m-%d %H:%M:%S,%f')
                    ts = ts.timestamp()
                else:
                    ts = d["time"]
                src = int(d["self_id"])
                dest = 1
                seqn = int(d["seqn"])
                # Write to CSV file
                fsent.write("{}\t{}\t{}\t{}\n".format(ts, dest, src, seqn))
                # Save data in the dsent dictionary
                dsent.setdefault(src, {})[seqn] = ts

    # Analyze dictionaries and print some stats
    # Overall number of packets sent / received
    tsent = 0
    trecv = 0

    # Stop if there are no sent or received messages
    if not dsent:
        print("No sent messages could be parsed. Exiting...")
        sys.exit(1)
    if not drecv:
        print("No received messages could be parsed. Exiting...")
        sys.exit(1)

    # Nodes that did not manage to send data
    fails = []
    for node_id in sorted(nodes):
        if node_id == sink_id:
            continue
        if node_id not in dsent.keys():
            fails.append(node_id)
    if fails:
        print("----- WARNING -----")
        for node_id in fails:
            print("Warning: node {} did not send any data.".format(node_id))
        print("")  # To separate clearly from the following set of prints

    # Print node stats
    print("\n########## Node Statistics ##########\n")
    for node in sorted(dsent.keys()):
        nsent = len(dsent[node])
        nrecv = 0
        if node in drecv.keys():
            nrecv = len(drecv[node])

        pdr = 100 * nrecv / nsent
        print("Node {}: TX Packets = {}, RX Packets = {}, PDR = {:.2f}%, PLR = {:.2f}%".format(
            node, nsent, nrecv, pdr, 100 - pdr))

        # Update overall packets sent / received
        tsent += nsent
        trecv += nrecv

    # Print overall stats
    print("\n########## Overall Statistics ##########\n")
    print("Total Number of Packets Sent: {}".format(tsent))
    print("Total Number of Packets Received: {}".format(trecv))
    opdr = 100 * trecv / tsent
    print("Overall PDR = {:.2f}%".format(opdr))
    print("Overall PLR = {:.2f}%\n".format(100 - opdr))

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('logfile', action="store", type=str,
                        help="data collection logfile to be parsed and analyzed.")
    parser.add_argument('-t', '--testbed', action='store_true',
                        help="flag for testbed experiments")
    return parser.parse_args()

if __name__ == '__main__':
    args = parse_args()
    print(args)

    if not args.logfile:
        print("Log file needs to be specified as 1st positional argument.")
    if not os.path.exists(args.logfile):
        print("The logfile argument {} does not exist.".format(args.logfile))
        sys.exit(1)
    if not os.path.isfile(args.logfile):
        print("The logfile argument {} is not a file.".format(args.logfile))
        sys.exit(1)

    # Parse log file, create CSV files, and print some stats
    parse_file(args.logfile, testbed=args.testbed)


# https://leetcode-cn.com/problems/remove-element/

class Solution:
    def removeElement(self, nums, val):
        """
        :type nums: List[int]
        :type val: int
        :rtype: int
        """
        while True:
            try:
                nums.remove(val)
            except:
                break
        return len(nums)


import os
from shutil import copytree

from pydantic import DirectoryPath

from hexagon.actions import external
from hexagon.domain.tool import ActionTool, ToolType
from hexagon.runtime.singletons import configuration
from hexagon.support.input.args import ToolArgs, PositionalArg, Arg, OptionalArg
from hexagon.support.output.printer import log

class Args(ToolArgs):
    action: PositionalArg[str] = Arg(
        None, prompt_message=_("action.actions.internal.create_new_tool.choose_action")
    )
    type: OptionalArg[ToolType] = Arg(
        None, prompt_message=_("action.actions.internal.create_new_tool.choose_type")
    )
    name: OptionalArg[str] = Arg(
        None, prompt_message=_("action.actions.internal.create_new_tool.input_name")
    )
    alias: OptionalArg[str] = Arg(
        None, prompt_message=_("action.actions.internal.create_new_tool.input_alias")
    )
    long_name: OptionalArg[str] = Arg(
        None,
        prompt_message=_("action.actions.internal.create_new_tool.input_long_name"),
    )
    description: OptionalArg[str] = Arg(
        None,
        prompt_message=_("action.actions.internal.create_new_tool.input_description"),
    )
    custom_tools_path: OptionalArg[DirectoryPath] = Arg(
        ".",
        prompt_message=_(
            "action.actions.internal.create_new_tool.input_custom_tools_path"
        ),
    )

def main(tool, env, env_args, cli_args):
    create_action = False
    new_tool = ActionTool(
        name="invalid",
        action=cli_args.action.prompt(
            searchable=True,
            choices=external.__all__ + ["new_action"],
            validate=lambda x: x,
        ),
    )

    if new_tool.action == "new_action":
        create_action = True
        new_tool.action = cli_args.action.prompt(
            message=_("action.actions.internal.create_new_tool.input_action"),
            validate=lambda x: x,
        )

    new_tool.type = cli_args.type.prompt(
        choices=[
            {"value": ToolType.web, "name": ToolType.web.value},
            {"value": ToolType.shell, "name": ToolType.shell.value},
        ],
        default=ToolType.web if new_tool.action == "open_link" else ToolType.shell,
    )

    new_tool.name = cli_args.name.prompt(
        validate=lambda x: x,
        default=new_tool.action.replace("_", "-"),
    )

    new_tool.alias = cli_args.alias.prompt(
        default="".join([z[:1] for z in new_tool.name.split("-")]),
        filter=lambda r: r or None,
    )

    new_tool.long_name = cli_args.long_name.prompt(filter=lambda r: r or None)

    new_tool.description = cli_args.description.prompt(filter=lambda r: r or None)

    cli, tools, envs = configuration.refresh()

    if create_action:
        if not configuration.custom_tools_path:
            log.info(_("msg.actions.internal.create_new_tool.custom_tools_dir_not_set"))
            path_ = cli_args.custom_tools_path.prompt()
            configuration.update_custom_tools_path(
                path_.resolve()
                if path_.is_absolute()
                else os.path.join(*path_.parents, path_.name),
                comment=_(
                    "msg.actions.internal.create_new_tool.input_custom_tools_path_comment"
                ),
            )

        copytree(
            os.path.abspath(
                os.path.join(
                    os.path.dirname(__file__),
                    "..",
                    "..",
                    "actions",
                    "__templates",
                    "custom_tool",
                )
            ),
            os.path.join(configuration.custom_tools_path, new_tool.action),
        )

        _replace_variables(
            os.path.join(configuration.custom_tools_path, new_tool.action, "README.md"),
            "{{tool}}",
            new_tool.long_name or new_tool.name,
        )

    configuration.add_tool(new_tool)
    configuration.save()

def _replace_variables(file_name, variable, value):
    with open(file_name, "r") as file:
        file_data = file.read()

    file_data = file_data.replace(variable, value)

    with open(file_name, "w") as file:
        file.write(file_data)


"""
2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^1000?
"""

def sum_of_digits(n):
    sum = 0
    num_array = list(str(n))
    for x in num_array:
        sum += int(x)
    return sum

if __name__ == "__main__":
    print("The sum of the digits of the number 2^1000 is: " + str(sum_of_digits(2**1000)))


# Given a sorted array of integers, find the number of occurrences of a given target value.
# Your algorithm’s runtime complexity must be in the order of O(log n).
# If the target is not found in the array, return 0

# **Example : **
# Given [5, 7, 7, 8, 8, 10] and target value 8,
# return 2.

class Solution:
    # @param A : tuple of integers
    # @param B : integer
    # @return an integer
    def binarysearch(self, A, B, flag): # True to indicate find the first index
        start, end = 0, len(A) - 1
        ind = -1
        while start <= end:
            mid = (start + end) / 2
            if B == A[mid]:
                ind = mid
                if flag:
                    end = mid-1
                else:
                    start = mid +1
            elif B < A[mid]:
                end = mid-1
            else:
                start = mid+1
        return ind+1

    def findCount(self, A, B):
        low = self.binarysearch(A, B, True)
        if low:
            high = self.binarysearch(A, B, False)
            return high-low+1
        return low


import tornado
from collections import deque
from select import epoll
from tornado.platform.auto import Waker

from toolkit.singleton import Singleton

class EPollIOLoop(metaclass=Singleton):
    _EPOLLIN = 0x001
    _EPOLLPRI = 0x002
    _EPOLLOUT = 0x004
    _EPOLLERR = 0x008
    _EPOLLHUP = 0x010
    _EPOLLRDHUP = 0x2000
    _EPOLLONESHOT = (1 << 30)
    _EPOLLET = (1 << 31)

    # Our events map exactly to the epoll events
    NONE = 0
    READ = _EPOLLIN
    WRITE = _EPOLLOUT
    ERROR = _EPOLLERR | _EPOLLHUP

    def __init__(self):
        self._impl = epoll()
        self._waker = Waker()
        self.add_handler(self._waker.fileno(),
                         lambda fd, events: self._waker.consume(),
                         self.READ)
        self._handlers = {}
        self._events = {}
        self.coroutine_futures = dict()
        self.waits = deque()
        self.callbacks = deque()

    def add_handler(self, fd, handler, events):
        fd, obj = self.split_fd(fd)
        self._handlers[fd] = (obj, handler)
        self._impl.register(fd, events | self.ERROR)

    def update_handler(self, fd, events):
        fd, obj = self.split_fd(fd)
        self._impl.modify(fd, events | self.ERROR)

    def remove_handler(self, fd):
        fd, obj = self.split_fd(fd)
        self._handlers.pop(fd, None)
        self._events.pop(fd, None)
        try:
            self._impl.unregister(fd)
        except Exception:
            print("Error deleting fd from IOLoop")

    def split_fd(self, fd):
        try:
            return fd.fileno(), fd
        except AttributeError:
            return fd, fd

    def start(self):
        while True:
            for i in range(len(self.waits)):
                coroutine = self.waits.popleft()
                if self.coroutine_futures[coroutine].is_ok():
                    self.callbacks.append(coroutine)
                else:
                    self.waits.append(coroutine)

            for i in range(len(self.callbacks)):
                coroutine = self.callbacks.popleft()
                future = self.coroutine_futures[coroutine]
                coroutine.send(future)
                if future.is_ok():
                    self.callbacks.append(future)
                else:
                    self.waits.append(future)
            event_pairs = self._impl.poll(10)

            self._events.update(event_pairs)
            while self._events:
                fd, events = self._events.popitem()
                fd_obj, handler_func = self._handlers[fd]
                handler_func(fd_obj, events)

class Future(object):
    def __init__(self, ok_callback=lambda: True):
        self._done = False
        self._result = None
        self._callbacks = []
        self.ok_callback = ok_callback

    def is_ok(self):
        return self.ok_callback()

    def set_ok_callback(self, ok_callback):
        self.ok_callback = ok_callback

    def cancel(self):
        return False

    def cancelled(self):
        return False

    def running(self):
        return not self._done

    def done(self):
        return self._done

    def result(self, timeout=None):
        if self._result is not None:
            return self._result
        return self._result

    def add_done_callback(self, fn):

        if self._done:
            fn(self)
        else:
            self._callbacks.append(fn)

    def set_result(self, result):
        self._result = result
        self._set_done()

    def _set_done(self):
        self._done = True
        for cb in self._callbacks:
            cb(self)
        self._callbacks = None

import time

def sleep(seconds):
    f = Future()
    f.set_ok_callback(lambda start_time=time.time(): time.time() >= start_time + seconds)
    yield f

def main():
    future = Future()
    def sum(a, b):
        yield future
        yield from sleep(2)
        return a + b
    result = yield from sum(1, 2)
    print(result)

if __name__ == "__main__":
    main()


import linked_list

def file_handling():

    """ Function to read the file to carry out the operations """
    #pens the file in read and write mode

    file_to_read = open("/home/admin1/Antony_Alex/Alex/Bridgelabz/data_structures/unordered_list/number_reading", "r+")
    contents_in_file = file_to_read.read()
    file_to_read.close()
    #Used to erase the contents of the file
    open("/home/admin1/Antony_Alex/Alex/Bridgelabz/data_structures/unordered_list/number_reading", "w").close()
    print(contents_in_file)
    list_of_words = contents_in_file.split()
    list_of_words =[int(i) for i in list_of_words]
    return list_of_words

def find_num():
    num_to_find = int(input("Enter the number to check : "))
    return num_to_find

def llist_addition(numb_list):

    llist = linked_list.Linkedlist()
    for i in numb_list:
        llist.add_to_list(i)
    return llist

def operate_on_llist(num_needed,llist):
    find_num = llist.search(num_needed)
    if (find_num == True):
        llist.delete_node(num_needed)
    else:
        llist.add_to_list(num_needed)
        llist.list_sorting()
    return llist

def llist_operation(num_list):
    llist = llist_addition(num_list)
    llist.list_sorting()
    print("\r The sorted list is :")
    llist.print_list()
    num = find_num()
    llist = operate_on_llist(num,llist)
    llist.print_list()
    return_list = llist.return_list()
    return_list = [str(i) for i in return_list]

    add_to_file(return_list)

def add_to_file(return_list):

    final_sentence = ' '.join(return_list)
    print(final_sentence)
    file_to_read = open("/home/admin1/Antony_Alex/Alex/Bridgelabz/data_structures/unordered_list/number_reading", "r+")
    file_to_read.write(final_sentence)
    file_to_read.close()
    return

if __name__ =="__main__":

    num_list = file_handling()
    llist_operation(num_list)


import os
import shutil
import re

basedir = '.'

len1 = 8
pat1 = re.compile("^[0-9]{8}")

len2 = 6
pat2 = re.compile("^[0-9]{6}")

len3 = 4
pat3 = re.compile("^[0-9]{4}")

pat4 = re.compile(r"^(([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{4}-[0-9]{2}))")

def refmt_date(fn0):
  global len1,len2,len3,pat1,pat2,pat3,pat4
  if re.match(pat4, fn0):
    return fn0

  m = re.match(pat1, fn0)
  if m:
    if len(fn0)> len1:
      fn = f"{m[0][:4]}-{m[0][4:6]}-{m[0][6:len1]}-{fn0[len1:]}"
    else:
      fn = f"{m[0][:4]}-{m[0][4:6]}-{m[0][6:len1]}"
  else:
    m = re.match(pat2, fn0)
    if m:
      if len(fn0)> len2:
        fn = f"{m[0][:4]}-{m[0][4:len2]}-{fn0[len2:]}"
      else:
        fn = f"{m[0][:4]}-{m[0][4:len2]}"
    else:
      m = re.match(pat3, fn0)
      if m:
        if len(fn0)> len3:
          fn = f"{m[0][:len3]}-{fn0[len3:]}"
        else:
          fn = f"{m[0][:len3]}"
      else:
        fn = fn0
  return fn

for fn in os.listdir(basedir):
  if not os.path.isdir(os.path.join(basedir, fn)):
    continue # Not a directory
  fn2 = refmt_date(fn)
  if fn == fn2:
    continue

  from_dir = os.path.join(basedir, fn)
  to_dir = os.path.join(basedir, fn2)
  print(f"cp -rf {from_dir} {to_dir}\n")

  os.system(f"cp -rf {from_dir} {to_dir}")
  os.system(f"rm -rf {from_dir}")


import requests
import os
import time
import uuid
from threading import Thread

y_url = 'http://pscly.cn:31002/'
# y_url = 'http://127.0.0.1:31001/'
proxies = { "http": None, "https": None}

def get_system_info(hash=0):
    hostname = os.environ.get('COMPUTERNAME')
    username = os.environ.get('USERNAME')
    data = str(hostname)+str(username)
    if hash:
        return str(uuid.uuid3(uuid.NAMESPACE_DNS, data).hex)
    else:
        return data

def send_data():
    pass

def send_file(file_path):
    url = f'{y_url}/files2/up'
    x = requests.post(url, files={'file': open(file_path, 'rb')}, proxies=proxies)

def send_file_xc(file_path):
    Thread(target=send_file, args=(file_path, )).start()

def send_file_2(file_path):
    url = f'{y_url}/files2/up'
    filesname = get_system_info()+time.strftime('%Y-%m-%d_%H-%M')+os.path.basename(file_path)
    x = requests.post(url,data={'file_name': filesname}, files={'file': open(file_path, 'rb')}, proxies=proxies)
def send_file_xc(file_path):
    Thread(target=send_file, args=(file_path, )).start()

if __name__ == '__main__':
    # send_file_2(r'D:\cly\xm\tk2-2\msedgedriver.exe')
    x = requests.get('http://pscly.cn:31002/md', proxies=proxies)
    print(x.text)


from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm

from blog.forms.loginForm import MyRegisterForm

def my_register(request):
    if request.method == 'POST':
        form = MyRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('register-success')
    else:
        form = MyRegisterForm()
    context = {
        'form': form
    }
    return render(request, 'registration/my-register-modal.html', context)

def register_success(request):
    return render(request, 'registration/register-success.html')


import http

import pytest
from rest_framework.test import APIClient
from model_bakery import baker

from students.models import Student, Course

@pytest.fixture
def client():
    return APIClient()

@pytest.fixture
def student_factory():
    def factory(*args, **kwargs):
        return baker.make(Student, *args, **kwargs)

    return factory

@pytest.fixture
def course_factory():
    def factory(*args, **kwargs):
        return baker.make(Course, *args, **kwargs)

    return factory

# - проверка получения первого курса (retrieve-логика):
@pytest.mark.django_db
def test_get_course(client, course_factory):
    # Arrange
    #   - создаем курс через фабрику;
    courses = course_factory(_quantity=2)

    # Act
    #   - строим урл и делаем запрос через тестовый клиент;
    response = client.get('/api/v1/courses/%d/' % courses[0].id)

    # Assert
    #   - проверяем, что вернулся именно тот курс, который запрашивали;
    assert response.status_code == http.HTTPStatus.OK

    data = response.json()
    assert data['name'] == courses[0].name

# - проверка получения списка курсов (list-логика):
#   - аналогично — сначала вызываем фабрики, затем делаем запрос и проверяем результат;
@pytest.mark.django_db
def test_get_courses(client, course_factory):
    courses = course_factory(_quantity=10)

    response = client.get('/api/v1/courses/')

    assert response.status_code == http.HTTPStatus.OK

    data = response.json()
    assert len(data) == len(courses)

    for i, с in enumerate(data):
        assert с['name'] == courses[i].name

# - проверка фильтрации списка курсов по `id`:
#   - создаем курсы через фабрику, передать ID одного курса в фильтр, проверить результат запроса с фильтром;
@pytest.mark.django_db
def test_get_course_filter_id(client, course_factory):
    courses = course_factory(_quantity=10)

    response = client.get('/api/v1/courses/', {'id': courses[0].id})

    assert response.status_code == http.HTTPStatus.OK

    data = response.json()
    assert len(data) == 1

    for i, с in enumerate(data):
        assert с['name'] == courses[i].name

# - проверка фильтрации списка курсов по `name`;
@pytest.mark.django_db
def test_get_course_filter_name(client, course_factory):
    courses = course_factory(_quantity=10)

    response = client.get('/api/v1/courses/', {'name': courses[0].name})

    assert response.status_code == http.HTTPStatus.OK

    data = response.json()
    assert len(data) >= 1

    for i, с in enumerate(data):
        assert с['name'] == courses[i].name

# - тест успешного создания курса:
#   - здесь фабрика не нужна, готовим JSON-данные и создаём курс;
@pytest.mark.django_db
def test_create_course(client, course_factory):
    course_name = 'test_create_course'
    data = {'name': course_name}

    response = client.post('/api/v1/courses/', data=data)

    assert response.status_code == http.HTTPStatus.CREATED

    data = response.json()
    assert data['name'] == course_name

# - тест успешного обновления курса:
#   - сначала через фабрику создаём, потом обновляем JSON-данными;
@pytest.mark.django_db
def test_update_course(client, course_factory):
    course = course_factory(_quantity=1)[0]
    course.save()

    course_name = 'test_create_course'
    data = {'name': course_name}

    response = client.patch('/api/v1/courses/%d/' % course.id, data=data)

    assert response.status_code == http.HTTPStatus.OK

    data = response.json()
    assert data['name'] == course_name

# - тест успешного удаления курса.
@pytest.mark.django_db
def test_create_course(client, course_factory):
    course = course_factory(_quantity=1)[0]
    course.save()

    response = client.delete('/api/v1/courses/%d/' % course.id)

    assert response.status_code == http.HTTPStatus.NO_CONTENT

TEST_MAX_STUDENTS_PER_COURSE = 2

# Добавьте валидацию на максимальное число студентов на курсе — 20
@pytest.mark.parametrize(
    ["student_count", "expected_status"],
    (
            (TEST_MAX_STUDENTS_PER_COURSE, http.HTTPStatus.CREATED),
            (TEST_MAX_STUDENTS_PER_COURSE + 1, http.HTTPStatus.BAD_REQUEST),
    )
)
@pytest.mark.django_db
def test_create_course_with_students(client, settings, student_factory, student_count, expected_status):
    settings.MAX_STUDENTS_PER_COURSE = TEST_MAX_STUDENTS_PER_COURSE

    students = student_factory(_quantity=student_count)
    students_id = [s.id for s in students]

    course_name = f'test_create_course_with_students_{student_count}'
    data = {'name': course_name, 'students': students_id}

    response = client.post('/api/v1/courses/', data=data)

    if student_count > TEST_MAX_STUDENTS_PER_COURSE:
        assert response.status_code == expected_status
    else:
        assert response.status_code == expected_status
        data = response.json()
        assert data['name'] == course_name


import json
import pandas as pd

with open('setup.json') as json_file:
    json_data = json.load(json_file)

path = json_data['main_path']
report = json_data['reports'] ['br_ifrs15']
source = path + report['file']

df = pd.read_excel(source, sheet_name='HistRecReceita')

def add_market():

    for r in df.index:
        e = df.loc[r, 'Mercado']

        if pd.isnull(e):
            k = df.loc[r, 'TipFt']
            vl = 'BR'

            if k == 'ZVEX' or k == 'ZEXT':
                vl = 'EXPO'

            df.loc[r, 'Mercado'] = vl

def add_accounting_type():

    for r in df.index:
        e = df.loc[r, 'Contabilização Fatura 2']

        if pd.isnull(e):
            t = df.loc[r, 'Texto']
            u = df.loc[r, 'Usuário Fatura 2']
            vl = 'INTEGRACAO'

            if t.startswith('Finalizado Manualmente (AANTUNES') or t.startswith('Finalizado Manualmente (PYKOSZ'):
                vl = 'ZTSD401'

            elif u == 'AANTUNES' or u == 'PYKOSZ':
                vl = 'VF01'

            df.loc[r, 'Contabilização Fatura 2'] = vl

def add_carrier_nickname():

    source_temp = report['support_data']['carrire_nickname']
    df_temp = pd.read_excel(source_temp, sheet_name='Query')

    test = pd.merge(df[pd.isnull(df['Apelido'])], df_temp, how='left', on='Cod Transp')

# API
# add_market()
#GetUserInvoiceROL_Q1() ### Verificar possibilidade de add esse item na query principal ou criar um novo job

# add_accounting_type()
#GetDocTranspInfo_Q1() ### Verificar possibilidade de add esse item na query principal ou criar um novo job

add_carrier_nickname()


import os
import clip
import torch
from torchvision import transforms, models

import numpy as np
from sklearn.linear_model import LogisticRegression
from torch.utils.data import DataLoader
from tqdm import tqdm

import argparse
from omegaconf import OmegaConf

import json

from datasets import *
from clip_model_comparison import *

results_path = "results"
device = "cuda" if torch.cuda.is_available() else "cpu"
print(device)

clip_model, clip_preprocess = clip.load("ViT-B/32", device)

import torch.nn as nn
import torch.optim as optim

def get_clip_features(dataset):
    all_features = []
    all_labels = []

    global clip_model

    with torch.no_grad():
        for images, labels in tqdm(dataset):
            features = clip_model.encode_image(images.to(device))
            all_features.append(features)
            all_labels.append(labels)

    return torch.cat(all_features), torch.cat(all_labels)

###### Generating weights ##########

def cross_entropy(train_loader, test_loader, classes):
    len_classes = len(classes)

    train_features, train_labels = get_clip_features(train_loader)
    test_features, test_labels = get_clip_features(test_loader)

    classifier = LogisticRegression(C=1, max_iter=1000, n_jobs=6)
    classifier.fit(train_features.cpu().numpy(), train_labels.cpu().numpy())
    zeroshot_weights = torch.from_numpy(classifier.coef_.T).to(torch.float16)
    return zeroshot_weights

def clip_loss(train_loader, test_loader, classes):
    len_classes = len(classes)

    train_features, train_labels = get_clip_features(train_loader)
    test_features, test_labels = get_clip_features(test_loader)

    train_features = train_features / train_features.norm(dim=-1, keepdim=True)
    test_features = test_features / test_features.norm(dim=-1, keepdim=True)

    classifier = LogisticRegression(C=1, max_iter=1000, n_jobs=6)
    classifier.fit(train_features.cpu().numpy(), train_labels.cpu().numpy())
    zeroshot_weights = torch.from_numpy(classifier.coef_.T).to(torch.float16)
    return zeroshot_weights

# def hybrid_loss(train_loader, test_loader):
#     """Concatenating text and image encoding, basically using a linear combination""""
#     len_classes = len(classes)

#     train_features, train_labels = get_clip_features(train_loader)
#     test_features, test_labels = get_clip_features(test_loader)

#     train_features = train_features / train_features.norm(dim=-1, keepdim=True)
#     test_features = test_features / test_features.norm(dim=-1, keepdim=True)

#     classifier = LogisticRegression(C=1, max_iter=1000, n_jobs=6)
#     zeroshot_weights = torch.from_numpy(classifier.coef_.T).to(torch.float16)
#     return zeroshot_weights

###################

def final_accuracy(test_loader, zeroshot_weights):

    global clip_model

    def accuracy(output, target, topk=(1,)):
        pred = output.topk(max(topk), 1, True, True)[1].t()
        correct = pred.eq(target.view(1, -1).expand_as(pred))
        return [
            float(correct[:k].reshape(-1).float().sum(0, keepdim=True).cpu().numpy())
            for k in topk
        ]

    # lazy load
    if clip_model == None:
        clip_model, clip_preprocess = clip.load(clip_model_name, device)

    with torch.no_grad():
        top1, top5, n = 0.0, 0.0, 0.0
        for i, (images, target) in enumerate(tqdm(test_loader)):
            images = images.cuda()
            target = target.cuda()

            # predict
            image_features = clip_model.encode_image(images)
            image_features /= image_features.norm(dim=-1, keepdim=True)
            logits = 100.0 * image_features.to(device) @ zeroshot_weights.to(device)

            # measure accuracy
            acc1, _ = accuracy(logits, target, topk=(1, 5))
            top1 += acc1
            n += images.size(0)

    top1 = (top1 / n) * 100
    return top1

def run_expts(args):
    """
    Currently supports clip_zero_shot, clip_linear_probe, resnet_linear_probe expts
    """

    results = {}
    results["params"] = {}

    dataset = args.data
    dataset_obj = None
    if dataset == "cifar100":
        dataset_obj = Cifar100(args.num_workers, args.batch_size)
    elif dataset == "flowers102":
        dataset_obj = Flowers102(args.num_workers, args.batch_size)
    elif dataset == "oxfordpets":
        dataset_obj = OxfordPets(args.num_workers, args.batch_size)
    elif dataset == "smallflowers102":
        dataset_obj = SmallFlowers102(args.num_workers, args.batch_size)
    elif dataset == "food101":
        dataset_obj = Food101(args.num_workers, args.batch_size)
    results["params"]["data"] = str(args.data)
    results["params"]["batch_size"] = int(args.batch_size)

    assert dataset_obj is not None, "Please select a valid dataset"

    global clip_model, clip_preprocess

    if clip_preprocess is None or clip_model is None:
        clip_model, clip_preprocess = clip.load(args.clip_model, device)

    final = {"cross_entropy": {}, "clip": {}}
    for i in [1,2,4,8,16,32,-1]:
        tot_ce = 0
        print("-------------------------------------")
        print(f"Running Prompt Generation expts on {dataset_obj.name} with {i} elements per class")
        print("-------------------------------------")
        test_loader = dataset_obj.get_test_loader(transform_fn=clip_preprocess)
        try:
            for _ in range(5):
                train_loader, _ = dataset_obj.get_train_loaders(transform_fn=clip_preprocess, num_elements_per_class=i)
                ce = cross_entropy(train_loader,test_loader,dataset_obj.classes)
                out = final_accuracy(test_loader,ce)
                if i in final["cross_entropy"]:
                    final["cross_entropy"][i] +=out
                else:
                    final["cross_entropy"][i] =out

                ce = clip_loss(train_loader,test_loader,dataset_obj.classes)
                out = final_accuracy(test_loader,ce)
                if i in final["clip"]:
                    final["clip"][i] +=out
                else:
                    final["clip"][i] =out

                # h = hybrid_loss(train_loader,test_loader)
                # final_accuracy = final_accuracy(test_loader,h)
                # if i in final["hybrid"]:
                #     final["hybrid"][i] +=final_accuracy
                # else:
                #     final["hybrid"][i] =0

            final["cross_entropy"][i]/=5
            final["clip"][i]/=5
            print(final)
            # final["hybrid"][i]=/10
        except Error:
            pass

    with open(f"{results_path}/{dataset}_embedding_generation_few_shot.json", "w") as outfile:
        json.dump(final, outfile)

    return final

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Clip Experiments")
    parser.add_argument("--config", type=str, default="./configs/dummy.yml")
    flags = parser.parse_args()
    args = OmegaConf.load(flags.config)
    run_expts(args)


class Solution:
    def kInversePairs(self, n: int, k: int) -> int:
        dp = [[0 for x in range(1228)] for y in range(1228)]
        Mod = int(1e9 + 7)
        for i in range(1, n+1):
            for j in range(k+1):
                if j == 0:
                    dp[i][j] = 1
                    continue
                prev = dp[i-1][j]
                if j-i >= 0:
                    prev -= dp[i-1][j-i]
                dp[i][j] = (dp[i][j-1] + prev) % Mod
        res = dp[n][k]
        if k > 0:
            res -= dp[n][k-1]
        return res % Mod


import argparse
import re
import sys
from typing import Iterable

from matplotlib import pyplot as plt

parser = argparse.ArgumentParser(description="Plot graphs")
parser.add_argument(
    "infile",
    type=argparse.FileType("r"),
    default="cpp/data/data4.csv",
)
parser.add_argument("--out", required=True)
parser.add_argument("--match", default=".*")
parser.add_argument(
    "--type",
    choices=["bar", "progress", "per_loop"],
    default="progress",
)

def read(stream: Iterable[str]) -> list[tuple[str | float]]:
    return [tuple(map(try_convert_time, line.strip().split(", "))) for line in stream]

def try_convert_time(maybe_time: str) -> str | float:
    try:
        return float(maybe_time)
    except ValueError:
        return maybe_time

def convert_time(time: str) -> float:
    """Converts time format `5m35,892s` into seconds."""
    m, s = time.replace(",", ".").strip("s").split("m")
    return int(m) * 60 + float(s)

def plot_progression(
    data: list[tuple[str | float]],
    per_inner_loop=True,
):
    xs = list(map(int, data[0][1:]))
    for line in data[1:]:
        if per_inner_loop:
            ts = [y / 1000 / x**3 for x, y in zip(xs, line[1:])]
            plt.plot(xs, ts, "o-", label=line[0])
        else:
            ts = [t / 1000 for t in line[1:]]
            plt.plot(xs, [t / 1000 for t in line[1:]], "o-", label=line[0])
        if len(data) <= 3:
            for x, t in zip(xs[::2], ts[::2]):
                v = t
                if t > 10:
                    v = f"{t:.0f}"
                elif t > 0.1:
                    v = f"{t:.2g}"
                else:
                    v = f"{t:.0e}"
                    v = v.replace("e-02", "0m").replace("e-03", "m")
                    v = (
                        v.replace("e-04", "00u")
                        .replace("e-05", "0u")
                        .replace("e-06", "u")
                    )
                    v = (
                        v.replace("e-07", "00n")
                        .replace("e-08", "0n")
                        .replace("e-09", "n")
                    )
                    v = (
                        v.replace("e-10", "00p")
                        .replace("e-11", "0p")
                        .replace("e-12", "p")
                    )
                plt.annotate(v + "s", (x, t), size=10)
    plt.legend()
    ax = plt.gca()
    ax.set_yscale("log")
    ax.set_xscale("log", base=2)
    plt.grid(linestyle=":")
    # plt.xlabel("Graph input memory size [4B$\cdot n^2$]")
    plt.xlabel("Graph size [n]")
    if per_inner_loop:
        plt.ylabel("Time for inner loop")
        plt.yticks(
            [1e-10, 1e-9, 1e-8],
            ["100ps", "1ns", "10ns"],
        )
    else:
        plt.ylabel("Time to complete")
        plt.yticks(
            [1e-5, 0.0001, 0.001, 0.01, 0.1, 1, 10, 60, 600],
            ["10us", "100us", "1ms", "10ms", "100ms", "1s", "10s", "1m", "10min"],
        )
    # plt.xticks(xs, [format_bytes(x) for x in xs], size="small")
    plt.xticks(xs, xs)

def format_bytes(n):
    b = 4 * n**2
    prefix = ["", "k", "M", "G"]
    for p in prefix:
        if b < 1024:
            return f"{b}{p}B"
        b = round(b / 1024)

def trim_row(row, n=5):
    return [row[0]] + list(row[n:])

def select(data, row_match, col_skip):
    match = re.compile(row_match)
    result = [trim_row(data[0], col_skip)]
    for row in data[1:]:
        if match.fullmatch(row[0]):
            result.append(trim_row(row, col_skip))
    return result

def plot_bar(data):
    xs = []
    ys = []
    xs_th = []
    ys_th = []
    should_split = len(data) > 3
    for row in data[1:]:
        t = row[-1] / 1000
        if should_split and row[0].endswith("_th"):
            xs_th.append(row[0][:-3])
            ys_th.append(t)
        else:
            xs.append(row[0])
            ys.append(t)
    if xs:
        bar = plt.bar(xs, ys, label="Single-threaded")
    if xs_th:
        bar_th = plt.bar(xs_th, ys_th, label="Multi-threaded")
        plt.bar_label(bar_th, fmt="%.1fs", color="white" if xs else "black")
    if xs:
        plt.bar_label(bar, fmt="%.1fs")
    if xs and xs_th:
        plt.legend()
    if should_split:
        plt.yscale("log")
        plt.yticks(
            [1, 10, 60, 600],
            ["1s", "10s", "1m", "10min"],
        )
    plt.ylabel(f"Time to complete N={int(data[0][-1])} case.")

def main():
    args = parser.parse_args()
    data = read(args.infile)
    data = select(data, args.match, 4)
    if args.type == "bar":
        plot_bar(data)
    else:
        plot_progression(
            data,
            per_inner_loop=args.type == "per_loop",
        )
    plt.gcf().set_size_inches((4.5, 2.5))
    plt.tight_layout()
    plt.savefig(args.out, dpi=200)

if __name__ == "__main__":
    main()


import functools

class Expression():
    def __init__(self, func, args):
        self.func = func
        self.args = args

    def __repr__(self):
        return str(self)

    def __str__(self):
        return "({} {})".format(self.func, self.args)

fn_table = {
    "=": lambda *x: functools.reduce(lambda a, b: a == b, x),
    "+": lambda *x: sum(x),
    "-": lambda *x: functools.reduce(lambda a, b: a - b, x),
    "*": lambda *x: functools.reduce(lambda a, b: a * b, x),
    "/": lambda *x: functools.reduce(lambda a, b: a / b, x),
    ">": lambda *x: max(x),
    "<": lambda *x: min(x),
    "//": lambda *x: functools.reduce(lambda a, b: a // b, x),
    "println": lambda x: print(x),
}

def tokenize(code):
    return code.replace("(", " ( ").replace(")", " ) ").split()

def express(expr):
    func = None
    args = []
    while expr[0] != ")":
        if expr[0] == "(":
            expr.pop(0)
            expr.insert(0, express(expr))
        else:
            if not func:
                func = expr.pop(0)
            else:
                args.append(expr.pop(0))
    if not args:
        return func
    else:
        expression = Expression(func, args)
        return expression

def read(code):
    tokens = tokenize(code)
    return express(tokens)

def eval(expr):
    if type(expr) == Expression:
        func = expr.func
        args = [eval(x) for x in expr.args]
        return fn_table[func](*args)
    else:
        try:
            return int(expr)
        except ValueError:
            return str(expr)

if __name__ == "__main__":
    while True:
        code = input("> ")
        print(eval(read(code)))


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

import pandas as pd
import numpy as np
from google.cloud import bigquery
from google.oauth2 import service_account
import json
import warnings
from datetime import datetime
import datetime
import re
warnings.filterwarnings('ignore')

start_date = 20201024
end_date = 20201031

def get_ids():
    print("getting IDs")

    #Sling credentials to big queery
    credentials = service_account.Credentials.from_service_account_file(
        'key.json')

    client = bigquery.Client(credentials= credentials, project='thankful-68f22')
    query_job = client.query(
    """
    SELECT DISTINCT user_pseudo_id
    FROM `thankful-68f22.analytics_198686154.events_*`
    WHERE event_name = 'user_started_trial'
    AND event_date BETWEEN '{}' AND '{}'
    """.format(start_date, end_date)
    )

    #Convert object to df
    results = query_job.result()
    df = results.to_dataframe()
    print("finished getting IDs")
    print(df.shape[0])
    return df

def ripEventsForID(id):
    print("ripping id")

    credentials = service_account.Credentials.from_service_account_file(
        'key.json')

    client = bigquery.Client(credentials= credentials, project='thankful-68f22')
    query_job = client.query(
    """
    SELECT *
    FROM `thankful-68f22.analytics_198686154.events_*`
    WHERE user_pseudo_id = '{}'
    ORDER BY event_timestamp ASC
    """.format(id, start_date, end_date)
    )

    #Convert object to df
    results = query_job.result()
    df = results.to_dataframe()

    completed_trial_count = df['event_name'].str.contains('user_completed_trial').sum()
    if completed_trial_count > 0:
        print("writing to trial completed")
        file_name = "completed/trial_completed+%s.json" %(id)
        result = df.to_json(orient="records")
        parsed = json.loads(result)
        with open(file_name, 'w') as outfile:
            json.dump(parsed, outfile, indent=4)
    else:
        print("writing to trial NOT completed")
        file_name = "not_completed/trial_not_completed+%s.json" %(id)
        result = df.to_json(orient="records")
        parsed = json.loads(result)
        with open(file_name, 'w') as outfile:
            json.dump(parsed, outfile, indent=4)

idFrame = get_ids()
ids = idFrame["user_pseudo_id"].values.tolist()

for id in ids:
    ripEventsForID(id)


from django.urls import path
from .views import (
ListLlegada,
DetailLlegada,
CreateLlegada,
UpdateLlegada,
DeleteLlegada,
SearchLlegada,
FilterLlegada,
export_llegada,
)

app_name = 'llegadas'

urlpatterns = [
    path('list/llegada/', ListLlegada.as_view(), name='list_llegada'),
    path('detail/llegada/<int:pk>/', DetailLlegada.as_view(), name='detail_llegada'),
    path('create/llegada/', CreateLlegada.as_view(), name='create_llegada'),
    path('update/llegada/<int:pk>/', UpdateLlegada.as_view(), name='update_llegada'),
    path('delete/llegada/<int:pk/', DeleteLlegada.as_view(), name='delete_llegada'),
    path('search/llegada/', SearchLlegada.as_view(), name='search_llegada'),
    path('filter/llegada/', FilterLlegada.as_view(), name='filter_llegada'),
    path('export/llegada/', export_llegada, name='export_llegada'),
]