'''
Author: Blank-vax 15554467517@163.com
Date: 2023-01-30 01:18:07
LastEditors: Blank-vax 15554467517@163.com
LastEditTime: 2023-01-30 11:44:14
FilePath: /FTCR-LMPPDA_Simulation/Multidimensional-Transformation-Comparison-Python/dataInsert.py
Description: Efficiency evaluation for data embedding and data extraction operations
'''

import random
import math
from line_profiler import LineProfiler

# Paramerters generation for evaluation
def paramsGeneration():
    smNumber = 20
    dimensionAccount = 10
    dataUpperBound = 7
    maxBits = math.ceil(math.log2(smNumber))+dataUpperBound
    # maxBits = 12
    return (smNumber, dimensionAccount, dataUpperBound, maxBits)

# Random original data generation for evaluation
def dataGeneration(dimensionAccount):
    originDataInSmartMeter = []
    for i in range(dimensionAccount):
        originDataInSmartMeter.append(random.getrandbits(7))
    # Print the original data collected by smart meters
    for i in range(dimensionAccount):
        print(originDataInSmartMeter[i], end = " ")
    return originDataInSmartMeter

# Data embedding process
def dataInsertDP(maxBits, dimensionAccount, originDataInSmartMeter):
    transformedResult = 0
    for index in range(dimensionAccount):
        # Convert decimal data to binary data
        binaryString = bin(originDataInSmartMeter[index])[2:]
        # Binary cascade
        binaryString += "0"*(maxBits*(index))
        # Decimal data recovery
        transformedResult += int(binaryString, 2)
    return transformedResult

# Data extraction process
def dataInsertDR(aggregatedResult, dimensionAccount, maxBits):
    multidimensionAggregatedDataList = []
    # Binary coding
    binaryString = bin(aggregatedResult)[2:]
    # Iteration from low to high
    for index in range(dimensionAccount):
        theta1 = maxBits*(index+1)
        theta2 = maxBits*index
        # Intercept binary data in the corresponding location
        blockedBinaryString = binaryString[theta2: theta1-1]
        # Transformed to decimal data
        multidimensionAggregatedDataList.append(int(blockedBinaryString, 2))
    return multidimensionAggregatedDataList

def main():
    # Parameters generation
    smNumber, dimensionAccount, dataUpperBound, maxBits = paramsGeneration()
    # Generation of smNumber and perform data transformation for original data
    aggregatedResult = 0
    for i in range(smNumber):
        # Generation of original data
        print("Smart Meter " + str(i+1))
        originDataInSmartMeter = dataGeneration(dimensionAccount=dimensionAccount)
        print("\n")
        # Perform data embedding
        transformedResult = dataInsertDP(maxBits=maxBits, dimensionAccount=dimensionAccount, originDataInSmartMeter=originDataInSmartMeter)
        # Perform addition operations for data of single dimention
        aggregatedResult += transformedResult
    # Data extraction of embedded data
    aggregatedMultidimensinDataList = dataInsertDR(aggregatedResult=aggregatedResult, dimensionAccount=dimensionAccount, maxBits=maxBits)
    # Print aggregation result
    for i in range(dimensionAccount):
        print(aggregatedMultidimensinDataList[i])

if __name__ == "__main__":

    lp = LineProfiler()

    lp.add_function(dataInsertDP)
    lp.add_function(dataInsertDR)

    test_func = lp(main)
    test_func()
    lp.print_stats()


import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

def caesarCipherAuth(request):

  if request.method == 'OPTIONS':
    headers = {
           'Access-Control-Allow-Origin': '*',
           'Access-Control-Allow-Methods': '*',
          'Access-Control-Allow-Headers': '*',
          'Access-Control-Max-Age': '3600'
      }
    return ('', 204, headers)

  cipherData = request.get_json()

  if not firebase_admin._apps:
    cred = credentials.Certificate("key.json")
    default_app = firebase_admin.initialize_app(cred)

  db = firestore.client()
  doc_ref = db.collection('users').document(cipherData["customerId"])
  doc = doc_ref.get()
  doc = doc.to_dict()

  result = ""
  response={
        "state": False
      }
  for i in range(len(cipherData["text"])):
    letter = cipherData["text"][i]
    result+=chr((ord(letter)+doc["key"] -97) % 26 +97)
    if(result == cipherData["decoded"]):
      response["state"]= True

  headers = {
     'Access-Control-Allow-Origin': '*'
  }
  return (response,200,headers)


from Report import Report

class ProjectImplementationReviewTableReportFactory(object):

    def __init__(self, context, **kw):
        self.context = context
        self.params = kw

    def getReport(self):
        # create and fill the report
        name = "Project Implementation Review Table Report"
        report = Report(name)
        report.setReportHeaders(( name,),)
        report.setTableHeaders(((
            'GEF ID',
            'IMIS No.',
            'Implementing Agency(ies)',
            'Focal Area',
            'Geographic Scope',
            'Region',
            'Country(ies)',
            'Project Title',
            'First Disbursement [date m/d/yyyy]',
            'Closure expected [date m/d/yyyy]',
            'Actual / Revised Closing [date m/d/yyyy]',
            'Project Type',
            'PDF Funding (if any) US$ m',
            'GEF grant US$ m',
            'Total GEF Grant (US$ m) =PDF + grant',
            'Expected Co-financing (US$ m)',
            'Total Project Cost ($m) =total GEF grant + co-financing',
            'Overall DO rating',
            'Overall IP rating',
            'Overall Risk rating',
            'Total GEF disbursement as of June 30, [year] ($m)',
            'Evaluation type',
            'Evaluation date',
            'Overall evaluation rating',
            ),))
        # XXX Implement this
        # report.setTableRows()
        # report.setTableTotals([])
        # report.setReportFooters()
        return report


#!/usr/bin/python3
import sys

class Day03:
    """
    Solution for https://adventofcode.com/2022/day/3
    """

    def __init__(self) -> None:
        """
        Constructor
        """
        self._input: list = None

    def read_input(self) -> None:
        """
        Read input from stdin and parse it into a useful data structure
        In this case, each line contains a bunch of characters
        Each character represents a type of item
        """
        raw_input = sys.stdin.read()

        self._input = raw_input.split('\n')
        self._input = self._input[0:-1]

    def _find_common_component_in_rucksack(self, rucksack: str) -> str:
        """
        Divide the rucksack into halves (left, right)
        Find the items that appear in both halves
        """
        left: str = rucksack[:int(len(rucksack)/2)]
        right: str = rucksack[int(len(rucksack)/2):]

        # Intersection of sets
        common_component_set: set = set(left) & set(right)
        return list(common_component_set)[0]

    def _calculate_item_priority(self, component: str) -> int:
        """
        Calculate the priority of an item as follows:
        a-z is 1-26, respectively
        A-Z is 27-52, respectively
        """
        if component.isupper():
            return ord(component) - 38
        return ord(component) - 96

    def part_one(self) -> int:
        """
        Return the sum of the priorities of the common components of each individual rucksack
        """
        total_priority: int = 0
        for rucksack in self._input:
            common_component: str = self._find_common_component_in_rucksack(rucksack)
            priority: int = self._calculate_item_priority(common_component)
            total_priority += priority

        return total_priority

    def part_two(self) -> int:
        """
        Return the sum of the priorities of the common components across each group of 3 rucksacks
        """
        total_priority: int = 0
        for i in range(0, len(self._input), 3):
            # Intersection of sets
            common_component_set: set = set(self._input[i]) & set(self._input[i+1]) & set(self._input[i+2])
            common_component: str = list(common_component_set)[0]
            priority: int = self._calculate_item_priority(common_component)
            total_priority += priority

        return total_priority

def main() -> None:
    """
    Main
    """
    solver = Day03()
    solver.read_input()

    print(f'Part 1: {solver.part_one()}')
    print(f'Part 2: {solver.part_two()}')

if __name__ == '__main__':
    main()


from rest_framework import pagination
from rest_framework.pagination import InvalidPage
from rest_framework.exceptions import NotFound
from rest_framework.response import Response

import six

__all__ = ('CustomPageNumberPagination',)

class CustomPageNumberPagination(pagination.PageNumberPagination):
    """Custom page number pagination."""

    page_size = 30
    max_page_size = 10000
    page_size_query_param = 'page_size'

    def paginate_queryset(self, queryset, request, view=None):
        """
        Paginate a queryset if required, either returning a
        page object, or `None` if pagination is not configured for this view.
        """
        #
        page_size = self.get_page_size(request)
        if not page_size:
            return None

        paginator = self.django_paginator_class(queryset, page_size)
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = paginator.num_pages

        try:
            self.page = paginator.page(page_number)
        except InvalidPage as exc:
            msg = self.invalid_page_message.format(
                page_number=page_number, message=six.text_type(exc)
            )
            raise NotFound(msg)

        if paginator.num_pages > 1 and self.template is not None:
            # The browsable API should display pagination controls.
            self.display_page_controls = True

        self.request = request
        return list(self.page.object_list)

    def get_paginated_response(self, data, extra_content=None):
        self.__data = data

        content = {}

        if extra_content and isinstance(extra_content, dict):
            content.update(extra_content)

        content.update({
            'count': self.page.paginator.count,
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'current_page': int(self.request.query_params.get('page', 1)),
            'page_size': self.get_page_size(self.request),
            'results': data,
        })

        return Response(content)


def draw(self, widget, cr):
        '''
        Draw just the exposed part of the backing store, scaled to fit
        '''
        if self.bot_size is None:
            # No bot to draw yet.
            self.draw_default_image(cr)
            return

        cr = driver.ensure_pycairo_context(cr)

        surface = self.backing_store.surface
        cr.set_source_surface(surface)
        cr.paint()


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

# # Fed-Learning in Wireless Environment
# 此函数用于构造所需数据集，并计算P(x)
# ## Import Libraries

# In[1]:

import pandas as pd
import numpy as np
from sklearn import svm, metrics
import math
import matplotlib.pyplot as plt

