from socket import *

serverName = 'localhost'
serverPort = 8000

try:
    clientSocket = socket(AF_INET, SOCK_STREAM)
    clientSocket.connect((serverName, serverPort))

    arr = [12, 35, 67, 98, 101]
    print('Array is:', arr)
    el = input('Choose your num: ')
    arr_str = ','.join(str(x) for x in arr)
    clientSocket.send((str(el) + ';' + arr_str).encode())

    pos = clientSocket.recv(1024)
    if pos:
        pos = pos.decode()
        if pos != "-1":
            print(f"The index of {el} in the array is {pos}")
        else:
            print(f"{el} is not present in the array")
    else:
        print("Server did not respond")
except ConnectionRefusedError:
    print(f"Could not connect to server at {serverName}:{serverPort}")
finally:
    clientSocket.close()


class Node:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity):
        self.capacity = capacity
        self.dic = dict()
        self.head = Node(0, 0)
        self.tail = Node(0, 0)
        self.head.next = self.tail
        self.tail.prev = self.head

    def get(self, key):
        if key in self.dic:
            node = self.dic[key]
            self._remove(node)
            self._add(node)
            return node.value
        return None

    def set(self, key, value):
        if key in self.dic:
            self._remove(self.dic[key])
        node = Node(key, value)
        self._add(node)
        self.dic[key] = node
        if len(self.dic) > self.capacity:
            node = self.head.next
            self._remove(node)
            del self.dic[node.key]

    def _add(self, node):
        n_prev = self.tail.prev
        n_prev.next = node
        self.tail.prev = node
        node.prev = n_prev
        node.next = self.tail

    def _remove(self, node):
        n_prev = node.prev
        n_next = node.next
        n_prev.next = n_next
        n_next.prev = n_prev


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

from django.contrib import admin
from django.contrib.auth.decorators import login_required
from website.views import (index_page, robots_txt, error_403,
                            error_404, error_500, favicon_ico)
from accounts.views import login, logout
from asterisk.views import (
    IndexPage, WebsitesPage, save_website_js, ExternalPhonesPage,
    ExternalPhoneAddView, ExternalPhoneEditView, InternalPhonesPage,
    InternalPhoneAddView, InternalPhoneEditView, EmployeesPage,
    EmployeeAddView, EmployeeEditView, StatPageView, DepartmentPage,
    DepartmentAddView, DepartmentEditView, update_call_status,
    check_wav_file_exists, get_wav_file, get_num_comments, add_call_comment,
    get_call_comments
)
admin.autodiscover()

urlpatterns = [
    url(r'^$', IndexPage.as_view(), name='home'),
    url(r'^get-num-comments/$', get_num_comments, name='get_num_comments'),
    url(r'^add-call-comment/$', add_call_comment, name='add_call_comment'),
    url(r'^get-call-comments/$', get_call_comments, name='get_call_comments'),
    url(r'^update-call-status/$', update_call_status,
        name='update_call_status'),
    url(r'^check-wav-file-exists/$', check_wav_file_exists,
        name='check_wav_file_exists'),
    url(r'^get-wav-file/$', get_wav_file, name='get_wav_file'),
    # url(r'^favicon.ico$', favicon_ico, name='favicon_ico'),
    url(r'^robots.txt$', robots_txt, name='robots_txt'),
    url(r'^login/$', login, name='main_login'),
    url(r'^logout/$', logout, name='logout'),
    url(r'^websites/$', WebsitesPage.as_view(), name='websites'),
    url(r'^external-phones/$', ExternalPhonesPage.as_view(),
        name='external_phones'),
    url(r'^external-phone-add/$', ExternalPhoneAddView.as_view(),
        name='external_phone_add'),
    url(r'^external-phone-edit/(?P<pk>[\w-]+)/$',
        ExternalPhoneEditView.as_view(), name='external_phone_edit'),
    url(r'^internal-phones/$', InternalPhonesPage.as_view(),
        name='internal_phones'),
    url(r'^internal-phone-add/$', InternalPhoneAddView.as_view(),
        name='internal_phone_add'),
    url(r'^internal-phone-edit/(?P<pk>[\w-]+)/$',
        InternalPhoneEditView.as_view(), name='internal_phone_edit'),
    url(r'^add-website/$', login_required(save_website_js),
        name='save_website_js'),
    url(r'^employees-list/$', EmployeesPage.as_view(), name='employees_page'),
    url(r'^employee-add/$', EmployeeAddView.as_view(), name='employee_add'),
    url(r'^employee-edit/(?P<pk>[\w-]+)/$', EmployeeEditView.as_view(),
        name='employee_edit'),
    url(r'^departments/$', DepartmentPage.as_view(), name='departments'),
    url(r'^department-add/$', DepartmentAddView.as_view(),
        name='department_add'),
    url(r'^department-edit/(?P<pk>[\w-]+)/$', DepartmentEditView.as_view(),
        name='department_edit'),
    url(r'^statistics/$', StatPageView.as_view(), name='stats'),
    url(r'^admin/', include(admin.site.urls)),
]

if 'rosetta' in settings.INSTALLED_APPS:
    urlpatterns += [
        url(r'^rosetta/', include('rosetta.urls')),
    ]


from firstfuncs_1618 import *

## CFSv1 (2000-2011)

## CFSv2 (2011-)
#land mask
lmask=xr.open_dataset(datadir+'aux_data/Air-Sea_FW/NCEP_CFSv2/LandCover/pgbh.gdas.201101.grb2.nc')
lmask['mask']=(('lat','lon'),lmask.LAND_L1_Avg.values[0,:,:])
lmask.mask.plot()
#eminusp
eplist=sort(glob.glob(datadir+'aux_data/Air-Sea_FW/NCEP_CFSv2/Average/EminusP/*.nc'))
ep=xr.open_dataset(eplist[0])
for ii,xx in enumerate(eplist[1:]):
    eptmp=xr.open_dataset(xx)
    ep=xr.concat([ep,eptmp],dim='time')
ep=ep.rename({'EMNP_L1_FcstAvg6hr':'ep'})
#surfacefluxes
hflist=sort(glob.glob(datadir+'aux_data/Air-Sea_FW/NCEP_CFSv2/Average/SurfaceFluxes/*.nc'))
hf=xr.open_dataset(hflist[0])
for ii,xx in enumerate(hflist[1:]):
    hftmp=xr.open_dataset(xx)
    hf=xr.concat([hf,hftmp],dim='time')

hf=hf.rename({'SHTFL_L1_FcstAvg6hr':'shf','LHTFL_L1_FcstAvg6hr':'lhf','DSWRF_L1_FcstAvg6hr':'dsw','USWRF_L1_FcstAvg6hr':'usw','DLWRF_L1_FcstAvg6hr':'dlw','ULWRF_L1_FcstAvg6hr':'ulw'})

hf=hf.where(lmask.mask==0)

hf.usw.mean(dim='time').plot()
hf.dsw.mean(dim='time').plot()
hf.lhf.mean(dim='time').plot()
hf.shf.mean(dim='time').plot()
ep.ep.mean(dim='time').plot()
#load NORESM boundaries and extract data within box
osnap=xr.open_dataset(datadir+'NorESM/NorESM_osnap_xray_1912.nc')
ns=xr.open_dataset(datadir+'NorESM/NorESM_ns_xray_1912.nc')
fs=xr.open_dataset(datadir+'NorESM/NorESM_fs_xray_1912.nc')
bso=xr.open_dataset(datadir+'NorESM/NorESM_bso_xray_1912.nc')

bnd_lon=hstack((fs.LONGITUDE.values,bso.LONGITUDE.values,ns.LONGITUDE.values[::-1],osnap.LONGITUDE.values[::-1],-45,-40,fs.LONGITUDE.values[0]))
bnd_lat=hstack((fs.LATITUDE.values,bso.LATITUDE.values,ns.LATITUDE.values[::-1],osnap.LATITUDE.values[::-1],60,75,fs.LATITUDE.values[0]))

plot(bnd_lon,bnd_lat,linewidth=3,color='k')

import regionmask

bnd_tpl=array(tuple((zip(bnd_lon,bnd_lat))))

mybox = regionmask.Regions([bnd_tpl], name='mybox')
ax = mybox.plot()

#create masks
epmask = mybox.mask(ep.lon.values,ep.lat.values)
hfmask = mybox.mask(hf.lon.values,hf.lat.values)

cut_ep=ep.where(epmask==0)
cut_hf=hf.where(hfmask==0)

cut_ep

cut_ep['time']=cut_hf['time']

cut_ep.ep.mean(dim='time').plot()
cut_hf.lhf.mean(dim='time').plot()
cut_hf.shf.mean(dim='time').plot()

def get_area(dat):
    lonmat,latmat=meshgrid(dat.lon,dat.lat)
    loni=vstack((lonmat.T-0.25,lonmat[:,-1].T+0.25)).T
    lathold=vstack((latmat.T,latmat[:,-1].T)).T
    lati=vstack((latmat+0.25,latmat[-1,:]+0.25))
    lonhold=vstack((latmat,latmat[-1,:]))
    # plot(lonmat[:10,:10],latmat[:10,:10],'.');
    # plot(loni[:10,:10],lati[:10,:10],'o');
    latdist=gsw.distance(lonhold,lati,axis=0)
    londist=gsw.distance(loni,lathold)
    dat['area']=(('lat','lon'),londist*latdist)
    return dat

cut_ep=get_area(cut_ep)
cut_hf=get_area(cut_hf)

cut_ep['ep_int']=(cut_ep.ep*cut_ep.area).sum(dim='lon').sum(dim='lat')/100/24/60/60/1e6
#convert from cm/day to Sv (10^6 m3/s)

cut_hf['hf_int']=((cut_hf.lhf+cut_hf.shf+cut_hf.ulw+cut_hf.usw-cut_hf.dsw-cut_hf.dlw)*cut_hf.area).sum(dim='lon').sum(dim='lat')/1e12
#convert to TW

cut_hf.area.plot()

int_all=xr.merge([cut_hf.hf_int,cut_ep.ep_int])
int_all.ep_int.plot()

int_all.to_netcdf(datadir+'aux_data/Air-Sea_FW/NCEP_CFSv2/NCEP_ephf_cutint_ilebras.nc','w')


add_library('peasycam')
add_library('controlP5')

fltSize = 10

def setup():
    size(800,450,P3D)
    noStroke()
    global cam, cp5, sldX, sldY, sldPX, sldPY
    cam=PeasyCam(this,100)
    cp5 = ControlP5(this)
    sldX = cp5.addSlider("div x").setRange(1.0,10.0).setValue(3.0).setPosition(10,10)
    sldPX = cp5.addSlider("phase x").setRange(-HALF_PI,HALF_PI).setPosition(10,40)
    sldY = cp5.addSlider("div y").setRange(1.0,10.0).setValue(3.0).setPosition(10,70)
    sldPY = cp5.addSlider("phase y").setRange(-HALF_PI,HALF_PI).setPosition(10,100)
    cp5.setAutoDraw(False)

def draw():
    if mouseX<200:
        cam.setActive(False)
    else:
        cam.setActive(True)
    background(0)
    #lights()
    directionalLight(255,200,200,1,0,-0.5)
    directionalLight(200,200,255,-1,0,-0.5)
    translate(-7.5*fltSize,-4*fltSize)
    for i in range(16):
        for j in range(9):
            pushMatrix()
            translate(i*fltSize,j*fltSize)
            rotateY(sin(sldPX.getValue()+i/sldX.getValue())*cos(sldPY.getValue()+j/sldY.getValue()))
            box(fltSize*0.9)
            popMatrix()

    cam.beginHUD()
    noLights()
    cp5.draw()
    cam.endHUD()


from typing import Dict, Union
import pdb
import logging

from overrides import overrides
import numpy
import torch
from torch.autograd import Variable

from allennlp.data.fields.field import Field
from allennlp.data.vocabulary import Vocabulary
from allennlp.common.checks import ConfigurationError

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

