import os
import requests
import openai
from dotenv import load_dotenv

load_dotenv()

news_api_key = os.getenv('NEWS_API')
openai_api_key = os.getenv('OPENAI_API_KEY')
organisation_id = os.getenv('OPENAI_ORG_ID')

openai.organization = organisation_id
openai.api_key = openai_api_key
openai.Model.list()

country = 'us'
url = f'https://newsapi.org/v2/top-headlines?country={country}&apiKey={news_api_key}'

result = requests.get(url)
data = result.json()

def summarise(text):
    response = openai.Completion.create(model='text-davinci-003',
                                        prompt=text,
                                        temperature=0,
                                        max_tokens=20)
    print(response['choices'][0]['text'].strip())

counter = 0
for article in data['articles']:
    counter += 1
    if counter > 5:
        break
    prompt = f"Summarise {article['url']} in one sentence."
    summarise(prompt)


"""题目描述：从上到下按层打印二叉树，同一层结点从左至右输出。每一层输出一行。"""

#链接：https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if not pRoot:
            return []
        queue=[pRoot]
        res=[]
        while queue:
            current=[]
            i=0
            flag=len(queue)
            while i<flag:
                point=queue.pop(0)
                current.append(point.val)
                if point.left:
                    queue.append(point.left)
                if point.right:
                    queue.append(point.right)
                i+=1
            if current:
                res.append(current)
        return res


# -*- coding: utf-8 -*-
import json
from datetime import date
import os

class ImoveisCrawlingPipeline(object):

    file_obj = None

    def open_spider(self, spider):
        category = spider.category
        file = os.getcwd() + "/files/imoveis/{}/{}OLX_{}.txt".format(category, category, date.today())
        self.file_obj = open(file, "w")

    def close_spider(self, spider):
        self.file_obj.close()

    def process_item(self, item, spider):
        item['titulo'] = item['titulo'].replace("00e2", "â").replace("00e1", "á").replace('00e9', 'é').\
            replace('00f3', 'ó').replace('00e7', 'ç').replace('00e3', 'ã').replace('00ed', 'í').replace('\\u', '')
        item['regiao'] = item['regiao'].replace('\t', '').replace('\n', '').replace("00e2", "â").\
            replace("00e1", "á").replace('00e9', 'é').replace('00f3', 'ó').replace('00e7', 'ç').\
            replace('00e3', 'ã').replace('00ed', 'í').replace('\\u', '')
        if item['detalhes']:
            item['detalhes'] = item['detalhes'].replace('\t', '').replace('\n', '').replace("00e2", "â").\
                replace("00e1", "á").replace('00e9', 'é').replace('00f3', 'ó').replace('00e7', 'ç').\
                replace('00e3', 'ã').replace('00ed', 'í').replace('\\u', '')

        line = json.dumps(dict(item)) + '\n'
        self.file_obj.write(line)
        return item


from sys import path, exc_info
from os import getcwd
from datetime import tzinfo, datetime
import requests
import json
from logging import getLogger

from config.config import log_data_to_local_couchdb, log_data_to_local_file

logger = getLogger('mvp.' + __name__)

def need_to_log_locally():
   return log_data_to_local_couchdb or log_data_to_local_file

# Log data to couchdb and/or file or neither.
#

def logData(sensor_name, status, attribute, subject, value, units, comment):

   # Need to factor out the next call.
   timestamp = '{:%Y-%m-%d %H:%M:%S}'.format(datetime.now())

   if log_data_to_local_file == True:
      logFile(timestamp, sensor_name, status, attribute, value, comment)

   if log_data_to_local_couchdb == True:
      logDB(timestamp, sensor_name, status, attribute, value, comment)

def logFile(timestamp, name, status, attribute, value, comment):
    #TBD - Need to put a file rotation scheme in place for the text file.
    #TBD - I'm not sure this is thread safe.  If the light controller and the logSensor
    #      threads both call it can things get messed up?:

    try:
        f = open(getcwd() + '/data/data.txt', 'a')
        s = name + ", " + status + ", " + attribute + ", " + value + "," + comment
        logger.debug('appending data: {} to file: {}'.format(s, f))
        f.write(s + "\n")
        f.close()
    except:
       logger.error('Error writing to data file: {}'.format(exc_info()[0]))

def logDB(timestamp, name, status, attribute, value, comment):

    s = name + ", " + status + ", " + attribute + ", " + value + "," + comment
    logger.debug('couchd db write: {}'.format(s))

    log_record = {'timestamp' : timestamp,
            'name' : name,
            'status' : status,
            'attribute' : attribute,
            'value' : value,
            'comment' : comment}
    json_data = json.dumps(log_record)
    headers = {'content-type': 'application/json'}

    """
    f there is a network problem like a DNS failure, or refused connection the Requests library will
    raise a ConnectionError exception.  With invalid HTTP responses, Requests will also raise an HTTPError
    exception, but these are rare.  If a request times out, a Timeout exception will be raised.
    If and when a request exceeds the preconfigured number of maximum redirections, then a TooManyRedirects
    exception will be raised.
    """

    r = requests.post('http://localhost:5984/mvp_sensor_data', data = json_data, headers=headers)


import pytest

def compute(s: str) -> int:
	score = 0
	for opp, _, you in s.strip().split('\n'):
		if you == 'X':
			if opp == 'C': score += 6
			elif opp == 'A': score += 3
			score += 1
		elif you == 'Y':
			if opp == 'A': score += 6
			elif opp == 'B': score += 3
			score += 2
		else:
			if opp == 'B': score += 6
			elif opp == 'C': score += 3
			score += 3

	return score
_INPUT = """
A Y
B X
C Z
"""

@pytest.mark.parametrize(
	('_input', 'expected'),
	[(_INPUT, 15)],
)
def test_computer(_input, expected): assert compute(_input) == expected

def main() -> int:
	with open("input.txt") as f: print(compute(f.read()))
	return 0

if __name__ == "__main__":
	raise SystemExit(main())


#User function Template for python3

def minSwap (arr, n, k) :
    # n = len(arr)
    number_of_ele = 0

    for ele in (arr):
        if ele <= k:
            number_of_ele+=1

    if number_of_ele <=1:
        return 0

    left = 0
    right = number_of_ele-1 #0 based indexing

    i =0
    not_required = 0
    while i<=right:
        if arr[i] > k:
            not_required+=1
        i+=1

    min_swaps = not_required
    while (right+1) < n:
        if arr[left] > k:
            not_required-=1
        left+=1
        right+=1
        if arr[right] > k:
            not_required+=1
        min_swaps= min(min_swaps,not_required)
    return min_swaps
    #Complete the function

#{
#  Driver Code Starts
#Initial Template for Python 3

for _ in range(0,int(input())):
    n = int(input())
    arr = list(map(int, input().strip().split()))
    k = int(input())
    ans = minSwap(arr, n, k)
    print(ans)

# } Driver Code Ends


# -*- mode: python -*-

block_cipher = None
added_files = [
         ( 'images', 'images' ),
         ( 'config.ini', '.' ),
         ('third-party','third-party')
         ]

a = Analysis(['main.py'],
             pathex=['D:\\workspace\\OwnProject\\jyeoo-crawler-gui'],
             binaries=[],
             datas=added_files,
             hiddenimports=['pymysql'],
             hookspath=[],
             runtime_hooks=[],
             excludes=['phantomjs','phantomjs.zip'],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          [],
          exclude_binaries=True,
          name='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          console=False , icon='images\\main.ico')
coll = COLLECT(exe,
               a.binaries,
               a.zipfiles,
               a.datas,
               strip=False,
               upx=True,
               name='main')


basic_answers = {'привет':'Привет', 'как дела?':'Нормально', 'пока':'Пока'}

def get_answer(question, answers = basic_answers):
    question = question.lower()
    print(answers[question])
    return answers[question]

def ask_user():
    question = ''
    answer = ''
    while answer != 'Пока':
        question = input('Введите вопрос: ')
        answer = get_answer(question)

ask_user()


def ex081():
    numeros = []
    condicao = 'S'
    qtd = 0

    while condicao == 'S':
        numeros.append(int(input('Digite um número: ')))
        condicao = input('Deseja continuar? [S/N]\n').upper()

    numeros.sort(reverse=True)

    if 5 in numeros:
        resultado = 'SIM'
    else:
        resultado = 'NÃO'

    print(f'Quantidade de números digitados: {len(numeros)}')
    print(f'Números digitados em ordem decrescente: {numeros}')
    print(f'O número 5 foi digitado? {resultado}')

ex081()


#from django.template import Context, loader
from django.shortcuts import render_to_response, get_object_or_404
from polls.models import Poll, Choice
from django.http import HttpResponseRedirect#, Http404, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext

def index(request):
    poll_list = Poll.objects.all().order_by('-pub_date')[:5]
    #t = loader.get_template('polls/index.html')
    #c = Context({
    #             'latest_poll_list': poll_list, # 'latest_poll_list' is the object that will used in the HTML
    #})
    #return HttpResponse(t.render(c))
    return render_to_response('polls/index.html', {'latest_poll_list': poll_list}) # it's a different way to implement, using shortcut (atalho). Using this way, you don't need to import the context, loader and HttpResponse

def detail(request, poll_id, name):
    #try:
    #    p = Poll.objects.get(pk = poll_id)
    #except Poll.DoesNotExist:
    #    raise Http404
    #return render_to_response()('polls/detail.html', {'poll': p})
    p = get_object_or_404(Poll, pk = poll_id)
    return render_to_response('polls/detail.html', {'poll': p, 'name': name}, context_instance=RequestContext(request))

def results(request, poll_id):
    p = get_object_or_404(Poll, pk = poll_id)
    return render_to_response('polls/results.html', { 'poll': p })

def vote(request, poll_id):
    p = get_object_or_404(Poll, pk = poll_id)

    try:
        selected_choice = p.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        return render_to_response('polls/detail.html', { 'poll': p,
                                                        'error_message': 'You didn\'t select a choice'
                                                      },
                                                      context_instance = RequestContext(request))
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing with POST data.
        # This prevents data from being posted twice if a user hits the Back button.
        return HttpResponseRedirect(reverse('polls.views.results', args = (p.id,)))


from django.shortcuts import render

from django.http.response import JsonResponse
from django.http.response import HttpResponse
from rest_framework.parsers import JSONParser
from rest_framework import status

from tutorials.models import Tutorial
from tutorials.serializers import TutorialSerializer
from rest_framework.decorators import api_view
from tutorials.utils import  get_query,get_column_names,get_max_cropORpest_state,get_top5_cropORpest, get_location
import datetime
from collections import defaultdict
from django.db.models import Q
import time
from tutorials.codeUtil2 import predict_pest

@api_view(['GET','POST'])
def chatbot_general_query(request):
    if(request.method=='GET'):
        qname= request.GET.get('crop',None)
        if(qname!=None):
            return JsonResponse( get_top5_cropORpest('crop'), safe=False)

        qname= request.GET.get('pest',None)
        if (qname!=None):
            return JsonResponse( get_top5_cropORpest('pest'), safe=False)

        else:
            return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET','POST'])
def chatbot_specific_query(request):
    if(request.method=='GET'):
        qname= request.GET.get('crop',None)
        if(qname!=None):
            return JsonResponse( get_max_cropORpest_state('crop',qname), safe=False)

        qname= request.GET.get('pest',None)
        if (qname!=None):
            return JsonResponse( get_max_cropORpest_state('pest',qname), safe=False)

        else:
            return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET','POST'])
def column_names(request):
    if(request.method=='GET'):
        list1= ['crop','pest','state_name','district_name']
        for item in list1:
            str=request.GET.get(item,None)
            if (str!=None):
                str=item
                break;
        if(str==None):
            return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)
        print("column",str)
        list_l1= get_column_names(str)
        list_l1=sorted(list_l1)
        return JsonResponse(list_l1,safe=False)

@api_view(['GET','POST'])
def district_of_state(request):
    if(request.method=='GET'):
        return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET','POST'])