if __name__ == '__main__':
    # 用户数据集大小和标签种类
    num_img = [600, 600, 600, 600, 600]
    #num_img = [1000, 600, 600, 400, 400]
    num_label = [1, 1, 1, 1, 8]

    X_train_user , y_train_user = [], []

    option = ['balance', 'unbalance']
    myoption = int(input("Enter the value for option(balance:0 unbalance:1): "))
    if myoption == 0:
        label = option[0]
    else:
        label = option[1]

    csv_path_train_data = 'csv/training_image.csv'
    X_all_train = pd.read_csv(csv_path_train_data, header=None)
    X_all_train = X_all_train.values

    csv_path_train_data = 'csv/training_label.csv'
    y_all_train = pd.read_csv(csv_path_train_data, header=None)
    y_all_train = y_all_train.values
    y_lable = []
    for k in range(len(num_img)):
        csv_path_train_data = 'user_csv/index/' + 'user' + str(k) + 'train_index_' + label + '.csv'
        train_index = pd.read_csv(csv_path_train_data, header=None)

        # 修剪数据集使得只有图片和标签,把序号剔除
        train_index = train_index.values
        train_index = train_index.T[0].astype(int)
        X_train_user.append(X_all_train[train_index, :])
        y_train_user.append(y_all_train[train_index])
        y_lable.append(set(y_train_user[k].flatten()))

    Px_all = np.zeros((1, X_all_train.shape[1]))
    Px_user = np.zeros((5, X_all_train.shape[1]))

    Px_all_gray = np.arange(784)
    Px_user_gray = {i: np.arange(784) for i in range(len(X_train_user))}
    for gray in range(256):
        for i in range(X_all_train.shape[1]):
            Px_all[0, i] = np.sum(X_all_train[:, i] == gray)
            Px_all[0, i] = Px_all[0, i] / 60000.0
            for j in range(len(X_train_user)):
                temp = X_train_user[j]
                Px_user[j, i] = np.sum(temp[:, i] == gray)
                Px_user[j, i] = 1.0 * Px_user[j, i] / len(temp[:, 0])
        for j in range(len(X_train_user)):
            Px_user_gray[j] = np.vstack((Px_user_gray[j], Px_user[j, :]))
        Px_all_gray = np.vstack((Px_all_gray, Px_all))

    Px_all_gray = Px_all_gray[1:, :]
    D_distribution = []
    D = []
    for idx in range(len(X_train_user)):
        Px = Px_user_gray[idx][1:, :]
        diff = Px_all_gray - Px
        diff = diff/255.0
        D_distribution.append(np.linalg.norm(diff, ord=1))
        temp = np.linalg.norm(diff, ord=2, axis=0)
        D.append(np.linalg.norm(temp, ord=1))

    print(D_distribution)
    print(D)
    print(y_lable)

    # compute Ld
    mu = 3.5169
    sigma = 0.2405
    Lm = []
    Ld = []
    for i in range(len(num_img)):
        Lm.append(1 / (4 * sigma ** 2 / num_img[i] + 2 * (mu * D[i]) ** 2))
        print(1/Lm[i])
    for i in range(len(num_img)):
        Ld.append(Lm[i] / (sum(Lm)))
    print(Ld)


"""Collection of functions for the SVM-based player"""

from minmaxsearch import *

import random
import json
import pickle

def board_to_inputs(board):
    """Convert a board to an 'input vector' list for the SVM
    Includes 1s and 0s for presence or absence of each piece for each player for each location, as well
    as total counts of each type of piece for each player"""

    players = [1, 2]
    pieces = ['checker', 'checker king', 'camel', 'bishop']
    result = {(player, piece): {(i, j): 0
                                for i in range(len(board))
                                for j in range(len(board))}
              for player in players for piece in pieces}
    for x, y in board.locations.values():
        piece = board[x, y]
        result[piece.player_num, piece.name][x, y] = 1
    counts = {(player, piece): sum(result[player, piece].values())
              for player in players for piece in pieces}
    return ([result[player, piece][i, j]
             for player in players
             for piece in pieces
             for i in range(len(board))
             for j in range(len(board))
             if (i + j) % 2 == 0] +
            [counts[player, piece]
             for player in players
             for piece in pieces])

class TrainedMinMaxSearchPlayer(MinMaxSearchPlayer):
    """Minmax search player that uses a support vector machine for the scoring heuristic"""

    def __init__(self, max_depth = 4, scoring_svm = None, randomize = 0, parallelize = True, dynamic_depth = True, num = None):
        # If no scoring svm is provided, try to load the pickled one
        # If that fails, try to run training
        if scoring_svm == None:
            try:
                scoring_svm = '../data/svm.pickle'
                open(scoring_svm)
            except FileNotFoundError:
               scoring_svm = '../data/training.json'

        # If the provided svm is a string ending with '.pickle', then load it from that file
        if isinstance(scoring_svm, str) and scoring_svm.endswith('.pickle'):
            print("Loading svm...")
            scoring_svm = pickle.load(open(scoring_svm, 'rb'))
        # If the provided svm is a string ending with '.json', then load training data from
        # that file and train a new SVM.  Dump the generated SVM to svm.pickle
        elif isinstance(scoring_svm, str) and scoring_svm.endswith('.json'):
            print("Building svm...")
            from sklearn import svm
            training_data = json.loads(open(scoring_svm).read())
            scoring_svm = svm.SVR()
            scoring_svm.fit(*training_data)
            pickle.dump(scoring_svm, open('../data/svm.pickle', 'wb'))

        self.scoring_svm = scoring_svm
        super().__init__(max_depth, randomize, parallelize, dynamic_depth, num)

    def score(self, board):
        """Apply the svm to the inputs"""
        res = self.scoring_svm.predict([board_to_inputs(board)])[0]
        if self.num == 1:
            return res
        else:
            return -res

    def heuristic(self, board, depth):
        """Node ordering heruistic, apply the SVM for the first 2 levels.  After that running the
        SVM is slower than the speed-up over the default heuristic of the number of active pieces
        each player owns"""
        if depth > self.max_depth - 2:
            return self.score(board)
        else:
            return super().heuristic(board, depth)


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

# In[1]:

import pandas as pd

#Reading Titanic file in CSV Format
df=pd.read_csv("F:\small_projects\Titanic_using_Naive_B\\titanic.csv")
target=df.Survived
df.head(3)

# In[2]:

#Dropping uneccessary columns
df.drop(['PassengerId','Name', 'SibSp', 'Parch','Cabin' ,'Ticket' ,'Embarked','Survived'],axis='columns',inplace=True)
df.head(5)

# In[3]:

#Fetures on which the surviving depends
inputs=df

# In[4]:

#converting Sex text column into binary numbers
dummies=pd.get_dummies(inputs.Sex)
dummies.head(3)

# In[5]:

#merging dummy column to the input dataset
inputs=pd.concat([inputs,dummies],axis='columns')
inputs.head(3)

# In[6]:

#dropping text sex column
inputs.drop('Sex',axis='columns',inplace=True)
inputs.head(5)

# In[7]:

#checking which column has null values
inputs.columns[inputs.isna().any()]

# In[8]:

inputs.Age[:10]

# In[9]:

#assigning the mean value to all null values in the column Age
inputs.Age= inputs.Age.fillna(inputs.Age.mean())
inputs.head(10)

# In[10]:

#splitting test and train data
from sklearn.model_selection import train_test_split
X_train, X_test, y_train,y_test=train_test_split(inputs,target,test_size=0.2)

# In[11]:

X_test.head(10)

# In[12]:

X_train.head(10)

# In[13]:

#GaussianNB Model
from sklearn.naive_bayes import GaussianNB
model=GaussianNB()

# In[14]:

#Training the model
model.fit(X_train,y_train)

# In[15]:

#Calculating Score for the model
model.score(X_test,y_test)

# In[16]:

#Predicting surviving values for the test dataset
model.predict(X_test[:10])

# In[17]:

y_test[:10]

# In[18]:

#Calculating the Probability of not surviving or surviving
model.predict_proba(X_test[:10])

# In[ ]:

# If Predicted value is 1: Survived and  0: Not survived


import pytest
from typing import List
import azbacklog.entities as entities

def test_initEpic():
    e = entities.Epic()
    assert isinstance(e, entities.Epic)
    assert isinstance(e.features, List)
    assert len(e.features) == 0
    assert isinstance(e.tags, List)
    assert len(e.tags) == 0

def test_set_title_to_string():
    e = entities.Epic()
    e.title = "Test"
    assert e.title == "Test"

def test_set_title_to_number():
    e = entities.Epic()

    with pytest.raises(TypeError) as exc:
        e.title = 42
    assert "value must be a string" in str(exc.value)

def test_set_description_to_string():
    e = entities.Epic()
    e.description = "Test"
    assert e.description == "Test"

def test_set_description_to_number():
    e = entities.Epic()

    with pytest.raises(TypeError) as exc:
        e.description = 42
    assert "value must be a string" in str(exc.value)

def test_add_features_to_feature_list():
    e = entities.Epic()
    for r in range(5):
        f = entities.Feature()
        e.add_feature(f)

    assert len(e.features) == 5
    assert isinstance(e.features, List)
    assert isinstance(e.features[0], entities.Feature)

def test_add_generics_to_feature_list():
    e = entities.Epic()
    with pytest.raises(TypeError) as exc:
        for r in range(5):
            e.add_feature(r)
    assert "value must be of type 'Feature'" in str(exc.value)

def test_add_tags_to_tag_list():
    e = entities.Epic()
    for r in range(5):
        t = entities.Tag()
        e.add_tag(t)

    assert len(e.tags) == 5
    assert isinstance(e.tags, List)
    assert isinstance(e.tags[0], entities.Tag)

def test_add_generics_to_tag_list():
    e = entities.Epic()
    with pytest.raises(TypeError) as exc:
        for r in range(5):
            e.add_tag(r)
    assert "value must be of type 'Tag'" in str(exc.value)


#!python3
"""
Print the list named "people"
Ask the user to enter a word from the list
Ask the user to enter another word
Replace the first word with the second word.

inputs:
string
string

outputs:
list

example:
['Alain', 'Brian', 'Chris', 'Justin', 'Angela', 'Rick']
Choose a person from the list to replace:Rick
Enter the replacement:Dan
['Alain', 'Brian', 'Chris', 'Justin', 'Angela', 'Dan']

"""
list=['Alain', 'Brian', 'Chris', 'Justin', 'Angela', 'Rick']
print(list)
n1=str(input("enter the name from the list:"))
n2=str(input("enter a new name:"))
i=list.index(n1)
list.remove(n1)
list.insert(i, n2)

print(list)
print("\n")


# Set up parameters:
k_size = 9  # Must be an odd number
vertex_ratio_h = .45
vertex_ratio_v = .60
low_thresh = 15
high_thresh = 50
L2gradient = False
rho = 2
theta = 1 * np.pi / 180.
min_votes = 15
min_line_len = 40
max_line_gap = 20
angle = 3 * np.pi / 16
angle_threshold = np.pi / 64