class NumericField(Field[numpy.ndarray]):
    """
    A ``LabelField`` is a categorical label of some kind, where the labels are either strings of
    text or 0-indexed integers (if you wish to skip indexing by passing skip_indexing=True).
    If the labels need indexing, we will use a :class:`Vocabulary` to convert the string labels
    into integers.

    This field will get converted into an integer index representing the class label.

    Parameters
    ----------
    label : ``Union[str, int]``
    label_namespace : ``str``, optional (default="labels")
        The namespace to use for converting label strings into integers.  We map label strings to
        integers for you (e.g., "entailment" and "contradiction" get converted to 0, 1, ...),
        and this namespace tells the ``Vocabulary`` object which mapping from strings to integers
        to use (so "entailment" as a label doesn't get the same integer id as "entailment" as a
        word).  If you have multiple different label fields in your data, you should make sure you
        use different namespaces for each one, always using the suffix "labels" (e.g.,
        "passage_labels" and "question_labels").
    skip_indexing : ``bool``, optional (default=False)
        If your labels are 0-indexed integers, you can pass in this flag, and we'll skip the indexing
        step.  If this is ``False`` and your labels are not strings, this throws a ``ConfigurationError``.
    """
    def __init__(self,
                 label: Union[float, int],
                 label_namespace: str = 'labels') -> None:
        self.label = label
        self._label_namespace = label_namespace
        self._label_id = numpy.array(label, dtype=numpy.float32)
        if not (self._label_namespace.endswith("labels") or self._label_namespace.endswith("tags")):
            logger.warning("Your label namespace was '%s'. We recommend you use a namespace "
                           "ending with 'labels' or 'tags', so we don't add UNK and PAD tokens by "
                           "default to your vocabulary.  See documentation for "
                           "`non_padded_namespaces` parameter in Vocabulary.", self._label_namespace)

    # idk what this is for
    @overrides
    def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
        if self._label_id is None:
            counter[self._label_namespace][self.label] += 1  # type: ignore

    @overrides
    def get_padding_lengths(self) -> Dict[str, int]:  # pylint: disable=no-self-use
        return {}

    def as_array(self, padding_lengths: Dict[str, int]) -> numpy.ndarray:  # pylint: disable=unused-argument
        return numpy.asarray([self._label_id])

    @overrides
    def as_tensor(self, padding_lengths: Dict[str, int],
                  cuda_device: int = -1,
                  for_training: bool = True) -> torch.Tensor:  # pylint: disable=unused-argument
        label_id = self._label_id.tolist()
        tensor = Variable(torch.FloatTensor([label_id]), volatile=not for_training)
        return tensor if cuda_device == -1 else tensor.cuda(cuda_device)

    @overrides
    def empty_field(self):
        return NumericField(0, self._label_namespace)


# https://projecteuler.net/problem=54

if __name__ == '__main__':

    try:

        def init():
            stringData = []
            fileHandler = open('project_euler_54_input.txt')
            for line in fileHandler:
                stringData.append(line.replace('\n', ''))

            # print(stringData)
            return stringData

        DATA = init()

        def score_hands(hands_str):
            HANDS = hands_str.split(" ")
            PLAYER_1 = HANDS[0:5]
            PLAYER_2 = HANDS[5:10]
            #print(PLAYER_1)
            #print(PLAYER_2)

            score_1 = hash_hand(PLAYER_1)
            score_2 = hash_hand(PLAYER_2)

            print(score_1)
            print(score_2)

            if score_1[0] > score_2[0]:
                return 1

            if score_2[0] > score_1[0]:
                return 2

            print("Tie! Breaking ...")
            for x in range(1, len(score_1), 1):
                if score_1[x] > score_2[x]:
                    return 1
                if score_2[x] > score_1[x]:
                    return 2

        CARD_MAP = {
            '1':1,
            '2':2,
            '3':3,
            '4':4,
            '5':5,
            '6':6,
            '7':7,
            '8':8,
            '9':9,
            'T':10,
            'J':11,
            'Q':12,
            'K':13,
            'A':14
        }

        def hash_hand(hand):
            print(hand)

            suits = {}
            cards = {}

            for x in range(0, len(hand), 1):
                card_str = str(hand[x])
                # print(card_str)
                suit_str = card_str[len(card_str) - 1:len(card_str)]
                num_str = CARD_MAP[card_str[0:len(card_str) - 1]]

                suit_check = suits.get(suit_str)
                if suit_check is None:
                    suits[suit_str] = 1
                else:
                    suits[suit_str] = suits[suit_str] + 1

                card_check = cards.get(num_str)
                if card_check is None:
                    cards[num_str] = 1
                else:
                    cards[num_str] = cards[num_str] + 1

            print(suits)
            print(cards)

            SUIT_KEYS = suits.keys()
            CARD_KEYS = cards.keys()

            # Arrays
            pairs = []
            singles = []

             # Booleans only
            is_flush = len(SUIT_KEYS) == 1
            is_royal = False

            # False when False
            # Takes highest card for tie breaks when True
            is_straight = False
            is_three_kind = False
            is_four_kind = False

            for x in range(0, len(CARD_KEYS), 1):
                KEY = CARD_KEYS[x]
                VAL = cards[KEY]

                if VAL == 1:
                    singles.append(KEY)

                if VAL == 2:
                    pairs.append(KEY)

                if VAL == 3:
                    is_three_kind = KEY

                if VAL == 4:
                    is_four_kind = KEY

            singles.sort()

            if len(singles) == 5:
                is_straight = singles[4]

                for x in range(0, len(singles) - 1, 1):
                    if singles[x] == singles[x+1] - 1:
                        continue
                    else:
                        is_straight = False

                if not is_straight == False and singles[4] == 14:
                    is_royal = True

            """
            SCORE MAP:

                'High Card':        1
                'One Pair':         2
                'Two Pairs':        3
                'Three of a Kind':  4
                'Straight':         5
                'Flush':            6
                'Full House':       7
                'Four of a Kind':   8
                'Straight Flush':   9
                'Royal Flush':      10
            """

            # returns [score, tie break 1, tie break 2, tie break 3]
            pairs.sort()

            if not is_straight == False and is_flush and is_royal:
                # Royal Flush - Tie Break
                print("Royal Flush")
                return [10, is_straight, is_straight, is_straight]

            if not is_straight == False and is_flush:
                # Straight Flush - Tie Break
                print("Straight Flush")
                return [9, is_straight, is_straight, is_straight]

            if not is_four_kind == False and len(singles) == 1:
                # Four of Kind - Tie Break
                print("Four of Kind")
                return [8, is_four_kind, singles[0], singles[0]]

            if not is_three_kind == False and len(pairs) == 1:
                # Full House - Tie Break
                print("Full House")
                return [7, is_three_kind, pairs[0], pairs[0]]

            if is_flush:
                # Flush - Tie Break
                print("Flush")
                return [6, is_flush, is_flush, is_flush]

            if not is_straight == False:
                # Straight - Tie Break
                print("Straight")
                return [5, is_straight, is_straight, is_straight]

            if not is_three_kind == False and len(singles) == 2:
                # Three of a Kind - Tie Break
                print("Three of a Kind")
                return [4, is_three_kind, singles[1], singles[0]]

            if len(pairs) == 2 and len(singles) == 1:
                # Two Pairs - Tie Break
                print("Two Pairs")
                return [3, pairs[1], pairs[0], singles[0]]

            if len(pairs) == 1 and len(singles) == 3:
                # One Pair - Tie Break
                print("One Pair")
                return [2, pairs[0], singles[2], singles[1]]

            if len(singles) == 5:
                # Highest Card - Tie Break
                print("High Card")
                return [1, singles[4], singles[3], singles[2]]

            print("Error: no score for hand " + str(hand) + " found!")
            raise Exception

        # print(hash_hand(['KS', 'QS', 'AS', 'JS', 'TS']))
        # print(hash_hand(['3S', '3D', '3C', 'JS', 'JD']))
        # print(hash_hand(['3S', '4S', '5S', '6S', '7S']))
        # print(hash_hand(['3S', '4S', '5S', '6S', '7D']))

        def solve():
            player_one_wins_total = 0

            for x in range(0, len(DATA), 1):
                outcome = score_hands(DATA[x])
                print("Player " + str(outcome) + " wins hand!\n")

                if outcome == 1:
                    player_one_wins_total = player_one_wins_total + 1

            print("Player one won: " + str(player_one_wins_total) + " times")
            return player_one_wins_total

        # solve() # Player one won: 376 times

    except Exception as ex:

        print('Exception: ' + str(ex))


import pytest
from Funciones import add_digits, fill_word

def test_sum_digits():
    assert add_digits(123)==6

@pytest.mark.parametrize(
        "input_number, expected",
        [
            (458, 17),
            (920, 11),
            (add_digits(5261), 5),
            (8375, 23),
            (add_digits(62934), 6)
        ]
)
def test_sum_digits_parameters(input_number,expected):
    assert add_digits(input_number)==expected

def test_fill_word():
    assert fill_word("UAI", "USUARIO")=="U_UA_I_"

@pytest.mark.parametrize(
        "input_characters, input_hidden_word, expected",
        [
            ("AODRH", "ARCHIVO", "AR_H__O"),
            ("NTE", "INTERNET", "_NTE_NET"),
            ("MPSR", "IMPRESORA", "_MPR_S_R_"),
        ]
)
def test_fill_word_parameters(input_characters, input_hidden_word, expected):
    assert fill_word(input_characters, input_hidden_word)==expected


import sqlite3
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Replace with your own token
bot = telegram.Bot(token='6280857926:AAF9I7zUDbaEE-gv0PuuT31JrALqffQ0MqE')

# Connect to the database
conn = sqlite3.connect('items.db')
c = conn.cursor()

# Create the items table if it does not exist
c.execute('''CREATE TABLE IF NOT EXISTS items
             (name text, price real)''')

# Insert some sample items
c.execute("INSERT INTO items VALUES ('spotify 1m', 10.0)")
c.execute("INSERT INTO items VALUES ('spotify 2m', 20.0)")
c.execute("INSERT INTO items VALUES ('spotify 3m', 30.0)")

# Handler for /start command
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Welcome to my store! Here are the items we sell:")

    # Retrieve the items from the database
    c.execute("SELECT * FROM items")
    items = c.fetchall()

    # Send the items as a list
    item_list = '\n'.join([f'{item[0]} - PHP {item[1]}' for item in items])
    context.bot.send_message(chat_id=update.effective_chat.id, text=item_list)

# Handler for text messages
def order(update, context):
    item_name = update.message.text

    # Check if the item is in the database
    c.execute("SELECT * FROM items WHERE name=?", (item_name,))
    item = c.fetchone()

    if item is None:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, that item is not available.")
    else:
        # Save the order to user data
        context.user_data['order'] = item_name
        context.user_data['price'] = item[1]

        # Send the GCash details
        context.bot.send_message(chat_id=update.effective_chat.id, text=f"To order {item_name} (PHP {item[1]}), please pay through GCash to 09550388450 and send a screenshot of the payment confirmation to me.")

# Handler for payment confirmation
def payment(update, context):
    if update.message.photo:
        # Check if the payment is correct
        amount_paid = 0.0
        for photo in update.message.photo:
            file_id = photo.file_id
            file = context.bot.get_file(file_id)
            file.download()
            amount_paid += 1.0 # Assume that each photo represents 1 PHP

        if amount_paid >= context.user_data['price']:
            # Send the confirmation message and the ordered items
            context.bot.send_message(chat_id=update.effective_chat.id, text="Thank you for your payment! Your order will be shipped soon.")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Here are your ordered items: {} - PHP {}".format(context.user_data['order'], context.user_data['price']))

