# Order to call these functions in:
# /createGame
# for each user in game.num_users:
#   /addUser
# for each round in game.num_rounds:
#   for each user in game.num_users:
#       /makeMarket
#   /playRound
#   /roundTransactions
#   /roundUnrealizedPnls
# /finalRoundRealizedPnls
# /finalRoundTotalPnls

import enum
from flask import Flask, json, request, jsonify, session, Response, Blueprint
from collections import OrderedDict
import copy
from .game import Game
from .player import Player
import sys

from .cache import cache
from .cache_api import cache as user_cache

gameA_api = Blueprint('gameA_api', __name__)

# TODO Configure for multiple games and with multiple players
@gameA_api.before_app_first_request
@cache.cached(timeout=300, key_prefix='game_users')
def create_game_users():
    return []

@gameA_api.route('/createGame', methods=['POST'])
def create_game():
    """
    Example body:
    {
        "true_values": [10, 20, 30],
        "num_players": 5,
        "override": true
    }
    """
    game = cache.get("game")
    game_users = cache.get('game_users')

    new_game = Game(true_values=request.json['true_values'], num_players=request.json['num_players'])
    if request.json.get("override", False):
        cache.clear()
        cache.set("game", new_game)
        cache.set("game_users", [])
    elif game is not None:
        return Response('Game already created', status=200)

    game = Game(true_values=request.json['true_values'], num_players=request.json['num_players'])

    for i in range(request.json['num_players']):
        game_users.append("Player {}".format(i))

    cache.set("game", game)
    cache.set('game_users', game_users)
    return Response('Game created', status=200)

@gameA_api.route('/addName', methods=['POST'])
def add_name():
    """
    Adds the name of the players.
    {
        'usernames': Alex Bob Charlie David Eevee
    }
    :return:
    """
    game_users = cache.get('game_users')
    msg = request.json['usernames']
    msg = msg.split()

    # Check user limit
    game = cache.get('game')
    if len(msg) > game.num_players:
        return Response("Exceeds max users", status=400)

    game.player_setup(msg)
    game_users = copy.deepcopy(msg)

    # Cache
    cache.set('game_users', game_users)
    cache.set('game', game)
    return Response(json.dumps(game_users), status=200)

def verify_get_user_pos(user_data):
    '''
    Helper function used to verify user and get user position,
    for setter functions (POST requests).
    '''
    game_users = cache.get('game_users')

    position = -1
    for i, pair in enumerate(game_users):
        if user_data == game_users[i]:
            position = i
            break
    if position == -1:
        return Response('User not in game', status=400)

    # Verification
    # users = user_cache.get('users')
    # verification = verify_user(user_data)
    # if verification.status_code != 200:
    #     return verification

    return position

@gameA_api.route("/makeMarket", methods=['POST'])
def make_market():
    '''
    Expects json data for a particular player to have:
    {
        "user": "Alex",
        "q1_bid": 0,
        "q1_ask": 0,
        "q1_bid_size": 0,
        "q1_ask_size": 0,
        "q2_bid": 0,
        "q2_ask": 0,
        "q2_bid_size": 0,
        "q2_ask_size": 0,
        "q3_bid": 0,
        "q3_ask": 0,
        "q3_bid_size": 0,
        "q3_ask_size": 0
    }
    '''
    game = cache.get('game')
    try:
        data = request.json
        user_data = data['user']  # username
        q1_bid, q1_bid_size, q1_ask, q1_ask_size = float(data['q1_bid']), int(data['q1_bid_size']), float(data['q1_ask']), int(data['q1_ask_size'])
        q2_bid, q2_bid_size, q2_ask, q2_ask_size = float(data['q2_bid']), int(data['q2_bid_size']), float(data['q2_ask']), int(data['q2_ask_size'])
        q3_bid, q3_bid_size, q3_ask, q3_ask_size = float(data['q3_bid']), int(data['q3_bid_size']), float(data['q3_ask']), int(data['q3_ask_size'])
    except:
        return Response(status=400)

    position = verify_get_user_pos(user_data)
    if isinstance(position, Response):
        return position  # return whatever error response the helper function gave

    try:
        assigned = game.players[position].assign_bids_and_asks([q1_bid_size, q1_bid, q1_ask, q1_ask_size], [q2_bid_size, q2_bid, q2_ask, q2_ask_size], [q3_bid_size, q3_bid, q3_ask, q3_ask_size])
    except Exception as e:
        return Response(str(e), status=400)

    cache.set('game', game)
    return Response(assigned, status=200)

@gameA_api.route("/playRound", methods=['POST'])
def play_round():
    '''
    Game class calculates all the transactions between players.
    First checks if all players have inputted their most recent markets
    No input needed for this function call.
    Call this function after all users have put in their markets for a given round.
    This function doesn't return anything, call the functions below for that.
    '''

    # Uncache game
    game = cache.get('game')
    game_users = cache.get('game_users')

    if len(game_users) != game.num_players:
        return Response("Not enough users", status=400)

    # make sure every user has inputted data exactly k times (where k is the current round of game)
    # for user, markets_made in game_users:
    #     if markets_made != game.num_rounds_played + 1:
    #         return Response("Mismatch between current round number and user's round", status=400)

    # Grab data
    try:
        result_bool = game.play_round()
    except Exception as e:
        return Response(str(e), status=400)

    # Recache game
    cache.set('game', game)

    return Response(result_bool, status=200)

@gameA_api.route('/undo', methods=['POST'])
def undo():
    """
    Undo last action
    """
    game = cache.get('game')

    # Perform action
    try:
        game = game.undo()
    except Exception as e:
        return Response(str(e), status=400)

    # Recache game
    cache.set('game', game)

    return Response("Undo", status=200)

@gameA_api.route('/end', methods=['POST'])
def end_game():
    """
    Ends the Game
    """
    game = cache.get('game')

    game.end_game = True

    # Cache
    cache.set('game', game)
    return Response("END GAME", status=200)

@gameA_api.route("/players", methods=['GET'])
def get_players():
    """
    Returns a list of usernames
    Example response:
    {
      ["Alex", "Bob", "Charlie"]
    }
    """
    users = cache.get('game_users')
    return Response(json.dumps(users), status=200)

@gameA_api.route("/market", methods=['GET'])
def get_market():
    """
    Returns all players' market
    """
    game = cache.get('game')
    response = game.get_market()
    return Response(json.dumps(response), status=200)

@gameA_api.route("/transaction", methods=['GET'])
def get_transaction():
    game = cache.get('game')
    response = game.get_last_transaction_display()
    return Response(json.dumps(response), status=200)

@gameA_api.route("/pnl", methods=['GET'])
def get_pnl_table():
    game = cache.get('game')
    response = game.get_adjusted_pnl_table()
    return Response(json.dumps(response), status=200)

@gameA_api.route("/finalRoundTotalPnls", methods=['GET', 'POST'])
def get_final_pnls():
    game = cache.get('game')
    try:
        response = game.pnls
    except:
        return Response("Didn't play final round yet", status=400)
    return Response(json.dumps(response), status=200)

@gameA_api.route("/avgTransaction", methods=['GET'])
def get_avg_transaction():
    game = cache.get('game')
    response = game.get_avg_transactions_prices()
    return Response(json.dumps(response), status=200)


#!/usr/bin/python3
# -*- coding: utf-8 -*-
#
# pip install TwitterAPI

# http://www.moongiant.com/fullmoons/2018/