def prediction(request):
    if request.method=='GET':
        stName = request.GET.get('state_name', None)
        pestName = request.GET.get('pest', None)

        if (stName == None or pestName == None):
                return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)
        x_axis, y_axis, upper_bnd, lower_bnd = predict_pest(pestName, stName)
        if (x_axis == -1):
                return HttpResponse("No query for this combo in dataset", status=status.HTTP_400_BAD_REQUEST)
        dict1 = {'x_axis': x_axis, 'y_axis': y_axis, 'upper_bnd': upper_bnd, 'lower_bnd': lower_bnd}
        return JsonResponse(dict1,safe=False)

@api_view(['GET','POST'])
def user_location(request):
    if request.method=='GET':
        Latitude = request.GET.get('Latitude', None)
        Longitude = request.GET.get('Longitude', None)

        if (Latitude == None or Longitude == None):
                return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)
        state_name = get_location(Latitude, Longitude)
        dict1 = {"state_name": state_name}
        return JsonResponse(dict1,safe=False)

@api_view(['GET','POST'])
def home_page(request):
    if request.method=='GET':
        dict={}
        dict['date__gte']= request.GET.get('date1', None)
        dict['date__lte']= request.GET.get('date2', None)
        dict['crop']=  request.GET.get('crop', None)
        dict['pest']=  request.GET.get('pest', None)
        dict['state_name']= request.GET.get('state_name', None)
        dict['district_name']= request.GET.get('district_name', None)

        dict2={}
        flag=0
        for item in dict.items():
            print(item[1])
            if (item[1]!="all"):        #important
                dict2[item[0]]=item[1]
            if (item[1]==None):
                flag=1
                break
        print(flag)
        if(flag==1):
            return HttpResponse("HTTP_400_BAD_REQUEST", status=status.HTTP_400_BAD_REQUEST)
        dict= get_query(dict2)
        return JsonResponse(dict,safe=False)

def dt_funct():
    dict=defaultdict(int)
    return dict

@api_view(['GET', 'POST'])
def tutorial_list_1(request):
    if request.method == 'GET':
        print("///////////////////////////////")
        check()
        title = request.GET.get('date1', None)
        title1 = request.GET.get('date2', None)
        print(title1)
        if title is not None:
            print("true")
            query_start_time = time.time()

            tutorials = Tutorial.objects.filter(Q(date__gte=title)&Q(date__lte=title1)).values_list('state_name','district_name','count')
            cnt1=0
            cnt2=0
            dict=defaultdict(dt_funct)
            for item in tutorials:
                print(item)
                dict[item[0]][item[1]]=dict[item[0]][item[1]]+item[2]
                cnt1=cnt1+1
                cnt2=cnt2+item[2]
            print("---Finished querying db in %s seconds ---" % (time.time() - query_start_time))
            print(cnt1)
            print(cnt2)
            return JsonResponse(dict,safe=False)
        else:
            tutorials= Tutorial.objects.all()
        tutorials_serializer = TutorialSerializer(tutorials,many=True)
        print(tutorials_serializer.data[0])
        return JsonResponse(tutorials_serializer,safe=False)

    if request.method == 'POST':
        tutorial_data = JSONParser().parse(request)
        print(tutorial_data['date'])
        tutorial_data['date'] = datetime.datetime.strptime(tutorial_data['date']+"T00:00:00Z", "%Y-%m-%dT%H:%M:%SZ")
        print(tutorial_data['date'])
        tutorial_serializer = TutorialSerializer(data=tutorial_data)
        if tutorial_serializer.is_valid():
            print("inside")
            #return JsonResponse(tutorial_serializer.validated_data)
            return HttpResponse(tutorial_serializer.data['date'])
        else:
            print(tutorial_serializer.errors)
            return HttpResponse("yo mannn  ")

@api_view(['GET', 'PUT', 'DELETE'])
def tutorial_detail(request, pk):
    # find tutorial by pk (id)
    try:
        tutorial = Tutorial.objects.get(pk=pk)
    except Tutorial.DoesNotExist:
        return JsonResponse({'message': 'The tutorial does not exist'}, status=status.HTTP_404_NOT_FOUND)

    # GET / PUT / DELETE tutorial

@api_view(['GET'])
def tutorial_list_published(request):
    return JsonResponse({'message': 'The tutorial does not exist'}, status=status.HTTP_404_NOT_FOUND)

    # GET all published tutorials


import os

import torch
import torchvision
from dotmap import DotMap
from torch.utils.data import DataLoader
import warnings
warnings.filterwarnings("ignore", category=UserWarning)  # suppress deprecation warning coming from torchvision
from torchvision import transforms as T

from src.dataset.celeba import CelebAGenerator
from src.dataset.transforms import transformer
from src.utils import config
from src.utils.config import get_config

def get_root(dataset_type):
    conf = get_config('config/default.env')
    return conf.dataset_root.__dict__[dataset_type]

def get_n_classes_and_channels(str_dataset):
    datasets = get_datasets(str_dataset)
    n_channels = int(datasets['train'][0][0].shape[0])
    return len(datasets.train.classes), n_channels

def get_data_loaders(str_dataset, seed=None, **kwargs):
    datasets = get_datasets(str_dataset)

    if seed is not None:
        torch.manual_seed(seed)

    common_settings = dict(batch_size=32, num_workers=4, drop_last=True)
    common_settings.update(**kwargs)

    if config.debug:
        batch_size = kwargs.get('batch_size', 50)
        datasets.train = data_utils.Subset(datasets.train, torch.arange(3 * batch_size + 1))
        datasets.val = data_utils.Subset(datasets.val, torch.arange(3 * batch_size + 1))

    train = DataLoader(datasets.train, shuffle=True, **common_settings)
    val = DataLoader(datasets.val, **common_settings)

    data_loaders = DotMap({'train': train, 'val': val})
    return data_loaders

def get_datasets(str_dataset):
    str_dataset = str_dataset.lower()

    if str_dataset == 'fashion':
        trans = transformer['mnist']
        return create_pytorch_datasets(torchvision.datasets.FashionMNIST, trans)
    elif str_dataset == 'mnist':
        trans = transformer['mnist']
        return create_pytorch_datasets(torchvision.datasets.MNIST, trans)
    elif str_dataset == 'cifar10':
        trans = transformer['cifar10']
        return create_pytorch_datasets(torchvision.datasets.CIFAR10, trans)
    elif str_dataset == 'cifar100':
        trans = transformer['cifar100']
        return create_pytorch_datasets(torchvision.datasets.CIFAR100, trans)
    elif str_dataset in ['celeba', 'celebagenerator']:
        trans = transformer['celeba']
        return create_celebalucid_datasets('celeba', trans)
    else:
        raise ValueError('Dataset {} is unknown.'.format(str_dataset))

def create_pytorch_datasets(dataset_func, trans):
    root = get_root('pytorch')
    train_trans = T.Compose(trans[0])
    val_trans = T.Compose(trans[1])

    try:
        train = dataset_func(root, train=True, transform=train_trans)
        val = dataset_func(root, train=False, transform=val_trans)
    except:
        train = dataset_func(root, train=True, download=True, transform=train_trans)
        val = dataset_func(root, train=False, download=True, transform=val_trans)

    return DotMap({'train': train, 'val': val})

def create_celebalucid_datasets(data_name, trans):
    root = get_root(data_name)

    csv = {
        'train': os.path.join(root, 'train.csv'),
        'val': os.path.join(root, 'test.csv')
    }

    trans = {
        'train': T.Compose(trans[0]),
        'val': T.Compose(trans[1])
    }

    train = CelebAGenerator(csv['train'], trans['train'])
    val = CelebAGenerator(csv['val'], trans['val'])
    return DotMap({'train': train, 'val': val})


import os

from ament_index_python.packages import get_package_share_directory

from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration

from launch_ros.actions import Node

def generate_launch_description():
    return LaunchDescription([
        DeclareLaunchArgument('namespace', default_value=''),
        nao_state_publisher()
    ])

def nao_state_publisher():

    urdf_file_name = 'nao.urdf'
    urdf = os.path.join(
        get_package_share_directory('nao_description'),
        'urdf',
        urdf_file_name)
    with open(urdf, 'r') as infp:
        robot_desc = infp.read()

    return Node(
            package='nao_state_publisher',
            executable='nao_state_publisher',
            namespace=LaunchConfiguration('namespace'),
            output='screen',
            parameters=[{'robot_description': robot_desc}],
            arguments=[urdf],
        )


import sys

from django.contrib.auth.models import User
from django.db.models import Q
from .models import *

class SelfField:
   pass

class RelatedField:

	def __init__(self, search):
		super().__init__()
		self.search = search
		print(self.search,'\n')

	@property
	def search_class(self):
		""" returns search class object """
		if self.search:
			if type(self.search) == str:
				try:
					return getattr(sys.modules[__name__], self.search)
				except:
					pass
			else:
				return self.search

		return None

	def get_ql(self, field, query):
		q = list()
		for item in self.search_class().get_mql(query=query):
			for key, value in item.items():
				q.append({field+'__'+key : value})

		return q

class Search:
	# returns field name of self class
	def get_fields(self):
			return [field for field in dir(self) if not callable(getattr(self, field)) and not field.startswith('__')]

	def get_ql(self, field, query):
		""" Returns generated lookups for single word in a query for a field"""
		q = list()
		for item in query.split(' '): # split query for multiple word search
			q.append({ field + '__istartswith': item })
		return q

	def get_mql(self, query):
		fields = self.get_fields()
		mql = list()
		for field in fields:
			field_obj = getattr(self, field)

			if type(field_obj) == SelfField: # calls the mql generator of self model
				mql += self.get_ql(field=field, query=query)

			elif type(field_obj) == RelatedField: # calls the mql generator of related model
				mql += field_obj.get_ql(field=field, query=query)

		return mql

	def get_full_mql(self, query):
		q = None
		for item in self.get_mql(query=query):
			if not q:
				q = Q(**item)
			else:
				q = q | Q(**item)
		return q

	def search(self,query):
		mql = self.get_full_mql(query=query)
		return self.Meta.model.objects.filter(mql).distinct()

#
#------------------------------------------------------------
#

class UserSearch(Search):
	username = SelfField()
	first_name = SelfField()
	last_name = SelfField()

	class Meta:
		model = User

class CallTypeSearch(Search):
	name = SelfField()

	class Meta:
		model = CallType

class CallPurposeSearch(Search):
	name = SelfField()

	class Meta:
		model = CallPurpose

class CallStatusSearch(Search):
	name = SelfField()

	class Meta:
		model = CallStatus

class CommunicationMediumSearch(Search):
	name = SelfField()

	class Meta:
		model = CommunicationMedium

class CallSearch(Search):
	call_type = RelatedField(search=CallTypeSearch)
	purpose = RelatedField(search=CallPurposeSearch)
	status = RelatedField(search=CallStatusSearch)
	class Meta:
		model = Call

class DealSearch(Search):
	title = SelfField()

	class Meta:
		model = Deal

class EventSearch(Search):
	print('bikash saerch type')
	location = SelfField()
	subject = SelfField()
	class Meta:
		model = Event

class FeedSearch(Search):
	employee = RelatedField(search = UserSearch)
	date = SelfField()
	deal = RelatedField(search = DealSearch )

	class Meta:
		model = Feeds


"""Shared ploting code for the web summary."""
import copy

BUTTON_RESET_SCALED_2D = "resetScale2d"
BUTTON_TO_IMAGE = "toImage"
TO_IMAGE_BUTTON_OPTIONS = "toImageButtonOptions"
MODE_BAR_BUTTONS = "modeBarButtons"
CONFIG = "config"
SHOW_AXIS_DRAG_HANDLES = "showAxisDragHandles"

PLOT_CONFIG = {
    "staticPlot": False,
    "displayModeBar": True,
    MODE_BAR_BUTTONS: [[BUTTON_TO_IMAGE, BUTTON_RESET_SCALED_2D]],
    SHOW_AXIS_DRAG_HANDLES: True,
    TO_IMAGE_BUTTON_OPTIONS: {"width": 730, "height": 650},      # ensure that this is square
    "scrollZoom": False,
}

