import sys
sys.path.append('/netapp/home/nick.polizzi/combs/src/')
import combs
import prody as pr
import pickle
import os
import gzip
# import collections
import networkx as nx
# import time

pdb_path = '/netapp/home/nick.polizzi/combs/src/runs/glutamine_binding_protein/1wdn_noligandH.pdb'
sample = combs.Sample()
sample.poi = pr.parsePDB(pdb_path)
# sample.bs_residues = list(zip([70, 75, 119, 118, 50, 67, 10, 115, 156, 13, 68, 157, 185],
#                               ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A']))
sample.bs_residues = list(zip([10, 12, 13, 16, 17, 50, 53, 67, 68, 69, 70, 72, 75,
                               88, 115, 117, 118, 119, 120, 122, 139, 156, 157, 160,
                               183, 185],
                              ['A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
                               'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',
                               'A', 'A']))
indir = '/netapp/home/nick.polizzi/combs/src/runs/glutamine_binding_protein/20170915/'
sample.set_rois()
sample.set_rois_phipsi()
sample.set_poi_clash_coords()
sample.set_roi_bb_coords()

relvdm_carboxylate = combs.Rel_Vandermer('carboxylate')
relvdm_carboxylate.rel_vdm_path = '/netapp/home/nick.polizzi/combs/results/carboxylate/rel_vdms/20170830/'
relvdm_carboxylate.load_rel_vdms_pickle(sample)
relvdm_carboxylate.set_rel_vdm_bb_coords()
relvdm_carboxylate.set_rois_rot_trans(sample)
relvdm_carboxylate.set_rel_vdm_tags(sample)
print('moving carboxylate vdMs')
relvdm_carboxylate.move_rel_vdms(sample)
print('removing clashing carboxylate vdMs')
relvdm_carboxylate.remove_clash(sample)
relvdm_carboxylate.reshape_ifgs()
print('finding carboxylate hotspots')
relvdm_carboxylate.find_hotspots(rmsd_cutoff=0.7)
relvdm_carboxylate.rel_vdms_pickle = None
relvdm_carboxylate.rel_vdm_ifg_coords = None
relvdm_carboxylate.rel_vdm_bb_coords = None
relvdm_carboxylate.rel_vdm_sc_coords = None
relvdm_carboxylate.rel_vdm_tags = None
relvdm_carboxylate.rel_vdm_resnames = None
relvdm_carboxylate._ifgs = None
relvdm_carboxylate._resn = None
relvdm_carboxylate._type = None
relvdm_carboxylate._vdm_tags = None
relvdm_carboxylate._indices = None
relvdm_carboxylate.ifg_dict = {'GLU': 'CG CD OE1 OE2'}

relvdm_carboxamide = combs.Rel_Vandermer('carboxamide')
relvdm_carboxamide.rel_vdm_path = '/netapp/home/nick.polizzi/combs/results/carboxamide/rel_vdms/20170830/'
relvdm_carboxamide.load_rel_vdms_pickle(sample)
relvdm_carboxamide.set_rel_vdm_bb_coords()
relvdm_carboxamide.set_rois_rot_trans(sample)
relvdm_carboxamide.set_rel_vdm_tags(sample)
print('moving carboxamide vdMs')
relvdm_carboxamide.move_rel_vdms(sample)
print('removing clashing carboxamide vdMs')
relvdm_carboxamide.remove_clash(sample)
relvdm_carboxamide.reshape_ifgs()
print('finding carboxamide hotspots')
relvdm_carboxamide.find_hotspots(rmsd_cutoff=0.7)
relvdm_carboxamide.rel_vdms_pickle = None
relvdm_carboxamide.rel_vdm_ifg_coords = None
relvdm_carboxamide.rel_vdm_bb_coords = None
relvdm_carboxamide.rel_vdm_sc_coords = None
relvdm_carboxamide.rel_vdm_tags = None
relvdm_carboxamide.rel_vdm_resnames = None
relvdm_carboxamide._ifgs = None
relvdm_carboxamide._resn = None
relvdm_carboxamide._type = None
relvdm_carboxamide._vdm_tags = None
relvdm_carboxamide._indices = None
relvdm_carboxamide.ifg_dict = {'GLN': 'CG CD OE1 NE2'}

relvdm_amino = combs.Rel_Vandermer('amino')
relvdm_amino.rel_vdm_path = '/netapp/home/nick.polizzi/combs/results/amino/rel_vdms/20170927/'
relvdm_amino.load_rel_vdms_pickle(sample)
relvdm_amino.set_rel_vdm_bb_coords()
relvdm_amino.set_rois_rot_trans(sample)
relvdm_amino.set_rel_vdm_tags(sample)
print('moving amino vdMs')
relvdm_amino.move_rel_vdms(sample)
print('removing clashing amino vdMs')
relvdm_amino.remove_clash(sample)
relvdm_amino.reshape_ifgs()
print('finding amino hotspots')
relvdm_amino.find_hotspots(rmsd_cutoff=0.7)
relvdm_amino.rel_vdms_pickle = None
relvdm_amino.rel_vdm_ifg_coords = None
relvdm_amino.rel_vdm_bb_coords = None
relvdm_amino.rel_vdm_sc_coords = None
relvdm_amino.rel_vdm_tags = None
relvdm_amino.rel_vdm_resnames = None
relvdm_amino._ifgs = None
relvdm_amino._resn = None
relvdm_amino._type = None
relvdm_amino._vdm_tags = None
relvdm_amino._indices = None
relvdm_amino.ifg_dict = {'LYS': 'CE NZ'}

relvdm_carboxamide.hotspot_subgraphs = list(
    sorted((comp for comp in nx.connected_component_subgraphs(relvdm_carboxamide.hotspot_graph) if len(comp) > 2),
           key=len, reverse=True))

relvdm_carboxylate.hotspot_subgraphs = list(
    sorted((comp for comp in nx.connected_component_subgraphs(relvdm_carboxylate.hotspot_graph) if len(comp) > 2),
           key=len, reverse=True))

relvdm_amino.hotspot_subgraphs = list(
    sorted((comp for comp in nx.connected_component_subgraphs(relvdm_amino.hotspot_graph) if len(comp) > 2),
           key=len, reverse=True))

outdir = '/netapp/home/nick.polizzi/combs/results/glutamine_binding_protein/20170927/output/'
try:
    os.makedirs(outdir)
except:
    pass

confs_indir = '/netapp/home/nick.polizzi/combs/src/runs/glutamine_binding_protein/confs/'
sample.ligand_conformers = [pr.parsePDB(confs_indir + file) for file in os.listdir(confs_indir)
                            if file in ['model0.pdb']]

sample.set_lig_ifg_dict(relvdm_carboxylate, 'CA C O OXT')
sample.set_lig_ifg_dict(relvdm_carboxamide, 'CG CD OE1 NE2')
sample.set_lig_ifg_dict(relvdm_amino, 'CA N')
sample.set_ligand_ifg_coords(relvdm_carboxylate)
sample.set_ligand_ifg_coords(relvdm_carboxamide)
sample.set_ligand_ifg_coords(relvdm_amino)
sample.set_rel_vdms([relvdm_carboxylate, relvdm_carboxamide, relvdm_amino])

def rev(name_pairs):
    return [((tup[0][1], tup[0][0]), tup[1]) for tup in name_pairs]

sample.name_pairs[('carboxylate', 'carboxamide')] = \
    [(('OXT', 'OE1'), 0.25), (('OXT', 'NE2'), 0.25), (('OXT', 'CG'), 0.3),
     (('O', 'OE1'), 0.25), (('O', 'NE2'), 0.25), (('O', 'CG'), 0.3),
     (('CA', 'OE1'), 0.3), (('CA', 'NE2'), 0.3), (('CA', 'CG'), 0.3)]
sample.name_pairs[('carboxamide', 'carboxylate')] = \
    rev(sample.name_pairs[('carboxylate', 'carboxamide')])

sample.name_pairs[('carboxylate', 'amino')] = \
    [(('OXT', 'CA'), 0.3), (('OXT', 'N'), 0.25),
     (('O', 'CA'), 0.3), (('O', 'N'), 0.25),
     (('CA', 'CA'), 0.3), (('CA', 'N'), 0.3)]
sample.name_pairs[('amino', 'carboxylate')] = \
    rev(sample.name_pairs[('carboxylate', 'amino')])

sample.name_pairs[('carboxamide', 'amino')] = \
    [(('OE1', 'CA'), 0.3), (('OE1', 'N'), 0.25),
     (('NE2', 'CA'), 0.3), (('NE2', 'N'), 0.25),
     (('CG', 'CA'), 0.3), (('CG', 'N'), 0.3)]
sample.name_pairs[('amino', 'carboxamide')] = \
    rev(sample.name_pairs[('carboxamide', 'amino')])

print('finding lig cst hotspots')
sample.find_ligand_cst_hotspots()
sample.set_protein_bb_coords(clash_cutoff=2.5)
sample.make_densities()
sample.set_lig_coords()
print('fitting lig confs to density')
sample.fit_lig_to_density()
if sample.poses:
    sample.pose_metrics(rmsd_cutoff=1.7)
    pscores = []
    ifgs = []
    num_sites = []
    poses = []
    for ind in sample.ranked_poses_by_score:
        pscore = sample.pose_scores[ind]
        ifg = sample.pose_num_satisfied_iFGs[ind]
        num_site = sample.pose_num_residues[ind]
        pose = ind
        if pscore > 1:
            pscores.append(pscore)
            ifgs.append(ifg)
            num_sites.append(num_site)
            poses.append(pose)
            for relvdm_key in sample.rel_vdms.keys():
                outdir_pdb = outdir + 'pose' + str(ind) + '/' + relvdm_key + '/'
                try:
                    os.makedirs(outdir_pdb)
                except:
                    pass
                sample.poses[ind].print_graph_pdbs(sample, relvdm_key, outdir_pdb)
            pr.writePDB(outdir + 'pose' + str(ind) + '/' + 'ligand.pdb', sample.poses[ind].ligand)
    if pscores:
        with open(outdir + 'gln_bp_pose_scores.txt', 'w') as outfile:
            outfile.write('pose scores, ' + ' '.join(str(s) for s in pscores) + '\n')
            outfile.write('number satisfied iFGs, ' + ' '.join(str(s) for s in ifgs) + '\n')
            outfile.write('number residue sites in pose, ' + ' '.join(str(s) for s in num_sites) + '\n')
            outfile.write('pose, ' + ' '.join(str(s) for s in poses) + '\n')

# if sample.pose_scores[sample.ranked_poses_by_score[0]] > 600:
sample.poi = None
sample.rois = None
with gzip.open(outdir + 'sample.pickle.gz', 'wb') as outfile:
    pickle.dump(sample, outfile)


from setuptools import setup
from setuptools import find_packages

__author__ = 'Sakthi Priyan H <sakthipriyans@gmail.com>'
__version__ = '0.0.1'

setup(
    # Basic package information.
    name='twython_service',
    version=__version__,
    packages=find_packages(),

    # Packaging options.
    include_package_data=True,

    # Package dependencies.
    install_requires=['twython>=2.5.4'],

    # Metadata for PyPI.
    author='Sakthi Priyan H',
    author_email='sakthipriyans@gmail.com',
    license='Apache License, Version 2.0',
    url='https://github.com/spriyan/twython-service',
    keywords='twitter api tweet twython service',
    description='Twython Service adds another level of abstraction while posting tweets via Twython.',
    long_description=open('README.md').read(),
    classifiers=[
        'Development Status :: 1 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: Apache License v2',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Communications :: Chat',
        'Topic :: Internet'
    ]
)


# Create a :class:`pyvista.Actor` and assign properties to it.
#
import pyvista as pv
actor = pv.Actor()
actor.prop = pv.Property(
    color='r',
    show_edges=True,
    interpolation='Physically based rendering',
    metallic=0.5,
    roughness=0.1
)
#
# Visualize how the property would look when applied to a mesh.
#
actor.prop.plot()
#
# Set custom properties not directly available in
# :func:`pyvista.Plotter.add_mesh`. Here, we set diffuse, ambient, and
# specular power and colors.
#
pl = pv.Plotter()
actor = pl.add_mesh(pv.Sphere())
prop = actor.prop
prop.diffuse = 0.6
prop.diffuse_color = 'w'
prop.ambient = 0.3
prop.ambient_color = 'r'
prop.specular = 0.5
prop.specular_color = 'b'
pl.show()