import sys
from json import load
from time import localtime
from time import strftime
from time import sleep
from os import path
from os import listdir
from random import randint
#from TwitterAPI import TwitterAPI
from mastodon import Mastodon

local_time = localtime()

year =  strftime("%Y", local_time)

with open(sys.path[0]+"/ilargia-"+year+".json", 'r') as f:
	j = load(f)

local_time = strftime("%Y-%m-%d", local_time)

found = False
for date in j:
        if date == local_time:
                found = True

if found == False:
	sys.exit()

# ze motatako irudidxek okinguz kontutan
allow_extension = ['.mp4', '.gif']

# irudiaren path-a hartu
#image_path = path.dirname(path.realpath(__file__))+"/images"
image_path = sys.path[0]+"/images"

if path.isdir(image_path):
	files = listdir(image_path)
else:
	print("Karpeta "+image_path+" ez da existitzen")
	sys.exit()

# irudi danak images dict-en sartun
images = {}
j = 0
for i in files:
	file_path = path.join(image_path, i)
	if path.isfile(file_path):
		extension = path.splitext(file_path)[1]
		if extension.lower() in allow_extension:
			images[j] = file_path
			j = j+1

# twitterrera argazkidxe idxen

#r = 0
#images = [sys.path[0]+"/ilargi_gorri.jpg"]

mastodon = Mastodon(
    access_token = sys.path[0]+"/mastodon.credentials",
    api_base_url = 'https://botsin.space'
)

# ikusi ia baten bat badauen
images_all = images
len = len(images.keys())
if len>0:
	r = randint(0, j-1)
	file = images[r]
	a = mastodon.media_post(file);
	images = []
	images.append([a.id])
else:
	images = []

# 30 segundu utziko diogu mastodonera irudi/bideoa igotzeko...
sleep(30)

title = 'ilargi betie... 🐺🌕 #zitalbot'

m = mastodon.status_post(title, None, images)

data = open(images_all[2], 'rb') # 01.gif
data = data.read()

"""
#title = title.decode('utf-8')+"\n"

with open(sys.path[0]+"/twitter.credentials", 'r') as f:
	j = load(f)

api = TwitterAPI(j['CONSUMER_KEY'], j['CONSUMER_SECRET'], j['ACCESS_TOKEN_KEY'], j['ACCESS_TOKEN_SECRET'])
r = api.request('media/upload', None, {'media': data})
media_id = r.json()['media_id']

r = api.request('statuses/update', {'status':title+"\n"+m.url, 'media_ids':media_id})

if r.status_code == 200:
	print("Txioa ondo bidali da ;)")
else:
	print("Errorea txioa bidaltzerakoan status code: "+r.status_code)

"""
sys.exit()


import cv_utils
import numpy as np
import math
import logging

logger = logging.getLogger(__name__)

def compare_calibrations(
    old_calibrations,
    new_calibrations
):
    old_device_ids = set(old_calibrations.keys())
    new_device_ids = set(new_calibrations.keys())
    common_device_ids = old_device_ids.intersection(new_device_ids)
    logger.info('Comparing {} old calibrations with {} new calibrations'.format(
        len(old_device_ids),
        len(new_device_ids)
    ))
    logger.info('Old and new calibrations contain {} common devices'.format(
        len(common_device_ids)
    ))
    calibration_comparisons = dict()
    for device_id in common_device_ids:
        relative_rotation_vector, relative_translation_vector = cv_utils.compose_transformations(
            rotation_vector_1=new_calibrations[device_id]['rotation_vector'],
            translation_vector_1=np.array([0.0, 0.0, 0.0]),
            rotation_vector_2=-old_calibrations[device_id]['rotation_vector'],
            translation_vector_2=np.array([0.0, 0.0, 0.0])
        )
        orientation_difference_angle_radians = np.linalg.norm(relative_rotation_vector)
        orientation_difference_angle_degrees = orientation_difference_angle_radians*360/(2*math.pi)
        orientation_difference_direction = relative_rotation_vector/orientation_difference_angle_radians
        old_position = cv_utils.extract_camera_position(
            rotation_vector=old_calibrations[device_id]['rotation_vector'],
            translation_vector=old_calibrations[device_id]['translation_vector'],
        )
        new_position = cv_utils.extract_camera_position(
            rotation_vector=new_calibrations[device_id]['rotation_vector'],
            translation_vector=new_calibrations[device_id]['translation_vector'],
        )
        position_difference = new_position - old_position
        position_difference_distance = np.linalg.norm(position_difference)
        position_difference_direction = position_difference/position_difference_distance
        calibration_comparisons[device_id] = {
            'orientation_difference_angle_radians': orientation_difference_angle_radians,
            'orientation_difference_angle_degrees': orientation_difference_angle_degrees,
            'orientation_difference_direction': orientation_difference_direction,
            'position_difference_distance': position_difference_distance,
            'position_difference_direction': position_difference_direction
        }
    return calibration_comparisons


import argparse
import sys

import keras
from keras.models import *
from keras.layers import *
from keras import *
import os

