#!/usr/bin/python2

"""RotarySwitch for mpd control."""

import os
import select
import subprocess
import time
import logging
import traceback
import signal
import sys

class MPD():

    """ mpd controller."""

    def __init__(self, logger):
        """Initialize thread."""
        self.logger = logger if logger else logging
        self.playlist = []

    def prev_album(self):
        """Play prev album song."""
        self.logger.info("prev album")
        playlist = self.get_playlist()
        pos = self.get_position()
        current_album = playlist[pos]['album']
        self.logger.info("current album: %s" % current_album)
        for prev_count, song in enumerate(reversed(playlist[:pos])):
            if prev_count == 0 and not current_album == song['album']:
                self.logger.info("detect current song is head in album.")
                current_album = song['album']
                self.logger.info("set current album: %s" % current_album)
                continue
            if not current_album == song['album']:
                new_pos = pos - prev_count + 1
                subprocess.check_output(
                    ['/usr/bin/mpc', 'play', str(new_pos)])
                self.logger.info("play %i" % new_pos)
                return
        subprocess.check_output(
            ['/usr/bin/mpc', 'play', '1'])

    def prev(self):
        """Play prev song."""
        self.logger.info("prev")
        subprocess.check_output(
            ['/usr/bin/mpc', 'prev'])

    def pause(self):
        """Pause song."""
        self.logger.info("pause")
        subprocess.check_output(
            ['/usr/bin/mpc', 'pause'])

    def play(self):
        """Play song."""
        self.logger.info("play")
        subprocess.check_output(
            ['/usr/bin/mpc', 'play'])

    def next(self):
        """Play next song."""
        self.logger.info("next")
        subprocess.check_output(
            ['/usr/bin/mpc', 'next'])

    def next_album(self):
        """Play prev album song."""
        self.logger.info("next album")
        playlist = self.get_playlist()
        pos = self.get_position()
        current_album = playlist[pos]['album']
        self.logger.info("current album: %s" % current_album)
        for next_count, song in enumerate(playlist[pos:]):
            if not current_album == song['album']:
                self.logger.info("new album: %s" % song['album'])
                new_pos = pos + next_count + 1
                subprocess.check_output(
                    ['/usr/bin/mpc', 'play', str(new_pos)])
                self.logger.info("play %i" % new_pos)
                return
        subprocess.check_output(
            ['/usr/bin/mpc', 'play', '1'])

    def get_playlist(self):
        """Return playlist."""
        out = subprocess.check_output(
            ['/usr/bin/mpc', 'playlist', '-f', '%album%'])
        return [{'album': i} for i in out.splitlines()]

    def get_position(self):
        """Return playlist playing position."""
        out = subprocess.check_output(
            ['/usr/bin/mpc', '-f', '%position%'])
        return int(out.splitlines()[0]) - 1

class App(object):

    """RotarySwitch for mpd control."""

    def __init__(self, prev_album, prev, pause, play, next, next_album,
                 logger=None):
        """Open gpio for prev/play/next button."""
        self.mpd = MPD(logger)
        self.logger = logger if logger else logging
        self.logger.info("start app")
        self._prev_album = prev_album
        self._prev = prev
        self._pause = pause
        self._play = play
        self._next = next
        self._next_album = next_album
        self._last = self._pause
        signal.signal(signal.SIGTERM, self.exit)
        signal.signal(signal.SIGINT, self.exit)

    def exit(self, signum, frame):
        """display of when exit app."""
        self.logger.info("stop app")
        sys.exit(0)

    def _gpio_read(self, f):
        """read gpio value."""
        f.seek(0)
        out = f.read().strip()
        return out

    def run(self):
        """Wait gpio value is changed."""
        epoll = select.epoll()
        epoll.register(self._prev_album,
                       select.EPOLLIN | select.EPOLLET)
        epoll.register(self._prev,
                       select.EPOLLIN | select.EPOLLET)
        epoll.register(self._pause,
                       select.EPOLLIN | select.EPOLLET)
        epoll.register(self._play,
                       select.EPOLLIN | select.EPOLLET)
        epoll.register(self._next,
                       select.EPOLLIN | select.EPOLLET)
        epoll.register(self._next_album,
                       select.EPOLLIN | select.EPOLLET)
        try:
            while True:
                try:
                    time.sleep(0.1)
                    for fileno, event in epoll.poll():
                        if self._gpio_read(self._prev_album) == '1':
                            if not self._last == self._prev_album:
                                self.mpd.prev_album()
                            self._last = self._prev_album
                        if self._gpio_read(self._prev) == '1':
                            if self._last not in [self._prev_album,
                                                  self._prev]:
                                self.mpd.prev()
                            self._last = self._prev
                        if self._gpio_read(self._pause) == '1':
                            if (self._last not in [self._prev,
                                                   self._prev_album]):
                                self.mpd.pause()
                            self._last = self._pause
                        if self._gpio_read(self._play) == '1':
                            self.mpd.play()
                            self._last = self._play
                        if self._gpio_read(self._next_album) == '1':
                            if not self._last == self._next_album:
                                self.mpd.next_album()
                            self._last = self._next_album
                        if self._gpio_read(self._next) == '1':
                            if self._last not in [self._next,
                                                  self._next_album]:
                                self.mpd.next()
                            self._last = self._next

                except subprocess.CalledProcessError:
                    time.sleep(1)
                except IndexError:
                    time.sleep(1)
        finally:
            epoll.unregister(self._prev_album)
            epoll.unregister(self._prev)
            epoll.unregister(self._pause)
            epoll.unregister(self._play)
            epoll.unregister(self._next)
            epoll.unregister(self._next_album)

def gpio_open(port, mode='r', register='', edge='none', active_low='0'):
    """Open gpio file."""
    if mode not in ['r', 'w']:
        raise Exception('unimplemented mode: %s' % mode)
    if edge not in ['none', 'rising', 'falling', 'both']:
        raise Exception('rtfm')
    port = str(port)
    if os.path.exists('/sys/class/gpio/gpio%s' % port):
        with open('/sys/class/gpio/unexport', 'w') as f:
            f.write(port)
    with open('/sys/class/gpio/export', 'w') as f:
        f.write(port)
    if mode == 'r':
        with open('/sys/class/gpio/gpio%s/direction' % port, 'w') as f:
            f.write('in')
        if register:
            with open('/sys/class/gpio/gpio%s/direction' % port, 'w') as f:
                f.write(register)
    elif mode == 'w':
        with open('/sys/class/gpio/gpio%s/direction' % port, 'w') as f:
            f.write('out')

    with open('/sys/class/gpio/gpio%s/edge' % port, 'w') as f:
        f.write(edge)
    with open('/sys/class/gpio/gpio%s/active_low' % port, 'w') as f:
        f.write(active_low)

    return open('/sys/class/gpio/gpio%s/value' % port, mode)

