#!/usr/bin/env python3
###############################################################################
###   Author: Nick Currier (nicholas.currier@gmail.com)
###   No warranty expressed or implied for any purposes
###   This header may not be removed for any reason
###
###   NOTES:
###      Gravity is always assumed to point in the negative z direction
###      All computations are performed in the inertial coordinate system
###
###############################################################################

# get some abstract base class tools
from abc import ABC, abstractmethod
import math
import numpy as np
from forceBase import *
import barometric as baro
import scipy.linalg as spl

# class to generalize the heat flux models available to the heat transfer module
# computes the heat flux per time step and returns the value
# body - moving object used to lookup atmospheric and motion quantities
class HeatingBase(ABC):
    def __init__(self, name, body):
        self._body = body
        self._Q_W_m2 = 0.0  # stores latest heat flux in W/m^2
        self._fout = open(name+'.txt', 'w')

    def __del__(self):
        self._fout.close()

    @abstractmethod
    def preTimeStep(self):
        # This function is called one time prior to each time steap (not iteration)
        pass

    @abstractmethod
    def innerIteration(self, time, wallTemp_K):
        # This function gets called repeatedly during nonlinear convergence each time step
        # Be warned: about this function doing anything that is stateful
        pass

    @abstractmethod
    def postTimeStep(self, time):
        pass

    # simple getter which returns heat flux in W/m^2
    def getHeatFlux(self):
        return self._Q_W_m2

#------------------------------ SIMPLE CONVECTION MODEL ------------------------------------------#

class ConvectionHeating(HeatingBase):
    # name - human readable name of the force class
    def __init__(self, bodies, noseRadius_m):
        name = bodies[0].getName() + '_convection'
        print("Initialize simple convection heating:" , name)
        super().__init__(name, bodies[0])
        self._noseRadius = noseRadius_m

        # write header for log file
        self._fout.write("Time_s      \tVelocity_m_s   \tQdot_W_cm^2 \tStagnationTemperature_K \tFreestreamTemperature_K\n")

    def __del__(self):
        pass

    def preTimeStep(self):
        # do nothing
        pass

    def innerIteration(self, time, wallTemp_K):
        k = self._body.getKinematicsOld()
        # all kinematics reported in the inertial frame
        pos = k._pos
        v = k._vel
        # get velocity vector
        vmag = np.linalg.norm(v)

        altitude = pos[2] # z is vertical direction

        # if altitude <= zero simply return no force
        if altitude <= 0.0:
            print("ConvectionHeating found below sea level - no contribution")
            return

        cond = baro.GetConditions(altitude)
        rho = cond['density_kg_m3']
        T = cond['temperature_K']

        self._Q_W_m2 = simpleAeroHeatLoad(vmag, rho, self._noseRadius)
        heatLoad = self._Q_W_m2/100.0/100.0 # W/cm^2

        print ("Heat conduction: ")
        print ("\tVelocity: %.4f m/s" %vmag)
        print ("\tQdot: %.4f W/cm^2" % (heatLoad))

        Tstag = GetStagnationTemperature(vmag, T)

        self._fout.write('%.6e\t%.6e\t%.6e\t%.6e\t%.6e\n'%(time, vmag, heatLoad, Tstag, T))

    def postTimeStep(self, time):
        # do nothing
        pass

# Returns rounded leading edge aeroheating estimate based on empirical correlation
# in W/m^2 units
def simpleAeroHeatLoad(velocity_m_s, density_kg_m3, noseRadius_m):
    import math
    v3 = velocity_m_s*velocity_m_s*velocity_m_s
    return 1.83e-4*v3*math.sqrt(density_kg_m3/noseRadius_m) #W/m^2

# Computes the total drag power consumed = drag force X distance
# Returns heat load estimate in W/m^2
def simpleDragPower(velocity_m_s, Cd, density_kg_m3):
    maxq = 0.5*density_kg_m3*velocity_m_s*velocity_m_s*Cd # N/m^2
    power = maxq*velocity_m_s # N*m/s / m^2 = J/s.m2 = W/m2
    return power

# Computes the stagnation temperature at given temperature for air
def GetStagnationTemperature(velocity, Tinf):
    Cp = 1006 # J/kg.K @ 300K
    return Tinf + (velocity*velocity)/(2.0*Cp)

#--------------------------------------- RADIATION MODEL ------------------------------------------#

class RadiationHeating(HeatingBase):
    # name - human readable name of the force class
    def __init__(self, bodies, emissivity):
        name = bodies[0].getName() + '_radiation'
        print("Initialize radiation heating:" , name)
        super().__init__(name, bodies[0])
        self._emissivity = emissivity

        # write header for log file
        self._fout.write("Time_s   \tVelocity_m_s   \tQdot_W_cm^2    \tWallTemperature_K  \tFreestreamTemperature_K\n")

    def __del__(self):
        pass

    def preTimeStep(self):
        # do nothing
        pass

    def innerIteration(self, time, wallTemp_K):
        k = self._body.getKinematicsOld()
        # all kinematics reported in the inertial frame
        pos = k._pos
        v = k._vel
        # get velocity vector
        vmag = np.linalg.norm(v)

        altitude = pos[2] # z is vertical direction

        # if altitude <= zero simply return no force
        if altitude <= 0.0:
            print("RadiationHeating found below sea level - no contribution")
            return

        cond = baro.GetConditions(altitude)
        rho = cond['density_kg_m3']
        T = cond['temperature_K']

        # we get this value from the layer model attached to the body
        Twall_K = wallTemp_K

        deltaT4 =  Twall_K*Twall_K*Twall_K*Twall_K - T*T*T*T

        Boltz = 5.6703e-8 # W/m^2.K^4

        self._Q_W_m2 = self._emissivity*Boltz*(deltaT4)
        heatLoad = self._Q_W_m2/100.0/100.0 # W/cm^2

        print ("Heat radiation: ")
        print ("\tQdot: %.4f W/cm^2" % (heatLoad))

        Tstag = GetStagnationTemperature(vmag, T)

        self._fout.write('%.6e\t%.6e\t%.6e\t%.6e\t%.6e\n'%(time, vmag, heatLoad, Twall_K, T))

    def postTimeStep(self, time):
        # do nothing
        pass

# -------------------------- THIN LAYER HEAT CONDUCTION -------------------------------------------#

class ThinLayerConductionPhysics(ForceBase):
    # name - human readable name of the force class
    def __init__(self, name, bodies, aref_m2, rho_kg_m3, Cp_J_kgK, k_W_mK, thickness_m, npts, initialTemperature_K, fluxList):
        print("Initialize thin layer conduction physics:" , name)
        super().__init__(name, bodies)
        self._fluxList = fluxList
        self._Tright = initialTemperature_K

        self._timeold = 0.0 # used to compute dt
        self._k_W_mK = k_W_mK
        self._alpha = k_W_mK/(Cp_J_kgK*rho_kg_m3) # diffusivity m^2/s
        #NOTE: rho*cp is volumetric heat capacity J/(m^3.K)

        # derived
        self._dx = thickness_m/(float)(npts-1)

        #Stability condition: (alpha*dt)/(dx*dx) for explicit solver

        # allocate the memory
        self._x = []
        self._T = []
        for i in range(0,npts):
            self._x.append(i*self._dx)
            self._T.append(initialTemperature_K)
        self._A = np.zeros((npts, npts))

        # write out grid
        print('Grid')
        for xpt in self._x:
            print('%4.4f\t' % xpt),
        print('\n')

        # set to body frame zero
        # forces are always zero from this class, it just rides along and computes heat
        location = np.array([0.0, 0.0, 0.0])
        self._forces = []
        for ibody in self._bodies:
            self._forces.append(ForceContainer())
            self._forces[-1].F = np.array([0.0, 0.0, 0.0])
            self._forces[-1].locationF = copy.deepcopy(location)
            #self._fContainer.Mmoment  -- no need to set this, it's zero
            self._forces[-1].locationM = copy.deepcopy(location)
            # we compute in the inertial frame since that's the frame we can get velocity in simplest
            self._forces[-1].frame = 'I'

        # write header for log file
        self._fout.write("Time_s       ")
        # print grid
        for xpt in self._x:
            self._fout.write('\tT_%4.4f' % xpt),
        self._fout.write('\n')

    def preTimeStep(self):
        for flux in self._fluxList:
            flux.preTimeStep()

    def innerIteration(self, dt, time):
        ibody = self._bodies[0]
        npts = len(self._x)
        dt = time - self._timeold
        A = self._A

        # setup matrix values
        Ka = (self._alpha*dt)/(self._dx*self._dx)
        for row in range(1,npts-1):
            A[row][row-1] = -Ka
            A[row][row] = 1 + 2.0*Ka
            A[row][row+1] = -Ka
        # setup boundary condition to be isothermal
        A[npts-1][npts-1] = 1
        # change the left end to have a constant heat flux condition
        A[0][0] = 1
        A[0][1] = -1

        # get LU decomposition of A
        LU, piv = spl.lu_factor(A)

        wallTemp_K = self._T[0]

        # TODO: loop over all heatflux components and sum them up
        heatFlux = 0.0
        for flux in self._fluxList:
            flux.innerIteration(time, wallTemp_K)
            heatFlux += flux.getHeatFlux() # returns in W/m^2
        print('\tTotal heat flux: %.4f W/m^2' %(heatFlux))
        print('\tTotal heat flux: %.4f W/cm^2' %(heatFlux/100.0/100.0))

        # update RHS which is T_i^n everywhere but at the boundaries
        b = self._T
        b[0] = heatFlux*self._dx/(self._k_W_mK)  # heat flux BC on left
        b[npts-1] = self._Tright       # isothermal BC on right

        # solve the matrix sytem Ax = b --> (LU)x = RHS
        self._Tnew = spl.lu_solve((LU,piv), b)

        # we have to return this per the interface but it's always zero
        return self._forces

    def postTimeStep(self, time):
        for flux in self._fluxList:
            flux.postTimeStep(time)

        # copy down solution
        self._timeold = time
        self._T = self._Tnew
        self._fout.write('%f' %(time))
        for iT in self._T:
            self._fout.write('\t%4.4f' % iT),
        self._fout.write('\n')

if __name__ == "__main__":
    import sys

    if len(sys.argv) != 4:
        raise ValueError('USAGE' + sys.argv[0] + ' <V m/s> <rho kg/m^3> <Radius m>')

    velocity_ms = float(sys.argv[1])
    density_kgm3 = float(sys.argv[2])
    noseRadius_m = float(sys.argv[3])

    heatLoad = simpleAeroHeatLoad(velocity_ms, density_kgm3, noseRadius_m)

    print("Simple heating: %.2f kW/m^2" % (heatLoad/1000.0))
    print("Simple heating: %.2f W/cm^2" % (heatLoad/100.0/100.0))

    Cd = 0.8
    powerLoad = simpleDragPower(velocity_ms, Cd, density_kgm3)

    print("\nPower heating: %.2f kW/m^2" % (powerLoad/1000.0))
    print("Power heating: %.2f W/cm^2" % (powerLoad/100.0/100.0))

    print("\nStagnation temperature: %.2f K" %(GetStagnationTemperature(velocity_ms, 300.0)))

    print("\nSimple/Power ratio: %.2e" %(heatLoad/powerLoad))

    print("\nSuggest using larger of two thermal numbers...")


n, k = map(int, input().split())
cnt=0
while(n != 1):
    cnt= cnt+1
    if n % k == 0:
        n=n//k
    else :
        n = n-1
print(cnt)
"""
책에 있는 정답

while n >=k:
    while n%k !=0:
        n-=1
        cnt +=1
    n//k
    cnt+=1
while n>1:
    n-=1
    cnt +=1
print(cnt)
"""


