# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/profile/ProfileUtils.py
import BigWorld
from debug_utils import LOG_ERROR, LOG_DEBUG
from gui.shared.formatters import text_styles
from gui.shared.utils.functions import getClanRoleString
from helpers import i18n
from gui.shared import g_itemsCache
from gui.shared.gui_items.dossier.stats import _MaxVehicleStatsBlock
from gui.Scaleform.locale.PROFILE import PROFILE
from gui.Scaleform.locale.MENU import MENU
from helpers.i18n import makeString

class HeaderItemsTypes(object):
    VALUE_PREFIX = 'value_'
    COMMON = 'common'
    RATIO = 'ratio'
    VALUES = 'values'

class ProfileUtils(object):
    UNAVAILABLE_VALUE = -1
    UNAVAILABLE_SYMBOL = '--'
    VIEW_TYPE_TABLES = 0
    VIEW_TYPE_CHARTS = 1

    def __init__(self):
        super(ProfileUtils, self).__init__()

    @staticmethod
    def packProfileDossierInfo(targetData):
        outcome = ProfileUtils.packProfileCommonInfo(targetData)
        vehicle = g_itemsCache.items.getItemByCD(targetData.getMaxXpVehicle())
        outcome['maxXPByVehicle'] = vehicle.shortUserName if vehicle is not None else ''
        outcome['marksOfMastery'] = targetData.getMarksOfMastery()[3]
        outcome['totalUserVehiclesCount'] = len(targetData.getVehicles())
        return outcome

    @staticmethod
    def packProfileCommonInfo(targetData):
        outcome = {}
        outcome['battlesCount'] = targetData.getBattlesCount()
        outcome['lossesCount'] = targetData.getLossesCount()
        outcome['winsCount'] = targetData.getWinsCount()
        outcome['hitsEfficiency'] = ProfileUtils.getValueOrUnavailable(targetData.getHitsEfficiency())
        outcome['maxXP'] = targetData.getMaxXp()
        outcome['avgXP'] = ProfileUtils.getValueOrUnavailable(targetData.getAvgXP())
        return outcome

    @staticmethod
    def getIconPath(icon):
        return '../maps/icons/library/dossier/' + icon

    @staticmethod
    def formatFloatPercent(value):
        if value != ProfileUtils.UNAVAILABLE_VALUE:
            value = value * 100
            value = BigWorld.wg_getNiceNumberFormat(value) + '%'
        return str(value)

    @staticmethod
    def getFormattedWinsEfficiency(targetData):
        winsEfficiency = targetData.getWinsEfficiency()
        formattedWinsEfficiency = ProfileUtils.formatFloatPercent(ProfileUtils.getValueOrUnavailable(winsEfficiency))
        return formattedWinsEfficiency

    @staticmethod
    def formatEfficiency(coeff2, valueReceiveFunction):
        if coeff2 > 0:
            return BigWorld.wg_getNiceNumberFormat(valueReceiveFunction())
        else:
            return ProfileUtils.UNAVAILABLE_VALUE

    @staticmethod
    def packLditItemData(text, description, tooltip, icon, additionalData = None, viewType = HeaderItemsTypes.COMMON):
        finalText = text
        enabled = True
        if text == -1 or text == '-1':
            enabled = False
            finalText = ProfileUtils.UNAVAILABLE_SYMBOL
        return {'type': viewType,
         'text': finalText,
         'description': i18n.makeString(description),
         'iconPath': ProfileUtils.getIconPath(icon),
         'tooltip': tooltip,
         'additionalData': additionalData,
         'enabled': enabled}

    @staticmethod
    def getValueOrUnavailable(targetValue):
        if targetValue is not None:
            return targetValue
        else:
            return ProfileUtils.UNAVAILABLE_VALUE

    @staticmethod
    def getDrawCount(battlesCount, lossesCount, winsCount):
        return battlesCount - (winsCount + lossesCount)

    @staticmethod
    def getLabelDataObject(label, data):
        return {'label': i18n.makeString(label),
         'data': data}

    @staticmethod
    def getLabelViewTypeDataObject(label, data, viewType):
        if viewType != ProfileUtils.VIEW_TYPE_TABLES and viewType != ProfileUtils.VIEW_TYPE_CHARTS:
            LOG_ERROR('Unknown view type', viewType)
            return None
        else:
            result = ProfileUtils.getLabelDataObject(label, data)
            result['viewType'] = viewType
            return result

    @staticmethod
    def createToolTipData(bodyParamsList):
        result = {}
        bodyData = None
        if bodyParamsList is not None:
            bodyData = {}
            for i in range(0, len(bodyParamsList)):
                bodyData[HeaderItemsTypes.VALUE_PREFIX + str(i)] = text_styles.titleFont(str(bodyParamsList[i]))

        result['body'] = bodyData
        result['header'] = {}
        result['note'] = None
        return result

    @staticmethod
    def getTotalBattlesHeaderParam(targetData, description, tooltip):
        battlesCount = targetData.getBattlesCount()
        lossesCount = targetData.getLossesCount()
        winsCount = targetData.getWinsCount()
        drawsCount = ProfileUtils.getDrawCount(battlesCount, lossesCount, winsCount)
        drawsStr = BigWorld.wg_getIntegralFormat(drawsCount) if drawsCount >= 0 else ProfileUtils.UNAVAILABLE_SYMBOL
        battlesToolTipData = [BigWorld.wg_getIntegralFormat(winsCount), BigWorld.wg_getIntegralFormat(lossesCount), drawsStr]
        return ProfileUtils.packLditItemData(BigWorld.wg_getIntegralFormat(battlesCount), description, tooltip, 'battles40x32.png', {'tooltipData': ProfileUtils.createToolTipData(battlesToolTipData)}, HeaderItemsTypes.VALUES)

    @staticmethod
    def getVehicleRecordTooltipData(getValueMethod):
        return ProfileUtils.getRecordTooltipDataByVehicle(g_itemsCache.items.getItemByCD(getValueMethod()))

    @staticmethod
    def getRecordTooltipDataByVehicle(vehicle):
        if vehicle is not None:
            return ProfileUtils.createToolTipData([vehicle.shortUserName])
        else:
            return ProfileUtils.createToolTipData(None)

    @staticmethod
    def getAvailableValueStr(value):
        if value != -1:
            return value
        return ProfileUtils.UNAVAILABLE_SYMBOL

    @staticmethod
    def getAvgDamageBlockedValue(targetData):
        value = ProfileUtils.formatEfficiency(targetData.getBattlesCountVer3(), targetData.getAvgDamageBlocked)
        return ProfileUtils.getAvailableValueStr(value)

class DetailedStatisticsUtils(object):

    @staticmethod
    def getDetailedDataObject(label, value, tooltip, tooltipData = None):
        dataObject = ProfileUtils.getLabelDataObject(label, value)
        dataObject['tooltip'] = tooltip
        dataObject['tooltipData'] = tooltipData
        return dataObject

    @staticmethod
    def getStatistics(targetData, isCurrentuser):
        battlesCount = targetData.getBattlesCount()
        lossesCount = targetData.getLossesCount()
        winsCount = targetData.getWinsCount()
        drawsCount = battlesCount - (winsCount + lossesCount)
        drawsStr = BigWorld.wg_getIntegralFormat(drawsCount) if drawsCount >= 0 else ProfileUtils.UNAVAILABLE_SYMBOL
        battlesToolTipData = [BigWorld.wg_getIntegralFormat(winsCount), BigWorld.wg_getIntegralFormat(lossesCount), drawsStr]
        formattedBattlesCount = BigWorld.wg_getIntegralFormat(battlesCount)
        winsEfficiency = targetData.getWinsEfficiency()
        formattedWinsEfficiency = ProfileUtils.formatFloatPercent(ProfileUtils.getValueOrUnavailable(winsEfficiency))
        dmgDealt = targetData.getDamageDealt()
        dmgReceived = targetData.getDamageReceived()
        damageBlockedByArmor = targetData.getDamageBlockedByArmor()
        potentialDamageReceived = targetData.getPotentialDamageReceived()
        pResDmg = potentialDamageReceived - damageBlockedByArmor
        avgXP = ProfileUtils.getValueOrUnavailable(targetData.getAvgXP())
        avgDmg = ProfileUtils.getValueOrUnavailable(targetData.getAvgDamage())
        maxXP = targetData.getMaxXp()
        maxXP_formattedStr = BigWorld.wg_getIntegralFormat(maxXP)
        maxXpVehicle = None
        maxDamageVehicle = None
        maxFragsVehicle = None
        if isinstance(targetData, _MaxVehicleStatsBlock):
            maxXpVehicle = g_itemsCache.items.getItemByCD(targetData.getMaxXpVehicle())
            maxDamageVehicle = g_itemsCache.items.getItemByCD(targetData.getMaxDamageVehicle())
            maxFragsVehicle = g_itemsCache.items.getItemByCD(targetData.getMaxFragsVehicle())
        maxExpToolTipData = ProfileUtils.getRecordTooltipDataByVehicle(maxXpVehicle)
        maxDestroyedToolTipData = ProfileUtils.getRecordTooltipDataByVehicle(maxFragsVehicle)
        maxDmg = targetData.getMaxDamage()
        maxDamageToolTipData = None
        if targetData.getBattlesCountVer3() > 0:
            maxDmg_formattedStr = BigWorld.wg_getIntegralFormat(maxDmg)
            maxDamageToolTipData = ProfileUtils.getRecordTooltipDataByVehicle(maxDamageVehicle)
            maxDamageTooltip = PROFILE.PROFILE_PARAMS_TOOLTIP_MAXDAMAGE
        else:
            maxDmg_formattedStr = ProfileUtils.UNAVAILABLE_VALUE
            maxDamageTooltip = PROFILE.PROFILE_PARAMS_TOOLTIP_UNAVAILABLEMAXDAMAGE
        return (ProfileUtils.getLabelDataObject(PROFILE.SECTION_STATISTICS_BODYPARAMS_LABEL_COMMON, [DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_TOTALBATTLES, formattedBattlesCount, PROFILE.PROFILE_PARAMS_TOOLTIP_BATTLESCOUNT, ProfileUtils.createToolTipData(battlesToolTipData)),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_TOTALWINS, formattedWinsEfficiency, PROFILE.PROFILE_PARAMS_TOOLTIP_WINS),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_SURVIVAL, ProfileUtils.formatFloatPercent(ProfileUtils.getValueOrUnavailable(targetData.getSurvivalEfficiency())), PROFILE.PROFILE_PARAMS_TOOLTIP_SURVIVAL),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_HITS, ProfileUtils.formatFloatPercent(ProfileUtils.getValueOrUnavailable(targetData.getHitsEfficiency())), PROFILE.PROFILE_PARAMS_TOOLTIP_HITS),
          None,
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_DAMAGECOEFFICIENT, ProfileUtils.formatEfficiency(dmgReceived, targetData.getDamageEfficiency), PROFILE.PROFILE_PARAMS_TOOLTIP_DAMAGECOEFF, ProfileUtils.createToolTipData((BigWorld.wg_getIntegralFormat(dmgDealt), BigWorld.wg_getIntegralFormat(dmgReceived)))),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_DESTRUCTIONCOEFFICIENT, ProfileUtils.formatEfficiency(targetData.getDeathsCount(), targetData.getFragsEfficiency), PROFILE.PROFILE_PARAMS_TOOLTIP_DESTROYCOEFF, ProfileUtils.createToolTipData((BigWorld.wg_getIntegralFormat(targetData.getFragsCount()), BigWorld.wg_getIntegralFormat(targetData.getDeathsCount())))),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_ARMORUSING, ProfileUtils.formatEfficiency(pResDmg, targetData.getArmorUsingEfficiency), PROFILE.PROFILE_PARAMS_TOOLTIP_ARMORUSING, ProfileUtils.createToolTipData([ProfileUtils.getAvgDamageBlockedValue(targetData)]))]), ProfileUtils.getLabelDataObject(PROFILE.SECTION_STATISTICS_BODYPARAMS_LABEL_AVERAGE, [DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_AVGEXPERIENCE_SHORT, BigWorld.wg_getIntegralFormat(avgXP), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGEX_SHORT),
          None,
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_AVGDAMAGE, BigWorld.wg_getIntegralFormat(avgDmg), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGDMG_SHORT),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_AVGRECEIVEDDAMAGE, BigWorld.wg_getIntegralFormat(ProfileUtils.getValueOrUnavailable(targetData.getAvgDamageReceived())), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGRECEIVEDDAMAGE),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_AVGASSISTEDDAMAGE_SHORTSELF if isCurrentuser else PROFILE.SECTION_STATISTICS_SCORES_AVGASSISTEDDAMAGE_SHORTOTHER, ProfileUtils.formatEfficiency(targetData.getBattlesCountVer2(), targetData.getDamageAssistedEfficiency), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGASSISTEDDAMAGE_SHORTSELF if isCurrentuser else PROFILE.PROFILE_PARAMS_TOOLTIP_AVGASSISTEDDAMAGE_SHORTOTHER),
          None,
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_AVGDETECTEDENEMIES, BigWorld.wg_getNiceNumberFormat(ProfileUtils.getValueOrUnavailable(targetData.getAvgEnemiesSpotted())), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGDETECTEDENEMIES),
          DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_AVGDESTROYEDVEHICLES, BigWorld.wg_getNiceNumberFormat(ProfileUtils.getValueOrUnavailable(targetData.getAvgFrags())), PROFILE.PROFILE_PARAMS_TOOLTIP_AVGDESTROYEDVEHICLES)]), ProfileUtils.getLabelDataObject(PROFILE.SECTION_STATISTICS_BODYPARAMS_LABEL_RECORD, [DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_MAXEXPERIENCE, maxXP_formattedStr, PROFILE.PROFILE_PARAMS_TOOLTIP_MAXEXP, maxExpToolTipData), DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_SCORES_MAXDAMAGE, maxDmg_formattedStr, maxDamageTooltip, maxDamageToolTipData), DetailedStatisticsUtils.getDetailedDataObject(PROFILE.SECTION_STATISTICS_DETAILED_MAXDESTROYEDVEHICLES, BigWorld.wg_getIntegralFormat(targetData.getMaxFrags()), PROFILE.PROFILE_PARAMS_TOOLTIP_MAXDESTROYED, maxDestroyedToolTipData)]))