def main():
    """Run app mainloop."""
    logging.basicConfig(
        filename='/var/log/mpd-button.log',
        format='[%(levelname)s] %(asctime)s [%(name)s] %(message)s',
        datefmt='%Y/%m/%d %H:%M:%S',
        level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    prev_album = gpio_open(22, edge='rising')
    prev = gpio_open(10, edge='rising')
    pause = gpio_open(9, edge='rising')
    play = gpio_open(11, edge='rising')
    next = gpio_open(23, edge='rising')
    next_album = gpio_open(24, edge='rising')
    sw = App(prev_album, prev, pause, play, next, next_album, logger)
    sw.run()

if __name__ == '__main__':
    main()


import unittest

from config import PathConfig
from database.oracle_database import OracleDatabase
from log.logger import logger
from public_method.base_action import BaseAction
from public_method.dbf_operation import creat_new_dbf

class EtfSplitXL(unittest.TestCase):
    """
    ETF拆分 限售股拆分
    """
    yaml = BaseAction().read_yaml(PathConfig().hu_a())['EtfSplit']['XL']

    def test_etfsplitxl(self):
        """
        ETF拆分 限售股拆分
        :return:
        """
        logger().info('-------------------------------')
        logger().info('开始执行：ETF拆分 限售股拆分 准备数据')
        dbf_path = self.yaml['dbfPath']
        dbf_result = creat_new_dbf(dbf_path)
        if not dbf_result:
            logger().info('dbf文件数据准备完成')
        else:
            logger().error('dbf文件数据准备异常，：{}'.format(dbf_result))
            assert False, dbf_result
        sql_path = self.yaml['sqlPath']
        sql = BaseAction().read_sql(sql_path)
        oracle = OracleDatabase()
        sql_result = oracle.update_sql(*sql)
        if not sql_result:
            logger().info('ETF拆分 限售股拆分 准备数据完成')
            assert True
        else:
            logger().error('ETF拆分 限售股拆分 准备数据异常')
            assert False, sql_result

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


import discord
from discord.ext import commands
from discord.ext.commands import has_permissions, bot_has_permissions, BotMissingPermissions, MissingPermissions
import datetime
import asyncio
import json
import aiohttp
from mongoconnection.vip import *

c = open("../config.json")
config = json.load(c)

l = open("../link.json")
link = json.load(l)

intents = discord.Intents.default()
intents.members = True

prefix = config["prefix"]
bot = commands.Bot(command_prefix = prefix, intents=intents,  case_insensitive = True)

def cooldown(rate, per_sec = 0, per_min = 0, per_hour = 0, type = commands.BucketType.default):
    return commands.cooldown(rate, per_sec + 60 * per_min + 3600 * per_hour, type)

vipNames = ["Ametista", "Jade", "Safira"]
vipRoles = [1051948366461939744, 1047268770504253561, 1047268807812595802]
vipEmojis = ["<a:ab_PurpleDiamond:938883672717787196>", "<a:ab_GreenDiamond:938880803692240927>", "<a:ab_BlueDiamond:938850305083314207>"]

bot.ses = aiohttp.ClientSession()
class cog_vip(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name = "vip", aliases = ["vippe"], pass_context = True)
    @cooldown(1, 3, type = commands.BucketType.user)
    async def vip(self, ctx):
        try:
            dbname = getDatabase()
            collectionName = dbname["vip"]
            vip = collectionName.find_one({"User": ctx.author.id})
            print(vip)
            if vip == None:
                noVip = discord.Embed(
                    title = f"Sem VIP!",
                    description = f"『❌』Você não possui um plano VIP ativo no momento. Confira todos os benefícios de se tornar um VIP em <#1047316824976523354>",
                    color = 0xFF0000
                )
                noVip.set_thumbnail(url = link["error"])
                noVip.set_footer(text = f"Pedido por {ctx.author.name}", icon_url = ctx.author.display_avatar.url)
                await ctx.reply(embed = noVip)
                return
            vipEmbed = discord.Embed(
                color = discord.Color.from_rgb(200, 20, 255)
            )
            vipRole = discord.utils.get(self.bot.get_guild(ctx.guild.id).roles, id = int(vipRoles[vip["Vip"]]))
            if vip["Role"] != None:
                roleFound = discord.utils.get(self.bot.get_guild(ctx.guild.id).roles, id = int(vip["Role"]))
                userRole = roleFound.mention
            else:
                userRole = "`Nenhum`"
            if vip["Channel"] != None:
                foundChannel = discord.utils.get(self.bot.get_guild(ctx.guild.id).voice_channels, id = int(vip["Channel"]))
                userChannel = foundChannel.mention
            else:
                userChannel = "`Nenhum`"
            if len(vip["Friends"]) == 0:
                userFriends = "`Nenhum`"
            else:
                f = []
                for friend in vip["Friends"]:
                    user = await self.bot.fetch_user(int(friend))
                    f.append(f"{user.mention}")
                userFriends = "\n".join(f)
            vipEmbed.set_author(name = f"『💎』VIP:", icon_url = self.bot.user.display_avatar.url)
            vipEmbed.add_field(name = f"『💎』VIP atual:", value = f"{vipRole.mention}", inline = False)
            vipEmbed.add_field(name = f"『⏰』Termina em:", value = f"<t:{vip['EndsAt']}>", inline = False)
            vipEmbed.add_field(name = f"『💼』Seu cargo:", value = userRole, inline = False)
            vipEmbed.add_field(name = f"『🔊』Seu canal:", value = userChannel, inline = False)
            vipEmbed.add_field(name = f"『👥』Amigos:", value = userFriends, inline = False)
            vipEmbed.set_thumbnail(url = ctx.author.display_avatar.url)
            vipEmbed.set_footer(text = f"Pedido por {ctx.author.name}", icon_url = ctx.author.display_avatar.url)
            await ctx.reply(embed = vipEmbed)
            return
        except Exception as e:
            print(e)

async def setup(bot):
    print(f"{prefix}vip")
    await bot.add_cog(cog_vip(bot))


#!/home/fengxiang/anaconda3/envs/wrfout/bin/python
# -*- encoding: utf-8 -*-
'''
Description:
郑州站逐小时降水变化柱状图
画累积降水的柱状图
-----------------------------------------
Time             :2021/06/04 14:32:20
Author          :Forxd
Version          :1.0
'''

# %%
import xarray as xr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from cycler import cycler
import datetime
import sys,os
import xarray as xr
import numpy as np
import pandas as pd

import salem  # 插值
import cartopy.crs as ccrs
import cartopy.feature as cfeat
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
from cartopy.io.shapereader import Reader, natural_earth
import matplotlib as mpl
from matplotlib.path import Path
import seaborn as sns
# import matplotlib.patches as patches
import matplotlib.pyplot as plt
import geopandas
import cmaps
from get_cmap import get_cmap_rain2
from multiprocessing import Pool

## 显示中文
plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# %%

def get_rain_zhenzhou():
    df_station = pd.read_csv('/mnt/zfm_18T/fengxiang/HeNan/Data/OBS/rain_station.csv')
    df = df_station
    df1 = df[(df['id']==57083)]
    df2 = pd.DataFrame(df1, columns=['time','lon', 'lat', 'data0'])
    df2['time'] = pd.to_datetime(df2['time'])
    da = xr.DataArray(
        df2['data0'].values,
        coords={
            'time':df2['time'].values,
            'lon':df2['lon'].values[0],
            'lat':df2['lat'].values[0],
        },
        dims=['time'],
    )
    return da

def draw_bar(dazz, damax):
    # da = da.sel(time=slice('2021-07-19 12', '2021-07-21 12'))
    da = dazz
    fig = plt.figure(figsize=(14, 8))
    ax = fig.add_axes([0.1,0.15,0.85, 0.79])
    # ax.bar(da.time, da)
    # import datetime
    tt = da.time.dt.strftime('%d/%H')
    x_label = tt
    ax.bar(tt, da, label='郑州')
    ax.plot(tt, damax, color='red',lw=1.5,  label='最大降水站点')
    # ax.hlines(y=30, xmin=tt[0], xmax=tt[-1])
    ax.axhline(y=30, color='black')
    ax.set_xlim(tt[0], tt[-1])
    # ax.hlines(y=30, xmin=tt[0], xmax=tt[-1])
    # ax.plot(tt, da)
    ax.set_xticks(x_label[::4],)  # 这个是选择哪几个坐标画上来的了,都有只是显不显示
    ax.set_yticks(np.arange(0, 220+1, 20))

    ax.xaxis.set_tick_params(labelsize=2.0*12, rotation=30)
    ax.yaxis.set_tick_params(labelsize=2.0*12)
    ax.tick_params(which='major',length=8,width=1.0) # 控制标签大小
    ax.tick_params(which='minor',length=4,width=0.5)  #,colors='b')
    ax.xaxis.set_minor_locator(plt.MultipleLocator(1))
    ax.yaxis.set_minor_locator(plt.MultipleLocator(10))
    ax.set_title('逐小时降水', fontsize=32)
    ax.set_xlabel('Date/Hour (UTC)', fontsize=26)
    ax.set_ylabel('Precip (mm)', fontsize=26)
    ax.legend(fontsize=20, edgecolor='white')
    fig_path = '/mnt/zfm_18T/fengxiang/HeNan/Draw/picture_rain/'
    fig_name = 'obs_rian_time_sequence.png'
    fig.savefig(fig_path+fig_name)

def get_max_station():
    """读取csv格式的站点数据

    Args:
        df_station (DataFrame): 输入csv格式站点数据

    Returns:
        [DataArray]: 小时雨强最大值
    """
    ## 才读的数据，它的时间格式是object
    df_station = pd.read_csv('/mnt/zfm_18T/fengxiang/HeNan/Data/OBS/rain_station.csv')
    # df_station = get_max_dataframe(aa)
    df_station['time']= pd.to_datetime(df_station['time'])
    t = pd.date_range(start='2021-07-18 00', end='2021-07-21 12', freq='1H')
    rain_list = []
    for tt in t:
        cc = df_station[df_station['time']==tt]
        rain_max = cc[(cc['lat']>32)&(cc['lat']<37)&(cc['lon']>110)&(cc['lon']<116)]['data0'].max()
        # rain_max = cc[(cc['lat']>32)&(cc['lat']<37)&(cc['lon']>110)&(cc['lon']<116)]['data0'].mean()
        rain_list.append(rain_max)
    rain_list
    ps = pd.Series(rain_list, index=t)
    da = xr.DataArray.from_series(ps)
    rain_obs_max = da.rename({'index':'time'})
    return rain_obs_max

def get_rain():
    """获得郑州站降水
    河南区域最大降水
    Returns:
        [type]: [description]
    """
    dazz = get_rain_zhenzhou()
    dazz = dazz.sel(time=slice('2021-07-19 00', '2021-07-21 08'))
    damax = get_max_station()
    damax = damax.sel(time=slice('2021-07-19 00', '2021-07-21 08'))
    ## 因为郑州站有部分时次的值是0，没有在列表中
    t1 = dazz.time
    t2 = damax.time
    rain = xr.Dataset()
    rain = xr.concat([damax, dazz], pd.Index(['max', 'zz'], name='model'))
    da_rain = rain.fillna(0)
    ds_rain = da_rain.to_dataset(dim='model')
    return ds_rain

if __name__ == '__main__':

    ds_rain = get_rain()
    draw_bar(ds_rain['zz'], ds_rain['max'])


from __future__ import annotations

from .app import TestApp
from .client import QuartClient
from .connections import WebsocketResponse
from .utils import (
    make_test_body_with_headers,
    make_test_headers_path_and_query_string,
    no_op_push,
    sentinel,
)

__all__ = (
    "make_test_body_with_headers",
    "make_test_headers_path_and_query_string",
    "no_op_push",
    "QuartClient",
    "sentinel",
    "TestApp",
    "WebsocketResponse",
)


#i dont know. i missed some logic there. if anyone found tat implement it
def lststr(m):
    str1 = ""
    for ele in m:
        str1 += ele
    return str1
code = input()
N = int(input())
f = []
q = []
r= dict()
m = []

for i in range(N):
    x = []
    y = []
    lst = []
    p = str(input())
    q = p.split()
    for j in q:
        b = list(j)
        lst.append(b)
    x.append(lst[0])
    x = [item for items in x for item in items]
    y.append(lst[1])
    y = [item for items in y for item in items]
    wordbag = dict(zip(x, y))
    #print(wordbag)
    r.update(wordbag)

code = list(code)
r.keys()
for k in code:
    if k in r.keys():
        m.append(r[k])
        #print(m)
print(lststr(m))


"""Create training and evaluation engines"""
from typing import Tuple, Any, TypeVar

import numpy as np
import pandas as pd
import torch
from ignite.contrib.handlers import TensorboardLogger
from ignite.engine import (create_supervised_evaluator,
                           create_supervised_trainer, Engine)
from ignite.metrics import Loss
from torch import Tensor, nn
from torch.utils.data.dataloader import DataLoader

from imagedl import Config
from imagedl.config import TestConfig
from imagedl.data import Split
from imagedl.nn.update_funs import update_functions
from .data import prepare_batch
from .logger import info
from .metric_handling import metrics_to_str, clean_metrics

T_co = TypeVar('T_co', covariant=True)

def evaluator(test_config: TestConfig, criterion: nn.Module, model: nn.Module,
              device: torch.device) -> Engine:
    """Create evaluator for validation"""
    metrics, eval_metric, *_ = test_config
    metrics['loss'] = Loss(criterion,
                           output_transform=lambda data: (data[0], data[1]))
    val_evaluator = create_supervised_evaluator(model, metrics, device,
                                                prepare_batch=prepare_batch)
    return val_evaluator

def evaluate(config: Config, test_dl: DataLoader[T_co], test_split: np.ndarray,
             criterion: nn.Module, model: nn.Module,
             device: torch.device, tb_logger: TensorboardLogger,
             engine: Engine) -> pd.DataFrame:
    """Test evaluator"""
    metrics, eval_metric, *_ = config.test
    metrics['loss'] = Loss(criterion,
                           output_transform=lambda x: (x[0], x[1]))
    test_evaluator = create_supervised_evaluator(model, metrics, device)
    test_evaluator.run(test_dl)
    metric_values = test_evaluator.state.metrics
    cleaned_metrics = clean_metrics(metrics, metric_values, config.legend)
    df = pd.DataFrame(cleaned_metrics, index=[0])
    df.to_csv(f'{config.job_dir}/metrics.csv', index=False)
    info(f'Test - ' + metrics_to_str(metrics, test_evaluator.state.metrics,
                                     config.legend, tb_logger,
                                     engine.state.epoch + 1, 'test_'))

    to_save = config.job_dir / 'test'
    to_save.mkdir(parents=True, exist_ok=True)
    with torch.no_grad():
        model.eval()
        batch_size = test_dl.batch_size if test_dl.batch_size is not None else 1
        for i, data in enumerate(test_dl):
            inp, out = prepare_batch(data, device)
            pred = model(inp)
            if isinstance(pred, torch.Tensor):
                pred = pred.cpu()
            else:
                pred = [p.cpu() for p in pred]
            img = config.visualize(inp, out, pred)
            indexes = test_split[i * batch_size:(i + 1) * batch_size]
            config.save_sample(img, to_save, indexes)
    return df

def create_trainer(config: Config, device: torch.device, split: Split,
                   own_split: bool) -> Tuple[Any, ...]:
    """Create training engine & load checkpoint"""
    ret_type = Tuple[Tensor, Tensor, float]

    def output_transform(x: Tensor, y: Tensor,
                         y_pred: Tensor, loss: Tensor) -> ret_type:
        """What trainer returns to metrics at each step"""
        return y_pred, y, loss.item()

    model, optimizer_fn, criterion, checkpoint = config.model_config
    model = model.to(device)
    optimizer = optimizer_fn(model.parameters())
    if optimizer.__class__ in update_functions:
        update_function = update_functions[optimizer.__class__]
        update = update_function(model, optimizer, criterion, device,
                                 output_transform, prepare_batch)
        trainer = Engine(update)
    else:
        trainer = create_supervised_trainer(model, optimizer, criterion, device,
                                            prepare_batch=prepare_batch,
                                            output_transform=output_transform)
    if checkpoint is not None:
        info(f'Resume from {checkpoint}')
        obj = torch.load(str(checkpoint))
        model.load_state_dict(obj['model'])
        optimizer.load_state_dict(obj['optimizer'])
        trainer.load_state_dict(obj['trainer'])
        if not own_split:
            split = Split.load_state_dict(obj['split'])
    return model, optimizer, criterion, split, trainer


import numpy as np
import math
import networkx as nx
import matplotlib.pyplot as plt

# This file is to initialize all the variables used in HyperType Model
####################################################################################################
#All Functions are below:
####################################################################################################

# parameters:
#     int keyNumber, number of keys in the key list
#     lst key_lst, a list consisting all the keys
#     lst prob, a list consisting probability fo keys
#     lst(3d) tensor, a 3 dimensional list of key combinations will be made after tensor_initialization is called
#     lst(2d) pt, a probability table
#     lst plst, a probability list
#     lst elst, an entry list
# tensor_initialization constructs the tensor (ten). After running, the procedure produces a tensor with combinations of
#     keys at each entry, according to the entry's index. Probability list (plst) and entry list (elst) are also produced.

def tensor_initialization(keyNumber,key_lst,prob,tensor,pt,plst,elst):
    for i in range(keyNumber):
        tensor.append([])
        pt.append([])
        for j in range(keyNumber):
            tensor[i].append([])
            pt[i].append([])
            for k in range(keyNumber):
                word = (key_lst[i]+key_lst[j]+key_lst[k])
                elst.append(word)
                Probability = prob[i]*prob[j]*prob[k]
                Probability = round(Probability,10)
                tensor[i][j].append(word)
                pt[i][j].append(Probability)

# parameters (above mentioned parameters will not be introduced again):
#     lst(2d) matrix, a 2 dimensional list of key combinations will be made after matrix_initialization is called
#     lst(2d) pm, probability matrix
#     lst mplst, probability list for the produced matrix
#     lst melst, entry list for the produced matrix
# matrix_initialization constructs the matrix (matrix). After running, the produre produces a matrix with combinations of two keys at
#     each entry, according to the entry's index. Probability list (mplst) and entry list (melst) are also produced.

def matrix_initialization(keyNumber,key_lst,prob,matrix,pm,mplst,melst):
    for i in range(keyNumber):
        matrix.append([])
        pm.append([])
        for j in range(keyNumber):
            word = (key_lst[i]+key_lst[j])
            melst.append(word)
            Probability = round(prob[i]*prob[j],10)
            matrix[i].append(word)
            pm[i].append(Probability)

# print_tensor takes a tensor and the key number, and will print the entries in the tensor.

def print_tensor(ten,keyNumber):
    for i in range(keyNumber):
        for j in range(keyNumber):
            print(ten[i][j][0], ten[i][j][1], ten[i][j][2])
        print('\n')

# layerSum takes a tensor, the key number, and the layer index. It will return the sum of probability of a layer of tensor.
def layerSum(ten,keyNumber,lay):
    sum = 0.0
    for i in range(keyNumber):
        for j in range(keyNumber):
            sum = sum + ten[lay][i][j]

    sum = round(sum,10)
    return sum

# rowSum takes a tensor, the key number, and the row index. It will sum up the probability of the desinated row for each layer, and return it.
def rowSum(ten,key,row):
    sum = 0.0
    for i in range(key):
        for j in range(key):
            sum = sum + ten[i][row][j]
    sum = round(sum,10)
    return sum

# colSum takes a tensor, the key number, and the col index. It will sum up the probability of the desinated column for each layer, and return it.
def colSum(ten,key,col):
    sum = 0.0
    for i in range(key):
        for j in range(key):
            sum = sum + ten[i][j][col]
    sum = round(sum,10)
    return sum

# colSum takes a tensor, the key number, and the row index. It will sum up the probability of the desinated row of mat, and return it.
def matrixRowSum(mat,key,row):
    sum = 0.0
    for i in range(key):
        sum = sum + mat[row][i]
    sum = round(sum,10)
    return sum

# parameters (above mentioned parameters will not be introduced again):
#     float al, an imbalance parameter from 0 to 1.
#     float be, an imbalance parameter from 0 to 1.
# imbalance will decrease type 2 and 3 entries of ten by multipling probability on type 2 and 3 entries by be, and probability of type 3 entries by al again.
#     Then type 1 entries will increase their probability by the amount that type 2 and 3 entries on their layers decreased.

def imbalance(ten,key,al,be,prob,plst): #tensor, keyNumber, alpha, beta
    for i in range(key):
        for j in range(key):
            for k in range(key):
                if (i != j and j != k and i != k):#white
                    ten[i][j][k] = round(ten[i][j][k]*al*be,10)
                elif(i == j == k):
                    1
                else:
                    ten[i][j][k] = round(ten[i][j][k]*be,10)
    for i in range(key):
        ten[i][i][i] = ten[i][i][i]+(prob[i]-layerSum(ten,key,i))
    for i in range(key):
        for j in range(key):
            for k in range(key):
                plst.append(ten[i][j][k])

# imbalanceMatrix will decrease type 2 entries of mat by multipling probability on type 2 entries by be.
#     Then type 1 entries will increase their probability by the amount that type 2 entries on
#     their layers decreased.
def imbalanceMatrix(mat,key,al,prob,mplst):#matrix, keyNumber, alpha
    for i in range(key):
        for j in range(key):
            if(i != j):
                mat[i][j] = round(mat[i][j]*al,10)
    for i in range(key):
        mat[i][i] = round(mat[i][i]+(prob[i]-matrixRowSum(mat,key,i)),10)
    for i in range(key):
        for j in range(key):
            mplst.append(mat[i][j])

#adding an edge with weights
def adding_edges(e1,e2,G):
    if G.has_edge(e1,e2):
        # we added this one before, just increase the weight by one
        G[e1][e2]['weight'] += 1
    else:
        # new edge. add with weight=1
        G.add_edge(e1,e2, weight=1)

# parameters (above mentioned parameters will not be introduced again):
#     grah G, a graph
# make takes the probability lists and entry lists for tensor and matrix, and constructs a triple (a group of three words) based on those Probability
#     and entries. A word is terminated if an space character is appended to it. When no word terminates, it chooses entries from ten; when one word terminates,
#     it chooses entries from mat; when two words terminate, it chooses entries from prob (in this case will only choose one letter from key array); when all
#     three words terminate, the triple will be added to G and returned.
def make(G,elst,plst,melst,mplst,key_lst,prob):
    L1 = ''
    L2 = ''
    L3 = ''
    T_L1 = True
    T_L2 = True
    T_L3 = True
    TNum = 3

    while(TNum == 3):
        lst = np.random.choice(elst,1,p=plst)[0]

        L1 = L1 + lst[0]

        L2 = L2 + lst[1]

        L3 = L3 + lst[2]

        if (lst[0] == 's'):
            T_L1 = False
            TNum = TNum - 1
        if (lst[1] == 's'):
            T_L2 = False
            TNum = TNum - 1
        if (lst[2] == 's'):
            T_L3 = False
            TNum = TNum - 1

    while(TNum == 2):
        lst = np.random.choice(melst,1,p=mplst)[0]
        if(T_L1 == False):
            L2 = L2 + lst[0]
            L3 = L3 + lst[1]
            if(lst[0] == 's'):
                T_L2 = False
                TNum = TNum - 1
            if(lst[1] == 's'):
                T_L3 = False
                TNum = TNum - 1
        elif(T_L2 == False):
            L1 = L1 + lst[0]
            L3 = L3 + lst[1]
            if(lst[0] == 's'):
                T_L1 = False
                TNum = TNum - 1
            if(lst[1] == 's'):
                T_L3 = False
                TNum = TNum - 1
        else:
            L1 = L1 + lst[0]
            L2 = L2 + lst[1]
            if(lst[0] == 's'):
                T_L1 = False
                TNum = TNum - 1
            if(lst[1] == 's'):
                T_L2 = False
                TNum = TNum - 1

    while(TNum == 1):
        lst = np.random.choice(key_lst,1,p=prob)[0]
        if(T_L1 == True):
            L1 = L1 + lst[0]
        elif(T_L2 == True):
            L2 = L2 + lst[0]
        else:
            L3 = L3 + lst[0]
        if(lst[0]=='s'):
            TNum = TNum - 1

    #adding edges to Graph
    if(L1!=L2):
        adding_edges(L1,L2,G)
    if(L1!=L3):
        adding_edges(L1,L3,G)
    if(L2!=L3):
        adding_edges(L2,L3,G)
    #in case all three nodes are the same
    G.add_node(L1)

    triple = []
    triple.append(L1)
    triple.append(L2)
    triple.append(L3)
    return triple

# parameters (above mentioned parameters will not be introduced again):
#     int triples, number of triples to generate
# generate_graph will generate triples with make() for the desinated number of triples, and put nodes and edges into G.
# For example, new_graph=generate_graph(G,10000,elst,plst,melst,mplst,key_lst,prob) will generate a new graph.

def generate_graph(G,triples,elst,plst,melst,mplst,key_lst,prob):
    graph = []
    for i in range(triples):
        graph.append(make(G,elst,plst,melst,mplst,key_lst,prob))#
    return graph

# parameters (above mentioned parameters will not be introduced again):
#     int nodes, number of nodes to generate
# generate_graph_nodes will generate triples with make() for the desinated number of nodes, and put nodes and edges into G.
# For example, new_graph=generate_graph_nodes(G,10000,elst,plst,melst,mplst,key_lst,prob) will generate a new graph.

def generate_graph_nodes(G,nodes,elst,plst,melst,mplst,key_lst,prob):
    graph = []
    while G.order()<nodes:
        graph.append(make(G,elst,plst,melst,mplst,key_lst,prob))
    return graph


def permute(n):
    if 1 < n <= 3:
        return None

    perm = []
    for i in range(2, n + 1, 2):
        perm.append(i)

    for i in range(1, n + 1, 2):
        perm.append(i)

    return perm

def main():
    n = int(input())

    perm = permute(n)
    if perm:
        print(*perm)
    else:
        print("NO SOLUTION")

if __name__ == "__main__":
    main()


# def numberOfBinaryTreeTopologies(n):
#     if n == 0:
#         return 1
#     numberOfTrees =0
#     for leftTreeSize in range(0,n):
#         rightTreeSize = n - 1 - leftTreeSize
#         numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize)
#         numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize)
#         numberOfTrees+=numberOfTreeLeft*numberOfTreeRight
#     return numberOfTrees

# def numberOfBinaryTreeTopologies(n,cache={0:1}):
#     if n in cache:
#         return cache[n]
#     numberOfTrees =0
#     for leftTreeSize in range(0,n):
#         rightTreeSize = n - 1 - leftTreeSize
#         numberOfTreeLeft = numberOfBinaryTreeTopologies(leftTreeSize,cache)
#         numberOfTreeRight = numberOfBinaryTreeTopologies(rightTreeSize,cache)
#         numberOfTrees+=numberOfTreeLeft*numberOfTreeRight
#     cache[n]=numberOfTrees
#     return numberOfTrees

def numberOfBinaryTreeTopologies(n):
    cache = [1]
    for m in range(1, n+1):
        numberOfTrees = 0
        for leftTreeSize in range(m):
            rightTreeSize = m-1-leftTreeSize
            numberOfLeftTrees = cache[leftTreeSize]
            numberOfRightTrees = cache[rightTreeSize]
            numberOfTrees += numberOfLeftTrees * numberOfRightTrees
        cache.append(
            numberOfTrees
        )
    return cache[n]

print(numberOfBinaryTreeTopologies(3))


from Actor import Actor
from random import randint, choice, random
from Bullet import Bullet
from Background import Background
from Rover import Rover
import Constants

alien_counter = 0 #static counter for the number of instances

class Alien(Actor):
    def __init__(self, arena):
        global alien_counter
        if(alien_counter > Constants.MAX_ALIEN_NUMBER): return #if there are already the maxium number of alien
        self._arena = arena
        self._x = randint(Constants.ALIEN_WIDTH, self._arena.size()[0]-Constants.ALIEN_WIDTH)
        self._y = randint(Constants.ALIEN_MIN_Y,Constants.ALIEN_MAX_Y)
        self._w, self._h = Constants.ALIEN_WIDTH, Constants.ALIEN_HEIGHT
        self._dx = Constants.ALIEN_SPEED
        alien_counter += 1
        arena.add(self)

    def move(self):
        if self._x + self._dx <= 0 or self._x + self._dx >= (self._arena.size()[0] - self._w): #change direction if border is touched
            self._dx *= -1
        if choice(range(Constants.CHANGE_DIRECTION_PROBABILITY)) == 0: #maybe it's time to change direction...
            self._dx *= -1
        if self.can_shoot(): #maybe it's time to shoot...
            Bullet(self._arena, (self.position()[0], self.position()[1] + Constants.BULLET_HEIGHT), Constants.VERTICAL_A,self)

        self._x += self._dx

    def is_out_of_canvas(self) -> bool:
        return False

    def collide(self, other):
        if isinstance(other,Background): return

        global alien_counter
        if(isinstance(other,Bullet)) and isinstance(other.get_author(),Rover):
            self._arena.remove(self)
            alien_counter -= 1

    def can_shoot(self) -> bool:
        '''
        returns true if the alien can shoot
        the probability is about 1/20
        '''
        return  (choice(range(Constants.SHOOT_PROBABILITY))) == 0

    def position(self)-> (int, int, int, int):
        return self._x, self._y, self._w, self._h

    def symbol(self) -> (int, int, int, int):
        return Constants.ALIEN_X, Constants.ALIEN_Y, self._w, self._h


import numpy as np
from utils import HCA

def get_wins_losses(game_df):
    wins = {}
    losses = {}
    for idx, row in game_df.iterrows():
        if row['margin'] > 0:
            wins[row['team']] = wins.get(row['team'], 0) + 1
            losses[row['opponent']] = losses.get(row['opponent'], 0) + 1
        else:
            losses[row['team']] = losses.get(row['team'], 0) + 1
            wins[row['opponent']] = wins.get(row['opponent'], 0) + 1
    return wins, losses

def get_offensive_efficiency(data):
    off_eff = {}
    for idx, row in data.iterrows():
        home_points = row['team_score']
        away_points = row['opponent_score']
        pace = row['pace']
        home_off_eff = home_points / pace
        away_off_eff = away_points / pace
        home = row['team']
        away = row['opponent']
        if home not in off_eff:
            off_eff[home] = []
        if away not in off_eff:
            off_eff[away] = []
        off_eff[row['team']].append(home_off_eff)
        off_eff[row['opponent']].append(away_off_eff)
    for team, off_effs in off_eff.items():
        off_eff[team] = np.mean(off_effs)
    return off_eff

def get_defensive_efficiency(data):
    def_eff = {}
    for idx, row in data.iterrows():
        home_points = row['team_score']
        away_points = row['opponent_score']
        pace = row['pace']
        home_def_eff = away_points / pace
        away_def_eff = home_points / pace
        home = row['team']
        away = row['opponent']
        if home not in def_eff:
            def_eff[home] = []
        if away not in def_eff:
            def_eff[away] = []
        def_eff[row['team']].append(home_def_eff)
        def_eff[row['opponent']].append(away_def_eff)
    for team, def_effs in def_eff.items():
        def_eff[team] = np.mean(def_effs)
    return def_eff

def get_adjusted_efficiencies(data, off_eff, def_eff):
    '''
    gets both adjusted defensive efficiency and adjusted offensive efficiency
    TODO: use HCA
    '''
    adj_off_eff = off_eff.copy()
    adj_def_eff = def_eff.copy()

    average_pace = np.mean(data['pace'])
    average_ppp = np.mean(data['team_score'] / data['pace'])

    for loop in range(100):
        off_eff_diffs = {team: [] for team in off_eff.keys()}
        def_eff_diffs = {team: [] for team in off_eff.keys()}

        game_offensive_efficiencies = {team: [] for team in off_eff.keys()}
        game_defensive_efficiencies = {team: [] for team in off_eff.keys()}
        for idx, row in data.iterrows():
            team_ppp = row['team_score'] / row['pace']
            opponent_ppp = row['opponent_score'] / row['pace']
            team_game_adjusted_offensive_efficiency = team_ppp - (adj_def_eff[row['opponent']] + average_ppp)
            team_game_adjusted_defensive_efficiency = opponent_ppp - (adj_off_eff[row['opponent']] + average_ppp)
            opponent_game_adjusted_offensive_efficiency = opponent_ppp - (adj_def_eff[row['team']] + average_ppp)
            opponent_game_adjusted_defensive_efficiency = team_ppp - (adj_off_eff[row['team']] + average_ppp)

            game_offensive_efficiencies[row['team']].append(team_game_adjusted_offensive_efficiency)
            game_defensive_efficiencies[row['team']].append(team_game_adjusted_defensive_efficiency)
            game_offensive_efficiencies[row['opponent']].append(opponent_game_adjusted_offensive_efficiency)
            game_defensive_efficiencies[row['opponent']].append(opponent_game_adjusted_defensive_efficiency)

        for team, off_effs in game_offensive_efficiencies.items():
            adj_off_eff[team] = np.mean(off_effs)
        for team, def_effs in game_defensive_efficiencies.items():
            adj_def_eff[team] = np.mean(def_effs)

    mean_off_eff = np.mean(list(adj_off_eff.values()))
    mean_def_eff = np.mean(list(adj_def_eff.values()))

    adj_off_eff = {team: 100 * (off_eff - mean_off_eff) for team, off_eff in adj_off_eff.items()}
    adj_def_eff = {team: 100 * (def_eff - mean_def_eff) for team, def_eff in adj_def_eff.items()}
    return adj_off_eff, adj_def_eff

def get_adjusted_offensive_efficiency(data, def_eff):
    adj_off_eff = {team: [] for team in def_eff.keys()}
    for idx, row in data.iterrows():
        home_points = row['team_score']
        away_points = row['opponent_score']
        pace = row['pace']
        away_def_eff = def_eff[row['team']]
        home_def_eff = def_eff[row['opponent']]
        home_adj_off_eff = home_points / pace - away_def_eff
        away_adj_off_eff = away_points / pace - home_def_eff
        adj_off_eff[row['team']].append(home_adj_off_eff)
        adj_off_eff[row['opponent']].append(away_adj_off_eff)
    for team, adj_off_effs in adj_off_eff.items():
        adj_off_eff[team] = np.mean(adj_off_effs)
    return adj_off_eff

def get_adjusted_defensive_efficiency(data, off_eff):
    adj_def_eff = {team: [] for team in off_eff.keys()}
    for idx, row in data.iterrows():
        home_points = row['team_score']
        away_points = row['opponent_score']
        pace = row['pace']
        away_off_eff = off_eff[row['team']]
        home_off_eff = off_eff[row['opponent']]
        home_adj_def_eff = away_points / pace - away_off_eff
        away_adj_def_eff = home_points / pace - home_off_eff
        adj_def_eff[row['team']].append(home_adj_def_eff)
        adj_def_eff[row['opponent']].append(away_adj_def_eff)
    for team, adj_def_effs in adj_def_eff.items():
        adj_def_eff[team] = np.mean(adj_def_effs)
    return adj_def_eff

def get_pace(data):
    paces = {}
    for idx, row in data.iterrows():
        pace = row['pace']
        home = row['team']
        away = row['opponent']
        if home not in paces:
            paces[home] = []
        if away not in paces:
            paces[away] = []
        paces[home].append(pace)
        paces[away].append(pace)
    for team, pace_lst in paces.items():
        paces[team] = np.mean(pace_lst)
    return paces

def get_remaining_sos(ratings_df, future_games):
    # returns a dictionary of remaining strength of schedule for each team
    remaining_sos = {team: [] for team in ratings_df['team'].unique()}
    for idx, row in future_games.iterrows():
        team = row['team']
        opponent = row['opponent']
        remaining_sos[team].append(ratings_df[ratings_df['team'] == opponent]['predictive_rating'].values[0])
        remaining_sos[opponent].append(ratings_df[ratings_df['team'] == team]['predictive_rating'].values[0])
    for team in remaining_sos:
        remaining_sos[team] = np.mean(remaining_sos[team])
    return remaining_sos


import logging
import os
from sklearn.externals import joblib
import multiprocessing as mp
from collections import defaultdict
from itertools import product
from typing import List
import mido
import numpy as np
from scipy.sparse import dok_matrix, vstack
from midi_ml.tools.util import copy_file_to_gcs

logger = logging.getLogger(__name__)
logger.setLevel("DEBUG")

def window_gen(sequence, n):
    """
    Generator that iterates over a window of size n in a given sequence
    :param sequence: the sequence we wish to iterate over
    :param n: the window size of the iteration
    :return:
    """
    low = 0
    high = n
    for element in sequence:
        window = sequence[low:high]
        if len(window) < n:
            break
        low += 1
        high += 1
        yield tuple(window)

class MidiFeatureCorpus(object):
    """
    Class to search through a directory for midi files and add them to a sparse_matrix of note tuples
    """

    def __init__(self, path: str, note_window_size: int = 2):
        self.path = path
        self.note_window_size_ = note_window_size
        self.files_ = self._depth_first_midi_search(self.path)
        self.note_sequence_set = self.initialize_note_sequence_set(note_window_size)
        self.sparse_matrix = dok_matrix((len(self.files_),
                                         len(self.note_sequence_set)),
                                        dtype=np.float32)

    def _depth_first_midi_search(self, path: str) -> List[str]:
        """
        Perform a recursive depth-first search through the files
        :param path:
        :return:
        """
        files_out = []
        paths = os.listdir(path)
        for p in paths:
            full_subpath = path + "/" + p
            try:
                # print(full_subpath)
                os.listdir(full_subpath)
                dfs_results = self._depth_first_midi_search(full_subpath)
                for file in dfs_results:
                    files_out.append(file)
            except NotADirectoryError:
                if full_subpath.endswith(".mid"):
                    files_out.append(full_subpath)
        return files_out

    @staticmethod
    def initialize_note_sequence_set(window_size: int):
        notes = [str(i) for i in range(128)]
        notes_copies = [notes for i in range(window_size)]
        note_sequences = []
        for combo in product(*notes_copies):
            note_sequences.append(combo[0] + "|" + combo[1])
        return note_sequences

    @staticmethod
    def get_n_note_sequence(midi: mido.MidiFile,
                            note_window_size: int = 2) -> List[str]:
        notes = [str(m.note) for m in midi if m.type == "note_on"]
        n_note_sequences = []
        for note_seq in window_gen(notes, note_window_size):
            n_note_sequences.append("|".join([note for note in note_seq]))
        return n_note_sequences

    @staticmethod
    def sequence_encoder(seq: List[str]) -> defaultdict(float):
        d = defaultdict(float)
        for entry in seq:
            d[entry] += 1.
        return d

    def _parse_file_as_sequence(self, file_name):
        parsed_file = mido.MidiFile(file_name)
        return self.get_n_note_sequence(parsed_file, self.note_window_size_)

    def parse_corpus(self):
        for i, file in enumerate(self.files_):
            try:
                sequence = self._parse_file_as_sequence(file)
                encoded_sequence = self.sequence_encoder(sequence)
                for (seq, count) in encoded_sequence.items():
                    j = self.note_sequence_set.index(seq)
                    self.sparse_matrix[i, j] = count
            # we accept generic errors here to avoid any of the possible corruptions in our midi files
            except:
                continue

class LabeledCorpusSet(object):
    """

    """

    def __init__(self, path: str, note_window_size: int = 2):
        self.path_ = path
        self.note_window_size_ = note_window_size
        self.corpus_name_list_ = os.listdir(self.path_)
        self.corpus_labels = []
        self.corpus_list_ = []
        matrix_shape = (0, len(MidiFeatureCorpus.initialize_note_sequence_set(note_window_size)))
        self.sparse_matrix = dok_matrix(matrix_shape)
        self.parsed_ = False

    @staticmethod
    def _parse_corpus(path: str, corpus_name: str, note_window_size: int = 2):
        logger.info("Parsing %s" % path + corpus_name)
        print("reading from {}".format(path + corpus_name))
        corpus = MidiFeatureCorpus(path + corpus_name, note_window_size)
        corpus.parse_corpus()
        corpus_labels = [corpus_name for label in range(corpus.sparse_matrix.get_shape()[0])]
        return (corpus.sparse_matrix, corpus_labels)

    def parse_corpus_set_parallel(self):
        """
        Parse each corpus on a separate core
        :return:
        """
        pool = mp.Pool(processes=os.cpu_count())
        paths_names_and_window_sizes = []
        for name in self.corpus_name_list_:
            paths_names_and_window_sizes.append((self.path_, name, self.note_window_size_))
        mp_out = pool.starmap(self._parse_corpus, paths_names_and_window_sizes)
        matrix_set = []
        for corpus_matrix, labels in mp_out:
            matrix_set.append(corpus_matrix)
            self.corpus_labels.append(labels)
        logger.info("Finished parsing corpus set")
        self.sparse_matrix = vstack(matrix_set)
        self.parsed_ = True

    def parse_corpus_set(self):
        """
        Iterates through the files in the corpus. Will ignore directory structure within
        a corpus (e.g. if cantatas and sonatas are in different files)
        """
        matrix_set = []
        for corpus_name in self.corpus_name_list_:
            file_path = self.path_ + corpus_name
            logger.info("reading from {}".format(file_path))
            print("reading from {}".format(file_path))
            corpus = MidiFeatureCorpus(file_path, self.note_window_size_)
            corpus.parse_corpus()
            self.corpus_list_.append(corpus)
            for label in range(corpus.sparse_matrix.shape[0]):
                self.corpus_labels.append(corpus_name)
            matrix_set.append(corpus.sparse_matrix)
        self.sparse_matrix = vstack(matrix_set)
        self.parsed_ = True

def main():
    logger.info("Reading corpus")
    labeled_corpus = LabeledCorpusSet(os.environ["DATA_IN_LOC"] + "/")
    labeled_corpus.parse_corpus_set()
    logger.info("Dumping corpus to disk")
    joblib.dump(labeled_corpus.sparse_matrix.todense().A, os.environ["DATA_OUT_LOC"] + "/sparse_matrix")
    joblib.dump(labeled_corpus.corpus_labels, os.environ["DATA_OUT_LOC"] + "/labels")
    logger.info("Copying files to GCS")
    print(labeled_corpus.sparse_matrix.todense().A.shape)
    for file in os.listdir(os.environ["DATA_OUT_LOC"]):
        copy_file_to_gcs(bucket_name="midi-ml",
                         filename=os.environ["DATA_OUT_LOC"] + file,
                         destination_path="parsed_corpus/" + file)


import fcntl
import logging
import os

from connection.ConnectionManager import ConnectionManager
from messages.ActionMessage import FollowUserPetition, FollowHashtagPetition
from messages.Buzz import Buzz
from listener.GenericListener import GenericListener
from utils.MessageUtils import MessageUtils

INCOMING_QUEUE_IP = 'localhost'
INCOMING_QUEUE_PORT = 5672
OUTGOING_QUEUE_IP = 'localhost'
OUTGOING_QUEUE_PORT = 5672
INCOMING_QUEUE_NAME = 'dispatcher-registrationhandler'
REGISTRATION_FOLDER = './reg'
USERS_INFO_FOLDER = './reg/users_info'

'''Persists registrations to hashtags and other users'''
class UserRegistrationHandler(GenericListener):

    def __init__(self):

        GenericListener.__init__(self,INCOMING_QUEUE_IP,INCOMING_QUEUE_PORT)
        self.outgoingConnectionManager = ConnectionManager(OUTGOING_QUEUE_IP,OUTGOING_QUEUE_PORT)
        self.incomingConnectionManager.declareQueue(INCOMING_QUEUE_NAME)
        self.initializeUserQueues()

    def initializeUserQueues(self):
        try:
            for user in os.listdir(USERS_INFO_FOLDER):
                self.incomingConnectionManager.declareQueue(user)
        except:
            logging.error("Folder path not configured for user registration")

    def updateUserRegistrations(self,user,registrationTarget):
        filename = USERS_INFO_FOLDER + '/' + user
        try:
            file = open(filename, 'a+r')
            fcntl.flock(file, fcntl.LOCK_EX) #Lock file for writing
        except IOError:
            logging.error("Folder path not configured for user registration")
        for line in file:
            if (line.strip() == registrationTarget):
                fcntl.flock(file, fcntl.LOCK_UN) #unlock file
                file.close()
                return False  # User was already registered in target
        file.write(registrationTarget + '\n')
        fcntl.flock(file, fcntl.LOCK_UN) #unlock file
        file.close()
        return True

    '''The registration target can be a Hashtag or another User'''
    def register(self, user, registrationTarget):
        shouldUpdate = self.updateUserRegistrations(user,registrationTarget)
        if(shouldUpdate):
            filename = REGISTRATION_FOLDER + '/' + registrationTarget
            file = open(filename, 'a+r')
            fcntl.flock(file, fcntl.LOCK_EX) #lock file for writing
            file.write(user + '\n')
            fcntl.flock(file, fcntl.LOCK_UN)
            file.close()

    def getFollowers(self,target):
        filename = REGISTRATION_FOLDER + '/' + target
        followers = []
        try:
            file = open(filename,'r')
            fcntl.flock(file, fcntl.LOCK_SH)
            for line in file:
                followers.append(line.strip())
        except IOError:
            #If here is because target does not have any follower so nothing should be done
            return followers
        fcntl.flock(file, fcntl.LOCK_UN)
        file.close()
        return followers

    def notifyFollowers(self,buzz):
        hashtags = buzz.getHashtags()
        buzzer = buzz.user
        followers = []
        followers += self.getFollowers(buzzer)
        for hashtag in hashtags:
            followers += self.getFollowers(hashtag)
        for follower in list(set(followers)):
            if(follower != buzzer): #to avoid sending message to it's own
                self.outgoingConnectionManager.writeToQueue(follower, buzz)

    def onMessageReceived(self, channel, method, properties, body):

        message = MessageUtils.deserialize(body)
        if(isinstance(message, FollowUserPetition)):
            logging.info("processing follow user petition")
            self.register(message.user,message.otherUser)
        elif(isinstance(message, FollowHashtagPetition)):
            logging.info("processing follow hashtag petition")
            self.register(message.user,message.hashtag)
        elif(isinstance(message, Buzz)):
            logging.info("processed buzz")
            self.notifyFollowers(message)
        self.incomingConnectionManager.ack(method.delivery_tag)
        if not self.keepRunning.get():
            self.stop()

    def _start(self):
        self.incomingConnectionManager.addTimeout(self.onTimeout)
        self.incomingConnectionManager.listenToQueue(INCOMING_QUEUE_NAME, self.onMessageReceived)


from tinygrad.tensor import Tensor
from tinygrad.tensor import Function
from .kernel import Kernel
import pdb

class RBFFunction(Function):
    def __init__(self, x1, x2):
        self.x1 = x1
        self.x2 = x2

    def forward(self, log_lengthscale):
        n, d = self.x1.shape
        m, _ = self.x2.shape

        res = Tensor.zeros(m, n)
        res = res.add(self.x1.matmul(self.x2.transpose()).mul(2)) # res = 2 x1 @ x2^T

        x1_squared = self.x1.reshape(n, 1, d).matmul(self.x1.reshape(n, d, 1))
        x1_squared = x1_squared.reshape(n, 1).expand(n, m)
        x2_squared = self.x2.reshape(m, 1, d).matmul(self.x2.reshape(m, d, 1))
        x2_squared = x2_squared.reshape(1, m).expand(n, m)
        res = res.add(x1_squared.mul(-1)).add(x2_squared.mul(-1)) # res = -(x - z)^2

        res = res.div(log_lengthscale.exp()) # res = -(x - z)^2 / lengthscale
        res = res.exp()

        self.kernel = res
        return res

    def backward(self, grad_output):
        kernel = self.kernel
        grad = kernel.log().mul(-1).mul(kernel)
        grad = grad.mul(grad_output.transpose())
        return Tensor.sum(grad)

class RBFKernel(Kernel):
    def __init__(self):
        self.log_lengthscale = Tensor.zeros(1, 1)

    def forward(self, x1, x2):
        n, _ = x1.shape
        m, _ = x2.shape
        self.log_lengthscale.expand(n, m)
        return RBFFunction(x1, x2)


def get_lines(path):
    with open(path, 'r', encoding='utf-8-sig') as f:
        return f.read().splitlines()

def part1(lines):
    def get_error_score(illegal_chars):
        score = {
            ')': 3,
            ']': 57,
            '}': 1197,
            '>': 25137,
            }
        return sum([sc for sc in [score[c] for c in illegal_chars]])

    openers = ['(', '[', '{', '<']
    key = {
        '(': 1,
        ')': 1,
        '[': 2,
        ']': 2,
        '{': 3,
        '}': 3,
        '<': 4,
        '>': 4,
    }
    illegal_chars = list()
    for line in lines:
        openers_encountered = list()
        for char in line:
            if char in openers:
                openers_encountered.append(char)
            elif key[openers_encountered[-1]] == key[char]:
                openers_encountered.pop()
            else:
                illegal_chars.append(char)
                break

    return get_error_score(illegal_chars)

def part2(lines: list):
    def get_score(openers: list):
        points = {
            '(': 1,
            '[': 2,
            '{': 3,
            '<': 4,
        }
        score = 0
        openers.reverse()
        for o in openers:
            score *= 5
            score += points[o]
        return score

    openers = ['(', '[', '{', '<']
    key = {
        '(': 1,
        ')': 1,
        '[': 2,
        ']': 2,
        '{': 3,
        '}': 3,
        '<': 4,
        '>': 4,
    }
    corrupted = False
    scores = list()
    for line in lines.copy():
        openers_encountered = list()
        for char in line:
            if char in openers:
                openers_encountered.append(char)
            elif key[openers_encountered[-1]] == key[char]:
                openers_encountered.pop()
            else:
                corrupted = True
                break
        if not corrupted:
            scores.append(get_score(openers_encountered))
        else:
            corrupted = False

    return sorted(scores)[(len(scores)-1)//2]

path = '10/10_input.txt'
lines = get_lines(path)

print(part1(lines))
print(part2(lines))


from footid1 import *
from crop_data import crop2top, crop2bottom
from tkinter import *
import matplotlib.pyplot as plt
import tkinter.filedialog
from PIL import Image
import tensorflow as tf
import numpy as np
from scipy import ndimage
import scipy
import cv2
import os

root_ = 'C:\\Users\\Neo\\Desktop\\source_test'
test = 'test.jpg'
standard_inner_data_path = 'C:\\Users\\Neo\\Desktop\\source_300_train'

def main(path):
    show_raw_data(path)
    show_4_scale(path)
    flag = predict(test)
    if flag is not False:
        status.set(1)
        result.set('结果是：'+flag)
        origin.set(flag)
    else:
        result.set('结果是：集外未知类别')

# 从GUI窗口中获取待检测图片路径
def save_path():
    filename = tkinter.filedialog.askopenfilename()
    if filename != '':
        lb.config(text="您选择的文件是：" + filename)
        main(filename)
    else:
        lb.config(text="您没有选择任何文件")
    return

# 显示输入图像
def show_raw_data(img_path):
    img = cv2.imread(img_path)
    if img.shape[0] < 500:
        shapeFlag.set(0)
    else:
        shapeFlag.set(1)
    print(img.shape)
    cv2.namedWindow('RawImage')
    cv2.imshow('RawImage', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def resize(img_path):
    image = np.array(ndimage.imread(img_path, flatten=False))
    image = scipy.misc.imresize(image, size=(64, 32))
    return image

# 用于展示四个尺度
def show_4_scale(img_path):
    # 全脚
    full_show = resize(img_path)
    # 脚掌
    top = crop2top(img_path)
    top_show = np.asarray(top)
    top_show = scipy.misc.imresize(top_show, size=(64, 32))
    # 脚跟
    bottom = crop2bottom(img_path)
    bottom_show = np.asarray(bottom)
    bottom_show = scipy.misc.imresize(bottom_show, size=(64, 32))
    # 脚掌中心
    center = get_center(top)
    center_show = np.asarray(center)
    center_show = scipy.misc.imresize(center_show, size=(64, 32))
    # 合并后在一个窗口显示
    img_show = np.hstack([full_show, top_show, bottom_show, center_show])
    cv2.namedWindow('Multi-scale')
    cv2.imshow('Multi-scale', img_show)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    pic_name = 'test.jpg'
    if os.path.exists(pic_name):
        os.remove(pic_name)
    cv2.imwrite(pic_name, full_show)

# 获取脚掌中心
def get_center(im):
    x_size, y_size = im.size
    start_point_xy = x_size / 4
    end_point_xy = x_size / 4 + x_size / 2
    start_point_yx = y_size / 4
    end_point_yx = y_size / 4 + y_size / 2
    box = (start_point_xy, start_point_yx, end_point_xy, end_point_yx)
    new_im = im.crop(box)
    return new_im

# 计算指定文件夹内所有图片的特征
def generate_feature_from_folder(folder_path):
    feature_list = []
    with tf.Session() as sess:
        foot_saver.restore(sess, 'display_checkpoint\\30000.ckpt')
        for img in os.listdir(folder_path):
            img_list = []
            temp_dir = os.path.join(folder_path, img)
            source_img = cv2.imread(temp_dir)
            img_list.append(source_img)
            source_img = np.array(img_list)
            feature = sess.run(h5, {h0: source_img})
            feature_list.append(feature)
        return feature_list

# 预测结果
def predict(img_path):
    img = cv2.imread(img_path)
    img_list = []
    img_list.append(img)
    img = np.array(img_list)
    # 目标文件夹
    result_folder = ''
    # 测试图特征
    # test_feature = np.array([])
    with tf.Session() as sess:
        foot_saver.restore(sess, 'display_checkpoint\\30000.ckpt')
        h_test_predict = sess.run(tf.nn.softmax(y), {h0: img})
        class_ = tf.argmax(h_test_predict, 1)
        class_ = sess.run(class_)
        # 加载数据标签的对应文件输出类别
        lis = np.load('display_data_label_npy\\data_label.npy')
        for i in range(lis.shape[0]):
            if lis[i, 1] == str(class_[0]):
                result_folder = lis[i, 0]
                break
        sess.close()
    # 加载源文件
    source = np.load('display_std_similarity\\std_similarity.npy')
    target = ''
    for row in range(source.shape[0]):
        if source[row, 0] == result_folder:
            target = source[row, 1]
    # 阈值
    t = float(0.90)
    # print(target)
    if float(target) < t:
        print('预测为集外')
        return False
    else:
        if shapeFlag.get() == 0:
            print('预测为集外')
            return False
        else:
            print('预测为集内')
            print('预测类别为：' + result_folder)
            return result_folder

# 显示预测结果对应文件夹中所有图片
def show_result(path):
    _path = os.path.join(root_, path)
    row = 1
    column = 0
    count = 0
    for img in os.listdir(_path):
        length = len(os.listdir(_path))
        if length < 6:
            if img == rawName.get():
                continue
            img_path = os.path.join(_path, img)
            img_ = Image.open(img_path)
            column += 1
            plt.subplot(row, length, column)
            plt.imshow(img_)
            plt.xticks([])
            plt.yticks([])
            count += 1
        else:
            if img == rawName.get():
                continue
            if count == 6:
                break
            column += 1
            img_path = os.path.join(_path, img)
            img_ = Image.open(img_path)
            plt.subplot(row, 6, column)
            plt.imshow(img_)
            plt.xticks([])
            plt.yticks([])
            count += 1
    plt.show()

# 选择测试图片并调用主函数
def chooseFile():
    filename = tkinter.filedialog.askopenfilename(title='选择文件')
    names = filename.split('/')
    rawName.set(names[len(names)-1])
    e.set(filename)
    rawPath.set(filename)

def show_raw(path):
    img = Image.open(path)
    plt.figure('Image')
    plt.imshow(img)
    plt.axis('off')
    plt.title('Original Shoeprint')
    plt.show()

if __name__ == '__main__':
    root = Tk()
    root.title('鞋印图像开集分类')

    lb = Label(root, text='请选择待测试图像')
    lb.pack()

    # 设置变量
    e = StringVar()
    result = StringVar()
    status = IntVar()
    origin = StringVar()
    rawPath = StringVar()
    rawName = StringVar()
    shapeFlag = IntVar()

    result.set('结果是：待检测')
    e_entry = Entry(root, width=68, textvariable=e)
    e_entry.pack()

    fm1 = Frame(root)
    submit_button = Button(fm1, text="选择", command=chooseFile, bg='yellow')
    submit_button.pack(side=LEFT)
    classify_button = Button(fm1, text="分类", command=lambda: main(e.get()), bg='red')
    classify_button.pack(side=LEFT)
    show_button = Button(fm1, text="原始类别库", command=lambda: show_result(origin.get()))
    show_button.pack(side=LEFT)
    raw_button = Button(fm1, text="显示测试图", command=lambda: show_raw(rawPath.get()), bg='gray')
    raw_button.pack(side=LEFT)
    fm1.pack(side=LEFT, padx=10)

    fm2 = Frame(root)
    result_label = Label(fm2, textvariable=result, bg='green')
    result_label.pack()
    fm2.pack(side=RIGHT, padx=10)

    root.mainloop()


import astropy.io.ascii as ascii
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
from matplotlib.lines import Line2D

filelist = ['B-phot-clean.csv','V-phot-clean.csv','R-phot-clean.csv']

obsname=['DOAO','LOAO','SOAO','30INCH','CCA250','Maidanak']
filtername=['B','V','R']
aperture=['auto','3"','5"','7"','psf']

vandykdat=ascii.read('vandykphot.dat')

Bdat=ascii.read(filelist[0])
Vdat=ascii.read(filelist[1])
Rdat=ascii.read(filelist[2])

galactic_extinction=[0.077,0.058,0.046] # BVR, I = 0.032 from NED, SF11

'''
 # column names
['filename', 'dateobs', 'jd',
 'zpauto', 'zpautoerr',
 'zpap3', 'zpap3err',
 'zpap5', 'zpap5err',
 'zpap7', 'zpap7err',
 'zppsf', 'zppsferr',
 'limit3', 'limit5', 'limit7',
 'starnum', 'note',
 'automag', 'automagerr',
 'ap3mag', 'ap3magerr',
 'ap5mag', 'ap5magerr',
 'ap7mag', 'ap7magerr',
 'psfmag', 'psfmagerr',
 'obs']

['MJD', 'B', 'Berr',
 'V', 'Verr',
 'R', 'Rerr',
 'unfilterd', 'unfilterderr',
 'I', 'Ierr', 'source']

'''

# Van Dyk light curve
dat=vandykdat # Van Dyk et al 2018
plt.errorbar(dat['MJD'], dat['B'],dat['Berr'],fmt='b.',alpha=0.5)
plt.errorbar(dat['MJD'], dat['V'],dat['Verr'],fmt='g.',alpha=0.5)
plt.errorbar(dat['MJD'], dat['R'],dat['Rerr'],fmt='r.',alpha=0.5)
#plt.xlim()
plt.ylim(21.5,14)
plt.xlim(57880,58150)
plt.xlabel('MJD')
plt.ylabel('Mag (VEGA)')
plt.legend(filtername)# ,'Van Dyk +2018')

#Bdat
indexreal, indexnone = np.where(Bdat['note']=='real'), np.where(Bdat['note']=='none')
Bdatreal, Bdatnone = Bdat[indexreal], Bdat[indexnone]
indexDOAO=np.where(Bdatreal['obs']=='DOAO')
indexLOAO=np.where(Bdatreal['obs']=='LOAO')
indexSOAO=np.where(Bdatreal['obs']=='SOAO')
index30inch=np.where(Bdatreal['obs']=='30inch')
indexCCA250=np.where(Bdatreal['obs']=='CCA250')
indexMaidanak=np.where(Bdatreal['obs']=='Maidanak')

plt.errorbar(Bdatreal['jd'][indexDOAO]-2400000.5,     Bdatreal['psfmag'][indexDOAO]+2,     Bdatreal['psfmagerr'][indexDOAO],fmt='bo', fillstyle='none')
plt.errorbar(Bdatreal['jd'][indexLOAO]-2400000.5,     Bdatreal['psfmag'][indexLOAO]+2,     Bdatreal['psfmagerr'][indexLOAO],fmt='b.')
plt.errorbar(Bdatreal['jd'][indexSOAO]-2400000.5,     Bdatreal['psfmag'][indexSOAO]+2,     Bdatreal['psfmagerr'][indexSOAO],    fmt='b^')
plt.errorbar(Bdatreal['jd'][index30inch]-2400000.5,   Bdatreal['psfmag'][index30inch]+2,   Bdatreal['psfmagerr'][index30inch],  fmt='bs', fillstyle='none')
plt.errorbar(Bdatreal['jd'][indexCCA250]-2400000.5,   Bdatreal['psfmag'][indexCCA250]+2,   Bdatreal['psfmagerr'][indexCCA250],  fmt='b+')
plt.errorbar(Bdatreal['jd'][indexMaidanak]-2400000.5, Bdatreal['psfmag'][indexMaidanak]+2, Bdatreal['psfmagerr'][indexMaidanak],fmt='b*')

#plt.errorbar(Bdat['jd'][indexnone]-2400000.5, Bdat['limit7'][indexnone], Bdat['zpap7err'][indexnone],lolims=Bdat['zpap7err'][indexnone])

### Bolometric Luminosity
galactic_extinction=[0.077,0.058,0.046]
c0,c1,c2,rms = -0.083,-0.139,-0.691,0.109 # Lyman +2014 B-V 0.0~1.3 range Bolometrice correction term
# BC_B= M_bol - M_B
# BC__B= c0 + c1*(B-V) + c2 * ((B-V)**2)
# (BVcolor-0.019), B-V(galactic extinction corrected) = B-0.077 - V-0.058 = BVcolor-0.019
BolCorB= c0 + c1*((BVcolor['BVcolor']-0.019)) + c2 * (((BVcolor['BVcolor']-0.019))**2)

#Vdat
indexreal, indexnone = np.where(Vdat['note']=='real'), np.where(Vdat['note']=='none')
Vdatreal, Vdatnone = Vdat[indexreal], Vdat[indexnone]

indexDOAO=np.where(Vdatreal['obs']=='DOAO')
indexLOAO=np.where(Vdatreal['obs']=='LOAO')
indexSOAO=np.where(Vdatreal['obs']=='SOAO')
index30inch=np.where(Vdatreal['obs']=='30inch')
indexCCA250=np.where(Vdatreal['obs']=='CCA250')
indexMaidanak=np.where(Vdatreal['obs']=='Maidanak')

plt.errorbar(Vdatreal['jd'][indexDOAO]-2400000.5,     Vdatreal['psfmag'][indexDOAO]+1,     Vdatreal['psfmagerr'][indexDOAO],    fmt='go', fillstyle='none')
plt.errorbar(Vdatreal['jd'][indexLOAO]-2400000.5,     Vdatreal['psfmag'][indexLOAO]+1,     Vdatreal['psfmagerr'][indexLOAO],    fmt='g.')
plt.errorbar(Vdatreal['jd'][indexSOAO]-2400000.5,     Vdatreal['psfmag'][indexSOAO]+1,     Vdatreal['psfmagerr'][indexSOAO],    fmt='g^')
plt.errorbar(Vdatreal['jd'][index30inch]-2400000.5,   Vdatreal['psfmag'][index30inch]+1,   Vdatreal['psfmagerr'][index30inch],  fmt='gs', fillstyle='none')
plt.errorbar(Vdatreal['jd'][indexCCA250]-2400000.5,   Vdatreal['psfmag'][indexCCA250]+1,   Vdatreal['psfmagerr'][indexCCA250],  fmt='g+')
plt.errorbar(Vdatreal['jd'][indexMaidanak]-2400000.5, Vdatreal['psfmag'][indexMaidanak]+1, Vdatreal['psfmagerr'][indexMaidanak],fmt='g*')

#Rdat
indexreal, indexnone = np.where(Rdat['note']=='real'), np.where(Rdat['note']=='none')
Rdatreal, Rdatnone = Rdat[indexreal], Rdat[indexnone]

indexDOAO=np.where(Rdatreal['obs']=='DOAO')
indexLOAO=np.where(Rdatreal['obs']=='LOAO')
indexSOAO=np.where(Rdatreal['obs']=='SOAO')
index30inch=np.where(Rdatreal['obs']=='30inch')
indexCCA250=np.where(Rdatreal['obs']=='CCA250')
indexMaidanak=np.where(Rdatreal['obs']=='Maidanak')

plt.errorbar(Rdatreal['jd'][indexDOAO]-2400000.5,     Rdatreal['psfmag'][indexDOAO],     Rdatreal['psfmagerr'][indexDOAO],    fmt='ro', fillstyle='none')
plt.errorbar(Rdatreal['jd'][indexLOAO]-2400000.5,     Rdatreal['psfmag'][indexLOAO],     Rdatreal['psfmagerr'][indexLOAO],    fmt='r.')
plt.errorbar(Rdatreal['jd'][indexSOAO]-2400000.5,     Rdatreal['psfmag'][indexSOAO],     Rdatreal['psfmagerr'][indexSOAO],    fmt='r^')
plt.errorbar(Rdatreal['jd'][index30inch]-2400000.5,   Rdatreal['psfmag'][index30inch],   Rdatreal['psfmagerr'][index30inch],  fmt='rs', fillstyle='none')
plt.errorbar(Rdatreal['jd'][indexCCA250]-2400000.5,   Rdatreal['psfmag'][indexCCA250],   Rdatreal['psfmagerr'][indexCCA250],  fmt='r+')
plt.errorbar(Rdatreal['jd'][indexMaidanak]-2400000.5, Rdatreal['psfmag'][indexMaidanak], Rdatreal['psfmagerr'][indexMaidanak],fmt='r*')

legend_elements = [Line2D([], [], marker='o', color='k', label='DOAO',ls='none', fillstyle='none'),
				   Line2D([], [], marker='.', color='k', label='LOAO',ls='none'),
				   Line2D([], [], marker='^', color='k', label='SOAO',ls='none'),
				   Line2D([], [], marker='s', color='k', label='30INCH',ls='none', fillstyle='none'),
				   Line2D([], [], marker='+', color='k', label='CCA250',ls='none'),
				   Line2D([], [], marker='*', color='k', label='Maidanak',ls='none'),
				  ]
plt.legend(handles=legend_elements)

#plt.errorbar(Bdat['jd'][indexnone]-2400000.5, Bdat['limit7'][indexnone], Bdat['zpap7err'][indexnone],lolims=Bdat['zpap7err'][indexnone])

plt.text(58140,18,'B+2',color='b',weight='bold',fontsize=12)
plt.text(58140,18.5,'V+1',color='g',weight='bold',fontsize=12)
plt.text(58140,19,'R',color='r',weight='bold',fontsize=12)

#plt.vlines(57898.99,14,22) # discovery date 57898.99 by Ron Arbour
plt.xlim(57880,58190)
plt.ylim(23,14)
plt.ylabel('Mag (Vega)')
plt.xlabel('MJD')
plt.title('SN 2017ein Light Curve')
plt.savefig('sn2017ein-LC.png')
plt.close()

#Bdat
#Vdat
#Rdat

BVcolor=ascii.read('BV-phot-clean-color.csv')
VRcolor=ascii.read('VR-phot-clean-color.csv')
BRcolor=ascii.read('BR-phot-clean-color.csv')

Vmax=2457913.1 # Van Dyk 2018
plt.subplots_adjust(hspace=0)
plt.subplot(311)
plt.errorbar(BVcolor['jd_1']-Vmax ,BVcolor['BVcolor'],BVcolor['BVcolorerr'], marker='o',fillstyle='none',color='k',ls='')
plt.ylabel('B-V')

plt.subplot(312)
plt.errorbar(VRcolor['jd_1']-Vmax ,VRcolor['VRcolor'],VRcolor['VRcolorerr'], marker='s',fillstyle='none',color='k',ls='')
plt.ylabel('V-R')

plt.subplot(313)
plt.errorbar(BRcolor['jd_1']-Vmax ,BRcolor['BRcolor'],BRcolor['BRcolorerr'], marker='^',fillstyle='none',color='k',ls='')
plt.ylabel('B-R')
plt.xlabel('Day since V Maximum')

plt.savefig('SN2017ein-color.png')

plt.close()

galactic_extinction=[0.077,0.058,0.046]
c0,c1,c2,rms = -0.083,-0.139,-0.691,0.109 # Lyman +2014 B-V 0.0~1.3 range Bolometrice correction term
# BC_B= M_bol - M_B
# BC__B= c0 + c1*(B-V) + c2 * ((B-V)**2)
# (BVcolor-0.019), B-V(galactic extinction corrected) = B-0.077 - V-0.058 = BVcolor-0.019
BolCorB= c0 + c1*((BVcolor['BVcolor']-0.019)) + c2 * (((BVcolor['BVcolor']-0.019))**2)

M_B=BVcolor['psfmag_1']-31.75-0.077
plt.plot( BVcolor['jd_1']-Vmax, Mbol_B,'bo')
plt.title('Bolometric Light Curve')
plt.xlabel('Day MJD')
plt.ylable('')
plt.show()


__author__ = 'TianluWang'
from config import time_node
from json_body_makeup import json_body_makeup
from datetime import datetime, timedelta
from open_app import ip_location

def static_files(files):

    json_bodys = []
    pre_time = str(time_node)[:-7].replace(" ", "T")

    for file in files:
        with open(file) as f:
            for line in f.readlines():
                line_list = line.split(' ')
                if line_list[3][1:-7] < pre_time:
                    continue
                tmp = line_list[5].split('/')[-1]
                if 'vendor' in tmp or 'app' in tmp:
                    measurement = 'static_files'
                    CST_time_s = line_list[3][1:-7].replace("T", " ")
                    CST_time = datetime.strptime(CST_time_s, '%Y-%m-%d %H:%M:%S')
                    UTC_time = CST_time - timedelta(hours=8)
                    time = str(UTC_time).replace(" ", "T")
                    value = {}
                    value['ip'] = line_list[0]
                    value['country'] = ip_location(value['ip'])
                    value['status'] = line_list[7]
                    value['time_cost_new'] = float(line_list[-3])
                    value['Android'] = 'Android' in line
                    value['iPhone'] = 'iPhone' in line
                    if 'Android' in line:
                        value['an_or_ios'] = '1'
                    else:
                        value['an_or_ios'] = '0'
                    value['url'] = line_list[5]
                    json_body = json_body_makeup(measurement, time, value)
                    json_bodys.append(json_body)

    return json_bodys


# На грузовом судне необходимо перевезти контейнеры, имеющие одинаковый габарит и разные массы (некоторые контейнеры
# могут иметь одинаковую массу). Общая масса всех контейнеров превышает грузоподъёмность судна.
# Количество грузовых мест на судне не меньше количества контейнеров, назначенных к перевозке. Какое максимальное
# количество контейнеров можно перевезти за один рейс и какова масса самого тяжёлого контейнера среди всех контейнеров,
# которые можно перевезти за один рейс?
# Входные данные.
# В первой строке входного файла находятся два числа: S — грузоподъёмность судна (натуральное число, не превышающее
# 100 000) и N — количество контейнеров (натуральное число, не превышающее 20 000). В следующих N строках находятся
# значения масс контейнеров, требующих транспортировки (все числа натуральные, не превышающие 100), каждое в отдельной
# строке.
# Выходные данные.
# Два целых неотрицательных числа: максимальное количество контейнеров, которые можно перевезти за один рейс и
# масса наиболее тяжёлого из них.
# https://inf-ege.sdamgia.ru/problem?id=36039

# Фактически, абсолютно такая же задача, как и 26 (1), только вместо файлов и места под файлы - грузы и грузоподъемность
# Поэтому нейминг переменных менять не стал
# files - грузы, size - грузоподъемность, memory - складываем подходящие грузы, biggest_file - самый большой груз

# Считываем размеры всех файлов и сортируем в порядке возрастания
files = sorted(list(map(int, open("36039.txt", "r").read().splitlines()[1:])))

# Считываем общий объём памяти
size = int(open("36039.txt", "r").readline().split(" ")[0])

memory = []                                                 # Сюда будем складывать подходящие файлы

for i in range(len(files)):                                 # Проходимся циклом по всем файлам
    if sum(memory) + files[i] <= size:                      # Если влезаем или ровно влезли
        memory.append(files[i])                             # То добавляем еще один файл

biggest_file = files[len(memory)-1] + size - sum(memory)    # Ищем размер самого большого файла который влезет
while biggest_file not in files:                            # Ищем этот файл во всех файлах, если его нет,
    biggest_file -= 1                                       # То уменьшаем на единицу

print(len(memory), biggest_file)


#从任意长度的可迭代对象中分解元素

record = ('name', 'addr', 'tel', 'tel2')
name, addr, *tel = record
print(name)
print(addr)
print(tel)

*before, after = [1, 2, 3, 4, 5, 6]
print(before)
print(after)

# 在循环中也好使
record = [('foo', 1, 2), ('bar', 'hello'), ('foo', 5, 6)]

def do_foo(x, y):
    print('foo', x, y)

def do_bar(s):
    print('bar', s)

for tag, *tags in record:
    if tag == 'foo':
        do_foo(*tags)
    elif tag == 'bar':
        do_bar(tags)


import random

import matplotlib.pyplot as plt
from rdflib import Graph, URIRef, RDF, RDFS, Literal, XSD

from classhierarchy import ClassHierarchyGenerator
from gaussian import Gaussian

GEOSPARQL_NS = 'http://www.opengis.net/ont/geosparql#'
FEATURE_CLS = URIRef(GEOSPARQL_NS + 'Feature')
GEOMETRY_CLS = URIRef(GEOSPARQL_NS + 'Geometry')
HAS_GEOMETRY = URIRef(GEOSPARQL_NS + 'hasGeometry')
AS_WKT = URIRef(GEOSPARQL_NS + 'asWKT')
WKT_TYPE = URIRef(GEOSPARQL_NS + 'wktLiteral')
LAT = URIRef('http://www.w3.org/2003/01/geo/wgs84_pos#lat')
LON = URIRef('http://www.w3.org/2003/01/geo/wgs84_pos#long')

def generate(
        num_points: int,
        num_classes: int,
        num_clusters: int,
        lat_min: float,
        lat_max: float,
        lon_min: float,
        lon_max: float,
        output_file_path: str):

    while True:
        class_hierarchy_genertor = \
            ClassHierarchyGenerator(num_classes, num_clusters)

        class_hierarchy = class_hierarchy_genertor.get_random_hierarchy()
        print(class_hierarchy)

        cluster_base_classes = \
            list(class_hierarchy.get_direct_subclasses(class_hierarchy.T))

        dist_lat = lat_max - lat_min
        dist_lon = lon_max - lon_min

        cluster_gaussians = []

        colors = list(plt.colormaps.get('Paired').colors)
        assert num_clusters <= len(colors)
        random.shuffle(colors)

        # create random Gaussian distributions
        for i in range(num_clusters):
            mu_lat = random.uniform(lat_min, lat_max)
            mu_lon = random.uniform(lon_min, lon_max)

            sigma_lon = random.uniform(
                dist_lon / (num_classes - 1), dist_lon / 3)
            sigma_lat = random.uniform(
                dist_lat / (num_classes - 1), dist_lat / 3)

            angle = random.uniform(0, 180)

            color = colors.pop()

            gaussian = Gaussian(
                mu_lat, mu_lon, sigma_lat, sigma_lon, angle, color)

            cluster_gaussians.append(gaussian)

        points = []
        point_clusters = []  # maybe not needed
        point_colors = []
        point_classes = []

        for i in range(num_points):
            # choose random cluster
            cluster_index = random.randint(0, num_clusters-1)
            point_clusters.append(cluster_index)
            cluster_gaussian = cluster_gaussians[cluster_index]
            color = cluster_gaussian.color
            point_colors.append(color)
            lat, lon = cluster_gaussian.get_point()
            points.append((lat, lon))
            cluster_base_cls = cluster_base_classes[cluster_index]
            cls = class_hierarchy.get_random_subclass_of(cluster_base_cls)
            point_classes.append(cls)
            plt.plot(lat, lon, 'o', color=color)

        plt.show()

        answer = input('Keep this random dataset? (y/n)').lower()

        if answer == 'y':
            break

    # write dataset to file
    g = Graph()

    g += class_hierarchy.as_graph()

    for i in range(len(points)):
        point = URIRef('http://ex.com/point%03i' % i)
        geometry = URIRef('http://ex.com/geometry%03i' % i)
        lat, lon = points[i]
        cls = point_classes[i]
        cluster = point_clusters[i]

        g.add((point, RDF.type, FEATURE_CLS))
        g.add((point, RDF.type, cls))
        g.add((point, RDFS.comment, Literal(f'Belongs to cluster {cluster}')))
        g.add((point, LAT, Literal(lat, None, XSD.double)))
        g.add((point, LON, Literal(lon, None, XSD.double)))
        g.add((point, HAS_GEOMETRY, geometry))
        g.add(
            (geometry, AS_WKT, Literal(f'POINT({lon} {lat})', None, WKT_TYPE)))

    g.serialize(output_file_path, format='ntriples')

# call example:
# if __name__ == '__main__':
#     # Dresden area
#     lon_min = 13.6301
#     lon_max = 13.8615
#     lat_min = 50.9815
#     lat_max = 51.1158
#     generate(100, 50, 4, lat_min, lat_max, lon_min, lon_max, '/tmp/dataset.nt')


#!/usr/bin/python3
"""Defines a Square class"""
from models.rectangle import Rectangle
# Rectangle = __import__('rectangle').Rectangle

class Square(Rectangle):
    """
    Represents the square model that inherits from the rectangle Model
    """

    def __init__(self, size, x=0, y=0, id=None):
        """
            Intialize a new rectangle

            Args:
                size(int): the size of the square
                x(int): the x coordinate of the square
                y(int): the y coordinate of the square
                id(int): the identity of the square
        """
        super().__init__(size, size, x, y, id)

    @property
    def size(self):
        """set/get the width of the square"""
        return self.width

    @size.setter
    def size(self, value):
        self.width = value
        self.height = value

    def __str__(self):
        """
            Overrides the __str__ method
        """
        text = "[Square] ({:d}) {:d}/{:d} - {:d}"
        return (text.format(self.id, self.x, self.y, self.width))

    def update(self, *args, **kwargs):
        """
            Update the class square by adding the public method
        """
        if (args and len(args) != 0):
            a = 0
            for arg in args:
                if a == 0:
                    if arg is None:
                        self.__init__(self.size, self.x, self.y)
                    else:
                        self.id = arg
                elif a == 1:
                    self.size = arg
                elif a == 2:
                    self.x = arg
                elif a == 3:
                    self.y = arg
                a += 1
        elif (kwargs and len(kwargs) != 0):
            for k, v in kwargs.items():
                if k == "id":
                    if v is None:
                        self.__init__(self.size, self.x, self.y)
                    else:
                        self.id = v
                elif k == "size":
                    self.size = v
                elif k == "x":
                    self.x = v
                elif k == "y":
                    self.y = v

    def to_dictionary(self):
        """
            Returns the dictionary representation of a Square
        """
        return dict(
            {"id": self.id, "size": self.size, "x": self.x, "y": self.y}
        )


from bs4 import BeautifulSoup
from requests import get

from scrap.decorator.common_decorators import timeit

@timeit
def jobs_wwr(keyword):

    # we work remotely 사이트 검색 url
    base_url = "https://weworkremotely.com/remote-jobs/search?utf8=%E2%9C%93&term="

    # 요청 후 응답 받기
    response = get(f"{base_url}{keyword}")

    # 응답 상태 코드에 따른 분기 처리
    if response.status_code != 200:
        print("Can't request website")
    else:
        results = {'site':'We Work Remotely'}
        list = []

        # html 파싱
        soup = BeautifulSoup(response.text, "html.parser")
        jobs = soup.find_all('section', class_="jobs")

        for job_section in jobs:
            job_posts = job_section.find_all('li')

            # 마지막 view-all을 클래스를 가진 li 제거
            job_posts.pop(-1)

            for post in job_posts:
                anchors = post.find_all('a')
                anchor  = anchors[1]
                title   = anchor.find('span', class_='title')
                link    = f'https://weworkremotely.com{anchor["href"]}'

                response_item = get(link)
                soup_item = BeautifulSoup(response_item.text, "html.parser")
                thumbnail_img = soup_item.find("div", class_="listing-logo").find('img')
                thumbnail = thumbnail_img["src"]

                # company 키워드로 탐색한 3개의 요소를 각각 할당
                company, kind, region = anchor.find_all('span', class_='company')

                job_data = {
                    'company' : company.string.replace(',', ' '),
                    'location': region.string.replace(',', ' '),
                    'position': title.string.replace(',', ' '),
                    'url'     : link,
                    'thumbnail': thumbnail
                }
                list.append(job_data)

        results['list'] = list

    return [results]


alzheimer_keywords = ["Memory loss", "Poor judgment", "Loss of spontaneity",
                          "Taking longer to complete normal daily tasks", "getting lost",
                          "Increased anxiety", "Chest pain", "forget things", "can't remember"]

heart_keywords = ["Chest pain","chest tightness", "Shortness of breath", "chest discomfort", "chest pressure",
                  "Numbness in the legs or arms", "Pain in upper belly area", "Lightheadedness","Dizziness",
                  "fast heartbeat", "palpitations", "Pain in the neck or back", "Swollen legs"]

lung_cancer_keywords = ["Chronic coughing", "Chest pain", "Shortness of breath","Coughing up blood",
                            "Wheezing", "Coughing up blood", "Tiredness", "Weight loss", "Bone pain", "Headache"]

stroke_keywords = ["Numbness or weakness in the face, arm, or leg", "Confusion", "Trouble with speaking",
            "Difficulty in understanding speech", "Trouble seeing in one or both eyes",
            "Trouble with walking", "Dizziness", "Loss of balance or lack of coordination",
            "Severe headache"]

keywords_dict = {"alzheimer": alzheimer_keywords, "HeartDisease": heart_keywords, "lung_cancer": lung_cancer_keywords, "Stroke": stroke_keywords}

all_keywords = alzheimer_keywords+heart_keywords+lung_cancer_keywords+stroke_keywords


import pickle
def top10():
    with open('/home/tig/gpweb/gpcountlist.pkl','rb') as f:
        li=pickle.load(f)
    ll=[]#dict 's total  list
    l2=[]
    l3=[]
    l4=[]
    l5=[]
    di={}
    for i in li:
         ll.append(eval(i[0]))
         di.update(eval(i[0]))
    for q in ll:
        for z in q.keys():
                l3.append(z)
    l1=list(set(l3))
    for i in l1:
        count=l3.count(i)
        l2.append(str(count)+i)
    l2.sort(reverse=True)
    l6=l2[0:10]
    for s in l6:
        l4.append(s[1:])
    with open('/home/tig/gpweb/gpdict.pkl','rb') as fi:
        dic=pickle.load(fi)
    return (l4[0:10],dic)
top10()


"""
coded by Kamino, kamino.plus@qq.com, 2022/4/15
未经许可不得转载
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
from tqdm import tqdm
from queue import PriorityQueue

def non_max_suppression(x):
    res = np.zeros_like(x)
    for i in range(x.shape[0]):
        for j in range(x.shape[1]):
            if x[i, j] == 0:
                continue
            if np.sum(x[i - 1:i + 2, j - 1:j + 2] > x[i, j]) == 0:
                # print(x[i - 1:i + 2, j - 1:j + 2])
                res[i, j] = x[i, j]
    return res

def hough_line(x, theta_prec=1.0, rho_prec=2.0, topk=1, weight_mat: np.ndarray = None, non_max=False):
    if weight_mat is not None:  # 权重矩阵得是方阵，且边长要是单数
        assert len(weight_mat.shape) and weight_mat.shape[0] == weight_mat.shape[1] and weight_mat.shape[0] % 2 == 1
    # theta_ax和rho_ax是霍夫空间两个轴的量化数组
    # 使用theta_prec和rho_prec两个参数来确定量化精度，数字越大量化越粗
    theta_ax = np.deg2rad(np.arange(0, 180, theta_prec))
    max_rho = np.sqrt(x.shape[0] ** 2 + x.shape[1] ** 2)
    rho_ax = np.arange(-max_rho, max_rho, rho_prec)
    # 霍夫空间：是一个rho行theta列的空间
    hough_space = np.zeros((len(rho_ax), len(theta_ax)))
    for i in tqdm(range(x.shape[0])):  # i行 j列
        for j in range(x.shape[1]):
            # 找到二值图像中的1点
            if x[i, j] == 0:
                continue
            # 对于每一个theta的量化值求rho
            for t in range(len(theta_ax)):
                rh = j * np.cos(theta_ax[t]) + i * np.sin(theta_ax[t])
                # 量化得到的rho值，由于rho可能为负数，而数组是没有负数索引的
                # （虽然python的负索引有倒数的意义），所以我们要平移到正确的
                # 位置上。
                # 1.加轴的最大值 2.除以精度 3.找到最近整数位
                # *4.给相邻区块加权添加
                # *5.非最大化抑制
                if weight_mat is None:
                    hough_space[int(round((rh + max_rho) / rho_prec)), t] += 1
                else:
                    tgt_point = (int(round((rh + max_rho) / rho_prec)), t)
                    offset = (weight_mat.shape[0] - 1) // 2
                    hot_area = hough_space[tgt_point[0] - offset:tgt_point[0] + offset + 1,
                               tgt_point[1] - offset:tgt_point[1] + offset + 1]
                    if hot_area.shape == weight_mat.shape:
                        hough_space[tgt_point[0] - offset:tgt_point[0] + offset + 1,
                        tgt_point[1] - offset:tgt_point[1] + offset + 1] += weight_mat
    if non_max is True:
        hough_space = non_max_suppression(hough_space)

    # 用优先队列（大顶堆）找到前n个结果
    if topk == 1:
        points = np.where(hough_space == np.max(hough_space))
        return (rho_ax[points[0]], theta_ax[points[1]]), hough_space
    else:
        queue = PriorityQueue()
        for i in range(hough_space.shape[0]):
            for j in range(hough_space.shape[1]):
                queue.put((-hough_space[i, j], rho_ax[i], theta_ax[j], i, j))
        res = [queue.get()[1:] for _ in range(topk)]
        return res, hough_space

img = cv2.imread("imgs/ironnet_small.jpg", cv2.IMREAD_GRAYSCALE)
canny_img = cv2.Canny(img, 200, 230)
kernel = np.array([[2, 4, 5, 4, 2], [4, 9, 12, 9, 4], [5, 12, 15, 12, 5], [4, 9, 12, 9, 4], [2, 4, 5, 4, 2]]) / 159
rho_thetas, hough_img = hough_line(canny_img, topk=10, rho_prec=1, theta_prec=0.5, weight_mat=None, non_max=True)

# 下面都是绘图了
# figure1是对比
fig = plt.figure(1)
ax = plt.subplot(2, 1, 1)
ax.imshow(img, cmap=plt.get_cmap('gray'))
ax.set_title('Result')
print("*" * 30)
print("预测出的直线方程")
for rho, theta, _, _ in rho_thetas:
    print(f"x*{round(np.cos(theta), 2)}+y*{round(np.sin(theta), 2)}={round(rho / 2, 2)}")
    x_ = np.arange(0, canny_img.shape[1])
    y_ = (rho - x_ * np.cos(theta)) / np.sin(theta)
    ax.plot(x_, y_, 'red')
plt.ylim([img.shape[0], 0])
print("*" * 30)
ax = plt.subplot(2, 1, 2)
ax.imshow(canny_img, cmap=plt.get_cmap('gray'))
ax.set_title('Canny')
# figure2是霍夫空间可视化
fig = plt.figure(2)
ax = plt.subplot(1, 1, 1)
ax.imshow(hough_img, origin='lower')
for _, _, ri, ti in rho_thetas:
    ax.scatter(ti, ri)
ax.set_ylabel(r'$\rho$')
ax.set_xlabel(r'$\theta$')
ax.set_title('Hough space')
plt.show()


r = 1000000

def rotate(n):
    n_list = [int(x) for x in str(n)]
    rotations = []
    for digit in range(len(str(n))):
        rotations.append(int(''.join(map(str,n_list))))
        n_list.append(n_list.pop(0))

    return rotations

def gen_primes(n):
    size = n//2
    sieve = [1]*size
    limit = int(n**0.5)
    for i in range(1,limit):
        if sieve[i]:
            val = 2*i+1
            tmp = ((size-1) - i)//val
            sieve[i+val::val] = [0]*tmp
    return [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]

print("Generating primes below {}...".format(r))
primes = gen_primes(r)
print("Primes generated...")
circular_primes = []

print()
print("Calculating circular primes below {}...".format(r))
for prime in primes:
    rotations = rotate(prime)
    primes_in_rotations = 0
    for i in rotations:
        if i not in primes:
            break
        else:
            primes_in_rotations += 1

        if primes_in_rotations == len(rotations) and prime not in circular_primes:
            circular_primes.append(prime)
            print("{} added!".format(str(prime)))

answer = len(circular_primes)
print("Complete! There are {} circular primes below {}".format(str(answer), str(r)))


import requests
import time

import mechanical_ops as mech

import pyrebase
from signal import pause

config = {
  "apiKey": "apiKey",
  "authDomain": "crawler-561c8.firebaseapp.com",
  "databaseURL": "https://crawler-561c8.firebaseio.com",
  "storageBucket": "crawler-561c8.appspot.com",
#   "serviceAccount": "path/to/serviceAccountCredentials.json"
}

firebase = pyrebase.initialize_app(config)
db = firebase.database()

def state_needed(message):
    db.update({"state_list": mech.get_state(), "state_needed": 0})

def set_action(message):
    action_list = message["data"]
    mech.set_speed(action_list)
    time.sleep(0.3)
try:
    db.child("state_needed").stream(state_needed)
    db.child("action_list").stream(set_action)
    print("Ready")
    pause()
except KeyboardInterrupt:
    print("Exiting...")


# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
from odoo import api, fields, models

class MailActivity(models.Model):
    _inherit = 'mail.activity'

    activity_objective_id = fields.Many2one(
        comodel_name='mail.activity.objective',
        string='Activity objective'
    )
    duration = fields.Float(
        string='Duration'
    )

    @api.multi
    def get_old_item_without(self, res_model, res_id):
        res = {
            'date_deadline': False,
            'summary': '',
            'activity_type_id': 0,
            'activity_objective_id': 0,
        }
        activity_ids = self.env['mail.activity'].sudo().search(
            [
                ('res_model', '=', res_model),
                ('res_id', '=', res_id)
            ],
            order="date_deadline asc"
        )
        if activity_ids:
            res = {
                'date_deadline': activity_ids[0].date_deadline,
                'summary': activity_ids[0].summary,
                'activity_type_id': activity_ids[0].activity_type_id.id,
                'activity_objective_id': activity_ids[0].activity_objective_id.id
            }
        # return
        return res

    @api.multi
    def regenerate_model_field(self, res_model, res_id):
        old_item = self.get_old_item_without(res_model, res_id)[0]
        # res_model_item
        res = self.env[res_model].sudo().browse(res_id)
        # next_activity_date_deadline
        if 'next_activity_date_deadline' in res:
            res.next_activity_date_deadline = old_item['date_deadline']
        # next_activity_summary
        if 'next_activity_summary' in res:
            res.next_activity_summary = old_item['summary']
        # next_activity_activity_type_id
        if 'next_activity_activity_type_id' in res:
            res.next_activity_activity_type_id = old_item['activity_type_id']
        # next_activity_activity_objective_id
        if 'next_activity_activity_objective_id' in res:
            res.next_activity_activity_objective_id = old_item['activity_objective_id']
        # return
        return res


import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from emote import user_data
from emote.keybinding import ButtonKeybinding

GRID_SIZE = 10

class Settings(Gtk.Dialog):
    def __init__(self, update_accelerator):
        Gtk.Dialog.__init__(
            self,
            title="Emote Settings",
            window_position=Gtk.WindowPosition.CENTER,
            resizable=False,
        )

        self.update_accelerator = update_accelerator

        header = Gtk.HeaderBar(title="Settings", show_close_button=True)
        self.set_titlebar(header)

        box = self.get_content_area()

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=GRID_SIZE)

        shortcut_label = Gtk.Label()
        shortcut_label.set_text("Keyboard Shortcut")
        shortcut_label.set_justify(Gtk.Justification.LEFT)
        hbox.pack_start(shortcut_label, False, False, GRID_SIZE)

        shortcut_keybinding = ButtonKeybinding()
        shortcut_keybinding.set_size_request(150, -1)
        shortcut_keybinding.connect("accel-edited", self.on_kb_changed)
        shortcut_keybinding.connect("accel-cleared", self.on_kb_changed)
        accel_string, _ = user_data.load_accelerator()
        shortcut_keybinding.set_accel_string(accel_string)

        hbox.pack_start(shortcut_keybinding, False, False, GRID_SIZE)
        box.pack_start(hbox, False, False, GRID_SIZE)

        self.show_all()
        self.present()

    def on_kb_changed(self, button_keybinding, accel_string=None, accel_label=None):
        self.update_accelerator(accel_string, accel_label)


#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals

AUTHOR = 'nlehuby'
SITENAME = 'Le blog de nlehuby'
SITEURL = ''

PATH = 'content'
STATIC_PATHS = ['initialement_publié_sur_drupalgardens', 'images']

THEME = "blue-penguin-theme"

TIMEZONE = 'Europe/Paris'

DEFAULT_LANG = 'fr'

SUMMARY_MAX_LENGTH = 40

# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEED_ATOM = None
AUTHOR_FEED_RSS = None

# Blogroll
LINKS = (('Pelican', 'http://getpelican.com/'),
         ('Python.org', 'http://python.org/'),
         ('Jinja2', 'http://jinja.pocoo.org/'),
         ('You can modify those links in your config file', '#'),)

# Social widget
SOCIAL = (('You can add links in your config file', '#'),
          ('Another social link', '#'),)

DEFAULT_PAGINATION = 5

#Menu blue-penguin
ARCHIVES_URL       = 'archives'
ARCHIVES_SAVE_AS   = 'archives/index.html'

MENU_INTERNAL_PAGES = (
    ('Tous les articles', ARCHIVES_URL, ARCHIVES_SAVE_AS),
)

# additional menu items
MENUITEMS = (
    ('Github', 'https://github.com/nlehuby'),
)

DISPLAY_HEADER = True
DISPLAY_FOOTER = True
DISPLAY_HOME   = True
DISPLAY_MENU   = True
# Uncomment following line if you want document-relative URLs when developing
#RELATIVE_URLS = True