for file in files:
    frame = mpimg.imread('challenge/' + file)
    fig = plt.figure(figsize = (15, 10))
    fig.text(.1, 1, file)
    result = process_image(frame,
                           k_size = k_size,
                           low_thresh = low_thresh,
                           high_thresh = high_thresh,
                           L2gradient = L2gradient,
                           rho = rho,
                           theta = theta,
                           min_votes = min_votes,
                           min_line_len = min_line_len,
                           max_line_gap = max_line_gap,
                           angle = angle,
                           angle_thresh = angle_threshold,
                           debug = True)


from odoo import models, fields

class ConstructionInvoice(models.Model):
    _name = "cstr.invoice"
    _inherits = {"account.move": "invoice_id"}
    _description = "Construction Invoice"

    invoice_id = fields.Many2one(
        "account.move", "Related Invoice", required=True, ondelete="cascade"
    )
    cstr_project_id = fields.Many2one("cstr.project", "Construction Project")
    additional_costs = fields.Float("Additional Costs")
    retention_fee = fields.Float("Retention Fee")


def shortestWordEditPath(source, target, words):
  queue = [(source, 0)]
  seen = set([source])

  while queue:
    current = queue.pop(0)
    current_word = current[0]
    current_count = current[1]

    if current_word == target:
      return current_count

    for neighbor in get_one_off(current_word, words):
      if neighbor not in seen:
        queue.append((neighbor, current_count + 1))
        seen.add(neighbor)
  return -1

def get_one_off(current_word, words):
  result_arr = []
  for word in words:
    count = 0
    if word == current_word or len(word) != len(current_word):
      continue
    for i in range(len(current_word)):
      if current_word[i] != word[i]:
        count+=1
        if count > 1:
          break
    if count <= 1:
      result_arr.append(word)
  return result_arr


import copy
from typing import Any, Literal, Self

import gymnasium as gym
import numpy as np
import torch
import torch.nn.functional as F

from tianshou.data import Batch, to_torch
from tianshou.data.batch import BatchProtocol
from tianshou.data.types import RolloutBatchProtocol
from tianshou.policy import BasePolicy
from tianshou.policy.base import TLearningRateScheduler
from tianshou.utils.net.continuous import VAE
from tianshou.utils.optim import clone_optimizer

class BCQPolicy(BasePolicy):
    """Implementation of BCQ algorithm. arXiv:1812.02900.

    :param actor_perturbation: the actor perturbation. `(s, a -> perturbed a)`
    :param actor_perturbation_optim: the optimizer for actor network.
    :param critic: the first critic network.
    :param critic_optim: the optimizer for the first critic network.
    :param critic2: the second critic network.
    :param critic2_optim: the optimizer for the second critic network.
    :param vae: the VAE network, generating actions similar to those in batch.
    :param vae_optim: the optimizer for the VAE network.
    :param device: which device to create this model on.
    :param gamma: discount factor, in [0, 1].
    :param tau: param for soft update of the target network.
    :param lmbda: param for Clipped Double Q-learning.
    :param forward_sampled_times: the number of sampled actions in forward function.
        The policy samples many actions and takes the action with the max value.
    :param num_sampled_action: the number of sampled actions in calculating target Q.
        The algorithm samples several actions using VAE, and perturbs each action to get the target Q.
    :param observation_space: Env's observation space.
    :param action_scaling: if True, scale the action from [-1, 1] to the range
        of action_space. Only used if the action_space is continuous.
    :param action_bound_method: method to bound action to range [-1, 1].
        Only used if the action_space is continuous.
    :param lr_scheduler: if not None, will be called in `policy.update()`.

    .. seealso::

        Please refer to :class:`~tianshou.policy.BasePolicy` for more detailed explanation.
    """

    def __init__(
        self,
        *,
        actor_perturbation: torch.nn.Module,
        actor_perturbation_optim: torch.optim.Optimizer,
        critic: torch.nn.Module,
        critic_optim: torch.optim.Optimizer,
        action_space: gym.Space,
        vae: VAE,
        vae_optim: torch.optim.Optimizer,
        critic2: torch.nn.Module | None = None,
        critic2_optim: torch.optim.Optimizer | None = None,
        # TODO: remove? Many policies don't use this
        device: str | torch.device = "cpu",
        gamma: float = 0.99,
        tau: float = 0.005,
        lmbda: float = 0.75,
        forward_sampled_times: int = 100,
        num_sampled_action: int = 10,
        observation_space: gym.Space | None = None,
        action_scaling: bool = False,
        action_bound_method: Literal["clip", "tanh"] | None = "clip",
        lr_scheduler: TLearningRateScheduler | None = None,
    ) -> None:
        # actor is Perturbation!
        super().__init__(
            action_space=action_space,
            observation_space=observation_space,
            action_scaling=action_scaling,
            action_bound_method=action_bound_method,
            lr_scheduler=lr_scheduler,
        )
        self.actor_perturbation = actor_perturbation
        self.actor_perturbation_target = copy.deepcopy(self.actor_perturbation)
        self.actor_perturbation_optim = actor_perturbation_optim

        self.critic = critic
        self.critic_target = copy.deepcopy(self.critic)
        self.critic_optim = critic_optim

        critic2 = critic2 or copy.deepcopy(critic)
        critic2_optim = critic2_optim or clone_optimizer(critic_optim, critic2.parameters())
        self.critic2 = critic2
        self.critic2_target = copy.deepcopy(self.critic2)
        self.critic2_optim = critic2_optim

        self.vae = vae
        self.vae_optim = vae_optim

        self.gamma = gamma
        self.tau = tau
        self.lmbda = lmbda
        self.device = device
        self.forward_sampled_times = forward_sampled_times
        self.num_sampled_action = num_sampled_action

    def train(self, mode: bool = True) -> Self:
        """Set the module in training mode, except for the target network."""
        self.training = mode
        self.actor_perturbation.train(mode)
        self.critic.train(mode)
        self.critic2.train(mode)
        return self

    def forward(
        self,
        batch: RolloutBatchProtocol,
        state: dict | BatchProtocol | np.ndarray | None = None,
        **kwargs: Any,
    ) -> Batch:
        """Compute action over the given batch data."""
        # There is "obs" in the Batch
        # obs_group: several groups. Each group has a state.
        obs_group: torch.Tensor = to_torch(batch.obs, device=self.device)
        act_group = []
        for obs_orig in obs_group:
            # now obs is (state_dim)
            obs = (obs_orig.reshape(1, -1)).repeat(self.forward_sampled_times, 1)
            # now obs is (forward_sampled_times, state_dim)

            # decode(obs) generates action and actor perturbs it
            act = self.actor_perturbation(obs, self.vae.decode(obs))
            # now action is (forward_sampled_times, action_dim)
            q1 = self.critic(obs, act)
            # q1 is (forward_sampled_times, 1)
            max_indice = q1.argmax(0)
            act_group.append(act[max_indice].cpu().data.numpy().flatten())
        act_group = np.array(act_group)
        return Batch(act=act_group)

    def sync_weight(self) -> None:
        """Soft-update the weight for the target network."""
        self.soft_update(self.critic_target, self.critic, self.tau)
        self.soft_update(self.critic2_target, self.critic2, self.tau)
        self.soft_update(self.actor_perturbation_target, self.actor_perturbation, self.tau)

    def learn(self, batch: RolloutBatchProtocol, *args: Any, **kwargs: Any) -> dict[str, float]:
        # batch: obs, act, rew, done, obs_next. (numpy array)
        # (batch_size, state_dim)
        batch: Batch = to_torch(batch, dtype=torch.float, device=self.device)
        obs, act = batch.obs, batch.act
        batch_size = obs.shape[0]

        # mean, std: (state.shape[0], latent_dim)
        recon, mean, std = self.vae(obs, act)
        recon_loss = F.mse_loss(act, recon)
        # (....) is D_KL( N(mu, sigma) || N(0,1) )
        KL_loss = (-torch.log(std) + (std.pow(2) + mean.pow(2) - 1) / 2).mean()
        vae_loss = recon_loss + KL_loss / 2

        self.vae_optim.zero_grad()
        vae_loss.backward()
        self.vae_optim.step()

        # critic training:
        with torch.no_grad():
            # repeat num_sampled_action times
            obs_next = batch.obs_next.repeat_interleave(self.num_sampled_action, dim=0)
            # now obs_next: (num_sampled_action * batch_size, state_dim)

            # perturbed action generated by VAE
            act_next = self.vae.decode(obs_next)
            # now obs_next: (num_sampled_action * batch_size, action_dim)
            target_Q1 = self.critic_target(obs_next, act_next)
            target_Q2 = self.critic2_target(obs_next, act_next)

            # Clipped Double Q-learning
            target_Q = self.lmbda * torch.min(target_Q1, target_Q2) + (1 - self.lmbda) * torch.max(
                target_Q1,
                target_Q2,
            )
            # now target_Q: (num_sampled_action * batch_size, 1)

            # the max value of Q
            target_Q = target_Q.reshape(batch_size, -1).max(dim=1)[0].reshape(-1, 1)
            # now target_Q: (batch_size, 1)

            target_Q = (
                batch.rew.reshape(-1, 1) + (1 - batch.done).reshape(-1, 1) * self.gamma * target_Q
            )

        current_Q1 = self.critic(obs, act)
        current_Q2 = self.critic2(obs, act)

        critic1_loss = F.mse_loss(current_Q1, target_Q)
        critic2_loss = F.mse_loss(current_Q2, target_Q)

        self.critic_optim.zero_grad()
        self.critic2_optim.zero_grad()
        critic1_loss.backward()
        critic2_loss.backward()
        self.critic_optim.step()
        self.critic2_optim.step()

        sampled_act = self.vae.decode(obs)
        perturbed_act = self.actor_perturbation(obs, sampled_act)

        # max
        actor_loss = -self.critic(obs, perturbed_act).mean()

        self.actor_perturbation_optim.zero_grad()
        actor_loss.backward()
        self.actor_perturbation_optim.step()

        # update target network
        self.sync_weight()

        return {
            "loss/actor": actor_loss.item(),
            "loss/critic1": critic1_loss.item(),
            "loss/critic2": critic2_loss.item(),
            "loss/vae": vae_loss.item(),
        }


from django.urls import path
from . import views
urlpatterns = [
    path('', views.index),
    path('books/new', views.book_register),
    path('books/<int:book_id>/', views.book_details),
    path('books/<int:book_id>/author', views.add_author),
    path('authors', views.index_authors),
    path('authors/new', views.author_register),
    path('authors/<int:author_id>', views.author_details),
    path('authors/<int:author_id>/book', views.add_book),
]


