###########################
## PART 10: Simple Game ###
### --- CODEBREAKER --- ###
## --Nope--Close--Match--  ##
###########################
import random
# It's time to actually make a simple command line game so put together everything
# you've learned so far about Python. The game goes like this:

# 1. The computer will think of 3 digit number that has no repeating digits.
# 2. You will then guess a 3 digit number
# 3. The computer will then give back clues, the possible clues are:
#
#     Close: You've guessed a correct number but in the wrong position
#     Match: You've guessed a correct number in the correct position
#     Nope: You haven't guess any of the numbers correctly
# 4. Based on these clues you will guess again until you break the code with a
#    perfect match!
#==============================================================================
def test_code(digits, userGuess):
    li = list(digits)
    #print (li)
    #print (userGuess)
    if li[0] == userGuess[0] and li[1] == userGuess[1] and li[2] == userGuess[2]:
        print("CODE BROKEN")
        return 0
    if li[0] == userGuess[0]:
        print("Match")
    elif li[1] == userGuess[1]:
        print("Match")
    elif li[2] == userGuess[2]:
        print("Match")
    elif li[0] == userGuess[1] or li[0] == userGuess[2] or li[1] == userGuess[2]:
        print("Close")
    else:
        print("Nope")
    return 1
#==============================================================================
code = [str(num) for num in range(10)]
random.shuffle(code)
code = code[:3]
win = 1

print("Welcome Code Breaker! Let's see if you can guess my 3 digit number!")
#print(guess)
while(win):
    guess = list(input("What is your guess? "))
    win = test_code(code, guess)


import socket
import requests

headers = {
'Host':'10.10.11.12',
'Connection':'keep-alive',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
'Content-Type':'application/x-www-form-urlencoded',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language':'zh-CN,zh;q=0.8'
}

data = {
'loginType':'',
'auth_type':'0',
'isBindMac':'0',
'pageid':'1',
'templatetype':'3',
'listbindmac':'0',
'isRemind':'0',
'loginTimes':'',
'groupId':'',
'userId':'这里输入账号',
'passwd':'这里输入密码'
}
# gethostbyname 返回的是 主机名 的IPv4 的地址格式，如果传入的参数是IPv4 的地址格式，则返回值跟参数一样，
# 这个函数不支持IPv6 的域名解析
localIP = socket.gethostbyname(socket.gethostname())
#gethostbyname_ex()它能够返回 一个三元组 （原始主机名，域名列表，IP地址列表），这个函数不支持IPv6的域名解析
#参数传入域名
ipList = socket.gethostbyname_ex(socket.gethostname())
ip = ipList[2][0]

url = 'http://10.10.11.12/portal.do?wlanuserip='+ ip +'&wlanacname=XF_BRAS&mac=eb:57:14:ac:00:00&vlan=0&rand=d2c08f2fd07e2'

p = requests.post(url,headers=headers,data=data)
r = requests.get('https://www.baidu.com')
if r.status_code == 200:
    print("登陆成功")
else:
    print("登陆失败")


"""
Linear Least-Squares Inversion
==============================

Here we demonstrate the basics of inverting data with SimPEG by considering a
linear inverse problem. We formulate the inverse problem as a least-squares
optimization problem. For this tutorial, we focus on the following:

    - Defining the forward problem
    - Defining the inverse problem (data misfit, regularization, optimization)
    - Specifying directives for the inversion
    - Recovering a set of model parameters which explains the observations

"""

#########################################################################
# Import Modules
# --------------
#

import numpy as np
import matplotlib.pyplot as plt

from discretize import TensorMesh

from SimPEG import (
    simulation,
    maps,
    data_misfit,
    directives,
    optimization,
    regularization,
    inverse_problem,
    inversion,
)

# sphinx_gallery_thumbnail_number = 3

#############################################
# Defining the Model and Mapping
# ------------------------------
#
# Here we generate a synthetic model and a mappig which goes from the model
# space to the row space of our linear operator.
#

nParam = 100  # Number of model paramters

# A 1D mesh is used to define the row-space of the linear operator.
mesh = TensorMesh([nParam])

# Creating the true model
true_model = np.zeros(mesh.nC)
true_model[mesh.cell_centers_x > 0.3] = 1.0
true_model[mesh.cell_centers_x > 0.45] = -0.5
true_model[mesh.cell_centers_x > 0.6] = 0

# Mapping from the model space to the row space of the linear operator
model_map = maps.IdentityMap(mesh)

# Plotting the true model
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
ax.plot(mesh.cell_centers_x, true_model, "b-")
ax.set_ylim([-2, 2])

#############################################
# Defining the Linear Operator
# ----------------------------
#
# Here we define the linear operator with dimensions (nData, nParam). In practive,
# you may have a problem-specific linear operator which you would like to construct
# or load here.
#

# Number of data observations (rows)
nData = 20

# Create the linear operator for the tutorial. The columns of the linear operator
# represents a set of decaying and oscillating functions.
jk = np.linspace(1.0, 60.0, nData)
p = -0.25
q = 0.25

def g(k):
    return np.exp(p * jk[k] * mesh.cell_centers_x) * np.cos(
        np.pi * q * jk[k] * mesh.cell_centers_x
    )

G = np.empty((nData, nParam))

for i in range(nData):
    G[i, :] = g(i)

# Plot the columns of G
fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
for i in range(G.shape[0]):
    ax.plot(G[i, :])

ax.set_title("Columns of matrix G")

#############################################
# Defining the Simulation
# -----------------------
#
# The simulation defines the relationship between the model parameters and
# predicted data.
#

sim = simulation.LinearSimulation(mesh, G=G, model_map=model_map)

#############################################
# Predict Synthetic Data
# ----------------------
#
# Here, we use the true model to create synthetic data which we will subsequently
# invert.
#

# Standard deviation of Gaussian noise being added
std = 0.01
np.random.seed(1)

# Create a SimPEG data object
data_obj = sim.make_synthetic_data(true_model, relative_error=std, add_noise=True)

#######################################################################
# Define the Inverse Problem
# --------------------------
#
# The inverse problem is defined by 3 things:
#
#     1) Data Misfit: a measure of how well our recovered model explains the field data
#     2) Regularization: constraints placed on the recovered model and a priori information
#     3) Optimization: the numerical approach used to solve the inverse problem
#

# Define the data misfit. Here the data misfit is the L2 norm of the weighted
# residual between the observed data and the data predicted for a given model.
# Within the data misfit, the residual between predicted and observed data are
# normalized by the data's standard deviation.
dmis = data_misfit.L2DataMisfit(simulation=sim, data=data_obj)

# Define the regularization (model objective function).
reg = regularization.WeightedLeastSquares(mesh, alpha_s=1.0, alpha_x=1.0)

# Define how the optimization problem is solved.
opt = optimization.InexactGaussNewton(maxIter=50)

# Here we define the inverse problem that is to be solved
inv_prob = inverse_problem.BaseInvProblem(dmis, reg, opt)

#######################################################################
# Define Inversion Directives
# ---------------------------
#
# Here we define any directiveas that are carried out during the inversion. This
# includes the cooling schedule for the trade-off parameter (beta), stopping
# criteria for the inversion and saving inversion results at each iteration.
#

# Defining a starting value for the trade-off parameter (beta) between the data
# misfit and the regularization.
starting_beta = directives.BetaEstimate_ByEig(beta0_ratio=1e-4)

# Setting a stopping criteria for the inversion.
target_misfit = directives.TargetMisfit()

# The directives are defined as a list.
directives_list = [starting_beta, target_misfit]

#####################################################################
# Setting a Starting Model and Running the Inversion
# --------------------------------------------------
#
# To define the inversion object, we need to define the inversion problem and
# the set of directives. We can then run the inversion.
#

# Here we combine the inverse problem and the set of directives
inv = inversion.BaseInversion(inv_prob, directives_list)

# Starting model
starting_model = np.zeros(nParam)

# Run inversion
recovered_model = inv.run(starting_model)

#####################################################################
# Plotting Results
# ----------------
#

# Observed versus predicted data
fig, ax = plt.subplots(1, 2, figsize=(12 * 1.2, 4 * 1.2))
ax[0].plot(data_obj.dobs, "b-")
ax[0].plot(inv_prob.dpred, "r-")
ax[0].legend(("Observed Data", "Predicted Data"))

# True versus recovered model
ax[1].plot(mesh.cell_centers_x, true_model, "b-")
ax[1].plot(mesh.cell_centers_x, recovered_model, "r-")
ax[1].legend(("True Model", "Recovered Model"))
ax[1].set_ylim([-2, 2])


import time
import threading
import allure
import pytest
from selenium import webdriver
from datetime import datetime

from test_Task04_MultiThreading import Testa

masters = "//a[@id='iMenuID_1']"
link = "http://localhost:8080/QuaLISWeb/index.html"

un="it"
pswd="123"
class Testabc():
    # In pytest data can't be passed at runtym
    # fixture represents a before method, scope = class it means this has to be run only once
    @pytest.fixture(scope="class")
    def test_parent(self):
        global kk
        global inputtime
        # inputtime = input("Enter the date & time: ")
        driver = webdriver.Chrome(executable_path="C:\\Users\\ate142\\PycharmProjects\\pythonProject1\\Automation\\chromedriver.exe")
        kk = Testa(driver)
# Parameterisation
    @pytest.mark.parametrize("var1,var2",[(un,pswd),(un,pswd)])
    def test_child(self, test_parent, var1, var2):
        inputtime = "07-03-2022 13:36:30"

        i=1
        while i > 0:
            systime = datetime.today()
            print(systime)
            timeconversion = systime.strftime("%d-%m-%Y %H:%M:%S")
            print(inputtime)
            print(timeconversion)
            if inputtime == timeconversion:
                kk.test_login(link, var1, var2)
                time.sleep(4)
                kk.test_xpathclick(masters)
                time.sleep(10)
                break

# For Parallel run, slave can be used. pytest -m markername -n marker count to run depends on parameter arguments


from cx_Freeze import setup,Executable

includefiles = ['1.txt','2.txt','3.txt','4.txt','5.txt','6.txt','7.txt','Comic.ttf','dog1.jpeg','Papyrus.ttc','boardre.py','Tetris.ogg']
includes = []
excludes = ['Tkinter']
packages = ['pygame']

setup(
    name = 'myapp',
    version = '0.1',
    description = 'A general enhancement utility',
    author = 'lenin',
    author_email = 'le...@null.com',
    options = {'build_exe': {'excludes':excludes,'packages':packages,'include_files':includefiles}},
    executables = [Executable('Game.py')]
)


from django.shortcuts import render
from .models import Plants
from .filters import plantsFilter
from .forms import SearchForm

# Create your views here.
def home(request):
    plantsByFamily = None
    # 請求方法為POST（使用者查詢）時，依據請求傳入的查詢條件篩選資料
    if request.method == "POST":
        form = SearchForm(request.POST)
        if form.is_valid():
            plantsByFamily = plantsFilter(formdata=form.cleaned_data)
    else:
        form = SearchForm()
    context = {
        'form': form,
        'plantsByFamily': plantsByFamily
    }
    return render(request, 'home.html', context)


class Solution:
    def findMin(self, nums):
        first, last = 0, len(nums) - 1
        '''
        loop invariant: 1. low < high
                        2. mid != high and thus A[mid] != A[high] (no duplicate exists)
                        3. minimum is between [low, high]
        The proof that the loop will exit:
        after each iteration either the 'high' decreases or the 'low' increases, so the interval [low, high] will always shrink.
        '''
        while first < last:
            midpoint = (first + last) // 2
            print(first);
            print(last);
            print(midpoint);

            if nums[midpoint] > nums[last]:
                # the minimum is in the right part
                first = midpoint + 1
            else:
                # the minimum is in the left part
                last = midpoint
        return nums[first]