# Make a spatial config that is similar but with no zoom or reset axis button
SPATIAL_PLOT_CONFIG = copy.deepcopy(PLOT_CONFIG)
SPATIAL_PLOT_CONFIG[MODE_BAR_BUTTONS] = [[]]
del SPATIAL_PLOT_CONFIG[TO_IMAGE_BUTTON_OPTIONS]
SPATIAL_PLOT_CONFIG[SHOW_AXIS_DRAG_HANDLES] = False

DEFAULT_WEB_FONT = "DIN Next LT Pro"

def add_font_to_layout(chart, font=DEFAULT_WEB_FONT):
    """ Updates a charts `layout` dictionary to use a specific font."""
    fnt = {"family": font}
    if isinstance(chart, dict):
        layout = chart['layout']
    elif hasattr(chart, "layout"):
        layout = chart.layout
    else:
        raise Exception("Must pass an object or dictionary to update layout font.")
    font_dict = layout.get('font', {})
    font_dict.update(fnt)
    layout['font'] = font_dict


"""There are three tasks to complete for this Bite:

Finish the function load_words which creates and returns a list of words from a text file.
Finish the function calc_word_value which calculates and returns a word's Scrabble value.
Finish the function max_word_value which finds and returns the dictionary word with the highest score.
Notes:

The text of the dictionary is downloaded for you and is available with the path contained in the variable DICTIONARY.
The words in the file are separated by a newline character.
Letters not found in LETTER_SCORES score zero points.
Look at the TESTS tab to see what your code needs to pass. Enjoy!
"""

import os
import urllib.request

# PREWORK
TMP = os.getenv("TMP", "/tmp")
S3 = 'https://bites-data.s3.us-east-2.amazonaws.com/'
DICT = 'dictionary.txt'
DICTIONARY = os.path.join(TMP, DICT)
urllib.request.urlretrieve(f'{S3}{DICT}', DICTIONARY)

