from fractions import Fraction
from random import randint, choice

class Participant:

	# This function is called when a participant is first initialized
	# Each participant will have its own p, q, a, g, and share
	# p: a largish prime number
	# q: also a largish prime number
	# a: p = aq + 1
	# g: a generator number
	# share: a share in the form (x, y)
	def __init__(self, p, q, a, g, share):
		self.p = p
		self.q = q
		self.a = a
		self.g = g
		self.share = share

	# This function is in charge of interpolating the shares of all participants
	# with regard to self (i.e self.share[0] will be the x-coordinate you interpolate at)
	# Calculate some variable v and indicator function I such that v = (I(x) * y) mod q
	# Returns (g ** v) mod p
	def partial_interpolate(self, all_participants):
		points = [p.share for p in all_participants]
		v = 0

		for j in range(len(points)):
			y = points[j][1]
			l = self.basis(points, 0, j) #?

			v += y*l

		v = v % self.q
		return mod_pow(self.g, v, self.p)

	# jth basis at x
	def basis(self, points, x, j):
		val = 1
		for m in range(len(points)):
			if not m == j:
				a = x - points[m][0]
				b = points[j][0] - points[m][0]

				if b == 0:
					pass
					#print "\noh no: ", points[j][0], points[m][0], " || ", j, m
				else:
					v = Fraction(a)/Fraction(b)
					val *= v

		return val

	# This function simulates a participant querying all other participants to see whether
	# or not they can recover the secret
	def query_participants(self, all_participants, query):
		secret = self.partial_interpolate(all_participants)

		actual = self.g ** (secret * self.a)
		actual = actual % self.p

		guess = self.g ** (query * self.a)
		guess = guess % self.p

		#print "actual: ", actual
		#print "guess: ", guess

		return actual == guess

# val: the secret
# k: the number of valid participant shares needed to recover the secret
# q: the prime you mod by as you'll be working in mod q
def distribute_shares(all_participants, val, k, q):
	r = 1000
	neg = [1, -1] #################
	coefs = [choice(neg) * Fraction(randint(1, r), randint(1, r)) for i in range(0, k-1)]
	coefs.insert(0, val)

	keys = set([])

	#keep adding unique keys
	while len(keys) < len(all_participants):
		p = randint(1, r)
		fp = polyVal(coefs, p)
		keys.add((p%q, fp%q))

	keys = list(keys)

	for i in range(len(all_participants)):
		all_participants[i].share = keys[i]

# given list of coefficents for p, find p(x)
def polyVal(coefs, x):
	val = 0
	i = 0
	for c in coefs:
		val += c * (x**i)
		i += 1
	return val

# computes the greatest common divisor of a and b
# Euclidian algorithm
def gcd(a, b):
	r = a % b
	if r == 0:
		return b
	else:
		return gcd(b, r)

# computes b to the p-th power mod q
# must be done in logarithmic time complexity
# note: don't do b ** p % q; this could overflow with very large numbers
def mod_pow(b, p, q):
	total = 1
	current = b

	binary = bin(int(p))
	binary = binary[2:]
	binary = binary[::-1]

	for bit in binary:
		if bit == '1':
			total = (total * current) % q
		current = (current ** 2) % q
	return total

# computes the inverse of x mod q
def inverse(x, q):
	if q == 1:
		return 0

	for i in range(1, q):
		if (i * x) % q == 1:
			return i

	return None


lines = []
l = -1
vars = []
import os
import colorama
from colorama import Fore, Back, Style
colorama.init(autoreset=True)

os.system("pip install colorama")

def code(code):
    # with open(f"modules.mits", "r", encoding="utf-8") as f:
    #     for line in f:
    #         if line != "\n":
    #             lines.append(line.replace("\n", ""))
    #     print(lines)
    #     if "__MitsLoader__" in lines:
    #         pass
    #     else:
    #         print("\33[31mFile can't be launched, missing init point key.")
    #         exit()

    def calc(fileline, calc):
        try:
            result = eval(f"{calc}")
            print(str(result).replace("None", ""))
            return result
        except Exception as e:
            print(Fore.RED + f"Line {fileline} error :\n'{calc}' can't be calculed.")
            exit()

    def CheckVar(fileline, var):
        splited_var = var.split(" ")
        if splited_var[0].endswith(":"):
            VarContent = var.replace(splited_var[0], "")
            if '"' in VarContent:
                InitVar("-1", splited_var[0].replace(":", ""), VarContent, tp="lt")
            else:
                if "*" in VarContent or "/" in VarContent or "+" in VarContent or "-" in VarContent:
                    InitVar("-1", splited_var[0].replace(":", ""), VarContent, tp="calc")

    def InitVar(fileline, varname, content, tp="lt"):
        if tp == "lt":
            vars.append(varname + " $£" + content)
        elif tp == "calc":
            vars.append(f"{varname} $£ {eval(str(content.replace(' ', '')))}")

    def DelVar(fileline, var):
        try:
            v = vars.index(var)
            pass
        except:
            print(Fore.RED + f"Line {fileline} error :\nVar '{var}' can't be found.")
            exit()

    def UseVar(varname):
        varname = varname.replace(" ", "")
        for element in vars:
            if varname in element:
                print(element.split("$£")[1].replace('"', ''))
                return

        print(Fore.RED + f"Line -1 error :\nVar '{varname}' can't be found.")

    def say(fileline, line):
        tosay = line.replace("say;", "")
        if '"' in tosay:
            tosay= tosay.replace('"', '')
            print(tosay)
            return tosay
        elif "{" in line and "}" in line:
            tosay = tosay.replace("{", '').replace("}", "")
            if "calc;" in line:
                tosay = tosay.replace("calc;", '').replace(" ", "")
                calc("-1", tosay)
            elif ":" in line:
                tosay = tosay.replace(":", "")
                UseVar(tosay)

    if code.startswith("--") and code.endswith("--"):
        pass
    if code.startswith("say;"):
        say(l, code)
    if code.startswith("del;"):
        DelVar(l, code.split(";")[0])
    if ":" in code:
        CheckVar(l, code)


from typing import List

class Colors:
    """
    https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
    """

    WARNING = "\033[93m"
    SUPER_WARNING = "\033[91m"
    OKGREEN = "\033[92m"
    ENDC = "\033[0m"
    BOLD = "\033[1m"
    ITALIC = "\033[3m"
    INACTIVE = "\u001b[38;5;240m\u001b[2m"
    GROOVY = "\u001b[38;5;105m"
    ULTRA_GROOVY = "\u001b[38;5;51m"
    UNDERLINE = "\033[4m"

def terminal_format(to_format: str, format_options: List[str]):
    return "".join(["".join(format_options), to_format, Colors.ENDC])


# (c) 2021 Okawo
# This code is licensed under MIT license (see LICENSE for details)

"""
this is an example of using virtualreality.templates

to get detailed overview of virtualreality.templates.PoserTemplate run this in your python interpreter:
	help(virtualreality.templates.PoserTemplate)

more examples/references:
	https://github.com/okawo80085/hobo_vr/blob/master/virtualreality/trackers/color_tracker.py

"""

import asyncio
import time
import numpy as np
from fractions import Fraction
import re
import pyrr

from virtualreality import templates

class MyPoser(templates.UduPoserTemplate):
    _CLI_SETTS = '''hobo_vr poser

Usage: poser [-h | --help] [options]

Options:
    -h, --help              shows this message
    -q, --quit              exits the poser
    -t, --test <pair>       test
    -e, --ipd <millim>      ipd in meters, float
    -u, --udu <string>      new udu string
    -T, --tr <loc>          set new location of the tracking reference, format float: x,y,z
    -d, --dist <val>        new distortion parameters, format float: k1,k2,zw,zh
    -i, --eyeGap <val>      new eye gap in pixels, int
'''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.coro_keep_alive['send'].is_alive = False
        # self.coro_keep_alive['send'].sleep_delay = 1

    async def _cli_arg_map(self, pair):
        if pair[0] == "--test" and pair[1]:
            a, b = pair[1].split(',')
            a, b = int(a), int(b)
            data = templates.settManager_Message_t.pack(a, b, *np.zeros((128,), dtype=np.uint32))
            resp = await self._send_manager(data)
            print (resp)

        elif pair[0] == "--tr" and pair[1]:
            f1, f2, f3 = [Fraction(i).limit_denominator(10000000) for i in pair[1].split(',')]
            data = templates.settManager_Message_t.pack(60, int(f1.numerator), int(f1.denominator), int(f2.numerator), int(f2.denominator), int(f3.numerator), int(f3.denominator), *np.zeros((123,), dtype=np.uint32))
            resp = await self._send_manager(data)
            print (resp)

        elif pair[0] == "--ipd" and pair[1]:
            f = Fraction(pair[1]).limit_denominator(10000000)
            data = templates.settManager_Message_t.pack(10, int(f.numerator), int(f.denominator), *np.zeros((127,), dtype=np.uint32))
            resp = await self._send_manager(data)
            print (resp)

        elif pair[0] == "--dist" and pair[1]:
            k1, k2, zw, zh = [Fraction(i).limit_denominator(10000000) for i in pair[1].split(',')]
            data = templates.settManager_Message_t.pack(40, int(k1.numerator), int(k1.denominator), int(k2.numerator), int(k2.denominator), int(zw.numerator), int(zw.denominator), int(zh.numerator), int(zh.denominator), *np.zeros((121,), dtype=np.uint32))
            resp = await self._send_manager(data)
            print (resp)

        elif pair[0] == "--eyeGap" and pair[1]:
            newGap = int(pair[1])
            data = templates.settManager_Message_t.pack(50, newGap, *np.zeros((128,), dtype=np.uint32))
            resp = await self._send_manager(data)
            print (resp)

        elif pair[0] == "--udu" and pair[1]:
            res = await self._sync_udu(pair[1])
            if res:
                print (res)

    @templates.PoserTemplate.register_member_thread(1 / 100)
    async def example_thread1(self):
        """moves the headset in a circle"""
        h = 0
        while self.coro_keep_alive["example_thread1"].is_alive:
            try:
                self.poses[0].z = np.sin(h)/3
                self.poses[0].x = np.cos(h/2)/3
                self.poses[0].y = np.cos(h/2)/3
                x, y, z, w = pyrr.Quaternion.from_z_rotation(h/5)
                self.poses[0].r_x = x
                self.poses[0].r_y = y
                self.poses[0].r_z = z
                self.poses[0].r_w = w
                h += 0.01

                await asyncio.sleep(self.coro_keep_alive["example_thread1"].sleep_delay)

            except Exception as e:
                print(f"example_thread1 failed: {e}")
                break
        self.coro_keep_alive["example_thread1"].is_alive = False

    @templates.PoserTemplate.register_member_thread(1 / 100, runInDefaultExecutor=True)
    def example_thread2(self):
        """moves the controller up and down"""
        h = 0
        while self.coro_keep_alive["example_thread2"].is_alive:
            try:
                if len(self.poses) > 1:
                    for i in range(1, len(self.poses)):
                        self.poses[i].y = 1 + np.cos(h+i) / 5
                    h += 0.01

                time.sleep(self.coro_keep_alive["example_thread2"].sleep_delay)

            except Exception as e:
                print(f"example_thread2 failed: {e}")
                break
        self.coro_keep_alive["example_thread2"].is_alive = False

poser = MyPoser('h c c')

asyncio.run(poser.main())


import attr

from .field import *

from collections import Iterable
import exam_gen.util.logging as logging

log = logging.new(__name__, level="DEBUG")