def getProfileCommonInfo(userName, dossier, clanInfo, clanEmblemId):
    clanNameProp = 'clanName'
    clanNameDescrProp = 'clanNameDescr'
    clanJoinTimeProp = 'clanJoinTime'
    clanPositionProp = 'clanPosition'
    clanEmblemProp = 'clanEmblem'
    import cgi
    lastBattleTimeUserString = None
    if dossier['total']['lastBattleTime']:
        lbt = dossier['total']['lastBattleTime']
        lastBattleTimeUserString = '%s %s' % (BigWorld.wg_getLongDateFormat(lbt), BigWorld.wg_getShortTimeFormat(lbt))
    value = {'name': userName,
     'registrationDate': '%s' % BigWorld.wg_getLongDateFormat(dossier['total']['creationTime']),
     'lastBattleDate': lastBattleTimeUserString,
     clanNameProp: '',
     clanNameDescrProp: '',
     clanJoinTimeProp: '',
     clanPositionProp: '',
     clanEmblemProp: 'img://' + clanEmblemId if clanEmblemId is not None else None}

    def getGoldFmt(str):
        return str

    if clanInfo is not None:
        value[clanNameProp] = cgi.escape(clanInfo[1])
        value[clanNameDescrProp] = cgi.escape(clanInfo[0])
        value[clanJoinTimeProp] = makeString(MENU.PROFILE_HEADER_CLAN_JOINDATE) % getGoldFmt(BigWorld.wg_getLongDateFormat(clanInfo[4]))
        value[clanPositionProp] = getGoldFmt(getClanRoleString(clanInfo[3]))
    return value


"""
Tests for the band difference model evaluation workflow.
"""

from __future__ import division, print_function, unicode_literals

import pytest
import numpy as np

@pytest.fixture
def band_difference_builder(configure, sample):  # pylint: disable=unused-argument
    """
    Create inputs for the band difference workflow.
    """
    from aiida.orm import DataFactory
    from aiida.orm.code import Code
    from aiida_tbextraction.model_evaluation import BandDifferenceModelEvaluation
    from aiida_bands_inspect.io import read_bands

    builder = BandDifferenceModelEvaluation.get_builder()
    builder.tbmodels_code = Code.get_from_string('tbmodels')
    builder.bands_inspect_code = Code.get_from_string('bands_inspect')
    builder.tb_model = DataFactory('singlefile')(
        file=sample('silicon/model.hdf5')
    )
    builder.reference_bands = read_bands(sample('silicon/bands.hdf5'))

    return builder

def test_bandevaluation(configure_with_daemon, band_difference_builder):  # pylint: disable=unused-argument,redefined-outer-name
    """
    Run the band evaluation workflow.
    """
    from aiida.work.launch import run
    builder = band_difference_builder
    output = run(builder)
    assert np.isclose(output['cost_value'].value, 0.)

def test_bandevaluation_launchmany(
    configure_with_daemon,  # pylint: disable=unused-argument
    band_difference_builder,  # pylint: disable=redefined-outer-name
    wait_for
):
    """
    Launch many band evaluation workflows, and check that the right number of workflows was executed.
    """
    from aiida.work import submit
    from aiida.orm import CalculationFactory
    from aiida.orm.querybuilder import QueryBuilder
    qb1 = QueryBuilder()
    qb2 = QueryBuilder()
    qb1.append(CalculationFactory('tbmodels.eigenvals'))
    qb2.append(CalculationFactory('bands_inspect.difference'))

    initial_count1 = qb1.count()
    initial_count2 = qb2.count()
    num_workflows = 100

    builder = band_difference_builder
    pks = []
    for _ in range(num_workflows):
        pks.append(submit(builder).pk)

    for process_id in pks:
        wait_for(process_id)

    end_count1 = qb1.count()
    end_count2 = qb2.count()
    assert end_count1 - initial_count1 == num_workflows
    assert end_count2 - initial_count2 == num_workflows


# -*- coding: utf-8 -*-
from time import sleep
from data.const import commands
from data.maps import *
from data.items import items
from data import messages
import pickle

class Player(object):
    def __init__(self, name):
        self.money = 50
        self.name = name
        self.level = 1
        self.map_x = self.map_y = 15
        self.zycie, self.max_hp = 50, 100
        self.mana, self.max_mp = 50, 100
        self.stats = {
            "siła": 15,
            "zwinność": 15,
            "pancerz": 15,
            "magia": 15,
        }
        self.equipped = [
            items["stalowy miecz"],
            items["diamentowa zbroja"],
        ]
        self.bag = [
            items["kamienny miecz"],
            items["jabłko"],
        ]

    # TO DELETE #
    def add_item(self, *name):
        try:
            item_name = " ".join(name)
            item = items[item_name.lower()]
            self.bag.append(item)
            print("{grn}Przedmiot {name} został dodany{rst}".format(grn=TextOptions.txtgrn,
                                                                    name=item_name,
                                                                    rst=TextOptions.txtrst))
        except KeyError:
            print("{red}Nie ma takiego przedmiotu{rst}".format(red=TextOptions.txtred,
                                                               rst=TextOptions.txtrst))

    # TO DELETE #
    def get_pos(self):
        print("x = %d, y = %d" % (self.map_x, self.map_y))

    def get_info(self):
        print(messages.PLAYER_INFO % (self.name, self.level))
        print("Posiadasz {} złota".format(self.money))

    def get_stats(self):
        for stat, val in self.stats.items():
            print("{} - {}".format(stat, val))

    def look_around(self):
        for direction, y, x in (('północ', -1, 0), ('wschód', 0, 1), ('południe', 1, 0), ('zachód', 0, -1)):
            print(messages.LOOK_AT % direction, end='')
            sleep(.5)
            if self.map_y + y >= 0 and \
               self.map_y + y <= MAP_HEIGHT-1 and \
               self.map_x + x >= 0 and \
               self.map_x + x <= MAP_WIDTH-1 and \
               map_grid[self.map_y+y][self.map_x+x] == "x":
                try:
                    m = Map(self.map_x+x, self.map_y+y)
                    print("Znajdujesz %s" % m.name)
                except AttributeError:
                    print(messages.FIND_UNKNOWN_PLACE)
            else:
                print()

    def go(self, direction):
        moved = 0
        keywords = {
            "west": ("left", "lewo", "west", "zachod", "zachód", "w"),
            "east": ("right", "prawo", "east", "wschod", "wschód", "e"),
            "north": ("up", "góra", "north", "północ", "polnoc", "n"),
            "south": ("down", "dół", "south", "południe", "poludnie", "s"),
        }
        if direction.lower() in keywords["west"] and self.map_x > 0 and map_grid[self.map_y][self.map_x-1] == "x":
            self.map_x -= 1
            moved = 1
        elif direction.lower() in keywords["east"] and \
                        self.map_x < MAP_WIDTH-1 and map_grid[self.map_y][self.map_x+1] == "x":
            self.map_x += 1
            moved = 1
        elif direction.lower() in keywords["north"] and self.map_y > 0 and map_grid[self.map_y-1][self.map_x] == "x":
            self.map_y -= 1
            moved = 1
        elif direction.lower() in keywords["south"] and self.map_y < MAP_HEIGHT-1 and \
                        map_grid[self.map_y+1][self.map_x] == "x":
            self.map_y += 1
            moved = 1
        elif direction not in keywords["west"] and dir not in keywords["east"] and \
                        dir not in keywords["north"] and dir not in keywords["south"]:
            print("Gdzie?")
        else:
            print(messages.NO_WAY)
        print(Map(self.map_x, self.map_y).possible_moves())
        if moved:
            return "self.update_map"

    def print_equipment(self):
        print("Ekwipunek")
        for item in self.equipped:
            print("{}[ZAŁOŻONE]{} {} - {}".format(TextOptions.txtgrn, TextOptions.txtrst, item.name, item.desc))
            for k, v in item.attrs.items():
                print("\t{}: {}".format(k, v))
        for item in self.bag:
            print("{} - {}".format(item.name, item.desc))
            if item.type == "consumable":
                print("\tilość: {}".format(item.count))
            for k, v in item.attrs.items():
                print("\t{}: {}".format(k, v))

    def eat(self, item=None):
        if item:
            for index, i in enumerate(self.bag):
                if i.name.lower() == item.lower() and i.type == "consumable":
                    print("Mmm..")
                    for attr, value in i.attrs.items():
                        setattr(self, attr, getattr(self, attr) + value)
                        print("+{} {}".format(value, attr))
                    if self.zycie > self.max_hp:
                        self.zycie = self.max_hp
                    if self.mana > self.max_mp:
                        self.mana = self.max_mp
                    i.count -= 1
                    if i.count < 1:
                        self.bag.pop(index)
                    break
            else:
                print(messages.DONT_HAVE)
        else:
            print("Hm?")