from typing import List
class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        unique = set()

        for email in emails:

            local, domain = email.split('@')

            plus = local.find('+')
            if plus != -1:
                local = local[:plus]

            local = local.replace('.', '')

            unique.add(local+'@'+domain)

        return len(unique)

test = ["test.email+alex@leetcode.com","test.email.leet+alex@code.com"]
ans = Solution().numUniqueEmails(test)
print(ans)


import math
import torch.nn as nn
import numpy as np
from collections import OrderedDict

class SEBlock(nn.Module):
    '''
    原理：
        1. 着重于模型设计中channel之间的关系
        2. SE通过对通道之间的相互依存关系显示建模来重新校准channel-wise feature，
            以此来选择性强调 information features、抑制 less useful ones.
        3. 提升了模型的表达能力
    出发点 & 目的：
        1. 每个卷积操作只能学习到局部的receptive field，而学习不到该区域以外的上下文信息
        2. SE block 让network对informative feature更加敏感，并且抑制没用的feature
    '''
    def __init__(self, planes, reduction=16):
        super(SEBlock, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Sequential(
            nn.Linear(planes, planes // reduction),
            nn.PReLU(),
            nn.Linear(planes // reduction, planes),
            nn.Sigmoid())

    def forward(self, x):
        b, c, _, _ = x.size()
        y = self.avg_pool(x).view(b, c)
        y = self.fc(y).view(b, c, 1, 1)
        return x * y

class IRBlock(nn.Module):
    '''
    IRBlock Resnet residual block

    Args:
        inplanes[in]: Number of channels in the input image
        outplanes[in]: Number of channels in the output image
        stride[in]: Stride for conv. Default: 1
        droprate[in]: Dropout rate for dropout layer. Default: 0.0
        downsample[in]: Downsample function for shortcut. Default: None
    '''
    expansion = 1

    def __init__(self, inplanes, outplanes, stride=1,
            bias=False, downsample=None, use_se=False):
        super(IRBlock, self).__init__()
        self.use_se = use_se

        # conv1
        self.bn0 = nn.BatchNorm2d(inplanes, affine=True)
        self.conv1 = nn.Conv2d(inplanes, inplanes, kernel_size=3,
            stride=1, padding=1, bias=bias)
        self.prelu = nn.PReLU()
        self.bn1 = nn.BatchNorm2d(inplanes, affine=True)

        # conv2
        self.conv2 = nn.Conv2d(inplanes, outplanes, kernel_size=3,
            stride=stride, padding=1, bias=bias)
        self.bn2 = nn.BatchNorm2d(outplanes, affine=True)

        self.downsample = downsample
        if use_se:
            self.se = SEBlock(outplanes)

    def forward(self, x):
        shortcut = x

        # conv1
        residual = self.bn0(x)
        residual = self.conv1(residual)
        residual = self.bn1(residual)
        residual = self.prelu(residual)

        # conv2
        residual = self.conv2(residual)
        residual = self.bn2(residual)

        if self.use_se:
            residual = self.se(residual)

        # downsample
        if self.downsample is not None:
            shortcut = self.downsample(x)

        out = self.prelu(residual + shortcut)

        return out

class LResNet(nn.Module):
    def __init__(self, layers, embedding_size, use_se=False):
        super(LResNet, self).__init__()
        self.use_se = use_se
        self.inplanes = 64

        # 3x112x112 => 64x56x56
        m = OrderedDict()
        m['conv1'] = nn.Conv2d(3, 64, kernel_size=3,
            stride=1, padding=1, bias=False)
        m['bn1'] = nn.BatchNorm2d(64)
        m['prelu'] = nn.PReLU()
        self.group1 = nn.Sequential(m)

        # 64x56x56 => 64x56x56 => 128x28x28 => 256x14x14 => 512x7x7
        self.layer1 = self._make_layer(64, layers[0], stride=2)
        self.layer2 = self._make_layer(128, layers[1], stride=2)
        self.layer3 = self._make_layer(256, layers[2], stride=2)
        self.layer4 = self._make_layer(512, layers[3], stride=2)

        self.group2 = nn.Sequential(
            OrderedDict([
                ('bn2', nn.BatchNorm2d(512)),
                ('dropout', nn.Dropout())
            ])
        )

        self.group3 = nn.Sequential(
            OrderedDict([
                ('fc', nn.Linear(512 * 7 * 7, embedding_size)),
                ('bn3', nn.BatchNorm1d(512))
            ])
        )

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                # equal to nn.init.xavier_normal_(m.weight)
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d) or isinstance(m, nn.BatchNorm1d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def forward(self, x):
        out = self.group1(x)

        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.layer4(out)

        out = self.group2(out)
        out = out.view(out.size(0), -1)
        out = self.group3(out)

        return out

    def _make_layer(self, planes, blocks, stride=1):
        downsample = None

        # downsample for shortcut
        if stride != 1 or self.inplanes !=  planes*IRBlock.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes*IRBlock.expansion,
                    kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * IRBlock.expansion))

        # the number of block is blocks
        # the first block increase the depth
        layers = []
        layers.append(IRBlock(self.inplanes, planes, stride,
            bias=False, downsample=downsample, use_se=self.use_se))
        self.inplanes = planes * IRBlock.expansion
        for _ in range(1, blocks):
            layers.append(IRBlock(self.inplanes, planes))

        return nn.Sequential(*layers)

def LResNet50(embedding_size, use_se=True, **kwargs):
    model = LResNet([3, 4, 14, 3], embedding_size, use_se)
    return model

def LResNet100(embedding_size, use_se=True, **kwargs):
    model = LResNet([3, 13, 30, 3], embedding_size, use_se)
    return model


# Module 1
# Excerise 1
fname = input("Input your First Name : ")
lname = input("Input your Last Name : ")
print ("Hello  " + lname + " " + fname)

# Excerise 2
a = int(input("Input an integer : "))
n1 = int( "%s" % a )
n2 = int( "%s%s" % (a,a) )
n3 = int( "%s%s%s" % (a,a,a) )
print (n1+n2+n3)

# Excercise 3
country  = str(input("What country are you from: "))

print('I have heard that '+ country + ' is a beautiful country.')

# Excercise 4
# n = int(input("Input a number: "))

n = 4

# use for loop to iterate 10 times
for i in range(1,11):
   print(n,'x',i,'=',n*i)

  # Excercise 5
   # n = int(input("Input a number: "))

n = 4

# use for loop to iterate 10 times
for i in range(1,11):
   print(n,'x',i,'=',n*i)

   #Excercise 5
   for i in range(1,11):
    for j in range (1,11):
        print(i*j, end='\t')
    print ('')


import sys
import os
import inspect
import subprocess
import hashlib

from python_toolkit.fileHelpers import find_files
from hdl_toolkit.intfLvl import UnitFromHdl

class VivadoHlsConfig():
    EXECUTABLE = ["bash", "/opt/Xilinx/Vivado_HLS/2015.2/vivado_hls.sh"]

def hashFile(file, hasher):
    BLOCKSIZE = 65536
    with open(file, 'rb') as afile:
        buf = afile.read(BLOCKSIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = afile.read(BLOCKSIZE)

def getHashInfoDirs(directory, exceptFiles=[]):
    hasher = hashlib.md5()
    if not os.path.exists (directory):
        return -1

    for root, dirs, files in os.walk(directory):
        for names in files:
            filepath = os.path.join(root, names)
            if filepath in exceptFiles:
                continue
            try:
                f1 = open(filepath, 'rb')
            except:
                # You can't open the file for some reason
                f1.close()
                continue

            while 1:
                # Read file in as little chunks
                buf = f1.read(4096)
                if not buf:
                    break
                hasher.update(hashlib.md5(buf).digest())
            f1.close()

    return hasher.digest()

class VivadoHLSUnit(UnitFromHdl):
    """
    @cvar _project: path to vivado hls project
    @cvar _top    : name of top
    """
    __hashFileName = "__hash__.txt"

    @classmethod
    def _runSynthesisInVivadoHls(cls):
        hashFileN = os.path.join(cls._project, cls.__hashFileName)
        try:
            with open(hashFileN) as hf:
                oldHash = int(hf.readline())
        except:
            oldHash = 0

        def getActualHash():
            return int.from_bytes((getHashInfoDirs(cls._project, exceptFiles=[hashFileN])), byteorder='little')

        actualHash = getActualHash()
        if oldHash != actualHash:
            #print("synt", oldHash, actualHash)
            originalCWD = os.getcwd()
            os.chdir(os.path.join(cls._project, ".."))

            synTcl = os.path.join(cls._project, "solution1/script.tcl")
            cmd = []
            cmd.extend(VivadoHlsConfig.EXECUTABLE)
            cmd.append(synTcl)
            sp = subprocess.Popen(cmd, shell=False,
                                 stdout=subprocess.DEVNULL, stderr=sys.stderr)
            sp.wait()
            os.chdir(originalCWD)
            actualHash = getActualHash()
            with open(hashFileN, "w") as hf:
                hf.write("%d" % actualHash)

        cls._collectSources()

    @classmethod
    def _collectSources(cls):
        cls._hdlSources = sorted(find_files(os.path.join(cls._project, "solution1/syn/vhdl/"), '*.vhd'),
                                  key=lambda f : f.endswith(cls._top + ".vhd"))

    @classmethod
    def _build(cls):
        # convert source filenames to absolute paths
        assert cls._project
        assert cls._top
        baseDir = os.path.dirname(inspect.getfile(cls))
        cls._project = os.path.join(baseDir, cls._project)

        cls._runSynthesisInVivadoHls()

        super(VivadoHLSUnit, cls)._build()


# -*- coding: utf-8 -*-
# @Author: chunyang.xu
# @Date:   2022-01-05 07:02:14
# @Last Modified by:   chunyang.xu
# @Last Modified time: 2022-01-13 12:50:31

import os
import json
import time
import requests
import shutil
import subprocess
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor

import m3u8
from Crypto.Cipher import AES

from mysetting import DOMAIN, APP_ID, HEADERS, COURSEAPI, PAGEAPI, COURSEDATA
from chrome_cookie import GetCooikiesFromChrome

import logging
import colorlog
log_colors_config = {
    'DEBUG': 'cyan',
    # 'INFO': 'yellow',
    'WARNING': 'red',
    'ERROR': 'red',
    'CRITICAL': 'red',
}
formatter = colorlog.ColoredFormatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(lineno)d - %(log_color)s%(message)s',
            log_colors=log_colors_config)

handler = logging.StreamHandler()
handler.setFormatter(formatter)
dlogger = logging.getLogger(__name__)
dlogger.addHandler(handler)
dlogger.setLevel(logging.DEBUG)

TARGETPATH = r'F:\深度之眼\tableau'

class XiaoE:

    def __init__(self, app_id, domain, headers, courseapi, pageapi):
        self.app_id = app_id
        self.domain = domain
        self.headers = headers
        self.courseapi = courseapi
        self.pageapi = pageapi
        self.cookie = self._get_cookie()
        self._check_targetpath()

    def _check_targetpath(self):
        if not os.path.exists(TARGETPATH):
            raise FileNotFoundError(f"[Errno 2] No such file or directory: '{TARGETPATH}', please change Variable 'TARGETPATH'")

    def _get_cookie(self):
        get_cookies = GetCooikiesFromChrome()
        cookie = get_cookies.get(self.domain)
        return cookie

    def create_headers(self):
        if not self.cookie:
            raise ValueError("please login")

        self.headers['Cookie'] = self.cookie
        return self.headers

    def myrequests_get(self, url, headers=None):
        try:
            req = requests.get(url, headers=headers, timeout=60)
        except Exception as e:
            dlogger.error(f"request 【{url}】 error, re request, error: {str(e)[:100]}")
            time.sleep(3)
            req = self.myrequests_get(url, headers=headers)

        while req.status_code != 200:
            # dlogger.warning(f"【{req.status_code}】request 【{url}】 error, re request")
            time.sleep(1)
            req = self.myrequests_get(url, headers=headers)
        return req

    def get_courseslist(self, coursedata):
        headers = self.create_headers()
        res = requests.post(self.courseapi, headers=headers, data=coursedata)
        res_json = res.json()
        # with open('./goods.json', 'w', encoding='utf-8') as f:
        #     json.dump(res_json, f)
        courseslist = res_json.get('data').get('goods_list')
        return courseslist

    def get_courseinfo(self, course):
        data = {}
        data['page_size'] = 20
        data['goods_id'] = course.get('term_id')
        data['goods_type'] = 25
        data['resource_type'] = [1, 2, 3, 4, 20]
        data['node_id'] = course.get('node_id')
        data['type'] = 1
        data['order_type'] = 0
        data = json.dumps(data)
        # dlogger.info(data)
        headers = self.create_headers()
        res = requests.post(self.courseapi, headers=headers, data=data)
        res_json = res.json()
        courseinfo = res_json.get('data').get('goods_list')
        return courseinfo

    def get_pageinfo(self, courseinfo):
        data = {}
        data['goods_id'] = courseinfo.get('node_id')
        data['goods_type'] = courseinfo.get('resource_type')

        data = json.dumps(data)
        # dlogger.info(data)
        headers = self.create_headers()
        res = requests.post(self.pageapi, headers=headers, data=data)
        res_json = res.json()
        pageinfo = res_json.get('data')
        return pageinfo

    def download_html(self, pageinfo):
        title = pageinfo.get('title')
        pagecontent = pageinfo.get('content')
        with open(f'{TARGETPATH}/{title}.html', 'w', encoding='utf-8') as f:
            f.write(pagecontent)

    def download_video(self, pageinfo):
        def create_video_headers():
            video_headers = {}
            video_headers['host'] = 'encrypt-k-vod.xet.tech'
            headers = self.create_headers()
            video_headers['referer'] = headers['referer']
            video_headers['user-agent'] = headers['user-agent']
            return video_headers

        def get_m3u8_data(m3u8_url):
            video_headers = create_video_headers()
            res = self.myrequests_get(m3u8_url, video_headers)
            m3u8_data = res.text
            if "#EXTM3U" not in m3u8_data:
                raise BaseException("非M3U8的链接")
            return m3u8_data

        def download_ts(m3u8_url, id, segment, temppath):
            url_prefix = m3u8_url.split('drm')[0] + 'drm/' if 'drm/' in m3u8_url else m3u8_url.split('v.f')[0]
            video_headers = create_video_headers()
            file_tmp = os.path.join(temppath, f"{id:0>4d}.ts")
            try:
                # key_method = segment.get('key').get('method')
                key_url = segment.get('key').get('uri')
                key = self.myrequests_get(key_url).content
                key_iv = segment.get('key').get('iv')
                key_iv = key_iv.replace("0x", "")[:16].encode()  # 偏移码
            except Exception as e:
                dlogger.error(e)
                key = None

            url = url_prefix + segment.get('uri')  # 拼接完整url
            res = self.myrequests_get(url, video_headers).content  # 获取视频内容
            if key:  # AES 解密
                try:
                    cryptor = AES.new(key, AES.MODE_CBC, key_iv)
                    with open(file_tmp, 'wb') as f:
                        f.write(cryptor.decrypt(res))
                except Exception as e:
                    dlogger.warning(f"{e}, id: {id}, segment: {segment}")
                    download_ts(url_prefix, id, segment, temppath)
            else:
                with open(file_tmp, 'wb') as f:
                    f.write(res)

        def merge_ts2mp4(title):
            temppath = os.path.join(TARGETPATH, title)
            temppath = temppath.replace('/', '\\')  # 后续用户合并，使用windows命令，必须这样处理
            targetpath = os.path.join(TARGETPATH, f'{title}.mp4')
            targetpath = targetpath.replace('/', '\\')  # 后续用户合并，使用windows命令，必须这样处理
            subresult = subprocess.run(["copy", "/b", f"{os.path.join(temppath, '*.ts')}", f"{targetpath}"],
                                       stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

            if not os.path.isfile(targetpath):
                dlogger.warning(f"stdin: {subresult.args}, stderr: {subresult.stderr}")
            else:
                shutil.rmtree(temppath)

        title = pageinfo.get('title')
        temppath = os.path.join(TARGETPATH, title)
        # 生成ts临时文件夹
        if not os.path.exists(temppath):
            os.mkdir(temppath)

        m3u8_url = pageinfo.get('video_m3u8')
        m3u8_data = get_m3u8_data(m3u8_url)
        m3u8_data = m3u8.loads(m3u8_data).data
        segments = m3u8_data.get('segments')
        segments_num = len(segments)

        with ThreadPoolExecutor(max_workers=60) as threadpool:
            list(tqdm(threadpool.map(download_ts, [m3u8_url]*segments_num, range(segments_num),
                      segments, [temppath]*segments_num),
                 total=segments_num, ncols=80, desc=f"[{title}](ts下载)"))

        merge_ts2mp4(title)

    def download(self, pageinfo):
        self.download_html(pageinfo)
        self.download_video(pageinfo)

    def download_by_course(self, course):
        st = time.time()
        courseinfo = self.get_courseinfo(course)

        if not courseinfo:
            lock_state = course.get('lock_state')
            title = course.get('title')
            unlock_time = course.get('unlock_time')
            if lock_state == 0:
                dlogger.warning(f"【{title}】 lock, unlock_time: {unlock_time} !")
            else:
                dlogger.warning(f"【{title}】 have no page !")
            return

        pageinfo = self.get_pageinfo(courseinfo[0])

        title = pageinfo.get('title')
        targetpath = os.path.join(TARGETPATH, f'{title}.mp4')
        if not os.path.exists(targetpath):
            self.download(pageinfo)
            et = time.time()
            dlogger.info(f"download 【{title}】 cost {et - st:.2f} seconds !")
        else:
            dlogger.info(f"{targetpath} already exists")

if __name__ == '__main__':
    xe = XiaoE(APP_ID, DOMAIN, HEADERS, COURSEAPI, PAGEAPI)
    courseslist = xe.get_courseslist(COURSEDATA)
    for course in courseslist:
        courseinfo = xe.download_by_course(course)


from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
    path('juegos/',views.juegos,name='juegos'),
    path('tarjetas/',views.tarjetas,name='tarJetas'),
    path('formulario/',views.formulario,name='formulario'),
    path('ju/',views.JuegoListView.as_view(),name='ju'),
    path('ju/<int:pk>',views.JuegoDetailView.as_view(),name='juego-detail'),
    path('compañia/<int:pk>',views.CompañiaDetailView.as_view(), name='compañia-detail'),
    path('compañia/',views.ComapñiaListView.as_view(),name='compañia'),
    path('genero/<int:pk>',views.GeneroDetailView.as_view(), name='genero-detail'),
    path('genero/',views.GeneroListView.as_view(),name='genero'),
]

urlpatterns+= [
    path('compañia/create/',views.CompañiaCreate.as_view(), name='compañia_create'),
    path('compañia/<int:pk>/delete/',views.CompañiaDelete.as_view(), name='compañia_delete'),
    path('compañia/<int:pk>/update/',views.CompañiaUpdate.as_view(), name='compañia_update'),

    path('ju/create/',views.JuegoCreate.as_view(), name='juego_create'),
    path('ju/<int:pk>/delete/',views.JuegoDelete.as_view(), name='juego_delete'),
    path('ju/<int:pk>/update/',views.JuegoUpdate.as_view(), name='juego_update'),

    path('genero/create/',views.GeneroCreate.as_view(), name='genero_create'),
    path('genero/<int:pk>/delete/',views.GeneroDelete.as_view(), name='genero_delete'),
    path('genero/<int:pk>/update/',views.GeneroUpdate.as_view(), name='genero_update'),
]


from multiprocessing.sharedctypes import Value
from pathlib import Path
import requests
import responses
from cdcs import CDCS
from pytest import raises

from mock_database import *

class TestCDCS():

    @property
    def host(self):
        """str: A fake host url for testing"""
        return 'https://fakeurl.fake'

    @property
    def cdcs_v3(self):
        try:
            return self.__cdcs_v3
        except:
            with responses.RequestsMock() as rsps:
                rsps.add(responses.GET, f'{self.host}/rest/core-settings/', status=200,
                     json={'core_version':'2.0.1'})
                cdcs = CDCS(host=self.host, username='')
            self.__cdcs_v3 = cdcs
            return self.__cdcs_v3

    @responses.activate
    def test_get_xslts_v3(self):
        """Tests get_xslts()"""

        # Add Mock responses
        xslt_responses(self.host, 3)

        # Test get_blobs() with no arguments
        xslts = self.cdcs_v3.get_xslts()
        assert xslts.id.tolist() == [1, 2, 3, 4]
        assert xslts.name.tolist() == ['template1-xsl1', 'template1-xsl2',
                                       'template2-xsl1', 'template3-xsl1']

    @responses.activate
    def test_get_xslt_v3(self):
        """Tests get_xslt()"""

        # Add Mock responses
        xslt_responses(self.host, 3)

        # Test get_xslt() with filename
        xslt = self.cdcs_v3.get_xslt(name='template1-xsl1')
        assert xslt.id == 1
        assert xslt.filename == 'template1-xsl1.xsl'

        # Test get_xslt() with id
        xslt = self.cdcs_v3.get_xslt(filename='template2-xsl1.xsl')
        assert xslt.id == 3
        assert xslt['name'] == 'template2-xsl1'

        # Test get_xslt() errors for multiple, no matches
        with raises(ValueError):
            xslt = self.cdcs_v3.get_xslt()
        with raises(ValueError):
            xslt = self.cdcs_v3.get_xslt(filename='fake.txt')

    @responses.activate
    def test_upload_xslt_v3(self, tmpdir):
        """Tests upload_xslt()"""

        # Add Mock responses
        xslt_responses(self.host, 3)

        # Create xslt name, content and file
        filename = Path(tmpdir, 'template3-xsl1.xsl')
        name = 'template3-xsl1'
        content = '<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/TR/xhtml1/strict"> <xsl:output method="html" encoding="utf-8" indent="yes" /></xsl:stylesheet>'
        with open(filename, 'w') as f:
            f.write(content)

        # Test upload_xslt() with only a filename
        self.cdcs_v3.upload_xslt(filename=filename)

        # Test upload_xslt() from name and content
        self.cdcs_v3.upload_xslt(name=name, content=content)

        # Test upload_xslt() from name, filename, and content
        self.cdcs_v3.upload_xslt(name=name, filename=filename, content=content)

    @responses.activate
    def test_update_xslt_v3(self, tmpdir):
        """Tests update_xslt()"""

        # Add Mock responses
        xslt_responses(self.host, 3)

        # Create xslt name, content and file
        filename = Path(tmpdir, 'template3-xsl1.xsl')
        name = 'template3-xsl1'
        content = '<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/TR/xhtml1/strict"> <xsl:output method="html" encoding="utf-8" indent="yes" /></xsl:stylesheet>'
        with open(filename, 'w') as f:
            f.write(content)

        xslt = self.cdcs_v3.get_xslt(name='template3-xsl1')

        # Test update_xslt()
        self.cdcs_v3.update_xslt(xslt=xslt, filename=filename, name=name)

        # Test update_xslt()
        self.cdcs_v3.update_xslt(xslt_id=4, filename=filename, name=name)

    @responses.activate
    def test_delete_xslt_v3(self):
        """Tests delete_xslt()"""

        # Add Mock responses
        xslt_responses(self.host, 3)

        xslt = self.cdcs_v3.get_xslt(name='template3-xsl1')

        # Test delete_xslt()
        self.cdcs_v3.delete_xslt(xslt=xslt)
        self.cdcs_v3.delete_xslt(xslt_id=4)
        self.cdcs_v3.delete_xslt(filename='template3-xsl1.xsl')

        # Test delete_xslt() with invalid inputs
        with raises(ValueError):
            self.cdcs_v3.delete_xslt(xslt=xslt, xslt_id=4)
        with raises(ValueError):
            self.cdcs_v3.delete_xslt(xslt=xslt, filename='template3-xsl1.xsl')
        with raises(ValueError):
            self.cdcs_v3.delete_xslt(xslt_id=4, filename='template3-xsl1.xsl')


#!/usr/bin/env python

import argparse
import os
import sys

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Prepare segmentation data")
    parser.add_argument("mode", type=str, choices=["gazebo_plugin"],
                        help="annotation format type")
    parser.add_argument("data_path", type=str,
                        help="Path to the directory of the dataset.")
    args = parser.parse_args()

    pairs = []
    if args.mode == "gazebo_plugin":
        files = os.listdir(args.data_path)
        label_files = [f for f in files if "label" in f]
        for label_file in label_files:
            img_file = label_file.replace("_labels", "")
            pairs.append((img_file, label_file))

    content = ""
    for pair in pairs:
        content += pair[0] + "\t" + pair[1] + "\n"
    content = content[:-1]  # cut last \n

    with open(os.path.join(args.data_path, "train.list"), "w+") as f:
        f.write(content)


import sys
import os
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt

def aa_composition(fasta_folder):
    f = fasta_folder
    for fasta_filename in os.listdir(f):
        fasta_file = open(fasta_filename, "r")
        for line in fasta_file:
            stripped_line = line.rstrip()
            if line[0] == ">" :
                continue
            else:
                aa_counter = Counter(stripped_line)
                print(aa_counter)

    return()

if __name__ == "__main__":
    fasta_folder = sys.argv[1]
    aa_composition(fasta_folder)


from cv2 import cv2
import numpy as np

from datetime import datetime
StartProcess = datetime.now()
from time import time

from PIL import Image

# DB
import pymysql
# GUID
import uuid

# Multi hilo_1 Test
import threading
import logging

#///////////////////////////////////////////
# Generamos Un GUID
#///////////////////////////////////////////
IdUnico = uuid.uuid4()
GuidTest = str(IdUnico)

#////////////////////////
CountFrame = 1

#/////////////////////////////
# Scalas
Scalas = [1,2,3,4,5,6,7,8]

#///////////////////////
# Time start

FrameProcess = 'scene1.png'

def FrameProcessing (Scala, FrameProcess):
    #print ("****************************************************")
    #print ("---------------New Frame Processing " , Scala,  "----------------")
    #/////////////////////////
    # Setting
    # Time start

    #starttimeScala = time()
    PercentageTotal = []
    PixelBlack = 0
    Pixelcolor = 0

    # Clasificacion de scalas
    if (Scala == 1):
        # High Red
        Color = "High Red"
        Scala_bajos = np.array([170, 100, 20])
        Scala_altos = np.array([179, 255, 255])
    elif (Scala == 2):
        # Low Red
        Color = "Low Red"
        Scala_bajos = np.array([0, 100, 20])
        Scala_altos = np.array([8, 255, 255])
    elif (Scala == 3):
        # orange
        Color = "Orange"
        Scala_bajos = np.array([9, 100, 20])
        Scala_altos = np.array([19, 255, 255])
    elif (Scala == 4):
        # yellow
        Color = "Yellow"
        Scala_bajos = np.array([20, 100, 20])
        Scala_altos = np.array([40, 255, 255])
    elif (Scala == 5):
        # Green
        Color = "Green"
        Scala_bajos = np.array([41, 100, 20])
        Scala_altos = np.array([69, 255, 255])
    elif (Scala == 6):
        # light blue
        Color = "Light blue"
        Scala_bajos = np.array([70, 100, 20])
        Scala_altos = np.array([105, 255, 255])
    elif (Scala == 7):
        # blue
        Color = "Blue"
        Scala_bajos = np.array([106, 100, 20])
        Scala_altos = np.array([129, 255, 255])
    else:
        #fuchsia
        Color = "Fuchsia"
        Scala_bajos = np.array([130,100, 20])
        Scala_altos = np.array([169, 255, 255])
    starttimeScala = time()
    #print (Scala, Color, Scala_bajos, Scala_bajos)

    #Cargamos la imagen
    #FrameProcess = "scene" + str(CountFrame) + ".png"
    img = cv2.imread(FrameProcess)

    #Convertimos la imagen a hsv:
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    #Detectamos los píxeles que estén dentro del rango que hemos establecido:
    mask = cv2.inRange(hsv, Scala_bajos, Scala_altos)

    # Escribir Frame Mask (Blanco y Negro)
    FramePresado ='FramePresado-' + str(Scala) +'.png'
    cv2.imwrite(FramePresado, mask)

    # Frame Analisis (Blanco y Negro)
    FrameColor = Image.open(FramePresado)
    # total de Pixeles y color de cada uno
    datos = list(FrameColor.getdata())
    # Segmentar Pixeles
    for dato in datos:
        if (int(dato)> 0):
            # Total de Pixeles Blanco-Color True
            Pixelcolor += 1
        else:
            # Total de Pixeles Negro-Color False
            PixelBlack += 1
    FrameColor.close()

    # Calculo Total de pixels y del % de Pixeles-color segun la scala
    TotalPixelsImg = len(datos)
    PorcentajeColorPixel = Pixelcolor*100/(Pixelcolor + PixelBlack)
    PorcentajeColorPixel = float("{0:.2f}".format(PorcentajeColorPixel))

    #AnalisisColor = [color, Pixelcolor]

    """print("")
    print (" - Frame: ", FrameProcess)
    print (" - ScalaID: ", Scala)
    print (" - Scala-Color: ", Color)
    print (" - Pixel-Total: ", TotalPixelsImg)
    print (" - Pixel-Back: ", PixelBlack)
    print (" - Pixel-Color: ", Pixelcolor)
    print (" - % Pixel-Color: ", PorcentajeColorPixel,"%")
    """
    print (" - ScalaID: ", Scala)
    print (" - Scala-Color: ", Color)
    print (" - % Pixel-Color: ", PorcentajeColorPixel,"%")

    PercentageTotal.append(PorcentajeColorPixel)

    # Time Frame Process
    elapsedtimeScala = time() - starttimeScala
    TimeScala = float("{0:.4f}".format(elapsedtimeScala))

    #
    from AddFrameData import AddDataFrameScala
    AddDataFrameScala (GuidTest, FrameProcess, Scala, TotalPixelsImg, PixelBlack, Pixelcolor, PorcentajeColorPixel, TimeScala)

    #
    print("Elapsed time Scala: ", Scala, " %0.4f seconds." % elapsedtimeScala)
    #print ("")

i= 1
while i < 5:
    start_time = time()
    FrameProcess = 'scene' + str(i) + '.png'
    print ("-------------------", FrameProcess, "-------------------")
    t1 = threading.Thread(name="hilo_1", target=FrameProcessing, args=(1, FrameProcess))
    t2 = threading.Thread(name="hilo_2", target=FrameProcessing, args=(2, FrameProcess))
    t3 = threading.Thread(name="hilo_3", target=FrameProcessing, args=(3, FrameProcess))
    t4 = threading.Thread(name="hilo_4", target=FrameProcessing, args=(4, FrameProcess))
    t5 = threading.Thread(name="hilo_5", target=FrameProcessing, args=(5, FrameProcess))
    t6 = threading.Thread(name="hilo_6", target=FrameProcessing, args=(6, FrameProcess))
    t7 = threading.Thread(name="hilo_7", target=FrameProcessing, args=(7, FrameProcess))
    t8 = threading.Thread(name="hilo_8", target=FrameProcessing, args=(8, FrameProcess))

    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t5.start()
    t6.start()
    t7.start()
    t8.start()

    t1.join()
    t2.join()
    t3.join()
    t4.join()
    t5.join()
    t6.join()
    t7.join()
    t8.join()

    elapsed_time = time() - start_time
    #TimeProcess = float("{0:.4f}".format(elapsed_time))
    #
    print("Elapsed time Total: %0.4f seconds." % elapsed_time)
    i += 1


#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals, print_function
from os.path import join, expanduser
import os
import socket
import logging

__version__ = "0.1.1"
__author__ = "Johan Bloemberg"
__license__ = "MIT"

log = logging.getLogger(__name__)

try:  # Python 2
    import ConfigParser as confiparser
except ImportError:  # Python 3
    import configparser
from configparser import ExtendedInterpolation

def merge(dict_1, dict_2):
    """Merge two dictionaries.

    Values that evaluate to true take priority over falsy values.
    `dict_1` takes priority over `dict_2`.

    """
    return dict((str(key), dict_1.get(key) or dict_2.get(key))
                for key in set(dict_2) | set(dict_1))

def get_environment(appname):
    prefix = '%s_' % appname.upper()
    vars = ([(k, v) for k, v in os.environ.items() if k.startswith(prefix)])

    return dict([(k.replace(prefix, '').lower(), v) for k, v in vars])

def get_config(appname, config_file):
    home = expanduser('~')
    files = [
        join('/etc', appname, 'config'),
        join('/etc', '%src' % appname),
        join(home, '.config', appname, 'config'),
        join(home, '.config', appname),
        join(home, '.%s' % appname, 'config'),
        join(home, '.%src' % appname),
        '%src' % appname,
        '.%src' % appname,
        config_file or ''
    ]

    config = configparser.ConfigParser(interpolation=ExtendedInterpolation())
    read = config.read(files)
    log.debug('files read: %s' % read)

    cfg_items = {}
    if config.has_section(appname):
        cfg_items = dict(config.items(appname))

    hn = socket.gethostname()
    host_section = '{}:{}'.format(appname, hn)
    if config.has_section(host_section):
        host_items = dict(config.items(host_section))
        cfg_items = merge(host_items, cfg_items)

    return cfg_items

def rcfile(appname, args={}, strip_dashes=True):
    """
        Read environment variables and config files and return them merged with
        predefined list of arguments.

        Parameters
        ----------
        appname: str
            Application name, used for config files and environemnt variable
            names.

        args
            arguments from command line (optparse, docopt, etc).

        strip_dashes: bool
            Strip dashes prefixing key names from args dict.

        Returns
        --------
        dict
            containing the merged variables of environment variables, config
            files and args.

        Notes
        -----
        Environment variables are read if they start with appname in uppercase
        with underscore, for example:

            TEST_VAR=1

        Config files compatible with ConfigParser are read and the section name
        appname is read, example:

            [appname]
            var=1

        We can also have host-dependent configuration values, which have
        priority over the default appname values.

            [appname]
            var=1

            [appname:mylinux]
            var=3

        Files are read from: /etc/appname/config,
                             /etc/appfilerc,
                             ~/.config/appname/config,
                             ~/.config/appname,
                             ~/.appname/config,
                             ~/.appnamerc,
                             appnamerc,
                             .appnamerc,
                             file provided by config variable in args.

        Example
        -------
            args = rcfile(__name__, docopt(__doc__, version=__version__))
    """
    if strip_dashes:
        for k in args.keys():
            args[k.lstrip('-')] = args.pop(k)

    environ = get_environment(appname)

    config = get_config(appname, args.get('config', ''))

    return merge(merge(args, config), environ)

#class HostExtendedInterpolation(ExtendedInterpolation):
#    """Advanced variant of interpolation, supports the syntax used by
#    `zc.buildout'. Enables interpolation between sections."""

#    _KEYCRE = re.compile(r"\$\{([^}]+)\}")

#    def before_get(self, parser, section, option, value, defaults):
#        L = []
#        self._interpolate_some(parser, option, L, value, section, defaults, 1)
#        return ''.join(L)

#    def before_set(self, parser, section, option, value):
#        tmp_value = value.replace('$$', '') # escaped dollar signs
#        tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
#        if '$' in tmp_value:
#            raise ValueError("invalid interpolation syntax in %r at "
#                             "position %d" % (value, tmp_value.find('$')))
#        return value

#    def _interpolate_some(self, parser, option, accum, rest, section, map,
#                          depth):
#        if depth > MAX_INTERPOLATION_DEPTH:
#            raise InterpolationDepthError(option, section, rest)
#        while rest:
#            p = rest.find("$")
#            if p < 0:
#                accum.append(rest)
#                return
#            if p > 0:
#                accum.append(rest[:p])
#                rest = rest[p:]
#            # p is no longer used
#            c = rest[1:2]
#            if c == "$":
#                accum.append("$")
#                rest = rest[2:]
#            elif c == "{":
#                m = self._KEYCRE.match(rest)
#                if m is None:
#                    raise InterpolationSyntaxError(option, section,
#                        "bad interpolation variable reference %r" % rest)
#                path = m.group(1).split(':')
#                rest = rest[m.end():]
#                sect = section
#                opt = option
#                try:
#                    if len(path) == 1:
#                        opt = parser.optionxform(path[0])
#                        v = map[opt]
#                    elif len(path) == 2:
#                        sect = path[0]
#                        opt = parser.optionxform(path[1])
#                        v = parser.get(sect, opt, raw=True)
#                    else:
#                        raise InterpolationSyntaxError(
#                            option, section,
#                            "More than one ':' found: %r" % (rest,))
#                except (KeyError, NoSectionError, NoOptionError):
#                    raise InterpolationMissingOptionError(
#                        option, section, rest, ":".join(path))
#                if "$" in v:
#                    self._interpolate_some(parser, opt, accum, v, sect,
#                                           dict(parser.items(sect, raw=True)),
#                                           depth + 1)
#                else:
#                    accum.append(v)
#            else:
#                raise InterpolationSyntaxError(
#                    option, section,
#                    "'$' must be followed by '$' or '{', "
#                    "found: %r" % (rest,))


#!/usr/bin/python3
"""
Function that prints a text with 2 new lines after each '.', '?', ':'
"""
def text_indentation(text):
    if not isinstance(text, str):
        raise TypeError("text must be a string")
    newText = ""
    for i in range(len(text)):
        if not i == 0 and text[i] == " " and text[i - 1] in ".?:":
            continue
        newText += text[i]
        if text[i] in ".?:":
            newText += "\n\n"
    print(newText, end="")


#!/usr/bin/env python3

class Solution:
    def reverse(self, x: int) -> int:
        """
        Given a 32-bit signed integer, reverse digits of an integer.

        Example 1:
        Input: 123
        Output: 321

        :type x: int
        :rtype: int
        """
        convert_int = ""
        result = -1

        if x == 0:
            return x
        elif x < 0:
            convert_int = str(abs(x))
            result = (int(convert_int[::-1]) * -1)
            if result < 2**31 * -1:
                return 0
            else:
                return result

        elif x > 0:
            convert_int = str(x)
            result = int(convert_int[::-1])

            if result > 2**31 - 1:
                return 0
            else:
                return result

solution = Solution()

print(solution.reverse.__doc__)
print("Inputting -321, expecting -123 => {0}".format(solution.reverse(-321)))


import webapp2
import base_page
from google.appengine.ext import ndb
import db_defs

def input_validation(self, message):
	bad_val = False

	if self.request.get('book_name') == None or self.request.get('book_name') == '':
		bad_val = True
		message['title'] = 'Title can not be left blank'
	if self.request.get('author_name') == None or self.request.get('author_name') == '':
		bad_val = True
		message['author'] = 'Author can not be left blank'
	if self.request.get('book_genre') == None or self.request.get('book_genre') == '':
		bad_val = True
		message['title'] = 'Genre can not be left blank'
	if self.request.get('book_rating') == None or self.request.get('book_rating') == '':
		bad_val = True
		message['title'] = 'Rating can not be left blank'
	if bad_val:
		return 1
	else:
		return 0

def add_book(self, book, message):
	validate = input_validation(self, message)

	if validate:
		return 1
	else:
		book.title = self.request.get('book_name')
		book.author = self.request.get('author_name')
		book.genre = self.request.get('book_genre')
		book.rating = int(self.request.get('book_rating'))

		if self.request.get('recommended_read') == "Yes":
			book.recommended = True
		else:
			book.recommended = False
		if (self.request.get('review_url') != None and self.request.get('review_url') != ''):
			book.url = self.request.get('review_url')
		else:
			book.url = None

		book.put()
		return 0

class Admin(base_page.BaseHandler):

	def __init__(self, request, response):
		self.initialize(request, response)
		self.template_values = {}

	def get(self):
		self.render('admin.html', self.template_values)

	def post(self):
		message = {}
		bookKey = ndb.Key(db_defs.Book, 'Book')

		book = db_defs.Book(parent=bookKey)

		if add_book(self, book, message):
			message['0'] = 'Book not added'
		else:
			message['0'] = 'Book ' + book.title + ' was added.'

		self.template_values['message'] = message
		self.render('admin.html', self.template_values)


#!/usr/bin/env python
# Copyright (c) 2010 DFCI/HSPH
# Author: Chongzhi Zang
#
# This software is distributable under the terms of the GNU General
# Public License (GPL) v2, the text of which can be found at
# http://www.gnu.org/copyleft/gpl.html. Installing, importing or
# otherwise using this module constitutes acceptance of the terms of
# this License.
#
# Disclaimer
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# Comments and/or additions are welcome (send e-mail to:
# czang@jimmy.harvard.edu).

import re, os, sys, shutil
from math import *
from string import *
from optparse import OptionParser
import operator

## from a gene expression data matrix, output a list of genes with at least one sample abs >= threshold.

def process(infile, threshold, outfile):
	f = open(infile,'r')
	o = open(outfile, 'w')
	for line in f:
		if not re.match("#", line):
			line = line.strip()
			sline = line.split()
			List = []
			for i in range(1,len(sline)):
				List.append(abs(atof(sline[i])))
			if max(List) >= threshold:
				o.write(sline[0]+'\n')
	f.close()
	o.close()

def main(argv):

	parser = OptionParser()
	parser.add_option("-a", "--all_input_file", action="store", type="string",
                      dest="in_file", help="island bed file", metavar="<file>")
	parser.add_option("-t", "--threshold", action="store", type="float",
                      dest="threshold", help="cutoff", metavar="<float>")
	parser.add_option("-o", "--output_file_name", action="store", type="string",
                      dest="out_file", help="output file name", metavar="<file>")

	(opt, args) = parser.parse_args(argv)
	if len(argv) < 6:
        	parser.print_help()
        	sys.exit(1)

	process(opt.in_file, opt.threshold, opt.out_file)

if __name__ == "__main__":
	main(sys.argv)


import telebot
import os
import time
from telebot import types

about = "Описание блюда"
id = [1,2,3,4]
class items:
	def garnir(message):
		bot = telebot.TeleBot('')
		f = open('images/1.jpg', 'rb')
		bot.send_photo(message.chat.id, f, None)
		keyboard = types.InlineKeyboardMarkup()
		it1 = types.InlineKeyboardButton(text="100 гр - 80 р",callback_data='buyy'+str(id[0]))
		keyboard.add(it1)
		bot.send_message(message.chat.id, about, reply_markup=keyboard)
		f = open('images/2.jpg', 'rb')
		bot.send_photo(message.chat.id, f, None)
		keyboard = types.InlineKeyboardMarkup()
		it2 = types.InlineKeyboardButton(text="100 гр - 100 р",callback_data='buyy'+str(id[1]))
		keyboard.add(it2)
		bot.send_message(message.chat.id, about, reply_markup=keyboard)
		f = open('images/3.jpg', 'rb')
		bot.send_photo(message.chat.id, f, None)
		keyboard = types.InlineKeyboardMarkup()
		it3 = types.InlineKeyboardButton(text="100 гр - 75 р",callback_data='buyy'+str(id[2]))
		keyboard.add(it3)
		bot.send_message(message.chat.id, about, reply_markup=keyboard)
		f = open('images/4.jpg', 'rb')
		bot.send_photo(message.chat.id, f, None)
		keyboard = types.InlineKeyboardMarkup()
		it4 = types.InlineKeyboardButton(text="100 гр - 83 р",callback_data='buyy'+str(id[3]))
		keyboard.add(it4)
		bot.send_message(message.chat.id, about, reply_markup=keyboard)


import FWCore.ParameterSet.Config as cms
import FWCore.ParameterSet.VarParsing as VarParsing

#----------------------------------------------------------------------------

# Setup Settings for ONIA TREE: PbPb 2018

HLTProcess     = "HLT" # Name of HLT process
isMC           = False # if input is MONTECARLO: True or if it's DATA: False
muonSelection  = "TwoGlbAmongThree" # Single muon selection: Glb(isGlobal), GlbTrk(isGlobal&&isTracker), Trk(isTracker), TwoGlbAmongThree (which requires two isGlobal for a trimuon, and one isGlobal for a dimuon) are available
applyEventSel  = True # Only apply Event Selection if the required collections are present
OnlySoftMuons  = True # Keep only isSoftMuon's (with highPurity because this is pp config) from the beginning of HiSkim. In any case, if applyCuts=True, isSoftMuon is required at HiAnalysis level for muons of selected dimuons.
applyCuts      = True # At HiAnalysis level, apply kinematic acceptance cuts + identification cuts (isSoftMuon or isTightMuon, depending on TightGlobalMuon flag) for muons from selected di(tri)muons + hard-coded cuts on the di(tri)muon that you would want to add (but recommended to add everything in LateDimuonSelection, applied at the end of HiSkim)
SumETvariables = False  # Whether to write out SumET-related variables
SofterSgMuAcceptance = True # Whether to accept muons with a softer acceptance cuts than the usual (pt>3.5GeV at central eta, pt>1.8 at high |eta|). Applies when applyCuts=True
doTrimuons     = True # Make collections of trimuon candidates in addition to dimuons, and keep only events with >0 trimuons
flipJpsiDirection = 7 # (number of) Flip direction of Jpsi momentum and PV-SV, before combining it with a third muon
doDimuonTrk    = False # Make collections of Jpsi+track candidates in addition to dimuons
atLeastOneCand = True # Keep only events that have one selected dimuon (or at least one trimuon if doTrimuons = true). BEWARE this can cause trouble in .root output if no event is selected by onia2MuMuPatGlbGlbFilter!
OneMatchedHLTMu = 13   # Keep only di(tri)muons of which the one(two) muon(s) are matched to the HLT Filter of this number. You can get the desired number in the output of oniaTree. Set to -1 for no matching. WARNING: it is the trigger bit+1 !
muonLessPV     = False  # Recalculate the PV without the two muons from the selected dimuon
#############################################################################
keepExtraColl  = False # General Tracks + Stand Alone Muons + Converted Photon collections
useSVfinder    = False # External SV finder to check if the muons are from a resolved SV
#----------------------------------------------------------------------------

# Print Onia Tree settings:
print( " " )
print( "[INFO] Settings used for ONIA TREE: " )
print( "[INFO] isMC                 = " + ("True" if isMC else "False") )
print( "[INFO] applyEventSel        = " + ("True" if applyEventSel else "False") )
print( "[INFO] keepExtraColl        = " + ("True" if keepExtraColl else "False") )
print( "[INFO] SumETvariables       = " + ("True" if SumETvariables else "False") )
print( "[INFO] SofterSgMuAcceptance = " + ("True" if SofterSgMuAcceptance else "False") )
print( "[INFO] muonSelection        = " + muonSelection )
print( "[INFO] onlySoftMuons        = " + ("True" if OnlySoftMuons else "False") )
print( "[INFO] doTrimuons           = " + ("True" if doTrimuons else "False") )
print( " " )

# set up process
process = cms.Process("HIOnia")

# setup 'analysis'  options
options = VarParsing.VarParsing ('analysis')

# Input and Output File Names
options.outputFile = "Oniatree.root"
options.secondaryOutputFile = "Jpsi_DataSet.root"
options.inputFiles =[
  'file:657ECBA9-4E31-0448-B23A-980CF9137A25.root'
  #'/store/hidata/HIRun2018A/HIDoubleMuonPsiPeri/AOD/04Apr2019-v1/260002/657ECBA9-4E31-0448-B23A-980CF9137A25.root',
  #'/store/hidata/HIRun2018A/HIDoubleMuon/AOD/04Apr2019-v1/310001/FED19720-0CE4-5B4D-91E0-DB230A5046EB.root'
]
options.maxEvents = 1000 # -1 means all events

# Get and parse the command line arguments
options.parseArguments()

triggerList    = {
		# Double Muon Trigger List
		'DoubleMuonTrigger' : cms.vstring(
			"HLT_HIL1DoubleMuOpen_v1",#0
			"HLT_HIL1DoubleMuOpen_OS_Centrality_40_100_v1", #1
			"HLT_HIL1DoubleMuOpen_Centrality_50_100_v1", #2
			"HLT_HIL1DoubleMu10_v1", #3
			"HLT_HIL2_L1DoubleMu10_v1",#4
			"HLT_HIL3_L1DoubleMu10_v1", #5
			"HLT_HIL2DoubleMuOpen_v1", #6
			"HLT_HIL3DoubleMuOpen_v1", #7
			"HLT_HIL3DoubleMuOpen_M60120_v1", #8
			"HLT_HIL3DoubleMuOpen_JpsiPsi_v1", #9
			"HLT_HIL3DoubleMuOpen_Upsi_v1", #10
			"HLT_HIL3Mu0_L2Mu0_v1", #11
			"HLT_HIL3Mu0NHitQ10_L2Mu0_MAXdR3p5_M1to5_v1",#12
			"HLT_HIL3Mu2p5NHitQ10_L2Mu2_M7toinf_v1",#13
			"HLT_HIL3Mu3_L1TripleMuOpen_v1",#14
                        "HLT_HIL3Mu0NHitQ10_L2Mu0_MAXdR3p5_M1to5_v1_L1step",#15
                        "HLT_HIL3Mu0NHitQ10_L2Mu0_MAXdR3p5_M1to5_v1_L2step",#16
                        "HLT_HIL3Mu0NHitQ10_L2Mu0_MAXdR3p5_M1to5_v1_L3step",#17
                        ),
		# Double Muon Filter List
		'DoubleMuonFilter'  : cms.vstring(
			"hltL1fL1sL1DoubleMuOpenL1Filtered0",
			"hltL1fL1sL1DoubleMuOpenOSCentrality40100L1Filtered0",
			"hltL1fL1sL1DoubleMuOpenCentrality50100L1Filtered0",
			"hltL1fL1sL1DoubleMu10L1Filtered0",
			"hltL2fL1sL1DoubleMu10L1f0L2Filtered0",
			"hltDoubleMuOpenL1DoubleMu10Filtered",
			"hltL2fL1sL1DoubleMuOpenL1f0L2Filtered0",
			"hltL3fL1DoubleMuOpenL3Filtered0",
			"hltL3fL1DoubleMuOpenL3FilteredM60120",
			"hltL3fL1DoubleMuOpenL3FilteredPsi",
			"hltL3fL1DoubleMuOpenL3FilteredUpsi",
			"hltL3f0L3Mu0L2Mu0Filtered0",
                        "hltL3f0L3Mu0L2Mu0DR3p5FilteredNHitQ10M1to5",
			"hltL3f0L3Mu2p5NHitQ10L2Mu2FilteredM7toinf",
                        "hltL3fL1sL1DoubleMuOpenL1fN3L2f0L3Filtered3",
                        "hltL1fL1sL1DoubleMuOpenMAXdR3p5L1Filtered0",#L1 step for Jpsi trigger
                        "hltL2fDoubleMuOpenL2DR3p5PreFiltered0",#L2 step
                        "hltL3f0L3Mu0L2Mu0DR3p5FilteredNHitQ10M1to5"#"hltL3f0DR3p5L3FilteredNHitQ10"#L3 step
			),
                # Single Muon Trigger List
                'SingleMuonTrigger' : cms.vstring(
                        "HLT_HIL1MuOpen_Centrality_70_100_v1",
                        "HLT_HIL1MuOpen_Centrality_80_100_v1",
                        "HLT_HIL2Mu3_NHitQ15_v1",
                        "HLT_HIL2Mu5_NHitQ15_v1",
                        "HLT_HIL2Mu7_NHitQ15_v1",
                        "HLT_HIL3Mu3_NHitQ10_v1",
                        "HLT_HIL3Mu5_NHitQ10_v1",
                        "HLT_HIL3Mu7_NHitQ10_v1",
                        "HLT_HIL3Mu12_v1",
                        "HLT_HIL3Mu15_v1",
                        "HLT_HIL3Mu20_v1",
                        "HLT_HIL2Mu3_NHitQ15_v2",
                        "HLT_HIL2Mu5_NHitQ15_v2",
                        "HLT_HIL2Mu7_NHitQ15_v2",
                        "HLT_HIL3Mu3_NHitQ10_v2",
                        "HLT_HIL3Mu5_NHitQ10_v2",
                        "HLT_HIL3Mu7_NHitQ10_v2",
                        "HLT_HIL3Mu12_v2",
                        "HLT_HIL3Mu15_v2",
                        "HLT_HIL3Mu20_v2",
			),
	        # Single Muon Filter List
	        'SingleMuonFilter'  : cms.vstring(
                        "hltL1fL1sL1MuOpenCentrality70100L1Filtered0",
                        "hltL1fL1sL1MuOpenCentrality80100L1Filtered0",
                        "hltL2fL1sMuOpenL1f0L2Filtered3NHitQ15",
                        "hltL2fL1sMuOpenL1f0L2Filtered5NHitQ15",
                        "hltL2fL1sMuOpenL1f0L2Filtered7NHitQ15",
                        "hltL3fL1sL1SingleMuOpenL1f0L2f0L3Filtered3NHitQ10",
                        "hltL3fL1sL1SingleMuOpenL1f0L2f0L3Filtered5NHitQ10",
                        "hltL3fL1sL1SingleMuOpenL1f0L2f0L3Filtered7NHitQ10",
                        "hltL3fL1sL1SingleMuOpenL1f7L2f0L3Filtered12",
                        "hltL3fL1sL1SingleMuOpenL1f7L2f0L3Filtered15",
                        "hltL3fL1sL1SingleMuOpenL1f7L2f0L3Filtered20",
                        "hltL2fL1sMu3OpenL1f0L2Filtered3NHitQ15",
                        "hltL2fL1sMu3OpenL1f0L2Filtered5NHitQ15",
                        "hltL2fL1sMu3OpenL1f0L2Filtered7NHitQ15",
                        "hltL3fL1sL1SingleMu3OpenL1f0L2f0L3Filtered3NHitQ10",
                        "hltL3fL1sL1SingleMu3OpenL1f0L2f0L3Filtered5NHitQ10",
                        "hltL3fL1sL1SingleMu3OpenL1f0L2f0L3Filtered7NHitQ10",
                        "hltL3fL1sL1SingleMu3OpenL1f7L2f0L3Filtered12",
                        "hltL3fL1sL1SingleMu3OpenL1f7L2f0L3Filtered15",
                        "hltL3fL1sL1SingleMu3OpenL1f7L2f0L3Filtered20",
			)
                }

## Global tag
if isMC:
  globalTag = '103X_upgrade2018_realistic_HI_v11'
else:
  globalTag = '103X_dataRun2_Prompt_v3'

#----------------------------------------------------------------------------

# load the Geometry and Magnetic Field
process.load('Configuration.StandardSequences.Reconstruction_cff')
process.load('Configuration.StandardSequences.Services_cff')
process.load('Configuration.Geometry.GeometryDB_cff')
process.load('Configuration.StandardSequences.MagneticField_38T_cff')

# Global Tag:
process.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_condDBv2_cff')
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, globalTag, '')
### For Centrality
process.load("RecoHI.HiCentralityAlgos.CentralityBin_cfi")
process.centralityBin.Centrality = cms.InputTag("hiCentrality")
process.centralityBin.centralityVariable = cms.string("HFtowers")
print('\n\033[31m~*~ USING CENTRALITY TABLE FOR PbPb 2018 ~*~\033[0m\n')
process.GlobalTag.snapshotTime = cms.string("9999-12-31 23:59:59.000")
process.GlobalTag.toGet.extend([
    cms.PSet(record = cms.string("HeavyIonRcd"),
        tag = cms.string("CentralityTable_HFtowers200_DataPbPb_periHYDJETshape_run2v1033p1x01_offline"),
        connect = cms.string("frontier://FrontierProd/CMS_CONDITIONS"),
        label = cms.untracked.string("HFtowers")
        ),
    ])

