from mortgage import Mortgage
import numpy as np
import locale
locale.setlocale(locale.LC_ALL, '')
import matplotlib.pyplot as plt

def money_fmt(num):
    return locale.currency(num, grouping = True)

m = Mortgage(
    apr = .037,
    loan_total = 500_000,
    loan_duration = 30,
    monthly_overage = 100
)

def plot_mortage(m):
    fig, ax = plt.subplots(1, 1)
    fig.set_size_inches(6, 6)
    ax = fig.gca()

    ax.text(0, 0,
            'Principal: {}\nAPR: {:.2}%\nMontly payment: {}\nCost in interest: {}\nTotal cost: {}'.format(
                money_fmt(m.principal),
                m.apr * 100,
                money_fmt(m.monthly_payment),
                money_fmt(m.cost_interest),
                money_fmt(m.cost_total)
            ),
            bbox = {
                    'facecolor':'white',
                    'alpha': 0.5,
                    'pad': 5
                }
           )

    ax.set_xticks(np.arange(0, len(m.months), 24*2))
    ax.set_yticks(np.arange(0, max(m.principals), 500))
    plt.grid(alpha=.25)

    plt.plot(m.months, m.interests, label = 'interest')
    plt.plot(m.months, m.principals, label = 'principal')
    plt.xlabel('Month')
    plt.ylabel('Money ($)')
    plt.legend()

    plt.show()

plot_mortage(m)


# 22.312, PSet07
#   by Travis Labossiere-Hickman (email: tjlaboss@mit.edu)
#
# Problem 10.9
# AHTR

import models
from math import pi, log, sqrt
from scipy.optimize import fsolve

# Given parameters
DPFRIC = 200000         # Pa
TIN = 600               # deg C
TMAX = 1000             # deg C
L = 10                  # m; length of fuel
DFLAT = 0.03            # m; flat-to-flat hexagon with
DFLOW = 0.01            # m; coolant channel diameter
AFLOW = pi/4*DFLOW**2   # m^2; coolant flow area

class Material(object):
	"""Material with thermal hydraulic properties

	Parameters:
	-----------
	:param rho:     float, kg/m^3; density
	:param k:       float, W/m-K;  conductivity
	:param mu:      float, Pa-s;   viscosity
	:param c:       float, J/kg-K; heat capacity

	Attributes:
	-----------
	pr:             float; Prandtl number
	"""
	def __init__(self, rho, k, mu, c):
		self.rho = rho
		self.k = k
		self.mu = mu
		self.c = c
		if self.mu:
			self.pr = c*mu/k
		else:
			self.pr = None

	def get_reynolds(self, g, lc = DFLOW):
		"""Return the Reynolds number at some mass flux

		Parameters:
		-----------
		g:          float, kg/s/m^2; mass flux
		lc:         float, m; characteristic length of flow
					[Default: DFLOW from constants]
		"""
		return g*lc/self.mu

# Given materials
sodium = Material(780, 60, 1.7E-4, 1300)
flibe = Material(1940, 1, 2E-3, 2410)
fuel = Material(8530, 6, None, 500)

def fric_pressure_drop(g, mat, f = models.mcadams, lz = L, lc = DFLOW):
	"""Find the pressure drop due to friction over the channel

	Parameters:
	-----------
	g:          float, kg/s/m^2; mass flux
	mat:        Material; which material to use for the coolant
	f:          function; which model to use for friction factor
				[Default: models.mcadams]
	lz:         float, m; length of the channel in which coolant flows
				[Default: L]
	lc:         float; characteristic length for the flow
				[Default: DFLOW]

	Returns:
	--------
	float, Pa; pressure drop across
	"""
	re = mat.get_reynolds(g, lc)
	fff = f(re)
	return fff*lz/lc*g**2/(2*mat.rho)

print("\nPart 1: Friction pressure drop")

dpna = lambda g: fric_pressure_drop(g, sodium) - DPFRIC
gna = fsolve(dpna, 10)[0]   # Mass flux, sodium
dpms = lambda g: fric_pressure_drop(g, flibe, models.blasius) - DPFRIC
gms = fsolve(dpms, 10)[0]   # Mass flux, flibe
print("\tMass fluxes (kg/s/m^2)")
print("\t\tNa: {:.2f},  \t\tMS: {:.2f}".format(gna, gms))
rena = sodium.get_reynolds(gna)
rems = flibe.get_reynolds(gms)
print("\tReynolds numbers")
print("\t\tNa: {:.3e}, \t\tMS: {:.3e}".format(rena, rems))
mna = gna*AFLOW     # mass flow rate, sodium
mms = gms*AFLOW     # mass flow rate, flibe
print("\tMass flow rates (kg/s)")
print("\t\tNa: {:.3f},  \t\tMS: {:.3f}".format(mna, mms))

print("\nPart 2: Pump work")
wna = mna/sodium.rho*DPFRIC
wms = mms/flibe.rho*DPFRIC
print("\tNa: {:.2f} W, \tMS: {:.2f} W".format(wna, wms))

print("\nPart 3: Max Linear Power rate")
# Find the dimensions of equivalent annular cell
area = 1/2*sqrt(3)*DFLAT**2     # Area of a regular hexagon
d_eq = 2*sqrt(area/pi)          # diameter of a circle
print("\tEquivalent diameter: {:.2f} cm".format(d_eq*100))
dratio = (d_eq/DFLOW)
fcoeff = (2*d_eq**2/(d_eq**2 - DFLOW**2)*log(d_eq/DFLOW) - 1)
print("\tPrandtl number")
print("\t\tNa: {:.2e}, \tMS: {:.2f}".format(sodium.pr, flibe.pr))

def linear_power(delta_t, mat, nu, mdot):
	"""Find the linear heat generation rate to produce a desired
	temperature change, using the thermal resistors metaphor.

	Parameters:
	-----------
	delta_t:    float, K; temperature change in the fluid
	mat:        Material; which material to use for the coolant
	nu:         float; Nusselt number to use for heat transfer
	mdot:       float, kg/s; mass flow rate of the coolant

	Returns:
	--------
	q1:         float, kW/m; linear heat generation rate
	"""
	global fcoeff, fuel
	r_fuel = fcoeff/(4*pi*fuel.k)
	r_wall = 1/(pi*nu*mat.k)
	r_flow = L/(mdot*mat.c)
	q1 = delta_t / (r_fuel + r_wall + r_flow)
	return q1

dt = TMAX - TIN
nuna = models.lyon(rena, sodium.pr)
nums = models.dittus_boelter(rems, flibe.pr)
print("\tNusselt number")
print("\t\tNa: {:.2f}, \tMS: {:.2f}".format(nuna, nums))
q1na = linear_power(dt, sodium, nuna, mna)
q1ms = linear_power(dt, flibe, nums, mms)
print("\tMaximum q' (kW/m)")
print("\t\tNa: {:.2f}, \tMS: {:.2f}".format(q1na/1000, q1ms/1000))

print("""\nPart 4: Coolant selection

Flibe is the clear choice of coolant for the AHTR. It offers a {:.0%} advantage
in linear heat generation rate over sodium, while requiring a pump of only
{:.1%} of the capacity required by sodium.""".format(q1ms/q1na, wms/wna))


from django.urls import path
from .views import (
    MyCustomView,
    CustomTokenObtainPairView,
    UserCreate,
    CustomTokenRefreshView,
    TestView, # Custom view for testing purposes. Comment to use in production.
)