@attr.s(init=False)
class DocSelect():
    """
    Associates record fields with documents and sub-documents
    """

    mapping = attr.ib()
    """
    Map from a document tree to various field selectors
    """

    selector = attr.ib(default=FieldSelect)
    """
    The field selector creator to use when none is specified, should be a
    callable that takes a user provided value and returns
    """

    norm_field = attr.ib(default=lambda f: (f,None))
    """
    A function that turns a field input into a field and some metadata.

    Used to allow mappings to contain additional info that might be useful.
    """

    def __new__(cls, *args, **kwargs):
        """
        Sorta idempotent normalised new.
        """

        if len(args) == 1 and len(kwargs) == 0:
            if isinstance(args[0], DocSelect):
                return args[0]

        return super(DocSelect, cls).__new__(cls)

    def __init__(self, *args, **kwargs):
        """
        Sorta idempotent normalised new.
        """

        if len(args) == 0 and len(kwargs) >= 0 and 'mapping' not in kwargs:
            _kwargs = dict()

            for k in ['selector', 'norm_field']:
                if k in kwargs: _kwargs[k] = kwargs.pop(k)

            kwargs = {'mapping': kwargs} | _kwargs

        self.__attrs_init__(*args, **kwargs)

    def __attrs_post_init__(self):

        _mapping = dict()

        for (k,v) in self.mapping.items():
            (field, meta) = self.norm_field(v)
            _mapping[k] = (self.norm_map_entry(field), meta)

        self.mapping = _mapping

    def norm_map_entry(self, entry):
        if isinstance(entry, DocSelect):
            return entry
        elif isinstance(entry, FieldSelect):
            return entry
        elif isinstance(entry, dict):
            return type(self)(mapping=entry,
                              selector=self.selector,
                              norm_field=self.norm_field)
        else:
            return self.selector(entry)

    def select(self, record, supress_error = False, with_meta = False):
        """
        Given a record produce a mapped dictionary of values.
        """

        result = dict()

        # Turn with_meta into a function that will turn the (match, meta) pair
        # into the result we want.
        if not callable(with_meta):
            as_tuple = lambda f, m: (f,m)
            only_field = lambda f, m: f
            with_meta = as_tuple if with_meta else only_field

        # Go through and grab the matching fields while assembling them
        # properly
        for (k, (fld, meta)) in self.mapping.items():
             match = fld.select(record, supress_error)
             if match != None:
                 result[k] = with_meta(match, meta)

        return result


from django.shortcuts import render, HttpResponse
from .models import *

# Create your views here.

def index(request):
	subs = Subscribed.objects.all()

	context = {
		'subs' : subs
	}
	return render(request, 'core/home.html', context)


# N 1.1 Median of Two Sorted Arrays
# Given two sorted arrays nums1 and nums2 of size m and n respectively,
# return the median of the two sorted arrays.

def get_input_number(text) -> int:
    while True:
        try:
            input_number = int(input(f'{text} '))
            return input_number
        except ValueError:
            print("The input is not a number.")

def get_median_of_sorted_arrays(arrayItems) -> int:
    middle_index = len(arrayItems) // 2
    middle_item = arrayItems[middle_index]

    if len(arrayItems) % 2 == 0:
        sum_of_middle_item = arrayItems[middle_index - 1] + arrayItems[middle_index]
        middle_of_sort_value = sum_of_middle_item / 2
    else:
        middle_of_sort_value = middle_item

    return middle_of_sort_value

def main():
    numbers1 = []
    numbers2 = []

    maxSet1 = get_input_number("Amount of number list set 1: ")
    for index in range(maxSet1):
        numbers1.append(get_input_number(f"Input a number {index + 1}: "))

    maxSet2 = get_input_number("Amount of number list set 2: ")
    for index in range(maxSet2):
        numbers2.append(get_input_number(f"Input a number {index + 1}"))

    combined = numbers1 + numbers2
    sorted_numbers = sorted(combined)

    middle_sort_value = get_median_of_sorted_arrays(sorted_numbers)

    print(f"\nCombine arrays: {sorted_numbers}")
    print(f"\nMedian of Two Sorted Arrays {middle_sort_value}")

    print("-- End program Nightmare1.1 --")

if __name__ == '__main__':
    main()

# The overall run time complexity should be O(log (m+n)).
#
# Example 1:
# Input: nums1 = [1,3], nums2 = [2]
# Output: 2.00000
# Explanation: merged array = [1,2,3] and median is 2.
#
# Example 2:
# Input: nums1 = [1,2], nums2 = [3,4]
# Output: 2.50000
# Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
#
# Constraints:
# nums1.length == m
# nums2.length == n
# 0 <= m <= 1000
# 0 <= n <= 1000
# 1 <= m + n <= 2000
# -10**6 <= nums1[i], nums2[i] <= 10**6


import math
a, b, x = map(int, input().split())
def angle(x):
    return math.atan(x) * 180 / math.pi
pre = 2 * (a**2 * b - x) / a**3
pro = a * b * b / x / 2
jd = 2 * x / a**3
if jd > b / a:
    print(angle(pre))
else:
    print(angle(pro))


"""Report the manhattan distance between a starting point and an ending point,
given a set of directions to follow to move between the two points."""

from distance import get_distance
from directions import load_directions, follow_directions

def main():
    directions = load_directions('directions.txt')
    starting_point = (0, 0)
    starting_orientation = 'N'
    ending_point, _ = follow_directions(starting_point, starting_orientation, *directions)
    print(get_distance(starting_point, ending_point))

if __name__ == '__main__':
    main()


"""
Created on Wed May 18 2022

@author: Jake Carter
PiE Homework 1 file 1:
Code for calculating BMI from height and weight inputs from user
"""
import sys

try:
    weightlbs = float(input('Enter weight (lbs): '))
    heightft = float(input('Enter height (ft): '))
except ValueError: # catches any non number inputs
    print('Invalid entry')
    sys.exit(-1)

if weightlbs <= 0 or heightft <= 0:
    print('Invalid weight or height')
    exit(-1)
weightkg = weightlbs * .4536
heightm = heightft * .3048
bmi = weightkg / (heightm ** 2)

print('Weight = {0} lbs = {1} kg,\nHeight = {2} ft = {3} m,\nBMI = {4}'.format(round(weightlbs, 3), round(weightkg,3), round(heightft,3), round(heightm,3), round(bmi,3)))

sys.exit()


#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

##################################################
import sys, time
##################################################
import _rightThumb._construct as __
appDBA=__.clearFocus(__name__,__file__);__.appReg=appDBA;
def focus(parentApp='',childApp='',reg=True):
	global appDBA;f=__.appName(appDBA,parentApp,childApp);
	if reg:__.appReg=f;
	return f
import _rightThumb._base3 as _
fieldSet=_.l.vars(focus(),__name__,__file__,appDBA)
_.load()
##################################################
_v = __.imp('_rightThumb._vars')
_str = __.imp('_rightThumb._string')
##################################################

def sw():
	pass
	#b)--> examples
	_.switches.register( 'Notes', '-n,-note,-notes' )
	_.switches.register( 'Download', '-dl,-download' )
	_.switches.register( 'Search-Notes-Content', '-db,--c,-cnt,-content' )
	_.switches.register( 'Print', '-p,-print' )
	#e)--> examples
	# _.switches.register( 'Files', '-f,-fi,-file,-files','file.txt', isData='glob,name,data,clean', description='Files', isRequired=False )

# __.setting('require-list',['Files,Plus','File,Has']) # todo
# __.setting('require-list',['Pipe','Files'])
__.setting('receipt-log')
__.setting('receipt-file')
__.setting('myFileLocations-skip-validation',False)
__.setting('require-pipe',False)
__.setting('require-pipe||file',False)
__.setting('pre-error',False)
__.setting('switch-raw',[])

_.appInfo[focus()] = {
	# 'app': '8facG-jo0Cxk',
	'file': 'pyJoplin.py',
	'liveAppName': __.thisApp( __file__ ),
	'description': 'Query the LIVE Joplin Desktop Database',
		# _.ail(1,'subject')+
		# _.aib('one')+
	'categories': [
						'DEFAULT',
				],
	'usage': [
						# 'epy another',
						# 'e nmap',
						# '',
	],
	'relatedapps': [
						# 'p another -file file.txt',
						# '',
	],
	'prerequisite': [
						# 'p another -file file.txt',
						# '',
	],
	'examples': [
						_.hp('p pyJoplin  + alexandria -content'),
						_.linePrint(label='simple',p=0),
						'',
	],
	'columns': [
					# { 'name': 'name', 'abbreviation': 'n' },
					# { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
	],
	'aliases': [
					# 'this',
					# 'app',
	],
	'notes': [
					# {},
	],
}

_.appData[focus()] = {
		'start': __.startTime,
		'uuid': '',
		'audit': [],
		'pipe': False,
		'data': {
					'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
					'table': {'sent': [], 'received': [] },
		},
	}

def triggers():
	_.switches.trigger( 'Files', _.myFileLocations, vs=True )
	_.switches.trigger( 'Ago', _.timeAgo )
	_.switches.trigger( 'Folder', _.myFolderLocations )
	_.switches.trigger( 'URL', _.urlTrigger )
	_.switches.trigger( 'Duration', _.timeFuture )

_.l.conf('clean-pipe',True)
_.l.sw.register( triggers, sw )

########################################################################################
#b)--> examples
#d)--> code hints to quickly get started
	#n)--> inline examples
		# any(ele in 'scott5' for ele in list('0123456789'))
		# if _.switches.isActive('Test'): test(); return None;
		# result=[]; result=[ _.pr(line) for i, line, bi in _.numerate( _.isData(r=0) )]
		# bk=[];[  bk.append(rec['backup']) for rec in backupLog if path == rec['file']]; bk=bk[-1];
		# a=(1 if True else 0) <--#
		#!)--> m=[[row[i] for row in matrix] for i in range(4)]

	#n)--> python globals
		# for k in globals(): print(k, eval(k) )

	#n)--> webpage from url
		# for subject in _.caseUnspecific( line, needle ): line = line.replace( subject, _.colorThis( subject, 'green', p=0 ) )

	#n)--> webpage from url
		# requests=__.imp('requests.post')
		#!)--> data=str(requests.post(url,data={}).content,'iso-8859-1')

	#n)--> import and backup example
		# _bk = _.regImp( __.appReg, 'fileBackup' ); _bk.switch( 'Silent' ); _bk.switch( 'isRunOnce' ); _bk.switch( 'Flag', 'APP' ); _bk.switch( 'DoNotSchedule' )
		# _bk.switch( 'Input', path ); bkfi = _bk.action();

	#n)--> inline
		# for rel in [ subject for subject in _.isData(r=0) if _.showLine(subject) ]: print(rel)

	#n)--> banner
		# banner=_.Banner(app); goss=banner.goss;
#e)--> examples
########################################################################################
#n)--> start

def jpage(p): global config; global _type_; return config[_type_].url.replace('[page]',str(p))

def all_data(t='notes'):
	global config
	global index
	global _type_
	_type_ = t
	# _.saveYML(index,'pyJoplin.yml')
	if not _type_ in index:
		index[_type_] = {}
		index[_type_]['parents'] = {}
		index[_type_]['ids'] = {}
		index[_type_]['rev'] = {}
		RECORDS = []
		while not config[_type_].current == config[_type_].max:

			config[_type_].current+=1
			print(_type_, 'page:',config[_type_].current)
			# print(jpage(config[_type_].current))
			page = _.URL( jpage(config[_type_].current) )
			if page == '{"items":[],"has_more":false}':
				config[_type_].max=config[_type_].current
				# _.pr(page,c='red')
			else:
				data = simplejson.loads(page)
				# try:
				# index.table = index.table + data
				for rec in data['items']:
					RECORDS.append(rec)

		# for rec in _.tables.returnSorted( 'RECORDS', 'd.epoch', RECORDS ):
		for rec in _.tables.returnSorted( 'RECORDS', 'title', RECORDS ):
			# print(rec)
			# print(rec['title'])
			if rec['parent_id']:
				if not rec['parent_id'] in index[_type_]['parents']: index[_type_]['parents'][rec['parent_id']] = []
				index[_type_]['parents'][rec['parent_id']].append(rec['id'])
				index[_type_]['ids'][rec['id']] = rec
			else:
				index[_type_]['ids'][rec['id']] = rec
				index['top'].append(rec['id'])
				print('parent:',rec['id'])
		_.saveYML(index,'pyJoplin.yml')
				# except:
				#     pass
				#     print('error')

spent={}

def varDepth(paths):
	var = "['xXx']"
	return var.replace('xXx',"']['".join(paths))

