#!/usr/bin/python3
# -*- coding: utf-8 -*-
# original code from https://github.com/hablijack  coverted and adapted to a rhasspy friendly environment by Gido Carper
# Gido also added 100 Cities with lantitude and longtitudes to be able to request gasoline prices in other cities

import requests, os, json, random

class Jokes:

    def __init__(self, language):
        self.language = language
        return

    def tell_joke(self):
        random_joke = random.randint(0, 4)

        # Joke of the day Free https://jokes.one/api/joke/#python
        # you can only ask for 10 jokes per hours in the first joke api (which contains 3 different categories)
        # you can get a 10$/month authentication key though
        if random_joke == 2:
            joke_url = 'https://api.jokes.one/jod?category=animal'
            joke = self.get_jokes(joke_url)
            try:
                return joke["contents"]["jokes"][0]["joke"]["text"]
            except Exception as ex:
                random_joke = random.randint(0, 1)

        if random_joke == 3:
            joke_url = 'https://api.jokes.one/jod?category=blonde'
            joke = self.get_jokes(joke_url)
            try:
                return joke["contents"]["jokes"][0]["joke"]["text"]
            except Exception as ex:
                random_joke = random.randint(0, 1)

        if random_joke == 4:
            joke_url = 'https://api.jokes.one/jod?category=knock-knock'
            joke = self.get_jokes(joke_url)
            try:
                return joke["contents"]["jokes"][0]["joke"]["text"]
            except Exception as ex:
                random_joke = random.randint(0, 1)

        if random_joke == 0:
            joke_url = 'https://api.chucknorris.io/jokes/random'
            joke = self.get_jokes(joke_url)

            if joke['value']:
                return joke['value']

        if random_joke == 1:
            joke_url = 'https://official-joke-api.appspot.com/random_joke'
            joke = self.get_jokes(joke_url)

            if joke["setup"]:
                print(joke["setup"] + '. ' + joke["punchline"])
                return joke["setup"] + '. ' + joke["punchline"]

        return self.language['noInternet']

    def get_jokes(self, joke_url):
        try:
            r = requests.get(joke_url)
            json_obj = json.loads(r.content.decode('utf-8'))
            return json_obj
        except (requests.exceptions.ConnectionError, ValueError):
            return self.language['noInternet']


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

"""
Replace invalid characters from a filename
"""

import os
import argparse
from pathlib import Path
from utils import common

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("input", type=Path, help="Path to directory or single file")
    args = parser.parse_args()

    # Sanity check
    if args.input is None:
        common.abort(parser.format_help())

    # If path is a directory, get a list of files
    files = common.list_directory(args.input.resolve(), None, True)

    for f in files:
        a = str(f).encode('utf-8', "ignore")
        os.rename(str(f), a)


from cmath import isnan
import boto3
from flask import Flask, jsonify

app = Flask(__name__)

@app.route('/ec2')
# ‘/’ URL is bound with hello_world() function.
def hello_world():

    ec2client = boto3.client(
        'ec2',
        aws_access_key_id='<access-key>',
        aws_secret_access_key='<secret-key>',
        region_name='us-west-2'
    )

    ec2detailsDict=dict()

    response = ec2client.describe_instances()

    for reservation in response["Reservations"]:
        for instance in reservation["Instances"]:
            print(instance)
            ec2detailsList=list()
            ec2detailsList.append(instance["InstanceId"])
            ec2detailsList.append(instance["PrivateIpAddress"])
            ec2detailsList.append(instance["Tags"])
            ec2detailsDict[instance["InstanceId"]]=[]
            ec2detailsDict[instance["InstanceId"]].extend(ec2detailsList)
    return jsonify(ec2detailsDict)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)


"""users package custom form validators"""
from flask_login import current_user
from wtforms import ValidationError
from models.account import Account

def unique_or_current_user_field(message=None):
    """Validates that email field is either equal to the user's current field
    or doesn't exist in the database
    """

    def validation(form, field):
        kwargs = {field.name: field.data}
        if (
                hasattr(current_user, field.name)
                and getattr(current_user, field.name) == field.data
        ):
            return
        if Account.objects(**kwargs).first():
            raise ValidationError(message)

    return validation


import torch
from torch import nn as nn
from torch.nn import functional as F

from basicsr.utils.registry import ARCH_REGISTRY
from .arch_util import ResidualBlockNoBN, make_layer
from .tmpalign_util import TMPAlign

@ARCH_REGISTRY.register()
class TMP(nn.Module):

    def __init__(self,
                 num_in_ch=3,
                 num_out_ch=3,
                 num_feat=64,
                 num_frame=5,
                 num_extract_block=5,
                 num_reconstruct_block=10,
                 center_frame_idx=None,
                 hr_in=False):

        super().__init__()
        if center_frame_idx is None:
            self.center_frame_idx = num_frame // 2
        else:
            self.center_frame_idx = center_frame_idx

        self.hr_in = hr_in

        # extract features for each frame
        self.conv_first = nn.Conv2d(num_in_ch, num_feat, 3, padding=1)
        self.feature_extraction = make_layer(ResidualBlockNoBN, num_extract_block, num_feat=num_feat)

        # align
        self.align = TMPAlign(num_feat=num_feat)

        # upsample
        self.upconv1 = nn.Conv2d(num_feat, 48, 3, 1, 1)
        self.pixel_shuffle = nn.PixelShuffle(4)

        # activation function
        self.lrelu = nn.LeakyReLU(negative_slope=0.1, inplace=True)

    def forward(self, x, hidden_states=None, return_hs=False):
        b, t, c, h, w = x.size()
        if self.hr_in:
            assert h % 16 == 0 and w % 16 == 0, ('The height and width must be multiple of 16.')
        else:
            assert h % 4 == 0 and w % 4 == 0, ('The height and width must be multiple of 4.')

        # extract features for each frame
        feat_origin = self.lrelu(self.conv_first(x.view(-1, c, h, w)))
        feat_l1 = self.feature_extraction(feat_origin)

        # align
        feat, hidden_states = self.align(feat_l1.view(b, t, -1, h, w), x, hidden_states)
        feat = feat.view(b*t, -1, h, w)

        # upsample
        out = feat
        out = self.pixel_shuffle(self.upconv1(out)).view(b, t, c, 4*h, 4*w)
        if self.hr_in:
            base = x
        else:
            base = F.interpolate(x.view(-1, c, h, w), scale_factor=4, mode='bilinear', align_corners=False).view(b, t, c, 4*h, 4*w)
        out += base

        if return_hs is True:
            return out, hidden_states
        else:
            return out


#!/usr/bin/env python3
import argparse

def get_args():
    parser = argparse.ArgumentParser(usage="%(prog)s\n\t./106bombyx n [k | i0 i1]")
    parser.add_argument("n", type=int, help="number of the first genration individuals")
    parser.add_argument("k", type=float, help="growth rate 1 to 4")
    parser.add_argument("i0", type=int, help="initial generation (included)")
    parser.add_argument("i1", type=int, help="final generation (included)")

    try:
        args = parser.parse_args(None, None)
    except SystemExit:
        exit(84)
    return args

def logistic_increment(x_prev, k):
    return k * x_prev * (1000 - x_prev) / 1000

def population(n, k, i0, i1):
    x1 = n
    x_next = x1
    res = []
    res.append([1, k, x1])

    for i in range(1, i1):
        x_next = logistic_increment(x_next, k)
        res.append([i + 1, k, x_next])
    return res[i0:i1 + 1]