import argparse
import os
from pymetasploit3.msfrpc import MsfRpcClient
import nmap

def main(args):
    ip = args.ip_address

    nm = nmap.PortScanner()
    nm.scan(ip, arguments='-sV -sC -p80')

    if not nm.has_host(ip):
        print("Could not find host")
        exit(1)
    print(nm[ip])
    print(nm.all_hosts())
    print(nm.scaninfo())
if __name__ == '__main__':

    parser = argparse.ArgumentParser(
                                    description = "Nmap and metasploit exploitation tool",
                                )
    parser.add_argument("-i", "--ip_address", default="",
                      help = "The ip address of the target")

    args = parser.parse_args()
    main(args)


import json
import os
import sys

from attrdict import AttrDict

config_path = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'config.json')
base_config = {
    'core': {
        'debug': False
    },
    'trakt': {
        'api_key': ''
    },
    'sonarr': {
        'url': 'http://localhost:8989',
        'api_key': '',
        'profile': 'HD-1080p',
        'root_folder': '/tv/',
        'tags': {
        }
    },
    'radarr': {
        'url': 'http://localhost:7878',
        'api_key': '',
        'profile': 'HD-1080p',
        'root_folder': '/movies/'
    },
    'filters': {
        'shows': {
            'blacklisted_genres': [],
            'blacklisted_networks': [],
            'allowed_countries': [],
            'blacklisted_min_runtime': 15,
            'blacklisted_min_year': 2000,
            'blacklisted_max_year': 2019,
            'blacklisted_tvdb_ids': [],
        },
        'movies': {
            'blacklisted_genres': [],
            'blacklisted_min_runtime': 60,
            'blacklisted_min_year': 2000,
            'blacklisted_max_year': 2019,
            'blacklist_title_keywords': [],
            'blacklisted_tmdb_ids': [],
            'allowed_countries': []
        }
    },
    'automatic': {
        'movies': {
            'interval': 20,
            'anticipated': 3,
            'trending': 3,
            'popular': 3,
            'boxoffice': 10
        },
        'shows': {
            'interval': 48,
            'anticipated': 10,
            'trending': 1,
            'popular': 1
        }
    },
    'notifications': {
        'verbose': True
    }
}
cfg = None

class AttrConfig(AttrDict):
    """
    Simple AttrDict subclass to return None when requested attribute does not exist
    """

    def __init__(self, config):
        super().__init__(config)

    def __getattr__(self, item):
        try:
            return super().__getattr__(item)
        except AttributeError:
            pass
        # Default behaviour
        return None

def build_config():
    if not os.path.exists(config_path):
        print("Dumping default config to: %s" % config_path)
        with open(config_path, 'w') as fp:
            json.dump(base_config, fp, sort_keys=True, indent=2)
        return True
    else:
        return False

def dump_config():
    if os.path.exists(config_path):
        with open(config_path, 'w') as fp:
            json.dump(cfg, fp, sort_keys=True, indent=2)
        return True
    else:
        return False

def load_config():
    with open(config_path, 'r') as fp:
        return AttrConfig(json.load(fp))

def upgrade_settings(defaults, currents):
    upgraded = False

    def inner_upgrade(default, current, key=None):
        sub_upgraded = False
        merged = current.copy()
        if isinstance(default, dict):
            for k, v in default.items():
                # missing k
                if k not in current:
                    merged[k] = v
                    sub_upgraded = True
                    if not key:
                        print("Added %r config option: %s" % (str(k), str(v)))
                    else:
                        print("Added %r to config option %r: %s" % (str(k), str(key), str(v)))
                    continue
                # iterate children
                if isinstance(v, dict) or isinstance(v, list):
                    did_upgrade, merged[k] = inner_upgrade(default[k], current[k], key=k)
                    sub_upgraded = did_upgrade if did_upgrade else sub_upgraded

        elif isinstance(default, list) and key:
            for v in default:
                if v not in current:
                    merged.append(v)
                    sub_upgraded = True
                    print("Added to config option %r: %s" % (str(key), str(v)))
                    continue
        return sub_upgraded, merged

    upgraded, upgraded_settings = inner_upgrade(defaults, currents)
    return upgraded, AttrConfig(upgraded_settings)

############################################################
# LOAD CFG
############################################################

# dump/load config
if build_config():
    print("Please edit the default configuration before running again!")
    sys.exit(0)
else:
    tmp = load_config()
    upgraded, cfg = upgrade_settings(base_config, tmp)
    if upgraded:
        dump_config()
        print("New config options were added, adjust and restart!")
        sys.exit(0)


from flask import Flask, request, abort, render_template, flash, redirect, url_for
from linebot import (LineBotApi, WebhookHandler)
from linebot.exceptions import (InvalidSignatureError)
from linebot.models import *
from datetime import datetime
import configparser

# LINE 聊天機器人的基本資料
config = configparser.ConfigParser()
config.read('config.ini')
#YOUR_CHANNEL_ACCESS_TOKEN #需改成自己的 #TOP=>股市小子=>圖片辨識機械人=> Messaging API
line_bot_api = LineBotApi(config.get('line-bot', 'channel_access_token'))
#YOUR_CHANNEL_SECRET #需改成自己的
handler = WebhookHandler(config.get('line-bot', 'channel_secret'))

app = Flask(__name__)

#直接回應圖片訊息   #需在imgur上傳圖片
@app.route("/sendImage/")
def sendImage(event):
    try:
        message = ImageSendMessage(
            original_content_url = "https://i.imgur.com/5PNBSaO.png",
            preview_image_url = "https://i.imgur.com/5PNBSaO.png"
        )
        line_bot_api.reply_message(event.reply_token, message)
    except:
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='系統還在準備中...'))


# Imports
import logging
import os
from os import fdopen, remove
import sys
from tempfile import mkstemp

provider_name = 'ansible'

# Logging
logger = logging.getLogger('logger')
logger.setLevel(logging.INFO)

# Import third-party and custom modules
try:
    import click
    from formatting import ansi_colors, reindent
    from yamlc import CLIInvocation
except ImportError as e:
    print('Failed to import at least one required module')
    print('Error was %s' % e)
    print('Please install/update the required modules:')
    print('pip install -U -r requirements.txt')
    sys.exit(1)

class ProviderCLI:
    def __init__(self, parameter_set=None, vars_input=None):
        if vars_input is None:
            vars_input = {}
        self.vars = vars_input
        self.parameter_set = parameter_set
        self.logger = logger
        pass

    @staticmethod
    def options(func):
        """Add provider-specific click options"""
        option = click.option('---debug', '---d', type=str, help='Start task run with ansible in debug mode',
                              default=False, required=False)
        func = option(func)
        option = click.option('---inventory', '---i', is_flag=False, help='Override embedded inventory specification',
                              required=False)
        func = option(func)
        return func

    @staticmethod
    def invocation(yaml_input_file=None,
                   string_vars=[],
                   default_vars={},
                   paramset_var=None,
                   bash_functions=[],
                   cli_vars='',
                   yaml_vars={},
                   list_vars=[],
                   debug=False,
                   args=None,
                   prefix='',
                   raw_args='',
                   kwargs={}):
        """Invoke commands according to provider"""
        logger.info('Ansible Command Provider')
        ansible_playbook_command = default_vars.get(
            'ansible_playbook_command', 'ansible-playbook')
        # Embedded inventory logic
        embedded_inventory = False
        inventory_input = kwargs.get('_inventory')
        embedded_inventory_string = yaml_vars.get('inventory')
        if not inventory_input and not embedded_inventory_string:
            logger.error(
                "Playbook does not contain an inventory declaration and no inventory was specified. Seek --help")
            sys.exit(1)
        elif inventory_input:
            ansible_inventory_file_path = inventory_input
            ansible_inventory_file_path_descriptor = None
        else:
            ansible_inventory_file_path_descriptor, ansible_inventory_file_path = mkstemp(prefix='ansible-inventory',
                                                                                suffix='.tmp.ini')
            logger.info("No inventory specified")
            logger.info("Writing a temporary inventory file %s (normally deleted after run)"
                        % ansible_inventory_file_path)
            inventory_input = embedded_inventory_string
            embedded_inventory = True
        ansible_extra_options = [
            '-e {k}="{v}"'.format(k=key, v=value) for key, value in kwargs.items() if value]
        ansible_extra_options.append('-e %s' % paramset_var)
        # Build command string
        inventory_command = '''
            if [[ ($inventory) && ( '{emb}' == 'True') ]];then
              echo -e """{ins}""" | while read line;do
                  eval "echo -e ${{line}}" >> "{inf}"
              done
            fi
            '''.format(
                emb=embedded_inventory,
                ins=inventory_input,
                inf=ansible_inventory_file_path,
                )
        inventory_command = reindent(inventory_command,0)
        pre_commands = '''
        {anc}
        {dsv}
        {dlv}
        {clv}
        {bfn}
        {inc}
        '''.format(
            anc=ansi_colors,
            dlv='\n'.join(list_vars),
            dsv='\n'.join(string_vars),
            clv=cli_vars,
            bfn='\n'.join(bash_functions),
            inc=inventory_command,
            deb=debug
        )
        ansible_command = '''
        {apc} ${{__ansible_extra_options}} -i {inf} {opt} {arg} {raw} {ply}
        '''.format(
            apc=ansible_playbook_command,
            inf=ansible_inventory_file_path,
            opt=' '.join(ansible_extra_options),
            ply=yaml_input_file,
            arg=args,
            raw=raw_args
        )
        command = reindent(pre_commands + ansible_command, 0)
        # Command invocation
        if prefix == 'echo':
            if debug:
                print(pre_commands)
                print(ansible_command)
            else:
                print(inventory_command)
                print(ansible_command)
        else:
            CLIInvocation().call(command)
        # Debugging
        if debug:
            ansible_command_file_descriptor, ansible_command_file_path = mkstemp(prefix='ansible-command',
                                                                                suffix='.tmp.sh')
            logger.debug('Ansible command file can be found here: %s' %
                         ansible_command_file_path)
            logger.debug('Ansible inventory file can be found here: %s' %
                         ansible_inventory_file_path)
            with fdopen(ansible_command_file_descriptor, "w") as f:
                f.write(command)
        else:
            if ansible_inventory_file_path_descriptor:
                os.close(ansible_inventory_file_path_descriptor)
                remove(ansible_inventory_file_path)


import os

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
from collections import namedtuple

from utils.config import opt
from data.dataset import Dataset, TestDataset,inverse_normalize
from models.utils.bbox import loc2bbox
from models import faster_rcnn_vgg16
from torch.utils.data import DataLoader
from utils import array_tool as at
from utils.losses import rpn_losses, roi_losses
from utils.visualization import draw

# os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
# os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
LossTuple = namedtuple('LossTuple',
                       ['rpn_loc_loss',
                        'rpn_cls_loss',
                        'roi_loc_loss',
                        'roi_cls_loss',
                        'total_loss'
                        ])

