"""Script to place a set of pdb coordinates at a certain distance r. """

import argparse
import numpy as np
from flowerpack.io.read_pdb import read_pdb
from flowerpack.misc.math import get_rotation_matrix

def main():
    # Command-line input.
    parser = argparse.ArgumentParser(description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("pdb", help="Path of the pdb.")
    parser.add_argument("-r", "--radius", default=35.0, type=float,
        help="Radius between 2 coms.")
    parser.add_argument("-b", "--basename", default="ensemble", type=str,
        help="Output basename.")
    args = parser.parse_args()

    pdb = read_pdb(args.pdb)
    pdb.guess_element()

    mu = pdb.select_res(chain="A")
    com = mu.com()

    xyz = pdb.get_xyz()
    xyz = xyz - com

    top_plane = pdb.select_res([7, 63, 83, 142, 172, 240, 253], chain="A")
    bottom_plane = pdb.select_res([27, 43, 103, 122, 192, 220, 273], chain="A")

    vec = top_plane.com() - bottom_plane.com()
    vec = vec / np.linalg.norm(vec)

    rot = get_rotation_matrix(vec, [0,0,1])

    for n,r in enumerate(xyz):
        r_vec = np.reshape(r, (3,1))
        new_r = np.dot(rot, r_vec)
        xyz[n] = np.reshape(new_r,(3,))

    pdb.update_xyz(xyz)

    xyz_mu = pdb.select_res(chain="A").get_xyz()
    xyz_delta = pdb.select_res(chain="B").get_xyz()

    cos_theta = np.cos(np.deg2rad(30))
    sin_theta = np.sin(np.deg2rad(30))
    rot = np.array([[cos_theta, -sin_theta, 0], [sin_theta, cos_theta, 0], [0, 0, 1]])

    for i in range(12):
        for n,r in enumerate(xyz_mu):
            r_vec = np.reshape(r, (3,1))
            new_r = np.dot(rot, r_vec)
            xyz_mu[n] = np.reshape(new_r,(3,))

        for j in range(12):
            for n,r in enumerate(xyz_delta):
                r_vec = np.reshape(r, (3,1))
                new_r = np.dot(rot, r_vec)
                xyz_delta[n] = np.reshape(new_r,(3,))

            xyz_delta_trans = xyz_delta + [0, 35, 0]

            xyz = np.append(xyz_mu, xyz_delta_trans, axis=0)
            pdb.update_xyz(xyz)
            pdb.save_pdb("{}_{}_{}.pdb".format(args.basename, i, j))
            xyz = np.append(xyz_mu, xyz_delta, axis=0)
            pdb.update_xyz(xyz)

if __name__ == "__main__":
    print("Generating pdbs...")
    main()
    print("Generating pdbs done!")


from django.shortcuts import render
from django.http import HttpResponse
# from django.views.generic import TemplateView
# from .forms import HelloForm
from .forms import FriendForm
from .models import Friend
from django.shortcuts import redirect
# from django.db.models import QuerySet
from django.views.generic import ListView
from django.views.generic import DetailView
from .forms import FindForm
from django.db.models import Q
from django.db.models import Count,Sum,Avg,Min,Max
from .forms import CheckForm
from django.core.paginator import Paginator
from .models import Friend, Message
from .forms import FriendForm, MessageForm

class FriendList(ListView):
    model = Friend

class FriendDetail(DetailView):
    model = Friend

def index(request, num=1):
    data = Friend.objects.all()
    page = Paginator(data, 3)
    # re1 = Friend.objects.aggregate(Count('age'))
    # re2 = Friend.objects.aggregate(Sum('age'))
    # re3 = Friend.objects.aggregate(Avg('age'))
    # re4 = Friend.objects.aggregate(Min('age'))
    # re5 = Friend.objects.aggregate(Max('age'))
    # msg = 'count:' + str(re1['age__count']) + '
Sum:' + str(re2['age__sum']) + '
Average:' + str(re3['age__avg']) + '
Min:' + str(re4['age__min']) + '
Max:' + str(re5['age__max'])
    params = {
        'title': 'Hello',
        'message':'',
        'data': page.get_page(num),
    }
    return render(request, 'k_app002/index.html', params)

# create model
def create(request):
    if (request.method == 'POST'):
        obj = Friend()
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/k_app002')
    params = {
        'title': 'Hello',
        'form': FriendForm(),
    }

    return render(request, 'k_app002/create.html', params)

def edit(request, num):
    obj = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend = FriendForm(request.POST, instance=obj)
        friend.save()
        return redirect(to='/k_app002')
    params = {
        'title': 'Hello',
        'id': num,
        'form': FriendForm(instance=obj),
    }
    return render(request, 'k_app002/edit.html', params)

def delete(request, num):
    friend = Friend.objects.get(id=num)
    if (request.method == 'POST'):
        friend.delete()
        return redirect(to='/k_app002')
    params = {
        'title': 'Hello',
        'id': num,
        'obj': friend,
    }
    return render(request, 'k_app002/delete.html', params)

def find(request):
    if (request.method == 'POST'):
        msg = request.POST['find']
        form = FindForm(request.POST)
        sql = 'select * from k_app002_friend'
        if (msg != ''):
            sql += ' where ' + msg
        data = Friend.objects.raw(sql)
        msg = sql
    else:
        msg = 'search words...'
        form = FindForm()
        data = Friend.objects.all()
    params = {
        'title': 'Hello',
        'message': msg,
        'form': form,
        'data': data,
    }
    return render(request, 'k_app002/find.html', params)

def check(request):
    params = {
        'title': 'Hello',
        'message': 'check validation.',
        'form': FriendForm(),
    }
    if (request.method == 'POST'):
        obj = Friend()
        form = FriendForm(request.POST, instance=obj)
        params['form'] = form
        if (form.is_valid()):
            params['message'] = 'OK!'
        else:
            params['message'] = 'no good.'
    return render(request, 'k_app002/check.html', params)

def message(request, page=1):
    if (request.method == 'POST'):
        obj = Message()
        form = MessageForm(request.POST, instance=obj)
        form.save()
    data = Message.objects.all().reverse()
    paginator = Paginator(data, 5)
    params = {
        'title': 'Message',
        'form': MessageForm(),
        'data': paginator.get_page(page),
    }
    return render(request, 'k_app002/message.html', params)


#!/usr/bin/env python3 -tt
"""
File: reassemble.py
-------------------
Assignment 2: Quest for the Holy Grail
Course: CS 41
Name: Simon Kim
SUNet: spkim

Joins spliced pixels of images. Also outputs the corresponding message.
"""
import imageutils as iu
import math

def pixelProximity(p1, p2):
	"""
	@param p1, p2: Two pixels
	@return: Absolute value of the difference of each pixel RGB values
	"""
	return abs(p1.red - p2.red) + abs(p1.green - p2.green) + abs(p1.blue - p2.blue) + abs(p1.alpha - p2.alpha)

def columnProximity(c1, c2):
	"""
	@param c1, c2: Two columns
	@return: Average value of the pixelProximity of two columns.
	"""
	answer = 0
	for i in range(len(c1)): #could have mapped this ;)
		answer += pixelProximity(c1[i], c2[i])
	return answer / len(c1)

def sliceProximity(s1, s2):
	"""
	Compares the right-most column of s1 with the left-most column of s2.

	@param s1, s2: Two slices
	@return: ColumnProximity of two slices
	"""
	return columnProximity(s1[-1], s2[0])

def glue_together(slices):
	"""
	@param slices: all the slices read from the input files
	@return: index of the slices in order of how they should come together
	"""
	remaining = set(range(len(slices)))
	answer = []
	# For destination: 62
	# For others: 3
	start = 62
	answer.append(start)
	remaining.remove(start)

	while len(remaining) > 0:
		key = slices[answer[-1]][1]
		minValue = float('inf')
		minSlice = None
		for s in remaining:
			val = sliceProximity(key, slices[s][1])
			if val < minValue:
				minValue = val
				minSlice = slices.index((slices[s][0], slices[s][1]))
		answer.append(minSlice)
		remaining.remove(minSlice)
	return answer

if __name__ == '__main__':
    """
    Puts together the slices and store it as a file named 'map'
    Also prints the corresponding message on console.

    MESSAGES:
    1) HOLY
    2) YOU FOUND A MESSAGE!
    """
    IMAGE_DIRECTORY = 'shredded/destination'
    files = iu.files_in_directory(IMAGE_DIRECTORY)

    # Stores tuple (filename, pixels)
    slices = [(fn, iu.load_image(fn)) for fn in files]
    answer = glue_together(slices)
    tm = []
    kw = ""
    for a in answer:
    	kw += slices[a][0][-5]
    	tm += slices[a][1]
    iu.save_image(tm, 'map')
    print(kw)

#great decomposition on this one! loved the functional programming of this one


# -*- coding: utf-8 -*-
from openerp import models, fields, api

class Postal_code(models.Model):
    _name = 'batoi_logic.postal_code'

    name = fields.Integer(String='Postal code', size=5, required=True)
    address_id = fields.One2many('batoi_logic.address', 'postal_code_id', 'Addresses with this Zip Code')
    city_id = fields.Many2one('batoi_logic.city', 'City', required=True)

    _sql_constraints = [
        ('batoi_logic_name', 'UNIQUE (name)', 'The postal code must be unique')]


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import sorl.thumbnail.fields
import datetime
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=128)),
                ('date', models.DateTimeField(default=datetime.datetime(2015, 8, 13, 9, 46, 45, 165938))),
                ('body', models.TextField(max_length=10000, blank=True)),
                ('upload_image', sorl.thumbnail.fields.ImageField(null=True, upload_to=b'blog_img', blank=True)),
                ('author', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


# Copyright (c) OpenMMLab. All rights reserved.
# Copyright (C) 2022 Habana Labs, Ltd. an Intel Company
from collections import OrderedDict
import numpy as np
import torch
import torch.distributed as dist
class LogBuffer:
    def __init__(self):
        self.val_history = OrderedDict()
        self.n_history = OrderedDict()
        self.running_sum = OrderedDict()
        self.running_count = OrderedDict()
        self.output = OrderedDict()
        self.ready = False
    def clear(self):
        self.val_history.clear()
        self.n_history.clear()
        self.running_sum.clear()
        self.running_count.clear()
        self.clear_output()
    def clear_output(self):
        self.output.clear()
        self.ready = False
    def update(self, vars, count=1):
        assert isinstance(vars, dict)
        for key, var in vars.items():
            if type(var) == type(torch.tensor([])):
                self.running_sum[key] = self.running_sum.get(key, 0) + count * var
                self.running_count[key] = self.running_count.get(key, 0) + count
            else:
                if key not in self.val_history:
                    self.val_history[key] = []
                    self.n_history[key] = []
                self.val_history[key].append(var)
                self.n_history[key].append(count)
    def average(self, n=0):
        """Average latest n values or all values."""
        assert n >= 0
        for key in self.val_history:
            values = np.array(self.val_history[key][-n:])
            nums = np.array(self.n_history[key][-n:])
            avg = np.sum(values * nums) / np.sum(nums)
            self.output[key] = avg
        for key in self.running_sum:
            if dist.is_available() and dist.is_initialized():
                dist.all_reduce(self.running_sum[key].div_(dist.get_world_size()))
            avg = (self.running_sum[key]/self.running_count[key]).item()
            self.running_sum[key] = 0
            self.running_count[key] = 0
            self.output[key] = avg

        self.ready = True


#!/usr/bin/env python

## =================================================================================
## Created Wednesday, May 31, 2017 at 11:52:31 (wesley.cobb@exxonmobil.com)
## Copyright (C) 2016, by Wesley Kenneth Cobb. All Rights Reserved.
## =================================================================================

##
## standard package imports
##

import os
import sys
import cv2
import time
import math
import string
import pickle
import scipy as sp
import numpy as np
import pandas as pa
import tensorflow as tf
import geopandas as gpa
import matplotlib.pyplot as plt

from image_clip import make_support_clips
from image_clip import ImageClip

##
## crop out a tanker image
##

def tanker_image(img, x, y, w, h, nobox=True):
    if (nobox == False):
        cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 1)
    return img[y:y+h, x:x+w, :]