##  DNN ==> C
def c_convert(model, path=''):
  prog=''

  ##  input, we assume that channel is in behind
  ##  uint8_t 'input[channel][row][column]'
  try:
    input_shape=model.layers[0].input.shape
    channel=input_shape[3].value
    row=input_shape[1].value
    column=input_shape[2].value
    fc = False
  except: fc = True

  ## prog+='  ' + 'uint8_t input[{0}][{1}][{2}];\n'.format(channel, row, column)
  #prog='#include \"network.h\"\n'
  prog+='#include <unistd.h>\n'
  prog+='#include <string.h>\n'
  prog+='#include <stdio.h>\n'
  prog+='#include <stdlib.h>\n'
  if not fc:
    prog+='unsigned network(float input[{0}][{1}][{2}])\n'.format(row, column, channel)
  else:
    prog+='unsigned network(float input[{0}])\n'.format(input_shape[1].value)
  prog+='{\n'

  iw=0 ## index of weights layer

  ##  Assumption: kernel is a box shape and stride is 1
  ##  Assumption: convolutional layer is of type '2d'
  ##  Assumption: channel is put behind
  for l in range(0, len(model.layers)):

    layer=model.layers[l]
    name=layer.name
    _inp=layer.input
    _out=layer.output
    is_conv=(name.find('conv2d')>=0)
    is_dense=(name.find('dense')>=0)
    is_activation=(name.find('activation')>=0)
    is_maxpooling=(name.find('max_pooling')>=0)
    is_flatten=(name.find('flatten')>=0)
    is_dropout=False ##   we do not allow dropout
    activation=''
    if is_conv or is_dense or is_activation: activation=layer.activation
    is_relu=(str(activation).find('relu')>=0) ##  (not is_relu) ==> is_linear

    prog+='\n  //  layer {0}: {1}\n'.format(l, name)

    weights=[]
    biases=[]
    if is_dense or is_conv:
      weights=model.get_weights()[iw]
      biases=model.get_weights()[iw+1]
      iw+=2

    if is_conv:
      prog+='  float layer{3}[{0}][{1}][{2}];\n'.format(_out.shape[1].value, _out.shape[2].value, _out.shape[3].value, l)
      kernel_size=layer.kernel_size ##  Assumption: kernels are of box shape with stride 1
      for i in range(0, _out.shape[1].value):
        for j in range(0, _out.shape[2].value):
          for k in range(0, _out.shape[3].value):
            prog+='  layer{0}[{1}][{2}][{3}]={4}'.format(l, i, j, k, biases[k])
            for I in range(0, kernel_size[0]):
              for J in range(0, kernel_size[1]):
                for K in range(0, weights.shape[2]): ## number of precendent filters
                  if l==0:
                    prog+=' + ({0})*input[{1}][{2}][{3}]'.format(weights[I][J][K][k], i+I, j+J, K)
                  else:
                    prog+=' + ({0})*layer{4}[{1}][{2}][{3}]'.format(weights[I][J][K][k], i+I, j+J, K, l-1)
            prog+=';\n'
            if is_relu:
              prog+='        if(layer{0}[{1}][{2}][{3}]<0) layer{0}[{1}][{2}][{3}]=0;\n'.format(l, i, j, k)
    elif is_flatten:
      s=_inp.shape[1].value * _inp.shape[2].value * _inp.shape[3].value
      prog+='  float layer{0}[{1}];\n'.format(l, s)
      for i in range(0, s):
        d0=int(i/(_inp.shape[2].value * _inp.shape[3].value))
        d1=int(( i % (_inp.shape[2].value * _inp.shape[3].value) ) / _inp.shape[3].value)
        d2=i - int(d0*(_inp.shape[2].value * _inp.shape[3].value)) - int(d1*_inp.shape[3].value)
        prog+='  layer{0}[{2}]=layer{1}[{3}][{4}][{5}];\n'.format(l, l-1, i, d0, d1, d2) ## there shall be a convolutional layer before the flatten layer
    elif is_dense:
      prog+='  float layer{0}[{1}];\n'.format(l, weights.shape[1])
      for i in range(0, weights.shape[1]):
        prog+='  layer{0}[{1}]={2}'.format(l, i, biases[i])
        for I in range(0, weights.shape[0]):
          if l==0:
            prog+=' + ({0})*input[{1}]'.format(weights[I][i], I)
          else:
            prog+=' + ({0})*layer{2}[{1}]'.format(weights[I][i], I, l-1)
        prog+=';\n'
        if is_relu:
          prog+='  if(layer{0}[{1}]<0) layer{0}[{1}]=0;\n'.format(l, i)

    elif is_maxpooling:
      pool_size=layer.pool_size ##  Assumption: maxpooling is of box shape with stride 1
      prog+='  float layer{3}[{0}][{1}][{2}];\n'.format(_out.shape[1].value, _out.shape[2].value, _out.shape[3].value, l)
      for i in range(0, _out.shape[1].value):
        for j in range(0, _out.shape[2].value):
          for k in range(0, _out.shape[3].value):
            prog+='  layer{0}[{1}][{2}][{3}]=0;\n'.format(l, i, j, k)
            ps0=pool_size[0]
            ps1=pool_size[1]
            for I in range(i*ps0, (i+1)*ps0):
              for J in range(j*ps1, (j+1)*ps1):
                prog+='  if(layer{0}[{5}][{6}][{4}]>layer{1}[{2}][{3}][{4}]) layer{1}[{2}][{3}][{4}]=layer{0}[{5}][{6}][{4}];\n'.format(l-1, l, i, j, k, I, J)

    elif is_activation: #is_relu:
      if is_relu:
        if len(_out.shape.as_list())>2:
          prog+='  float layer{3}[{0}][{1}][{2}];\n'.format(_out.shape[1].value, _out.shape[2].value, _out.shape[3].value, l)
          for i in range(0, _out.shape[1].value):
            for j in range(0, _out.shape[2].value):
              for k in range(0, _out.shape[3].value):
                prog+='  if(layer{0}[{2}][{3}][{4}]>0) layer{1}[{2}][{3}][{4}]=layer{0}[{2}][{3}][{4}];\n'.format(l-1, l, i, j, k)
                prog+='  else layer{0}[{1}][{2}][{3}]=0;\n'.format(l, i, j, k)
        else:
          prog+='  float layer{0}[{1}];\n'.format(l, _out.shape[1].value)
          for i in range(0, _out.shape[1].value):
            prog+='  if(layer{0}[{2}]>0) layer{1}[{2}]=layer{0}[{2}];\n'.format(l-1, l, i)
            prog+='  else layer{0}[{1}]=0;\n'.format(l, i)
      else:  ##  we only support ReLU and lienar for now
        if len(_out.shape.as_list())>2:
          prog+='  float layer{3}[{0}][{1}][{2}];\n'.format(_out.shape[1].value, _out.shape[2].value, _out.shape[3].value, l)
          for i in range(0, _out.shape[1].value):
            for j in range(0, _out.shape[2].value):
              for k in range(0, _out.shape[3].value):
                prog+='  layer{1}[{2}][{3}][{4}]=layer{0}[{2}][{3}][{4}];\n'.format(l-1, l, i, j, k)
        else:
          prog+='  float layer{0}[{1}];\n'.format(l, _out.shape[1].value)
          for i in range(0, _out.shape[1].value):
            prog+='  layer{1}[{2}]=layer{0}[{2}];\n'.format(l-1, l, i)
    else:
        if not l==len(model.layers)-1:
          print ('Unrecpgnizable DNN structure...layer {0}'.format(l))
          print (model.layers[l])
          sys.exit(0)

    if l==len(model.layers)-1: ## softmax
      prog+='  unsigned ret=0;\n'
      prog+='  float res=-100000;\n'
      for i in range(0, _out.shape[1].value):
        prog+='  if(layer{0}[{1}]>res)'.format(l, i)
        prog+='  {\n'
        prog+='    res=layer{0}[{1}];\n'.format(l,i )
        prog+='    ret={0};\n'.format(i)
        prog+='  }\n'
      prog+='  return ret;\n'
      break
  ####
  prog+='}\n'

  #index = 3
  #with open('data/mnist_train_csv.txt') as f:
  #  lines = [line.rstrip() for line in f]
  #  inp = lines[index].split(',')
  #  for i in range(0, len(inp)):
  #      inp[i] = (int)(inp[i])

  prog+='int main(int argc, char* argv[]) {\n'
  if not fc:
    prog+='  float finput[{0}][{1}][{2}];\n'.format(row, column, channel)
  else:
    prog+='  float finput[{0}];\n'.format(input_shape[1].value)
    for i in range(0, input_shape[1].value):
        prog += '  finput[{0}]={1};\n'.format(i, _inp[i])
  prog+='  printf(\"%d\",network(finput));\n'

  prog+='}\n'

  #return prog
  dnn_file = open(path+'network.c', 'w')
  #dnn_file.write(prog)
  #dnn_file.close()
  #dnn_file = open('network.h', 'w')
  #prog='#include <stdint.h>\n'
  #if not fc:
  #  prog+='unsigned network(float input[{0}][{1}][{2}]);\n'.format(row, column, channel)
  #else:
  #  prog+='unsigned network(float input[{0}]);\n'.format(input_shape[1].value)
  dnn_file.write(prog)
  dnn_file.close()