# Create the handlers and attach them to the dispatcher
updater = Updater(token='6280857926:AAF9I7zUDbaEE-gv0PuuT31JrALqffQ0MqE', use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(MessageHandler(Filters.regex(r'^\d+$'), order))
dispatcher.add_handler(MessageHandler(Filters.photo, payment))

# Start the bot
updater.start_polling()
updater.idle()

# Close the database connection
conn.close()


from datetime import datetime
from typing import List
import logging
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup

import discord
from discord import app_commands
from discord.ext import commands

from uqcsbot.bot import UQCSBot
from uqcsbot.yelling import yelling_exemptor

MAX_COUPONS = 10  # Prevents abuse
COUPONESE_DOMINOS_URL = "https://www.couponese.com/store/dominos.com.au/"

class HTTPResponseException(Exception):
    """
    An exception for when a HTTP response is not requests.codes.ok
    """

    def __init__(self, http_code: int, *args: object) -> None:
        super().__init__(*args)
        self.http_code = http_code

class DominosCoupons(commands.Cog):
    def __init__(self, bot: UQCSBot):
        self.bot = bot

    @app_commands.command()
    @app_commands.describe(
        number_of_coupons="The number of coupons to return. Defaults to 5 with max 10.",
        ignore_expiry="Indicates to include coupons that have expired. Defaults to True.",
        keywords="Words to search for within the coupon. All coupons descriptions will mention at least one keyword.",
    )
    @yelling_exemptor(input_args=["keywords"])
    async def dominoscoupons(
        self,
        interaction: discord.Interaction,
        number_of_coupons: int = 5,
        ignore_expiry: bool = True,
        keywords: str = "",
    ):
        """
        Returns a list of dominos coupons
        """
        if number_of_coupons < 1 or number_of_coupons > MAX_COUPONS:
            await interaction.response.send_message(
                content=f"You can't have that many coupons. Try a number between 1 and {MAX_COUPONS}.",
                ephemeral=True,
            )
            return
        await interaction.response.defer(thinking=True)

        try:
            coupons = _get_coupons(number_of_coupons, ignore_expiry, keywords.split())
        except RequestException as error:
            logging.warning(
                f"Could not connect to dominos coupon site ({COUPONESE_DOMINOS_URL}): {error.response.content}"
            )
            await interaction.edit_original_response(
                content=f"Sadly could not reach the coupon website (<{COUPONESE_DOMINOS_URL}>)..."
            )
            return
        except HTTPResponseException as error:
            logging.warning(
                f"Received a HTTP response code {error.http_code}. Error information: {error}"
            )
            await interaction.edit_original_response(
                content=f"Could not find the coupons on the coupon website (<{COUPONESE_DOMINOS_URL}>)..."
            )
            return

        if not coupons:
            await interaction.edit_original_response(
                content=f"Could not find any coupons matching the given arguments from the coupon website (<{COUPONESE_DOMINOS_URL}>)."
            )
            return

        embed = discord.Embed(
            title="Domino's Coupons",
            url=COUPONESE_DOMINOS_URL,
            description=f"Keywords: *{keywords}*" if keywords else None,
            timestamp=datetime.now(),
        )
        for coupon in coupons:
            embed.add_field(
                name=coupon.code,
                value=f"{coupon.description} *[Expires: {coupon.expiry_date}]*",
                inline=False,
            )
        await interaction.edit_original_response(embed=embed)

class Coupon:
    def __init__(self, code: str, expiry_date: str, description: str) -> None:
        self.code = code
        self.expiry_date = expiry_date
        self.description = description

    def is_valid(self) -> bool:
        try:
            expiry_date = datetime.strptime(self.expiry_date, "%Y-%m-%d")
            now = datetime.now()
            return all(
                [
                    expiry_date.year >= now.year,
                    expiry_date.month >= now.month,
                    expiry_date.day >= now.day,
                ]
            )
        except ValueError:
            return True

    def keyword_matches(self, keyword: str) -> bool:
        return keyword.lower() in self.description.lower()

def _get_coupons(n: int, ignore_expiry: bool, keywords: List[str]) -> List[Coupon]:
    """
    Returns a list of n Coupons
    """

    coupons = _get_coupons_from_page()

    if not ignore_expiry:
        coupons = [coupon for coupon in coupons if coupon.is_valid()]

    if keywords:
        coupons = [
            coupon
            for coupon in coupons
            if any(coupon.keyword_matches(keyword) for keyword in keywords)
        ]
    return coupons[:n]

def _get_coupons_from_page() -> List[Coupon]:
    """
    Strips results from html page and returns a list of Coupon(s)
    """
    http_response = requests.get(COUPONESE_DOMINOS_URL)
    if http_response.status_code != requests.codes.ok:
        raise HTTPResponseException(http_response.status_code)
    soup = BeautifulSoup(http_response.content, "html.parser")
    soup_coupons = soup.find_all(class_="ov-coupon")

    coupons: List[Coupon] = []

    for soup_coupon in soup_coupons:
        expiry_date_str = soup_coupon.find(class_="ov-expiry").get_text(strip=True)
        description = soup_coupon.find(class_="ov-desc").get_text(strip=True)
        code = soup_coupon.find(class_="ov-code").get_text(strip=True)
        coupon = Coupon(code, expiry_date_str, description)
        coupons.append(coupon)

    return coupons

async def setup(bot: UQCSBot):
    await bot.add_cog(DominosCoupons(bot))


# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request, route

class SaleController(http.Controller):
    @http.route("/check_sale_order", type="http", website=True, auth="public")
    def check_sale_order(self):
        sale_orders = request.env["sale.order"].sudo().search([])
        return request.render(
            "purchase_append.sale_order_page", {"sale_orders": sale_orders}
        )

    @http.route("/view_sale_order", type="http", website=True, auth="public")
    def view_sale_order(self, **post):
        if post:
            sale_id = int(post["sale_orders"])
            invoice_add = (
                request.env["sale.order"].browse(int(sale_id)).partner_invoice_id
            )
            invoice_address = (
                invoice_add.street
                + " "
                + (invoice_add.street2 or "")
                + " "
                + invoice_add.city
                + " "
                + (invoice_add.state_id and invoice_add.state_id.name or "")
                + " "
                + (invoice_add.country_id and invoice_add.country_id.name or "")
            )

            delivery_add = (
                request.env["sale.order"].browse(int(sale_id)).partner_shipping_id
            )
            delivery_address = (
                delivery_add.street
                + " "
                + (delivery_add.street2 or "")
                + " "
                + delivery_add.city
                + " "
                + (delivery_add.state_id and delivery_add.state_id.name or "")
                + " "
                + (delivery_add.country_id and delivery_add.country_id.name or "")
            )

            vals = {
                "sale_data": request.env["sale.order"].sudo().browse(sale_id),
                "partner_invoice_address": invoice_address,
                "partner_delivery_address": delivery_address,
            }
            tracking_order_vals = {
                "sales_order_ref": sale_id,
                "user_name": request._uid,
            }
            request.env["tracking.order"].sudo().create(tracking_order_vals)

            return request.render("purchase_append.view_sale_order_page", vals)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 22:49:38 2020

@author: lenovo
"""

#引入unittest
import unittest
#引入报告模板
import HTMLTestRunner
#引入request库
import requests
#引入json管理
import json

#测试类，继承了unittest.TestCase
class TestLHL(unittest.TestCase):
    #用于初始化操作可选
    def setUp(self):
        #地址前缀
        self.base_url='http://v.juhe.cn'
        #设置请求头信息
        self.headers={'Content-Type':'application/json'}
    #用于结束之后的清理工作，可选
    def tearDown(self):
        pass

    #@unittest.skip("这句如果注释掉就会跳过此用例不执行")
    #测试case,一定是以test开头
    def test_LHL_1(self):
        '''date格式正确'''
        #完整的接口请求地址
        self.full_url=self.base_url+'/laohuangli/d'
        #接口请求参数
        self.params={'key':'key','date':'2018-01-01'}
        #异常处理模块
        try:
            #调用requests库中的get方法请求接口
            r=requests.get(self.full_url,params=self.params,headers=self.headers)
            #对返回的内容进行解码
            json_r=r.json()
            #打印相关内容
            print('HTTP状态码=',r.status_code)
            print('响应时间（毫秒)=',r.elapsed.microseconds)
            #断言检查，返回的error_code是否为0
            self.assertEqual(json_r['error_code'],0)
            print("实际结果符合预期结果")
            print("响应内容=",json_r)
        except Exception as e:
            print('错误：%s'%e)
#通过添加类名来运行
all_suite=unittest.makeSuite(TestLHL)
#设置为调试模式，可以看到更多日志输出
runner=unittest.TextTestRunner(verbosity=2)
#设置报告保存位置F:\python
filename='F://python/report.html'
#以写方式打开，准备写入数据
fp=open(filename,'wb')
#执行测试，并写入数据
runner=HTMLTestRunner.HTMLTestRunner(stream=fp,title='接口测试报告',description='接口测试')
runner.run(all_suite)
#关闭文件，如果不关闭则无法写入数据
fp.close()


from client.models.game_objects.first_player import FirstPlayer
from client.models.game_objects.gorilla import Gorilla
from client.models.game_objects.ladder import Ladder
from client.models.game_objects.platform import Platform
from client.models.game_objects.princess import Princess
from client.models.game_objects.second_player import SecondPlayer
from common.constants import SCENE_HEIGHT, SCENE_GRID_BLOCK_HEIGHT, SCENE_WIDTH, SCENE_GRID_BLOCK_WIDTH
from common.enums.layout_block import LayoutBlock

class GridPainter:
    def __init__(self):
        pass

    """ Paints objects inside layout to a scene """
    def paint_layout(self, scene, layout):
        rows = int(SCENE_HEIGHT / SCENE_GRID_BLOCK_HEIGHT)
        columns = int(SCENE_WIDTH / SCENE_GRID_BLOCK_WIDTH)

        for row in range(rows):
            for column in range(columns):
                if layout[row][column] == LayoutBlock.Platform:
                    temp = Platform()
                    temp.setPos(column * SCENE_GRID_BLOCK_WIDTH, row * SCENE_GRID_BLOCK_HEIGHT)
                    scene.addItem(temp)
                elif layout[row][column] == LayoutBlock.Ladder:
                    temp = Ladder()
                    temp.setPos(column * SCENE_GRID_BLOCK_WIDTH, row * SCENE_GRID_BLOCK_HEIGHT)
                    scene.addItem(temp)
                elif layout[row][column] == LayoutBlock.Player_1:
                    if isinstance(scene.me, FirstPlayer):
                        scene.me.starting_x = column * SCENE_GRID_BLOCK_WIDTH
                        scene.me.starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5
                        scene.me.item.setPos(scene.me.starting_x, scene.me.starting_y)
                        scene.addItem(scene.me.item)
                    else:
                        scene.opponent.starting_x = column * SCENE_GRID_BLOCK_WIDTH
                        scene.opponent.starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5
                        scene.opponent.item.setPos(scene.opponent.starting_x, scene.opponent.starting_y)
                        scene.addItem(scene.opponent.item)
                    layout[row][column] = None
                elif layout[row][column] == LayoutBlock.Player_2:
                    if isinstance(scene.me, SecondPlayer):
                        scene.me.starting_x = column * SCENE_GRID_BLOCK_WIDTH + 13
                        scene.me.starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5
                        scene.me.item.setPos(scene.me.starting_x, scene.me.starting_y)
                        scene.addItem(scene.me.item)
                    else:
                        scene.opponent.starting_x = column * SCENE_GRID_BLOCK_WIDTH + 13
                        scene.opponent.starting_y = row * SCENE_GRID_BLOCK_HEIGHT + 5
                        scene.opponent.item.setPos(scene.opponent.starting_x, scene.opponent.starting_y)
                        scene.addItem(scene.opponent.item)
                    layout[row][column] = None
                elif layout[row][column] == LayoutBlock.Princess:
                    scene.princess = Princess(scene, column * SCENE_GRID_BLOCK_WIDTH, row * SCENE_GRID_BLOCK_HEIGHT)
                    scene.addItem(scene.princess.item)
                elif layout[row][column] == LayoutBlock.Gorilla:
                    scene.gorilla = Gorilla(column * SCENE_GRID_BLOCK_WIDTH, row * SCENE_GRID_BLOCK_HEIGHT - 15)
                    scene.addItem(scene.gorilla.item)


import pytest

user_in_x = 1
user_in_y = 1
user_in_z = 1

coordinates_list = []

def get_coordinates():
    for coordX in range(0, user_in_x + 1):
        for coordY in range(0, user_in_y + 1):
            for coordZ in range(0, user_in_z + 1):
                temp_list = []
                temp_list.append(coordX)
                temp_list.append(coordY)
                temp_list.append(coordZ)
                coordinates_list.append(temp_list)
    return coordinates_list

def test_get_coordinates():
    assert get_coordinates() == [[coordX, coordY, coordZ]
                                 for coordX in range(user_in_x + 1)
                                 for coordY in range(user_in_y + 1)
                                 for coordZ in range(user_in_z + 1)
                                 ]


import numpy as np

from gym.spaces import Box
from gym import ObservationWrapper

class ResizeObservation(ObservationWrapper):
    r"""Downsample the image observation to a square image. """
    def __init__(self, env, shape):
        super(ResizeObservation, self).__init__(env)
        if isinstance(shape, int):
            shape = (shape, shape)
        assert all(x > 0 for x in shape), shape
        self.shape = tuple(shape)

        obs_shape = self.shape + self.observation_space.shape[2:]
        self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)

    def observation(self, observation):
        import cv2
        observation = cv2.resize(observation, self.shape[::-1], interpolation=cv2.INTER_AREA)
        if observation.ndim == 2:
            observation = np.expand_dims(observation, -1)
        return observation


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 31 14:59:28 2021

@author: Administrator
"""

key=int(input('要查找的数值：'))
d=[6,12,18,25,25,25,35,46,58,60]
f=False
i=0
j=len(d)-1
while i<=j:
    m=(i+j)//2
    if d[m]<=key:
        j=m-1
    else:
        i=m+1
if d[i]==key:
    print(key,i)
else:
    print('不存在')

高二上/对分找第一个.py


import torch
import torch.nn as nn
import torch.nn.functional as F
from torchcrf import CRF
from w2v import load_word2vec

class BiLSTM_CRF(nn.Module):
    def __init__(self,
                 word2seq,
                 char2seq,
                 tag2seq,
                 config,
                 num_heads=8):
        super(BiLSTM_CRF, self).__init__()
        self.word2seq = word2seq
        self.char2seq = char2seq
        self.tag2seq = tag2seq
        self.config = config

        self.char_embedding = nn.Embedding(len(self.char2seq), self.config.char_embedding_dim)
        self.char_cnn = nn.Conv2d(in_channels=self.config.max_char_len, out_channels=1, kernel_size=3, stride=1, padding=1)

        if self.config.use_pretrain_embedding:
            self.embedding = nn.Embedding.from_pretrained(load_word2vec(self.config.embedding_path, word2seq), freeze=False)
        else:
            self.embedding = nn.Embedding(len(self.word2seq), self.config.embedding_dim)
        self.lstm = nn.LSTM(input_size=self.config.embedding_dim + self.config.char_embedding_dim, hidden_size=self.config.hidden_size, batch_first=True, bidirectional=True)
        self.dropout = nn.Dropout(p=self.config.dropout)
        self.fc = nn.Linear(self.config.hidden_size * 2, len(self.tag2seq))
        if self.config.use_crf:
            self.crf = CRF(num_tags=len(self.tag2seq), batch_first=True)
        if self.config.use_att:
            self.mul_att = nn.MultiheadAttention(embed_dim=self.config.hidden_size * 2, batch_first=True, dropout=self.config.dropout, num_heads=num_heads)

    def encode(self, sentences):
        output, (h_n, _) = self.lstm(sentences)  # output [batch_size, length, hidden_size * 2] h_n [num_lays*num_direction, batch_size, hidden_size]
        output = self.dropout(output)
        if self.config.use_att:
            output, _ = self.mul_att(output, output, output)
        emit_score = self.fc(output)  # emit_score[batch_size, length, len(tag2seq)]
        return emit_score

    def pad_result(self, pred, seq_len):
        for pred_tag in pred:
            if len(pred_tag) < seq_len:
                pred_tag += [0] * (seq_len - len(pred_tag))
        pred = torch.tensor(pred).to(self.config.device)
        return pred

    def forward(self, sentences, chars, tags=None):
        """
        计算loss
        sentences:[batch_size, max_len]
        chars: [batch_size, max_len, max_char_len]
        tags:[batch_size, max_len]
        """
        seq_len = sentences.size()[-1]
        mask = sentences != 1
        sentences = self.embedding(sentences)  # sentences[batch_size, max_len, embedding_dim]
        chars = self.char_embedding(chars).transpose(1, 2)  # chars: [batch_size, max_len, max_char_len, char_embedding_dim]
        chars = self.char_cnn(chars).squeeze(1)
        sentences = torch.cat((sentences, chars), -1)
        emit_score = self.encode(sentences)
        if tags is None:
            if self.config.use_crf:
                pred = self.crf.decode(emissions=emit_score, mask=mask)
                pred = self.pad_result(pred, seq_len)
            else:
                pred = emit_score.transpose(1, 2)
                pred = pred.argmax(1)
            return pred
        else:
            if self.config.use_crf:
                loss = self.crf(emissions=emit_score, tags=tags, mask=mask) * -1
            else:
                loss = torch.nn.functional.cross_entropy(emit_score.transpose(1, 2), tags)
            return loss


from matplotlib import pyplot
import numpy as np
import os
import shutil
import caffe2.python.predictor.predictor_exporter as pe

from caffe2.python import (
    brew,
    core,
    model_helper,
    net_drawer,
    optimizer,
    visualize,
    workspace,
)

# If you would like to see some really detailed initializations,
# you can change --caffe2_log_level=0 to --caffe2_log_level=-1
core.GlobalInit(['caffe2', '--caffe2_log_level=0'])
print("Necessities imported!")

# If True, a more complicated convolutional model is used
# If False, a multilayer perceptron model is used
USE_LENET_MODEL = True

# This section preps your image and test set in a lmdb database
def DownloadResource(url, path):
    '''Downloads resources from s3 by url and unzips them to the provided path'''
    import requests, zipfile, io
    print(("Downloading... {} to {}".format(url, path)))
    r = requests.get(url, stream=True)
    z = zipfile.ZipFile(io.StringIO(r.content))
    z.extractall(path)
    print("Completed download and extraction.")

current_folder = os.path.join(os.path.expanduser('~'), 'caffe2_notebooks')
data_folder = os.path.join(current_folder, 'tutorial_data', 'mnist')
root_folder = os.path.join(current_folder, 'tutorial_files', 'tutorial_mnist')
db_missing = False

if not os.path.exists(data_folder):
    os.makedirs(data_folder)
    print(("Your data folder was not found!! This was generated: {}".format(data_folder)))

# Look for existing database: lmdb
if os.path.exists(os.path.join(data_folder,"mnist-train-nchw-lmdb")):
    print("lmdb train db found!")
else:
    db_missing = True

if os.path.exists(os.path.join(data_folder,"mnist-test-nchw-lmdb")):
    print("lmdb test db found!")
else:
    db_missing = True

# attempt the download of the db if either was missing
if db_missing:
    print("one or both of the MNIST lmbd dbs not found!!")
    db_url = "http://download.caffe2.ai/databases/mnist-lmdb.zip"
    try:
        DownloadResource(db_url, data_folder)
    except Exception as ex:
        print(("Failed to download dataset. Please download it manually from {}".format(db_url)))
        print(("Unzip it and place the two database folders here: {}".format(data_folder)))
        raise ex

if os.path.exists(root_folder):
    print("Looks like you ran this before, so we need to cleanup those old files...")
    shutil.rmtree(root_folder)

os.makedirs(root_folder)
workspace.ResetWorkspace(root_folder)

print(("training data folder:" + data_folder))
print(("workspace root folder:" + root_folder))

def AddInput(model, batch_size, db, db_type):
    # load the data
    data_uint8, label = brew.db_input(
        model,
        blobs_out=["data_uint8", "label"],
        batch_size=batch_size,
        db=db,
        db_type=db_type,
    )
    # cast the data to float
    data = model.Cast(data_uint8, "data", to=core.DataType.FLOAT)
    # scale data from [0,255] down to [0,1]
    data = model.Scale(data, data, scale=float(1./256))
    # don't need the gradient for the backward pass
    data = model.StopGradient(data, data)
    return data, label

def AddMLPModel(model, data):
    size = 28 * 28 * 1
    sizes = [size, size * 2, size * 2, 10]
    layer = data
    for i in range(len(sizes) - 1):
        layer = brew.fc(model, layer, 'dense_{}'.format(i), dim_in=sizes[i], dim_out=sizes[i + 1])
        layer = model.net.Relu(layer, 'relu_{}'.format(i))
    softmax = model.net.Softmax(layer, 'softmax')
    return softmax

def AddLeNetModel(model, data):
    '''
    This part is the standard LeNet model: from data to the softmax prediction.

    For each convolutional layer we specify dim_in - number of input channels
    and dim_out - number or output channels. Also each Conv and MaxPool layer changes the
    image size. For example, kernel of size 5 reduces each side of an image by 4.

    While when we have kernel and stride sizes equal 2 in a MaxPool layer, it divides
    each side in half.
    '''
    # Image size: 28 x 28 -> 24 x 24
    conv1 = brew.conv(model, data, 'conv1', dim_in=1, dim_out=20, kernel=5)
    # Image size: 24 x 24 -> 12 x 12
    pool1 = model.net.MaxPool(conv1, 'pool1', kernel=2, stride=2)
    # Image size: 12 x 12 -> 8 x 8
    conv2 = brew.conv(model, pool1, 'conv2', dim_in=20, dim_out=50, kernel=5)
    # Image size: 8 x 8 -> 4 x 4
    pool2 = model.net.MaxPool(conv2, 'pool2', kernel=2, stride=2)
    # 50 * 4 * 4 stands for dim_out from previous layer multiplied by the image size
    fc3 = brew.fc(model, pool2, 'fc3', dim_in=50 * 4 * 4, dim_out=500)
    fc3 = model.net.Relu(fc3, 'relu3')
    pred = brew.fc(model, fc3, 'pred', 500, 10)
    softmax = model.net.Softmax(pred, 'softmax')
    return softmax

def AddModel(model, data):
    if USE_LENET_MODEL:
        return AddLeNetModel(model, data)
    else:
        return AddMLPModel(model, data)

def AddAccuracy(model, softmax, label):
    """Adds an accuracy op to the model"""
    accuracy = model.Accuracy([softmax, label], "accuracy")
    return accuracy

def AddTrainingOperators(model, softmax, label):
    """Adds training operators to the model."""
    xent = model.LabelCrossEntropy([softmax, label], 'xent')
    # compute the expected loss
    loss = model.AveragedLoss(xent, "loss")
    # track the accuracy of the model
    AddAccuracy(model, softmax, label)
    # use the average loss we just computed to add gradient operators to the model
    model.AddGradientOperators([loss])
    optimizer.build_sgd(
        model,
        base_learning_rate=0.1,
        policy="step",
        stepsize=1,
        gamma=0.999,
    )

def AddBookkeepingOperators(model):
    """This adds a few bookkeeping operators that we can inspect later.

    These operators do not affect the training procedure: they only collect
    statistics and prints them to file or to logs.
    """
    # Print basically prints out the content of the blob. to_file=1 routes the
    # printed output to a file. The file is going to be stored under
    #     root_folder/[blob name]
    model.Print('accuracy', [], to_file=1)
    model.Print('loss', [], to_file=1)
    # Summarizes the parameters. Different from Print, Summarize gives some
    # statistics of the parameter, such as mean, std, min and max.
    for param in model.params:
        model.Summarize(param, [], to_file=1)
        model.Summarize(model.param_to_grad[param], [], to_file=1)
    # Now, if we really want to be verbose, we can summarize EVERY blob
    # that the model produces; it is probably not a good idea, because that
    # is going to take time - summarization do not come for free. For this
    # demo, we will only show how to summarize the parameters and their
    # gradients.

arg_scope = {"order": "NCHW"}
train_model = model_helper.ModelHelper(name="mnist_train", arg_scope=arg_scope)
data, label = AddInput(
    train_model, batch_size=64,
    db=os.path.join(data_folder, 'mnist-train-nchw-lmdb'),
    db_type='lmdb')
softmax = AddModel(train_model, data)
AddTrainingOperators(train_model, softmax, label)
AddBookkeepingOperators(train_model)

# Testing model. We will set the batch size to 100, so that the testing
# pass is 100 iterations (10,000 images in total).
# For the testing model, we need the data input part, the main AddModel
# part, and an accuracy part. Note that init_params is set False because
# we will be using the parameters obtained from the train model.
test_model = model_helper.ModelHelper(
    name="mnist_test", arg_scope=arg_scope, init_params=False)
data, label = AddInput(
    test_model, batch_size=100,
    db=os.path.join(data_folder, 'mnist-test-nchw-lmdb'),
    db_type='lmdb')
softmax = AddModel(test_model, data)
AddAccuracy(test_model, softmax, label)

# Deployment model. We simply need the main AddModel part.
deploy_model = model_helper.ModelHelper(
    name="mnist_deploy", arg_scope=arg_scope, init_params=False)
AddModel(deploy_model, "data")
# You may wonder what happens with the param_init_net part of the deploy_model.
# No, we will not use them, since during deployment time we will not randomly
# initialize the parameters, but load the parameters from the db.

print(str(train_model.net.Proto())[:400] + '\n...')
print(str(train_model.param_init_net.Proto())[:400] + '\n...')

# The parameter initialization network only needs to be run once.
# Now all the parameter blobs are going to be initialized in the workspace.
workspace.RunNetOnce(train_model.param_init_net)

# Creating an actual network as a C++ object in memory.
# We need this as its going to be used a lot.
# So we avoid an object every single time it is used.

# overwrite=True allows you to run this cell several times and avoid errors
workspace.CreateNet(train_model.net, overwrite=True)

# Set the iterations number and track the accuracy & loss
total_iters = 200
accuracy = np.zeros(total_iters)
loss = np.zeros(total_iters)

# Now, we will manually run the network for 200 iterations.
for i in range(total_iters):
    workspace.RunNet(train_model.net)
    accuracy[i] = workspace.blobs['accuracy']
    loss[i] = workspace.blobs['loss']

# After the execution is done, let's plot the values.
pyplot.plot(loss, 'b')
pyplot.plot(accuracy, 'r')
pyplot.legend(('Loss', 'Accuracy'), loc='upper right')
pyplot.show()

# Let's look at some of the data.
pyplot.figure()
data = workspace.FetchBlob('data')
_ = visualize.NCHW.ShowMultiple(data)
pyplot.figure()
softmax = workspace.FetchBlob('softmax')
_ = pyplot.plot(softmax[0], 'ro')
pyplot.title('Prediction for the first image')
pyplot.show()

if USE_LENET_MODEL:
    pyplot.figure()
    # We look into the first conv layer output. Change this to conv2 in order to look into the second one.
    conv = workspace.FetchBlob('conv1')

    # We can look into any channel. Think of it as a feature model learned.
    # In this case we look into the 5th channel. Play with other channels to see other features
    conv = conv[:,[5],:,:]

    _ = visualize.NCHW.ShowMultiple(conv)

    pyplot.show()

# param_init_net here will only create a data reader
# Other parameters won't be re-created because we selected init_params=False before
workspace.RunNetOnce(test_model.param_init_net)
workspace.CreateNet(test_model.net, overwrite=True)
test_accuracy = np.zeros(100)
for i in range(100):
    workspace.RunNet(test_model.net.Proto().name)
    test_accuracy[i] = workspace.FetchBlob('accuracy')
# After the execution is done, let's plot the values.
pyplot.plot(test_accuracy, 'r')
pyplot.title('Acuracy over test batches.')
print('test_accuracy: %f' % test_accuracy.mean())
pyplot.show()

# construct the model to be exported
# the inputs/outputs of the model are manually specified.
pe_meta = pe.PredictorExportMeta(
    predict_net=deploy_model.net.Proto(),
    parameters=[str(b) for b in deploy_model.params],
    inputs=["data"],
    outputs=["softmax"],
)

# save the model to a file. Use minidb as the file format
pe.save_to_db("minidb", os.path.join(root_folder, "mnist_model.minidb"), pe_meta)
print("The deploy model is saved to: " + root_folder + "/mnist_model.minidb")

# we retrieve the last input data out and use it in our prediction test before we scratch the workspace
blob = workspace.FetchBlob("data")
pyplot.figure()
_ = visualize.NCHW.ShowMultiple(blob)

# reset the workspace, to make sure the model is actually loaded
workspace.ResetWorkspace(root_folder)

# verify that all blobs are destroyed.
print("The blobs in the workspace after reset: {}".format(workspace.Blobs()))

# load the predict net
predict_net = pe.prepare_prediction_net(os.path.join(root_folder, "mnist_model.minidb"), "minidb")

# verify that blobs are loaded back
print("The blobs in the workspace after loading the model: {}".format(workspace.Blobs()))

# feed the previously saved data to the loaded model
workspace.FeedBlob("data", blob)

# predict
workspace.RunNetOnce(predict_net)
softmax = workspace.FetchBlob("softmax")

# the first letter should be predicted correctly
pyplot.figure()
_ = pyplot.plot(softmax[0], 'ro')
pyplot.title('Prediction for the first image')

pyplot.show()


# imports

import os, cv2, itertools, re

import keras

from keras.utils.np_utils import to_categorical

from keras.datasets import mnist

from keras.layers import Convolution2D, Dropout

from keras.models import Sequential

from keras import layers

from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D

from keras.models import Model

import numpy as np

import pandas as pd

import seaborn as sns

import matplotlib.pyplot as plt

from sklearn.metrics import confusion_matrix

import random as rnd

from keras import backend as K

from keras.utils import np_utils

from keras.callbacks import CSVLogger

from keras.models import load_model

from keras.utils import np_utils as npu

from keras.preprocessing.image import ImageDataGenerator

from sklearn.utils import shuffle

import sklearn

from sklearn.model_selection import train_test_split

# function to return the most frequent element in a list (for good/bad predictions)

def most_frequent(listt):

    return max(set(listt), key = listt.count)

# the mnist model

def mnist_model():

    model = Sequential()

    model.add(Convolution2D(32, (3, 3), padding='same', input_shape=(28, 28, 1)))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='same'))

    model.add(Dropout(0.25))

    model.add(Convolution2D(64, (3, 3), padding='same'))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='same'))

    model.add(Dropout(0.25))

    model.add(Flatten())

    model.add(Dense(128))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(Dropout(0.25))

    model.add(Dense(10))

    model.add(Activation('softmax'))

    return model