#----------------------------------------------------------------------------

# For OniaTree Analyzer
from HiAnalysis.HiOnia.oniaTreeAnalyzer_cff import oniaTreeAnalyzer
oniaTreeAnalyzer(process,
                 muonTriggerList=triggerList, #HLTProName=HLTProcess,
                 muonSelection=muonSelection, useL1Stage2=True, isMC=isMC, outputFileName=options.outputFile, muonlessPV=muonLessPV, doTrimu=doTrimuons, doDimuTrk=doDimuonTrk, flipJpsiDir=flipJpsiDirection)

process.onia2MuMuPatGlbGlb.dimuonSelection       = cms.string("charge==0 && 2.5 < mass && mass < 3.6 && abs(daughter('muon1').innerTrack.dz - daughter('muon2').innerTrack.dz) < 25")
process.onia2MuMuPatGlbGlb.trimuonSelection      = cms.string("abs(charge)==1 && 3.0 < mass && mass < 7.8 && abs(daughter('muon1').innerTrack.dz - daughter('muon2').innerTrack.dz) < 25")
process.onia2MuMuPatGlbGlb.lowerPuritySelection  = cms.string("(isGlobalMuon || isTrackerMuon || genParticleRef(0).isNonnull) && abs(innerTrack.dxy)<4 && abs(innerTrack.dz)<25 && abs(eta) < 2.4 && ((abs(eta) < 1. && pt >= 3.3) || (1. <= abs(eta) && abs(eta) < 2. && p >= 2.9) || (2. <= abs(eta) && pt >= 0.8))")#tracker muon acceptance
#process.onia2MuMuPatGlbGlb.higherPuritySelection = cms.string("") ## No need to repeat lowerPuritySelection in there, already included
if applyCuts:
  process.onia2MuMuPatGlbGlb.LateDimuonSel         = cms.string("userFloat(\"vProb\")>0.01") #0.002
  process.onia2MuMuPatGlbGlb.LateTrimuonSel        = cms.string("userFloat(\"vProb\")>0.005 && userFloat(\"ppdlPV3D\")>0 && userFloat(\"ppdlPV\")>0 && userFloat(\"cosAlpha3D\")>0.5")