##
## place a tanker image fragment into another image somewhere...
##

def put_tanker_image_at(img, tanker, point, flipx=False, flipy=False):
    (h,w,c) = tanker.shape
    (x,y) = point
    if (flipx == False) and (flipy == False):
        img[y:y+h-1, x:x+w-1, :] = tanker[0:h-1, 0:w-1, :]
    elif (flipx == True) and (flipy == False):
        img[y:y+h-1, x:x+w-1, :] = tanker[0:h-1, w:0:-1, :]
    elif (flipx == False) and (flipy == True):
        img[y:y+h-1, x:x+w-1, :] = tanker[h:0:-1, 0:w-1, :]
    elif (flipx == True) and (flipy == True):
        img[y:y+h-1, x:x+w-1, :] = tanker[h:0:-1, w:0:-1, :]

##
## random pick left or right
##
def randomPickLeft(enabled=True):
    if (enabled == True):
        if (int(np.random.rand() * 2)) == 0:
            return True
        else:
            return False
    else:
        return False

##
## random flip image across Y axis True or False
##
def randomFlipX(enabled=False):
    if (enabled == True):
        if (int(np.random.rand() * 2)) == 0:
            return True
        else:
            return False
    else:
        return False
##
## random flip image across X axis True or False
##
def randomFlipY(enabled=False):
    if (enabled == True):
        if (int(np.random.rand() * 2)) == 0:
            return True
        else:
            return False
    else:
        return False

##
## produce the relevant supporting clips...
##
def simulation_support_clips(data_dir='simulation', ULHC=(0,0), LRHC=(428,625), verbose=True, overwrite=True):
    make_support_clips(data_dir='simulation', ULHC=ULHC, LRHC=LRHC, verbose=verbose, overwrite=overwrite)

##
## the main function...
##

if (__name__ == "__main__"):
    '''
    '''
    x_size   = 625
    y_size   = 428
    draw_box = True
    scroll   = False

    ## create various support clips from the images
    ## found in the data directory...
    if (os.path.exists('./data/khark_color.clp') == False):
        make_support_clips()

    ## instantiate an imageclip object...
    color = ImageClip('khark_color')

    ## load the clip...
    color.load()

    ## display some of the images...
    if (scroll == True):
        print("\n...scrolling through images in clip")
        for name in color.skeys:
            img = cv2.resize(color.clip[name], (x_size, y_size))
            cv2.imshow('Viewer', img)
            print("...now displaying \'%s\' in Viewer" % name)
            cv2.waitKey(3000)
        cv2.destroyAllWindows()

    ## this is the image we're working with...
    print("...building stack of tanker images to use in synthesis")
    tankers = []
    print("...tanker fragments from image \'data/khark/20120529.png\'")
    img = cv2.resize(color.clip['20120529.png'].copy(), (x_size, y_size))
    ## upper left hand side tankers...
    #tankers.append(tanker_image(img,  35,  68, 13, 33, nobox=True))
    tankers.append(tanker_image(img, 35,  70, 13, 32, nobox=True))
    #tankers.append(tanker_image(img,  60, 110, 13, 33, nobox=True))
    tankers.append(tanker_image(img, 60, 112, 13, 31, nobox=True))
    tankers.append(tanker_image(img, 532, 298,  8, 18, nobox=True))

    print("...target image \'data/khark/20130716.png\'")

    # generate a sequence of simulation images...
    if (os.path.exists('simulation') == False):
        os.mkdir('simulation')
    if (os.path.exists('simulation/khark') == False):
        simulation_dir = 'simulation/khark'
        os.mkdir('simulation/khark')

        # save the objects clip so that we have a reference set to
        # search-for and match-against...
        objects_clip_name = 'simulation/khark_objects.clp'
        objects_clip = {}
        for i in range(0,len(tankers)):
            object_name = ("%d" % i)
            objects_clip[object_name] = tankers[i]
        pickle.dump(objects_clip,open(objects_clip_name,'wb'))

        # one frame per week (for example)
        generated_frames = 52
        generated_tankers = 0

        for f in range(0, generated_frames):
            # randomly pick the number of tankers to add...
            n_random = int(4 * np.random.rand() + 0.5)
            print("...randomly placing %d tankers" % n_random)
            img = cv2.resize(color.clip['20130716.png'].copy(), (x_size, y_size))
            # randomly place that many tankers in the scene...
            in_this_image = 0
            for i in range(0,n_random):
                # randomly choos a tanker from our list...
                this_tanker = int(len(tankers) * np.random.rand()) # randomly pick {0, 1, 2}
                # generate random locations though constrain to be at sea...
                if (randomPickLeft() == True):
                    x = int( 40 + 60 * np.random.rand())
                    y = int( 40 + 200 * np.random.rand())
                else:
                    x = int(530 + 60 * np.random.rand())
                    y = int( 40 + 350 * np.random.rand())

                try:
                    put_tanker_image_at(img, tankers[this_tanker], (x,y), flipx=randomFlipX(), flipy=randomFlipY())
                    in_this_image += 1

                except Exception as e:
                    print("...ignoring exception (not counting trial placement)")

            generated_tankers += in_this_image
            cv2.imshow('Viewer', img)
            this_file_name = ("%s/im%0.3d_%0.2d.png" % (simulation_dir,f,in_this_image))
            cv2.imwrite(this_file_name,img)
            print("...saved %s, current running total = %d" % (this_file_name, generated_tankers))

        time.sleep(10)
        print("...%d generated tankers appear in the simulation" % generated_tankers)

    # generate the simulation support clips
    if (os.path.exists('simulation/khark_color.clp') == False):
        simulation_support_clips()

    # now load and play the clip...
    simulation = ImageClip('khark_color', dpath='simulation')
    simulation.load()
    simulation.play(xres=625, yres=428, fps=1, repeat=1)