def train(**kwargs):
    opt._parse(kwargs)

    dataset = Dataset(opt)
    num_img = len(dataset)
    print('load data')
    dataloader = DataLoader(dataset, batch_size=1, shuffle=True,
                            num_workers=opt.num_workers)
    testset = TestDataset(opt)
    test_dataloader = DataLoader(testset, batch_size=1,shuffle=False,
                                 num_workers=opt.num_workers,
                                 pin_memory=True)

    faster_rcnn = faster_rcnn_vgg16.FasterRCNNVGG16().cuda()
    print('model construct completed.')
    if opt.load_path:
        faster_rcnn.load(opt.load_path)
        print('load pretrained model from {}'.format(opt.load_path))

    writer = SummaryWriter('./log')
    print('Add summary writer.')

    # img, bbox, label, scale = next(iter(dataloader))
    # img, bbox, label = img.cuda(), bbox.cuda(), label.cuda()
    # writer.add_graph(faster_rcnn, (img, bbox, label, scale))

    optimizer = optim.SGD(faster_rcnn.parameters(),lr=opt.lr, momentum=0.9, weight_decay=opt.weight_decay)

    for epoch in range(opt.epoch):
        if epoch==9:
            for param_group in optimizer.param_groups:
                param_group['lr'] *= opt.lr_decay
        for step, (img, bbox, label, scale) in enumerate(dataloader):
            scale = at.scalar(scale)
            img, bbox, label = img.cuda(), bbox.cuda(), label.cuda()

            rpn, roi, sample_roi = faster_rcnn(img, bbox, label, scale)

            rpn_loc_loss, rpn_cls_loss = rpn_losses(rpn.rpn_loc, rpn.rpn_score, rpn.gt_rpn_loc,
                                                    rpn.gt_rpn_label, opt.rpn_sigma)

            roi_loc_loss, roi_cls_loss = roi_losses(roi.roi_loc, roi.roi_score, roi.gt_roi_loc,
                                                    roi.gt_roi_label, opt.roi_sigma)

            losses = [10*rpn_loc_loss, rpn_cls_loss, 10*roi_loc_loss, roi_cls_loss]
            losses = losses + [sum(losses)]
            loss =LossTuple(*losses)

            optimizer.zero_grad()
            loss.total_loss.backward()
            print('step:{} ,rpn loc loss:{:.4f}, roi loc loss:{:.4f}'.format(step, loss.rpn_loc_loss.item(), loss.roi_loc_loss.item()))
            optimizer.step()

            writer.add_scalars('loss',{
                'rpn_loc_loss':loss.rpn_loc_loss,
                'rpn_cls_loss':loss.rpn_cls_loss,
                'roi_loc_loss':loss.roi_loc_loss,
                'roi_cls_loss':loss.roi_cls_loss,
                'total_loss':loss.total_loss
            }, step + epoch*num_img)
            # visualization
            # draw(roi.roi_score[:,:20].detach().cpu().numpy(), loc2bbox(sample_roi.cpu().numpy(), roi.roi_loc.detach().cpu().numpy()), img.cpu()[0], step, writer)

        torch.save(faster_rcnn, 'voc_epoch_{}.pt'.format(epoch+1))
    print('over')

if __name__ == '__main__':
    import fire

    fire.Fire()


from django import template
from django.conf import settings
from django.core.urlresolvers import reverse

register = template.Library()

@register.inclusion_tag('multiuploader/multiuploader_main.html')
def multiuploader(create_view=None, list_view=None, create_url=None, list_url=None, include_container=True, **view_kwargs):
    context = {
        'static_url': settings.STATIC_URL,
        'include_container': include_container
    }

    if create_url is not None:
        context['create_url'] = create_url
    elif create_view is not None:
        context['create_url'] = reverse(create_view, kwargs=view_kwargs)

    if list_url is not None:
        context['list_url'] = list_url
    elif list_view is not None:
        context['list_url'] = reverse(list_view, kwargs=view_kwargs)

    return context


from sklearn import svm
import numpy as np
from sklearn.neighbors import KNeighborsClassifier

###########################################
#Choose the K value in the KNN
###########################################

k = 7

###########################################
#Training the clf (classifier)
###########################################

def create_labeled_data():
    minlist = list()
    xlist = list()
    ylist = list()
    with open(("Data/train-io.txt"), "r", encoding="utf-8") as f:
        for i, line in enumerate(f):
            if i <= 300000:
                for word in line.split():
                    minlist.append(word)
                for x, word in enumerate(minlist):
                    if x == 12:
                        ylist.append(word)
                        minlist.remove(word)
                xlist.append(minlist)
                minlist = list()
    return xlist, ylist

x, Y = create_labeled_data()
# convert x into a numpy array
X = np.array(x)
# create instance of svm classifier
clf = KNeighborsClassifier(n_neighbors = k)
# fit the 12-D input to the correct output of 1 or 0
clf.fit(X, Y)

##############################################################
#Read in test-in and predict labels
##############################################################

def test_data():
    minlist = list()
    queries = list()
    with open(("Data/test-in.txt"), "r", encoding="utf-8") as f:
         for i, line in enumerate(f):
            if i <= 10000:
                for word in line.split():
                    minlist.append(word)
                queries.append(minlist)
                minlist = list()
    return queries

qs = test_data()
# predict either 1 or 0 for each input
predicted_ans = clf.predict(qs)
print(predicted_ans)

##############################################################
#Output result to test-out.txt file
##############################################################

def output_file (predicted_ans):
    with open(("Data/test-out.txt"), "w", encoding="utf-8") as f:
        for label in predicted_ans:
            f.write(label)
            f.write("\n")

output_file(predicted_ans)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 20 12:03:02 2018

Detecta y devuelve la region del LED del contador de UTE