process.onia2MuMuPatGlbGlb.onlySoftMuons         = cms.bool(OnlySoftMuons)
process.hionia.minimumFlag      = cms.bool(keepExtraColl)           #for Reco_trk_*
process.hionia.useGeTracks      = cms.untracked.bool(keepExtraColl) #for Reco_trk_*
process.hionia.fillRecoTracks   = cms.bool(keepExtraColl)           #for Reco_trk_*
process.hionia.CentralitySrc    = cms.InputTag("hiCentrality")
process.hionia.CentralityBinSrc = cms.InputTag("centralityBin","HFtowers")
process.hionia.srcTracks        = cms.InputTag("generalTracks")
process.hionia.primaryVertexTag = cms.InputTag("offlinePrimaryVertices")
process.hionia.genParticles     = cms.InputTag("genParticles")
process.hionia.SofterSgMuAcceptance = cms.bool(SofterSgMuAcceptance)
process.hionia.SumETvariables   = cms.bool(SumETvariables)
process.hionia.applyCuts        = cms.bool(applyCuts)
process.hionia.AtLeastOneCand   = cms.bool(atLeastOneCand)
process.hionia.OneMatchedHLTMu  = cms.int32(OneMatchedHLTMu)
process.hionia.useSVfinder      = cms.bool(useSVfinder)
process.hionia.checkTrigNames   = cms.bool(False)