class Game(object):
    def __init__(self):
        self.player = Player(input(messages.CREATE_PLAYER))
        self.npc = NPC_LIST
        self.running = True
        self.map = Map(self.player.map_x, self.player.map_y)
        self.map.get_info()
        self.loop()

    def loop(self):
        while self.running:
            try:
                command, *args = input("{}<{}hp {}mp {}x {}y>{} ".format(TextOptions.bakblu,
                                                                             self.player.zycie,
                                                                             self.player.mana,
                                                                             self.player.map_x,
                                                                             self.player.map_y,
                                                                             TextOptions.txtrst)).split()
                command = commands[command].split(".")
                if command[0] == "self":
                    getattr(self, command[1])(*args)
                else:
                    try:
                        result = getattr(getattr(self, command[0]), command[1])(*args)
                    except (KeyError, ValueError):
                        result = None
                    if result:
                        func, *args = result.split()
                        func = func.split(".")
                        if func[0] == "self":
                            getattr(self, func[1])(*args)
                        else:
                            getattr(getattr(self, func[0]), func[1])(*args)
            except (KeyError, ValueError):
                print("Nie rozumiem")

    def update_map(self):
        self.map = Map(self.player.map_x, self.player.map_y)
        self.map.get_info()

    def save(self, output=None):
        import os
        if not output:
            output = "./saves/%s" % self.player.name
        else:
            output = "./saves/"+output
        try:
            os.mkdir("./saves")
        except OSError:
            pass
        if os.path.isfile(output):
            print(messages.FILE_EXISTS)
            if input("> ").lower() != "tak":
                print(messages.CANCEL)
                return None
        with open(output, mode="wb") as f:
            pickle.dump(self, f)
            print(messages.FILE_SAVED % output)

    def talk_to_npc(self, *name):
        try:
            name = " ".join(name)
            for npc in self.map.npcs:
                if npc.name.lower() == name.lower():
                    self.player = self.npc[name.lower()].talk(self.player)
            else:
                raise KeyError
        except KeyError:
            print("Nie ma tu takiej osoby")

    def quit_game(self):
        import sys
        sys.exit()


import wave,time
from pyaudio import PyAudio, paInt16

framerate = 16000  # 采样率
num_samples = 2000  # 采样点
channels = 1  # 声道
sampwidth = 2  # 采样宽度2bytes
FILEPATH = 'speech.wav'

def save_wave_file(filepath, data):
    wf = wave.open(filepath, 'wb')
    wf.setnchannels(channels)
    wf.setsampwidth(sampwidth)
    wf.setframerate(framerate)
    wf.writeframes(b''.join(data))
    wf.close()

# 录音
def my_record():
    pa = PyAudio()
    # 打开一个新的音频stream
    stream = pa.open(format=paInt16, channels=channels,
                     rate=framerate, input=True, frames_per_buffer=num_samples)
    my_buf = []  # 存放录音数据

    t = time.time()
    print('正在录音...')

    while time.time() < t + 4:  # 设置录音时间（秒）
        # 循环read，每次read 2000frames
        string_audio_data = stream.read(num_samples)
        my_buf.append(string_audio_data)
    print('录音结束.')
    save_wave_file(FILEPATH, my_buf)
    stream.close()
my_record()


import pandas as pd
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt

df = pd.read_csv('vehicles.csv')
print('pycharm')
print(df.columns)
sns_plot = sns.lmplot(df.columns[0], df.columns[1], data=df, fit_reg=False)
sns_plot.axes[0,0].set_ylim(0,)
sns_plot.axes[0,0].set_xlim(0,)
sns_plot.savefig("scaterplot_vehicle.png",bbox_inches='tight')
plt.show()

sns_plot2 = sns.distplot(df['Current fleet'], bins=20, kde=False, rug=True).get_figure()
plt.show()
sns_plot2.savefig("current_fleet.png",bbox_inches='tight')

sns_plot3 = sns.distplot(df['New Fleet'].dropna(), bins=20, kde=False, rug=True).get_figure()
plt.show()
sns_plot3.savefig("new_fleet.png",bbox_inches='tight')


# Reports extension for Review Board.
from django.db.models import Q
from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib.auth.models import User
from django.http import HttpRequest
from reviewboard.extensions.base import Extension
from reviewboard.extensions.hooks import DashboardHook, URLHook
from reviewboard.scmtools.models import Repository

class UserBasedDashboardHook(DashboardHook):
    def __init__(self, extension, entries):
        super(DashboardHook, self).__init__(extension)

        self.report_details = {
            'not_closed_with_shipit': {
                'label': 'Not closed with Shipit',
                'url': settings.SITE_ROOT +
                "customreports/?name=not_closed_with_shipit",
            },
            'not_reviewed': {
                'label': 'Not Reviewed',
                'url': settings.SITE_ROOT +
                "customreports/?name=not_reviewed",

            },
            'not_reviewed_by_me': {
                'label': 'Not Reviewed By Me',
                'url': settings.SITE_ROOT +
                "customreports/?name=not_reviewed_by_me",
            }
        }

    def __getattribute__(self, name):
        """ Get Attribute from module

        At this point, Reviewboard extensions dont provide a way to get
        Request object during every page load. The Dashboard hook gets
        its entries when its loaded and uses it for all pages. This
        method uses a (ugly) hack to get the stacktrace from the current
        page and get the request object(and hence the user object) so I
        can do user specific things. This will change in the future when
        RB provides per-page hooks (as in NavigationBarHook)
        """
        if name == 'entries':
            import sys
            f = sys._getframe()
            username = None
            while f:
                request = f.f_locals.get('request')
                if isinstance(request, HttpRequest):
                    username = request.user.username
                    break
                f = f.f_back

            if len(self.extension.settings['selected_reports']) == 0:
                return

            # Set the basic details for the hooks (minus subitems)
            entries = [
                {
                    'label': 'Reports',
                    'url': '#',
                    'subitems': []
                }
            ]

            # Populate the subitems with what reports have been configured
            for report in self.extension.settings['selected_reports']:
                if report in self.report_details:
                    entries[0]['subitems'].append(self.report_details[report])

            user = User.objects.filter(username=username)
            repositories = Repository.objects.filter(Q(public=1) |
                                                     Q(users__in=user) |
                                                     Q(review_groups__users__in=user))

            if len(repositories) == 0:
                return entries
            else:
                if 'filter_by_repo' in \
                        self.extension.settings['selected_reports']:
                    filter_entries = {
                        'label': 'Filter by Repository',
                        'url': '#',
                    }
                    subitems = []
                    for repo in repositories:
                        subitem = {'label': str(repo.name),
                                   'url': settings.SITE_ROOT +
                                   "customreports/?name=filter_by_repo&object=" +
                                   str(repo.id)
                                   }
                        subitems.append(subitem)

                    filter_entries['subitems'] = subitems

                    entries.append(filter_entries)

                return entries
        else:
            return DashboardHook.__getattribute__(self, name)

class CustomReportsExtension(Extension):
    is_configurable = True

    def __init__(self, *args, **kwargs):
        super(CustomReportsExtension, self).__init__(*args, **kwargs)

        self.url_hook = URLHook(self, patterns('',
                                (r'^customreports/',
                                 include('rbcustomreports.urls'))))

        self.dashboard_hook = UserBasedDashboardHook(self, entries=[])


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

from datetime import datetime
from pytz import timezone

import babel
from odoo import api, fields, models, tools, _
from datetime import date, datetime, time, timedelta
from odoo.exceptions import UserError
from odoo.osv import expression

class HrPayslip(models.Model):
    _inherit = 'hr.payslip'

    settlement = fields.Boolean(string='Settlement')
    settlemen_date = fields.Date(string='Settlemen date', readonly=True, required=False,
        default=lambda self: fields.Date.to_string(date.today().replace(day=1)), states={'draft': [('readonly', False)]})
    reason_liquidation = fields.Selection([
            ('1', 'TERMINACIÓN DE CONTRATO'),
            ('2', 'SEPARACIÓN VOLUNTARIA'),
            ('3', 'ABANDONO DE EMPLEO'),
            ('4', 'DEFUNCIÓN'),
            ('7', 'AUSENTISMOS'),
            ('8', 'RESICIÓN DE CONTRATO'),
            ('9', 'JUBILACIÓN'),
            ('A', 'PENSIÓN'),
            ('5', 'CLAUSURA'),
            ('6', 'OTROS'),
            ],
            string='Reason for liquidation',
            required=False,
            states={'draft': [('readonly', False)]})
    agreement_employee = fields.Boolean(string='Agreement with the employee')
    amount_agreement = fields.Float('Amount of the agreement', required=False)
    indemnify_employee = fields.Boolean(string='Indemnify the employee')
    compensation_20 = fields.Boolean(string='I will pay the compensation of 20 days per year worked?')

    previous_contract_date = fields.Date('Previous Contract Date', related="contract_id.previous_contract_date", help="Start date of the previous contract for antiquity.")
    date_start = fields.Date('Start Date', required=True, default=fields.Date.today,
        help="Start date of the contract.", related="contract_id.date_start")
    date_end = fields.Date('End Date',
        help="End date of the contract", related="contract_id.date_end")
    years_antiquity = fields.Integer(string='Antiquity', related="contract_id.years_antiquity")
    days_rest = fields.Integer(string='Días de antiguedad ultimo año', related="contract_id.days_rest")
    type_contract = fields.Selection(string='Tipo de contrato', related="contract_id.type_id.type")

    @api.onchange('complete_name')
    def _compute_complete_name(self):
        for name in self:
            complete_name = name.name
            if name.last_name:
                complete_name += ' ' + name.last_name
            if name.last_name:
                complete_name += ' ' + name.mothers_last_name
            name.complete_name = complete_name

    @api.onchange('indemnify_employee','agreement_employee')
    def _compute_complete_name(self):
        for settlement in self:
            if settlement.indemnify_employee:
                settlement.agreement_employee = False
                settlement.amount_agreement = 0
            else:
                settlement.compensation_20 = False
            if settlement.agreement_employee:
                settlement.indemnify_employee = False
                settlement.compensation_20 = False
            else:
                settlement.amount_agreement = 0

    @api.multi
    def print_settlement_report(self):
        payroll_dic = {}
        data={
            'payroll_data':payroll_dic
            }
        return self.env.ref('payroll_mexico.action_report_settlement_template').report_action(self, {})