@author: nicolas
"""
import cv2
from detect import detect
import numpy as np

def extraer_region(img_color):

    img_gray = cv2.cvtColor(img_color, cv2.COLOR_BGR2GRAY)
    img_blur = cv2.medianBlur(img_gray, 55)
    #Aplico umbral para tener imagen binaria
    ret, thresh = cv2.threshold(img_blur, 127, 255, 0)
    #Hallo contornos
    (_, contours, _) = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    #Hallo contornos que sean rectangulos y los ploteo
    rectangles = []
    for contour in contours:
        shape = detect(contour)
        if shape == "rectangle":
            rect = cv2.boundingRect(contour)
            rectangles.append(rect)

    total_area = thresh.size
    max_allowed = total_area*0.3
    rectangles = [rectangle for rectangle in rectangles if rectangle[2] * rectangle[3] < max_allowed]
    ganamos = np.argmax([rectangle[2] * rectangle[3] for rectangle in rectangles])

    rect = rectangles[ganamos]
    region = img_color[rect[1]:rect[1]+rect[3], rect[0]:rect[0]+rect[2], :]

    return region


from enum import Enum
from queue import PriorityQueue
import numpy as np
import numpy as np
from scipy.spatial import Voronoi
from bresenham import bresenham
import numpy.linalg as LA

def create_grid(data, drone_altitude, safety_distance):
    """
    Returns a grid representation of a 2D configuration space
    based on given obstacle data, drone altitude and safety distance
    arguments.
    """

    # minimum and maximum north coordinates
    north_min = np.floor(np.min(data[:, 0] - data[:, 3]))
    north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))

    # minimum and maximum east coordinates
    east_min = np.floor(np.min(data[:, 1] - data[:, 4]))
    east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))

    # given the minimum and maximum coordinates we can
    # calculate the size of the grid.
    north_size = int(np.ceil(north_max - north_min))
    east_size = int(np.ceil(east_max - east_min))

    # Initialize an empty grid
    grid_size = (north_size, east_size)
    grid = np.zeros(grid_size)

    # Populate the grid with obstacles
    for i in range(data.shape[0]):
        north, east, alt, d_north, d_east, d_alt = data[i, :]
        if alt + d_alt + safety_distance > drone_altitude:
            obstacle = [
                int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)),
                int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)),
                int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)),
                int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)),
            ]
            grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1

    return grid, int(north_min), int(east_min), grid_size

def create_2_dot_5_grid(data, safety_distance):
    """
    Returns a grid representation of a 2.5D configuration space
    based on given obstacle data, drone altitude and safety distance
    arguments.
    """

    # minimum and maximum north coordinates
    north_min = np.floor(np.min(data[:, 0] - data[:, 3]))
    north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))

    # minimum and maximum east coordinates
    east_min = np.floor(np.min(data[:, 1] - data[:, 4]))
    east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))

    # given the minimum and maximum coordinates we can
    # calculate the size of the grid.
    north_size = int(np.ceil(north_max - north_min))
    east_size = int(np.ceil(east_max - east_min))

    # Initialize an empty grid
    grid_size = (north_size, east_size)
    grid = np.zeros(grid_size)

    # Populate the grid with obstacles
    for i in range(data.shape[0]):
        north, east, alt, d_north, d_east, d_alt = data[i, :]

        obstacle = [
            int(np.clip(north - d_north - safety_distance - north_min, 0, north_size-1)),
            int(np.clip(north + d_north + safety_distance - north_min, 0, north_size-1)),
            int(np.clip(east - d_east - safety_distance - east_min, 0, east_size-1)),
            int(np.clip(east + d_east + safety_distance - east_min, 0, east_size-1)),
        ]
        grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = alt + d_alt

    return grid, int(north_min), int(east_min), grid_size

# Assume all actions cost the same.
class Action(Enum):
    """
    An action is represented by a 3 element tuple.

    The first 2 values are the delta of the action relative
    to the current grid position. The third and final value
    is the cost of performing the action.
    """

    WEST = (0, -1, 1)
    EAST = (0, 1, 1)
    NORTH = (-1, 0, 1)
    SOUTH = (1, 0, 1)
    SW = (1, -1, np.sqrt(2))
    NE = (-1, 1, np.sqrt(2))
    NW = (-1, -1, np.sqrt(2))
    SE = (1, 1, np.sqrt(2))

    @property
    def cost(self):
        return self.value[2]

    @property
    def delta(self):
        return (self.value[0], self.value[1])

def valid_actions(grid, current_node):
    """
    Returns a list of valid actions given a grid and current node.
    """
    valid_actions = list(Action)
    n, m = grid.shape[0] - 1, grid.shape[1] - 1
    x, y = current_node

    # check if the node is off the grid or
    # it's an obstacle

    if x + 1 > n or y + 1 > m or grid[x + 1, y + 1] == 1:
            valid_actions.remove(Action.SE)
    if x - 1 < 0 or y + 1 > m or grid[x - 1, y + 1] == 1:
        valid_actions.remove(Action.NE)

    if x + 1 > n or y - 1 < 0 or grid[x + 1, y - 1] == 1:
        valid_actions.remove(Action.SW)

    if x - 1 < 0 or y - 1 < 0 or grid[x - 1, y - 1] == 1:
        valid_actions.remove(Action.NW)
    if x - 1 < 0 or grid[x - 1, y] == 1:
        valid_actions.remove(Action.NORTH)
    if x + 1 > n or grid[x + 1, y] == 1:
        valid_actions.remove(Action.SOUTH)
    if y - 1 < 0 or grid[x, y - 1] == 1:
        valid_actions.remove(Action.WEST)
    if y + 1 > m or grid[x, y + 1] == 1:
        valid_actions.remove(Action.EAST)

    return valid_actions

def a_star_grid(grid, h, start, goal):

    path = []
    path_cost = 0
    queue = PriorityQueue()
    queue.put((0, start))
    visited = set(start)

    branch = {}
    found = False
    i = 0
    while not queue.empty():
        i+=1
        item = queue.get()
        current_node = item[1]
        if current_node == start:
            current_cost = 0.0
        else:
            current_cost = branch[current_node][0]

        if current_node == goal:
            print('Found a path.')
            found = True
            break
        else:
            for action in valid_actions(grid, current_node):
                # get the tuple representation
                da = action.delta
                next_node = (current_node[0] + da[0], current_node[1] + da[1])
                branch_cost = current_cost + action.cost
                queue_cost = branch_cost + h(next_node, goal)

                if next_node not in visited:
                    visited.add(next_node)
                    branch[next_node] = (branch_cost, current_node, action)
                    queue.put((queue_cost, next_node))

    if found:
        # retrace steps
        n = goal
        path_cost = branch[n][0]
        path.append(goal)
        while branch[n][1] != start:
            path.append(branch[n][1])
            n = branch[n][1]
        path.append(branch[n][1])
    else:
        print('**********************')
        print('Failed to find a path!')
        print('**********************')
    return path[::-1], path_cost

def heuristic(position, goal_position):
    return np.linalg.norm(np.array(position) - np.array(goal_position))

def prune(path, epsilon=5):

    def pt(p):
        return np.array([p[0], p[1], 1.])

    def isColinear(p1, p2, p3):
        mat = np.vstack((pt(p1), pt(p2), pt(p3)))
        det = np.linalg.det(mat)
        if np.abs(det) < epsilon:
            return True
        else:
            return False

    pruned_path = path
    i = 0
    while i < len(pruned_path) - 2:
        p1 = pruned_path[i]
        p2 = pruned_path[i + 1]
        p3 = pruned_path[i + 2]

        if isColinear(pt(p1), pt(p2), pt(p3)):
            pruned_path.remove(p2)
        else:
            i += 1

    return pruned_path

def can_connect(n1, n2):
    '''
    casts two points as a shapely LineString() object
    tests for collision with a shapely Polygon() object
    returns True if connection is possible, False otherwise
    '''

    l = LineString([n1, n2])
    for p in polygons:
        #if p.crosses(l) and p.height >= min(n1[2], n2[2]):
        if p.crosses(l):
            return False
    return True

def create_graph(nodes, k):
    '''
    defines a networkx graph as g = Graph()
    defines a tree = KDTree(nodes)
    test for connectivity between each node and
    k of it's nearest neighbors
    if nodes are connectable, add an edge to graph
    Iterate through all candidate nodes!
    '''

    g = nx.Graph()
    tree = KDTree(nodes)
    for n1 in nodes:
        # for each node connect try to connect to k nearest nodes
        idxs = tree.query([n1], k, return_distance=False)[0]

        for idx in idxs:
            n2 = nodes[idx]
            if np.array_equal(n1, n2):
                continue
            if can_connect(n1, n2):
                g.add_edge(tuple(n1), tuple(n2), weight=1)
    return g

def a_star_graph(graph, heuristic, start_ne, goal_ne):
    """Modified A* to work with NetworkX graphs."""

    start = closest_point(graph, start_ne)
    goal = closest_point(graph, goal_ne)
    if start == goal:
        return [], 0

    path = []
    queue = PriorityQueue()
    queue.put((0, start))
    visited = set(start)

    branch = {}
    found = False

    while not queue.empty():
        item = queue.get()
        current_cost = item[0]
        current_node = item[1]

        if current_node == goal:
            #print('Found a path.')
            found = True
            break
        else:
            for next_node in graph[current_node]:
                cost = graph.edges[current_node, next_node]['weight']
                new_cost = current_cost + cost + heuristic(next_node, goal)

                if next_node not in visited:
                    visited.add(next_node)
                    queue.put((new_cost, next_node))

                    branch[next_node] = (new_cost, current_node)

    path = []
    path_cost = 0
    if found:
        # retrace steps
        path = []
        n = goal
        path_cost = branch[n][0]
        while branch[n][1] != start:
            path.append(branch[n][1])
            n = branch[n][1]
        path.append(branch[n][1])

    return path[::-1], path_cost

def get_home_position():
    """
    Returns home position from colliders.csv
    """

    f = open ('colliders.csv')
    first_row = f.readlines()[0].replace('\n','').split(', ')
    f.close()
    lat0 = float(first_row[0].strip('lat0 '))
    lon0 = float(first_row[1].strip('lon0 '))
    return lon0, lat0

def create_grid_and_edges(data, drone_altitude, safety_distance, resolution = 1):
    """
    Returns a grid representation of a 2D configuration space
    along with Voronoi graph edges given obstacle data and the
    drone's altitude.
    """

    # minimum and maximum north coordinates
    north_min = np.floor(np.min(data[:, 0] - data[:, 3]))
    north_max = np.ceil(np.max(data[:, 0] + data[:, 3]))

    # minimum and maximum east coordinates
    east_min = np.floor(np.min(data[:, 1] - data[:, 4]))
    east_max = np.ceil(np.max(data[:, 1] + data[:, 4]))

    # given the minimum and maximum coordinates we can
    # calculate the size of the grid.
    north_size = int(np.ceil(north_max - north_min) / resolution)
    east_size = int(np.ceil(east_max - east_min) / resolution)

    # Initialize an empty grid
    grid = np.zeros((north_size, east_size))
    # Initialize an empty list for Voronoi points
    points = []
    # Populate the grid with obstacles
    for i in range(data.shape[0]):
        north, east, alt, d_north, d_east, d_alt = data[i, :]
        if alt + d_alt + safety_distance > drone_altitude:
            obstacle = [
                int(np.clip((north - d_north - safety_distance - north_min) / resolution, 0, north_size-1)),
                int(np.clip((north + d_north + safety_distance - north_min) / resolution, 0, north_size-1)),
                int(np.clip((east - d_east - safety_distance - east_min) / resolution, 0, east_size-1)),
                int(np.clip((east + d_east + safety_distance - east_min) / resolution, 0, east_size-1)),
            ]
            grid[obstacle[0]:obstacle[1]+1, obstacle[2]:obstacle[3]+1] = 1

            # add center of obstacles to points list
            points.append([int((north - north_min) / resolution),
                           int((east - east_min) / resolution)])

    # create a voronoi graph based on
    # location of obstacle centres
    graph = Voronoi(points)

    # check each edge from graph.ridge_vertices for collision
    edges = []
    for v in graph.ridge_vertices:
        p1 = graph.vertices[v[0]]
        p2 = graph.vertices[v[1]]

        cells = list(bresenham(int(p1[0]), int(p1[1]), int(p2[0]), int(p2[1])))
        hit = False

        for c in cells:
            # First check if we're off the map
            if np.amin(c) < 0 or c[0] >= grid.shape[0] or c[1] >= grid.shape[1]:
                hit = True
                break
            # Next check if we're in collision
            if grid[c[0], c[1]] == 1:
                hit = True
                break

        # If the edge does not hit on obstacle
        # add it to the list
        if not hit:
            # array to tuple for future graph creation step)
            p1 = (p1[0], p1[1])
            p2 = (p2[0], p2[1])
            edges.append((p1, p2))

    return edges
    #return grid, edges, north_min, np.ceil(north_max - north_min), east_min, np.ceil(east_max - east_min)

def closest_point(graph, current_point):
    """
    Compute the closest point in the `graph`
    to the `current_point`.
    """
    closest_point = None
    dist = 100000
    for p in graph.nodes:
        d = LA.norm(np.array(p) - np.array(current_point))
        if d < dist:
            closest_point = p
            dist = d
    return closest_point

def random_goal(north_range, east_range,
                start=(0,0,0), min_dist = 0, max_altitude = 20):
    """
    Returns a random goal, expressed in NED format
    ((north, east, down)

    Args:
    north_range: tuple(min,max) all inclusive
    easth_range: tuple(min,max) all inclusive
    down_range: tuple(min,max) all inclusive
    start: start location in NED format
    min_dist: integer representing the minimum distance between start and goal
    """
    data = np.loadtxt('colliders.csv', delimiter=',', dtype='float32', skiprows=2)
    dot_5_grid, north_offset, east_offset, _ = create_2_dot_5_grid(data, 5)
    occupied_location = True
    dist = 0
    while dist < min_dist or occupied_location:
        ne_coord = (np.random.randint(north_range[0], north_range[1]+1),
        np.random.randint(east_range[0], east_range[1]+1))
        dist = np.linalg.norm(np.array(ne_coord) - np.array(start))
        #print ("Goal altitude = {}".format(dot_5_grid[ne_coord[0] - north_offset][ne_coord[1] - east_offset]))
        occupied_location = (dot_5_grid[ne_coord[0] - north_offset][ne_coord[1] - east_offset] > max_altitude)
    ned_coord = (ne_coord[0], ne_coord[1], int(dot_5_grid[ne_coord[0] - north_offset][ne_coord[1] - east_offset]))
    return ned_coord

def create_moving_grid(current_loc, name, grid_size, res):
    """
    Creates a grid with the current location as the center of the grid
    """

    grid = {
    "name": name,
    "origin": np.array(current_loc[:2]) - np.array(grid_size) / 2,
    "offset": (0,0),
    "resolution": res,
    "size": grid_size,
    "data": np.zeros(grid_size)
    }
    return grid

def in_grid_3D(m_coord_pt, grid):
    """
    Returns True if a point with map coordinates m_coord_pt is in grid
    """
    g_coord_pt = map_to_grid_3D(m_coord_pt, grid)
    for i in range(len(m_coord_pt)):
        if not (0<=g_coord_pt[i]<grid["size"][i]):
            return False
    return True

def in_grid(m_coord_pt, grid):
    """
    Returns True if a point with map coordinates m_coord_pt is in grid
    """
    g_coord_pt = map_to_grid(m_coord_pt, grid)
    test = (0<=g_coord_pt[0]<grid["size"][0]) and (0<=g_coord_pt[1]<grid["size"][1])
    return test

def intersect_grid_pts (pt_a, pt_b, grid):
    """
    Finds the point at the intersection of the line formed by 2 points and the grid
    Assumes we move from pt_a to pt_b
    """

    # Notation: y = mx + b - linear Equation
    if abs((pt_b[1] - pt_a[1])) > 0.1:
        m = (pt_b[0] - pt_a[0])/(pt_b[1] - pt_a[1])

        if m == 0:
            b = pt_a[0]
        else:
            b = (pt_b[1] * pt_a[0] - pt_a[1] * pt_b[0]) / (pt_b[1] - pt_a[1])

            if pt_b[0] > pt_a[0]:
                y1 = grid["origin"][0] + \
                grid["size"][0] * grid["resolution"] - \
                grid["resolution"] /2
                x1 = (y1 - b) / m
            else:
                y1 = grid["origin"][0] + \
                grid["resolution"] /2
                x1 = (y1 - b) / m

        if pt_b[1] > pt_a[1]:
            x2 = grid["origin"][1] + \
            grid["size"][1] * grid["resolution"] - \
            grid["resolution"] /2
            y2 = m * x2 + b
        else:
            x2 = grid["origin"][1] + \
            grid["resolution"] /2
            y2 = m * x2 + b

        #print ("The 2 possible points are: {}, {}".format([y1, x1], [y2, x2]))
        if in_grid(np.array([y2, x2]), grid):
            inter_pt = np.array([y2, x2])
        else:
            inter_pt = np.array([y1, x1])

    else:
        x1 = pt_b[1]
        if pt_b[0] > pt_a[0]:
            y1 = grid["origin"][0] + \
            grid["size"][0] * grid["resolution"] - \
            grid["resolution"] /2
        else:
            y1 = grid["origin"][0] + \
            grid["resolution"] /2
        inter_pt = np.array([y1, x1])

    return inter_pt

def map_to_grid(m_coord_pt, grid):
    """
    Converts map coordinates to a grid coordinate
    """
    g_coord = [int((m_coord_pt[0] - grid["origin"][0]) / grid["resolution"]),
                 int((m_coord_pt[1] - grid["origin"][1]) / grid["resolution"])]
    return g_coord

def grid_to_map(g_coord, grid):
    """
    Converts grid coordinates to a map coordinate
    """
    m_coord = [g_coord[0] * grid["resolution"] + grid["origin"][0],
                 g_coord[1] * grid["resolution"] + grid["origin"][1]]
    return m_coord


import os

import numpy as np
import tensorflow as tf
from absl import app, flags
from skimage import io
from tensorflow.compat.v1 import ConfigProto, InteractiveSession

from core.dataset import CreateDataset
from core.unet import Unet

# Setup dynamic gpu memory growth.
config = ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)

FLAGS = flags.FLAGS

flags.DEFINE_string('logdir', None,
                    'the dir of weights file saved by model.save_weights().')
flags.DEFINE_string('label_file_path', None,
                    'Path of testing dataset label file.')
flags.DEFINE_integer('batch_size', 1, 'Global batch size.')
flags.DEFINE_integer('image_size', 1024, 'Size of each image side to use.')
flags.DEFINE_boolean('preprocess', False, 'Whether to use preprocessed image.')
flags.DEFINE_integer('num_classes', 2, 'Number of classes.')
flags.DEFINE_boolean('transpose_conv', False,
                     'Whether to use Conv2DTranspose as upsample layer.')
flags.DEFINE_boolean('visulize', False, 'Whether to visulize predicts.')

def visulize_predicts(predicts, images, labels, masks, logdir, idx):
  """ Visulizing predicts with different color:
    error -> red, right -> green, miss -> blue.

  Args:
    predicts: numpy array, shape = [batch, h, w].
    images: numpy array, shape = [batch, h, w, 1 or 3].
    labels: numpy array, shape = [batch, h, w, 1].
    masks: numpy array, shape = [batch, h, w, 1].
    logdir: str, to stores the floder of visualization results.
    idx: int, use to name result image, images[i] -> str(idx+i).jpg.
  """
  visulize_dir = os.path.join(logdir, 'visulize')
  if not os.path.exists(visulize_dir): os.mkdir(visulize_dir)

  if images.shape[-1] == 1:
    images = np.tile(images, [1, 1, 1, 3])

  for i in range(predicts.shape[0]):
    right = predicts[i][:, :, np.newaxis] * labels[i] * masks[i]
    error = predicts[i][:, :, np.newaxis] - right
    miss = labels[i] - right

    vis = np.concatenate([error, right, miss], axis=-1)
    vis = np.concatenate([images[i], vis * 255], axis=0)

    vis_path = os.path.join(visulize_dir, str(idx+i)+'.png')
    io.imsave(vis_path, vis.astype(np.uint8))

def main(argv):
  # Load datasets.
  test_dataset = CreateDataset(
    file_path=FLAGS.label_file_path,
    image_size=FLAGS.image_size,
    batch_size=FLAGS.batch_size,
    preprocess=FLAGS.preprocess,
    augmentation=False,
    repeat=False)

  model = Unet(
      data_format='channels_last',
      classes=FLAGS.num_classes,
      transpose_conv=FLAGS.transpose_conv)
  weights_path = os.path.join(FLAGS.logdir, 'unet_weights')
  model.load_weights(weights_path)

  # Setup metric.
  mIoU = tf.keras.metrics.MeanIoU(num_classes=2)

  count = 0
  for idx, (images, labels, masks) in enumerate(test_dataset):
    logits = model.build_call(images, training=False)
    predicts = np.argmax(logits.numpy(), axis=-1)

    # optinal.
    if FLAGS.visulize:
      visulize_predicts(predicts, images, labels, masks, FLAGS.logdir, count)
      count += predicts.shape[0]

    mIoU.update_state(labels, predicts, masks)

  cm = mIoU.total_cm
  print('confuse mat:\n', cm.numpy().astype(np.int32))
  print('IoU: ', (cm[1, 1] / (cm[0, 1] + cm[1, 0] + cm[1, 1])).numpy())
  print('mIoU: ', mIoU.result().numpy())

if __name__ == '__main__':
    app.run(main)


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

# ExportDemexTradesAndTransfersToKoinly
# Copyright © 2021 Eporediese for Switcheo / MaiTePora <3
# Licenced under GPL

# Creates CSV files in a format the the tax software Koinly understands, from Demex account trades and transfers for any Demex addresses
# The CSV files are written in the location that this script is executed
# This is not tax advice. The user accepts that the output of this tool should be reviewed for accuracy and completeness

# LIBRARYS
# ------------------------------------------------------------------------------
# Tradehub Python API: https://mai-te-pora.github.io/tradehub-python/index.html
import tradehub
from tradehub.wallet import Wallet
from tradehub.transactions import Transactions
from tradehub.authenticated_client import AuthenticatedClient
from tradehub.types import CreateOrderMessage

# Date manipulation
import datetime;
import time;
from datetime import date

# Regular expressions
import re

# PARAMETERS
# ------------------------------------------------------------------------------
# Provide the mneumonic of any wallet (can be an empty wallet)
myMnemonic = 'these are twelve words that used together allow access to your wallet' #Tradehub mnemonic (example here: 12 word TradeHub mnemonic)

# Provide the Demex addresses that you want to pull trades and transfers for
demexAddresses = [
    'swth1primary', # Primary
    'swth1secondary' # Secondary
]

# CONSTANTS
# ------------------------------------------------------------------------------
demPK = Wallet(myMnemonic, network='mainnet')
clientDem = AuthenticatedClient(demPK, network='mainnet',trusted_ips=None, trusted_uris=['http://54.255.5.46:5001', 'http://175.41.151.35:5001'])

# MAIN
# ------------------------------------------------------------------------------
print(f'Connected To Tradehub --- {demPK.address}')

transDem = Transactions(demPK,
             trusted_ips=None,
             trusted_uris=['http://54.255.5.46:5001', 'http://175.41.151.35:5001'],
             network="mainnet")

# Iterate over Demex adresses

for address in demexAddresses:

    #print (address)

    # Get external transfers for Demex address
    transfers = transDem.get_external_transfers(address)
    #print (transfers)

    # Get trades (note: can set date range if needed)
    trades = transDem.get_address_trades('','',address) # Limited to 200 trades?
    #print (trades)

    # ct stores current time
    ct = datetime.datetime.now()
    #print("current time:-", ct)

    # Convert to a format that can be used in a filename
    fileDate = str(ct.month) + str(ct.day) + str(ct.year) + str(ct.hour) + str(ct.minute) + str(ct.second)
    #print (fileDate)

    # Open the output Koinly transfer history CSV file
    transferFilename = "koinly_transfer_history_for_" + address + "_at_" + str(fileDate) + ".csv"
    #print (transferFilename)
    transferFile = open(transferFilename, "w")

    # Open the output Koinly trade history CSV file
    tradeFilename = "koinly_trade_history_for_" + address + "_at_" + str(fileDate) + ".csv"
    #print (transferFilename)
    tradeFile = open(tradeFilename, "w")

    # Write out CSV files in Koinly file format
    # Trasfer tmplate is here: https://docs.google.com/spreadsheets/d/13H9kREcrNJmCNxkpYK-AaRlkWh8PSshbpPBmewmDX4o/edit#gid=0
    # Trade template is here: https://docs.google.com/spreadsheets/d/1MEVrdiS941S-s0igBZKh-pbW5TqJb4mpfkmnDzDkCcg/edit#gid=0
    # All date fields must be formatted like this: YYYY-MM-DD HH:mm:ss.
    # For ex. if you want to enter 5th Jan 2019 the date will be 2019-01-05.
    # All dates should be in UTC.

    transferHeader = "Koinly Date,Amount,Currency,Label,TxHash\n"
    #print (header)
    transferFile.write(transferHeader)

    tradeHeader = "Koinly Date,Pair,Side,Amount,Total,Fee Amount,Fee Currency,Order ID,Trade ID\n"
    tradeFile.write(tradeHeader)

# Iterate over transfers
# Koinly Date	Amount	Currency	Label	TxHash

for transfer in transfers:

    #print (transfer)

    # Extract timestamp
    transferEpoch = transfer['timestamp']
    #print (transferEpoch)

    # Convert Epoch timestamp format to YYYY-MM-DD HH:mm:ss format
    # In UTC
    koinlyTimestamp = datetime.datetime.utcfromtimestamp(transferEpoch).strftime('%Y-%m-%d %H:%M:%S')

    # Extract amount
    transferAmount = transfer['amount']

    # Extract currency
    transferSymbol = transfer['symbol']

    # Convert Demex to Koinly symbols
    if (transferSymbol == "SWTHN"):
        koinlySymbol = "SWTH"
    else:
        koinlySymbol = transferSymbol

    # Extract Transaction type
    transferType = transfer['transfer_type']

    # Extract Transaction hash to use as label
    transferHash = transfer['transaction_hash']

    # Extract Transaction status
    transferStatus = transfer['status']

    if (transferStatus == 'success'):
        transferFile.write(koinlyTimestamp + "," + transferAmount + "," + koinlySymbol.upper() + "," + transferType + "," + transferHash + "\n")

# Iterate over trades
# Koinly Date	Pair	Side	Amount	Total	Fee Amount	Fee Currency	Order ID	Trade ID

for trade in trades:

    #print (trade)

    # Extract timestamp
    tradeEpoch = trade['block_created_at']
    #print (tradeEpoch)

    # Convert block timestamp format to YYYY-MM-DD HH:mm:ss format

    s = re.findall('(.+)T(.+)\.', tradeEpoch)
    #print (s)
    #print (s[0][0])
    #print (s[0][1])
    koinlyTimestamp = s[0][0] + " " + s[0][1]
    #print (koinlyTimestamp)

    # Extract amount
    tradeAmount = trade['quantity']

    # Construct Buy|Sell side
    if (trade['side'] == 'sell'):
        tradeSide = 'Sell'
    else:
        tradeSide = 'Buy'

    # Extract trade pair
    tradePairExtracted = trade['market']
    #print (tradePairExtracted)
    # Convert to Koinly format and known coins
    s = re.findall('(.+[^\d])[\d]*_(.+[^\d])[\d]*', tradePairExtracted)
    fromCurrencyExtracted = s[0][0].upper()
    toCurrencyExtracted = s[0][1].upper()
    tradePair = s[0][0].upper() + "-" + s[0][1].upper()
    #print (tradePair)

    # Extract trade price and use to calculate the total
    tradePrice = trade['price']
    #print (tradePrice)
    #print (tradeAmount)
    tradeTotal = float(tradePrice) * float(tradeAmount)
    #print (str(tradeTotal))

    # Extract fee amount
    tradeFeeAmount = str(trade['fee_amount'])

    # Extract fee total
    tradeFeeCurrencyExtracted = trade['fee_denom']
    #print (tradeFeeCurrencyExtracted)
    # Convert to Koinly format and known coins
    s = re.findall('(.+[^\d])[\d]*', tradeFeeCurrencyExtracted)
    tradeFeeCurrency = s[0].upper()
    #print (tradeFeeCurrency)

    # Extract order ID
    tradeOrderID = str(trade['order_id'])

    # Extract trade ID
    tradeTradeID = str(trade['id'])

    tradeFile.write(koinlyTimestamp + "," + tradePair + "," + tradeSide + "," + str(tradeAmount) + "," + str(tradeTotal) + "," + tradeFeeAmount + "," + tradeFeeCurrency + "," + tradeOrderID + "," + tradeTradeID + "\n")

transferFile.close()
tradeFile.close()


import discord
import asyncio
import logging
import wavelink
import math
from .queue import MusicQueue
from . import utils
from hourai.utils import embed
from hourai.db import proto

log = logging.getLogger('hourai.music.player')

PROGRESS_BAR_WIDTH = 12
TRACKS_PER_PAGE = 10
POST_TRACK_WAIT = 5.0

def get_default_channel(guild):
    channels = filter(lambda ch: ch.permissions_for(guild.me).connect,
                      guild.voice_channels)
    return next(channels, None)

async def get_voice_channel(guild):
    music_config = await get_music_config(ctx)
    channel = None
    if music_config.HasField('voice_channel_id'):
        channel = ctx.guild.get_channel(music_config.voice_channel_id)
        if isinstance(channel, discord.VoiceChannel):
            channel = None
    return channel or get_default_channel(ctx.guild)

class Unauthorized(Exception):
    pass

class HouraiMusicPlayer(wavelink.Player):

    def __init__(self, bot, guild_id: int, node: wavelink.Node):
        super().__init__(bot, guild_id, node)

        self.next_event = asyncio.Event()
        self.queue = MusicQueue()

        self.current = None
        self._requestor_id = None

        self.skip_votes = set()

        self.queue_msg = None
        self.now_playing_msg = None

        self.queue_ui = None
        self.np_msg = None

        bot.loop.create_task(self.__player_loop())

    async def get_music_config(self):
        config = await self.bot.storage.music_configs.get(self.guild_id)
        return config or proto.MusicConfig()

    async def set_music_config(self, music_config):
        await self.bot.storage.music_configs.set(self.guild_id,
                                                 music_config)

    async def __init_player_loop(self):
        await self.set_preq('Flat')
        config = await self.get_music_config()
        await self.set_volume(config.volume)

    async def __player_loop(self):
        await self.bot.wait_until_ready()
        await self.__init_player_loop()
        while True:
            try:
                self.next_event.clear()

                if self.is_connected and len(self.queue) <= 0:
                    # Stop playing the song and disconnect
                    await self.disconnect()
                    await super().stop()

                requestor_id, song = await self.queue.get()
                if not song:
                    continue

                if not self.is_connected:
                    channel = await get_voice_channel(self.guild)
                    if channel is None:
                        continue
                    await self.connect(channel.id)

                self.current = song
                self._requestor_id = requestor_id

                await self.play(song)

                self.next_event.clear()
                # Wait for TrackEnd event to set our event...
                await self.next_event.wait()

                # Wait for a few seconds before loading the next track due to the
                # potential delay
                await asyncio.sleep(POST_TRACK_WAIT)

                # Clear votes...
                self.skip_votes.clear()
                self.current = None
                self._requestor_id = None
            except Exception:
                log.exception(f'Exception while playing for guild '
                              f'{self.guild_id}:')

    async def disconnect(self):
        await super().disconnect()
        self.current = None
        self._requestor_id = None
        self.skip_votes.clear()

    async def hook(self, event):
        if isinstance(event, wavelink.TrackEnd):
            if event.reason in ('FINISHED', 'LOAD_FAILED'):
                self.play_next()
        elif isinstance(event, wavelink.TrackException):
            log.error(event.error)

    @property
    def guild(self):
        return self.bot.get_guild(self.guild_id)

    @property
    def voice_channel(self):
        guild = self.guild
        if guild is None:
            return None
        # Get the first voice channel where the bot user is in, default to None
        return next((vc for vc in guild.voice_channels
                     if guild.me in vc.members), None)

    @property
    def voice_channel_members(self):
        channel = self.voice_channel
        return () if channel is None else channel.members

    @property
    def entries(self):
        return list(self.queue)

    @property
    def current_requestor(self):
        guild = self.guild
        if self._requestor_id is None or guild is None:
            return None
        return guild.get_member(self._requestor_id)

    @property
    def is_playing(self):
        return self.is_connected and self.current is not None

    def play_next(self, skip=False):
        """Plays the next song. If a song is currently playing, it will be
        skipped.
        """
        # Avoid triggering the
        if self.is_playing:
            self.next_event.set()

    def enqueue(self, user, track):
        """Adds a single track to the queue from a given user."""
        return self.queue.put((user.id, track))

    def remove_entry(self, user, idx):
        """Removes a track from the player queue.

        If the provided user is not the one who requested the track. Raises
        Unauthorized.
        If the index is invalid, raises IndexError
        """
        user_id, track = self.queue[idx]
        if user.id != user_id:
            raise Unauthorized
        res = self.queue.remove(idx)
        assert res == (user_id, track)
        return res

    def clear_user(self, user):
        """Removes all of the user's enqueued tracks from the queue"""
        return self.queue.remove_all(user.id)

    def shuffle_user(self, user):
        """Shuffles all of the user's enqueued tracks from the queue"""
        return self.queue.shuffle(user.id)

    def vote_to_skip(self, user, threshold):
        """Adds a vote to skip the current song. If over the threshold it will
        skip the current song.

        Returns true if the song was skipped, false otherwise.
        """
        self.skip_votes.add(user.id)
        if self.current_requestor == user or len(self.skip_votes) > threshold:
            self.play_next(skip=True)
            return True
        return False

    def clear_vote(self, user):
        """Removes a vote to skip from the vote pool."""
        self.skip_votes.remove(user.id)

    async def stop(self):
        """Clears the queue and disconnects the voice client."""
        self.queue.clear()
        self.play_next()
        if self.queue_msg is not None:
            await self.queue_msg.stop()
        if self.np_msg is not None:
            await self.np_msg.stop()

    async def set_volume(self, volume):
        await super().set_volume(volume)
        music_config = (await self.get_music_config()) or proto.MusicConfig()
        music_config.volume = volume
        await self.set_music_config(music_config)

    async def create_queue_message(self, channel):
        return await self.__run_ui('queue_msg', MusicQueueUI, channel)

    async def create_now_playing_message(self, channel):
        return await self.__run_ui('np_msg', MusicNowPlayingUI, channel)

    async def __run_ui(self, attr, ui_type, channel):
        ui = getattr(self, attr)
        if ui is not None:
            await ui.stop()
        ui = ui_type(self)
        setattr(self, attr, ui)
        return await ui.run(channel)

class MusicPlayerUI(embed.MessageUI):

    def __init__(self, player):
        assert player is not None
        super().__init__(player.bot)
        self.player = player

class MusicNowPlayingUI(MusicPlayerUI):

    async def create_content(self):
        channel = self.player.voice_channel
        if channel is None or self.player.current is None:
            await self.stop()  # Nothing playing, stop here
            return ':notes: **Now Playing...**'
        return f':notes: **Now Playing in {channel.name}...**'

    async def create_embed(self):
        embed = discord.Embed()
        track = self.player.current
        if track is None:
            embed.title = 'No music playing'
            prefix = utils.STOP_EMOJI
            suffix = ''
            progress = 2.0  # At 200% progress, blank progress bar
            await self.stop()
        else:
            embed.title = track.title
            embed.url = track.uri
            prefix = (utils.PAUSE_EMOJI if self.player.paused
                      else utils.PLAY_EMOJI)
            suffix = (f'`[{utils.time_format(self.player.position)}/'
                      f'{utils.time_format(track.duration)}]`')
            progress = float(self.player.position) / float(track.duration)

        requestor = self.player.current_requestor
        if requestor is not None:
            avatar_url = (requestor.avatar_url or
                          requestor.default_avatar_url)
            name = f'{requestor.name}#{requestor.discriminator}'
            embed.set_author(name=name, icon_url=avatar_url)

        progress_bar = utils.progress_bar(progress, PROGRESS_BAR_WIDTH)
        embed.description = prefix + progress_bar + suffix + ":speaker:"
        return embed

class MusicQueueUI(MusicNowPlayingUI):

    def __init__(self, player):
        super().__init__(player)
        self.current_page = 0
        self.frozen_queue = list(self.player.queue)
        self.iterations_left = 60   # 5 minutes

        self.add_button(utils.PREV_PAGE_EMOJI, self.__next_page)
        self.add_button(utils.NEXT_PAGE_EMOJI, self.__prev_page)

    def __prev_page(self):
        self.current_page = max(self.current_page - 1, 0)

    def __next_page(self):
        queue_length = len(self.player.queue)
        page_count = math.ceil(queue_length / TRACKS_PER_PAGE)
        self.current_page = min(self.current_page + 1, page_count - 1)

    async def create_content(self):
        track = self.player.current
        if track is None or len(self.player.queue) <= 0:
            return await super().create_content()
        duration = utils.time_format(self.get_queue_duration())
        return (f'{utils.PLAY_EMOJI} **{track.title}**\n :notes: Current Queue'
                f' | {len(self.player.queue)} entries | `{duration}`')

    async def create_embed(self):
        queue_length = len(self.player.queue)
        if queue_length <= 0:
            return await super().create_embed()
        queue = list(self.player.queue)
        elem = []
        page_start = TRACKS_PER_PAGE * self.current_page
        page_end = page_start + TRACKS_PER_PAGE
        page_count = math.ceil(queue_length / TRACKS_PER_PAGE)
        idx = page_start + 1
        for requestor_id, track in queue[page_start:page_end]:
            duration = utils.time_format(track.duration)
            elem.append(f'`{idx}.` `[{duration}]` **{track.title}** - '
                        f'<@{requestor_id}>')
            idx += 1
        embed = discord.Embed(description='\n'.join(elem))
        if page_count > 1:
            embed.set_footer(text=f'Page {self.current_page + 1}/{page_count}')
        self.iterations_left -= 1
        if self.iterations_left <= 0:
            await self.stop()
        return embed

    def get_queue_duration(self):
        return sum(t.duration for r, t in self.frozen_queue)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
#author: wu.zheng midday.me

import os
import tensorflow as tf
import numpy as np
from dataset import data_factory
import model
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('--name',  help='an integer for the accumulator', )
parser.add_argument('--max_step', default=500000, help='max step for train')

def train():
  NUM_CLASS = data_factory.get_data_config(args.name)['num_class']
  CHECK_POINTS_PATH = data_factory.get_data_config(args.name)['check_points_path']
  train_model = model.UnetModel(NUM_CLASS, is_training=True )
  global_step = tf.train.get_or_create_global_step()
  update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
  saver = tf.train.Saver()
  with tf.control_dependencies(update_ops):
    loss_op = tf.train.AdamOptimizer(learning_rate=0.00001).minimize(train_model.loss, global_step=global_step)
    train_op = tf.group([loss_op, update_ops])
  tf.summary.scalar(name='seg_loss', tensor=train_model.seg_loss)
  tf.summary.scalar(name='aux_loss', tensor=train_model.aux_loss)
  tf.summary.scalar(name="loss", tensor=train_model.loss)
  tf.summary.scalar(name="acc", tensor=train_model.acc)
  merge_summary_op = tf.summary.merge_all()
  with tf.Session() as sess:
    ckpt = tf.train.latest_checkpoint(CHECK_POINTS_PATH)
    init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
    sess.run(init)
    if ckpt:
      st = int(ckpt.split("-")[-1])
      saver.restore(sess, ckpt)
      sess.run(global_step.assign(st))
      print("restore from %s"%(ckpt))
    summary_writer = tf.summary.FileWriter(CHECK_POINTS_PATH)
    summary_writer.add_graph(sess.graph)
    for batch_data in data_factory.get_data_iterator(args.name):
      if batch_data is None:
        print("Warning: batch_data is None")
        continue
      labels = np.array(batch_data[1])
      labels = np.expand_dims(labels, -1)
      images = np.array(batch_data[0])
      _, loss, _, acc, s, summary = sess.run([train_op, train_model.loss, train_model.acc_op, train_model.acc, global_step, merge_summary_op],
          feed_dict={train_model.image: images, train_model.label: labels})
      print("step:%d loss : %f acc: %f"%(s, loss , acc ))
      if s % 100 == 0:
        summary_writer.add_summary(summary=summary, global_step=s)
        saver.save(sess=sess, save_path=os.path.join(CHECK_POINTS_PATH, 'model'), global_step=s)
      if s > args.max_step:
        print("train finish")
        break

if __name__ == '__main__':
  args = parser.parse_args()
  train()


#Libraries

from crypto_trading import *
from pandas import read_csv
import matplotlib.pyplot as plt
import sys
import multiprocessing as mp
import numpy as np
import itertools
import pickle
from classifier_all import get_data

#Genetic
#from GA_optimization import *

coin_name = "eth"
df_price = read_csv('./backtesting/%s_price.csv'%(coin_name), header=0, index_col=0)
df_output = read_csv('./backtesting/%s_output.csv'%(coin_name), header=0, index_col=0)
start_row = 4970
end_row = 5000

# Start
start_investment = 100000
port = launch_backtesting(df_price,df_output,Portfolio(start_investment),0.01,100)
port.historical_positions['netto_profit'].sum()

##### PLOT

portfolio1 = port
all_signal = True

df_price.index = pd.to_datetime(df_price.index,unit='s')
portfolio1.signals_all.index = pd.to_datetime(portfolio1.signals_all.index,unit='s')
portfolio1.signals_taken.index = pd.to_datetime(portfolio1.signals_taken.index,unit='s')

if all_signal:
  #All signals
  buy_signal = portfolio1.signals_all[portfolio1.signals_all['buy'] == 1]['buy']
  sell_signal = portfolio1.signals_all[portfolio1.signals_all['sell'] == -1]['sell']
else:
  #Taken signals
  buy_signal = portfolio1.signals_taken[portfolio1.signals_all['buy'] == 1]['buy']
  sell_signal = portfolio1.signals_taken[portfolio1.signals_all['sell'] == -1]['sell']

plt.plot(buy_signal.index, df_price.ix[buy_signal.index]['Close'], '^', markersize=10, color='g',label='Buy')
plt.plot(sell_signal.index, df_price.ix[sell_signal.index]['Close'], 'v', markersize=10, color='r',label='Sell')

  #Price
plt.plot(df_price[24:48].index, df_price[24:48]['Close'], label='Bitcoin')

plt.xlabel('Date')
plt.ylabel('Price (USD)')
plt.legend(loc=0)
plt.show()

##### END PLOT


import cv2

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # utilizar la wecam

# para utilizar el mdodelo que genera el soft
majinBooClassif = cv2.CascadeClassifier(
    'C:/Users/Usuario/Desktop/proyectos python/IArecognizer/classifier/cascade.xml')

while True:

    ret, frame = cap.read()
    img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    toy = majinBooClassif.detectMultiScale(img_gray, scaleFactor=9, minNeighbors=91, minSize=(
        50, 50))  # se convierte la imagen en escala de gris y se guarda en variable toy

    for (x, y, w, h) in toy:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0),
                      2)  # dibujar el rectangulo
        cv2.putText(frame, 'Benjamin', (x, y-10), 2, 0.7, (0, 255, 0),
                    2, cv2.LINE_AA)  # colocar el nombre del objeto

    cv2.imshow('frame', frame)

    if cv2.waitKey(1) == 27:
        break