import pandas as pd
import numpy as np
import random
import sklearn
from sklearn.datasets.samples_generator import make_regression
import pylab
from scipy import stats
import math

def batch_gradient_descent(alpha, x, y, ep=0.0000000001, max=1000000):
    converged = False # for while loop
    iter = 0 # starting iteration
    m = x.shape[0] # number of samples for range

    #inital weights
    w = [0.25, 0.25]

    # total error
    J = sum([(w[0] + w[1]*x[i] - y[i])**2 for i in range(m)])

    # Iterate until we see convergence or "ep"
    while not converged:
        # for each sample we find the gradient 1/m * w0 + w1(xi) - y(i)
        g0 = 1.0/m * sum([(w[0] + w[1]*x[i] - y[i]) for i in range(m)])
        g1 = 1.0/m * sum([(w[0] + w[1]*x[i] - y[i])*x[i] for i in range(m)])

        # update weights
        tmp0 = w[0] - alpha * g0
        tmp1 = w[1] - alpha * g1

        w[0] = tmp0
        w[1] = tmp1

        # mean squared error
        err = sum([(y[i] - (w[1]*x[i] + w[0]))**2 for i in range(m)])

        c = abs(J-err)

        print('Iteration = %s | error = %s | EP = %.10f' %(iter, err, c))

        if c <= ep:
            print('Converged after %s Iterations! With Convergence = %.10f' %(iter, c))
            converged = True

        J = err #update error
        iter += 1 #increase iteration

        # if we reach max iterations of 1,000,000 converged is True
        if iter == max:
            print('Max Iterations Reached!')
            converged = True

    return w[0], w[1]

if __name__ == '__main__':

    alpha = 0.0001 #learning rate
    ep = 0.0000000001
    x = np.array([2,4,6,7,8,10])
    y = np.array([5,7,14,14,17,19])

    w0, w1 = batch_gradient_descent(alpha, x, y, ep, max=1000000) #call batch to determine w0,w1
    print('w0 = %.10f w1 = %.10f' %(w0, w1))

    x, y = make_regression(n_samples=6, n_features=1, n_informative=1, random_state=0, noise=35)

    slope, intercept, r_value, p_value, slope_std_error = stats.linregress(x[:,0], y)
    print('Intercept = %s slope = %s' %(intercept, slope))

    x5 = intercept * 5 + slope
    print('When x = 5, y = %s' %(x5))
    neg100 = intercept * -100 + slope
    print('When x = -100, y = %s' %(neg100))
    x100 = intercept * 100 + slope
    print('When x = 100, y = %s' %(x100))

    for i in range(x.shape[0]):
        y_pred = w0 + w1*x

    pylab.plot(x,y,'o')
    pylab.plot(x,y_pred,'k-')
    pylab.show()


import os
import csv

#Set variables
total_month=0

months=[]
total_revenue=0
revenue_change=0
revenue_changes=[]
previous_revenue=0
sum_revenue_change=0
av_revenue_change=0

#Open file
csv_path=os.path.join("budget_data.csv")
with open (csv_path) as csvfile:
    csv_reader=csv.reader(csvfile, delimiter=',')
    next(csv_reader, None)

    #Create file with no header
    line=next(csv_reader, None)

    revenue=float(line[1])
    greatest_increase=revenue
    greatest_decrease=revenue

    #Loop through each row and calculate summary info
    for row in csv_reader:
        total_month=total_month+1
        months.append(line[0])
        total_revenue=total_revenue+revenue

        if total_month>1:
            revenue_change=revenue-previous_revenue
            revenue_changes.append(revenue_change)
            previous_revenue=revenue

        sum_revenue_change=sum(revenue_changes)
        av_revenue_change=sum_revenue_change/(total_month)
        greatest_increase=max(revenue_changes)
        greatest_decrease=min(revenue_changes)
        max_month_index= revenue_changes.index(greatest_increase)
        min_month_index= revenue_changes.index(greatest_decrease)
        max_month=months[max_month_index]
        min_month=months[min_month_index]

#Print summary info
print("Financial Analysis")
print("--------------------------")
print(f"Total months: {(total_month)}")
print(f'Total: {(total_revenue)}')
print(f'Average Change: ${(av_revenue_change)}')
print(f'Greatest Increase in Profits: {(max_month)} (${(greatest_increase)})')
print(f'Greatest Decrease in Profits: {(min_month)} (${(greatest_decrease)})')


import subprocess, socket

PORT = 5554
ADDRESS = "127.0.0.1"
subprocess.Popen(["ffplay", "tcp://{}:{}?listen".format(ADDRESS, PORT)])

#Simulate chunks
def split_into_chunks(data, nr_chunks):
    chunk_size = int(len(data) / nr_chunks)
    chunks = []
    for i in range(nr_chunks):
        chunks.append(data[i*chunk_size: (i+1)*chunk_size])

    return chunks

with open("../sample.mkv", "rb") as f:
    nr_chunks = 100
    file = f.read()
    chunks = split_into_chunks(file, nr_chunks)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ADDRESS, PORT))

    for i in range(nr_chunks):
        s.sendall(chunks[i])


import os
import glob

import pandas as pd
from omegaconf import OmegaConf
from sklearn.model_selection import train_test_split
from transformers import WhisperProcessor, WhisperModel, AutoFeatureExtractor, Wav2Vec2Model

from preload_data import prepare_data

def create_metadata_ravdess(ravdess_base_dir: str):
    """
    Creates a metadata of the ravdess dataset
    """
    int2emotion = {
        "01": "neutral",
        "02": "calm",
        "03": "happy",
        "04": "sad",
        "05": "angry",
        "06": "fearful",
        "07": "disgust",
        "08": "surprised",
    }

    audio_paths = glob.glob(
        os.path.join(
            ravdess_base_dir,
            '**',
            '*.wav'
        ),
        recursive=True
    )

    # print(audio_paths)

    genders = []
    emotions = []
    actors = []
    labels = []

    for _, audio_path in enumerate(audio_paths):
        filename = os.path.basename(audio_path).split('.')[0]

        modality = filename.split('-')[0]
        vocal_channel = filename.split('-')[1]
        emotion = filename.split('-')[2]
        actor = filename.split('-')[6]

        assert modality=="03"
        assert vocal_channel=="01"

        if int(actor)%2 == 0:
            gender = 'female'
        else:
            gender = 'male'

        genders.append(gender)
        emotions.append(int2emotion[emotion])
        actors.append(int(actor))
        labels.append(int(emotion)-1)

    df = pd.DataFrame(
        list(
            zip(
                audio_paths,
                genders,
                emotions,
                actors,
                labels
            )
        ),
        columns=[
            'wav_file',
            'gender',
            'emotion',
            'actor',
            'label'
        ]
    )

    return df

def split_dataset(
    df: pd.DataFrame = None,
    frac_train: float = 0.70,
    frac_val: float = 0.10,
    frac_test: float = 0.20,
):
    """
    Split the data into subsets for training, validation, and testing.
    The same speakers are present in all subsets.
    """
    X_train, X_temp, _, _ = train_test_split(
        df,
        df["label"],
        test_size=(1.0 - frac_train),
        stratify=df[["gender", "emotion", "actor"]],
        random_state=42
    )

    X_val, X_test, _, _  = train_test_split(
        X_temp,
        X_temp["label"],
        test_size=frac_test,
        stratify=X_temp[["gender", "emotion", "actor"]],
        random_state=42
    )

    return X_train, X_val, X_test

def split_dataset_actors(df: pd.DataFrame):
    """
    Split the data into subsets for training, validation, and testing.
    The speakers are split up so that there is a distinct speakers for each subset.
    """
    train_actors = [i for i in range(1, 17)]
    val_actors = [i for i in range(17, 19)]
    test_actors = [i for i in range(19, 25)]

    X_train = df[df["actor"].isin(train_actors)]
    X_val = df[df["actor"].isin(val_actors)]
    X_test = df[df["actor"].isin(test_actors)]

    return X_train, X_val, X_test

def main():
    ravdess_df = create_metadata_ravdess(
        ravdess_base_dir="../../data/ravdess"
    )
    encoder = "whisper"
    use_pooling = True
    base_dir_output = f"../../data/ravdess_preloaded_{encoder}_pooled"

    X_train, X_val, X_test = split_dataset_actors(df=ravdess_df)

    X_train.to_csv("../../data/ravdess_train_metadata.csv", index=False)
    X_val.to_csv("../../data/ravdess_eval_metadata.csv", index=False)
    X_test.to_csv("../../data/ravdess_test_metadata.csv", index=False)

    # if encoder == "whisper":
    #     print("Using Whisper Embeddings... ")
    #     processor = AutoFeatureExtractor.from_pretrained("openai/whisper-base")
    #     model = WhisperModel.from_pretrained("openai/whisper-base")
    #     model = model.encoder
    #     model.eval()

    # if encoder == "wav2vec2":
    #     print("Using Wav2vec2 Embeddings... ")
    #     processor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-xls-r-300m")
    #     model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-xls-r-300m")
    #     model.eval()

    # prepare_data(
    #     X_train=X_train,
    #     X_val=X_val,
    #     X_test=X_test,
    #     target_sampling_rate=16000,
    #     base_dir_output=base_dir_output,
    #     encoder=model,
    #     processor=processor,
    #     filename_column="wav_file",
    #     base_dir_data="",
    #     mean_pooled=use_pooling
    # )

if __name__ == "__main__":
    main()


from pymongo import MongoClient

from flask import Flask, render_template, jsonify, request

app = Flask(__name__)

client = MongoClient('localhost', 27017)
db = client.moviestar

# HTML 화면 보여주기
@app.route('/')
def home():
    return render_template('index.html')

# API 역할을 하는 부분
# DB에 있는 모든 배우의 정보를 클라이언트에 넘겨줌.
@app.route('/api/list', methods=['GET'])
def show_stars():
    # 배우들을 좋아요가 많은 순으로 정렬
    actors = list(db.mystar.find({}, {'_id': False}).sort('like', -1))

    return jsonify({'movie_stars': actors})

# 클라이언트한테 배우의 이름을 받아서 해당하는 배우의 좋아요를 DB에서 1을 증가시킴.
@app.route('/api/like', methods=['POST'])
def like_star():
    actor_name = request.form['actor_name']
    actor = db.mystar.find_one({'name': actor_name})
    current_like = actor['like']
    #현재 좋아요 + 1
    new_like = current_like + 1
    #db에 업데이트
    db.mystar.update_one({'name': actor_name}, {'$set': {'like': new_like}})

    return jsonify({'msg': '좋아요 완료'})