class HrPayrollStructure(models.Model):
    _inherit = 'hr.payroll.structure'

    settlement = fields.Boolean(string='Settlement structure?')
    payroll_type = fields.Selection([
            ('ordinary_payroll', 'Ordinary Payroll'),
            ('extraordinary_payroll', 'Extraordinary Payroll')],
            string='Payroll Type',
            required=True,)


from django.shortcuts import render
from gallery.models import MenDem

# Create your views here.
def gallery_index(request):
    men_dem = MenDem.objects.all()
    context = {
        'men_dem': men_dem
    }
    return render(request, 'gallery_index.html', context)

def man_details(request, pk):
    man = MenDem.objects.get(pk=pk)
    context = {
        'man': man
    }
    return render(request, 'man_details.html', context)


# coding=utf-8
import logging

import os
import telebot

from kzn_bot.sites import (
    Kzn, presets, UserSearchData, Filters, user_filters_cache)

logger = logging.getLogger(__name__)

BOT = GOD = None

MARKUP_HIDE = telebot.types.ReplyKeyboardRemove()

def initialize_bot(token_path):
    if not os.path.exists(token_path):
        raise ValueError('No token file found! get token from bot father')

    with open(token_path) as fh:
        bot_father_token = fh.readline().strip()
        god = fh.readline().strip()

    if BOT:
        try:
            BOT.stop_polling()
        except Exception as e:
            logger.exception(e)

    bot = telebot.TeleBot(bot_father_token, threaded=False)

    @bot.message_handler(commands=Filters.keys)
    def number_command(message):
        @user_filters_cache.filter_saver
        def handler(message, key):
            user_id = message.chat.id
            value = message.text[:Filters.max_value_len]
            log_msg = u'New key filter for user {u}: {k}={v}'.format(
                k=key, v=value, u=message.chat.first_name)
            logger.info(log_msg)

            filters = user_filters_cache[user_id]
            if filters:
                cached_user_filter = user_filters_cache.get_last(user_id)
                cached_user_filter.update(**{key: value})
            else:
                user_filters_cache.add(user_id, **{key: value})

            if GOD:
                BOT.send_message(GOD, log_msg)
                BOT.send_message(GOD, '; '.join(
                    [str(k) for k in user_filters_cache._data.keys()]))

        key = message.text.strip(u'/')
        BOT.send_message(message.chat.id,
                         Filters.description.get(key,
                                                 u'Не распознанная команда'))

        callback_fn = lambda msg: handler(msg, key)
        BOT.register_next_step_handler(message, callback_fn)

    @bot.message_handler(commands=['start'])
    @user_filters_cache.filter_saver
    def start_command(message):
        user_filters_cache.clear(message.chat.id)
        logger.debug(
            'New user %d : %s' % (message.chat.id, message.chat.first_name))
        BOT.send_message(message.chat.id,
                         u'Сейчас пришлю последние 10 документов')
        if GOD:
            BOT.send_message(
                GOD,
                u'New user {0}, {1}'.format(message.chat.first_name,
                                            unicode(message.chat.id)))

    @bot.message_handler(commands=['clear'])
    @user_filters_cache.filter_saver
    def clear_command(message):
        e = "Нет фильтрации"
        user_filters_cache.clear(message.chat.id)
        logger.debug('User cleared filters: %d' % message.chat.id)
        BOT.send_message(message.chat.id,
                         str(user_filters_cache[message.chat.id]) or e)

    @bot.message_handler(commands=['list'])
    def list_command(message):
        e = "Нет фильтрации"
        BOT.send_message(message.chat.id,
                         str(user_filters_cache[message.chat.id]) or e)
        logger.debug(str(message.chat.id) + ': ' +
                     str(user_filters_cache[message.chat.id]))

    @bot.message_handler(commands=['add'])
    @user_filters_cache.filter_saver
    def add_command(message):
        if len(user_filters_cache[message.chat.id]) >= UserSearchData.max_filters:
            msg = (u'Достигнуто максимально допустимое количество '
                   u'фильтров: %d' % UserSearchData.max_filters)
        else:
            user_filters_cache.add(message.chat.id)
            msg = str(user_filters_cache[message.chat.id])
        logger.debug(msg)
        BOT.send_message(message.chat.id, msg)

    @bot.message_handler(commands=['presets'])
    def presets_command(message):
        @user_filters_cache.filter_saver
        def callback(msg):
            filter_name = msg.text
            if filter_name in presets:
                user_id = msg.chat.id
                user_filters_cache.add(user_id, **presets[filter_name])

                user_msg = u'Фильтр добавлен: {0}'.format(filter_name)
            else:
                user_msg = u'Неверно задан фильтр: {0}'.format(filter_name)

            markup_hide = MARKUP_HIDE
            BOT.send_message(message.chat.id, user_msg,
                             reply_markup=markup_hide)
            logger.debug(user_msg + u' ' + msg.chat.first_name)
            if GOD:
                BOT.send_message(GOD, user_msg + u' ' + msg.chat.first_name)

        markup = telebot.types.ReplyKeyboardMarkup(one_time_keyboard=True,
                                                   selective=True)
        markup.row(*presets.keys())

        msg = BOT.send_message(message.chat.id, u"Выберите фильтр",
                               reply_markup=markup)

        BOT.register_next_step_handler(msg, callback)

    return bot, god

def emergency_message(message, default=None):
    if not os.path.exists('token'):
        raise ValueError('No token file found! get token from bot father')

    with open('token') as fh:
        bot_father_token = fh.readline().strip()
        god = fh.readline().strip()

    if god:
        msg = message or default or 'Error occurred! Save the bot'
        try:
            bot = telebot.TeleBot(bot_father_token, threaded=False)
            bot.send_message(god, msg)

        except Exception as e:
            logger.critical(e)
    else:
        logger.critical('No god persists')

def send_data(user_id, **kwargs):
    for url, title in Kzn.get_new_doc(user_id, **kwargs):
        msg = title.replace(u'\n', u' ').strip() + u'\n' + url
        try:
            BOT.send_message(user_id, msg)
        except Exception as e:
            logger.critical(e)
            emergency_message(unicode(user_id)+u' '+unicode(e),
                              'unrecognized error')

        else:
            logger.debug('user "%s" got message: %s' % (user_id, msg))


import os
import random

from datetime import datetime as dt, timedelta as td

from core_modules.helpers import get_pynode_digest_int
from core_modules.chunk_storage import ChunkStorage
from core_modules.helpers import hex_to_chunkid, chunkid_to_hex
from core_modules.settings import NetWorkSettings
from core_modules.logger import initlogging

class Chunk:
    def __init__(self, chunkid):
        if type(chunkid) != int:
            raise ValueError("chunkid is not int!")

        self.chunkid = chunkid
        self.verified = False
        self.is_ours = False
        self.last_fetch_time = None

    def __str__(self):
        return "chunkid: %s, verified: %s, is_ours: %s" % (chunkid_to_hex(self.chunkid),
                                                           self.verified, self.is_ours)