cap.release()
cv2.destroyAllWindows()


# coding=utf-8
import json
from flask import render_template, redirect, request, url_for, flash
from flask_login import current_user, login_user, logout_user, login_required
from nectar.template import templated
from nectar import db
from nectar.models import User
from nectar import db
from forms import WifiQueryForm
from jester import Jester
from . import takeout

jester = Jester()

header = [u'SSID', u'BSSID', u'密码', u'加密方式', u'商户id', u'商户名称', u'省份', u'城市', u'经纬度']
security_map = [u'开放网络', u'WEP', u'WPA', u'EAP']

def refine_result(result):
    new = []
    for ap in result:
        tmp = {}
        lon, lat = 0.0, 0.0
        for k, v in ap.items():
            if k == 'ssid':
                tmp[u'SSID'] = v
            elif k == 'bssid':
                tmp[u'BSSID'] = v
            elif k == 'password':
                tmp[u'密码'] = v[:3] + len(v[:3]) * '*' if v else '-'
            elif k == 'security':
                tmp[u'加密方式'] = security_map[int(v)]
            elif k == 'shop_id':
                tmp[u'商户id'] = v if v > 0 else '-'
            elif k == 'shop_name':
                tmp[u'商户名称'] = v if v else '-'
            elif k == 'lon':
                lon = v
            elif k == 'lat':
                lat = v
            elif k == 'province':
                tmp[u'省份'] = v if v else '-'
            elif k == 'city':
                tmp[u'城市'] = v if v else '-'
            else:
                tmp[k] = v
            # 格式化经纬度
            if lon and lat:
                tmp[u'经纬度'] = '({0}, {1})'.format(lon, lat)
            else:
                tmp[u'经纬度'] = '-'
        new.append(tmp)
    return new

