# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\complex\mother_plant_battle.py
# Compiled at: 2020-09-17 02:52:35
# Size of source mod 2**32: 26813 bytes
import itertools, random
from buffs.tunable import TunableBuffReference
from date_and_time import create_time_span
from distributor.rollback import ProtocolBufferRollback
from distributor.shared_messages import build_icon_info_msg, IconInfoData
from event_testing.test_events import TestEvent
from interactions.aop import AffordanceObjectPair
from interactions.context import InteractionContext, QueueInsertStrategy, InteractionSource
from interactions.priority import Priority
from objects.components.state import TunableStateValueReference
from sims4.localization import TunableLocalizedString
from sims4.tuning.instances import lock_instance_tunables
from sims4.tuning.tunable import TunableReference, TunableSimMinute, TunableResourceKey, TunableList
from sims4.tuning.tunable_base import GroupNames
from situations.base_situation import SituationDisplayPriority, _RequestUserData
from situations.bouncer.bouncer_request import SelectableSimRequestFactory
from situations.bouncer.bouncer_types import BouncerRequestPriority
from situations.complex.mother_plant_battle_ops import MotherplantBattleStates
from situations.situation_complex import SituationComplexCommon, SituationState, CommonSituationState, SituationStateData, TunableInteractionOfInterest
from situations.situation_meter import StatBasedSituationMeterData
from situations.situation_types import SituationDisplayType, SituationUserFacingType
import alarms, interactions, services, sims4.resources
logger = sims4.log.Logger('Situations', default_owner='jjacobson')

class PrepareForBattleSituationState(SituationState):

    def _on_set_sim_role_state(self, sim, *args, **kwargs):
        (super()._on_set_sim_role_state)(sim, *args, **kwargs)
        if self.owner.num_of_sims >= len(self.owner._guest_list):
            self.owner._change_state(self.owner.base_battle_situation_state())

    @property
    def zombie_attack_valid(self):
        return False

    def _get_role_state_overrides(self, sim, job_type, role_state_type, role_affordance_target):
        motherplant = self.owner._get_motherplant()
        return (role_state_type, motherplant)

class BattleThePlantSituationState(CommonSituationState):

    @property
    def zombie_attack_valid(self):
        return True

class AttackBattleThePlantSituationState(CommonSituationState):

    @property
    def zombie_attack_valid(self):
        return True

    def timer_expired(self):
        self.owner._change_state(self.owner.base_battle_situation_state())

class InspireBattleThePlantSituationState(CommonSituationState):

    @property
    def zombie_attack_valid(self):
        return True

    def timer_expired(self):
        self.owner._change_state(self.owner.base_battle_situation_state())

class RallyBattleThePlantSituationState(CommonSituationState):

    @property
    def zombie_attack_valid(self):
        return True

    def timer_expired(self):
        self.owner._change_state(self.owner.base_battle_situation_state())

class WarblingWarcryBattleThePlantSituationState(CommonSituationState):

    @property
    def zombie_attack_valid(self):
        return False

    def timer_expired(self):
        self.owner._change_state(self.owner.base_battle_situation_state())