class ChunkManager:
    def __init__(self, nodenum, nodeid, basedir, aliasmanager):
        # initialize logger
        # IMPORTANT: we must ALWAYS use self.__logger.* for logging and not logging.*,
        # since we need instance-level logging
        self.__logger = initlogging('', __name__)

        # our node id
        self.__nodeid = nodeid

        # the actual storage layer
        self.__storagedir = os.path.join(basedir, "chunkdata")
        self.__storage = ChunkStorage(self.__storagedir, mode=0o0700)

        # alias manager
        self.__alias_manager = aliasmanager

        # databases we keep
        self.__chunk_db = {}
        self.__missing_chunks = {}

        # tmp storage
        self.__tmpstoragedir = os.path.join(basedir, "tmpstorage")
        self.__tmpstorage = ChunkStorage(self.__tmpstoragedir, mode=0o0700)

        # run other initializations
        self.__initialize()

    def __str__(self):
        return "%s" % self.__nodeid

    def __initialize(self):
        self.__logger.debug("Initializing")

        # initializations
        self.__recalculate_ownership_of_all_chunks()
        self.__verify_all_files_on_disk()
        # self.__purge_orphaned_storage_entries()
        # self.__purge_orphaned_files()

    def __verify_all_files_on_disk(self):
        self.__logger.debug("Verifying local files in %s" % self.__storagedir)

        # reads the filesystem and fills our DB of chunks we have
        for chunkid in self.__storage.index():
            if not self.__storage.verify(chunkid):
                self.__logger.warning("Verify failed for local file at boot, deleting: %s" % chunkid_to_hex(chunkid))
                self.__storage.delete(chunkid)

    def __recalculate_ownership_of_all_chunks(self):
        for chunk, chunkid in self.__chunk_db.items():
            self.__update_chunk_ownership(chunk)

    def __update_chunk_ownership(self, chunk):
        # if even a single alias says we own this chunk, we do
        actual_chunk_is_ours = self.__alias_manager.we_own_chunk(chunk.chunkid)

        if actual_chunk_is_ours:
            # maintain file db
            # self.__logger.debug("Chunk %s is now OWNED" % chunkid_to_hex(chunk.chunkid))
            chunk.is_ours = True

            # fetch if missing
            if not chunk.verified:
                self.__fetch_chunk_locally_or_mark_missing(chunk)
        else:
            # self.__logger.debug("Chunk %s is now DISOWNED" % chunkid_to_hex(chunk.chunkid))
            chunk.is_ours = False

            # TODO: we can purge chunk if we no longer need it

        return actual_chunk_is_ours

    def __mark_chunk_as_missing(self, chunk):
        # self.__logger.warning("Chunk %s missing, added to todolist" % chunkid_to_hex(chunk.chunkid))
        chunk.verified = False
        self.__missing_chunks[chunk.chunkid] = chunk

    def __store_missing_chunk(self, chunk, data):
        # store chunk
        self.__storage.put(chunk.chunkid, data)
        chunk.verified = True

        if self.__missing_chunks.get(chunk.chunkid) is not None:
            del self.__missing_chunks[chunk.chunkid]

        # self.__logger.debug("Chunk %s is loaded" % chunkid)

    def __fetch_chunk_locally_or_mark_missing(self, chunk):
        # if we don't have it or it's not verified for some reason, fetch it
        if not chunk.verified:
            data = None

            # do we have it locally? - this can happen if we just booted up
            if self.__storage.verify(chunk.chunkid):
                # self.__logger.debug("Found chunk %s locally" % chunkid_to_hex(chunk.chunkid))
                data = self.__storage.get(chunk.chunkid)

            # do we have it in tmp storage?
            if data is None:
                if self.__tmpstorage.verify(chunk.chunkid):
                    data = self.__tmpstorage.get(chunk.chunkid)
                    # self.__logger.debug("Found chunk %s in temporary storage" % chunkid_to_hex(chunk.chunkid))

            # did we find the data?
            if data is not None:
                self.__store_missing_chunk(chunk, data)
            else:
                # we need to fetch the chunk using RPC
                self.__mark_chunk_as_missing(chunk)

    def __purge_orphaned_storage_entries(self):
        self.__logger.info("Purging orphaned files")
        for chunkid, chunk in self.__chunk_db.items():
            if not chunk.is_ours or not chunk.verified:
                self.__storage.delete(chunkid)

    def __purge_orphaned_files(self):
        self.__logger.debug("Purging local files in %s" % self.__storagedir)

        # reads the filesystem and fills our DB of chunks we have
        for chunkid in self.__storage.index():
            chunk = self.__chunk_db.get(chunkid)

            if chunk is None:
                # we don't know what this file is (perhaps it used to belong to us but not anymore)
                self.__storage.delete(chunkid)

        self.__logger.debug("Discovered %s files in local storage" % len(self.__chunk_db))

    def __get_or_create_chunk(self, chunkid):
        created = False
        if self.__chunk_db.get(chunkid) is None:
            created = True
            self.__chunk_db[chunkid] = Chunk(chunkid=chunkid)

        chunk = self.__chunk_db[chunkid]
        return created, chunk

    # START - CHUNK FETCHER
    def get_missing_chunks_num(self):
        return len(self.__missing_chunks)

    def get_random_missing_chunks(self, sample_size):
        now = dt.now()

        missing_chunks = []
        for chunkid, chunk in self.__missing_chunks.items():
            # if chunk has been fetched previously
            if chunk.last_fetch_time is not None:
                # and CHUNK_REFETCH_INTERVAL seconds have elapsed since
                elapsed = (now - chunk.last_fetch_time).total_seconds()
                if elapsed < NetWorkSettings.CHUNK_REFETCH_INTERVAL:
                    self.__logger.debug("Not refetching chunk: %s, elapsed: %s" % (chunkid_to_hex(chunkid), elapsed))
                    continue

            missing_chunks.append(chunkid)

        # If sample size is less than the missing chunk list, we return it all. random.sample() errors out
        # when sample_size < len(items). This also conveniently handles the case when the list is empty
        if len(missing_chunks) <= sample_size:
            return missing_chunks
        else:
            return random.sample(missing_chunks, sample_size)

    def failed_to_fetch_chunk(self, chunkid):
        chunk = self.__chunk_db.get(chunkid)
        if chunk is None:
            # seems like this chunk got deleted while we were fetching it
            return
        self.__logger.warning("Failed to fetch chunk %s" % chunkid_to_hex(chunkid))
        chunk.last_fetch_time = dt.now()

    def store_missing_chunk(self, chunkid, data):
        chunk = self.__chunk_db.get(chunkid)
        if chunk is None:
            # seems like this chunk got deleted while we were fetching it
            return

        self.__store_missing_chunk(chunk, data)
    # END - CHUNK FETCHER

    def select_random_chunks_we_have(self, n):
        chunks_we_have = []
        for chunk_id, chunk in self.__chunk_db.items():
            if chunk.verified and chunk.is_ours:
                chunks_we_have.append(chunk)

        if len(chunks_we_have) == 0:
            # we have no chunks yet
            return []

        return random.sample(chunks_we_have, n)

    def update_mn_list(self, added, removed):
        if len(added) + len(removed) > 0:
            if self.__nodeid in removed:
                # TODO: figure out what to do here
                self.__logger.warning("I am removed from the MN list, aborting %s" % self.__nodeid)
                # return

            self.__logger.info("MN list has changed -> added: %s, removed: %s" % (added, removed))
            self.dump_internal_stats("DB STAT Before")
            self.__recalculate_ownership_of_all_chunks()
            # self.__purge_orphaned_storage_entries()
            # self.__purge_orphaned_db_entries()
            self.dump_internal_stats("DB STAT After")

    def add_new_chunks(self, chunks):
        # self.dump_internal_stats("DB STAT Before")
        for chunkid in chunks:
            created, chunk = self.__get_or_create_chunk(chunkid)
            self.__update_chunk_ownership(chunk)
        # self.dump_internal_stats("DB STAT After")

    def store_chunk_in_temp_storage(self, chunkid, data):
        if chunkid != get_pynode_digest_int(data):
            raise ValueError("data does not match chunkid!")

        self.__tmpstorage.put(chunkid, data)

    def get_chunk_if_we_have_it(self, chunkid):
        if not self.__alias_manager.we_own_chunk(chunkid):
            raise ValueError("We don't own this chunk!")

        chunk = self.__chunk_db.get(chunkid)
        if chunk is None:
            self.__logger.info("This chunk is missing from our database, is it in any valid tickets? %s" %
                               chunkid_to_hex(chunkid))
            return None

        return self.get_chunk(chunk)

    def get_chunk(self, chunk):
        # try to find chunk in chunkstorage
        if chunk.verified:
            return self.__storage.get(chunk.chunkid)

        # fall back to try and find chunk in tmpstorage
        #  - for tickets that are registered through us, but not final on the blockchain yet, this is how we bootstrap
        #  - we are also graceful and can return chunks that are not ours...
        if self.__tmpstorage.verify(chunk.chunkid):
            return self.__tmpstorage.get(chunk.chunkid)

        # we have failed to find the chunk, mark it as missing
        self.__mark_chunk_as_missing(chunk)

    # DEBUG FUNCTIONS
    def dump_internal_stats(self, msg=""):
        if msg == "":
            prefix = ""
        else:
            prefix = "%s -> " % msg
        tried_fetch_but_failed = [x.chunkid for x in self.__missing_chunks.values() if x.last_fetch_time is not None]
        self.__logger.debug("%schunk_db: %s, missing_chunks: %s, failed_fetch: %s" % (
            prefix, len(self.__chunk_db), len(self.__missing_chunks), len(tried_fetch_but_failed)))

    def dump_file_db(self):
        for k, v in self.__chunk_db.items():
            self.__logger.debug("FILE %s: %s" % (chunkid_to_hex(k), v))
            self.__storage.get(k)
    # END


import numpy as np
import matplotlib.pyplot as pl
import hazel
import h5py
import sys

filename = sys.argv[1]
x_coordinate = int(sys.argv[2])
y_coordinate = int(sys.argv[3])
x_range = int(sys.argv[4])
y_range = int(sys.argv[5])
l_left = int(sys.argv[6])
l_right = int(sys.argv[7])
local = int(sys.argv[8])
output = sys.argv[9]

#Here we read the data from the cube:
from astropy.io import fits

dataset = fits.open(filename)
stokes = dataset[0].data
ll = dataset[1].data

n_wvl = l_right - l_left

if (local):
	loc_continuum = np.amax(stokes[:,:,0,l_left:l_right],axis=2)
	stokes /= loc_continuum[:,:,np.newaxis,np.newaxis]

else:
	qs = np.mean(np.amax(stokes[:,:,0,l_left:l_right],axis=2))
	stokes[:,:,:,:] /= qs

# Save the data for the inversion
# First the wavelength axis
np.savetxt('10830_gregor.wavelength', ll[l_left:l_right], header='lambda')

# Now the wavelength dependent weights
f = open('10830_gregor.weights', 'w')
f.write('# WeightI WeightQ WeightU WeightV\n')
for i in range(n_wvl):
    f.write('1.0    1.0   1.0   1.0\n')
f.close()

noise = 2E-3
# And the Stokes parameters
n_pixel = x_range*y_range

stokes_3d = stokes[x_coordinate:x_coordinate+x_range,y_coordinate:y_coordinate+y_range,:,l_left:l_right]
stokes_3d = stokes_3d.reshape(x_range*y_range,4,n_wvl)
stokes_3d = stokes_3d.transpose(0,2,1)
sigma_3d = np.zeros((n_pixel,n_wvl,4), dtype=np.float64)
sigma_3d[:,:,:] = noise
los_3d = np.zeros((n_pixel,3), dtype=np.float64)
los_3d[:,0] = 0.0
los_3d[:,1] = 0.0
los_3d[:,2] = 90.0
boundary_3d = np.zeros((n_pixel,n_wvl,4), dtype=np.float64)
boundary_3d[:,:,0] = 1.0

f = h5py.File(output, 'w')
db_stokes = f.create_dataset('stokes', stokes_3d.shape, dtype=np.float64)
db_sigma = f.create_dataset('sigma', sigma_3d.shape, dtype=np.float64)
db_los = f.create_dataset('LOS', los_3d.shape, dtype=np.float64)
db_boundary = f.create_dataset('boundary', boundary_3d.shape, dtype=np.float64)
db_stokes[:] = stokes_3d
db_sigma[:] = sigma_3d
db_los[:] = los_3d
db_boundary[:] = boundary_3d
f.close()


import logging
from comm import db

logger = logging.getLogger('app')