@takeout.route('/wifi', methods=['GET', 'POST'])
@templated('takeout/wifi.html')
def wifi():
    form = WifiQueryForm()
    if form.validate_on_submit():
        resp = jester.query(form.ssid.data)
        resultSet = refine_result(resp['result'])
        return dict(form=form, resultSet=resultSet, header=header)
    flash('无效的SSID')
    return dict(form=form)


from __future__ import absolute_import, unicode_literals

import os
from celery import Celery

# from components.models import Messages, Profile

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'whatsapp_auto.settings')

app = Celery('whatsapp_auto')

app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {}'.format(self.request))

if __name__ == '__main__':
    app.start()


'''
Single Layer Perceptron
Author: Yuya Jeremy Ong (yuyajeremyong@gmail.com)
'''
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F

class SLP(nn.Module):
    def __init__(self, input_shape, output_shape, hidden_shape=40, device=torch.device('cpu')):
        super(SLP, self).__init__()

        self.device = device
        self.input_shape = input_shape[0]
        self.hidden_shape = hidden_shape
        self.output_shape = output_shape

        self.linear = nn.Linear(self.input_shape, self.hidden_shape)
        self.out = nn.Linear(self.hidden_shape, self.output_shape)

    def forward(self, x):
        x = torch.from_numpy(x).float().to(self.device)
        x = F.relu(self.linear(x))
        x = self.out(x)

        return x


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