import config
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import makedir_exist_ok, apply_fn
from .utils import make_model

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__init__()
        self.model = make_model(config.PARAM['model'])
        makedir_exist_ok('./output/tmp')

    def pack(self, code):
        code = np.packbits(code.detach().cpu().numpy().astype(np.int8)).reshape(-1, 1)
        return code

    def unpack(self, code):
        code = torch.from_numpy(code.astype(np.float32)).to(config.PARAM['device'])
        return code

    def loss_fn(self, output, target):
        if config.PARAM['loss_fn'] == 'bce':
            loss_fn = F.binary_cross_entropy
        elif config.PARAM['loss_fn'] == 'mse':
            loss_fn = F.mse_loss
        elif config.PARAM['loss_fn'] == 'mae':
            loss_fn = F.l1_loss
        else:
            raise ValueError('Not valid loss function')
        loss = loss_fn(output, target)
        return loss

    def forward(self, input):
        output = {'loss': torch.tensor(0, device=config.PARAM['device'], dtype=torch.float32), 'img': [], 'code': []}
        x = input['img'] * 2 - 1
        reconstructed = x.new_zeros(x.size())
        indices = torch.arange(input['img'].size(0),device=config.PARAM['device'])
        for i in range(config.PARAM['num_iter']):
            encoded = []
            node_indices = []
            for j in range(config.PARAM['num_node']):
                node_x = x[input['label'] == j]
                if node_x.size(0) == 0:
                    continue
                encoded.append(self.model['encoder'][j](node_x))
                node_indices.append(indices[input['label'] == j])
            encoded = torch.cat(encoded, dim=0)
            node_indices = torch.cat(node_indices, dim=0)
            encoded[node_indices] = encoded
            code = self.model['quantizer'](encoded)
            output['code'].append(self.pack(code))
            decoded = self.model['decoder'](code)
            decoded = (decoded + 1) / 2 if i == 0 else decoded
            reconstructed = reconstructed + decoded
            output['loss'] = output['loss'] + self.loss_fn(reconstructed, input['img'])
            x = input['img'] - reconstructed
            output['img'].append(reconstructed)
        output['loss'] = output['loss'] / config.PARAM['num_iter']
        for i in range(1,config.PARAM['num_iter']):
            output['code'][i] = np.concatenate((output['code'][i-1], output['code'][i]), axis=1)
        apply_fn(self, 'free_hidden')
        return output

def dist_codec():
    config.PARAM['model'] = {}
    config.PARAM['model']['encoder'] = [
        ({'cell': 'ConvCell', 'input_size': config.PARAM['num_channel'], 'output_size': 32, 'kernel_size': 1,
         'stride': 1, 'padding': 0, 'bias': True, 'activation': config.PARAM['activation'],
         'normalization': config.PARAM['normalization']},
        {'cell': 'PixelShuffleCell', 'mode': 'down', 'scale_factor': 2},
        {'cell': 'ConvLSTMCell', 'input_size': 128, 'output_size': 128, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'PixelShuffleCell', 'mode': 'down', 'scale_factor': 2},
        {'cell': 'ConvLSTMCell', 'input_size': 512, 'output_size': 128, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'PixelShuffleCell', 'mode': 'down', 'scale_factor': 2},
        {'cell': 'ConvLSTMCell', 'input_size': 512, 'output_size': 128, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'ConvCell', 'input_size': 128, 'output_size': config.PARAM['code_size'], 'kernel_size': 1,
         'stride': 1, 'padding': 0, 'bias': False, 'activation': config.PARAM['activation'],
         'normalization': config.PARAM['normalization']},)
    ] * config.PARAM['num_node']
    config.PARAM['model']['quantizer'] = {'cell': 'QuantizationCell'}
    config.PARAM['model']['decoder'] = (
        {'cell': 'ConvCell', 'input_size': config.PARAM['code_size'], 'output_size': 128, 'kernel_size': 1,
         'stride': 1, 'padding': 0, 'bias': False, 'activation': config.PARAM['activation'],
         'normalization': config.PARAM['normalization']},
        {'cell': 'ConvLSTMCell', 'input_size': 128, 'output_size': 512, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'PixelShuffleCell', 'mode': 'up', 'scale_factor': 2},
        {'cell': 'ConvLSTMCell', 'input_size': 128, 'output_size': 512, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'PixelShuffleCell', 'mode': 'up', 'scale_factor': 2},
        {'cell': 'ConvLSTMCell', 'input_size': 128, 'output_size': 128, 'kernel_size': 3, 'stride': 1,
         'padding': 1, 'bias': False, 'num_layers': 1, 'activation': config.PARAM['activation']},
        {'cell': 'PixelShuffleCell', 'mode': 'up', 'scale_factor': 2},
        {'cell': 'ConvCell', 'input_size': 32, 'output_size': config.PARAM['num_channel'], 'kernel_size': 1,
         'stride': 1, 'padding': 0, 'bias': False, 'activation': config.PARAM['activation'],
         'normalization': config.PARAM['normalization']}
    )
    model = Model()
    return model


def gcd(m,n):
    i = 1
    while i<=a and i<=b:
        if a%i==0 and b%i==0:
            gcd=i
        i=i+1
    return gcd

a = int(input('a = '))
b = int(input('b = '))
print('최대공약수 :', gcd(a,b))


from django.db import models

from applications.departamento.models import *
#ckeditor
from ckeditor.fields import RichTextField
# Create your models here.

class Habilidades(models.Model):
    habilidad = models.CharField("Habilidad", max_length=50)

    class Meta:
        verbose_name="Habilidad"
        verbose_name_plural="Habilidades de los empleados"

    def __str__(self):
        return str(self.id)+'--'+ self.habilidad

class Empleado(models.Model):

    Job=(
        ('0' , 'CONTADOR'),
        ('1' , 'ADMINISTRADOR'),
        ('2' , 'ECONOMISTA'),
        ('3' , 'OTRO'),
    )

    first_name = models.CharField('Nombres', max_length=50)
    last_name = models.CharField('Apellidos', max_length=50)
    full_name = models.CharField('Nombre completo', max_length=120, blank=True) #que no es obligatorio

    job = models.CharField('Trabajo', max_length=1, choices=Job)  #Lista de Opciones el valor que se guarda en la base es el numero
    #ojo primero importar el modelo al que se va a relacionar
    #Luego s epone el model a relacionar
    #comando  fk
    departamento = models.ForeignKey(Departamento, on_delete=models.CASCADE)
    #m2m
    #Relacion de muchos a muchos con la tabla habilidades de arriba
    habilidades = models.ManyToManyField(Habilidades)
    #Para el Ckeditor
    hoja_vida= RichTextField()
    foto = models.ImageField(upload_to="empleado", blank=True, null=True)

    class Meta:
        verbose_name="Empleado"
        verbose_name_plural="Empleados de la empresa"
        ordering = ['first_name'] #Orden los elementos si le pones ["-name"] es la inversa
        unique_together=('first_name',) #no permite que se registren elementos convinados del nombre y nombre corto

    def __str__(self):
        return str(self.id)+'--'+ self.first_name + '--' + self.last_name


class Solution:
    def numUniqueEmails(self, emails):
        """
        :type emails: List[str]
        :rtype: int
        """
        res = set()
        for email in emails:
            local, host = email.split('@')
            res.add(local.split('+')[0].replace('.','')+'@'+host)
        return len(res)


import requests
from requests.auth import HTTPBasicAuth
from local import GIT_TOKEN
from subprocess import call, check_output
import re
from app import *

BASE_URL = "https://api.github.com/repos/PresidentNick/cs373-idb/"

def get_stat():
	Stat = {}
	contributors = requests.get(BASE_URL + "stats/contributors", auth=HTTPBasicAuth('will555413', GIT_TOKEN)).json()
	issues = requests.get(BASE_URL + "issues?state=all&per_page=100", auth=HTTPBasicAuth('will555413', GIT_TOKEN)).json()

	print(contributors)

	Stat["WC"] = [0, 0]
	Stat["XW"] = [0, 0]
	Stat["XK"] = [0, 0]
	Stat["EC"] = [0, 0]
	Stat["NP"] = [0, 0]

	for contributor in contributors:
		if contributor["author"]["login"] == "will555413":
			Stat["WC"][0] = contributor["total"]
		elif contributor["author"]["login"] == "phoebe0607":
			Stat["XW"][0] = contributor["total"]
		elif contributor["author"]["login"] == "XiangyiKong":
			Stat["XK"][0] = contributor["total"]
		elif contributor["author"]["login"] == "ercardenas":
			Stat["EC"][0] = contributor["total"]
		elif contributor["author"]["login"] == "PresidentNick":
			Stat["NP"][0] = contributor["total"]

	for issue in issues:
		# print(issue)
		if issue["user"]["login"] == "will555413":
			Stat["WC"][1] += 1
		elif issue["user"]["login"] == "phoebe0607":
			Stat["XW"][1] += 1
		elif issue["user"]["login"] == "XiangyiKong":
			Stat["XK"][1] += 1
		elif issue["user"]["login"] == "ercardenas":
			Stat["EC"][1] += 1
		elif issue["user"]["login"] == "PresidentNick":
			Stat["NP"][1] += 1

	Stat["total"] = [0, 0]
	for key, val in Stat.items():
		if key == "total":
			continue
		Stat["total"][0] += int(val[0])
		Stat["total"][1] += val[1]

	return Stat

def capture_test():
	# out = subprocess.check_output(["python", "TestCollatz.py"], universal_newlines=True)
	call(["rm", "tests.tmp"])
	capture_text = check_output(["make", "tests.tmp"], universal_newlines=True)
	lst = re.split("\n", capture_text)
	lst.pop(0)
	lst.pop(0)
	lst.pop(0)
	out = ''
	for line in lst:
		out += line + '\n'
	return out


import io
import matplotlib.pyplot as plt
import numpy as np
import pymorphy2