base=''
def _hierarchy(paths):
	global index
	def _hier_(pa):
		global hierarchy
		global base
		xXx = _archy_(pa)
		ex = 'if not "'+xXx[0]+'" in hierarchy'+xXx[1]+': hierarchy'+varDepth(pa)+'={};'
		# print(ex)
		exec(ex)
		# hierarchy
		# print(xXx)
	def _archy_(pa):
		p=pa.copy()
		global hierarchy
		global base
		vd = varDepth(pa)
		ix=p[-1]
		p.pop()
		if not p:
			vx=base
			if not pa[0] in hierarchy:
				# print(base)
				hierarchy[pa[0]]={}
		else:
			vx=varDepth(p)
			# ix=p[-1]
		return ix, vx

	global hierarchy
	# print('bof')
	# print(paths)
	for i,ID in enumerate(paths):
		_.v.IDs[ID]=1
		if _.v.print: _.pr('_.v.IDs[ID]=1',ID,index['folders']['ids'][ID]['title'].strip())
		p=[]
		for ii,iD in enumerate(paths):
			p.append(iD)
			if i==ii: break
		_hier_(p)
	# _hier_(paths)

		# print(vx, ix)
	# print('eof')

def fullpath2(ID):
	paths = fullpath(ID)
	if not ID in paths: paths.append(ID)
	for p in paths: _.v.IDs[p]=1
	names=[]
	for p in paths:
		if p in index['folders']['ids']: names.append(index['folders']['ids'][p]['title'])
		if p in index['notes']['ids']:   names.append(index['notes']['ids'][p]['title'])
	return '  / '.join(names)

def fullpath(ID,r=0):
	global index
	if not r: _.v.path=[]
	_.v.path = [ID] + _.v.path
	# .append(ID)
	try:
		if ID in index['folders']['ids']:
			rec = index['folders']['ids'][ID]
			if rec['parent_id']:
				return fullpath(rec['parent_id'],r=1)
	except Exception as e:
		pass
		# _.e(e)
	if not ID in _.v.path: _.v.path.append(ID)
	for i in _.v.path: _.v.IDs[i]=1
	_hierarchy(_.v.path)
	PATHS=[]
	for p in _.v.path:
		if not p in PATHS: PATHS.append(p)
	return PATHS.copy()

def tabs(cnt):
	cnt-=1
	c=0
	result = ''
	while not c == cnt:
		c+=1
		result += '    '
	return result

def buildChildren(ID):
	global index
	if ID in spent: return None
	spent[ID]=1
	if ID in index['folders']['ids']:
		rec = index['folders']['ids'][ID]
		if not rec['parent_id']: level = 0
		# print( index['folders']['ids'] )
		# print( ID, p, rec['title'] )
		paths = fullpath(ID)
		level = len(paths)
		if 0 and ID == '88903608dadf4da2991c1adb9ed3a8e4':
			print(level,paths)
			# paths.fullpath()
			for i in paths:
				print( tabs(len(fullpath(i))), index['folders']['ids'][i]['title'] )

		# print( ID, level, rec['title'], rec['parent_id'] )
		if False:
			try:
				print(tabs(level),rec['title'].strip(),          ' - ',index['folders']['ids'][rec['parent_id']]['title'].strip(), ID  )
			except Exception as e:
				print(tabs(level),rec['title'].strip()  )
		if ID in index['folders']['parents']:
			for iD in index['folders']['parents']:
				if not iD == ID:
					buildChildren(iD)

hierarchy = {}
_.v.IDs={}
def traverse(dic,r=0):
	if not r: _hierarchy(_.v.path)
	global index
	for k in dic:
		l=len(fullpath(k))
		# if k in _.v.IDs or not _.switches.isActive('Plus'):
		if True:
			if k in index['folders']['ids']: _.pr( l, tabs(l), index['folders']['ids'][k]['title'].strip(), c='cyan' )
			# if k in index['notes']['ids']: _.pr( l, tabs(l), index['notes']['ids'][k]['title'].strip(), c='cyan' )

			# xref = set(list(_.v.IDs.keys())) & set(list(dic[k].keys()))
			# for xr in xref:
			#     if xr in index['notes']['ids']: _.pr( l+1, tabs(l+1), index['notes']['ids'][xr]['title'].strip(), c='darkcyan' )
			#     if xr in index['folders']['ids']: _.pr( l+1, tabs(l+1), index['folders']['ids'][xr]['title'].strip(), c='darkcyan' )

			if _.switches.isActive('Notes'):
				if k in index['notes']['parents']:
					if k in index['notes']['parents']:
						xref = set(list(_.v.IDs.keys())) & set(index['notes']['parents'][k])
						for xr in xref: _.pr( l+1, tabs(l+1), index['notes']['ids'][xr]['title'].strip(), c='darkcyan' )
					# if k in index['folders']['parents']:
					#     xref = set(list(_.v.IDs.keys())) & set(index['folders']['parents'][k])
					#     for xr in xref: _.pr( l+1, tabs(l+1), index['folders']['ids'][xr]['title'].strip(), c='darkcyan' )

					# # print("index['notes']['parents'][k]",index['notes']['parents'][k])
					# for c in index['notes']['parents'][k]:
					#     # if _.showLine(index['notes']['ids'][c]['title']):
					#     if c in _.v.IDs or not _.switches.isActive('Plus'):
					#         _.pr( l+1, tabs(l+1), index['notes']['ids'][c]['title'].strip(), c='darkcyan' )
		traverse(dic[k],r=1)
_.v.print=False
def traverseSearch(dic,r=0):
	global index
	global hierarchy
	if not r: hierarchy={};_.v.IDs={};
	_.v.print=False
	for k in dic:
		if _.showLine(index['folders']['ids'][k]['title']):
			l=len(fullpath(k))
			# _.pr( l, tabs(l), index['folders']['ids'][k]['title'].strip(), c='cyan' )
		if _.switches.isActive('Notes'):
			if k in index['notes']['parents']:
				for c in index['notes']['parents'][k]:
					# if c in index['notes']['ids']:
					if _.showLine(index['notes']['ids'][c]['title']):
						_.v.IDs[c]=1
						fullpath(c)
						# _.pr( l+1, tabs(l+1), index['notes']['ids'][c]['title'].strip(), c='darkcyan' )
		traverseSearch(dic[k],r=1)

def process():
	global hierarchy
	if _.switches.isActive('Plus') or _.switches.isActive('Minus'):
		_.v.IDs={}
		if not _.switches.isActive('Search-Notes-Content'):
			for i in index['folders']['ids']: fullpath(i)
			# _.pv(hierarchy)
			traverseSearch(hierarchy.copy())
		else:
			_.pr(line=1,c='ColorBold.gray')
			queryDB(sql = "SELECT DISTINCT * FROM notes QUERY ")
			_.pr(line=1,c='ColorBold.gray')
			queryDB(sql = "SELECT DISTINCT * FROM folders QUERY ")
	_.pr(line=1,c='ColorBold.gray')
	traverse(hierarchy)
	# print(_.toYML(hierarchy))

def action():
	_.pr(line=1,c='green')
	_.pr(line=1,c='green')
	if _.switches.isActive('Search-Notes-Content'): _.switches.fieldSet( 'Notes', 'active', True )
	# if _.switches.isActive('Search-Notes-Content'): queryDB(); return None;
	load()
	all_data('folders')
	all_data('notes')

	global index

	# for k in index: print(k)
	if not _.switches.isActive('Plus') and not _.switches.isActive('Minus'):
		for i in index['folders']['ids']: fullpath(i)

	# for ID in index['top']: buildChildren(ID)
	process()
	# _.pv(index)
	# _.pr( _.toYML(_.v.IDs), c='green' )

	# _.pv(data)

def load():
	global config
	global index
	if not _.switches.isActive('Download'): index = _.getYML('pyJoplin.yml')
	token = _keychain.imp.key('joplin-token')
	# config['notes'].url = 'http://localhost:41184/notes/?token=[joplin-token]'.replace('[joplin-token]',token)

	config['folders'] = _.dot()
	config['folders'].url = 'http://localhost:41184/folders/?token=[joplin-token]'.replace('[joplin-token]',token)
	config['folders'].current = 0
	config['folders'].max = 2
	config['folders'].max = 13
	config['folders'].direction = 'ASC'
	config['folders'].direction = 'DESC'
	config['folders'].url = config['folders'].url+'&order_by=updated_time&order_dir='+config['folders'].direction+'&limit=100&page=[page]'
	config['notes'] = _.dot()
	config['notes'].url = 'http://localhost:41184/notes/?token=[joplin-token]'.replace('[joplin-token]',token)
	config['notes'].current = 0
	config['notes'].max = 2
	config['notes'].max = 100000
	config['notes'].direction = 'ASC'
	config['notes'].direction = 'DESC'
	config['notes'].url = config['notes'].url+'&order_by=updated_time&order_dir='+config['notes'].direction+'&limit=100&page=[page]'
index = {}
index['top'] = []
config = {}
data = _.dot()
_keychain = _.regImp( __.appReg, 'keychain' )
simplejson = __.imp('simplejson')
_.v.db='C:\\Users\\Scott\\.config\\joplin-desktop\\database.sqlite'
##################################################
#b)--> examples
# banner=_.Banner(dependencies)
# goss=banner.goss
# goss('-\t this app will sherlock tf out of any python app or python module')
#e)--> examples
def fields(t='notes'):
	connection = sqlite3.connect(_.v.db)
	connection.row_factory = sqlite3.Row
	sql = 'SELECT * FROM notes LIMIT 1'.replace('notes',t)
	cursor = connection.execute(sql)
	row = cursor.fetchone()
	names = row.keys()
	return names

import sqlite3
def queryDB(sql = "SELECT DISTINCT * FROM notes QUERY LIMIT 2"):
	while '  ' in sql: sql=sql.replace('  ',' ')
	table=sql.lower().split(' from ')[1].split(' ')[0]

	# sql = 'SELECT id, parend_id FROM notes LIMIT 2'

	y = "(body LIKE '%FIELD%')"
	n = "(body NOT LIKE '%FIELD%')"
	yL=[]
	yL2=[]
	nL=[]
	if table == 'notes':
		for f in _.switches.values('Plus'): yL.append(y.replace('FIELD',f))
		for f in _.switches.values('Minus'): nL.append(y.replace('FIELD',f))
	for f in _.switches.values('Plus'): yL2.append(y.replace('body','title').replace('FIELD',f))
	for f in _.switches.values('Minus'): nL.append(y.replace('body','title').replace('FIELD',f))

	add=[]
	if yL: add.append(' AND '.join(yL))
	if yL2: add.append(' AND '.join(yL2))
	if nL: add.append(' OR '.join(nL))
	if add:
		BOTH = ' ( '+' ) OR ( '.join(add)+ ' ) '
		# print(BOTH)
	else: BOTH=''
	if BOTH: BOTH = ' WHERE '+BOTH
	else: sql=sql.replace('DISTINCT','')
	sql = sql.replace('QUERY',BOTH)
	# print(sql)
	nm = fields(table)
	# ' AND '.join()
	conn = sqlite3.connect(_.v.db)
	c = conn.cursor()
	c.execute(sql)
	records = c.fetchall()
	_.pr(len(records), sql,c='purple')
	for rec in records:
		r={}
		for i,k in enumerate(nm): r[k]=rec[i]
		# _.pr( fullpath(r['parent_id']) )
		fullpath(r['id'])
		fullpath(r['parent_id'])
		_.v.IDs[r['id']]=1
		_.v.IDs[r['parent_id']]=1
		if r['parent_id']: fullpath(r['parent_id'])
		# _.pv(r)
		if _.switches.isActive('Print'):

			_.pr('    ID:',r['id'],c='yellow')
			if fullpath2(r['id']):
				_.pr(' path:',fullpath2(r['id']),c='darkcyan')
			_.pr(' path:',fullpath2(r['parent_id']),c='Background.yellow')
			_.pr(' title:',r['title'],c='Background.blue')
		if not 'body' in r:
			if _.switches.isActive('Print'): _.pr('  type: folder',c='green')
			_.v.IDs[r['id']]=1

		else:
		# if 'body' in r:
			_.v.IDs[r['id']]=1
			if _.showLine(r['body']):
				fullpath(r['parent_id'])
				if _.switches.isActive('Print'):
					body=r['body']
					for item in _.switches.values('Plus'):
						for vVv in _.caseUnspecific(r['body'],item): body=body.replace(vVv,_.pr(vVv,c='green',p=0))
					_.pr('  BODY:',body)