import io
import mock
import os

import charms_openstack.test_utils as test_utils

import charms.ovn_charm as ovn_charm

class TestOVNConfigProperties(test_utils.PatchHelper):

    def test_ovn_key(self):
        self.assertEquals(ovn_charm.ovn_key(None),
                          os.path.join(ovn_charm.OVS_ETCDIR, 'key_host'))

    def test_ovn_cert(self):
        self.assertEquals(ovn_charm.ovn_cert(None),
                          os.path.join(ovn_charm.OVS_ETCDIR, 'cert_host'))

    def test_ovn_ca_cert(self):
        cls = mock.MagicMock()
        cls.charm_instance.name = mock.PropertyMock().return_value = 'name'
        self.assertEquals(ovn_charm.ovn_ca_cert(cls),
                          os.path.join(ovn_charm.OVS_ETCDIR, 'name.crt'))

class Helper(test_utils.PatchHelper):

    def setUp(self):
        super().setUp()
        self.patch_release(ovn_charm.BaseOVNChassisCharm.release)
        self.patch_object(ovn_charm.reactive, 'is_flag_set',
                          return_value=False)
        self.patch_object(
            ovn_charm.charms_openstack.adapters, '_custom_config_properties')
        self._custom_config_properties.side_effect = {}
        self.target = ovn_charm.BaseOVNChassisCharm()
        # remove the 'is_flag_set' patch so the tests can use it
        self._patches['is_flag_set'].stop()
        setattr(self, 'is_flag_set', None)
        del(self._patches['is_flag_set'])
        del(self._patches_start['is_flag_set'])

    def patch_target(self, attr, return_value=None):
        mocked = mock.patch.object(self.target, attr)
        self._patches[attr] = mocked
        started = mocked.start()
        started.return_value = return_value
        self._patches_start[attr] = started
        setattr(self, attr, started)

class TestOVNChassisCharm(Helper):

    def test_optional_openstack_metadata(self):
        self.assertEquals(self.target.packages, ['ovn-host'])
        self.assertEquals(self.target.services, ['ovn-host'])
        self.patch_object(
            ovn_charm.charms_openstack.adapters, '_custom_config_properties')
        self._custom_config_properties.side_effect = {}
        self.patch_object(ovn_charm.reactive, 'is_flag_set',
                          return_value=True)
        c = ovn_charm.BaseOVNChassisCharm()
        self.assertEquals(c.packages, [
            'ovn-host', 'networking-ovn-metadata-agent', 'haproxy'
        ])
        self.assertEquals(c.services, [
            'ovn-host', 'networking-ovn-metadata-agent'])

    def test_run(self):
        self.patch_object(ovn_charm.subprocess, 'run')
        self.patch_object(ovn_charm.ch_core.hookenv, 'log')
        self.target.run('some', 'args')
        self.run.assert_called_once_with(
            ('some', 'args'),
            stdout=ovn_charm.subprocess.PIPE,
            stderr=ovn_charm.subprocess.STDOUT,
            check=True,
            universal_newlines=True)

    def test_configure_tls(self):
        self.patch_target('get_certs_and_keys')
        self.get_certs_and_keys.return_value = [{
            'cert': 'fakecert',
            'key': 'fakekey',
            'cn': 'fakecn',
            'ca': 'fakeca',
            'chain': 'fakechain',
        }]
        with mock.patch('builtins.open', create=True) as mocked_open:
            mocked_file = mock.MagicMock(spec=io.FileIO)
            mocked_open.return_value = mocked_file
            self.target.configure_cert = mock.MagicMock()
            self.target.run = mock.MagicMock()
            self.target.configure_tls()
            mocked_open.assert_called_once_with(
                '/etc/openvswitch/charmname.crt', 'w')
            mocked_file.__enter__().write.assert_called_once_with(
                'fakeca\nfakechain')
            self.target.configure_cert.assert_called_once_with(
                ovn_charm.OVS_ETCDIR,
                'fakecert',
                'fakekey',
                cn='host')

    def test_configure_ovs(self):
        self.patch_target('run')
        self.patch_target('restart_all')
        self.patch_object(ovn_charm, 'ovn_key')
        self.patch_object(ovn_charm, 'ovn_cert')
        self.patch_object(ovn_charm, 'ovn_ca_cert')
        ovsdb_interface = mock.MagicMock()
        db_sb_connection_strs = mock.PropertyMock().return_value = ['dbsbconn']
        ovsdb_interface.db_sb_connection_strs = db_sb_connection_strs
        cluster_local_addr = mock.PropertyMock().return_value = (
            'cluster_local_addr')
        ovsdb_interface.cluster_local_addr = cluster_local_addr
        self.target.configure_ovs(ovsdb_interface)
        self.run.assert_has_calls([
            mock.call('ovs-vsctl', 'set-ssl', mock.ANY, mock.ANY, mock.ANY),
            mock.call('ovs-vsctl', 'set', 'open', '.',
                      'external-ids:ovn-encap-type=geneve', '--',
                      'set', 'open', '.',
                      'external-ids:ovn-encap-ip=cluster_local_addr', '--',
                      'set', 'open', '.',
                      'external-ids:system-id=cluster_local_addr'),
            mock.call('ovs-vsctl', 'set', 'open', '.',
                      'external-ids:ovn-remote=dbsbconn'),
        ])
        self.run.reset_mock()
        self.target.enable_openstack = True
        self.patch_object(ovn_charm.ovn, 'SimpleOVSDB')
        managers = mock.MagicMock()
        self.SimpleOVSDB.return_value = managers
        self.target.configure_ovs(ovsdb_interface)
        managers.find.assert_called_once_with(
            'target="ptcp:6640:127.0.0.1"')
        self.run.assert_has_calls([
            mock.call('ovs-vsctl', 'set-ssl', mock.ANY, mock.ANY, mock.ANY),
            mock.call('ovs-vsctl', 'set', 'open', '.',
                      'external-ids:ovn-encap-type=geneve', '--',
                      'set', 'open', '.',
                      'external-ids:ovn-encap-ip=cluster_local_addr', '--',
                      'set', 'open', '.',
                      'external-ids:system-id=cluster_local_addr'),
            mock.call('ovs-vsctl', 'set', 'open', '.',
                      'external-ids:ovn-remote=dbsbconn'),
            mock.call('ovs-vsctl', '--id', '@manager',
                      'create', 'Manager', 'target="ptcp:6640:127.0.0.1"',
                      '--', 'add', 'Open_vSwitch', '.', 'manager_options',
                      '@manager'),
        ])

    def test_configure_bridges(self):
        self.patch_object(ovn_charm.os_context, 'NeutronPortContext')
        npc = mock.MagicMock()

        def _fake_resolve_ports(mac_or_if):
            result = []
            for entry in mac_or_if:
                if ':' in entry:
                    result.append('eth0')
                    continue
                result.append(entry)
            return result

        npc.resolve_ports.side_effect = _fake_resolve_ports
        self.NeutronPortContext.return_value = npc
        self.patch_target('config')
        self.config.__getitem__.side_effect = [
            '00:01:02:03:04:05:br-provider eth5:br-other',
            'provider:br-provider other:br-other']
        self.patch_object(ovn_charm.ovn, 'SimpleOVSDB')
        bridges = mock.MagicMock()
        bridges.find.side_effect = [
            [
                {'name': 'delete-bridge'},
                {'name': 'br-other'}
            ],
            StopIteration,
        ]
        ports = mock.MagicMock()
        ports.find.side_effect = [[{'name': 'delete-port'}]]
        opvs = mock.MagicMock()
        self.SimpleOVSDB.side_effect = [bridges, ports, opvs]
        self.patch_object(ovn_charm.ovn, 'del_br')
        self.patch_object(ovn_charm.ovn, 'del_port')
        self.patch_object(ovn_charm.ovn, 'add_br')
        self.patch_object(ovn_charm.ovn, 'list_ports')
        self.list_ports().__iter__.return_value = []
        self.patch_object(ovn_charm.ovn, 'add_port')
        self.target.configure_bridges()
        npc.resolve_ports.assert_has_calls([
            mock.call(['00:01:02:03:04:05']),
            mock.call(['eth5']),
        ], any_order=True)
        bridges.find.assert_has_calls([
            mock.call('name=br-provider'),
            mock.call('name=br-other'),
        ], any_order=True)
        self.del_br.assert_called_once_with('delete-bridge')
        self.del_port.assert_called_once_with('br-other', 'delete-port')
        self.add_br.assert_has_calls([
            mock.call('br-provider', ('charm-ovn-chassis', 'managed')),
            mock.call('br-other', ('charm-ovn-chassis', 'managed')),
        ], any_order=True)
        self.add_port.assert_has_calls([
            mock.call(
                'br-provider', 'eth0', ('charm-ovn-chassis', 'br-provider')),
            mock.call(
                'br-other', 'eth5', ('charm-ovn-chassis', 'br-other')),
        ], any_order=True)
        opvs.set.assert_has_calls([
            mock.call('.', 'external_ids:ovn-bridge-mappings',
                      'other:br-other,provider:br-provider'),
            mock.call('.', 'external_ids:ovn-cms-options',
                      'enable-chassis-as-gw'),
        ])