# the cats vs dogs convolutional model

def animals_model():

    model = Sequential()

    model.add(Convolution2D(32, (3,3), padding='same', input_shape=(80, 80, 1)))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Convolution2D(64, (3,3), padding='same'))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Dropout(0.4))

    model.add(Convolution2D(128, (3,3), padding='same'))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Dropout(0.4))

    model.add(Convolution2D(256, (3,3), padding='same'))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Dropout(0.4))

    model.add(Convolution2D(512, (3,3), padding='same'))

    model.add(BatchNormalization())

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(2, 2)))

    model.add(Dropout(0.4))

    model.add(Flatten())

    model.add(Dropout(0.4))

    model.add(Dense(120))

    model.add(Activation('relu'))

    model.add(Dense(2))

    model.add(Activation('softmax'))

    return model
# setting the batch size for each epoch, number of classes (2), number of epochs

BATCH_SIZE = 64

num_classes = 2

NUM_EPOCHS = 50

# array of labels for plotting confusion matrix and badly classified images

animal_labels = ["cat", "dog"]

# paths to the train and test data

TRAIN_DIR = '../input/dogs-vs-cats-redux-kernels-edition/train/'

TEST_DIR = '../input/dogs-vs-cats-redux-kernels-edition/test/'

# data preparation

X = []