class tableModule(object):
    def __init__(self, tablename):
        self.tablename = tablename
        self.init_table_mate()

    # 初始化表属性
    def init_table_mate(self):
        # 初始化列信息
        self.colnames, self.coltypes = self.get_col_info()
        self.meta = dict(zip(self.colnames, self.coltypes))
        # 构建SQL语句段
        colkey_str = ','.join(self.colnames) # col1,col2,col3
        colval_str = '"%(' + ')s","%('.join(self.colnames) + ')s"'  # "%(col1)s","%(col2)s","%(col3)s"
        self.sql_query_default = 'select %s from %s' % (colkey_str, self.tablename)
        self.sql_insert_default = 'insert into %s(%s) values(%s)' % (self.tablename, colkey_str, colval_str)
        self.sql_delete_default = 'delete from %s ' % self.tablename
        self.sql_query_count = 'select count(*) as total_count from %s ' % self.tablename

    # 表结构属性
    def get_col_info(self):
        db_connection = db.get_normal_connect()
        cursor = db_connection.cursor()
        colname_list = []
        coltype_list = []
        try:
            cursor.execute('select * from %s where zid=0' % self.tablename)
        except Exception as err:
            logger.exception('error to init %s:%s' % (self.tablename, str(err)))
        else:
            fields =cursor.description
            for field in fields:
                colname_list.append(field[0])
                coltype_list.append(field[1])
        cursor.close()
        db.resume_normal_connect(db_connection)
        return colname_list, coltype_list

    # 获取insert语句
    def sql_insert_form_data(self, data):
        data_unit = data
        new_col_list = data_unit.keys()
        # new_col_list = [col for col in self.colnames if col in data_unit.keys()]
        colnamestr = '`' + '`,`'.join(new_col_list) + '`'
        colvalstr = '"%(' + ')s","%('.join(new_col_list) + ')s"'
        sql_insert = "insert into %s (%s) values(%s)" % (self.tablename, colnamestr, colvalstr)
        return sql_insert

    # 获取update语句
    def sql_update_from_data(self, data, recid):
        print(data)
        col_list = data.keys()
        new_col_list = []
        for col_name in col_list:
            new_col_list.append('%s="%%(%s)s"' % (col_name, col_name))
        sql_update = "update %s set %s WHERE zid=%s " % (self.tablename, ','.join(new_col_list), recid)
        return sql_update

    # 获取delete语句
    def sql_delete_form_data(self, recid):
        sql_delete = '%s where zid=%s' % (self.sql_delete_default, recid)
        return sql_delete


"""
onnxruntimetriton

Offers the class InferenceSession which can be used as a drop-in replacement for the ONNX Runtime
session object.

"""

import tritonclient.http as tritonhttpclient
import numpy as np

class NodeArg:
    def __init__(self, name, shape):
        self.name = name
        self.shape = shape

class InferenceSession:
    def __init__(self, path_or_bytes, sess_options=None, providers=[]):
        self.client = tritonhttpclient.InferenceServerClient("localhost:8000")
        model_metadata = self.client.get_model_metadata(model_name=path_or_bytes)

        self.request_count = 0
        self.model_name = path_or_bytes
        self.inputs = []
        self.outputs = []
        self.dtype_mapping = {}

        for (src, dest) in (
            (model_metadata["inputs"], self.inputs),
            (model_metadata["outputs"], self.outputs),
        ):
            for element in src:
                dest.append(NodeArg(element["name"], element["shape"]))
                self.dtype_mapping[element["name"]] = element["datatype"]

        self.triton_enabled = True

    def get_inputs(self):
        return self.inputs

    def get_outputs(self):
        return self.outputs

    def run(self, output_names, input_feed, run_options=None):
        inputs = []
        for key, val in input_feed.items():
            val = np.expand_dims(val, axis=0)
            input = tritonhttpclient.InferInput(key, val.shape, self.dtype_mapping[key])
            input.set_data_from_numpy(val)
            inputs.append(input)

        outputs = []

        for output_name in output_names:
            output = tritonhttpclient.InferRequestedOutput(output_name)
            outputs.append(output)

        res = self.client.async_infer(
            self.model_name, inputs, request_id=str(self.request_count), outputs=outputs
        )
        res = res.get_result()
        results = []
        for output_name in output_names:
            results.append(res.as_numpy(output_name))

        return results


## -*- encoding: utf-8 -*-
import os
import sys
from setuptools import setup
from codecs import open # To open the README file with proper encoding
from setuptools.command.test import test as TestCommand # for tests

# Get information from separate files (README, VERSION)
def readfile(filename):
    with open(filename,  encoding='utf-8') as f:
        return f.read()

# For the tests
class SageTest(TestCommand):
    def run_tests(self):
        errno = os.system("sage -t --force-lib sage_widget_adapters")
        if errno != 0:
            sys.exit(1)
        errno = os.system("sage -t --force-lib sage_combinat_widgets")
        if errno != 0:
            sys.exit(1)

setup(
    name = "sage-combinat-widgets",
    version = readfile("VERSION"),
    description='Jupyter widgets for SAGE Combinat',
    long_description = readfile("README.rst"),
    url='https://github.com/sagemath/sage-combinat-widgets',
    author='Odile Bénassy, Nicolas M. Thiéry',
    author_email='odile.benassy@u-psud.fr',
    license='GPLv3+',
    classifiers=[
      # How mature is this project? Common values are
      #   3 - Alpha
      #   4 - Beta
      #   5 - Production/Stable
      'Development Status :: 3 - Alpha',
      'Intended Audience :: Science/Research',
      'Topic :: Scientific/Engineering :: Mathematics',
      'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
      'Programming Language :: Python :: 2.7',
    ], # classifiers list: https://pypi.python.org/pypi?%3Aaction=list_classifiers
    keywords = "SageMath widget combinatorics",
    packages = ['sage_combinat_widgets', 'sage_widget_adapters', 'sage_widget_adapters.combinat', 'sage_widget_adapters.graphs', 'sage_widget_adapters.matrix'],
    cmdclass = {'test': SageTest}, # adding a special setup command for tests
    install_requires = ['ipywidgets']
)


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

# group_func.py
# Created by Eric W Bridgeford on 2016-04-03.
# Email: ebridge2@jhu.edu

import warnings

warnings.simplefilter("ignore")
import pickle
from ndmg.stats.qa_mri import qa_mri as mqa
import numpy as np
import ndmg.utils as mgu
import os
import plotly.offline as pyo
from plotly.tools import FigureFactory as ff
from ndmg.utils import loadGraphs
from ndmg.stats.qa_graphs import compute_metrics
from ndmg.stats.qa_graphs_plotting import make_panel_plot
import networkx as nx
from ndmg.stats.plotly_helper import *

class group_func(object):
    def __init__(self, basedir, outdir, atlas=None, dataset=None):
        """
        A class for group level quality control.

        **Positional Arguments:**
            - basedir:
                - the ndmg-formatted functional outputs.
                  should have a qa/ folder contained within it.
            - outdir:
                - the directory to place all group level quality control.
            - dataset:
                - an optional parameter for the name of the dataset
                  to be present in the quality control output filenames.
        """
        print(atlas)
        self.ndmgdir = basedir
        self.qadir = "{}/qa".format(self.ndmgdir)
        self.outdir = outdir
        self.conn_dir = "{}/connectomes".format(self.ndmgdir)
        self.dataset = dataset
        self.atlas = atlas
        (self.qa_files, self.subs) = self.get_qa_files()
        self.connectomes = self.get_connectomes()
        self.qa_objects = self.load_qa()
        self.group_level_analysis()
        pass

    def get_qa_files(self):
        """
        A function to load the relevant quality assessment files,
        for all the subjects we have in our study, given a properly-formatted
        ndmg functional directory.
        """
        qa_files = []
        subs = []
        for sub in os.listdir(self.qadir):
            sub_qa = "{}/{}/{}_stats.pkl".format(self.qadir, sub, sub)
            # if the files exists, add it to our qa_files
            if os.path.isfile(sub_qa):
                qa_files.append(sub_qa)
                subs.append(sub)
        return (qa_files, subs)

    def get_connectomes(self):
        """
        A function to load the relevant connectomes for all of the subjects
        for each parcellation we have.
        """
        connectomes = {}
        for label in os.listdir(self.conn_dir):
            print(label)
            this_label = []
            label_dir = "{}/{}".format(self.conn_dir, label)
            for connectome in os.listdir(label_dir):
                conn_path = "{}/{}".format(label_dir, connectome)
                if os.path.isfile(conn_path):
                    this_label.append(conn_path)
            connectomes[label] = this_label
        return connectomes

    def load_qa(self):
        """
        A function to load the quality control objects.
        """
        qa_objects = []
        for qa_file in self.qa_files:
            # load the qa objects as qa_mri objects
            qa_objects.append(mqa.load(qa_file))
        return qa_objects

    def group_level_analysis(self):
        """
        A function to perform group level analysis after loading the
        functional qa objects properly.
        """
        self.group_reg()
        self.group_motion()

    def group_reg(self):
        """
        A function that performs group level registration quality control.
        """
        regdir = "{}/{}".format(self.outdir, "reg")
        cmd = "mkdir -p {}".format(regdir)
        mgu.execute_cmd(cmd)

        self_reg_sc = []
        temp_reg_sc = []
        cnr = []
        snr = []
        for sub in self.qa_objects:
            self_reg_sc.append(sub.self_reg_sc)
            temp_reg_sc.append(sub.temp_reg_sc)
            cnr.append(sub.cnr)
            snr.append(sub.snr)

        fig_cnr = plot_rugdensity(cnr)
        fig_snr = plot_rugdensity(snr)
        fig_sreg = plot_rugdensity(self_reg_sc)
        fig_treg = plot_rugdensity(temp_reg_sc)

        figs = [fig_cnr, fig_snr, fig_sreg, fig_treg]
        names = [
            "temporal Contrast to Noise Ratio",
            "temporal Signal to Noise Ratio",
            "Self Registration Score",
            "Template Registration Score",
        ]
        ylab = ["Density", "Density", "Density", "Density"]
        xlab = ["Ratio", "Ratio", "Score", "Score"]
        traces = [fig_to_trace(fig) for fig in figs]

        fname_multi = "registration_qa.html"
        # if a dataset name is provided, add it to the name
        if self.dataset is not None:
            fname_multi = "{}_{}".format(self.dataset, fname_multi)
        fname_multi = "{}/{}".format(regdir, fname_multi)
        multi = traces_to_panels(traces, names=names, ylabs=ylab, xlabs=xlab)
        pyo.plot(multi, validate=False, filename=fname_multi)
        pass

    def group_motion(self):
        """
        A function that performs group level motion corrective quality control.
        """
        mcdir = "{}/{}".format(self.outdir, "mc")
        cmd = "mkdir -p {}".format(mcdir)
        mgu.execute_cmd(cmd)

        trans_abs = np.zeros((len(self.qa_objects)))
        trans_rel = np.zeros((len(self.qa_objects)))
        trans_abs_gt = np.zeros((len(self.qa_objects)))
        trans_rel_gt = np.zeros((len(self.qa_objects)))

        FD_mean = [sub.fd_mean for sub in self.qa_objects]
        FD_max = [sub.fd_max for sub in self.qa_objects]
        FD_gt_100um = [sub.fd_gt_100um for sub in self.qa_objects]
        FD_gt_200um = [sub.fd_gt_200um for sub in self.qa_objects]

        fig_mean = plot_rugdensity(FD_mean)
        fig_max = plot_rugdensity(FD_max)
        fig_gt_100um = plot_rugdensity(FD_gt_100um)
        fig_gt_200um = plot_rugdensity(FD_gt_200um)

        figs = [fig_mean, fig_max, fig_gt_100um, fig_gt_200um]
        names = [
            "Average FD KDE",
            "Max FD KDE",
            "Number of FD > 0.1 mm KDE",
            "Number of FD > 0.2 mm KDE",
        ]
        ylab = ["Density", "Density", "Density", "Density"]
        xlab = [
            "Average FD (mm)",
            "Average Motion (mm)",
            "Number of Volumes",
            "Number of Volumes",
        ]
        traces = [fig_to_trace(fig) for fig in figs]

        fname_multi = "motion_correction.html"

        # if a dataset name is provided, add it to the name
        if self.dataset is not None:
            fname_multi = "{}_{}".format(self.dataset, fname_multi)
        fname_multi = "{}/{}".format(mcdir, fname_multi)

        multi = traces_to_panels(traces, names=names, ylabs=ylab, xlabs=xlab)
        pyo.plot(multi, validate=False, filename=fname_multi)
        pass