########################################################################################
if __name__ == '__main__':
	#b)--> examples

	# banner.pr()
	# if len(_.switches.all())==0: banner.gossip()

	#e)--> examples
	action()
	_.isExit(__file__)

# buildChildren

# process
# _.v.IDs[
# _.v.IDs=
# len(fullpath

# todo: turn stuff on
# todo: turn stuff on
# todo: turn stuff on
# todo: turn stuff on
# todo: turn stuff on
# todo: turn stuff on


from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Client
from .forms import NewClientForm

def client_list(request):
    clients = Client.objects.filter(added_date__lte=timezone.now()).order_by('added_date')
    return render(request, 'manejoclientes/client_list.html', {'clients': clients})

def client_detail(request, pk):
    client = get_object_or_404(Client, pk=pk)
    return render(request, 'manejoclientes/client_detail.html', {'client': client})

def client_new(request):
	if request.method == "POST":
		form = NewClientForm(request.POST)
		if form.is_valid():
			client = form.save(commit=False)
			#post.author = request.user
			#post.published_date = timezone.now()
			client.save()
			return redirect('manejoclientes.views.client_detail', pk=client.pk)
	else:
		form = NewClientForm()
	return render(request, 'manejoclientes/new_client.html', {'form': form})

def client_edit(request, pk):
        client = get_object_or_404(Client, pk=pk)
        if request.method == "POST":
            form = NewClientForm(request.POST, instance=client)
            if form.is_valid():
                #client = form.save(commit=False)
                client.save()
                return redirect('manejoclientes.views.client_detail', pk=client.pk)
        else:
            form = NewClientForm(instance=client)
        return render(request, 'manejoclientes/new_client.html', {'form': form})


sleeping_rating = 5
ice_cream_rating = 6
first_name = 'Pit'
last_name = 'Christodoulou'
my_name = first_name + ' ' + last_name

happiness_rating = (sleeping_rating + ice_cream_rating) / 2

print("happiness_rating variable type is ", type(happiness_rating), '\n',
      "my_name variable type is ", type(my_name), '\n',
      "ice_cream_rating variable type is ", type(ice_cream_rating), '\n')

print('My name is ' + first_name + ' and I give eating ice cream a score of ' + str(ice_cream_rating) + ' out of 10!')
print('I am ' + my_name + ' and my sleeping enjoyment rating is ' + str(sleeping_rating) + ' / 10!')
print('Based on the factors above, my happiness rating is ' + str(happiness_rating) + ' out of 10, or 85.0 %!')


import numpy as np

def document_generator(a, rho, T, P, N):
    '''
    a, rho: corpus-level parameters
    T: transformation matrix. ntopic * K * dg
    P: success probability for each topics. K*d matrix. Between 0 and 1.
    N: the number of documents.

    output:
    X: N*d, X[i] = document[i]
    Y: Y[i] = label[i]
    G: membership
    U: transformed membership
    '''

    nlabel = len(T) # number of classes
    d = len(P[0]) # dim(x)

    Y = np.random.choice(list(range(nlabel)),N) # labels
    G = np.random.dirichlet(a*rho,N)
    U = np.array([np.dot(T[Y[i]], G[i]) for i in range(N)])

    logitP = np.log(P/(1-P))
    logitX = np.dot(U,logitP)
    PX = 1/(1+np.exp(-logitX))

    X = np.random.binomial(1,PX,(N,d))

    return X, Y, G, U


"""Basic tests for Bayesian quadrature method."""

import numpy as np
import pytest

from probnum import LambdaStoppingCriterion
from probnum.quad.integration_measures import LebesgueMeasure
from probnum.quad.solvers import BayesianQuadrature
from probnum.quad.solvers.belief_updates import BQStandardBeliefUpdate
from probnum.quad.solvers.initial_designs import LatinDesign, MCDesign
from probnum.quad.solvers.policies import (
    MaxAcquisitionPolicy,
    RandomMaxAcquisitionPolicy,
    RandomPolicy,
    VanDerCorputPolicy,
)
from probnum.quad.solvers.stopping_criteria import (
    ImmediateStop,
    IntegralVarianceTolerance,
    MaxNevals,
    RelativeMeanChange,
)
from probnum.randprocs.kernels import ExpQuad
from probnum.randvars import Normal

@pytest.fixture
def input_dim():
    return 3

@pytest.fixture
def data(input_dim):
    def fun(x):
        return 2 * np.ones(x.shape[0])

    nodes = np.ones([5, input_dim])
    fun_evals = fun(nodes)
    return nodes, fun_evals, fun

@pytest.fixture
def bq(input_dim):
    return BayesianQuadrature.from_problem(
        input_dim=input_dim,
        domain=(0, 1),
    )

@pytest.fixture
def bq_no_policy(input_dim):
    return BayesianQuadrature.from_problem(
        input_dim=input_dim,
        domain=(0, 1),
        policy=None,
    )

_all_designs = ["mc", "latin"]
_all_acq_policies = ["us", "ivr", "mi"]

# =======================================
# Tests for '__init__' method start here.
# =======================================

def test_bayesian_quadrature_wrong_input(input_dim):
    """These exceptions are raised in the __init__ method."""
    measure = LebesgueMeasure(domain=(0, 1), input_dim=input_dim)

    # initial design is given but policy is not given
    with pytest.raises(ValueError):
        BayesianQuadrature(
            kernel=ExpQuad(input_shape=(input_dim,)),
            measure=measure,
            policy=None,
            belief_update=BQStandardBeliefUpdate(jitter=1e-6, scale_estimation=None),
            stopping_criterion=MaxNevals(max_nevals=10),
            initial_design=MCDesign(n_nodes=3, measure=measure),
        )

# ===========================================
# Tests for 'from_problem' method start here.
# ===========================================

# Tests for correct assignments start here.

@pytest.mark.parametrize(
    "policy, policy_type",
    [
        ("bmc", RandomPolicy),
        ("vdc", VanDerCorputPolicy),
        ("us_rand", RandomMaxAcquisitionPolicy),
        ("mi_rand", RandomMaxAcquisitionPolicy),
        ("ivr_rand", RandomMaxAcquisitionPolicy),
        ("us", MaxAcquisitionPolicy),
        ("mi", MaxAcquisitionPolicy),
        ("ivr", MaxAcquisitionPolicy),
    ],
)
def test_bq_from_problem_policy_assignment(policy, policy_type):
    """Test if correct policy is assigned from string identifier."""
    bq = BayesianQuadrature.from_problem(input_dim=1, domain=(0, 1), policy=policy)
    assert isinstance(bq.policy, policy_type)

@pytest.mark.parametrize(
    "design, design_type", [("mc", MCDesign), ("latin", LatinDesign)]
)
def test_bq_from_problem_initial_design_assignment(design, design_type):
    """Test if correct initial design is assigned from string identifier."""
    bq = BayesianQuadrature.from_problem(
        input_dim=1, domain=(0, 1), initial_design=design
    )
    assert isinstance(bq.initial_design, design_type)

@pytest.mark.parametrize(
    "max_evals, var_tol, rel_tol, t",
    [
        (None, None, None, LambdaStoppingCriterion),
        (1000, None, None, MaxNevals),
        (None, 1e-5, None, IntegralVarianceTolerance),
        (None, None, 1e-5, RelativeMeanChange),
        (None, 1e-5, 1e-5, LambdaStoppingCriterion),
        (1000, None, 1e-5, LambdaStoppingCriterion),
        (1000, 1e-5, None, LambdaStoppingCriterion),
        (1000, 1e-5, 1e-5, LambdaStoppingCriterion),
    ],
)
def test_bq_from_problem_stopping_criterion_assignment(max_evals, var_tol, rel_tol, t):
    """Test if correct stopping criterion is assigned from input parameters."""
    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
        options=dict(max_evals=max_evals, var_tol=var_tol, rel_tol=rel_tol),
    )
    assert isinstance(bq.stopping_criterion, t)

def test_bq_from_problem_default_attribute_types(bq, bq_no_policy):
    """Test if default are sets correctly (using the default options dict)."""

    # defaults if policy is available
    assert isinstance(bq.measure, LebesgueMeasure)
    assert isinstance(bq.kernel, ExpQuad)
    assert isinstance(bq.stopping_criterion, LambdaStoppingCriterion)
    assert isinstance(bq.policy, RandomPolicy)
    assert bq.initial_design is None

    # defaults if no policy is available
    assert isinstance(bq_no_policy.measure, LebesgueMeasure)
    assert isinstance(bq_no_policy.kernel, ExpQuad)
    assert isinstance(bq_no_policy.stopping_criterion, ImmediateStop)
    assert bq_no_policy.policy is None
    assert bq_no_policy.initial_design is None

def test_bq_from_problem_options_values_default():
    """Test if default values of the options dictionary are set correctly."""

    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
    )

    # batch_size default
    assert bq.policy.batch_size == 1

    # jitter default
    assert bq.belief_update.jitter == 1e-8

def test_bq_from_problem_options_values_custom():
    """Test if custom values of the options dictionary are set correctly
    (apart from design and policy options)."""

    # batch_size manual value
    batch_size = 3
    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
        options=dict(batch_size=batch_size),
    )
    assert bq.policy.batch_size == batch_size

    # jitter manual value
    jitter = 1.3
    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
        options=dict(jitter=jitter),
    )
    assert bq.belief_update.jitter == jitter

@pytest.mark.parametrize("design", _all_designs)
def test_bq_from_problem_options_design_values_default(design):
    """Test if default values in options dict related to design are set correctly."""
    input_dim = 5
    bq = BayesianQuadrature.from_problem(
        input_dim=input_dim,
        domain=(0, 1),
        initial_design=design,
    )
    assert bq.initial_design.n_nodes == int(5 * input_dim)

@pytest.mark.parametrize("design", _all_designs)
def test_bq_from_problem_options_design_values_custom(design):
    """Test if custom values in options dict related to design are set correctly."""
    input_dim = 5
    n_initial_design_nodes = 3
    assert int(input_dim * 5) != n_initial_design_nodes  # since this is the default
    bq = BayesianQuadrature.from_problem(
        input_dim=input_dim,
        domain=(0, 1),
        initial_design=design,
        options=dict(n_initial_design_nodes=n_initial_design_nodes),
    )
    assert bq.initial_design.n_nodes == n_initial_design_nodes

@pytest.mark.parametrize("policy", _all_acq_policies)
def test_bq_from_problem_options_policy_values_default(policy):
    """Test if default values in options dict related to policies are set correctly."""
    # n_candidates
    bq = BayesianQuadrature.from_problem(
        input_dim=2, domain=(0, 1), policy=policy + "_rand"
    )
    assert bq.policy.n_candidates == int(1e2)

    # n_restarts
    bq = BayesianQuadrature.from_problem(input_dim=2, domain=(0, 1), policy=policy)
    assert bq.policy.n_restarts == int(10)

@pytest.mark.parametrize("policy", _all_acq_policies)
def test_bq_from_problem_options_policy_values_custom(policy):
    """Test if custom values in options dict related to policies are set correctly."""
    # n_candidates for random policies
    n_candidates = 5
    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
        policy=policy + "_rand",
        options=dict(n_candidates=n_candidates),
    )
    assert bq.policy.n_candidates == n_candidates

    # n_restarts for policies with optimizers
    n_restarts = 5
    bq = BayesianQuadrature.from_problem(
        input_dim=2,
        domain=(0, 1),
        policy="us",
        options=dict(n_restarts=n_restarts),
    )
    assert bq.policy.n_restarts == n_restarts

# Tests for input checks and exception raises start here.