scrabble_scores = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
                   (4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z")]
LETTER_SCORES = {letter: score for score, letters in scrabble_scores
                 for letter in letters.split()}

# start coding

def load_words():
    """Load the words dictionary (DICTIONARY constant) into a list and return it"""
    with open(DICTIONARY, "r") as file:
        dic_list = [x.strip() for x in file]

    return dic_list

def calc_word_value(word):
    """Given a word calculate its value using the LETTER_SCORES dict"""
    score = 0
    for letter in word.upper():
        if letter in LETTER_SCORES.keys():
            score += LETTER_SCORES.get(letter)
    return score

def max_word_value(words):
    """Given a list of words calculate the word with the maximum value and return it"""
    max_dic = {}
    for word in words:
        max_word = calc_word_value(word)
        max_dic.update({word: max_word})

    return max(max_dic, key=max_dic.get)


from bs4 import BeautifulSoup
import nltk # importing the natural language toolkit
from nltk.util import ngrams # importing ngrams to create bigram indexes
from nltk.corpus import stopwords
import numpy as np
import pickle # importing pickle to convert objects to bytestream and use later
from collections import Counter

INDEX = "./pickles_imp2/" # creating directory for pickled objects

all_docs = []

for i in [15,19,25,30,45]:
    f = open("AC_wiki_" + str(i), encoding="utf8")
    filecontent = f.read()
    # Separating the different documents using a split on end doc tag
    docs = filecontent.split("</doc>")
    # Parsing the split output docs using bs and lxml leaving the last split as it would be empty
    docs = [BeautifulSoup(doc + "</doc>", "lxml") for doc in docs][:-1]
    all_docs.extend(docs)
    f.close()

# Creating the list of doc ids, doc titles and document text to zip them together
doc_id = [] # List that contains ids of all documents
doc_title = [] # List that contains title of all documents
doc_text = [] # List that contains content of all documents
docs_dict = {} # term_dictonary with id and title as key-value
for doc in all_docs:
    id = doc.find_all("doc")[0].get("id")
    title = doc.find_all("doc")[0].get("title")
    text = doc.get_text()
    doc_id.append(id)
    doc_title.append(title)
    doc_text.append(text)
    docs_dict[id] = title
# Zipping all the lists together
indexed_docs = list(zip(doc_id, doc_title, doc_text))

# Creation of vocabulary with all the content we have
tokens = []
for page in doc_text:
    # Using the nltk word tokenizer to get word tokens from a given doc content
    tokens.extend(nltk.word_tokenize(page))
vocabulary = sorted(set(tokens))

tdf = {}  # term frequency for all terms in the vocab
for term in vocabulary:
    tdf[term] = {}
for document in indexed_docs:
    d_id = document[0] # ID of the specific doc
    d_tokens = nltk.word_tokenize(document[2]) # Tokens for specific doc
    for term in d_tokens:
        if term in tdf: # Why is this required as all terms are there in vocab
            if d_id in tdf[term]:
                tdf[term][d_id] = tdf[term][d_id] + 1
            else:
                tdf[term][d_id] = 1

wt = {}  # for storing the tf-wt(logarithmic)
sos = {}  # sum of squares of wt for final normalization
for doc in doc_id:
    sos[doc] = 0
for term in vocabulary:
    term_dict = tdf[term]
    wt[term] = {}
    for key, value in term_dict.items():
        wt[term][key] = 1 + np.log10(value) # key is the doc id and value is tf for respective doc id
        sos[key] = sos[key] + wt[term][key] ** 2

norm = {}  # Normalized logarithmic term document frequencies
for term in vocabulary:
    term_dict = tdf[term]
    norm[term] = {}
    for key, value in term_dict.items():
        norm[term][key] = wt[term][key] / (np.sqrt(sos[key]))

#bigrams
bigrams = [] #list of all bigrams in corpus
bigram_freq = {} # dictionary which contains bigrams as key as frequency as value
first_word = {} # dictionary which contains first word
second_word = {} # dictionary which contains second word

stop_words = set(stopwords.words('english'))
for content in doc_text:
    temp = list(ngrams(nltk.word_tokenize(content),2))
    bigrams.extend(temp)

unique_bigrams = list(set(bigrams)) # list of unique bigrams
num_bigrams = len(bigrams) # number of bigrams

#Creating the dictionary containing the bigram frequency
for val in bigrams:
  if val in bigram_freq:
    bigram_freq[val] = bigram_freq[val] + 1
  else:
    bigram_freq[val]=1

#frequency of tokens
for token in tokens:
    first_word[token] = 0
    second_word[token] = 0
for token in tokens:
    first_word[token] = first_word[token] + 1
    second_word[token] = second_word[token] + 1

chi_square_scores = {}

#calculating chi-square scores for all the bigrams
for bigram in unique_bigrams:
	word1 = bigram[0] #word1 of the bigram
	word2 = bigram[1] #word2 of the bigram
	o11 = bigram_freq[bigram] #freq of bigram in the corpus
	o21 = first_word[word1] - o11
	o12 = second_word[word2] - o11
	o22 = num_bigrams - o11 - o21 - o12
	chi_score = num_bigrams*(((o11*o22-o21*o12)**2)/((o11+o21)*(o11+o12)*(o21+o22)*(o12+o22)))
	if(o21 + o12 > 10):
			chi_square_scores[bigram] = chi_score

#sort collocations in descending order of importance
collocations = sorted(chi_square_scores.items(), key = lambda x:(x[1], x[0]),reverse=True)

frequent_collocations = [] #storing the top 1000 collocations

#Getting the 1000 most common bigrams
count = 0
for (bi,chi_score) in collocations:
    count = count + 1
    if count <= 1000:
          frequent_collocations.append(bi)
    else:
      break

bigram_tdf = {} #Dictionary containing tdf of the bigrams in the documents
for term in frequent_collocations:
    bigram_tdf[term] = {}

#To create natural term document frequency of the frequent collocations
for doc in indexed_docs:
    d_id = doc[0]
    doc_bigrams = ngrams(nltk.word_tokenize(doc[2]),2)
    for bigram in doc_bigrams:
        if bigram not in bigram_tdf:
            continue
        if d_id in bigram_tdf[bigram]:
            bigram_tdf[bigram][d_id] = bigram_tdf[bigram][d_id] + 1
        else:
            bigram_tdf[bigram][d_id] = 1

#Calculating the bigram normalized logarithmic tf for top 1000 collocations
bigram_wt = {}
bigram_sos = {}
bigram_norm = {}

for doc in doc_id:
    bigram_sos[doc] = 0

#Getting the bigram normalised tdf
for bigram in bigram_tdf:
    bigram_dict = bigram_tdf[bigram]
    bigram_wt[bigram] = {}
    bigram_norm[bigram] = {}
    for key,value in bigram_dict.items():
        bigram_wt[bigram][key] = 1 + np.log10(value)
        bigram_sos[key] = bigram_sos[key] + bigram_wt[bigram][key]**2
    for key,value in bigram_dict.items():
        bigram_norm[bigram][key] = bigram_wt[bigram][key] / (np.sqrt(bigram_sos[key]))

#dictionary for inverse document frequency of all terms in vocab
idf = {}
for term in vocabulary:
    if len(norm[term]) == 0:
        idf[term] = 0
    else:
        idf[term] = np.log10(len(all_docs) / len(norm[term]))

# Creation of the index and dumping as bytestream using pickle
# Using wb to write in binary mode.
norm_tfwt = open(INDEX + 'Normalized_tdf', 'wb')
pickle.dump(norm, norm_tfwt)
norm_tfwt.close()

term_idfs = open(INDEX + 'term_idf', 'wb')
pickle.dump(idf, term_idfs)
term_idfs.close()

doc_dictionary = open(INDEX + 'docs_dict', 'wb')
pickle.dump(docs_dict, doc_dictionary)
doc_dictionary.close()

vocab = open(INDEX + 'Vocabulary', 'wb')
pickle.dump(vocabulary, vocab)
vocab.close()

bigram_tdfs = open(INDEX+'bigram_tdf','wb')
pickle.dump(bigram_tdf, bigram_tdfs)
bigram_tdfs.close()

bigram_norm_tfwt = open(INDEX+'bigram_normalized_tdf','wb')
pickle.dump(bigram_norm, bigram_norm_tfwt)
bigram_norm_tfwt.close()


"""
NIM             : 24010316140048
Nama            : Ahmad Alexander
Deskripsi       : Tugas Terakhir Praktikum B1
Tanggal         : 10 Desember 2020
"""

from ListofList import *
from TreeB import *

# LIST#
L1 = []
L2 = [1, 2, 3]
L3 = [1, [2, 3], [4]]
L4 = ["u", "n", "d", "i" "p"]

# MATRIX#
M2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
M1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# SET#
H1 = [4, 5, 6]
H2 = []

# TREE#
P1 = [1, [2, [3, [], []], [4, [], []]], [5, [], []]]
P2 = [2, [], []]

"""""" "LIST" """"""
"""1"""
# DefSpek
# SumElmtX : Integer, List of integer --> integer
# SumElmtX (X, L) menjumlahkan nilai elemen list tanpa elemen bernilai X
# Realisasi
def SumElmtX(X, L):
    if IsList(L):
        if IsEmpty(L):
            return 0
        elif IsList(FirstElmt(L)):  # ngecek list of list
            return SumElmtX(X, FirstElmt(L)) + SumElmtX(X, Tail(L))
        elif FirstElmt(L) == X:
            return 0 + SumElmtX(X, Tail(L))
        else:
            return FirstElmt(L) + SumElmtX(X, Tail(L))
    else:
        return 0

L = [1, 2, 3, 4, 5]
# Aplikasi : SumElmtX(5, L) --> 10
print(SumElmtX(5, L))

"""2"""
# DefSpek
# MaxList : List of integer --> Integer
# MaxList(L) menghasilkan nilai elemen terbesar dari list L
# Realisasi
def MaxList(L):
    if IsOneElmt(L):
        return FirstElmt(L)
    else:
        if MaxList(Tail(L)) > FirstElmt(L):
            return MaxList(Tail(L))
        else:
            return FirstElmt(L)

L = [2, 4, 5, 1]
# Aplikasi : MaxList(L) --> 5
print(MaxList(L))

# Hint : Untuk memudahkan, buat fungsi untuk mengecek nilai maksimum

"""3"""
# DefSpek
# MinList : List of integer --> Integer
# MinList(L) menghasilkan nilai elemen terkecil dari list L
# Realisasi
def MinList(L):
    if IsOneElmt(L):
        return FirstElmt(L)
    else:
        if MinList(Tail(L)) < FirstElmt(L):
            return MinList(Tail(L))
        else:
            return FirstElmt(L)

L = [2, 4, 5, 1]
# Aplikasi : MinList(L) --> 1
print(MinList(L))

"""4"""
# DefSpek
# UraikanListOfList : List of list --> List
# UraikanListOfList(L) menghasilkan hasil penguraian dari List of list L menjadi list biasa
# Realisasi
def UraikanListOfList(L):
    if not L:
        return []
    if isinstance(FirstElmt(L), list):
        return UraikanListOfList(FirstElmt(L)) + UraikanListOfList(Tail(L))
    else:
        return [FirstElmt(L)] + UraikanListOfList(Tail(L))

L = [1, [2, 3], 4, [5]]
# Aplikasi : UraikanListOfList(L) --> [1, 2, 3, 4, 5]
print(UraikanListOfList(L))

"""5"""
# DefSpek
# ListMaxMin : List of integer --> List
# ListMaxMin(L) membuat List dengan anggotanya hanya 2 elemen yaitu elemen terbesar dan terkecil dari list L
# Realisasi
def ListMaxMin(L):
    if not IsEmpty(L):
        if not IsOneElmt(L):
            return [MinList(L)] + [MaxList(L)]
        else:
            return L
    else:
        return []

L = [4, 2, 5, 3, 7, 1]
# Aplikasi : ListMaxMin(L) ---> [1, 7]
print(ListMaxMin(L))

"""6"""
# DefSpek
# SetElmtXzero : Integer, list of integer --> list of integer
# SetElmtXzero(L,3) menghasilkan list baru yang mengganti setiap elemen x menjadi 0
# Realisasi
def SetElmtXzero(L, x):
    if IsListInt(L):
        if not IsEmpty(L):
            if FirstElmt(L) == x:
                return Konso(FirstElmt(L) * 0, SetElmtXzero(Tail(L), x))
            else:
                return Konso(FirstElmt(L), SetElmtXzero(Tail(L), x))
        else:
            return L
    else:
        return 0

L = [1, 2, 3, 4, 5]
# Aplikasi : SetElmtXzero(L,3) --> [1, 2, 0, 4, 5]
print(SetElmtXzero(L, 3))

"""7"""
# DefSpek
# XPos : List of char --> Integer
# XPos(L,X) menghasilkan posisi index dari char X yang dicari
# Realisasi
def XPos(L, X):
    if IsListChar(L) and not IsEmpty(L):
        if FirstElmt(L) == X:
            index = L.index(FirstElmt(L))
            return index
        else:
            return 1 + XPos(Tail(L), X)

L = ["j", "a", "y", "a"]
# Aplikasi : XPos(L,'a') --> 1
# Hint : Index dimulai dari 0. Huruf 'a' pada contoh di atas berada pada POSISI INDEX ke-1 dari list L
#          Jika ada lebih dari satu karakter yang sama, return index karakter pertama yang ketemu
print(XPos(L, "a"))

"""8"""
# DefSpek
# SortMax(L) : list of integer --> list of integer
# SortMax(L) menghasilkan list baru dimana mengurutkan elemen dari yang terbesar ke terkecil
# Hint : Ada di diktat, tinggal ubah sedikit
# Realisasi
def SortMax(L):
    if NbElmt(L) < 2:
        return L
    else:
        # i = L.index(max(L))
        # return [L[i]] + SortMax(L[:i] + L[i + 1 :])
        return Insort(L)

print(SortMax(L2))

"""""" "SET" """"""
"""9"""
# DefSpek
# RemberAll : Set --> Empty Set
# RemberAll(H) menghapus semua elemen pada set H
# Realisasi
def RemberAll(H):
    if IsEmpty(H):
        return []
    if not IsEmpty(H):
        return Konso([], RemberAll(Tail(H)))
    else:
        return RemberAll(Tail(H))

H = [1, 2, 3, 4]
# Aplikasi : RemberAll(H) --> []
# Hint : Jangan langsung return []
print(RemberAll(H))

"""""" "TREE" """"""
"""10"""
# DefSpek
# TinggiPohon : Binary Tree --> Integer
# TinggiPohon(P) menghasilkan tinggi dari pohon P (Tinggi pohon dimulai dari 1)
#                4              --Level 1
#             /     \
#           2         5         --Level 2
#         /
#       1                       --Level 3
# Realisasi
def TinggiPohon(P):
    if IsTreeEmpty(P) or IsOneElmtPB(P):
        return 1
    else:
        if TinggiPohon(Left(P)) > TinggiPohon(Right(P)):
            return TinggiPohon(Left(P)) + 1
        else:
            return TinggiPohon(Right(P)) + 1

P = [4, [2, [1, [], []], [[], [], []]], [5, [], []]]
# Aplikasi : TinggiPohon(P) --> 3
# Hint : Hati-hati dengan perbedaan tinggi Left(P) dan Right(P)
print(TinggiPohon(P))

"""11"""
# DefSpek
# IsBalanceTree : Binary Tree  --> Boolean
# IsBalanceTree(P) mengecek apakah pohon P merupakan balance tree
#                4
#             /     \
#           2         5
#         /             \
#       1                 6
def IsBalanceTree(P):
    if IsTreeEmpty(P) or IsOneElmtPB(P):
        return True
    else:
        if TinggiPohon(Left(P)) == TinggiPohon(Right(P)):
            return True
        else:
            return False

P = [4, [2, [1, [], []], [[], [], []]], [5, [], [[6], [], []]]]
# Aplikasi : IsBalanceTree(P) --> True
# Hint : Balance tree bernilai true ketika selisih tinggi pohon Right dan Left tidak lebih dari 1
#        : ATAU selisih banyaknya node Right dan Left tidak lebih dari 1
print(IsBalanceTree(P))

"""12"""
# DefSpek
# Terkiri : Binary Search Tree --> Node dalam integer
# Terkiri(P) menghasilkan node terkiri dari pohon P
#                7
#             /     \
#           2         8
#         /   \      /
#       1       3  6
#                  /
#                 5
# Realisasi
def Terkiri(P):
    if not IsTreeEmpty(P):
        if IsExistLeft(P):
            if IsTreeEmpty(Akar(Left(P))):
                return Akar(Left(P))
            else:
                return Terkiri(Left(P))
        else:
            return Akar(P)
    else:
        return None

P = [7, [2, [1, [], []], [3, [], []]], [8, [6, [[5], [], []], []], []]]
# Aplikasi : Terkiri(P) --> 1
# Hint : Node terkiri selalu node paling kecil dari BinarySearchTree
print(Terkiri(P))

"""13"""
# DefSpek
# IsSkewRight : Binary Tree  --> Node atau integer
# IsSkewRight(P) mengecek apakah pohon P condong kanan
def IsSkewRight(P):
    if IsTreeEmpty(P):
        return False
    else:
        if IsOneElmtPB(P):
            return True
        else:
            if IsUnerRight(P):
                return IsSkewRight(Right(P))
            else:
                return False

# P1
#                7
#                  \
#                    8
#                      \
#                        9
#                         \
#                           10
P1 = [7, [], [8, [], [9, [], [10, [], []]]]]
# Aplikasi : IsSkewRight(P1) --> True
print(IsSkewRight(P1))

# P2
#                7
#             /     \
#           2         8
#         /   \      /
#       1       3  6
#                  /
#                 5
P2 = [7, [2, [1, [], []], [3, [], []]], [8, [6, [5, [], []], []], []]]
# Aplikasi : IsSkewRight(P2) --> False
print(IsSkewRight(P2))
"""""" "SOAL BONUS" """"""
"""Buat latihan aja, nggak usah dikumpulin"""
"""999"""
# DefSpek
# ReversePohon : Binary Tree  --> Tree
# ReversePohon(P) menghasilkan pohon P yang sudah di reverse
def ReversePohon(P):
    P[1], P[2] = P[2], P[1]
    if IsExistLeft(P):
        ReversePohon(P[1])
    if IsExistRight(P):
        ReversePohon(P[2])
    return P

P = [1, [2, [4, [8, [], []], [9, [], []]], [5, [], []]], [3, [6, [], []], [7, [], []]]]
print(ReversePohon(P))

#                1
#             /      \
#           2          3
#         /   \      /    \
#       4      5   6      7
#      / \
#     8   9

# Aplikasi : ReversePohon(P) -->
P = [1, [3, [7, [], []], [6, [], []]], [2, [5, [], []], [4, [9, [], []], [8, [], []]]]]

print(ReversePohon(P))

#                1
#             /      \
#           3          2
#         /   \      /    \
#       7      6   5      4
#                           / \
#                          9   8


from tkinter import *

def imprimirEsporte():
    ve = vesporte.get() #Recebe o valor da variavel
    if ve == "f":
        print("Esporte Futebol")
    elif ve == "v":
        print("Esporte Volei")
    elif ve == "b":
        print("Esporte Basquete")
    else:
        print("Selecione um Esporte")

app = Tk()
app.title("CFB Cursos")
app.geometry("500x300")

vesporte = StringVar() #Armazenara o valor do Radio Button
vcor = StringVar()

rb_futebol = Radiobutton(app, text = "Futebol", value = "f", variable = vesporte)
rb_futebol.pack()

rb_volei = Radiobutton(app, text = "Volei", value = "v", variable = vesporte)
rb_volei.pack()

rb_basquete = Radiobutton(app, text = "Basquete", value = "b", variable = vesporte)
rb_basquete.pack()

rb_verde = Radiobutton(app, text = "Verde", value = "#0F0", variable = vcor)
rb_verde.pack()

rb_vermelho = Radiobutton(app, text = "Vermelho", value = "#F00", variable = vcor)
rb_vermelho.pack()

btn_esporte = Button(app, text = "Esporte Selecionado", command = imprimirEsporte)
btn_esporte.pack()

app.mainloop()


#!/bin/python3

# Time to solution: 9 min
# https://www.hackerrank.com/challenges/crush/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays
# Hard

import math
import os
import random
import re
import sys

#
# Complete the 'arrayManipulation' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
#  1. INTEGER n
#  2. 2D_INTEGER_ARRAY queries
#

'''
Instead of applying the sum to every element of array's slice, only take care of the borders (a and b).
'''
def arrayManipulation(n, queries):
    array = [0]*(n+1)
    for q in queries:
        array[int(q[0])-1] += int(q[2])
        array[int(q[1])] -= int(q[2])

    max_val = 0
    sum_val = 0
    for q in range(n):
        sum_val += array[q]
        max_val = sum_val if sum_val > max_val else max_val
    return max_val

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    first_multiple_input = input().rstrip().split()

    n = int(first_multiple_input[0])

    m = int(first_multiple_input[1])

    queries = []

    for _ in range(m):
        queries.append(list(map(int, input().rstrip().split())))

    result = arrayManipulation(n, queries)

    fptr.write(str(result) + '\n')

    fptr.close()


import os
import sys

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5 import QtCore
from PyQt5 import QtGui

current_directory = os.path.dirname(os.path.abspath(__file__))
parent_directory = os.path.abspath(os.path.join(current_directory, os.pardir))
resource_directory = os.path.join(current_directory, "resources")
sys.path.append(os.path.join(parent_directory, "core"))

from game import Game
from unit import Directions

class Aquarium(QWidget):
    score_changed = QtCore.pyqtSignal()

    def __init__(self, parent):
        super(Aquarium, self).__init__()
        self.game = Game((self.size().width(), self.size().height()))
        self.score = self.game.score
        self.score_changed.emit()
        self.paused = False
        self.load_pictures()
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.action)
        self.timer.start(40)

    def resizeEvent(self, event):
        self.game.constrain((event.size().width(), event.size().height()))

    def paintEvent(self, event):
        canvas = QtGui.QPainter()
        canvas.begin(self)
        canvas.setPen(QtCore.Qt.NoPen)
        canvas.drawPixmap(0, 0, self.background.scaled(self.size().width(),
                          self.size().height()))
        for alien in self.game.aliens:
            self.draw_alien(canvas, alien)
        for fish in self.game.fishes:
            self.draw_fish(canvas, fish)
        for coin in self.game.coins:
            self.draw_coin(canvas, coin)
        for food in self.game.food:
            self.draw_food(canvas, food)

    @QtCore.pyqtSlot()
    def spawn_fish(self):
        self.game.spawn_fish()

    @QtCore.pyqtSlot()
    def upgrade_weapon(self):
        self.game.upgrade_weapon()

    @QtCore.pyqtSlot()
    def upgrade_food(self):
        self.game.upgrade_food()

    @QtCore.pyqtSlot()
    def pause(self):
        self.paused = True

    @QtCore.pyqtSlot()
    def unpause(self):
        self.paused = False

    def mousePressEvent(self, event):
        if event.button() == QtCore.Qt.LeftButton:
            self.game.mouse_press(event.x(), event.y())

    def load_pictures(self):
        # Alien
        self.alien_images = {
            'lion': QtGui.QPixmap(
                os.path.join(resource_directory, "alien.png")),
            'blue': QtGui.QPixmap(
                os.path.join(resource_directory, "alien2.png"))}
        self.alien_images_mirrored = {}.fromkeys(self.alien_images)
        self.fill_mirrored(self.alien_images, self.alien_images_mirrored)

        # Fish
        self.fish_images = {
            'swim': QtGui.QPixmap(
                os.path.join(resource_directory, "fish_swim.png")),
            'eat': QtGui.QPixmap(
                os.path.join(resource_directory, "fish_eat.png")),
            'turn': QtGui.QPixmap(
                os.path.join(resource_directory, "fish_turn.png")),
            'hungry_die': QtGui.QPixmap(
                os.path.join(resource_directory, "fish_die.png")),
            'hungry_swim': QtGui.QPixmap(
                os.path.join(resource_directory, "hungry_swim.png")),
            'hungry_eat': QtGui.QPixmap(
                os.path.join(resource_directory, "hungry_eat.png")),
            'hungry_turn': QtGui.QPixmap(
                os.path.join(resource_directory, "hungry_turn.png"))}
        self.fish_images_mirrored = {}.fromkeys(self.fish_images)
        self.fill_mirrored(self.fish_images, self.fish_images_mirrored)

        # Food
        self.food_image = QtGui.QPixmap(
            os.path.join(resource_directory, "food.png"))

        # Coin
        self.coin_image = QtGui.QPixmap(
            os.path.join(resource_directory, "coin.png"))

        # Background
        self.background = QtGui.QPixmap(
            os.path.join(resource_directory, "background.png"))

    def fill_mirrored(self, normal_images, mirrored):
        for key, value in normal_images.items():
            mirror = value.toImage()
            mirror = mirror.mirrored(True, False)
            mirrored[key] = QtGui.QPixmap().fromImage(mirror)

    def action(self):
        """ Incorporates all objects' actions and calls the repaint event."""
        if not self.paused:
            self.game.actions()
            if self.score != self.game.score:
                self.score = self.game.score
                self.score_changed.emit()
            self.repaint()

    def draw_alien(self, canvas, alien):
        if alien.mirrored:
            image = self.alien_images_mirrored[alien.kind]
        else:
            image = self.alien_images[alien.kind]
        if alien.state == 'swim':
            state = 0
        else:
            state = 160
        canvas.drawPixmap(alien.x, alien.y, image,
                          alien.frame, state, 160, 160)

    def draw_fish(self, canvas, fish):
        state = fish.state
        if fish.hungry:
            state = 'hungry_' + state
        if fish.mirrored:
            image = self.fish_images_mirrored[state]
        else:
            image = self.fish_images[state]
        canvas.drawPixmap(fish.x, fish.y, image,
                          fish.frame, fish.size * 80, 80, 80)

    def draw_coin(self, canvas, coin):
        canvas.drawPixmap(coin.x, coin.y, self.coin_image,
                          coin.frame, coin.worth * 72, 72, 72)

    def draw_food(self, canvas, food):
        canvas.drawPixmap(food.x, food.y, self.food_image,
                          food.frame, 0, 40, 40)