# 클라이언트한테 배우의 이름을 받아서 해당하는 배우 삭제
@app.route('/api/delete', methods=['POST'])
def delete_star():
    actor_name = request.form['actor_name']

    db.mystar.delete_one({'name': actor_name})
    return jsonify({'msg': '삭제 완료'})

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)


from flask import Flask, jsonify, request,render_template, redirect, url_for, flash
from flask_mysqldb import MySQL
import yaml

db=yaml.load(open('database_details.yaml'))

#initializing
app=Flask(__name__)
#config Mysql
app.config['MYSQL_HOST']=db['mysql_host']
app.config['MYSQL_USER']=db['mysql_user']
app.config['MYSQL_PASSWORD']=db['mysql_password']
app.config['MYSQL_DB']=db['mysql_db']
#cursor class not neccessary exactly but it helps to get the data in dictionay
#format, normally it just return tuples, but dict is more easy to read.
# app.config['MYSQL_CURSORCLASS']='DictCursor'

#instantiating mysqldb
mysql = MySQL(app)

@app.route('/home',methods=['GET'])
def data():
    if request.method =='GET':
        cur=mysql.connection.cursor()
        cur.execute("SELECT * FROM example")
        userDetails = cur.fetchall()

        return render_template('users.html', userDetails=userDetails)

@app.route('/post',methods=['GET','POST'])
def post():
    if request.method =='POST':
        userdetail = request.form
        name = userdetail['username']
        age = userdetail['age']
        cursor = mysql.connection.cursor()
        try:
            cursor.execute('''CREATE TABLE example(name VARCHAR(20), age INTEGER)''')
        except Exception as e:
            pass
        finally:
            cursor.execute('''INSERT INTO example VALUES(%s, %s)''',(name,age))
            mysql.connection.commit()
            cursor.close()

        return redirect('/home')
    return render_template('index.html')

@app.route('/update',methods=['POST','GET'])
def update():
    if request.method=='POST':
        userdetail = request.form
        name = userdetail['username']
        age = userdetail['age']
        cursor = mysql.connection.cursor()
        cursor.execute('''UPDATE example SET age=%s WHERE name=%s''',(age,name))
        mysql.connection.commit()
        cursor.close()
        return redirect(url_for('data'))
    return render_template('update.html')

@app.route('/delete',methods=['POST','GET'])
def delete():
    if request.method=='POST':
        userdetail = request.form
        name = userdetail['user']
        cursor = mysql.connection.cursor()
        #In the below (name,) means to unpack the values
        cursor.execute("DELETE FROM example WHERE name=%s",(name))
        '''You need to add a trailing comma to your query to pass a tuple,
         rather than a string as an argument.'''
        # flash("deleted successfully")
        mysql.connection.commit()
        cursor.close()
        return redirect(url_for('data'))
    return render_template('del.html')
if __name__ == '__main__':
    app.run(debug=True)


#!/usr/bin/env python3

# Team Clara:
# Elisa Andrade
# Jorge Chong

# Currently: we are having problems creating more input/output nodes
# So for the moment depth is not used but we experimented with it

import cv2
import depthai as dai
import numpy as np
from datetime import datetime
import mediapipe_utils as mpu
from pathlib import Path
from FPS import FPS, now
import threading
import queue as Queue
import equal_tempered as eqtmp
from pythonosc import udp_client
import argparse

# Credits:
# Hand Tracking Model from: geax
# https://github.com/geaxgx/depthai_hand_tracker

# Landmarks:
LM_WRIST = 0
LM_THUMB_CMC = 1
LM_THUMB_MCP = 2
LM_THUMB_IP = 3
LM_THUMB_TIP = 4
LM_INDEX_FINGER_MCP = 5
LM_INDEX_FINGER_PIP = 6
LM_INDEX_FINGER_DIP = 7
LM_INDEX_FINGER_TIP = 8
LM_MIDDLE_FINGER_MCP = 9
LM_MIDDLE_FINGER_PIP = 10
LM_MIDDLE_FINGER_DIP = 11
LM_MIDDLE_FINGER_TIP = 12
LM_RING_FINGER_MCP = 13
LM_RING_FINGER_PIP = 14
LM_RING_FINGER_DIP = 15
LM_RING_FINGER_TIP = 16
LM_PINKY_MCP = 17
LM_PINKY_PIP = 18
LM_PINKY_DIP = 19
LM_PINKY_TIP = 20

# Parameters
PARAMS = {
    'CAPTURE_DEVICE': 0,
    'KEY_QUIT': 'q',
    'HUD_COLOR': (153,219,112),
    'LANDMARKS_COLOR': (0,255,0),
    'LANDMARKS': [
                    LM_WRIST,
                    LM_THUMB_TIP,
                    LM_INDEX_FINGER_TIP,
                    LM_MIDDLE_FINGER_TIP,
                    LM_RING_FINGER_TIP,
                    LM_PINKY_TIP
                ],
    'MEDIAPIPE_HANDS_MODE': False,
    'MEDIAPIPE_HANDS_MAXHANDS': 2,
    'MEDIAPIPE_HANDS_DETECTION_CONFIDENCE': 0.5,
    'MEDIAPIPE_HANDS_TRACKING_CONFIDENCE': 0.5,
    'PALM_DETECTION_INPUT_LENGTH': 128,
    'LM_INPUT_LENGTH': 224,
    'VIDEO_RESOLUTION': dai.ColorCameraProperties.SensorResolution.THE_1080_P,
    'MONO_LEFT_RESOLUTION': dai.MonoCameraProperties.SensorResolution.THE_800_P,
    'MONO_RIGHT_RESOLUTION': dai.MonoCameraProperties.SensorResolution.THE_800_P,
    # 'MONO_LEFT_RESOLUTION': dai.MonoCameraProperties.SensorResolution.THE_400_P,
    # 'MONO_RIGHT_RESOLUTION': dai.MonoCameraProperties.SensorResolution.THE_400_P,
    # 'PALM_DETECTION_MODEL_PATH': "models/palm_detection_6_shaves.blob",
    # 'LM_DETECTION_MODEL_PATH': "models/hand_landmark_6_shaves.blob",
    'PALM_DETECTION_MODEL_PATH': "models/palm_detection.blob",
    'LM_DETECTION_MODEL_PATH': "models/hand_landmark.blob",
    'ROI_DP_LOWER_TH': 100,
    'ROI_DP_UPPER_TH': 10000,
    'INITIAL_ROI_TL': dai.Point2f(0.4, 0.4),
    'INITIAL_ROI_BR': dai.Point2f(0.6, 0.6),
    'PREVIEW_WIDTH': 576,
    'PREVIEW_HEIGHT': 324,
    'SCREEN_MIN_FREQ': 0.5,
    'SCREEN_MAX_FREQ': 1,
    'SC_SERVER': '127.0.0.1',
    'SC_PORT': 57121
}

# def to_planar(arr: np.ndarray, shape: tuple) -> list:
def to_planar(arr: np.ndarray, shape: tuple) -> np.ndarray:
    resized = cv2.resize(arr, shape, interpolation=cv2.INTER_NEAREST)
    return resized.transpose(2,0,1)