import attr
import requests
from requests.auth import HTTPBasicAuth

from config import logger
from config.exceptions import RequestFailedException, RequestTokenException

@attr.s(slots=True)
class OAuth2:
    access_token_uri = attr.ib(type=str, validator=attr.validators.instance_of(str))
    client_id = attr.ib(type=str, validator=attr.validators.instance_of(str))
    client_secret = attr.ib(type=str, validator=attr.validators.instance_of(str))
    grant_type = attr.ib(
        type=str,
        default="client_credentials",
        validator=attr.validators.instance_of(str),
    )
    _token = attr.ib(type=str, default="", validator=attr.validators.instance_of(str))

    @property
    def token(self) -> str:
        return self._token

    @property
    def authorization_header(self) -> dict:
        return {"Authorization": f"Bearer {self._token}"}

    def request_token(self, client_auth: HTTPBasicAuth, data: dict) -> None:
        try:
            response = requests.post(self.access_token_uri, auth=client_auth, data=data)
            if response.ok:
                self._token = response.json().get("access_token")
                logger.info("Access token successfully obtained.")
                logger.debug(f"access_token: {self._token}")
            else:
                raise RequestTokenException(
                    "Failed to retrieve oauth2 access_token. "
                    f"HTTP Response code: {response.status_code}."
                )
        except requests.exceptions.MissingSchema as err:
            logger.error(err)
            raise RequestFailedException("Access token URI it's empty")

    def configure(self) -> None:
        client_auth = HTTPBasicAuth(self.client_id, self.client_secret)
        data = {"grant_type": f"{self.grant_type}"}
        self.request_token(client_auth, data)


import scannerpy
import cv2
import numpy as np
from scannerpy import Database, DeviceType, Job, ColumnType, FrameType
from scannerpy.stdlib import pipelines

import subprocess
from os.path import join
import numpy as np
import glob
import os

import argparse

parser = argparse.ArgumentParser(description='Depth estimation using Stacked Hourglass')
parser.add_argument('--path_to_data', default='/home/krematas/Mountpoints/grail/data/barcelona/')
parser.add_argument('--visualize', action='store_true')
opt, _ = parser.parse_known_args()

dataset = opt.path_to_data
image_files = glob.glob(join(dataset, 'players', 'images', '*.jpg'))
image_files.sort()
image_files = image_files[:10]

mask_files = glob.glob(join(dataset, 'players', 'poseimgs', '*.png'))
mask_files.sort()
mask_files = mask_files[:10]

db = Database()

cwd = os.path.dirname(os.path.abspath(__file__))
if not os.path.isfile(os.path.join(cwd, 'segment_op/build/libsegment_op.so')):
    print(
        'You need to build the custom op first: \n'
        '$ pushd {}/segment_op; mkdir build && cd build; cmake ..; make; popd'.
        format(cwd))
    exit()

# To load a custom op into the Scanner runtime, we use db.load_op to open the
# shared library we compiled. If the op takes arguments, it also optionally
# takes a path to the generated python file for the arg protobuf.
db.load_op(
    os.path.join(cwd, 'segment_op/build/libsegment_op.so'),
    os.path.join(cwd, 'segment_op/build/segment_pb2.py'))

encoded_image = db.sources.Files()
frame = db.ops.ImageDecoder(img=encoded_image)

encoded_mask = db.sources.Files()
mask_frame = db.ops.ImageDecoder(img=encoded_mask)

my_segment_imageset_class = db.ops.MySegment(frame=frame, mask=mask_frame, w=128, h=128, sigma1=1.0, sigma2=0.01)
output_op = db.sinks.FrameColumn(columns={'frame': my_segment_imageset_class})

job = Job(
    op_args={
        encoded_image: {'paths': image_files},
        encoded_mask: {'paths': mask_files},

        output_op: 'example_resized',
    })
[out_table] = db.run(output_op, [job], force=True)
out_table.column('frame').save_mp4(join(dataset, 'players', 'instance_segm.mp4'))


import random
import sqlite3

def generador(a, b):

    cadena = random.randrange(a, b)
    return cadena

#Dificultad
def inicio():
    nivel = None

    while nivel != "1" and nivel != "2" and nivel != "3":
        print("Escriba '1' Para el primer nivel (3 digitos)")
        print("Escriba '2' Para el segundo nivel (4 digitos)")
        print("Escriba '3' Para el tercer nivel (5 digitos)")
        nivel = input("Escoja el nivel de dificultad: ")
        if nivel != "1" and nivel != "2" and nivel != "3":
            print("Por favor ingrese una de las tres opciones.")

    if nivel == "1":
        vidas = 10
        nrand1 = 100
        nrand2 = 999
    elif nivel == "2":
        vidas = 7
        nrand1 = 1000
        nrand2 = 9999
    elif nivel == "3":
        vidas = 5
        nrand1 = 10000
        nrand2 = 99999

    return nrand1, nrand2, vidas, nivel

def comparacion(numgen, v, niv):
    listum = []
    lisnumgen = []
    num = input("Escriba el numero que piense que se genero: ")
    strnumgen = str(numgen)
    for i in num:
        listum.append(i)
    for n in strnumgen:
        lisnumgen.append(n)

    #Comparar digito por digito
    for j in range(len(num)):
        for k in range(len(strnumgen)):
            if num[j] == strnumgen[j] and j == k:
                print("has acertado el numero: {} en la posición {}".format(strnumgen[j], j + 1))
                v += 1
    if listum == lisnumgen:
        print("Has adivinado el numero!")

        score(niv, v, numgen)

        input()
        exit()
    else:
        descontar_vidas(v)

    return listum

def descontar_vidas(v):
    print("\nTe quedan {} vidas".format(v))
    if v == 0:
        print("Perdiste :(")
        quit()

def score(niv, vid, cod):
    db = sqlite3.connect("HighScore.db")
    cursor = db.cursor()

    nom = input("¡Felicidades! Ingrese su apodo: ")

    cursor.execute("INSERT INTO 'Nivel {}' VALUES ('{}', {}, {})".format(niv, nom, vid, cod))

    #CREADOR DE TABLAS EN SQLITE3, NO USAR
    #cursor.execute("CREATE TABLE 'Nivel 1' ('Apodo' TEXT, 'Vidas' INTEGER, 'Numero' INTEGER)")
    #cursor.execute("CREATE TABLE 'Nivel 2' ('Apodo' TEXT, 'Vidas' INTEGER, 'Numero' INTEGER)")
    #cursor.execute("CREATE TABLE 'Nivel 3' ('Apodo' TEXT, 'Vidas' INTEGER, 'Numero' INTEGER)")

    cursor.execute("SELECT * FROM 'Nivel {}' ORDER BY 2 DESC".format(niv))
    scores = cursor.fetchall()

    print("\nHigh Score table")
    print()

    cont = 0

    for users in scores:
        if cont < 5:
            print(users)
            cont += 1

    db.commit()
    db.close()

print("¡Bienvenidos a Master Mind!")
print("El objetivo del juego es sencillo, un numero sera generado aleatoriamente según el nivel de dificultad que escoja.\nSe le pedirá ingresar un numero y si corresponde el mismo numero en el lugar exacto al numero generado se le mostrata un mensaje de acierto.\nUna vez que acierte todos los numeros ¡ganara!\n")

n1, n2, vida, nivel = inicio()
ngenerado = generador(n1, n2)
while ngenerado != comparacion:
    vida -= 1

    comparacion(ngenerado, vida, nivel)


# all code from [3]
import sqlite3 # Standard Python Library

def connect_db():
    db = sqlite3.connect('database.db') # Create/connect to database Requires elevated privalges to run (ie from cmd/terminal or pycharm running as admin)
    db.cursor().execute('CREATE TABLE IF NOT EXISTS comments ' # Create table comments with int ID (Primary Key) and comment text attributes
                        '(id INTEGER PRIMARY KEY, '
                        'comment TEXT)')
    db.commit() # Commit changes
    return db

def add_comment(comment):
    db = connect_db() # Connect to DB
    db.cursor().execute('INSERT INTO comments (comment) ' # Insert comment with passed in variable
                        'VALUES (?)', (comment,))
    db.commit() # Commit changes

def get_comments(search_query=None):
    db = connect_db() # Connect to DB
    results = [] # Initialise results list
    get_all_query = 'SELECT comment FROM comments' # Get all comments
    for (comment,) in db.cursor().execute(get_all_query).fetchall(): # Append get_all_query output to results list.
        if search_query is None or search_query in comment:
            results.append(comment)
    return results


from flask import Flask, jsonify, request
from flask_restful import Resource, Api
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.applications.xception import Xception
from keras.models import load_model
from pickle import load
import numpy as np
from PIL import Image

app = Flask(__name__)
api = Api(app)

class Caption:
    def __init__(self):
        self.__tokenizer = load(open("tokenizer.p", "rb"))
        self.__model = load_model('models/final.h5')
        self.__xception_model = Xception(include_top=False, pooling="avg")
        self.__max_length = 32

    def startChain(self, image_path):
        self.__filename = image_path
        self.__photo = self.extract_features()
        self.__desc = self.generate_desc()

    def extract_features(self):
        try:
            image = Image.open(self.__filename)

        except:
            print(
                "ERROR: Couldn't open image! Make sure the image path and extension is correct")
        image = image.resize((299, 299))
        image = np.array(image)
        # for images that has 4 channels, we convert them into 3 channels
        if image.shape[2] == 4:
            image = image[..., :3]
        image = np.expand_dims(image, axis=0)
        image = image/127.5
        image = image - 1.0
        feature = self.__xception_model.predict(image)
        return feature

    def word_for_id(self, integer, tokenizer):
        for word, index in tokenizer.word_index.items():
            if index == integer:
                return word
        return None

    def generate_desc(self):
        in_text = 'start'
        for i in range(self.__max_length):
            sequence = self.__tokenizer.texts_to_sequences([in_text])[0]
            sequence = pad_sequences([sequence], maxlen=self.__max_length)
            pred = self.__model.predict([self.__photo, sequence], verbose=0)
            pred = np.argmax(pred)
            word = self.word_for_id(pred, self.__tokenizer)
            if word is None:
                break
            in_text += ' ' + word
            if word == 'end':
                break
        return in_text

    def ret_desc(self):
        return self.__desc

caption_img = Caption()

class HelloWorld(Resource):
    def post(self):
        obj = request.get_json(silent=True)
        # print("\n\n\n" + obj + "\n\n\n")
        if obj["image"]:
            caption_img.startChain(obj["image"])
            json = {"description": caption_img.ret_desc()}
            return jsonify(json)
        else:
            json = {'status': "failed"}
            return jsonify(json)

    def get(self):
        global caption_img
        caption_img.startChain(
            "/home/senear/github/Electron/ImgCaption/backend/foo.jpg")

        json = {"description": caption_img.ret_desc()}
        return jsonify(json)

api.add_resource(HelloWorld, '/api')

if __name__ == '__main__':
    app.run(debug=True)