import os
import re
import sys
import operator
import detect_snps

chr_number = sys.argv[1]
start = int(sys.argv[2])
end = int(sys.argv[3])
snps_file = sys.argv[4]

############################################################################################

def generate_flanking_snp(cds,snps_array):

	for line in cds:

		#ENSGALT00000042749      1       35753   35950   1       198     -1

		if re.search("^(\S+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(.*1)$",line):

#			print line

			sub = re.search("^(\S+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(\d+)\t+(.*1)$",line)

			transcript_title = sub.group(1)

			exon_start = int(sub.group(3))
			exon_end  = int(sub.group(4))

			local_start = int(sub.group(5))
			local_end = int(sub.group(6))

			for snp in snps_array:

				if re.search("^(chr[\d+\w])\s+\d+\s+\.\s+(\w+)\s+(\w+)\s+",snp):

					sub = re.search("^(chr[\d+\w])\s+(\d+)\s+\.\s+(\w+)\s+(\w+)\s+",snp)

					dna_ori = sub.group(3)

					dna_sub = sub.group(4)

					snp_position = int(sub.group(2))

					if operator.gt(snp_position,exon_start) and operator.lt(snp_position,exon_end):

						snp_local = snp_position-exon_start+local_start-1 # need to adjust later

						if operator.eq(len(dna_ori),1) and operator.eq(len(dna_sub),1): # SNPs !!!

							print >> out_1, transcript_title,sub.group(1)+"\t"+str(snp_position)+"\t"+"["+dna_ori+"/"+dna_sub+"]"+"\t"+"coding region"+"\t"+str(snp_local)

						elif operator.gt(len(dna_ori),1) and operator.eq(len(dna_sub),1): # deletion !!!

							print >> out_1, transcript_title,sub.group(1)+"\t"+str(snp_position)+"\t"+"["+"B"+"/"+"X"+"]"+"\t"+"coding region"+"\t"+str(snp_local)

						elif operator.eq(len(dna_ori),1) and operator.gt(len(dna_sub),1): # insertion !!!

							print >> out_1, transcript_title,sub.group(1)+"\t"+str(snp_position)+"\t"+"["+dna_ori+"/"+"X"+"]"+"\t"+"coding region"+"\t"+str(snp_local)

						elif operator.gt(len(dna_ori),1) and operator.gt(len(dna_sub),1): # Indels !!!

							print >> out_1, transcript_title,sub.group(1)+"\t"+str(snp_position)+"\t"+"["+"B"+"/"+"X"+"]"+"\t"+"coding region"+"\t"+str(snp_local)

					if operator.gt(snp_position,exon_start-5) and operator.lt(snp_position,exon_start+5):

						print >> out_2, transcript_title+"\t"+str(snp_position)+"\t"+"["+dna_ori+"/"+dna_sub+"]"+"\t"+"splicing site"

					if operator.gt(snp_position,exon_end-5) and operator.lt(snp_position,exon_end+5):

						print >> out_2, transcript_title+"\t"+str(snp_position)+"\t"+"["+dna_ori+"/"+dna_sub+"]"+"\t"+"splicing site"

####################################################################################################################################################

if __name__ == '__main__':

	snps_list = detect_snps.extra_snps(chr_number,start,end,snps_file)
	x = open("../source/cds.txt",'r')

	out_1 = open("../source/snps_in_cds.txt",'w')

	out_2 = open("../source/snps_in_flanking_regions.txt",'w')

	generate_flanking_snp(x,snps_list)


'''
473. Matchsticks to Square
https://leetcode.com/problems/matchsticks-to-square/
'''
from typing import List

from test_tool import assert_value

class Solution:
    def makesquare(self, matchsticks: List[int]) -> bool:
        def backtrack(idx):
            if idx == len(matchsticks):
                return not sum(edges)

            for e_idx in range(len(edges)):
                if not edges[e_idx]:
                    continue
                if edges[e_idx] < matchsticks[idx]:
                    continue
                edges[e_idx] -= matchsticks[idx]
                if backtrack(idx + 1):
                    return True
                edges[e_idx] += matchsticks[idx]
                if edges[e_idx] == edge:
                    break
            return False

        edge, resid = divmod(sum(matchsticks), 4)
        if resid:
            return False
        matchsticks.sort(reverse=True)
        if matchsticks[0] > edge:
            return False

        edges = [edge] * 4
        return backtrack(0)


#!/usr/bin/env python
from __future__ import division
import os
import json
import struct
import tempfile
import shutil
import datetime
import traceback
import time
from bson.objectid import ObjectId

try:
    import Queue as queue
except ImportError:
    import queue

try:
    import SocketServer as socketserver
except ImportError:
    import socketserver

from dss.tools import buffer, thread, process, ffmpeg, Suppress
from dss.tools.os import set_pipe_max_size
from dss.tools.show import Show
from dss.config import config
from dss.storage import db
from dss.websocket import WebsocketBroadcast

from .enum import ContentType, DataContent
from .const import WAIT_TIMEOUT, HEADER_SIZE
from .processing.media import Media
from .processing.data import DataProc

show = Show('Mobile')

rtmpconf = config['rtmp-server']

