"""empty message

Revision ID: 5d716a544ce2
Revises:
Create Date: 2018-11-20 20:59:12.496003

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '5d716a544ce2'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('reviews',
    sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
    sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
    sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('field_reviews',
    sa.Column('created_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
    sa.Column('updated_at', sa.DateTime(), server_default=sa.text('now()'), nullable=True),
    sa.Column('id', postgresql.UUID(), server_default=sa.text('uuid_generate_v4()'), nullable=False),
    sa.Column('review_id', postgresql.UUID(), nullable=False),
    sa.Column('class_name', sa.String(length=256), nullable=False),
    sa.Column('field_name', sa.String(length=256), nullable=False),
    sa.Column('recall_difficulty', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['review_id'], ['reviews.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('field_reviews')
    op.drop_table('reviews')
    # ### end Alembic commands ###


from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import CustomUser, Newsfeed

# Register your models here.

class CustomUserAdmin(UserAdmin):
    list_display = ('id', 'phone_number')

UserAdmin.fieldsets += (
    (
        'custom_fields', {
            'fields': ('phone_number',)
        }
    ),
)

admin.site.register(CustomUser, CustomUserAdmin)

@admin.register(Newsfeed)
class NewsfeedAdmin(admin.ModelAdmin):
    list_display = ('id', 'user', 'news')


from odoo import models, fields, _
from odoo.http import request

class ProductProduct(models.Model):
    _inherit = 'product.product'

    stock_notification_partner_ids = fields.Many2many('res.partner', relation='stock_notification_product_partner_rel', string='Back in stock Notifications')

    def _has_stock_notification(self, partner):
        self.ensure_one()
        return partner in self.stock_notification_partner_ids

    def _get_cart_qty(self, website=None):
        if not self.allow_out_of_stock_order:
            website = website or self.env['website'].get_current_website()
            # When the cron is run manually, request has no attribute website, and that would cause a crash
            # so we check for it
            cart = website and request and hasattr(request, 'website') and website.sale_get_order() or None
            if cart:
                return sum(cart._get_common_product_lines(product=self).mapped('product_uom_qty'))
        return 0

    def _is_sold_out(self):
        self.ensure_one()
        if not self.type == 'product':
            return False
        free_qty = self.env['website'].get_current_website()._get_product_available_qty(self.sudo())
        return free_qty <= 0

    def _website_show_quick_add(self):
        return (self.allow_out_of_stock_order or not self._is_sold_out()) and super()._website_show_quick_add()

    def _send_availability_email(self):
        for product in self.search([('stock_notification_partner_ids', '!=', False)]):
            if product._is_sold_out():
                continue
            for partner in product.stock_notification_partner_ids:
                self_ctxt = self.with_context(lang=partner.lang)
                product_ctxt = product.with_context(lang=partner.lang)
                body_html = self_ctxt.env['ir.qweb']._render(
                    'website_sale_stock.availability_email_body', {'product': product_ctxt})
                msg = self_ctxt.env['mail.message'].sudo().new(dict(body=body_html, record_name=product_ctxt.name))
                full_mail = self_ctxt.env['mail.render.mixin']._render_encapsulate(
                    "mail.mail_notification_light",
                    body_html,
                    add_context=dict(message=msg, model_description=_("Product")),
                )
                context = {'lang': partner.lang}  # Use partner lang to translate mail subject below
                mail_values = {
                    "subject": _("The product '%(product_name)s' is now available", product_name=product_ctxt.name),
                    "email_from": (product.company_id.partner_id or self.env.user).email_formatted,
                    "email_to": partner.email_formatted,
                    "body_html": full_mail,
                }
                del context

                mail = self_ctxt.env['mail.mail'].sudo().create(mail_values)
                mail.send(raise_exception=False)
                product.stock_notification_partner_ids -= partner


#!/usr/bin/env python
import subprocess, os
import argparse
import time

parser = argparse.ArgumentParser()
parser.add_argument('-i', '--inpath', default=None, help="path to input directory containing non-basecalled reads")
parser.add_argument('-o', '--outpath', default=None, help="path to output directory for basecalled reads")
parser.add_argument('--dimension', default='1d', help="dimension of sequenced library; 1d or 2d")
parser.add_argument('--email', default=None, help="email address for sbatch notifications")

parser.add_argument('--test', default=False, action='store_true', help="make sure that albacore is working correctly; do not run from SBATCH")
parser.add_argument('--dryrun', default=False, action='store_true', help="print commands to be run, but do not call them")
args = parser.parse_args()

if args.dimension == '1d':
    w = 'r94_450bps_linear.cfg'
else:
    w = 'r94_250bps_2d.cfg'

if args.test:
    assert args.email, "No email address given; necessary for SBATCH"
    call = 'sbatch --mail-type=FAIL,END --mail-user=%s --wrap=\"read_fast5_basecaller.py -h\"'%(args.email)
    print(call)
    try:
        subprocess.call('read_fast5_basecaller.py -h', shell=True)
        subprocess.call(call, shell=True)
    except:
        print("Unable to run Albacore. Ensure that proper requisite module is loaded with:\n\nmodule load Python/3.5.2-foss-2016b-fh1\n")
else:
    assert args.inpath, "No input path given"
    assert args.outpath, "No output path given"
    assert args.email, "No email address given; necessary for SBATCH"

    for dirname in os.listdir(args.inpath):
        acall = 'read_fast5_basecaller.py -i %s/%s -t 8 -c %s -r -s %s -o fast5'%(args.inpath, dirname, w, args.outpath)
        call = [ 'sbatch', '--time=24:00:00', '--mem=30000', '--mail-type=FAIL', '--mail-user=%s'%(args.email), '--wrap="%s"'%(acall) ]
        print(" ".join(call))
        if not args.dryrun:
            subprocess.call(" ".join(call), shell=True)
            time.sleep(15)


def read_file(file_name):
    with open(file_name,"r") as f:
        dataset = f.read().splitlines()
    return dataset

def get_labels(file_name):
    all_labels = []
    dataset = read_file(file_name)
    for data in dataset:
        if(data[0] == '>'):
            all_labels.append(data[1:])
    return all_labels

def get_sequence(file_name):
    all_sequence = []
    dataset = read_file(file_name)
    prevStr = ""
    for data in dataset:
        if(data[0] != '>'):
            prevStr += data
        else:
            all_sequence.append(prevStr)
            prevStr = ""
    all_sequence.append(prevStr)
    return all_sequence

def get_sequence_label(file_name):
    dataset = read_file(file_name)
    all_sequence = []
    all_label = []
    prevStr = ""
    for data in dataset:
        if(data[0] != '>'):
            prevStr += data
        else:
            if(prevStr != ""):
                all_sequence.append(prevStr)
                prevStr = ""
            all_label.append(data[1:])
    all_sequence.append(prevStr)
    return all_sequence,all_label


import numpy as np
import matplotlib as mpl
mpl.use('Agg')

import matplotlib.pyplot as plt
import glob
import deepdish as dd
import sys
import os

# some general plot styles for consistency
from galaxy_analysis.plot import plot_styles as ps
from galaxy_analysis.utilities import utilities

colors = {'Disk' : ps.black,
              'CNM'  : ps.purple,
              'WNM'  : ps.purple,
              'HIM'  : ps.purple,
              'Molecular' : 'red',
          'FullBox'  : ps.magenta,
          'stars'    : ps.orange,
          'GravBound' : ps.blue,
          'OutsideBox' : ps.green }

ls = {'Disk' : '-',
         'CNM' : '-',
         'WNM' : '--',
         'HIM' : ':',
         'Molecular' : '-',
      'FullBox' : '-',
      'stars'   : '-',
      'GravBound' : '-',
      'OutsideBox' : '-'}

def plot_sequestering(directory = './', fields = None, elements = None,
                      fraction = None):
    """
    Given a directory, goes through all data outputs in that
    directory and plots the time evolution of the mass contained
    in specified gas phases for a given species. The default behavior
    is to plot all fields for each element on a different plot for each
    element.

    fields : list, default is to use all of: Disk, CNM, WNM, HIM, FullBox,
             stars, Molecular, OutsideBox, GravBound

    elements : list, default is to loop through all elements: H, He, C, N,
               O, Mg, Ca, Si, Mn, S, Fe, Y, Eu, and Metals

    fraction : optional, string. Plot the mass fraction. Normalize all
               lines by one of the fields listed above.
    """

    output_dir = directory + '/sequestering/'

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    if not fraction is None:
        output_dir += fraction + '/'

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    sfields = fields
    if sfields is None:
        sfields = ['Disk', 'CNM', 'WNM', 'HIM', 'FullBox',
                   'stars', 'Molecular', 'OutsideBox', 'GravBound']
    #
    # get all data
    #
    all_output = np.sort(glob.glob(directory + '/DD*.h5'))

    all_elements = elements
    if all_elements is None:
        # this is a hacky way of getting the metal fields - should just save this to file
        metal_fields = dd.io.load(all_output[0], '/gas_meta_data/masses/FullBox')
        exclude      = ['H','HI','HII','H2','Metals','Total','He','HeI','HeII','HeIII']
        metal_fields = utilities.sort_by_anum([x for x in metal_fields if (not any([y in x for y in exclude]))])

        individual_metals = metal_fields
        all_elements = ['H','He','Metals'] + individual_metals

    for element in all_elements:
        fig, ax = plt.subplots()

        # construct dictionary and time array
        plot_data = {}
        t         = np.zeros(len(all_output))

        for s in sfields:
            plot_data[s] = np.zeros(len(all_output))

        # loop through all output, gathering time and mass values
        for i in np.arange(len(all_output)):
            t[i] = dd.io.load(all_output[i], '/meta_data/Time')
            x    = dd.io.load(all_output[i], '/gas_meta_data/masses')

            # now loop through all fields
            for s in sfields:
                if element == 'Metals' and s == 'stars':
                    plot_data[s][i] = x[s]['metals']
                else:
                    plot_data[s][i] = x[s][element]

        # normalize if necessary
        norm = np.ones(np.size(plot_data[sfields[0]]))
        if not fraction is None:
            norm = 1.0 / plot_data[fraction]

        ymax = np.max(plot_data['FullBox'] * norm)
        if fraction is None:
            ymax = 5.0 * ymax

        ymin = 1.0E-8 * ymax

        # try and set something reasonable for minimum if it exists
        ymin = np.max( [ymin, np.min(plot_data['stars'] * norm)*10.0] )

        for s in sfields:

            # ignore fields that are too tiny to show up on plot
            if np.max(plot_data[s] * norm) < ymin:
                continue

            ax.plot(t, plot_data[s] * norm, lw = ps.lw, label=s, ls = ls[s], color = colors[s])

        ax.set_xlabel(r'Time (Myr')

        if not fraction is None:
            ax.set_ylabel('Mass Fraction of ' + element + ' relative to ' + fraction)
        else:
            ax.set_ylabel(element + r' Mass (M$_{\odot}$)')

        ax.set_ylim(ymin, ymax)
        ax.semilogy()
        plt.minorticks_on()
        fig.set_size_inches(8,8)
        plt.tight_layout()
        ax.legend(loc='best', ncol = 2)

        outname = output_dir + '/' + element + '_sequestering.png'
        if not fraction is None:
            outname = output_dir + '/' + element + '_' + fraction + '_fraction_sequestering.png'

        fig.savefig(outname)
        plt.close(fig)
        del(plot_data)

    return

def plot_surface_density_profiles(directory = './', normalize = False):

    output_dir = directory + '/radial_profiles/'
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    output_dir = output_dir + 'surface_density/'
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    all_output = np.sort(glob.glob(directory + '/DD*.h5'))

    da = dd.io.load(all_output[-1])
    fields = [k[1] for k in da['gas_profiles']['surface_density']['disk'].keys() if k != 'xbins']

    ls = ['-','--',':']
    color = ['black',ps.purple,ps.blue,ps.orange]

    for ele in fields:
        lsi = 0
        ci  = 0

        norm = 1.0
        ymin = 1.0E99
        ymax = -1.0E99

        k1 = 'gas'
        try:
            temp = da['gas_profiles']['surface_density']['disk'][(k1,ele)]
        except:
            k1 = 'enzo'

        if normalize:
            da = dd.io.load(all_output[0])
            norm = da['gas_profiles']['surface_density']['disk'][(k1,ele)]

        fig, ax = plt.subplots()

        for i in np.floor(np.linspace(0, len(all_output) - 1, 12)):
            i = int(i)
            da = dd.io.load( all_output[i])

            t = da['meta_data']['Time']

            y = da['gas_profiles']['surface_density']['disk'][(k1,ele)]
            x = da['gas_profiles']['surface_density']['disk']['xbins']
            x = (x[1:] + x[:-1])*0.5

            ax.plot(x, y * norm, lw = 3, ls = ls[lsi], color = color[ci], label = "t = %0.1f Myr"%(t))

            ymax = np.max( [ymax, np.max(y * norm)])
            ymin = np.min( [ymin, np.min(y * norm)])

            lsi = lsi + 1
            if lsi >= len(ls):
                lsi = 0
                ci = ci + 1

        ax.set_xlabel(r'Radius (pc)')
        ax.set_ylabel(r'$\Sigma_{\rm ' + ele + '}$ (M$_{\odot}$ pc$^{-2}$)')
        ax.semilogy()
#        ax.semilogx()
        ax.set_xlim(0.0, 2000.0)

        ymin = np.max( [ymin, 1.0E-5*ymax])
        ax.set_ylim(ymin, ymax)

        plt.minorticks_on()
        fig.set_size_inches(8,8)
        plt.tight_layout()
        ax.legend(loc='best', ncol = 2)

        outname = output_dir + ele
        if normalize:
            outname = outname + '_norm'
        outname = outname + '_radial_profile.png'
        fig.savefig(outname)
        plt.close(fig)

    return

def plot_mass_profiles(directory = './', normalize = False):
    """
    Plot cumulative radial profiles at 6 different times (evenly spaced)
    throughout the simulation.
    """

    output_dir = directory + '/radial_profiles/'

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    all_output = np.sort(glob.glob(directory + '/DD*.h5'))

    da = dd.io.load(all_output[-1])
    fields = [k[1] for k in da['gas_profiles']['accumulation']['sphere'].keys() if k != 'xbins']

    ls = ['-','--',':']
    color = ['black',ps.purple,ps.blue,ps.orange]

    for ele in fields:
        lsi = 0
        ci  = 0

        norm = 1.0

        if normalize:
            da = dd.io.load(all_output[0])
            norm = da['gas_profiles']['accumulation']['sphere'][('gas',ele)]

        fig, ax = plt.subplots()

        for i in np.floor(np.linspace(0, len(all_output) - 1, 12)):
            i = int(i)
            da = dd.io.load( all_output[i])

            t = da['meta_data']['Time']

            y = da['gas_profiles']['accumulation']['sphere'][('gas',ele)]
            x = da['gas_profiles']['accumulation']['sphere']['xbins']
            x = (x[1:] + x[:-1])*0.5

            ax.plot(x, np.cumsum(y) * norm, lw = 3, ls = ls[lsi], color = color[ci], label = "t = %0.1f Myr"%(t))

            lsi = lsi + 1
            if lsi >= len(ls):
                lsi = 0
                ci = ci + 1

        ax.set_xlabel(r'Radius (kpc)')
        ax.set_ylabel(r'Mass (M$_{\odot}$)')
        ax.semilogy()
#        ax.semilogx()
        ax.set_xlim(0.0, 15.0)

        plt.minorticks_on()
        fig.set_size_inches(8,8)
        plt.tight_layout()
        ax.legend(loc='best', ncol = 2)

        outname = output_dir + ele
        if normalize:
            outname = outname + '_norm_'
        outname = outname + 'radial_profile.png'
        fig.savefig(outname)
        plt.close(fig)

    return

if __name__ == "__main__":

    directory = './'
    if len(sys.argv) == 2:
        directory = sys.argv[1]

    plot_sequestering(directory = directory)
    print("completed total sequestering")
    plot_surface_density_profiles(directory = directory)
    print("completed surface density profiles")
    plot_mass_profiles(directory = directory)
    print("completed mass profiles")

    # Disk and FullBox are likely the only two fractions that make
    # sense given the way the data is constructed. Other fractions are
    # certainly possible but will be misleading without recomputing
    # analysis (i.e. GravBound isn't useful unless I'm doing
    # fraction of a given field that is GravBound, which would
    # require re-computing, not just dividing by GravBound)
    plot_sequestering(directory = directory, fraction = 'Disk')
    plot_sequestering(directory = directory, fraction = 'FullBox')


import matplotlib.pyplot as  plt
import numpy as np

t=np.linspace(0,np.pi*2)

f1 = np.sin(t)
f2 = np.sin(2*t)
f3 = np.cos(t)

plt.title("Plot of sin(t), sin(2t) and cos(t)")
plt.xlabel("Angle (radians)")
plt.ylabel("Value of function")
plt.plot(t,f1,marker='o')
plt.plot(t,f2,marker='o')
plt.plot(t,f3,marker='o')
plt.legend(['sin(t)','sin(2t)','cos(t)'])
plt.show()

#3D plot
def surface_plot(func,title):
    x = np.outer(np.linspace(-np.pi, np.pi, 50), np.ones(50))
    y = x.copy().T
    z = func(x,y)
    fig = plt.figure()
    ax = plt.axes(projection ='3d')
    ax.plot_surface(x, y, z, cmap ='viridis', edgecolor ='green')
    ax.set_title(title)
    ax.set_xlabel('x axis')
    ax.set_ylabel('y axis')
    ax.set_zlabel('f(x,y)')
    plt.show()
#heatmap
def heatmap(func,title):
    x = np.outer(np.linspace(-np.pi, np.pi, 50), np.ones(50))
    y = x.copy().T
    z = func(x,y)
    z = z[:-1, :-1]
    z_min, z_max = -np.abs(z).max(), np.abs(z).max()
    fig, ax = plt.subplots()
    c = ax.pcolormesh(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
    ax.set_title(title)
    ax.axis([x.min(), x.max(), y.min(), y.max()])
    ax.set_xlabel('x axis')
    ax.set_ylabel('y axis')
    fig.colorbar(c, ax=ax)
    plt.show()

surface_plot(lambda x, y: y*np.sin(x),'3D Plot of f(x,y) = ysin(x)')
surface_plot(lambda x, y: x**2 * y**2, '3D Plot of f(x,y) = x^2 y^2')

heatmap(lambda x, y: y*np.sin(x),'Heatmap of f(x,y) = ysin(x)')
heatmap(lambda x, y: x**2 * y**2, 'Heatmap of f(x,y) = x^2 y^2')


# Imports

import pygame
import sys
import random
import pickle

# Floor and Buildings

def draw_floor():
    screen.blit(floor_surface, (floor_x_pos, 130))
    screen.blit(floor_surface, (floor_x_pos + 1280, 130))

def create_building1():
    random_building_pos = random.choice(building1_height)
    bottom_building = building1_surface.get_rect(midtop=(2000, random_building_pos))
    return bottom_building

def draw_buildings1(buildings):
    for building in buildings:
        screen.blit(building1_surface, building)

def create_building2():
    random_building_pos = random.choice(building2_height)
    bottom_building = building2_surface.get_rect(midtop=(1500, random_building_pos))
    return bottom_building

def draw_buildings2(buildings):
    for building in buildings:
        screen.blit(building2_surface, building)

def create_building3():
    random_building_pos = random.choice(building3_height)
    bottom_building = building3_surface.get_rect(midtop=(1700, random_building_pos))
    return bottom_building

def draw_buildings3(buildings):
    for building in buildings:
        screen.blit(building3_surface, building)

def move_buildings(buildings):
    for building in buildings:
        building.centerx -= 3
    return buildings

def stop_buildings(buildings):
    for building in buildings:
        building.centerx += 3
    return buildings

# Collision checker

def check_collision(buildings1, buildings2, buildings3, bogey1_rect):
    for building in buildings1:
        if ship_rect.colliderect(building):
            return 'Your ship collided with a building!'
    for building in buildings2:
        if ship_rect.colliderect(building):
            return 'Your ship collided with a building!'
    for building in buildings3:
        if ship_rect.colliderect(building):
            return 'Your ship collided with a building!'

    if ship_rect.colliderect(bogey1_rect):
        return 'Your ship collided with another ship!'

    if ship_rect.top <= -100 or ship_rect.bottom >= 720:
        return 'Your ship went out of bounds!'

    return 'Game Running'

# Ship Animations

def rotate_ship(ship):
    new_ship = pygame.transform.rotozoom(ship, -ship_movement * 3, 1)
    return new_ship

def ship_animation():
    new_ship = ship_frames[ship_index]
    new_ship_rect = new_ship.get_rect(center=(200, ship_rect.centery))
    return new_ship, new_ship_rect

# All screens

def score_display(game_state):
    if game_state == 'main_game':
        score_surface = game_font.render(f'Distance: {str(score)} kms', True, (118, 118, 118))
        score_rect = score_surface.get_rect(center=(120, 705))
        screen.blit(score_surface, score_rect)

        control_surface = game_font.render(f'Boost: Space - Hover: X (Hold) - Restart: R', True, (120, 120, 120))
        control_rect = control_surface.get_rect(center=(970, 705))
        screen.blit(control_surface, control_rect)

        pygame.draw.rect(screen, black, [250, 682, 402, 34])
        pygame.draw.rect(screen, grey, [251, 683, 400, 32])
        pygame.draw.rect(screen, black, [255, 687, boost, 24])

    if game_state == 'game_over':
        score_surface = game_font.render(f'Distance: {str(score)} kms', True, (180, 150, 150))
        score_rect = score_surface.get_rect(center=(640, 200))
        screen.blit(score_surface, score_rect)

        reason_surface = game_font.render(f'{over_message}', True, (180, 150, 150))
        reason_rect = reason_surface.get_rect(center=(640, 420))
        screen.blit(reason_surface, reason_rect)

        high_score_surface = game_font.render(f'Highest Distance: {str(high_score)} kms', True, (180, 150, 150))
        high_score_rect = high_score_surface.get_rect(center=(640, 560))
        screen.blit(high_score_surface, high_score_rect)

        new_game_surface = game_font.render(f'Restart: Enter - Quit: Esc', True, (180, 150, 150))
        new_game_rect = new_game_surface.get_rect(center=(640, 700))
        screen.blit(new_game_surface, new_game_rect)

    if game_state == 'game_start':
        high_score_surface = game_font.render(f'Highest Distance: {str(high_score)} kms', True, (180, 150, 150))
        high_score_rect = high_score_surface.get_rect(center=(640, 420))
        screen.blit(high_score_surface, high_score_rect)

        new_game_surface = game_font.render(f'Start: Enter - Quit: Esc', True, (180, 150, 150))
        new_game_rect = new_game_surface.get_rect(center=(640, 700))
        screen.blit(new_game_surface, new_game_rect)

# Score updating and saving function

def update_score(score, high_score):
    if score > high_score:
        high_score = score
        with open('score.dat', 'wb') as file:
            pickle.dump(high_score, file)
    return high_score

# Basics setup

pygame.mixer.pre_init(frequency=44100, size=16, channels=1, buffer=256)
pygame.init()
screen = pygame.display.set_mode((1280, 720))
clock = pygame.time.Clock()
game_font = pygame.font.Font('assets/distant galaxy 2.ttf', 24)

# Game Variables

gravity = 0.04
ship_movement = 0
movement = True
game_active = False
game_start = True
game_paused = False
boost = 392
over_message = 'Game Running'
grey = pygame.color.Color('#808080')
black = pygame.color.Color('#000000')
score = 0

# Checking for previous high score

try:
    with open('score.dat', 'rb') as file:
        high_score = pickle.load(file)
except:
    high_score = 0

pygame.display.set_caption("ArcShooter")
icon = pygame.image.load('assets/icon0.png')
pygame.display.set_icon(icon)
counter = 0

# Variables for image assets

bg_surface1 = pygame.image.load('assets/shooterbkg2.png').convert()
bg_surface2 = pygame.image.load('assets/shooterbkg3.png').convert()
bg_surface3 = pygame.image.load('assets/shooterbkg4.png').convert()
bg_surface4 = pygame.image.load('assets/shooterbkg5.png').convert()

floor_surface = pygame.image.load('assets/movingbkg.png').convert_alpha()
cloud1_surface = pygame.image.load('assets/cloud.png').convert_alpha()
cloud2_surface = pygame.image.load('assets/cloud1.png').convert_alpha()

floor_x_pos = 0
cloud1_x_pos = 1280
cloud2_x_pos = 2000

ship_downvec = pygame.image.load('assets/ship1.png').convert_alpha()
ship_downvec = pygame.transform.scale(ship_downvec, (80, 20))
ship_midvec = pygame.image.load('assets/ship2.png').convert_alpha()
ship_midvec = pygame.transform.scale(ship_midvec, (80, 20))
ship_upvec = pygame.image.load('assets/ship3.png').convert_alpha()
ship_upvec = pygame.transform.scale(ship_upvec, (80, 20))
ship_frames = [ship_downvec, ship_midvec, ship_upvec]
ship_index = 2
ship_surface = ship_frames[ship_index]
shipX = 200
shipY = 420
ship_rect = ship_surface.get_rect(center=(shipX, shipY))
SHIPVEC = pygame.USEREVENT + 1
pygame.time.set_timer(SHIPVEC, 100)

building1 = pygame.image.load('assets/build1.png').convert_alpha()
building1_surface = building1
building1_list = []
SPAWNBUILDING1 = pygame.USEREVENT
pygame.time.set_timer(SPAWNBUILDING1, 750)
building1_height = [220, 250, 350, 450, 500, 550]

building2 = pygame.image.load('assets/build2.png').convert_alpha()
building2_surface = building2
building2_list = []
SPAWNBUILDING2 = pygame.USEREVENT
pygame.time.set_timer(SPAWNBUILDING2, 1500)
building2_height = [200, 228, 364, 439, 565, 592]

building3 = pygame.image.load('assets/build3.png').convert_alpha()
building3_surface = building3
building3_list = []
SPAWNBUILDING3 = pygame.USEREVENT
pygame.time.set_timer(SPAWNBUILDING3, 2250)
building3_height = [190, 290, 378, 419, 449, 497]

bogey1_downvec = pygame.image.load('assets/bogey1a.png').convert_alpha()
bogey1_midvec = pygame.image.load('assets/bogey1b.png').convert_alpha()
bogey1_upvec = pygame.image.load('assets/bogey1c.png').convert_alpha()
bogey1_frames = [bogey1_downvec, bogey1_midvec, bogey1_upvec]
bogey1_index = 0
bogey1_surface = bogey1_frames[bogey1_index]
bogey1X = 1400
bogey1Y = random.randint(60, 220)
bogey1_rect = bogey1_surface.get_rect(center=(bogey1X, bogey1Y))
BOGEY1VEC = pygame.USEREVENT + 1
pygame.time.set_timer(BOGEY1VEC, 100)

game_over_surface = pygame.image.load('assets/gameover.png').convert_alpha()
game_over_rect = game_over_surface.get_rect(center=(640, 360))

game_start_surface = pygame.image.load('assets/gamestart.png').convert_alpha()
game_start_rect = game_start_surface.get_rect(center=(640, 360))

# Main Game Loop

while True:

    # Disabling movement if boost is empty

    if boost > 392:
        boost = 392
    elif boost < 0:
        boost = 0
    if boost < 1:
        movement = False
    else:
        movement = True

    # Player Control Inputs

    for event in pygame.event.get():

        # Keyboard inputs

        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        keys = pygame.key.get_pressed()

        if  movement and keys[pygame.K_SPACE]:
            ship_movement = 0
            ship_movement -= 2
            boost -= 3

        if movement and keys[pygame.K_x]:
            ship_movement = -gravity
            boost -= 6

        if keys[pygame.K_RETURN] and game_active is False:
            game_active = True
            game_start = False
            building1_list.clear()
            building2_list.clear()
            building3_list.clear()
            over_message = 'Game Running'
            ship_rect.center = (shipX, shipY)
            ship_movement = 0
            score = 0
            boost = 392
            bogey1X = 2000
            bogey1Y = random.randint(70, 220)

        if keys[pygame.K_r] and game_active is True:
            game_active = True
            game_start = False
            building1_list.clear()
            building2_list.clear()
            building3_list.clear()
            over_message = 'Game Running'
            ship_rect.center = (shipX, shipY)
            ship_movement = 0
            score = 0
            boost = 392
            bogey1X = 2000
            bogey1Y = random.randint(70, 220)

        if keys[pygame.K_p]:
            game_paused = True

        if keys[pygame.K_p] and game_paused is True:
            game_paused = False

        if keys[pygame.K_ESCAPE]:
            pygame.quit()
            sys.exit()

        if not any(keys):
            boost += 2

        # Event types

        if event.type == SPAWNBUILDING1:
            building1_list.append(create_building1())
        if event.type == SPAWNBUILDING2:
            building2_list.append(create_building2())
        if event.type == SPAWNBUILDING3:
            building3_list.append(create_building3())

        if event.type == SHIPVEC:
            if ship_index < 2:
                ship_index += 1
            else:
                ship_index = 0

            ship_surface, ship_rect = ship_animation()

    # Background Movement

    if counter == 0:
        screen.blit(bg_surface1, (0, 0))
        counter = 1
    elif counter == 1:
        screen.blit(bg_surface2, (0, 0))
        counter = 2
    elif counter == 2:
        screen.blit(bg_surface3, (0, 0))
        counter = 3
    elif counter == 3:
        screen.blit(bg_surface4, (0, 0))
        counter = 0

    # Floor Movement

    floor_x_pos -= 1
    draw_floor()
    if floor_x_pos <= -1280:
        floor_x_pos = 0

    if game_active:

        # Ship

        checker = True
        ship_movement += gravity
        rotated_ship = rotate_ship(ship_surface)
        ship_rect.centery += ship_movement
        screen.blit(rotated_ship, ship_rect)
        over_message = check_collision(building1_list, building2_list, building3_list, bogey1_rect)
        if over_message != 'Game Running':
            checker = False
        game_active = checker

        # Buildings

        building1_list = move_buildings(building1_list)
        draw_buildings1(building1_list)
        building2_list = move_buildings(building2_list)
        draw_buildings2(building2_list)
        building3_list = move_buildings(building3_list)
        draw_buildings3(building3_list)

        score += 1
        score_display('main_game')

        # Contacts

        bogey1X -= 2
        bogey1_surface = bogey1_frames[bogey1_index]
        bogey1_index += 1
        screen.blit(bogey1_surface, (bogey1X, bogey1Y))
        if bogey1X <= -400:
            bogey1X = 1400
            bogey1Y = random.randint(70, 220)
        if bogey1_index > 2:
            bogey1_index = 0
        bogey1_rect = bogey1_surface.get_rect(center=(bogey1X + 80, bogey1Y))

    elif game_start:
        screen.blit(game_start_surface, game_start_rect)
        high_score = update_score(score, high_score)
        score_display('game_start')

    else:
        screen.blit(game_over_surface, game_over_rect)
        high_score = update_score(score, high_score)
        score_display('game_over')

    # Pause
    if game_paused:
        screen.blit(game_over_surface, game_over_rect)
        building1_list = stop_buildings(building1_list)
        building2_list = stop_buildings(building2_list)
        building3_list = stop_buildings(building3_list)
        bogey1X += 2

    # Clouds

    cloud1_x_pos -= .5
    screen.blit(cloud1_surface, (cloud1_x_pos, 50))
    if cloud1_x_pos <= -400:
        cloud1_x_pos = 1280
    cloud2_x_pos -= .5
    screen.blit(cloud2_surface, (cloud2_x_pos, 110))
    if cloud2_x_pos <= -400:
        cloud2_x_pos = 2000

    # Frame Rate

    pygame.display.update()
    clock.tick(60)


import argparse
import logging
import hashlib
import sqlite3

from pathlib import Path

from alive_progress import alive_bar
from Bio import SeqIO

parser = argparse.ArgumentParser(
    description='Annotate IPSs by NCBI nrp IDs and PSCs by nrp cluster gene labels.'
)
parser.add_argument('--db', action='store', help='Path to Bakta db file.')
parser.add_argument('--nrp', action='store', help='Path to NCBI NRP fasta file.')
parser.add_argument('--pcla-proteins', action='store', dest='pcla_proteins', help='Path to NCBI NRP PCLA proteins file.')
parser.add_argument('--pcla-clusters', action='store', dest='pcla_clusters', help='Path to NCBI NRP PCLA clusters file.')
args = parser.parse_args()

db_path = Path(args.db).resolve()
nrp_path = Path(args.nrp).resolve()
pcla_proteins_path = Path(args.pcla_proteins).resolve()
pcla_clusters_path = Path(args.pcla_clusters).resolve()

logging.basicConfig(
    filename='bakta.db.log',
    filemode='a',
    format='%(name)s - NCBI-NRP - %(levelname)s - %(message)s',
    level=logging.INFO
)
log_ups = logging.getLogger('UPS')
log_ips = logging.getLogger('IPS')
log_psc = logging.getLogger('PSC')

print('import PCLA proteins and cluster information...')
pcla_cluster_annotations = {}
with pcla_clusters_path.open() as fh, alive_bar() as bar:
    for line in fh:
        (id_, id, product, proteins, organisms, conserved_in_organism, conserved_in_taxid, gene, hmm) = line.split('\t')
        gene = gene.strip()
        product = product.strip().replace('"', '')
        if(gene == ''):
            gene = None
        if(product == '' or product.lower() == 'hypothetical protein' or product.lower() == 'uncharacterized protein' or product.lower() == 'uncharacterized conserved protein'):
            product = None
        pcla_cluster_annotations[id] = (gene, product)
    bar()

nrp_annotations = {}
with pcla_proteins_path.open() as fh, alive_bar() as bar:
    for line in fh:
        (cluster_id, id, definition, organism, taxid, length) = line.split('\t')
        if(cluster_id in pcla_cluster_annotations):
            nrp_annotations[id] = pcla_cluster_annotations[cluster_id]
        bar()
del pcla_cluster_annotations
print(f'found {len(nrp_annotations)} NRP / gene annotations')

print('lookup UPS by NRP hash & update WP_* / gene annotations...')
nrps_processed = 0
nrps_not_found = 0
nrps_wo_ips = 0
ups_updated = 0
psc_updated_gene = 0
psc_updated_product = 0
ncbi_nrp_path = Path(args.nrp).resolve()
with ncbi_nrp_path.open() as fh, sqlite3.connect(str(db_path), isolation_level='EXCLUSIVE') as conn, alive_bar() as bar:
    conn.execute('PRAGMA page_size = 4096;')
    conn.execute('PRAGMA cache_size = 100000;')
    conn.execute('PRAGMA locking_mode = EXCLUSIVE;')
    conn.execute(f'PRAGMA mmap_size = {20 * 1024 * 1024 * 1024};')
    conn.execute('PRAGMA synchronous = OFF;')
    conn.execute('PRAGMA journal_mode = OFF')
    conn.execute('PRAGMA threads = 2;')
    conn.commit()
    conn.row_factory = sqlite3.Row
    for record in SeqIO.parse(fh, 'fasta'):
        nrps_processed += 1
        nrp_id = record.id
        seq = str(record.seq).upper()
        seq_hash = hashlib.md5(seq.encode())
        seq_hash_digest = seq_hash.digest()
        seq_hash_hexdigest = seq_hash.hexdigest()
        rec_ups = conn.execute('SELECT length, uniref100_id FROM ups WHERE hash=?', (seq_hash_digest,)).fetchone()
        if(rec_ups is not None):
            assert rec_ups['length'] == len(seq), f"Detected hash duplicate with different seq length! hash={seq_hash_hexdigest}, NCRBI-NRP-id={nrp_id}, UniParc-id={rec_ups['uniparc_id']}, NCRBI-NRP-length={length}, db-length={rec_ups['length']}"
            if(rec_ups['uniref100_id']):
                rec_ips = conn.execute('SELECT * FROM ips WHERE uniref100_id=?', (rec_ups['uniref100_id'],)).fetchone()
                if(rec_ips is not None):
                    (gene, product) = nrp_annotations.get(nrp_id, (None, None))
                    log_ups.debug(
                        'ncbi-nrp-id=%s, hash=%s, uniref100=%s, uniref90=%s, gene=%s, product=%s',
                        nrp_id, seq_hash.hexdigest(), rec_ips['uniref100_id'], rec_ips['uniref90_id'], gene, product
                    )
                    conn.execute('UPDATE ups SET ncbi_nrp_id=? WHERE hash=?', (nrp_id[3:], seq_hash_digest))  # annotate IPS with NCBI nrp id (WP_*)
                    log_ups.info('UPDATE ups SET ncbi_nrp_id=%s WHERE hash=%s', nrp_id[3:], seq_hash_hexdigest)
                    ups_updated += 1
                    if(rec_ips['uniref90_id'] is not None):
                        if(gene is not None):
                            conn.execute('UPDATE psc SET gene=? WHERE uniref90_id=?', (gene, rec_ips['uniref90_id']))
                            log_psc.info('UPDATE psc SET gene=%s WHERE uniref90_id=%s', gene, rec_ips['uniref90_id'])
                            psc_updated_gene += 1
                        if(product is not None):
                            rec_psc = conn.execute('SELECT * FROM psc WHERE uniref90_id=?', (rec_ips['uniref90_id'],)).fetchone()
                            if(rec_psc is not None and rec_psc['product'] is None):
                                conn.execute('UPDATE psc SET product=? WHERE uniref90_id=?', (product, rec_ips['uniref90_id']))
                                log_psc.info('UPDATE psc SET product=%s WHERE uniref90_id=%s', product, rec_ips['uniref90_id'])
                                psc_updated_product += 1
                else:
                    nrps_wo_ips += 1
            else:
                nrps_wo_ips += 1
        else:
            nrps_not_found += 1
        if((nrps_processed % 1000000) == 0):
            conn.commit()
        bar()
    conn.commit()
print(f'NRPs processed: {nrps_processed}')
log_ups.debug('summary: # UPS with annotated NRP IDs=%i', ups_updated)
print(f'UPSs with annotated WP_* id: {ups_updated}')
log_psc.debug('summary: # PSC with annotated genes=%i', psc_updated_gene)
print(f'PSCs with annotated gene names: {psc_updated_gene}')
log_psc.debug('summary: # PSC with annotated products=%i', psc_updated_product)
print(f'PSCs with annotated gene products: {psc_updated_product}')
print(f'NRPs not found: {nrps_not_found}')
print(f'NRPs w/o IPS: {nrps_wo_ips}')


import pytest
import time
from regionfinder import TSDBClient, error

class MockTSDBResponse:
    def __init__(self, json_data):
        self.json_data = json_data

    def json(self):
        return self.json_data

fake_tsuid = '000000000000BBBBBBCCCCCC'
salted_tsuid = '1222222AAAAAABBBBBB'
def get_side_effect(arg):
    if 'dict' in arg:
        return MockTSDBResponse(dict())
    if 'empty_arr' in arg:
        return MockTSDBResponse([])
    if 'empty_dps' in arg:
        return MockTSDBResponse({'dps':{}, 'tsuids': [fake_tsuid]})
    if 'salted' in arg:
        return MockTSDBResponse([{'dps':{'1514764800': '1.0'}, 'tsuids': [salted_tsuid]}])
    return MockTSDBResponse([{'dps':{'1514764800': '1.0'}, 'tsuids': [fake_tsuid]}])

class TestTSDBClient:
    def test_get_encoded_timestamp(self):
        client = TSDBClient('', 3, 0)
        assert client._get_encoded_timestamp(0) == ('0'*8)
        assert client._get_encoded_timestamp(4095) == ('0'*5 + 'F'*3)
        assert len(client._get_encoded_timestamp(time.time())) == 8

    def test_get_rowkeys_of(self, mocker):
        mocker.patch('regionfinder.tsdb_client.requests.get', side_effect=get_side_effect)
        client = TSDBClient('', 6, 0)
        with pytest.raises(error.RegionFinderError):
            client.get_rowkeys_of('dict')
        with pytest.raises(error.RegionFinderError):
            client.get_rowkeys_of('empty_arr')
        with pytest.raises(error.RegionFinderError):
            client.get_rowkeys_of('empty_dps')
        assert len(client.get_rowkeys_of('normal')[0]) == (len(fake_tsuid) + 8)

        client = TSDBClient('', 3, 1)
        assert len(client.get_rowkeys_of('salted')[0]) == (len(salted_tsuid) + 8)


import pyasge

class Door:
    def __init__(self, position: pyasge.Point2D):
        self.sprite = pyasge.Sprite()
        self.sprite.loadTexture("/data/images/door.png")
        self.door_states = {
            'closed': pyasge.Point2D(0, 0),
            'opening_1': pyasge.Point2D(0, 64),
            'opening_2': pyasge.Point2D(0, 128),
            'open': pyasge.Point2D(0, 192)
        }
        self.set_sprite(self.door_states['closed'])
        self.sprite.x = position.x - self.sprite.width * 0.25
        self.sprite.y = position.y - self.sprite.height * 0.25
        self.sprite.scale = 1.2
        self.sprite.z_order = 2
        self.door_open = False
        self.elapsed_time = 0.0

    def set_sprite(self, pos: pyasge.Point2D):
        self.sprite.src_rect[pyasge.Sprite.SourceRectIndex.START_Y] = int(pos.y) + 1
        self.sprite.src_rect[pyasge.Sprite.SourceRectIndex.LENGTH_Y] = int(self.sprite.getTexture().height) * 0.25 - 2
        self.sprite.height = int(self.sprite.getTexture().height * 0.25) - 2

    def get_centre(self) -> pyasge.Point2D:
        sprite_centre = pyasge.Point2D(self.sprite.x + self.sprite.width * 0.5, self.sprite.y + self.sprite.height * 0.5)
        return sprite_centre

    def update(self, game_time: pyasge.GameTime):
        if self.door_open and self.elapsed_time < 1.0:
            if self.elapsed_time < 0.25:
                self.set_sprite(self.door_states['closed'])
            elif self.elapsed_time < 0.5:
                self.set_sprite(self.door_states['opening_1'])
            elif self.elapsed_time < 0.75:
                self.set_sprite(self.door_states['opening_2'])
            else:
                self.set_sprite(self.door_states['open'])

            self.elapsed_time += game_time.fixed_timestep


# Licensed under a 3-clause BSD style license - see LICENSE.rst

import os

import numpy as np
import pytest

from sofia_redux.instruments.hawc.datafits import DataFits
from sofia_redux.instruments.hawc.steps.stepscanmapflat import StepScanMapFlat
from sofia_redux.instruments.hawc.steps.stepscanmapflat import Reduction as SMR
from sofia_redux.instruments.hawc.tests.resources \
    import DRPTestCase, scan_raw_data

class TestScanMapFlat(DRPTestCase):
    def test_siso(self, tmpdir):
        hdul = scan_raw_data()
        ffile = str(tmpdir.join('test.fits'))
        hdul.writeto(ffile, overwrite=True)
        hdul.close()
        df = DataFits(ffile)

        # move to tmpdir -- writes temp files
        with tmpdir.as_cwd():
            step = StepScanMapFlat()

            out = step(df, options="rounds=1")
            assert isinstance(out, DataFits)
            assert len(out.imgnames) == 4
            assert 'R ARRAY GAIN' in out.imgnames
            assert 'T ARRAY GAIN' in out.imgnames
            assert 'R BAD PIXEL MASK' in out.imgnames
            assert 'T BAD PIXEL MASK' in out.imgnames

    def test_errors(self, tmpdir, capsys, mocker):
        # make some minimal input data
        df = DataFits()
        df.imageset(np.zeros((10, 10)), imagename='PRIMARY IMAGE')
        df.imageset(np.zeros((10, 10)), imagename='NOISE')
        df.imageset(np.zeros((10, 10)), imagename='EXPOSURE')
        df.setheadval('TELVPA', 270.0)
        df.setheadval('BUNIT', 'counts')
        fname = str(tmpdir.join('testdata.fits'))
        df.filename = fname
        df.save()

        # mock scanmap to return faster
        mocker.patch.object(SMR, 'run', return_value=None)

        with tmpdir.as_cwd():
            step = StepScanMapFlat()
            # default -- no output saved by mock scanmap, so will raise error
            with pytest.raises(ValueError):
                step(df)
            capt = capsys.readouterr()
            assert 'Unable to open scan map output file' in capt.err

            # if df.filename is not on disk, it will check for
            # df.rawname
            df.rawname = fname
            df.filename = 'badfile.fits'
            with pytest.raises(ValueError):
                step(df)
            step.arglist = {}
            capt = capsys.readouterr()
            assert os.path.basename(fname) in capt.out
            assert 'badfile.fits' not in capt.out

    def test_scanmapflat_frame_clip(self, tmpdir, capsys):
        """Test scan map frame clipping options in flat mode."""
        # make some data to test
        nf = 80
        hdul = scan_raw_data(nframe=nf)
        ffile = str(tmpdir.join('test.fits'))
        hdul.writeto(ffile, overwrite=True)
        hdul.close()
        inp = DataFits(ffile)

        with tmpdir.as_cwd():
            step = StepScanMapFlat()

            # run with all frames used, turning off some other
            # clipping options
            options = 'downsample=1 blacklist=vclip,fillgaps ' \
                      'shift=0 chopper.shift=0 rounds=1 q'
            step(inp, use_frames='', options=options)
            capt = capsys.readouterr()
            assert f'Reading {nf} frames' in capt.out
            assert f'{nf} valid frames' in capt.out

            # run with a specific range, with negative values on end
            step(inp, use_frames='5:-5', options=options)
            capt = capsys.readouterr()
            assert f'{nf - 10} valid frames' in capt.out
            assert f'Removing {10} frames outside range'


import matplotlib.pyplot as plt
import requests
import cartopy.crs as ccrs

def get_iss_coords():
    response = requests.get("http://api.open-notify.org/iss-now.json")
    coords = response.json()
    lat = float(coords['iss_position']['latitude'])
    lon = float(coords['iss_position']['longitude'])
    return lat, lon

def plot_coords(lat, lon):
    plt.clf()
    ax = plt.axes(projection=ccrs.PlateCarree())
    ax.stock_img()
    print(type(ax))
    plt.plot(lon, lat, color='red', linewidth=2, marker='o')
    plt.tight_layout()
    plt.show()

lat, lon = get_iss_coords()
plot_coords(lat, lon)


movie_list = {
    1: {"name": "The Princess", "rating": 26},
    2: {"name": "Spider-Man: No Way Home", "rating": 81},
    3: {"name": "Morbius", "rating": 64},
    4: {"name": "The Northman", "rating": 72},
    5: {"name": "Troll", "rating": 67},
    6: {"name": "Avatar", "rating": 76},
    7: {"name": "The Woman King", "rating": 79}
}

def get_rating(movie_id):
    return movie_list[movie_id]["rating"]

result_1 = sorted(movie_list, key=get_rating, reverse=True)
for id in result_1:
    print(movie_list[id])

print("-"*50)
result_2 = sorted(movie_list, key=lambda id: movie_list[id]["rating"], reverse=True)
for id in result_2:
    print(movie_list[id])


import random
from unidecode import unidecode

def jogar():

    def bem_vindo():
        print("************************************", end="\n")
        print('Bem vindo ao jogo de forca !', end='\n')
        print("************************************", end="\n\n")

    def definir_palavra_secreta():
        escolher_palavra = open('palavras.txt', 'r', encoding='utf-8')
        palavras = escolher_palavra.read().split('\n')
        escolher_palavra.close()

        return palavras[random.randrange(0, 30)]

    def perdeu():
        print('Que pena, voce perdeu !', end="\n\n")
        print('A palavra secreta era: ', palavra_secreta, sep="", end="\n\n")

    bem_vindo()

    palavra_secreta = definir_palavra_secreta()
    forcas = 7

    # display = ('{} ' * len(palavra_secreta)).format(*('_ ' * len(palavra_secreta)).split()).split()  # ['_', '_', ...]
    display = ['_' for letra in palavra_secreta]

    enforcou = False
    acertou = False

    while (not enforcou and not acertou):

        escolha = int(input('O que voce quer fazer ?\n(1) Chutar uma letra\n(2) Adivinhar a palavra secreta\n'))

        if (escolha == 1):
            chute = unidecode(input('Digite uma letra: '))

            index_palavra_secreta = 0
            letras_encontradas = []
            acerto = False
            for letra in palavra_secreta:
                if (unidecode(letra.lower()) == chute.lower()):
                    letras_encontradas.append(index_palavra_secreta)
                    acerto = True
                index_palavra_secreta += 1
            if (acerto):
                for index in letras_encontradas:
                    display[index] = palavra_secreta.capitalize()[index]
                print(*display)
            else:
                forcas -= 1
                print('A letra {} nao existe na palavra secreta !\nForca: {}'.format(chute, forcas))
                print(*display)
            if (not forcas):
                perdeu()
                enforcou = True
        elif (escolha == 2):
            palavra_usuario = input('Digite a palavra: ')
            if (palavra_secreta.lower() == palavra_usuario.lower()):
                print('Parabens ! Voce ganhou !!!')
                acertou = True
            else:
                perdeu()
                enforcou = True
        else:
            print('Escolha uma opcao valida !')

    print('Fim do jogo !')

if (__name__ == '__main__'):
    jogar()


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

'''
Date        : Fri Dec 11 12:56:00 CET 2020
Autor       : Leonid Burmistrov
Description : Simple reminder-training example.

'''

import numpy as np
import math
from itertools import combinations

def printinfo(func):
    def wrapper():
        print("")
        print("Simple reminder-training example. Function name : {} --> ".format(func.__name__))
        func()
    return wrapper

@printinfo
def div_by_zero(a=1.0):
    return a/0.0

@printinfo
def div_by_zero_try(a=1.0):
    try:
        return a/0.0
    except ZeroDivisionError: return None

def main():
    try:
        zeroDivisionVal=div_by_zero()
        print('zeroDivisionVal = ',zeroDivisionVal)
    except: pass
    zeroDivisionVal=div_by_zero_try()
    print('zeroDivisionVal = ',zeroDivisionVal)

if __name__ == "__main__":
    main()


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

"""
判断字符串开头与结尾
"""

__author__ = 'tomtiddler'

import os, stat

# str.startswith()
# str.endswith()

d = os.listdir(".")

if __name__ == "__main__":
    # print(d)
    for name in d:
        if name.endswith((".sh", ".py")):
            # print(oct(os.stat(name).st_mode))  #
            os.chmod(name, os.stat(name).st_mode | stat.S_IXUSR)  # 更改文件的执行权限


'''
Mostrar en pantalla si dos números enteros positivos n1 y n2 son amigos. Los números amigos son pares
de números enteros positivos en los cuales la suma de los divisores propios de cada número es igual al
otro número. En otras palabras, dos números amigos cumplen la condición de que la suma de los
divisores propios de uno de ellos es igual al otro número, y viceversa. Por ejemplo, el par de números
(220, 284) es un par de números amigos. Los divisores propios de 220 son 1, 2, 4, 5, 10, 11, 20, 22, 44,
55 y 110. Si sumamos estos números, obtenemos 284, que es el segundo número del par. Por otro lado,
los divisores propios de 284 son 1, 2, 4, 71 y 142, y si los sumamos, obtenemos 220, que es el primer
número del par.
'''

primero_num = int(input('Digite el primer numero: '))
segundo_num = int(input('Digite el segundo numero: '))
sum_primer_num = 0
sum_segundo_num = 0
for i in range(1, primero_num):
    if primero_num % i == 0:
        sum_primer_num += i

for j in range(1, segundo_num):
    if segundo_num % j == 0:
        sum_segundo_num += j
print('-' * 40)
if sum_primer_num == segundo_num:
    if sum_segundo_num == primero_num:
        print(f'Los numeros {primero_num} y {segundo_num} son amigos ')
else:
    print(f'Los numeros {primero_num} y {segundo_num} !No son amigos¡ ')

print('-' * 40)


import logging
import math
from overpy import Overpass
from geofence import Geofences
from models import Gym, init_database
from s2sphere import LatLng, CellId

# Specify app for a database connection and log to show module name in logs.
app = None
log = logging.getLogger(__name__)
db = init_database(app)
EARTH_CIRCUMFERENCE_METERS = 400750170

def earthMetersToRadians(meters):
    return (2 * math.pi) * (float(meters) / EARTH_CIRCUMFERENCE_METERS)

def ex_query(s, w, n, e):
    # Query Overpass for known gym areas.
    api = Overpass()
    result = api.query("""
    [out:json]
    [date:"2016-07-10T00:00:00Z"]
    [timeout:620]
    [bbox:{},{},{},{}];
    (
        // Tags that are confirmed to classify gyms as 'parks' for EX Raids.
        way[leisure=park];
        way[landuse=recreation_ground];
        way[leisure=recreation_ground];
        way[leisure=pitch];
        way[leisure=garden];
        way[leisure=golf_course];
        way[leisure=playground];
        way[landuse=meadow];
        way[landuse=grass];
        way[landuse=greenfield];
        way[natural=scrub];
        way[natural=heath];
        way[natural=grassland];
        way[landuse=farmyard];
        way[landuse=vineyard];
        way[landuse=farmland];
        way[landuse=orchard];
    );
    out body;
    >;
    out skel qt;
    """.format(s, w, n, e))

    return result

def update_ex_gyms(geofence):
    # Parse geofence file.
    log.info('Finding border points from geofence.')
    geofence = Geofences.parse_geofences_file(geofence, '')
    fence = geofence[0]['polygon']

    # Figure out borders for bounding box.
    south = min(fence, key=lambda ev: ev['lat'])['lat']
    west = min(fence, key=lambda ev: ev['lon'])['lon']
    north = max(fence, key=lambda ev: ev['lat'])['lat']
    east = max(fence, key=lambda ev: ev['lon'])['lon']

    log.info('Finding parks within zone.')
    ex_gyms = ex_query(south, west, north, east)
    gyms = Gym.get_gyms(south, west, north, east)

    if not gyms:
        log.error('No gyms detected within geofence, exiting.')
        exit(1)

    log.info(
        'Checking {} gyms against {} parks.'.format(len(gyms),
                                                    len(ex_gyms.ways)))
    # Retrieve list of confirmed EX gyms to update the DB.
    confirmed_ex_gyms = filter(lambda gym: __gym_is_ex_gym(gym, ex_gyms),
                               gyms.values())

    if not confirmed_ex_gyms:
        log.info('No EX-eligible gyms found.')
        exit(1)
    Gym.set_gyms_in_park(confirmed_ex_gyms, True)

def __gym_is_ex_gym(gym, ex_gyms):
    gympoint = [float(gym['latitude']),
                float(gym['longitude'])]
    s2_center = get_s2_cell_center(gympoint[0], gympoint[1], 20)

    for way in ex_gyms.ways:
        data = [{'lat': float(e.lat), 'lon': float(e.lon)} for e in way.nodes]

        if Geofences.is_point_in_polygon_custom(s2_center, data):
            gymname = gym['name'] or gym['gym_id']
            log.info('{} is eligible for EX raids.'.format(
                gymname.encode('utf8')))
            return True
    return False

def get_s2_cell_center(lat, lng, level):
    lat_lng = LatLng.from_degrees(lat, lng)
    cell_id = CellId.from_lat_lng(lat_lng).parent(level)
    center = cell_id.to_lat_lng()
    return {'lat': float(center.lat().degrees),
            'lon': float(center.lng().degrees)}


#!/usr/bin/env python3
from . import config

def get_targets():
    """
    Return all valid targets
    """

    return config.targets

def get_build_variants():
    """
    Return all valid build variants
    """

    build_variants = set()

    for key in config.distros:
        if "build_variants" in config.distros[key]:
            build_variants.update(set(config.distros[key]["build_variants"]))

def get_variant_distro_parent(variant):
    """
    Return the name of variant distro's parent distro
    """
    search_key = "variants"
    for key in config.distros:
        if search_key in config.distros[key]:
            if variant in config.distros[key][search_key]:
                return key

    return None

def get_distros():
    """
    Return all valid distros
    """

    distros = set()

    for key in config.distros:
        distros.add(key)

        if "variants" in config.distros[key]:
            distros.update(set(config.distros[key]["variants"]))

    return distros

def _get_distro_dict_value(distro, search_key):
    """
    Return value mapped to key in distro dictionary
    """
    for key in config.distros:
        if key == distro:
            if search_key in config.distros[key]:
                return config.distros[key][search_key]

        if "variants" not in config.distros[key]:
            continue

        for variant in config.distros[key]["variants"]:
            if variant == distro:
                if search_key in config.distros[key][variant]:
                    return config.distros[key][variant][search_key]
                elif search_key in config.distros[key]:
                    return config.distros[key][search_key]

    return None

def get_long_distro_name(distro):
    """
    Return long name for distro
    """
    return _get_distro_dict_value(distro, "name")

def get_distro_versions(distro):
    """
    Return valid versions for distro
    """
    search_key = "versions"
    versions = []

    value = _get_distro_dict_value(distro, search_key)
    if (value != None):
        versions.extend(value)

    value = _get_distro_dict_value(distro, "variants")
    if (value != None):
        for variant in value:
            if distro != variant:
                continue
            elif search_key in value[variant]:
                versions.extend(value[variant][search_key])

    return versions

def get_distro_repo_url(distro):
    """
    Return sync url for distro
    """
    return _get_distro_dict_value(distro, "url")

def get_distro_repo_dir(build_dir, distro, version):
    """
    Return repo source directory for distro
    """
    return build_dir + "/" + distro + "-" + version


## Program for bus algorithm ##

'''
Sample i/p
2
4
6 5 9 4
3
8 6 2
'''
from collections import OrderedDict

status = False
val = 1
t = int(input(''))
d1 = mc = {}
ord_dic = {}
for i in range(0,t):
	bn = int(input(('')))
	cb = raw_input('')
	d1[bn] = cb
	ord_dic[val] = bn
	val = val + 1

for k,v in d1.items():
	v = [int(i) for i in v.split(' ')]
	if len(v) != k:
		print('Please enter costs for %d buses' %(k))
		status = False
		break
	d1[k] = v
	status = True

if status:
	for k,v in d1.items():
	    c,s = 0, [];
	    li = sorted(v)
	    for i in range(len(v)):
	        if i == 0:
	            a,b = li[i],li[i+1]
	            c = c + (a+b)
	        else:
	            if i == len(li) - 1:
	                break
	            a,b = c,li[i+1]
	            c = a+b
	        s.append(c)
	    mc[k] = sum(s)
	# print mc
	# descending = OrderedDict(sorted(mc.items(), key=lambda kv: kv[1], reverse=True))
	for j in ord_dic.keys():
		ord_dic[j] = mc.get(ord_dic.get(j))
	for i in ord_dic.keys():
		print(ord_dic.get(i))


def two_sum(arr, target):
    l, r = 0, len(arr) -1
    while arr[l] + arr[r] != target:
        if arr[l] + arr[r] < target:
            l += 1
        else:
            r -= 1
    return [l+1, r+1]

print(two_sum([1,3,4,5,7,10,11], 9))


import pygame

def player_image_load():
    image_types = {
        "Attack" : [],
        "Dead" : [],
        "Idle" : [],
        "Jump" : [],
        "Jump_Attack" : [],
        "Jump_Throw" : [],
        "Run" : [],
        "Slide" : [],
        "Throw" : [],
    }

    for image_type in image_types:
        for i in range(0,10):
            image_to_load = pygame.image.load(f"./images/ninja/{image_type}__00{i}.png")
            image_to_load = pygame.transform.scale_by(image_to_load,.35)
            image_types[image_type].append(image_to_load)
    return image_types

def monster_image_load(monster_name,type):
    image_types = {
        "ATTAK" : [],
        "DIE" : [],
        "IDLE" : [],
        "HURT" : [],
        "JUMP" : [],
        "RUN" : [],
        "WALK" : [],
    }
    for image_type in image_types:
        for i in range(0,7):
            image_to_load = pygame.image.load(f"./images/{monster_name}/{image_type}/{image_type}_00{i}.png")
            factor_to_scale_by = .35
            if(type == "ork"):
                factor_to_scale_by = .2
            image_to_load = pygame.transform.scale_by(image_to_load,factor_to_scale_by)
            image_types[image_type].append(image_to_load)
    return image_types


import pandas as pd
from itertools import chain
from predict_code.multiprocess_model import send_data
# it is for getting data from app.py
class check_html_data:
    def __init__(self,list_data):
        self.list_data=list_data
    def check_data(self):
       # print(self.list_data)
        key_list = list(self.list_data.keys())
        dat_list=[]
        if "neural_network" in key_list:
            data_o="single"
            key_data=['neural_network','text_data','file_name']
            out = {x: self.list_data[x] for x in key_data}
            dat_list.append(out)

        if "lstm_model" in key_list:
            data_o="lstm"
            key_data=['lstm_model','text_data','file_name']
            out = {x: self.list_data[x] for x in key_data}
            dat_list.append(out)

        if "Conv_network" in key_list:
            data_o="conv"
            key_data=['Conv_network','text_data','file_name']
            out = {x: self.list_data[x] for x in key_data}
            dat_list.append(out)
        len_data=len(dat_list)
        send_value3=send_data(len_data,dat_list)
        data_out=send_value3.worker()
        data_value=list(chain.from_iterable(data_out))
        conv_data_v = list(filter(lambda x: x['model'] in ['Conv_network'], data_value))
        neural_network = list(filter(lambda x: x['model'] in ['neural_network'], data_value))
        lstm_data_v = list(filter(lambda x: x['model'] in ['Lstm_model'], data_value))
        data_save=[]
        if (len(conv_data_v)>0):
            conv_neural_sort=[d for d in conv_data_v if d['sentiment_type']=="Positive"]
            conv_neural_sort2=[d for d in conv_data_v if d['sentiment_type']=="Negative"]
            conv_data_positive=len(conv_neural_sort)
            conv_data_negative=len(conv_neural_sort2)
            data_output={"conv_network_positive":conv_data_positive,"conv_network_negative":conv_data_negative,"model":"Conv_network"}
            data_save.append(data_output)

        if (len(neural_network)>0):
            neural_network_sort=[d for d in neural_network if d['sentiment_type']=="Positive"]
            neural_network_sort2=[d for d in neural_network if d['sentiment_type']=="Negative"]
            neural_data_positive=len(neural_network_sort)
            neural_data_negative=len(neural_network_sort2)
            data_output={"neural_network_positive":neural_data_positive,"neural_network_negative":neural_data_negative,"model":"neural_network"}
            data_save.append(data_output)
        if (len(lstm_data_v)>0):
            lstm_network_sort=[d for d in lstm_data_v if d['sentiment_type']=="Positive"]
            lstm_network_sort2=[d for d in lstm_data_v if d['sentiment_type']=="Negative"]
            lstm_data_positive=len(lstm_network_sort)
            lstm_data_negative=len(lstm_network_sort2)
            data_output={"lstm_network_positive":lstm_data_positive,"lstm_network_negative":lstm_data_negative,"model":"lstm_network"}
            data_save.append(data_output)
        return data_save


from pyful import look
from pyful import message

from pyful.widget.listbox import ListBox, Entry

def define_menu(name, items):
    Menu.items[name] = items

class Menu(ListBox):
    items = {}

    def __init__(self):
        ListBox.__init__(self, "Menu")
        self.title = ""
        self.current = None

    def show(self, name, pos=0):
        if name not in self.items:
            return message.error("Undefined menu `{0}'".format(name))
        self.title = name
        self.current = self.items[name]
        self.refresh()
        entries = [Entry("{0} ({1})".format(item[0], item[1])) for item in self.current]
        super(self.__class__, self).show(entries, pos)

    def hide(self):
        self.current = None
        super(self.__class__, self).hide()

    def refresh(self):
        y, x = self.stdscr.getmaxyx()
        odd = y % 2
        base_y = y//2 + odd
        height = base_y + self.zoom
        if height > y-2:
            height = y - 2
            self.zoom = height - base_y
        elif height < 3:
            height = 3
            self.zoom = height - base_y
        width = x // 3
        self.panel.resize(height, width, y-height-3, 0)
        self.panel.attr = look.colors["MenuWindow"]

    def run(self):
        swap = self.current
        func = self.current[self.cursor][-1]
        func()
        if self.current is swap:
            self.hide()

    def input(self, key):
        if key in self.keymap:
            self.keymap[key]()
        else:
            swap = self.current
            names, keys, funcs = zip(*self.current)
            try:
                funcs[keys.index(key)]()
                if swap is self.current:
                    self.hide()
            except ValueError:
                pass


"""
Created on Wed Aug 19 18:55:30 2020