process.oniaTreeAna.replace(process.hionia, process.centralityBin * process.hionia )

if applyEventSel:
  process.load('HeavyIonsAnalysis.Configuration.collisionEventSelection_cff')
  process.load('HeavyIonsAnalysis.EventAnalysis.clusterCompatibilityFilter_cfi')
  process.load('HeavyIonsAnalysis.Configuration.hfCoincFilter_cff')
  process.load("RecoVertex.PrimaryVertexProducer.OfflinePrimaryVerticesRecovery_cfi")
  process.oniaTreeAna.replace(process.hionia, process.hfCoincFilter2Th4 * process.primaryVertexFilter * process.clusterCompatibilityFilter * process.hionia )

if atLeastOneCand:
  if doTrimuons:
      process.oniaTreeAna.replace(process.onia2MuMuPatGlbGlb, process.onia2MuMuPatGlbGlb * process.onia2MuMuPatGlbGlbFilterTrimu)
      process.oniaTreeAna.replace(process.patMuonSequence, process.filter3mu * process.pseudoDimuonFilterSequence * process.patMuonSequence)
  elif doDimuonTrk:
      process.oniaTreeAna.replace(process.onia2MuMuPatGlbGlb, process.onia2MuMuPatGlbGlb * process.onia2MuMuPatGlbGlbFilterDimutrk)
      process.oniaTreeAna.replace(process.patMuonSequence, process.pseudoDimuonFilterSequence * process.patMuonSequence)
  else:
      process.oniaTreeAna.replace(process.onia2MuMuPatGlbGlb, process.onia2MuMuPatGlbGlb * process.onia2MuMuPatGlbGlbFilter)
      #BEWARE, pseudoDimuonFilterSequence asks for opposite-sign dimuon in given mass range. But saves a lot of time by filtering before running PAT muons
      process.oniaTreeAna.replace(process.patMuonSequence, process.pseudoDimuonFilterSequence * process.patMuonSequence)