y = []

convert = lambda category : int(category == 'dog')

# importing and processing training data

def create_test_data(path):

    for p in os.listdir(path):

        if(os.path.join(path,p) != '../input/dogs-vs-cats-redux-kernels-edition/train/train'):

            category = p.split(".")[0]

            category = convert(category)

            # conversion to grayscale

            img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)

            # resize all images to 80x80 pixels

            new_img_array = cv2.resize(img_array, dsize=(80, 80))

            X.append(new_img_array)

            y.append(category)

create_test_data(TRAIN_DIR)

X = np.array(X).reshape(-1, 80,80,1)

y = np.array(y)

# normalizing image data

X = X/255.0

# validation and training split

X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=1)

# importing the test data

X_test = []

def create_test1_data(path):

    for p in os.listdir(path):

        if(os.path.join(path,p) != '../input/dogs-vs-cats-redux-kernels-edition/test/test'):

            img_array = cv2.imread(os.path.join(path,p),cv2.IMREAD_GRAYSCALE)

            new_img_array = cv2.resize(img_array, dsize=(80, 80))

            X_test.append(new_img_array)

create_test1_data(TEST_DIR)

X_test = np.array(X_test).reshape(-1,80,80,1)

X_test = X_test/255

# one hot encoding of vector labels: 0 - cat, 1- dog

y_train = to_categorical(y_train)

y_val = to_categorical(y_val)

print(y_val.shape)

# initializing conv model

animal_cnn = animals_model()

# compiling model

animal_cnn.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# imageDataGenerators for data augmentation

train_datagen = ImageDataGenerator(

    shear_range=0.2,

    zoom_range=0.2,

    horizontal_flip=True)

val_datagen = ImageDataGenerator(

    shear_range=0.2,

    zoom_range=0.2,

    horizontal_flip=True)

train_generator = train_datagen.flow(X_train, y_train, batch_size=BATCH_SIZE)

validation_generator = val_datagen.flow(X_val, y_val, batch_size=BATCH_SIZE)

# training the network

train_history = animal_cnn.fit_generator(

    train_generator,

    steps_per_epoch=X_train.shape[0] // BATCH_SIZE,

    epochs=NUM_EPOCHS,

    validation_data=validation_generator,

    verbose=0,

    validation_steps=X_val.shape[0] // BATCH_SIZE

)

# saving the network

animal_cnn.save('dogs_cats_model.h5')

# testing network performance

score = animal_cnn.evaluate(X_val, y_val, verbose=1)

print('Dogs vs Cats Evaluation Loss: ', score[0])

print('Dogs vs Cats Evaluation Accuracy: ', score[1])

# Print Model Stats

print('Training accuracy')

print(max(train_history.history['accuracy']))

print('Validation accuracy')

print(max(train_history.history['val_accuracy']))

# plotting training/validation accuracy/loss evolution

plt.figure()

plt.plot(train_history.history['accuracy'], color='C0', label='Training acc')

plt.title('Dogs vs Cats CNN Training Accuracy')

plt.ylabel('Accuracy')

plt.xlabel('Epoch')

plt.legend(loc='lower right')

plt.show()

plt.figure()

plt.plot(train_history.history['loss'], color='C0', label='Training loss')

plt.title('Dogs vs Cats CNN Training Loss')

plt.ylabel('Loss')

plt.xlabel('Epoch')

plt.legend(loc='upper right')

plt.show()

plt.figure()

plt.plot(train_history.history['val_accuracy'], color='C0', label='Validation acc')

plt.title('Dogs vs Cats CNN Validation Accuracy')

plt.ylabel('Accuracy')

plt.xlabel('Epoch')

plt.legend(loc='lower right')