def test_bq_from_problem_wrong_inputs(input_dim):
    """Exceptions raised in from-problem classmethod."""
    # neither measure nor domain is provided
    with pytest.raises(ValueError):
        BayesianQuadrature.from_problem(input_dim=input_dim)

    # unknown policy is provided
    with pytest.raises(NotImplementedError):
        BayesianQuadrature.from_problem(
            input_dim=input_dim, domain=(0, 1), policy="unknown_policy"
        )

    # unknown initial_design is provided
    with pytest.raises(NotImplementedError):
        BayesianQuadrature.from_problem(
            input_dim=input_dim,
            domain=(0, 1),
            policy="bmc",
            initial_design="unknown_design",
        )

# ========================================
# Tests for 'integrate' method start here.
# ========================================

@pytest.mark.parametrize("initial_design_provided", [True, False])
@pytest.mark.parametrize("nodes_provided", [True, False])
def test_integrate_output_shapes(initial_design_provided, nodes_provided, data, rng):
    # the test uses max_evals stopping condition in order to check the shapes
    # consistently.

    max_evals = 15
    n_design_nodes = 4

    # get data
    nodes, fun_evals, fun = data
    (n_nodes, input_dim) = nodes.shape

    params = dict(input_dim=input_dim, domain=(0, 1))
    options = dict(max_evals=max_evals)
    n_updates = max_evals

    # get correct shapes and values
    if nodes_provided:
        n_updates += -n_nodes + 1
    else:
        nodes, fun_evals = None, None

    if initial_design_provided:
        n_updates += -n_design_nodes + (1 - 1 * nodes_provided) * 1
        params["initial_design"] = "mc"
        options["n_initial_design_nodes"] = n_design_nodes

    assert n_updates > 1  # make sure that some nodes are collected

    bq = BayesianQuadrature.from_problem(**params, options=options)
    res, bq_state, info = bq.integrate(
        fun=fun, nodes=nodes, fun_evals=fun_evals, rng=rng
    )
    assert isinstance(res, Normal)
    assert isinstance(bq_state.integral_belief, Normal)
    assert isinstance(bq_state.scale_sq, float)
    assert len(bq_state.kernel_means) == max_evals
    assert len(bq_state.previous_integral_beliefs) == n_updates
    assert bq_state.nodes.shape == (max_evals, input_dim)
    assert bq_state.fun_evals.shape == (max_evals,)
    assert bq_state.gram.shape == (max_evals, max_evals)

# Tests for 'integrate' input checks and exception raises start here.

def test_integrate_wrong_input(bq, data, rng):
    """Exception tests shared by all bq methods."""
    # The combination of inputs below is important to trigger the correct exception.

    nodes, fun_evals, fun = data

    # no integrand provided (neither fun nor fun_evals)
    with pytest.raises(ValueError):
        bq.integrate(fun=None, nodes=nodes, fun_evals=None, rng=rng)

    # wrong fun_evals shape
    with pytest.raises(ValueError):
        bq.integrate(fun=fun, nodes=nodes, fun_evals=fun_evals[:, None], rng=rng)

    # wrong nodes shape
    with pytest.raises(ValueError):
        bq.integrate(fun=fun, nodes=nodes[:, None], fun_evals=None, rng=rng)

    # number of points in nodes and fun_evals do not match
    wrong_nodes = np.vstack([nodes, np.ones([1, nodes.shape[1]])])
    with pytest.raises(ValueError):
        bq.integrate(fun=fun, nodes=wrong_nodes, fun_evals=fun_evals, rng=rng)

def test_integrate_with_policy_wrong_input(bq, data, rng):
    """Exception tests specific to when a policy is given."""
    # The combination of inputs below is important to trigger the correct exception.

    nodes, fun_evals, fun = data

    # a policy always requires fun
    with pytest.raises(ValueError):
        bq.integrate(fun=None, nodes=nodes, fun_evals=fun_evals, rng=rng)

    # no rng provided but policy requires it
    with pytest.raises(ValueError):
        bq.integrate(fun=fun, nodes=None, fun_evals=None, rng=None)

def test_integrate_no_policy_wrong_input(bq_no_policy, data):
    """Exception tests specific to when no policy is given."""
    # The combination of inputs below is important to trigger the correct exception.

    nodes, fun_evals, fun = data

    # no nodes provided
    with pytest.raises(ValueError):
        bq_no_policy.integrate(fun=None, nodes=None, fun_evals=fun_evals)

    # fun is ignored if fun_evals are given
    with pytest.warns(Warning):
        bq_no_policy.integrate(fun=fun, nodes=nodes, fun_evals=fun_evals)

def test_integrate_initial_design_wrong_input(rng):
    """Exception tests specific to when an initial design is given."""
    # The combination of inputs below is important to trigger the correct exception.

    # no rng provided but initial design requires it (and policy does not)
    with pytest.raises(ValueError):
        bq = BayesianQuadrature.from_problem(
            input_dim=1,
            domain=(0, 1),
            policy="vdc",  # does not need rng
            initial_design="mc",  # needs rng
        )
        bq.integrate(
            fun=lambda x: np.ones(x.shape[0]), nodes=None, fun_evals=None, rng=None
        )


from __future__ import absolute_import
from __future__ import unicode_literals

import io
import ntpath
import os
import shutil
import unittest

import ftputil
import ftputil.sync

# Assume the test subdirectories are or will be in the current directory.
TEST_ROOT = os.getcwd()

class TestLocalToLocal(unittest.TestCase):

    def setUp(self):
        if not os.path.exists("test_empty"):
            os.mkdir("test_empty")
        if os.path.exists("test_target"):
            shutil.rmtree("test_target")
        os.mkdir("test_target")

    def test_sync_empty_dir(self):
        source = ftputil.sync.LocalHost()
        target = ftputil.sync.LocalHost()
        syncer = ftputil.sync.Syncer(source, target)
        source_dir = os.path.join(TEST_ROOT, "test_empty")
        target_dir = os.path.join(TEST_ROOT, "test_target")
        syncer.sync(source_dir, target_dir)

    def test_source_with_and_target_without_slash(self):
        source = ftputil.sync.LocalHost()
        target = ftputil.sync.LocalHost()
        syncer = ftputil.sync.Syncer(source, target)
        source_dir = os.path.join(TEST_ROOT, "test_source/")
        target_dir = os.path.join(TEST_ROOT, "test_target")
        syncer.sync(source_dir, target_dir)

# Helper classes for `TestUploadFromWindows`

class LocalWindowsHost(ftputil.sync.LocalHost):

    def __init__(self):
        self.path = ntpath
        self.sep = "\\"

    def open(self, path, mode):
        # Just return a dummy file object.
        return io.StringIO("")

    def walk(self, root):
        """
        Return a list of tuples as `os.walk`, but use tuples as if the
        directory structure was

        <root>
            dir1
                dir11
                file1
                file2

        where <root> is the string passed in as `root`.
        """
        join = ntpath.join
        return [(root,
                 [join(root, "dir1")],
                 []),
                (join(root, "dir1"),
                 ["dir11"],
                 ["file1", "file2"])
                ]

class DummyFTPSession(object):

    def pwd(self):
        return "/"

class DummyFTPPath(object):

    def abspath(self, path):
        # Don't care here if the path is absolute or not.
        return path

    def isdir(self, path):
        return ("dir" in path)

    def isfile(self, path):
        return ("file" in path)

class ArgumentCheckingFTPHost(ftputil.FTPHost):

    def __init__(self, *args, **kwargs):
        super(ArgumentCheckingFTPHost, self).__init__(*args, **kwargs)
        self.path = DummyFTPPath()

    def _make_session(self, *args, **kwargs):
        return DummyFTPSession()

    def mkdir(self, path):
        assert "\\" not in path

    def open(self, path, mode):
        assert "\\" not in path
        return io.StringIO("")

class TestUploadFromWindows(unittest.TestCase):

    def test_no_mixed_separators(self):
        source = LocalWindowsHost()
        target = ArgumentCheckingFTPHost()
        local_root = ntpath.join("some", "directory")
        syncer = ftputil.sync.Syncer(source, target)
        # If the following call raises any `AssertionError`s, the
        # `unittest` framework will catch them and show them.
        syncer.sync(local_root, "not_used_by_ArgumentCheckingFTPHost")

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


#Głodna żaba
#minimalna liczba skoków

def zaba(T, i, j):
    if i >= len(T) - 1:
        return 0
    mini = float('inf')
    j += T[i]
    for k in range(1, j+1):
        tmp = zaba(T, i+k, j-k)
        if tmp < mini:
            mini = tmp
    return mini + 1

T = [3,0,2,1,0,2,5,0]
print(zaba(T, 0, 0))


import numpy as np

# numpy构建神经网络
# N为训练数据个数，D_in为输入层大小，H为隐藏层大小，D_out为输出层大小
# 我们定义一个输入层为1000维向量，隐藏层为100个神经元，输出层层10个神经元的神经网络
batch_size, D_in, H, D_out =64, 1000, 100, 10

# 随机创建训练数据
x = np.random.randn(D_in, batch_size)
y = np.random.randn(D_out, batch_size)

# 根据我们的模型，包含2个权重层，分别为100个神经元的隐藏层和10个神经元的输出层
w1 = np.random.randn(H, D_in) # 隐藏层
w2 = np.random.randn(D_out, H) # 输出层

lr = 1e-4
for t in range(3000):
    # 进行前向传播
    h = w1.dot(x) # 输出数据传入隐藏层
    h_sigmod = 1 / (1 + np.exp(-h))
    y_pred = w2.dot(h_sigmod) # 隐藏层输出的数据进入输出层

    # 计算损失函数
    loss = np.square(y_pred - y).sum()
    print("\r epoch={} loss={}".format(t, loss), end=' ')

    # 反向传播
    grad_y_pred = 2.0 * (y_pred - y) # 首先Loss对输出数据求导，这个结果将是输出层的上游梯度,对应于公式的 2q

    grad_w2 = grad_y_pred.dot(h.T) # 这里计算Loss对输出层w2的偏导数，上游梯度为grad_y_pred，local gradient为h，对应于公式的2qx^T

    # 为了计计算Loss对w1的偏导数，W1*x中的本地偏导数很容易得到是X^T，但是还需要求得上一层传播过来的上游偏导数
    grad_sigmod = w2.T.dot(grad_y_pred) #

    #
    grad_h = grad_sigmod*(h_sigmod*(1-h_sigmod))

    grad_w1 = grad_h.dot(x.T) # 最后计算Loss对隐藏层w1的偏导数，上游梯度为grad_h，，local gradient为x，对应于公式的2qx^T

    # 执行梯度下降
    w1 -= lr * grad_w1
    w2 -= lr * grad_w2


import scipy.optimize as opt #高级优化函数的包
import lrCostFunction as lCF
from sigmoid import *

#定义一个优化函数 实际上调用的是Python内置的高级优化函数
#可以把它想象成梯度下降法 但是不用手动设置学习率
''' fmin_cg优化函数 第一个参数是计算代价的函数 第二个参数是计算梯度的函数 参数x0传入初始化的theta值
    args传入训练样本的输入特征矩阵X,对应的2分类新标签y,正则化惩罚项系数lmd
    maxiter设置最大迭代优化次数
'''
def optimizeTheta(theta,X,y,lmd):
    res=opt.fmin_cg(lCF.Compute_cost,fprime=lCF.Compute_grad,x0=theta,\
                    args=(X,y,lmd),maxiter=50,disp=False,full_output=True)
    return res[0],res[1]

def one_vs_all(X, y, num_labels, lmd):

    (m, n) = X.shape #m为训练样本数  n为原始输入特征数

    '''
    逻辑回归多分类器的训练过程：
    用逻辑回归做多分类 相当于做多次2分类 每一次把其中一个类别当作正类 其余全是负类
    手写数字识别是10分类 需要做十次2分类
    比如：第一次把数字0当作正类 设置新的标签为1  数字1-9为负类  设置新的标签是0 进行2分类
         第一次把数字1当作正类 设置新的标签为1  数字2-9和0为负类  设置新的标签是0 进行2分类
         以此类推

    '''
    all_theta = np.zeros((num_labels, n + 1)) #存放十次2分类的 最优化参数
    initial_theta=np.zeros(n+1)   #每一次2分类的初始化参数值

    X = np.c_[np.ones(m), X]  #添加一列特征 值为1

    for i in range(num_labels):
        print('Optimizing for handwritten number {}...'.format(i))
        iclass=i if i else 10 #数字0 属于第十个类别
        logic_Y=np.array([1 if x==iclass else 0 for x in y]) #设置每次2分类的新标签
        itheta,imincost=optimizeTheta(initial_theta,X,logic_Y,lmd)
        all_theta[i,:]=itheta
    print('Done')

    return all_theta #返回十次2分类的 最优化参数