# Hand tracking based theremin (the CV Part)
class Ether:
    def __init__(
        self,
        queue,
        pd_path=PARAMS['PALM_DETECTION_MODEL_PATH'],
        pd_score_thresh=0.5,
        pd_nms_thresh=0.3,
        lm_path=PARAMS['LM_DETECTION_MODEL_PATH'],
        lm_score_threshold=0.5
    ):
        self.queue = queue
        self.pd_path = pd_path
        self.pd_score_thresh = pd_score_thresh
        self.pd_nms_thresh = pd_nms_thresh
        self.lm_path = lm_path
        self.lm_score_threshold = lm_score_threshold

        self.show_landmarks = True
        self.show_handedness = False

        # Create SSD anchors
        # https://github.com/google/mediapipe/blob/master/mediapipe/modules/palm_detection/palm_detection_cpu.pbtxt
        anchor_options = mpu.SSDAnchorOptions(
            num_layers=4,
            min_scale=0.1484375,
            max_scale=0.75,
            input_size_height=128,
            input_size_width=128,
            anchor_offset_x=0.5,
            anchor_offset_y=0.5,
            strides=[8,16,16,16],
            aspect_ratios=[1.0],
            reduce_boxes_in_lowest_layer=False,
            interpolated_scale_aspect_ratio=1.0,
            fixed_anchor_size=True
        )
        self.anchors = mpu.generate_anchors(anchor_options)
        self.nb_anchors = self.anchors.shape[0]
        print(f"{self.nb_anchors} anchors have been created")

        # Rendering flags
        self.show_pd_box = True
        self.show_pd_kps = False
        self.show_rot_rect = False
        self.show_scores = False
        self.show_landmarks = True

        # Preview Sizes
        self.preview_width = PARAMS['PREVIEW_WIDTH']
        self.preview_height = PARAMS['PREVIEW_HEIGHT']

        # Palm detector input size
        self.pd_input_length = PARAMS['PALM_DETECTION_INPUT_LENGTH']

        # Landmark detector input size
        self.lm_input_length = PARAMS['LM_INPUT_LENGTH']

    # Post process inference from Palm Detector
    def pd_postprocess(self, inference):
        scores = np.array(
            inference.getLayerFp16("classificators"),
            dtype=np.float16) # 896
        bboxes = np.array(
            inference.getLayerFp16("regressors"),
            dtype=np.float16).reshape((self.nb_anchors,18)) # 896x18
        # Decode bboxes
        self.regions = mpu.decode_bboxes(
            self.pd_score_thresh,
            scores,
            bboxes,
            self.anchors)
        # Non maximum suppression
        self.regions = mpu.non_max_suppression(self.regions, self.pd_nms_thresh)
        mpu.detections_to_rect(self.regions)
        mpu.rect_transformation(self.regions, self.frame_size, self.frame_size)

    # Process Landmarks
    def lm_postprocess(self, region, inference):
        region.lm_score = inference.getLayerFp16("Identity_1")[0]
        region.handedness = inference.getLayerFp16("Identity_2")[0]
        lm_raw = np.array(inference.getLayerFp16("Identity_dense/BiasAdd/Add"))
        # lm_raw = np.array(inference.getLayerFp16("Squeeze"))

        lm = []
        for i in range(int(len(lm_raw)/3)):
            # x,y,z -> x/w,y/h,z/w (here h=w)
            lm.append(lm_raw[3*i:3*(i+1)]/self.lm_input_length)
        region.landmarks = lm

    # Transform xy coordinates to normalized xy
    def lm_transform(self, region):
        src = np.array([(0, 0), (1, 0), (1, 1)], dtype=np.float32)
        dst = np.array([ (x, y) for x,y in region.rect_points[1:]], dtype=np.float32) # region.rect_points[0] is left bottom point !
        mat = cv2.getAffineTransform(src, dst)

        dst_normal = np.array([ (x/self.frame_size, y/self.frame_size) for x,y in region.rect_points[1:]], dtype=np.float32) # region.rect_points[0] is left bottom point !
        mat_normal = cv2.getAffineTransform(src, dst_normal)

        lm_xy = np.expand_dims(np.array([(l[0], l[1]) for l in region.landmarks]), axis=0)
        lm_xy = np.squeeze(cv2.transform(lm_xy, mat)).astype(np.int)

        lm_xy_normal = np.expand_dims(np.array([(l[0], l[1]) for l in region.landmarks]), axis=0)
        lm_xy_normal = np.squeeze(cv2.transform(lm_xy_normal, mat_normal)).astype(np.float32)

        region.lm_xy = lm_xy
        region.lm_xy_normalized = lm_xy_normal
        # y rescaled
        lm_xy_y_rescaled = lm_xy_normal.copy()
        lm_xy_y_rescaled[:, 1] = (lm_xy_y_rescaled[:, 1] - self.pad_h / self.frame_size) * (self.frame_size/self.preview_height)
        region.lm_xy_y_rescaled = lm_xy_y_rescaled

    # Render Landmarks
    def lm_render(self, frame, region):
        if region.lm_score > self.lm_score_threshold:
            if self.show_rot_rect:
                cv2.polylines(frame, [np.array(region.rect_points)], True, (0,255,255), 2, cv2.LINE_AA)

            if self.show_landmarks:
                src = np.array([(0, 0), (1, 0), (1, 1)], dtype=np.float32)
                dst = np.array([ (x, y) for x,y in region.rect_points[1:]], dtype=np.float32) # region.rect_points[0] is left bottom point !
                # print(region.rect_points[1:])
                mat = cv2.getAffineTransform(src, dst)
                lm_xy = np.expand_dims(np.array([(l[0], l[1]) for l in region.landmarks]), axis=0)
                lm_xy = np.squeeze(cv2.transform(lm_xy, mat)).astype(np.int)
                list_connections = [[0, 1, 2, 3, 4],
                                    [0, 5, 6, 7, 8],
                                    [5, 9, 10, 11, 12],
                                    [9, 13, 14 , 15, 16],
                                    [13, 17],
                                    [0, 17, 18, 19, 20]]
                lines = [np.array([lm_xy[point] for point in line]) for line in list_connections]
                cv2.polylines(frame, lines, False, (255, 0, 0), 2, cv2.LINE_AA)
                for x,y in lm_xy:
                    # print(x,y)
                    cv2.circle(frame, (x, y), 3, (0,128,255), -1)

    # Transform the normalized x, y and form a message to send
    # to a queue for further processing (interaction)
    def xy_message(self, region):
        handedness = 'R'
        if region.handedness < 0.5:
            handedness = 'L'
        # Renormalize
        w = self.preview_width
        h = self.preview_height
        y_factor = w/h
        pts = region.lm_xy_normalized.copy()
        pts[:,1] = pts[:,1]/y_factor
        # Message
        message = {
            'handedness': handedness,
            'original_xy': region.lm_xy_normalized,
            'original_xy_y_rescaled': region.lm_xy_y_rescaled,
            'xy': pts
        }
        return message

    # Stop Sending Messages
    def stop_message(self):
        message = {
            'STOP': 1
        }
        return message

    # Draw lines
    def draw_lines(self, frame, region):
        pos = region.lm_xy[0, :]
        w = self.preview_width
        cv2.line(frame, (pos[0], 0), (pos[0], w), (0,255,0), 1)
        cv2.line(frame, (0, pos[1]), (w, pos[1]), (0,255,0), 1)

    # Draw mean line (take the mean of x pos and draw a line)
    def draw_mean_line_r(self, frame, region):
        if region.handedness >= 0.5:
            pos = region.lm_xy[PARAMS['LANDMARKS'], 0]
            mean_pos_x = int(np.mean(pos))
            w = self.preview_width
            cv2.line(frame, (mean_pos_x, 0), (mean_pos_x, w), (0,255,0), 1)

    # Draw min line (take the min of x pos and draw a line)
    def draw_min_line_r(self, frame, region):
        # print(region.handedness)
        if region.handedness >= 0.5:
            # pos = region.lm_xy[PARAMS['LANDMARKS'], 0]
            pos = region.lm_xy[:, 0]
            min_pos_x = int(np.min(pos))
            w = self.preview_width
            cv2.line(frame, (min_pos_x, 0), (min_pos_x, w), (0,255,0), 1)

    # Pipeline
    def create_pipeline(self):
        print("[{}]: Creating Pipeline...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        # Pipeline
        pipeline = dai.Pipeline()
        # pipeline.setOpenVINOVersion(version = dai.OpenVINO.Version.VERSION_2021_2)

        print("[{}]: Setting up Depth...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        # Mono Left Camera
        mono_l = pipeline.createMonoCamera()
        # Mono Right Camera
        mono_r = pipeline.createMonoCamera()
        # Mono Camera Settings
        mono_l.setResolution(PARAMS['MONO_LEFT_RESOLUTION'])
        mono_l.setBoardSocket(dai.CameraBoardSocket.LEFT)
        mono_r.setResolution(PARAMS['MONO_RIGHT_RESOLUTION'])
        mono_r.setBoardSocket(dai.CameraBoardSocket.RIGHT)
        #mono_l.setFps(10)
        #mono_r.setFps(10)
        # Depth and Depth Calculator
        stereo = pipeline.createStereoDepth()
        spatial_calc = pipeline.createSpatialLocationCalculator()
        # Depth / Calculator / Config / Outputs and Inputs
        # xout_depth = pipeline.createXLinkOut()
        xout_spatial_data = pipeline.createXLinkOut()
        xin_spatial_calc_config = pipeline.createXLinkIn()
        # Stream Names
        # xout_depth.setStreamName("depth")
        xout_spatial_data.setStreamName("spatial")
        xin_spatial_calc_config.setStreamName("spatial_calc_config")
        # Stereo Depth parameters
        output_depth = True
        output_rectified = False
        lr_check = False
        subpixel = False
        stereo.setOutputDepth(output_depth)
        stereo.setOutputRectified(output_rectified)
        stereo.setConfidenceThreshold(255)
        stereo.setLeftRightCheck(lr_check)
        stereo.setSubpixel(subpixel)
        # Mono L / R -> Stereo L / R
        mono_l.out.link(stereo.left)
        mono_r.out.link(stereo.right)
        # Passtrough Stereo -> Stereo Calc -> Output Depth
        # spatial_calc.passthroughDepth.link(xout_depth.input)
        # Stereo Depth -> Stereo Calc
        stereo.depth.link(spatial_calc.inputDepth)
        # Configure the initial ROI (Body center) for Spatial Calc
        spatial_calc.setWaitForConfigInput(False)
        first_config = dai.SpatialLocationCalculatorConfigData()
        first_config.depthThresholds.lowerThreshold = PARAMS['ROI_DP_LOWER_TH']
        first_config.depthThresholds.upperThreshold = PARAMS['ROI_DP_UPPER_TH']
        first_config.roi = dai.Rect(PARAMS['INITIAL_ROI_TL'], PARAMS['INITIAL_ROI_BR'])
        spatial_calc.initialConfig.addROI(first_config)
        # # Spatial Calc -> Out spatial
        # spatial_calc.out.link(xout_spatial_data.input)
        # In spatial_calc_config -> Spatial Calc Config
        # # xin_spatial_calc_config.out.link(spatial_calc.inputConfig)

        # Color Camera
        print("[{}]: Color Camera...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        cam = pipeline.createColorCamera()
        cam.setPreviewSize(self.preview_width, self.preview_height)
        cam.setInterleaved(False)
        cam.setBoardSocket(dai.CameraBoardSocket.RGB)
        cam_out = pipeline.createXLinkOut()
        cam_out.setStreamName("cam_out")
        cam.preview.link(cam_out.input)

        # Palm Detector
        print("[{}]: Mediapipe Palm Detector NN...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        pd_nn = pipeline.createNeuralNetwork()
        pd_nn.setBlobPath(str(Path(self.pd_path).resolve().absolute()))
        pd_nn.setNumInferenceThreads(2)
        pd_in = pipeline.createXLinkIn()
        pd_in.setStreamName("pd_in")
        pd_in.out.link(pd_nn.input)
        pd_out = pipeline.createXLinkOut()
        pd_out.setStreamName("pd_out")
        pd_nn.out.link(pd_out.input)

        # Hand Landmark Detector
        print("[{}]: Mediapipe Hand Landmark NN...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        lm_nn = pipeline.createNeuralNetwork()
        lm_nn.setBlobPath(str(Path(self.lm_path).resolve().absolute()))
        lm_nn.setNumInferenceThreads(2)
        lm_in = pipeline.createXLinkIn()
        lm_in.setStreamName("lm_in")
        lm_in.out.link(lm_nn.input)
        lm_out = pipeline.createXLinkOut()
        lm_out.setStreamName("lm_out")
        lm_nn.out.link(lm_out.input)

        print("[{}]: Pipeline Created...".format(
            datetime.now().strftime("%d/%m/%Y %H:%M:%S")
            )
        )
        return pipeline

    def run(self):
        pipeline = self.create_pipeline()
        with dai.Device(pipeline) as device:
            print(device.startPipeline())

            # Queues
            # 1. Out: Video output
            q_video = device.getOutputQueue(name="cam_out", maxSize=1, blocking=False)
            # 2. In: Palm Detector Input
            q_pd_in = device.getInputQueue(name="pd_in")
            # 3. Out: Palm Detector Output
            q_pd_out = device.getOutputQueue(name="pd_out", maxSize=4, blocking=False)
            # 4. Landmarks Out
            q_lm_out = device.getOutputQueue(name="lm_out", maxSize=4, blocking=False)
            # 5. Landmarks In
            q_lm_in = device.getInputQueue(name="lm_in")
            # 6. Out: Depth
            #q_d = device.getOutputQueue(name="depth", maxSize=4, blocking=False)
            # 7. Out: Spatial Avg Estimation (Calculator)
            #q_spatial = device.getOutputQueue(name="spatial", maxSize=4, blocking=False)
            # 8. In: Config for Spatial Calculator
            #q_spatial_config = device.getInputQueue("spatial_calc_config")

            while True:
                in_video = q_video.get()
                video_frame = in_video.getCvFrame()

                # Dimensions of the Video Frame
                h, w = video_frame.shape[:2]
                self.h = h
                self.w = w
                # Padding top and bottom
                self.frame_size = max(self.h, self.w)
                self.pad_h = int((self.frame_size - self.h)/2)
                self.pad_w = int((self.frame_size - self.w)/2)

                video_frame = cv2.copyMakeBorder(
                    video_frame,
                    self.pad_h,
                    self.pad_h,
                    self.pad_w,
                    self.pad_w,
                    cv2.BORDER_CONSTANT
                )

                frame_nn = dai.ImgFrame()
                frame_nn.setWidth(self.pd_input_length)
                frame_nn.setHeight(self.pd_input_length)
                frame_nn.setData(to_planar(video_frame, (self.pd_input_length, self.pd_input_length)))
                q_pd_in.send(frame_nn)

                annotated_frame = video_frame.copy()

                # Get palm detection
                inference = q_pd_out.get()
                self.pd_postprocess(inference)

                # Data for landmarks
                for region in self.regions:
                    img_hand = mpu.warp_rect_img(
                        region.rect_points,
                        video_frame,
                        self.lm_input_length,
                        self.lm_input_length
                    )
                    nn_data = dai.NNData()
                    nn_data.setLayer("input_1", to_planar(img_hand, (self.lm_input_length, self.lm_input_length)))
                    q_lm_in.send(nn_data)

                # Retrieve Landmarks
                for region in self.regions:
                    inference = q_lm_out.get()
                    self.lm_postprocess(region, inference)
                    self.lm_render(annotated_frame, region)

                    # Print Handedness, and Coordinates
                    if region.lm_score > self.lm_score_threshold:
                        # [0,1] normalization of loandmark points
                        self.lm_transform(region)
                        # self.draw_mean_line(annotated_frame, region)
                        self.draw_min_line_r(annotated_frame, region)

                        # Post message
                        message = self.xy_message(region)
                        self.queue.put(message)

                #annotated_frame = annotated_frame[self.pad_h:self.pad_h+h, self.pad_w:self.pad_w+w]
                # invert
                inverted_frame = annotated_frame.copy()
                inverted_frame = cv2.flip(inverted_frame, 1)
                # show
                cv2.imshow("Landmarks", inverted_frame)
                key = cv2.waitKey(1)
                if key == ord('q') or key == 27:
                    message = self.stop_message()
                    self.queue.put(message)

                    break
                elif key == 32:
                    # Pause on space bar
                    cv2.waitKey(0)

            # message = self.stop_message()
            # self.queue.put(message)

# Create Synth in supercollider
class EtherSynth:
    def __init__(
            self,
            sc_server,
            sc_port
        ):
        self.sc_server = sc_server
        self.sc_port = sc_port
        print("> Initializing SC Client at {}:{} <".format(self.sc_server, self.sc_port))

    def set_tone(self, frequency):
        print("------> theremin freq: {} Hz <------".format(frequency))
        sc_client = udp_client.SimpleUDPClient(self.sc_server, self.sc_port)
        sc_client.send_message("/main/f", frequency)

    def set_volume(self, volume):
        print("------> theremin vol: {} <------".format(volume))
        sc_client = udp_client.SimpleUDPClient(self.sc_server, self.sc_port)
        sc_client.send_message("/main/a", volume)

# Process messages from inference (specific hand landmarks)
# and send proper parameters to synthesizer
class SynthMessageProcessor(threading.Thread):
    def __init__(
            self,
            queue,
            synth,
            scale,
            min_freq=PARAMS['SCREEN_MIN_FREQ'],
            max_freq=PARAMS['SCREEN_MAX_FREQ']
        ):
        threading.Thread.__init__(self)
        self.synth = synth
        self.queue = queue
        self.active = True
        self.screen_min_freq = min_freq
        self.screen_max_freq = max_freq
        # Scale
        self.scale = scale

        # Vol
        self.volume = 0

    # Process a Hand Landmark Message
    def process(self, message):
        landmarks = 1.0 - message['original_xy']
        # print(landmarks)
        # pos = landmarks[PARAMS['LANDMARKS'], 0]
        pos = landmarks[:, 0]
        # mean_pos_x = np.mean(pos)
        max_pos_x = np.max(pos)

        # Rigth Hand: Tone Control
        if message['handedness'] == 'R':
            if max_pos_x >= self.screen_min_freq:
                # clip and rescale to [0,1]
                tmp_x = np.clip(max_pos_x, self.screen_min_freq, self.screen_max_freq)
                # tmp_x = np.clip(mean_pos_x, self.screen_min_freq, self.screen_max_freq)
                x = (tmp_x - self.screen_min_freq) / (self.screen_max_freq - self.screen_min_freq)
                # convert freq
                freq = self.scale.from_0_1_to_f(x)
                # send to synth
                self.synth.set_tone(freq)

        # Left Hand: Volume Control
        if message['handedness'] == 'L':
            lm_l = 1.0 - message['original_xy_y_rescaled']
            # print(lm_l)
            pos_y = lm_l[PARAMS['LANDMARKS'], 1]
            min_pos_y = np.min(pos_y)
            max_pos_y = np.max(pos_y)
            if max_pos_y > self.volume:
                self.volume = max_pos_y
            else:
                self.volume = min_pos_y
            # clip to [0,1]
            y = np.clip(self.volume, 0, 1)

            if y > 0.8:
                y = 1
            if y < 0.2:
                y = 0

            # send to synth
            self.synth.set_volume(y)

    # Run thread
    def run(self):
        while self.active:
            message = self.queue.get()
            if 'STOP' in message:
                self.active = False
            else:
                # Process
                self.process(message)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('--scserver', default="{}".format(PARAMS['SC_SERVER']), type=str,
                        help="IP Address of Supercollider Server")
    parser.add_argument("--scport", default=PARAMS['SC_PORT'], type=int,
                        help="Port of Supercollider Server")
    args = parser.parse_args()

    scale = eqtmp.EqualTempered(octaves=3, start_freq=440, resolution=1000)
    # Create Synthesizer
    synth = EtherSynth(args.scserver, args.scport)
    # Message Queues
    messages = Queue.Queue()
    # Process Thread
    smp = SynthMessageProcessor(messages, synth, scale)
    smp.start()
    # OAKD inference processor
    there = Ether(messages)
    there.run()


import json
def permutations(array):
    if len(array) == 0:#沒有元素的時候
        return [[]]
    if len(array) == 1:
        return [array]
    else:
        arr = []
        for i in range(len(array)):
            array[0], array[i] = array[i], array[0]#決定第一個固定的數字
            start = array[0]
            end = permutations(array[1:])#往下切陣列
            for x in end:
                arr.append([start]+x)#頭加尾
    return arr
def BF(input):
    N = len(input)
    a =[]
    l=[]
    sum=0
    min=10000000
    cost=input
    for i in range(N):#產生可能的排列
        a.append(i)
    l=permutations(a)
    for p in range(len(l)):
        sum=0
        for job in range(N):
            sum+=cost[job][l[p][job]]#job 跟 agent 對應,p代表第幾個組合
        if sum<min:#找最小可能
            assign=l[p]
            min=sum
    return min,assign

# main
with open('input.json', 'r') as inputFile:
    data = json.load(inputFile) # load data
    for key in data:
        input = data[key] # load each input

        # Brute Force Algorithm

        min,assignment = BF(input)

        print('Question: ' + str(key))
        print('Assignment:', assignment)
        print('Cost:', min)
        print()


import os.path
import time

from androguard.core.bytecodes.apk import APK
from androguard.misc import AnalyzeAPK
import util
from util import logger

def get_features(file_path):
    time_start = time.time()
    if os.path.isdir(file_path):
        return
    file_output_parts = os.path.splitext(file_path)[0].split("/")
    file_output_parts[-1] += ".json"
    file_output_parts.insert(len(file_output_parts)-1, "json")
    file_output_path = ""
    for part in file_output_parts:
        file_output_path = os.path.join(file_output_path, part)
    file_output_dir = file_output_path[:file_output_path.rfind("\\")]
    if not os.path.exists(file_output_dir):
        os.mkdir(file_output_dir)
    if os.path.exists(file_output_path):
        logger.info("the APK " + file_path + " already abstracted")
        return

    logger.info("start to analyze the APK " + file_path + "...")
    a = APK(file_path)
    data = {}
    declared_xml_pms = set()
    declared_pms = set()
    activities = set()
    services = set()
    providers = set()
    receivers = set()
    hardware = set()

    for pms in a.get_permissions():
        declared_xml_pms.add(pms)
    for pms in a.get_declared_permissions():
        declared_pms.add(pms)
    for activity in a.get_activities():
        activities.add(activity)
    for service in a.get_services():
        services.add(service)
    for provider in a.get_providers():
        providers.add(provider)
    for receiver in a.get_receivers():
        receivers.add(receiver)
    for feature in a.get_features():
        hardware.add(feature)
    data['declared_xml_pms'] = declared_xml_pms
    data['declared_pms'] = declared_pms
    data['activities'] = activities
    data['services'] = services
    data['providers'] = providers
    data['receivers'] = receivers
    data['hardware'] = hardware

    sensitive_apis = set()
    android_suspicious_apis = ["getExternalStorageDirectory", "getSimCountryIso", "execHttpRequest",
                               "sendTextMessage", "getSubscriberId", "getDeviceId", "getPackageInfo",
                               "getSystemService", "getWifiState",
                               "setWifiEnabled", "setWifiDisabled", "Cipher"]
    other_suspicious_apis = ["Ljava/net/HttpURLconnection;->setRequestMethod(Ljava/lang/String;)",
                             "Ljava/net/HttpURLconnection",
                             "Lorg/apache/http/client/methods/HttpPost",
                             "Landroid/telephony/SmsMessage;->getMessageBody",
                             "Ljava/io/IOException;->printStackTrace", "Ljava/lang/Runtime;->exec"]
    a, d, dx = AnalyzeAPK(file_path)
    for method in dx.get_methods():
        api = str(method.get_method())
        for other_suspicious_api in other_suspicious_apis:
            if other_suspicious_api in api:
                sensitive_apis.add(api)
        if (";->" not in api) or (not api.startswith("Landroid")):
            continue
        api_parts = api.split(";->")
        api_class = api_parts[0].strip()
        api_name = api_parts[1].split("(")[0].strip()
        if api_name in android_suspicious_apis:
            sensitive_apis.add(api_class + ";->" + api_name)
    data['sensitive_apis'] = sensitive_apis

    util.get_json(file_output_path, data)
    time_final = time.time()
    logger.info(file_path + " analyzed successfully in " + str(time_final - time_start) + "s")

def solution(*paths):
    apk_list = []
    for path in paths:
        apk_list.extend(util.get_file_list(path))

    for path in apk_list:
        get_features(path)


import numpy as np
from six import string_types, integer_types
from synge.shape import _intradistance_aux, _aux_rms

def _validate_shape(shape):
    if not (
        hasattr(shape, "__iter__") and (len(shape) == 2 or len(shape) == 1)
    ) and not isinstance(shape, integer_types):
        raise ValueError('Error! "shape" must be an integer or a tuple with size 2!')
    return True

def _validate_shape_intradistance(shape):
    if not (hasattr(shape, "__iter__") and len(shape) == 2):
        raise ValueError('Error! "shape" must be a tuple with size 2!')
    return True

distributions_list = {
    "uniform": lambda shape, param1, param2: np.random.uniform(
        param1 - param2, param1 + param2, shape
    ),
    "gaussian": lambda shape, param1, param2: np.random.normal(param1, param2, shape),
    "logistic": lambda shape, param1, param2: np.random.logistic(param1, param2, shape),
    # "triangular": lambda shape, param1,param2: np.random.triangular(-param1, 0, param2, shape),
    # "gamma": lambda shape, param1,param2: np.random.gamma(
    #     2 + 8 * np.random.rand(), param1 / 5, shape
    # ),
    # "gap": lambda shape, param1,param2: gap(shape, param1),
    # "binaire": lambda shape, param1,param2: np.random.choice([0, 1], shape),
}
"""List of distributions for which you can just provide a string as input."""

# Aliases for distributions should be put here.
distributions_list["normal"] = distributions_list["gaussian"]

valid_distributions = distributions_list.keys()
"""List of valid strings for distributions."""

class Distribution(object):
    def __init__(self, f, **kwargs):
        self.f = f
        self.kwargs = kwargs

    def __call__(self, shape, intra_distance, *args, **kwargs):
        new_kwargs = self.kwargs.copy()
        new_kwargs.update(kwargs)  # add keyword arguments given in __init__
        if intra_distance:
            assert _validate_shape_intradistance(shape)
            out = _intradistance_aux(shape)
            return out * self.f((shape[0], 1), *args, **new_kwargs)
        else:
            assert _validate_shape(shape)
            return self.f(shape, *args, **new_kwargs)

def gap(shape, param):
    out = np.zeros(shape)
    try:
        for j in range(shape[1]):
            new_shape = (2 * shape[0], 1)
            aux = np.random.normal(0, param, new_shape)
            med_aux = _aux_rms(aux)
            median = np.median(med_aux)
            out[:, j] = aux[med_aux > median][: shape[0]]
    except BaseException:
        j = 0
        new_shape = (2 * shape[0], 1)
        aux = np.random.normal(0, param, new_shape)
        med_aux = _aux_rms(aux)
        median = np.median(med_aux)
        out[:, j] = aux[med_aux > median][: shape[0]]
    return out

def get_dist_function(d):
    """
    Transforms distribution name into respective function.
    Args:
        d (str or function): Input distribution str/function.
    Returns:
        function: Actual function to compute the intended distribution.
    """
    if isinstance(d, Distribution):
        return d
    elif hasattr(d, "__call__"):
        return Distribution(d)
    elif isinstance(d, string_types):
        try:
            return Distribution(distributions_list[d])
        except KeyError:
            raise ValueError(
                'Invalid distribution name "'
                + d
                + '". Available names are: '
                + ", ".join(distributions_list.keys())
            )
    else:
        raise ValueError("Invalid distribution input!")


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

from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop
import pickle
import os
import bz2

from search.snippeter import Snippeter
import search.manifest as manifest

class QueryHandler(RequestHandler):
    def initialize(self, docs, snippeter):
        self.docs = docs
        self.snippeter = snippeter

    def _gen_results(self, docids, q):
        docids = docids.split(",")
        docids = [int(x) for x in docids]
        results = []

        snippets = self.snippeter.snippet_batch(docids, q)

        for docid in docids:
            results.append({
                "doc_id" : docid,
                "title" : self.docs[docid]["metadata"]["title"],
                "url" : self.docs[docid]["metadata"]["url"],
                "snippet" : snippets[docid],
            })

        return results

    def get(self):
        docids = self.get_argument("id")
        q = self.get_argument("q")
        self.write({
            "results" : self._gen_results(docids, q)
        })

def make_doc_app(doc_f, tfidf_f, snippet_len):
    docs = pickle.load(bz2.open(doc_f, "rb"))
    tfidf = pickle.load(open(tfidf_f, "rb"))
    snippeter = Snippeter(tfidf, docs, snippet_len)
    app = Application([
        (r'/doc', QueryHandler, dict(docs=docs, snippeter=snippeter))
    ])

    return app

'''
import re

def get_port(url):
    return int(re.findall(r':([0-9]+)', url)[0])

if __name__ == "__main__":
    import sys
    srv_id = int(sys.argv[1])
    app = make_doc_app(srv_id)
    app.listen(get_port(manifest.DOC_SRV[srv_id]))
    IOLoop.current().start()
'''


import scapy.all as scapy
from scapy_http import http

def listen_packets(interface):
    print("------------------------------------------------")
    print("Packet Listener has started working.")
    scapy.sniff(iface=interface, store=False, prn=analyze_packets)

def analyze_packets(packet):
    if packet.haslayer(http.HTTPRequest):
        if packet.haslayer(scapy.Raw):
            print(packet[scapy.Raw].load)


import itertools
from typing import Union, List, Tuple

from allennlp.data.dataset_readers import DatasetReader
from allennlp.data import Vocabulary
from torch.utils.data import Dataset
from allennlp.data.dataset import Batch
from allennlp.data.instance import Instance

class AllennlpDataset(Dataset):

    def __init__(self,
                 vocab: Vocabulary,
                 iterable: List=None,
                 reader: DatasetReader=None,
                 dataset_path: Union[str, List[str], Tuple[str]]=None
                 ):

        self.vocab = vocab
        self.reader = reader
        self.dataset_path = dataset_path
        if iterable is not None:
            self.iterable = iterable
        else:
            assert reader is not None and dataset_path is not None
            if type(dataset_path) in [list, tuple]:
                self.iterable = list(itertools.chain(*[self.reader.read(x) for x in dataset_path]))
            else:
                self.iterable = self.reader.read(dataset_path)
        self.iterator = (x for x in self.iterable)

        self._length = None

    def __len__(self):
        """
        This is gross but will go away in the next pytorch release,
        as they are introducing an `IterableDataset` class which doesn't
        need to have a length:
        https://pytorch.org/docs/master/data.html#torch.utils.data.IterableDataset
        """
        if self._length is None:
            self._length = 0
            for i in self.iterator:
                self._length += 1
            self.iterator = (x for x in self.iterable)
        return self._length

    def __getitem__(self, idx) -> Instance:
        get_next = next(self.iterator, None)
        if get_next is None:
            self.iterator = (x for x in self.iterable)
            get_next = next(self.iterator)
        return get_next

    # Function to tell the torch DataLoader how to batch up our custom data, i.e Instances
    def allennlp_collocate(self, batch):
        batch = Batch(batch)
        batch.index_instances(self.vocab)
        return batch.as_tensor_dict(batch.get_padding_lengths())


#!/usr/bin/env python3
from tkinter import*
import rospy
from std_msgs.msg import Int16

frame=Tk()
frame.geometry("200x200")
L1= Label(frame,font=('Arial',40), text = "0")
L1.pack()

rospy.init_node('GUI')
rate = rospy.Rate(10)
rate.sleep()

def read(num):
    sensor_read = num.data
    L1.config(text=str(sensor_read))

sub = rospy.Subscriber('Topic_Sensor', Int16, callback= read)

frame.mainloop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec  1 10:07:10 2017

@author: eduardopoleo
"""

# Building the CNN
from keras.models import Sequential
from keras.layers import Conv2D # images are 2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten # conver the feature map into the vector to feed the NN
from keras.layers import Dense

# Initializing the CNN

classifier = Sequential()

# Convolution
#args:
# number of feature detectors ( the more the better usually )
# number of columns per feature detector
# number of rows per feature detector
# input_shape(dim1, dim2, number_of_channels)
classifier.add(Conv2D(32, (3, 3), input_shape = (32, 32, 3), activation = 'relu')) # tensorflow backend order

# Pooling
# pool_size: size of the subtable that slides over the feature table to choose the max feature
classifier.add(MaxPooling2D(pool_size = (2,2)))

# Train Acc: 0.80, Test Acc: 0.77
# Adding an additional layer to improve Acc results:

classifier.add(Conv2D(32, (3, 3), activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2,2)))

# Flattening
classifier.add(Flatten())

# Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))

# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Fitting the CNN to the images taken from (https://keras.io/preprocessing/image/)

from keras.preprocessing.image import ImageDataGenerator

# pre proccessing the image to prevent overfitting
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

# just need to scale the test set not process it cuz it's used on predictions
test_datagen = ImageDataGenerator(rescale=1./255)

training_set = train_datagen.flow_from_directory(
        'dataset/training_set',
        target_size=(32, 32),
        batch_size=32,
        class_mode='binary')

# the dimensions to which all images found will be resized.
# Default: (256, 256). Do not know if you can go higher
# In general higher better cuz we have more information about the pixels but it's more
# computational intensive.
test_set = test_datagen.flow_from_directory(
        'dataset/test_set',
        target_size=(32, 32),
        batch_size=32,
        class_mode='binary')

history = classifier.fit_generator(
        training_set,
        steps_per_epoch=8000/32, # number of batches to be considered on the training set
        epochs=1) # number of batches to bbe considered on the test set.

# Part 3, Making new prediction

import numpy as np
from keras.preprocessing import image

test_image = image.load_img('dataset/single_prediction/cat_or_dog_2.jpg', target_size=(32, 32))
test_image = image.img_to_array(test_image) # add the color dimention => 3
test_image = np.expand_dims(test_image, axis = 0)
result = classifier.predict_generator(test_image, steps = 2000/32)

training_set.class_indices