morph = pymorphy2.MorphAnalyzer()
dictionary = {}
with io.open("estimations.txt", encoding='utf-8') as f:
    text = f.read()
    words = text.split("\n")
    for i in words:
        if len(i):
            word = i.split()
            dictionary[word[0]] = int(word[1])
positive_adjs = []
negative_adjs = []
frequency_positive = []
frequency_negative = []
with io.open("Frequency.txt",encoding='utf-8') as f:
    data = f.read().split('\n')
    words = []
    data_about_words = []
    for line in data:
        if len(positive_adjs) >= 5 and len(negative_adjs) >= 5:
            break
        components = line.split(":")
        if components:
            p = morph.parse(components[0])
            if p[0].tag.POS == 'ADJF':
                if dictionary[components[0]] > 0 and len(positive_adjs) <= 5:
                    positive_adjs.append(components)
                    frequency_positive.append(components[1].split()[0])
                if dictionary[components[0]] < 0 and len(negative_adjs) <= 5:
                    negative_adjs.append(components)
                    frequency_negative.append(components[1].split()[0])

with io.open("Adjectives.txt", 'w', encoding='utf-8')as f:
    f.write("Top-5 Positive:\n")
    for i in positive_adjs:
        f.write(i[0]+" "+ i[1]+"\n")
    f.write("Top-5 Negative:\n")
    for i in negative_adjs:
        f.write(i[0]+" "+i[1]+"\n")
# Graph
barWidth = 0.25
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
bars1 = [i for i in frequency_positive]
bars2 = [i for i in frequency_negative]
r1 = [i[0] for i in positive_adjs]
r2 = [i[0] for i in negative_adjs]
graph2 = ax1.bar(r2[::-1], bars2[::-1], width=barWidth, color = 'red')
graph1 = ax2.bar(r1[::-1], bars1[::-1], width=barWidth, color = 'green')
plt.show()


# Alec
# testingAverageUsingFunctions.py
# 9/16/19
# Version 1.12

# A program that asks the user to enter five test scores.
# The program should display a letter grade for each score
# and the average test score

def calc_average():
    total = 0
    for grade in range(1,6):
        print('Test number', grade, end='')
        testScore = int(input(': '))
        if testScore > 100 or testScore < 0:
            print('Invalid test score. Please enter a number greater than 0 ' \
            'and less than 101 for grade',grade, end='')
            testScore = int(input(': '))
            determine_grade(testScore)

        total+= testScore

    average = total / 5
    print('Final grade: ', end='')
    determine_grade(average)

def determine_grade(testScore):
    if testScore <= 100 and testScore >= 90:
        print('Your score of ', testScore, 'is an A!')

    elif testScore <= 89.9 and testScore >= 80:
        print('Your score of ', testScore, 'is a B.')

    elif testScore <= 79.9 and testScore >= 70:
        print('Your score of ', testScore, 'is a C')

    elif testScore <= 69.9 and testScore >= 70:
        print('Your score of ', testScore, 'is a D')

    else:
        print('Your score of', testScore, 'is an F')

calc_average()


import arrow
import decimal
import random
import uuid
from bloop import (Column, DateTime, Integer, UUID, String,
                   Map, TypedMap, Float, new_base, engine_for_profile)

# ================================================
# Model setup
# ================================================

engine = engine_for_profile("test-user-bloop")
Base = new_base()

Product = Map(**{
    'Name': String,
    'Rating': Float,
    'Updated': DateTime('US/Pacific'),
    'Description': Map(**{
        'Title': String,
        'Body': String
    }),
    'Sellers': TypedMap(Integer)
})

class Item(Base):
    id = Column(UUID, hash_key=True)
    data = Column(Product)
engine.bind(base=Base)

# ================================================
# Usage
# ================================================

item = Item(id=uuid.uuid4())
item.data = {
    'Name': 'item-name',
    'Rating': decimal.Decimal(str(random.random())),
    'Updated': arrow.now(),
    'Description': {
        'Title': 'item-title',
        'Body': 'item-body',
    },
    'Sellers': {}
}

for i in range(4):
    seller_name = 'seller-{}'.format(i)
    item.data['Sellers'][seller_name] = random.randint(0, 100)

engine.save(item)


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

# 常用事件集
# QUIT       用户按下关闭按钮 none
# ATIVEEVENT Pygame被激活或隐藏 gain,state
# KEYDOWN    键盘按下 unicode,key,mod
# KEYUP      键盘放开 key,mode
# MOUSEMOTION 鼠标移动 pos,rel,buttons
# MOUSEBUTTONDOWN 鼠标按下 pos,button
# MOUSEBUTTONUP   鼠标放开 pos,button
# JOYAXISMOTION   游戏手柄移动 joy axis value
# JOYBALLMOTION   joy,axis,value
# JOYHATMOTION    joy,axis,value
# JOYBUTTONDOWN   joy,button
# JOYBUTTONUP     joy,button
# VIDEORESIZE     pygame窗口缩放 size,w,h
# VIDEOEXPOSE     pygame窗口全屏?
# USEREVENT       触发一个用户事件  code

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
SCREEN_SIZE = (640,480)
screen = pygame.display.set_mode(SCREEN_SIZE,0,32)

font = pygame.font.SysFont("arial",16)
font_height = font.get_linesize()
event_text = []

while True:
    # 获得事件和名称
    event = pygame.event.wait()
    event_text.append(str(event))

    # 只保留一个屏幕的文字
    event_text = event_text[-SCREEN_SIZE[1]/font_height:]

    if event.type == QUIT:
        exit()

    screen.fill((255,255,255))

    y = SCREEN_SIZE[1] - font_height
    for text in reversed(event_text):
        screen.blit(font.render(text,True,(0,0,0)),(0,y))
        y -= font_height

    pygame.display.update()


class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        rows, cols, color = len(image), len(image[0]), image[sr][sc]
        if color == newColor:
            return image
        def dfs(row, col):
            if image[row][col] == color:
                image[row][col] = newColor
                if row - 1 >= 0:
                    dfs(row - 1, col)
                if row + 1 < rows:
                    dfs(row + 1, col)
                if col - 1 >= 0:
                    dfs(row, col - 1)
                if col + 1 < cols:
                    dfs(row, col + 1)
        dfs(sr, sc)
        return image


import atexit
import fcntl

import requests
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.mongodb import MongoDBJobStore
from pymongo import MongoClient

from config import MONGO_DB, MONGO_HOST, MONGO_PORT, FLASK_HOST, FLASK_PORT
from db.manager import db_manager

class Scheduler(object):
    mongo = MongoClient(host=MONGO_HOST, port=MONGO_PORT, connect=False)
    task_col = 'apscheduler_jobs'

    # scheduler jobstore
    jobstores = {
        'mongo': MongoDBJobStore(database=MONGO_DB,
                                 collection=task_col,
                                 client=mongo)
    }

    # scheduler instance
    scheduler = BackgroundScheduler(jobstores=jobstores)

    def execute_spider(self, id: str, params: str = None):
        print(f'executing spider {id}')
        print(f'params: {params}')
        self.scheduler.print_jobs(jobstore='mongo')
        query = {}
        if params is not None:
            query['params'] = params
        r = requests.get('http://%s:%s/api/spiders/%s/on_crawl' % (
            FLASK_HOST,
            FLASK_PORT,
            id
        ), query)

    def update(self):
        print('updating...')
        # remove all existing periodic jobs
        self.scheduler.remove_all_jobs()
        self.mongo[MONGO_DB][self.task_col].remove()

        periodical_tasks = db_manager.list('schedules', {})
        for task in periodical_tasks:
            cron = task.get('cron')
            cron_arr = cron.split(' ')
            second = cron_arr[0]
            minute = cron_arr[1]
            hour = cron_arr[2]
            day = cron_arr[3]
            month = cron_arr[4]
            day_of_week = cron_arr[5]
            self.scheduler.add_job(func=self.execute_spider,
                                   args=(str(task['spider_id']), task.get('params'),),
                                   trigger='cron',
                                   jobstore='mongo',
                                   day_of_week=day_of_week,
                                   month=month,
                                   day=day,
                                   hour=hour,
                                   minute=minute,
                                   second=second)
        self.scheduler.print_jobs(jobstore='mongo')
        print(f'state: {self.scheduler.state}')
        print(f'running: {self.scheduler.running}')

    def run(self):
        f = open("scheduler.lock", "wb")
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            self.update()
            self.scheduler.start()
        except:
            pass

        def unlock():
            fcntl.flock(f, fcntl.LOCK_UN)
            f.close()

        atexit.register(unlock)

scheduler = Scheduler()

if __name__ == '__main__':
    scheduler.run()


#!/usr/bin/env python
#
#  Copyright (c) 2015 - 2021, Intel Corporation
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions
#  are met:
#
#      * Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#
#      * Redistributions in binary form must reproduce the above copyright
#        notice, this list of conditions and the following disclaimer in
#        the documentation and/or other materials provided with the
#        distribution.
#
#      * Neither the name of Intel Corporation nor the names of its
#        contributors may be used to endorse or promote products derived
#        from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
#  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

from __future__ import absolute_import

import unittest
import json
import geopmpy.agent