import math
marks = []

print("Program to find ODD or EVEN")
input_count = int(input("How many numbers you WANT to check? "))

for i in range(0, input_count):
    num = int(input("Enter a num: "))
    marks.append(num)
    # You can use marks.insert which keeps the number in the front

for m in marks:
    if m % 2 == 0:
        print(m, " Is even num")
    else:
        print(m, " Is ODD num")


import pandas as pd

char_map = {'Alef' : ')',
            'Ayin' : '(',
            'Bet' : 'b',
            'Dalet' : 'd',
            'Gimel' : 'g',
            'He' : 'x',
            'Het' : 'h',
            'Kaf' : 'k',
            'Kaf-final' : '\\',
            'Lamed' : 'l',
            'Mem' : '{',
            'Mem-medial' : 'm',
            'Nun-final' : '}',
            'Nun-medial' : 'n',
            'Pe' : 'p',
            'Pe-final' : 'v',
            'Qof' : 'q',
            'Resh' : 'r',
            'Samekh' : 's',
            'Shin' : '$',
            'Taw' : 't',
            'Tet' : '+',
            'Tsadi-final' : 'j',
            'Tsadi-medial' : 'c',
            'Waw' : 'w',
            'Yod' : 'y',
            'Zayin' : 'z'}

#gives back dictionary for all ngrams of length length_n_grams
#where every ngram will get start_freqs added to amount times seens
def count_ngrams(length_n_grams, start_freqs):

    def make_combinations(l1,l2):
        combinations = []
        for x in l1:
            for y in l2:
                if isinstance(x, (list,)):
                    combinations.append(x + [y])
                else:
                    combinations.append([x,y])
        return combinations

    all_letters = []
    for x in char_map:
        all_letters.append(x)

    #read in excelsheet with ngrams
    data_df = pd.read_excel("ngrams_frequencies_withNames.xlsx")
    data_list = data_df.values.tolist()

    #make datalist with right char_map words
    count_sequences = []
    count = [0,0,0,0,0,0,0,0,0,0,0,0]
    for r in data_list:
        new_sequence = []
        letters = r[1].split("_")
        count[len(letters)] += 1
        for l in letters:
            if l == "Tasdi-final":
                l = "Tsadi-final"
            if l == "Tsadi":
                l = "Tsadi-medial"
            new_sequence.append(l)
        new_sequence.reverse()
        count_sequences.append((new_sequence,r[2]))

    #make a list of all possible sequences
    combos = all_letters
    for k in range(length_n_grams - 1):
        combos2 = make_combinations(combos,all_letters)
        combos = combos2
    all_sequences = ["_".join(c) for c in combos]

    #make dict for recording frequencies
    freqs = dict()
    for c in all_sequences:
        freqs[c] = start_freqs

    # For each word in the data
    # for each sequence of n length in word
    # add the amount to sequence of word seen
    for s,c in count_sequences[100:200]:
        if len(s) >= length_n_grams:
            b = 0
            e = length_n_grams
            for p in range(len(s) - length_n_grams + 1):
                current_gram = s[b:e]
                word_gram = "_".join(current_gram)
                freqs[word_gram] += c
                b += 1
                e += 1

    return freqs


import numpy as np
from skimage import data
from skimage import novice
from skimage.novice import Picture
from skimage import data_dir

img = novice.open('noise50.png')
px = img[10,50]
print (px)

width = img.width
heigth = img.height
for n in range(width):
	for n2 in range(heigth):
		b = 0.07 * int(img[n, n2].blue)
		g = 0.72 * int(img[n, n2].green)
		r = 0.21 * int(img[n, n2].red)
		aux = (g+b+r)
		img[n, n2] = (aux,aux,aux)

#filtros lineares Convulação *
matrizX = [[1,0,-1],[2,0,-2],[1,0,1]]
matrizY = [[1,2,1],[0,0,0],[-1,-2,-1]]

div = 0
novaimagem = np.zeros(shape=(width, heigth, 3), dtype=np.uint8)
pad = (len(matrizX)-1)/2

for n in range(width-len(matrizX)):
	for n2 in range(heigth-len(matrizX)):
		somatorioBX = 0
		somatorioGX = 0
		somatorioRX = 0
		somatorioBY = 0
		somatorioGY = 0
		somatorioRY = 0
		bX = 0
		gX = 0
		rX = 0
		bY = 0
		gY = 0
		rY = 0
		divY = 0
		divX = 0

		for x in range(len(matrizX)):
			for y in range(len(matrizX)):
				#blue
				Xpos = n+x-pad
				Ypos = n2+y-pad
				if(Xpos >= 0 and Xpos < heigth and Ypos >= 0 and Ypos < width):
					bX += int(img[n+x, n2+y].blue) * matrizX[x][y]
					gX += int(img[n+x, n2+y].green) * matrizX[x][y]
					rX += int(img[n+x,n2+y].red) * matrizX[x][y]

					bY += int(img[n+x, n2+y].blue) * matrizY[x][y]
					gY += int(img[n+x, n2+y].green) * matrizY[x][y]
					rY += int(img[n+x,n2+y].red) * matrizY[x][y]

					divX += matrizX[x][y]
					divY += matrizY[x][y]

		if(divX ==0): divX = 1
		if(divY ==0): divY = 1
		somatorioBX = bX/divX
		somatorioGX = gX/divX
		somatorioRX = rX/divX

		somatorioBY = bX/divY
		somatorioGY = gX/divY
		somatorioRY = rX/divY

		GRX = (somatorioBX**2 + somatorioBY**2)
		GGX = (somatorioGX**2 + somatorioGY**2)
		GBX = (somatorioRX**2 + somatorioRY**2)

		GRX = GRX **(1/2)
		GGX = GGX **(1/2)
		GBX = GBX **(1/2)

		if(GRX > 255):
			GRX = 255

		if(GRX <0):
			GRX = 0

		if(GGX > 255):
			GGX = 255
		if(GGX <0):
			GGX = 0

		if(GBX > 255):
			GBX = 255
		if(GBX <0):
			GBX = 0

		novaimagem[n, n2] = (GRX, GGX, GBX)

novaimagem = Picture(array=novaimagem)
novaimagem.show()


#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##

# import os
import sys
import time
# import simplejson as json
# from threading import Timer

##################################################
# construct registration

import _rightThumb._construct as __
appDBA = __.clearFocus( __name__, __file__ )
# appDBA = __name__
__.appReg = appDBA
def focus( parentApp='', childApp='', reg=True ):
	global appDBA
	f = __.appName( appDBA, parentApp, childApp )
	if reg:
		__.appReg = f
	return f
__.registeredApps.append(focus())

import _rightThumb._base3 as _
_.load()

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

import _rightThumb._vars as _v
import _rightThumb._string as _str
# import _rightThumb._encryptString as _blowfish
# import _rightThumb._date as _date
# import _rightThumb._dir as _dir
# import _rightThumb._md5 as _md5
# import _rightThumb._mimetype as _mime

# import _rightThumb._backupLog as _bkLog
# _bkLog = _.regImp( __.appReg, '_rightThumb._backupLog' )

# import _rightThumb._auditCodeBase as _code
# _code = _.regImp( __.appReg, '_rightThumb._auditCodeBase' )
# _omit = _.regImp( __.appReg, 'omitTable' )
	# _omit.imp.inTable( 'the' )
# _inDic = _.regImp( __.appReg, 'inDic' )
	# _inDic.switch( 'All' )
	# _inDic.imp.testAll( 'fight' )
	# _inDic.imp.testOne( 'austen' )

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

# from lxml import html
# import requests
# import cssselect
# import sqlite3

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

def appSwitches():
	_.switches.register('Input', '-i,-code','family.talk.structure.attribute.set( {n,t,t} );')

_.appInfo[focus()] = {
	'file': 'genCodeLine.py',
	'description': 'Generate Code',
	'categories': [
						'tool',
						'code',
						'generate'
				],
	'relatedapps': [],
	'prerequisite': [],
	'examples': [],
	'columns': [],
	}

_.appData[focus()] = {
	'start': time.time(),
	'uuid': '',
	'audit': [],
	'pipe': [],
	}

_.appInfo[focus()]['examples'].append('type %tmpf0% | p genCodeLine -code "family.talk.structure.attribute.set( {n,t,t} );"')

# _.appInfo[focus()]['columns'].append({'name': 'name', 'abbreviation': 'n'})

def registerSwitches( argvProcessForce=False ):
	global appDBA
	if not __.appReg == appDBA and appDBA in __.appReg:

		if not __name__ == '__main__':
			_.argvProcess = argvProcessForce
		else:
			_.argvProcess = True

		_.load()
		_.appInfo[__.appReg] = _.appInfo[appDBA]
		_.appData[__.appReg] = _.appData[appDBA]
	__.constructRegistration(_.appInfo[__.appReg]['file'],__.appReg)
	appSwitches()

	# _.switches.trigger('Input',_.myFileLocations)
		# trigger settings
	_.myFileLocation_Print = False

	# _.switches.trigger('Watched', _.txt2Date)
	# _.switches.trigger('Input',_.formatColumns)

	_.defaultScriptTriggers()
	_.switches.process()

if not __name__ == '__main__':
	_.argvProcess = False
else:
	_.argvProcess = True

registerSwitches()

def fieldSet( switchName, switchField, switchValue, theFocus=False ):
	if not type( theFocus ) == bool:
		theFocus = theFocus
	_.switches.fieldSet( switchName, switchField, switchValue, theFocus )

_.appData[__.appReg]['pipe'] = False
if __name__ == '__main__':
	if not sys.stdin.isatty():
		_.setPipeData( sys.stdin.readlines(), __.appReg )

########################################################################################
# data = _.tables.returnSorted( 'data', 'd.timestamp', data )
# _.switches.fieldSet( 'Long', 'active', True )
# _.tables.register( 'data', table )
# _.tables.print( 'data', 'name' )
########################################################################################
# START

def action():
	if _.switches.isActive('Input'):
		codeRaw = _.switches.value('Input')
		if not '{' in codeRaw:
			_.pr( 'Error: expected' )
			_.pr( '\t"family.talk.structure.attribute.set( {n,t,t} );"' )
			sys.exit()
		start = codeRaw.split( '{' )[0]
		end = codeRaw.split( '}' )[1]
		formatingX = codeRaw.split( '{' )[1].split( '}' )[0]
		formating = formatingX.split( ',' )

		if not type( _.appData[__.appReg]['pipe'] ) == bool:
			for i,row in enumerate(_.appData[__.appReg]['pipe']):
				if len( row ):
					data = []
					delim = '\t'
					if delim in row:
						row = _str.cleanBE( row, delim )
						data = row.split( delim )
					delim = ','
					if delim in row:
						row = _str.cleanBE( row, delim )
						data = row.split( delim )

					result = start
					for ii,x in enumerate(data):
						if  'n' in formating[ii].lower():
							result += x + ', '
						else:
							result += "'" + x + "'" + ', '

					result = _str.cleanBE( result, ', ' )
					result += end
					_.pr( result )

########################################################################################
if __name__ == '__main__':
	action()


from dataclasses import dataclass
from modelo.recursos import Database

@dataclass
class CategoriaEgresoDTO:
    nombre: str
    descripcion: str
    id: int = None

class NombreError(Exception):
    def __str__(self):
        return "Nombre invalido"

class CategoriaUsoError(Exception):
    def __str__(self):
        return "Error, categoria/s en uso"