class MediaHandler(socketserver.BaseRequestHandler, object):
    """  Packet header description

        The packet header will provide the type of payload data, and the size.

        [ T | S | S | S | S | D | D | ... ]

        T - 1st byte              - Type of message
        S - 2nd to 5th bytes      - Size of payload
        D - Data payload

        Currently we envision just 4 types of messages:
        Metadata, Video, Audio and User generated data.
    """

    provider_prefix = 'M'
    _handlers = set()
    _handlers_lock = thread.Lock()
    _time_limit = config.getint('mobile', 'time_limit')

    def setup(self):
        self._id = None
        self.run = True
        self.proc = None
        self.video = None
        self.audio = None
        self.destination_url = None
        self.data_processing = None
        self.thumbnail_path = None
        self.buffer = buffer.Buffer(self.request)
        self.data_queue = queue.Queue()
        self.tmpdir = tempfile.mkdtemp(dir=config['mobile']['dir'])
        self._timer_alarm = False
        self.timer = thread.Timer(self._time_limit, self.timer_alarm) \
            if self._time_limit else None
        self._error = []
        self.__cleanup_executed = False

    def add_handler(self):
        with self._handlers_lock:
            self._handlers.add(self)

    def remove_handler(self):
        with self._handlers_lock:
            self._handlers.remove(self)

    @property
    def error(self):
        return self._error

    @error.setter
    def error(self, value):
        self._error.append(value)

    @classmethod
    def wait_handlers(cls):
        while cls._handlers:
            time.sleep(0.1)

    def timer_alarm(self):
        self._timer_alarm = True

    def file(self, name, open_options=None):
        """ Return the name of a file in the temp dir.
            If open_options is supplied, the file will
            be opened and returned.
        """
        fname = os.path.join(self.tmpdir, name)
        if open_options is None:
            return fname
        return open(fname, open_options)

    def cleanup(self):
        """ Close pipes, remove files and temp dir and
            kills the transcoding process.
        """
        if self.__cleanup_executed:
            return

        s = Suppress(Exception)

        # Stop timer if any
        if self.timer is not None:
            self.timer.cancel()

        # Stop all threads
        with s: self.audio.stop()
        with s: self.video.stop()
        with s: self.data_processing.stop()

        # Remove entry from database
        if self._id:
            db.mobile.update({'_id': self._id}, {'$set': {'active': False}})

        # Remove temp directory and thumbnail
        with s: shutil.rmtree(self.tmpdir)
        with s: os.remove(self.thumbnail_path)

        WebsocketBroadcast.select('mobile_location').cls.broadcast_message({
            'name': self.get_stream_name(),
            'info': 'finished'
        })

        self.__cleanup_executed = True
        if s.errors:
            show.warn('Errors during cleanup:', *s.errors, sep='\n', end='\n\n')
        show('Mobile stream "{0}" has ended'.format(self._id))

    def finish(self):
        try:
            self.cleanup()
        except Exception as e:
            show.error('Exception while cleaning:', repr(e))
        finally:
            self.remove_handler()

    def handle(self):
        try:
            self._handle()
        except BaseException:
            show.error(traceback.format_exc())
            raise

    def _handle(self):
        self.request.settimeout(WAIT_TIMEOUT)
        self.add_handler()
        db_data = {'start': datetime.datetime.utcnow(),
                   'active': True}

        # Read the first data block.
        # It should have complete metadata information with at least the
        # provided id, if it is known (or falsy value otherwise)
        typ, payload = self.read_data()
        typ = DataContent[typ]
        if typ is DataContent.metadata:
            action, payload = DataProc.decode_data(payload)
            try:
                self._id = ObjectId(payload['id'])
            except Exception:
                pass
        else:
            show.error('Received first data block of type {0.name!r}({0.value}).\n'
                       'Expected {1.name!r}({1.value})', typ, DataContent.metadata)
            return

        response = db.mobile.update({'_id': self._id}, db_data, upsert=True)
        self._id = response.get('upserted', self._id)
        self.send_data(ContentType.meta, {'id': str(self._id)})
        self.destination_url = os.path.join(
            rtmpconf['addr'], rtmpconf['app'], self.get_stream_name()
        )
        show('New mobile stream:', self.destination_url)

        audio_filename = self.file('audio.ts')
        video_filename = self.file('video.ts')
        try:
            os.mkfifo(audio_filename)
            os.mkfifo(video_filename)
        except OSError as e:
            show.error('Failed to create FIFO:', e)
            return

        audio_pipe = os.open(audio_filename, os.O_RDWR)
        video_pipe = os.open(video_filename, os.O_RDWR)
        set_pipe_max_size(audio_pipe, video_pipe)

        self.audio = Media(audio_pipe, self, 'audio').start()
        self.video = Media(video_pipe, self, 'video').start()
        self.data_processing = DataProc(self).start()

        thumb = config['thumbnail']
        self.thumbnail_path = os.path.join(
            thumb['dir'], self.get_stream_name()
        ) + '.' + thumb['format']

        thumb_rate = str(1. / int(thumb['mobile_interval']))

        args = ffmpeg.cmd_inputs_outputs(
            '-y -re', [audio_filename, video_filename], '',
            ['-c:v copy -c:a copy -bsf:a aac_adtstoasc -f flv',
             '-r ' + thumb_rate + ' -update 1 -an'],
            [self.destination_url, self.thumbnail_path]
        )

        # Start the timer for alarm
        if self.timer is not None:
            self.timer.start()

        with self.file('proc_output', 'w') as out:
            with self.file('proc_err', 'w') as err:
                self.handle_proc_loop(args, out, err)

    def handle_proc_loop(self, proc_args, stdout, stderr):
        """ Open transcoding process and read data from buffer
            until the client stops sending data.
        """
        with process.Popen(proc_args, stdout=stdout, stderr=stderr) as self.proc:
            while self.server.is_running \
                    and not self._timer_alarm \
                    and not self.error \
                    and self.proc.poll() is None:
                try:
                    type, payload = self.read_data()
                except Exception:
                    show.warn('Timeout')
                    break

                if not self.run or type is None:
                    break

                self.handle_content(type, payload)

            if self._timer_alarm:
                show('Stream finished due to time limit: {0} seconds'.format(self._time_limit))

    def handle_content(self, type, payload):
        try:
            type = DataContent[type]
        except KeyError:
            show.warn('Invalid header type "%s"' % type)

        if type in (DataContent.metadata, DataContent.userdata):
            self.data_queue.put((type, payload))
        elif type is DataContent.video:
            self.video.add_data(payload)
        elif type is DataContent.audio:
            self.audio.add_data(payload)
        else:
            show.warn('Unknown content received: ' +
                      'Type: {0}, Payload: {1!r}'.format(type, payload))

    def process_header(self, data):
        """ Strips out the header
            Takes away the header data and returns it as a tuple of values.
        """
        size = struct.unpack('!I', data[1:])
        return data[0], size[0]

    def read_data(self):
        """ Read next packet from buffer.
            Refer to the "MediaHandler" doc for the packet description.
        """
        buff = self.buffer.read(HEADER_SIZE)
        if not buff:
            return None, None
        typ, size = self.process_header(buff)
        payload = self.buffer.read(size)
        if not payload:
            return None, None
        return typ, payload

    @classmethod
    def build_metadata(cls, type, content):
        data = {'type': type.name, 'content': content}
        return json.dumps(data).encode('utf-8')

    def send_data(self, type, content):
        # Deprecated. Use write_data directly
        self.write_data(type, content, as_metadata=True)

    def write_data(self, data_type, data, as_metadata=False):
        if as_metadata:
            data = self.build_metadata(data_type, data)
            data_type = DataContent.metadata

        header = struct.pack('!BI', data_type.value, len(data))
        self.request.sendall(header + data)

    def get_stream_name(self):
        return self.stream_name(self._id)

    @classmethod
    def stream_name(cls, id):
        return cls.provider_prefix + '_' + str(id)


"""
Test module for main.data.load
"""

import unittest
import os.path
import pandas as pd
from main.data import load

class TestLoad(unittest.TestCase):
    """
    Test class for main.data.load
    """

    def test_from_csv(self):
        """
        Provides the DJIA dataset to be loaded, provides the absolute path, based on the relative
        path that this file is contained within.
        :return:
        """
        curr_filepath = os.path.abspath(__file__)
        djia_filepath = os.path.join(
            curr_filepath,
            '../../../../../datasets/existing/dow_jones/Combined_News_DJIA'
            '.csv')
        abs_djia_filepath = os.path.abspath(djia_filepath)
        result = load.from_csv(abs_djia_filepath)
        self.assertEqual(isinstance(result, pd.DataFrame), True)

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


import os
import sys
import math
import glob
import numpy as npy
import fastran_tools
import matplotlib.pyplot as plt

from scipy.optimize import curve_fit
from matplotlib.backends.backend_pdf import PdfPages

colors = ['red','blue','green','orange','black','cyan','sienna','magenta','teal','olive','steelblue','deeppink','indigo','purple','maroon','lime']
colors.extend(['gold','lawngreen','sandybrown','cadetblue','deepskyblue'])
colors.extend(['#0000FF','#FF4040','#8A2BE2','#458B00','#E3CF57','#8EE5EE','#FF7F24','#FF1493','#97FFFF','#FFD700','#FF69B4','#27408B'])
colors.extend(['#FFF68F','#7A8B8B','#FFAEB9','#EE9572','#20B2AA','#B3EE3A','#FFBBFF','#8E8E38','#FF8247','#EE82EE','#FFFF00','#8B8B00'])

CEND    = '\033[0m'
CRED    = '\33[31m'
CBLUE   = '\33[34m'
CGREEN  = '\33[32m'
CYELLOW = '\33[33m'

eped_folders  = []
eped_folders += sorted(glob.glob("FNSF_EPED_scan_NEPED_IP_??p??"))

IP_ORDER   = []
NPED_ORDER = []
for ifolder in eped_folders:
    eped_files = sorted(glob.glob("%s/SUMMARY/e*" % ifolder))
    for ifile in eped_files:
        epeddata = fastran_tools.read_eped_outputs(ifile)
        IP_ORDER.append(epeddata['ip']['data'][-1])
        NPED_ORDER.append(epeddata['neped']['data'][-1])

IP_ORDER   = sorted(list(set(IP_ORDER)))
NPED_ORDER = sorted(list(set(NPED_ORDER)))

NIP   = len(IP_ORDER)
NNPED = len(NPED_ORDER)

IP2D   = npy.zeros((NIP,NNPED),dtype=float); IP2D[:]   = None
NPED2D = npy.zeros((NIP,NNPED),dtype=float); NPED2D[:] = None
PPED2D = npy.zeros((NIP,NNPED),dtype=float); PPED2D[:] = None
WPED2D = npy.zeros((NIP,NNPED),dtype=float); WPED2D[:] = None

reportpath = os.path.abspath(".")+"/fastran_report/"
if not os.path.isdir(reportpath):
   os.system('mkdir '+reportpath)

figurepath = os.path.abspath(".")+"/fastran_report/Figures/"
if not os.path.isdir(figurepath):
   os.system('mkdir '+figurepath)

epedfigs = PdfPages(figurepath+'eped_fit_plots.pdf')

individual_flag = False
collective_flag = True

for ifolder in eped_folders:
    eped_files = sorted(glob.glob("%s/SUMMARY/e*" % ifolder))
    IP1D = []; NPED1D = []; PPED1D = []; WPED1D = []
    for ifile in eped_files:
        epeddata = fastran_tools.read_eped_outputs(ifile)
       #crnt_index = IP_ORDER.index(epeddata['ip']['data'][-1])
        crnt_index = NPED_ORDER.index(epeddata['neped']['data'][-1])
        if epeddata['p_E1']['data'][-1] <= 0.0 or epeddata['wid_E1']['data'][-1] <= 0.0: continue
        if epeddata['neped']['data'][-1] < 10.5: continue
        IP2D[eped_folders.index(ifolder),  crnt_index] = epeddata['ip']['data'][-1]
        NPED2D[eped_folders.index(ifolder),crnt_index] = epeddata['neped']['data'][-1]
        PPED2D[eped_folders.index(ifolder),crnt_index] = epeddata['p_E1']['data'][-1]
        WPED2D[eped_folders.index(ifolder),crnt_index] = epeddata['wid_E1']['data'][-1]

eped_fit_model = lambda X, A, B, C: A * X[0]**B * X[1]**C
IP11D   = [x for x in IP2D.flatten()   if math.isnan(x) == False]
NPED11D = [x for x in NPED2D.flatten() if math.isnan(x) == False]
PPED11D = [x for x in PPED2D.flatten() if math.isnan(x) == False]
WPED11D = [x for x in WPED2D.flatten() if math.isnan(x) == False]
(PPED_A1, PPED_B1, PPED_C1), pcov = curve_fit(eped_fit_model, (NPED11D,IP11D), PPED11D)
(WPED_A1, WPED_B1, WPED_C1), pcov = curve_fit(eped_fit_model, (NPED11D,IP11D), WPED11D)

if collective_flag:
    fig = plt.figure("EPED Model",dpi=200)
    ax1 = fig.add_subplot(221)
    ax2 = fig.add_subplot(222)
    ax3 = fig.add_subplot(223)
    ax4 = fig.add_subplot(224)

[nrow,ncol] = npy.shape(IP2D)