# Kim de Bie 11077379
# This Python script loads csv data into JSON objects.
# I previously used (an altered) version of this code for my 'Heuristieken' project.

import csv
import json
# Returns a dictionary with area names as keys and neighbours as values
def load_json(filename):

    # open provided file
    file_csv = open(filename, 'r')

    # create field names
    fieldnames = ("country", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2014")

    # initiate reader for the csv file
    reader = csv.DictReader(file_csv, fieldnames)

    # create list
    data = []

    # read all rows of csv_file and save them as lists (within list)
    for row in reader:
        data.append(row)

    # turn into JSON and save as textfile
    with open("jsondataGNI.json", 'wb') as outfile:
        json.dump(data, outfile)

# call the load_json function
json_data = load_json("GNIgrowth2005-14.csv")


from framework_extensions.utils.abstract_service import AbstractService
from framework_extensions.screensot_tools.conf_lib.Constants    import TT_Constants
from framework_extensions.bulk_strategies_duplicator.utils.populate_bulk_strategy_content import populate_entity_campaign_strategy_service,populate_strategy_info_from_service
from framework_tests.utilities import session_helper
import logging
import xml.etree.ElementTree as ET
import requests

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class BulkStrategyToolService(AbstractService):
#     def __init__(self,driver):
#         super(ScreenshotToolService, self).__init__(driver)
    def svc_call_strategy_subobject(self, **kwargs):
        logger.info('Start reading svc_call_strategy_subobject...')
        payload_data=kwargs['payload_data']
        strategy_id=kwargs['strategy_id']
        cookies=kwargs['cookies']
        #session_helper.t1_login_session(self,TT_Constants['Base_URL'])
        response=requests.post('http://pi.mediamath.com/tools/bulk_strategy_duplicator/strategy/%s/subobjects'%strategy_id,'POST',payload_data,cookies = cookies)
        logger.info('Finishing reading svc_call_strategy_subobject...')
        return response

    def svc_call_campaign_strategy_list(self, **kwargs):
        logger.info('Start reading svc_call_campaign_strategy_list...')
        campaign=kwargs['campaign']
        page_limit= dict['page_limit'] if hasattr(dict, 'page_limit') else 100
        query='campaign=%s?page_limit=%s'%(campaign,page_limit)
        session_helper.t1_login_session(self,TT_Constants['Base_URL'])
        response = self.adama.get(TT_Constants['Base_URL']+'t1/api/v2.0/strategies/limit/%s'%query)
        srv_campaign_strategy_result_list=populate_entity_campaign_strategy_service('campaign',response.content)
        #response = self._call(TT_Constants['Base_URL']+'t1/api/v2.0/strategies/limit/%s'%query, 'GET')
        #response.headers['status'] , 'Failed to parse response for article version history service'
        logger.info('Finishing reading svc_call_campaign_strategy_list...')
        return srv_campaign_strategy_result_list

    def svc_call_bsd_strategies_info(self, **kwargs):#self,
        logger.info('Start reading svc_call_bsd_strategies_infofr..')
        #page_limit= dict['page_limit'] if hasattr(dict, 'page_limit') else 15
        #order_by= dict['order_by'] if hasattr(dict, 'order_by') else 'descending'
        strategies=kwargs['strategies']
        #query='?order_by=%s&page_limit=%s&q=name=:*%s*'%(order_by,page_limit,name)
        session_helper.t1_login_session(self,TT_Constants['Base_URL'])
        response = self.adama.get(TT_Constants['Base_URL']+'t1/api/v2.0/strategies/%s'%strategies)
        srv_strategies_info_list,id,entity_type=populate_strategy_info_from_service(response.content)
        srv_strategies_info_list=dict(srv_strategies_info_list)
        srv_strategies_info_list['id']=id
        srv_strategies_info_list['entity_type']=entity_type
        logger.info('Finishing reading svc_call_bsd_strategies_info...DONE')
        return srv_strategies_info_list

    def svc_call_all_campaigns_for_advertiser(self, **kwargs):#self,
        logger.info('Start reading svc_call_all_campaigns_for_advertiser...')
        #page_limit= dict['page_limit'] if hasattr(dict, 'page_limit') else 15
        #order_by= dict['order_by'] if hasattr(dict, 'order_by') else 'descending'
        advertiser=kwargs['advertiser']
        #query='?order_by=%s&page_limit=%s&q=name=:*%s*'%(order_by,page_limit,name)
        session_helper.t1_login_session(self,TT_Constants['Base_URL'])
        response = self.adama.get(TT_Constants['Base_URL']+'t1/api/v2.0/campaigns/limit/advertiser=%s'%advertiser)
        srv_campaign_info_list=populate_entity_campaign_strategy_service('campaign',response.content)
        logger.info('Finishing reading svc_call_all_campaigns_for_advertiser...DONE')
        return srv_campaign_info_list

    def retrive_strategy_info_from_service(self,srv_response,attr):

        xml = ET.fromstring(srv_response)
        strategy_list=[row.attrib["%s"%attr] for row in xml.iter('prop')]

        return strategy_list


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        ('fund', '0005_data_member_users'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='member',
            name='email',
        ),
    ]


from PIL import Image
import os

def rotateImages():
    for image in os.listdir(os.getcwd()):
        if (image.endswith(".jpg")):
            img = Image.open(image)
            img.transpose(Image.FLIP_LEFT_RIGHT).save(image)
            img.close()

if __name__ == '__main__':
    rotateImages()


"""
Copyright (c) 2020 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import absolute_import

from flexmock import flexmock
import pytest

from atomic_reactor.inner import DockerBuildWorkflow
from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException
from atomic_reactor.plugins.pre_check_user_settings import CheckUserSettingsPlugin

from tests.constants import TEST_IMAGE
from tests.stubs import StubInsideBuilder, StubSource

def mock_dockerfile(tmpdir, labels):
    base = 'From fedora:30'
    cmd = 'CMD /bin/cowsay moo'
    extra_labels = [
        'LABEL {}'.format(label)
        for label in labels

    ]
    data = '\n'.join([base] + extra_labels + [cmd])
    tmpdir.join('Dockerfile').write(data)

def mock_workflow(tmpdir):
    workflow = DockerBuildWorkflow(
        TEST_IMAGE,
        source={"provider": "git", "uri": "asd"}
    )
    workflow.source = StubSource()
    builder = StubInsideBuilder().for_workflow(workflow)
    builder.set_df_path(str(tmpdir))
    builder.tasker = flexmock()
    workflow.builder = flexmock(builder)

    return workflow

def mock_env(tmpdir, docker_tasker, labels=(), flatpak=False):
    if not flatpak:
        # flatpak build has no Dockefile
        mock_dockerfile(tmpdir, labels)
    workflow = mock_workflow(tmpdir)
    plugin_conf = [{'name': CheckUserSettingsPlugin.key,
                    'args': {'flatpak': flatpak}}]

    runner = PreBuildPluginsRunner(docker_tasker, workflow, plugin_conf)

    return runner

class TestDockerfileChecks(object):
    """
    Test checks related to Dockerfile
    """

    @pytest.mark.parametrize('labels,expected_fail', (
        (['com.redhat.delivery.appregistry=true',
          'com.redhat.delivery.operator.bundle=true'],
         True),
        (['com.redhat.delivery.appregistry=true',
          'com.redhat.delivery.operator.bundle=false'],
         False),
        (['com.redhat.delivery.appregistry=true'], False),
        (['com.redhat.delivery.operator.bundle=true'], False),
    ))
    def test_mutual_exclusivity_of_labels(self, tmpdir, docker_tasker, labels, expected_fail):
        """Appregistry and operator.bundle labels are mutually exclusive"""
        runner = mock_env(tmpdir, docker_tasker, labels=labels)
        if expected_fail:
            with pytest.raises(PluginFailedException) as e:
                runner.run()
            assert 'only one of labels' in str(e.value)
        else:
            runner.run()

    def test_flatpak_skip_dockerfile_check(self, tmpdir, docker_tasker, caplog):
        """Flatpak builds have no user Dockerfiles, dockefile check must be skipped"""
        runner = mock_env(tmpdir, docker_tasker, flatpak=True)
        runner.run()

        assert 'Skipping Dockerfile checks' in caplog.text


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 21 23:12:15 2018

@author: villtord
"""
import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import pyqtSignal,QTimer,QThread
from Simple_UI_3 import Ui_MainWindow
import send_motor
import time

import pygame

global com_port_name, get_pos, motor_stop, move_abs
global offset_steps, offset_mm, steps_per_mm
global position_LEED, position_EXCH, position_PASS

com_port_name = 'COM3'

get_pos = bytearray ([1,6,1,0,0,0,0,0])
motor_stop = bytearray ([1,3,0,0,0,0,0,0,4])
move_abs = bytearray ([1,4,0,0])
move_rel = bytearray ([1,4,1,0])
roll_speed = 300
roll_right = bytearray ([1,1,0,0])
roll_left = bytearray ([1,2,0,0])

offset_steps = -716948
offset_mm   = 245
steps_per_mm = 16026.45

position_LEED = 244
position_EXCH = 75
position_PASS = 10

def convert (value,flag):

    global offset_steps, offset_mm, steps_per_mm

    if flag == True:                #make convertion from mm to microsteps

        result = int (offset_steps + (offset_mm-value)*steps_per_mm)

    else:                           #make convertion from microsteps to mm

        result = offset_mm - (value-offset_steps)/steps_per_mm

    return result

class update_position(QThread):

    global get_pos, com_port_name

    new_value_trigger = pyqtSignal(float)

    def __init__(self, *args, **kwargs):

        super(self.__class__, self).__init__()
        print ("get_value initializeed")

    def update_position (self):

        self.check = get_pos
        try:
            self.position = int (send_motor.send_command(com_port_name, self.check)) # in microsteps
            self.position_mm = convert(self.position, False)
            self.new_value_trigger.emit(self.position_mm)
        except:
            print ('can not get the position')
            pass