plt.show()

plt.figure()

plt.plot(train_history.history['val_loss'], color='C0', label='Validation loss')

plt.title('Dogs vs Cats CNN Validation Loss')

plt.ylabel('Loss')

plt.xlabel('Epoch')

plt.legend(loc='upper right')

plt.show()

# getting predictions for the test data for the confusion matrix

y_pred = animal_cnn.predict(X_val)

y_pred = np.argmax(y_pred,axis=1)

y_true = np.asarray([np.argmax(i) for i in y_val])

print(y_pred.shape)

print(y_true.shape)

# generating confusion matrix

cm = confusion_matrix(y_true, y_pred)

print(cm)

cm_norm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

# plotting confusion matrix

sns.set(font_scale=1.5)

fig, ax = plt.subplots(figsize=(10,10))

ax = sns.heatmap(

    cm_norm, annot=True, linewidths=0, square=False, cmap='Greens',

    yticklabels=animal_labels, xticklabels=animal_labels,

    vmin=0, vmax=np.max(cm_norm), fmt='.2f',

    annot_kws={'size': 20}

)

ax.set(xlabel='Predicted Label', ylabel='Actual Label', title='Dogs vs Cats CNN Confusion Matrix')

plt.show()

# plotting predictions for the first 10 test images

for x in range(0, 10):

    original_test_image = X_test[x].reshape(1,80, 80, 1)

    prediction = animal_cnn.predict(original_test_image)

    prediction_text = ""

    pred_val = max(prediction[0])

    if prediction[0][0] == pred_val:

        prediction_text = "cat"

    else:

        prediction_text = "dog"

    plt.xticks([])

    plt.yticks([])

    plt.imshow(X_test[x, :, :, 0], cmap='gray')

    title_text = "Predicted: " + prediction_text

    pic_name = "prediction" + str(x) + ".jpg"

    plt.title(title_text, fontsize=20)

    plt.savefig(pic_name)

    plt.show()


n, m, k = map(int, input().split())

mod = 998244353
inv = pow(m, mod-2, mod)

dp = [[0]*(n+1) for _ in range(k+1)]
dp[0][0] = 1
for i in range(k):
    for j in range(n):
        for v in range(1, m+1):
            if j+v <= n:
                dp[i+1][j+v] += dp[i][j] * inv
                dp[i+1][j+v] %= mod
            else:
                over = j+v - n
                dp[i+1][n - over] += dp[i][j] * inv
                dp[i+1][n - over] %= mod
ans = 0
for i in range(k+1):
    ans += dp[i][n]
    ans %= mod
print(ans)


# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 16:54:42 2019