irow = 0
for irow in range(nrow):
    IP1_TEST   = [x for x in IP2D[irow,:]               if math.isnan(x) == False]
    IP2_TEST   = [x for x in IP2D.transpose()[irow,:]   if math.isnan(x) == False]
    NPED1_TEST = [x for x in NPED2D[irow,:]             if math.isnan(x) == False]
    NPED2_TEST = [x for x in NPED2D.transpose()[irow,:] if math.isnan(x) == False]
    if IP1_TEST and IP2_TEST and NPED1_TEST and NPED2_TEST:
        if individual_flag:
            fig = plt.figure("EPED Model_%04d" % irow ,dpi=200)
            ax1 = fig.add_subplot(221)
            ax2 = fig.add_subplot(222)
            ax3 = fig.add_subplot(223)
            ax4 = fig.add_subplot(224)

        if all(IP2_TEST == IP2_TEST[0]):
            IP   = IP2D.transpose()[irow,:]
            NPED = NPED2D.transpose()[irow,:]
            PPED = PPED2D.transpose()[irow,:]
            WPED = WPED2D.transpose()[irow,:]

            PPED_Model = PPED_A1*NPED**PPED_B1*IP**PPED_C1
            PPED_exind = abs(PPED - PPED_Model) > 0.1
            ax2.plot(NPED,1.0e3*PPED,color=colors[irow],marker='o',linestyle="")
            ax2.plot(NPED,1.0e3*PPED_A1*NPED**PPED_B1*IP**PPED_C1,color=colors[irow])
            ax2.yaxis.tick_right()
            ax2.yaxis.set_label_position("right")
            ax2.set_ylabel("$P_{ped}$",fontsize=12)
            ax2.set_title("$W_{ped}$ = %3.2f$N_{eped}^{%3.2f}$$I_P^{%3.2f}$" % (WPED_A1,WPED_B1,WPED_C1),fontsize=14)

            WPED_Model = WPED_A1*NPED**WPED_B1*IP**WPED_C1
            WPED_exind = abs(WPED - WPED_Model) > 0.1
            ax4.plot(NPED,WPED,color=colors[irow],marker='o',linestyle="")
            ax4.plot(NPED,WPED_A1*NPED**WPED_B1*IP**WPED_C1,color=colors[irow])
            ax4.yaxis.tick_right()
            ax4.yaxis.set_label_position("right")
            ax4.set_ylabel("$W_{ped}$",fontsize=12)
            ax4.set_xlabel("$N_{PED}$",fontsize=12)

            IP   = IP2D[irow,:]
            NPED = NPED2D[irow,:]
            PPED = PPED2D[irow,:]
            WPED = WPED2D[irow,:]

            ax1.plot(IP,1.0e3*PPED,color=colors[irow],marker='o',linestyle="")
            ax1.plot(IP,1.0e3*PPED_A1*NPED**PPED_B1*IP**PPED_C1,color=colors[irow])
            ax1.set_ylabel("$P_{ped}$",fontsize=12)
            ax1.set_title("$P_{ped}$ = %3.2f$N_{eped}^{%3.2f}$$I_P^{%3.2f}$" % (1.0e3*PPED_A1,PPED_B1,PPED_C1),fontsize=14)

            ax3.plot(IP,WPED,color=colors[irow],marker='o',linestyle="")
            ax3.plot(IP,WPED_A1*NPED**WPED_B1*IP**WPED_C1,color=colors[irow])
            ax3.set_ylabel("$W_{ped}$",fontsize=12)
            ax3.set_xlabel("$I_{P}$",fontsize=12)

        elif all(NPED2_TEST == NPED2_TEST[0]):
            IP   = IP2D[irow,:]
            NPED = NPED2D[irow,:]
            PPED = PPED2D[irow,:]
            WPED = WPED2D[irow,:]

            PPED_Model = PPED_A1*NPED**PPED_B1*IP**PPED_C1
            PPED_exind = abs(PPED - PPED_Model) < 0.008
            ax2.plot(NPED[PPED_exind],1.0e3*PPED[PPED_exind],color=colors[irow],marker='o',linestyle="")
            ax2.plot(NPED,1.0e3*PPED_A1*NPED**PPED_B1*IP**PPED_C1,color=colors[irow])
            ax2.yaxis.tick_right()
            ax2.yaxis.set_label_position("right")
            ax2.set_ylabel("$P_{ped}$ (kPa)",fontsize=12)
            ax2.set_title("$W_{ped}$ = %3.2f$N_{eped}^{%3.2f}$$I_P^{%3.2f}$" % (WPED_A1,WPED_B1,WPED_C1),fontsize=14)

            WPED_Model = WPED_A1*NPED**WPED_B1*IP**WPED_C1
            WPED_exind = abs(WPED - WPED_Model) < 0.0010
            ax4.plot(NPED[WPED_exind],WPED[WPED_exind],color=colors[irow],marker='o',linestyle="")
            ax4.plot(NPED,WPED_A1*NPED**WPED_B1*IP**WPED_C1,color=colors[irow])
            ax4.yaxis.tick_right()
            ax4.yaxis.set_label_position("right")
            ax4.set_ylabel("$W_{ped}$",fontsize=12)
            ax4.set_xlabel("$N_{PED}$",fontsize=12)

            IP   = IP2D.transpose()[irow,:]
            NPED = NPED2D.transpose()[irow,:]
            PPED = PPED2D.transpose()[irow,:]
            WPED = WPED2D.transpose()[irow,:]

            PPED_Model = PPED_A1*NPED**PPED_B1*IP**PPED_C1
            PPED_exind = abs(PPED - PPED_Model) < 0.008
            ax1.plot(IP[PPED_exind],1.0e3*PPED[PPED_exind],color=colors[irow],marker='o',linestyle="")
            ax1.plot(IP,1.0e3*PPED_A1*NPED**PPED_B1*IP**PPED_C1,color=colors[irow])
            ax1.set_ylabel("$P_{ped}$ (kPa)",fontsize=12)
            ax1.set_title("$P_{ped}$ = %3.2f$N_{eped}^{%3.2f}$$I_P^{%3.2f}$" % (1.0e3*PPED_A1,PPED_B1,PPED_C1),fontsize=14)

            WPED_Model = WPED_A1*NPED**WPED_B1*IP**WPED_C1
            WPED_exind = abs(WPED - WPED_Model) < 0.0025
            ax3.plot(IP[WPED_exind],WPED[WPED_exind],color=colors[irow],marker='o',linestyle="")
            ax3.plot(IP,WPED_A1*NPED**WPED_B1*IP**WPED_C1,color=colors[irow])
            ax3.set_ylabel("$W_{ped}$",fontsize=12)
            ax3.set_xlabel("$I_{P}$ (MA)",fontsize=12)

        if individual_flag:
            fig.suptitle("EPED Fitting Model",fontsize=16)
            fig.tight_layout(rect=[0, 0.03, 1, 0.95])
            fig.subplots_adjust(wspace=0,hspace=0)

            epedfigs.savefig(fig)
            plt.close(fig)

if collective_flag:
    fig.suptitle("EPED Fitting Model",fontsize=16)
    fig.tight_layout(rect=[0, 0.03, 1, 0.95])
    fig.subplots_adjust(wspace=0,hspace=0)

    epedfigs.savefig(fig)
    plt.close(fig)

epedfigs.close()


from turtle import Turtle, Screen
INITIAL_SEGS = 3
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0

class Snake:

    def __init__(self):
        self.snake = []
        self.create_snake(INITIAL_SEGS)
        self.head = self.snake[0]

    # Create a Snake body
    def create_snake(self, num_of_segments=1):
        for new_segment in range(len(self.snake), len(self.snake) + num_of_segments, 1):
            new_segment = Turtle("square")
            new_segment.color("white")
            new_segment.penup()
            self.snake.append(new_segment)

    def reset(self):
        for seg in self.snake:
            seg.goto(1000, 1000)
        self.snake.clear()
        self.create_snake(INITIAL_SEGS)
        self.head = self.snake[0]

    def move(self):
        for seg in range(len(self.snake) - 1, 0, -1):
            new_xcor = self.snake[seg - 1].xcor()
            new_ycor = self.snake[seg - 1].ycor()
            self.snake[seg].setpos(new_xcor, new_ycor)
        self.head.forward(MOVE_DISTANCE)

    def moveUp(self):
        if self.head.heading() != DOWN:
            self.head.setheading(UP)

    def moveDown(self):
        if self.head.heading() != UP:
            self.head.setheading(270)

    def moveLeft(self):
        if self.head.heading() != RIGHT:
            self.head.setheading(180)

    def moveRight(self):
        if self.head.heading() != LEFT:
            self.head.setheading(0)


"""Fomos contratados por um grande bancopara desenvolver o seu novo sistema. Essebanco deseja modernizar suas operações epara isso escolheu a linguagem Python.Para a primeira versão do sistema devemos implementar apenas 3 operações: depósito,saque e extrato."""

menu = """

[1] Depositar
[2] Sacar
[3] Extrato
[4] Sair

=> """

saldo = 0
limite = 500
extrato = ""
numero_saques = 0
LIMITE_SAQUES = 3

while True:

    opcao = int(input(menu))

    if opcao == 1:
        valor = float(input("Digite o valor que deseja depositar: R$"))
        if valor > 0:
            saldo += valor
            extrato += f"Valor depositado: R${valor:.2f}\n"
            print(f"Saldo atual: R${saldo:.2f}")
        else:
            print("Valor inserido invalido!")

    elif opcao == 2:
        valor = float(input("Digite o valor que deseja sacar: R$"))

        if numero_saques >= LIMITE_SAQUES:
            print("Voce excedeu o numero de saque diario")
        elif valor > 500 or valor < 0:
            print("Valor invalido. O Valor de saque deve ser entre R$1 até R$500")
        elif valor > saldo:
            print("O valor maior que o saldo atual")
        else:
            numero_saques += 1
            saldo -= valor
            extrato += f"Valor retidado: R${valor:.2f}\n"
            print(f"Valor sacado com sucesso, o seu saldo atual eh: R${saldo:.2f}")

    elif opcao == 3:
        print("#"*50)
        print(f"EXTRATO".center(50)) #a função .center(), centraliza ums string ou variavel em um print.
        print("#"*50)
        print("Sem extrato" if not extrato else extrato) #verificação se o extrato contém algum processo como deposito ou saque
        print(f"Saldo atual: R${saldo:.2f}".center(50))
        print("#"*50)

    elif opcao == 4:
        break

    else:
        print("Operação inválida, por favor selecione novamente a operação desejada.")


#Problem 2 (Leap Years - **)

year = int(input("please input a year and I will check if its a leap year\n"))

check1 = (year % 100)
check2 = (year % 400)
check3 = (year % 4)

if check1 == 0:
    if check2 == 0:
        print("leap-year")
    else:
        print("not a leap-year")
else:
    if check3 == 0:
        print("leap-year")
    else:
        print("not a leap year")


import numpy as np
import pickle
from random import randrange
import networkx as nx

class Board:

    def get_page_rank(self):
        G = nx.from_numpy_matrix(self.board_2d)
        pr = nx.pagerank(G,0.001)
        return np.fromiter(pr.values(), dtype=float)

    def init_player_pos(self,num_players):

        init_stops = [13,26,29,34,50,53,91,94,103,112,117,132,138,141,155,174,197,198]
        self.player_pos = [0]*num_players
        for player_index in range(len(self.player_pos)):
            self.player_pos[player_index] = init_stops[randrange(len(init_stops))] -1
            init_stops.remove(self.player_pos[player_index] + 1)
            print("player%s initialized at position:  %s" %(player_index, self.player_pos[player_index] + 1))

    def set_player_pos(self,player,pos):
        print("player %s changed from pos %s \t  to %s " %(player, self.player_pos[player] + 1, pos + 1) )
        self.player_pos[player] = int(pos)

    def __init__(self, num_players):
        self.board = pickle.load(open("rides.pkl","rb"))
        self.N = self.board.shape[1]
        self.board_2d = self.board.sum(axis=0) > 0
        self.pagerank = self.get_page_rank()
        self.init_player_pos(num_players)


from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'ask.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^$',
        'qa.views.base_pagin'),
    url(r'^popular\/$',
        'qa.views.base_popular'),
    url(r'^question\/(?P<slug>\d+)\/$',
        'qa.views.post_details'),
    url(r'^ask\/$',
        'qa.views.add_action'),
    url(r'^answer\/$',
        'qa.views.add_answer'),
)


## Disregard the inefficient code below, it works so that counts for something.

C = int(input())
N = int(input())

graph = {}
# get the input and build the graph
for i in range(0, N):
	(a, b) = input().split(" ")
	(a, b) = (int(a), int(b))

	if (a in graph):
		graph[a].append(b)
	else:
		graph[a] = [b]
	if (b not in graph):
		graph[b] = []

## now we have the input,
# pull out dfs and look for that cycle!

def dfs_visit(graph, currentNode, visited, courses_taken, instack):
	visited.append(currentNode)
	instack.append(currentNode)
	for arg in graph[currentNode]:
		if (arg not in visited):
			dfs_visit(graph, arg, visited, courses_taken, instack)
		if (arg in instack):
			# cycle detected!
			return
	instack.remove(currentNode)
	if (currentNode not in courses_taken):
		courses_taken.append(currentNode)
	if (len(courses_taken) >= C):
		print("Good")
		exit(0)

def dfs(graph):

	courses_taken = []

	for node in graph:
		visited = []
		instack = []
		dfs_visit(graph, node, visited, courses_taken, instack)

	print("Bad")

dfs(graph)


import os
os.environ["KERAS_BACKEND"] = 'tensorflow'

import tensorflow as tf
from models.dual_encoder_dense.model_dual_encoder_dense import dot_semantic_nn
from dataset.ubuntu_dialogue_corpus import UDCDataset
from test_tube.log import Experiment
from tensorflow.contrib.keras.api.keras.utils import Progbar
import numpy as np