class ServiceCategoriaEgreso:
    def __init__(self):
        self.database = Database.get()
        self.cursor = self.database.cursor()

    def registrar_cat_egreso(self, data: CategoriaEgresoDTO):
        if data.nombre == "":
            raise NombreError
        self.cursor.execute(
            "INSERT INTO categorias_egreso (id, nombre, descripcion) VALUES (%s, %s, %s)",
            (data.id, data.nombre, data.descripcion),
        )
        self.database.commit()

    def editar_cat_egreso(self, data: CategoriaEgresoDTO):
        if data.nombre == "":
            raise NombreError
        self.cursor.execute(
            "UPDATE categorias_egreso SET nombre=%s, descripcion=%s WHERE id = %s",
            (data.nombre, data.descripcion, data.id),
        )
        self.database.commit()

    def eliminar_cat_egreso(self, data: CategoriaEgresoDTO):
        try:
            self.cursor.execute("DELETE FROM categorias_egreso WHERE id = %s", data.id)
            self.database.commit()
        except pymysql.Error:
            raise CategoriaUsoError

    def obtener_cat_egreso(self):
        self.cursor.execute("SELECT id, nombre, descripcion FROM categorias_egreso")
        return [
            CategoriaEgresoDTO(
                categoria["nombre"], categoria["descripcion"], categoria["id"]
            )
            for categoria in self.cursor.fetchall()
        ]


# _*_coding:utf-8_*_
# created by Alex Li on 11/5/17

import random
from cal_time import *
import copy
import sys

sys.setrecursionlimit(100000)

@cal_time
def bubble_sort(li):
    for i in range(len(li)-1):  #第i趟
        exchange = False
        for j in range(len(li)-i-1):
            if li[j] > li[j+1]:
                li[j], li[j+1] = li[j+1], li[j]
                exchange = True
        if not exchange:
            return

def partition(li, left, right):
    tmp = li[left]
    while left < right:
        while left < right and li[right] >= tmp: #从右面找比tmp小的数
            right -= 1      # 往左走一步
        li[left] = li[right] #把右边的值写到左边空位上
        # print(li, 'right')
        while left < right and li[left] <= tmp:
            left += 1
        li[right] = li[left] #把左边的值写到右边空位上
        # print(li, 'left')
    li[left] = tmp      # 把tmp归位
    return left

def _quick_sort(li, left, right):
    if left<right:  # 至少两个元素
        mid = partition(li, left, right)
        _quick_sort(li, left, mid-1)
        _quick_sort(li, mid+1, right)

@cal_time
def quick_sort(li):
    _quick_sort(li, 0, len(li)-1)

li = list(range(10000, 0, -1))
random.shuffle(li)
#
# li1 = copy.deepcopy(li)
# li2 = copy.deepcopy(li)
#
quick_sort(li)
# bubble_sort(li2)
#
# print(li1)
# print(li2)

# li = [9,8,7,6,5,4,3,2,1]
# partition(li, 0, len(li)-1)
# print(li)

10企业应用及面试/1-算法&设计模式/算法/算法入门/查找排序/quick_sort.py


from Player import Player
from Deck import Deck
from Card import Card

class Game:
    def __init__(self):
        name1=input("プレイヤー1の名前を入力:")
        name2=input("プレイヤー2の名前を入力:")
        self.deck = Deck()
        self.p1=Player(name1)
        self.p2=Player(name2)

    def print_wins(self,winner):
        """
        買ったやつを出力
        """
        print("\n")
        print("このラウンドは{}が勝ち".format(winner))

    def print_draw(self,p1name,p1card,p2name,p2card):
        """
        誰が何を引いたかを出力
        """
        print("\n")
        print("{}は{}を引き、{}は{}を引きました".format(p1name,p1card,p2name,p2card))

    def result(self,p1,p2):
        """
        play_gameメソッドで使う
        """
        if p1.win > p2.win:
            return p1.name
        if p1.win < p2.win:
            return p2.name
        else:
            return "引き分け"
    def play_game(self):
        """
        ここで前の3つのメソッドを使う
        """
        cards=self.deck.cards #これはリスト,単にwhileの条件で使う
        print("戦争を始めます")
        while len(cards) >= 2:
            response = input("qで終了、それ以外でplay")
            if response == "q":
                break
            p1_draw = self.deck.draw_card()
            p2_draw = self.deck.draw_card()
            self.print_draw(self.p1.name,p1_draw,self.p2.name,p2_draw)
            if p1_draw > p2_draw:
                self.p1.win += 1
                self.print_wins(self.p1.name)
            else:
                self.p2.win += 1
                self.print_wins(self.p2.name)

        r=self.result(self.p1,self.p2)

        print("ゲーム終了、{}の勝ち!".format(r))


# -*- coding: utf-8 -*-
"""Tensorflow interface functions.

Author: Bohdan Starosta
University of Strathclyde Physics Department
"""

import logging
import numpy as np
import tensorflow as tf

import displot.models as models
import displot.weights as weights

log = logging.getLogger('displot')

def predict(X, model_id, weights_id):
    """Output predictions for input samples using selected trained model.

    Args:
        X (numpy.ndarray): Input data to use for predictions.
        model_id (str): Model identifier in string format.
        weights_id (tuple): Weights file identifier in tuple of strings format.
            The tuple should be of the form: (model_id, iteration_id).

    Returns:
        numpy.ndarray: Predictions.

    """
    model = models.load_model(model_id)
    model_nn = weights.load_weights(weights_id[0], weights_id[1])

    single_image = False
    if len(X.shape) == 2:
        single_image = True
        X = np.array([X])

    X = model.pack_data(X)
    log.debug(
        "after pack: min(X)={0}, max(X)={1}, avg(X)={2}, var(X)={3}".format(
            np.min(X), np.max(X), np.average(X), np.var(X)
        )
    )

    pred = model_nn.predict(X)
    log.debug(
        "after predict: min(X)={0}, max(X)={1}, avg(X)={2}, var(X)={3}".format(
            np.min(pred), np.max(pred), np.average(pred), np.var(pred)
        )
    )

    pred = model.unpack_data(pred)

    if single_image is True:
        pred = np.squeeze(pred)

    return pred

def detect_gpu_support():
    """Output information about the state of GPU support to STDERR.

    Returns:
        None

    """
    if not tf.test.is_built_with_cuda():
        log.warning("Tensorflow is not built with CUDA.")
        return
    pgpus = tf.config.list_physical_devices('GPU')
    log.info(
        "Physical GPUs: {0}".format(len(pgpus))
    )


class parent:
    def parent_display():
        print("in the parents")

class student(parent):
    def display(self):
        print("in the student")
        print("going to parent")
        parent.parent_display()

student_obj=student()
student_obj.display()


# coding=utf-8
#C:\Python27\Doc python
__author__='Sean Wang'
#data@:2016-12-12
# coding=gbk
#print out.decode('gbk').encode('utf-8')   #output have Chinese word and English word

from pysnmp.entity.rfc3413.oneliner import cmdgen

cg = cmdgen.CommandGenerator()                          ##获得CommandGenerator对象

def snmpgetwalk(*args):
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorindex, varBindTable = cmdGen.bulkCmd(
        cmdgen.CommunityData('public'),
        cmdgen.UdpTransportTarget(('10.245.59.210', 30161)),
        0, 2,
        args[0],
        args[1],
    )
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%sat%s' % (
            errorStatus.prettyPrint(),
            errorindexandvarBinds[int(errorindex) - 1][0] or '?'
        )
              )
    for varBindTableRow in varBindTable:
        for name, val in varBindTableRow:
            print("WALK showing:", '%s=%s' % (name.prettyPrint(), val.prettyPrint()))

def snmpgetbulk(*args):
    errorIndication, errorStatus, errorIndex, varBinds = cg.nextCmd(\
        cmdgen.CommunityData('my-agent', 'public', 1), cmdgen.UdpTransportTarget(('10.245.59.210', 161)),\
        args[0])
    print(errorIndication, errorStatus, errorStatus)
    for content in varBinds:
        print("SNMP content:", content[0][1])

def snmpget(*args):
    errorIndication, errorStatus, errorIndex, varBinds = cg.getCmd( #0代表v1,1代表v2c
                                                    cmdgen.CommunityData('my-agent', 'public', 1),
        ##社区信息，my-agent ,public 表示社区名,1表示snmp v2c版本，0为v1版本
                                                    cmdgen.UdpTransportTarget(('10.245.59.210', 161)),
        ##这是传输的通道，传输到IP 192.168.70.237, 端口 161上(snmp标准默认161 UDP端口)
                                                     args[0])
        ##传送的OID,个人认为MIB值
    print("SNMPGET:", str(varBinds[0]))                  ##varBinds返回是一个stulp，含有MIB值和获得值

def runit(loop=None):
    OID_W = '.1.3.6.1'                                  #walk oid
    OID_N = '.1.3.6.1.2.1.1'                            #get bulk with oid
    # snmpgetbulk(OID_N)                                  #Can using for single OID get value
    # snmpgetwalk(OID_N, OID_W)                           #Can using for single OID get value
    for i in range(1, loop):
        OID = '.1.3.6.1.2.1.1.%s.0'%i
        snmpget(OID)                                    #Can using for single OID get value
        print("i:", i)

if __name__ == "__main__":
    runit(loop=8)

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

#!/usr/bin/python3
#-*-coding=utf-8-*-
#本模块由乾颐堂陈家栋编写，用于乾颐盾Python课程！
#QQ:594284672
#亁颐堂官网www.qytang.com
#乾颐盾课程包括传统网络安全（防火墙，IPS...）与Python语言和黑客渗透课程！
from pysnmp.entity.rfc3413.oneliner import cmdgen

def cmdgen_bulkcmd():
    cmdGen = cmdgen.CommandGenerator()
    errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(
            cmdgen.CommunityData('public'),
            cmdgen.UdpTransportTarget(('10.245.59.210', 161)),
            0, 25,
            '1.3.6.1.2.1.2.2.1.2',
            '1.3.6.1.2.1.2.2.1.7',
        )
    if errorIndication:
        print(errorIndication)
    elif errorStatus:
        print('%sat%s' % (
            errorStatus.prettyPrint(),
            errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?'
        ))
    elif varBindTable == []:
        print("OID has no value, please try available one!")
    elif varBindTable:
        for varBindTableRow in varBindTable:
            for name, val in varBindTableRow:
                print('SNMP WALK: %s=%s' % (name.prettyPrint(), val.prettyPrint()))

# cmdgen_bulkcmd()


# sum = lambda arg1, arg2: arg1 + arg2
# # 调用sum函数
# print("运行结果：", sum(10, 20))
# print("运行结果：", sum(20, 20))

# def fun(a,b,opt):
#    	print("a=%d"%a)
#    	print("b=%d" %b)
#    	print("result=",opt(a,b))
# fun(11,22,lambda x,y:x+y)
# print("-------------------")
# fun(11,22,lambda x,y:x-y)

stus = [
    {"name":"zhangsan", "age":18},
    {"name":"lisi", "age":19},
    {"name":"wangwu", "age":17}
]
#按name排序：
stus.sort(key = lambda x:x['name'])
print("按name排序后的结果为：",stus)
#按age排序
stus.sort(key = lambda x:x['age'])
print("按age排序后的结果为：",stus)