Process SARS-CoV-2 sequences, reconstruct ancestral states and return fitness features for model trainng

@author: david
"""

import pandas as pd
import re
import dendropy
from Bio import SeqIO
import AncestralReconstruction
import numpy as np
from ete3 import Tree
from pathlib import Path

def fasta2df(fasta_file):

    "Get sequences from fasta"
    seq_dic = {}
    for record in SeqIO.parse(fasta_file, "fasta"):
        seq_dic[record.id] = [i for i in record.seq]
    df = pd.DataFrame.from_dict(seq_dic, orient='index')

    return df

def filter_sites(df,freq_cutoff = 0.0):

    "Code mostly taken from filter_invariants.py function:"
    "https://github.com/btmartin721/raxml_ascbias/blob/master/ascbias.py"

    #bases = ["A","G","C","T"]
    alphabet = ["A","R","N","D","C","Q","E","G","H","I","L","K","M","F","P","S","T","W","Y","V"]

    invariant_lst = list()

    # Loop through each dataframe column
    for i in df.columns:

        # Gets unique values at each column and saves to list
        column_unique = df[i].unique().tolist()

        # Intersects column_unique with bases list
        intersect = [value for value in alphabet if value in column_unique]

        # If column contains only ambigous or IUPAC characters
        # Save the column index for dropping later
        if not any(value for value in alphabet if value in column_unique):
            invariant_lst.append(i)

        # Get frequency of each variant
        freqs = df[i].value_counts(normalize=True)
        if len(freqs.index) > 1:
            major_var = freqs.index[1]
            major_var_freq = freqs[1]
            if major_var == 'X' and len(freqs.index) > 2: # was major_var == '-'
                major_var = freqs.index[2]
                major_var_freq = freqs[2]
            if major_var == '-': # added to catch case were major variant is '-" in translated seqs
                major_var_freq = 0
        else:
            major_var_freq = 0

        # If site is invariant (only A, C, G, or T); ignores N's and "-"
        # OR frequency of major variant is less than frequency threshold cutoff
        if len(intersect) == 1 or major_var_freq < freq_cutoff:

            # Saves column indexes to list
            invariant_lst.append(i)

    # Drops invariant sites from dataframe
    df.drop(invariant_lst, axis=1, inplace=True)

    return df

def filter_variants(df,freq_cutoff):

    drop_lst = list()

    # Loop through each dataframe column
    for i in df.columns:

        # Get frequency of each variant
        freqs = df[i].value_counts(normalize=True)
        if len(freqs.index) > 1:
            var_freq = freqs[1]
        else:
            var_freq = 0 # Presumably this dosn't happen but just in case

        # If frequency of variant is less than frequency threshold cutoff
        if var_freq < freq_cutoff:
            drop_lst.append(i)

    # Drop sites from dataframe
    df.drop(drop_lst, axis=1, inplace=True)

    return df

def replace_missing(df):

    "Replace missing characters with consensus type"
    for i in df.columns:
        consensus = df[i].value_counts().index[0]
        if consensus == '-':
            print("WARNING: missing value '-' is consensus type at: ",str(i))
        df[i].replace(['-'], consensus, inplace=True)
    return df

def drop_consensus_dummies(df):

    "Drop dummy variable columns for consensus type"
    drop_lst = list()
    for i in df.columns:
        if '_' in i:
            var_str = i.split('_')[1]
        else:
            var_str = i
        splits = re.split(r'(\d+)', var_str)
        consensus = splits[0]
        var = splits[-1]
        if consensus == var: # If variant is consensus
            drop_lst.append(i)
    df.drop(drop_lst, axis=1, inplace=True)

    return df

def drop_root_state_dummies(df):

    "Drop dummy variable columns for consensus type"
    drop_lst = list()
    for i in df.columns:
        if df.loc['root'][i]: # If dummy represents root state
            drop_lst.append(i)
    df.drop(drop_lst, axis=1, inplace=True)

    return df

def drop_X_variants(df):

    "Drop dummy variable columns for consensus type"
    drop_lst = list()
    for i in df.columns:
        if i[-1] == 'X': # if undetermined
            drop_lst.append(i)
    df.drop(drop_lst, axis=1, inplace=True)

    return df

def rename_sites_defunct(df,prefix=''):

    for i in df.columns:
        consensus = df[i].value_counts().index[0]
        new_label = prefix + consensus+str(i+1) # index from 1
        df.rename(columns={i: new_label},inplace=True)

    return df

def rename_sites(df,prefix='',method='consensus'):

    for i in df.columns:
        if method == 'consensus':
            consensus = df[i].value_counts().index[0]
            new_label = prefix + consensus+str(i+1) # index from 1
        elif method == 'root':
            root_state = df.loc['root'][i]
            splits = i.split('_')
            if len(splits) > 1:
                prefix = splits[0] + '_'
                variant = splits[1]
            else:
                prefix = ''
                variant = i
            new_label = prefix + root_state + variant[1:]
        else:
            print("Renaming method not recognized")
            new_label = i
        df.rename(columns={i: new_label},inplace=True)

    return df

def get_geographic_locs(df,column_name,mapToRegion=False):

    path = './covid-analysis/maps/'
    code_map_file = path + 'code2StateMap.csv'
    state_map_file = path + 'state2HHSRegionMap.csv'

    code_df = pd.read_csv(code_map_file, index_col=0)
    codeMap = {index:row['State'] for index, row in code_df.iterrows()}

    state_df = pd.read_csv(state_map_file, index_col=0)
    stateMap = {index:row['Region'] for index, row in state_df.iterrows()}

    drop_indexes = []
    locations = []
    #for idx in df.index:
    for index, row in df.iterrows():

        gloc = row['virus_name'].split('/')[2] # if taking from GISAID metadata file
        #gloc = idx.split('/')[2] # after 2nd backslash
        gloc = gloc[:2] # first two chars should be state

        if gloc in codeMap:
            state_loc = codeMap[gloc]
            if mapToRegion:
                mapped_loc = stateMap[state_loc]
            else:
                mapped_loc = state_loc
        else:
            mapped_loc = 0 # 0 represents unknown
            print("Unrecognized geographic location: " + gloc)

        locations.append(mapped_loc)

    df[column_name] = locations
    df.drop(drop_indexes,inplace=True) # drop unknowns

    return df

def assign_pango_lineage_from_gisaid(df,column_name,pango_df):

    "Assign lineages"
    lines = []
    for index, row in df.iterrows():
        if index in pango_df.index:
            lines.append(pango_df.loc[index]['covv_lineage'])
        else:
            lines.append('None')
    df[column_name] = lines
    df[column_name].replace([np.nan], 'None', inplace=True)

    "Reduce # of lineages by iterativly mapping rare lineages to parent lineage until parent meets inclusion criteria"
    line_counts = df[column_name].value_counts()
    lineages_to_retain = line_counts[line_counts>=35].index # using 300 for paper results, was 100
    lineages_to_retain = lineages_to_retain.insert(0,'B.1.526')
    lineages_to_retain = lineages_to_retain.insert(0,'B.1.427')
    lineMap = {}
    for index, value in line_counts.items():
        if index in lineages_to_retain:
            lineMap[index] = index
        else:
            parent = index
            while parent not in lineages_to_retain:
                splits = parent.split('.')
                if len(splits) == 1:
                    parent = 'LowFreq' # splits[0]
                    break
                parent = '.'.join(splits[0:-1]) # returns parent e.g. B.1.1.7 --> B.1.1
            lineMap[index] = parent

    "Re-assign lineages"
    lines = []
    for index, row in df.iterrows():
        lines.append(lineMap[row[column_name]])
    df[column_name] = lines

    return df

def get_nsp6_del_state(df,align_file,column_name):

    "This is specifically hardcoded the nsp6 del9 deletion"
    seq_dict = SeqIO.to_dict(SeqIO.parse(align_file, "fasta"))
    deletions = []
    for index, row in df.iterrows():
        rec = seq_dict.get(index)
        seq_str = str(rec.seq[11287:11296]) # genomic start pos is shifted -1 for zero-based indexing
        del_str = '-'*9
        if seq_str == del_str:
            deletions.append(1)
        else:
            deletions.append(0)

    df[column_name] = deletions

    return df

def get_ORF9_del_state(df,align_file,column_name):

    "This is specifically hardcoded the ORF9 TRS -3 deletion"
    seq_dict = SeqIO.to_dict(SeqIO.parse(align_file, "fasta"))
    deletions = []
    for index, row in df.iterrows():
        rec = seq_dict.get(index)
        seq_str = str(rec.seq[28270]) # genomic start pos is shifted -1 for zero-based indexing
        del_str = '-'
        if seq_str == del_str:
            deletions.append(1)
        else:
            deletions.append(0)

    df[column_name] = deletions

    return df

def get_features(align_file,as_string=True):

    df = pd.read_csv(align_file, index_col=0)
    features = [column for column in df.columns]
    if as_string:
        features = ' '.join(features)
    return features

analysis_dir = Path("/Users/david/Documents/GitHub/phyloTF2/covid-analysis")
tree_dir = analysis_dir / "phylogenies" / 'GISAID-hCoV-19-phylogeny-2021-03-08'
base_dir = Path(__file__).parent.parent / "data"

meta_file = base_dir / "hcov_USA_post2020-09-01_EMSI_subsampled_metadata.csv"
tree_file = str(tree_dir / "hcov_march2021_USA_post2020-09-01_dated.tre")
subtree_file = str(base_dir / "hcov_USA_post2020-09-01_EMSI_mini.tre")
labeled_tree_file = str(base_dir / "hcov_USA_post2020-09-01_EMSI_mini_labeled.tre") # tree with internal labels

align_file = base_dir / 'hcov_USA_post2020-09-01_EMSI_subsampled_aligned.fasta'
unencoded_csv = base_dir / "hcov_USA_post2020-09-01_unencodedAncStates_dels+pangoline.csv"

"Get meta data file"
merged_df = pd.read_csv(meta_file,sep=",",index_col='accession_id')
filtered_taxa = merged_df.index.tolist()

"Extract tree of desired samples using dendropy"
#subtree_file = str(tree_dir / "hcov_USA_post2020-09-01_EMSI_mini.tre")
#filtered_taxa_spaces = [t.replace('_',' ') for t in filtered_taxa] # need to replace underscores with spaces to match dendropy taxon labels
#taxa = dendropy.TaxonNamespace()
#tree = dendropy.Tree.get(file=open(tree_file, 'r'), schema="newick", rooting="default-rooted", taxon_namespace=taxa)
#taxa_to_retain = set([taxon for taxon in tree.taxon_namespace if taxon.label in filtered_taxa_spaces])
#filtered_tree = tree.extract_tree_with_taxa(taxa=taxa_to_retain)
#filtered_tree.write(path=subtree_file,schema='newick',suppress_annotations=True,suppress_rooting=True)

"Get geographic locations"
#merged_df = get_geographic_locs(merged_df,'STATE',mapToRegion=False) # get states
#merged_df = get_geographic_locs(merged_df,'REGION',mapToRegion=True) # get states

"Work around since pangolin lineage assignments are not working"
desktop_dir = Path('/Users/david/Desktop/')
gisaid_metadata_file = desktop_dir / "GISAID_metadata_2021-03-10_USA.csv"
pangolin_df = pd.read_csv(gisaid_metadata_file,sep=",",index_col='covv_accession_id')
merged_df = assign_pango_lineage_from_gisaid(merged_df,'PANGOLINE',pangolin_df)
pangolin_lineage_counts = merged_df['PANGOLINE'].value_counts()
print(pangolin_lineage_counts)

"Add deletion features"
"Encode nsp6 deletion as binary variable in meta data"
del_label = 'nsp6_Delta9'
merged_df = get_nsp6_del_state(merged_df,align_file,del_label)

"Encode ORF9 TRS deletion as binary variable in meta data"
del_label = 'ORF9_TRS-3'
merged_df = get_ORF9_del_state(merged_df,align_file,del_label)

# "Get features to reconstruct"
features = ['PANGOLINE', 'nsp6_Delta9', 'ORF9_TRS-3']
# #features = merged_df.columns.to_list()

# "First assign internal labels to tree and then create new df for ancestral features"
tree = Tree(subtree_file, format=1)
tree = AncestralReconstruction.label_internal_nodes(tree)
node_labels = [node.name for node in tree.traverse("preorder")]
anc_df = pd.DataFrame(index=node_labels)

"Run MP ancestral state reconstruction for all features"
reconstruct = True # set false if already reconstructed
if reconstruct:
    for f in features:
        print('Reconstructing: ' + f)
        feature_dic = {}
        for index, row in merged_df.iterrows():
            feature_dic[index] = row[f]
        tree, anc_dic = AncestralReconstruction.reconstruct_MP(tree,feature_dic)
        anc_df[f] = pd.Series(anc_dic)
    tree.write(format=1, outfile=labeled_tree_file)

# "Save unencoded ancestral states df"
anc_df.to_csv(unencoded_csv,index_label='node')
# #anc_df = pd.read_csv(unencoded_csv,sep=",",index_col='node')


import asyncio
from typing import List

import aiohttp

from pyhanko.sign.general import SigningError
from pyhanko.sign.signers.csc_signer import (
    CSCAuthorizationInfo,
    CSCAuthorizationManager,
    CSCServiceSessionInfo,
    CSCSigner,
    fetch_certs_in_csc_credential,
)

class CSCDummyClientAuthManager(CSCAuthorizationManager):
    def __init__(self, session, session_info, credential_info, waste_time=0):
        self.session = session
        super().__init__(
            csc_session_info=session_info, credential_info=credential_info
        )
        self.authorizations_requested = 0
        self.waste_time = waste_time

    async def authorize_signature(
        self, hash_b64s: List[str]
    ) -> CSCAuthorizationInfo:
        self.authorizations_requested += 1
        session_info = self.csc_session_info
        req_data = self.format_csc_auth_request(hash_b64s=hash_b64s)
        session = self.session

        url = session_info.endpoint_url("credentials/authorize")
        async with session.post(
            url,
            headers=self.auth_headers,
            json=req_data,
            raise_for_status=True,
            timeout=30,
        ) as response:
            try:
                response_data = await response.json()
            except aiohttp.ClientError as e:
                raise SigningError("Credential auth request failed") from e

        if self.waste_time:
            await asyncio.sleep(self.waste_time)
        return self.parse_csc_auth_response(response_data)

class CSCDummy:
    def __init__(
        self,
        endpoint_url,
        credential_id,
        timeout: int,
        waste_time=0,
        **signer_kwargs,
    ):
        self.timeout = timeout
        self.svc_info = CSCServiceSessionInfo(
            service_url=endpoint_url,
            credential_id=credential_id,
            oauth_token='deadbeef',
            api_ver='v1',
        )
        self.waste_time = waste_time
        self.signer_kwargs = signer_kwargs
        self.session = None

    async def __aenter__(self):
        svc_info = self.svc_info
        self.session = session = aiohttp.ClientSession()
        creds = await fetch_certs_in_csc_credential(
            session=session, csc_session_info=svc_info
        )
        auth_manager = CSCDummyClientAuthManager(
            session, svc_info, credential_info=creds, waste_time=self.waste_time
        )
        signer = CSCSigner(
            session,
            auth_manager=auth_manager,
            sign_timeout=self.timeout,
            **self.signer_kwargs,
        )
        return signer

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        if self.session is not None:
            await self.session.close()


import random
from math import sqrt
# choosing a number between 1 to 100
num=random.randint(1,100)
def get_hint1():
  global num
  if(num%2==0):
    return "The Number you're guessing is even"
  else:
    return "The Number you're guessing is odd"

def is_prime(num):
  for i in range(2,int(sqrt(num))):
    if(num%i==0):return False
  return True

def get_hint2():
  global num
  if(is_prime(num) and num > 9):
    return "The Number is two digit prime number"
  elif(is_prime(num) and num > 9):
    return "The Number is single digit prime number"
  elif(num>9):
    return "The Number is two digit number which is not a prime"
  else:
    return "The Number is single digit number which is not a prime"

def get_hint3():
  global num
  if(num>=90):
    return "The Number is greater than 90"
  elif(num>=80 and num<90):
    return "The Number lies between 80 and 90"
  elif(num>=70 and num<80):
    return "The Number lies between 70 and 80"
  elif(num>=60 and num<70):
    return "The Number lies between 60 and 70"
  elif(num>=50 and num<60):
    return "The Number lies between 50 and 60"
  elif(num>=40 and num<50):
    return "The Number lies between 40 and 50"
  elif(num>=30 and num<40):
    return "The Number lies between 30 and 40"
  elif(num>=20 and num<30):
    return "The Number lies between 20 and 30"
  else:
    return "The Number lies between 10 and 20"

# Easy level game
def easy_level_guessing():
  lives=7
  hints=3
  while(lives>0):
    guess=int(input("Guess the number between 1 to 100: "))
    if(guess==num):
      print(f"Hoorayy!!You guessed the number correctly!The Number was {num}")
      break
    else:
      print("Wrong Guess.")
      lives-=1
      if(lives==0):
        print(f"Sorry,Unfortunately you cannot guess the number.The number was {num}")
        break
      hint=input(f"You've {lives} remaining guesses.Want help?Type 'yes' or 'no'").lower()
      if(hint=='yes'):
        if(hints==3):print(get_hint1())
        elif(hints==2):print(get_hint2())
        elif(hints==1):print(get_hint3())
        else:print("Sorry,You're out of hints.")
        hints-=1

# hard level game
def hard_level_guessing():
  lives=5
  hints=3
  while(lives>0):
    guess=int(input("Guess the number between 1 to 100: "))
    if(guess==num):
      print(f"Hoorayy!!You guessed the number correctly!The Number was {num}")
      break
    else:
      lives-=1
      if(lives==0):
        print(f"Sorry,Unfortunately you cannot guess the number.The number was {num}")
        break
      hint=input(f"You've {lives} remaining guesses.Want help?Type 'yes' or 'no'").lower()
      if(hint=='yes'):
        if(hints==3):print(get_hint1())
        elif(hints==2):print(get_hint2())
        else:print("Sorry,You're out of hints.")
        hints-=1


# report schema
from init import db, ma
from marshmallow import fields
from datetime import datetime

class Report(db.Model):
    __tablename__ = 'reports'

    id = db.Column(db.Integer, primary_key=True)
    time_reported = db.Column(db.DateTime, default=datetime.utcnow) # Time and date posted
    broken = db.Column(db.Boolean, default=False)

    # Foreign Keys
    location_id = db.Column(db.Integer, db.ForeignKey('locations.id'))
    user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'))

    # Do cascade deletes later for links
    # Relationships
    location = db.relationship('Location', back_populates='reports', cascade='all, delete')
    user = db.relationship('User', back_populates='reports', cascade='all, delete')
    comments = db.relationship('Comment', back_populates='report', cascade='all, delete')
    votes = db.relationship('Vote', backref='report')

# Returning userSchema is only for admins unless searched username is same as user
class ReportSchema(ma.Schema):

    # Schema Connections
    location = fields.Nested('LocationSchema')
    user = fields.Nested('UserSchema', exclude=['id', 'email', 'password', 'is_admin'])
    comments = fields.List(fields.Nested('CommentSchema'))

    # Formats time to readable string
    time_reported = fields.DateTime(format='%Y-%m-%d %H:%M:%S')

    # add a field for votes
    upvotes = fields.Method("get_upvotes")
    downvotes = fields.Method("get_downvotes")

    # Count the votes
    def get_upvotes(self, obj):
        return len([vote for vote in obj.votes if vote.vote_type == "upvote"])

    def get_downvotes(self, obj):
        return len([vote for vote in obj.votes if vote.vote_type == "downvote"])

    class Meta:
        fields = ('id','broken','location','user','time_reported', 'comments', 'upvotes', 'downvotes')


import statistics

print("你好吖!")
print("""This is a
    long line code.""")

x = 10
x += 1
print(x)

lists = []
rap = ["1", "2", "3"]
rock = ["4", "5", "6"]
djs = ["7", "8", "9"]
lists.append(rap)
lists.append(rock)
lists.append(djs)
rap = lists[0]
rap.append("hello")
print(lists)

location = []
la = (12.11, 34.444)
chicago = (223.1, 565.4)
location.append(la)
location.append(chicago)
print(location)

rap = ["1", "2", "3"]
rock = ["4", "5", "6"]
somemusic = (rap, rock)
print(somemusic)

fruits = {"apple": "red", "banana": "yellow"}
my_list = [fruits]
print(my_list)
my_tuple = (fruits,)
print(my_tuple)

mydict = {
    "location": (40.221, 74.222),
    "celebs": ["allen", "jay", "bacon"],
    "facts": {"state": "ny", "country": "usa"}
}
print(mydict)

"hello"*2

"hello ha".capitalize()

"{}fish".format("sha")

value = "once upon a time.I jumped over the puddle".split(".")
print(value)

join_thing = "abc"
result = "+".join(join_thing)
print(result)

test = '  hello  '
print(test.strip())

replace_test = "hello this is a replace test"
print(replace_test.replace("this", "kao"))

print("aninals".index("i"))

print("\nhello\nworld")

fict = ["Toast", "asian", "austin", "orwell"]
print(fict[0:2])
print(fict[:2])
print(fict[2:])

name = "shafish"
for char in name:
    print(char)

tv = ["error", "ok", "false", "true"]
i = 0
for show in tv:
    new = tv[i]
    new = new.upper()
    tv[i] = new
    i += 1

print(tv)

tv = ["error", "ok", "false", "true"]
for i, show in enumerate(tv):
    new = tv[i]
    new = new.upper()
    tv[i] = new

print(tv)

for i in range(1, 9):
    print(i)

x = 10
while x > 0:
    print('{}'.format(x))
    x -= 1
print("新年好！！")

for i in range(1, 6):
    print(i)
    if i == 2:
        break

nums = [1, 5, 33, 21, 55]
statistics.mean(nums)

# 中值
statistics.median(nums)

# 众值
statistics.mode(nums)

class Orange:
    def __init__(self, w, c):
        self.weight = w
        self.color = c
        print("created!")

or1 = Orange(10,"yellow")
print(or1.weight)
print(or1.color)
or1.weight = 20
or1.color = "dark"
print(or1.weight)
print(or1.color)

class Orange:
    # 类创建对象实例
    def __init__(self, w, c):
        self.weight = w
        self.color = c
        self.mold = 0
        print("created!")

    # 计算橘子的腐烂公式
    def rot(self, days, temp):
        self.mold = days * temp

orange = Orange(6, "green")
print(orange.mold)
orange.rot(10,34)
print(orange.mold)

class Rectangle():
    def __init__(self, w, l):
        self.width = w
        self.len = l

    def area(self):
        return self.width * self.len

    def change_size(self, w, l):
        self.width = w
        self.len = l

rectangle = Rectangle(30, 40)
print(rectangle.area())
rectangle.change_size(40, 50)
print(rectangle.area())

class Shape():
    def __init__(self, w, l):
        self.width = w
        self.len = l

    def print_size(self):
        print(" {} by {}".format(self.width, self.len))

class Square(Shape):
    pass

my_square = Square(20, 25)
my_square.print_size()

class Dog():
    def __init__(self, name, bread, owner):
        self.name = name
        self.bread = bread
        self.owner = owner

class Person():
    def __init__(self, name):
        self.name = name

mick = Person("make")
stan = Dog("job", "bulldog", mick)
print(stan.owner.name)


import os
from General_Utilities.control_rutas import setting_routes
from modules.django_rootes import *

key = 'resources'
path = setting_routes(key)[0]

projects_list = get_django_projects(path)
project_path = select_django_project(projects_list)
print(project_path)
os.chdir(project_path)
# print(os.getcwd())
# Correr el servidor
os.system('python .\manage.py runserver')


from email import header
import math
from env import BOARD_SIZE, HORIZON, ACTIONS, phi
import numpy as np
from env import GridWorld
import utils
from utils import device
import tensorboardX
import sys
ps = []
data_path = "/media/Z/shun/storage/gridworld/dataset"
model_path = "/media/Z/shun/storage/gridworld/model"
# policy_name = f""

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--c', type=float, default=1)
parser.add_argument('--epsilon', type=float, default=0.01)
parser.add_argument('--exp', type=float, default=0.05)
#parser.add_argument('--lamb', type=float, default=1)
#parser.add_argument('--beta', type=float)
parser.add_argument('--seed', type=int, default=1)
args = parser.parse_args()

# Tensorboard & Logger
# model_dir = f"{model_path}/pevi_phi1_nt-{utils.num_trajectories}_h-{HORIZON}_fromql_substract"
model_dir = f"{model_path}/pevi_true_nt-{utils.num_trajectories}_h-{HORIZON}_from_random"
txt_logger = utils.get_txt_logger(model_dir)
tb_writer = tensorboardX.SummaryWriter(model_dir)

# Log command and all script arguments
txt_logger.info("{}\n".format(" ".join(sys.argv)))
txt_logger.info("{}\n".format(args))

# Set seed for all randomness sources
utils.seed(args.seed)
txt_logger.info(f"Device: {device}\n")
txt_logger.info(f"Model dir: {model_dir}\n")

# Load env
dataset = utils.Dataset(utils.state_dim, utils.action_dim)
# dataset.load(data_path + "/qltab_dataset--nt-2000_h-40")
dataset.load(data_path + f"/random_dataset--nt-{utils.num_trajectories}_h-{HORIZON}")
env = GridWorld()
K = utils.num_trajectories
d = phi(env.current_location, ACTIONS[0]).shape[0]
prob = np.zeros([BOARD_SIZE]*utils.state_dim+[len(ACTIONS)]+[HORIZON])
VHat = np.zeros([BOARD_SIZE]*utils.state_dim+[HORIZON+1])
states = dataset.state[0:K*HORIZON,:].reshape((K, HORIZON, utils.state_dim))
actions = dataset.action[0:K*HORIZON,:].reshape((K, HORIZON, utils.action_dim))
rewards = dataset.reward[0:K*HORIZON].reshape((K, HORIZON))

#Hyperparameters
exp = args.exp
lamb = 1
shrink_rate = 0.5
beta_init = 1
#epsilon = args.epsilon
#xi = math.log(2*d*HORIZON*K/epsilon)
#lamb = 1
#c = 20
#beta = c*d*HORIZON*math.sqrt(xi)
K = utils.num_trajectories
VHat = np.zeros([BOARD_SIZE, BOARD_SIZE, HORIZON+1])
state = env.current_location
d = phi(state, ACTIONS[0]).shape[0]

def train():
    num_horizon = 0
    for h in list(range(1, HORIZON+1))[::-1]:

        print("Running at period", h)
        states_h, actions_h, rewards_h = states[:, h-1, :], actions[:, h-1, :], rewards[:, h-1]

        header = ["state", "action", "reward"]
        data = [states_h, actions_h, rewards_h]

        big_lambd = lamb*np.identity(d)
        var = 0
        for tau in range(K):
            s_tau_h, a_tau_h, r_tau_h = states_h[tau], actions_h[tau], rewards_h[tau]
            big_lambd = big_lambd + np.matmul(phi(s_tau_h, a_tau_h), phi(s_tau_h, a_tau_h).T)
            id = tuple(s_tau_h.astype(np.int32).reshape(1, -1)[0])
            var = var + phi(s_tau_h, a_tau_h)*(r_tau_h + VHat[id][h])
            # header_K = ["tau", "r_tau_h"]
            # data_K = [tau, r_tau_h.item()]
            # # print(type(s_tau_h), type(a_tau_h), type(r_tau_h.item()), type(big_lambd), type(var))
            # for field, value in zip(header_K, data_K):
            #     tb_writer.add_scalar(field, value, tau)
        w_hat_h = np.linalg.inv(big_lambd).dot(var)

        Big_Gamma_h = Q_Overline_h = Q_hat_h = pi_h = np.zeros([BOARD_SIZE]*utils.state_dim+[len(ACTIONS)])
        index_x = 0
        for x in np.ndindex((BOARD_SIZE,)*utils.state_dim):
            for a in range(len(ACTIONS)):
                beta = beta_init
                s = np.asarray(x)
                Big_Gamma_h[x][a] = math.sqrt(np.matmul(np.matmul(phi(s,a).T, np.linalg.inv(big_lambd)),phi(s,a)))
                while (np.dot(phi(s,a).T, w_hat_h) - beta*Big_Gamma_h[x][a] < 0 and beta > 0.01):
                    beta = beta*shrink_rate
                Q_Overline_h[x][a] = np.dot(phi(s,a).T, w_hat_h) - beta*Big_Gamma_h[x][a]
                Q_hat_h[x][a] = np.clip(Q_Overline_h[x][a], 0, HORIZON - h + 1)

            for a in range(len(ACTIONS)):
                if (a == np.argmax(Q_hat_h[x][:])):
                    #pi_h[x][a] = 1 - args.exp
                    pi_h[x][a] = 1
                else:
                    #pi_h[x][a] = args.exp/(len(ACTIONS))
                    pi_h[x][a] = 0
            index_x+=1
        for x in np.ndindex((BOARD_SIZE,)*utils.state_dim):
            sum = np.sum(pi_h[x][:])
            for a in range(len(ACTIONS)):
                pi_h[x][a] = pi_h[x][a]/sum
            VHat[x][h-1] = np.dot(Q_hat_h[x][:], pi_h[x][:])
        prob[:, :, :, h-1] = pi_h
        # header_678 = ["Q_Overline_h_"+str(a) for a in range(len(ACTIONS))]
        # header_678+= ["Q_hat_h_"+str(a) for a in range(len(ACTIONS))]
        # header_678+= ["Big_Gamma_h_"+str(a) for a in range(len(ACTIONS))]
        # # print(type(Q_Overline_h[0][0]), type(Q_hat_h[0][0]), type(Big_Gamma_h[0][0]))
        # # print(Q_Overline_h[0][0].shape, Q_hat_h[0][0].shape, Big_Gamma_h[0][0].shape)
        # # print(Q_Overline_h[0][0][a].item())
        # data_678 = [Q_Overline_h[0][0][a].item() for a in range(len(ACTIONS))]
        # data_678+= [Q_hat_h[0][0][a].item() for a in range(len(ACTIONS))]
        # data_678+= [Big_Gamma_h[0][0][a].item() for a in range(len(ACTIONS)) ]
        # # print(type(x))
        # for field, value in zip(header_678, data_678):
        #     tb_writer.add_scalar(field, value, num_horizon)
        num_horizon+=1

prob = train()
np.save(model_dir, prob)
txt_logger.info(f"Saved offline policy to {model_dir}.npy")


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os
import sys
from PyQt5.QtWidgets import QApplication
from core import Logger
from widgets import Login, DeployCard, UpdateDialog
from logic import LoginSignLogic, SqlManager
from model import LoginStatus

if getattr(sys, 'frozen', False):
    # frozen
    dir_ = sys._MEIPASS
else:
    # unfrozen
    dir_ = os.path.dirname(os.path.realpath(__file__))
sys.path.append(dir_)

log = Logger(__name__).get_log()

class MainWindow(object):
    def __init__(self):
        self._loginWindows = None
        self._toolWindows = None
        self._updateDialog = None

        self._loginLogic = LoginSignLogic()

        # check auto login
        cacheUser = self._loginLogic.getCacheUser()
        if cacheUser and self._loginLogic.autoLogin(cacheUser.Name, cacheUser.Password):
            self.showTools()
        else:
            self.showLogin()

    def showLogin(self):
        self._loginWindows = Login()
        self._loginWindows.loginSignal.connect(self.onLoginCallback)
        self._loginWindows.show()

    def showTools(self):
        self._toolWindows = DeployCard()
        self._toolWindows.show()
        self._updateDialog = UpdateDialog(self._toolWindows)

    def onLoginCallback(self, status):
        if status == LoginStatus.Success:
            self._loginWindows.close()
            self.showTools()

if __name__ == '__main__':
    app = QApplication(sys.argv)  # QApplication相当于main函数，也就是整个程序（很多文件）的主入口函数。对于GUI程序必须至少有一个这样的实例来让程序运行。
    try:

        window = MainWindow()

        result = app.exec_()
        sys.exit(result)
    except Exception as e:
        log.error(str(e))
    finally:
        SqlManager().dispose()