if useSVfinder:
    from RecoVertex.AdaptiveVertexFinder.inclusiveVertexFinder_cfi import *
    from RecoVertex.AdaptiveVertexFinder.vertexMerger_cfi import *
    from RecoVertex.AdaptiveVertexFinder.trackVertexArbitrator_cfi import *

    process.inclusiveVertexFinderLoose = inclusiveVertexFinder.clone(
        vertexMinDLen2DSig = 1.5,
        vertexMinDLenSig = 1.25,
        vertexMinAngleCosine = 0.001,
        maximumLongitudinalImpactParameter = 0.6, #default = 0.3
        maxNTracks = 10, #default = 30
        minPt = 1.2, #following muon acceptance
        #useVertexReco = False,
        #fitterSigmacut = 3.,
        clusterizer = cms.PSet(
            seedMax3DIPSignificance = cms.double(9999.),#default
            seedMax3DIPValue = cms.double(9999.),#default
            seedMin3DIPSignificance = cms.double(1.6), # default=1.2
            seedMin3DIPValue = cms.double(0.005), # default = 0.005
            clusterMaxDistance = cms.double(0.05),#default = 0.05
            clusterMaxSignificance = cms.double(3.),#default = 4.5
            distanceRatio = cms.double(10.),#default = 20
            clusterMinAngleCosine = cms.double(0.001), # default = 0.5
            maxTimeSignificance = cms.double(3.5),#default
        ),
    )

    process.vertexMergerLoose = vertexMerger.clone(
        secondaryVertices = "inclusiveVertexFinderLoose"
    )
    process.trackVertexArbitratorLoose = trackVertexArbitrator.clone(
        secondaryVertices = cms.InputTag("vertexMergerLoose")
    )
    process.inclusiveSecondaryVerticesLoose = vertexMerger.clone(
        secondaryVertices = "trackVertexArbitratorLoose",
        maxFraction = 0.2, # default 0.7 - 0.2
        minSignificance = 3. # default 2 - 10
    )
    process.inclusiveVertexingTask = cms.Task(
        process.inclusiveVertexFinderLoose,
        process.vertexMergerLoose,
        process.trackVertexArbitratorLoose,
        process.inclusiveSecondaryVerticesLoose
    )
    process.inclusiveVertexing = cms.Sequence(process.inclusiveVertexingTask)
    process.oniaTreeAna.replace(process.hionia, process.inclusiveVertexing*process.hionia)

    from RecoBTag.SecondaryVertex.secondaryVertexTagInfos_cfi import *
    inclusiveSecondaryVertexFinderLooseTagInfos = secondaryVertexTagInfos.clone()
    # use external SV collection made from IVF
    inclusiveSecondaryVertexFinderLooseTagInfos.extSVCollection     = cms.InputTag('inclusiveSecondaryVerticesLoose')
    inclusiveSecondaryVertexFinderLooseTagInfos.useExternalSV = cms.bool(True)