"""
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""

class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        needSwap = False
        i = len(nums) - 1
        while i > 0:
            if nums[i - 1] < nums[i]:
                needSwap = True
                break
            i -= 1
        if needSwap:
            i = i - 1
            j = len(nums) - 1
            while j > i:
                if nums[j] > nums[i]:
                    temp = nums[i]
                    nums[i] = nums[j]
                    nums[j] = temp
                    break
                j -= 1
            i = i + 1
        j = len(nums) - 1
        while i < j:
            temp = nums[i]
            nums[i] = nums[j]
            nums[j] = temp
            i += 1
            j -= 1


import asyncio
import logging
import time
from itertools import chain

import aiohttp

from uz.client.exceptions import (
    FailedObtainToken, HTTPError, BadRequest, ResponseError, ImproperlyConfigured)
from uz.client.model import DATE_FMT, Train, Station, Coach
from uz.client.utils import parse_gv_token, get_random_user_agent

logger = logging.getLogger('uz.client')

class UZClient(object):

    base_url = 'http://booking.uz.gov.ua/en'

    def __init__(self, session=None, request_timeout=10):
        self._session = session
        self.request_timeout = request_timeout

        self._token_lock = asyncio.Lock()
        self._token = None
        self._token_date = 0
        self._token_max_age = 600  # 10 minutes
        self._user_agent = None

    def __enter__(self):
        self._session = aiohttp.ClientSession()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.session.close()

    @property
    def session(self):
        if self._session is None:
            raise ImproperlyConfigured('Session is not configured')
        return self._session

    @property
    def user_agent(self):
        if self._user_agent is None:
            self._user_agent = get_random_user_agent()
        return self._user_agent

    def _is_token_outdated(self):
        return (time.time() - self._token_date) > self._token_max_age

    async def get_token(self):
        if self._is_token_outdated():
            async with self._token_lock:
                if self._is_token_outdated():
                    self._user_agent = None
                    self.session.cookies.clear()
                    headers = {'User-Agent': self.user_agent}
                    page = await self.call('', raw=True, headers=headers)
                    page = page.decode('utf-8')
                    self._token = parse_gv_token(page)
                    if self._token is None:
                        raise FailedObtainToken(page)
                    self._token_date = time.time()
        return self._token

    async def get_headers(self):
        return {
            'User-Agent': self.user_agent,
            'GV-Ajax': '1',
            'GV-Referer': self.base_url,
            'GV-Token': await self.get_token()
        }

    def uri(self, endpoint):
        return '{}/{}'.format(self.base_url, endpoint)

    def get_session_id(self):
        sid = self.session.cookies.get('_gv_sessid')
        return sid and sid.value

    async def call(self, endpoint, method='POST', raw=False, *args, **kwargs):
        if 'headers' not in kwargs:
            kwargs['headers'] = await self.get_headers()

        uri = self.uri(endpoint)
        logger.debug('Fetching: %s', uri)
        logger.debug('Headers: %s', kwargs['headers'])
        logger.debug('Cookies: %s', self.session.cookies)

        with aiohttp.Timeout(self.request_timeout):
            async with self.session.request(
                    method, uri, *args, **kwargs) as response:
                body = await response.read()
                if not response.status == 200:
                    try:
                        json = await response.json()
                    except Exception:  # TODO: narrow exception
                        json = None
                    ex = BadRequest if response.status == 400 else HTTPError
                    raise ex(response.status, body, kwargs.get('data'), json)
                if raw:
                    return body
                json = await response.json()
                if json.get('error'):
                    raise ResponseError(response.status, body, kwargs.get('data'), json)
                return json

    async def search_stations(self, name):
        endpoint = 'purchase/station/{}/'.format(name)
        result = await self.call(endpoint)
        return [Station.from_dict(i) for i in result['value']]

    async def fetch_first_station(self, name):
        stations = await self.search_stations(name)
        return stations and stations[0] or None

    async def list_trains(self, date, source_station, destination_station):
        data = dict(
            station_id_from=source_station.id,
            station_id_till=destination_station.id,
            date_dep=date.strftime(DATE_FMT),
            time_dep='00:00',
            time_dep_till='',
            another_ec=0,
            search='')
        result = await self.call('purchase/search/', data=data)
        return [Train.from_dict(i) for i in result['value']]

    async def fetch_train(self, date, source_station, destination_station, train_num):
        trains = await self.list_trains(date, source_station, destination_station)
        for train in trains:
            if train.num == train_num:
                return train

    async def list_coaches(self, train, coach_type):
        data = dict(
            station_id_from=train.source_station.id,
            station_id_till=train.destination_station.id,
            train=train.num,
            model=train.model,
            date_dep=train.departure_time.timestamp,
            round_trip=0,
            another_ec=0,
            coach_type=coach_type.letter
        )
        result = await self.call('purchase/coaches/', data=data)
        return [Coach.from_dict(i) for i in result['coaches']]

    async def list_seats(self, train, coach):
        data = dict(
            station_id_from=train.source_station.id,
            station_id_till=train.destination_station.id,
            train=train.num,
            coach_num=coach.num,
            coach_class=coach.klass,
            coach_type_id=coach.type_id,
            date_dep=train.departure_time.timestamp
        )
        result = await self.call('purchase/coach/', data=data)
        return set(chain(*result['value']['places'].values()))

    async def book_seat(self, train, coach, seat, firstname, lastname):
        data = dict(
            code_station_from=train.source_station.id,
            code_station_to=train.destination_station.id,
            train=train.num,
            date=train.departure_time.timestamp,
            round_trip=0)

        place = dict(
            ord=0,
            coach_num=coach.num,
            coach_class=coach.klass,
            coach_type_id=coach.type_id,
            place_num=seat,
            firstname=firstname,
            lastname=lastname,
            bedding=0,
            child='',
            stud='',
            transp=0,
            reserve=0)
        for key, value in place.items():
            data['places[0][{}]'.format(key)] = value
        result = await self.call('cart/add/', data=data)
        return result


from collections import deque
import sys

dx = [0,0,-1,1]
dy = [-1,1,0,0]

def solution(board,n,m):

    map_board = [[0] * m for i in range(n)]

    q = deque()
    q.append({'row': 0, 'col': 0})
    map_board[0][0] = 1

    while len(q) != 0:
        front = q.popleft()
        row = front['row']
        col = front['col']

        for i in range(4):
            nrow = row + dy[i]
            ncol = col + dx[i]
            if ( nrow >= 0
                and nrow < n
                and ncol >= 0
                and ncol < m
                and board[nrow][ncol] == '1'
                and map_board[nrow][ncol] == 0) :

                q.append({'row':nrow, 'col':ncol})
                map_board[nrow][ncol] = map_board[row][col] + 1
                if nrow == n -1 and ncol == m - 1:
                    break

    return map_board[n-1][m-1]

if __name__ == '__main__':
    n,m = list(map(int,sys.stdin.readline().rstrip().split()))
    board = [list(sys.stdin.readline()[:-1]) for i in range(n)]

    ans = solution(board, n, m)
    print(ans)


#Сафиуллина Арина ИВТ 2 курс
#Напишите программу, которая реализует нахождение наибольшего общего делителя двух чисел A, B
#Тесты оформите с помощью pytest или UnitTest.

def nod(a, b):
    while b:
        a, b = b, a % b
    return a
a = int(input('a = '))
b = int(input('b = '))
print ('NOD = ', nod(a, b))


import json
import urllib.request, urllib.parse, urllib.error
import requests
import ssl
import time
import sys
import codecs
import csv
import pprint as pp
import re
from secrets import INuser_pass

tagname = input('input tag name: ')

insightlyurl = 'https://api.insight.ly/v2.2/Organisations/Search?'

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

# create a new CSV file
fhand = open(tagname + '_OrganizationsList_with_Emails_and_URLs.csv', 'w', newline='', encoding='utf-8')
csvfhand = csv.writer(fhand)
csvfhand.writerow(['Hospital','Hospital ID','Hospital Email','Hospital URL'])

count = 0
while True:

    parms = dict()
    parms['tag'] = tagname
    parms['skip'] = count
    parms['top'] = 500
    parms['count_total'] = 'true'

    url = insightlyurl + urllib.parse.urlencode(parms)

    print('Retrieving', url)

    uh = requests.get(url, auth = INuser_pass)

    try:
        status = uh.status_code
        print("Status Code:", status)
        if status != 200:
            print("==== Successful Response Failed ====")
            break
    except:
        print("==== Failure to Retrieve Status ====")
        continue

    dumps = uh.headers
    dumps_total = int(dumps["X-Total-Count"])

    data = uh.json()  # this is a list

    EMAIL_REGEX = re.compile(r"[^@]+@[^@]+\.[^@]+")
    URL_REGEX = re.compile(r"(http:\/\/www\.|http:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$")

    for item in data:
        # pp.pprint(item)
        # print('')
        # hospname = str(item['ORGANISATION_NAME'].encode('utf-8'))
        # hospname = hospname[2:-1]
        hospname = item["ORGANISATION_NAME"]
        hospID = item['ORGANISATION_ID']

        # print('length of tags ',len(item['TAGS'])

        for u in item["CONTACTINFOS"]:
            if URL_REGEX.match(u["DETAIL"]):
                url = u["DETAIL"]
            else:
                url = ''
                continue

        # print('length of CUSTOMFIELDS ',len(item['CUSTOMFIELDS']))
        # emaillist = list()
        for r in item["CUSTOMFIELDS"]:
            if EMAIL_REGEX.match(r["FIELD_VALUE"]):  # search for email, skip phone numbers
                # email = str(r["FIELD_VALUE"].encode('utf-8'))
                # email = email[2:-1]
                email = r["FIELD_VALUE"]
                # emaillist.append(email)
                try:
                    print(hospname)
                    print(hospID)
                    print(email)
                    print(url)
                    csvfhand.writerow([hospname,hospID,email,url])
                except:
                    continue
                continue
            else:
                email = ''
                continue

        #write hospital name and email to csv
        # csvhosphand.writerow([hospname])
        # csvIDhand.writerow([hospname,hospID])
        count += 1

    if count % 2 == 0:
        print('Compiling Data...')
        print(count)
        time.sleep(5)

    if count == dumps_total:
        print("Total of",count, "records written to file.")
        break

# cur.close()
fhand.close()
# hosphand.close()
# IDhand.close()


# Import LCD library
from RPLCD import i2c

import RPi.GPIO as GPIO
# Import sleep library
from time import sleep
lcdmode = 'i2c'
cols = 20
rows = 4
charmap = 'A00'
i2c_expander = 'PCF8574'
# Generally 27 is the address;Find yours using: i2cdetect -y 1
address = 0x27
port = 1 # 0 on an older Raspberry Pi

import subprocess

# Initialise the LCD
lcd = i2c.CharLCD(i2c_expander, address, port=port, charmap=charmap,
                  cols=cols, rows=rows)
lcd.home()
lcd.clear()

sleep(.1)

GPIO.setmode(GPIO.BOARD)

def display_stats():
  lcd.home()

  # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load
  cmd = "hostname -I | cut -d\' \' -f1"
  IP = subprocess.check_output(cmd, shell = True )
  cmd = "top -bn1 | grep load | awk '{printf \"CPU Load: %.2f\", $(NF-2)}'"
  CPU = subprocess.check_output(cmd, shell = True )
  cmd = "free -m | awk 'NR==2{printf \"Mem: %s/%sMB %.2f%%\", $3,$2,$3*100/$2 }'"
  MemUsage = subprocess.check_output(cmd, shell = True )
  cmd = "df -h | awk '$NF==\"/\"{printf \"Disk: %d/%dGB %s\", $3,$2,$5}'"
  Disk = subprocess.check_output(cmd, shell = True )

  # Write two lines of text.
  lcd.write_string("IP: " + str(IP)[2:-3][:cols])
  lcd.crlf()
  lcd.write_string(str(CPU)[2:-1][:cols])
  lcd.crlf()
  lcd.write_string(str(MemUsage)[2:-1][:cols])
  lcd.crlf()
  lcd.write_string(str(Disk)[2:-1][:cols])

while True:
  display_stats()
  sleep(.3)


firstname = "Mavis"
surname = "de Ridder"

age = 17

town = "Sassenheim"
address = "Julianalaan 23"

school = "Mediacollege Amsterdam"
school_town = "Amsterdam"
school_address = "Contactweg 36"
distance_to_school = 35.4

hair_colour = ["zwart", "blond"]

print("Ik heet " + firstname + " " + surname + ".", end=" ")
print("Ik ben " + str(age) + " jaar oud, en ik woon in " + town + ". Mijn adres is " + address + ". Mijn haarkleur is nu", end=" ")
print(*hair_colour, sep=" & ", end="")
print(".")
print("Ik ga naar het " + school + " in " + school_town + ". Het adres is " + school_address + ", en de afstand naar school is " + str(distance_to_school) + "km.")

input("Press enter to quit...")