def train_main(hparams):
    """
    Main training routine for the dot semantic network bot
    :return:
    """

    # -----------------------
    # INIT EXPERIMENT
    # ----------------------
    exp = Experiment(name=hparams.exp_name,
                     debug=hparams.debug,
                     description=hparams.exp_desc,
                     autosave=False,
                     save_dir=hparams.test_tube_dir)

    exp.add_meta_tags(vars(hparams))

    # -----------------------
    # LOAD DATASET
    # ----------------------
    udc_dataset = UDCDataset(vocab_path=hparams.vocab_path,
                             train_path=hparams.dataset_train_path,
                             test_path=hparams.dataset_test_path,
                             val_path=hparams.dataset_val_path,
                             max_seq_len=hparams.max_seq_len)

    # -----------------------
    # INIT TF VARS
    # ----------------------
    # context holds chat history
    # utterance holds our responses
    # labels holds the ground truth labels
    context_ph = tf.placeholder(dtype=tf.int32, shape=[hparams.batch_size, None], name='context_seq_in')
    utterance_ph = tf.placeholder(dtype=tf.int32, shape=[hparams.batch_size, None], name='utterance_seq_in')

    # ----------------------
    # EMBEDDING LAYER
    # ----------------------
    # you can preload your own or learn in the network
    # in this case we'll just learn it in the network
    embedding_layer = tf.Variable(tf.random_uniform([udc_dataset.vocab_size, hparams.embedding_dim], -1.0, 1.0), name='embedding')

    # ----------------------
    # RESOLVE EMBEDDINGS
    # ----------------------
    # look up embeddings
    context_embedding = tf.nn.embedding_lookup(embedding_layer, context_ph)
    utterance_embedding = tf.nn.embedding_lookup(embedding_layer, utterance_ph)

    # avg all embeddings (sum works better?)
    # this generates 1 vector per training example
    context_embedding_summed = tf.reduce_mean(context_embedding, axis=1)
    utterance_embedding_summed = tf.reduce_mean(utterance_embedding, axis=1)

    # ----------------------
    # OPTIMIZATION PROBLEM
    # ----------------------
    model, _, _, pred_opt = dot_semantic_nn(context=context_embedding_summed,
                                            utterance=utterance_embedding_summed,
                                            tng_mode=hparams.train_mode)

    # allow optiizer to be changed through hyper params
    optimizer = get_optimizer(hparams=hparams, minimize=model)

    # ----------------------
    # TF ADMIN (VAR INIT, SESS)
    # ----------------------
    sess = tf.Session()
    init_vars = tf.global_variables_initializer()
    sess.run(init_vars)

    # Add ops to save and restore all the variables.
    saver = tf.train.Saver()

    # ----------------------
    # TRAINING ROUTINE
    # ----------------------
    # admin vars
    nb_batches_served = 0
    eval_every_n_batches = hparams.eval_every_n_batches

    train_err = 1000
    precission_at_1 = 0
    precission_at_2 = 0

    # iter for the needed epochs
    print('\n\n', '-'*100,'\n  {} TRAINING\n'.format(hparams.exp_name.upper()), '-'*100, '\n\n')
    for epoch in range(hparams.nb_epochs):
        print('training epoch:', epoch + 1)
        progbar = Progbar(target=udc_dataset.nb_tng, width=50)
        train_gen = udc_dataset.train_generator(batch_size=hparams.batch_size, max_epochs=1)

        # mini batches
        for batch_context, batch_utterance in train_gen:

            feed_dict = {
                context_ph: batch_context,
                utterance_ph: batch_utterance
            }

            # OPT: run one step of optimization
            optimizer.run(session=sess, feed_dict=feed_dict)
            # update loss metrics
            if nb_batches_served % eval_every_n_batches == 0:

                # calculate test error
                train_err = model.eval(session=sess, feed_dict=feed_dict)
                precission_at_1 = test_precision_at_k(pred_opt, feed_dict, k=1, sess=sess)
                precission_at_2 = test_precision_at_k(pred_opt, feed_dict, k=2, sess=sess)

                # update prog bar
                exp.add_metric_row({'tng loss': train_err, 'P@1': precission_at_1, 'P@2': precission_at_2})

            nb_batches_served += 1

            progbar.add(n=len(batch_context), values=[('train_err', train_err),
                                                      ('P@1', precission_at_1),
                                                      ('P@2', precission_at_2)])

        # ----------------------
        # END OF EPOCH PROCESSING
        # ----------------------
        # calculate the val loss
        print('\nepoch complete...\n')
        check_val_stats(model, pred_opt, udc_dataset, hparams, context_ph, utterance_ph, exp, sess, epoch)

        # save model
        save_model(saver=saver, hparams=hparams, sess=sess, epoch=epoch)

        # save exp data
        exp.save()

def evaluate_recall(y, y_test, k=1):
    num_examples = float(len(y))
    num_correct = 0
    for predictions, label in zip(y, y_test):
        if label in predictions[:k]:
            num_correct += 1
    return num_correct/num_examples

def test_precision_at_k(pred_opt, feed_dict, k, sess):
    sims = pred_opt.eval(session=sess, feed_dict=feed_dict)
    labels = range(0, len(sims))
    for i, pred_vector in enumerate(sims):
        sims[i] = [i[0] for i in sorted(enumerate(pred_vector), key=lambda x: x[1])][::-1]

    recall_score = evaluate_recall(sims, labels, k)
    return recall_score

def get_optimizer(hparams, minimize):
    opt = None
    name = hparams.optimizer_name
    if name == 'sgd':
        opt = tf.train.GradientDescentOptimizer(learning_rate=hparams.lr_1).minimize(minimize)
    if name == 'adam':
        opt = tf.train.AdamOptimizer(learning_rate=hparams.lr_1).minimize(minimize)
    if name == 'rmsprop':
        opt = tf.train.RMSPropOptimizer(learning_rate=hparams.lr_1).minimize(minimize)

    return opt

def save_model(saver, hparams, sess, epoch):
    print('saving model...')

    # create path if not around
    model_save_path = hparams.model_save_dir + '/{}/epoch_{}'.format(hparams.exp_name, epoch)
    if not os.path.isdir(model_save_path):
        os.makedirs(model_save_path)

    model_name = '{}/model.cpkt'.format(model_save_path)

    save_path = saver.save(sess, model_name)
    print('model saved at', save_path, '\n\n')

def check_val_stats(model, pred_opt, data, hparams, X_ph, Y_ph, exp, sess, epoch):
    """
    Runs through validation data to check the overall mean loss
    :param model:
    :param data:
    :param hparams:
    :param X_ph:
    :param Y_ph:
    :param exp:
    :param sess:
    :param epoch:
    :return:
    """
    print('checking val loss...')
    max_val_batches = 100
    val_gen = data.val_generator(batch_size=hparams.batch_size, max_epochs=1)

    overall_err = []
    overall_p_1 = []
    overall_p_2 = []
    progbar = Progbar(target=max_val_batches, width=50)
    for batch_nb in range(max_val_batches):
        batch_X, batch_Y = next(val_gen)
        if len(batch_X) == 0:
            continue

        # aggregate data
        feed_dict = {
            X_ph: batch_X,
            Y_ph: batch_Y
        }

        # calculate metrics
        val_err = model.eval(session=sess, feed_dict=feed_dict)
        precission_at_1 = test_precision_at_k(pred_opt, feed_dict, k=1, sess=sess)
        precission_at_2 = test_precision_at_k(pred_opt, feed_dict, k=2, sess=sess)

        # track metrics for means
        overall_err.append(val_err)
        overall_p_1.append(precission_at_1)
        overall_p_2.append(precission_at_2)

        # update exp and progbar
        exp.add_metric_row({'val loss': val_err, 'val P@1': precission_at_1, 'val P@2': precission_at_2})
        progbar.add(n=1)

    # log and save val metrics
    overall_val_mean_err = np.asarray(overall_err).mean()
    overall_p_1_mean = np.asarray(overall_p_1).mean()
    overall_p_2_mean = np.asarray(overall_p_2).mean()
    exp.add_metric_row({'epoch_mean_err': overall_val_mean_err,
                        'epoch_P@1_mean': overall_p_1_mean,
                        'epoch_P@2_mean': overall_p_2_mean,
                        'epoch': epoch + 1})

    print('\nval loss: ', overall_val_mean_err,
          'epoch_P@1_mean: ', overall_p_1_mean,
          'epoch_P@2_mean: ', overall_p_2_mean)
    print('-'*100)


class NamedExplodingObject(object):
    """An object which has no attributes but produces a more informative
    error message when accessed.

    Parameters
    ----------
    name : str
        The name of the object. This will appear in the error messages.

    Notes
    -----
    One common use for this object is so ensure that an attribute always exists
    even if sometimes it should not be used.
    """
    def __init__(self, name, extra_message=None):
        self._name = name
        self._extra_message = extra_message

    def __getattr__(self, attr):
        extra_message = self._extra_message
        raise AttributeError(
            'attempted to access attribute %r of ExplodingObject %r%s' % (
                attr,
                self._name,
            ),
            ' ' + extra_message if extra_message is not None else '',
        )

    def __repr__(self):
        return '%s(%r%s)' % (
            type(self).__name__,
            self._name,
            # show that there is an extra message but truncate it to be
            # more readable when debugging
            ', extra_message=...' if self._extra_message is not None else '',
        )


import conllu
from IPython import embed
import numpy as np
import networkx as nx
import random

def mean_d_dist(tree):
    return np.mean([abs(wi-hi) for wi, hi in enumerate(tree, start=1) if hi != 0])

def mean_h_dist(tree):
    tree_1 = nx.DiGraph()
    tree_1.add_edges_from([(x,i) for i,x in enumerate(tree, start=1)])
    return np.mean([len(nx.shortest_path(tree_1, 0, n)) for n in tree_1 if n != 0])

def read_file(file):
    language = '<' + file.split('/')[-1].split('_')[0] + '>'
    labels = set([])
    dataset = []
    with open(file) as f:
        parsed_file = conllu.parse_incr(f)
        for i, sentence in enumerate(parsed_file):
            ws, hs, rs, ps = list(zip(*[(s['form'], s['head'], s['deprel'], s['upostag']) for
                                        s in sentence if type(s['id']) is int]))
            # ignore sentences with <= 3 words
            if len(ws) <= 3:
                continue

            for l in rs:
                labels.add(l)

            dataset.append({'forms': list(map(lambda x: x.lower(), ws)),
                            'heads': list(hs),
                            'deprels': list(rs),
                            'upos': list(ps),
                            'len': len(ws),
                            'mhd': mean_d_dist(list(hs)),
                            'mdd': mean_h_dist(list(hs)),
                            'random': random.random(),
                            'language': language})
    return dataset, labels


class OSMArea:
    def __init__(self, name=None, idd=None, level=1, members=None):
        self.level = level
        self.id = idd
        self.members = members
        if members is None:
            self.members = list()
        self.name = name

    def __repr__(self):
        return 'OSMArea {} {}'.format(self.name, self.id)


"""
Flavor fixtures.

@author: schipiga@mirantis.com
"""

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

import pytest

from mcp_tests.nova.steps import FlavorSteps
from mcp_tests.utils import generate_ids

__all__ = [
    'create_flavor',
    'flavor',
    'flavor_steps'
]

@pytest.fixture
def flavor_steps(nova_client):
    """Fixture to get flavor steps."""
    return FlavorSteps(nova_client.flavors)

@pytest.yield_fixture
def create_flavor(flavor_steps):
    """Fixture to create flavor with options.

    Can be called several times during test.
    """
    flavors = []

    def _create_flavor(flavor_name):
        flavor = flavor_steps.create_flavor(flavor_name)
        flavors.append(flavor)
        return flavor

    yield _create_flavor

    for flavor in flavors:
        flavor_steps.delete_flavor(flavor)

@pytest.fixture
def flavor(create_flavor):
    """Fixture to create flavor with default options before test."""
    flavor_name = next(generate_ids('flavor'))
    return create_flavor(flavor_name)