def test_k(n, k, i0, i1):
    res = []
    while(k <= 4):
        res += population(n, k, i0, i1)
        k += 0.01
    return res

def with_rate(n, k):
    res = population(n, k, 0, 100)
    for elt in res:
        print(elt[0], elt[2])
    return

def with_borne(n, i0, i1):
    res = test_k(n, 1, i0, i1)
    for elt in res:
        print(elt[1], elt[2])
    return

args = get_args()
if (len(args) == 2):
    print("3")
if (len(args) == 3):
    print("4")

with_rate(10, 3.3)
# with_borne(10, 10000, 10010)


import pandas as pd
from datetime import datetime, timedelta
from main.constants import *
from main.model.naive_hybrid_baseline_als_model import Model as NHBAModel

DEFAULT_TIME_RANGE = 7
# tuned from [1,3,7,30] on 11 users (min_rating >= 500)

class Model:
	"""
	state:
		self.user
		self.name
		self.data
		self.<hyperparameter_name> ...
	"""

	def __init__(self, user_id, model_name, data_reviews):
		"""
		user_id:
			this model is for a specific user

		model_name:
			give this model a name

		data_reviews:
			pandas dataframe where each row is review
		"""
		self.user = user_id
		self.name = model_name
		self.data = data_reviews

		self.latest_rating_range = timedelta(days = DEFAULT_TIME_RANGE)

		last_valid_time = data_reviews[data_reviews[COL_USER] == user_id] \
					.sort_values(COL_TIMESTAMP, ascending=False) \
					.iloc[0][COL_TIMESTAMP] - self.latest_rating_range.total_seconds()

		df = data_reviews[data_reviews[COL_TIMESTAMP] >= last_valid_time]

		self.model = NHBAModel(
			user_id=self.user,
			model_name=f"{self.name}_nhba",
			data_reviews=df
			)

	def close(self):
		"""
		do something when close this model
		"""
		self.model.close()

	def train(self):
		"""
		train on hyperparmaters
		"""
		self.model.train()

	def predict(self, k=10, removeSeen=True):
		"""
		predict top 10 restaurants on user

		if k <= 0, return all predictions
		"""
		if not removeSeen:
			return self.model.predict(k=k, removeSeen=removeSeen)

		naive_pred = self.model.predict(k=0, removeSeen=removeSeen)

		user_item_columns = [COL_USER, COL_ITEM]
		pred = naive_pred.loc[
					~naive_pred.set_index(user_item_columns).index.isin(
						self.data.set_index(user_item_columns).index
					)
				]

		if k <= 0:
			return pred
		else:
			return pred.head(k)

	def save_model(self, output_dir):
		"""
		save this model under output_dir with self.<model_name>_<current_time>
		"""
		pass


from collections import deque
import sys
sys.stdin=open("input.txt")

def cal(num, k):
    if k==0:
        return num+1
    elif k==1:
        return num-1
    elif k==2:
        return num*2
    elif k==3:
        return num-10

def bfs():

    while queue:
        s,cnt=queue.popleft()
        for k in range(4):
            next=cal(s,k)
            if next==m:
                return cnt+1
            if 1<=next<=1000000 and not visited[next]:
                queue.append((next,cnt+1))
                visited[next]=1

for t in range(int(input())):
    n,m=map(int,input().split())
    queue=deque()
    visited=[0]*1000001
    cnt=0

    queue.append((n,0))
    visited[n]=1

    print("#{} {}".format(t+1,bfs()))

Python/SW Expert Academy/Programming Advanced/Graph/5247. 연산.py


from inputFiles import file_path as fp
from fastapi import APIRouter

# APIRouter creates path operations for item module
router = APIRouter(
    prefix="/AdventOfCode",
    tags=["Day 5"],
    responses={404: {"description": "Not found"}},
)

file = open(fp.file_path + 'day_05.txt', "r")
parts = file.read()[:-1].split('\n\n')

cratesStack = parts[0].split('\n')
moves = parts[1].split('\n')

# prepare stacks
numberOfStacks = int(cratesStack[len(cratesStack) - 1][-2])
maxHeightOfStack = len(cratesStack) - 1
stacks = [[] for _ in range(numberOfStacks)]
for i in range(maxHeightOfStack):
    line = cratesStack[i]
    crates = line[1::4]
    for s in range(len(crates)):
        if crates[s] != " ":
            stacks[s].append(crates[s])
stacks = [stack[::-1] for stack in stacks]

@router.get("/day5/part1")
async def Solve_Part_One():
    return [
        {"result": solvePart1()}
    ]

@router.get("/day5/part2")
async def Solve_Part_Two():
    return [
        {"result": solvePart2()}
    ]

def solvePart1():
    for move in moves:
        moveSplit = move.split(" ")
        number = int(moveSplit[1])
        stackFrom = int(moveSplit[3])
        stackTo = int(moveSplit[5])

        for n in range(number):
            elem = stacks[stackFrom - 1].pop()
            stacks[stackTo - 1].append(elem)
    res = [stack[-1] for stack in stacks]
    result = ""
    for stack in stacks:
        result += stack[-1]
    return result

def solvePart2():
    for move in moves:
        moveSplit = move.split(" ")
        number = int(moveSplit[1])
        stackFrom = int(moveSplit[3])
        stackTo = int(moveSplit[5])
        temp = []
        for n in range(number):
            temp.append(stacks[stackFrom - 1].pop())
        for x in temp[::-1]:
            stacks[stackTo - 1].append(x)
    result = ""
    for stack in stacks:
        result += stack[-1]

    return result


# ----------------------------------------------------------
# Lab #5: Cryptarithmetic with CSP
# General cryptarithmetic puzzle solver.
#
# Date: 13-Oct-2023
# Authors:
#           A01747327 Jorge Rea
#           A01753911 Oswaldo Hernández
# ----------------------------------------------------------

from csp import Constraint, CSP
from typing import Dict, List, Optional

class CryptarithmeticConstraint(Constraint[str, int]):
    def __init__(self, unique_letters: List[str], words: List[str], answer: str, max_word_length: int) -> None:
        super().__init__(unique_letters)
        self.unique_letters: List[str] = unique_letters
        self.words: List[str] = words
        self.answer: str = answer
        self.max_word_length: int = max_word_length

    def satisfied(self, assignment: Dict[str, int]) -> bool:
        # Check for duplicate assignments
        if len(set(assignment.values())) < len(assignment):
            return False

        if len(assignment) != len(self.unique_letters):
            return True

        total_word_sum = 0
        for i in range(self.max_word_length):
            for word in self.words:
                if i < len(word):
                    index = len(word) - 1 - i
                    total_word_sum += assignment[word[index]] * 10 ** i

        total_answer_sum = 0
        for i in range(len(self.answer)):
            index = len(self.answer) - 1 - i
            total_answer_sum += assignment[self.answer[index]] * 10 ** i

        return total_word_sum == total_answer_sum

def solve_cryptarithmetic_puzzle(addends: List[str], answer: str) -> Optional[Dict[str, int]]:
    unique_letters = list(set("".join(addends + [answer])))
    unique_letters.sort()

    possible_digits = {letter: list(range(10)) for letter in unique_letters}

    csp = CSP(unique_letters, possible_digits)
    csp.add_constraint(CryptarithmeticConstraint(
        unique_letters, addends, answer, max(map(len, addends))))

    solution = csp.backtracking_search()

    if solution is None:
        return None
    else:
        upper_solution = {key.upper(): value for key,
                          value in solution.items()}
        return upper_solution