process.oniaTreeAna = cms.Path(process.offlinePrimaryVerticesRecovery * process.oniaTreeAna)
#----------------------------------------------------------------------------
#Options:
process.source = cms.Source("PoolSource",
#process.source = cms.Source("NewEventStreamFileReader", # for streamer data
		fileNames = cms.untracked.vstring( options.inputFiles ),
                            #skipEvents=cms.untracked.uint32(3000)
		)
process.TFileService = cms.Service("TFileService",
		fileName = cms.string( options.outputFile )
		)
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(options.maxEvents) )
process.options   = cms.untracked.PSet(wantSummary = cms.untracked.bool(True))

process.schedule  = cms.Schedule( process.oniaTreeAna )
#process.SimpleMemoryCheck = cms.Service("SimpleMemoryCheck", ignoreTotal = cms.untracked.int32(1))

################ Offline Primary Vertices Recovery
from HLTrigger.Configuration.CustomConfigs import MassReplaceInputTag
process = MassReplaceInputTag(process,"offlinePrimaryVertices","offlinePrimaryVerticesRecovery")
process.offlinePrimaryVerticesRecovery.oldVertexLabel = "offlinePrimaryVertices"


from bs4 import BeautifulSoup
from urllib.request import urlopen
from urllib.parse import urlparse, parse_qsl

class Stop:

	def __init__(self, name, stopid, area, zone, addl, lat, lon):
		self.name = name
		self.id = stopid
		self.area = area
		self.zone  = zone
		self.addl = addl
		self.lat = lat
		self.lon = lon

	def toCSV(self):
		self.name = '"' + self.name.replace('"','""') + '"' #wrap in quotes and escape '"''
		self.addl = '"' + self.addl.replace('"','""') + '"'
		return("{},{},{},{},{},{},{}\n".format(self.id,self.name,self.zone,self.lat,self.lon,self.area,self.addl))

#-------------------------------------------------
stops = [] #container for stop objects
BASE_URL = "http://tcat.nextinsight.com"
urlcontents = urlopen(BASE_URL+"/allstops.php")
allstops = BeautifulSoup(urlcontents)

links = allstops.find(id="page").find("p").find_all("a")

print("Found {} stops. Starting data collection.".format(len(links)))
for link in links:
	#extract useful info from the link
	stopurl = link.get("href")
	print("Collecting data in: " + stopurl)

	name = link.get_text()

	#visit the stop link
	urlcontents = urlopen(BASE_URL + stopurl)
	stop = BeautifulSoup(urlcontents)
	area = stop.find("h4",text="Area").find_next_sibling().get_text()
	zone = stop.find("h4", text="Fare Zone").find_next_sibling().get_text()
	zone = zone.replace("Zone ","") #strip Zone prefix
	addl = stop.find("h4", text="Additional Information").find_next_sibling().get_text()
	addl = addl.replace("\n","") #strip newlines
	mapurl = stop.find("a", text="View Stop On Map").get("href") #?lat=42.393639&lon=-76.362834&stopid=9368
	mapquery = parse_qsl(urlparse(mapurl).query)

	#[('lat', '42.458150'), ('lon', '-76.475667'), ('stopid', '3660')]
	lat = mapquery[0][1]
	lon = mapquery[1][1]
	stopid = mapquery[2][1]

	#create the stop object
	stops.append(Stop(name, stopid, area, zone, addl, lat, lon))

print("Data collection finished.\nCollected {} stops.\nBegin writing to file.".format(len(stops)))

f = open('TCATstops.csv', 'w')
f.write("id,name,zone,lat,lon,area,addl\n")

#iterate through stop objects
for stop in stops:
	f.write(stop.toCSV())

f.close()
print("Completed")


from flask import Flask ,jsonify,abort, make_response

from flask import request

from flask import  url_for

app = Flask(__name__)
tasks = [{
    'id': 1,
    'title': 'buy groceries',
    'description': 'milk ',
    'done': False
}, {
    'id': 2,
    'title': 'Learn Python',
    'description': 'need to find',
    'done': False
}]

@app.route('/todo/api/v1.0/tasks' , methods = ['POST'])
def creat_task():
    if not request.json or not 'title' in request.json:
        abort(404)
    task = {'id': tasks[-1]['id'] + 1,
            'title': request.json['title'],
            'description': request.json.get('description', ""),
            'done': False
            }
    tasks.append(task)
    return jsonify({'task': task}), 201

def make_public_task(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id = task['id'], _external=True)
        else:
            new_task[field] = task[field]
    return new_task

@app.route('/todo/api/v1.0/tasks', methods = ['GET'])
def get_tasks():
    return jsonify({'tasks': map(make_public_task, tasks)})

if __name__ == '__main__':
    app.run(debug=True)


def longest_common_substring(word_a, word_b):
    # 2d array construction
    cols = len(word_a)
    rows = len(word_b)
    table = []
    for i in range(cols):
        col = []
        for j in range(rows):
            col.append(0) # initialization with 0
        table.append(col)

    # maximum distance calculation
    max_dist = 0
    for i in range(cols):
        for j in range(rows):
            if word_a[i] == word_b[j]:
                if i > 0 and j > 0:
                    table[i][j] = table[i-1][j-1] + 1
                else:
                    table[i][j] = 1
            else:
                table[i][j] = 0
        if table[i][i] > max_dist:
            max_dist = table[i][i]

    print(table)

    return max_dist