solution = Solution();
nums = [3,5,9,12,0,1];
result = solution.findMin(nums);
print(result);


"""
A simple Python script to send messages to a sever over Bluetooth
using PyBluez (with Python 2).
"""

import bluetooth
import random
import time
import smbus

bus = smbus.SMBus(1)

ADC_ADDRESS = 0x4b

serverMACAddress = 'D8:3A:DD:3C:D9:91'
port = 4
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((serverMACAddress, port))

while True:
    data = bus.read_i2c_block_data(ADC_ADDRESS, 0)
    #data = [random.randrange(0,255)]
    print(data[0])
    s.send(str(data[0]))

    time.sleep(0.25)
#sock.close()


# -*- coding:utf-8 -*-
from typing import List

class Solution:
    def nextGreaterElements(self, nums: List[int]) -> List[int]:
        if not nums: return []

        nums = nums + nums
        nums_len = len(nums)
        stack = []
        tmp = []
        for i in range(len(nums)):
            while stack and nums[stack[-1]] < nums[i]:
                cur = stack.pop()
                tmp.append([cur, nums[i]])

            stack.append(i)

        for i in range(len(stack)):
            tmp.append([stack[i], -1])
        tmp = sorted(tmp, key=lambda d: d[0])
        ans = []
        for i in range(nums_len // 2):
            ans.append(tmp[i][1])
        return ans

if __name__ == '__main__':
    # nums = [4, 2, 3, 1]
    nums = [1, 2, 1]
    ans = Solution().nextGreaterElements(nums)
    print(ans)


from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()

# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from . import PrimitiveSum, SHELLS, SPHERICALNAMES

class AtomicBasisFunction(PrimitiveSum):
    """ Stores an atomic basis function.

    Note:
        Either l and m should be passed, or cart, but not both.

    Args:
        atom (moldesign.Atom): The atom this basis function belongs to
        index (int): the index of this basis function (it is stored as
            ``wfn.basis[self.index]``)
        n (int): principal quantum number (``n>=1``) - shell metadata (used for labeling only)
        l (int): total angular momentum quantum number (``l<=n-1``)
        m (int): z-angular momentum quantum number (optional -
             for spherical sets only; ``|m|<=l``)
        cart (str): cartesian component (optional; for cartesian sets only)
        primitives (List[PrimitiveBase]): List of primitives, if available
    """
    def __init__(self, atom, n=None, l=None, m=None, cart=None, primitives=None):
        super().__init__(primitives)
        self._atom = atom
        self.atom_index = atom.index
        self.n = n
        self.l = l
        self.m = m
        if cart is not None:
            assert self.m is None, 'Both cartesian and spherical components passed!'
            assert len(cart) == self.l, \
                'Angular momentum does not match specified component %s' % cart
            for e in cart:
                assert e in 'xyz'
            self.cart = ''.join(sorted(cart))
        else:
            self.cart = None

        # These quantities can't be defined until we assemble the entire basis
        self.coeffs = None
        self.molecule = atom.molecule
        self.basis = None
        self.occupation = None
        self.wfn = None

    @property
    def atom(self):
        """ moldesign.Atom: the atom this basis function belongs to

        We get the atom via an indirect reference, making it easier to copy the wavefunction
        """
        if self.wfn is not None:
            return self.wfn.mol.atoms[self.atom_index]
        else:
            return self._atom

    @property
    def orbtype(self):
        """ A string describing the orbital's angular momentum state.

        Examples:
            >>> AtomicBasisFunction(n=1, l=0).orbtype
            's'
            >>> AtomicBasisFunction(n=2, l=1, cart='y').orbtype
            'py'
            >>> AtomicBasisFunction(n=3, l=2, m=0).orbtype
            'd(z^2)'
        """
        if self.l == 0: t = 's'
        elif self.cart is not None: t = SHELLS[self.l] + self.cart
        else: t = SPHERICALNAMES[self.l, self.m]
        return t

    @property
    def aotype(self):
        """ A string describing the orbital's state.

        Examples:
            >>> AtomicBasisFunction(n=1, l=0).aotype
            '1s'
            >>> AtomicBasisFunction(n=2, l=1, cart='y').aotype
            '2py'
            >>> AtomicBasisFunction(n=3, l=2, m=0).aotype
            '3d(z^2)'
        """
        t = self.orbtype
        if self.n:
            return '%s%s' % (self.n, t)
        else:
            return t

    def __str__(self):
        return 'AO ' + self.name

    @property
    def name(self):
        try:
            return '%s on atom %s' % (self.aotype, self.atom.name)
        except:
            return 'Basis Fn'

    def __repr__(self):
        return '<%s %s>' % (self.__class__.__name__, self.name)


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 16:53:23 2016

"""

"""
Utility functions needed for the project
"""

import math
import sys
from parmeter import globalvar, CylVector, CartVector

def BBSquareIntensity(T, lowlambda, highlambda):
    """
    This function returns the mean specific intensity emitted by a black body
    with temperature T in a square bandpass from lowlambda to highlambda.
    Specifically, the function returns ( \int_lowlambda^highlambda B(lambda) d lambda ) / deltalambda
    where B(lambda) is in specific intensity form.  It uses the precalculated
    table Zzeta.dat and does a logarithmic interpolation in the table. The
    wavelengths must be in centimeters but the intensity is in ergs/cm^2/sec/Angstrom.
    """
    c = 2.99792e+10
    h = 6.626075e-27
    k = 1.38065e-16

    if( lowlambda >= highlambda ):
        print("lowlambda must be lt highlambda in BBSquareIntensity().")
    if( (lowlambda == 0) or (highlambda == 0) ):
        print("Both wavelengths must be gt zero in BBSquareIntensity().")

    Zeta2 = ( h * c ) / (  lowlambda * k * T )
    Zeta1 = ( h * c ) / ( highlambda * k * T )

    if( (Zeta1 < globalvar.deltaBBzeta) or (Zeta2 < globalvar.deltaBBzeta) ):
        print("lambda x T too high in BBSquareIntensity().")

    if( Zeta1 >= globalvar.BBzetamax ):
        meanI = 0.0
        return meanI
    else:
        logZeta1 = math.log( Zeta1 )
        nlow = Zeta1 / globalvar.deltaBBzeta
        ZetaLow = nlow * globalvar.deltaBBzeta
        logZetaLow = math.log( ZetaLow )
        nhigh = nlow + 1
        logZetaHigh = math.log( ZetaLow + globalvar.deltaBBzeta )
        logZBBzetaLow  = math.log( globalvar.ZBBzeta[nlow]  )
        logZBBzetaHigh = math.log( globalvar.ZBBzeta[nhigh] )
        slope = (logZBBzetaHigh - logZBBzetaLow) / (logZetaHigh - logZetaLow)
        logZBBzeta1 = logZBBzetaLow + (logZeta1 - logZetaLow) * slope
        ZBBzeta1 = math.exp( logZBBzeta1 )

    if( Zeta2 >= globalvar.BBzetamax ):
      ZBBzeta2 = globalvar.ZBBzeta[globalvar.maxBBzetaindex]

    else:
        logZeta2 = math.log( Zeta2 )
        nlow = Zeta2 / globalvar.deltaBBzeta
        ZetaLow = nlow * globalvar.deltaBBzeta
        logZetaLow = math.log( ZetaLow )
        nhigh = nlow + 1
        logZetaHigh = math.log( ZetaLow + globalvar.deltaBBzeta )
        logZBBzetaLow  = math.log( globalvar.ZBBzeta[nlow]  )
        logZBBzetaHigh = math.log( globalvar.ZBBzeta[nhigh] )
        slope = (logZBBzetaHigh - logZBBzetaLow) / (logZetaHigh - logZetaLow)
        logZBBzeta2 = logZBBzetaLow + (logZeta2 - logZetaLow) * slope
        ZBBzeta2 = math.exp( logZBBzeta2 )

    meanI = ( T*T*T*T ) * (ZBBzeta2 - ZBBzeta1) / (highlambda - lowlambda)
    meanI *= 1.0e-08

    return meanI

def BBFilterIntensity(T, filter):
    """
    This function returns the mean specific intensity emitted by a black
    body with temperature T observed through a filter.
    """
    findex = -1;
    for i in range(globalvar.maxIBBfilterindex):
        if globalvar.IBBfilterName[i] == filter:
            findex = i
            break

    if( findex == -1 ):
        print("Unknown filter name in BBFilterIntensity.");

    if( (T < globalvar.IBBT[0]) or (T > globalvar.IBBT[globalvar.maxIBBTindex]) ):
        print("T out of range in BBFilterIntensity.")
    if( T == globalvar.IBBT[globalvar.maxIBBTindex] ):
        intensity = globalvar.IBBtable[globalvar.maxIBBTindex][findex]
        return( intensity )

    minTindex = (T - globalvar.IBBTmin) / globalvar.IBBdeltaT
    maxTindex = minTindex + 1
    slope = (globalvar.IBBtable[maxTindex][findex] - globalvar.IBBtable[minTindex][findex]) / globalvar.IBBdeltaT
    intensity = slope * (T - globalvar.IBBT[minTindex]) + globalvar.IBBtable[minTindex][findex]

    return intensity

def AngleDistance( theta1, phi1, theta2, phi2):
    """
    Calculates the angular distance between two directions, where
    the directions are given by their coordinates (theta,phi) in
    the spherical polar coordinate system.  All angles in radians.
    """
    cosa = math.cos(theta1) * math.cos(theta2) + math.sin(theta1) * math.sin(theta2) * math.cos(phi2 - phi1)
    a = math.acos( cosa )

    return( a )

def CartDotProd( A, B):
    """
    Calculates the dot product of two vectors, both of which
    are in Cartesian coordinates.
    """
    prod = A.x * B.x + A.y * B.y + A.z * B.z

    return( prod )

def Cart2Sphere( Acart, theta, phi ):
    """
    This converts a vector from Cartesian coordinates to
    spherical polar coordinates.  More specifically, it calculates
    the components of the vector in spherical polar coordinates
    given its components in Cartesian coordinates.
    """
    sint = math.sin( theta )
    cost = math.cos( theta )
    sinp = math.sin( phi )
    cosp = math.cos( phi )

    m11 =   sint * cosp
    m21 =   cost * cosp
    m31 = - sinp

    m12 =   sint * sinp
    m22 =   cost * sinp
    m32 =   cosp

    m13 =   cost
    m23 = - sint
    m33 =   0.0

    Asphere = CylVector()
    Asphere.r     = m11 * Acart.x + m12 * Acart.y + m13 * Acart.z
    Asphere.theta = m21 * Acart.x + m22 * Acart.y + m23 * Acart.z
    Asphere.phi   = m31 * Acart.x + m32 * Acart.y + m33 * Acart.z

    return( Asphere )

def Sphere2Cart( Asphere, theta, phi ):
    """
    This converts a vector from spherical polar coordinates to
    Cartesian coordinates.  More specifically, it calculates
    the components of the vector in Cartesian coordinates
    given its components in Spherical polar coordinates.
    """
    sint = math.sin( theta )
    cost = math.cos( theta )
    sinp = math.sin( phi )
    cosp = math.cos( phi )

    m11 =   sint * cosp
    m21 =   sint * sinp
    m31 =   cost

    m12 =   cost * cosp
    m22 =   cost * sinp
    m32 = - sint

    m13 = - sinp
    m23 =   cosp
    m33 =   0.0

    Acart = CartVector()
    Acart.x = m11 * Asphere.r + m12 * Asphere.theta + m13 * Asphere.phi
    Acart.y = m21 * Asphere.r + m22 * Asphere.theta + m23 * Asphere.phi
    Acart.z = m31 * Asphere.r + m32 * Asphere.theta + m33 * Asphere.phi

    return( Acart )

def Cyl2Cart( Asphere, zeta ):
    """
    This converts a vector from cylindrical coordinates to
    Cartesian coordinates.  More specifically, it calculates
    the components of the vector in Cartesian coordinates
    given its components in cylindrical coordinates.
    """
    sinzeta = math.sin( zeta )
    coszeta = math.cos( zeta )

    m11 =   sinzeta
    m21 =   0.0
    m31 =   coszeta

    m12 =   coszeta
    m22 =   0.0
    m32 = - sinzeta

    m13 =   0.0
    m23 =   1
    m33 =   0.0

    Acart = CartVector()
    Acart.x = m11 * Asphere.rho + m12 * Asphere.zeta + m13 * Asphere.h
    Acart.y = m21 * Asphere.rho + m22 * Asphere.zeta + m23 * Asphere.h
    Acart.z = m31 * Asphere.rho + m32 * Asphere.zeta + m33 * Asphere.h

    return( Acart )

def Planck( mode, temperature, lambdanu ):
    """
    Returns the specific intensity emitted by the surface of a black body:

      Fnu     = ( 2*h*nu^3 / c^2)      / ( exp[ h*nu / k*T ] - 1 )

       Flambda = ( 2*h*c^2 / lambda^5 ) / ( exp[ h*c / lambda*k*T ] -1 )

     Input data:
      mode         "NU"     returns Fnu     in units of erg/sec/cm^2/Hz
                   "LAMBDA" returns Flambda in units of erg/sec/cm^2/cm
      temperature  in degrees Kelvin
      lambdanu     wavelength in cm if mode=LAMBDA
                   frequency  in Hz if mode=NU

    Note that the Planck function is normalized such that
      (integral over frequency) = ( sigma / pi ) * T**4
    Thus, it is the monochromatic specific intensity per unit area.
    """
    h = 6.62608e-27
    c=  2.99792e+10
    k = 1.38066e-16
    if( temperature <= 1.0 ):
        sys.exit("Temperature out of range in function Planck.")
    if( mode == "NU" ):
        nu = lambdanu
        x = ( 2.0 * h * nu * nu * nu ) / ( c * c )
        y = ( h * nu ) / ( k * temperature )
        Fnu = x / ( math.exp( y ) - 1.0 )
        return( Fnu )
    elif( mode == "LAMBDA"):
        Lambda = lambdanu
        x = ( 2.0 * h * c * c ) / pow( Lambda, 5.0 )
        y = ( h * c ) / ( Lambda * k * temperature )
        Flambda = x / ( math.exp( y ) - 1.0 )
        return( Flambda )
    else:
        sys.exit("Unrecognized mode in function Planck().")

    return(-1.0)


"""
Classes to help create events files in python
These may be useful in creating the behavioral data file if
you collected your data in python instead of MATLAB

===Example usage===

fname = 'behavioral.mat'
x = events(['yourdata.txt'])
spio.savemat(fname, {'events':x, 'first':x.first})

# Load back into python
x = spio.loadmat(fname, squeeze_me=True, struct_as_record=False)

"""

import scipy.io as spio

class category:
    def __init__(self, name):
        self.name = name
        self.start = []

class events:
    def __init__(self, data):
        conds = ['ITI', 'Neg', 'Pos', 'Neut']
        self.categories = [category(name) for name in conds]
        self.first = None # Set this

        # Fill self.categories.start with the onset times (use seconds)!


import discord, logging, json
import asyncio
import datetime
import pytz
import schedule
import toks
from tinydb import TinyDB, Query

db = TinyDB('data.json')
client = discord.Client()
Users = Query()

BIRTHDAY_ROLE = toks.BIRTHDAY_ROLE
BIRTHDAY_CHANNEL = toks.BIRTHDAY_CHANNEL
RESPONSE_CHANNEL = toks.RESPONSE_CHANNEL
LEMON_SERVER = toks.LEMON_SERVER
TESTING_CHANNEL = toks.TESTING_CHANNEL
TEST_ROLE = toks.TEST_ROLE
HOME_SERVER = toks.HOME_SERVER
OWNER_ID = toks.OWNER_ID
CLIENT_TOKEN = toks.CLIENT_TOKEN
KAIT_ID = toks.KAIT_ID
# Print the starting text
print('---------------')
print('lemonbot')
print('---------------')
print('Starting lemonbot...')

logging.basicConfig(level=logging.WARNING)

def getDate():
    now = datetime.datetime.now(pytz.timezone('US/Pacific'))
    date = {
        'year': now.year,
        'month': now.month,
        'day': now.day,
        'hour': now.hour,
        'minute': now.minute,
        'second': now.second,
    }
    return date
@client.event
async def on_ready():
    print(client.user.name + ' Launched!')

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    elif message.content.startswith('!purge'):
        await client.delete_message(message)
        if message.author.id == OWNER_ID: #dats me
            db.purge()
            await client.send_message(message.author, 'Birthday database purged!')
        else:
            await client.send_message(message.author, 'no')
            await client.send_file(message.channel, './res/img/unacceptable.png')
            msg = '{0.author.mention} has attempted to purge the db.'.format(message)
            await client.send_message(message.channel, msg)
            await client.send_message(message.channel, "Ahh! Atatatatat-No! That is why I'm royal, and *you* are servile!")
            await client.send_file(message.channel, './res/img/unacceptable.png')

    elif message.content.startswith("!status"):
        await client.send_message(message.channel, "Stop screaming! Why are you screaming?!")
    elif message.content.startswith('!purpose'):
        await client.send_file(message.channel, './res/img/purpose.png')
    elif message.content.startswith('!today'):
        date = getDate()
        msg = "Today's date is: {}/{}/{}".format(str(date['month']), str(date['day']), str(date['year']))
        await client.send_message(message.channel, msg)
    elif message.content.startswith('!code'):
        await client.send_message(message.channel, 'https://github.com/AndrewYW/lemonbot')
    elif message.content.startswith('!bday'):
        if message.channel.id == BIRTHDAY_CHANNEL:
            if message.content == "!bday":
                await client.send_message(message.channel, "{0.author.mention}: Need to include month and day.".format(message))
            else:
                await client.delete_message(message)
                await bday_command(message)
    elif message.content.startswith('!list'):
        if message.author.id == OWNER_ID or message.author.id == KAIT_ID:
            doc = db.all()
            for item in doc:
                string = item['user'] + ', birthday: ' + str(item['month']) + ' ' + str(item['day'])
                await client.send_message(client.get_channel(RESPONSE_CHANNEL), string)

    elif message.content.startswith('!lemonbot'):
        await client.send_message(message.channel, """
            Lemonbot, the bot for lemons.
            Commands list and formatting:
            [!status]: Checks status of bot.
            [!purpose]: Just try it.
            [!today]: Returns today's date in mm/dd/yyyy format.
            [!bday mm dd]: Adds your birthday to the database.
            [!code]: Links the Github repo of Lemonbot.
            """)

async def bday_command(message):
    auth = message.author
    temp = message.content.split(" ")
    if len(temp) == 3 and temp[1].isdigit() and temp[2].isdigit():
        month = int(temp[1])
        date = int(temp[2])
        if not db.contains(Users.id == auth.id):
            db.insert({
                'user': auth.name,
                'id': auth.id,
                'text': message.content,
                'month': month,
                'day': date,
                'birthday': False,
                'changed': False
            })
            await client.send_message(client.get_channel(RESPONSE_CHANNEL), 'Inserted into database: {0.author}'.format(message))
            await client.send_message(message.channel, '{0.author.mention}: Add success!'.format(message))
        else:
            if not Users.changed and Users.birthday:
                db.update({
                    'month': month,
                    'day': date,
                    'changed': True
                }, Users.id == auth.id)
                await client.send_message(message.channel, 'Updating birthday entry for: {0.author.mention}'.format(message))
                await client.send_message(client.get_channel(RESPONSE_CHANNEL), 'Updated entry for {0.author}'.format(message))
    else:
        await client.send_message(message.channel, "'They didn't understand my lemon styles. I like this way better.'")
        await client.send_message(message.channel, 'Proper format: "!bday mm dd"')

async def scrub_bdays(month, day):
    """
    Get all members of Lemon Fam
    Clear given role role from every member
    I really hope this works lmao
    """
    lemonServer = client.get_server(LEMON_SERVER)
    role = discord.utils.get(lemonServer.roles, id = BIRTHDAY_ROLE)
    birthdayLemons = db.search(Users.day != day)
    amount = "Removing: " + str(len(birthdayLemons)) + " members today"
    await client.send_message(client.get_channel(RESPONSE_CHANNEL), amount)
    if len(birthdayLemons) > 0:
        for doc in birthdayLemons:
            lemon = lemonServer.get_member(doc['id'])
            if lemon:
                if len(lemon.roles) > 0:
                    if role in lemon.roles:
                        await client.remove_roles(lemon, role)
                        await client.send_message(client.get_channel(RESPONSE_CHANNEL), "Removed role")

async def add_bdays(month, day):
    """
    Scan through database
    If doc birthday value matches today's date, add role to that member
    """
    lemonServer = client.get_server(LEMON_SERVER) #LEMON_SERVER
    birthdayLemons = db.search((Users.month == month) & (Users.day == day) & (Users.birthday==False))
    if len(birthdayLemons) > 0:
        amount = "Adding " + str(len(birthdayLemons)) + " members today"
        await client.send_message(client.get_channel(RESPONSE_CHANNEL), amount)
        for doc in birthdayLemons:
            lemon = lemonServer.get_member(doc['id'])
            db.update({'birthday': True}, Users.id == lemon.id)
            update = "Birthday today: " + str(lemon.name)
            await client.send_message(client.get_channel(RESPONSE_CHANNEL), update)
            role = discord.utils.get(lemonServer.roles, id=BIRTHDAY_ROLE)
            await client.add_roles(lemon, role) #BIRTHDAY_ROLE
            await client.send_message(client.get_channel(RESPONSE_CHANNEL), "Added role to a user")

async def daily_check():
    """
    Scan through database
    Return list of docs where birthday matches current date
    if birthday in members.roles
    For each document:
    """
    await client.wait_until_ready()
    while not client.is_closed:
        date = getDate()
        current = 'Current day: ' + str(date['month']) + "/" + str(date['day']) + "/" + str(date['year'])
        await client.send_message(client.get_channel(RESPONSE_CHANNEL), current ) #Private testing channel
        await scrub_bdays(date['month'], date['day'])
        await asyncio.sleep(10)
        await add_bdays(date['month'], date['day'])

        await asyncio.sleep(86400) #repeat daily -- 86400 seconds in a day

if __name__ == '__main__':
    client.loop.create_task(daily_check())
    client.run(CLIENT_TOKEN)


"""
This file defines the LIF class along with associated functionality.
"""

from typing import List, NamedTuple

import numpy as np

class LIFParams(NamedTuple):
    dt: float = 0.05 # msec
    c_m: float = 58.72 # pF
    g_l: float = 9.43 # 1/GOhm (nS)
    v_l: float = -78.85 # mV
    v_th: float = -51.68 # mV
    k_j: np.ndarray = np.array([0.003, 0.1]) # msec^-1
    f_j: np.ndarray = np.array([-9.18, -198.94]) # pA
    b_j: np.ndarray = np.array([1.0, 1.0]) # no unit

class LIF:
    """Initializes LIF neuron with parameters provided."""
    def __init__(self, params: LIFParams):
        self.dt = params.dt
        self.c_m = params.c_m
        self.g_l = params.g_l
        self.v_l = params.v_l
        self.v_th = params.v_th
        self.k_j = params.k_j
        self.b_j = params.b_j
        self.f_j = params.f_j

        # States to track
        self.v = self.v_l
        self.i_j = np.zeros(2)

    def forward(self, i_ext):
        """
        Computes response to external/applied current using following equations.

        If V > V_th:
        V(t) = V_l # Reset voltage
        I_j(t) = I_j(t-1) * f_j + b_j

        Else:
        V(t) = V(t) + (dt / C_m) * (I_ext(t) + sum(I_j(t-1)) - g_l * (V(t-1) - V_l)
        I_j(t) = I_j(t-1) * (1 - k_j * dt)

        Arguments:
        - i_ext: list
          list of externally applied currents (pA)
        - dt: float
          timestep duration to use in forward euler
        Returns:
        - s: list
          list of 1s and 0s pertaining to whether a neuron spiked
          in each timestep corresponding to the applied current
        """
        s = []
        for i_step in i_ext:
            if self.v > self.v_th:  # Spiking case
                self.v = self.v_l
                self.i_j = self.i_j * self.f_j + self.b_j
                s.append(1)
            else:  # Base case
                dv = (1 / self.c_m) * (i_step + np.sum(self.i_j) - self.g_l * (self.v - self.v_l))
                self.v += dv * self.dt
                self.i_j = self.i_j - self.k_j * self.i_j * self.dt
                s.append(0)
        return s


#!/usr/bin/env python3
###############################################################################
# Includes
###############################################################################

import struct
from xml.sax.handler import property_xml_string
import rclpy
from rclpy.node import Node
from std_msgs.msg import Int32
from sensor_msgs.msg import Image, PointCloud2, PointField
from geometry_msgs.msg import PoseStamped
from iii_interfaces.msg import Powerline, PowerlineDirection
#import ros2_numpy

import cv2 as cv
from cv_bridge import CvBridge

import numpy as np

import time
import copy
import sys
import os
import math
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.lines as mlines

from threading import Thread, Lock

from sshkeyboard import listen_keyboard

###############################################################################
#  Defines
###############################################################################
global image_width
image_width  = 640 #1920
global image_height
image_height  = 480 #1080
global img_dims
img_dims = (image_width, image_height)

###############################################################################
# Class
###############################################################################

class IdDrawer(Node):

    key_thread = None

    def __init__(self):
        self.pl_ = None
        self.pl_buff_ = []

        self.pl_dir_ = None
        self.pl_dir_buff_ = []

        self.buff_size_ = 2

        self.pl_lock_ = Lock()
        self.dir_lock_ = Lock()

        self.key_thread = Thread(target=self.keylistener, args=())

        self.pressed_keys = []
        self.typed_ID = -1

        super().__init__("image_drawer")
        self.pl_sub_ = self.create_subscription(
            Powerline,
            "/pl_mapper/powerline",
            self.on_pl_msg,
            10
        )

        self.pl_direction_sub_ = self.create_subscription(
            PoseStamped,
            "/pl_dir_computer/powerline_direction",
            self.on_pl_direction,
            10
        )

        self.drawn_img_pub_ = self.create_publisher(
            Image,
            "/ID_image",
            10
        )

        self.ID_pub_ = self.create_publisher(
            Int32,
            "/typed_ID",
            10
        )

        timer_period = 0.1  # seconds
        self.timer = self.create_timer(timer_period, self.draw_image)

    def on_pl_msg(self, msg):
        if self.pl_lock_.acquire(blocking=True):
            self.pl_ = msg
            self.pl_buff_.append(self.pl_)
            if len(self.pl_buff_) == self.buff_size_+1:
                self.pl_buff_.pop(0)
            self.pl_lock_.release()

    def on_pl_direction(self, msg):
        if self.dir_lock_.acquire(blocking=True):
            self.pl_dir_ = msg
            self.pl_dir_buff_.append(self.pl_dir_)
            if len(self.pl_dir_buff_) == self.buff_size_+1:
                self.pl_dir_buff_.pop(0)
            self.dir_lock_.release()

    def rotate_xy(self, x, y, angle):

        rot_mat = np.matrix([[math.cos(angle), -math.sin(angle)], [math.sin(angle), math.cos(angle)]])

        xy = np.matrix([[x],[y]])

        rot_xy = np.matmul(rot_mat, xy)

        return rot_xy[0][0], rot_xy[1][0]

    def draw_image(self):

        if len(self.pl_buff_) < self.buff_size_-1 or len(self.pl_dir_buff_) < self.buff_size_-1:
            return

        pl = []
        if self.pl_lock_.acquire(blocking=True):
            if len(self.pl_buff_) == self.buff_size_-1:
                pl_temp = self.pl_
                for i in range(pl_temp.count):
                    pl.append([pl_temp.poses[i].position.x, pl_temp.poses[i].position.y, pl_temp.poses[i].position.z])
                pl = np.asarray(pl)
            else:
                pl_temp = self.pl_buff_.pop(0)
                for i in range(pl_temp.count):
                    pl.append([pl_temp.poses[i].position.x, pl_temp.poses[i].position.y, pl_temp.poses[i].position.z])
                pl = np.asarray(pl)
            self.pl_lock_.release()

        if self.dir_lock_.acquire(blocking=True):
            temp_dir = self.pl_dir_buff_.pop(0)

            pl_dir = math.atan2(
                2*(temp_dir.pose.orientation.w*temp_dir.pose.orientation.z+temp_dir.pose.orientation.x*temp_dir.pose.orientation.y),
                1-2*(temp_dir.pose.orientation.y*temp_dir.pose.orientation.y+temp_dir.pose.orientation.z*temp_dir.pose.orientation.z)
            )

            self.dir_lock_.release()

        # something wrong with rotation ?

        rotated_points_x = []
        points_z = []

        p_x = []
        p_y = []

        for i in range(len(pl)):
            to_rot_x = pl[i][0]
            to_rot_y = pl[i][1]
            # print("X,Y: ", to_rot_x, to_rot_y)
            rot_x, rot_y = self.rotate_xy(to_rot_x, to_rot_y, -pl_dir+1.57)
            # print("rot X,Y: ", rot_x, rot_y)
            rotated_points_x.append(rot_x)
            points_z.append(pl[i][2])

            p_x.append(pl[i][0])
            p_y.append(pl[i][2])

        fig, ax = plt.subplots()
        ax.scatter(rotated_points_x, points_z, linewidth=0.000001, color='green', label='Powerlines (#ID)')
        ax.scatter(0, 0, linewidth=0.000001, color='red', label='Ego', marker='X')

        n = []

        for i in range(pl_temp.count):
            n.append(pl_temp.ids[i])

        for i, txt in enumerate(n):
            ax.annotate(txt, (rotated_points_x[i], points_z[i]))

        ax.legend()

        plt.axis('square')

        # plt.show()

        fig.canvas.draw()

        img = np.frombuffer(fig.canvas.tostring_rgb(), dtype=np.uint8)
        # img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
        img  = img.reshape(fig.canvas.get_width_height()[::-1] + (3,))

        # img is rgb, convert to opencv's default bgr
        img = cv.cvtColor(img,cv.COLOR_RGB2BGR)

        cvb = CvBridge()
        msg = cvb.cv2_to_imgmsg(img, encoding="bgr8")

        self.drawn_img_pub_.publish(msg)

        plt.cla()
        plt.clf()
        plt.close('all')

    ## Key press handling

    def press(self, key):
        numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

        if key == 'e' or key == 'enter':

            if len(self.pressed_keys) < 1:
                print("Key sequence has length 0, no ID submitted")

            else:
                key_string = ""

                for i in range(len(self.pressed_keys)):
                    key_string = key_string + str(self.pressed_keys[i])
                    self.typed_ID = int(key_string)

                if len(self.pressed_keys) > 10 or self.typed_ID > 2147483647:
                    print("Entered ID outside range [0, 2147483648], clearing sequence")
                    self.pressed_keys.clear()
                    print("Type ID - current key sequence: [ ]")
                    print("Press 'del' to clear or 'enter' to submit sequence\n")
                    return

                print("ID", self.typed_ID, "submitted, clearing sequence")
                self.pressed_keys.clear()

                msg = Int32()
                msg.data = self.typed_ID
                self.ID_pub_.publish(msg)

        elif key == 'x' or key == 'delete':
                print("Clearing typed sequence")
                self.pressed_keys.clear()

        elif key == 'backspace':
            print("Deleted latest entry")

            if len(self.pressed_keys) > 0:
                self.pressed_keys.pop()

        elif key in numbers:
            self.pressed_keys.append(key)

        else:
            print("Unsupported command:", key)

        key_string = ""
        for i in range(len(self.pressed_keys)):
            key_string = key_string + str(self.pressed_keys[i])
        print("Type ID - current key sequence: [", key_string, "]")
        print("Press 'del' to clear or 'enter' to submit sequence\n")

    def keylistener(self):

        print("\nEnter powerline ID")
        print("Press 'del' to clear or 'enter' to submit sequence\n")

        listen_keyboard(
            on_press=self.press,
        )

###############################################################################
# Main
###############################################################################

if __name__ == "__main__":
    rclpy.init()

    print("Starting IdDrawer node")

    minimal_publisher = IdDrawer()

    minimal_publisher.key_thread.start()

    rclpy.spin(minimal_publisher)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    minimal_publisher.destroy_node()
    rclpy.shutdown()


#!/usr/bin/env python3

import argparse
import os
import sys
from typing import Iterable, Iterator, List, Optional, Text, Tuple

from rich.console import Console  # type: ignore

from . import __version__
from .color import color_unified_diff_line
from .diff import external_diff, u_diff
from .textiter import head, tail
from .utils import file_exists, get_tables_argument_list

def main() -> None:  # pragma: no cover
    # try/except block rationale:
    # handles "premature" socket closure exception that is
    # raised by Python when stdout is piped to tools like
    # the `head` executable and socket is closed early
    # see: https://docs.python.org/3/library/signal.html#note-on-sigpipe
    try:
        run(sys.argv[1:])
    except BrokenPipeError:
        # Python flushes standard streams on exit; redirect remaining output
        # to devnull to avoid another BrokenPipeError at shutdown
        devnull = os.open(os.devnull, os.O_WRONLY)
        os.dup2(devnull, sys.stdout.fileno())
        sys.exit(0)

def run(argv: List[Text]) -> None:
    # ------------------------------------------
    # argparse command line argument definitions
    # ------------------------------------------
    parser = argparse.ArgumentParser(description="An OpenType table diff tool for fonts.")
    parser.add_argument("--version", action="version", version=f"fdiff v{__version__}")
    parser.add_argument(
        "-l", "--lines", type=int, default=3, help="Number of context lines (default: 3)"
    )
    parser.add_argument(
        "--include",
        type=str,
        default=None,
        help="Comma separated list of tables to include",
    )
    parser.add_argument(
        "--exclude",
        type=str,
        default=None,
        help="Comma separated list of tables to exclude",
    )
    parser.add_argument("--head", type=int, help="Display first n lines of output")
    parser.add_argument("--tail", type=int, help="Display last n lines of output")
    parser.add_argument("--external", type=str, help="Run external diff tool command")
    parser.add_argument(
        "-c",
        "--color",
        action="store_true",
        default=False,
        help="Force ANSI escape code color formatting in all environments",
    )
    parser.add_argument(
        "--nomp",
        action="store_true",
        help="Do not use multi process optimizations (default: on)",
    )
    parser.add_argument(
        "--nocolor",
        action="store_true",
        default=False,
        help="Do not use ANSI escape code colored diff (default: on)",
    )
    parser.add_argument("PREFILE", help="Font file path/URL 1")
    parser.add_argument("POSTFILE", help="Font file path/URL 2")

    args: argparse.Namespace = parser.parse_args(argv)

    # /////////////////////////////////////////////////////////
    #
    #  Validations
    #
    # /////////////////////////////////////////////////////////

    # ----------------------------------
    #  Incompatible argument validations
    # ----------------------------------
    #   --include and --exclude are mutually exclusive options
    if args.include and args.exclude:
        sys.stderr.write(
            f"[*] Error: --include and --exclude are mutually exclusive options. "
            f"Please use ONLY one of these options in your command.{os.linesep}"
        )
        sys.exit(1)

    # -------------------------------
    #  File path argument validations
    # -------------------------------

    if not args.PREFILE.startswith("http") and not file_exists(args.PREFILE):
        sys.stderr.write(
            f"[*] ERROR: The file path '{args.PREFILE}' can not be found.{os.linesep}"
        )
        sys.exit(1)
    if not args.PREFILE.startswith("http") and not file_exists(args.POSTFILE):
        sys.stderr.write(
            f"[*] ERROR: The file path '{args.POSTFILE}' can not be found.{os.linesep}"
        )
        sys.exit(1)

    # /////////////////////////////////////////////////////////
    #
    #  Command line logic
    #
    # /////////////////////////////////////////////////////////

    # instantiate a rich Console
    console = Console()

    # parse explicitly included or excluded tables in
    # the command line arguments
    # set as a Python list if it was defined on the command line
    # or as None if it was not set on the command line
    include_list: Optional[List[Text]] = get_tables_argument_list(args.include)
    exclude_list: Optional[List[Text]] = get_tables_argument_list(args.exclude)

    # flip logic of the command line flag for multi process
    # optimization use
    use_mp: bool = not args.nomp

    if args.external:
        # ------------------------------
        #  External executable tool diff
        # ------------------------------
        # head and tail are not supported when external diff tool is called
        if args.head or args.tail:
            sys.stderr.write(
                f"[ERROR] The head and tail options are not supported with external "
                f"diff executable calls.{os.linesep}"
            )
            sys.exit(1)

        # lines of context filter is not supported when external diff tool is called
        if args.lines != 3:
            sys.stderr.write(
                f"[ERROR] The lines option is not supported with external diff "
                f"executable calls.{os.linesep}"
            )
            sys.exit(1)

        try:
            with console.status("Processing...", spinner="dots10"):
                ext_diff: Iterable[Tuple[Text, Optional[int]]] = external_diff(
                    args.external,
                    args.PREFILE,
                    args.POSTFILE,
                    include_tables=include_list,
                    exclude_tables=exclude_list,
                    use_multiprocess=use_mp,
                )

                # write stdout from external tool
                for line, exit_code in ext_diff:
                    # format with color by default unless:
                    #   (1) user entered the --nocolor option
                    #   (2) we are not piping std output to a terminal
                    # Force formatting with color in all environments if the user includes
                    # the `-c` / `--color` option
                    if (not args.nocolor and console.is_terminal) or args.color:
                        sys.stdout.write(color_unified_diff_line(line))
                    else:
                        sys.stdout.write(line)
                    if exit_code is not None:
                        sys.exit(exit_code)
        except Exception as e:
            sys.stderr.write(f"[*] ERROR: {e}{os.linesep}")
            sys.exit(1)
    else:
        # ---------------
        #  Unified diff
        # ---------------
        # perform the unified diff analysis
        with console.status("Processing...", spinner="dots10"):
            try:
                uni_diff: Iterator[Text] = u_diff(
                    args.PREFILE,
                    args.POSTFILE,
                    context_lines=args.lines,
                    include_tables=include_list,
                    exclude_tables=exclude_list,
                    use_multiprocess=use_mp,
                )
            except Exception as e:
                sys.stderr.write(f"[*] ERROR: {e}{os.linesep}")
                sys.exit(1)

            # re-define the line contents of the diff iterable
            # if head or tail is requested
            if args.head:
                iterable = head(uni_diff, args.head)
            elif args.tail:
                iterable = tail(uni_diff, args.tail)
            else:
                iterable = uni_diff

            # print unified diff results to standard output stream
            has_diff = False
            # format with color by default unless:
            #   (1) user entered the --nocolor option
            #   (2) we are not piping std output to a terminal
            # Force formatting with color in all environments if the user includes
            # the `-c` / `--color` option
            if (not args.nocolor and console.is_terminal) or args.color:
                for line in iterable:
                    has_diff = True
                    sys.stdout.write(color_unified_diff_line(line))
            else:
                for line in iterable:
                    has_diff = True
                    sys.stdout.write(line)

        # if no difference was found, tell the user in addition to the
        # the zero exit status code.
        if not has_diff:
            print("[*] There is no difference in the tested OpenType tables.")


from Poll import Poll
from Components.Converter.Converter import Converter
from enigma import eTimer, iPlayableService, iServiceInformation
from Components.Element import cached

try:
	from bitratecalc import eBitrateCalculator
	ISBITRATE = True
except ImportError:
	ISBITRATE = False

class OpenEcmInfo(Poll, Converter, object):
	bitrate = 0
	vbitrate = 1
	abitrate = 2
	videoBitrate = None
	audioBitrate = None
	videoBitrate_conn = None
	audioBitrate_conn = None
	video = audio = 0

	def __init__(self, type):
		Converter.__init__(self, type)
		Poll.__init__(self)
		self.type = type
		self.poll_interval = 1000
		self.poll_enabled = True
		if type == "bitrate":
			self.type = self.bitrate
		elif type == "vbitrate":
			self.type = self.vbitrate
		elif type == "abitrate":
			self.type = self.abitrate
		self.clearData()
		self.initTimer = eTimer()
		try:
			self.initTimer.callback.append(self.initBitrateCalc)
		except:
			self.initTimer_conn = self.initTimer.timeout.connect(self.initBitrateCalc)

	def clearData(self):
		self.videoBitrate = None
		self.audioBitrate = None
		self.video = self.audio = 0

	def initBitrateCalc(self):
		service = self.source.service
		vpid = apid = dvbnamespace = tsid = onid = -1
		if service:
			serviceInfo = service.info()
			vpid = serviceInfo.getInfo(iServiceInformation.sVideoPID)
			apid = serviceInfo.getInfo(iServiceInformation.sAudioPID)
			tsid = serviceInfo.getInfo(iServiceInformation.sTSID)
			onid = serviceInfo.getInfo(iServiceInformation.sONID)
			dvbnamespace = serviceInfo.getInfo(iServiceInformation.sNamespace)

		if vpid > 0 and ISBITRATE and (self.type == self.vbitrate or self.type == self.bitrate):
			try:
				self.videoBitrate = eBitrateCalculator(vpid, dvbnamespace, tsid, onid, 1000, 1024*1024)
				self.videoBitrate.callback.append(self.getVideoBitrateData)
			except:
				self.videoBitrate = eBitrateCalculator(vpid, dvbnamespace, tsid, onid, 1000, 1024*1024)
				self.videoBitrate_conn = self.videoBitrate.timeout.connect(self.getVideoBitrateData)

		if apid > 0 and ISBITRATE and (self.type == self.bitrate or self.type == self.abitrate):
			try:
				self.audioBitrate = eBitrateCalculator(apid, dvbnamespace, tsid, onid, 1000, 64*1024)
				self.audioBitrate.callback.append(self.getAudioBitrateData)
			except:
				self.audioBitrate = eBitrateCalculator(apid, dvbnamespace, tsid, onid, 1000, 64*1024)
				self.audioBitrate_conn  = self.audioBitrate.timeout.connect(self.getAudioBitrateData)

	@cached
	def getText(self):
		service = self.source.service
		info = service and service.info()
		if not info:
			return ""

		if service.streamed() is not None:
			return ""

		if self.type == self.bitrate:
			return _("Video:") + str(self.video) + "  " + _("Audio:") + str(self.audio)

		elif self.type == self.vbitrate:
			return _("Video:") + str(self.video)

		elif self.type == self.abitrate:
			return _("Audio:") + str(self.audio)

	text = property(getText)

	def getVideoBitrateData(self, value, status):
		if status:
			self.video = value
		else:
			self.videoBitrate = None
			self.video = 0
		Converter.changed(self, (self.CHANGED_POLL,))

	def getAudioBitrateData(self, value, status):
		if status:
			self.audio = value
		else:
			self.audioBitrate = None
			self.audio = 0
		Converter.changed(self, (self.CHANGED_POLL,))

	def changed(self, what):
		if what[0] == self.CHANGED_SPECIFIC:
			if what[1] == iPlayableService.evStart:
				self.initTimer.stop
				self.initTimer.start(1000, True)
			elif what[1] == iPlayableService.evEnd:
				self.clearData()
				Converter.changed(self, what)
		elif what[0] == self.CHANGED_POLL:
			self.downstream_elements.changed(what)


import base64
import cPickle as pickle
import codecs
import zlib

def create_names():
    with codecs.open("allCountries.txt", encoding="ascii", errors="replace") as f_in:
        with open("names.txt", "w") as f_out:
            for line in f_in:
                elems = line.split(u'\t')
                try:
                    f_out.write("%s\n" % elems[2].strip())
                except:
                    continue

def is_word_not_in_bloom_filter(word, array, k=3):
    m = len(array)
    for i in xrange(1, k + 1):
        key = word * i
        bit = (abs(hash(key))) % m
        if array[bit] is False:
            return True
    return False

def create_bloom_filter(m=12000000, k=2):
    array = [False] * m
    with open("names.txt") as f_in:
        lines = (line.strip() for line in f_in)
        for line in lines:
            for i in xrange(1, k + 1):
                key = line * i
                bit = (abs(hash(key))) % m
                array[bit] = True
    serialized = base64.encodestring(zlib.compress(pickle.dumps(array, -1), 9))
    with open("serialized.txt", "w") as f_out:
        f_out.write(serialized)

if __name__ == "__main__":
    create_bloom_filter()


import unittest
import glob
import os.path as op

def BOLD_FIR_files(     analysis_info,
                        experiment,
                        fir_file_reward_list = '',
                        glm_file_mapper_list = '',
                        behavior_file_list = '',
                        mapper_contrast = 'stim',
                        h5_file = '',
                        roi_list = ['V1','V2','V3']
                        ):
    """Performs a per-slice FIR deconvolution on nifti-files in_files,
    with per-slice regressors from slice_regressor_list of nifti files,
    and per-TR regressors from vol_regressors text file.
    Uses standard HRF and its time-derivative.
    Assumes slices to be the last spatial dimension of nifti files,
    and time to be the last.

    Parameters
    ----------
    in_file : str
        Absolute path to nifti-file.
    slice_regressor_list : list
        list of absolute paths to per-slice regressor nifti files
    vol_regressor_list : str
        absolute path to per-TR regressor text file

    Returns
    -------
    res_file : str
        Absolute path to nifti-file containing residuals after regression.
    rsq_file : str
        Absolute path to nifti-file containing rsq of regression.
    beta_file : str
        Absolute path to nifti-file containing betas from regression.

    """

    import nibabel as nib
    import numpy as np
    import numpy.linalg as LA
    import scipy as sp
    import os
    import os.path as op
    import pandas as pd
    from spynoza.nodes.utils import get_scaninfo
    from fir import FIRDeconvolution
    from hedfpy import HDFEyeOperator
    import tempfile
    import bottleneck as bn
    # from behavior import behavior_timing
    from utils import roi_data_from_hdf

    threshold = 1.67
    zero_interval = [-2.5,-0.5]

    # roi data
    mapper_alias = op.split(glm_file_mapper_list[0])[-1][:-7] + '_logp'

    # the first file is longer in one or two subjects, so we take the scaninfo of the second file
    TR, dims, dyns, voxsize, affine = get_scaninfo(fir_file_reward_list[1])

    # behavior
    event_names, all_behav_event_times, rename_dict, which_event_name_rewarded = behavior_timing(experiment, behavior_file_list, dyns, TR)
    fir_aliases = [op.split(fir_file_reward_list[0])[-1][:-7] + '_%s'%en for en in event_names]

    out_figures = []
    for roi in roi_list:
        contrast_data = roi_data_from_hdf(data_types_wildcards = [mapper_alias], roi_name_wildcard = roi, hdf5_file = h5_file, folder_alias = 'GLM')
        fir_data = [roi_data_from_hdf(data_types_wildcards = [fa], roi_name_wildcard = roi, hdf5_file = h5_file, folder_alias = 'GLM') for fa in fir_aliases]
        deconvolution_interval_timepoints = np.linspace(analysis_info['fir_interval'][0], analysis_info['fir_interval'][1], fir_data[0].shape[-1], endpoint = False)

        # for experiment 'unpredictable' and 'variable' the masking contrast is the initial mapper
        if experiment in ['unpredictable', 'variable', 'stream-up']:
            if mapper_contrast == 'stim':
                fir_time_course_dict = {en: fd[contrast_data[:,1]>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)}
            elif mapper == 'surround':
                fir_time_course_dict = {en: fd[contrast_data[:,4]>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)}
        elif experiment == 'predictable':
            rewarded_location, rewarded_orientation = which_event_name_rewarded.split('_')
            # check which stimulus was rewarded and implement correct contrast values
            if rewarded_location == 'left':
                rsci,nrsci = [1,4], [7,10]
            elif rewarded_location == 'right':
                rsci,nrsci = [7,10], [1,4]
            # create joined contrast values (not averaged just yet - T values should sort-of sum.)
            if mapper_contrast == 'rewarded_stim':
                contrast_data_joined = contrast_data[:,rsci[0]] + contrast_data[:,rsci[1]]
            elif mapper_contrast == 'nonrewarded_stim':
                contrast_data_joined = contrast_data[:,nrsci[0]] + contrast_data[:,nrsci[1]]
            else:
                print('unknown mask type for experiment predictable')
            # create ROIs with these contrasts
            fir_time_course_dict = {en: fd[contrast_data_joined>threshold].mean(axis = 0) for en,fd in zip(event_names, fir_data)}

        if experiment == 'unpredictable':
            out_figures.append(
                            plot_fir_results_unpredictable(deconvolution_interval_timepoints,
                                                        event_names,
                                                        fir_time_course_dict,
                                                        zero_interval = zero_interval,
                                                        use_zero_interval = False,
                                                        suffix = roi
                                                        ))
        elif experiment == 'predictable':
            out_figures.append(
                            plot_fir_results_predictable(deconvolution_interval_timepoints,
                                                        rename_dict,
                                                        event_names,
                                                        fir_time_course_dict,
                                                        zero_interval = zero_interval,
                                                        use_zero_interval = False,
                                                        suffix = roi
                                                        ))
        elif experiment == 'variable':
            out_figures.append(
                            plot_fir_results_variable(deconvolution_interval_timepoints,
                                                        event_names,
                                                        fir_time_course_dict,
                                                        zero_interval = zero_interval,
                                                        use_zero_interval = False,
                                                        suffix = roi
                                                        ))

        # the derived data types are added in the plot functions, and overwritten such that the no-zero'd data are saved
        out_values = np.array([np.squeeze(fir_time_course_dict[key]) for key in fir_time_course_dict.iterkeys()]).T
        out_columns = [key for key in fir_time_course_dict.iterkeys()]

        out_df = pd.DataFrame(out_values, columns = out_columns, index = deconvolution_interval_timepoints)

        store = pd.HDFStore(h5_file)
        store['/fir/'+experiment+'/'+roi+'_'+mapper_contrast] = out_df
        store.close()

    return out_figures

class FIRTestCase(unittest.TestCase):

    def setUp(self):
        import glob
        import os.path as op
        from utils.plotting import *
        from utils.behavior import behavior_timing

        # standard test path and subject
        test_path = '/home/shared/-2014/reward/new/'
        test_sj = 'sub-004'
        h5_file= glob.glob(op.join(test_path, test_sj, 'h5/*roi.h5'))[0]
        fir_frequency = 10
        fir_interval = [-2.0,7.0]
        data_type = '_pupil_bp_zscore'
        lost_signal_rate_threshold = 0.15
        method = 'fir'

        experiment = 'unpredictable'
        # input files
        fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_reward*.nii.gz'))
        fir_file_reward_list.sort()
        glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz'))
        glm_file_mapper_list.sort()
        # behavior files
        behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-unpredictable_reward*.tsv'))
        behavior_file_list.sort()

        experiment = 'predictable'
        # input files
        fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-predictable_reward*.nii.gz'))
        fir_file_reward_list.sort()
        glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-predictable_mapper*.nii.gz'))
        glm_file_mapper_list.sort()
        # behavior files
        behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-predictable_reward*.tsv'))
        behavior_file_list.sort()

        experiment = 'variable'
        # # input files
        fir_file_reward_list = glob.glob(op.join(test_path, test_sj, 'psc/*-variable_*_reward*.nii.gz'))
        fir_file_reward_list.sort()
        glm_file_mapper_list = glob.glob(op.join(test_path, test_sj, 'psc/*-unpredictable_mapper*.nii.gz'))
        glm_file_mapper_list.sort()
        # behavior files
        behavior_file_list = glob.glob(op.join(test_path, test_sj, 'events/tsv/*-variable_*_reward*.tsv'))
        behavior_file_list.sort()

    def runTest(self):
        fit_FIR_nuisances_all_files(
            example_func = self.example_func,
            in_files = self.in_files,
            slice_regressor_lists = self.slice_regressor_lists,
            vol_regressor_list = self.vol_regressor_list,
            behavior_file_list = self.behavior_file_list,
            fir_frequency = 4,
            fir_interval = [-3.0,15.0]
            )


# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from openstack.tests.functional.shared_file_system import base

class ShareSnapshotTest(base.BaseSharedFileSystemTest):
    def setUp(self):
        super(ShareSnapshotTest, self).setUp()

        self.SHARE_NAME = self.getUniqueString()
        self.SNAPSHOT_NAME = self.getUniqueString()
        my_share = self.operator_cloud.shared_file_system.create_share(
            name=self.SHARE_NAME,
            size=2,
            share_type="dhss_false",
            share_protocol='NFS',
            description=None,
        )
        self.operator_cloud.shared_file_system.wait_for_status(
            my_share,
            status='available',
            failures=['error'],
            interval=5,
            wait=self._wait_for_timeout,
        )
        self.assertIsNotNone(my_share)
        self.assertIsNotNone(my_share.id)
        self.SHARE_ID = my_share.id

        msp = self.operator_cloud.shared_file_system.create_share_snapshot(
            share_id=self.SHARE_ID, name=self.SNAPSHOT_NAME, force=True
        )
        self.operator_cloud.shared_file_system.wait_for_status(
            msp,
            status='available',
            failures=['error'],
            interval=5,
            wait=self._wait_for_timeout,
        )
        self.assertIsNotNone(msp.id)
        self.SNAPSHOT_ID = msp.id

    def tearDown(self):
        snpt = self.operator_cloud.shared_file_system.get_share_snapshot(
            self.SNAPSHOT_ID
        )
        sot = self.operator_cloud.shared_file_system.delete_share_snapshot(
            snpt, ignore_missing=False
        )
        self.operator_cloud.shared_file_system.wait_for_delete(
            snpt, interval=2, wait=self._wait_for_timeout
        )
        self.assertIsNone(sot)
        sot = self.operator_cloud.shared_file_system.delete_share(
            self.SHARE_ID, ignore_missing=False
        )
        self.assertIsNone(sot)
        super(ShareSnapshotTest, self).tearDown()

    def test_get(self):
        sot = self.operator_cloud.shared_file_system.get_share_snapshot(
            self.SNAPSHOT_ID
        )
        self.assertEqual(self.SNAPSHOT_NAME, sot.name)

    def test_list(self):
        snaps = self.operator_cloud.shared_file_system.share_snapshots(
            details=True
        )
        self.assertGreater(len(list(snaps)), 0)
        for snap in snaps:
            for attribute in (
                'id',
                'name',
                'created_at',
                'updated_at',
                'description',
                'share_id',
                'share_proto',
                'share_size',
                'size',
                'status',
                'user_id',
            ):
                self.assertTrue(hasattr(snap, attribute))

    def test_update(self):
        u_snap = self.operator_cloud.shared_file_system.update_share_snapshot(
            self.SNAPSHOT_ID, display_description='updated share snapshot'
        )
        get_u_snap = self.operator_cloud.shared_file_system.get_share_snapshot(
            u_snap.id
        )
        self.assertEqual('updated share snapshot', get_u_snap.description)


#!/usr/bin/env python3

import io
import os
import sys

# Currently the rd page is not copied into the trace. If you want to change
# the contents of the rd page, think carefully about trace compatibility.
# One option would be to save the (replay) rd page into the trace and have
# replay default to the old rd page if the saved page is not present.

def write_rd_page(f, is_64, is_replay):
    # The length of each code sequence must be RD_PAGE_SYSCALL_STUB_SIZE.
    # The end of each syscall instruction must be at offset
    # RD_PAGE_SYSCALL_INSTRUCTION_END.
    if is_64:
        bytes = bytearray([
            0x0f, 0x05, # syscall
            0xc3, # ret
        ])
    else:
        bytes = bytearray([
            0xcd, 0x80, # int 0x80
            0xc3, # ret
        ])
    nocall_bytes = bytearray([
        0x31, 0xc0, # xor %eax,%eax
        0xc3, # ret
    ])

    # traced
    f.write(bytes)
    # privileged traced
    f.write(bytes)

    # untraced
    f.write(bytes)
    # untraced replay-only
    if is_replay:
        f.write(bytes)
    else:
        f.write(nocall_bytes)
    # untraced record-only
    if is_replay:
        f.write(nocall_bytes)
    else:
        f.write(bytes)

    # privileged untraced
    f.write(bytes)
    # privileged untraced replay-only
    if is_replay:
        f.write(bytes)
    else:
        f.write(nocall_bytes)
    # privileged untraced record-only
    if is_replay:
        f.write(nocall_bytes)
    else:
        f.write(bytes)

    ff_bytes = bytearray([0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff])
    f.write(ff_bytes)

generators_for = {
    'rd_page_32': lambda stream: write_rd_page(stream, False, False),
    'rd_page_64': lambda stream: write_rd_page(stream, True, False),
    'rd_page_32_replay': lambda stream: write_rd_page(stream, False, True),
    'rd_page_64_replay': lambda stream: write_rd_page(stream, True, True),
}

def main(argv):
    filename = argv[0]
    base = os.path.basename(filename)

    if os.access(filename, os.F_OK):
        with open(filename, 'rb') as f:
            before = f.read()
    else:
        before = ""

    stream = io.BytesIO()
    generators_for[base](stream)
    after = stream.getvalue()
    stream.close()

    if before != after:
        with open(filename, 'wb') as f:
            f.write(after)

if __name__ == '__main__':
    main(sys.argv[1:])


import numpy as np
import dill as pickle

from hic3defdr.util.matrices import select_matrix

class CoreHiC3DeFDR(object):
    """
    Mixin class providing core saving and loading functionality for HiC3DeFDR.
    """
    @property
    def picklefile(self):
        return '%s/pickle' % self.outdir

    @classmethod
    def load(cls, outdir):
        """
        Loads a HiC3DeFDR analysis object from disk.

        It is safe to have multiple instances of the same analysis open at once.

        Parameters
        ----------
        outdir : str
            Folder path to where the HiC3DeFDR was saved.

        Returns
        -------
        HiC3DeFDR
            The loaded object.
        """
        with open('%s/pickle' % outdir, 'rb') as handle:
            return cls(outdir=outdir, **pickle.load(handle))

    def load_bias(self, chrom):
        """
        Loads the bias matrix for one chromosome.

        The rows of the bias matrix correspond to bin indices along the
        chromosome. The columns correspond to the replicates.

        The bias factors for bins that fail ``bias_thresh`` are set to zero.
        This is designed so that all pixels in these bins get dropped during
        union pixel set computation.

        Parameters
        ----------
        chrom : str
            The name of the chromosome to load the bias matrix for.

        Returns
        -------
        np.ndarray
            The bias matrix.
        """
        bias = np.array([np.loadtxt(pattern.replace('<chrom>', chrom))
                         for pattern in self.bias_patterns]).T
        bias[(np.any(bias < self.bias_thresh, axis=1)) |
             (np.any(bias > 1. / self.bias_thresh, axis=1)), :] = 0
        return bias

    def load_data(self, name, chrom=None, idx=None, rep=None, cond=None,
                  coo=False):
        """
        Loads arbitrary data for one chromosome or all chromosomes.

        Parameters
        ----------
        name : str
            The name of the data to load.
        chrom : str, optional
            The name of the chromosome to load data for. Pass None if this data
            is not organized by chromosome. Pass 'all' to load data for all
            chromosomes.
        idx : np.ndarray or tuple of np.ndarray, optional
            Pass a boolean array to load only a subset of the data. Pass a tuple
            of exactly two boolean arrays to chain the indices.
        rep : str, optional
            If the data is a (pixels, reps) rectangular array, pass the name of
            a rep to get a (pixels,) vector of data for just that rep.
        cond : str, optional
            If the data is a (pixels, conds) rectangular array, pass the name of
            a condition to get a (pixels,) vector of data for just that
            condition.
        coo : bool
            Pass True to return a COO-format ``(row, col, data)`` tuple of
            ``np.ndarray``. ``chrom`` cannot be 'all', and ``idx`` must be None
            (this function will handle filtering automatically).

        Returns
        -------
        data or (concatenated_data, offsets) or (row, col, data) : np.ndarray
            The loaded data for one chromosome, or a tuple of the concatenated
            data and an array of offsets per chromosome. ``offsets`` satisfies
            the following properties: ``offsets[0] == 0``,
            ``offsets[-1] == concatenated_data.shape[0]``, and
            ``concatenated_data[offsets[i]:offsets[i+1], :]`` contains the data
            for the ``i``th chromosome. If called with ``coo=True``, this
            function returns a COO-format ``(row, col, data)`` tuple of
            ``np.ndarray``.
        """
        # short-circuit when asking for loop_idx when no loop_patterns exist
        if name == 'loop_idx' and self.loop_patterns is None and idx is None \
                and chrom != 'all':
            disp_idx = np.load_data('disp_idx', chrom)
            return np.ones(disp_idx.sum(), dtype=bool)

        # resolve col_idx
        col_idx = self.design.index.tolist().index(rep) if rep is not None \
            else self.design.columns.tolist().index(cond) if cond is not None \
            else None

        # handle coo
        if coo:
            if chrom == 'all' or idx is not None:
                raise ValueError("cannot pass coo=True with chrom='all' or idx")
            if name in ['row', 'col', 'bias', 'cov_per_bin', 'disp_per_bin']:
                raise ValueError('data with name %s cannot be loaded as COO'
                                 % name)
            if name in ['raw', 'size_factors', 'scaled', 'disp_idx']:
                row = self.load_data('row', chrom)
                col = self.load_data('col', chrom)
            elif name in ['loop_idx', 'disp', 'mu_hat_null', 'mu_hat_alt',
                          'llr', 'pvalues']:
                disp_idx = self.load_data('disp_idx', chrom)
                row = self.load_data('row', chrom, idx=disp_idx)
                col = self.load_data('col', chrom, idx=disp_idx)
            elif name in ['qvalues']:
                disp_idx = self.load_data('disp_idx', chrom)
                loop_idx = self.load_data('loop_idx', chrom)
                row = self.load_data('row', chrom, idx=(disp_idx, loop_idx))
                col = self.load_data('col', chrom, idx=(disp_idx, loop_idx))
            else:
                raise ValueError('data name %s not recognized' % name)
            data = self.load_data(name, chrom)
            if col_idx is not None:
                return row, col, data[:, col_idx]
            return row, col, data

        # index chaining
        if type(idx) == tuple:
            big_idx, small_idx = idx
            big_idx = big_idx.copy()
            big_idx[np.where(big_idx)[0][~small_idx]] = False
            idx = big_idx

        # tackle simple cases first
        if chrom is None:
            fname = '%s/%s.npy' % (self.outdir, name)
        elif chrom != 'all':
            fname = '%s/%s_%s.npy' % (self.outdir, name, chrom)
        else:
            fname = None
        if fname is not None:
            if idx is None:
                data = np.load(fname)
                if col_idx is not None:
                    return data[:, col_idx]
                return data
            else:
                data = np.load(fname, mmap_mode='r')
                if col_idx is not None:
                    return data[idx, col_idx]
                return data[idx]

        # idx is genome-wide, this tracks where we are in idx so that we can
        # find a subset of idx that aligns with the current chrom
        idx_offset = 0

        # list of data arrays per chromosome
        all_data = []

        # running total of the sizes of the elements of all data
        offset = 0

        # saves value of offset after each chrom
        offsets = [0]

        # loop over chroms
        for chrom in self.chroms:
            fname = '%s/%s_%s.npy' % (self.outdir, name, chrom)
            if idx is not None:
                data = np.load(fname, mmap_mode='r')
                full_data_size = data.shape[0]
                data = data[idx[idx_offset:idx_offset+full_data_size]]
                idx_offset += full_data_size
            else:
                data = np.load(fname)
            offset += data.shape[0]
            offsets.append(offset)
            all_data.append(data)
        all_data = np.concatenate(all_data)
        if col_idx is not None:
            return all_data[:, col_idx], np.array(offsets)
        return all_data, np.array(offsets)

    def save_data(self, data, name, chrom=None):
        """
        Saves arbitrary data for one chromosome to disk.

        Parameters
        ----------
        data : np.ndarray
            The data to save.
        name : str
            The name of the data to save.
        chrom : str or np.ndarray, optional
            The name of the chromosome to save data for, or None if this data is
            not organized by chromosome. Pass an np.ndarray of offsets to save
            data for all chromosomes.
        """
        if chrom is None:
            np.save('%s/%s.npy' % (self.outdir, name), data)
        elif isinstance(chrom, np.ndarray):
            for i, c in enumerate(self.chroms):
                self.save_data(data[chrom[i]:chrom[i + 1]], name, c)
        else:
            np.save('%s/%s_%s.npy' % (self.outdir, name, chrom), data)

    def load_disp_fn(self, cond):
        """
        Loads the fitted dispersion function for a specific condition from disk.

        Parameters
        ----------
        cond : str
            The condition to load the dispersion function for.

        Returns
        -------
        function
            Vectorized. Takes in the value of the covariate the dispersion was
            fitted against and returns the appropriate dispersion.
        """
        picklefile = '%s/disp_fn_%s.pickle' % (self.outdir, cond)
        with open(picklefile, 'rb') as handle:
            return pickle.load(handle)

    def save_disp_fn(self, cond, disp_fn):
        """
        Saves the fitted dispersion function for a specific condition and
        chromosome to disk.

        Parameters
        ----------
        cond : str
            The condition to save the dispersion function for.
        disp_fn : function
            The dispersion function to save.
        """
        picklefile = '%s/disp_fn_%s.pickle' % (self.outdir, cond)
        with open(picklefile, 'wb') as handle:
            return pickle.dump(disp_fn, handle, -1)

    def get_matrix(self, name, chrom, row_slice, col_slice, rep=None,
                   cond=None):
        """
        Loads data with ``name`` as a dense matrix specified by ``chrom,
        row_slice, col_slice``.

        Parameters
        ----------
        name : str
            The name (stage) of the data to load. Add a special suffix '_mean'
            to average per-rep stages within condtiions.
        chrom : str
            The chromosome to select data from.
        row_slice, col_slice : slice
            Row and column slice to use, respectively.
        rep, cond : str, optional
            Pass the rep name or condition name if the data specified by
            ``name`` has multiple columns.

        Returns
        -------
        np.ndarray
            The selected dense matrix.
        """
        if name.endswith('_mean'):
            reps = self.design[self.design[cond]].index.tolist()
            return np.mean(
                [self.get_matrix(name.strip('_mean'), chrom, row_slice,
                                 col_slice, rep=r)
                 for r in reps],
                axis=0
            )
        return select_matrix(
            row_slice,
            col_slice,
            *self.load_data(name, chrom, rep=rep, cond=cond, coo=True)
        )


# -*- coding: utf-8 -*-
"""
@author: efemuratucarli
"""

# Write a program that asks the user to enter an
# integer and prints two integers, root and pwr, such that 1 < pwr < 6
# and root**pwr is equal to the integer entered by the user. If no such
# pair of integers exists, it should print a message to that effect.

x = int(input("Enter an integer: "))
pwr = 2
root = 0
while root**pwr < abs(x):
    pwr = pwr + 1
    if pwr == 5 and root**pwr < abs(x):
        root += 1
        pwr = 2
    if root**pwr > abs(x):
        root += 1
        pwr = 2

if root ** pwr == abs(x):
    if x < 0 and pwr % 2 == 1:
        print("(",-root,")","**",pwr,"=",x,sep="")
    if x >= 0:
        print(root,"**",pwr,"=",x)

else:
    print("The number",x,"cannot be expressed as a root**pwr form when pwr is in the interval of (1-6)")

Chapter 3-Some Simple Numerical Programs/RootandPower(Chapter3.1).py


def breakpoint(p):
    bp = []

    for i in range(1, len(p)):
        if abs(p[i] - p[i-1]) > 1:
            bp.append(i)

    return bp

def printRound(p, a, b):
    if 10 in p[a:b]:
        x = 1
    else:
        x = 2

    print(p, ' - ', '(', a, ',', b-1, ')', sep='')
    print(' ', ' '*(a*3), '-'*((b-a)*3-x), sep='')

def reversal_dist(p1, p2):
    if p1 == p2:
        return 0

    p_start = [0] + [p1.index(x)+1 for x in p2] + [len(p1)+1]

    count = 0
    reversal_list = [[[p_start, count]]]
    bp_min = len(breakpoint(p_start))

    while count < len(p_start)+1:
        reversal_list.append([])
        new_reversals = []

        for perm_item in reversal_list[count]:
            perm = perm_item[0]
            revs = perm_item[2:]
            bp = breakpoint(perm)

            for i in range(len(bp)):
                for j in range(i+1, len(bp)):
                    a = bp[i]
                    b = bp[j]
                    if b-a > 1:

                        p_new = perm[:a] + list(reversed(perm[a:b])) + perm[b:]
                        bp_new = len(breakpoint(p_new))

                        if len(perm_item)>2:
                            revs = perm_item[2:][0]+[a]+[b-1]
                        else:
                            revs = [a,b-1]

                        if bp_new == 0:
                            return p_new, count+1, revs
                        elif bp_new < bp_min:
                            bp_min = bp_new
                            reversal_list[count+1] = []
                            reversal_list[count+1].append([p_new, count+1, revs])
                        elif bp_new == bp_min:
                            reversal_list[count+1].append([p_new, count+1, revs])

        count += 1

def checkAnswer(to_match, to_reverse, revs):

    temp = to_reverse
    for i in range(0, len(revs), 2):
        a = revs[i]-1
        b = revs[i+1]

        printRound(temp, a, b)
        temp = temp[:a] + list(reversed(temp[a:b])) + temp[b:]

    if temp == to_match:
        print(temp, '<-- Correct Match!\n')
    else:
        print(temp, '<-- Incorrect Match!\n')

def main():
    # Read the input .txt file.
    with open('./rosalind_sort.txt', 'r') as infile:
        pair = infile.read().strip().split('\n')
        permA, permB = [list(map(int, p.split(' '))) for p in pair]

    perm, count, revs = reversal_dist(permA, permB)

    print(count)
    for i in range(len(revs), 0, -2):
        print(revs[i-2], revs[i-1])

if __name__ == '__main__':
    main()


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

'''
路由完善：
        修改装饰器路由，由原先的使用正则表达式，改为更为简单的写法
        @r2.route(r'/hello/{name:str}/{age:int}') # 抛去正则表达式，这样写很简单。下面的方式要求框架的使用者熟悉正则。
        @r2.route(r'/hello/(?P<name>\w+)$')
'''
import re
from collections import namedtuple
from webob import Request, Response # webob里封装了Request和Response
from webob.dec import wsgify # webob提供的装饰器，可以将代码大大简化
from webob.exc import HTTPNotFound
#from webob.exc import * # 引入webob所有的Exception

# 这里我们把 str 分成3种：1.str 所有不包含 / 的字符；2.word 字母、数字和下划线；3.any：任意字符
PATTERNS = {
    'str': '[^/].+', # 不包含 /，且至少一个字符
    'word': '\w+',
    'any': '.+', # 任意字符，但是至少包含一个
    'int': '[+-]?\d+', # int类型的正则表达式，可选的+或-号，后面是数字
    'float': '[+-]?\d+\.\d+' # float类型正则表达式
}

CASTS= {
    'str': str,
    'word': str,
    'any': str,
    'int': int,
    'float': float
}

Route = namedtuple('Route', ['pattern', 'methods', 'casts', 'handler'])

class Router:
    def __init__(self, prefix='', domain=None):
        self.routes = []
        self.domain = domain
        self.prefix = prefix

    def _route(self, rule, methods, handler):
        pattern, casts = self._rule_parse(rule)
        self.routes.append(Route(pattern, methods, casts, handler))

    def _rule_parse(self, rule):
        pattern = []
        spec = []
        casts = {}
        is_spec = False

        # @r2.route('/hello/{name}/{age:int}') # /hello/(?P<name>[^/]+)/(?P<age>[+-]?\d+)$
        for c in rule:
            if c == '{' and not is_spec:
                is_spec = True # 开始spec字段
            elif c == '}' and is_spec:
                is_spec = False # 结束spec字段
                # TODO process spec
                name, p, c = self._spec_parse(''.join(spec))
                spec = []
                pattern.append(p)
                casts[name] = c
            elif is_spec:
                spec.append(c)
            else:
                pattern.append(c)

        return '{}$'.format(''.join(pattern)), casts

    def _spec_parse(self, src):
        tmp = src.split(':')  # spec= age:int
        if len(tmp) > 2:
            raise Exception('error pattern')
        name = tmp[0]
        type = 'str'  # type默认为str类型的
        if len(tmp) == 2:
            type = tmp[1]
        pattern = '(?P<{}>{})'.format(name, PATTERNS[type])
        return name, pattern, CASTS[type]

    # def route(self, pattern, methods=None):
    #     if methods is None:
    #         methods = ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTION')
    #
    #     def dec(fn): # fn就是传递进来的handler
    #         self._route(pattern, methods, fn)
    #         return fn # 这里不需要执行fn，原样返回就行了
    #
    #     return dec
    def route(self, rule, methods=None):
        if methods is None:
            methods = ('GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTION')

        def dec(fn): # fn就是传递进来的handler
            self._route(rule, methods, fn)
            def wrap(*args, **kwargs):
                return fn # 这里不需要执行fn，原样返回就行了
            return wrap

        return dec

    def _domian_match(self, request):
        return self.domain is None or re.match(self.domain, request.host)

    def _prefix_match(self, request):
        return request.path.startswith(self.prefix)

    def match(self, request):
        if self._domian_match(request) and self._prefix_match(request):
            for route in self.routes:
                if request.method in route.methods:
                    m = re.match(route.pattern, request.path.replace(self.prefix, '', 1))
                    if m:
                        request.args = {}
                        for k, v in m.groupdict().items():
                            request.args[k] = route.casts[k](v)
                        return route.handler

class Application:
    def __init__(self, **options): # options这里作为全局的设置，传递给views
        self.routers = []
        self.options = options

    def add_router(self, router):
        self.routers.append(router)

    @wsgify
    def __call__(self, request):
        for router in self.routers:
            handler = router.match(request)
            if handler:
                return handler(self, request)
        raise HTTPNotFound(detail='no handler match')

# 上面都是框架代码，下面是业务代码
from webob.exc import HTTPTemporaryRedirect
from html import escape

r1 = Router()
r2 = Router('/r2') # 前缀r2，127.0.0.1:3000/r2/hello/jkzhao
r3 = Router(domain='jinzhi.wisedu.com') # 需要修改hosts文件，配置ip地址和这个主机名相对应。但是改完之后，所有的就得用域名的方式访问

@r3.route('/')
def main(app, request):
    # return Response('this is man page')
    raise HTTPTemporaryRedirect(location='/r2/hello/jkzhao/26') # 302临时跳转,webob内部实现了

@r2.route('/hello/{name}/{age:int}') # 抛去正则表达式，这样写很简单，不写类型就是string。下面的方式要求框架的使用者熟悉正则。
# @r2.route(r'/hello/(?P<name>\w+)$') # 传递方式变为 127.0.0.1:3000/hello/jkzhao 这样就可以通过path来传递参数了
def hello(app, request):
    print(request.args['age'])
    print(type(request.args['age']))
    body = 'hello {}'.format(escape(request.args.get('name')))
    return Response(body)

@r1.route('/favicon.ico')
def favicon(app, request):
    with open('./favicon.ico', 'rb') as f:
        response = Response(body=f.read(), content_type='image/x-icon')
        return response

if __name__ == '__main__':
    from wsgiref.simple_server import make_server # 是不是单线程要看容器，这就是个单线程容器

    app = Application()
    app.add_router(r1)
    app.add_router(r2)
    app.add_router(r3)

    server = make_server('0.0.0.0', 3000, app) # 创建一个容器
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()


from collections import defaultdict
class Solution(object):
    def distinctNames(self, ideas):
        """
        :type ideas: List[str]
        :rtype: int
        """
        dic = defaultdict(set)
        for idea in ideas:
            dic[idea[1:]].add(idea[0])

        cs = 'abcdefghijklmnopqrstuvwxyz'
        cts = {a:{b:0 for b in cs} for a in cs}
        sm =0
        for key in dic:
            values = dic[key]
            for a in values:
                for b in cs:
                    if b in values: continue
                    sm += cts[a][b]
            for a in values:
                for b in cs:
                    if b in values: continue
                    cts[b][a] +=1

        return sm*2

re =Solution().distinctNames(["aaa","baa","caa","bbb","cbb","dbb"])
print(re)


from hashlib import new
import random
from turtle import Turtle

COLORS = ["red", "orange", "yellow", "green", "blue", "purple"]
STARTING_MOVE_DISTANCE = 5
MOVE_INCREMENT = 5

class CarManager:
    def __init__(self):
        self.cars = []
        self.car_speed = STARTING_MOVE_DISTANCE

    def create(self):
        random_chance = random.randint(1, 8)
        if random_chance == 1:
            new_car = Turtle("square")
            new_car.shapesize(1, 2, 1)
            new_car.color(random.choice(COLORS))
            new_car.penup()
            random_y = random.randint(-250, 250)
            new_car.goto(350, random_y)
            self.cars.append(new_car)

    def move(self):
        for car in self.cars:
            car.backward(self.car_speed)

    def levelup(self):
        self.car_speed += MOVE_INCREMENT


from sos.report.plugins import Plugin, IndependentPlugin, PluginOpt

class Libraries(Plugin, IndependentPlugin):

    short_desc = 'Dynamic shared libraries'

    plugin_name = 'libraries'
    profiles = ('system',)

    option_list = [
        PluginOpt('ldconfigv', default=False,
                  desc='collect verbose ldconfig output')
    ]

    def setup(self):
        self.add_copy_spec(["/etc/ld.so.conf", "/etc/ld.so.conf.d"])
        if self.get_option("ldconfigv"):
            self.add_cmd_output("ldconfig -v -N -X")

        self.add_env_var([
            'PATH',
            'LD_LIBRARY_PATH',
            'LD_PRELOAD'
        ])

        ldconfig = self.collect_cmd_output("ldconfig -p -N -X")

        if ldconfig['status'] == 0:
            # Collect library directories from ldconfig's cache
            dirs = set()
            for lib in ldconfig['output'].splitlines():
                s = lib.split(" => ", 2)
                if len(s) != 2:
                    continue
                dirs.add(s[1].rsplit('/', 1)[0])

            if dirs:
                self.add_cmd_output("ls -lanH %s" % " ".join(dirs),
                                    suggest_filename="ld_so_cache")

# vim: set et ts=4 sw=4 :


import matplotlib.pyplot as plt
from PIL import Image

plt.rcParams['font.sans-serif'] ="SimHei"
img=Image.open("lena512color.tiff")

plt.figure(figsize=(10,10))
plt.subplot(221)
plt.axis("off")
plt.imshow(img)
plt.title("原图",fontsize=20)

plt.subplot(222)
plt.axis("off")
img_flr=img.transpose(Image.FLIP_LEFT_RIGHT)
plt.imshow(img_flr)
plt.title("左右翻转",fontsize=20)

plt.subplot(223)
plt.axis("off")
img_r90=img.transpose(Image.ROTATE_90)
plt.imshow(img_r90)
plt.title("逆时针翻转90度",fontsize=20)

plt.subplot(224)
plt.axis("off")
img_tp=img.transpose(Image.TRANSPOSE)
plt.imshow(img_tp)
plt.title("转置",fontsize=20)

plt.show()


#%%
flower_list = ['gerbera', 'lily', 'rose', 'tulip', 'tulip', 'gerbera']

#%%
unique_flowers = list(set(flower_list))
unique_flowers
# %%
name_list = ['Arie', 'Lily', 'Rose']
age_list  = [20, 30, 40]
# %%
dict(zip(name_list, age_list))
# %%
import requests

# %%
response = requests.get("https://opendata.rdw.nl/resource/m9d7-ebf2.json")
# %%
car_list = response.json()
# %%
import pandas as pd

cars_df = pd.DataFrame(car_list)
# %%


# Cycle Detection Algorithm using Union Find Algorithm with given list of edges.

def unionFind():
    parent = [-1]*5
    def findparent(node):
        if parent[node]==-1:
            return node
        else:
            return findparent(parent[node])
    def union(x,y):
            parent[x] = y
    def checkcycle(edges):
        for u,v in edges:
            x = findparent(u)
            y =findparent(v)
            if x==y:
                return True
            else:
                union(x,y)
        return False
    return checkcycle([[1,2],[2,3],[2,4],[3,4],[4,5]])
unionFind()