if __name__ == "__main__":
    print(solve_cryptarithmetic_puzzle(['SEND', 'MORE'], 'MONEY'))


from openerp.osv import fields, osv
from openerp.tools.translate import _
import time

import logging

_logger = logging.getLogger(__name__)

class grp_set_def_cur_rate_type(osv.osv):
    _inherit = "res.currency.rate"

    _columns = {
        'rate_presupuesto': fields.float('Tipo cambio presupuesto', digits=(12, 6), help='Tipo de cambio para enviar al SIIF'),
        'rate_arbitraje': fields.float('Arbitraje', digits=(12, 6), help='Tipo de cambio arbitraje'), #001 Arbitraje
    }

    _defaults = {
        'rate_presupuesto': 1,
        'rate_arbitraje': 1,
    }

grp_set_def_cur_rate_type()

class grp_calcular_arbitraje(osv.osv):
    _inherit = "res.currency"

    def _current_rate_presupuesto(self, cr, uid, ids, name, arg, context=None):
        raise_on_no_rate= False
        if context is None:
            context = {}
        res = {}

        if 'date' in context:
            date = context.get('date')
        else:
            date = time.strftime('%Y-%m-%d')
        date = date or time.strftime('%Y-%m-%d')

        for id in ids:
            cr.execute('SELECT rate_presupuesto FROM res_currency_rate '
                       'WHERE currency_id = %s '
                         'AND name::date <= %s '
                       'ORDER BY name desc LIMIT 1',
                       (id, date))
            if cr.rowcount:
                res[id] = cr.fetchone()[0]
            elif not raise_on_no_rate:
                res[id] = 0
            else:
                currency = self.browse(cr, uid, id, context=context)
                raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
        return res

    #001 Arbitraje
    def _current_rate_arbitraje(self, cr, uid, ids, name, arg, context=None):

        raise_on_no_rate= False
        if context is None:
            context = {}
        res = {}

        if 'date' in context:
            date = context.get('date')
        else:
            date = time.strftime('%Y-%m-%d')
        date = date or time.strftime('%Y-%m-%d')

        for id in ids:
            cr.execute('SELECT rate_arbitraje FROM res_currency_rate '
                       'WHERE currency_id = %s '
                         'AND name::date <= %s '
                       'ORDER BY name desc LIMIT 1',
                       (id, date))
            if cr.rowcount:
                res[id] = cr.fetchone()[0]
            elif not raise_on_no_rate:
                res[id] = 0
            else:
                currency = self.browse(cr, uid, id, context=context)
                raise osv.except_osv(_('Error!'),_("No currency rate associated for currency %d for the given period" % (id)))
        return res
    #001 Fin arbitraje

    def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
        if context is None:
            context = {}
        ctx = context.copy()
        from_currency = self.browse(cr, uid, from_currency.id, context=ctx)
        to_currency = self.browse(cr, uid, to_currency.id, context=ctx)

        pricelist_type = context.get('pricelist_type', False) or 'sale'  # pricelist_type default to 'sale' and use buying rate
        to_currency_rate = 0.0
        from_currency_rate = 0.0
        # kittiu: Buying rate
        if pricelist_type == 'sale':
            if from_currency.rate == 0 or to_currency.rate == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _('No buying rate found \n' \
                        'for the currency: %s \n' \
                        'at the date: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate
            from_currency_rate = from_currency.rate
        # kittiu: Selling rate
        if pricelist_type == 'purchase':
            if from_currency.rate_sell == 0 or to_currency.rate_sell == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _('No selling rate found \n' \
                        'for the currency: %s \n' \
                        'at the date: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_sell
            from_currency_rate = from_currency.rate_sell
        if pricelist_type == 'presupuesto':
            if from_currency.rate_presupuesto == 0 or to_currency.rate_presupuesto == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _(u'No se encontró tipo de cambio de presupuesto '
                                                   u'para la moneda: %s '
                                                   u'en la fecha: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_presupuesto
            from_currency_rate = from_currency.rate_presupuesto
        if pricelist_type == 'arbitraje':
            if from_currency.rate_arbitraje == 0 or to_currency.rate_arbitraje == 0:
                date = context.get('date', time.strftime('%Y-%m-%d'))
                if from_currency.rate == 0:
                    currency_symbol = from_currency.symbol
                else:
                    currency_symbol = to_currency.symbol
                raise osv.except_osv(_('Error'), _(u'No se encontró tipo de cambio de arbitraje '
                                                   u'para la moneda: %s '
                                                   u'en la fecha: %s') % (currency_symbol, date))
            to_currency_rate = to_currency.rate_arbitraje
            from_currency_rate = from_currency.rate_arbitraje
        # kittiu: check Smaller/Bigger currency
        to_rate = to_currency.type_ref_base == 'bigger' and (1 / to_currency_rate) or to_currency_rate
        from_rate = from_currency.type_ref_base == 'bigger' and (1 / from_currency_rate) or from_currency_rate
        return to_rate / from_rate

    _columns = {
        'rate_presupuesto': fields.function(_current_rate_presupuesto, string='Tipo cambio presupuesto', digits=(12, 6),
            help='El tipo de cambio para presupuesto.'),
        'rate_arbitraje': fields.function(_current_rate_arbitraje, string='Arbitraje', digits=(12, 6),
            help='El tipo de cambio arbitraje.'), #001 Arbitraje
    }
grp_calcular_arbitraje()


from functools import reduce

# declaracio de funcions
def comptar(l):
   p = {}
   for x in l:
      p.setdefault(x, 0)
      p[x] += 1
   return p

def comptar2(l, k):
   p = {}
   for i in range(len(l)):
      p.setdefault(k[i], {})
      p[k[i]].setdefault(l[i], 0)
      p[k[i]][l[i]] += 1
   return p

def Pxik(atr, N, k):
   if atr in N[k]:
      return N[k][atr] / Nk[k]
   else:
      return Nk[k] / n ** 2

def classify(t):
   l = [(k , Nk[k] / n *
        reduce(lambda x, y: x * y,
               map(Pxik, t, Nxik,
                   [k for a in range(len(t))])))
        for k in Nk.keys()]
   return max(l, key=lambda x: x[1])[0]

# carrega de l'arxiu
l = list(map(lambda l: (l.strip()).split(','),
             open('mushroom.data.txt', 'r').readlines()))

# construccio del training: 2 de cada 3
train = list(map(lambda x: x[1],
                 filter(lambda v: v[0] % 3 != 0, enumerate(l))))
n = len(train)

# construccio del test: 1 de cada 3
test = list(map(lambda x: x[1],
                filter(lambda v: v[0] % 3 == 0, enumerate(l))))

# transposta del training
m = list(zip(*train))

# Numerador de P(k)
Nk = comptar(m[0])

# Numerador de P(xi|k)
Nxik = [ comptar2 (m[ i ] , m[ 0 ] ) for i in range (1 , len (m) ) ]

# Classificacio
classes = list(map(lambda x: x.pop(0), test))
prediccions = list(map(classify, test))

# Nombre de correctes
print('Prec.:', len(list(filter(lambda x: x[0] == x[1],
                                zip(*[prediccions, classes]))))
                / len(test) * 100, '%')


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QRadioButton, QPushButton, QButtonGroup, QGridLayout
from PyQt5.QtCore import Qt

class MyWindow(QWidget):
    def __init__(self):
        super().__init__()

    #     # Création des radio boutons
    #     self.radio1 = QRadioButton("Radio 1", self)
    #     self.radio2 = QRadioButton("Radio 2", self)
    #     self.radio3 = QRadioButton("Radio 3", self)

    #     # Création du bouton poussoir
    #     self.pushButton = QPushButton("Appuyer", self)

    #     # Ajout des radio boutons à un groupe
    #     self.group = QButtonGroup(self)
    #     self.group.addButton(self.radio1)
    #     self.group.addButton(self.radio2)
    #     self.group.addButton(self.radio3)

    #     # Connexion du signal toggled()
    #     self.radio1.toggled.connect(self.on_radio1_toggled)

    #     # Disposition des widgets
    #     layout = QGridLayout(self)
    #     layout.addWidget(self.radio1, 0, 0)
    #     layout.addWidget(self.radio2, 1, 0)
    #     layout.addWidget(self.radio3, 2, 0)

    #     # Masquage du bouton poussoir
    #     self.pushButton.hide()

    #     # Ajout du bouton poussoir à droite
    #     layout.addWidget(self.pushButton, 3, 0, alignment=Qt.AlignRight)

    #     # Définir la largeur de la première colonne à 1
    #     layout.setColumnStretch(0, 1)

    #     self.setLayout(layout)

    # def on_radio1_toggled(self):
    #     # Si le premier bouton est sélectionné, le bouton poussoir apparaît
    #     if self.radio1.isChecked():
    #         self.pushButton.show()
    #     # Sinon, le bouton poussoir disparaît
    #     else:
    #         self.pushButton.hide()

    # Création des boutons radio
        self.radio1 = QRadioButton("Substract by gradient", self)
        self.radio2 = QRadioButton("Simple Threshold", self)

        self.pushButton = QPushButton("Import image...", self)

        self.group = QButtonGroup(self)
        self.group.addButton(self.radio1)
        self.group.addButton(self.radio2)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())


import re ,time ,requests
from pagermaid.listener import listener
from pagermaid.utils import alias_command ,obtain_message
#此版本是修改版，原版作者我也不知道是谁
def convert_time_to_str(time):
    #时间数字转化成字符串，不够10的前面补个0
    if (time < 10):
        time = '0' + str(time)
    else:
        time=str(time)
    return time
def sec_to_data(y):

    h=int(y//3600 % 24)
    d = int(y // 86400)
    h=convert_time_to_str(h)
    d=convert_time_to_str(d)
    return d + "天" + h+'小时'
def StrOfSize(size):
    def strofsize(integer, remainder, level):
        if integer >= 1024:
            remainder = integer % 1024
            integer //= 1024
            level += 1
            return strofsize(integer, remainder, level)
        elif integer < 0:
            integer = 0
            return strofsize(integer, remainder, level)
        else:
            return integer, remainder, level

    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    integer, remainder, level = strofsize(size, 0, 0)
    if level+1 > len(units):
        level = -1
    return ( '{}.{:>03d} {}'.format(integer, remainder, units[level]) )
@listener(is_plugin=True, outgoing=True, command=alias_command("subinfo"),
          description='识别订阅链接并获取信息\n使用方法：使用该命令发送或回复一段带有一条或多条订阅链接的文本',parameters='<url>')
async def subinfo(context):
    headers = {
'User-Agent': 'ClashforWindows/0.18.1'
}
    try:
        message_raw = await obtain_message(context)
        await context.edit('信息获取中')
        final_output=''
        url_list=re.findall("https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]",message_raw)#使用正则表达式查找订阅链接并创建列表
        for url in url_list:
            try:
                res=requests.get(url,headers=headers,timeout=5)#设置5秒超时防止卡死
            except:
                final_output=final_output+'连接错误'+'\n\n'
                continue
            if res.status_code == 200:
                try:
                    info = res.headers['subscription-userinfo']
                    info_num = re.findall('\d+',info)
                    time_now=int(time.time())
                    output_text_head='订阅链接：'+url+'\n已用上行：`'+StrOfSize(int(info_num[0]))+'`\n已用下行：`'+StrOfSize(int(info_num[1]))+ '`\n剩余：`'+StrOfSize(int(info_num[2])-int(info_num[1])-int(info_num[0]))+'`\n总共：`'+StrOfSize(int(info_num[2]))
                    if len(info_num) == 4:
                        timeArray = time.localtime(int(info_num[3])+28800)
                        dateTime = time.strftime("%Y-%m-%d", timeArray)
                        if time_now <= int(info_num[3]):
                            lasttime=int(info_num[3])-time_now
                            output_text=output_text_head+'`\n此订阅将于`'+dateTime+'`过期'+'，剩余`'+sec_to_data(lasttime)+'`'
                        elif time_now > int(info_num[3]):
                            output_text=output_text_head+'`\n此订阅已于`'+dateTime+'`过期！'
                    else:
                        output_text=output_text_head+'`\n到期时间：`没有说明捏`'
                except:
                    output_text='无流量信息捏'
            else:
                output_text='无法访问'
            final_output=final_output+output_text+'\n\n'
        await context.edit(final_output)
    except:
        await context.edit('参数错误')


import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

A = [
 [0.5, 0.5, 0],
 [0.5, 0.25, 0.5],
 [0, 0.25, 0.5]
]

B = [[0], [0], [0]]
C = [0.8, 0.2, 0.2]
D = 0

# condizione iniziale (distribuzione di probabilità di un dato evento)
x0 = [1, 0, 0] # evento certo soleggiato

# modello a tempo discreto
previsioni = signal.dlti(A, B, C, D)

# tempi
t0 = 0
tf = 31
incr = 1 # anno
t = np.arange(t0, tf, incr, dtype=int)

# ingressi
u = np.zeros((len(t), 1)) # il sistema resta isolato anche con u != 0

# simulazione
_, y, x = signal.dlsim(previsioni, u, t, x0)

# graphs
## soleggiato
plt.subplot(3, 1, 1)
plt.stem(t, y[:,0])
plt.grid(True)
plt.title('Soleggiato')

## nuvoloso
plt.subplot(3, 1, 2)
plt.stem(t, x[:,1])
plt.grid(True)
plt.title('Nuvoloso')

## piovoso
plt.subplot(3, 1, 3)
plt.stem(t, x[:,2])
plt.grid(True)
plt.title('Piovoso')


import numpy as np
import scipy.io as sio
import torch
from sklearn import preprocessing

def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Linear') != -1:
        m.weight.data.normal_(0.0, 0.02)
        m.bias.data.fill_(0)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

def map_label(label, classes):
    mapped_label = torch.LongTensor(label.size())
    for i in range(classes.size(0)):
        mapped_label[label==classes[i]] = i
    return mapped_label
class Logger(object):
    def __init__(self, filename):
        self.filename = filename
        f = open(self.filename+'.log', "a")
        f.close()

    def write(self, message):
        f = open(self.filename+'.log', "a")
        f.write(message)
        f.close()

class DATA_LOADER(object):
    def __init__(self, opt):
        if opt.matdataset:
            if opt.dataset == 'imageNet1K':
                self.read_matimagenet(opt)
            else:
                self.read_matdataset(opt)
        self.index_in_epoch = 0
        self.epochs_completed = 0

    def read_matdataset(self, opt):
        matcontent = sio.loadmat(opt.dataroot + "/" + opt.dataset + "/" + opt.image_embedding + ".mat")
        feature = matcontent['features'].T
        label = matcontent['labels'].astype(int).squeeze() - 1
        matcontent = sio.loadmat(opt.dataroot + "/" + opt.dataset + "/" + opt.class_embedding + "_splits.mat")
        # numpy array index starts from 0, matlab starts from 1
        trainval_loc = matcontent['trainval_loc'].squeeze() - 1
        # train_loc = matcontent['train_loc'].squeeze() - 1
        # val_unseen_loc = matcontent['val_loc'].squeeze() - 1
        test_seen_loc = matcontent['test_seen_loc'].squeeze() - 1
        test_unseen_loc = matcontent['test_unseen_loc'].squeeze() - 1
        self.attribute = torch.from_numpy(matcontent['att'].T).float()

        if not opt.validation:
            if opt.preprocessing:
                if opt.standardization:
                    print('standardization...')
                    scaler = preprocessing.StandardScaler()
                else:
                    scaler = preprocessing.MinMaxScaler()

                _train_feature = scaler.fit_transform(feature[trainval_loc])
                _test_seen_feature = scaler.transform(feature[test_seen_loc])
                _test_unseen_feature = scaler.transform(feature[test_unseen_loc])
                self.train_feature = torch.from_numpy(_train_feature).float()
                mx = self.train_feature.max()
                self.train_feature.mul_(1/mx)
                self.train_label = torch.from_numpy(label[trainval_loc]).long()
                self.test_unseen_feature = torch.from_numpy(_test_unseen_feature).float()
                self.test_unseen_feature.mul_(1/mx)
                self.test_unseen_label = torch.from_numpy(label[test_unseen_loc]).long()
                self.test_seen_feature = torch.from_numpy(_test_seen_feature).float()
                self.test_seen_feature.mul_(1/mx)
                self.test_seen_label = torch.from_numpy(label[test_seen_loc]).long()
            else:
                self.train_feature = torch.from_numpy(feature[trainval_loc]).float()
                self.train_label = torch.from_numpy(label[trainval_loc]).long()
                self.test_unseen_feature = torch.from_numpy(feature[test_unseen_loc]).float()
                self.test_unseen_label = torch.from_numpy(label[test_unseen_loc]).long()
                self.test_seen_feature = torch.from_numpy(feature[test_seen_loc]).float()
                self.test_seen_label = torch.from_numpy(label[test_seen_loc]).long()
        else:
            self.train_feature = torch.from_numpy(feature[train_loc]).float()
            self.train_label = torch.from_numpy(label[train_loc]).long()
            self.test_unseen_feature = torch.from_numpy(feature[val_unseen_loc]).float()
            self.test_unseen_label = torch.from_numpy(label[val_unseen_loc]).long()

        self.seenclasses = torch.from_numpy(np.unique(self.train_label.numpy()))
        self.unseenclasses = torch.from_numpy(np.unique(self.test_unseen_label.numpy()))
        self.ntrain = self.train_feature.size()[0]
        self.ntrain_class = self.seenclasses.size(0)
        self.ntest_class = self.unseenclasses.size(0)
        self.train_class = self.seenclasses.clone()
        self.allclasses = torch.arange(0, self.ntrain_class+self.ntest_class).long()

        self.train_mapped_label = map_label(self.train_label, self.seenclasses)

    def next_batch_one_class(self, batch_size):
        if self.index_in_epoch == self.ntrain_class:
            self.index_in_epoch = 0
            perm = torch.randperm(self.ntrain_class)
            self.train_class[perm] = self.train_class[perm]

        iclass = self.train_class[self.index_in_epoch]
        idx = self.train_label.eq(iclass).nonzero().squeeze()
        perm = torch.randperm(idx.size(0))
        idx = idx[perm]
        iclass_feature = self.train_feature[idx]
        iclass_label = self.train_label[idx]
        self.index_in_epoch += 1
        return iclass_feature[0:batch_size], iclass_label[0:batch_size], self.attribute[iclass_label[0:batch_size]]

    def next_batch(self, batch_size):
        idx = torch.randperm(self.ntrain)[0:batch_size]
        batch_feature = self.train_feature[idx]
        batch_label = self.train_label[idx]
        return batch_feature, batch_label
    # select batch samples by randomly drawing batch_size classes
    def next_batch_uniform_class(self, batch_size):
        batch_class = torch.LongTensor(batch_size)
        for i in range(batch_size):
            idx = torch.randperm(self.ntrain_class)[0]
            batch_class[i] = self.train_class[idx]

        batch_feature = torch.FloatTensor(batch_size, self.train_feature.size(1))
        batch_label = torch.LongTensor(batch_size)
        batch_att = torch.FloatTensor(batch_size, self.attribute.size(1))
        for i in range(batch_size):
            iclass = batch_class[i]
            idx_iclass = self.train_label.eq(iclass).nonzero().squeeze()
            idx_in_iclass = torch.randperm(idx_iclass.size(0))[0]
            idx_file = idx_iclass[idx_in_iclass]
            batch_feature[i] = self.train_feature[idx_file]
            batch_label[i] = self.train_label[idx_file]
            batch_att[i] = self.attribute[batch_label[i]]
        return batch_feature, batch_label, batch_att


from django.shortcuts import render
from .forms import GeeksForm
from .models import GeeksModel

def home_view(request):
    context = {}
    if request.method == "POST":
        form = GeeksForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data.get("name")
            img = form.cleaned_data.get("geeks_field")
            obj = GeeksModel.objects.create(
                                 title = name,
                                 img = img
                                 )
            obj.save()
            print(obj)
    else:
        form = GeeksForm()
    context['form']= form
    return render(request, "home.html", context)


# Imported libraries
import numpy as npy
import matplotlib.pyplot as plt
import tensorflow as tf
from tqdm import tqdm
import time as tm
import timeit as ti
from keras.models import Model
from tensorflow.keras.optimizers import Adam, SGD

# This class loads the CIFAR10 dataset to feed it to the GAN.
class dataset_load:
    ver = tf.__version__
    msg_0_0 = f"\nWorking with a Generative Adversarial Network Using TensorFlow and Keras version: {ver}\n"
    print(msg_0_0)
    tm.sleep(1)
    # Progress bar.
    for progress in tqdm(range(101), desc="Loading..", ascii=False, ncols=75):
        tm.sleep(0.01)

    print("\nStarting----->\n")
    tm.sleep(1)

    # Loads the CIFAR10 dataset
    (X, y), (_, _) = tf.keras.datasets.cifar10.load_data()

    X = X[y.flatten() == 8]

    # Loads, reads, and split the dataset.
    msg_0 = X.shape, y.shape, _.shape, _.shape

    # Input shape.
    image_shape = (32, 32, 3)
    latent_dims = 100

    # Dataset progress bar.
    for progress_2 in tqdm(range(101), desc="Loading Dataset", ascii=False, ncols=75):
        tm.sleep(0.01)

    msg_1 = f"\nCIFAR10 dataset--------------------------------------->>\n{msg_0}\n\n"
    print(msg_1)
    tm.sleep(1)

# This class houses the generator conv network.
class build_generator:
    generator_net = tf.keras.Sequential()

    generator_net.add(tf.keras.layers.Dense(128 * 8 * 8, activation='relu', input_dim=dataset_load.latent_dims))
    generator_net.add(tf.keras.layers.Reshape((8, 8, 128)))
    generator_net.add(tf.keras.layers.UpSampling2D())

    generator_net.add(tf.keras.layers.Conv2D(128, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.BatchNormalization(momentum=0.78))
    generator_net.add(tf.keras.layers.Activation("relu"))
    generator_net.add(tf.keras.layers.UpSampling2D())

    generator_net.add(tf.keras.layers.Conv2D(64, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.BatchNormalization(momentum=0.78))
    generator_net.add(tf.keras.layers.Activation("relu"))

    generator_net.add(tf.keras.layers.Conv2D(3, kernel_size=3, padding="same"))
    generator_net.add(tf.keras.layers.Activation("tanh"))

    noise = tf.keras.Input(shape=(dataset_load.latent_dims,))
    image = generator_net(noise)

    generator_net.summary()

    sent1 = Model(noise, image)

# This class houses the discriminator network.
class build_discriminator:
    discriminator_net = tf.keras.Sequential()

    discriminator_net.add(tf.keras.layers.Conv2D(32, kernel_size=3, strides=2, input_shape=dataset_load.image_shape,
                                                 padding="same"))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(64, kernel_size=3, strides=2, padding="same"))
    discriminator_net.add(tf.keras.layers.ZeroPadding2D(padding=((0, 1), (0, 1))))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.82))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(128, kernel_size=3, strides=2, padding="same"))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.82))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.2))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Conv2D(256, kernel_size=3, strides=1, padding="same"))
    discriminator_net.add(tf.keras.layers.BatchNormalization(momentum=0.8))
    discriminator_net.add(tf.keras.layers.LeakyReLU(alpha=0.25))
    discriminator_net.add(tf.keras.layers.Dropout(0.25))

    discriminator_net.add(tf.keras.layers.Flatten())
    discriminator_net.add(tf.keras.layers.Dense(1, activation='sigmoid'))

    image = tf.keras.Input(shape=dataset_load.image_shape)
    validity = discriminator_net(image)

    discriminator_net.summary()

    sent2 = Model(image, validity)