#def write_harness(isl):
#  s=0
#  if len(isl)>2: s=isl[1]*isl[2]*isl[3]
#  else: s=isl[1]
#  harness=''
#  harness+='#include "network.h"\n'
#  harness+='#include <unistd.h>\n'
#  harness+='#include <string.h>\n'
#  harness+='#include <stdio.h>\n'
#  harness+='#include <stdlib.h>\n'
#  harness+='\n'
#  harness+='int main(int argc, char* argv[]) {\n'
#  harness+='  uint8_t iinput[{0}][{1}][{2}];\n'.format(isl[1], isl[2], isl[3])
#  harness+='  float finput[{0}][{1}][{2}];\n'.format(isl[1], isl[2], isl[3])
#  harness+='  FILE *myFile;\n'
#  harness+='  if(argc == 2)\n'
#  harness+='  {\n'
#  harness+='    myFile = fopen(argv[1], "r");\n'
#  harness+='    for (int i=0; i < {0}; i++)\n'.format(isl[1])
#  harness+='      for (int j=0; j < {0}; j++)\n'.format(isl[2])
#  harness+='        for (int k=0; k < {0}; k++)\n'.format(isl[3])
#  harness+='        {\n'
#  harness+='          fscanf(myFile, "%d", &iinput[i][j][k] );\n'
#  harness+='          finput[i][j][k]=iinput[i][j][k]/255.0;\n'
#  harness+='        }\n'
#  harness+='  }\n'
#  harness+='  // else\n'
#  harness+='  // {\n'
#  harness+='  //   for (int i=0; i < {0}; i++)\n'.format(s)
#  harness+='  //   {\n'
#  harness+='  //     scanf("%d", &input[i]);\n'
#  harness+='  //   }\n'
#  harness+='  // }\n'
#  harness+='  network(finput);\n'
#  harness+='}\n'
#  h_file = open('harness.c', 'w')
#  h_file.write(harness)
#  h_file.close()
#
#  ## makefile
#  harness=''
#  harness+='CFLAGS ?= -g -w\n'
#  harness+='\n'
#  harness+='all:	harness\n'
#  harness+='\n'
#  harness+='clean:\n'
#  harness+='	rm -f harness\n'
#  harness+='\n'
#  harness+='harness: harness.c\n'
#  harness+='	${CC} ${CFLAGS} network.c harness.c -o harness\n'
#  h_file = open('Makefile', 'w')
#  h_file.write(harness)
#  h_file.close()

def main():
  parser=argparse.ArgumentParser(
          description='To convert a DNN model to c program' )

  parser.add_argument('--model', action='store', nargs='+', default = 'None', help='The input neural network model (.h5)')
  parser.add_argument("--vgg16-model", dest='vgg16', help="vgg16 model", action="store_true")
  parser.add_argument("--outputs", dest="outs", default="outs",
                    help="the output directory", metavar="DIR")

  args=parser.parse_args()
  if args.vgg16:
      model = VGG16()
  else:
      model = load_model(args.model[0])
  model.summary()
  path = args.outs
  if not path[-1] == '/': path += '/'
  if not os.path.exists(path):
    os.system('mkdir -p {0}'.format(path))

  c_convert(model, path)

if __name__=="__main__":
  main()


#!/usr/bin/env python3
"""
Delete an attribute from the ansible inventory.
"""

import os
import sys
import json

import yaml

if len(sys.argv) > 1:
    INVENTORY = sys.argv[1]
else:
    INVENTORY = "./inventory/"

def run():
    """ Main function """
    if not os.path.exists(INVENTORY):
        print("Folder do no exists: {}".format(INVENTORY))
        exit(1)

    stdin = sys.stdin.read()

    if stdin:
        try:
            todelete = json.loads(stdin)
        except ValueError:
            print("error reading JSON content", file=sys.stderr)
            exit(1)

        for to_delete in todelete:

            path = os.path.join(
                os.path.abspath(INVENTORY), "host_vars/", to_delete["server"]
            )
            if not os.path.exists(path):
                print("Folder do no exists: {}".format(path))
                exit(1)

            generated_file = os.path.join(path, "generated.yaml")

            with open(generated_file, "r") as stream:
                ymldata = yaml.load(stream, Loader=yaml.FullLoader)
                client_list = ymldata["clients"]
                client_name = to_delete["proxy_alias"]
                try:
                    del client_list[client_name]
                except Exception:
                    pass

            with open(generated_file, "w") as stream:
                try:
                    yaml.dump(ymldata, stream)
                except yaml.YAMLError as exc:
                    print(exc)
        else:
            exit(0)
    else:
        print("can't read stdin", file=sys.stderr)
        exit(1)

if __name__ == "__main__":
    run()


# This Python 3 environment comes with many helpful analytics libraries installed

# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python

# For example, here's several helpful packages to load in

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the "../input/" directory.

# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

from subprocess import check_output

print(check_output(["ls", "../input"]).decode("utf8"))

# Any results you write to the current directory are saved as output.
train = pd.read_json(open("../input/train.json", "r"))

test = pd.read_json(open("../input/test.json", "r"))
test_id = test.listing_id
badcols = [ i for i in train.columns if 'id' in i]

badcols = badcols+['photos','description','display_address','street_address']
train = train.drop(train[badcols],axis=1)

test = test.drop(test[badcols],axis=1)
train.head()

def date_clean(dat):

    dat["created"] = pd.to_datetime(dat["created"])

    dat["year"] = dat["created"].dt.year

    dat["month"] = dat["created"].dt.month

    dat["day"] = dat["created"].dt.day

    dat["hour"] = dat["created"].dt.hour

    del dat['created']

    return(dat)

train=date_clean(train)

test=date_clean(test)
def n_feat(dat):

    dat['features'] =     dat.features.apply(lambda x: len(x))

    return(dat)

train = n_feat(train)

test = n_feat(test)
trainY = train['interest_level']

del train['interest_level']

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier(n_estimators=500)

clf.fit(train, trainY)
result = clf.predict_proba(test)
labels2idx = {label: i for i, label in enumerate(clf.classes_)}

labels2idx
sub = pd.DataFrame()

sub["listing_id"] = test_id

for label in ["high", "medium", "low"]:

    sub[label] = result[:, labels2idx[label]]

sub.head()
sub.to_csv("submission_rf.csv", index=False)


# Definition for an interval.
class Interval(object):
    def __init__(self, s=0, e=0):
        self.start = s
        self.end = e

import bisect