urlpatterns = [
    path('v1/custom/service', MyCustomView.as_view(), name='my_custom_view'),
    path('token', CustomTokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('token/refresh', CustomTokenRefreshView.as_view(), name='token_refresh'),
    path('user/create', UserCreate.as_view(), name='user_create'),
    path('test', TestView.as_view(), name='testView'), # Custom view for testing purposes. Comment to use in production.
]


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

# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import os
import subprocess

import six

if six.PY3:
    DEVNULL = subprocess.DEVNULL
else:
    DEVNULL = open(os.devnull, 'w')

def device_properties(path):
    """Given a device path, e.g. '/sys/class/block/sda', returns a dict of
    properties for the device.
    """
    cmd = ['udevadm', 'info', '-q', 'property', path]
    try:
        out = subprocess.check_output(cmd, stderr=DEVNULL)
    except subprocess.CalledProcessError:
        return {}

    # Output from udevadm info looks like the following:
    # $ udevadm info -q property /sys/class/block/sda
    # DEVLINKS=/dev/disk/by-id/wwn-0x600508e000000000f8253aac9a1abd0c ...
    # DEVNAME=/dev/sda
    # DEVPATH=/devices/pci0000:00/0000:00:07.0/...
    # DEVTYPE=disk
    # ID_BUS=scsi
    # ID_MODEL=Logical_Volume
    # ID_MODEL_ENC=Logical\x20Volume\x20\x20
    # ID_PART_TABLE_TYPE=dos
    # ID_PART_TABLE_UUID=0000ebf3
    # ID_PATH=pci-0000:04:00.0-scsi-0:1:0:0
    # ID_PATH_TAG=pci-0000_04_00_0-scsi-0_1_0_0
    # ID_REVISION=3000
    # ID_SCSI=1
    # ID_SERIAL=3600508e000000000f8253aac9a1abd0c
    # ID_SERIAL_SHORT=600508e000000000f8253aac9a1abd0c
    # ID_TYPE=disk
    # ID_VENDOR=LSI
    # ID_VENDOR_ENC=LSI\x20\x20\x20\x20\x20
    # ID_WWN=0x600508e000000000
    # ID_WWN_VENDOR_EXTENSION=0xf8253aac9a1abd0c
    # ID_WWN_WITH_EXTENSION=0x600508e000000000f8253aac9a1abd0c
    # MAJOR=8
    # MINOR=0
    # SUBSYSTEM=block
    # TAGS=:systemd:
    # USEC_INITIALIZED=10219204
    res = {}
    for line in six.text_type(out.strip()).split('\n'):
        parts = line.split('=', 1)
        if len(parts) != 2:
            continue
        key = parts[0]
        val = parts[1]
        res[key] = val
    return res


#Задайте список из N элементов, заполненных числами из промежутка [-N, N]. Найдите произведение элементов на указанных позициях. Позиции вводятся с клавиатуры

from random import random

N = int(input('Введите количество элементов: '))
M1, M2 = list(map(int, input('Введите позиции элементов через пробел: ').split()))

import random

def ListOfElem(n):
    el = random.randint(-n, n)
    return el

list = []
for i in range(N):
    list.append(ListOfElem(N))

print(f'Список из {N} элементов: {list} ')
print(f'Произведение элементов: {list[M1] * list[M2]} ')


import os
os.environ['KMP_WARNINGS'] = 'off'
import time
import math
import argparse
import numpy as np
from thop import profile
from PIL import Image

import torch
import torch.nn as nn
from torchsummary import summary
import torch.distributed as dist
from torch.utils.tensorboard import SummaryWriter

from src.model import get_model
from src.dataset import get_dataset
from src.utils import get_logger

from ipdb import set_trace as st
def debug():
    if dist.get_rank() == 0:
        st()
        torch.distributed.barrier()
    else:
        torch.distributed.barrier()

# set random seed
def setup_seed(seed):
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    np.random.seed(seed)
    torch.backends.cudnn.deterministic = True

def get_opt_from_yaml(path):
    assert os.path.exists(path), f"{path} must exists!"
    import yaml
    with open(path, 'r') as f:
        opt = yaml.load(f)
    return opt

def get_data_loaders(opt):
    data_opt = opt['dataset']
    Logger = get_logger()
    Logger.info(f"Start to get dataset {data_opt['name']}...")
    trainset, testset = get_dataset(opt)

    train_sampler = torch.utils.data.distributed.DistributedSampler(trainset)
    trainloader = torch.utils.data.DataLoader(
        trainset,
        sampler=train_sampler,
        batch_size=data_opt['batch_size'],
        num_workers=data_opt['num_workers'],
        pin_memory=data_opt['pin_memory'],
        shuffle=data_opt['shuffle'], drop_last=True)

    if data_opt['val'] is not None:
        Logger.info("testset is Valid.")
        test_sampler = torch.utils.data.distributed.DistributedSampler(testset)
        testloader = torch.utils.data.DataLoader(
            testset,
            sampler=test_sampler,
            batch_size=data_opt['batch_size'],
            num_workers=data_opt['num_workers'],
            pin_memory=data_opt['pin_memory'],
            shuffle=data_opt['shuffle'], drop_last=True)
    else:
        Logger.info("testset is NONE.")
        testloader = None
        test_sampler = None

    return trainloader, testloader, train_sampler, test_sampler

def print_opts(opt, logger, start=2):
    if isinstance(opt, dict):
        for key, value in opt.items():
            if isinstance(value, dict):
                logger.info(' '*start + str(key))
                print_opts(value, logger, start+4)
            else:
                logger.info(' ' * start + str(key) + ' ' * start + str(value))
    else:
        logger.info(' '*start + str(opt))

def get_visualize_img(img): # img: [B T C H W]
    # mean = torch.tensor([0.485, 0.456, 0.406])
    # std = torch.tensor([0.229, 0.224, 0.225])
    # x = img[:8].detach().cpu() * std[None, None, :, None, None] + \
    #     mean[None, None, :, None, None]
    x = img[:8].detach().cpu()
    show_x = torch.clamp(x, min=0, max=1)
    b, t, c, h, w = show_x.shape
    show_x = show_x.permute((0, 3, 1, 4, 2)).numpy()
    show_x = show_x.reshape((b * h, t * w, c)) * 255.
    show_x = Image.fromarray(show_x.astype(np.uint8)).convert('RGB')
    return show_x

def print_unused_params(model):
    for name, param in model.named_parameters():
        if param.grad is None or torch.all(param.grad==0):
            print(name)

if __name__ == '__main__':
    assert torch.cuda.is_available()

    parser = argparse.ArgumentParser(description="VQVAES")
    parser.add_argument('--opt', default=None, type=str, help="config file path")
    parser.add_argument('--save_dir', default=None, type=str)
    parser.add_argument('--split', default=None, type=str)
    parser.add_argument('--local_rank', type=int)
    args = parser.parse_args()
    opt = get_opt_from_yaml(args.opt)

    print("Start to init torch distribution...")
    dist.init_process_group(backend='nccl', init_method='env://')
    print("Finish initializing torch distribution...")

    # get current experiment path
    setup_seed(10)
    writer = None
    Logger = get_logger(logging_file="tmp.log", name="tmp", isopen=True)

    # load train data and test data
    if args.split == 'train':
        opt['dataset']['batch_size'] = 1
        opt['dataset']['step'] = 1
        opt['dataset']['name'] += '_EXT'
        trainloader, _, _, _ = get_data_loaders(opt)
        Logger.info(f"Start to convert training set...")
        from tqdm import tqdm
        td = tqdm(range(len(trainloader)))
        trainloader_iter = enumerate(trainloader)
        for _ in td:
            i, inputs = next(trainloader_iter)
            np.save(os.path.join(args.save_dir, "{:010d}.npy".format(i)), inputs)

    elif args.split == 'test':
        opt['dataset']['batch_size'] = 1
        opt['dataset']['step'] = 20
        opt['dataset']['name'] += '_EXT'
        _, testloader, _, _ = get_data_loaders(opt)
        Logger.info(f"Start to convert testing set...")
        from tqdm import tqdm
        td = tqdm(range(len(testloader)))
        testloader_iter = enumerate(testloader)
        for _ in td:
            i, inputs = next(testloader_iter)
            np.save(os.path.join(args.save_dir, "{:010d}.npy".format(i)), inputs)

    else:
        raise NotImplementedError


from __future__ import print_function
import requests
import schedule
import time
import subprocess
import info
import pickle
import base64
import os
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

SCOPES = ['https://www.googleapis.com/auth/gmail.modify']

def create_message(to, subject, message):
    """Create a message for an email.

    Args:
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart()
    message['to'] = to
    message['from'] = info.email_address
    message['subject'] = subject

    aMessage = MIMEText(message)
    message.attach(aMessage)

    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

def send_email(provider, message):
    try:
        message = provider.users().messages().send(userId=info.email_address, body=message).execute()
        print('Message ID: %s' % message['id'])
        print("Message has been successfully sent!")
        return message
    except Exception as e:
        print("An error has occurred: %s" % e)
        return None

def send_message(message):
    subprocess.call("osascript sendMessage.applescript '%s' '%s'" % (f'{info.phone}', f'{message}'), shell=True)

def get_affirmation():
    return requests.get('https://www.affirmations.dev/random').text

def email_message(message):
    credits = None

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            credits = pickle.load(token)
    if not credits or not credits.valid:
        if credits and credits.expired and credits.refresh_token:
            credits.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            credits = flow.run_local_server(port=3000)
        with open('token.pickle', 'wb') as token:
            pickle.dump(credits, token)

    service = build('gmail', 'v1', credentials=credits)

    message = create_message(f'{info.phone}{info.carrier}', 'Affirmation', message)
    send_email(service, message)

def job():
    try:
        affirmation = get_affirmation()
        if affirmation != '':
            if info.mac:
                send_message(affirmation)
            else:
                email_message(affirmation)
        else:
            print("Error has occurred, please try again.")
    except Exception as e:
        print("An error has occurred: %s" % e)

if __name__ == "__main__":
    schedule.every().day.at(info.time).do(job)

    while True:
        schedule.run_pending()
        time.sleep(1)


import turtle

def petal(t, radius, angle):
    for i in range(2):
        t.circle(radius, angle)
        t.left(180 - angle)

def flower(t, n, radius, angle):
    for i in range(n):
        petal(t, radius, angle)
        t.left(360.0 / n)

def move(t, length):
    window = turtle.Screen()
    window.bgcolor("Yellow")
    t.pu()
    t.fd(length)
    t.pd()

anms = turtle.Turtle()
anms.speed(100)

anms.color("green")
anms.shape("turtle")
move(anms, -150)
anms.begin_fill()
flower(anms, 7, 60.0, 60.0)
anms.end_fill()

anms.color("red")
move(anms, 150)
anms.begin_fill()
flower(anms, 10, 30.0, 70.0)
anms.end_fill()

anms.color("blue")
move(anms, 150)
anms.begin_fill()
flower(anms, 14, 70.0, 50.0)
anms.end_fill()

turtle.mainloop()


# -*- coding: utf-8 -*-
"""The tar extracted file-like object implementation."""

# Note: that tarfile.ExFileObject is not POSIX compliant for seeking
# beyond the file size, hence it is wrapped in an instance of file_io.FileIO.

import os

from dfvfs.file_io import file_io
from dfvfs.resolver import resolver

class TarFile(file_io.FileIO):
  """Class that implements a file-like object using tarfile."""

  def __init__(self, resolver_context):
    """Initializes the file-like object.

    Args:
      resolver_context: the resolver context (instance of resolver.Context).
    """
    super(TarFile, self).__init__(resolver_context)
    self._current_offset = 0
    self._file_system = None
    self._size = 0
    self._tar_ext_file = None

  def _Close(self):
    """Closes the file-like object.

       If the file-like object was passed in the init function
       the data range file-like object does not control the file-like object
       and should not actually close it.

    Raises:
      IOError: if the close failed.
    """
    self._tar_ext_file.close()
    self._tar_ext_file = None

    self._file_system.Close()
    self._file_system = None

  def _Open(self, path_spec=None, mode='rb'):
    """Opens the file-like object defined by path specification.

    Args:
      path_spec: optional the path specification (instance of path.PathSpec).
                 The default is None.
      mode: optional file access mode. The default is 'rb' read-only binary.

    Raises:
      AccessError: if the access to open the file was denied.
      IOError: if the file-like object could not be opened.
      PathSpecError: if the path specification is incorrect.
      ValueError: if the path specification is invalid.
    """
    if not path_spec:
      raise ValueError(u'Missing path specfication.')

    file_system = resolver.Resolver.OpenFileSystem(
        path_spec, resolver_context=self._resolver_context)

    file_entry = file_system.GetFileEntryByPathSpec(path_spec)
    if not file_entry:
      file_system.Close()
      raise IOError(u'Unable to retrieve file entry.')

    self._file_system = file_system
    tar_file = self._file_system.GetTarFile()
    tar_info = file_entry.GetTarInfo()

    self._tar_ext_file = tar_file.extractfile(tar_info)

    self._current_offset = 0
    self._size = tar_info.size

  # Note: that the following functions do not follow the style guide
  # because they are part of the file-like object interface.

  def read(self, size=None):
    """Reads a byte string from the file-like object at the current offset.

       The function will read a byte string of the specified size or
       all of the remaining data if no size was specified.

    Args:
      size: optional integer value containing the number of bytes to read.
            Default is all remaining data (None).

    Returns:
      A byte string containing the data read.

    Raises:
      IOError: if the read failed.
    """
    if not self._is_open:
      raise IOError(u'Not opened.')

    if self._current_offset < 0:
      raise IOError(u'Invalid current offset value less than zero.')

    if self._current_offset > self._size:
      return b''

    if size is None or self._current_offset + size > self._size:
      size = self._size - self._current_offset

    self._tar_ext_file.seek(self._current_offset, os.SEEK_SET)

    data = self._tar_ext_file.read(size)

    # It is possible the that returned data size is not the same as the
    # requested data size. At this layer we don't care and this discrepancy
    # should be dealt with on a higher layer if necessary.
    self._current_offset += len(data)

    return data

  def seek(self, offset, whence=os.SEEK_SET):
    """Seeks an offset within the file-like object.

    Args:
      offset: the offset to seek.
      whence: optional value that indicates whether offset is an absolute
              or relative position within the file. Default is SEEK_SET.

    Raises:
      IOError: if the seek failed.
    """
    if not self._is_open:
      raise IOError(u'Not opened.')

    if whence == os.SEEK_CUR:
      offset += self._current_offset
    elif whence == os.SEEK_END:
      offset += self._size
    elif whence != os.SEEK_SET:
      raise IOError(u'Unsupported whence.')

    if offset < 0:
      raise IOError(u'Invalid offset value less than zero.')
    self._current_offset = offset

  def get_offset(self):
    """Returns the current offset into the file-like object.

    Raises:
      IOError: if the file-like object has not been opened.
    """
    if not self._is_open:
      raise IOError(u'Not opened.')

    return self._current_offset

  def get_size(self):
    """Returns the size of the file-like object.

    Raises:
      IOError: if the file-like object has not been opened.
    """
    if not self._is_open:
      raise IOError(u'Not opened.')

    return self._size


"""Backend part of the weather application."""
import sqlite3
import csv
import sys
import os
import datetime
import unidecode

data_file = "data.csv"

def file_reader(data_file):
    """Open CSV file and appends data to a list."""
    ext = ext_check(data_file)
    if ext:
        with open(data_file, 'r', encoding='utf-8') as csv_file:
            reader = csv.reader(csv_file, delimiter=';')
            data = []
            for row in reader:
                data.append(row)
            return data
    elif not ext:
        return "File is not in the correct format"

def ext_check(file):
    """Check if extension is csv."""
    ext = os.path.splitext(file)
    if ext[1] == '.csv':
        return True
    else:
        return False

def process_file(file):
    """Insert values from uploaded file."""
    file = os.path.join('instance', file)
    data = file_reader(file)
    db = access_db()
    c = db.cursor()
    if type(data) is list:
        attribute_id = insert_values_to_attribute_table(data, c)
        insert_values_to_datapoints_table(data, c, attribute_id)
        db.commit()
        close_db(db)
        return "File uploaded succesfully!"
    else:
        close_db(db)
        return data

def get_attributes():
    """Get attributes from table."""
    db = access_db()
    c = db.cursor()
    sqlite_get_data = """SELECT Name, DisplayName FROM Attributes;"""
    attr_data = c.execute(sqlite_get_data)
    data_to_return = []
    for row in attr_data:
        data_to_return.append({"name": row[0], "displayName": row[1]})
    close_db(db)
    return data_to_return

def get_data(filters):
    """Get data from databases using filters."""
    db = access_db()
    c = db.cursor()
    data = c.execute(
        "SELECT ID, Unit FROM Attributes WHERE Name = ?", (filters["Argument"],))
    for bit in data:
        attr_id = bit[0]
        unit = bit[1]
    dates = filters["timeArgument"]
    if filters["timeIntervallType"] == "TIME_INTERVALL":
        start_date = dates[0]
        start_date = start_date.split("-")
        start_date[0] = int(start_date[0])
        start_date[1] = int(start_date[1])
        start_date[2] = int(start_date[2])
        end_date = dates[1]
        end_date = end_date.split("-")
        end_date[0] = int(end_date[0])
        end_date[1] = int(end_date[1])
        end_date[2] = int(end_date[2])
        sql_get_data = """SELECT * FROM Datapoints WHERE (Year >= ? AND Month >= ? AND (Day >= ? OR Month != ? OR Year != ?))
                         AND (Year < ? OR (Year = ? AND Month <= ? AND (Day <= ? OR Month != ?))) AND AttributeID = ?;"""
        datapoints_to_return = c.execute(sql_get_data, (start_date[0], start_date[1],
                                                        start_date[2], start_date[1], start_date[0],
                                                        end_date[0], end_date[0], end_date[1], end_date[2], end_date[1], attr_id))
        data_to_return = []
        for data in datapoints_to_return:
            data_to_return.append({"id": data[0],
                                   "year": int(data[1]),
                                   "month": int(data[2]),
                                   "day": int(data[3]),
                                   "time": int(data[4]),
                                   "value": data[5],
                                   "unit": unit
                                   })
        close_db(db)
        return data_to_return
    elif filters["timeIntervallType"] == "MONTH":
        month = dates[0]
        month = int(month)
        sql_get_data = "SELECT * FROM Datapoints WHERE Month = ? AND AttributeID = ?;"
        datapoints_to_return = c.execute(
            sql_get_data, (month, attr_id))
        data_to_return = []
        for data in datapoints_to_return:
            data_to_return.append({"id": data[0],
                                   "year": int(data[1]),
                                   "month": int(data[2]),
                                   "day": int(data[3]),
                                   "time": int(data[4]),
                                   "value": data[5],
                                   "unit": unit
                                   })
        close_db(db)
        return data_to_return
    close_db(db)

def insert_values_to_datapoints_table(data, c, attribute_id):
    """Seperate string of data into comma seperated values.
    and add to datapoint table.
    """
    date_index = 0
    for row in data:
        if len(row) != 0 and row[0] == "Datum" and row[1] == "Tid (UTC)":
            date_index = data.index(row)
    for row in range((date_index + 1), len(data)):
        date = datetime.datetime.fromisoformat(data[row][0])
        time = datetime.datetime.strptime(data[row][1], '%H:%M:%S')
        sql_insert = "INSERT INTO Datapoints(Year, Month, Day, Time, Value, AttributeID) VALUES ( ?, ?, ?, ?, ?, ?)"
        c.execute(sql_insert, (date.year, date.month, date.day,
                               time.hour, data[row][2], str(attribute_id)))

def insert_values_to_attribute_table(data, c):
    """Check for special characters and replace with english alphabet
    (if necessary) and add to datapoint table."""
    parameter_index_column = 0
    attribute_index_column = 0
    parameter_index_row = 0
    attribute_index_row = 0
    string_to_add = ""
    for row in data:
        if len(row) != 0 and "Parameternamn" in row:
            parameter_index_column = row.index("Parameternamn")
            parameter_index_row = data.index(row)
            break
    for row in data:
        if len(row) != 0 and "Enhet" in row:
            attribute_index_column = row.index("Enhet")
            attribute_index_row = data.index(row)
            break
    sql_insert = " INSERT INTO Attributes (Name, DisplayName, Unit) VALUES ( ?, ?, ?)"
    c.execute(sql_insert, (unidecode.unidecode(data[parameter_index_row + 1][parameter_index_column]).lower(
    ), data[parameter_index_row + 1][parameter_index_column], data[attribute_index_row + 1][attribute_index_column]))
    return c.lastrowid

def access_db():
    """Retrieve database."""
    db = sqlite3.connect(
        'instance\\weather_data.db',
        detect_types=sqlite3.PARSE_DECLTYPES
    )
    db.row_factory = sqlite3.Row
    return db

def close_db(db):
    """Close database connection."""
    db.close()

def initialize_database():
    """Creates database (if it does not exist)."""
    sql_create_datapoints_table = """CREATE TABLE IF NOT EXISTS Datapoints (
        ID integer PRIMARY KEY,
        Year integer,
        Month integer,
        Day integer,
        Time integer,
        Value real,
        AttributeID integer);"""
    sql_create_attributes_table = """CREATE TABLE IF NOT EXISTS Attributes(
        ID integer PRIMARY KEY,
        Name text,
        DisplayName text,
        Unit text
        );"""
    db = access_db()
    c = db.cursor()
    c.execute("PRAGMA foreign_keys = ON;")
    attributes_table = c.execute(sql_create_attributes_table)
    datapoints_table = c.execute(sql_create_datapoints_table)
    db.commit()
    list_of_values = file_reader(data_file)
    attribute_id = insert_values_to_attribute_table(list_of_values, c)
    insert_values_to_datapoints_table(list_of_values, c, attribute_id)
    db.commit()
    print('Database successfully created!')
    close_db(db)

if __name__ == '__main__':
    globals()[sys.argv[1]]()


import sys

def main():
    if len(sys.argv) < 2:
        sys.exit("Too few command-line arguments")
    elif len(sys.argv) > 2:
        sys.exit("Too many command-line arguments")
    if not sys.argv[1].endswith(".py"):
        sys.exit("Not a Python file")
    i = 0
    try:
        with open(sys.argv[1], "r") as file:
            lines = file.readlines()
        for _ in lines:
            if not _.strip().startswith("#") and _.strip():
                i += 1
        print(i)
    except FileNotFoundError:
        sys.exit("File does not exist")

if __name__ == "__main__":
    main()


class Solution(object):
    # recursive
    def maxDepth(self,root):
        if not root:
            return 0
        if not root.children: return 1
        return max(self.maxDepth(node) for node in root.children) + 1

    # BFS (use a queue, the last level we see will be the depth)

    def maxDepth2(self,root):
        queue = []
        if root:
            queue.append((root,1))
        depth = 0
        for(node,level) in queue:
            depth = level
            queue +=[(child, level+1) for child in node.children]
        return depth

    # DFS (use a stack, use max to update depth)
    def maxDepth3(self,root):
        stack =[]
        if root: stack.append((root, 1))
        while stack:
            (node, d) = stack.pop()
            depth = max(depth, d)
            for child in node.children:
                stack.append((child, d+1))
        return depth


import time
import sys

def delay_print(s):
    for c in s:
        sys.stdout.write(c)
        sys.stdout.flush()
        time.sleep(0.15)

def error_checking(command, size):
   try:
       command = command.replace(".", "")
       command = int(command)

   except ValueError:
       print("You must choose one of the number options!")
       return -1

   if (int(command) < 1) or (int(command) > size):
       print("You must choose one of the number options!")
       return -1

   return int(command)

def ls():
    delay_print(">help ls\n")
    print("The 'ls' command displays all the directories and files in the current directory")
    input("Press enter to continue...")

def cd():
    delay_print(">help cd\n")
    print("The 'cd' command lets you choose a new directory to move to")
    print("Example: 'cd Pictures' changes to the Pictures directory")
    input("Press enter to continue...")

def cat():
    delay_print(">help cat\n")
    print("The 'cat' command lets you print a file's contents to the screen")
    print("Example: 'cat mypasswords.txt' will print any text in the file to this screen")
    input("Press enter to continue...")

def ssh():
    delay_print(">help ssh\n")
    print("The 'ssh' command allows you to switch to a different user on a network using the username and password")
    print("Example: 'ssh burd@192.168.0.2' will switch to burd on the 192.168.0.2 network")
    input("Press enter to continue...")

def nmap():
    delay_print(">help nmap\n")
    print("The 'nmap' command allows you to see all the services and ports running on an IP")
    print("Example: 'nmap burd@192.168.0.2' will show all the services and ports for the user burd")

def helphelp():
    delay_print(">help help\n")
    print("Seriously?... \nThe 'help' command gives information on how to use different commands")
    input("Press enter to continue...")

def level1main():
    while True:
        print("What command do you need help with? \n1. ls \n2. cd \n3. cat \n4. ssh \n5. help \n6. Go back")
        userinput = error_checking(input(">"), 5)
        if userinput == -1:
            return
        if userinput == 1:
            ls()
        if userinput == 2:
            cd()
        if userinput == 3:
            cat()
        if userinput == 4:
            ssh()
        if userinput == 5:
            help(1)
        if userinput == 6:
            return
def level2main():
    while True:
        print("What command do you need help with? \n1. ls \n2. cd \n3. cat \n4. ssh \n5. nmap \n6. help \n7. Go back")
        userinput = error_checking(input(">"), 7)
        if userinput == -1:
            return
        if userinput == 1:
            ls()
        if userinput == 2:
            cd()
        if userinput == 3:
            cat()
        if userinput == 4:
            ssh()
        if userinput == 5:
            nmap()
        if userinput == 6:
            help(1)
        if userinput == 7:
            return
def level3main():
    while True:
        print("What command do you need help with? \n1. ls \n2. cd \n3. cat \n4. ssh \n5. help \n6. Go back")
        userinput = error_checking(input(">"), 6)
        if userinput == -1:
            return
        if userinput == 1:
            ls()
        if userinput == 2:
            cd()
        if userinput == 3:
            cat()
        if userinput == 4:
            ssh()
        if userinput == 5:
            help(1)
        if userinput == 6:
            return

def help (level):
    if level == 1:
        level1main()
    if level == 2:
        level2main()
    if level == 3:
        level3main()


import os.path as path

def thank_you(donor_dict):
    #Record single donation and thank donor
    fullname = input('What is the full name of the donor? Type list to see donors. Type exit to quit task \n')
    if fullname.lower() == 'list':
        print(list(donor_dict.keys()))
    elif fullname.lower() == "exit":
        return None
    else:
        #Find donor in list or create a new one
        if fullname not in donor_dict:
            donor_dict[fullname] = []
        newdonation = float(input('What is the value of the donation (numbers only)?\n'))
        donor_dict[fullname].append(newdonation)

        #Print the thank you email
        print(f'Dear {fullname}, \n Thank you for your generous donation. We appreciate the support from people like you. \n Thank you,\n Charity Name')

def create_report(donor_dict):
    # Create report data from donor list
    donor_report = dict()

    for name in donor_dict:
        donations = len(donor_dict[name])
        # Add up all donations
        total_given = sum(donor_dict[name])
        avg_gift = total_given / donations
        donor_report[name] = [total_given,donations,avg_gift]

    name_lst = list(donor_report.keys())
    name_lst_sorted = sorted(name_lst, key = lambda name:donor_report[name][0],reverse=True)

    # Format report
    header = ['Name', 'Total Given', '# of Gifts', 'Average Gift']
    header_format = "{:<20}" + "{:^15}" + "{:^15}" + "{:^10}"
    row_name_format = "{:<20}"
    row_data_format = "${:>15.2f}" + "{:^15}" + "${:>10.2f}"

    print(header_format.format(*header))
    print('-' * 70)
    for name in name_lst_sorted:
        print(row_name_format.format(name) + row_data_format.format(*donor_report[name]))

def thank_all(donor_dict):
    #Generates .txt files of Thank Yous for all donors
    directory = input('What file path do you want the Thank You notes to be in? \n')
    for donor in donor_dict:
        filename = donor.replace(" ","") + ".txt"
        full_filename = path.join(directory,filename)
        with open(full_filename,'w') as f:
            f.write(f'Dear {donor}, \n Thank you for your generous donation. We appreciate the support from people like you. \n Thank you,\n Charity Name')

if __name__ == "__main__":

    #Donors
    donor_dict = {'Luke Skywalker':[10,20,30], 'Leslie Knope':[100,300],'Dwight Schrute':[345,345345],'Freddie Mercury':[23532,32],'Jennifer Aniston':[235,2352]}

    #MAIN
    while True:
        print("Options: \n 1 - Send a Single Thank You \n 2 - Create Report \n 3 - Send all donors Thank You \n 4 - Exit ")
        response = input('What would you like to do?\n')
        switch_dict = {'1':thank_you,'2':create_report,'3':thank_all}

        if response in switch_dict:
            switch_dict[response](donor_dict)

        #Exit Program
        elif response =='4':
            break

        #Require valid input
        else:
            print("Please pick a valid option")


###################################################################
#                                                                 #
#         Contains sample problem generator for sample.in         #
#                                                                 #
###################################################################

import sys

sys.path.append("../..")

import src.mesh
import src.input

def sampleProblemGenerator(
    pin: src.input.PsychoInput, pmesh: src.mesh.PsychoArray
) -> None:
    """Generates the problem in by inputting the information to the problem mesh

    This function is called in `main.py` and sets the initial conditions
    specified in the problem input (pin) onto the problem mesh (pmesh).

    Needs to exist for each problem type in order for everything to work.

    Parameters
    ----------
    pin : PsychoInput
        Contains the problem information stored in the PsychoInput
        object

    pmesh : PsychoArray
        PsychoArray mesh which contains all of the current mesh information
        and the conserved variables Un

    """

    rho0 = pin.value_dict["rho0"]
    p0 = pin.value_dict["p0"]
    u0 = pin.value_dict["u0"]
    v0 = pin.value_dict["v0"]

    pmesh.Un[0, :, :] = rho0
    pmesh.Un[1, :, :] = rho0 * u0
    pmesh.Un[2, :, :] = rho0 * v0
    # pmesh.arr[3,:,:] = rho0 * total energy

    return


import os
commandln = input("Input your command ('r' để khởi động lại máy/ 's' để tắt máy) ")
timewait = int(input("Nhập thời gian chờ "))
if commandln == 'r':
    os.system("shutdown -t 0 -r -f {timewait}")
elif commandln == 's':
    os.system("shutdown -s -t {timewait}")
else:
    print("Không hợp lí! ")
stopcommandln = input("Bạn có muốn dừng không? (y/n) ")
if stopcommandln == 'y':
    os.system("shutdown -a")
elif stopcommandln == 'n':
    print("Đã bỏ qua stopcommandln.")
else:
    print("")

_T/tự động tắt máy và restart máy/exe.py


import os
import socket

"""
Tutorial

Source: https://realpython.com/python-sockets/
"""

if __name__ == "__main__":
    HOST = "127.0.0.1"  # localhost
    PORT = 65432

    # Becasue socket.socket() creates a socket object that supports the context manager type, so you can use it in a with statement. There’s no need to call s.close():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()

        conn, addr = s.accept()  # Blocks and provides new socket

        with conn:
            print(f"Connected by {addr}")
            while True:
                data = conn.recv(1024)
                if not data:
                    break
                conn.sendall(data) # Echoes back


from tkinter import *
from PIL import ImageTk, Image
import cv2
import csv
import face_recognition
import numpy as np
import pickle
from numpy import savetxt
import datetime
import time
import os.path

# Capture frames from Camera #
cap = cv2.VideoCapture(0)
medText = 28

# Initialise Variables for locations and encodings #
face_locations = []
face_encodings = []
face_names = []

# Security Path and time Ranges #
image_path = "./security/"
start = datetime.time(10, 15)
end = datetime.time(11)

# Some code used from https://github.com/ageitgey/face_recognition/blob/master/examples/facerec_from_webcam_faster.py #

class Cam(Frame):
    def __init__(self, parent, event_name="", *args, **kwargs):
        Frame.__init__(self, parent, bg='black')
        self.title = "Unknown"

        # Shows name of user being detected #
        self.infoText = "Recognising Face: "
        self.info = Label(self, text=self.infoText, font=('Helvetica', medText), fg="blue", bg="black")
        self.userName = Label(self, text=self.title, font=('Helvetica', medText), fg="white", bg="black")
        if event_name != "enable":
            self.info.pack(side=LEFT, anchor=W)
        self.userName.pack(side=TOP, anchor=CENTER)
        self.lmain = Label(self)

        # Enable camera preview (enabled from Mirror.py) #
        if event_name == "enable":
            self.lmain.pack(side=TOP)
        self.video()

    def readUserName(self):
        return self.userName.cget("text")

    def video(self):
        process_this_frame = True
        # Reads pickle data from file that stores facial data #
        with open('./webserver/dataset_faces.dat', 'rb') as f:
            all_face_encodings = pickle.load(f)
        known_face_encodings = np.array(list(all_face_encodings.values()))
        known_face_names = list(all_face_encodings.keys())

        # Open CV resizing and changing the colour of the frame #
        ret, frame = cap.read()
        small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
        rgb_small_frame = small_frame[:, :, ::-1]
        if process_this_frame:
            # Reading face locations and encodings #
            face_locations = face_recognition.face_locations(rgb_small_frame)
            face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
            face_names = []
            name = "No User Detected"
            self.userName.config(text = name)
            # Checking if Face measurements match to ones in dataset_faces.dat #
            for face_encoding in face_encodings:
                matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
                name = "Unknown"
                self.userName.config(text = name)
                face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
                best_match_index = np.argmin(face_distances)
                if matches[best_match_index]:
                    name = known_face_names[best_match_index]
                    self.userName.config(text = name)
                else:
                    # Unknown user detected during time range #
                    timestamp = datetime.datetime.now().time()
                    check = start <= timestamp <= end
                    # If user is unknown and the time is in the time range - Save the frame #
                    if check == True:
                        timestamp2 = datetime.datetime.now()
                        timestampStr = timestamp2.strftime("%d_%b_%Y__%H_%M_%S")
                        timestampStrFilePath = timestamp2.strftime("%d_%b_%Y")
                        directory = image_path + timestampStrFilePath + "/"
                        if not os.path.isdir(directory):
                            os.mkdir(directory)
                        filename = timestampStr + ".jpg"
                        filepath = os.path.join(directory, filename)
                        cv2.imwrite(filepath, frame)
                face_names.append(name)
        process_this_frame = not process_this_frame
        # Used for Camera preview #
        for (top, right, bottom, left), name in zip(face_locations, face_names):
            top *= 4
            right *= 4
            bottom *= 4
            left *= 4
            cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
            cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
            font = cv2.FONT_HERSHEY_DUPLEX
            cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
        img = Image.fromarray(frame)
        imgtk = ImageTk.PhotoImage(image=img)
        self.lmain.imgtk = imgtk
        self.lmain.configure(image=imgtk)
        self.lmain.after(1, self.video)


'''
Thomas Mullins
Definition: Write a program that calculates and displays information about a
flight sale from MSP to CHI.
Final1.py
5/9/19
'''
#Define main
import pyinputplus as pyip
def main():
    #Exception handling
    while True:
        try:
            tickets, bags = input1()
            ticket_total, bag_total, total, tax, admin_fee, final_total, final_tax = processing1(tickets, bags)
            output1(ticket_total, bag_total, total, tax, admin_fee, final_total, tickets, bags, final_tax)
        except Exception as err:
            print(err)
        #Repeat function
        answer = input('Would you like to run this program again? Enter Y or N: ')
        while answer.upper() != 'Y' and answer.upper() != 'N':
            answer = input('Please enter Y or N: ')

        if answer.upper() == 'NO':
            print(f'\nThank for using the program')
            break

def input1():
    #User input
    print('Welcome to Andy\'s Flight Club!')
    print('Limit of 4 tickets & 2 suitcases ($20ea) per passenger.\n')
    tickets = input('Enter the number of tickets up to 4: ')
    #Validation for tickets
    while tickets.isnumeric() is False or int(tickets) >= 5 or int(tickets) == 0:
        tickets = input('\t\tEnter 1, 2, 3, 4 only: ')

    #Validation for bags
    bags = input('Enter the number of suitcases up to 2 per ticket: ')
    bags_allowed = int(tickets)*2
    while bags.isnumeric() is False or int(bags) < 0 or int(bags) > (int(tickets)*2):
        bags = input(f'Enter 0 through {bags_allowed} for your {tickets} tickets:')

    return tickets, bags

def processing1(tickets, bags):
    #Processing all totals
    ticket_total = tickets*123
    ticket_total = float(ticket_total)
    bag_total = bags*20
    bag_total = float(bag_total)
    total = bags+tickets
    tax = 0.075 *total
    final_tax = tax*100
    final_tax = float(final_tax)
    admin_fee = 10 * tickets
    admin_fee = float(admin_fee)
    final_total = total+tax+admin_fee

    return ticket_total, bag_total, total, tax, admin_fee, final_total, final_tax
#User output for all final prices
def output1(ticket_total, bag_total, total, tax, admin_fee, final_total, tickets, bags, final_tax):
    print('\nThanks for using Andy\'s Flight Club Calculator!')
    print('{:<20}{:>13}{:>9.2f}'.format(str(tickets)+'tickets @ $123 each', '$', ticket_total))
    print('{:<20}{:>12}{:>9.2f}'.format(str(bags) + 'suitcases @ $20 each', '$', bag_total))
    print('{:<20}{:>4}{:>9.2f}'.format('7.5% Tax (Tickets & suicases)', '$', final_tax))
    print('{:<20}{:>6}{:>9.2f}'.format('Admin Fees @ $10 per person', '$', admin_fee))
    print('{:<20}{:>6}{:>9.2f}'.format('Totla cost for your journey', '$', final_total))

main()


# Aurelia Arnett
# Purpose: To load Tweets from database collections stored in MongoDB server & initial data discovery
# The tweets that are loaded in are from two different user timeline collections: @airbnb and @vrbo

import pymongo

client = pymongo.MongoClient('localhost', 27017) # call the server

# Part 1: Read in JSON formatted data from two Mongo DB collections (@Airbnb and @Vrbo)
# Tweets have been collected using the run_twitter_simple_search_save.py and the TweetAuth.py programs
# This component returns Tweets with from user timeline query collected & stored in the MongoDB server

#Airbnb
db1 = client.airbnbtimeline #define a term for the @Airbnb db
dbcoll1 = db1.airbnbs #define a term for the @Airbnb db collection

#VRBO
db2 = client.vrbotimeline #define a term for the @Vrbo db
dbcoll2 = db2.vrbos #define a term for the @Vrbo db collection

# Find Tweets that are in English and convert them from JSON structures into a standard python list
#Airbnb
tweets_airbnb=dbcoll1.find() #search through  the @Airbnb db collection
for tweet in tweets_airbnb:
   if tweet['lang'] == 'en': # return Tweets in English only
      tweetlist_airbnb = [tweet for tweet in tweets_airbnb]
#VRBO
tweets_vrbo=dbcoll2.find() #define a term for the @Vrbo db collection
for tweet in tweets_vrbo:
   if tweet['lang'] == 'en':
      tweetlist_vrbo = [tweet for tweet in tweets_vrbo]

# Define a function that will print the 1st Tweet in a collection
def print_tweet_data(tweets):
   for tweet in tweets:
         print('User:', tweet['user']['name'])
         print('Message:', tweet['text'])
         print('Hashtags:', [hashtag['text'] for hashtag in tweet['entities']['hashtags']] )
         print('Number of retweets:', tweet['retweet_count'])
         if not tweet['place'] is None:
            print('Place:', tweet['place']['full_name'])

#print the first Tweet in each collection
print('Example tweet from the Airbnb Collection:')
print('Total Tweets in collection', len(tweetlist_airbnb))
print_tweet_data(tweetlist_airbnb[:1])
print()
print('Example tweet from the VRBO Collection:')
print('Total Tweets in collection', len(tweetlist_vrbo))
print_tweet_data(tweetlist_vrbo[:1])
print()

# Part 2: Count total number of retweets in each timeline collection
countretweetsAirbnb = 0
for tweet in tweetlist_airbnb: #sort through the @airbnb timeline collection to find retweet info
   if int(tweet['retweet_count']) > 1:
      countretweetsAirbnb += 1 #count total number of retweets
#print(countretweetsAirbnb)

countretweetsVrbo = 0
for tweet in tweetlist_vrbo: #sort through the @vrbo timeline collection to find retweet info
   if int(tweet['retweet_count']) > 1:
      countretweetsVrbo += 1 #count total number of retweets
#print(countretweetsVrbo)

# Part 3: Export retweet information to a csv file
import csv
outfile = "4-1compareRetweets.csv" #Name of output csv file
with open(outfile, 'w', newline='') as csvfileout:
   retweetWriter = csv.writer(csvfileout, delimiter=',', quoting=csv.QUOTE_MINIMAL) #define the row writer
   retweetWriter.writerow(['Timeline Collection', 'Total number of retweets'])
   retweetWriter.writerow(['@Airbnb', countretweetsAirbnb]) #information on Airbnb
   retweetWriter.writerow(['@Vrbo', countretweetsVrbo]) #information on Vrbo
   retweetWriter.writerow(['for a collection of 1999 Tweets from the @Airbnb timeline collection & 1999 Tweets from the @Vrbo timeline'])
csvfileout.close()

Scripting - Airbnb Ratings/Store-MongoDB.py


from itertools import combinations as combos
import re
import typing as t
import numpy as np

try:
    from IPython.core.display import HTML
except ImportError:
    HTML = None

from ..text import lowers

class _Conflict:
    def __init__(self, *terms: t.Tuple[t.Union["_Conflict", str]]):
        self.terms = []
        for term in terms:
            if isinstance(term, _Conflict):
                self.terms.extend(term.terms)
            else:
                self.terms.append(term)

    def add(self, term: str):
        self.terms.append(term)

class ValInfo(t.NamedTuple):
    '''Info about a single possible value in a logic grid.

    cat - the string name of the category it belongs to
    val - the actual value
    fullname - a unique identifier for this value, typically "<cat>:<val>"
    idx - the index in the category list corresponding to this value
    '''
    cat: str
    val: str
    idx: int

    @property
    def fullname(self) -> str:
        return '{}:{}'.format(self.cat, self.val)

    def __str__(self) -> str:
        return self.fullname

class AmbiguityError(KeyError):
    def __init__(self, value: str, conf: _Conflict):
        if len(conf.terms) == 2:
            a, b = conf.terms
            super().__init__(f'{value} could be {a} or {b}')
        else:
            terms = ', '.join(str(t) for t in conf.terms)
            super().__init__(f'{value} could be any of: {terms}')
        self.value = value
        self.conf = conf

class CatMan:
    '''Manager for discrete categories.

    The input should be a dict or dict-like object whose keys are the names of
    the categories and whose values are ordered lists of the possible values in
    each category.

    This object allows you to get information about a value in an intelligent
    way. For example:

    >>> c = CatMan(dict(
    ...     color=['red', 'green', 'blue'],
    ...     size=['small', 'medium', 'large']))
    >>> c['color:red']
    ValInfo(cat='color', val='red', idx=0)
    >>> c['red']
    ValInfo(cat='color', val='red', idx=0)

    Different categories can have overlapping values; you'll get an
    AmbiguityError if you try to use an ambiguous unqualified name:

    >>> c = CatMan(dict(
    ...    name = ['Alice', 'Violet'],
    ...    color = ['Red', 'Violet']))
    >>> c['color:Violet']
    ValInfo(cat='color', val='Violet', idx=1)
    >>> c['name:Violet']
    ValInfo(cat='name', val='Violet', idx=1)
    >>> c['Violet']
    Traceback (most recent call last):
        ...
    puztool...AmbiguityError: 'Violet could be name:Violet or color:Violet'
    '''

    def __init__(self, cats):
        self.catmap = {}
        self.lookup = {}
        self.categories = list(cats)
        for cat, domain in cats.items():
            self.catmap[cat] = []
            for idx, val in enumerate(domain):
                info = ValInfo(cat, val, idx)
                self.catmap[cat].append(info)
                self.lookup[info.fullname] = info
                old = self.lookup.get(info.val)
                if old is None:
                    self.lookup[info.val] = info
                else:
                    self.lookup[info.val] = _Conflict(old, info)

    @property
    def num_cats(self):
        return len(self.catmap)

    @property
    def num_items(self):
        return len(self.catmap[self.categories[0]])

    def domain(self, cat):
        return self.catmap[cat]

    @property
    def all_domains(self):
        return self.catmap

    def get_info(self, value, cat=None):
        '''Get info about a value.

        If the input is a ValInfo, it'll just be returned. Otherwise, we return
        the ValInfo from our internal lookup table, raising a KeyError if it's
        not there or an AmbiguityError if it's an ambiguous name.
        '''
        if isinstance(value, ValInfo):
            return value
        v = self.lookup.get(value, None)
        if v is None:
            raise KeyError(value)
        if isinstance(v, _Conflict):
            if cat is not None:
                value = '{}:{}'.format(cat, value)
                return self.get_info(value)
            raise AmbiguityError(value, v)
        return v

    def get_cat(self, value):
        return self.get_info(value).cat

    def get_fullname(self, value):
        return self.get_info(value).fullname

    def get_index(self, value):
        return self.get_info(value).idx

    def __getitem__(self, key):
        if isinstance(key, (list, tuple)):
            name, val = key
            key = f'{name}:{val}'
        if key in self.lookup:
            return self.get_info(key)
        return self.catmap[key]

class CatGrid(CatMan):
    '''A logic grid.

    The input is a dictionary of categories where each key is a category name
    and each value is a list or set of possible values for one category (the
    order within each column is irrelevant).

    The input can also be a pandas DataFrame where the column names are the
    category names and the values are the category values.

    The CatGrid then creates a bunch of numpy object arrays, such that
    g.grids[key1][key2][x,y] indicates whether the row with value x for key1
    has value y for key2.

    For example, suppose your data is three names, favorite colors, and signs:

    >>> from puztool.parse import parse_table
    >>> frame = parse_table("""
    ... name      color   sign
    ... Brita     Blue    Ares
    ... Galal     Green   Scorpio
    ... Parvaneh  Red     Virgo
    ... """, header=0)
    >>> g = CatGrid(frame)

    Each value gets assigned a unique name of the form <category>:<value>. In
    the above case, for example, 'name:Brita' refers to the value 'Brita' in
    the name category. However, the helper functions will also infer the
    category if the term is unambiguous - 'Brita' also refers to that value
    (but it would not if 'Brita' was also a value in another category).
    '''

    def __init__(self, categories):
        super().__init__(categories)
        self.pairs = list(combos(self.categories, 2))  # this comes up a lot
        self.grids = {n: {} for n in self.categories}
        for f1, f2 in self.pairs:
            g = np.empty((self.num_items, self.num_items), dtype='object')
            # Both entries point to different views of the same matrix
            self.grids[f1][f2] = g
            self.grids[f2][f1] = g.T

    def exclude(self, *vals):
        '''Indicate that these values are mutually exclusive.

        This marks all intersections of values in vals as False.
        '''
        infos = map(self.get_info, vals)
        for i1, i2 in combos(infos, 2):
            if i1.cat == i2.cat:
                continue
            self.grids[i1.cat][i2.cat][i1.idx, i2.idx] = False

    def require(self, *vals):
        '''Indicate that these values must go together

        This marks all intersections of values in vals as True.

        It will complain if two values are from the same category, as requiring
        both would mean there are no solutions to the grid.
        '''
        infos = map(self.get_info, vals)
        for i1, i2 in combos(infos, 2):
            if i1.cat == i2.cat:
                msg = "Cannot require both {} and {}".format(i1, i2)
                raise ValueError(msg)
            self.grids[i1.cat][i2.cat][i1.idx, i2.idx] = True

    def requireOne(self, first, options):
        '''Indicate that one of options must go with first.

        All values in options should be from the same category, and first
        should be from a different one.
        '''
        i1 = self.get_info(first)
        options = [self.get_info(opt) for opt in options]
        categories = set(opt.cat for opt in options)
        if len(set(categories)) > 1:
            raise ValueError(
                "requireOne options must be in a single category.")
        cat = list(categories)[0]
        g = self.grids[i1.cat][cat]
        old = list(g[i1.idx, :])
        g[i1.idx, :] = False
        for i2 in options:
            g[i1.idx, i2.idx] = old[i2.idx] or None

    # Helpers for jsingler.de links
    def _get_encoded_grid(self, val):
        # Map each category to a letter and return the list of entries matching
        # val in the form e.g. a3b5
        letters = dict(zip(self.categories, lowers))
        for f1, f2 in self.pairs:
            a = letters[f1]
            b = letters[f2]
            for i in range(self.num_items):
                for j in range(self.num_items):
                    if self.grids[f1][f2][i, j] == val:
                        yield '{}{}{}{}'.format(a, i, b, j)

    def _encl(self, items):
        return '!({})'.format(','.join(str(e) for e in items))

    def _get_params(self):
        d = dict(at='s', ms='s', nc=self.num_cats, ni=self.num_items, v=0)
        encl = self._encl

        def esc(s):
            # The escaping they use seems a little weird so I didn't bother.
            # Just strip any chars that would ruin the link.
            return re.sub(r'\W', '', s)
        items = []
        for cat in self.categories:
            items.append(encl(esc(str(x.val)) for x in self.domain(cat)))
        d['items'] = encl(items)
        d['n'] = encl(self._get_encoded_grid(False))
        d['p'] = encl(self._get_encoded_grid(True))
        return ','.join('{}:{}'.format(k, v) for (k, v) in d.items())

    def get_link(self):
        '''Get a link that will display this grid on jsingler.de'''
        base = 'http://www.jsingler.de/apps/logikloeser/?language=en#({})'
        return base.format(self._get_params())

    def html_link(self):
        '''get_link, but returns an HTML object that ipython can display.'''
        link = self.get_link()
        if HTML is None:
            return link
        return HTML("{0}".format(link))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/5/20 14:37
# @Author  : shiman
# @File    : drawing_utils.py
# @describe:

import torch
import colorsys

import matplotlib.pyplot as plt

def show_images(imgs, num_rows, num_cols, scale=1.5, titles=None):
    """展示多个图片"""
    figsize = (num_cols*scale, num_cols*scale)  # 定义展示图片尺寸
    _, axes = plt.subplots(num_rows, num_cols, figsize=figsize)
    axes = axes.flatten()
    for i, (img, ax) in enumerate(zip(imgs, axes)):
        if torch.is_tensor(img):
            ax.imshow(img.numpy())
        else:
            ax.imshow(img)
        ax.axes.get_xaxis().set_visible(False)  # 不展示XY轴刻度
        ax.axes.get_yaxis().set_visible(False)
        if titles:
            ax.set_title(titles[i])

def apply(image, aug, num_rows=2, num_cols=4, scale=1.5):
    """定义图像增广方法"""
    y = [aug(image) for _ in range(num_cols*num_rows)]
    show_images(y, num_rows, num_cols, scale=scale)

def get_color_bar(classes_num):
    hsv_tuple = [(1.0 * x/classes_num, 1, 1) for x in range(classes_num)]
    rgb_tuple = [colorsys.hsv_to_rgb(*x) for x in hsv_tuple]
    rgb_tuple = [(int(x[0]*255), int(x[1]*255), int(x[2]*255)) for x in rgb_tuple]


from matplotlib.pyplot import waitforbuttonpress
import numpy as np
import torch
from torch.backends import cudnn
cudnn.enabled = True
import imageio
import importlib
from tool import imutils
import argparse
import cv2
import os.path
import torch.nn.functional as F
from DPT.DPT import DPTSegmentationModel
from myTool import *
from tool.metrics import Evaluator
from PIL import Image
from pycocotools.coco import COCO
from pycocotools import mask

def getImgId(name, load_dict):
	# load_dict = json.load(open(path, 'r'))
	images = load_dict['images']

	for i in range(len(images)):
		file_name = images[i]['file_name'].split('.')[0]
		if file_name == name:
				#print(images[i])
				return images[i]['id']

cls_dict = {}
for index, item in enumerate(coco_classes):
    category_id = item['id']
    cls_dict[index] = category_id

base_dir = '/home/users/u5876230/coco/'
ann_file = os.path.join(base_dir, 'annotations/instances_{}{}.json'.format('val', 2014))
coco = COCO(ann_file)
coco_mask = mask
CAT_LIST = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
                24, 25, 27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49,
                50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 70, 72, 73, 74, 75,
                76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]

def get_coco_gt(name, h, w):
    img_id = getImgId(name, coco.dataset)

    cocotarget = coco.loadAnns(coco.getAnnIds(imgIds=img_id))
    mask = np.zeros((h, w), dtype=np.uint8)
    # print(cocotarget)
    for instance in cocotarget:
        rle = coco_mask.frPyObjects(instance['segmentation'], h, w)
        m = coco_mask.decode(rle)
        cat = instance['category_id']

        if cat in CAT_LIST:
            c = CAT_LIST.index(cat)

        else:
            continue
        if len(m.shape) < 3:
            mask[:, :] += (mask == 0) * (m * c)
        else:
            mask[:, :] += (mask == 0) * (((np.sum(m, axis=2)) > 0) * c).astype(np.uint8)
    return mask

def _crf_with_alpha(pred_prob, ori_img):
    bgcam_score = pred_prob.cpu().data.numpy()
    crf_score = imutils.crf_inference_inf(ori_img, bgcam_score, labels=81)

    return crf_score

if __name__ == '__main__':
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"] = '0'

    parser = argparse.ArgumentParser()
    parser.add_argument("--weights", default='./netWeights/RRM_final.pth', type=str)
    parser.add_argument("--out_cam_pred", default='./output/result/no_crf', type=str)
    parser.add_argument("--out_la_crf", default='./output/result/crf', type=str)
    parser.add_argument("--out_color", default='./output/result/color', type=str)
    parser.add_argument("--LISTpath", default="./voc12/val(id).txt", type=str)
    parser.add_argument("--IMpath", default="/home/users/u5876230/coco/val2014/", type=str)
    parser.add_argument("--val", default=False, type=bool)

    args = parser.parse_args()

    evaluator = Evaluator(num_class=81)
    im_path = args.IMpath
    img_list = os.listdir('/home/users/u5876230/coco/val2014/')

    print(len(img_list))
    pred_softmax = torch.nn.Softmax(dim=0)
    # img_list = ['2007_000464 ']
    for index, i in enumerate(img_list):
        print(i)
        print(index)
        # i = ((i.split('/'))[2])[0:-4]
        i= i[0:-3]

        print(os.path.join(im_path, i[:-1] + '.jpg'))
        img_temp = cv2.imread(os.path.join(im_path, i[:-1] + '.jpg'))

        h, w, _ = img_temp.shape
        img_original = img_temp.astype(np.uint8)

        if args.val==True:

            target_path = os.path.join('/home/users/u5876230/coco/segmentation/', '{}.png'.format(i[:-1]))
            target = np.asarray(Image.open(target_path), dtype=np.int32)
            name = i[:-1]
            print(name)
            seg_mask = get_coco_gt(name, h, w)
            print(seg_mask)
            print(np.unique(seg_mask))


from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from subprocess import run
import drive

class Notepad():
    def __init__(self):
        self.window = Tk()
        self.window_title = None
        self.window_icon = None
        self.menu_bar = None
        self.status_bar = None
        self.text_box = None
        self.text = None

        self.file_path = None
        self.file_name = None
        self.file_dialog = None

    def update_variables(self):
        try:
            self.file_path = self.file_dialog.name
            self.file_name = self.file_path.split('/')[-1]
            self.window_title = self.window.title(self.file_name)
        except AttributeError:
            pass

    def get_text(self):
        self.text = self.text_box.get('1.0', END)
        self.save_text()

    def save_text(self):
        self.file_dialog = filedialog.asksaveasfile(mode='w')
        self.update_variables()
        if self.file_dialog is not None:
            self.file_dialog.write(self.text)
            self.status_bar['text'] = 'Saved!'
            self.set_status_bar_color('green', 'white')
            self.file_dialog.close()

    def open_file(self):
        self.text_box.delete('1.0', END) # clear textbox before opening new file

        self.file_dialog = filedialog.askopenfile(mode='r')
        self.update_variables()
        if self.file_dialog is not None:
            self.text_box.insert(INSERT, self.file_dialog.read())
            self.status_bar['text'] = 'Opened!'
            self.set_status_bar_color(bg='green', fg='white')
            self.file_dialog.close()

    def upload_to_drive(self):
        drive.main()
        drive.upload(self.file_name, self.file_path, 'text/txt')
        self.status_bar['text'] = 'Uploaded!'
        self.set_status_bar_color(bg='green', fg='white')

    def confirm_quit(self):
        answer = messagebox.askyesnocancel("Quit?", "Are you sure you want to quit?")
        if answer == True:
            quit()

    def set_status_bar_color(self, bg='black', fg='white'):
        self.status_bar.configure(bg=bg, fg=fg)

    def key(self, event):
        key_pressed = event.char
        if key_pressed == '(':
            self.text_box.insert(INSERT, ')')
        if key_pressed == '[':
            self.text_box.insert(INSERT, ']')
        if key_pressed == '{':
            self.text_box.insert(INSERT, '}')
        if key_pressed == '\"':
            self.text_box.insert(INSERT, '\"')
        if key_pressed == '\'':
            self.text_box.insert(INSERT, '\'')

    def run(self):
        if ".py" in self.file_path:
            command = r"python " + self.file_path
            output = run(command)
        elif ".java" in self.file_path:
            compiler = r"javac " + self.file_path
            run(compiler)
            command = r"java" + self.file_path
            output = run(command)
        else:
            self.status_bar['text'] = 'Unrunnable file'
            self.set_status_bar_color(bg='red', fg='black')

    def create_window(self):
        self.window.geometry('500x500')
        self.window.geometry("+700+250")
        self.window.protocol("WM_DELETE_WINDOW", self.confirm_quit)
        self.window_title = self.window.title('Untitled')
        self.window_icon = self.window.iconbitmap(r'C:\_Code_\Python\Notepad--\pencil.ico')
        self.menu_bar = Menu(self.window)
        self.menu_bar.add_command(label="Open", command=self.open_file)
        self.menu_bar.add_command(label="Save", command=self.get_text)
        self.menu_bar.add_command(label='Save to Drive', command=self.upload_to_drive)
        self.menu_bar.add_command(label='Run', command=self.run)
        self.menu_bar.add_command(label="Quit", command=self.confirm_quit)
        self.window.config(menu=self.menu_bar)
        self.status_bar = Label(self.window, text='', bd=1, relief=SUNKEN, anchor=W)
        self.status_bar.pack(side=BOTTOM, fill=X)
        self.set_status_bar_color()
        self.text_box = Text(self.window, height=500, width=500, tabs=("2c"))
        self.text_box.configure(bg='black')
        self.text_box.configure(fg='white')
        self.text_box.configure(insertbackground="white")
        self.text_box.pack()

def main():
    notepad = Notepad()
    notepad.create_window()
    notepad.window.bind("<Key>", notepad.key)
    notepad.window.mainloop()

main()


import re
# The RegEx library
#
# our regular expression (to find e-mails)
# and text to search
#
regex = '\s[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}[\s]'
text = """This is example of text with x@y.z embedded e-mails
that we'll use as@gmail.com
line with no addresses
others@insail.two valid email@addresses.com
The re module is awonderful@thing."""
print('** Search text ***\n'+text)
print('** Regex ***\n'+regex+'\n***')
#
#

utext = text.upper()
#
#
# perform a search (any emails found?)
s = re.search(regex, utext)
if s:
    print('*** At least one email found "'+s.group()+'"')
#
# now, find all matches
#
m = re.findall(regex, utext)
if m:
    for match in m:
        print('Match found', match.strip())


""" Impersonate myself.
"""
import argparse
import sys
import time
from collections import OrderedDict
from multiprocessing.dummy import Pool
from pathlib import Path
from typing import Dict, List

from slackit import Event, Message, Receiver
from slackit._config import Config, configure
from slackit.roam import today
from slackit.services import SERVICE_REGISTRY

def _report(receiver: Receiver, messages: List[Message], delay: int) -> None:
    print(f"Sending {messages} to receiver {receiver} after {delay} seconds.")

def _shoot(receiver: Receiver, messages: List[Message], delay: int) -> None:
    """For multiprocessing."""
    time.sleep(delay)
    service = SERVICE_REGISTRY[receiver.service_name](receiver.receiver_id)
    service.send_many(messages=messages)

def main() -> None:
    """Impersonate myself."""
    parser = argparse.ArgumentParser(description=main.__doc__)
    parser.add_argument(
        "-c",
        "--config",
        type=argparse.FileType("r"),
        required=True,
    )
    parser.add_argument(
        "-e",
        "--event",
        required=True,
    )
    parser.add_argument(
        "--check-date",
        action="store_true",
        help="Only run if today's date matches the config.",
    )

    args = parser.parse_args()

    try:
        configure(Path(args.config.name))

        event_spec = Config.get(args.event)

        if args.check_date and today() not in str(event_spec):
            print(f"Couldn't find {today()} in the event spec. Aborting!")
            sys.exit(0)

        event = Event.from_spec(event_spec)
        per_recv: Dict[Receiver, List[Message]] = OrderedDict()

        for r_spec, m_spec in event.message_gen:
            _messages = per_recv.setdefault(Receiver.from_spec(r_spec), [])
            _messages.append(Message.from_spec(m_spec))

        if not per_recv:
            print("Nothing to do!")
            sys.exit(0)

        _args = list(zip(per_recv.keys(), per_recv.values(), event.delay_gen()))
        for _arg in _args:
            _report(*_arg)

        with Pool(len(per_recv)) as pool:
            pool.starmap(_shoot, _args)

    except Exception as exc:  # pylint: disable=broad-except
        sys.exit(exc)

    print("Done!")

if __name__ == "__main__":
    main()


from itertools import permutations

def fact(num):
	if num <= 1:
		return 1
	return num * fact(num - 1)

def main():
	# ls = list(permutations(range(10)))
	# rep = (list(ls[999999]))
	# print("".join([str(i) for i in rep]))

	position = 999999
	factoList = [fact(i) for i in range(10)]
	listComp = [i for i in range(10)]
	positionList = []
	comb = []

	for i in range(len(listComp)):
		positionList.append(position // factoList[-(i + 1)])
		position -= (position // factoList[-(i + 1)]) * factoList[-(i + 1)]

	for i in positionList:
		comb.append(listComp[i])
		del listComp[i]

	print("".join([str(i) for i in comb]))

if __name__ == '__main__':
	main()


from setuptools import setup, find_packages

with open("README.md", encoding="utf-8") as f:
    long_des = str(f.read())

setup(
    name='flet_translator',
    version='1.2.7',
    author='SKbarbon',
    description='A package that help flet developers to make their apps support multiple languages',
    long_description=long_des,
    long_description_content_type='text/markdown',
    url='https://github.com/SKbarbon/flet_translator',
    install_requires=["flet", "sacremoses", "deep-translator"],
    packages=find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: Microsoft :: Windows"
    ],
)


#region Information
'''
This module contains useful functions for building geometry
nodes node trees inside of Blender.
'''
#endregion
#region Imports
import bpy
from easybpy import *
#endregion
#region Main Class
class GeometryNodes:

    # Variables
    tree = None
    control = None
    group_input = None
    group_output = None

    # Class init
    def __init__(self, name = "New Node Object"):
        control = self.create_control_object(name)

    def create_control_object(self, name):
        o = create_object(name, "Node Objects")
        select_only(o)
        bpy.ops.node.new_geometry_nodes_modifier()

        # Essential variables for the class.
        self.tree = self.get_node_tree(o)
        self.group_input = self.tree.nodes["Group Input"]
        self.group_output = self.tree.nodes["Group Output"]
        return o

    def get_node_tree(self, object):
        return object.modifiers["GeometryNodes"].node_group

    def add_object(self, ref = None):
        objnode = self.tree.nodes.new(type="GeometryNodeObjectInfo")
        if ref is not None:
            objref = get_object(ref)
            objnode.inputs[0].default_value = objref
        return objnode

    def output_geometry(self, ref):
        node = get_node(self.tree.nodes,ref)
        index = get_index_of_output(node, "Geometry")
        create_node_link(node.outputs[index], self.group_output.inputs[0])

    def connect_geometry(self, first, second):
        first_index = get_index_of_output(first, "Geometry")
        second_index = get_index_of_input(second, "Geometry")
        create_node_link(first.outputs[first_index], second.inputs[second_index])

    def boolean(self, first, second):
        boolnode = self.tree.nodes.new(type="GeometryNodeBoolean")
        first_index = get_index_of_output(first, "Geometry")
        second_index = get_index_of_output(second, "Geometry")
        create_node_link(boolnode.inputs[0], first.outputs[first_index])
        create_node_link(boolnode.inputs[1], second.outputs[second_index])
        return boolnode

    def join_geometry(self, first, second):
        joinnode = self.tree.nodes.new(type="GeometryNodeJoinGeometry")
        first_index = get_index_of_output(first, "Geometry")
        second_index = get_index_of_output(second, "Geometry")
        create_node_link(joinnode.inputs[0], first.outputs[first_index])
        create_node_link(joinnode.inputs[1], second.outputs[second_index])
        return joinnode

    def transform(self, objsource):
        transformnode = self.tree.nodes.new(type="GeometryNodeTransform")
        obj_index = get_index_of_output(objsource, "Geometry")
        create_node_link(objsource.outputs[obj_index],transformnode.inputs[0])
        return transformnode
#endregion


# A parameter
# Arguments are used as the actual values we provide to a function

# Positional arguments are arguments that are required to be in the proper position. ie if when the parameters where defined as name , emoji the arguments must be in that order to be properly returned.

# Keyword arguments makes it possible for us not to worry  about the position.
def show_tree(name, emoji):
    #           variable/parameters
    print(f'Hello {name} {emoji}')
    # The parameters created above can be used in the print
print()

# These are positional arguments
show_tree('Jacob', 'ðŸ˜ƒ') # These are the arguments
show_tree('Fritz', 'ðŸ˜ƒ')
show_tree('Jack', 'ðŸ˜ƒ')
show_tree('Anna', 'ðŸ˜ƒ')
# Parameters are used for when we define the function
# Arguments are used for when we we call / invoke the function

# Keyword arguments
# This is bad practice cuz it complicates the code more than how it actually is
show_tree(emoji='ðŸ˜€', name='Emiley')

#Keyword arguments are confused with default parameters

#Default parameters allow us to give what we want as default where we define the function at once.
# When you're unable to call functions which have been given, print out the default names given as shown below.

# In my opinion this is the best followed by the positional arguments
def mantel(name='Kendrick', emoji='ðŸ˜ '):
    print(f'Hey {name} {emoji}')
print()

mantel()
mantel('Fred', 'ðŸ˜ƒ')

Day 8/Default parameters and keyword arguments.py


# import model
import gp
import evaluate
import random
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm

if __name__ == '__main__':

    #model.exe()

    xmax = 352
    ymax = 1216
    a = []
    b = []

    # #preは２２５までおｋ
    # i=216
    # path = 'pre_test_results/data{}/'.format(i)
    # path1 = 'nomal_result/data216/'

    # xs = 180
    # xf = 220
    # ys = 450
    # yf = 600

    # error, var = evaluate.exe(path, path1, xs, xf, ys, yf)
    # error = error.reshape(1,-1)[0]
    # for e in error:
    #     if e>0:
    #         a.append(e)
    # breakpoint()

    # empty = [235, 250, 268, 274, 288, 291]

    for i in tqdm(range(0, 300)):
        # path = 'pre_test_results/data{}/'.format(i)
        # path1 = 'sample_result/data{}/'.format(i)
        # path1 = 'nomal_result/data{}/'.format(i)
        # path = 'test_results/data{}/'.format(i)
        path = 'penalty_only_test_results/data{}/'.format(i)

        # マスクする領域をランダムに決める
        # xs = random.randint(100,xmax)
        # xf = xs + 80
        # ys = random.randint(0,ymax)
        # yf = ys + 30
        # if random.randint(0,1)==1:
        #     xf = xs + 30
        #     yf = ys + 80
        # if xf >= xmax:
        #     tmp = xf - xs
        #     xf = xs
        #     xs = xf - tmp
        # if yf >= ymax:
        #     tmp = yf - ys
        #     yf = ys
        #     ys = yf - tmp

        # マスクする領域を固定する
        xs = 180
        xf = 220
        ys = 450
        yf = 600

        try:
            # 説明変数の不確実性を考慮したガウス過程回帰を実行
            # gp.exe_with_uncer(path, xs, xf, ys, yf)

            # ガウス過程回帰を実行する
            gp.exe(path, xs, xf, ys, yf, i)

            # 予測値の評価をする
            error, var = evaluate.exe(path, path, xs, xf, ys, yf)
            # error, corr = evaluate.t_test(path, path, xs, xf, ys, yf)
        except:
            print(i)
            continue
        error = error.reshape(1,-1)[0]
        var = var.reshape(1, -1)[0]
        a.append(error)
        b.append(var)

    # # # # # breakpoint()

    # a = np.array(a).reshape(1,-1)[0]
    # b = np.array(b).reshape(1,-1)[0]
    a = np.array(a)
    b = np.array(b)
    np.save('ttest_pe_only_error', a)
    np.save('ttest_pe_only_corr', b)
    # plt.figure(figsize=(16, 5))
    # plt.scatter(b,a)
    # plt.xlabel('variance')
    # plt.ylabel('relative error')
    # plt.savefig('eval3.png' , format="png")
    # # breakpoint()


"""
Assorted standardized text elements like progress bars, graphs/charts,
headers, etc.
"""

import math
from src.daemons.server.ansi import ANSI_HI_WHITE, ANSI_HI_GREEN, ANSI_HI_YELLOW, ANSI_HI_RED, ANSI_GREEN, ANSI_NORMAL, ANSI_YELLOW, ANSI_RED

def progress_bar_str(char_limit, max_value, current_value):
    """
    Returns a pretty progress bar string, complete with colorization.

    :param int char_limit: How wide the progress bar (in characters) should
        be. This includes the bar and its brackets. Must be at least 6.
    :param int max_value: The maximum numeric value for the data represented
        in the bar.
    :param int current_value: The current value for the value represented
        in the bar.
    :rtype: basestring
    :returns: A properly formatted progress bar.
    """

    assert char_limit > 6, "Bars must be at least 6 characters wide."

    max_bar_width = char_limit - 2
    perc = float(current_value) / max_value
    bar_width = int(math.floor(perc * max_bar_width))
    if perc >= 0.9:
        bar_color = ANSI_HI_GREEN
    elif perc >= 0.75:
        bar_color = ANSI_NORMAL + ANSI_GREEN
    elif perc >= 0.5:
        bar_color = ANSI_HI_YELLOW
    elif perc >= 0.3:
        bar_color = ANSI_NORMAL + ANSI_YELLOW
    elif perc >= 0.2:
        bar_color = ANSI_HI_RED
    else:
        bar_color = ANSI_NORMAL + ANSI_RED

    buf = ANSI_HI_WHITE + '[' + bar_color
    buf += ('=' * bar_width) + (' ' * (max_bar_width - bar_width))
    buf += ANSI_HI_WHITE + ']' + ANSI_NORMAL
    return buf, int(math.floor(perc * 100)), bar_color


from typing import cast

import pytest
from recon.stats import get_ner_stats
from recon.types import Example, NERStats, Span, Token
from recon.validation import filter_overlaps, upcase_labels

@pytest.fixture()
def messy_data():
    return [
        {
            "text": "Denver, Colorado is a city.",
            "spans": [
                {"start": 0, "end": 6, "label": "GPE"},
                {"start": 0, "end": 16, "label": "LOC"},
            ],
            "meta": "Cities Data",
        }
    ]

def test_upcase_labels(example_corpus):
    stats = cast(NERStats, get_ner_stats(example_corpus.train))
    assert "skill" in stats.n_annotations_per_type
    assert "product" in stats.n_annotations_per_type
    assert "SKILL" in stats.n_annotations_per_type

    example_corpus._train.apply_("recon.v1.upcase_labels")
    fixed_stats = cast(NERStats, get_ner_stats(example_corpus.train))
    assert "skill" not in fixed_stats.n_annotations_per_type
    assert "product" not in fixed_stats.n_annotations_per_type

def test_filter_overlaps():
    def get_test_example(span_offsets):
        spans = []
        for so in span_offsets:
            spans.append(Span(text="x" * (so[1] - so[0]), start=so[0], end=so[1], label=so[2]))
        return Example(text="x" * 1500, spans=spans)

    def spans_to_offsets(spans):
        return [(span.start, span.end, span.label) for span in spans]

    test_entities = [(0, 5, "ENTITY"), (6, 10, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(0, 5, "ENTITY"), (6, 10, "ENTITY")]

    test_entities = [(0, 5, "ENTITY"), (5, 10, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(0, 5, "ENTITY"), (5, 10, "ENTITY")]

    test_entities = [(0, 5, "ENTITY"), (4, 10, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(4, 10, "ENTITY")]

    test_entities = [(0, 5, "ENTITY"), (0, 5, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(0, 5, "ENTITY")]

    test_entities = [(0, 5, "ENTITY"), (4, 11, "ENTITY"), (6, 20, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(0, 5, "ENTITY"), (6, 20, "ENTITY")]

    test_entities = [(0, 5, "ENTITY"), (4, 7, "ENTITY"), (10, 20, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(0, 5, "ENTITY"), (10, 20, "ENTITY")]

    test_entities = [(1368, 1374, "ENTITY"), (1368, 1376, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(1368, 1376, "ENTITY")]

    test_entities = [
        (12, 33, "ENTITY"),
        (769, 779, "ENTITY"),
        (769, 787, "ENTITY"),
        (806, 811, "ENTITY"),
    ]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [
        (12, 33, "ENTITY"),
        (769, 787, "ENTITY"),
        (806, 811, "ENTITY"),
    ]

    test_entities = [
        (189, 209, "ENTITY"),
        (317, 362, "ENTITY"),
        (345, 354, "ENTITY"),
        (364, 368, "ENTITY"),
    ]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [
        (189, 209, "ENTITY"),
        (317, 362, "ENTITY"),
        (364, 368, "ENTITY"),
    ]

    test_entities = [(445, 502, "ENTITY"), (461, 473, "ENTITY"), (474, 489, "ENTITY")]
    result = filter_overlaps(get_test_example(test_entities))
    assert spans_to_offsets(result.spans) == [(445, 502, "ENTITY")]


from google.api_core import retry
import google.generativeai as palm
import os
import re
import config
import os
import tenacity
from time import sleep

# Set PaLM API key from environment or config file
api_key = os.environ.get("PALM_API_KEY")
if (api_key is None or api_key == "") and os.path.isfile(os.path.join(os.getcwd(), "keys.cfg")):
    cfg = config.Config('keys.cfg')
    api_key = cfg.get("PALM_API_KEY")
palm.configure(api_key=api_key)

@retry.Retry()
def retry_chat(**kwargs):
    return palm.chat(**kwargs)

@retry.Retry()
def retry_reply(x, arg):
    return x.reply(arg)

@tenacity.retry(wait=tenacity.wait_random_exponential(min=150, max=500), stop=tenacity.stop_after_attempt(6))
def generate_text(*args, **kwargs):
    return palm.generate_text(*args, **kwargs)

# PALM Chat
class PalmChat:
    def __init__(self, model="models/chat-bison-001"):
        self.defaults = {
            'model': model,
            'temperature': 0,
            'top_p': 1,
            'candidate_count': 1
        }
        self.response = None

    def init_chat(self, context="You are a helpful assisstant", init_message="Hello"):
        # initialize chat
        response = None
        response = retry_chat(
        **self.defaults,
        context=context,
        messages=init_message
        )
        self.response = response

    def reply(self, reply):
        self.response = retry_reply(self.response, reply)
        while self.response.last == None:
            self.response = retry_reply(self.response, reply)

    def get_response(self):
        output = self.response.last
        # clean output
        output = re.sub("\n", " ", output)
        return output

def PalmCompletion(phrase, model="models/text-bison-001", num_samples=1):
    # Request configuration disabling all safety settings to prevent blocking
    config = {
        'model': model,
        'temperature': 0,
        'top_p': 1,
        'candidate_count': num_samples,
        'safety_settings': [{"category":"HARM_CATEGORY_DEROGATORY","threshold":4},{"category":"HARM_CATEGORY_TOXICITY","threshold":4},{"category":"HARM_CATEGORY_VIOLENCE","threshold":4},{"category":"HARM_CATEGORY_SEXUAL","threshold":4},{"category":"HARM_CATEGORY_MEDICAL","threshold":4},{"category":"HARM_CATEGORY_DANGEROUS","threshold":4}],
    }
    # to prevent rate limiting
    sleep(2)
    response = generate_text(
        **config,
        prompt=phrase
    )
    output = response.result
    # clean output
    if isinstance(output, str):
        output = re.sub("\n", " ", output)
    return output

if __name__ == "__main__":
    chat = PalmChat()
    chat.init_chat(init_message="I have 3 apples and 10 bananas. How many fruits do I have in total?")
    for i in range(5):
        print(chat.get_response())
        x = input("> ")
        chat.reply(x)


#! /usr/bin/env python3
"""
eliminate some of the boiler-plate involved in running our "on hardware"
qemu tests, which are actually examples.
"""
import os
import shlex
import subprocess

def main(verbose=False):
    our_dir = os.path.dirname(os.path.realpath(__file__))
    for example in os.listdir(os.path.join(our_dir, "examples")):
        if example.startswith("test_"):
            command = 'cargo run --example {} --release --features="embedded-hal" --target thumbv7m-none-eabi'.format(
                os.path.splitext(example)[0]
            )
            print("running `{}`".format(command))
            subprocess.run(shlex.split(command), check=True)

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("--verbose", "-v", action="store_true", help="verbose output")

    args = parser.parse_args()
    main(verbose=args.verbose)