class TestAgent(unittest.TestCase):
    def test_policy_names(self):
        for agent in geopmpy.agent.names():
            policy = geopmpy.agent.policy_names(agent)
            self.assertTrue(type(policy) is list)

    def test_sample_names(self):
        for agent in geopmpy.agent.names():
            sample = geopmpy.agent.sample_names(agent)
            self.assertTrue(type(sample) is list)

    def test_agent_names(self):
        names = geopmpy.agent.names()
        expected = set(['power_balancer', 'power_governor',
                        'frequency_map', 'monitor'])
        self.assertEqual(expected, set(names))

    def test_json(self):
        for agent in geopmpy.agent.names():
            policy_names = geopmpy.agent.policy_names(agent)
            exp_policy = {}
            for pp in policy_names:
                exp_policy[pp] = 'NAN'
            policy_val = [float('nan')] * len(policy_names)
            json_str = geopmpy.agent.policy_json(agent, policy_val)
            res_policy = json.loads(json_str)
            self.assertEqual(exp_policy, res_policy)

if __name__ == '__main__':
    unittest.main()


def ASE(indelFile, mpileupFile):
    D = {}
    inFile = open(indelFile)
    for line in inFile:
        fields = line.split('\t')
        ch = 'chr'+fields[3]
        start = int(fields[4])
        end = int(fields[5])
        k = ch + ':' + str(start)
        D[k] = [0, 0]
    inFile.close()

    inFile = open(mpileupFile)
    for line in inFile:
        line = line.strip()
        fields = line.split('\t')
        indel = int(fields[5])
        ref = int(fields[3])
        alt = int(fields[4])
        k = fields[0] + ':' + fields[1]
        if k in D and indel == 0:
            D[k][0] = ref
            D[k][1] = alt
    inFile.close()

    inFile = open(indelFile)
    ouFile = open(indelFile + '.ase', 'w')
    for line in inFile:
        line = line.rstrip()
        fields = line.split('\t')
        ch = 'chr'+fields[3]
        start = int(fields[4])
        end = int(fields[5])
        k = ch + ':' + str(start)
        ref = D[k][0]
        alt = D[k][1]
        ouFile.write(line+'\t'+str(ref) + '\t' + str(alt) + '\n')
    inFile.close()
    ouFile.close()

ASE('GS000008422-ASM.query.exonic_variant_function-HEK293-A01', 'E13R004a01_sorted.bam.mpileup.extracted')


import random2
import sys
from PyQt5 import QtWidgets, QtTest, QtGui, QtCore as QC

fontTText = QtGui.QFont("Saira", 24)
fontLText = QtGui.QFont("Semi", 10)
fontBtn = QtGui.QFont("Kanit", 10)
fontQlabel = QtGui.QFont("Kanit", 10)
fontWait = QtGui.QFont("Kanit", 20)