class Solution(object):
    def findRightInterval(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[int]
        """
        n = len(intervals)
        if n <= 0: return []
        if 1 == n: return [-1]
        data = sorted(zip(range(len(intervals)), intervals), cmp=lambda a,b: a[1].start - b[1].start)
        rs, starts = [], [d[1].start for d in data]
        for interval in intervals:
            i = bisect.bisect_left(starts, interval.end)
            if i == n: rs.append(-1)
            else: rs.append(data[i][0])
        return rs


# -*- coding: utf-8 -*-
import sys,os
import csv
import json
import re
import string
import ast
import uuid
import itertools
import codecs
from operator import itemgetter
from subprocess import Popen, PIPE
from inspect import currentframe, getframeinfo
import argparse

import numpy as np

from performance import Performances
from collection_stats import CollectionStats
from run_subqueries import RunSubqueries

class RunProximitySubqueries(RunSubqueries):
    """
    run the proximity sub-queries.
    """
    def __init__(self, path, corpus_name):
        super(RunProximitySubqueries, self).__init__(path, corpus_name)
        self.subqueries_runfiles_root = os.path.join(self.output_root, 'proximity_runfiles')
        if not os.path.exists(self.subqueries_runfiles_root):
            os.makedirs(self.subqueries_runfiles_root)
        self.subqueries_performance_root = os.path.join(self.output_root, 'proximity_performances')
        if not os.path.exists(self.subqueries_performance_root):
            os.makedirs(self.subqueries_performance_root)
        self.collected_results_root = os.path.join(self.output_root, 'proximity_collected_results')
        if not os.path.exists(self.collected_results_root):
            os.makedirs(self.collected_results_root)

        self.final_results_root = '../all_results'
        self.final_output_root = os.path.join(self.final_results_root, 'subqueries')
        if not os.path.exists(self.final_output_root):
            os.makedirs(self.final_output_root)

        self.type_mapping = {
            1: 'uw',
            2: 'od',
            3: 'uw+od'
        }

    def run_indri_runquery(self, query_str, runfile_ofn, qid='0', rule=''):
        with open(runfile_ofn, 'w') as f:
            command = ['IndriRunQuery_EX -index=%s -trecFormat=True -count=1000 -query.number=%s -query.text="%s" -rule=%s'
                % (os.path.join(self.corpus_path, 'index'), qid, query_str, rule)]
            p = Popen(command, shell=True, stdout=f, stderr=PIPE)
            returncode = p.wait()
            p.communicate()
            if returncode != 0:
                raise NameError("Run Query Error: %s" % (command) )

    def batch_run_subqueries_paras(self, _type=1, query_length=0):
        all_paras = []
        if query_length == 0: #all queries
            queries = self.get_queries()
        else:
            queries = self.get_queries_of_length(query_length)
        queries = {ele['num']:ele['title'] for ele in queries}
        for qid, query in queries.items():
            all_subqueries = self.get_subqueries(query)
            if not os.path.exists(os.path.join(self.subqueries_mapping_root, qid)):
                with open(os.path.join(self.subqueries_mapping_root, qid), 'wb') as f:
                    json.dump(all_subqueries, f, indent=2)
            for subquery_id, subquery_str in all_subqueries.items():
                subquery_len = len(subquery_str.split())
                if _type == 1:
                    subquery_str = '#uw%d(' % (4*subquery_len)+subquery_str+')'
                elif _type == 2:
                    subquery_str = '#od%d(' % (4*subquery_len)+subquery_str+')'
                elif _type == 3:
                    subquery_str = '#combine(' + '#uw%d(' % (4*subquery_len)+subquery_str+')' \
                        + '#od%d(' % (4*subquery_len)+subquery_str+')' \
                        +')'
                type_str = self.type_mapping[_type]
                run_file_root = os.path.join(self.subqueries_runfiles_root, type_str)
                if not os.path.exists(run_file_root):
                    os.makedirs(run_file_root)
                performance_root = os.path.join(self.subqueries_performance_root, type_str)
                if not os.path.exists(performance_root):
                    os.makedirs(performance_root)
                runfile_fn = os.path.join(run_file_root, qid+'_'+subquery_id)
                performance_fn = os.path.join(performance_root, qid+'_'+subquery_id)
                if not os.path.exists(performance_fn):
                    all_paras.append((self.corpus_path, self.collection_name, qid, subquery_str, subquery_id, type_str, runfile_fn, performance_fn))
        return all_paras

    def run_subqueries(self, qid, subquery_id, query, type_str, runfile_ofn, eval_ofn):
        self.run_indri_runquery(query, runfile_ofn, qid, type_str)
        self.eval(runfile_ofn, eval_ofn)

    def batch_collect_results_paras(self):
        queries = self.get_queries()
        return [(self.corpus_path, self.collection_name, q['num']) for q in queries]

    def collection_all_results(self, req_qid):
        qid_results = []
        for fn in os.listdir(self.subqueries_performance_root):
            fn_split = fn.split('_')
            qid = fn_split[0]
            if qid != req_qid:
                continue
            subquery_id = fn_split[1]
            model_para = fn_split[2]
            with open(os.path.join(self.subqueries_mapping_root, qid)) as f:
                subquery_mapping = json.load(f)
            try:
                with open(os.path.join(self.subqueries_performance_root, fn)) as f:
                    first_line = f.readline()
                    ap = first_line.split()[-1]
            except:
                continue
            #print fn, subquery_mapping
            qid_results.append( (subquery_id, subquery_mapping[subquery_id], model_para, ap) )

        qid_results.sort(key=self.sort_subquery_id)
        with open(os.path.join(self.collected_results_root, req_qid), 'wb') as f:
            wr = csv.writer(f)
            wr.writerows(qid_results)

    def sort_subquery_key(self, k):
        subquery_id_split = k.split('_')[0].split('-')
        return int(subquery_id_split[0])+float(subquery_id_split[1])/10.0

    def output_optimal_dist(self):
        optimals = {}
        queries = self.get_queries()
        queries = {ele['num']:ele['title'] for ele in queries}
        model_paras = set()
        for qid in os.listdir(self.collected_results_root):
            with open(os.path.join(self.collected_results_root, qid)) as f:
                csvr = csv.reader(f)
                for row in csvr:
                    subquery_id = row[0]
                    subquery = row[1]
                    model_para = row[2]
                    model_paras.add(model_para)
                    ap = float(row[3])
                    if model_para not in optimals:
                        optimals[model_para] = {}
                    subquery_len = int(subquery_id.split('-')[0])
                    if qid not in optimals[model_para]:
                        optimals[model_para][qid] = []
                    optimals[model_para][qid].append((subquery_len, ap))
        for model_para in optimals:
            for qid in optimals[model_para]:
                optimals[model_para][qid].sort(key=itemgetter(1), reverse=True)

        res = {}
        for qid, query in queries.items():
            query_len = len(query.split())
            for model_para in model_paras:
                if qid not in optimals[model_para]:
                    continue
                if model_para not in res:
                    res[model_para] = {}
                if query_len not in res[model_para]:
                    res[model_para][query_len] = {}
                optimal_subquery_len = optimals[model_para][qid][0][0]
                if optimal_subquery_len not in res[model_para][query_len]:
                    res[model_para][query_len][optimal_subquery_len] = 0
                res[model_para][query_len][optimal_subquery_len] += 1

        with open(os.path.join(self.final_output_root, self.collection_name+'-optimal_subquery_dist.md'), 'wb') as f:
            f.write('## %s\n' % (self.collection_name))
            for model_para in res:
                f.write('\n### %s\n' % (model_para))
                f.write('| | | | | |\n')
                f.write('|--------|--------|--------|--------|--------|\n')
                for query_len in res[model_para]:
                    f.write('| %d |' % (query_len))
                    for optimal_subquery_len in res[model_para][query_len]:
                        f.write(' %d:%d |' % (optimal_subquery_len, res[model_para][query_len][optimal_subquery_len]))
                    f.write('\n')

    def output_results(self, query_length=0):
        if query_length == 0: #all queries
            queries = self.get_queries()
        else:
            queries = self.get_queries_of_length(query_length)
        queries = {int(ele['num']):ele['title'] for ele in queries}
        methods = ['okapi', 'dir']
        optimal_model_performances = Performances(self.corpus_path).load_optimal_performance(methods)
        model_paras = []
        for p in optimal_model_performances:
            model_para = 'method:%s,' % p[0] + p[2]
            model_paras.append(model_para)
        subquery_data = {}
        for qid, query in queries.items():
            subquery_data[qid] = {}
            with open(os.path.join(self.collected_results_root, str(qid))) as f:
                csvr = csv.reader(f)
                for row in csvr:
                    subquery_id = row[0]
                    subquery = row[1]
                    model_para = row[2]
                    ap = row[3]
                    _key = subquery_id+'_'+subquery
                    if _key not in subquery_data[qid]:
                        subquery_data[qid][_key] = {}
                    subquery_data[qid][_key][model_para] = ap

        all_data = []
        for qid in sorted(subquery_data):
            subqueries = sorted(subquery_data[qid], key=self.sort_subquery_key)
            all_data.append(subqueries)
            all_data[-1].insert(0, str(qid))
            for model_para in model_paras:
                all_data.append([str(subquery_data[qid][q][model_para]) if model_para in subquery_data[qid][q] else '' for q in subqueries[1:]])
                all_data[-1].insert(0, model_para)

        with open(os.path.join(self.final_output_root, self.collection_name+'-'+str(query_length)+'.csv'), 'wb') as f:
            cw = csv.writer(f)
            cw.writerows(all_data)

        # markdown output
        cs = CollectionStats(self.corpus_path)
        max_row_len = max([len(ele) for ele in all_data])
        with open(os.path.join(self.final_output_root, self.collection_name+'-'+str(query_length)+'.md'), 'wb') as f:
            f.write('%s|\n' % ('| ' * max_row_len))
            f.write('%s|\n' % ('|---' * max_row_len))
            cur_qid = 0
            cur_queries = []
            for i, data in enumerate(all_data):
                if i % 3 != 0: # numerical values (MAP) line
                    if len(data) == 1:
                        continue
                    _max = np.argmax([float(ele) for ele in data[1:]])+1
                    for j in range(len(data)):
                        if j == _max:
                            f.write('| **%s** ' % data[j])
                        else:
                            f.write('| %s ' % data[j])
                    f.write(' |\n')
                    # read and output the details in runfile
                    if _max+1 != len(data):
                        lines_cnt = 10
                        runfile_max = os.path.join(self.subqueries_runfiles_root, '%s_%s_%s' % (cur_qid, cur_queries[_max].split('_')[0], data[0]))
                        with open(runfile_max) as rf:
                            first_few_lines_max = [line.split()[1]+' '+line.split()[-1] for line in rf.readlines()[:lines_cnt]]
                        runfile_allterms = os.path.join(self.subqueries_runfiles_root, '%s_%s_%s' % (cur_qid, cur_queries[-1].split('_')[0], data[0]))
                        with open(runfile_allterms) as rf:
                            first_few_lines_allterms = [line.split()[1]+' '+line.split()[-1] for line in rf.readlines()[:lines_cnt]]
                        # also read term stats
                        all_terms_stats = []
                        for t in cur_queries[-1].split('_')[1].split():
                            all_terms_stats.append([k+':'+str(v) for k,v in cs.get_term_stats(t).items() if k!='raw'])
                            all_terms_stats[-1].insert(0, t)
                        term_line_idx = 0
                        for zipped in zip(first_few_lines_max, first_few_lines_allterms):
                            for ele in zipped:
                                f.write('| %s ' % (ele))
                            for ele in all_terms_stats:
                                f.write('| %s ' % (ele[term_line_idx]))
                            term_line_idx += 1
                            f.write(' |\n')
                else: # qid query line
                    cur_qid = data[0]
                    cur_queries = data
                    f.write('| %s |\n' % (' | '.join([d.split('_')[-1] for d in data])))


import typing
from typing import Any, Iterable, NamedTuple, Type, Tuple, Union

import immutabledict

from google.protobuf import any_pb2
from dm_env_rpc.v1 import dm_env_rpc_pb2
from dm_env_rpc.v1 import error
from google.protobuf import message

_MESSAGE_TYPE_TO_FIELD = immutabledict.immutabledict({
    field.message_type.name: field.name
    for field in dm_env_rpc_pb2.EnvironmentRequest.DESCRIPTOR.fields
})

# An unpacked extension request (anything).
# As any proto message that is not a native request is accepted, this definition
# is overly broad - use with care.
DmEnvRpcExtensionMessage = message.Message

# A packed extension request.
# Wraps a DmEnvRpcExtensionMessage.
DmEnvRpcPackedExtensionMessage = any_pb2.Any

# A native request RPC.
DmEnvRpcNativeRequest = Union[
    dm_env_rpc_pb2.CreateWorldRequest,
    dm_env_rpc_pb2.JoinWorldRequest,
    dm_env_rpc_pb2.StepRequest,
    dm_env_rpc_pb2.ResetRequest,
    dm_env_rpc_pb2.ResetWorldRequest,
    dm_env_rpc_pb2.LeaveWorldRequest,
    dm_env_rpc_pb2.DestroyWorldRequest,
]

# A native response RPC.
DmEnvRpcNativeResponse = Union[
    dm_env_rpc_pb2.CreateWorldResponse,
    dm_env_rpc_pb2.JoinWorldResponse,
    dm_env_rpc_pb2.StepResponse,
    dm_env_rpc_pb2.ResetResponse,
    dm_env_rpc_pb2.ResetWorldResponse,
    dm_env_rpc_pb2.LeaveWorldResponse,
    dm_env_rpc_pb2.DestroyWorldResponse,
]

# A native request RPC, or an extension message, wrapped in Any.
DmEnvRpcRequest = Union[DmEnvRpcNativeRequest, DmEnvRpcPackedExtensionMessage]
# A native response RPC, or an extension message, wrapped in Any.
DmEnvRpcResponse = Union[DmEnvRpcNativeResponse, DmEnvRpcPackedExtensionMessage]

def pack_rpc_request(
    request: Union[DmEnvRpcRequest, DmEnvRpcExtensionMessage],
) -> DmEnvRpcRequest:
  """Returns a DmEnvRpcRequest that is suitable to send over the wire.

  Arguments:
    request: The request to pack.

  Returns:
    Native request - returned as-is.
    Packed extension (any_pb2.Any) - returned as-is.
    Everything else - assumed to be an extension; wrapped in any_pb2.Any.
  """
  # pytype: disable=bad-return-type
  return _pack_message(request, _get_union_args(DmEnvRpcNativeRequest))

def unpack_rpc_request(
    request: Union[DmEnvRpcRequest, DmEnvRpcExtensionMessage],
    *,
    extension_type: Union[
        Type[message.Message], Iterable[Type[message.Message]]
    ],
) -> Union[DmEnvRpcRequest, DmEnvRpcExtensionMessage]:
  """Returns a DmEnvRpcRequest without a wrapper around extension messages.

  Arguments:
    request: The request to unpack.
    extension_type: One or more extension protobuf classes of known extension
      types.

  Returns:
    Native request - returned as-is.
    Unpacked extension in |extension_type| - returned as-is.
    Packed extension (any_pb2.Any) in |extension_type| - returned unpacked

  Raises:
    ValueError: The message is packed (any_pb2.Any), but not in |extension_type|
        or the message type is not a native request or known extension.
  """
  return _unpack_message(
      request,
      _get_union_args(DmEnvRpcNativeRequest),
      extension_type=extension_type)

def pack_rpc_response(
    response: Union[DmEnvRpcResponse, DmEnvRpcExtensionMessage],
) -> DmEnvRpcResponse:
  """Returns a DmEnvRpcResponse that is suitable to send over the wire.

  Arguments:
    response: The response to pack.

  Returns:
    Native response - returned as-is.
    Packed extension (any_pb2.Any) - returned as-is.
    Everything else - assumed to be an extension; wrapped in any_pb2.Any.
  """
  # pytype: disable=bad-return-type
  return _pack_message(response, _get_union_args(DmEnvRpcNativeResponse))

def unpack_rpc_response(
    response: Union[DmEnvRpcResponse, DmEnvRpcExtensionMessage],
    *,
    extension_type: Union[
        Type[message.Message], Iterable[Type[message.Message]]
    ],
) -> Union[DmEnvRpcRequest, DmEnvRpcExtensionMessage]:
  """Returns a DmEnvRpcResponse without a wrapper around extension messages.

  Arguments:
    response: The response to unpack.
    extension_type: One or more extension protobuf classes of known extension
      types.

  Returns:
    Native response - returned as-is.
    Unpacked extension in |extension_type| - returned as-is.
    Packed extension (any_pb2.Any) in |extension_type| - returned unpacked

  Raises:
    ValueError: The message is packed (any_pb2.Any), but not in |extension_type|
        or the message type is not a native request or known extension.
  """
  return _unpack_message(response, _get_union_args(DmEnvRpcNativeResponse),
                         extension_type=extension_type)

class EnvironmentRequestAndFieldName(NamedTuple):
  """EnvironmentRequest and field name used when packing."""
  environment_request: dm_env_rpc_pb2.EnvironmentRequest
  field_name: str

def pack_environment_request(
    request: DmEnvRpcRequest) -> EnvironmentRequestAndFieldName:
  """Constructs an EnvironmentRequest containing a request message.

  Args:
    request: An instance of a dm_env_rpc Request type, such as
      CreateWorldRequest.

  Returns:
    A tuple of (environment_request, field_name) where:
      environment_request: dm_env_rpc.v1.EnvironmentRequest containing the input
        request message.
      field_name: Name of the environment request field holding the input
        request message.
  """
  field_name = _MESSAGE_TYPE_TO_FIELD[type(request).__name__]
  environment_request = dm_env_rpc_pb2.EnvironmentRequest()
  getattr(environment_request, field_name).CopyFrom(request)
  return EnvironmentRequestAndFieldName(environment_request, field_name)

def unpack_environment_response(
    environment_response: dm_env_rpc_pb2.EnvironmentResponse,
    expected_field_name: str) -> DmEnvRpcResponse:
  """Extracts the response message contained within an EnvironmentResponse.

  Args:
    environment_response: An instance of dm_env_rpc.v1.EnvironmentResponse.
    expected_field_name: Name of the environment response field expected to be
      holding the dm_env_rpc response message.

  Returns:
    dm_env_rpc response message wrapped in the input environment response.

  Raises:
    DmEnvRpcError: The dm_env_rpc EnvironmentResponse contains an error.
    ValueError: The dm_env_rpc response message contained in the
      EnvironmentResponse is held in a different field from the one expected.
  """
  response_field_name = environment_response.WhichOneof('payload')
  if response_field_name == 'error':
    raise error.DmEnvRpcError(environment_response.error)
  elif response_field_name == expected_field_name:
    return getattr(environment_response, expected_field_name)
  else:
    raise ValueError('Unexpected response message! expected: '
                     f'{expected_field_name}, actual: {response_field_name}')

def _pack_message(
    msg: message.Message,
    union_types: Tuple[Type[Any], ...],
) -> message.Message:
  """Packs a message based on its union types.

  Args:
    msg: The message to process.
    union_types: Determines which types are "native" and "extension".
        "native" types are passed through, unchanged.
        "extension" types are packed into an Any message and returned.

  Returns:
    A message within union_types, or an Any proto.
  """
  if isinstance(msg, union_types):
    return msg

  if isinstance(msg, any_pb2.Any):
    return msg

  # Assume the message is an extension.
  packed = any_pb2.Any()
  packed.Pack(msg)
  return packed

def _unpack_message(
    msg: message.Message,
    union_types: Tuple[Type[Any], ...],
    *,
    extension_type: Union[
        Type[message.Message], Iterable[Type[message.Message]]
    ],
) -> message.Message:
  """Packs a message based on its union types.

  Args:
    msg: The message to process.
    union_types: Determines which types are "native" and "extension". "native"
      types are passed through, unchanged. "extension" types are packed into an
      Any message and returned.
    extension_type: Type or type(s) used to match extension messages. The first
      matching type is used.

  Returns:
    An upacked message within |union_types| or an unpacked extension message
    with type within |extension_type|.

  Raises:
    TypeError: Raised if a return type could not be determined.
  """
  if isinstance(msg, union_types):
    return msg

  if isinstance(extension_type, type):
    extension_type = (extension_type,)
  else:
    extension_type = tuple(extension_type)

  if isinstance(msg, extension_type):
    return msg

  if isinstance(msg, any_pb2.Any):
    matching_type = next(
        (e for e in extension_type if msg.Is(e.DESCRIPTOR)), None)

    if not matching_type:
      raise ValueError(
          'Extension type could not be found to unpack message: '
          f'{type(msg).__name__}.\n'
          f'Known Types:\n' + '\n'.join(f'- {e}' for e in extension_type))

    unpacked = matching_type()
    msg.Unpack(unpacked)
    return unpacked

  raise ValueError(
      'Message type does not appear in union_types and is not an extension: '
      f'{type(msg).__name__}.\n'
      f'Union Types:\n' + '\n'.join(f'- {t}' for t in union_types))

def _get_union_args(union) -> Tuple[Type[Any], ...]:
  """Python version-safe function for getting the types in a union."""
  # __args__ exists < v3.8, typing.get_args() exists >= 3.8.
  return getattr(union, '__args__', None) or typing.get_args(union)


class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side " + str(i + 1) + " : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side", i + 1, "is", self.sides[i])

class Triangle(Polygon):
    def __init__(self):
        Polygon.__init__(self, 3)

    def findArea(self):
        a, b, c = self.sides
        # calculate the semi-perimeter
        s = (a + b + c) / 2
        area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
        print('The area of the triangle is %0.2f' % area)

# def __init__(self, param):
#     return None

t = Triangle()
t.inputSides()

t.dispSides()
t.findArea()

# Two built-in functions isinstance() and issubclass() are used to check inheritances.

# The function isinstance() returns True if the object is an instance of the class or other classes derived from it.
print("\nisinstance")

print(isinstance(t, Triangle))
print(isinstance(t, Polygon))
print(isinstance(t, int))
print(isinstance(t, object))

print("\nissubclass")

# Similarly, issubclass() is used to check for class inheritance.
print(issubclass(Polygon, Triangle))
print(issubclass(Triangle, Polygon))
print(issubclass(bool, int))


import sys
import ply.yacc as yacc
from listas_lex import tokens

# To comment multi line use CTRL + SHIFT + / (7)

# Elementos(1+2)
#           /|\
#          1 2 3
# 1: Elementos(1) -> NUM -> 1
# 2: OP -> +
# 3: Elemento(2) -> NUM -> 2

# Frase : Elementos
# Elementos: Elementos OP Elemento
#          | Elemento
# Elemento: NUM

#def p_grammar(p):
#    """"
#    Frase : Elementos
#    Elementos: Elementos OP Elemento
#             | Elemento
#    Elemento: NUM
#    """
# definir acoes spbre produções

def p_Frase(p):
    "Frase : Elementos"

def p_Elementos(p):
    "Elementos : Elementos OP Elemento"
    # print(p[1],p[2],p[3])
    if(p[1]):
    # Pegar nos elementos abaixo e efetuar a op de acordo com o OP
        if(p[2]=="+"):
            parser.output += int(p[1])+p[3]
        else:
            parser.output += int(p[1])-p[3]
    else:
        if(p[2]=="+"):
            parser.output += int(p[3])
        else:
            parser.output += int(p[3])

def p_Elementos_simples(p):
    "Elementos : Elemento"

def p_Elemento(p):
    "Elemento : NUM"
    print(p[1])
    p[0] = p[1]

def p_error(p):
    print("Error", p)
    parser.erro = True

parser = yacc.yacc()

for linha in sys.stdin:
    parser.output = 0
    parser.erro = False
    parser.parse(linha)
    if not parser.erro:
        print("Frase Valida")
        print(parser.output)
    else:
        print("Frase invalida")


from __future__ import with_statement
"""
    Copyright 2009 Oregon State University

    This file is part of Pydra.

    Pydra is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Pydra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Pydra.  If not, see <http://www.gnu.org/licenses/>.
"""

import logging
import os
from threading import Lock
import zlib
logger = logging.getLogger('root')

from django.db.models import Q

import pydra_settings
from logger import task_log_path
from pydra.models import TaskInstance, WorkUnit
from pydra.cluster.module import Module
from pydra.cluster.tasks import STATUS_CANCELLED, STATUS_FAILED, STATUS_COMPLETE
from pydra.util import makedirs

STATUSES = (STATUS_FAILED, STATUS_CANCELLED, STATUS_COMPLETE)

class MasterLogAggregator(Module):
    """
    Module for aggregating logs from tasks run on different nodes in the
    cluster.  This includes physically transfering logs to the master
    and aggregating the logs into a cohesive form once its there
    """

    _shared = [
        'workers',
        'nodes'
    ]

    def __init__(self):

        self._interfaces = [
            self.aggregate_task_logs
        ]

        self._listeners = {
            'CLUSTER_IDLE':self.aggregate_logs
        }

        self.task_iteration_lock = Lock()
        self.transfer_lock = Lock()
        self.transfers = []

    def aggregate_logs(self, workers=None):
        """
        Scans TaskInstances and their Workunits and selects logs to aggregate.

        This function synchronizes querying and iteration of tasks and workunits
        with pending log transfers.  This is required because as each worker
        becomes idle.  It will trigger a call to this function. A full iteration
        will occur before the next call is processed, reducing the number of
        times a task might be processed.

        @param workers [None] - list of idle workers.  Logs are only requested
                                from idle workers.  If None, logs are retrieved
                                from all workers
        """
        with self.task_iteration_lock:
            logger.info('Cluster Idle, aggregating all logs')
            query = TaskInstance.objects \
                        .filter(Q(log_retrieved=False) \
                                | Q(workunits__log_retrieved=False)) \
                        .order_by('completed') \
                        .distinct()
            for task in query:
                self.aggregate_task_logs(task)

    def aggregate_task_logs(self, task, workers=None):
        """
        aggregates all logs for a give task or workunit.  Logs are not
        retrieved if the task or workunit is still running.  Completed workunits
        for a running task will be retrieved

        @param workers [None] - list of idle workers.  Logs are only requested
                                from idle workers.  If None, logs are retrieved
                                from all workers
        """
        if isinstance(task, (int,)):
            task = TaskInstance.objects.get(task)

        # aggregate main task log
        if not task.log_retrieved and task.status in STATUSES:
            if not workers or task.worker in workers:
                self.aggregate_log(task.worker, task.id)

        # aggregate workunit logs, if any
        for wu in task.workunits.filter(log_retrieved=False) \
                                    .filter(status__in=STATUSES):
            if not workers or wu.worker in workers:
                self.aggregate_log(wu.worker, task.id, wu.subtask_key, \
                               wu.workunit)

    def aggregate_log(self, worker, task, subtask=None, workunit=None):
        """
        Aggregates a single log file.  Either the main task log, or a subtask
        log

        This function synchronizes per file download requests to prevent excess
        requests for the same file.

        @param worker - id of worker sending the log
        @param task - id of task
        @param subtask - task path for subtask, default=None
        @param workunit - id of workunit, default=None
        """
        if worker not in self.workers:
            logger.debug("Can't aggregate logs for unknown worker %s" % worker)
            return

        key = (task, subtask, workunit)
        with self.transfer_lock:
            if key in self.transfers:
                return
            else:
                self.transfers.append(key)
        logger.debug('Requesting Log: %s %s %s' % key)
        remote = self.workers[worker]
        deferred = remote.callRemote('send_log', task, subtask, workunit)
        deferred.addCallback(self.receive_log, worker, \
                             task, subtask, workunit)

    def receive_log(self, response, worker, task, subtask=None, workunit=None):
        """
        Callback from a successful call to Node.send_log.  Saves the log
        locally, updates state, and deletes the remote log.

        @param worker - id of worker sending the log
        @param task - id of task
        @param subtask - task path for subtask, default=None
        @param workunit - id of workunit, default=None
        """
        logger.debug('Receiving Log: %s %s %s' % (task, subtask, workunit))

        if not response:
            logger.debug("Bogus log: %s %s %s" % (task, subtask, workunit))
            return
        log = zlib.decompress(response)

        d, path = task_log_path(task, subtask, workunit)

        try:
            makedirs(d)
        except OSError:
            # Couldn't make our path to our log; give up.
            logger.debug("Couldn't recieve log: %s %s %s"
                % (task, subtask, workunit))
            return
        out = open(path, 'w')
        out.write(log)

        # mark log as received
        if workunit:
            item = WorkUnit.objects.get(task_instance__id=task, \
                                        workunit=workunit)
        else:
            item = TaskInstance.objects.get(id=task)
        item.log_retrieved = True
        item.save()

        # delete remote log
        remote = self.workers[worker]
        remote.callRemote('delete_log', task, subtask, workunit)

class NodeLogAggregator(Module):
    """
    Module for aggregating logs from tasks run on different nodes in the
    cluster.  This is the Node side of the process and includes functions for
    retrieving and deleting local logs
    """

    _shared = ['worker_key']

    def __init__(self):
        self._remotes = [
            ('MASTER', self.send_log),
            ('MASTER', self.delete_log)
        ]

        self.delete_lock = Lock()

    def send_log(self, master, worker, task, subtask=None, workunit=None):
        """
        Sends the requested log file

        @param worker - id of worker
        @param task - id of task
        @param subtask - task path for subtask, default=None
        @param workunit - id of workunit, default=None
        """
        d, path = task_log_path(task, subtask, workunit, worker)
        try:
            logger.debug('Sending Log: %s' % path)
            log = open(path, 'r')
            text = log.read()
            compressed = zlib.compress(text)
            return compressed
        except IOError:
            logger.debug("Couldn't send log: %s" % path)

    def delete_log(self, master, worker, task, subtask=None, workunit=None):
        """
        deletes the requested log file

        @param worker - id of worker
        @param task - id of task
        @param subtask - task path for subtask, default=None
        @param workunit - id of workunit, default=None
        """
        d, path = task_log_path(task, subtask, workunit, worker)
        logger.debug('Deleting Log: %s' % path)
        # synchronize deletes to ensure directory gets deleted
        with self.delete_lock:
            try:
                # Remove the log and any directories emptied in the process
                os.remove(path)
                os.removedirs(d)
            except os.error:
                pass