import json
from pathlib import Path

def flesh_and_blood_summary(path: Path):
    with path.open(newline='') as jsonfile:
        year_json = json.load(jsonfile)

        # Calculate self / anonymous ids
        self_id = year_json['userInfo']['meRefId']
        anonymous_id = None
        for player in year_json['players']:
            if player['isAnonymous']:
                anonymous_id = player['id']

        # Setup stat variables
        game_formats = {}
        # blitz = {
        #     'heroes': {},
        #     'plays': 0,
        #     'times_went_first': 0,
        #     'wins': 0,
        #     'losses': 0,
        #     'ties': 0,
        #     'wins_when_first': 0,
        # }

        # Parse data from plays
        for play in year_json['plays']:
            if play['ignored']:
                continue

            # Get game format object to use
            game_format = play.get('board')

            if game_format is None:
                print("Missing format for game " + play['uuid'])
                continue

            game_format_stats = game_formats.get(game_format)

            if game_format_stats is None:
                game_format_stats = {
                    'heroes': {},
                    'plays': 0,
                    'times_went_first': 0,
                    'wins': 0,
                    'losses': 0,
                    'ties': 0,
                    'wins_when_first': 0,
                }
                game_formats[game_format] = game_format_stats

            # Calculate stats
            game_format_stats['plays'] += 1

            winner_exists = False
            self_role = None
            self_start_player = False
            self_won = False
            heroes_played_against = set()

            for player in play['playerScores']:
                role = player.get('role')
                hero = game_format_stats['heroes'].get(role)

                if hero is None:
                    hero = {
                        'played_as': 0,
                        'times_went_first_as': 0,
                        'wins_as': 0,
                        'losses_as': 0,
                        'ties_as': 0,
                        'wins_when_first_as': 0,
                        'played_against': 0,
                        'times_went_first_against': 0,
                        'wins_against': 0,
                        'losses_against': 0,
                        'ties_against': 0,
                        'wins_when_first_against': 0,
                    }

                    game_format_stats['heroes'][role] = hero

                if player['winner']:
                    winner_exists = True

                # Player is me
                if player['playerRefId'] == self_id:
                    self_role = role
                    hero['played_as'] += 1

                    if player['startPlayer']:
                        self_start_player = True
                        game_format_stats['times_went_first'] += 1
                        hero['times_went_first_as'] += 1
                    if player['winner']:
                        self_won = True
                        game_format_stats['wins'] += 1
                        hero['wins_as'] += 1
                    if player['startPlayer'] and player['winner']:
                        game_format_stats['wins_when_first'] += 1
                        hero['wins_when_first_as'] += 1
                # Player is not me
                else:
                    heroes_played_against.add(role)

                    if player['winner']:
                        game_format_stats['losses'] += 1
                        hero['losses_against'] += 1

            for hero_against in heroes_played_against:
                hero_object = game_format_stats['heroes'].get(hero_against)
                hero_object['played_against'] += 1

                if self_start_player:
                    hero_object['times_went_first_against'] += 1
                if self_won:
                    hero_object['wins_against'] += 1
                if self_start_player and self_won:
                    hero_object['wins_when_first_against'] += 1

            if not winner_exists:
                game_format_stats['ties'] += 1

                game_format_stats['heroes'].get(self_role)['ties_as'] += 1
                for hero in heroes_played_against:
                    game_format_stats['heroes'].get(hero)['ties_against'] += 1
            elif not self_won:
                game_format_stats['heroes'].get(self_role)['losses_as'] += 1

    # Print results
    output_text = ""

    for game_format_name in sorted(game_formats):
        output_text += create_format_results_table(game_format_name, game_formats[game_format_name])
        output_text += "\n"

    print(output_text)

def create_format_results_table(format_name, format_object):
    output_text = ""

    win_percent = round(format_object['wins'] / format_object['plays'] * 100, 2) if format_object['plays'] > 0 else 0.0
    win_percent_when_first = round(format_object['wins_when_first'] / format_object['times_went_first'] * 100, 2) if format_object['times_went_first'] > 0 else 0.0

    output_text += f"### {format_name}\n"

    output_text += f"#### Overall\n"
    output_text += "| Plays | Wins | Losses | Ties | Win Percentage | Times Went First | Wins When First Player | Win % When First Player |\n"
    output_text += "| --- | --- | --- | --- | --- | --- | --- | --- |\n"
    output_text += f"| {format_object['plays']} | {format_object['wins']} | {format_object['losses']} | {format_object['ties']} | {win_percent}% | {format_object['times_went_first']} | {format_object['wins_when_first']} | {win_percent_when_first}% |\n"
    output_text += "\n"

    output_text += f"#### Hero Stats As\n"
    output_text += "| Hero | Plays | Wins | Losses | Ties | Win Percentage | Times Went First | Wins When First Player | Win % When First Player |\n"
    output_text += "| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n"

    for hero in sorted(format_object['heroes']):
        hero_object = format_object['heroes'][hero]

        plays = hero_object['played_as']

        if plays == 0:
            continue

        times_went_first = hero_object['times_went_first_as']
        wins = hero_object['wins_as']
        losses = hero_object['losses_as']
        ties = hero_object['ties_as']
        win_percent = round(wins / plays * 100, 2) if plays > 0 else 0.0
        wins_when_first = hero_object['wins_when_first_as']
        win_percent_when_first = round(wins_when_first / times_went_first * 100, 2) if times_went_first > 0 else 0.0

        output_text += f"| {hero} | {plays} | {wins} | {losses} | {ties} | {win_percent}% | {times_went_first} | {wins_when_first} | {win_percent_when_first}% |\n"

    output_text += "\n"

    output_text += f"#### Hero Stats Against\n"
    output_text += "| Hero | Plays | Wins | Losses | Ties | Win Percentage | Times Went First | Wins When First Player | Win % When First Player |\n"
    output_text += "| --- | --- | --- | --- | --- | --- | --- | --- | --- |\n"

    for hero in sorted(format_object['heroes']):
        hero_object = format_object['heroes'][hero]

        plays = hero_object['played_against']

        if plays == 0:
                continue

        times_went_first = hero_object['times_went_first_against']
        wins = hero_object['wins_against']
        losses = hero_object['losses_against']
        ties = hero_object['ties_against']
        win_percent = round(wins / plays * 100, 2) if plays > 0 else 0.0
        wins_when_first = hero_object['wins_when_first_against']
        win_percent_when_first = round(wins_when_first / times_went_first * 100, 2) if times_went_first > 0 else 0.0

        output_text += f"| {hero} | {plays} | {wins} | {losses} | {ties} | {win_percent}% | {times_went_first} | {wins_when_first} | {win_percent_when_first}% |\n"

    output_text += "\n"

    return output_text


import numpy as np
from PIL import Image
from wordcloud import WordCloud,ImageColorGenerator

#打开文件，大写转小写
word=open('1.txt','r',encoding='utf-8').read().lower()

#按空格分词，生成列表
for ch in '\,\.\?\!\(\)\:\'\"\-':
    word=word.replace(ch," ")
words=word.split( )

#词频统计，生成字典
counts={}
for w in words:
    if len(w)==1:
        continue
    else:
        counts[w]=counts.get(w,0)+1

#设置停用词，过滤
sw={"the","that","and","of","to","for","in","does"}
for w in sw:
    del counts[w]

#设置模板和字体
image=np.array(Image.open('1.jpg'))
font="C:\Windows\Fonts\simsun.ttc"

#设置参数
cloud=WordCloud(mask=image,font_path=font,background_color="white",
                max_words=80,min_font_size=10,max_font_size=80)

#按词频绘制
cloud.generate_from_frequencies(counts)

#保存文件
cloud.to_file('yun.jpg')


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

from openerp import models, fields, api

from ..model_names.amazon_setting import AMAZON_SETTINGS_TABLE

_IR_CRON_XMLID = 'amdeb_amazon.ir_cron_amazon_sync'
_INTERVAL_NUMBER_FIELD = 'interval_number'
_ACTIVE_FIELD = 'active'