class joystick_control_class(QThread):

    global get_pos, com_port_name

    joystick_trigger = pyqtSignal(str)

    def __init__(self, *args, **kwargs):

        super(self.__class__, self).__init__()

        pygame.init()

        pygame.joystick.init()

        self.my_joystick = None
        self.joystick_names = []

        # Enumerate joysticks
        for i in range(0, pygame.joystick.get_count()):   # returns number of joysticks
             self.joystick_names.append(pygame.joystick.Joystick(i).get_name())

        print ( self.joystick_names)

        # By default, load the first available joystick.
        if (len( self.joystick_names) > 0):
             self.my_joystick = pygame.joystick.Joystick(0)
             self.my_joystick.init()
        print ("joystick control initializeed")
#        print ('number of axes: ',  self.my_joystick.get_numaxes())
#        print ('number of buttons: ',  self.my_joystick.get_numbuttons())
#        print ('number of hats: ',  self.my_joystick.get_numhats())

    def start (self):
        done = False
        motion_flag = False
        # -------- Main Program Loop -----------
        while done == False:
            time.sleep(0.05)
            # EVENT PROCESSING STEP
            for event in pygame.event.get(): # User did something
                if event.type == pygame.QUIT: # If user clicked close
                    done = True # Flag that we are done so we exit this loop

                # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION
                if event.type == pygame.JOYBUTTONDOWN:
                    print("Joystick button pressed. ", event.button)
                    if event.button == 0:
                        print ('stop button was pressed')
                        self.joystick_trigger.emit('stop')
                    elif (event.button == 2) and ((self.my_joystick.get_button(4)==1) or (self.my_joystick.get_button(5)==1)):
                        print ('LEED')
                        self.joystick_trigger.emit ('LEED')
                    elif (event.button == 3) and ((self.my_joystick.get_button(4)==1) or (self.my_joystick.get_button(5)==1)):
                        print ('EXCH')
                        self.joystick_trigger.emit ('EXCH')
                    elif (event.button == 1) and ((self.my_joystick.get_button(4)==1) or (self.my_joystick.get_button(5)==1)):
                        print ('PASS')
                        self.joystick_trigger.emit ('PASS')

                elif event.type == pygame.JOYHATMOTION:
                    if (event.value[0] == 1) and ((self.my_joystick.get_button(4)==1) or (self.my_joystick.get_button(5)==1)):
                        print ('shifting right')
                        self.joystick_trigger.emit ('shift_right')
                    elif (event.value[0] == -1) and ((self.my_joystick.get_button(4)==1) or (self.my_joystick.get_button(5)==1)):
                        print ('shifting left')
                        self.joystick_trigger.emit ('shift_left')

                if event.type == pygame.JOYBUTTONUP and ((event.button == 4) or (event.button == 5)):
                    print("Joystick safety button UNpressed. ", event.button)
                    if (abs(self.my_joystick.get_axis(4))>0.8):
                        print ('stop button was pressed')
                        motion_flag = False
                        self.joystick_trigger.emit('stop')

                elif event.type == pygame.JOYAXISMOTION:
                    time.sleep(0.1)

                    if (event.axis == 4) and (self.my_joystick.get_button(4) == 1) and (self.my_joystick.get_button(5) == 1):
                        if (self.my_joystick.get_axis(4)>0.8):
                            if not motion_flag:
                                print ('start moving right')
                                motion_flag = True
                                self.joystick_trigger.emit('move_right')
                            else:
                                print ('keep moving right')
                        elif (self.my_joystick.get_axis(4)<-0.8):
                            if not motion_flag:
                                print ('start moving left')
                                motion_flag = True
                                self.joystick_trigger.emit('move_left')
                            else:
                                print ('keep moving left')
                        else:
                            if motion_flag:
                                print ('stopped')
                                motion_flag = False
                                self.joystick_trigger.emit('stop')
                    elif (event.axis == 4) and (motion_flag) and ((self.my_joystick.get_button(4) == 0) or (self.my_joystick.get_button(5) == 0)):
                        print ('stopped')
                        motion_flag = False
                        self.joystick_trigger.emit('stop')

    def stop (self):

        self.my_joystick.quit()

class ExampleApp(QWidget, Ui_MainWindow):

    global com_port_name, get_pos, motor_stop, move_abs, roll_right, roll_left
    global position_LEED, position_EXCH, position_PASS

    def __init__(self):

        super(self.__class__, self).__init__()
        self.setupUi(self)

        """ Start monitoring the current position and connect all signals"""

        self.update_thread = update_position()

        self.pushButton.clicked.connect(lambda: self.move_motor(self.lineEdit.text()))
        self.pushButton_1.clicked.connect(self.joystick_operation)
        self.pushButton_2.clicked.connect(self.stop_motor)
        self.pushButton_3.clicked.connect(lambda: self.shift_motor(1,self.lineEdit_3.text()))   # L shift
        self.pushButton_4.clicked.connect(lambda: self.shift_motor(-1,self.lineEdit_3.text()))  # R shift
        self.pushButton_5.clicked.connect(lambda: self.move_motor(self.lineEdit_4.text()))      # LEED
        self.pushButton_6.clicked.connect(lambda: self.move_motor(self.lineEdit_5.text()))      # EXCH
        self.pushButton_7.clicked.connect(lambda: self.move_motor(self.lineEdit_6.text()))      # PASS

        self.start()

        """ Show the LEED, EXCH and PASS positions """
        self.lineEdit_4.setText(str(position_LEED))
        self.lineEdit_5.setText(str(position_EXCH))
        self.lineEdit_6.setText(str(position_PASS))

    def start (self):

        self.update_thread.new_value_trigger.connect(self.update_position_label)

        self.timer_x = QTimer(self)
        self.timer_x.timeout.connect(self.update_thread.update_position)
        self.timer_x.start(1000)

    def stop_motor(self):

        self.command = motor_stop                                            # construct command
        send_motor.send_command(com_port_name, self.command)                   # senf command

    def update_position_label (self, value):

        self.position_mm = value
        self.lineEdit_2.setText("{:1.1f}".format(self.position_mm))

    def roll_motor (self, value):

        if (float (value) >= 0):
            print ('rolling right ', value)
            self.command = roll_right+roll_speed.to_bytes(4, byteorder='big',signed=True)
            send_motor.send_command(com_port_name, self.command)
        else:
            print ('rolling left ', value)
            self.command = roll_left+roll_speed.to_bytes(4, byteorder='big',signed=True)
            send_motor.send_command(com_port_name, self.command)

    def move_motor (self, value):

        if (float (value) <= 265) & (float (value) >= 0):
            self.lineEdit.setText(value)
            self.value = convert (float(value), True)
            print ('moving to ', self.value)
            self.command = move_abs + (self.value).to_bytes(4, byteorder='big',signed=True)
            send_motor.send_command(com_port_name, self.command)

    def shift_motor(self, flag, value):

        self.shift=float(value)
        if (self.shift <= 50) & (self.shift >= 0):
            if flag == -1:
                self.shift = (-1)*self.shift
            self.new_value = float(self.lineEdit_2.text())+self.shift
            self.lineEdit.setText(str(self.new_value))
            print (self.new_value)
            self.shift_steps = convert (self.new_value, True)
            print (self.shift_steps)
            self.command = move_abs + (self.shift_steps).to_bytes(4, byteorder='big',signed=True)
            send_motor.send_command(com_port_name, self.command)

    def joystick_operation(self):

        if self.pushButton_1.isChecked():
            self.pushButton_1.setText("Disable Joystick")
            self.joystick_monitor = joystick_control_class()
            self.joystick_monitor.joystick_trigger.connect (self.joystick_processing)

            self.joystick_monitor.start()
        else:
            print ("not checked")
            self.pushButton_1.setText("Enable Joystick")
            self.joystick_monitor.stop()

    def joystick_processing(self, parameter):

        self.joystick_command = parameter

        if self.joystick_command == 'stop':
            self.stop_motor()
        elif self.joystick_command == 'shift_left':
            self.shift_motor(1,self.lineEdit_3.text())
        elif self.joystick_command == 'shift_right':
            self.shift_motor(-1,self.lineEdit_3.text())
        elif self.joystick_command == 'LEED':
            self.move_motor(self.lineEdit_4.text())
        elif self.joystick_command == 'EXCH':
            self.move_motor(self.lineEdit_5.text())
        elif self.joystick_command == 'PASS':
            self.move_motor(self.lineEdit_6.text())
        elif self.joystick_command == 'move_right':
            self.roll_motor(1)
        elif self.joystick_command == 'move_left':
            self.roll_motor(-1)

    def __del__ (self):

        self.stop_motor()
        self.update_thread.quit()
        self.timer_x.stop()
        self.timer_x.deleteLater()

def main():
    app = QApplication(sys.argv)  # A new instance of QApplication
    form = ExampleApp()                 # We set the form to be our ExampleApp (design)
    form.setWindowTitle("Motor control")
    form.show()                         # Show the form
    sys.exit(app.exec_())
    app.exec_()                         # and execute the app

if __name__ == '__main__':              # if we're running file directly and not importing it
    main()                              # run the main function


import numpy as np
import csv
from sklearn.datasets import fetch_20newsgroups
twenty_train=fetch_20newsgroups(subset='train')
emission_probability=np.array([[0.4,0.3,0.3]#晴的隐藏状态：0.4打球，0.3读书，0.3访友
                                  ,[0.2,0.3,0.5],#阴的隐藏状态是：0.2打球，0.3读书，0.5访友
                               [0.1,0.8,0.1]])#雨的隐藏状态是：0.1打球，0.8读书，0.1访友

transition_probabilty=np.array([[0.7,0.2,0.1],#晴天：晴0.6，阴0.2，雨0.1
                                [0.3,0.5,0.2],#阴天：晴0.3，阴0.5，雨0.2
                                [0.3,0.4,0.3]])#雨天：晴0.3，阴0.4，雨0.3

start_probability=np.array([0.5,0.2,0.3])
from hmmlearn import hmm
model=hmm.MultinomialHMM(n_components=3)
model.startprob_=start_probability
model.transmat_=transition_probabilty
model.emissionprob_=emission_probability
dic=[]
dic.append('晴天')
dic.append('阴天')
dic.append('雨天')
observer=[]
observer.append('打球')
observer.append('读书')
observer.append('访友')

observerstr=[]
predictstr=[]
observe_chain=np.array([0,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2,1,0]).reshape(-1,1)
predict=model.predict(observe_chain)
print(predict)
temp=[0,2,1,1,1,1,1,1,2,2,2,2,2,2,2,2,1,0]
for i in list(predict):
    predictstr.append(dic[i])
    # predictstr.append(dic[j])
for i in temp:
    observerstr.append(observer[i])
    # predictstr.append(dic[j])
print('显示层：',observerstr)
print('预测层：',predictstr)
print(model.score(observe_chain))

scikit练习/隐马尔科夫模型预测儿子生活规律.py

隐马尔科夫模型预测儿子生活规律.py