@author: michael.mercado
"""
import Tkinter as Tk

#create class MainGui
#esablish the size of the rootwindow

class CheckButton():
    def __init__(self, master, text):
        self.var = Tk.IntVar()
        self.text=text
        c = Tk.Checkbutton(
            master, text=text,
            variable=self.var,
            command=self.check)
        c.pack()

    def check(self):
        try:
            self.var1 = self.var.get()
            print (self.text, "is", self.var1)
            return self.var1
        except:
            raise

class StartButton():
    def __init__(self):
        pass

class MainGui(CheckB):
    def __init__(self):

        self.root = Tk.Tk()         #get the root window
        self.root.title("RT GUI")   # add a title to the root window
        self.root.geometry("800x800")
        self.root.resizable(0,0)
        self.frame = Tk.Frame(master = self.root,width=1000, height=1000, bg='blue')
        self.addCheckbutton()
        self.frame.pack()
 # this is where you put the dimension of the frame

    def addCheckbutton(self):
        self.check1 = CheckButton(self.frame, text="RandomFrequencyTest")
        self.check2 = CheckButton(self.frame, text="RandomPowerTest")
        self.check3 = CheckButton(self.frame, text="RandomFtfTest")

    def sampleProgram(self):
        print ("Running a program...")

    def RunEngine(self):

        try:
            self.check1(command = self.sampleProgram)

        except:
            pass

#initialize parameters
#create root window
#create selection buttons
#attach start button
#attach stop button

if __name__=='__main__':
    gui = MainGui()
    gui.root.mainloop()


import logging

from aiogram import Router
from aiogram.filters import Command
from aiogram.types import Message

from src.application.postman.dto import DispatchMessage
from src.application.postman.service import PostmanService
from src.application.subscribers.dto import Subscriber
from src.application.subscribers.interfaces import SubscriberRepo

logger = logging.getLogger(__name__)
router = Router()

@router.message(Command("subscribe"))
async def command_subscribe(message: Message, sub_repo: SubscriberRepo) -> None:
    sub: Subscriber | None = await sub_repo.get_by_username(message.from_user.username)

    if sub is not None:
        await message.reply("Already subscribed!")
        return

    sub = Subscriber(
        telegram_id=str(message.from_user.id), telegram_username=message.from_user.username
    )
    await sub_repo.create(sub)
    await message.reply("Subscribed!")

@router.message(Command("send"))
async def command_start_dispatch(message: Message, postman: PostmanService) -> None:
    msg = DispatchMessage(
        from_username=message.from_user.username, message=message.text
    )
    logger.info(f"Performing dispatch: {msg!r}")
    await postman.perform_dispatch(msg)


from OANDA_Historical import *
import statsmodels.formula.api as smf
#print(api.get_instruments())

SPX = OANDA_Base(symbol='SPX500_USD', start= monthsAgo(120), end= lastDay(), granularity='D', price='M', amount=10000, ftc=0.000, ptc=0.0008, verbos=True)
DAX = OANDA_Base(symbol='DE30_EUR', start= monthsAgo(120), end= lastDay(), granularity='D', price='M', amount=10000, ftc=0.000, ptc=0.0008, verbos=True)
df = pd.DataFrame()
df['SPX'] = SPX.get_data()['return']
df['DAX'] = DAX.get_data()['return']

''' plot

df.plot(subplots=True, grid=True, style='b',figsize=(8,6))
plt.show()
'''

result = smf.ols(formula="SPX ~ DAX", data=df).fit()
print(result.params)
print(result.summary())

plt.plot(df['SPX'], df['DAX'], 'r.')
ax = plt.axis()
x = np.linspace(ax[0], ax[1] +0.01)
plt.plot(x, result.params[0] + result.params[1] * x, 'b', lw=2)
plt.grid(True)
plt.axis('tight')
plt.show()

print(df.corr())

df.rolling(50).corr(pairwise=True).plot(grid=True,style='b')
plt.show()


#! /usr/bin/python

'''Convert emor.txt and inv_emor.txt into header file format so it can be
included in a C++ class'''

import re

def print_seq(file, key, vals):
    first = True
    l = ""
    i = 0
    for v in vals:
        if first:
            first = False
        else:
            l = l + ", "

        if (i % 8) == 0:
            l = l + "\n"
        i = i + 1

        l = l + str(v)

    print >>file, "const float GammaEMORBase::%s_[] = {%s};" % (key, l)

def convert(basename):
    inp = open(basename + ".txt")

    key = ""
    all_seq = {}
    cur_seq = []
    first = True;

    for line in inp:
        match = re.match(r'\s*(\S+.*?)\s*=', line)

        if (match):
            if (not first):
                all_seq[key] = cur_seq
                cur_seq = []

            else:
                first = False;

            key = match.group(1)

        else:
            line_parts = re.split(r"\s+", line)

            for p in line_parts:
                try:
                    num = float(p)
                    cur_seq.append(num)
                except:
                    pass

    all_seq[key] = cur_seq
    cur_seq = []

    outp = open("modpar_" + basename + ".h", "w")
    print >>outp, '''/*
*
* Sensor response curve data converted from '%s.txt'
*
* The EMOR model was proposed and described by  M.D. Grossberg
* and S.K. Nayar from the University of Columbia (Computer
* Vision Laboratory). For more information on EMoR please visit
*
* http://www.cs.columbia.edu/CAVE/software/softlib/dorf.php
*
*/
/// @cond''' % basename

    param_seq = []
    param_keys = {}
    dst_seq = []
    for key in all_seq.keys():
        match = re.match(r'(\S+)\((\d+)\)', key)
        if (match):
            c = match.group(1)
            n = int(match.group(2))
            s = "%s%02i" % (c,n)

            param_seq.append(s)
            param_keys[s] = key

        else:
            print_seq(outp, key, all_seq[key])

    param_seq.sort()

    for key in param_seq:
        print_seq(outp, key, all_seq[param_keys[key]])

    print >>outp, "/// @endcond"
    outp.close()
    inp.close()

convert("emor")
convert("invemor")


import math
class Node():
    def __init__(self,id):
        self.id = id
        self.parents = []
        self.children = []

    def add_child(self,node):
        self.assert_id_not_exist(node.id,self.children)
        self.children.append(node)

    def add_parent(self,node):
        #self.assert_id_not_exist(node.id,self.parents)
        if node.id not in map(lambda x:x.id,self.parents):
            self.parents.append(node)

    def assert_id_not_exist(self,id,l):
        #assert id not in map(lambda x:x.id,l)
        pass

class Graph():
    def __init__(self):
        self._id_map = {}

    def get_nodes(self):
        return list(self._id_map.values())

    def get_childern(self,id):
        return self._id_map[id].children

    def get_parents(self,id):
        return self._id_map[id].parents

    def spawn(self,list_of_edges):
        for src_id,tar_id in list_of_edges:
            self.add_edge(src_id,tar_id)

    def add_edge(self,src_id,tar_id):
        src_node = self._get_default_node(src_id)
        tar_node = self._get_default_node(tar_id)
        src_node.add_child(tar_node)
        tar_node.add_parent(src_node)

    def _get_default_node(self,nid):
        if nid not in self._id_map:
            self._id_map[nid] = Node(nid)
        return self._id_map[nid]

class PageRank():
    def __init__(self,graph,dampling_factor=0.1,eps=0.01):
        self.graph = graph
        self.dampling_factor = dampling_factor
        self.eps = 0.01
        self._rank_map = {}
        self._init()

    def _init(self):
        nodes = self.graph.get_nodes()
        n = len(nodes)
        for node in nodes:
            self._rank_map[node.id] = 1/n

    def iterate(self):
        nodes = self.graph.get_nodes()
        n = len(nodes)
        while True:
            new_rank = {}
            for node in nodes:
                rank =  self.dampling_factor/n + (1-self.dampling_factor)*\
                            sum(map(lambda node: self._rank_map[node.id]/len(node.children),node.parents))
                new_rank[node.id] = rank
            diff  = {k:self._rank_map[k]-new_rank[k] for k in self._rank_map}
            self._rank_map = new_rank
            #self.print_res()
            if self.norm(diff.values())<self.eps:
                break

    def norm(self,x):
        return sum(map(lambda t :abs(t),x))

    def print_res(self,sort=True):
        if sort:
            items = sorted(self._rank_map.items(),key=lambda x:-1*x[1])
        else:
            items = self._rank_map.items()
        print('result:')
        for k,v in items:
            print("node %s --> (%.5f)"%(str(k),v))
        print('- '*50)

class HITS():
    def __init__(self,graph,eps=0.01):
        self.eps = eps
        self.graph = graph
        self._aut_map = {}
        self._hub_map = {}
        self._init()

    def _init(self):
        for node in self.graph.get_nodes():
            #print(node.id)
            self._aut_map[node.id] = 1
            self._hub_map[node.id] = 1

    def iterate(self):
        cnt = 0
        while True:
            #print('iterate %d'%(cnt))
            #self.print_res()
            diff_norm_auth,diff_norm_hub = 0,0
            new_aut_map = {}
            new_hub_map = {}
            for node in self.graph.get_nodes():
                new_auth = sum(map(lambda node: self._hub_map[node.id],node.parents))
                new_hub =  sum(map(lambda node: self._aut_map[node.id],node.children))
                new_aut_map[node.id] = new_auth
                new_hub_map[node.id] = new_hub
                #diff_norm_auth += (new_auth-self._aut_map[node.id])**2
                #diff_norm_hub += (new_hub-self._hub_map[node.id])**2
                #self._hub_map[node.id],self._aut_map[node.id] = new_hub,new_auth
            norm_aut = self.norm(new_aut_map.values())
            norm_hub = self.norm(new_hub_map.values())

            for k,v in new_aut_map.items():
                new_aut_map[k] = new_aut_map[k]/norm_aut
                new_hub_map[k] = new_hub_map[k]/norm_hub

            for k in new_aut_map:
                diff_norm_auth = (new_aut_map[k]-self._aut_map[k])**2
                diff_norm_hub =  (new_hub_map[k]-self._hub_map[k])**2

            self._aut_map,self._hub_map = new_aut_map,new_hub_map

            cnt+=1
            if math.sqrt(diff_norm_auth)+math.sqrt(diff_norm_hub) < self.eps:
                break

    def norm(self,values,t=1):
        if t == 1:
            return sum(map(lambda x:x,values))
        return sum(map(lambda x:x*x,values))

    def rank_by_auth(self):
        for k,v in sorted(self._aut_map.items(),key=lambda x:-1*x[1]):
            self.print_node(k)

    def rank_by_hub(self):
        for k,v in sorted(self._hub_map.items(),key=lambda x:-1*x[1]):
            self.print_node(k)

    def print_res(self):
        print('result:')
        for k in sorted(self._aut_map.keys()):
            self.print_node(k)
        print('- '*50)

    def print_node(self,k):
        print("node %s --> (%.3f,%.3f)"%(str(k),self._aut_map[k],self._hub_map[k]))

class SimRank():
    def __init__(self,graph,C=0.5):
        self.graph = graph
        self.C = C
        self.sim_matrix = {}
        self._init()

    def _init(self):
        nodes = self.graph.get_nodes()
        for node1 in nodes:
            for node2 in nodes:
                if node1.id == node2.id:
                    self.sim_matrix[(node1.id,node2.id)] = 1
                else:
                    self.sim_matrix[(node1.id,node2.id)] = 0

    def iterate(self,k=100):
        nodes = self.graph.get_nodes()
        for i in range(k):
            for node1 in nodes:
                for node2 in nodes:
                    self.sim_matrix[(node1.id,node2.id)] = self._sim_func(node1,node2)

    def print_res(self):
        nodes = sorted(self.graph.get_nodes(),key=lambda x:x.id)
        print('similarity result , C = %.5f'%(self.C))
        for node1 in nodes:
            for node2 in nodes:
                if node2.id >= node1.id and self.sim_matrix[(node1.id,node2.id)]>0:
                    print('%s,%s -->%.5f'%(str(node1.id),str(node2.id),self.sim_matrix[(node1.id,node2.id)]))

    def _sim_func(self,node1,node2):
        if node1.id == node2.id:
            return 1.0
        parents1 = node1.parents
        parents2 = node2.parents
        if len(parents1)*len(parents2) == 0:
            return 0
        sim_sum = 0.0
        for p1 in parents1:
            for p2 in parents2:
                sim_sum+= self.sim_matrix[(p1.id,p2.id)]
        sim_sum= self.C*sim_sum/(len(parents1)*len(parents2))
        return sim_sum


from setuptools import setup, find_packages

with open("requirements.txt") as f:
	install_requires = f.read().strip().split("\n")

# get version from __version__ variable in bank_connector_erpnext/__init__.py
from bank_connector_erpnext import __version__ as version

setup(
	name="bank_connector_erpnext",
	version=version,
	description="ERPNext - Bank Connector",
	author="Aerele Technologies Private Limited",
	author_email="hello@aerele.in",
	packages=find_packages(),
	zip_safe=False,
	include_package_data=True,
	install_requires=install_requires
)


from collections import defaultdict
def solution(fees, records):
    answer = []
    dic = defaultdict(list)
    fee = [0] * 9999

    for record in records:
        time, num, status = record.split()
        if status == "IN":
            dic[num].append(time)
        else:
            xh, xm = dic[num][-1].split(":")
            yh, ym = time.split(":")
            dic[num].pop()
            zh = int(yh) - int(xh)
            zm = int(ym) - int(xm)
            temp = (zh * 60) + zm
            fee[int(num)] += temp

    for d in dic:
        if dic[d]:
            xh, xm = dic[d][-1].split(":")
            temp = ((23-int(xh)) * 60) + (59-int(xm))
            fee[int(d)] += temp

    for f in fee:
        if f != 0:
            if f <= fees[0]:
                answer.append(fees[1])
            else:
                if (f-fees[0]) % fees[2] == 0:
                    answer.append(fees[1] + (((f-fees[0])//fees[2]) * fees[3]))
                else:
                    answer.append(fees[1] + (((f-fees[0])//fees[2]+ 1) * fees[3]))
    return answer

print(solution([180, 5000, 10, 600],["05:34 5961 IN", "06:00 0000 IN", "06:34 0000 OUT", "07:59 5961 OUT", "07:59 0148 IN", "18:59 0000 IN", "19:09 0148 OUT", "22:59 5961 IN", "23:00 5961 OUT"]))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import sys

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None

# Weight and bias

def weight_variable(shape):
    """
    Initialize weight matrices with truncated normal distribution with standard deviation of 0.1.

    In general, shape = [filter_height, filter_width, in_channels, out_channels].
    """
    init = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(init)

def bias_variable(shape):
    """
    Initialize bias vectors with constant value of 0.1.

    In general, shape = [out_channels].
    """
    init = tf.constant(0.1, shape=shape)
    return tf.Variable(init)

# Layers

def conv2d(x, W):
    """2D convolution of x with filter W, unit stride."""
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def maxpool2d(x):
    """2x2 max pooling layer with non-overlapping kernel stride."""
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def flatten(x):
    size = 1
    for dim in x.shape.as_list()[1:]:
        size *= dim
    return tf.reshape(x, [-1, size])

def fullconn(x, W):
    return tf.matmul(x, W)

# Model

def model(x_image, x_image_shape = [28, 28]):
    # Layer 0 (2D convolution layer)
    filter_shape_0 = [10, 10]
    in_channels_0 = 1
    out_channels_0 = 32

    # Reshape input
    batch = -1
    x_0 = tf.reshape(x_image, [batch] + list(x_image_shape) + [in_channels_0])

    w_0 = weight_variable(filter_shape_0 + [in_channels_0, out_channels_0])
    b_0 = bias_variable([out_channels_0])

    z_0 = conv2d(x_0, w_0) + b_0

    x_1 = tf.nn.relu(z_0)

    # Layer 1 (Max pool 2x2)
    in_channels_1 = out_channels_0
    out_channels_1 = in_channels_1

    x_2 = maxpool2d(x_1)

    # Layer 2 (2D convolution layer)
    filter_shape_2 = [5, 5]
    in_channels_2 = out_channels_1
    out_channels_2 = 16

    w_2 = weight_variable(filter_shape_2 + [in_channels_2, out_channels_2])
    b_2 = bias_variable([out_channels_2])

    z_2 = conv2d(x_2, w_2) + b_2

    x_3 = tf.nn.relu(z_2)

    # Layer 3 (Max pool 2x2)
    in_channels_3 = out_channels_2
    out_channels_3 = in_channels_3

    x_4 = maxpool2d(x_3)

    # Layer 4 (Flatten)
    in_channels_4 = out_channels_3
    out_channels_4 = in_channels_4

    x_5 = flatten(x_4)

    # Layer 5 (Fully connected layer)
    in_channels_5 = x_5.shape.as_list()[-1]
    out_channels_5 = 1024

    w_5 = weight_variable([in_channels_5, out_channels_5])
    b_5 = bias_variable([out_channels_5])

    z_5 = fullconn(x_5, w_5) + b_5

    x_6 = tf.nn.relu(z_5)

    # Layer 6 (Fully connected layer)
    in_channels_6 = out_channels_5
    out_channels_6 = 10

    w_6 = weight_variable([in_channels_6, out_channels_6])
    b_6 = bias_variable([out_channels_6])

    z_6 = fullconn(x_6, w_6) + b_6

    return z_6

def main(_):
    # Open output files
    train_stream = open("train_accuracy.csv", "w")
    print("Epoch,Train Accuracy\n", file=train_stream)

    test_stream = open("test_accuracy.csv", "w")
    print("Epoch,Test Accuracy\n", file=test_stream)

    # Import data
    mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

    # Create the model
    x = tf.placeholder(tf.float32, [None, 784])
    y = model(x)

    # Define loss and optimizer
    y_ = tf.placeholder(tf.float32, [None, 10])

    # The raw formulation of cross-entropy,
    #
    #   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),
    #                                 reduction_indices=[1]))
    #
    # can be numerically unstable.
    #
    # So here we use tf.nn.softmax_cross_entropy_with_logits on the raw
    # outputs of 'y', and then average across the batch.

    cross_entropy = tf.reduce_mean(
            tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
    train_step = tf.train.AdagradOptimizer(1e-3).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    sess = tf.InteractiveSession()
    sess.run(tf.global_variables_initializer())

    # Train
    batch_size = 100
    epochs = 200
    batch_num = 1
    while mnist.train.epochs_completed < epochs:
        prev_nepoch = mnist.train.epochs_completed
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        if mnist.train.epochs_completed > prev_nepoch:
            train_accuracy = sess.run(accuracy, feed_dict={x: mnist.train.images, y_: mnist.train.labels})
            print("{},{}\n".format(prev_nepoch, train_accuracy), file=train_stream)
            test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
            print("{},{}\n".format(prev_nepoch, test_accuracy), file=test_stream)
            batch_num = 1
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        if batch_num % 100 == 0:
            batch_accuracy = sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys})
            print("Epoch: {0}, Batch: {1}, Accuracy: {2:.4f}".format(mnist.train.epochs_completed + 1, batch_num, batch_accuracy))
        batch_num += 1

    # Test trained model
    test_accuracy = sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})
    print("\n Test Accuracy: {0:.4f}".format(test_accuracy))

    train_stream.close()
    test_stream.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                                            help='Directory for storing input data')
    FLAGS, unparsed = parser.parse_known_args()
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)


# -*- coding: utf-8 -*-
"""
Created on Fri Dec 30 15:59:31 2016