class mainWindow(QtWidgets.QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Çekiliş V1.0")
        self.setWindowIcon(QtGui.QIcon("images/giveaway.png"))
        self.setGeometry(510, 100, 950, 850)

        self.setFixedSize(950, 850)

        self.titleImage = QtWidgets.QLabel()
        self.titleImage.setPixmap(QtGui.QPixmap("images/giveaway.png"))

        self.titleText = QtWidgets.QLabel("Çekiliş V1.0")
        self.titleText.setFont(fontTText)

        self.textEdit = QtWidgets.QTextEdit()
        self.textEdit.setFont(fontLText)

        self.listTitle = QtWidgets.QLabel("Kişi Listesi")
        self.listTitle.setAlignment(QC.Qt.AlignCenter)
        self.listTitle.setFont(fontTText)

        self.textList = QtWidgets.QListWidget()
        self.textList.setFont(fontLText)

        self.textEditTitle = QtWidgets.QLabel("Kişi Giriş")
        self.textEditTitle.setFont(fontTText)
        self.textEditTitle.setAlignment(QC.Qt.AlignCenter)

        self.persono = QtWidgets.QSpinBox()
        self.persono.setValue(1)
        self.persono.valueChanged.connect(self.valueError)

        self.personumber = QtWidgets.QLabel("Kaç Kişi Çekilecek ?")
        self.personumber.setAlignment(QC.Qt.AlignCenter)
        self.personumber.setFont(fontQlabel)

        self.personTransferBtn = QtWidgets.QPushButton(
            QtGui.QIcon("images/user-add.svg"), "Kişi Ekle")
        self.personTransferBtn.clicked.connect(self.persontransfer)
        self.personTransferBtn.setFont(fontBtn)
        self.personAllClearBtn = QtWidgets.QPushButton(
            QtGui.QIcon("images/trash.svg"), "Tüm Kişileri Çıkar")
        self.personAllClearBtn.clicked.connect(self.personAllClear)
        self.personAllClearBtn.setFont(fontBtn)
        self.personRemoveBtn = QtWidgets.QPushButton(
            QtGui.QIcon("images/user-remove.svg"), "Kişi Çıkar")
        self.personRemoveBtn.clicked.connect(self.personremove)
        self.personRemoveBtn.setFont(fontBtn)
        self.start = QtWidgets.QPushButton(
            QtGui.QIcon("images/start.png"), "Başlat")
        self.start.clicked.connect(self.startGiveaway)
        self.start.setFont(fontBtn)
        self.wait = QtWidgets.QLabel("")
        self.wait.setFont(fontWait)
        self.wait.setAlignment(QC.Qt.AlignCenter)
        self.result = QtWidgets.QPushButton(
            QtGui.QIcon("images/giveaway.png"), "Sonuç")
        self.result.clicked.connect(self.openResult)
        self.result.setFont(fontBtn)
        self.result.setHidden(True)

        horizontal1 = QtWidgets.QHBoxLayout()
        vertical1 = QtWidgets.QVBoxLayout()

        horizontal2 = QtWidgets.QHBoxLayout()
        vertical2 = QtWidgets.QVBoxLayout()

        vertical3 = QtWidgets.QVBoxLayout()

        vertical1.addWidget(self.textEditTitle)
        vertical1.addWidget(self.textEdit)

        horizontal1.addLayout(vertical1)
        horizontal1.addStretch()
        horizontal1.addLayout(vertical3)
        horizontal1.addStretch()
        horizontal1.addLayout(horizontal2)

        vertical2.addWidget(self.listTitle)
        vertical2.addWidget(self.textList)

        horizontal2.addLayout(vertical2)

        vertical3.addStretch()
        vertical3.addWidget(self.personTransferBtn)
        vertical3.addWidget(self.personRemoveBtn)
        vertical3.addWidget(self.personAllClearBtn)
        vertical3.addStretch()
        vertical3.addWidget(self.personumber)
        vertical3.addWidget(self.persono)
        vertical3.addWidget(self.start)
        vertical3.addWidget(self.wait)
        vertical3.addWidget(self.result)
        vertical3.addStretch()

        window = QtWidgets.QWidget()
        window.setLayout(horizontal1)

        self.setCentralWidget(window)
        self.show()

    def valueError(self):
        if self.persono.value() <= 0:
            self.persono.setValue(1)
            QtWidgets.QMessageBox.critical(
                self, "Hata !", "Kişi sayısı 0 olamaz!", QtWidgets.QMessageBox.Ok)

    def persontransfer(self):
        persons = self.textEdit.toPlainText()
        personlist = persons.split()
        for person in personlist:
            self.textList.addItem(person)
        self.textEdit.clear()

    def personAllClear(self):
        self.textList.clear()

    def personremove(self):
        for item in self.textList.selectedItems():
            self.textList.takeItem(self.textList.row(item))

    def startGiveaway(self):
        try:
            persons = []
            for index in range(self.textList.count()):
                persons.append(self.textList.item(index).text())
            global winperson
            winperson = []
            while True:
                rndm = random2.choice(persons)
                winperson.append(rndm)
                if len(winperson) == int(self.persono.value()):
                    self.wait.setText("Kişi Çekiliyor...")
                    QtTest.QTest.qWait(4000)
                    self.wait.setText("Tebrikler! 🎊")
                    QtTest.QTest.qWait(2000)
                    self.wait.setHidden(True)
                    self.result.show()
                    break
                elif self.persono.value() == 0:
                    QtWidgets.QMessageBox.critical(
                        self, "Hata!", "Lütfen Bir Kişi Sayısı Belirtiniz!")
                    break
        except IndexError:
            QtWidgets.QMessageBox.critical(
                self, "Hata!", "Liste İçerisi Boş!\nLütfen liste içerisine kişi ekleyiniz!")

    def openResult(self):
        self.resultOpen = resulT()
        self.resultOpen.show()

class resulT(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Kazananlar!")
        self.setGeometry(750, 150, 500, 500)
        self.setWindowIcon(QtGui.QIcon("images/giveaway.png"))

        fontTitle = QtGui.QFont("Aldrich", 28)
        fontText = QtGui.QFont("Cairo Semi-bold", 10)

        winlist = QtWidgets.QListWidget()
        winlist.setFont(fontText)
        winlist.setItemAlignment(QC.Qt.AlignCenter)

        for winper in winperson:
            winlist.addItem(winper)

        sonucTitle = QtWidgets.QLabel("🎉 Kazananlar 🎉")
        sonucTitle.setFont(fontTitle)
        sonucTitle.setAlignment(QC.Qt.AlignCenter)

        horizontal = QtWidgets.QHBoxLayout()
        vertical = QtWidgets.QVBoxLayout()

        horizontal.addStretch()
        horizontal.addWidget(winlist)
        horizontal.addStretch()

        vertical.addStretch()
        vertical.addWidget(sonucTitle)
        vertical.addStretch()
        vertical.addLayout(horizontal)
        vertical.addStretch()

        self.setLayout(vertical)
        self.show()

stylesheet = """
 QPushButton{
   border: 4px solid #E4E4E4;
   border-radius: 10px;
   width: 180px;
   height: 30px;
   color: #E4E4E4;
 }
 QPushButton:hover{
     color: black;
 }
 QTextEdit{
     color: white;
     font-size: 14px;
     border: 6px solid #E4E4E4;
     border-radius: 8px;
 }
 QListWidget{
     color: white;
     font-size: 14px;
     border: 6px solid #E4E4E4;
     border-radius: 8px;
 }
 QSpinBox{
     border: 4px solid #E4E4E4;
     border-radius: 6px;
     color: #E4E4E4;
 }
 QWidget{
     color: #E4E4E4;
     background-color: #7A7A7A;
 }
"""

app = QtWidgets.QApplication(sys.argv)
app.setStyleSheet(stylesheet)
main = mainWindow()
sys.exit(app.exec_())


# coding=utf-8
from django.conf import settings
from django.db import models
from participants.models import Library

BANNER_PLACES = (
    ('left', u'Слева'),
    ('bottom', u'Под профилем библиотеки')
)

class Banner(models.Model):
    libraries = models.ManyToManyField(
        Library,
        blank=True,
        verbose_name=u'Организации, на сайтах которых будет показан банер'
    )
    library_creator = models.ForeignKey(Library, related_name='library_creator')
    in_descendants = models.BooleanField(
        default=False,
        verbose_name=u'Банер отображается на сайтах дочерних организаций'
    )
    lang = models.CharField(
        verbose_name=u"Язык",
        db_index=True,
        max_length=2,
        choices=settings.LANGUAGES,
        help_text=u'Язык системы, при котором будет отображен банер'
    )
    place = models.CharField(
        max_length=64,
        choices=BANNER_PLACES,
        default=BANNER_PLACES[0][0],
        verbose_name=u'Место размещения'
    )
    image = models.ImageField(
        upload_to=u'participant_banners/%Y/%m/%d',
        verbose_name=u'Картинка для банера', help_text=u'Загружайте файлы JPG и PNG с латинскими названиями'
    )
    title = models.CharField(
        max_length=500,
        blank=True,
        verbose_name=u'Название'
    )
    description = models.TextField(
        max_length=1000,
        blank=True,
        verbose_name=u'Описание'
    )
    url = models.CharField(
        max_length=500,
        verbose_name=u'Ссылка для клика по банеру',
        blank=True
    )
    target_blank = models.BooleanField(
        default=False,
        verbose_name=u'Открывать ссылку в новой вкладке'
    )
    show_period = models.IntegerField(
        default=5,
        help_text=u'Период показа в секундах'
    )
    global_banner = models.BooleanField(
        default=False,
        db_index=True,
        verbose_name=u'Глобальный банер',
        help_text=u'Будет отображен на всех сайтах без исключения'
    )
    active = models.BooleanField(
        default=True,
        db_index=True,
        verbose_name=u'Активный'
    )
    order = models.IntegerField(
        default=0,
        verbose_name=u'Порядок вывода',
        db_index=True
    )
    start_date = models.DateTimeField(verbose_name=u'Дата начала показа', db_index=True)
    end_date = models.DateTimeField(verbose_name=u'Дата окончания показа', db_index=True)

    class Meta:
        ordering = ['-order', '-id']
        verbose_name = u'Банер'
        verbose_name_plural = u'Банеры'
        permissions = (
            ('bind_to_descendants', u'Bind to descendants organisations'),
        )


#!/usr/bin/env python
# coding=utf-8
###########################################################
#  proj_1.py
#  Ryan Vollmer - CS 325
#  Various solutions to max subarray problem.
###########################################################
import math

def max_enum(arr):
    """ Loops through pairs of indicies
        keeping the best sum so far.
        @param  {array} arr     - array to find max sum of
        @return {int}           - sum of max sum
        @return {array}         - subarray of max sum
    """
    arr_len = len(arr)
    max_sum = 0
    max_arr = []
    for i in range(arr_len):
        for j in range(i, arr_len):
            cur_arr = []
            cur_sum = 0
            for k in range(i, j + 1):
                cur_sum = cur_sum + arr[k]
                cur_arr.append(arr[k])
            if cur_sum > max_sum:
                max_sum = cur_sum
                max_arr = cur_arr[:]
    return max_sum, max_arr

def max_memoize(arr):
    """ Loops through pairs of indicies
        keeping the best sum so far.
        Uses memoization to keep track of past values.
        @param  {array} arr     - array to find max sum of
        @return {int}           - sum of max sum
        @return {array}         - subarray of max sum
    """
    arr_len = len(arr)
    max_sum = 0
    max_arr = []
    for i in range(arr_len):
        cur_sum = 0
        cur_arr = []
        for j in range(i, arr_len):
            cur_sum = cur_sum + arr[j]
            cur_arr.append(arr[j])
            if cur_sum > max_sum:
                max_sum = cur_sum
                max_arr = cur_arr[:]
    return max_sum, max_arr

def max_div_conq(arr):
    """ Uses divide and conquer to find maximum subarray
        @param {array} arr      - array to find max sum of
        @return {int}           - sum of max sum
        @return {array}         - subarray of max sum
    """
    if not len(arr):
        return 0, []
    s, l, h = _max_div_conq(arr, 0, len(arr) - 1)
    return s, arr[l:h + 1]

def _max_div_conq(arr, left, right):
    """ Helper function for max_div_conq
        Recursively finds largest max subarray.
        @param {array} arr      - array to find max sum of
        @return {int}           - sum of max sum
        @return {int}           - left index of max array
        @return {int}           - right index of max array
    """
    # base case, single element
    if left == right:
        return arr[left], left, right
    mid = int(math.floor((left + right) / 2))
    # get max of all subarrays
    max_left, low_left, left_high = _max_div_conq(arr, left, mid)
    max_right, low_right, high_right = _max_div_conq(arr, mid + 1, right)
    # find cross section max
    mid_low = mid
    mid_high = mid + 1
    max_mid_left = arr[mid_low]
    max_mid_right = arr[mid_high]
    cur = 0
    for i in range(mid, left - 1, -1):
        cur = cur + arr[i]
        if cur > max_mid_left:
            max_mid_left = cur
            mid_low = i
    cur = 0
    for i in range(mid + 1, right + 1):
        cur = cur + arr[i]
        if cur > max_mid_right:
            max_mid_right = cur
            mid_high = i
    # max in cross section
    if max_mid_left + max_mid_right > max(max_left, max_right):
        return max_mid_left + max_mid_right, mid_low, mid_high
    # max in left section
    if max_left > max_right:
        return max_left, low_left, left_high
    return max_right, low_right, high_right

def max_linear(arr):
    """ Finds max subarray in linear time based off
        the fact a max subarray A[1..j] is eiher a
        max subarray of A[1..j] or a subarray of A[i..j+1]
        for some 1 <= i <= j.
        @param {array} arr      - array to find max sum of
        @return {int}           - sum of max sum
        @return {array}         - subarray of max sum
    """
    max_sum = max_cur = arr[0]
    low = high = tmp = 0
    for i in range(1, len(arr)):
        if arr[i] > max_cur + arr[i]:
            max_cur = arr[i]
            tmp = i
        else:
            max_cur = max_cur + arr[i]
        if max_cur > max_sum:
            max_sum = max_cur
            low = tmp
            high = i
    return max_sum, arr[low:high + 1]

def print_result(func, arr):
    """ Print test case for given function
        @param {func} func      - function to run test on
        @param {array} arr      - array to use in test
    """
    print(arr)
    s, a = func(arr)
    print(a)
    print(s)
    print('\n')

def main():
    # arr = [31, -41, 59, 26, -53, 58, -97, -93, -23, 84]
    with open('MSS_TestProblems.txt') as f:
        for line in f:
            arr = line.split(' ')
            if arr[-1] == '\n':
                del arr[-1]
            arr = [int(x) for x in arr]
            print_result(max_enum, arr)
            print_result(max_memoize, arr)
            print_result(max_div_conq, arr)
            print_result(max_linear, arr)

if __name__ == '__main__':
    main()


import pandas as pd

#criar arquivo txt baseado na planilha de indice
def gerarIndiceTXT(diretorio, frase):
    f = open(diretorio,"a+")
    f.write(frase)
    f.close()

def salvarPlanilhaCSV(df,file_name):
    df.to_csv(file_name, sep='\t', encoding='utf-8')

def gerarDictIndice(dir_csv_indice):
    indice_csv = pd.read_csv(dir_csv_indice, delimiter=",")
    dict_indice = indice_csv.set_index('chave')['valor'].to_dict()
    return dict_indice

def carregarCsvEmDataframe(dir_csv):
    return pd.read_csv(dir_csv, delimiter=",")

def decodificarColunasDeDataframe(nomeArquivo, dataframe, dict_indice):
    c = []
    for column in dataframe.columns:
        i = nomeArquivo + "_" + column
        if(i in dict_indice):
            c.append(dict_indice[i])
        else:
            c.append(column)
    return c

def removerColunasDoDataframe(dataframe, cols):
    return dataframe.drop(columns=cols)

def toLowerCase(strings):
    x = []
    for s in strings:
        x.append(s.lower())

    return x

def decodificarValoresDaColuna(df, colunas, indices):
    for coluna in colunas:
        idx = [i for i in indices.keys() if coluna in i]
        if(idx):
            values = list(map(int,[i.split("_")[-1] for i in idx]))
            dic = dict(zip(values,[indices[i] for i in idx]))

            df[coluna] = df[coluna].map(dic)

    return df

#carregando indices
idx = gerarDictIndice("../csv/indice.csv")
#print(idx)
#carregando csv de  teste
df = carregarCsvEmDataframe("../csv/Basico_MG.csv")
#colocando caracteres das colunas para minusculo
df.columns = toLowerCase(df.columns)

#colunas removidas
del_cols = ['cod_uf', 'nome_da_uf', 'cod_meso', 'nome_da_meso',
       'cod_micro', 'nome_da_micro', 'cod_rm', 'nome_da_rm', 'cod_municipio',
       'nome_do_municipio', 'cod_distrito',
       'cod_subdistrito', 'nome_do_subdistrito','nome_do_distrito', 'cod_bairro',
       'nome_do_bairro', 'var01', 'var02',
       'var03', 'var04', 'var05', 'var06', 'var07', 'var08', 'var09', 'var10',
       'var11', 'var12', 'var13']
#removendo colunas
df = removerColunasDoDataframe(df,del_cols)

#decodificando colunas
df.columns = decodificarColunasDeDataframe("basico", df, idx)

#decodificando valores das colunas que restaram
df = decodificarValoresDaColuna(df, df.columns, idx)
print(df)


from shutil import copyfile
import numpy as np
import os
from scipy.optimize import curve_fit
from scipy.optimize import leastsq
import pickle
import matplotlib.pyplot as plt
from matplotlib import rcParams
import sys

def get_populations(ics, datadir, state_from, state_to):
    ''' Get population data for transfer events from state_from to state_to. '''

    print('Loading excited state trajectories and extracting population information.')
    absolute_transfer = {}
    relative_transfer = {}
    energy_gaps = {}

    for ic in ics:
        data = pickle.load(open(datadir+('/%04d.pickle' %ic), 'rb'))
        total_ic_transfer = 0
        for tbf_key in data.keys():
            tbf = data[tbf_key]
            tbf_state = tbf['spawn_info']['tbf_state']
            if tbf_state==state_to:
                parent_state = tbf['spawn_info']['parent_state']
                if parent_state==state_from:

                    # Get the population of the parent TBF at the time of spawning
                    parent_key = '%04d-%04d' %(ic, tbf['spawn_info']['parent_id'])
                    parent_tbf = data[parent_key]
                    spawn_time = tbf['spawn_info']['spawn_time']
                    parent_tbf_times = parent_tbf['time_steps']
                    spawn_ind_parent = np.argmin(np.abs(parent_tbf_times - spawn_time))
                    parent_pop = parent_tbf['populations'][spawn_ind_parent]

                    # Get the population of the current TBF after population exchange has stabilized
                    tbf_pop = tbf['populations']
                    if len(tbf_pop) > 20:
                        pop_transferred = tbf_pop[20]
                        upper = tbf['energies']['s%d' %state_from][:20]
                        lower = tbf['energies']['s%d' %state_to][:20]
                        min_gap = np.min(np.abs(upper-lower)) * 27.21138602
                    else:
                        pop_transferred = tbf_pop[-1]
                        upper = tbf['energies']['s%d' %state_from][:-1]
                        lower = tbf['energies']['s%d' %state_to][:-1]
                        min_gap = np.min(np.abs(upper-lower)) * 27.21138602

                    if parent_pop > pop_transferred:
                        transfer_efficiency = pop_transferred / parent_pop
                        total_ic_transfer += pop_transferred
                        absolute_transfer[tbf_key] = pop_transferred
                        relative_transfer[tbf_key] = transfer_efficiency
                        energy_gaps[tbf_key] = min_gap

        print('Total transferred: ', total_ic_transfer)
        print()

    return absolute_transfer, relative_transfer, energy_gaps

def plot_transfer(absolute_transfer, relative_transfer, energy_gaps, bin_spacing=0.05):

    tbf_keys = [ x for x in absolute_transfer.keys() ]
    all_populations = [ absolute_transfer[key] for key in tbf_keys ]
    all_efficiencies = [ relative_transfer[key] for key in tbf_keys ]
    all_energy_gaps = [ energy_gaps[key] for key in tbf_keys ]

    nbins = int( np.ceil(np.max(all_energy_gaps) / bin_spacing) )

    # Compute fractional population transferred from absolute transfer
    abs_bins = np.zeros(nbins)
    total_population_transfer = np.sum(all_populations)
    for pop, gap in zip(all_populations, all_energy_gaps):
        abs_bins[ int(np.floor(gap/bin_spacing)) ] += pop
    abs_bins = abs_bins / total_population_transfer

    # Compute average efficiency for each gap
    rel_bins = {}
    for b in range(nbins):
        rel_bins['%d' %b] = []
    for pop, gap in zip(all_efficiencies, all_energy_gaps):
        rel_bins['%d' %(int(np.floor(gap/bin_spacing)))].append(pop)
    rel_bins2 = np.zeros(nbins)
    for b in range(nbins):
        nevents = len(rel_bins['%d' %b])
        rel_bins2[b] = np.sum(rel_bins['%d' %b]) / nevents
    # If fractional transfer is small in a bin, its efficiency is more or less an artifact,
    # so zero it out. Threshold set at 0.01.
    rel_bins = [ rel_bins2[b] if abs_bins[b]>0.01 else 0 for b in range(nbins) ]

    rcParams.update({'figure.autolayout': True})
    fig, ax1 = plt.subplots(figsize=(6,5))
    labelsize = 14
    ticksize = 12
    plt.rc('xtick',labelsize=ticksize)
    plt.rc('ytick',labelsize=ticksize)

    width = 0.3 * bin_spacing
    x_labels = np.arange(nbins)*bin_spacing
    abs_bars = ax1.bar(x_labels - width/2, abs_bins, width, label='Absolute Population Transfer', color='darkslateblue')
    ax1.set_ylabel('Fractional Population Transferred', fontsize=labelsize, color='darkslateblue')
    ax1.set_xlabel('Minimum Energy Gap [eV]', fontsize=labelsize, color='black')
    ax1.set_xticks([ bin_spacing*x for x in range(0, nbins) ])
    ax1.tick_params('y', colors='darkslateblue', labelsize=ticksize)
    ax1.tick_params('x', colors='black', labelsize=ticksize)

    ax2 = ax1.twinx()
    rel_bars = ax2.bar(x_labels + width/2, rel_bins, width, label='Population Transfer Efficiency', color='mediumvioletred')
    ax2.set_ylabel('Relative Population Transferred', fontsize=labelsize, color='mediumvioletred', rotation=270, labelpad=20)
    ax2.tick_params('y', colors='mediumvioletred', labelsize=ticksize)

    if not os.path.isdir('./figures/'):
        os.mkdir('./figures/')
    plt.savefig('./figures/population_transfer.pdf', dpi=300)
    plt.close()

'''
Specify the time grid and ICs to use.
Can use a coarser time grid than is used here and it shouldn't change the result.
'''
datadir = '../../1_collect_data/data/'
fmsinfo = pickle.load(open(datadir+'/fmsinfo.pickle', 'rb'))
ics = fmsinfo['ics']
nstates = fmsinfo['nstates']
absolute_transfer, relative_transfer, energy_gaps = get_populations(ics, datadir, state_from=1, state_to=0)
plot_transfer(absolute_transfer, relative_transfer, energy_gaps)


import sqlite3
from parse_class_1 import *

# Создание таблицы
def create_tables_in_db():
    conn = sqlite3.connect("olympiad.db")
    cursor = conn.cursor()
    cursor.execute("""CREATE TABLE Olympiad
                      (olymp_id int,
                      name text,
                      description text,
                      status text,
                      class_start int,
                      class_stop int,
                      id_sub int)
                    """)
    cursor.execute("""CREATE TABLE Date
                      (olymp_id int,
                      date_start text,
                      date_stop text,
                      name text)
                    """)
    cursor.execute("""CREATE TABLE User
                      (user_id int,
                      email text)
                      """)
    cursor.execute("""CREATE TABLE User_Subject
                      (user_id int,
                      subject text)
                      """)
    cursor.execute("""CREATE TABLE User_Class
                      (user_id int,
                      class int)
                      """)
    cursor.close()
def inserting(k):
    conn = sqlite3.connect("olympiad.db")
    cursor = conn.cursor()
    a = parse_sub(k)
    ##@%В52а#@н$я л$о%@х
    print(a)
    for i in range(len(a)):
        ##ID
        execute1 = '''insert into Olympiad(olymp_id,name,description,status,class_start,class_stop,id_sub) values(?,?,?,?,?,?,?)'''
        cursor.execute(execute1, (
        a[i].id,
        a[i].name,
        a[i].desc,
        a[i].status,
        a[i].class_start,
        a[i].class_stop,
        a[i].id_sub
        ))
        if len(a[i].date) != 0:
            for k in range(len(a[i].date)):
                execute2 = '''insert into Date(olymp_id,date_start,date_stop,name) values(?,?,?,?)'''
                cursor.execute(execute2, (
                a[i].id,
                a[i].date[k].get('start'),
                a[i].date[k].get('stop'),
                a[i].date[k].get('name')
                ))
        ##НАДО!
        #a = parse_sub(k)
    conn.commit()
    ##results
    ##ID
    """cursor.execute("SELECT olymp_id FROM Olympiad ORDER BY olymp_id")
    results = cursor.fetchall()
    print(results)
    ##name
    cursor.execute("SELECT name FROM Olympiad ORDER BY name")
    results = cursor.fetchall()
    print(results)
    ##description
    cursor.execute("SELECT description FROM Olympiad ORDER BY description")
    results = cursor.fetchall()
    print(results)
    ##status
    cursor.execute("SELECT status FROM Olympiad ORDER BY status")
    results = cursor.fetchall()
    print(results)
    ##class_start
    cursor.execute("SELECT class_start FROM Olympiad ORDER BY class_start")
    results = cursor.fetchall()
    print(results)
    ##class_stop
    cursor.execute("SELECT class_stop FROM Olympiad ORDER BY class_stop")
    results = cursor.fetchall()
    print(results)"""
    ##date_start
    #cursor.execute("SELECT date_start FROM Date ORDER BY date_start")
    #results = cursor.fetchall()
    #print(results)
    ##date_stop
    #cursor.execute("SELECT date_stop FROM Date ORDER BY date_stop")
    #results = cursor.fetchall()
    #print(results)
"""create_tables_in_db()
i = 1
call = is_sub_exist(i)
while call != False:
    inserting(i)
    i += 1
    call = is_sub_exist(i)"""

def reading():
    conn = sqlite3.connect("olympiad.db")
    cursor = conn.cursor()
    cursor.execute("SELECT olymp_id FROM Olympiad ORDER BY olymp_id")
    id = cursor.fetchall()
    print(id)
    ##name
    cursor.execute("SELECT name FROM Olympiad ORDER BY name")
    name = cursor.fetchall()
    print(name)
    ##description
    cursor.execute("SELECT description FROM Olympiad ORDER BY description")
    description = cursor.fetchall()
    print(description)
    ##status
    cursor.execute("SELECT status FROM Olympiad ORDER BY status")
    status = cursor.fetchall()
    print(status)
    ##class_start
    cursor.execute("SELECT class_start FROM Olympiad ORDER BY class_start")
    class_start = cursor.fetchall()
    print(class_start)
    ##class_stop
    cursor.execute("SELECT class_stop FROM Olympiad ORDER BY class_stop")
    class_stop = cursor.fetchall()
    print(class_stop)

reading()


# encoding=utf-8

'''python3'''
from PIL import Image
import numpy as np
import skimage.io as io
import tensorflow as tf
import glob
import os
import re
import sys
import cv2
import codecs

'''label.txt 格式     ：      1.png '地方涅米完'    '''

# Iuput image should be in (150*600*3), 4 views/png.
# charset_file is original fsns charset_size=134.txt file.

# image_input_filename = '/media/ryk/ML_disk/Project/FSNS_license/attention_ocr/python/datasets/data/fsns/resized/*.png'
# tfrecords_output_filename = 'validation_6'
# charset_file = '/media/ryk/ML_disk/Project/FSNS_license/attention_ocr/python/datasets/data/fsns/charset_size=134.txt'

image_input_filename = '/Users/swdcaiyun/Desktop/for_google_ocr/dst/*.png'
tfrecords_output_filename = 'validation_6'

charset_file = '/Users/swdcaiyun/Desktop/for_google_ocr/charset_size=134.txt'

label_path='/Users/swdcaiyun/Desktop/for_google_ocr/dst/label.txt'

def _bytes_feature(value):
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

def _int64_feature(value):
    return tf.train.Feature(int64_list=tf.train.Int64List(value=value))

def encode_utf8_string(text, length, charset, null_char_id=133):

    values=charset.keys()  #int 序号
    keys=charset.values()   #char

    keys = list(keys)
    values=list(values)

    char_ids_padded = []
    char_ids_unpadded = []

    pad_null_for_chars = [null_char_id for x in range(37-length)]

    for i in range(length):
        char_ids_padded.append(values[keys.index(list(text)[i])])

    char_ids_unpadded = list(char_ids_padded)

    char_ids_padded.extend(pad_null_for_chars)

    print('------',char_ids_padded)

    return char_ids_padded, char_ids_unpadded

# For debugging/checking only.
def read_charset(filename, null_character=u'\u2591'):
    """Reads a charset definition from a tab separated text file.

    charset file has to have format compatible with the FSNS dataset.

    Args:
      filename: a path to the charset file.
      null_character: a unicode character used to replace '<null>' character. the
        default value is a light shade block.

    Returns:
      a dictionary with keys equal to character codes and values - unicode
      characters.
    """
    pattern = re.compile(r'(\d+)\t(.+)')
    charset = {}
    with tf.gfile.GFile(filename) as f:
        for i, line in enumerate(f):
            m = pattern.match(line)
            if m is None:
                logging.warning('incorrect charset file. line #%d: %s', i, line)
                continue
            code = int(m.group(1))
            # char = m.group(2).decode('utf-8') #python2 对
            char = m.group(2)
            if char == '<nul>':
                char = null_character
            charset[code] = char
    return charset

writer = tf.python_io.TFRecordWriter(tfrecords_output_filename)
num_of_views = 4

# Read charset_size=134.txt as charset just for debugging.
charset = read_charset(charset_file)

#读取label文件  image \t label

label={}
with codecs.open(label_path,'r','utf-8') as f_label:
    for j in f_label:
        content_list=j.strip().split('\t')
        #image
        label_key=content_list[0]
        #label
        label_value=content_list[1]
        label[label_key]=label_value

print(label)

for file in glob.iglob(image_input_filename):
    # File name is text or ground truth. Length is either 7 or 8.
    # Image size: [H x W x 3] == [150 X 600 X 3] (4 views/image)

    head, tail = os.path.split(file)

    text = label[tail]
    print (text)
    length = len(text)
    print(length)
    img = np.array(Image.open(file))
    char_ids_padded, char_ids_unpadded = encode_utf8_string(text, length, charset, null_char_id=133)
    # print char_ids_padded, char_ids_unpadded

    _, pngVector = cv2.imencode('.png', img)
    imgStr = pngVector.tostring()

    text=b'aaaaaaaa'
    example = tf.train.Example(features=tf.train.Features(feature={
        'image/encoded': _bytes_feature([imgStr]),
        'image/format': _bytes_feature([b'PNG']),
        'image/width': _int64_feature([img.shape[1]]),
        'image/orig_width': _int64_feature([img.shape[1] // num_of_views]),
        'image/class': _int64_feature(char_ids_padded),
        'image/unpadded_class': _int64_feature(char_ids_unpadded),
        'image/text': _bytes_feature([text])

    }))

    writer.write(example.SerializeToString())

writer.close()

# for file in glob.iglob(image_input_filename):
#     # File name is text or ground truth. Length is either 7 or 8.
#     # Image size: [H x W x 3] == [150 X 600 X 3] (4 views/image)
#
#     head, tail = os.path.split(file)
#     filename = tail.split('.', 1)
#
#     text = filename[0]
#     length = len(text)
#     img = np.array(Image.open(file))
#     char_ids_padded, char_ids_unpadded = encode_utf8_string(text, length, charset, null_char_id=133)
#     # print char_ids_padded, char_ids_unpadded
#
#     _, pngVector = cv2.imencode('.png', img)
#     imgStr = pngVector.tostring()
#
#     example = tf.train.Example(features=tf.train.Features(feature={
#         'image/encoded': _bytes_feature([imgStr]),
#         'image/format': _bytes_feature(['PNG']),
#         'image/width': _int64_feature([img.shape[1]]),
#         'image/orig_width': _int64_feature([img.shape[1] / num_of_views]),
#         'image/class': _int64_feature(char_ids_padded),
#         'image/unpadded_class': _int64_feature(char_ids_unpadded),
#         'image/text': _bytes_feature([text])}))
#
#     writer.write(example.SerializeToString())
#
# writer.close()


import time
import gym
import gym_apl
#import numpy as np

from baselines import deepq

def callback(lcl, _glb):
    # stop training if reward exceeds 499
    #is_solved = lcl['t'] > 100 and sum(lcl['episode_rewards'][-101:-1]) / 100 >= 1.1
    #print(sum(lcl['episode_rewards'][-101:-1]) / 100)
    #return is_solved
    return False

def main():
    ##np.seterr(all='raise')
    env = gym.make("apl-v0")
    #act = deepq.learn(
        #env,
        #network='mlp',
        #lr=1e-3,
        #checkpoint_freq=None,
        #total_timesteps=int(1e5),
        #buffer_size=50000,
        #exploration_fraction=0.1,
        #exploration_final_eps=0.02,
        #print_freq=10,
        #load_path="./models/apl-v0-dqn-20181003-151750",
        #callback=callback
    #)
    #timestr = time.strftime("%Y%m%d-%H%M%S")
    #act.save("./models/apl-v0-dqn-" + timestr)
    act = deepq.load_act("./models/apl-v0-dqn-20181003-152611.pickle")
    while True:
        obs, done = env.reset(), False
        episode_rew = 0
        while not done:
            env.render()
            obs, rew, done, _ = env.step(act(obs[None])[0])
            episode_rew += rew
        print("Episode reward", episode_rew)

if __name__ == '__main__':
    main()