# this function displays the generated images.
# every 2500 epochs.
def image_plotter():
    r, c = 4, 4

    noise = npy.random.normal(0, 1, (r * c, dataset_load.latent_dims))
    generated_image = GAN.generator.predict(noise)

    generated_image = 0.5 * generated_image + 0.5

    fig, axs = plt.subplots(r, c)
    count = 0

    for i in range(r):
        for j in range(c):
            axs[i, j].imshow(generated_image[count])
            axs[i, j].axis('off')
            count += 1

    plt.show()
    plt.close()

# This class builds the GAN by combining the networks.
class GAN:
    discriminator = build_discriminator.discriminator_net

    discriminator.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5),
                          metrics=['Accuracy'])

    build_discriminator.discriminator_net.trainable = False

    generator = build_generator.generator_net
    z = tf.keras.Input(shape=(dataset_load.latent_dims,))
    image = generator(z)

    validity = build_discriminator.discriminator_net(image)

    combined_network = Model(z, validity)
    combined_network.compile(loss='binary_crossentropy', optimizer=Adam(0.0002, 0.5))

# this class starts the training process on the generator and the discriminator.
class Net_training:
    num_epochs = 15000
    batch_size = 32
    display_interval = 2500
    losses = []

    X = (dataset_load.X / 127.5) - 1

    valid = npy.ones((batch_size, 1))

    valid += 0.05 * npy.random.random(valid.shape)

    fake = npy.zeros((batch_size, 1))
    fake += 0.05 * npy.random.random(fake.shape)

    for epoch in range(num_epochs):
        index = npy.random.randint(0, X.shape[0], batch_size)
        images = X[index]

        noise = npy.random.normal(0, 1, (batch_size, dataset_load.latent_dims))

        generated_images = GAN.generator.predict(noise)

        discm_loss_real = GAN.discriminator.train_on_batch(images, valid)
        discm_loss_fake = GAN.discriminator.train_on_batch(generated_images, fake)
        discm_loss = 0.5 * npy.add(discm_loss_real, discm_loss_fake)

        genr_loss = GAN.combined_network.train_on_batch(noise, valid)

        if epoch % display_interval == 0:
            image_plotter()

        # displays the respective number of losses per epochs.
        tqdm.write(f"\nEpoch: {epoch} | \nGAN Loss: {genr_loss} "
                   f"| \nReal Loss: {discm_loss_real} | \nFake Loss: {discm_loss_fake}\n")

    # plots the images from the last epoch.
    noise = npy.random.normal(size=(40, dataset_load.latent_dims))

    generated_images = GAN.generator.predict(noise)
    generated_images = 0.5 * generated_images + 0.5

    f, ax = plt.subplots(5, 8, figsize=(16, 10))
    for img_data_2, image in enumerate(generated_images):
        ax[img_data_2 // 8, img_data_2 % 8].imshow(image)
        ax[img_data_2 // 8, img_data_2 % 8].axis('off')

    plt.show()
    plt.savefig(f"Image generates from the last epoch.jpg")
    plt.close()

# runtime evaluation
class model_eval:
    runtime_duration = ti.timeit(build_generator, number=1)
    runtime_duration_2 = ti.timeit(build_discriminator, number=2)
    GAN_Runtime = {'Generator_runtime': f"\nGenerator: {runtime_duration}",
                   'Discriminator_runtime': f"\nDiscriminator: {runtime_duration_2}"}

    print(GAN_Runtime['Generator_runtime'] + GAN_Runtime['Discriminator_runtime'])

if __name__ == "__main__":
    dataset_load()
    model_eval()

Applying Machine Learning and Neural Networks/Generative Adversarial Network/GAN_V1.py


import logging

from sqlalchemy.engine import Engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker
from SQLAlchemy.ex_sa_00 import create_db_engine
from SQLAlchemy.ex_sa_09 import Base, Kyc

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

def create_kyc_table(engine: Engine) -> bool:
    status = False

    if not engine.dialect.has_table(engine, 'kyc'):
        Base.metadata.create_all(db_engine)

        logging.info("Created the kyc table !!!")

        status = True
    else:
        logging.info("The kyc table already exists !!!")

    return status

def insert_kyc_recs(engine: Engine):
    if engine.dialect.has_table(engine, 'kyc'):
        Session = sessionmaker(bind=engine)

        session = Session()

        try:
            ad_kyc = Kyc(kyc_flag=True, cid=1, ano=1001)
            session.add(ad_kyc)
            session.commit()

            logging.info("Inserted kyc for Alice")
        except SQLAlchemyError as e:
            logging.error(e)

        try:
            bb_kyc = Kyc(cid=2, ano=1002)
            session.add(bb_kyc)
            session.commit()

            logging.info("Inserted kyc for Bob")
        except SQLAlchemyError as e:
            logging.error(e)

        try:
            cd_kyc = Kyc(cid=3, ano=1003)
            session.add(cd_kyc)
            session.commit()

            logging.info("Inserted kyc for Charlie")
        except SQLAlchemyError as e:
            logging.error(e)

        session.close()
    else:
        logging.info("The kyc table *DOES NOT* exist !!!")

if __name__ == "__main__":
    db_engine = create_db_engine()
    if create_kyc_table(db_engine):
        insert_kyc_recs(db_engine)


from hashlib import new
from django.http import HttpRequest
from django.shortcuts import redirect, render, HttpResponse
from .forms import *

from order.models import *

# Create your views here.
def index(request):
    return redirect('orderslip')

def orderslip(request, order=OrderSlip.objects.latest('order_id').order_id):
    context = {
        'LastOrderSlip' : OrderSlip.objects.filter(order_id=order).first(),
        'OrderItem' : OrderItem.objects.filter(order=order),
        'ItemAddOn' : ItemAddOn.objects.all(),
        'OrderSlip' : OrderSlip.objects.all()
    }
    return render(request, 'orderslip.html', context)

def neworderslip(request):
    if request.method == 'POST':
        form = OrderSlipForm(request.POST)
        if form.is_valid():
            print("VALID!")
            customer_name = form.cleaned_data['customer_name']
            date_ordered = form.cleaned_data['date_ordered']

            print(customer_name, date_ordered)
            newOrderSlip = form.save()
            return redirect('orderslip', order=newOrderSlip.order_id)

    form = OrderSlipForm()
    return render(request, 'form.html', {'form' : form})

def neworderitem(request, order):
    if request.method == 'POST':
        form = OrderItemForm(request.POST)
        if form.is_valid():
            print("VALID!")
            newOrderItem = form.save()
            return redirect('orderslip', order=newOrderItem.order_id)

    form = OrderItemForm({'order':order})
    return render(request, 'form.html', {'form' : form})

def newitemaddon(request, order_item):
    if request.method == 'POST':
        form = ItemAddOnForm(request.POST)
        if form.is_valid():
            print("VALID!")
            if(form.cleaned_data['add_on_quantity'] != 0):
                print("No quantity. Not saved.")
                newItemAddOn = form.save()
                return redirect('orderslip', order=newItemAddOn.order_item.order_id)
            return redirect('orderslip', order=form.cleaned_data['order_item'].order_id)

    form = ItemAddOnForm({'order_item':order_item})
    return render(request, 'form.html', {'form' : form})

def data(request):
    context = {
        'Recipe' : Recipe.objects.all(),
        'Ingredient' : Ingredient.objects.all(),
        'OrderSlip' : OrderSlip.objects.all(),
        'OrderItem' : OrderItem.objects.all(),
        'ItemAddOn' : ItemAddOn.objects.all()
    }
    return render(request, 'data.html', context=context)

def deleteOrderSlip(request, order_id):
    try:
        OrderSlip.objects.filter(order_id=order_id).delete()
    except:
        print("No Order Slip found.")
    LastOrderSlip = OrderSlip.objects.latest('order_id')
    return redirect('orderslip', order=LastOrderSlip.order_id)

def deleteOrderItem(request, order_item_id):
    OrderItemToDelete = OrderItem.objects.filter(order_item_id=order_item_id).first()
    try:
        OrderSlipID = OrderItemToDelete.order.order_id
        OrderItemToDelete.delete()
        return redirect('orderslip', order=OrderSlipID)
    except:
        print("No Order Item found.")
        return redirect('orderslip')

def deleteItemAddOn(request, item_addon_id):
    ItemAddOnToDelete = ItemAddOn.objects.filter(item_addon_id=item_addon_id).first()
    try:
        OrderSlipID = ItemAddOnToDelete.order_item.order.order_id
        ItemAddOnToDelete.delete()
        return redirect('orderslip', order=OrderSlipID)
    except:
        print("No Item Add-On found.")
        return redirect('orderslip')


#-*- coding: utf-8 -*-
from trytond.model import ModelSQL, ModelView, fields

__all__ = ['Rango']

class Rango(ModelSQL, ModelView):
    "Rango"
    __name__ = 'sigcoop_usuario.rango'
    #minimo y maximo de rango de acciones asignadas
    minimo = fields.Integer('Minimo', required=True)
    maximo = fields.Integer('Maximo', required=True)
    #Referencia asociados
    asociado = fields.Many2One('party.party', 'Asociado', domain=[('asociado', '=', True)])


from weibopy.auth import OAuthHandler
from weibopy.api import API
import configparser

MAX_PIC_NUM = 3

def press_sina_weibo():
    '''''
    调用新浪微博Open Api实现通过命令行写博文，功能有待完善
    author: socrates
    date:2012-02-06
    新浪微博：@偶是正太
    '''
    sina_weibo_config = configparser.ConfigParser()
    #读取appkey相关配置文件
    try:
        sina_weibo_config.readfp(open('sina_weibo_config.ini'))
    except ConfigParser.Error:
        print ('read sina_weibo_config.ini failed.')

    #获取需要的信息
    consumer_key = sina_weibo_config.get("userinfo","CONSUMER_KEY")
    consumer_secret =sina_weibo_config.get("userinfo","CONSUMER_SECRET")
    token = sina_weibo_config.get("userinfo","TOKEN")
    token_sercet = sina_weibo_config.get("userinfo","TOKEN_SECRET")

    #调用新浪微博OpenApi(python版)
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.setAccessToken(token, token_sercet)
    api = API(auth)

    #通过命令行输入要发布的内容
#    weibo_content = raw_input('Please input content:')
#    status = api.update_status(status=weibo_content)
#    print "Press sina weibo successful, content is: %s" % status.text
    iNum = 2
    while True:
        #上传图片，名称和内容如果重复，open api会检查，内容采用了取当前时间的机制
        #图片名称从0-5循环遍历
        status = api.upload( str(iNum)+'.jpg', 'test '+str(iNum) )

        if iNum == MAX_PIC_NUM:
            break
        else:
            iNum += 1

if __name__ == '__main__':
    press_sina_weibo()


from decimal import Decimal
from dateutil.relativedelta import relativedelta

from trytond.model import ModelView, fields
from trytond.wizard import Wizard, StateView, StateReport, Button
from trytond.report import Report
from trytond.pool import Pool
from trytond.pyson import Eval, If
from trytond.transaction import Transaction

MAX_COLS = 24

class PrintCashFlowReportStart(ModelView):
    'Print Cash-Flow'
    __name__ = 'cooperative_ar.print_cashflow.start'

    company = fields.Many2One('company.company', 'Company', required=True)
    analytic_account = fields.Many2One('analytic_account.account',
        'Analytic Account', required=True,
        domain=[
            ('company', '=', Eval('company', -1)),
            ('type', '=', 'root'),
            ],
        depends=['company'])
    from_date = fields.Date('From Date', required=True,
        domain=[
            If(Eval('to_date') & Eval('from_date'),
                ('from_date', '<=', Eval('to_date')),
                ()),
            ],
        depends=['to_date'])
    to_date = fields.Date('To Date', required=True,
        domain=[
            If(Eval('from_date') & Eval('to_date'),
                ('to_date', '>=', Eval('from_date')),
                ()),
            ],
        depends=['from_date'])

    @classmethod
    def default_company(cls):
        return Transaction().context.get('company')

class PrintCashFlowReport(Wizard):
    'Print Cash-Flow'
    __name__ = 'cooperative_ar.print_cashflow'

    start = StateView('cooperative_ar.print_cashflow.start',
        'cooperative_cashflow_ar.print_cashflow_report_start_view', [
            Button('Cancel', 'end', 'tryton-cancel'),
            Button('Print', 'print_', 'tryton-print', True),
            ])
    print_ = StateReport('cooperative_ar.cashflow')

    def do_print_(self, action):
        data = {
            'company': self.start.company.id,
            'analytic_account': self.start.analytic_account.id,
            'from_date': self.start.from_date,
            'to_date': self.start.to_date,
            }
        return action, data

class CashFlowReport(Report):
    'Cash-Flow'
    __name__ = 'cooperative_ar.cashflow'

    @classmethod
    def get_context(cls, records, header, data):
        pool = Pool()
        Company = pool.get('company.company')

        report_context = super().get_context(records, header, data)

        report_context['company'] = Company(data['company'])
        report_context['from_date'] = data['from_date']
        report_context['to_date'] = data['to_date']

        columns = cls._get_date_columns(data['from_date'], data['to_date'])
        report_context['columns'] = [x['lbl']
            for x in columns.values()] + ['Total']
        if len(report_context['columns']) < MAX_COLS:
            for idx in range(MAX_COLS - len(report_context['columns'])):
                report_context['columns'].append('')

        # Sales
        sales_raw = cls._get_sale_records(data)
        report_context['sales_raw'] = sales_raw.values()

        sales_summary = cls._get_sale_summary(columns, sales_raw)
        report_context['sales_summary'] = sales_summary.values()

        # Expenses
        expenses_raw = cls._get_expense_records(data)
        report_context['expenses_raw'] = expenses_raw.values()

        expenses_summary = cls._get_expense_summary(columns, expenses_raw)
        report_context['expenses_summary'] = expenses_summary.values()

        # Cooperative Receipts
        receipts_raw = cls._get_receipt_records(data)
        report_context['receipts_raw'] = receipts_raw.values()

        receipts_summary = cls._get_receipt_summary(columns, receipts_raw)
        report_context['receipts_summary'] = receipts_summary.values()

        # Synthesis
        synthesis = cls._get_synthesis(columns,
            sales_summary, expenses_summary, receipts_summary)
        report_context['synthesis'] = synthesis.values()

        return report_context

    @classmethod
    def _get_date_columns(cls, from_date, to_date):
        res = {}
        date = from_date
        idx = 0
        while date < to_date and idx < MAX_COLS:
            year, month = date.year, date.month
            res[(year, month)] = {'idx': idx, 'lbl': '%s/%s' % (month, year)}
            date = date + relativedelta(months=1)
            idx += 1
        return res

    @classmethod
    def _get_sale_records(cls, data):
        pool = Pool()
        Company = pool.get('company.company')
        Currency = pool.get('currency.currency')
        SaleLine = pool.get('sale.line')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}
        company = Company(data['company'])

        clause = [
            ('sale.company', '=', data['company']),
            ('sale.state', 'in',
                ['projected', 'confirmed', 'processing', 'done']),
            ('type', '=', 'line'),
            ('manual_delivery_date', '>=', data['from_date']),
            ('manual_delivery_date', '<=', data['to_date']),
            ]
        sale_lines = SaleLine.search(clause,
            order=[('manual_delivery_date', 'ASC')])
        if not sale_lines:
            return records

        for line in sale_lines:
            year = line.manual_delivery_date.year
            month = line.manual_delivery_date.month
            category_id = None
            for analytic_line in line.analytic_accounts:
                if (analytic_line.root.id == data['analytic_account'] and
                        analytic_line.account):
                    category_id = analytic_line.account.id
            key = (year, month, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.manual_delivery_date):
                records[key]['amount'] += Currency.compute(
                    company.currency, line.amount, line.currency)
        return records

    @classmethod
    def _get_sale_summary(cls, columns, sales_raw):
        records = {}
        for key, line in sales_raw.items():
            category_id = key[2]
            if category_id not in records:
                records[category_id] = {
                    'category': line['category'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[category_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[category_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_purchase_records(cls):
        return []

    @classmethod
    def _get_expense_records(cls, data):
        pool = Pool()
        MoveLine = pool.get('account.move.line')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}

        clause = [
            ('move.company', '=', data['company']),
            ('account.cashflow_report', '=', True),
            ('move.state', '=', 'posted'),
            ('move.date', '>=', data['from_date']),
            ('move.date', '<=', data['to_date']),
            ]
        move_lines = MoveLine.search(clause,
            order=[('move.date', 'ASC')])
        if not move_lines:
            return records

        for line in move_lines:
            year = line.move.date.year
            month = line.move.date.month
            category_id = None
            for analytic_line in line.analytic_lines:
                if (analytic_line.account.root.id ==
                        data['analytic_account'] and
                        analytic_line.account):
                    category_id = analytic_line.account.id
            key = (year, month, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.move.date):
                records[key]['amount'] += abs(line.debit - line.credit)
        return records

    @classmethod
    def _get_expense_summary(cls, columns, expenses_raw):
        records = {}
        for key, line in expenses_raw.items():
            category_id = key[2]
            if category_id not in records:
                records[category_id] = {
                    'category': line['category'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[category_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[category_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_receipt_records(cls, data):
        pool = Pool()
        Company = pool.get('company.company')
        Currency = pool.get('currency.currency')
        Recibo = pool.get('cooperative.partner.recibo')
        AnalyticAccount = pool.get('analytic_account.account')

        records = {}
        company = Company(data['company'])

        clause = [
            ('company', '=', data['company']),
            ('state', 'in', ['projected', 'confirmed']),
            ('date', '>=', data['from_date']),
            ('date', '<=', data['to_date']),
            ]
        receipts = Recibo.search(clause,
            order=[('date', 'ASC')])
        if not receipts:
            return records

        for line in receipts:
            year = line.date.year
            month = line.date.month
            category_id = None
            #for analytic_line in line.analytic_accounts:
                #if (analytic_line.root.id == data['analytic_account'] and
                        #analytic_line.account):
                    #category_id = analytic_line.account.id
            key = (year, month, line.partner.id, category_id)
            if key not in records:
                records[key] = {
                    'year': year,
                    'month': month,
                    'partner': line.partner.rec_name,
                    'category': (category_id and
                        AnalyticAccount(category_id).name or ''),
                    'amount': Decimal(0),
                    }
            with Transaction().set_context(date=line.date):
                records[key]['amount'] += Currency.compute(
                    company.currency, line.amount, line.currency)
        return records

    @classmethod
    def _get_receipt_summary(cls, columns, receipts_raw):
        records = {}
        for key, line in receipts_raw.items():
            partner_id = key[2]
            if partner_id not in records:
                records[partner_id] = {
                    'partner': line['partner'],
                    'columns': dict((idx, None) for idx in range(MAX_COLS)),
                    'total': Decimal(0),
                    }
            date = key[:2]
            if date not in columns:
                continue
            records[partner_id]['columns'][columns[date]['idx']] = line[
                'amount']
            records[partner_id]['total'] += line['amount']

        total_idx = len(columns)
        for k, v in records.items():
            v['columns'][total_idx] = v['total']
        return records

    @classmethod
    def _get_synthesis(cls, columns,
            sales_summary, expenses_summary, receipts_summary):
        records = {}
        result_columns = dict((idx, None) for idx in range(MAX_COLS))

        # Sales
        records[1] = {
            'name': 'Ventas',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in sales_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[1]['columns'][idx] is None:
                    records[1]['columns'][idx] = Decimal(0)
                records[1]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] += value

        # Expenses
        records[2] = {
            'name': 'Gastos',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in expenses_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[2]['columns'][idx] is None:
                    records[2]['columns'][idx] = Decimal(0)
                records[2]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] -= value

        # Cooperative Receipts
        records[3] = {
            'name': 'Retiros',
            'columns': dict((idx, None) for idx in range(MAX_COLS)),
            }
        for record in receipts_summary.values():
            for idx, value in record['columns'].items():
                if value is None:
                    continue
                if records[3]['columns'][idx] is None:
                    records[3]['columns'][idx] = Decimal(0)
                records[3]['columns'][idx] += value
                if result_columns[idx] is None:
                    result_columns[idx] = Decimal(0)
                result_columns[idx] -= value

        # Result
        records[9] = {
            'name': 'Resultado',
            'columns': result_columns,
            }

        return records