@author: luzhangqin
"""

import matplotlib.pylab as plt
from matplotlib.font_manager import FontProperties

from sklearn.linear_model import LinearRegression

#显示中文
font = FontProperties(fname = r'/usr/share/fonts/truetype/arphic/ukai.ttc', size = 10)

def runplt():
    #创建一个用来显示图形输出的一个窗口对象
    plt.figure()
    plt.title('批萨价格与直径数据', fontproperties = font)
    plt.xlabel('直径（英寸）', fontproperties = font)
    plt.ylabel('价格（美元）', fontproperties = font)
    #[xmin, xmax, ymin, ymax]
    plt.axis([0, 25, 0, 25])
    #网格
    plt.grid(True)
    return plt

if __name__ == '__main__':
    plt = runplt()
    x = [[6], [8], [10], [14], [18]]
    y = [[7], [9], [13], [17.5], [18]]
    #测试集
    x_test = [[8], [9], [11], [16], [12]]
    y_test = [[11], [8.5], [15], [18], [11]]

    model = LinearRegression()
    model.fit(x,y)
    #R方
    r2 = model.score(x_test, y_test)
    print(r2)


print('Programa média do aluno')
UN1 = (float(input('Digite a nota da primeira unidade: ')))
UN2 = (float(input('Digite a nota da segunda unidade: ')))
UN3 = (float(input('Digite a nota da terceira unidade: ')))

if UN1 > UN2:
    if UN2 > UN3:
        menor1 = (UN2)
        menor2 = (UN3)
        melhor = (UN1)
    elif UN1 > UN3:
        menor1 = (UN2)
        menor2 = (UN3)
        melhor = (UN1)
    else:
        menor1 = (UN1)
        menor2 = (UN2)
        melhor = (UN3)
elif UN3 > UN2:
    menor1 = (UN2)
    menor2 = (UN1)
    melhor = (UN3)
elif UN3 > UN1:
    menor1 = (UN3)
    menor2 = (UN1)
    melhor = (UN2)
else:
    menor1 = (UN1)
    menor2 = (UN3)
    melhor = (UN2)

print('As menores notas deste aluno são: %.f e %.f ' %(menor1,menor2))
print('A maior nota deste aluno é %.f '%(melhor))
print()
media = (menor1 + menor2) // 2
resultado = (media + melhor) // 2

print('Media final do aluno: %.f' %(resultado))


# -*- coding: UTF-8 -*-
# 作者：hao.ren3
# 时间：2020/1/3 13:55
# IDE：PyCharm

import os

def kill_service(port):
    result = os.popen("netstat -antp | grep 0.0.0.0.0:" + str(port) + " | awk '{print $7}' | awk -F/ '{print $1}'")
    res = result.read()
    for line in res.splitlines():
        current_pid = str(line).strip()
        os.popen("kill "+current_pid)

if __name__ == '__main__':
    kill_service(5000)
    kill_service(5001)
    kill_service(5002)


import os

from .file import *
from .transform import one_hot_encode_data, merge_splits, split_data, scale_data
from .uci import download_UCI
from .torch import get_torchvision_data

def load_data(source="local", split_vars = None, merge_before_split=False, one_hot_encode=True, **kwargs):
	dataloader = select_dataloader(source)

	#using kwargs["data"] instead of data, cause data may be inside kwargs in case from=="as_param" may avoid duplication?
	data = dataloader(**kwargs)

	if split_vars is not None: data = split_vars(data)

	if merge_before_split: merge_splits(**kwargs)

	data = split_data(data, **kwargs)

	data, data_scaler = scale_data(data, **kwargs)

	if one_hot_encode: data = one_hot_encode_data(data, **kwargs)

	if data_scaler is None: return data
	return data, data_scaler

def select_dataloader(source):
	###Select data loading
	loc = source.lower()
	if loc == "uci":
		dataloader = download_UCI
	# elif kwargs["from"].lower() == "tfds":
	# 	dataloader = get_tfds_data
	elif loc == "torchvision":
		dataloader = get_torchvision_data
	elif loc == "local":
		dataloader = get_local_data
	elif loc == "as_param":
		dataloader = lambda *args, **kwargs: kwargs["data"]
	elif callable(loc):
		dataloader = loc
	else:
		raise NotImplementedError("DATA IMPORT NOT IMPLEMENTED FROM", loc)
	return dataloader

def get_local_data(name, data_folder = "../data/", loader_params = {}, **kwargs):
	filename = os.path.join(data_folder,name)
	ext = filename.split(".")[-1]
	if ext=="npz": #already a dict
		dct = load_arrays(filename, loader_params, **kwargs)
		return dct
	# elif ext in ["pkl","pickle"]: #already a dict
	# 	dct = load_pickle(filename)
	# 	return dct
	else:
		if ext=="csv":
			app = load_csv(filename, loader_params, **kwargs)
		elif ext=="npy":
			app = load_numpy(filename, loader_params, **kwargs)
		elif ext=="npz":
			app = load_npz(filename, loader_params, **kwargs)
		return {"x": app}
	raise NotImplementedError


import re
from bs4 import BeautifulSoup
import sys
sys.path.append("..")
from crawler import DBHelper,CrawlerHelper
from crawler.shop import MGStage
#https://www.prestige-av.com/goods/goods_list.php?mode=&mid=&sort=near&word=&count=100&page=135
pcookie={'age_auth':'1'}
def spider_goodlist():
    baseurl='https://www.prestige-av.com/goods/goods_list.php?mode=&mid=&sort=near&word=&count=100&page={pageindex}'
    pageindex=1
    while True:
        print(f'page:{pageindex}')
        goodlisturl=baseurl.replace('{pageindex}',str(pageindex))
        html=CrawlerHelper.get_requests(goodlisturl,cookies=pcookie).text
        bs = BeautifulSoup(html, "html.parser")
        links=bs.find_all('a',href=re.compile('https://www.prestige-av.com/goods/goods_detail.php\?sku='))

        for link in links:
            url=link['href']
            dvdid=url[55:]
            title=link.img.get_text()

            dvdidreal=dvdid
            if dvdidreal.startswith('gooe-'):
                continue
            if dvdidreal.startswith('poh-'):
                continue
            elif dvdidreal.startswith('ctkt'):
                dvdidreal = dvdidreal.replace('ctkt', '', 1)
            elif dvdidreal.startswith('tkt'):
                dvdidreal = dvdidreal.replace('tkt', '', 1)  # GOOE
            elif dvdidreal.startswith('gooe') :
                    dvdidreal = dvdidreal.replace('gooe', '', 1)
            elif dvdidreal.startswith('sha'):
                    dvdidreal = dvdidreal.replace('sha', '', 1)
            elif dvdidreal.startswith('mgs'):
                    dvdidreal = dvdidreal.replace('mgs', '', 1)
            if DBHelper.check_dvdid_exist(dvdidreal.upper()):
                #print(f'{dvdid} existed')
                pass
            else:
                print(url)
                print(f'{dvdid} not found')
                crawler_goods_detail(dvdid)

        pageindex+=1
        if len(re.findall('次へ',html))==0:
            break
def crawler_goods_detail(dvdid):
    url=f'https://www.prestige-av.com/goods/goods_detail.php?sku={dvdid}'
    html = CrawlerHelper.get_requests(url, cookies=pcookie).text
    bs = BeautifulSoup(html, "html.parser")

    code=dvdid.upper()
    if code.startswith('CTKT'):
        code=code.replace('CTKT', '', 1)
    elif code.startswith('TKT'):
        code=code.replace('TKT', '', 1)#GOOE
    elif code.startswith('GOOE'):
        code = code.replace('GOOE', '', 1)
    elif code.startswith('SHA'):
        code = code.replace('SHA', '', 1)
    cid = code
    piccode = code

    title=bs.title.get_text().split('|')[0].strip()
    bs_detail=bs.find('div',class_='product_detail_layout_01')

    has_mgslink = False
    mgslink=bs_detail.find('a', href=re.compile(f'https://www.mgstage.com/product/product_detail/'))
    if mgslink:
        MGStage.spider_moviePage(mgslink['href'])
        return

    #
収録時間：
[\s]*
(\d*)min

    length=None
    length=re.findall('
収録時間：
[\s]*
(\d*)min
',html)
    if len(length) > 0:
        length=length[0]
    rdate=None
    rdatetag=bs_detail.find('a',href=re.compile('/goods/goods_list.php\?mode=date&mid='))
    if rdatetag:
        rdate=rdatetag.get_text().strip()
    studio=None
    studiotag = bs_detail.find('a', href=re.compile('/goods/goods_list.php\?mode=maker&mid='))
    if studiotag:
        studio = studiotag.get_text().strip()
    label = None
    labeltag = bs_detail.find('a', href=re.compile('/goods/goods_list.php\?mode=label&mid='))
    if labeltag:
        label = labeltag.get_text().strip()
    series = None
    seriestag = bs_detail.find('a', href=re.compile('/goods/goods_list.php\?mode=series&mid='))
    if seriestag:
        series = seriestag.get_text().strip()
    if series == '写真集':
        return
    actslist = []
    actstag=bs_detail.find_all('a',href=re.compile('/goods/goods_list.php\?mode=actress&mid='))
    for acttag in actstag:

        actslist.append(acttag.get_text().strip().replace(' ',''))
    genrelist = []
    genrestag = bs_detail.find_all('a', href=re.compile('/goods/goods_list.php\?mode=genre&mid='))
    for genretag in genrestag:
        genrename=genretag.get_text().strip()
        if genrename=='グッズ':
            return
        genrelist.append(genretag.get_text().strip())
    director=None
    piccount=len(bs.find_all('img', alt=title))
    print(f'has_mgslink:{has_mgslink}')
    print(f"cid:{cid}")
    print(f'code:{code}')
    print(f'title:{title}')
    print(f'length:{length}')
    print(f'rdate:{rdate}')
    print(f'director:{director}')
    print(f'studio:{studio}')
    print(f'label:{label}')
    print(f'series:{series}')
    print(f'pic:{piccode} count:{piccount}')
    print(actslist)
    print(genrelist)

    DBHelper.save_movie(code=code, cid=cid, title=title, length=length, rdate=rdate,
                        director=director, studio=studio, label=label, series=series,
                        piccode=piccode, piccount=piccount, source=1001,
                        actresslist=actslist, genrelist=genrelist)

if __name__ == '__main__':
    #print(len('https://www.prestige-av.com/goods/goods_detail.php?sku='))
    spider_goodlist()


from flask_restful import Resource, abort

from app.db import db, Contract, Proposal, Challenge
from app.comm.decorators import with_poll_contract
from app.util.reqargs import with_args, Argument
from app.util.types import address
from app.util.abi_data import create_params_data
from app.util.eth_call import (
    get_community_token_address,
    get_community_token_address,
    eth_call,
)
from eth_utils import to_hex, to_bytes
from eth_abi import decode_single

from decimal import Decimal

class VotingPower(Resource):
    path = "/voting/<addr>/<int:on_chain_id>/voting-power/<voter>"

    @with_poll_contract(addr="addr")
    def get(self, addr, on_chain_id, voter, poll_contract):
        voting_snapshot = 0
        contract = (
            db.session.query(Contract)
            .filter_by(address=poll_contract.address)
            .one_or_none()
        )

        if contract.contract_type == "TCR":
            challenge = db.session.query(Challenge).filter_by(
                tcr_address=poll_contract.address, challenge_id=on_chain_id
            ).one_or_none() or abort(400, message=f"Challenge not found")
            voting_snapshot = challenge.token_snap_shot
            token_address = get_community_token_address(poll_contract.address)
        elif contract.contract_type == "PARAMETER":
            proposal = db.session.query(Proposal).filter_by(
                parameter_address=poll_contract.address, proposal_id=on_chain_id
            ).one_or_none() or abort(400, message=f"Challenge not found")
            voting_snapshot = proposal.token_snap_shot
            token_address = get_community_token_address(addr)
        else:
            abort(400)

        voting_power = Decimal(
            decode_single(
                "uint256",
                to_bytes(
                    hexstr=eth_call(
                        token_address,
                        "historicalVotingPowerAtNonce(address,uint256)",
                        to_hex(
                            create_params_data(
                                ("address", voter), ("uint256", voting_snapshot)
                            )
                        ),
                    )
                ),
            )
        )
        return {
            "result": {
                "votingPower": voting_power,
                "votingSnapShot": voting_snapshot,
            }
        }


import messagebird
import sqlite3
import os

def fetch_contacts(conn):
    cursor = conn.cursor()
    cursor.execute(
        "SELECT c.phone FROM contacts as c WHERE c.phone LIKE '57%' AND  c.city LIKE 'Bogota' AND c.sent IS FALSE LIMIT 10")
    # results = [phone.split('57')[-1] for (phone,) in cursor.fetchall()]
    results = [phone for (phone,) in cursor.fetchall()]
    cursor.close()
    return results

def send_sms(conn, client, phone):
    try:
        client.message_create(
            'MessageBird',
            '+' + phone,
            os.getenv('MESSAGE_BODY')
        )

        cursor = conn.cursor()
        cursor.execute(
            "UPDATE contacts SET sent = TRUE WHERE phone like ?", (phone,))
        conn.commit()
        print('sms sent')
    except messagebird.client.ErrorException as e:
        print(e)
        print('Error sending the sms')

if __name__ == '__main__':
    conn = sqlite3.connect('contacts.db', timeout=10)
    contacts = fetch_contacts(conn)
    key = os.getenv('MESSAGEBIRD_ACCESS_KEY')
    client = messagebird.Client(key)
    for contact in contacts:
        print(contact)
        send_sms(conn, client, contact)