class MotherPlantBattleSituation(SituationComplexCommon):
    MOTHER_PLANT_METER_ID = 1
    PLAYER_HEALTH_METER_ID = 2
    INSTANCE_TUNABLES = {'player_job':TunableReference(description='\n            Job for the main player sim that fights the plant.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'player_sim_role_state':TunableReference(description='\n            Role state for the main player sim Role.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'other_player_jobs':TunableReference(description='\n            Job for the other player Sims that are not the main Sim and are not\n            participating as helpers.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'other_player_sims_role_state':TunableReference(description='\n            Role state for the other player Sims.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'helper_1_job':TunableReference(description='\n            Job for one of the helper Sims for the fight.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'helper_2_job':TunableReference(description='\n            Job for one of the helper Sims for the fight.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'helper_3_job':TunableReference(description='\n            Job for one of the helper Sims for the fight.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'helper_sim_prepare_role_state_1':TunableReference(description='\n            Role state for helper Sim 1 when preparing for battle.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'helper_sim_prepare_role_state_2':TunableReference(description='\n            Role state for helper Sim 2 when preparing for battle.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'helper_sim_prepare_role_state_3':TunableReference(description='\n            Role state for helper Sim 3 when preparing for battle.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'zombie_job':TunableReference(description='\n            Job for the Zombies for the fight.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.SITUATION_JOB)),
     'zombie_prepare_role_state':TunableReference(description='\n            Role state for the zombie Sims when preparing for battle.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.ROLE_STATE)),
     'zombie_fight_interaction':TunableReference(description='\n            Interaction pushed on zombies to get them to fight a Sim.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.INTERACTION)),
     'zombie_fight_interaction_timer':TunableSimMinute(description='\n            Timer for the amount of time between zombie attacks.\n            ',
       minimum=1,
       default=30),
     'player_health_statistic':TunableReference(description="\n            The statistic that we will use in order to determine the Sim's\n            health for the motherplant.\n            ",
       manager=services.get_instance_manager(sims4.resources.Types.STATISTIC)),
     'motherplant_health_statisic':TunableReference(description="\n            The statistic that we will use in order to determine the Sim's\n            health for the motherplant.\n            ",
       manager=services.get_instance_manager(sims4.resources.Types.STATISTIC)),
     'victory_interaction_of_interest':TunableInteractionOfInterest(description='\n            The interaction of interest that we are looking for to determine\n            victory.\n            '),
     'retreat_interaction_of_interest':TunableInteractionOfInterest(description='\n            The interaction of interest that we are looking for to determine\n            retreat.\n            '),
     'loss_interaction_mixer':TunableReference(description='\n            The affordance that will be pushed on the primary Sims if they\n            lose.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.INTERACTION)),
     'fight_affordance':TunableReference(description='\n            The primary fight interaction that we will use to run the defeat\n            mixer the player Sim.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.INTERACTION)),
     'helper_victory_affordance':TunableReference(description='\n            The affordance that will be pushed on the helper Sims if they\n            achieve victory.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.INTERACTION)),
     'helper_lose_affordance':TunableReference(description='\n            The affordance that will be pushed on the helper Sims if they\n            lose.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.INTERACTION)),
     'mother_plant_definition':TunableReference(description='\n            The actual mother plant itself.\n            ',
       manager=services.definition_manager()),
     'base_battle_situation_state':BattleThePlantSituationState.TunableFactory(locked_args={'allow_join_situation':True,
      'time_out':None},
       tuning_group=GroupNames.STATE),
     'attack_battle_situation_state':AttackBattleThePlantSituationState.TunableFactory(locked_args={'allow_join_situation': True},
       tuning_group=GroupNames.STATE),
     'inspire_battle_situation_state':InspireBattleThePlantSituationState.TunableFactory(locked_args={'allow_join_situation': True},
       tuning_group=GroupNames.STATE),
     'rally_battle_sitaution_state':RallyBattleThePlantSituationState.TunableFactory(locked_args={'allow_join_situation': True},
       tuning_group=GroupNames.STATE),
     'warbling_warcry_battle_situation_state':WarblingWarcryBattleThePlantSituationState.TunableFactory(locked_args={'allow_join_situation': True},
       tuning_group=GroupNames.STATE),
     'save_lock_tooltip':TunableLocalizedString(description='\n            The tooltip/message to show when the player tries to save the game\n            while this situation is running. Save is locked when situation starts.\n            ',
       tuning_group=GroupNames.UI),
     'mother_plant_meter_settings':StatBasedSituationMeterData.TunableFactory(description='\n            The meter used to track the health of the mother plant.\n            ',
       tuning_group=GroupNames.SITUATION,
       locked_args={'_meter_id': MOTHER_PLANT_METER_ID}),
     'player_health_meter_settings':StatBasedSituationMeterData.TunableFactory(description='\n            The meter used to track the health of the player team.\n            ',
       tuning_group=GroupNames.SITUATION,
       locked_args={'_meter_id': PLAYER_HEALTH_METER_ID}),
     'mother_plant_icon':TunableResourceKey(description='\n            Icon to be displayed in the situation UI beside the mother plant\n            health bar.\n            ',
       resource_types=sims4.resources.CompoundTypes.IMAGE,
       default=None,
       allow_none=True,
       tuning_group=GroupNames.SITUATION),
     'states_to_set_on_start':TunableList(description='\n            A list of states to set on the motherplant on start.\n            ',
       tunable=TunableStateValueReference(description='\n                The state to set.\n                ')),
     'states_to_set_on_end':TunableList(description='\n            A list of states to set on the motherplant on end.\n            ',
       tunable=TunableStateValueReference(description='\n                The state to set.\n                ')),
     'victory_reward':TunableReference(description='\n            The Reward received when the Sim wins the situation.\n            ',
       manager=services.get_instance_manager(sims4.resources.Types.REWARD)),
     'victory_audio_sting':TunableResourceKey(description='\n            The sound to play when the Sim wins the battle.\n            ',
       resource_types=(
      sims4.resources.Types.PROPX,),
       default=None,
       tuning_group=GroupNames.AUDIO),
     'defeat_audio_sting':TunableResourceKey(description='\n            The sound to play when the Sim loses the battle.\n            ',
       resource_types=(
      sims4.resources.Types.PROPX,),
       default=None,
       tuning_group=GroupNames.AUDIO),
     'possessed_buff':TunableBuffReference(description='\n            Possessed Buff for zombie Sims. \n            ')}

    @property
    def user_facing_type(self):
        return SituationUserFacingType.MOTHER_PLANT_EVENT

    @property
    def situation_display_type(self):
        return SituationDisplayType.VET

    @property
    def situation_display_priority(self):
        return SituationDisplayPriority.HIGH

    @classmethod
    def _states(cls):
        return (SituationStateData(1, PrepareForBattleSituationState),
         SituationStateData.from_auto_factory(2, cls.base_battle_situation_state),
         SituationStateData.from_auto_factory(3, cls.attack_battle_situation_state),
         SituationStateData.from_auto_factory(4, cls.inspire_battle_situation_state),
         SituationStateData.from_auto_factory(5, cls.rally_battle_sitaution_state),
         SituationStateData.from_auto_factory(6, cls.warbling_warcry_battle_situation_state))

    @classmethod
    def default_job(cls):
        pass

    @classmethod
    def _get_tuned_job_and_default_role_state_tuples(cls):
        return ((cls.player_job, cls.player_sim_role_state),
         (
          cls.other_player_jobs, cls.other_player_sims_role_state),
         (
          cls.helper_1_job, cls.helper_sim_prepare_role_state_1),
         (
          cls.helper_2_job, cls.helper_sim_prepare_role_state_2),
         (
          cls.helper_3_job, cls.helper_sim_prepare_role_state_3),
         (
          cls.zombie_job, cls.zombie_prepare_role_state))

    def __init__(self, *args, **kwargs):
        (super().__init__)(*args, **kwargs)
        self._zombie_attack_alarm_handle = None
        self._registered_test_events = set()
        self._player_health_tracking_situation_goal = None
        self._statistic_watcher_handle = None
        self._victory = False

    @property
    def end_audio_sting(self):
        if self._victory:
            return self.victory_audio_sting
        return self.defeat_audio_sting

    def _get_reward(self):
        if self._victory:
            return self.victory_reward

    def _get_motherplant(self):
        return next(iter(services.object_manager().get_objects_of_type_gen(self.mother_plant_definition)))

    def _push_loss_on_player(self):
        motherplant = self._get_motherplant()
        for sim, situation_sim in self._situation_sims.items():
            if situation_sim.current_job_type is self.player_job:
                parent_si = sim.si_state.get_si_by_affordance(self.fight_affordance)
                if parent_si is not None:
                    interaction_context = InteractionContext(sim, InteractionSource.PIE_MENU, Priority.Critical)
                    aop = AffordanceObjectPair(self.loss_interaction_mixer, motherplant, self.fight_affordance, parent_si)
                    aop.test_and_execute(interaction_context) or logger.error('Attempting to push Motherplant Battle Ending Interaction, but failed.')

        self._push_interaction_on_all_helpers(self.helper_lose_affordance)

    def on_goal_completed(self, goal):
        super().on_goal_completed(goal)
        self._push_loss_on_player()
        self._self_destruct()

    def _on_set_sim_job(self, sim, job_type):
        super()._on_set_sim_job(sim, job_type)
        if job_type is self.zombie_job:
            sim.add_buff_from_op((self.possessed_buff.buff_type), buff_reason=(self.possessed_buff.buff_reason))

    def _on_statistic_updated(self, stat_type, old_value, new_value):
        if stat_type is self.player_health_statistic:
            self._player_health_tracking_situation_goal.set_count(new_value)
            self._player_health_meter.send_update_if_dirty()
        else:
            if stat_type is self.motherplant_health_statisic:
                self._mother_plant_meter.send_update_if_dirty()

    def _zombie_attack(self, _):
        if not self._cur_state.zombie_attack_valid:
            return
        zombies = []
        for sim, situation_sim in self._situation_sims.items():
            if situation_sim.current_job_type is self.zombie_job:
                zombies.append(sim)

        zombie_to_attack = random.choice(zombies)
        context = InteractionContext(sim, (InteractionContext.SOURCE_SCRIPT),
          (interactions.priority.Priority.High),
          insert_strategy=(QueueInsertStrategy.NEXT),
          bucket=(interactions.context.InteractionBucketType.DEFAULT))
        zombie_to_attack.push_super_affordance(self.zombie_fight_interaction, None, context)

    def _push_interaction_on_all_helpers(self, interaction_to_push):
        for sim, situation_sim in self._situation_sims.items():
            if situation_sim.current_job_type is self.helper_1_job or situation_sim.current_job_type is self.helper_2_job or situation_sim.current_job_type is self.helper_3_job:
                context = InteractionContext(sim, (InteractionContext.SOURCE_SCRIPT),
                  (interactions.priority.Priority.High),
                  insert_strategy=(QueueInsertStrategy.NEXT),
                  bucket=(interactions.context.InteractionBucketType.DEFAULT))
                sim.push_super_affordance(interaction_to_push, None, context)

    def handle_event(self, sim_info, event, resolver):
        super().handle_event(sim_info, event, resolver)
        if event != TestEvent.InteractionComplete:
            return
        elif resolver(self.victory_interaction_of_interest):
            self._push_interaction_on_all_helpers(self.helper_victory_affordance)
            self._victory = True
            self._self_destruct()
        else:
            if resolver(self.retreat_interaction_of_interest):
                self._push_loss_on_player()
                self._self_destruct()

    def start_situation(self):
        services.get_persistence_service().lock_save(self)
        super().start_situation()
        self._change_state(PrepareForBattleSituationState())
        motherplant = self._get_motherplant()
        motherplant.set_stat_value((self.player_health_statistic), 0, add=True)
        motherplant.set_stat_value((self.motherplant_health_statisic), (self.motherplant_health_statisic.max_value), add=True)
        for state_value in self.states_to_set_on_start:
            motherplant.set_state(state_value.state, state_value)

        statistic_tracker = motherplant.statistic_tracker
        self._statistic_watcher_handle = statistic_tracker.add_watcher(self._on_statistic_updated)
        self._setup_situation_meters()
        self._zombie_attack_alarm_handle = alarms.add_alarm(self, create_time_span(minutes=(self.zombie_fight_interaction_timer)),
          (self._zombie_attack),
          repeating=True)
        for custom_key in itertools.chain(self.victory_interaction_of_interest.custom_keys_gen(), self.retreat_interaction_of_interest.custom_keys_gen()):
            custom_key_tuple = (
             TestEvent.InteractionComplete, custom_key)
            self._registered_test_events.add(custom_key_tuple)
            services.get_event_manager().register_with_custom_key(self, TestEvent.InteractionComplete, custom_key)

    def _setup_situation_meters(self):
        motherplant = self._get_motherplant()
        self._mother_plant_meter = self.mother_plant_meter_settings.create_meter_with_sim_info(self, motherplant)
        self._player_health_meter = self.player_health_meter_settings.create_meter_with_sim_info(self, motherplant)

    def build_situation_start_message(self):
        msg = super().build_situation_start_message()
        with ProtocolBufferRollback(msg.meter_data) as (meter_data_msg):
            self.mother_plant_meter_settings.build_data_message(meter_data_msg)
        with ProtocolBufferRollback(msg.meter_data) as (meter_data_msg):
            self.player_health_meter_settings.build_data_message(meter_data_msg)
        build_icon_info_msg(IconInfoData(icon_resource=(self.mother_plant_icon)), None, msg.icon_info)
        return msg

    def _destroy(self):
        super()._destroy()
        services.get_persistence_service().unlock_save(self)
        for event_type, custom_key in self._registered_test_events:
            services.get_event_manager().unregister_with_custom_key(self, event_type, custom_key)

        motherplant = self._get_motherplant()
        statistic_tracker = motherplant.statistic_tracker
        statistic_tracker.remove_watcher(self._statistic_watcher_handle)
        for state_value in self.states_to_set_on_end:
            motherplant.set_state(state_value.state, state_value)

        self._registered_test_events.clear()
        if self._mother_plant_meter is not None:
            self._mother_plant_meter.destroy()
        if self._player_health_meter is not None:
            self._player_health_meter.destroy()

    def get_lock_save_reason(self):
        return self.save_lock_tooltip

    def set_motherplant_situation_state(self, motherplant_battle_state):
        if motherplant_battle_state == MotherplantBattleStates.ATTACK:
            self._change_state(self.attack_battle_situation_state())
        else:
            if motherplant_battle_state == MotherplantBattleStates.INSPIRE:
                self._change_state(self.inspire_battle_situation_state())
            else:
                if motherplant_battle_state == MotherplantBattleStates.RALLY:
                    self._change_state(self.rally_battle_sitaution_state())
                else:
                    if motherplant_battle_state == MotherplantBattleStates.WARBLING_WARCRY:
                        self._change_state(self.warbling_warcry_battle_situation_state())

    def _on_proxy_situation_goal_setup(self, goal):
        self._player_health_tracking_situation_goal = goal

    def _issue_requests(self):
        super()._issue_requests()
        request = SelectableSimRequestFactory(self, (_RequestUserData()),
          (self.other_player_jobs),
          (self.exclusivity),
          request_priority=(BouncerRequestPriority.EVENT_DEFAULT_JOB))
        self.manager.bouncer.submit_request(request)

lock_instance_tunables(MotherPlantBattleSituation, audio_sting_on_start=None,
  main_goal_audio_sting=None)


cont = 0
import json
import oauth2
from time import sleep
import urllib.parse

consumer_Key = 'Your_Consumer_Key'
consumer_Secret = 'Your_Secret_Consumer_Key'
access_Token = 'Your_Acess_Token'
access_Token_Secret = 'Your_Secret_Acess_Token'

consumer = oauth2.Consumer(consumer_Key, consumer_Secret)
token = oauth2.Token(access_Token, access_Token_Secret)
cliente = oauth2.Client(consumer, token)
print()

while True:
    try:
        alfabeto = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
                    'w', 'v', 'x', 'y', 'z']
        for letra in alfabeto:
            pesquisa = letra
            pesquisa_code = urllib.parse.quote(pesquisa)
            print()
            requisicao1 = cliente.request(
                'https://api.twitter.com/1.1/search/tweets.json?q=' + pesquisa_code + '&lang=pt')
            decode = requisicao1[1].decode()
            resultado = json.loads(decode)
            tweets = resultado['statuses']
            for tweet in tweets:
                id = str(tweet['id'])
                requisicao2 = cliente.request('https://api.twitter.com/1.1/favorites/create.json?id=' + id,
                                              method='POST')
                cont += 1
                print()
                print(cont)
                print('-' * 43)
                sleep(15)
            print()
    except:
        quit()
        print('An error has ocurred, trying again in 30 seconds!')
        print()
        sleep(30)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy2 Experiment Builder (v1.75.01), Januar 15, 2013, at 11:12
If you publish work using this script please cite the relevant PsychoPy publications
  Peirce, JW (2007) PsychoPy - Psychophysics software in Python. Journal of Neuroscience Methods, 162(1-2), 8-13.
  Peirce, JW (2009) Generating stimuli for neuroscience using PsychoPy. Frontiers in Neuroinformatics, 2:10. doi: 10.3389/neuro.11.010.2008
"""

from __future__ import division  # so that 1/3=0.333 instead of 1/3=0
from psychopy import visual, core, data, event, logging, gui
from psychopy.constants import *  # things like STARTED, FINISHED
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions

# Store info about the experiment session
expName = 'None'  # from the Builder filename that created this script
expInfo = {u'session': u'001', u'participant': u''}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName

# Setup files for saving
if not os.path.isdir('data'):
    os.makedirs('data')  # if this fails (e.g. permissions) we will get error
filename = 'data' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['date'])
logFile = logging.LogFile(filename+'.log', level=logging.DEBUG)
logging.console.setLevel(logging.WARNING)  # this outputs to the screen, not a file

# An ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(name=expName, version='',
    extraInfo=expInfo, runtimeInfo=None,
    originPath=None,
    savePickle=True, saveWideText=True,
    dataFileName=filename)

# Setup the Window
win = visual.Window(size=[800, 800], fullscr=False, screen=0, allowGUI=True, allowStencil=False,
    monitor='testMonitor', color=[0,0,0], colorSpace='rgb')

# Initialize components for Routine "pythonCode"
pythonCodeClock = core.Clock()
triggers = {'grating':{'1.0':11, '0.75':12,'0.5':13,'0.25':14,'0.0':15}, 'fixCross':8}
###
from ctypes import windll
parallelPort = windll.inpout32
portAddress = 0xD010
def writeTrigger(trigCode):
    parallelPort.Out32(portAddress, trigCode)
###
myDict = {'contrast': [1.0, 0.75, 0.5, 0.25], 'orientation':[225, 315],
        'probeMatch':[1, 0]}
###
import csv
def generateTrials(myDict):
    '''
    generates a list of trials to write to csv file
    supply 3 columns to be factorially combined
    myDict = {'contrast': [1.0, 0.75, 0.5, 0.25], 'orientation':[225, 315],
        'probeMatch':[1, 0]}
    '''
    columnHeaders = myDict.keys()
    # header = ",".join(columnHeaders)
    trialList = data.createFactorialTrialList(myDict)
    with open('mainTrials.csv', 'wb') as mainTrialsFile:
        writer = csv.writer(mainTrialsFile, dialect='excel')
        writer.writerow(columnHeaders)
        for row in trialList:
            writer.writerow(row.values())

generateTrials(myDict)
###

# Initialize components for Routine "instructions1"
instructions1Clock = core.Clock()
text = visual.TextStim(win=win, ori=0, name='text',
    text='Any text\n\nincluding line breaks',
    font='Arial',
    pos=[0, 0], height=10, wrapWidth=None,
    color='white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Initialize components for Routine "trial"
trialClock = core.Clock()
fixCrossTrial = visual.TextStim(win=win, ori=0, name='fixCrossTrial',
    text='+',
    font='Arial',
    pos=[0, 0], height=10, wrapWidth=None,
    color='white', colorSpace='rgb', opacity=1,
    depth=0.0)
grating1 = visual.GratingStim(win=win, name='grating1',
    tex='sin', mask='circle',
    ori=1.0, pos=[0, 0], size=[150, 150], sf=0.04, phase=0.0,
    color=[1,1,1], colorSpace='rgb', opacity=1.0,
    texRes=512, interpolate=True, depth=-1.0)

# Initialize components for Routine "interTrialInterval"
interTrialIntervalClock = core.Clock()
fixCrossITI = visual.TextStim(win=win, ori=0, name='fixCrossITI',
    text='+',
    font='Arial',
    pos=[0, 0], height=30, wrapWidth=None,
    color='white', colorSpace='rgb', opacity=1,
    depth=0.0)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer()  # to track time remaining of each (non-slip) routine

#------Prepare to start Routine"pythonCode"-------
t = 0
pythonCodeClock.reset()  # clock
frameN = -1
# update component parameters for each repeat

# keep track of which components have finished
pythonCodeComponents = []
for thisComponent in pythonCodeComponents:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "pythonCode"-------
continueRoutine = True
while continueRoutine:
    # get current time
    t = pythonCodeClock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # check if all components have finished
    if not continueRoutine:  # a component has requested that we end
        routineTimer.reset()  # this is the new t0 for non-slip Routines
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in pythonCodeComponents:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the [Esc] key)
    if event.getKeys(["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#-------Ending Routine "pythonCode"-------
for thisComponent in pythonCodeComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

#------Prepare to start Routine"instructions1"-------
t = 0
instructions1Clock.reset()  # clock
frameN = -1
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
instructions1Components = []
instructions1Components.append(text)
for thisComponent in instructions1Components:
    if hasattr(thisComponent, 'status'):
        thisComponent.status = NOT_STARTED

#-------Start Routine "instructions1"-------
continueRoutine = True
while continueRoutine and routineTimer.getTime() > 0:
    # get current time
    t = instructions1Clock.getTime()
    frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
    # update/draw components on each frame

    # *text* updates
    if t >= 0.0 and text.status == NOT_STARTED:
        # keep track of start time/frame for later
        text.tStart = t  # underestimates by a little under one frame
        text.frameNStart = frameN  # exact frame index
        text.setAutoDraw(True)
    elif text.status == STARTED and t >= (0.0 + 1.0):
        text.setAutoDraw(False)

    # check if all components have finished
    if not continueRoutine:  # a component has requested that we end
        routineTimer.reset()  # this is the new t0 for non-slip Routines
        break
    continueRoutine = False  # will revert to True if at least one component still running
    for thisComponent in instructions1Components:
        if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
            continueRoutine = True
            break  # at least one component has not yet finished

    # check for quit (the [Esc] key)
    if event.getKeys(["escape"]):
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

#-------Ending Routine "instructions1"-------
for thisComponent in instructions1Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
mainTrials = data.TrialHandler(nReps=1, method='random',
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions('conditions.csv'),
    seed=None, name='mainTrials')
thisExp.addLoop(mainTrials)  # add the loop to the experiment
thisMainTrial = mainTrials.trialList[0]  # so we can initialise stimuli with some values

for thisMainTrial in mainTrials:
    currentLoop = mainTrials

    #------Prepare to start Routine"trial"-------
    t = 0
    trialClock.reset()  # clock
    frameN = -1
    # update component parameters for each repeat
    grating1.setOpacity(thisMainTrial.contrast)
    grating1.setOri(randint(0,180))
    # keep track of which components have finished
    trialComponents = []
    trialComponents.append(fixCrossTrial)
    trialComponents.append(grating1)
    for thisComponent in trialComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "trial"-------
    continueRoutine = True
    while continueRoutine:
        # get current time
        t = trialClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *fixCrossTrial* updates
        if frameN >= 0 and fixCrossTrial.status == NOT_STARTED:
            # keep track of start time/frame for later
            fixCrossTrial.tStart = t  # underestimates by a little under one frame
            fixCrossTrial.frameNStart = frameN  # exact frame index
            fixCrossTrial.setAutoDraw(True)
        elif fixCrossTrial.status == STARTED and frameN >= (fixCrossTrial.frameNStart + 30):
            fixCrossTrial.setAutoDraw(False)

        # *grating1* updates
        if frameN >= 30 and grating1.status == NOT_STARTED:
            # keep track of start time/frame for later
            grating1.tStart = t  # underestimates by a little under one frame
            grating1.frameNStart = frameN  # exact frame index
            grating1.setAutoDraw(True)
        elif grating1.status == STARTED and frameN >= (grating1.frameNStart + 60):
            grating1.setAutoDraw(False)

        # check if all components have finished
        if not continueRoutine:  # a component has requested that we end
            routineTimer.reset()  # this is the new t0 for non-slip Routines
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in trialComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the [Esc] key)
        if event.getKeys(["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()
            if fixCrossTrial.status == STARTED and fixCrossTrial.frameNStart == frameN:
                writeTrigger(triggers['fixCross'])
                logging.log(level=logging.DEBUG, msg='showFixCrossTrial')
            if grating1.status == STARTED and grating1.frameNStart == frameN:
                writeTrigger(triggers['grating'][str(thisMainTrial.contrast)])
                logging.log(level=logging.DEBUG, msg='showGrating1')
            core.wait(0.005)
            writeTrigger(0)

    #-------Ending Routine "trial"-------
    for thisComponent in trialComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)

    #------Prepare to start Routine"interTrialInterval"-------
    t = 0
    interTrialIntervalClock.reset()  # clock
    frameN = -1
    routineTimer.add(2.000000)
    # update component parameters for each repeat
    # keep track of which components have finished
    interTrialIntervalComponents = []
    interTrialIntervalComponents.append(fixCrossITI)
    for thisComponent in interTrialIntervalComponents:
        if hasattr(thisComponent, 'status'):
            thisComponent.status = NOT_STARTED

    #-------Start Routine "interTrialInterval"-------
    continueRoutine = True
    while continueRoutine and routineTimer.getTime() > 0:
        # get current time
        t = interTrialIntervalClock.getTime()
        frameN = frameN + 1  # number of completed frames (so 0 is the first frame)
        # update/draw components on each frame

        # *fixCrossITI* updates
        if t >= 0.0 and fixCrossITI.status == NOT_STARTED:
            # keep track of start time/frame for later
            fixCrossITI.tStart = t  # underestimates by a little under one frame
            fixCrossITI.frameNStart = frameN  # exact frame index
            fixCrossITI.setAutoDraw(True)
        elif fixCrossITI.status == STARTED and t >= (0.0 + 2.0):
            fixCrossITI.setAutoDraw(False)

        # check if all components have finished
        if not continueRoutine:  # a component has requested that we end
            routineTimer.reset()  # this is the new t0 for non-slip Routines
            break
        continueRoutine = False  # will revert to True if at least one component still running
        for thisComponent in interTrialIntervalComponents:
            if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
                continueRoutine = True
                break  # at least one component has not yet finished

        # check for quit (the [Esc] key)
        if event.getKeys(["escape"]):
            core.quit()

        # refresh the screen
        if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
            win.flip()

    #-------Ending Routine "interTrialInterval"-------
    for thisComponent in interTrialIntervalComponents:
        if hasattr(thisComponent, "setAutoDraw"):
            thisComponent.setAutoDraw(False)
    thisExp.nextEntry()

# completed 1 repeats of 'mainTrials'

# get names of stimulus parameters
if mainTrials.trialList in ([], [None], None):  params = []
else:  params = mainTrials.trialList[0].keys()
# save data for this loop
mainTrials.saveAsExcel(filename + '.xlsx', sheetName='mainTrials',
    stimOut=params,
    dataOut=['n','all_mean','all_std', 'all_raw'])
mainTrials.saveAsText(filename + 'mainTrials.csv', delim=',',
    stimOut=params,
    dataOut=['n','all_mean','all_std', 'all_raw'])

# Shutting down:
win.close()
core.quit()


# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2015 Prime Consulting (<http://prime.cv>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from datetime import datetime
from datetime import date as dt
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp

class res_partner(osv.osv):
	_inherit = "res.partner"

	def _purchase_invoice_count(self, cr, uid, ids, field_name, arg, context=None):
		PurchaseOrder = self.pool['rfq.hcv']
		Invoice = self.pool['account.invoice']
		return {
			partner_id: {
                'rfq_order_count': PurchaseOrder.search_count(cr,uid, [('partner_id', 'child_of', partner_id)], context=context),
                'supplier_invoice_count': Invoice.search_count(cr,uid, [('partner_id', 'child_of', partner_id), ('type','=','in_invoice')], context=context)
            }
            for partner_id in ids
        }

	_columns = {
		'purchase_line_ids': fields.one2many('product.supplierinfo.hcv', 'partner_id', 'Products Supplied'),
        'rfq_order_count': fields.function(_purchase_invoice_count, string='# of Purchase Order', type='integer', multi="count"),
	}

class product_supplierinfo_hcv(osv.osv):
	_name = "product.supplierinfo.hcv"
	_description = "Products Supplied"
	_columns = {
		'partner_id': fields.many2one('res.partner', 'Supplier'),
		'product_id': fields.many2one('product.product', 'Product'),
		'name': fields.char('Product'),
		'price': fields.float('Price'),
		'delivery_date': fields.date('Delivery Date'),
		'delivery_time': fields.char('Delivery Time(in Days)'),
	}


# This file modify json data if it hasn't the classification data

def get_w(data):
	v = data.split('"v":')[1]
	d_parse = data.split(', "v":')[0]
	w = d_parse.split((', "w": '))[1]
	return w

def get_v(data):
	v = data.split('"v":')[1]
	v = float(v.split('}')[0])
	return v

def get_classification_w(w):
	if w[0] == '-' and abs(float(w)) >= 2.0:
		classification = 'radically_right'
	if w[0] == '-' and abs(float(w)) >= 1.0:
		classification = 'strongly_right'
	elif w[0] == '-' and abs(float(w)) >= 0.5:
		classification = 'moderately_right'
	elif w[0] == '-' and abs(float(w)) >= 0.1:
		classification = 'slightly_right'
	elif abs(float(w)) >= 2.0:
		classification = 'radically_left'
	elif abs(float(w)) >= 1.0:
		classification = 'strongly_left'
	elif abs(float(w)) >= 0.5:
		classification = 'moderately_left'
	elif abs(float(w)) >= 0.1:
		classification = 'slightly_left'
	else:
		classification = 'slight'
	return classification

def get_classification_v(v):
	if v > 11:
		classification = 'very_fast'
	elif v > 9:
		classification = 'fast'
	elif v > 7:
		classification = 'moderate'
	else:
		classification = 'slow'
	return classification

def get_classification_v_5(v):
	if v > 11:
		classification = 'very_fast'
	elif v > 9:
		classification = 'fast'
	elif v > 7:
		classification = 'moderate'
	elif v > 0:
		classification = 'slow'
	else:
		classification = 'negative'
	return classification

if __name__ == "__main__":
	filename = 'dl-driver/Net/Dataset/data.json'
	output = ''

	with open(filename, "r+") as f:
		data = f.read()
		data_parse = data.split('{')[1:]

		for d in data_parse:
			w = get_w(d)
			classification = get_classification_w(w)
			output = output + '{"class_w_9": ' + classification + ', ' + d

		f.seek(0)
		f.write(output)
		f.truncate()


#encoding:utf-8
#By:Eastmount CSDN 2021-08-20
import cv2
import numpy as np
import matplotlib.pyplot as plt

#读取图片
img = cv2.imread('lena-hd.png')

#灰度转换
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#直方图均衡化处理
result = cv2.equalizeHist(gray)

#显示图像
plt.subplot(221)
plt.imshow(gray, cmap=plt.cm.gray), plt.axis("off"), plt.title('(a)')
plt.subplot(222)
plt.imshow(result, cmap=plt.cm.gray), plt.axis("off"), plt.title('(b)')
plt.subplot(223)
plt.hist(img.ravel(), 256), plt.title('(c)')
plt.subplot(224)
plt.hist(result.ravel(), 256), plt.title('(d)')
plt.show()


import json
import bot_data
import dataset
from os.path import isfile
import time

# Checks if user statistics file exists
def check(user_id):
    if not isfile("rpg-data/social/"+str(user_id)+".json"):
        with open("rpg-data/social/"+str(user_id)+".json", "w") as social_file:
            social_file.write(json.dumps(bot_data.social_dict))

# increments a stat
def increment(user_id, key, count=1):
    db = dataset.connect("sqlite:///pb.db")
    user = db["users"].find_one(user_id=user_id)
    nvalue = count
    if user:
        if key in user and user[key] != None:
            nvalue = user[key] + count
    db["users"].update({"user_id": user_id, key: nvalue}, ["user_id"])

def genuser(user_id, username, first_name, last_name):
    db = dataset.connect("sqlite:///pb.db")
    if db["users"].find_one(user_id=user_id):
        db["users"].update(dict(user_id=user_id,
                                username=username,
                                first_name=first_name,
                                last_name=last_name), ["user_id"])
    else:
        db["users"].insert(dict(user_id=user_id,
                                username=username,
                                first_name=first_name,
                                last_name=last_name))
# Check command timeout
def check_next_use(user_id, key, timeout=60):
    db = dataset.connect("sqlite:///pb.db")
    data = db["users"].find_one(user_id=user_id)

    if "last_used_"+key not in data or data["last_used_"+key] == None:
        db["users"].update({"user_id": user_id, "last_used_"+key: time.time()}, ["user_id"])
        return 0
    else:
        last_used = data["last_used_"+key]
        if last_used < time.time()-timeout:
            db["users"].update({"user_id": user_id, "last_used_"+key: time.time()}, ["user_id"])
            return 0
        else:
            return abs(int(last_used-time.time()+timeout))


import json
import math

class CodeClassifier:
    with open('code_freq.json', 'r') as f:
        code_freq = json.load(f)
    with open('text_freq.json', 'r') as f:
        text_freq = json.load(f)

    def classify(self, str):
        text_sum = 0
        code_sum = 0
        for c in str:
            text_sum += math.log(CodeClassifier.text_freq[c])
            code_sum += math.log(CodeClassifier.code_freq[c])
        return 1 / (1 + math.exp(text_sum - code_sum))

def gen_next_split(src, n):
    m = len(src)
    tag = False
    for i in reversed(range(m)):
        if src[i] != n - (m - i - 1):
            tag = True
            break
    if not tag:
        return None
    new = src[i] + 1
    return src[:i] + list(range(new, new + m - i))

def otsu_n(arr, m):
    n = len(arr)
    splits = list(range(m))
    max_splits = splits.copy()
    max_val = 0
    mean = sum(arr) / n
    while splits is not None:
        val = 0
        extend = [0] + splits + [n]
        for i in list(range(m + 1)):
            start = extend[i]
            end = extend[i + 1]
            if start == end:
                continue
            miu = sum(arr[start:end]) / (end - start)
            val += (end - start) / n * (miu - mean) ** 2
        # print("splits=" + str(splits))
        # print("\tval=" + str(val))
        if val > max_val:
            max_val = val
            max_splits = splits.copy()
        splits = gen_next_split(splits, n)

    return max_splits

def test_otsu():
    classifier = CodeClassifier()
    with open('test.txt', 'r') as f:
        lines = f.read().splitlines()
        probs = []
        for line in lines:
            probs.append(classifier.classify(line))

    print("splits:")
    splits = otsu_n(probs, 5)
    j = 0
    for (i, prob) in enumerate(probs):
        if j < len(splits) and splits[j] == i:
            print('-------------------------------------------------------------------')
            j += 1
        print("%d: %.3f %s" % (i, prob, lines[i]))

def test_next_split():
    splits = list(range(3))
    while splits is not None:
        print(splits)
        splits = gen_next_split(splits, 5)

def test_prob():
    classifier = CodeClassifier()
    with open('test.txt', 'r') as f:
        lines = f.read().splitlines()
        for line in lines:
            prob = classifier.classify(line)
            print('%.5f %s' % (prob, line))

if __name__ == '__main__':
    # test_next_split()
    # test_otsu()
    test_prob()


import pandas as pd

df = pd.read_csv("iris.csv") #csv dosyamiza girmek icin kullanilir. bunu df ye atadik.

#print(df.Species.unique()) # kac tur Species var onu verir. Unique, Kisacasi: o sutunda hangi cesit urunler var

#df.info() # df dosyasinda kac kolon urun ortalama max min gibi degerler hakkinda bilgiler verir.

#setosa = df[df.Species == "Iris-setosa"] #Species sutunundaki tum "Iris-setosa"  olanlari suz ve  setosa adli degiskene atadik

#versicolor = df[df.Species == "Iris-versicolor"] #usttekinin aynisi :)

import matplotlib.pyplot as plt

df1 = df.drop(["Id"], axis=1)

setosa = df[df.Species == "Iris-setosa"]
versicolor = df[df.Species == "Iris-versicolor"]
virginica = df[df.Species == "Iris-virginica"]

plt.plot(setosa.Id, setosa.PetalLengthCm, color="red", label= "setosa")
plt.plot(versicolor.Id, versicolor.PetalLengthCm, color="green", label= "versicolor")
plt.plot(virginica.Id, virginica.PetalLengthCm, color="blue", label= "virginica")
plt.legend()# x y cizgisi olusturur
plt.xlabel("Id")
plt.ylabel("PetalLengthCm")
plt.show()


from django.urls import path
from posts.views import post_list, post_create, post_detail, post_edit, post_delete, post_list_category

app_name='posts'
urlpatterns = [
    path('', post_list, name='post_list'),
    path('create/', post_create, name='post_create'),
    path('<slug>/', post_detail, name='post_detail'),
    path('<slug>/edit/', post_edit, name='post_edit'),
    path('<slug>/delete/', post_delete, name='post_delete'),
    path('categories/<category_slug>/', post_list_category, name='post_list_category')
]


import random
from game import Actions
import mdp
import mdpEnvironment
import util
import featureExtractors

import numpy as np
import numpy.linalg

class ContinuousWorld(mdp.MarkovDecisionProcess):
  """
  A MDP that captures continuous state space, while the agent moves in discrete steps.

  State: (location, orientation) of the agent
  Action: 8 directional movement, with a fixed step size.
  Transition: trivial.
  Reward: upon reaching a target / obstacle, obtain the corresponding reward.
          upon reaching a segment, if this segment is newer than the one visited before,
          then obtain the reward.
  """
  def __init__(self, init):
    """
    Args:
      init: a dict, that has attributes to be appended to self
            objs, boundary, radius.
    """
    # this adds necessary attributes of this MDP from a domain initializer
    # domains are coded in continuousWorldDomains
    self.__dict__.update(init)

    # reward values that getReward will use
    self.rewards = {'targs': 1, 'obsts': -1, 'segs': 1, 'elevators': 0, 'entrance': 0}
    self.noise = 0.0 # DUMMY - need assumption on what it means to be noisy

    # stats set
    self.touchedObstacleSet = []
    self.collectedTargetSet = []

    if not 'livingReward' in self.__dict__.keys():
      self.livingReward = 0

  def getReachedObjects(self, l):
    """
    Determine whether a state is close to any object, within radius.
    The radius for obstacles should be larger than that of targets.
    A waypoint is 'reached' when the agent gets closer to the next waypoint.

    Args:
      l: the loc to be checked.
    Return:
      [(String, int)]: A list of the type of object that it's in the radius of, and its id.
                       Return [] if nothing matches.
    """
    ret = []

    # get a target?
    tLocs = self.objs['targs']
    for targIdx in xrange(len(tLocs)):
      dist = numpy.linalg.norm(np.subtract(l, tLocs[targIdx]))
      if dist < self.radius:
        ret.append(('targs', targIdx))

    # run into an obstacle?
    oLocs = self.objs['obsts']
    for obstIdx in xrange(len(tLocs)):
      dist = numpy.linalg.norm(np.subtract(l, oLocs[obstIdx]))
      if dist < self.radius:
        ret.append(('obsts', obstIdx))

    # close to the next segment? remove the current one
    sLocs = self.objs['segs']
    if len(sLocs) > 1:
      # when get closer to the next one
      distSeg1 = numpy.linalg.norm(np.subtract(l, sLocs[0]))
      distSeg2 = numpy.linalg.norm(np.subtract(l, sLocs[1]))
      if distSeg1 > distSeg2 :
        ret.append(('segs', 0))
    elif len(sLocs) == 1:
      # if only one left, just approach it
      distSeg = numpy.linalg.norm(np.subtract(l, sLocs[0]))
      if distSeg < self.radius * 2: # larger buffer
        ret.append(('segs', 0))

    return ret

  def setLivingReward(self, reward):
    """
    The (negative) reward for exiting "normal" states.

    Note that in the R+N text, this reward is on entering
    a state and therefore is not clearly part of the state's
    future rewards.
    """
    self.livingReward = reward

  def setNoise(self, noise):
    """
    The probability of moving in an unintended direction.
    """
    self.noise = noise

  def getPossibleActions(self, state):
    """
    Returns list of valid actions for 'state'.

    This discretizes possible aciton set.
    """
    return ('north','west','south','east', 'ne', 'se', 'nw', 'sw')

  def getStates(self):
    """
    Return list of random states. This is usually for sanity check.
    """
    states = []
    width = self.xBoundary[1] - self.xBoundary[0]
    height = self.xBoundary[1] - self.xBoundary[0]

    while len(states) < 400:
      x = self.xBoundary[0] + random.random() * width
      y = self.yBoundary[0] + random.random() * height
      states.append(((x, y), 0))

    return states

  def getReward(self, state, action, nextState):
    """
    Get reward for state, action, nextState transition.

    Note that the reward depends only on the state being
    departed (as in the R+N book examples, which more or
    less use this convention).
    """
    loc, orient = state
    nextLoc, nextOrient = nextState

    reward = 0

    # get the list of contacted objects
    objInfoList = self.getReachedObjects(nextLoc)

    for nextStateType, nextObjId in objInfoList:
      if nextStateType != 'segs':
        # add rewards for target and obstacles
        reward += self.rewards[nextStateType]

        # keep a set of reached objects
        objLoc = self.objs[nextStateType][nextObjId]
        if nextStateType == 'obsts' and not objLoc in self.touchedObstacleSet:
          self.touchedObstacleSet.append(objLoc)
        elif nextStateType == 'targs':
          self.collectedTargetSet.append(objLoc)

    # give rewards for waypoint segments, except training targets or obstacles
    if not hasattr(self, 'category') or self.category == 'segs':
      nextSeg = self.objs['segs'][1] if len(self.objs['segs']) > 1 else self.objs['segs'][0]

      dist, angle = featureExtractors.getDistAngle(loc, nextSeg, orient)
      nextStepDist, nextStepAngle = featureExtractors.getDistAngle(nextLoc, nextSeg, orient)
      [pathIntercept, pathDist] = featureExtractors.getProjectionToSegment(nextLoc, self.objs['segs'])

      if nextStepDist < dist and pathDist < 1:
        # reward for shrinking distance
        # give unit reward
        #reward += self.rewards['segs']
        # or give discounted reward
        reward += self.rewards['segs'] * (1 - pathDist ** 2)

    return reward or self.livingReward

  def clearObj(self, objType, objId):
    """
    Clear an object from self.objs, usually because the agent has got it.
    """
    del self.objs[objType][objId]

  def getStartState(self):
    """
    Start at the starting location, with no segment previously visited.
    """
    loc = self.objs['entrance']

    # face towards the center of the domain
    if loc[0] < 0: angle = 45.0 / 180 * np.pi
    else: angle = - 135.0 / 180 * np.pi
    return (loc, angle)

  def isFinal(self, state):
    """
    Check whether we should terminate at this state.
    """
    loc, orient = state

    # cleared the targets or the waypoints.
    return len(self.objs['segs']) == 0 or len(self.objs['targs']) == 0

  def getTransitionStatesAndProbs(self, state, action):
    """
    Basically following physics laws, but considering:
    - stay within self.xBoundary and self.yBoundary (may bump into the boundary)
    - change seg in the state representation upon reaching a new segment
    """
    loc, orient = state

    # move to new loc and check whether it's allowed
    newLoc = np.add(loc, np.multiply(self.step, Actions._directions[action]))
    if not self.isAllowed(newLoc):
      newLoc = loc

    newOrient = orient # doesn't change orient in this mdp

    successors = [((newLoc, newOrient), 1)]

    return successors

  def __aggregate(self, statesAndProbs):
    """
    Make sure stateAndProbs.keys() is a set (without duplicates)
    """
    counter = util.Counter()
    for state, prob in statesAndProbs:
      counter[state] += prob
    newStatesAndProbs = []
    for state, prob in counter.items():
      newStatesAndProbs.append((state, prob))
    return newStatesAndProbs

  def isAllowed(self, loc):
    """
    Check whether this state is valid
    """
    x, y = loc
    if x < self.xBoundary[0] or x >= self.xBoundary[1]: return False
    if y < self.yBoundary[0] or y >= self.yBoundary[1]: return False
    return True

class ContinuousEnvironment(mdpEnvironment.MDPEnvironment):
  def step(self, state, action, nextState, reward):
    # remove objects if necessary
    # clear this object upon getting it
    loc, orient = state
    nextLoc, nextOrient = nextState

    objInfoLists = self.mdp.getReachedObjects(nextLoc)
    # to remove object by id, make sure remove the ones with larger id first
    # so the list won't screw up.
    if len(objInfoLists) > 0: objInfoLists.reverse()

    for nextStateType, nextObjId in objInfoLists:
      if nextStateType == 'targs' or nextStateType == 'segs':
        self.mdp.clearObj(nextStateType, nextObjId)


import time
import cv2
import sys
import numpy
from commandesPython import Arduino
from datetime import datetime
from time import strftime

port = 'COM3'
ard = Arduino(port)

print('access port available')

xValue = 90
yValue = 70
ard.servoAttach(1, 6)
ard.servoAttach(2, 7)
ard.servoWrite(1, xValue)
ard.servoWrite(2, yValue)

video = cv2.VideoCapture(0)

fourcc = cv2.VideoWriter_fourcc(*'XVID')

dateNow = datetime.now()
date = str(dateNow.day) + "-" + str(dateNow.hour) + "-" + str(dateNow.minute)
number = dateNow.hour
writer = cv2.VideoWriter("videos/projet-"+str(date)+".avi", fourcc, 25.0, (640, 480))

face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt2.xml')

# Define an initial bounding box
bbox = (287, 23, 86, 320)

while True:

    ok, frame = video.read()
    if not ok:
        print('Cannot read video file')
        sys.exit()

    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    height, width = frame.shape[:2]
    yScrCen = int(height/2)
    xScrCen = int(width/2)
    yScrLim = int(yScrCen/2)
    xScrLim = int(xScrCen/2)
    yScrSaf = int(height/15)
    xScrSaf = int(width/10)
    ec = 20

    for (x,y,w,h) in faces:
        cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)

    cv2.imshow('Detection',frame)

    #if cv2.waitKey(1) & 0xFF == ord('t'):
    if(faces != ()):

        bbox = tuple(faces[0])
        continuer = True

        while continuer:

            if(continuer):

                continuer = False

                # Initialize tracker with first frame and bounding box
                # change size : MedianFow, TDL
                # not : KCF, MIL

                # ATTENTION !
                """
                    SI TRACKER CHANGE :
                        -   MODIFIER CONDITION "facesDet !=" ?
                        - ? par "()" si TLD
                        - ? par "0" et "facesDet" par "facesDet[0][0]" si KCF

                """
                tracker = cv2.TrackerKCF_create()
                ok = tracker.init(frame, bbox)

                end = False

                nbImages = 0

                while True:
                    nbImages += 1

                    # Read a new frame
                    ok, frame = video.read()
                    frame = cv2.flip(frame, 1)

                    if not ok:
                        print('we can not read the video')
                        break

                    # Update tracker
                    ok, bbox = tracker.update(frame)

                    if(not ok):
                        if(not end):
                            print("end of tracking")
                            end = True
                        facesDet = face_cascade.detectMultiScale(frame, 1.2, 5)
                        print(facesDet)
                        if(facesDet != ()):
                            if(facesDet[0][0] != 0):
                                bbox = tuple(facesDet[0])
                                print("new detection : " + str(bbox))
                                continuer = True
                                break

                    if(nbImages % 10 == 0 and ok):
                        print("images = 10")
                        print(frame.shape)
                        print(bbox)
                        print(ok)
                        print(int(bbox[0]+bbox[2])-int(bbox[0]))
                        print(int(bbox[1]+bbox[3])-int(bbox[1]))
                        frameROI = frame[int(bbox[1]-ec):int(bbox[1]+bbox[3]+ec), int(bbox[0]-ec):int(bbox[0]+bbox[2]+ec)]
                        print(frameROI.shape)
                        facesDet = face_cascade.detectMultiScale(frameROI, 1.2, 5)
                        print(facesDet)
                        if(facesDet == ()):
                            facesDet = [[0,0,0,0]]
                            print("test faces Det : '" + str(facesDet[0][0]) + "'")
                        if(facesDet[0][0] == 0):
                            facesDet = face_cascade.detectMultiScale(frame, 1.2, 5)
                            if(facesDet != ()):
                                if(facesDet[0][0] != 0):
                                    new = bbox
                                    bbox = tuple(facesDet[0])
                                    continuer = True
                                    print("10 secondes worked : " + str(new))
                                    print("10 secondes is now : " + str(bbox))
                                    break

                    # Draw bounding box
                    if ok:
                        x, y, w, h = (int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]))

                        cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),2)

                        xFaceCen = x + int(w/2)
                        yFaceCen = y + int(h/2)

                        xEcart = abs(xScrCen - xFaceCen) - xScrSaf
                        yEcart = abs(yScrCen - yFaceCen) - yScrSaf

                        xDep = int(xEcart / 100) + 1
                        yDep = int(yEcart /100) + 1

                        if(xScrCen - xScrSaf > xFaceCen):
                            xValue -= xDep
                            if(xValue < 0):
                                xValue = 0
                        if(xScrSaf + xScrCen < xFaceCen):
                            xValue += xDep
                            if(xValue > 180):
                                xValue = 180
                        if(yScrCen - yScrSaf > yFaceCen):
                            yValue -= yDep
                            if(yValue < 0):
                                yValue = 0
                        if(yScrSaf + yScrCen < yFaceCen):
                            yValue += yDep
                            if(yValue > 180):
                                yValue = 180

                    ard.servoWrite(1, xValue)
                    ard.servoWrite(2, yValue)

                    # Display result
                    cv2.imshow("Detection", frame)
                    writer.write(frame)
                    print(x)
                    print(y)

                    # Exit if ESC pressed
                    k = cv2.waitKey(1) & 0xff
                    if k == ord('a') :
                        break

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video.release()
cv2.destroyAllWindows()


"""imports"""
import numpy as np

def sgn(x, Derivative=False):
    if not Derivative:
        return 1 / (1 + np.exp(-x))
    else:
        out = sgn(x)
        return out * (1 - out)

def linear(x, Derivative=False):
    if not Derivative:
        return x
    else:
        return 1.0

def gaussian(x, Derivative=False):
    if not Derivative:
        return np.exp(-x**2)
    else:
        return -2*x*np.exp(-x**2)

def linear(x, Derivative=False):
    if not Derivative:
        return np.tanh(x)
    else:
        return 1.0-np.tanh(x)**2

class Backpropagation:

    layercount=0
    shape=None
    weights=[]
    tfuncs =[]
    """methods"""
    def __init__(self,layerSize, layerFunctions=None):

        self.layercount = len(layerSize)-1
        self.shape = layerSize

        self._layerInput = []
        self._layerOutput = []

        if layerFunctions is None:
            lfuncs=[]
            for i in range(self.layercount):
                if i == self.layercount -1:
                    lfuncs.append(linear)
                else:
                    lfuncs.append(sgn)
        else:
            if len(layerSize)!=len(layerFunctions):
                raise valueError("incompatable list of functions")
            elif layerFunctions[0] is not None:
                raise ValueError("Input layer cannot have transfer function")
            else:
                lfuncs=self.tfuncs[1:]

        self.tfuncs=lfuncs
        for(l1,l2) in zip(layerSize[:-1],layerSize[1:]):
            self.weights.append(np.random.normal(scale=0.1, size=(l2,l1+1)))

    def run(self,input):
        lnCases = input.shape[0]
        self._layerInput=[]
        self._layerOutput=[]

        for index in range(self.layercount):
            if index==0:
                layerInput=self.weights[0].dot(np.vstack([input.T,np.ones([1,lnCases])]))
            else:
                layerInput=self.weights[index].dot(np.vstack([self._layerOutput[-1],np.ones([1,lnCases])]))

            self._layerInput.append(layerInput)
            self._layerOutput.append(self.tfuncs[index](layerInput))

        return self._layerOutput[-1].T

    def train(self,input,target,trainignRate=0.2):
        delta=[]
        lncases=input.shape[0]

        self.run(input)

        for index in reversed(range(self.layercount)):
            if index==self.layercount-1:
                output_delta=self._layerOutput[index]-target.T
                error= np.sum(output_delta**2)
                delta.append(output_delta*sgn(self._layerInput[index],True))
            else:
                delta_backward=self.weights[index+1].T.dot(delta[-1])
                delta.append(delta_backward[:-1,:]*self.tfuncs[index](self._layerInput[index],True))

        for index in range(self.layercount):
            delta_index = self.layercount-1-index
            if index==0:
                layerOutput=np.vstack([input.T,np.ones([1,lncases])])
            else:
                layerOutput=np.vstack([self._layerOutput[index-1],np.ones([1,self._layerOutput[index-1].shape[1]])])

            weightDelta=np.sum(\
                layerOutput[None,:,:].transpose(2,0,1)*delta[delta_index][None,:,:].transpose(2,1,0)\
                ,axis=0)

            self.weights[index]-=trainignRate*weightDelta
        return error

    """transfer function"""

if __name__ =="__main__":
    bp=Backpropagation((2,3,4,1))
    print(bp.shape)
    print(bp.weights)
    #lfuncs=[None,gaussian,linear]
    lvlInput=np.array([[0,0],[1,1],[2,2],[6,6],[11,11]])
    lvlTarget = np.array([[0.01], [0.1], [0.2], [0.65], [0.98]])
    lnMax=100000
    lnerr= 1e-5
    for i in range(lnMax+1):
        err=bp.train(lvlInput,lvlTarget)
        if i%2500==0:
            print("Interation:{0} \t Error {1:0.6f}".format(i,err))
        if err<=lnerr:
            print("Minimum Error Reached at iteration {0}".format(i))
            break
    lvlOutput = bp.run(lvlInput)

    print("Input: {0} \n Output: {1}".format(lvlInput, lvlOutput))


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

from pyGRBaglow import constants as cc
import numpy as np

class reddening(object):
    """
    Class to to model the host and galactic dust and
    gas attenuation of a grb spectrum because
    """

    def __init__(self, wavelength, z, Av):
        """
        Parameters
        ----------
        wavelength: `float` or `array`
        wavelength, in angstroms

        z: `float`
            redshift

        Av : `float`
            Amount of attenuation in V band, in mag
        """

        self.Av = float(Av)
        self.z = float(z)
        self.wavelength = np.atleast_1d(wavelength)

    def NHI_host(self):
        """
        Compute the Hydrogen column density in the host galaxy (in H/cm2)

        Parameters
        ----------
        None

        Returns
        -------
        NHI: `float`
            hydrogen column density, in H/cm2
        """
        # So far we just assume that this is 4 four times higher than
        # in our galaxy.
        # Should be a free parameter if X ray data are used
        return 4. * self.Av * 1.79e21

    def extinction_laws_coeff(self, extinction_law):
        """
        Define the parameters for the extinction law for each cases
        using the "Drude" model by Li and al 2008

        Parameters
        ----------
        extinction_law: `str`
            type of extinction law to use.
            Choices: mw, lmc, smc, linear, calzetti, grb1, grb2

        Returns
        -------
        NHI: `float`
            hydrogen column density, in H/cm2

        """
        if extinction_law.lower() == 'mw':
            c1 = 14.4
            c2 = 6.52
            c3 = 2.04
            c4 = 0.0519
        elif extinction_law.lower() == 'lmc':
            c1 = 4.47
            c2 = 2.39
            c3 = -0.988
            c4 = 0.0221
        elif extinction_law.lower() == 'smc':
            c1 = 38.7
            c2 = 3.83
            c3 = 6.34
            c4 = 0.
        elif extinction_law.lower() == 'linear':
            c1 = 66.2
            c2 = 4.97
            c3 = 22.1
            c4 = 0.
        elif extinction_law.lower() == 'calzetti':
            c1 = 44.9
            c2 = 7.56
            c3 = 61.2
            c4 = 0.
        elif extinction_law.lower() == 'grb1':
            c1 = 0.025
            c2 = 0.048
            c3 = -2.
            c4 = 0.
        elif extinction_law.lower() == 'grb2':
            c1 = 0.015
            c2 = 0.15
            c3 = -2.
            c4 = 0.
        return [c1, c2, c3, c4]

    def Li07(self, extinction_law='smc', Xcut=False):
        """
        Compute the optical depth due to dust reddening

        Parameters
        ----------
        extinction_law : `str`, optional, default: smc
             model of extinction to be used:
             Choices: mw, lmc, smc, linear, calzetti, grb1, grb2

        Xcut: `boolean`, optional, default: False
             Whether to set attenuation to 0 for wavelength below 700 angstrom
             Useful when coupling with X-ray data

        Returns
        ------
        Alambda_over_Av: `float` or `array`
                reddening law

        Trans_dust: `float` or `array`
                Transmission coefficient due to dust reddening
                to be applied to the spectrum
        """
        # Load the coefficient corresponding to the desired
        # extinction curve template
        [c1, c2, c3, c4] = self.extinction_laws_coeff(extinction_law)

        nus = cc.c_light_m_s / (self.wavelength * 1e-10)

        nu = nus * (1 + self.z)
        wavel_mic = self.wavelength * 1e-4 / (1 + self.z)

        # Check if the wavelength is a scalar or an array
        # Otherwise can not iterate over 0-d array
        wavel_mic = np.atleast_1d(wavel_mic)

        # First term accounting for the far UV extinction rise
        UV_extinction = c1 / ((wavel_mic / 0.08)**c2 +
                              (0.08 / wavel_mic)**c2 + c3)

        # Second term accounting for the near-IR/visible extinction
        # Ugly hack to fix non understood indetation pb with pep8
        IR_vis_ext = ((233. * (1. - c1 /
                               (6.88**c2 + 0.145**c2 + c3) - c4 / 4.60))
                      / ((wavel_mic / 0.046)**2. +
                         (0.046 / wavel_mic)**2. + 90.))

        # Third term accounting for the 2175 Angstrom extinction bump
        PAH_bump = c4 / ((wavel_mic / 0.2175)**2. +
                         (0.2175 / wavel_mic)**2. - 1.95)

        # In the rest frame
        Awavel_over_Av = UV_extinction + IR_vis_ext + PAH_bump

        # Set arbitrarily the negative extinction to zero
        w = np.where(Awavel_over_Av < 0.)
        Awavel_over_Av[w] = 0.

        # Applied a cut for wavelength below 700 angstrom
        # Useful when coupling with Xray data
        if Xcut:
            w = np.where(wavel_mic < 0.07)
            Awavel_over_Av[w] = 0.

        # Return optical depth due to dust reddening in funtion of wavelength
        Tau_dust = self.Av / 1.086 * Awavel_over_Av
        Trans_dust = np.exp(-Tau_dust)

        w = np.where(Trans_dust <= 0.)
        Trans_dust[w] = 0.
        w = np.where(Trans_dust > 1.)
        Trans_dust[w] = 1.

        return [Awavel_over_Av, Trans_dust]

    def Pei92(self, Rv='default', ext_law='smc', Xcut=False):
        """
        Extinction laws from Pei 1992 article

        Parameters
        ----------
        Rv: `float`, optional, default: default
            selective attenuation Rv = Av / E(B-V)
            if 'default' set values by default from article
            if a float is given, use this value instead

        ext_law: `str`
            type of extinction law to use.
            Choices: mw, lmc, smc

        Xcut: `boolean`, optional, default: False
             Whether to set attenuation to 0 for wavelength below 700 angstrom
             Useful when coupling with X-ray data

        Returns
        -------
        [Alambda_over_Ab, Trans_dust]

        Alambda_over_Ab : `array`
            atteanuation as a function of wavelength normalise by A_B
            (attenuation in B band)

        Trans_dust: `array`
            transmission through dust as a function of wavelength

        """

        wvl = self.wavelength * 1e-4 / (1 + self.z)
        if ext_law.lower() == 'smc':
            if Rv == 'default':
                Rv = 2.93
            a = [185, 27, 0.005, 0.010, 0.012, 0.03]
            wvl_ = [0.042, 0.08, 0.22, 9.7, 18, 25]
            b = [90, 5.50, -1.95, -1.95, -1.80, 0.0]
            n = [2.0, 4.0, 2.0, 2.0, 2.0, 2.0]

        elif ext_law.lower() == 'lmc':
            if Rv == 'default':
                Rv = 3.16
            a = [175, 19, 0.023, 0.005, 0.006, 0.02]
            wvl_ = [0.046, 0.08, 0.22, 9.7, 18, 25]
            b = [90, 5.5, -1.95, -1.95, -1.8, 0.0]
            n = [2.0, 4.5, 2.0, 2.0, 2.0, 2.0]

        elif ext_law.lower() == 'mw':
            if Rv == 'default':
                Rv = 3.08
            a = [165, 14, 0.045, 0.002, 0.002, 0.012]
            wvl_ = [0.046, 0.08, 0.22, 9.7, 18, 25]
            b = [90, 4.0, -1.95, -1.95, -1.8, 0.0]
            n = [2.0, 6.5, 2.0, 2.0, 2.0, 2.0]

        sums = np.zeros(len(wvl))
        for i in range(len(a)):
            sums += a[i] / ((wvl / wvl_[i])**n[i] +
                            (wvl_[i] / wvl)**n[i] + b[i])

        # Need to check whether extrapolation is needed
        # outside the range defined in Pei92
        Alambda_over_Ab = (1 / Rv + 1) * sums

        # Applied a cut for wavelength below 700 angstrom
        # Useful when coupling with Xray data
        if Xcut:
            w = np.where(wvl < 0.07)
            Alambda_over_Ab[w] = 0

        # Return optical depth due to dust reddening in funtion of wavelength
        Tau_dust = self.Av * Alambda_over_Ab / 1.086

        Trans_dust = np.exp(-Tau_dust)

        Trans_dust[Trans_dust < 0] = 0
        Trans_dust[Trans_dust > 1] = 1

        return [Alambda_over_Ab, Trans_dust]

    def gas_absorption(self, NHx=0.2):
        """
        Compute the optical depth due to gas absorption

        Parameters
        ----------
        NHx: `float`, optional, default: 0.2
             Metal column density from soft Xrays absortpion
             (in units 1e22 /cm2/mag), expressed in units of equivalent
             hydrogen column density assuming solar abundances.
             In Milky Way:
             NHx/Av = 1.7 to 2.2 1e21 cm-2/mag (default set to 2)

        Returns
        ------
        Trans_gas : `array`
             Transmission coefficient due to the gas absorption either
             occuring in our galaxy or within the host.

        """
        nus = cc.c_light_m_s / (self.wavelength * 1e-10)
        Tau_gas = np.zeros(len(nus))

        # Set NHx in units 1e22 /cm2/mag
        NHx *= 1e22

        # Define the equivalent HI column density depending whether we study
        # the host or our galaxy
        """
        if self.z == 0:
             NHI = self.Av * 1.79e21    # cm-2
        else:
             NHI = self.NHI_host()    # cm-2
        """
        NHI = self.Av * NHx

        for i in range(len(nus)):
            # photon frequency (Hz) in the rest frame
            nu = nus[i] * (1 + self.z)
            # photon energy (keV) in the rest frame
            E_kev = nu * cc.H_planck / (1e3 * cc.e_elec)
            E_kev2 = E_kev**2.
            E_kev3 = E_kev**3.

            # if E_kev < 13.6e-3:    #912 A (Lyman limit)
            #     c0=0; c1=0; c2=0
            # 41nm / 410A
            if E_kev < 0.030:
                coeffs = [0, 0, 0, 'H']
            # 12.4 nm
            elif E_kev < 0.100:
                coeffs = [17.3, 608.1, -2150, 'He']
            # 4.37 nm
            elif E_kev < 0.284:
                coeffs = [34.6, 267.9, -476.1, 'C']
            elif E_kev < 0.400:
                coeffs = [78.1, 18.8, 4.3, 'N']
            elif E_kev < 0.532:
                coeffs = [71.4, 66.8, -51.4, 'O']
            elif E_kev < 0.707:
                coeffs = [95.5, 145.8, -61.1, 'Fe-L']
            elif E_kev < 0.867:
                coeffs = [308.9, -380.6, 294.0, 'Ne']
            elif E_kev < 1.303:
                coeffs = [120.6, 169.3, -47.7, 'Mg']
            elif E_kev < 1.840:
                coeffs = [141.3, 146.8, -31.5, 'Si']
            elif E_kev < 2.471:
                coeffs = [202.7, 104.7, -17.0, 'S']
            elif E_kev < 3.210:
                coeffs = [342.7, 18.7, 0.0, 'Ar']
            elif E_kev < 4.038:
                coeffs = [352.2, 18.7, 0.0, 'Ca']
            elif E_kev < 7.111:
                coeffs = [433.9, -2.4, 0.75, 'Fe']
            elif E_kev < 8.331:
                coeffs = [629.0, 30.9, 0.0, 'Ni']
            # 124pm/1.24A
            elif E_kev < 10.:
                coeffs = [701.2, 25.2, 0.0, '...']
            else:
                coeffs = [0., 0., 0., 'None']

            # Figure of M&M
            sige3 = (coeffs[0] + coeffs[1] * E_kev + coeffs[2] * E_kev2)
            # cross section per hydrogen atom /cm2
            sig = sige3 / E_kev3 * 1e-24

            Tau_gas[i] = sig * NHI

        Trans_gas = np.exp(-Tau_gas)

        Trans_gas[Trans_gas < 1e-5] = 0
        Trans_gas[Trans_gas > 1] = 1

        return Trans_gas


# Kamil Pastwa
# kpastew@gmail.com

import matplotlib.pyplot as plt

# Problem fizyczny
k = 1.5
m = 2.1

# Warunki rozwiazania numerycznego
delta_t_list = [0.001, 0.1, 0.5]
x_0 = 1.75
v_0 = 0.0

t_0 = 0.0
t_end = 15.0

# tablica przechowujaca kolejne kroki czasowe - potrzebna do narysowania wykresu
time_lists = {}

# slowniki z tablicami polozen i predkosci wyliczonymi zmodyfikowanym algorytmem Eulera dla kolejnych krokow czasowych
mod_euler_x_lists = {}
mod_euler_v_lists = {}

# ... oraz algorytmem Verlet
verlet_x_lists = {}
verlet_v_lists = {}

for delta_t in delta_t_list:
    t = t_0
    x_mod_euler = x_0
    v_mod_euler = v_0
    x_verlet = x_0
    v_verlet = v_0

    time_list = [t_0]
    # tablice z polozeniami i predkosciami
    mod_euler_x_list = [x_0]
    mod_euler_v_list = [v_0]

    verlet_x_list = [x_0]
    verlet_v_list = [v_0]

    while t < t_end:

        # Zmodyfikowana metoda Eulera
        v_mod_euler += -k / m * mod_euler_x_list[-1] ** 3 * delta_t
        x_mod_euler += v_mod_euler * delta_t

        mod_euler_x_list.append(x_mod_euler)
        mod_euler_v_list.append(v_mod_euler)

        # Algorytm Verlet
        if t == t_0:
            x_verlet = x_mod_euler
        else:
            x_verlet = -verlet_x_list[-2] + 2 * verlet_x_list[-1] - (k / m * verlet_x_list[-1] ** 3) * delta_t ** 2

        v_verlet = (x_verlet - verlet_x_list[-1]) / delta_t

        verlet_x_list.append(x_verlet)
        verlet_v_list.append(v_verlet)

        t += delta_t
        time_list.append(t)

    time_lists[str(delta_t)] = time_list
    mod_euler_x_lists[str(delta_t)] = mod_euler_x_list
    mod_euler_v_lists[str(delta_t)] = mod_euler_v_list
    verlet_x_lists[str(delta_t)] = verlet_x_list
    verlet_v_lists[str(delta_t)] = verlet_v_list

def draw_chart(result_lists, title, ylabel):
    for delta_t in delta_t_list:
        plt.plot(time_lists[str(delta_t)], result_lists[str(delta_t)], label='dt = ' + str(delta_t))

    plt.title(title)
    plt.xlabel('czas [s]')
    plt.ylabel(ylabel)
    plt.legend()
    plt.show()

draw_chart(mod_euler_x_lists, title="Zmodyfikowany algorytm Eulera - wykres polozenia", ylabel="polozenie[m]")
draw_chart(mod_euler_v_lists, title="Zmodyfikowany algorytm Eulera - wykres predkosci", ylabel="predosc[m/s]")
draw_chart(verlet_x_lists, title="Algorytm Verlet - wykres polozenia", ylabel="polozenie[m]")
draw_chart(verlet_v_lists, title="Algorytm Verlet - wykres predkosci", ylabel="predosc[m/s]")


from conftest import QL_URL, crate_translator as translator
from datetime import datetime
from reporter.tests.utils import insert_test_data
from utils.common import assert_equal_time_index_arrays
import pytest
import requests
import pdb

entity_type = 'Room'
attr_name_1 = 'temperature'
attr_name_2 = 'pressure'
n_days = 6

def query_url(values=False):
    url = "{qlUrl}/types/{entityType}"
    if values:
        url += '/value'
    return url.format(
        qlUrl=QL_URL,
        entityType=entity_type
    )

@pytest.fixture()
def reporter_dataset(translator):
    insert_test_data(translator, [entity_type], n_entities=3, index_size=n_days)
    yield

def assert_1TNENA_response(obtained, expected, values_only=False):
    """
    Check API responses for 1TNENA
    """
    assert isinstance(obtained, dict)
    if not values_only:
        assert obtained['entityType'] == entity_type
        obt_entities_index = obtained['entities'][0]['index']
        exp_entities_index = expected['entities'][0]['index']
    else:
        obt_entities_index = obtained['values'][0]['index']
        exp_entities_index = expected['values'][0]['index']

    assert_equal_time_index_arrays(obt_entities_index, exp_entities_index)

    assert obtained == expected

def test_1TNENA_defaults(reporter_dataset):
    r = requests.get(query_url())
    assert r.status_code == 200, r.text

    # Assert Results
    expected_temperatures = list(range(n_days))
    expected_pressures = [t*10 for t in expected_temperatures]
    expected_index = [
        '1970-01-{:02}T00:00:00.000'.format(i+1) for i in expected_temperatures
    ]
    expected_attributes = [
        {
            'attrName': attr_name_2,
            'values' : expected_pressures
        },
        {
            'attrName': attr_name_1,
            'values' : expected_temperatures
        }
    ]
    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': expected_index
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': expected_index
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room2',
            'index': expected_index
        }
    ]
    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert_1TNENA_response(obtained, expected)

def test_1TNENA_one_entity(reporter_dataset):
    # Query
    entity_id = 'Room1'
    query_params = {
        'id': entity_id
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    obtained_data = r.json()
    assert isinstance(obtained_data, dict)

    expected_temperatures = list(range(n_days))
    expected_pressures = [t*10 for t in expected_temperatures]
    expected_index = [
        '1970-01-{:02}T00:00:00.000'.format(i+1) for i in expected_temperatures
    ]

    expected_attributes = [
        {
            'attrName': attr_name_2,
            'values' : expected_pressures
        },
        {
            'attrName': attr_name_1,
            'values' : expected_temperatures
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': expected_index
        }
    ]
    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }
    obtained = r.json()
    assert_1TNENA_response(obtained, expected)

def test_1TNENA_some_entities(reporter_dataset):
    # Query
    entity_id = 'Room0,Room2'
    query_params = {
        'id': entity_id
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    expected_temperatures = list(range(n_days))
    expected_pressures = [t*10 for t in expected_temperatures]
    expected_index = [
        '1970-01-{:02}T00:00:00.000'.format(i+1) for i in expected_temperatures
    ]

    expected_attributes = [
        {
            'attrName': attr_name_2,
            'values' : expected_pressures
        },
        {
            'attrName': attr_name_1,
            'values' : expected_temperatures
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': expected_index
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room2',
            'index': expected_index
        },
    ]

    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert_1TNENA_response(obtained, expected)

def test_1TNENA_values_defaults(reporter_dataset):
    # Query
    query_params = {
        'id': 'Room0,,Room1,RoomNotValid',  # -> validates to Room0,Room1.
    }
    r = requests.get(query_url(values=True), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    expected_temperatures = list(range(n_days))
    expected_pressures = [t*10 for t in expected_temperatures]
    expected_index = [
        '1970-01-{:02}T00:00:00.000'.format(i+1) for i in expected_temperatures
    ]

    expected_attributes = [
        {
            'attrName': attr_name_2,
            'values' : expected_pressures
        },
        {
            'attrName': attr_name_1,
            'values' : expected_temperatures
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': expected_index
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': expected_index
        },
    ]

    expected = {
        'values': expected_entities
    }

    obtained = r.json()
    assert_1TNENA_response(obtained, expected, values_only=True)

def test_not_found():
    query_params = {
        'id': 'RoomNotValid'
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 404, r.text
    assert r.json() == {
        "error": "Not Found",
        "description": "No records were found for such query."
    }

def test_weird_ids(reporter_dataset):
    """
    Invalid ids are ignored (provided at least one is valid to avoid 404).
    Empty values are ignored.
    Order of ids is preserved in response (e.g., Room1 first, Room0 later)
    """
    query_params = {
        'id': 'Room1,RoomNotValid,,Room0,',  # -> validates to Room0,Room1.
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    expected_temperatures = list(range(n_days))
    expected_pressures = [t*10 for t in expected_temperatures]
    expected_index = [
        '1970-01-{:02}T00:00:00.000'.format(i+1) for i in expected_temperatures
    ]

    expected_attributes = [
        {
            'attrName': attr_name_2,
            'values' : expected_pressures
        },
        {
            'attrName': attr_name_1,
            'values' : expected_temperatures
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': expected_index
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': expected_index
        },
    ]

    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert_1TNENA_response(obtained, expected)

def test_aggregation_is_per_instance(translator):
    """
    Attribute Aggregation works by default on a per-instance basis.
    Cross-instance aggregation not yet supported.
    It would change the shape of the response.
    """
    t = 'Room'
    insert_test_data(translator, [t], entity_id='Room0', index_size=3)
    insert_test_data(translator, [t], entity_id='Room1', index_size=3)

    query_params = {
        'attrs': 'temperature',
        'id': 'Room0,Room1',
        'aggrMethod': 'sum'
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    expected_attributes = [
        {
            'attrName': attr_name_1,
            'values' : [sum(range(3))]
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': ['', '']
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': ['', '']
        }
    ]

    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert isinstance(obtained, dict)
    assert obtained == expected

    # Index array in the response is the used fromDate and toDate
    query_params = {
        'attrs': 'temperature',
        'id': 'Room0,Room1',
        'aggrMethod': 'max',
        'fromDate': datetime(1970, 1, 1).isoformat(),
        'toDate': datetime(1970, 1, 6).isoformat(),
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    expected_attributes = [
        {
            'attrName': attr_name_1,
            'values' : [2]
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': ['1970-01-01T00:00:00', '1970-01-06T00:00:00']
        },
        {
            'attributes': expected_attributes,
            'entityId': 'Room1',
            'index': ['1970-01-01T00:00:00', '1970-01-06T00:00:00']
        }
    ]

    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert isinstance(obtained, dict)
    assert obtained == expected

@pytest.mark.parametrize("aggr_period, exp_index, ins_period", [
    ("day",    ['1970-01-01T00:00:00.000',
                '1970-01-02T00:00:00.000',
                '1970-01-03T00:00:00.000'], "hour"),
    ("hour",   ['1970-01-01T00:00:00.000',
                '1970-01-01T01:00:00.000',
                '1970-01-01T02:00:00.000'], "minute"),
    ("minute", ['1970-01-01T00:00:00.000',
                '1970-01-01T00:01:00.000',
                '1970-01-01T00:02:00.000'], "second"),
])
def test_1TNENA_aggrPeriod(translator, aggr_period, exp_index, ins_period):
    # Custom index to test aggrPeriod
    for i in exp_index:
        base = datetime.strptime(i, "%Y-%m-%dT%H:%M:%S.%f")
        insert_test_data(translator,
                         [entity_type],
                         index_size=5,
                         index_base=base,
                         index_period=ins_period)

    # aggrPeriod needs aggrMethod
    query_params = {
        'aggrPeriod': aggr_period,
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 400, r.text

    # Check aggregation with aggrPeriod
    query_params = {
        'attrs': 'temperature',
        'aggrMethod': 'sum',
        'aggrPeriod': aggr_period,
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 200, r.text

    # Assert Results
    exp_sum = 0 + 1 + 2 + 3 + 4

    expected_attributes = [
        {
            'attrName': attr_name_1,
            'values' : [exp_sum, exp_sum, exp_sum]
        }
    ]

    expected_entities = [
        {
            'attributes': expected_attributes,
            'entityId': 'Room0',
            'index': exp_index
        }
    ]

    expected = {
        'entities': expected_entities,
        'entityType': entity_type
    }

    obtained = r.json()
    assert isinstance(obtained, dict)
    assert_1TNENA_response(obtained, expected)

def test_1TNENA_aggrScope(reporter_dataset):
    # Notify users when not yet implemented
    query_params = {
        'aggrMethod': 'avg',
        'aggrScope': 'global',
    }
    r = requests.get(query_url(), params=query_params)
    assert r.status_code == 501, r.text


# -*- coding: utf-8 -*-

#==============================================================================
# Imports
#==============================================================================

import random as rnd
import networkx as nx
import matplotlib as mpl
import sys
from system_class_def import *
from agent_class_def import *
from function_def import *
from network_analysis import *

#==============================================================================
# Parameters
#==============================================================================

num_nodes = 100
num_edges = 3
num_ticks = 50
num_runs = 1
hazard_triggered = 1
num_affected = 20

# rescaled first component scores of hazard scenarios
HazardDict = {"Automation": 1.3,
              "Meter Reading": 0.89867133572128,
              "Remote Connect": 1.19725205261451,
              "Outage Detection": 0.7,
              "Power Theft": 0.976680716275362,
              "Pricing": 0.813628981657745,
              "Customer Information": 0.875750820478405,
              "Distributed Resources": 0.937800864934615,
              "Transmissions": 1.10726609072683,
              "Test Value": 1.0}

HazardName = "Automation"
HazardMultiplier = HazardDict[HazardName]

GovernmentMultiplier = .4
GovernmentDelay = hazard_triggered + 2
GovernmentStop = GovernmentDelay + 50

MediaMultiplier = 1.2
MediaDelay = 2
MediaReportingIntensity = (num_affected/float(num_nodes))*2

#==============================================================================
# Simulation
#==============================================================================

# uncommment below code and comment out network creation further down in
# order to run simulation with same starting conditions

#social_network = barabasi_albert(Agent, num_nodes, num_edges)
#for node in social_network.nodes():
#    node.init_neighbors(social_network)

for run in range(num_runs):

    # network creation
    social_network = barabasi_albert(Agent, num_nodes, num_edges)
    for node in social_network.nodes():
        node.init_neighbors(social_network)

#    uncomment below code to collect before-run data on network ties and
#    Euclidean distance matrix of differences in risk perceptions
#    network_analysis(social_network, "before")

    Sim = Simulation()
    SimState = SystemState()

    Sim.init_network(social_network)
    Sim.init_institutions(Media, Government, GovernmentMultiplier,
                          Hazard, HazardName, HazardMultiplier)
    Sim.init_parameters(num_ticks, hazard_triggered, num_affected,
                        MediaDelay, MediaMultiplier,
                        MediaReportingIntensity, GovernmentStop,
                        GovernmentDelay,
                        False)

    # record data at beginning of run before any tick behaviour
    SimState.record_data(Sim.report_state())

    for tick in range(num_ticks):
        Sim.tick(tick)
        SimState.record_data(Sim.report_state())

    # after each run, save data to file named according to run number
    SimState.save_data("%s" % run)

    if num_runs > 1:
        for node in social_network.nodes():
            node.re_initialise()
    else:
        d = Sim.report_rs_sent_received()
#        uncomment below code to record Euclidean distance data after
#        a simulation run
#        network_analysis(social_network, "after")

# Saving the parameters of the current scenario
with open("scenario_parameters.txt", "w") as outfile:
    outfile.write("num_nodes: %s" % num_nodes + '\n')
    outfile.write("num_edges: %s" % num_edges + '\n')
    outfile.write("num_ticks: %s" % num_ticks + '\n')
    outfile.write("num_runs: %s" % num_runs + '\n')
    outfile.write("hazard_triggered: %s" % hazard_triggered + '\n')
    outfile.write("num_affected: %s" % num_affected + '\n')
    outfile.write("HazardMultiplier: %s" % HazardMultiplier + '\n')
    outfile.write("HazardName: %s" % HazardName + '\n')
    outfile.write("GovernmentMultiplier: %s" % GovernmentMultiplier + '\n')
    outfile.write("GovernmentDelay: %s" % GovernmentDelay + '\n')
    outfile.write("GovernmentStop: %s" % GovernmentStop + '\n')
    outfile.write("MediaMultiplier: %s" % MediaMultiplier + '\n')
    outfile.write("MediaDelay: %s" % MediaDelay +  '\n')
    outfile.write("MediaReportingIntensity: %s" % MediaReportingIntensity + '\n')