print(longest_common_substring("hish", "vista"))


import math

liczba = int(input('Podaj liczbę: '))
dwojkowy = []

while True:
    tempLiczba = math.floor(liczba / 2)
    tempReszta = liczba % 2

    dwojkowy.append(str(tempReszta))

    liczba = tempLiczba

    if liczba == 0:
        break

print(''.join(dwojkowy[::-1]))


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from time import time

from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core import validators
from django.forms.utils import ErrorDict
from django.forms.widgets import HiddenInput
from django.utils.crypto import salted_hmac

from antispam.forms import AntispamFormMixin
from attachment.fields import AttachmentField
from attachment.forms import TemporaryAttachmentFormMixin
from common_utils import get_meta
from common_utils.middlewares.ThreadLocal import get_current_request
from rich_editor.forms import RichOriginalField
from threaded_comments.models import Comment

COMMENT_MAX_LENGTH = getattr(settings, 'COMMENT_MAX_LENGTH', 50000)

class SecurityFormMixin(object):
	timestamp = forms.IntegerField(widget=forms.HiddenInput)
	security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
	honeypot = forms.CharField(required=False, label='Ak do tohto poľa niečo napíšete bude príspevok pvažovaný za spam.')

	def generate_security_data(self):
		security_dict = {
			'timestamp': int(time())
		}
		security_dict.update(self.additional_security_data())
		security_dict['security_hash'] = self.generate_security_hash(security_dict)
		return security_dict

	def additional_security_data(self):
		return {}

	def generate_security_hash(self, security_dict):
		key_salt = 'secutity_form'
		value = '-'.join(str(v) for v in security_dict.values())
		return salted_hmac(key_salt, value).hexdigest()

	def security_errors(self):
		errors = ErrorDict()
		for f in ['timestamp', 'security_hash']:
			if f in self.errors:
				errors[f] = self.errors[f]
		return errors

	def clean_honeypot(self):
		value = self.cleaned_data["honeypot"]
		if value:
			raise forms.ValidationError(self.fields["honeypot"].label)
		return value

	def clean_timestamp(self):
		ts = self.cleaned_data['timestamp']
		if time() - ts > (2 * 60 * 60):
			raise forms.ValidationError('Timestamp check failed')
		return ts

	def clean_security_hash(self):
		security_dict = self.generate_security_data()
		del security_dict['security_hash']
		expected_hash = self.generate_security_hash(security_dict)
		actual_hash = self.cleaned_data['security_hash']
		if not expected_hash == actual_hash:
			raise forms.ValidationError('Security hash check failed.')
		return actual_hash

class CommentForm(SecurityFormMixin, TemporaryAttachmentFormMixin, AntispamFormMixin, forms.ModelForm):
	original_comment = RichOriginalField(
		parsers=get_meta(Comment).get_field('original_comment').parsers,
		label='Komentár',
		validators=[validators.MaxLengthValidator(COMMENT_MAX_LENGTH)]
	)

	attachment = AttachmentField(label='Príloha', required=False)
	upload_session = forms.CharField(widget=HiddenInput, required=False)

	class Meta:
		model = Comment
		fields = [
			'content_type',
			'object_id',
			'parent',
			'subject',
			'user_name',
			'original_comment'
		]
		widgets = {
			'content_type': forms.HiddenInput,
			'object_id': forms.HiddenInput,
			'parent': forms.HiddenInput,
		}

	def __init__(self, target_object, parent_id, data=None, initial=None, *args, **kwargs):
		self.parent_id = parent_id
		self.target_object = target_object
		initial = initial or {}
		initial.update(self.generate_security_data())
		super(CommentForm, self).__init__(data=data, initial=initial, *args, **kwargs)
		self.fields['parent'].required = True
		self.request = get_current_request()
		if self.request.user.is_authenticated():
			del self.fields['user_name']
		else:
			self.fields['user_name'].required = True
		self.process_attachments()

	def get_model(self):
		return Comment

	def get_comment_object(self):
		if self.is_valid():
			return self.save(commit=False)
		else:
			return None

	def additional_security_data(self):
		return {
			'parent': self.parent_id,
			'object_id': self.target_object.pk,
			'content_type': ContentType.objects.get_for_model(self.target_object).pk,
		}

	def check_for_duplicate_comment(self, new):
		possible_duplicates = Comment.objects.filter(
			content_type=new.content_type,
			object_id=new.object_id,
			user_name=new.user_name,
		)
		for old in possible_duplicates:
			if old.submit_date.date() == new.submit_date.date() and old.original_comment == new.original_comment:
				return old
		return new


# -*- coding: utf-8 -*-
from django.db import models
from django.utils import timezone

# Create your models here.
class Bill(models.Model):
    metodo_choices = {
        'CA': 'Cash', # Efectivo
        'CC': 'Credit card', # Tarjeta
        'TR': 'Transfer', # Transferencia
        'PA': 'Paypal', # Paypal
        'CH': 'Check', # Cheque
        'OT': 'Other' # Otro
    }
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE, editable=True)
    emisor = models.CharField(max_length=100)
    importe = models.DecimalField(max_digits=13, decimal_places=2)
    fechahora = models.DateTimeField(blank=False)
    metodo = models.CharField(
        max_length=2,
        choices=list(metodo_choices.items()),
        default='CA',
        blank=False
    )
    descripcion = models.TextField(blank=True)
    insercion = models.DateTimeField(default=timezone.now, editable=False)

    def __str__(self):
        return '[%s] %s : %s € (%s)' % (
            self.fechahora,
            self.emisor,
            '{:13.2f}'.format(self.importe).strip(),
            self.metodo_choices[str(self.metodo)]
        )


'''
Compress

Authors: Alexander Ryan

This program compresses a text file. The input is a text file
and the ouput is a compressed version of the text file.

'''

NUM_BYTES = 256

ALL_BYTES = set()
for byte_val in range(NUM_BYTES):
    ALL_BYTES.add(chr(byte_val))

def get_unused_bytes(string):
    '''
    Returns the number of unique bytes
    that are not being used in the string.

    This gives us an indication of how many bytes
    we can use to substitute n_grams in the string.

    For example if a particular string used 200 out of
    the 256 possible unique bytes, there are only 56
    different bytes we can use in the compression.

    Parameters:

        string: a string of text you want compressed.

    Result:

        a list of all the unique bytes
        not present in the string.

    '''
    used_bytes = set(string)
    return ALL_BYTES.difference(used_bytes)

def get_ngrams(string, ngram_size):
    '''
    Breaks the string entered into chunks, formally called ngrams,
    with the size given by the parameter ngram_size.
    These ngrams are then added to a list, result.

    Parameters:

        string: a string of text you want compressed.
        ngram_size: the size of each ngram of the string.
                    For example if we broke the string 'apple'
                    with ngram size of 2 it would be
                    ['ap', 'pp', 'pl', 'le']

    Result:

        A list of all the ngrams of text in the string,
        with size in characters given by the ngram_size.

    '''
    result = []
    upper_index = len(string) - ngram_size
    for index in range(upper_index + 1):
        next_ngram = string[index:index + ngram_size]
        result.append(next_ngram)
    return result

def freqs(seq):
    '''
    Counts the number of times each individual ngram appears in the list.
    This data is mapped to a dictionary.
    Each different ngram will have a number for each
    time it appears in the sequence

    Parameters:

        seq: A list of ngrams.
             An example input could be the get_ngram function result

    Result:

        A dictionary which lists all the different ngrams
        and the number of times they appeared in the given seq

    '''
    counters = {}
    for item in seq:
        if item in counters:
            counters[item] += 1
        else:
            counters[item] = 1
    return counters

def get_second_item(seq):
    '''
    Returns the second item in the list

    Parameters:

        seq: A list of ngrams.

    Result:

       The second value in the list.

    '''
    return seq[1]

def sorted_ngrams_by_freq(dict):
    '''
    The ngams in the dictionary are sorted by the
    number associated with them, which represents
    the number of times they appear in the string.
    This sorted frequency is put into a list called result

    Parameters:

        dict: A dictionary of ngrams with an associated number
              which respresents how many times they
              appeared in the original string.

    Result:

        A dictionary sorted by the number associated with each ngram.
        The ngrams which appear most frequently
        will appear towards the start of the dictionary.

    '''
    items = dict.items()
    sorted_items = sorted(items, key=get_second_item, reverse=True)
    result = []
    for ngram, _freq in sorted_items:
        result.append(ngram)
    return result

MAX_MAPPINGS = 255

def make_ngram_encoding(sorted_ngrams, encoding_bytes):
    '''
    For evry ngram in the list of sorted ngrams and encoding byte
    Add the encoding byte to the list of result
    If this list of encoding bytes becomes equal or greater than 255 stop the function

    The result is returned at the end

    Parameters:

        sorted_ngrams: A list of the ngrams, sorted by their frequency in the original string.
        encoding_bytes:

    '''
    result = {}
    count = 0
    for ngram, encoding_byte in zip(sorted_ngrams, encoding_bytes):
        if count >= MAX_MAPPINGS:
            break
        result[ngram] = encoding_byte
        count += 1
    return result

def make_header(ngram_size, encoded_ngrams):
    '''

    Parameters:

        ngram_size:
        encoded_ngrams:

    '''
    number_mappings = len(encoded_ngrams)
    number_mappings_as_char = chr(number_mappings)
    ngram_size_as_char = chr(ngram_size)
    result = number_mappings_as_char + ngram_size_as_char
    for ngram in encoded_ngrams:
        result += ngram + encoded_ngrams[ngram]
    return result

def make_encoded_string(string, ngram_size, encoded_ngrams):
    '''

    Parameters:

        string:
        ngram_size:
        encoded_ngrams:

    Result

    '''
    result  = ''
    index = 0
    while index < len(string):
        ngram = string[index:index + ngram_size]
        if ngram in encoded_ngrams:
            result += encoded_ngrams[ngram]
            index += ngram_size
        else:
            result += string[index]
            index += 1
    return result

MINIMUM_ENCODING_BYTES = 1

def compress_file(ngram_size, in_filename, out_filename):
    '''

    Parameters:

        ngram_size:
        in_filename:
        out_filename:

    Result:

    '''
    if ngram_size <= 0:
        print("n-gram size must be greater than 0")
        return

    in_file = open(in_filename)
    contents = in_file.read()
    in_file.close()

    encoding_bytes = list(get_unused_bytes(contents))
    num_encoding_bytes = len(encoding_bytes)

    if num_encoding_bytes <= MINIMUM_ENCODING_BYTES:
        print("Cannot compress file %s" % in_filename)
        print("Insufficient unused bytes in file")
        print("Found %s unused bytes, but %s are required" %
                 (num_encoding_bytes, MINIMUM_ENCODING_BYTES))
        return

    ngrams = get_ngrams(contents, ngram_size)
    num_ngrams = len(ngrams)

    if num_ngrams == 0:
        print("Cannot compress file %s" % in_filename)
        print("Zero ngrams found, perhaps file is too small?")
        return

    ngram_freqs = freqs(ngrams)
    sorted_ngrams = sorted_ngrams_by_freq(ngram_freqs)
    encoded_ngrams = make_ngram_encoding(sorted_ngrams, encoding_bytes)
    header = make_header(ngram_size, encoded_ngrams)
    encoded_contents = make_encoded_string(contents, ngram_size,
                           encoded_ngrams)

    out_file = open(out_filename, 'w')
    out_file.write(header)
    out_file.write(encoded_contents)
    out_file.close()