class Configuration(models.TransientModel):
    _name = AMAZON_SETTINGS_TABLE
    _inherit = 'res.config.settings'

    default_merchant_id = fields.Char(
        string='Merchant Id',
        required=True,
        help="The Amazon Merchant Identifier",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_access_key = fields.Char(
        string='Access Key',
        required=True,
        help="The Amazon MWS access key",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_secret_key = fields.Char(
        string='Secret Key',
        required=True,
        help="The Amazon MWS secret key",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_synchronization_interval = fields.Integer(
        string='Synchronization Interval (minutes)',
        required=True,
        default=10,
        help="The minimum interval for Amazon automatic synchronization",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_product_brand = fields.Char(
        string='Product Brand',
        help="This is the default value for product brand.",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_amazon_department = fields.Char(
        string='Amazon Department',
        help="This is the default value for Amazon Product Department such"
             "as womens, mens, baby-boys etc found in an Amazon "
             "Browse Tree Guide (BTG) file.",
        default='womens',
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_amazon_item_type = fields.Char(
        string='Amazon Item Type',
        help="This is the default value for Amazon Product item type "
             "such as apparel-accessories, pants, handbags, etc found "
             "in an Amazon Browse Tree Guide (BTG) file.",
        default='handbags',
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_image_location = fields.Char(
        string='Product Image Location',
        required=True,
        help="The product image HTTP location without trailing slash. "
             "The location is public-accessible http (not https) url. Image "
             "name uses a pattern of SKU_main.jpg, SKU_1.jpg, "
             "SKU_2.jpg, ..., SKU_8.jpg. The SKU is the product SKU. "
             "Image size must be smaller than 10MB.",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    default_active_flag = fields.Boolean(
        string='Active Flag',
        # set to False thus not run before configuration is done
        default=False,
        help="Enable or disable Amazon automatic integration",
        default_model=AMAZON_SETTINGS_TABLE,
    )

    # set cron job interval and active status
    def set_settings(self, cr, uid, ids, context):
        env = api.Environment(cr, uid, context)
        cron_record = env.ref(_IR_CRON_XMLID)

        config = self.browse(cr, uid, ids[0], context)
        interval = config.default_synchronization_interval
        active = config.default_active_flag
        values = {_INTERVAL_NUMBER_FIELD: interval,
                  _ACTIVE_FIELD: active, }
        cron_record.write(values)


from file_generator_library.log_support import *
from file_generator_library.dataset_functions import (
    adjust_quote,
    build_quoted_string,
    format_double,
    separate,
)

from file_generator_library.utilities import *
from file_generator_library.timer_support import *

class CellFormatDescription:
    def __init__(
        self,
        decimal_mark=".",
        digit_grouping_char=",",
        digit_grouping_mode=0,
        str_for_null="",
    ):
        self.decimal_mark = decimal_mark
        self.digit_grouping_char = digit_grouping_char
        self.digit_grouping_mode = digit_grouping_mode
        self.str_for_null = str_for_null

class Dataset:
    def __init__(self, source_values=None, source_layout=None):
        self.rows = []
        self.formatted_rows = []
        self.header = None
        self.float_types = ["float"]
        self.int_types = ["int", "row"]
        self.row_index_type = "row"
        self.str_types = ["str"]
        self.float_formula = "float_formula:"
        self.str_hierarchy = "str_parent:"

        self.format_parameters = {
            "file_name": "",
            "quote_around_str": "",
            "row_count": 0,
            "field_separator": name_char("\t"),
            "row_separator": name_char("\n"),
            "encoding": "utf-8",
            "include_bom": "No",
            "slices": 0,
            "decimal_mark": name_char("."),
            "digit_grouping_mode": "0",
            "digit_grouping_char": name_char(","),
            "digit_grouping_source": "default",
        }

        if source_layout is not None:
            self.set_structure(source_layout)

        if source_values is None:
            return
        elif type(source_values) == dict:
            self.append(Datarow(source_values))
        elif type(source_values) == list:
            self.append_from_list_of_dictionaries(source_values)

    def is_int_value(self, ftype):
        return ftype in self.int_types

    def is_float_value(self, ftype):
        return ftype in self.float_types

    def is_str_value(self, ftype):
        return ftype in self.str_types

    def is_row_index(self, ftype):
        return ftype == self.row_index_type

    def is_float_formula(self, ftype):
        return ftype.startswith(self.float_formula)

    def is_float_class(self, ftype):
        return self.is_float_value(ftype) or self.is_float_formula(ftype)

    def is_str_class(self, ftype):
        return self.is_str_value(ftype) or self.is_str_hierarchy(ftype)

    def is_int_class(self, ftype):
        return self.is_int_value(ftype)

    def is_str_hierarchy(self, ftype):
        return ftype.startswith(self.str_hierarchy)

    def row_count(self):
        return len(self.rows)

    def formatted_row_count(self):
        return len(self.formatted_rows)

    def get_row(self, row_index):
        if row_index < len(self.rows):
            return self.rows[row_index]
        else:
            return None

    def get_formatted_row(self, row_index):
        if row_index < len(self.formatted_rows):
            return self.formatted_rows[row_index]
        else:
            return None

    def append_from_list_of_dictionaries(self, data_dict_list):
        if self.header is None:
            dh = Datarow()
            dh.add_from_dict(data_dict_list[0])
            dh.values_to_type()
            self.set_structure(dh)

        for dict in data_dict_list:
            dr = Datarow()
            dr.add_from_dict(dict)
            self.append(dr)

    def set_structure(self, datarow):
        self.header = datarow

    def append(self, datarow):
        if self.header is None:
            dh = datarow.clone()
            dh.values_to_type()
            self.set_structure(dh)

        self.rows.append(datarow)
        self.format_parameters["row_count"] = len(self.rows)

    def format_cells(
        self,
        decimal_mark=".",
        digit_grouping_char="",
        digit_grouping_mode=0,
        str_for_null="",
    ):

        if digit_grouping_mode > 0 and digit_grouping_char == "":
            tmp_grouping_char = ","
            tmp_grouping_mode = digit_grouping_mode
            tmp_grouping_source = "Auto set digit grouping char to ','"
        elif digit_grouping_mode == 0 and digit_grouping_char != "":
            tmp_grouping_char = digit_grouping_char
            tmp_grouping_mode = 1
            tmp_grouping_source = "Auto set digit grouping mode to 1"
        else:
            tmp_grouping_char = digit_grouping_char
            tmp_grouping_mode = digit_grouping_mode
            tmp_grouping_source = "user parameters"

        self.format_parameters["decimal_mark"] = name_char(decimal_mark)
        self.format_parameters["digit_grouping_mode"] = tmp_grouping_mode
        self.format_parameters["digit_grouping_char"] = name_char(tmp_grouping_char)
        self.format_parameters["digit_grouping_src"] = tmp_grouping_source

        with MyTimer("format_cells"):
            cell_format = CellFormatDescription(
                decimal_mark,
                digit_grouping_char=tmp_grouping_char,
                digit_grouping_mode=tmp_grouping_mode,
                str_for_null=str_for_null,
            )

            self.formatted_rows = []
            for input_row in self.rows:
                dr = Datarow(linked_source_row=input_row)
                dr.source = input_row
                for field_name, field_type in self.header.cell_values.items():
                    input_value = input_row.get_cell(field_name, none_if_missing=True)
                    #                    input_value = input_row.cell_values[field_name]

                    if input_value is None:
                        dr.add_cell(field_name, str_for_null)

                    elif self.is_str_class(field_type):
                        dr.add_cell(field_name, str(input_value))

                    elif self.is_float_class(field_type):
                        with MyTimer("format_float"):
                            output_value = format_double(
                                input_value,
                                decimal_mark,
                                tmp_grouping_char,
                                tmp_grouping_mode,
                            )
                            dr.add_cell(field_name, output_value)

                    elif self.is_int_class(field_type):
                        with MyTimer("format_int"):
                            output_value = str(input_value)
                            dr.add_cell(field_name, output_value)

                    else:
                        print(
                            f"Unrecognized field type {field_type} used for {field_name}."
                        )

                self.formatted_rows.append(dr)

    def write_file(
        self,
        filename,
        write_bom=False,
        field_separator="\t",
        row_ending_str="\n",
        quote_around_str="",
        quote_if_delimiter='"',
        has_header=True,
        blank_before_header=0,
        blank_after_header=0,
        str_encoding="utf-8",
        slice_nbr=0,
    ):

        tmp_encoding = str_encoding

        if len(self.formatted_rows) < 1:
            print(
                "The dataset is not properly formatted. Please call the method format_cells()"
            )
            return

        print(f"Writing file {filename}...")

        if write_bom:
            if str_encoding[0:3] != "utf":
                print(
                    f"Encoding set to {str_encoding} but write_bom is {write_bom}, switching to utf-8."
                )
                tmp_encoding = "utf-8"

        self.format_parameters["file_name"] = filename
        self.format_parameters["quote_around_str"] = name_char(quote_around_str)
        self.format_parameters["encoding"] = tmp_encoding
        self.format_parameters["include_bom"] = write_bom

        self.format_parameters["slices"] = slice_nbr

        if field_separator == "\t":
            self.format_parameters["field_separator"] = name_char("\t")
        else:
            self.format_parameters["field_separator"] = name_char(field_separator)

        #   self.format_parameters["row_separator"] = "\\n"

        if slice_nbr == 0:
            file = open(filename, "w", encoding=tmp_encoding)
            file.close()

        with open(filename, "a", encoding=tmp_encoding) as file:
            if write_bom:
                file.write("\ufeff")

            if slice_nbr == 0:
                for i in range(0, blank_before_header):
                    file.write(row_ending_str)

                if has_header:
                    tmp_sep_before = ""
                    for field_name in self.header.cell_keys:
                        file.write(tmp_sep_before)
                        file.write(field_name)
                        tmp_sep_before = field_separator
                    file.write(row_ending_str)

                for i in range(0, blank_after_header):
                    file.write(row_ending_str)

            for row in self.formatted_rows:
                tmp_sep_before = ""
                for field_name in self.header.cell_keys:
                    field_value = row.cell_values[field_name]
                    field_type = self.header.cell_values[field_name]
                    file.write(tmp_sep_before)

                    tmp_output = build_quoted_string(
                        field_type,
                        field_value,
                        field_separator,
                        quote_around_str,
                        quote_if_delimiter,
                    )
                    file.write(tmp_output)

                    tmp_sep_before = field_separator

                file.write(row_ending_str)

        print(f"Done writing file {filename}.")

        pass

class Datarow:
    def __init__(self, linked_source_row=None, source_values=None):
        # key is field name / value is current value
        self.cell_values = {}
        self.cell_keys = []
        self.dataset = None
        # key is field name / value is original value (before defect injection)
        self.defect_cell_names = {}
        self.linked_source = linked_source_row

        if source_values is None:
            return

        if type(source_values) == dict:
            self.add_from_dict(source_values)
            return

        if type(source_values) == Datarow:
            for name, value in source_values.cell_values.items():
                self.add_cell(name, value)

            self.dataset = source_values.dataset

    def clone(self):
        return Datarow(source_values=self)

    def link(self, dataset):
        self.dataset = dataset

    def count(self):
        return len(self.cell_values)

    def set_cell(self, name, value):
        if name not in self.cell_keys:
            print(f"Cannot set field {name} to {value}.")
            exit(-1)
        self.cell_values[name] = value

    def set_cell_defect(self, name, value):
        self.defect_cell_names[name] = self.get_cell(name)
        self.set_cell(name, value)

    def get_cell(self, name, none_if_missing=False):
        if name not in self.cell_keys:
            if none_if_missing:
                return None
            else:
                print(f"Cannot get field {name}.")
                exit(-1)

        return self.cell_values[name]

    def get_name_by_index(self, cell_index):
        if cell_index < len(self.cell_keys):
            return self.cell_keys[cell_index]
        else:
            return None

    def get_cell_names(self):
        tmp = []
        for item in self.cell_keys:
            tmp.append(item)
        return tmp

    def get_cell_by_index(self, cell_index):
        if cell_index < len(self.cell_keys):
            return self.cell_values[self.cell_keys[cell_index]]
        else:
            return None

    def add_from_dict(self, source_dict, forced_value=None):
        for k, v in source_dict.items():
            if forced_value is not None:
                self.add_cell(k, forced_value)
            else:
                self.add_cell(k, v)
        return self

    def add_cell(self, name, value):
        self.cell_values[name] = value
        if name not in self.cell_keys:
            self.cell_keys.append(name)

    def values_to_type(self):
        for name, value in self.cell_values.items():
            tmp = type(value)
            if tmp == int:
                self.cell_values[name] = "int"
            elif tmp == float:
                self.cell_values[name] = "float"
            else:
                self.cell_values[name] = "str"

def document_dataset(layout):
    ds = Dataset()

    dh = Datarow()
    dh.add_cell("field_name", "str")
    dh.add_cell("field_type", "str")
    dh.add_cell("formula", "str")
    dh.add_cell("parent", "str")

    ds.set_structure(dh)

    for field_name, field_type in layout.cell_values.items():
        dr = Datarow()
        dr.add_cell("field_name", field_name)
        dr.add_cell("field_type", "?")
        dr.add_cell("formula", "")
        dr.add_cell("parent", "")

        if ds.is_float_formula(field_type):
            dr.add_cell("field_type", "float")
            dr.add_cell("formula", field_type[len("float_formula:") :])
        elif ds.is_str_hierarchy(field_type):
            dr.add_cell("field_type", "str")
            dr.add_cell("parent", field_type[len("str_parent:") :])
        else:
            dr.add_cell("field_type", field_type)
        ds.append(dr)

    return ds

def compare_str(test, expected_value, value):
    if value == expected_value:
        return
    print(f"Expecting [{expected_value}, but got {value} at test {test}]")


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

def F(n):
    """Ritorna il numero di modi di piastrellare
    un bagno 2xn ben squadrato"""
    assert n >= 0
    if n == 0:
        return 1
    if n == 1:
        return 2
    return F(n-1) + G(n-1) + H(n-2)

def G(n):
    """Ritorna il numero di modi di piastrellare
    un bagno 2x(n+1) che ha perso una cella d'angolo.
    ben squadrato. Nota: la riga corta ha n celle."""
    assert n >= 0
    if n == 0:
        return 1
    return F(n) + G(n-1)

def H(n):
    """Ritorna il numero di modi di piastrellare
    un bagno 2x(n+2) che ha perso due celle di cui precisamente una d'angolo e poi una sua limitrofa. Nota: la riga corta ha n celle."""
    assert n >= 0
    return G(n) + F(n)

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

def stampaPiastrellatureF(n):
    """Stampa tutte le piastrellature del bagno 2xN compatibili con quanto si trova nella variabile globale piastrellatura.
       Resta da scegliere come piastrellare quel sottobagno di celle (i,j)
       con  piastrellatura[i][j] = 0.
       Esso è un bagno 2xn ben squadrato collocato a destra entro il bagno 2xN."""
    assert n >= 0
    if n == 0:
        printPiastrellatura()
        return
    min_free = 1
    assert piastrellatura[0][N-n-1] != 0
    if min_free == piastrellatura[0][N-n-1]:
        min_free += 1
    if min_free == piastrellatura[1][N-n-1]:
        min_free += 1
    if min_free == piastrellatura[0][N-n-1]:
        min_free += 1
    free2 = min_free + 1
    if free2 == piastrellatura[0][N-n-1]:
        free2 += 1
    if free2 == piastrellatura[1][N-n-1]:
        free2 += 1
    if free2 == piastrellatura[0][N-n-1]:
        free2 += 1
    if n == 1:
        piastrellatura[0][N-1] = piastrellatura[1][N-1] = min_free
        printPiastrellatura()
        piastrellatura[0][N-1] = min_free
        piastrellatura[1][N-1] = free2
        printPiastrellatura()
        return
    piastrellatura[0][N-1] = piastrellatura[1][N-1] = min_free
    stampaPiastrellatureF(n-1)
    piastrellatura[0][N-1] = piastrellatura[1][N-1] = 0
    piastrellatura[0][N-1] = min_free
    stampaPiastrellatureG(n-1)
    piastrellatura[0][N-1] = 0
    stampaPiastrellatureH(n-2)
    piastrellatura[0][N-1] = piastrellatura[0][N-2] = min_free

def stampaPiastrellatureG(n):
    """Stampa tutte le piastrellature del bagno 2xN compatibili con quanto si trova nella variabile globale piastrellatura.
       Resta da scegliere come piastrellare quel sottobagno di celle (i,j)
       con  piastrellatura[i][j] = 0.
       Esso è un bagno 2x(n+1) che ha perso una cella d'angolo.
       Nota: la riga corta ha n celle."""
    assert n >= 0
    if n == 0:
        piastrellatura[i][j] = 0
        return 1

    return stampaPiastrellatureF(n) + stampaPiastrellatureG(n-1)

def stampaPiastrellatureH(n):
    """Stampa *tutte* le piastrellature di
    un bagno 2x(n+2) che ha perso due celle di cui precisamente una d'angolo e poi una sua limitrofa. Nota: la riga corta ha n celle."""
    assert n >= 0
    return stampaPiastrellatureG(n) + stampaPiastrellatureF(n)

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

with open("input.txt", "r") as fr:
    N = int(fr.readline())

fw = open("output.txt", "w")

def printPiastrellatura():
    for i in range(N):
        fw.write(str(piastrellatura[0][i]) + " ")
    fw.write("\n")
    for i in range(N):
        fw.write(str(piastrellatura[1][i]) + " ")
    fw.write("\n")

fw.write(str(F(N)))
fw.write("\n")

piastrellatura = [ [0]*N, [0]*N]

#printPiastrellatura()

stampaPiastrellatureF(N)


from __future__ import annotations

__all__ = ["BatchDict", "check_same_batch_size", "check_same_keys", "get_seq_lens"]

from collections.abc import (
    Hashable,
    ItemsView,
    Iterable,
    Iterator,
    KeysView,
    Sequence,
    ValuesView,
)
from typing import Any, TypeVar

import numpy as np
import torch
from coola import objects_are_allclose, objects_are_equal
from coola.utils.format import str_indent, str_mapping
from torch import Tensor

from redcat.base import BaseBatch

TBaseBatch = TypeVar("TBaseBatch", bound=BaseBatch)
# Workaround because Self is not available for python 3.9 and 3.10
# https://peps.python.org/pep-0673/
TBatchDict = TypeVar("TBatchDict", bound="BatchDict")

class BatchDict(BaseBatch[dict[Hashable, TBaseBatch]]):
    r"""Implements a batch object to represent a dictionary of batches.

    Args:
    ----
        data (dict): Specifies the dictionary of batches.

    Example usage:

    .. code-block:: pycon

        >>> import torch
        >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
        >>> batch = BatchDict(
        ...     {
        ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
        ...         "key2": BatchList(["a", "b"]),
        ...     }
        ... )
        >>> batch
        BatchDict(
          (key1): tensor([[0, 1, 2, 3, 4],
                    [5, 6, 7, 8, 9]], batch_dim=0, seq_dim=1)
          (key2): BatchList(data=['a', 'b'])
        )
    """

    def __init__(self, data: dict[Hashable, TBaseBatch]) -> None:
        if not isinstance(data, dict):
            raise TypeError(f"Incorrect type. Expect a dict but received {type(data)}")
        check_same_batch_size(data)
        self._data = data

    def __repr__(self) -> str:
        data_str = str_indent(str_mapping({key: repr(value) for key, value in self._data.items()}))
        return f"{self.__class__.__qualname__}(\n  {data_str}\n)"

    @property
    def batch_size(self) -> int:
        return next(iter(self._data.values())).batch_size

    @property
    def data(self) -> dict[Hashable, TBaseBatch]:
        return self._data

    #################################
    #     Dictionary operations     #
    #################################

    def __contains__(self, key: Hashable) -> bool:
        return key in self._data

    def __getitem__(self, key: Hashable) -> TBaseBatch:
        return self._data[key]

    def __iter__(self) -> Iterator[Hashable]:
        return iter(self._data)

    def __len__(self) -> int:
        return len(self._data)

    def __setitem__(self, key: Hashable, value: TBaseBatch) -> None:
        if value.batch_size != self.batch_size:
            raise RuntimeError(
                f"Incorrect batch size. Expected {self.batch_size} but received {value.batch_size}"
            )
        self._data[key] = value

    def get(self, key: Hashable, default: TBaseBatch | None = None) -> TBaseBatch | None:
        return self._data.get(key, default)

    def items(self) -> ItemsView:
        return self._data.items()

    def keys(self) -> KeysView:
        return self._data.keys()

    def values(self) -> ValuesView:
        return self._data.values()

    #################################
    #     Conversion operations     #
    #################################

    def to_data(self) -> dict:
        return {key: value.to_data() for key, value in self._data.items()}

    ###############################
    #     Creation operations     #
    ###############################

    def clone(self) -> TBatchDict:
        return self.__class__({key: batch.clone() for key, batch in self._data.items()})

    #################################
    #     Comparison operations     #
    #################################

    def allclose(
        self, other: Any, rtol: float = 1e-5, atol: float = 1e-8, equal_nan: bool = False
    ) -> bool:
        if not isinstance(other, self.__class__):
            return False
        return objects_are_allclose(
            self.data, other.data, rtol=rtol, atol=atol, equal_nan=equal_nan
        )

    def equal(self, other: Any) -> bool:
        if not isinstance(other, self.__class__):
            return False
        return objects_are_equal(self.data, other.data)

    ###########################################################
    #     Mathematical | advanced arithmetical operations     #
    ###########################################################

    def permute_along_batch(self, permutation: Sequence[int] | Tensor) -> TBatchDict:
        return self.__class__(
            {k: v.permute_along_batch(permutation) for k, v in self._data.items()}
        )

    def permute_along_batch_(self, permutation: Sequence[int] | Tensor) -> None:
        for value in self._data.values():
            value.permute_along_batch_(permutation)

    def permute_along_seq(self, permutation: Sequence[int] | Tensor) -> TBatchDict:
        r"""Permutes the data along the sequence dimension.

        The same permutation is applied on all the sequences. This
        method should be called only if all the sequences have the
        same length.

        This method only permutes the values that implement
        ``permute_along_seq``.

        Args:
        ----
            permutation (sequence or ``torch.Tensor`` of type long
                and shape ``(dimension,)``): Specifies the permutation
                to use on the data. The dimension of the permutation
                input should be compatible with the shape of the data.

        Returns:
        -------
            ``BatchDict``: A new batch with permuted data.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.permute_along_seq([2, 1, 3, 0, 4])
            BatchDict(
              (key1): tensor([[2, 1, 3, 0, 4],
                             [7, 6, 8, 5, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "permute_along_seq"):
                val = val.permute_along_seq(permutation)
            out[key] = val
        return self.__class__(out)

    def permute_along_seq_(self, permutation: Sequence[int] | Tensor) -> None:
        r"""Permutes the data along the sequence dimension.

        The same permutation is applied on all the sequences. This
        method should be called only if all the sequences have the
        same length.

        This method only permutes the values that implement
        ``permute_along_seq``.

        Args:
        ----
            permutation (sequence or ``torch.Tensor`` of type long
                and shape ``(dimension,)``): Specifies the permutation
                to use on the data. The dimension of the permutation
                input should be compatible with the shape of the data.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.permute_along_seq_([2, 1, 3, 0, 4])
            >>> batch
            BatchDict(
              (key1): tensor([[2, 1, 3, 0, 4],
                             [7, 6, 8, 5, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        for val in self._data.values():
            if hasattr(val, "permute_along_seq_"):
                val.permute_along_seq_(permutation)

    def shuffle_along_seq(self, generator: torch.Generator | None = None) -> TBatchDict:
        r"""Shuffles the data along the sequence dimension.

        This method should be called only if all the sequences have
        the same length.

        Args:
        ----
            generator (``torch.Generator`` or ``None``, optional):
                Specifies an optional random generator.
                Default: ``None``

        Returns:
        -------
            ``BatchDict``:  A new batch with shuffled data.

        Raises:
            RuntimeError if the batch has multiple sequence lengths.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.shuffle_along_seq()
            BatchDict(
              (key1): tensor([[...]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        seq_lens = get_seq_lens(self._data)
        if not seq_lens:
            return self
        if len(seq_lens) > 1:
            raise RuntimeError(
                f"Invalid operation because the batch has multiple sequence lengths: {seq_lens}"
            )
        return self.permute_along_seq(torch.randperm(seq_lens.pop(), generator=generator))

    def shuffle_along_seq_(self, generator: torch.Generator | None = None) -> None:
        r"""Shuffles the data along the sequence dimension.

        This method should be called only if all the sequences have
        the same length.

        Args:
        ----
            generator (``torch.Generator`` or ``None``, optional):
                Specifies an optional random generator.
                Default: ``None``

        Raises:
        ------
            RuntimeError if the batch has multiple sequence lengths.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.shuffle_along_seq()
            >>> batch
            BatchDict(
              (key1): tensor([[...]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        seq_lens = get_seq_lens(self._data)
        if not seq_lens:
            return
        if len(seq_lens) > 1:
            raise RuntimeError(
                f"Invalid operation because the batch has multiple sequence lengths: {seq_lens}"
            )
        self.permute_along_seq_(torch.randperm(seq_lens.pop(), generator=generator))

    ################################################
    #     Mathematical | point-wise operations     #
    ################################################

    ###########################################
    #     Mathematical | trigo operations     #
    ###########################################

    ##########################################################
    #    Indexing, slicing, joining, mutating operations     #
    ##########################################################

    def append(self, other: TBaseBatch) -> None:
        check_same_keys(self.data, other.data)
        for key, value in self._data.items():
            value.append(other[key])

    def cat_along_seq(self, batches: TBaseBatch | Sequence[TBaseBatch]) -> TBatchDict:
        r"""Concatenates the data of the batch(es) to the current batch
        along the sequence dimension and creates a new batch.

        Note that only the sequences are concatenated.

        Args:
        ----
            batches (``BatchDict`` or  ``Sequence``): Specifies the
                batch(es) to concatenate along the sequence dimension.

        Returns:
        -------
            ``BatchDict``: A batch with the concatenated data
                along the sequence dimension.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> b = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> b.cat_along_seq(
            ...     BatchDict({"key1": BatchedTensorSeq(torch.tensor([[10, 11, 12], [20, 21, 22]]))})
            ... )
            BatchDict(
              (key1): tensor([[ 0,  1,  2,  3,  4, 10, 11, 12],
                        [ 5,  6,  7,  8,  9, 20, 21, 22]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        if isinstance(batches, BatchDict):
            batches = [batches]
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "cat_along_seq"):
                val = val.cat_along_seq([batch[key] for batch in batches])
            out[key] = val
        return self.__class__(out)

    def cat_along_seq_(self, batches: TBaseBatch | Sequence[TBaseBatch]) -> None:
        r"""Concatenates the data of the batch(es) to the current batch
        along the sequence dimension and creates a new batch.

        Note that only the sequences are concatenated.

        Args:
        ----
            batches (``BatchDict`` or  ``Sequence``): Specifies the
                batch(es) to concatenate along the sequence dimension.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> b = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> b.cat_along_seq_(
            ...     BatchDict({"key1": BatchedTensorSeq(torch.tensor([[10, 11, 12], [20, 21, 22]]))})
            ... )
            >>> b
            BatchDict(
              (key1): tensor([[ 0,  1,  2,  3,  4, 10, 11, 12],
                        [ 5,  6,  7,  8,  9, 20, 21, 22]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        if isinstance(batches, BatchDict):
            batches = [batches]
        for key, val in self._data.items():
            if hasattr(val, "cat_along_seq_"):
                val.cat_along_seq_([batch[key] for batch in batches])

    def chunk_along_batch(self, chunks: int) -> tuple[TBatchDict, ...]:
        keys = self._data.keys()
        batches = []
        for values in zip(*[batch.chunk_along_batch(chunks) for batch in self._data.values()]):
            batches.append(self.__class__({key: value for key, value in zip(keys, values)}))
        return tuple(batches)

    def extend(self, other: Iterable[BatchDict | Sequence[TBatchDict]]) -> None:
        for batch in other:
            self.append(batch)

    def index_select_along_batch(self, index: Tensor | Sequence[int]) -> TBatchDict:
        return self.__class__(
            {key: value.index_select_along_batch(index) for key, value in self._data.items()}
        )

    def index_select_along_seq(self, index: Tensor | Sequence[int]) -> TBatchDict:
        r"""Slices the batch along the sequence dimension at the given
        indices.

        Args:
        ----
            index (``torch.Tensor`` of type long and shape
                ``(seq_len,)`` or ``(batch_size, seq_len,)`` or
                ``Sequence``): Specifies the indices to select.

        Returns:
        -------
            ``BatchDict``: A new batch sliced along the sequence
                dimension at the given indices.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.index_select_along_seq([2, 4])
            BatchDict(
              (key1): tensor([[2, 4], [7, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
            >>> batch.index_select_along_seq(torch.tensor([2, 4]))
            BatchDict(
              (key1): tensor([[2, 4], [7, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
            >>> batch.index_select_along_seq(torch.tensor([[2, 4], [4, 3]]))
            BatchDict(
              (key1): tensor([[2, 4], [9, 8]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "index_select_along_seq"):
                val = val.index_select_along_seq(index)
            out[key] = val
        return self.__class__(out)

    def repeat_along_seq(self, repeats: int) -> TBatchDict:
        r"""Repeats the batch along the sequence dimension.

        Args:
        ----
            repeats (int): Specifies the number of times to repeat
                the batch along the sequence dimension.

        Returns:
        -------
            ``BatchDict``: A repeated version of the input batch.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.repeat_along_seq(2)
            BatchDict(
              (key1): tensor([[0, 1, 2, 3, 4, 0, 1, 2, 3, 4],
                        [5, 6, 7, 8, 9, 5, 6, 7, 8, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "repeat_along_seq"):
                val = val.repeat_along_seq(repeats)
            out[key] = val
        return self.__class__(out)

    def select_along_batch(self, index: int) -> dict:
        return {key: value.select_along_batch(index) for key, value in self._data.items()}

    def slice_along_batch(
        self, start: int = 0, stop: int | None = None, step: int = 1
    ) -> TBatchDict:
        return self.__class__(
            {key: value.slice_along_batch(start, stop, step) for key, value in self._data.items()}
        )

    def slice_along_seq(self, start: int = 0, stop: int | None = None, step: int = 1) -> TBatchDict:
        r"""Slices the batch in the sequence dimension.

        Args:
        ----
            start (int, optional): Specifies the index where the
                slicing of object starts. Default: ``0``
            stop (int, optional): Specifies the index where the
                slicing of object stops. ``None`` means last.
                Default: ``None``
            step (int, optional): Specifies the increment between
                each index for slicing. Default: ``1``

        Returns:
        -------
            ``BatchedTensorSeq``: A slice of the current batch.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.slice_along_seq(start=2)
            BatchDict(
              (key1): tensor([[2, 3, 4],
                        [7, 8, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
            >>> batch.slice_along_seq(stop=3)
            BatchDict(
              (key1): tensor([[0, 1, 2],
                        [5, 6, 7]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
            >>> batch.slice_along_seq(step=2)
            BatchDict(
              (key1): tensor([[0, 2, 4],
                        [5, 7, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "slice_along_seq"):
                val = val.slice_along_seq(start, stop, step)
            out[key] = val
        return self.__class__(out)

    def split_along_batch(
        self, split_size_or_sections: int | Sequence[int]
    ) -> tuple[TBatchDict, ...]:
        keys = self._data.keys()
        batches = []
        for values in zip(
            *[batch.split_along_batch(split_size_or_sections) for batch in self._data.values()]
        ):
            batches.append(self.__class__({key: value for key, value in zip(keys, values)}))
        return tuple(batches)

    def take_along_seq(self, indices: TBaseBatch | np.ndarray | Tensor | Sequence) -> TBatchDict:
        r"""Takes values along the sequence dimension.

        Args:
        ----
            indices (``BaseBatch`` or ``numpy.ndarray`` or
                ``torch.Tensor`` or `` Specifies the indices to take
                along the batch dimension.

        Returns:
        -------
            ``BatchDict``: The batch with the selected data.

        Example usage:

        .. code-block:: pycon

            >>> import torch
            >>> from redcat import BatchDict, BatchList, BatchedTensorSeq
            >>> batch = BatchDict(
            ...     {
            ...         "key1": BatchedTensorSeq(torch.arange(10).view(2, 5)),
            ...         "key2": BatchList(["a", "b"]),
            ...     }
            ... )
            >>> batch.take_along_seq(torch.tensor([[3, 0, 1], [2, 3, 4]]))
            BatchDict(
              (key1): tensor([[3, 0, 1],
                        [7, 8, 9]], batch_dim=0, seq_dim=1)
              (key2): BatchList(data=['a', 'b'])
            )
        """
        out = {}
        for key, val in self._data.items():
            if hasattr(val, "take_along_seq"):
                val = val.take_along_seq(indices)
            out[key] = val
        return self.__class__(out)

    ########################
    #     mini-batches     #
    ########################

    #################
    #     Other     #
    #################

    def summary(self) -> str:
        data_str = str_mapping({key: value.summary() for key, value in self._data.items()})
        return f"{self.__class__.__qualname__}(\n  {str_indent(data_str)}\n)"

def check_same_batch_size(data: dict[Hashable, BaseBatch]) -> None:
    r"""Checks if the all the batches in a group have the same batch
    size.

    Args:
    ----
        group (``BaseBatch`` or dict or sequence): Specifies the group
            of batches to check.

    Raises:
    ------
        RuntimeError if there are several batch sizes.

    Example usage:

    .. code-block:: pycon

        >>> from redcat import BatchedTensor, BatchedTensorSeq
        >>> from redcat.batchdict import check_same_batch_size
        >>> check_same_batch_size(
        ...     {
        ...         "key1": BatchedTensorSeq(torch.ones(2, 3)),
        ...         "key2": BatchedTensor(torch.ones(2, 6)),
        ...     }
        ... )
    """
    if not data:
        raise RuntimeError("The dictionary cannot be empty")
    batch_sizes = {val.batch_size for val in data.values()}
    if len(batch_sizes) != 1:
        raise RuntimeError(
            "Incorrect batch size. A single batch size is expected but received several values: "
            f"{batch_sizes}"
        )

def check_same_keys(data1: dict, data2: dict) -> None:
    r"""Checks if the dictionaries have the same keys.

    Args:
    ----
        data1 (dict): Specifies the first dictionary.
        data2 (dict): Specifies the second dictionary.

    Raises:
    ------
        RuntimeError if the keys are different.

    Example usage:

    .. code-block:: pycon

        >>> from redcat import BatchedTensor, BatchedTensorSeq
        >>> from redcat.batchdict import check_same_keys
        >>> check_same_keys(
        ...     {
        ...         "key1": BatchedTensorSeq(torch.ones(2, 3)),
        ...         "key2": BatchedTensor(torch.ones(2, 6)),
        ...     },
        ...     {
        ...         "key1": BatchedTensorSeq(torch.zeros(2, 4)),
        ...         "key2": BatchedTensor(torch.zeros(2, 4)),
        ...     },
        ... )
    """
    keys1 = set(data1.keys())
    keys2 = set(data2.keys())
    if keys1 != keys2:
        raise RuntimeError(f"Keys do not match: ({keys1} vs {keys2})")

def get_seq_lens(data: dict[Hashable, BaseBatch]) -> set[int]:
    r"""Gets the sequence lengths from the inputs.

    Args:
    ----
        data (dict): Specifies the data with the sequences.

    Returns:
    -------
        set: The sequence lengths.

    Example usage:

    .. code-block:: pycon

        >>> from redcat import BatchedTensor, BatchedTensorSeq
        >>> from redcat.batchdict import get_seq_lens
        >>> get_seq_lens(
        ...     {
        ...         "key1": BatchedTensorSeq(torch.ones(2, 3)),
        ...         "key2": BatchedTensor(torch.ones(2, 6)),
        ...     }
        ... )
        {3}
    """
    return {val.seq_len for val in data.values() if hasattr(val, "seq_len")}


from collections import namedtuple
import sys
import os

"""Basic sript for generating command that will remove all explicitly stated
pages using tkpdf"""

def collectUserData():
    """Uply little thing to collect all the data we want from the user (feilds in named tuple)"""
    request = namedtuple("request", ["orginalDocName", "newDocName", "numPages", "pagesToRemove"])
    if(len(sys.argv)==1):
        print("name of the doc")
        request.orginalDocName = input()
        print("name of the output doc")
        request.newDocName = input()
    else:
        request.orginalDocName = sys.argv[1]
        request.newDocName = sys.argv[2]
    print("num of pages in doc")
    request.numPages = int(input())
    request.pagesToRemove = []
    pageRemoval = -1
    print("enter the pages that you want removed")

    while pageRemoval != "":
        pageRemoval = input()
        if pageRemoval.isdigit():
            pageRemoval = int(pageRemoval)
            if pageRemoval >= 1 and pageRemoval <= request.numPages:
                request.pagesToRemove.append(pageRemoval)
            else:
                print("this is not a page within bounds 1-%s" % request.numPages)
    return request

def cmdGen(requestu):
    """Formats the command that we want based on the usere request"""
    toolName = "pdftk"
    correctNums = " ".join([str(x) for x in range(1, request.numPages+1) if x not in request.pagesToRemove])
    cmd = "%s %s cat %s output %s"%(toolName, request.orginalDocName, correctNums, request.newDocName)
    return cmd

request = collectUserData()
#print(cmdGen(request))
os.system(cmdGen(request))


#!/usr/bin/env python
"""
Serve your awesome snippet via HTTP
"""
from gevent import monkey; monkey.patch_all()

import inspect
import functools
import importlib

import bottle

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

#
# configurations
#
MODULES = ['os.path']

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

# import all function from specified modules
modules = [importlib.import_module(m) for m in MODULES]
functions = [f for m in modules for f in vars(m).values() if inspect.isfunction(f)]

#
# helper functions
#
def generate_route(f):
    # get module name for specified function
    modulename = inspect.getmodule(f).__name__

    # get function name
    name = f.__name__

    # done
    return '/%s/%s' % (modulename, name)

#
# routes
#
@bottle.route('/', method=['GET'])
def index():
    """
    Display list of all available functions and their signature
    """
    template = """

Webapizer Server

                Function
                Signature

            % for url, signature in sorted(funclist):

                {{ url }}

{{ signature }}

            % end

    """
    funclist = [(generate_route(f), repr(inspect.getargspec(f).args)) for f in functions]
    return bottle.template(template, funclist=funclist)

def handler(f, *args):
    """
    Invoke function with provided arguments
    """
    return f(*args, **bottle.request.params)

# register route for all functions
for f in functions:
    # generate route for this function
    route = generate_route(f)

    # register
    bottle.route(route, ['GET', 'POST'], functools.partial(handler, f))

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

if __name__ == '__main__':
    # run
    bottle.debug(True)
    bottle.run(host='localhost', port=8888, debug=True, server='gevent')


#  Description: Getting the number of combinations for 0 to 52 cards

def main():

    #making factorial function
    def factorial(num):
        fact = 1
        for i in range (1,num+1):
            fact *= i
        return fact

    #combination function
    def combinations(n,r):
        x = factorial(n)
        y = factorial(r)
        z = factorial(n-r)
        integer = x // (y*z)
        return integer

    #header
    print()
    print("Cards",end='')
    print(format("Combinations",">17s"))
    print("="*22)

    #printing numbers of cards and their combinations
    for i in range(0,53):
        print(format(i,">3d"),end="")
        print(format(combinations(52,i),">19d"))
    print()

main()


import cv2 as cv
import datetime
import os
import time

def camera_shoot():
    camera=cv.VideoCapture(0)
    r,frame = camera.read()
    folder='images/'
    if not os.path.exists(folder):
        os.makedirs(folder)
    if r:
        filename = f"Login_on_{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.jpg"
        path=os.path.join(folder,filename)
        cv.imwrite(path,frame)
        #printf("Image Saved");

        #Video record
        format=cv.VideoWriter_fourcc(*'mp4v')
        out=cv.VideoWriter(f"{folder}Login_on_{filename}.mp4",format,30.0,(640,480))
        start_time=time.time()
        while True:
            r,frame = camera.read()
            out.write(frame)
            remain_time = time.time()-start_time
            if remain_time >= 10:
                out.release()
                break
    camera.release()
    cv.destroyAllWindows()

camera_shoot()


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

import pexpect
actions = [
    ('', '# ', 'starting'),
    ('power on', 'Changing power on succeeded', ''),
    ('discoverable on', 'Changing discoverable on succeeded', ''),
    ('connect B8:09:8A:F3:ED:FC', 'Connection succeedful', 'connecting keyboard'),
    ('connect E8:80:2E:E6:D6:0E', 'Connection succeedful', 'connecting touchpad'),
    ('connect 2C:41:A1:47:69:F5', 'Connection succeedful', 'connecting speaker'),
    ('exit', '', ''),
]

cmd = 'bluetoothctl'
print(f'Running cmd:{cmd}')
ctl = pexpect.spawn(cmd)
for action, expect, memo in actions:
    try:
        print(memo if memo else action)
        if action: ctl.sendline(action)
        if expect: idx = ctl.expect(expect, timeout=5)
    except pexpect.EOF:
        print("EOF")
    except pexpect.TIMEOUT:
        print("TIMEOUT")
ctl.close()


from flask import render_template,redirect,session,request, flash
from flask_app import app
from flask_app.models.user import User
from flask_app.models.band import Band

@app.route('/new/band')
def new_band():
    if 'user_id' not in session:
        return redirect('/logout')
    data = {
        "id":session['user_id']
    }
    return render_template('new_band.html',user=User.get_by_id(data))

@app.route('/create/band',methods=['POST'])
def create_band():
    if 'user_id' not in session:
        return redirect('/logout')
    if not Band.validate_band(request.form):
        return redirect('/new/band')
    data = {
        "name": request.form["name"],
        "genre": request.form["genre"],
        "home_city": request.form["home_city"],
        "founders_id": session["user_id"]
    }
    Band.save(data)
    return redirect('/home')

@app.route('/edit/band/<int:id>')
def edit_band(id):
    if 'user_id' not in session:
        return redirect('/logout')
    data = {
        "id":id
    }
    user_data = {
        "id":session['user_id']
    }
    return render_template("edit_band.html",edit=Band.get_one(data),user=User.get_by_id(user_data))

@app.route('/update/band',methods=['POST'])
def update_band():
    if 'user_id' not in session:
        return redirect('/logout')
    if not Band.validate_band(request.form):
        return redirect('/new/band')
    data = {
        "name": request.form["name"],
        "genre": request.form["genre"],
        "home_city": request.form["home_city"],
        "id": request.form['id']
    }
    Band.update(data)
    return redirect('/home')

@app.route('/show/band/<int:id>')
def show_band(id):
    if 'user_id' not in session:
        return redirect('/logout')
    data = {
        "id":id
    }
    user_data = {
        "id":session['user_id']
    }
    return render_template("show_band.html",band=Band.get_one(data),user=User.get_by_id(user_data))

@app.route('/destroy/band/<int:id>')
def destroy_band(id):
    if 'user_id' not in session:
        return redirect('/logout')
    data = {
        "id":id
    }
    Band.destroy(data)
    return redirect('/home')


from urllib import parse
from django import template

register = template.Library()

def video_embed(context, url):
    url_data = urlparse.urlparse(url)
    query = urlparse.parse_qs(url_data.query)
    try:
        video_id = query["v"][0]
        context['embed_url'] = ('http://youtube.com/embed/%s' % video_id)
    except KeyError:
        context['video_url'] = url
    return context('trail_detail.html', {'youtube_video': youtube_video})


try:
   T = int(input())
except:
   T = 0

for _ in range(T):
    N, K= map(int, input().rstrip().split())
    Dict_words_arr = list(map(str, input().rstrip().split()))
    phrases = []

    for i in range(K):
       phrase = list(map(str,input().rstrip().split()))
       phrases.append(phrase)

    Flag = 0
    res = []
    for i in range(N):
        Flag = 0
        for j in range(K):
            if Dict_words_arr[i] in phrases[j]:
                Flag = 1
                break
        if Flag == 1:
             res.append("YES")
        else:
             res.append("NO")

    print(*res)


import paho.mqtt.client as mqtt
import json
import datetime

from pyparsing import one_of

client = mqtt.Client("room-controller")

# sensing topics
# 326project/smartbuilding/hvac/<floorno>/<roomno>/temperature
tempSensorTopic = "326project/smartbuilding/hvac/0/0/temperature"
tempSensorTopic2 = "326project/smartbuilding/hvac/0/1/temperature"
# 326project/smartbuilding/hvac/<floorno>/<roomno>/pressure
presSensorTopic = "326project/smartbuilding/hvac/0/0/pressure"
presSensorTopic2 = "326project/smartbuilding/hvac/0/1/pressure"

# control topics
# 326project/smartbuilding/hvac/<floorno>/<roomno>/control/ahu
ahuControlTopic = "326project/smartbuilding/hvac/0/0/control/ahu"
ahuControlTopic2 = "326project/smartbuilding/hvac/0/1/control/ahu"

# change threasholds
# 326project/smartbuilding/hvac/<floorno>/<roomno>/control/temp-thresh
tempThreasholdChangeTopic = "326project/smartbuilding/hvac/0/0/control/temp-thresh"
tempThreasholdChangeTopic2 = "326project/smartbuilding/hvac/0/1/control/temp-thresh"
# 326project/smartbuilding/hvac/<floorno>/<roomno>/control/pressure-thresh
pressureThreasholdChangeTopic = "326project/smartbuilding/hvac/0/0/control/pressure-thresh"
pressureThreasholdChangeTopic2 = "326project/smartbuilding/hvac/0/1/control/pressure-thresh"

tempThreashold = 30 # default
tempThreashold2 = 30 # default

pressureThreashold = 1 # default
pressureThreashold2 = 1 # default

# allowed ranges
tempCanChange = 1
tempCanChange2 = 1

pressureCanChange = 0.1
pressureCanChange2 = 0.1

# previous values
previousBlowerSpeed = 40 # default
previousBlowerSpeed2 = 40 # default

previousRatio = 0.3 # default
previousRatio2 = 0.3 # default

def on_message_for_temp(client, userdata, message):
    data = json.loads(message.payload)
    values = list(data.values())
    temperature = values[1]

    global previousBlowerSpeed
    global previousRatio

    if (temperature < (tempThreashold - tempCanChange)):  # increase the ratio by 0.1
        previousRatio += 0.1
        if previousRatio > 1:
            previousRatio = 1
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed,
            "ratio": round(previousRatio, 2)
        }
        client.publish(ahuControlTopic, json.dumps(x))
        print("published to topic " + ahuControlTopic + " new ratio - " + str(previousRatio))

    elif (temperature > tempThreashold + tempCanChange):
        previousRatio -= 0.1
        if previousRatio < 0:
            previousRatio = 0

        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed,
            "ratio": round(previousRatio, 2)
        }
        client.publish(ahuControlTopic, json.dumps(x))
        print("published to topic " + ahuControlTopic + " new ratio - " + str(previousRatio))

def on_message_for_pressure(client, userdata, message):
    data = json.loads(message.payload)
    values = list(data.values())
    pressure = values[1]

    global previousBlowerSpeed
    global previousRatio

    if (pressure < (pressureThreashold - pressureCanChange)):  # increase the blower speed by 1
        previousBlowerSpeed = min(previousBlowerSpeed+1, 100)
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed,
            "ratio": round(previousRatio, 2)
        }
        client.publish(ahuControlTopic, json.dumps(x))
        print("published to topic " + ahuControlTopic + " new blower speed - " + str(previousBlowerSpeed))

    elif (pressure > pressureThreashold + pressureCanChange):
        previousBlowerSpeed = max(previousBlowerSpeed-1, 0)
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed,
            "ratio": round(previousRatio, 2)
        }
        client.publish(ahuControlTopic, json.dumps(x))
        print("published to topic " + ahuControlTopic + " new blower speed - " + str(previousBlowerSpeed))

##### Change threasholds

# changing temp threashold
def on_message_for_temp_threshold(client, userdata, message):
    data = json.loads(message.payload)

    global tempThreashold
    values = list(data.values())
    tempThreashold = values[1]
    print()
    print("**********************************")
    print("new threashold temperature is " + str(tempThreashold))
    print("**********************************")
    print()

# changing pressure threashold
def on_message_for_pressure_threshold(client, userdata, message):
    data = json.loads(message.payload)
    global pressureThreashold
    values = list(data.values())
    pressureThreashold = values[1]
    print()
    print("**********************************")
    print("new threashold pressure is " + str(pressureThreashold))
    print("**********************************")
    print()

# ---------------------------------------------------------------------------------------------------------------------
def on_message_for_temp2(client, userdata, message):
    data = json.loads(message.payload)
    values = list(data.values())
    temperature = values[1]

    global previousBlowerSpeed2
    global previousRatio2

    if (temperature < (tempThreashold2 - tempCanChange2)):  # increase the ratio by 0.1
        previousRatio2 += 0.1
        if previousRatio2 > 1:
            previousRatio2 = 1
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed2,
            "ratio": round(previousRatio2, 2)
        }
        client.publish(ahuControlTopic2, json.dumps(x))
        print("published to topic " + ahuControlTopic2 + " new ratio - " + str(previousRatio2))

    elif (temperature > tempThreashold2 + tempCanChange2):
        previousRatio2 -= 0.1
        if previousRatio2 < 0:
            previousRatio2 = 0

        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed2,
            "ratio": round(previousRatio2, 2)
        }
        client.publish(ahuControlTopic2, json.dumps(x))
        print("published to topic " + ahuControlTopic2 + " new ratio - " + str(previousRatio2))

def on_message_for_pressure2(client, userdata, message):
    data = json.loads(message.payload)
    values = list(data.values())
    pressure = values[1]

    global previousBlowerSpeed2
    global previousRatio2

    if (pressure < (pressureThreashold2 - pressureCanChange2)):  # increase the blower speed by 1
        previousBlowerSpeed2 = min(previousBlowerSpeed2+1, 100)
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed2,
            "ratio": round(previousRatio2, 2)
        }
        client.publish(ahuControlTopic2, json.dumps(x))
        print("published to topic " + ahuControlTopic2 + " new blower speed - " + str(previousBlowerSpeed2))

    elif (pressure > pressureThreashold2 + pressureCanChange2):
        previousBlowerSpeed2 = max(previousBlowerSpeed2-1, 0)
        x = {
            "time": datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S'),
            "speed": previousBlowerSpeed2,
            "ratio": round(previousRatio2, 2)
        }
        client.publish(ahuControlTopic2, json.dumps(x))
        print("published to topic " + ahuControlTopic2 + " new blower speed - " + str(previousBlowerSpeed2))

##### Change threasholds

# changing temp threashold2
def on_message_for_temp_threshold2(client, userdata, message):
    data = json.loads(message.payload)

    global tempThreashold2
    values = list(data.values())
    tempThreashold2 = values[1]
    print()
    print("**********************************")
    print("new threashold temperature is " + str(tempThreashold2))
    print("**********************************")
    print()

# changing pressure threashold
def on_message_for_pressure_threshold2(client, userdata, message):
    data = json.loads(message.payload)

    global pressureThreashold2
    values = list(data.values())
    pressureThreashold2 = values[1]
    print()
    print("**********************************")
    print("new threashold pressure is " + str(pressureThreashold2))
    print("**********************************")
    print()

client.message_callback_add(tempSensorTopic, on_message_for_temp)
client.message_callback_add(presSensorTopic, on_message_for_pressure)
client.message_callback_add(tempThreasholdChangeTopic, on_message_for_temp_threshold)
client.message_callback_add(pressureThreasholdChangeTopic, on_message_for_pressure_threshold)

client.message_callback_add(tempSensorTopic2, on_message_for_temp2)
client.message_callback_add(presSensorTopic2, on_message_for_pressure2)
client.message_callback_add(tempThreasholdChangeTopic2, on_message_for_temp_threshold2)
client.message_callback_add(pressureThreasholdChangeTopic2, on_message_for_pressure_threshold2)

client.connect("10.40.18.10", port=1883)

client.subscribe([(tempSensorTopic, 0), (presSensorTopic, 0),
                  (tempThreasholdChangeTopic, 0), (pressureThreasholdChangeTopic, 0),
                  (tempSensorTopic2, 0), (presSensorTopic2, 0),
                  (tempThreasholdChangeTopic2, 0), (pressureThreasholdChangeTopic2, 0)
                  ])
client.loop_forever()


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

import main_fee_dialog
from PyQt5.QtWidgets import QDialog, QComboBox, QLineEdit,QDateTimeEdit,QDateEdit
from PyQt5.QtCore import pyqtSignal, QDateTime

class FeeDialog(QDialog, main_fee_dialog.Ui_Dialog):
    _dataSignal = pyqtSignal(type({}))

    def __init__(self, parentNew=None):
        self.parentWindow = parentNew
        QDialog.__init__(self, parentNew)
        self.setupUi(self)
        self.dateTimeEdit_fdate.setDisplayFormat("yyyy-MM-dd HH:mm:ss")

        self.pushButton_submit.clicked.connect(self.data_slot)
        self.pushButton_exit.clicked.connect(self.close_slot)

    def fill_data(self, record):
        """
        父窗口传入子窗口数据
        :param record: tuple
        :return: None
        """
        self.lineEdit_fno.setText(record[0])
        self.lineEdit_fnumber.setText(record[1])
        Vtime = QDateTime.fromString(record[6], "yyyy-MM-dd HH:mm:ss")
        self.dateTimeEdit_fdate.setDateTime(Vtime)
        self.lineEdit_rno.setText(record[3])
        self.lineEdit_cno.setText(record[4])
        self.lineEdit_pno.setText(record[5])
        self.lineEdit_frecipefee.setText(record[6])
        self.lineEdit_fdiscount.setText(record[7])
        self.lineEdit_fsum.setText(record[8])

    def data_slot(self):
        data = {'fno': "{}".format(self.lineEdit_fno.text()),
                'fnumber': "{}".format(self.lineEdit_fnumber.text()),
                'fdate': "'{}'".format(self.dateTimeEdit_fdate.text()),
                'rno': "{}".format(self.lineEdit_rno.text()),
                'cno': "{}".format(self.lineEdit_cno.text()),
                'pno': "'{}'".format(self.lineEdit_pno.text()),
                'frecipefee': "{}".format(self.lineEdit_frecipefee.text()),
                'fdiscount': "{}".format(self.lineEdit_fdiscount.text()),
                'fsum': "{}".format(self.lineEdit_fsum.text()),
                }
        self._dataSignal.emit(data)
        self.close()

    def close_slot(self):
        self.close()


import logging
import argparse
from time import sleep

from telegram_notifier import telegram_notify
from settings import token

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

logger = logging.getLogger(__name__)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--username', dest='uname')
    parser.add_argument('--message', dest='msg')
    args = parser.parse_args()

    @telegram_notify(token, args.uname, args.msg)
    def fn():
        sleep(10)

    fn()


#######################################################################
# GROUP 23
# CITY: Melbourne
# MEMBERS:
#  - Vitaly Yakutenko - 976504
#  - Shireen Hassan - 972461
#  - Himagna Erla - 975172
#  - Areeb Moin - 899193
#  - Syed Muhammad Dawer - 923859
#######################################################################
import json
import os
import time
import yaml
import pandas as pd
from glob import glob
from shapely.geometry import Point, Polygon
from api.couch_db import TweetsDB

def australia_check(coordinates):
    australia = [[109.94541423022338,-9.67869330662115],[155.03330484714022,-9.67869330662115],[155.03330484714022,-39.93552098705151],[109.94541423022338,-39.93552098705151]]
    australia_box = Polygon(australia)
    if isinstance(coordinates[0], list):              #check if polygon
        coordinate_polygon = Polygon(coordinates[0])
        pnt = Point(coordinate_polygon.centroid)

    else:
        pnt = Point(coordinates)

    if australia_box.contains(pnt):
        return True
    else:
        return False

def geo_check(coordinates):
    if isinstance(coordinates[0], list):              #check if polygon
        coordinate_polygon = Polygon(coordinates[0])
        pnt = Point(coordinate_polygon.centroid)

    else:
        pnt = Point(coordinates)

    for i in range(len(features)):
        for j in range(len(features[i]['geometry']['coordinates'])):

            poly = Polygon(features[i]['geometry']['coordinates'][j][0])
            idx = int(features[i]['properties']['sa4_code16'])

            if pnt.within(poly):
                return {'SA4_name':features[i]['properties']['feature_name'],
                        'SA4_code':idx,
                        'GCCSA_name':mappings_df.loc[idx]['GCCSA_NAME_2016'],
                        'GCCSA_code':mappings_df.loc[idx]['GCCSA_CODE_2016'],
                        'State_name':mappings_df.loc[idx]['STATE_NAME_2016']}
                break

            elif pnt.touches(poly):
                return {'SA4_name':features[i]['properties']['feature_name'],
                        'SA4_code':idx,
                        'GCCSA_name':mappings_df.loc[idx]['GCCSA_NAME_2016'],
                        'GCCSA_code':mappings_df.loc[idx]['GCCSA_CODE_2016'],
                        'State_name':mappings_df.loc[idx]['STATE_NAME_2016']}
                break

def none_geo_check(coordinates):
    dist_from_point = []
    dist_point_id = []
    if isinstance(coordinates[0], list):              #check if polygon
        coordinate_polygon = Polygon(coordinates[0])
        pnt = Point(coordinate_polygon.centroid)

    else:
        pnt = Point(coordinates)

    for i in range(len(features)):
        for j in range(len(features[i]['geometry']['coordinates'])):

            poly = Polygon(features[i]['geometry']['coordinates'][j][0])

            dist_from_point.append(poly.exterior.distance(pnt))
            dist_point_id.append(i)

    min_index = dist_point_id[dist_from_point.index(min(dist_from_point))]
    idx = int(features[min_index]['properties']['sa4_code16'])
    return {'SA4_name':features[i]['properties']['feature_name'],
                        'SA4_code':idx,
                        'GCCSA_name':mappings_df.loc[idx]['GCCSA_NAME_2016'],
                        'GCCSA_code':mappings_df.loc[idx]['GCCSA_CODE_2016'],
                        'State_name':mappings_df.loc[idx]['STATE_NAME_2016']}

print('Starting application...')

os.chdir('../')

with open("config.yaml", 'r') as ymlfile:
    cfg = yaml.load(ymlfile)
    ymlfile.close()

#db connections
couch_db_conf = cfg['COUCHDB']
#create an instance of TWEETSDB and pass the connection details
couch_db = TweetsDB(couch_db_conf)

sa2_australia = cfg['AURIN_DATA']['sa2_australia']
df = pd.read_csv(sa2_australia)

columns = ['SA4_CODE_2016', 'SA4_NAME_2016', 'GCCSA_NAME_2016', 'STATE_NAME_2016','GCCSA_CODE_2016']

mappings_df = df[columns].drop_duplicates().set_index('SA4_CODE_2016')
mappings_df.head()

sa4_geo_tag = cfg['AURIN_DATA']['sa4_data_for_geo']
with open(sa4_geo_tag, 'r') as fp:
    data = json.load(fp)
    fp.close()

features = data['features']

geo_tasks_path= cfg['QUEUES']['geo_tasks']

print('Initialisation finished.')
print('Starting processing queue ...')
i = 1

couch_db = TweetsDB(couch_db_conf)

while True:
    try:
        geo_tweets = glob('{}/*.txt'.format(geo_tasks_path))[:1000]

        for path in geo_tweets:
            try:
                tweet_id = path.split('/')[-1].split('.')[0]
                with open(path, 'r') as fp:
                    geo = json.load(fp)
                    fp.close()
                geo_doc =geo_check(geo['coordinates'])
                #if australia_check(geo['coordinates']):         #geotag only if in Australia
                if geo_doc== None:
                    none_geo = none_geo_check(geo['coordinates'])
                    couch_db.update_document(tweet_id,none_geo)
                    print('Task {} was processed.'.format(path))
                    try:
                        os.remove(path)
                    except OSError as e:
                            ## if failed, report it back to the user ##
                        print ("Error: {} - {},".format(e.filename,e.strerror))
                else:
                    couch_db.update_document(tweet_id,geo_doc)
                    print('Task {} was processed.'.format(path))
                    try:
                        os.remove(path)
                    except OSError as e:
                            ## if failed, report it back to the user ##
                        print ("Error: {} - {},".format(e.filename,e.strerror))

            except Exception as e:
                print('Tweet {} wasn\'t geotagged and updated on DB due to error. {}'.format(tweet_id, e))
                couch_db.reconnect()

        print('Iteration: {}\tFiles processed: {}'.format(i, len(geo_tweets)))

    except Exception as e:
        couch_db.reconnect()

    i+=1
    time.sleep(1)


from __future__ import absolute_import, print_function, unicode_literals

class ErrorCodes(object):
    # 数据平台的平台代码--7位错误码的前2位
    BKDATA_PLAT_CODE = "15"
    # 数据平台子模块代码--7位错误码的3，4位
    BKDATA_METADATA = "30"

class MetaDataErrorCodes(object):
    COMMON = 000
    CLIENT = 500
    TASK = 550

    def __init_(
        self,
        parent_err_codes=ErrorCodes,
    ):
        self.parent_err_codes = parent_err_codes
        for k, v in vars(self.__class__).items():
            if k.isupper():
                setattr(self, k, self.full_error_code(v))

    def full_error_code(self, sub_code):
        return int(
            self.parent_err_codes.BKDATA_PLAT_CODE
            + self.parent_err_codes.BKDATA_METADATA
            + str(sub_code)
        )

class StandardErrorMixIn(Exception):
    code = None
    msg_template = None
    default_msg = None
    data = None

    def __init__(self, *args, **kwargs):
        if "message_kv" in kwargs:
            if not args:
                message = self.msg_template.format(**kwargs[str("message_kv")])
            elif len(args) == 1:
                message = args[0].format(**kwargs[str("message_kv")])
            else:
                raise TypeError(
                    "Multi args and message_kv is not allowed at same time in standard error."
                )
        elif args:
            if len(args) == 1:
                message = args[0]
            else:
                message = self.msg_template.format(*args)
        else:
            message = self.default_msg

        self.data = {}
        if "data" in kwargs:
            data = kwargs.pop(str("data"))
            if not isinstance(data, dict):
                self.data["content"] = data
            else:
                self.data.update(data)

        if message:
            super(StandardErrorMixIn, self).__init__(
                message.encode("utf8") if isinstance(message, str) else message
            )
        else:
            super(StandardErrorMixIn, self).__init__()

class MetaDataError(StandardErrorMixIn, Exception):
    code = MetaDataErrorCodes().COMMON
    msg_template = "MetaData System Error: {error}."

class MetaDataTaskError(MetaDataError):
    code = MetaDataErrorCodes().TASK + 1
    msg_template = "MetaData Task Error: {error}."


import csv
import time
import operator
from collections import defaultdict, namedtuple
from operator import itemgetter
import matplotlib.pyplot as plt
import numpy as np
from collections import defaultdict
from datetime import datetime
import time

class PlotSpi:
	def __init__(self, logfile):
		self.logfilepath = "logs/" + logfile
	def readCSV(self):
		csv_file = open(self.logfilepath, mode='r')
		data = csv.DictReader(csv_file)
		return data
	def parselog(self, logtype):
		logdata = self.readCSV()
		num_log = len(logtype)
		log_dict = {}
		val_array = []
		for x in range(num_log):
			val_array.append([])
			log_dict[logtype[x]]=x
		flag=1
		for row in logdata:
			if flag:
				initial_time = time.mktime(datetime.strptime(row["timestamp"], "%Y-%m-%d %H:%M:%S").timetuple())
				flag=0
			val_array[log_dict[row["logid"]]].append((time.mktime(datetime.strptime(row["timestamp"], "%Y-%m-%d %H:%M:%S").timetuple()) - initial_time, row["timetaken"]))
		for x in range(num_log):
			plt.figure(x)
			x_val = [p[0] for p in val_array[x]]
			y_val = [float(p[1]) for p in val_array[x]]
			plt.plot(x_val, y_val)
			plt.title(logtype[x])
			plt.xlabel("simulation time")
			plt.ylabel(logtype[x]+"in milliseconds")
			plt.savefig(logtype[x]+"performance")

			plt.figure(x+num_log)
			plt.boxplot(x_val,y_val)
			plt.xlabel("Number of samples")
			plt.ylabel(logtype[x]+"in milliseconds")
			plt.savefig(logtype[x]+"performance_box", bbox_inches='tight')

def main():
	logfile = "./log.csv"
	inst = PlotSpi(logfile)
	inst_data = inst.parselog(["REGISTER", "SIGN_GS", "SIGN_HY", "VERIFYGM"])

main()


# time:  O(A logA + B logB)
def sum_swap(A, B):
    A.sort()
    B.sort()
    sum1 = sum(A)
    sum2 = sum(B)
    target = (sum1 - sum2) / 2

    min = float('inf')
    pair = None
    i = 0
    j = 0
    while i < len(A) and j < len(B):
        diff = A[i] - B[j]
        if diff == target:
            return (A[i], B[j])
        if abs(diff - target) < min:
            min = abs(diff - target)
            pair = (A[i], B[j])
        if diff < target:
            i += 1
        else:
            j += 1
    return pair

cases = [
    ([4,1,2,3], [3,5,2,6]),
    ([4,1,2,3], [-1,9,2,6]),
    ([4,0,2,3], [3,5,2,6]),
]
for A, B in cases:
    print(sum_swap(A, B))


import os
import shutil
from re import findall
from sys import argv, exit

if len(argv) < 2:
    print("Video directory not given")
    exit(1)

def move(direc):
    print(os.listdir(direc))
    for vid in os.listdir(direc):
        format = findall(r"\.\w{3}", vid)
        mod_chap = findall(r"mo?d?\d+\-?.*\-\d+", vid)
        if mod_chap:
            print(f"Moving {vid} -> {mod_chap}")
            shutil.move(direc+"/"+vid, direc+"/"+mod_chap[0]+format[0])

for direc in argv[1:]:
    move(direc)


import os

def chType(obj):
    """
        Aggressive  checking !
    """
    if os.path.isfile(obj):
        return True
    elif os.path.isdir(obj):
        return False
    else:
        try:
            open(obj).close()
            return True
        except FileNotFoundError:
            # IDK maybe need True
            return False
        except PermissionError:
            return False
        except OSError:
            return False

def fixWarpPath(text: str):
    if text.__len__() > 20:
        return f"{text[0:8]}..{text[-10:]}"

    return text

def getSubFolder(s_path, d_path):
    basename = os.path.basename(s_path)
    return d_path[d_path.find(basename) + len(basename)+1:]

def idValid(_id: str):

    if _id.__len__() > 9:
        return 0

    size_of_id = 0
    for index, number in enumerate(_id):
        num_id = int(number)
        result = str(num_id * ((index % 2)+1))
        if result.__len__() % 2 == 0:
            result = str(int(result[0])+int(result[1]))
        size_of_id += int(result)

    return size_of_id % 10 == 0


import pyro
import pyro.distributions as dist

# This section introduces the notion of exploiting conditional independence between
# variables to run VI in minibatches.
# To allow Pyro to use minibatches, we need to tell it that the observational vars
# obs_i are independent. We draw on the "plate" idea in graphical model, indicating
# the obs_i's are actually replicates of each other, independent and generated given
# "latent_fairness".

def model(data):
    f = pyro.sample("latent_fairness", dist.Beta(alpha0, beta0))
    # loop over the observed data [WE ONLY CHANGE THE NEXT LINE]
    for i in pyro.plate("data_loop", len(data)):
        pyro.sample("obs_{}".format(i), dist.Bernoulli(f), obs=data[i])

# tensorized version
def model_tensor(data):
    f = pyro.sample("latent_fairness", dist.Beta(alpha0, beta0))

    with plate('observe_data'):
        pyro.sample('obs', dist.Bernoulli(f), obs=data)

# automatic (random) subsampling
# the idea is the .step() and .evaluate_loss() functions of the SVI estimator will
# use minibatches, much like how neural network trains in minibatches
# the loss at each time step will be scaled by dataset_size/minibatch_size
# the scaling is why we need to tell plate both the dataset size and minibatch size

with plate('observe_data', size=10, subsample_size=5) as ind:
    pyro.sample('obs', dist.Bernoulli(f),
                obs=data.index_select(0, ind))

# one problem is plate by default uses a random sampling, instead you maay want to
# make sure you iterate over the entire dataset, even if the  minibatches are random
# see the docs for customer subsampling strategies.

# This tutorial gets a bit more complicated. There are a couple of other major ideas
# (which seem too advanced to be relevant). One is the notion of thinking about
# nontrivial cases where independence exists between variables. The second is using
# "plate" in complex ways, by putting it into the "guide", by recursing it, etc.


import time
import requests
import json
import xlwt
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import BackendApplicationClient as BAC

#Client ID and Secret acquired through PGA Website
client_id = r'id'
client_secret = r'secret'

#Create Backend App Client for OAuth
client = BAC(client_id=client_id)
oauth = OAuth2Session(client=client)
#Generate Token from PGA Tour API
myToken = oauth.fetch_token(token_url='url', client_id=client_id, client_secret=client_secret)

#Parse through to eliminate unneccesary data
s = str(myToken)
pieces = s.split(',')
piece = pieces[0].split('\'')
token = piece[3]
print(token) #print token for test purposes, remove later

#Request leaderboard data from pgatour link using a point in time example
myUrl = 'PointInTimeURL'
result = requests.get(myUrl, headers={'Content-Type':'application/json', 'Authorization': 'Bearer {}'.format(token)})

#Convert request data into json data
data = result.json()

#Get all values from leaderboard section
leaderboard = []
for key in data[0]:
    if key == 'leaderboard':
        leaderboard = data[0].get(key)

#Parse through data until a readable format is attained
values = []
for key in leaderboard:
    values.append(key)
players = []
for key in values:
    players.append(key)

keys = ['p_id', 'name', 'first_name', 'last_name', 'amateur', 'country',
'status', 'GrpNum', 'feat_grp', 'start_hole', 'tee_time', 'position',
'total', 'round_score', 'thru', 'movement', 'maxrnd', 'courseacronym', 'course_id']

print("Creating Excel Sheet...")
book = xlwt.Workbook(encoding="utf-8")

sheet1 = book.add_sheet("Sheet 1")

i = 0
for k in keys:
    sheet1.write(0, i, k)
    i = i+1

i = 1
j = 0
for s in players:
    j = 0
    for k in keys:
        sheet1.write(i, j, s[k])
        j = j+1
    i = i+1
book.save("PGAData.xls")
print("Excel Sheet Successfully created.")
#Wait 60 seconds so the program does not overload the server
print("waiting...")
time.sleep(60)
print("done")


from bs4 import BeautifulSoup
from time import sleep
import time
import requests
from random import randint
from html.parser import HTMLParser
import json

USER_AGENT = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
searching_url='https://html.duckduckgo.com/html/?q='
class SearchEngine:
	@staticmethod
	def search(query, sleep=True):
		if sleep: # Prevents loading too many pages too soon
			sleeptime = randint(10, 100)
			print("sleep for "+ str(sleeptime) +" seconds.")
			time.sleep(sleeptime)
		temp_url = '+'.join(query.split()) #for adding + between words for the query
		url = searching_url + temp_url
		#print(url)
		soup = BeautifulSoup(requests.get(url, headers=USER_AGENT).text,"html.parser")
		#print(soup)
		new_results = SearchEngine.scrape_search_result(soup)
		return new_results
	@staticmethod
	def scrape_search_result(soup):
		raw_results = soup.find_all("a", attrs = {"class" : "result__a"})
		results = []
		#implement a check to get only 10 results and also check that URLs must not be duplicated
		for result in raw_results:
			link = result.get('href')
			results.append(link)
		return results

def writeJson(dictionary):
  # Serializing json
	json_object = json.dumps(dictionary, indent=4)
	# Writing to sample.json
	with open("hw1.json", "w") as outfile:
		outfile.write(json_object)
def readJson():
  with open('hw1.json', 'r') as openfile:
    json_object = json.load(openfile)
    return json_object

resJSON={}
queries = []
with open('100QueriesSet4.txt') as f:
	while(True):
		line = f.readline()
		if(line):
			line = line[:-2]
			queries.append(line)
		else:
			break
f.close()
queries0 = queries[0:1]
queries1 = queries[0:25]
queries2 = queries[25:50]
queries3 = queries[50:75]
queries4 = queries[75:100]
for queryStr in queries4:
  resJSON=readJson()
  result = SearchEngine.search(queryStr,sleep=True)
  result= list(dict.fromkeys(result))
  print(queryStr)
  print(len(result))
  resJSON[queryStr]=result[:10]
  #print(resJSON)
  writeJson(resJSON)


from respect_validation.Exceptions.FilteredValidationException import FilteredValidationException

class AlphaException(FilteredValidationException):

    _default_templates = {
        'default': {
            'standard': '{name} must contain only letters (a-z)',
            'extra': '{name} must contain only letters (a-z) and {additional_chars}',
        },
        'negative': {
            'standard': '{name} must not contain letters (a-z)',
            'extra': '{name} must not contain letters (a-z) or {additional_chars}',
        }
    }


from random import randint, choice

def get_in(xs):
    if xs == []:
        return None
    else:
        return choice(xs)

def get_out(xs):
    if xs == []:
        return randint(0, 100)
    else:
        candidate = xs[0]
        while candidate in xs:
            candidate = randint(0, 100)
        return candidate

print("randomness = [")
for _ in range(1000):
    xs = [ randint(0, 100) for _ in range(randint(0, 20)) ]
    x_in = get_in(xs)
    x_out = get_out(xs)
    print("  (", xs, ",", x_in, ",", x_out, "),")
print("]")


#!/usr/bin/env python3

import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC, LinearSVC	#support vector machine
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.naive_bayes import GaussianNB
from xgboost import XGBClassifier

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

#-------------------
# ingest & clean
#-------------------
train_data = pd.read_csv('data/train.csv')
# printing the count for the data will let you kow if there's any missing data
# so you know what to clean
#print(train_data.count())
#print(train_data.describe())

# replace 'male' with 0 and 'female' with 1 in the 'Sex' column
train_data.Sex.replace(
  to_replace=['male', 'female'],
  value=[0, 1],
  inplace=True)

# fill the NaN ages with the mean passenger age
train_data.Age = train_data.Age.fillna(train_data.Age.mean())

# one-hot encoding
train_data = pd.get_dummies(train_data, prefix_sep='_', columns=['Embarked'])
#print(train_data.head())

#----------------------------
# build learning model
#----------------------------
train_y = train_data.Survived

features = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked_C', 'Embarked_Q', 'Embarked_S']
train_X = train_data[features]
#print(train_X.head())

# gotta try them all to see which works best :|
#train_model = RandomForestClassifier()
#train_model = ExtraTreesClassifier()
#train_model = AdaBoostClassifier()
#train_model = GradientBoostingClassifier()
#train_model = LogisticRegression()
#train_model = KNeighborsClassifier()
#train_model = DecisionTreeClassifier()
#train_model = SVC()
#train_model = LinearSVC()
#train_model = GaussianProcessClassifier()
#train_model = GaussianNB()
train_model = XGBClassifier()

train_model.fit(train_X, train_y)

#---------------------------
# model validation
#---------------------------
test_data = pd.read_csv('data/test.csv')
#print(test_data.count())
#print(test_data.describe())

# replace 'male' with 0 and 'female' with 1 in the 'Sex' column
test_data.Sex.replace(
  to_replace=['male', 'female'],
  value=[0, 1],
  inplace=True)

test_data.Age = test_data.Age.fillna(test_data.Age.mean())
test_data.Fare = test_data.Fare.fillna(test_data.Fare.mean())

test_data = pd.get_dummies(test_data, prefix_sep='_', columns=['Embarked'])

test_X = test_data[features]
#print(test_X.count())
test_predictions = train_model.predict(test_X)
print(test_predictions)

result = pd.DataFrame(
  {
    'PassengerId': test_data.PassengerId,
    'Survived': test_predictions
  },
  columns=['PassengerId', 'Survived']
)

result.to_csv('gender_submission.csv', index=False)


square_len = 1
target = 312051
while square_len ** 2 < target:
    square_len += 2
print(square_len)
index_x_t = None
index_y_t = None
grid = [[0 for i in range(square_len)] for j in range(square_len)]
index_x = index_y = square_len - 1
c = square_len ** 2
for index in range(square_len):
    grid[index_y][index_x] = c
    if c == target:
        index_x_t = index_x
        index_y_t = index_y
    c -= 1
    index_x -= 1

index_x = 0
index_y -= 1
for index in range(square_len - 1):
    grid[index_y][index_x] = c
    if c == target:
        index_x_t = index_x
        index_y_t = index_y
    c -= 1
    index_y -= 1

index_x = 1
index_y = 0
for index in range(square_len - 1):
    grid[index_y][index_x] = c
    if c == target:
        index_x_t = index_x
        index_y_t = index_y
    c -= 1
    index_x += 1

index_x = square_len - 1
index_y = 1
for index in range(square_len - 2):
    grid[index_y][index_x] = c
    if c == target:
        index_x_t = index_x
        index_y_t = index_y
    c -= 1
    index_y += 1

print(index_x_t, index_y_t, abs(index_x_t - square_len // 2), abs(index_y_t - square_len // 2), abs(index_x_t - square_len // 2) + abs(index_y_t - square_len // 2))