# coding=utf-8

class Setting:
    """存储游戏《外星人入侵》中的所有设置的类"""

    def __init__(self):
        """初始化游戏的设置"""
        # 屏幕设置
        self.screen_width = 1080
        self.screen_height = 720
        self.bg_color = (230, 230, 230)  # 蓝色(30, 144, 255)
        # 飞船设置（有几条命）
        self.ship_limit = 3
        # 子弹设置 宽3px，高15px 深灰色的子弹，速度比飞船速度稍慢
        self.bullet_width = 50   # 子弹宽度 50
        self.bullet_height = 15  # 15
        self.bullet_color = (148, 0, 211)   # 子弹颜色 蓝色
        self.bullets_allowed = 5  # 限制子弹数量

        # 外星人下落速度设置
        self.fleet_drop_speed = 15  # 下落速度 下移量更多

        # 加快游戏节奏的速度
        self.speedup_scale = 1.1  # 速度增加的倍率
        self.score_sacle = 1.5  # 分数的提高速度

        self.initialize_dynamic_settings()  # 调用函数

    def initialize_dynamic_settings(self):
        """初始化随游戏进行而变化的（动态）设置，也可以用来重置游戏设置"""
        self.ship_speed = 1.5   # 初始速度
        self.bullet_speed = 3.0
        self.alien_speed = 1.5

        # fleet_direction 为1 表示向右移动， -1 表示向左移动
        self.fleet_direction = 1  # 移动方向

        # 一个外星人的分值 计分
        self.alien_points = 50

    def increase_speed(self):
        """提高速度和外星人分数设置"""
        self.ship_speed *= self.speedup_scale
        self.bullet_speed *= self.speedup_scale
        self.alien_speed *= self.speedup_scale

        self.alien_points = int(self.alien_points * self.score_sacle)
        # print(self.alien_points)


from time import sleep

try:
    import pyglet
    from pyglet.gl import *
except ImportError:
    print("GET PYGLET!!!")
    input()
from pyglet.window import key
from manual_player import *

GRID_SIZE = np.array([192, 128])  # Number of grids per screen
POS_MATRIX = np.zeros(GRID_SIZE, dtype=np.int8)  # Create 2D collision-position matrix
SCREEN_SIZE = np.array([1920, 1024])  # Designate a screen-size
GRID_QUANTIZATION = SCREEN_SIZE / GRID_SIZE  # Size of each square
KEY_DICT = {}
NUM_PLAYERS = 3
current_players = NUM_PLAYERS

window = pyglet.window.Window(SCREEN_SIZE[0], SCREEN_SIZE[1], resizable=True)
players_list = []

reset_text = pyglet.text.Label('Resetting game state', \
                               font_name='Times New Roman', \
                               font_size=36, \
                               color=(255, 255, 255, 255), \
                               x=window.width // 2, \
                               y=window.height // 2, \
                               anchor_x='center', anchor_y='center')

def bind_key(obj, symbol_list):
    for symbol in symbol_list:
        KEY_DICT[symbol] = obj

players_list.append(Player(96, 96, 1, ('c3B', (255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0)), \
                           ('c3B', (120, 0, 0, 120, 0, 0, 120, 0, 0, 120, 0, 0)), \
                           GRID_QUANTIZATION, GRID_SIZE, "Player 1"))

players_list.append(Player(36, 33, 2, ('c3B', (0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255, 0)), \
                           ('c3B', (0, 120, 0, 0, 120, 0, 0, 120, 0, 0, 120, 0)), \
                           GRID_QUANTIZATION, GRID_SIZE, "Player 2"))

players_list.append(Player(156, 33, 3, ('c3B', (0, 0, 255, 0, 0, 255, 0, 0, 255, 0, 0, 255)), \
                           ('c3B', (0, 0, 120, 0, 0, 120, 0, 0, 120, 0, 0, 120)), \
                           GRID_QUANTIZATION, GRID_SIZE, "Player 3"))

for player in players_list:
    player.set_initial_direction(GRID_SIZE)

players_list[1].set_controls((key.W, key.S, key.A, key.D))
bind_key(players_list[1], (key.W, key.S, key.A, key.D))
players_list[2].set_controls((key.UP, key.DOWN, key.LEFT, key.RIGHT))
bind_key(players_list[2], (key.UP, key.DOWN, key.LEFT, key.RIGHT))
players_list[0].set_controls((key.I, key.K, key.J, key.L))
bind_key(players_list[0], (key.I, key.K, key.J, key.L))

code_batch = pyglet.graphics.Batch()

@window.event
def on_key_press(symbol, modifier):
    if symbol in KEY_DICT:
        KEY_DICT[symbol].change_dir(symbol)

@window.event
def on_draw():
    window.clear()
    code_batch.draw()
    batch = pyglet.graphics.Batch()
    for player_inst in players_list:
        if player_inst.active:
            batch.add(4, gl.GL_QUADS, None, ('v2f', player.draw_pos), player.color)
    batch.draw()

def update(dt=0):
    global POS_MATRIX, code_batch, current_players, NUM_PLAYERS
    try:
        for player in players_list:
            if POS_MATRIX[player.x][player.y] == 0:
                POS_MATRIX[player.x][player.y] = player.code
                current_draw_position = [player.x * GRID_QUANTIZATION[0], player.y * GRID_QUANTIZATION[1], \
                                         player.x * GRID_QUANTIZATION[0], (player.y + 1) * GRID_QUANTIZATION[1], \
                                         (player.x + 1) * GRID_QUANTIZATION[0], (player.y + 1) * GRID_QUANTIZATION[1], \
                                         (player.x + 1) * GRID_QUANTIZATION[0], player.y * GRID_QUANTIZATION[1]]
                if player.active:
                    code_batch.add(4, gl.GL_QUADS, None, ('v2f', current_draw_position), player.trail_color)
            else:
                player.death()
            player.update(GRID_QUANTIZATION, GRID_SIZE)
    except PlayerDeath as death_tag:
        if current_players > 2:
            current_players -= 1
            player.new_set(GRID_QUANTIZATION, GRID_SIZE)
            player.set_initial_direction(GRID_SIZE)
            death_tag.player_name.dx = 0
            death_tag.player_name.dy = 0
            death_tag.player_name.active = False
        else:
            current_players = NUM_PLAYERS
            game_state = pyglet.text.Label('%s lost.' % death_tag.player_name.name, \
                                           font_name='Times New Roman', \
                                           font_size=36, \
                                           color=(0, 255, 255, 0), \
                                           x=SCREEN_SIZE[0] / 2, \
                                           y=SCREEN_SIZE[1] / 2, \
                                           anchor_x='center', anchor_y='center')
            print(death_tag.player_name.name)
            game_state.draw()
            sleep(0.5)
            reset_text.draw()
            for player in players_list:
                player.new_set(GRID_QUANTIZATION, GRID_SIZE)
                player.set_initial_direction(GRID_SIZE)
                player.active = True
            POS_MATRIX = np.zeros(GRID_SIZE, dtype=np.int8)
            code_batch = pyglet.graphics.Batch()
            sleep(0.5)

window.schedule = pyglet.clock.schedule_interval(update, 1 / 45.0)  # update at 60Hz
pyglet.app.run()


#!/usr/bin/env python2

import urllib
import re
from bs4 import BeautifulSoup

url = 'https://www.washington.edu/students/timeschd/SPR2016/'

soup = BeautifulSoup(urllib.urlopen(url))

link = soup.find_all('a', href=re.compile('^(?!http).*html$'), class_=None)

all_links = []

for l in link:
	all_links.append('https://www.washington.edu/students/timeschd/SPR2016/'+re.sub('\d+', '', l.get('href')))

f = open("Courses_List.txt", "w")

for l in all_links:
	course = BeautifulSoup(urllib.urlopen(l))
	#print course.prettify()
	for c in course.find_all('td'):
		for b in c.find_all('b', recursive=False):
			x = ''
			for a in b.find_all('a'):
				if a.string is None:
					x += ''
				else:
					x += a.string
			if x != '':
				f.write(x.encode('ascii', 'ignore')+'\n')

# for l in all_links:
# 	course = BeautifulSoup(urllib.urlopen(l))
# 	for c in course.find_all('a'):
# 		for b in c.find_all('b'):
# 			print b.string


# O(n log n) time, O(n) space
INF = 1000000+1 # Requires -INF < x[i] < INF

def lis(x):
# Return some longest increasing subsequence of x
	n = len(x)
	a = [[INF] for i in range(n+1)]
	a[0] = [-INF]

	lmax = 0
	for v in x:
		lb, ub = 0, n # Invariant: a[lb][-1] < v <= a[ub][-1]
		while ub - lb > 1:
			mid = (lb + ub) // 2
			if a[mid][-1] < v:
				lb = mid
			else:
				ub = mid
		a[ub].append(v)
		lmax = max(ub, lmax)

	L = []
	for i in range(1,lmax+1):
		L.append(a[i][-1])
	return L

def main():
	n = int(input())
	x = [int(s) for s in input().split()]
	L = lis(x)
	opt = len(L)
	print(' '.join(map(str,L)))

if __name__ == "__main__": main()


# @Author: dileep
# @Last Modified by:   dileep

import json
import os
import random
import pytest
from microbial_ai.io import ModelTable
from microbial_ai.metabolism import Microbe

CURRPATH = os.path.dirname(__file__)

@pytest.fixture(scope="module")
def model_table():
    return ModelTable(db_uri=f"sqlite:///{CURRPATH}/data/models.db",
                      model_path=f"{CURRPATH}/data/metabolic_models")

@pytest.fixture
def core_model(model_table):
    [model] = model_table.fetch_byid([17])  # 838 is actual database
    return model

@pytest.fixture
def random_model(model_table):
    mid = random.randint(1, 21)  # 857 in actual database
    [model] = model_table.fetch_byid([mid])  # 791 for ecoli
    return model

@pytest.fixture
def known_microbes(model_table):
    [core, ecoli] = model_table.fetch_byid([17, 19])  # 838, 791 is actual database
    return core, ecoli

@pytest.fixture
def random_microbes(model_table):
    mids = random.sample(range(1, 21), k=3)  # 857 in actual database
    [model1, model2, model3] = model_table.fetch_byid(mids)
    return model1, model2, model3

@pytest.mark.filterwarnings('ignore')
@pytest.fixture
def known_microbiome(known_microbes):
    return [Microbe(m) for m in known_microbes]

@pytest.mark.filterwarnings('ignore')
@pytest.fixture
def random_microbiome(random_microbes):
    return [Microbe(m) for m in random_microbes]

@pytest.fixture
def microbe_dict():
    config_path = os.path.join(CURRPATH, 'data/config/config.json')
    with open(config_path, 'r') as fid:
        json_data = json.load(fid)
    return json_data['microbes-test']

@pytest.fixture
def core_media():
    config_path = os.path.join(CURRPATH, 'data/config/config.json')
    with open(config_path, 'r') as fid:
        json_data = json.load(fid)
    return json_data['media']

@pytest.fixture
def core_exrxns():
    config_path = os.path.join(CURRPATH, 'data/config/config.json')
    with open(config_path, 'r') as fid:
        json_data = json.load(fid)
    return json_data['ex_rxns']


#!C:\Python36\python
from http import cookies
import time, os
cook = os.environ.get("HTTP_COOKIE")
cookie = cookies.SimpleCookie(cook)
user = cookie.get("name")
lasttime = cookie.get("date_visited")
#dtime = str(time.ctime(int(lasttime)))
if user == None:
    cookie = cookies.SimpleCookie()
    cookie["name"] = "amrin"
    cookie["date_visited"] = str(time.time())
    print(cookie)
    msg = "
คุณคือ -> %s
" % cookie["name"].value
else:
    dtime = time.ctime(float(lasttime.value))
    msg = "
ขอต้อนรับอีกครั้งคุณ -> %s, เยี่ยมชมล่าสุด : %s
" % (user.value, dtime)
print("Content-Type: text/html")
print()
print(msg)
print("
เนื้อหาหน้าเว็บที่สอง
")


import time
import os
from selenium import webdriver
import math
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--remote-debugging-port=9222")

def calc(x):
    return str(math.log(abs(12*math.sin(int(x)))))

try:
    browser = webdriver.Chrome(chrome_options=chrome_options)
    browser.get("http://suninjuly.github.io/alert_accept.html")
    button = browser.find_element_by_xpath('//button[contains(text(), "I want to go on a magical journey!")]')
    button.click()
    confirm = browser.switch_to.alert
    confirm.accept()
    num = browser.find_element_by_xpath('//span[@id="input_value"]').text
    calc_result = calc(num)
    element = browser.find_element_by_xpath('//input[@id="answer"]')
    element.send_keys(calc_result)

    button = browser.find_element_by_xpath('//button[contains(text(), "Submit")]')
    button.click()

finally:
    print(browser.switch_to.alert.text)
    browser.quit()


"""
Filename:     calc_temporal_aggregate.py
Author:       Damien Irving, irving.damien@gmail.com
Description:  Calculate the linear trend or climatology

"""

# Import general Python modules

import sys, os, pdb
import argparse
import numpy, math
import iris
from iris.experimental.equalise_cubes import equalise_attributes
from decimal import Decimal

# Import my modules

cwd = os.getcwd()
repo_dir = '/'
for directory in cwd.split('/')[1:]:
    repo_dir = os.path.join(repo_dir, directory)
    if directory == 'ocean-analysis':
        break

modules_dir = os.path.join(repo_dir, 'modules')
sys.path.append(modules_dir)

try:
    import general_io as gio
    import timeseries
    import grids
    import convenient_universal as uconv
    import spatial_weights
except ImportError:
    raise ImportError('Must run this script from anywhere within the ocean-analysis git repo')

# Define functions

def calc_linear_trend(data, xaxis):
    """Calculate the linear trend.
    polyfit returns [a, b] corresponding to y = a + bx
    """

    if data.mask[0]:
        return data.fill_value
    else:
        return numpy.polynomial.polynomial.polyfit(xaxis, data, 1)[-1]

def get_agg_cube(cube, agg):
    """Get the temporally aggregated data.

    Args:
      cube (iris.cube.Cube)
      agg (str)

    """

    coord_names = [coord.name() for coord in cube.dim_coords]
    assert coord_names[0] == 'time'

    if agg == 'trend':
        trend_data = timeseries.calc_trend(cube, per_yr=True)
        agg_cube = cube[0, ::].copy()
        agg_cube.data = trend_data
        try:
            agg_cube.units = str(cube.units) + ' yr-1'
        except ValueError:
            agg_cube.units = 'yr-1'
    elif agg == 'clim':
        agg_cube = cube.collapsed('time', iris.analysis.MEAN)
    agg_cube.remove_coord('time')

    return agg_cube

def lat_tropics(cell):
    return -30 < cell < 30

def subtract_tropics(cube):
    """Subtract the mean tropics trend."""

    lat_constraint = iris.Constraint(latitude=lat_tropics)
    tropics_cube = cube.extract(lat_constraint)
    tropics_mean = tropics_cube.collapsed(['longitude', 'latitude'], iris.analysis.MEAN)

    cube.data = cube.data - tropics_mean.data

    return cube

def vertical_mean(cube):
    """Calculate the vertical mean"""

    coord_names = [coord.name() for coord in cube.dim_coords]
    depth_axis = cube.coord('depth')

    assert depth_axis.units in ['m', 'dbar'], "Unrecognised depth axis units"
    if depth_axis.units == 'm':
        weights = spatial_weights.calc_vertical_weights_1D(depth_axis, coord_names, cube.shape)
    elif depth_axis.units == 'dbar':
        assert coord_names == ['time', 'depth', 'latitude', 'longitude'], "2D weights will not work for curvilinear grid"
        weights = spatial_weights.calc_vertical_weights_2D(depth_axis, cube.coord('latitude'), coord_names, cube.shape)

    cube = cube.collapsed('depth', iris.analysis.MEAN, weights=weights)
    cube.remove_coord('depth')

    return cube

def main(inargs):
    """Run the program."""

    # Read data
    try:
        time_constraint = gio.get_time_constraint(inargs.time_bounds)
    except AttributeError:
        time_constraint = iris.Constraint()

    depth_constraint = gio.iris_vertical_constraint(inargs.min_depth, inargs.max_depth)

    with iris.FUTURE.context(cell_datetime_objects=True):
        cube = iris.load(inargs.infiles, gio.check_iris_var(inargs.var) & depth_constraint)
        history = cube[0].attributes['history']
        atts = cube[0].attributes
        equalise_attributes(cube)
        iris.util.unify_time_units(cube)
        cube = cube.concatenate_cube()

        cube = gio.check_time_units(cube)
        cube = cube.extract(time_constraint)

        cube = iris.util.squeeze(cube)

        if 'salinity' in inargs.var:
            cube = gio.salinity_unit_check(cube)

        infile_metadata = {inargs.infiles[0]: history}

    if inargs.annual:
        cube = timeseries.convert_to_annual(cube, full_months=True)

    if inargs.min_depth or inargs.max_depth:
        cube = vertical_mean(cube)

    agg_cube = get_agg_cube(cube, inargs.aggregation)

    if inargs.regrid:
        before_sum = agg_cube.data.sum()
        before_mean = agg_cube.data.mean()
        agg_cube, coord_names, regrid_status = grids.curvilinear_to_rectilinear(agg_cube)
        if regrid_status:
            print('Warning: Data has been regridded')
            print('Before sum:', '%.2E' % Decimal(before_sum) )
            print('After sum:', '%.2E' % Decimal(agg_cube.data.sum()) )
            print('Before mean:', '%.2E' % Decimal(before_mean) )
            print('After mean:', '%.2E' % Decimal(agg_cube.data.mean()) )

    if inargs.subtract_tropics:
        agg_cube = subtract_tropics(agg_cube)

    if inargs.land_mask:
        sftlf_cube = iris.load_cube(inargs.land_mask, 'land_area_fraction')
        agg_cube = uconv.apply_land_ocean_mask(agg_cube, sftlf_cube, 'ocean')

    atts['history'] = gio.write_metadata(file_info=infile_metadata)
    agg_cube.attributes = atts

    iris.FUTURE.netcdf_no_unlimited = True
    iris.save(agg_cube, inargs.outfile)

if __name__ == '__main__':

    extra_info ="""
author:
  Damien Irving, irving.damien@gmail.com

"""

    description='Calculate the temporal aggregate (linear trend or climatology) at each grid point'
    parser = argparse.ArgumentParser(description=description,
                                     epilog=extra_info,
                                     argument_default=argparse.SUPPRESS,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.add_argument("infiles", type=str, nargs='*', help="Input files")
    parser.add_argument("var", type=str, help="Variable standard_name")
    parser.add_argument("aggregation", type=str, choices=('trend', 'clim'), help="Method for temporal aggregation")
    parser.add_argument("outfile", type=str, help="Output file name")

    parser.add_argument("--time_bounds", type=str, nargs=2, metavar=('START_DATE', 'END_DATE'),
                        help="Time period [default = entire]")

    parser.add_argument("--min_depth", type=float, default=None,
                        help="Only include data below this vertical level")
    parser.add_argument("--max_depth", type=float, default=None,
                        help="Only include data above this vertical level")

    parser.add_argument("--subtract_tropics", action="store_true", default=False,
                        help="Subtract the mean tropics trend from all data points")
    parser.add_argument("--regrid", action="store_true", default=False,
                        help="Regrid to a regular lat/lon grid")

    parser.add_argument("--land_mask", type=str, default=None,
                        help="Name of sftlf file to use for land mask")

    parser.add_argument("--annual", action="store_true", default=False,
                        help="Convert data to annual mean before calculating aggregate [default=False]")

    args = parser.parse_args()
    main(args)


import enum
import re
from collections import defaultdict
from typing import (
    Any,
    Callable,
    DefaultDict,
    Dict,
    List,
    Mapping,
    Match,
    NamedTuple,
    Pattern,
    Tuple,
    Union,
)

from django.db.models import Q

from sentry import eventstore
from sentry.api.base import Endpoint
from sentry.incidents.models import Incident
from sentry.models import Group, Project
from sentry.shared_integrations.exceptions import ApiError
from sentry.web.decorators import transaction_start
from sentry.utils import json

from .client import SlackClient
from .requests import SlackEventRequest, SlackRequestError
from .utils import build_group_attachment, build_incident_attachment, parse_link, logger

UnfurledUrl = Any

class LinkType(enum.Enum):
    ISSUES = "issues"
    INCIDENTS = "incidents"
    DISCOVER = "discover"

class UnfurlableUrl(NamedTuple):
    url: str
    args: Mapping[str, Any]

class Handler(NamedTuple):
    matcher: Pattern
    arg_types: Mapping[str, type]
    fn: Callable[[Any, List[UnfurlableUrl]], UnfurledUrl]

def unfurl_issues(integration, links: List[UnfurlableUrl]) -> UnfurledUrl:
    """
    Returns a map of the attachments used in the response we send to Slack
    for a particular issue by the URL of the yet-unfurled links a user included
    in their Slack message.

    url_by_issue_id: a map with URL as the value and the issue ID as the key
    event_id_by_url: a map with the event ID in a URL as the value and the URL as the key
    """
    group_by_id = {
        g.id: g
        for g in Group.objects.filter(
            id__in={link.args["issue_id"] for link in links},
            project__in=Project.objects.filter(organization__in=integration.organizations.all()),
        )
    }
    if not group_by_id:
        return {}

    out = {}
    for link in links:
        issue_id = link.args["issue_id"]

        if issue_id in group_by_id:
            group = group_by_id[issue_id]
            # lookup the event by the id
            event_id = link.args["event_id"]
            event = eventstore.get_event_by_id(group.project_id, event_id) if event_id else None
            out[link.url] = build_group_attachment(
                group_by_id[issue_id], event=event, link_to_event=True
            )
    return out

def unfurl_incidents(integration, links: List[UnfurlableUrl]) -> UnfurledUrl:
    filter_query = Q()
    # Since we don't have real ids here, we use the org slug so that we can
    # make sure the identifiers correspond to the correct organization.
    for link in links:
        identifier = link.args["incident_id"]
        org_slug = link.args["org_slug"]
        filter_query |= Q(identifier=identifier, organization__slug=org_slug)

    results = {
        i.identifier: i
        for i in Incident.objects.filter(
            filter_query,
            # Filter by integration organization here as well to make sure that
            # we have permission to access these incidents.
            organization__in=integration.organizations.all(),
        )
    }
    if not results:
        return {}

    return {
        link.url: build_incident_attachment(
            action=None,
            incident=results[link.args["incident_id"]],
        )
        for link in links
        if link.args["incident_id"] in results
    }

# XXX: The regex matchers could be more tightly bound to our configured domain,
# but slack limits what we can unfurl anyways so its probably safe
_link_handlers = {
    LinkType.ISSUES: Handler(
        fn=unfurl_issues,
        matcher=re.compile(
            r"^https?\://[^/]+/[^/]+/[^/]+/issues/(?P<issue_id>\d+)(?:/events/(?P<event_id>\w+))?"
        ),
        arg_types={
            "issue_id": int,
            "event_id": str,
        },
    ),
    LinkType.INCIDENTS: Handler(
        fn=unfurl_incidents,
        matcher=re.compile(
            r"^https?\://[^/]+/organizations/(?P<org_slug>[^/]+)/incidents/(?P<incident_id>\d+)"
        ),
        arg_types={
            "org_slug": str,
            "incident_id": int,
        },
    ),
}

def match_link(link: str) -> Union[Tuple[LinkType, Match], Tuple[None, None]]:
    for link_type, handler in _link_handlers.items():
        match = handler.matcher.match(link)
        if match:
            return link_type, match
    return None, None

# XXX(dcramer): a lot of this is copied from sentry-plugins right now, and will
# need refactored
class SlackEventEndpoint(Endpoint):
    authentication_classes = ()
    permission_classes = ()

    def _get_access_token(self, integration):
        # the classic bot tokens must use the user auth token for URL unfurling
        # we stored the user_access_token there
        # but for workspace apps and new slack bot tokens, we can just use access_token
        return integration.metadata.get("user_access_token") or integration.metadata["access_token"]

    def on_url_verification(self, request, data):
        return self.respond({"challenge": data["challenge"]})

    def on_message(self, request, integration, token, data):
        channel = data["channel"]
        # if it's a message posted by our bot, we don't want to respond since
        # that will cause an infinite loop of messages
        if data.get("bot_id"):
            return self.respond()

        access_token = self._get_access_token(integration)

        headers = {"Authorization": "Bearer %s" % access_token}
        payload = {
            "channel": channel,
            "blocks": [
                {
                    "type": "section",
                    "text": {
                        "type": "mrkdwn",
                        "text": "Want to learn more about configuring alerts in Sentry? Check out our documentation.",
                    },
                },
                {
                    "type": "actions",
                    "elements": [
                        {
                            "type": "button",
                            "text": {"type": "plain_text", "text": "Sentry Docs"},
                            "url": "https://docs.sentry.io/product/alerts-notifications/alerts/",
                            "value": "sentry_docs_link_clicked",
                        }
                    ],
                },
            ],
        }

        client = SlackClient()
        try:
            client.post("/chat.postMessage", headers=headers, data=payload, json=True)
        except ApiError as e:
            logger.error("slack.event.on-message-error", extra={"error": str(e)})

        return self.respond()

    def _parse_url(self, link) -> Union[Tuple[LinkType, Mapping[str, Any]], Tuple[None, None]]:
        """
        Determines if the URL is something we are able to unfurl, if it is we
        will return the named groups from the regex match, along with the link
        type.
        """
        link_type, match = match_link(link)

        if link_type is None or match is None:
            return None, None

        return link_type, match.groupdict()

    def on_link_shared(self, request, integration, token, data):
        matches: DefaultDict[LinkType, List[UnfurlableUrl]] = defaultdict(list)
        links_seen = set()

        # An unfurl may have multiple links to unfurl
        for item in data["links"]:
            try:
                # We would like to track what types of links users are sharing,
                # but it's a little difficult to do in sentry since we filter
                # requests from Slack bots. Instead we just log to Kibana
                logger.info(
                    "slack.link-shared", extra={"slack_shared_link": parse_link(item["url"])}
                )
            except Exception as e:
                logger.error("slack.parse-link-error", extra={"error": str(e)})

            link_type, args = self._parse_url(item["url"])

            if not link_type or args is None:
                continue

            # Coerce link argument types
            arg_types = _link_handlers[link_type].arg_types
            clean_args = {k: arg_types[k](v) if v is not None else None for k, v in args.items()}

            # Don't unfurl the same thing multiple times
            seen_marker = (link_type, frozenset(args.items()))
            if seen_marker not in links_seen:
                links_seen.add(seen_marker)
            else:
                continue

            matches[link_type].append(UnfurlableUrl(url=item["url"], args=clean_args))

        if not matches:
            return

        # Unfurl each link type
        results: Dict[str, Any] = {}
        for link_type, unfurl_data in matches.items():
            results.update(_link_handlers[link_type].fn(integration, unfurl_data))

        if not results:
            return

        access_token = self._get_access_token(integration)

        payload = {
            "token": access_token,
            "channel": data["channel"],
            "ts": data["message_ts"],
            "unfurls": json.dumps(results),
        }

        client = SlackClient()
        try:
            client.post("/chat.unfurl", data=payload)
        except ApiError as e:
            logger.error("slack.event.unfurl-error", extra={"error": str(e)})

        return self.respond()

    # TODO(dcramer): implement app_uninstalled and tokens_revoked
    @transaction_start("SlackEventEndpoint")
    def post(self, request):
        try:
            slack_request = SlackEventRequest(request)
            slack_request.validate()
        except SlackRequestError as e:
            return self.respond(status=e.status)

        if slack_request.is_challenge():
            return self.on_url_verification(request, slack_request.data)

        if slack_request.type == "link_shared":
            resp = self.on_link_shared(
                request,
                slack_request.integration,
                slack_request.data.get("token"),
                slack_request.data.get("event"),
            )

            if resp:
                return resp

        if slack_request.type == "message":
            resp = self.on_message(
                request,
                slack_request.integration,
                slack_request.data.get("token"),
                slack_request.data.get("event"),
            )

            if resp:
                return resp

        return self.respond()


from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from dashboard.models import Area
from dashboard.models import Data
from dashboard.models import RawData
from manage_devices.models import Node
from django.http import JsonResponse
from django.http import HttpResponse
from datetime import datetime
from django.db.models.functions import TruncMonth
from django.db.models import Avg
from django.template.loader import get_template
from django.template.loader import render_to_string
from api.serializers import DataSerialization, NodeSerialization, RawDataSerialization, AreaSerialization

class ReportIndex(LoginRequiredMixin, View):
    def get(self, request):
        areas = Area.objects.all()
        return render(request, template_name='report/index.html', context={
            'areas': areas,
        })

class ReportShowOnView(LoginRequiredMixin, View):
    def get(self, request):
        area = request.GET.get('area')
        date_start = datetime.strptime(request.GET.get('month_start'), '%a %b %d %Y %H:%M:%S %Z%z')
        date_end = datetime.strptime(request.GET.get('month_end'), '%a %b %d %Y %H:%M:%S %Z%z')

        if area == 'all':
            areas = Area.objects.all()
            areas_serialized = AreaSerialization(data=areas, many=True)
            areas_serialized.is_valid()
            data_to_send = {}
            nodes_to_send = {}
            for area in areas:
                data_by_area_and_day = Data.objects.filter(measuring_date__range=[date_start.date(), date_end.date()],
                                                           area_id=area).order_by('measuring_date')
                nodes_by_area = Node.objects.filter(area=area)
                data_by_area = {}
                for node in nodes_by_area:
                    data_by_node = data_by_area_and_day.filter(node=node)
                    data_serialized = DataSerialization(data=data_by_node, many=True)
                    data_serialized.is_valid()
                    data_by_area[node.id] = data_serialized.data
                data_to_send[area.id] = data_by_area
                nodes_serialized = NodeSerialization(data=nodes_by_area, many=True)
                nodes_serialized.is_valid()
                nodes_to_send[area.id] = nodes_serialized.data
            dict_data = {
                'data': data_to_send,
                'areas': areas_serialized.data,
                'nodes': nodes_to_send
            }
        else:
            area_object = Area.objects.get(pk=area)
            data_by_area_and_day = Data.objects.filter(measuring_date__range=[date_start.date(), date_end.date()],
                                                       area_id=area).order_by('measuring_date')
            area_serialized = AreaSerialization(instance=area_object)
            nodes = Node.objects.filter(area=area)
            data_to_send = {}
            for node in nodes:
                data_by_node = data_by_area_and_day.filter(node=node)
                data_serialized = DataSerialization(data=data_by_node, many=True)
                data_serialized.is_valid()
                data_to_send[node.id] = data_serialized.data
            nodes_serialized = NodeSerialization(data=nodes, many=True)
            nodes_serialized.is_valid()
            dict_data = {
                'data': data_to_send,
                'area': area_serialized.data,
                'nodes': nodes_serialized.data
            }
        return JsonResponse(dict_data, safe=False)

# def aveage_data_by_month(data):
#     data

# class ReportExport(LoginRequiredMixin, View):
#     def get(self, request):
#         htmp_template = get_template('report/index.html')
#         html_string = htmp_template.render()
#         pdf_file = HTML(string=html_string).write_pdf()
#         response = HttpResponse(pdf_file, content_type='application/pdf')
#         response['Content-Disposition'] = 'attachment;filename="report.pdf"'
#         return response


#!/usr/bin/python3

import logging
import os
import time

logger = logging.getLogger("nitsi.logger")

class Logger_Exeception(BaseException):
    pass

# This function should create the necessary folders
# and touch the logging files
def init_logging(path):
    logger.debug("Init logging directory")

    try:
        path = os.path.abspath(path)
    except BaseException as e:
        logger.error("Failed to get the absolute path for: {}".format(path))

    if os.path.isdir(path):
        log_dir = "{}/log".format(path)
    elif os.path.isfile(path):
        log_dir = "{}/{}.log".format(os.path.dirname(path), os.path.basename(path))

    if not os.path.exists(log_dir):
        os.mkdir(log_dir)

    time_dir = log_dir + "/" + time.strftime("%Y-%m-%d_%H-%M-%S" ,time.gmtime(time.time()))

    if os.path.exists(time_dir):
        logger.error("Path {} alreday exist".format(time_dir))
        raise Logger_Exeception
    else:
        os.mkdir(time_dir)

    return time_dir

class TestFormatter(logging.Formatter):
    def __init__(self, start_time=None, name=None, longest_machine_name=10):
        super().__init__(fmt="[%(asctime)s] %(message)s")
        logger.debug("Initiating TestFormatter for")
        if start_time == None:
            self.starttime = time.time()
        else:
            self.starttime = start_time

        if name == None:
            self.name = ""
        else:
            self.name = name

        self.longest_machine_name = longest_machine_name

    def converter(self, recordtime):

        # This returns a timestamp relatively to the time when we started
        # the test.

        recordtime -= self.starttime

        return time.gmtime(recordtime)

    def format(self, record):
        return "[{}][{:^{align}}] {}".format(self.formatTime(record),
                                                self.name,
                                                record.getMessage(),
                                                align=self.longest_machine_name)

    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        t = time.strftime("%H:%M:%S", ct)
        s = "{}.{:03d}".format(t, round(record.msecs,None))
        return s

class Log_Formatter(logging.Formatter):
    def __init__(self):
        super().__init__(fmt="[%(asctime)s] [%(levelname)s] %(message)s")
        logger.debug("Initiating Log_Formatter")

    def format(self, record):
        # We use 8 to align the levelname, because CRITICAL ist the longest name and has 8 chars
        return "[{}][{:^}][{:^8}] {}".format(self.formatTime(record),
                                                record.name,
                                                record.levelname,
                                                record.getMessage())

    def formatTime(self, record, datefmt=None):
        t = time.strftime("%H:%M:%S", time.gmtime(record.created))
        s = "{}.{:03d}".format(t, round(record.msecs,None))
        return s


'''

A function to count the number of words in a file

'''

def count_words(failename):
    try:
        with open(filename, encoding='utf-8') as f_obj:
            file_contents = f_obj.read()

    except FileNotFoundError:
        message = "Sorry the file '" + filename + "' does not exist"
        print(message)

    else:
        # Count the number of words in a file
        words = file_contents.split()
        number_words = len(words)
        print("The file '" + filename + "' has '" + str(number_words) + "' words in it.")

'''
Create a list to store the filenames in so that the function will go through them all
and print out the output
'''
filenames = ["alice1.txt", "alice1.txt", "alice1.txt", "nosuchfile.txt"]
# We have create a list called filenames and added three files in it

# We have a for loop to loop through each item (filename) in the list filenames
# and count the words

for filename in filenames:
    count_words(filename)

Python Crash Course/Chapter 10 Files and Exceptions/Exceptions/word_count.py


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

import hashlib  # hashlib is the replacement of the deprecated sha module in Python2
import os, sys
from random import randint
import __init__
from sha1classes.XmlSha1ExceptionClassesMod import FileSystemHasFilenamesThatHaveAnUnknownEncoding

HEXS_ABOVE_9 = 'abcdef' # lowercase
HEX_DIGITS = '0123456789' + HEXS_ABOVE_9
SHA1_CHUNK_SIZE = 40
hex_40digit_max = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
# lambda_str_hex_digit = lambda digit : HEX_DIGITS[digit] or None
lambda_randint_0_15  = lambda _ : randint(0,15)
nonhex_filter        = lambda s : s.lower() not in HEX_DIGITS

SHA1_CHUNK_SIZE = 40
ENCODINGS_TO_TRY_IN_ORDER_FOR_FILENAMES = ['iso-8859-1','windows-1250','windows-1252']

def get_tag_text_and_encoding_if_necessary(sha1file_tag, filename):
  '''
  This is an important function and has been also documented at the beginning of this modolue.
  It is called when UnicodeDecodeError is raised, meaning that we need to try some encodings to "make it go" to the node.text field.
  Once it's successful, an extra XML-attribute, called 'encoding', is added to the file tag.
  This extra attribute is essential at the moment when this file-tag is read from the XML.
  '''
  sha1file_tag.text = None
  for encoding in ENCODINGS_TO_TRY_IN_ORDER_FOR_FILENAMES:
    try:
      sha1file_tag.text = str(filename, encoding, 'strict')
      #print 'filename in tag is', filename, 'encoding is', encoding
      break
    except UnicodeDecodeError:
      pass
  if sha1file_tag.text == None:
    error_msg = 'File System Has Filenames That Have An Unknown Encoding, please try to rename them removing accents.'
    raise FileSystemHasFilenamesThatHaveAnUnknownEncoding(error_msg)
  sha1file_tag.set('encoding', encoding)

def convertHexIntToChar(hexInt):
  '''
  This function is equivalent to lambda lambda_str_hex_digit
  The lambda is preferrable in terms of performance than this function
  '''
  if not (0 <= hexInt <= 15):
    raise ValueError('hexInt, in the char-convert context, should be from 0 to 15. It is %d' %hexInt)
  if hexInt < 10:
    return str(hexInt)
  return HEXS_ABOVE_9[hexInt-10]

def generate_a_40char_random_hex_plan_b():
  '''
  Please, for performance reasons, instead of using this function,
  use function generate_a_40char_random_hex() below

  This function will be called from the latter in case
  Python's change the way it represents a long hexadecimal number
  '''
  hex_40digit_list = list(map(lambda_randint_0_15, range(40)))
  hex_40char_list  = list(map(convertHexIntToChar, hex_40digit_list))
  # hex_40char_list  = map(convertHexIntToChar, hex_40digit_list)
  return ''.join(hex_40char_list).lower()

def stuff_hex_number_to_a_40char_str(long_n):
  '''
  Test Case:

  TC1
  long_n = 0xA
  return should be '000000000...000A', 39 zeroes followed by 'A'

  TC2
  long_n = hex_40digit_max
  return should be a 40-char string all filled-in with "F's"

  @see other Test Cases in the unit tests
  '''
  #str_n = hex(long_n)
  str_n = '%x' %long_n
  #if not str_n.startswith('0x') or not str_n.endswith('L') or
  if len(str_n) > 43:
    return generate_a_40char_random_hex_plan_b()
    #raise ValueError, 'Program Error: '
  #str_n = str_n[2:-1] # strip off the 0x at the beginning and the L (long number) at the end
  if len(str_n) < 40:
    str_n = str_n.zfill(40)
  return str_n.lower()

def generate_sha1hexdigest_from_filepath(file_abspath):
  '''
  This functions mimics, so to say, the sha1sum "bash" executable from the command line.
  It reads a file and passes its contents to the sha.new() method,
    then, returns the object's hex-digest 40-char hexadecimal string.
  '''
  if os.path.isfile(file_abspath):
    content = open(file_abspath, 'rb').read()
    sha1hash = hashlib.sha1()
    sha1hash.update(content)
    return sha1hash.hexdigest()
  return None

def generate_a_40char_random_hex(not_colliding_with=[], n_of_tries=0):
  '''
  Test Case:
  Generate a number and check it's in-between 0 and hex_40digit_max

  '''
  if n_of_tries > 3 + len(not_colliding_with):
    raise IndexError('Giving up generate_a_40char_random_hex() :: n_of_tries (=%d) surpassed limit' %n_of_tries)
  #hex_list_40 = map(xrange(40), randint(16))
  long_n = randint(0, hex_40digit_max)
  random_40char_sha1hex = stuff_hex_number_to_a_40char_str(long_n)
  if random_40char_sha1hex in not_colliding_with:
    return generate_a_40char_random_hex(not_colliding_with, n_of_tries+1)
  return random_40char_sha1hex

def transpose_sha1sum_and_filename_dict_into_tuple_list(sha1sum_and_filename_dict):
  '''

  DEPRECATED

  This function is not longer needed or useful because filenames sorting is more difficult
    with the changes that connected one or more filenames to one sha1sum.

  This set of functions can use the double "sha1hex" and "filename" either as a dict or as tuple/list
  As a dict, the sha1hex is the key and the filename is the value, in the key:value paradigm
  As a tuple/list, the pairs sha1hex/filename are tuples in a list

  The strategy in using a tuple/list is to ease out the sorting/ordering, so that
    processing could loop thru files in alphabetical/alphanumerical order,
    as with dicts, this is more difficult to accomplish (at least using Python versions below 3!)
  '''
  sha1sum_and_filename_tuple_list = []
  for sha1hex in list(sha1sum_and_filename_dict.keys()):
    filenames = sha1sum_and_filename_dict[sha1hex]
    sha1sum_and_filename_tuple_list.append((sha1hex, filenames))
  # order it by filename!
  # sha1sum_and_filename_tuple_list.sort(key = lambda list_obj: list_obj[1])
  return sha1sum_and_filename_tuple_list

def fetch_sha1sum_and_filename_tuple_list_if_a_conventioned_flatsha1file_exists(abspath):
  '''
  This function is a wrapper around the above one (fetch_sha1sum_and_filename_dict_if_a_conventioned_flatsha1file_exists())
  If a dict is returned, it will return its "tuple list transpose".
  '''
  sha1sum_and_filename_dict = fetch_sha1sum_and_filename_dict_if_a_conventioned_flatsha1file_exists(abspath)
  if sha1sum_and_filename_dict == None:
    return None
  return transpose_sha1sum_and_filename_dict_into_tuple_list(sha1sum_and_filename_dict)

  # the validate() method guarantees there won't be a filename having 2 sha1sums
  # if it does, an exception will be raised
  sha1sum_and_filename_dict.validate()
  return sha1sum_and_filename_dict

def is_it_a_sha1hex(sha1hex):
  '''
  '''
  if len(str(sha1hex)) != 40:
    return False
  if type(sha1hex) == int:
    return True
  try:
    boolean_list = list(map(nonhex_filter, sha1hex))
    if True in boolean_list:
      return False
    else:
      return True
  except AttributeError:
    # if this exception has been raised, sha1hex is neither an int nor a string-like
    # however, if it's int-convertible, it will pass this checking below
    pass
  try:
    int(sha1hex, 16)
  except ValueError:
    return False
  return True

import unittest
class Test1(unittest.TestCase):

  def test_convert_one_digit_hex_to_str(self):

    hex_int = 0xA
    hex_str = convertHexIntToChar(hex_int)
    self.assertEqual(hex_str, 'a')

    hex_int = 10
    hex_str = convertHexIntToChar(hex_int)
    self.assertEqual(hex_str, 'a')

  def test_generate_40char_both_methods(self):

    # 1st method
    hex_str = generate_a_40char_random_hex()
    self.assertEqual(len(hex_str), 40)
    self.assertEqual(hex_str, hex_str.lower())

    # 2nd method
    hex_str = generate_a_40char_random_hex_plan_b()
    self.assertEqual(len(hex_str), 40)
    self.assertEqual(hex_str, hex_str.lower())

  def test_equality_between_generated_and_given(self):
    hex_int = 0xA
    hex_str = stuff_hex_number_to_a_40char_str(hex_int)
    s_39_zeroes_plus_ending_A = '0'*39 + 'A'
    self.assertEqual(hex_str, s_39_zeroes_plus_ending_A.lower())

def unittests():
  unittest.main()

def process():
  '''
  '''
  pass

if __name__ == '__main__':
  if 'ut' in sys.argv:
    sys.argv.remove('ut')
    unittests()
  process()


from All_Names_Module import *
exec(identify_file_str)

P = {}

P[GPU] = 0
P[BATCH_SIZE] = 64
P[DISPLAY] = True
P[VERBOSE] = True
P[LOAD_ARUCO] = False
P[BAIR_CAR_DATA_PATH] = opjD('bdd_car_data_July2017_LCR')
P[CODE_PATH] = CODE_PATH__
P[IGNORE] = [reject_run,left,out1_in2]#,'Smyth','racing','local','Tilden','campus']
P[REQUIRE_ONE] = []
P[USE_STATES] = [1,2,3]
P[N_FRAMES] = 2
P[N_STEPS] = 10
P[STRIDE] = 9#3 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
P[NETWORK_OUTPUT_FOLDER] = opjD('LCR_temp')
P[SAVE_FILE_NAME] = 'save_file_LCR_pt3'
P[save_net_timer] = Timer(60*30)
P[print_timer] = Timer(15)
P[TRAIN_TIME] = 60*10.0
P[VAL_TIME] = 60*1.0
P[RESUME] = True
if RESUME:
    P[INITIAL_WEIGHTS_FOLDER] = opj(P[NETWORK_OUTPUT_FOLDER],'weights')
    P[WEIGHTS_FILE_PATH] = most_recent_file_in_folder(P[INITIAL_WEIGHTS_FOLDER],['save_file'],[])

#

#EOF


import numpy as np
import cv2
cam = cv2.VideoCapture(0,cv2.CAP_DSHOW)
cv2.namedWindow("test")
img_counter = 0
while True:
    ret, frame = cam.read()
    cv2.imshow("test", frame)
    if not ret:
        break
    k = cv2.waitKey(1)
    if k%256 == 27:
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        img_name = "opencv_frame_0.png"
        cv2.imwrite(img_name, frame)
        print("{} written!".format(img_name))
cam.release()
cv2.destroyAllWindows()


def solution(clothes):
    category = list(set([x[1] for x in clothes]))
    combination = []
    answer = 1
    for items in category:
        combination.append([x[0] for x in clothes if x[1]==items])
    for items in combination:
        answer *= (len(items)+1)
    return answer-1

clothes = [["yellow_hat", "headgear"], ["blue_sunglasses", "eyewear"], ["green_turban", "headgear"]]

print(solution(clothes))


import json
import argparse

args = argparse.ArgumentParser()
args.add_argument("questions",type=str)
args.add_argument("exp",type=str)
args.add_argument("output",type=str)
args = args.parse_args()

ques = open(args.questions)
exp = open(args.exp)
out = open(args.output,'w')

exp_map = dict()

for lines in exp:
    line = json.loads(lines)
    exp_map[line['id']] = line

ques_map = dict()

for lines in ques:
    line = json.loads(lines)
    line['question']['cose'] = exp_map[line['id']]["explanation"]["open-ended"]
    ques_map[line['id']] = line

for key in ques_map:
    st = json.dumps(ques_map[key])
    out.write(st+'\n')

out.close()


#!/usr/bin/env python
import glob
#import numpy as np
import lcatr.schema

results = []

fo = open("/home/homer/lsst/lcatr/share/flat_acq/v1/status.out", "r");
tsstat = fo.read();
fo.close();

results.append(lcatr.schema.valid(lcatr.schema.get('flat_acq'),stat=tsstat))

files = glob.glob('/home/homer/lsst/ArchonImage*.fits')
#files.append(flat_acq_file)
data_products = [lcatr.schema.fileref.make(item) for item in files]
results.extend(data_products)

lcatr.schema.write_file(results)
lcatr.schema.validate_file()


_SCORES = [
    (1,  set('aeioulnrst')),
    (2,  set('dg')),
    (3,  set('bcmp')),
    (4,  set('fhvwy')),
    (5,  set('k')),
    (8,  set('jx')),
    (10, set('qz')),
]

def score(word: str) -> int:
    return sum(_get_score_for_letter(letter) for letter in word)

def _get_score_for_letter(letter: str) -> int:
    lowercase_letter = letter.lower()

    for letter_score, letters in _SCORES:
        if lowercase_letter in letters:
            return letter_score

    return 0


from time import time, sleep

import boto3
import requests
import simplejson

URL_TRANSACTIONS = 'https://www.bitstamp.net/api/v2/transactions/{}/?time=minute'
PAIRS = ['btcusd', 'btceur', 'eurusd', 'xrpusd', 'xrpeur', 'xrpbtc', 'ltcusd', 'ltceur', 'ltcbtc', 'ethusd', 'etheur', 'ethbtc']

def get_transactions_minute_json(pair):
    transactions = simplejson.loads(requests.get(URL_TRANSACTIONS.format(pair)).text)
    timestamp = int(time())
    if not transactions:
        return {
            'error': 'No transactions executed in the last minute.',
            'timestamp': timestamp,
            'currency_pair': pair,
            'log_type': 'transactions_minute',
        }
    prices = [float(transaction['price']) for transaction in transactions]
    return {
        'currency_pair': pair,
        'price_open': prices[-1],
        'price_close': prices[0],
        'price_low': min(prices),
        'price_high': max(prices),
        'price_minute_avg': sum(prices)/len(prices),
        'timestamp': timestamp,
        'log_type': 'transactions_minute'
    }

client = boto3.client(
    's3',
    aws_access_key_id='***',
    aws_secret_access_key='***'
)

while (True):
    multiline_json_string = '\n'.join([simplejson.dumps(get_transactions_minute_json(pair)) for pair in PAIRS])
    client.put_object(Body=b'{}'.format(multiline_json_string), Bucket='bitstamp-transaction-log', Key=str(int(time())))
    sleep(60)


import numpy as np
from scipy import stats
class neuroCorrelation:
    """
    This class is for the correlation between trait similarity matrix and neural correlation matrix
    """
    # include the flattened trait similarity matrix into the class
    def __init__(self, traitMatrix):
        """
        :param traitMatrix: this is a vector of the lower triangle of trait similarity matrix of a given valence.
        """
        self.traitMatrix = traitMatrix

    def correlate(self, brainData):
        """
        generate a function which generate the coefficient of a person correlation between the neural matrix and the trait similarity matrix
        :param brainData: this is a fmri_dataset of a given valence after z-scoring within runs
        :return: the correlation coefficient between neural correlation matrix and trait similarity matrix of a given valence
        """
        # generate a similarity matrix across each pair of samples
        neuro_sim = np.corrcoef(brainData.samples)

        # take lower triangle of the neuro similarity matrix and flatten
        neuro_sim_flat = np.tril(neuro_sim, k=-1).flatten()

        # generage a mask matrix of 1
        ones_matrix = np.ones(np.shape(neuro_sim))

        # take lower triangle of the ones matrix and flatten to generate a mask
        onesflat = np.tril(ones_matrix, k=-1).flatten()

        # calculate the correlation between neuro similarity matrix and trait similarity matrix, and apply the mask to take the lower triangle
        corr_output = stats.pearsonr(neuro_sim_flat[onesflat != 0], self.traitMatrix[onesflat != 0])

        # only return the correlation coefficient, but not the p-value
        return corr_output[0]


# -*- coding: utf-8 -*-
"""Dependency controller."""
from werkzeug.exceptions import NotFound

from ..database import db_session
from ..models import Dependency
from .utils import raise_if_operator_does_not_exist, uuid_alpha

def list_dependencies(operator_id):
    """Lists all dependencies under a operator.

    Args:
        operator_id (str): the operator uuid.

    Returns:
        A list of all dependencies.
    """
    raise_if_operator_does_not_exist(operator_id)

    dependencies = db_session.query(Dependency) \
        .filter_by(operator_id=operator_id) \
        .order_by(Dependency.uuid.asc()) \
        .all()

    return [dependency.as_dict() for dependency in dependencies]

def list_next_operators(operator_id):
    raise_if_operator_does_not_exist(operator_id)

    dependencies = db_session.query(Dependency) \
        .filter_by(dependency=operator_id) \
        .order_by(Dependency.uuid.asc()) \
        .all()

    return [dependency.as_dict()["operatorId"] for dependency in dependencies]

def create_dependency(operator_id, dependency):
    """Creates a new dependency in our database.

    Args:
        operator_id (str): the operator uuid.
        dependency (str): the dependency operator uuid.

    Returns:
        Dependency info.
    """
    dependency = Dependency(uuid=uuid_alpha(),
                            operator_id=operator_id,
                            dependency=dependency)
    db_session.add(dependency)
    db_session.commit()
    return dependency.as_dict()

def delete_dependency(uuid):
    """Delete an dependency in our database.

    Args:
        uuid (str): the dependency uuid to look for in our database.

    Returns:
        The deletion result.
    """
    dependency = Dependency.query.get(uuid)

    if dependency is None:
        raise NotFound("The specified dependency does not exist")

    db_session.delete(dependency)
    db_session.commit()

    return {"message": "Dependency deleted"}


"""
define several static config in this script
"""

import os

# root path
curPath = os.path.abspath(os.path.dirname(__file__))

# eeg file path
eeg_file_path = "D:/eegData"

# the number of channels
channel_count = 62

# a sample eeg file,we can read some basic information depend on it
sample_eeg_file = os.path.join(eeg_file_path, "health_control/eyeclose/jkdz_cc_20180430_close.vhdr")

# name of bands we calculate
band_name = ['delta', 'theta', 'alpha1', 'alpha2', 'beta', 'gamma', 'full_band']

# we collect eeg about 3 minutes,if there are more than 5000000 points we think it is a bad file
bad_signal_length = 5000000

# bad channel name
bad_channel_name = ['Oz', 'ECG']

# low filter
low_filter_n = 40

# resample
resample_n = 160

# the path of calculate features saving csv
features_path = os.path.join(curPath, "cal_feature_data")

# the path for analyzing all features
all_features_path = os.path.join(curPath, "analyze_features")

# the path of select features path
select_features_path = os.path.join(all_features_path, "select_features")

# the path of classify result
classify_path = os.path.join(all_features_path, "classify")

# the path of ml model
classify_model_path = os.path.join(all_features_path, "model")

# the path of png
classify_image_path = os.path.join(all_features_path, "image")

# the path of mrmr
classify_mrmr_path = os.path.join(all_features_path, "mrmr")

# the path of classify detail result
classify_detail_path = os.path.join(classify_path, "info")


from collections import namedtuple, defaultdict, Counter, deque
import itertools as it
import numpy as np
from abc import ABC, abstractmethod
from utils import PriorityQueue
import time
np.set_printoptions(precision=3, linewidth=200)
from scipy import stats
from tqdm import tqdm, trange, tnrange
from copy import deepcopy
import random
from agents import Component, Model
from utils import softmax

class Policy(Component):
    """Chooses actions."""
    def __init__(self):
        super().__init__()

    @abstractmethod
    def act(self, state):
        """Returns an action to take in the given state."""
        pass

    def attach(self, agent):
        if not hasattr(agent, 'env'):
            raise ValueError('Must attach env before attaching policy.')
        super().attach(agent)

class FunctionPolicy(Policy):
    def __init__(self, policy):
        super().__init__()
        self.policy = policy

    def act(self, state):
        return self.policy(state)

class RandomPolicy(Policy):
    """Chooses actions randomly."""
    def __init__(self):
        super().__init__()

    def act(self, state):
        try:
            return random.choice(list(self.env.actions(state)))
        except:
            return self.env.action_space.sample()

class SoftmaxPolicy(Policy):
    """Samples actions from a softmax over preferences."""
    def __init__(self, preference=None, temp=1e-9, noise=1e-9):
        super().__init__()
        if preference is None:
            assert hasattr(self, 'preference')
        else:
            self.preference = preference
        self.temp = temp
        self.noise = noise

    def act(self, state):
        probs = self.action_distribution(state)
        probs += np.random.rand(len(probs)) * self.noise
        probs /= probs.sum()
        return np.random.choice(len(probs), p=probs)

    def action_distribution(self, state):
        q = np.zeros(self.n_action) - 1e30
        for a in self.env.actions(state):
            q[a] = self.preference(state, a)
        return softmax(q, self.temp)

    def preferences(self, state):
        q = np.zeros(self.n_action) - 1e30
        for a in self.env.actions(state):
            q[a] = self.preference(state, a)
        return q

class RandomTreePolicy(Policy):
    """Chooses actions randomly."""
    def __init__(self):
        super().__init__()

    def act(self, state):
        actions = list(self.env.actions(self.env._state))
        return random.choice(actions)

class MaxQPolicy(Policy):
    """Chooses the action with highest Q value."""
    def __init__(self, Q, epsilon=0.5, anneal=.95, **kwargs):
        super().__init__(**kwargs)
        self.Q = Q
        self.epsilon = epsilon
        self.anneal = anneal

    def act(self, state, anneal_step=0):
        q = self.Q.predict(state)
        epsilon = self.epsilon * self.anneal ** anneal_step
        if np.random.rand() < epsilon:
            noise = np.random.random(q.shape) * 1000
        else:
            noise = np.random.random(q.shape) * .001
        return np.argmax(q + noise)

class LiederPolicy(Policy):
    """The meta-policy of Lieder et al. (2017) AAAI."""
    def __init__(self, theta, bad_max=False):
        self.theta = np.array(theta)

    def act(self, state):
        def Q(a):
            if a == self.env.term_action:
                return self.env.expected_term_reward(self.env._state)
            else:
                try:
                    return np.dot(self.theta, self.env.action_features(a))
                except:
                    print(a, self.env.term_action)
                    raise
        action = max(self.env.actions(state), key=Q)
        return action

    def preference(self, action):
        if action == self.env.term_action:
            return self.env.expected_term_reward(self.env._state)
        else:
            if not hasattr(self.env._state[action], 'sample'):
                return -100
            else:
                return np.dot(self.theta, self.env.action_features(action))

class MaxQSamplePolicy(Policy):
    """Chooses the action with highest sampled Q value.

    `Q.predict` must have the kwarg `return_var`."""
    def __init__(self, Q, **kwargs):
        super().__init__(**kwargs)
        self.Q = Q
        self.save_regret = True

    def act(self, state):
        q, var = self.Q.predict(state, return_var=True)
        sigma = var ** 0.5
        q_samples = q + np.random.randn() * sigma
        a = np.argmax(q_samples)
        if self.save_regret:
            q = q.flat
            a1 = np.argmax(q)
            self.save('max', a == a1)
            self.save('regret', q[a1] - q[a])
        return a

class ActorCritic(Policy):
    """docstring for ActorCritic"""
    def __init__(self, critic, actor_lr=0.001, discount=.99, actor_lambda=1, **kwargs):
        super().__init__()
        self.critic = critic
        self.discount = discount
        self.actor_lambda = actor_lambda
        self.actor_lr = actor_lr

        self._actor_discount = np.array([(self.discount * self.actor_lambda) ** i
                                         for i in range(5000)])

        #self.memory = deque(maxlen=100)
        self.batch_size = 20

    def attach(self, agent):
        super().attach(agent)
        self.actor = self.build_actor()

    def build_actor(self):
        from keras.layers import Dense
        from keras.models import Sequential
        from keras.optimizers import Adam, Nadam
        actor = Sequential([
            Dense(24, input_dim=self.state_size, activation='relu',
                  kernel_initializer='he_uniform'),
            # Dense(24, activation='relu',
            #       kernel_initializer='he_uniform'),
            Dense(self.n_action, activation='softmax',
                  kernel_initializer='he_uniform')
        ])
        # actor.summary()
        actor.compile(loss='categorical_crossentropy',
                      optimizer=Nadam(self.actor_lr))
        return actor

    def act(self, state):

        policy = self.actor.predict(np.asarray(state).reshape(1, -1)).flatten()
        return np.random.choice(self.n_action, 1, p=policy)[0]

    # update networks every episode
    def finish_episode(self, trace):
        if len(self.memory) >= self.batch_size:
            batch = np.random.choice(self.memory, self.batch_size)
            batch.append(trace)
            self.train_batch(batch)

    def train_batch(self, traces):
        def data():
            for trace in traces:
                yield trace['states'][:-1], trace['actions'], trace['rewards']

        state, action, reward = map(np.concatenate, zip(*data()))
        n_step = len(state)
        # See Schulman et al. 2016 ICLR paper
        value = np.r_[self.critic.predict(state).flat, 0]  # final state value
        delta = reward + self.discount * value[1:] - value[:-1]  # pg. 4
        advantage = np.zeros((n_step, self.n_action))
        value_target = np.zeros((n_step, 1))

        for i in range(n_step):
            adv = np.sum(delta[i:] * self._actor_discount[:n_step-i])
            advantage[i, action[i]] = adv
            val_error = np.sum(delta[i:] * self._critic_discount[:n_step-i])
            value_target[i, 0] = value[i] + val_error
            # value_target[i, 0] = reward[i] + self.discount * value[i+1]

        self.actor.fit(state, advantage, epochs=1, verbose=0)
        self.critic.fit(state, value_target, epochs=1, verbose=0)

    def train(self, trace):
        state = np.stack(trace['states'][:-1])  # ignore final state
        action = trace['actions']
        reward = trace['rewards']
        n_step = len(state)

        # See Schulman et al. 2016 ICLR paper
        value = np.r_[self.critic.predict(state).flat, 0]  # final state value
        delta = reward + self.discount * value[1:] - value[:-1]  # pg. 4
        advantage = np.zeros((n_step, self.n_action))
        value_target = np.zeros((n_step, 1))

        for i in range(n_step):
            adv = np.sum(delta[i:] * self._actor_discount[:n_step-i])
            advantage[i, action[i]] = adv
            val_error = np.sum(delta[i:] * self._critic_discount[:n_step-i])
            value_target[i, 0] = value[i] + val_error
            # value_target[i, 0] = reward[i] + self.discount * value[i+1]

        self.actor.fit(state, advantage, epochs=1, verbose=0)
        self.critic.fit(state, value_target, epochs=1, verbose=0)

class GeneralizedAdvantageEstimation(Policy):
    """A variance-reducing extension of Advantage Actor Critic.

    https://arxiv.org/abs/1506.02438
    """
    def __init__(self, actor_lr=0.001, critic_lr= 0.005, discount=.99, actor_lambda=1, critic_lambda=1, **kwargs):
        super().__init__()
        self.discount = discount
        self.actor_lambda = actor_lambda
        self.critic_lambda = critic_lambda
        self.actor_lr = actor_lr
        self.critic_lr = critic_lr

        self._actor_discount = np.array([(self.discount * self.actor_lambda) ** i
                                         for i in range(5000)])
        self._critic_discount = np.array([(self.discount * self.critic_lambda) ** i
                                          for i in range(5000)])

        self._memory = deque(maxlen=100)
        self.batch_size = 20

    def attach(self, agent):
        super().attach(agent)
        self.actor = self.build_actor()
        self.critic = self.build_critic()

    def build_actor(self):
        from keras.layers import Dense
        from keras.models import Sequential
        from keras.optimizers import Nadam
        actor = Sequential([
            # Dense(24, input_dim=self.state_size, activation='relu',
            #       kernel_initializer='he_uniform'),
            # Dense(24, activation='relu',
            #       kernel_initializer='he_uniform'),
            Dense(self.n_action, input_dim=self.state_size, activation='softmax',
                  kernel_initializer='he_uniform')
        ])
        # actor.summary()
        actor.compile(loss='categorical_crossentropy',
                      optimizer=Nadam(self.actor_lr))
        return actor

    # critic: state is input and value of state is output of model
    def build_critic(self):
        from keras.layers import Dense
        from keras.models import Sequential
        from keras.optimizers import Nadam
        critic = Sequential([
            # Dense(24, input_dim=self.state_size, activation='relu',
            #       kernel_initializer='he_uniform'),
            # Dense(24, activation='relu',
            #       kernel_initializer='he_uniform'),
            Dense(1, input_dim=self.state_size, activation='linear',
                  kernel_initializer='he_uniform')
        ])
        # critic.summary()
        critic.compile(loss="mse", optimizer=Nadam(self.critic_lr))
        return critic

    def act(self, state):
        policy = self.actor.predict(state.reshape(1, -1)).flatten()
        return np.random.choice(self.n_action, 1, p=policy)[0]

    # update networks every episode
    def finish_episode(self, trace):
        if len(self._memory) >= self.batch_size:
            batch = np.random.choice(self._memory, self.batch_size)
            batch.append(trace)
            self.train_batch(batch)
        else:
            self.train(trace)

    def train_batch(self, traces):
        def data():
            for trace in traces:
                yield trace['states'][:-1], trace['actions'], trace['rewards']

        state, action, reward = map(np.concatenate, zip(*data()))
        n_step = len(state)
        # See Schulman et al. 2016 ICLR paper
        # value = np.r_[self.critic.predict(state).flat, 0]  # final state value
        value = np.r_[state.sum(1), 0]
        delta = reward + self.discount * value[1:] - value[:-1]  # pg. 4
        advantage = np.zeros((n_step, self.n_action))
        value_target = np.zeros((n_step, 1))

        for i in range(n_step):
            adv = np.sum(delta[i:] * self._actor_discount[:n_step-i])
            advantage[i, action[i]] = adv
            val_error = np.sum(delta[i:] * self._critic_discount[:n_step-i])
            value_target[i, 0] = value[i] + val_error
            # value_target[i, 0] = reward[i] + self.discount * value[i+1]

        self.actor.fit(state, advantage, epochs=1, verbose=0)
        self.critic.fit(state, value_target, epochs=1, verbose=0)

    def train(self, trace):
        state = np.stack(trace['states'][:-1])  # ignore final state
        action = trace['actions']
        reward = trace['rewards']
        n_step = len(state)

        # See Schulman et al. 2016 ICLR paper
        value = np.r_[self.critic.predict(state).flat, 0]  # final state value
        delta = reward + self.discount * value[1:] - value[:-1]  # pg. 4
        advantage = np.zeros((n_step, self.n_action))
        value_target = np.zeros((n_step, 1))

        for i in range(n_step):
            adv = np.sum(delta[i:] * self._actor_discount[:n_step-i])
            advantage[i, action[i]] = adv
            val_error = np.sum(delta[i:] * self._critic_discount[:n_step-i])
            value_target[i, 0] = value[i] + val_error
            # value_target[i, 0] = reward[i] + self.discount * value[i+1]

        self.actor.fit(state, advantage, epochs=1, verbose=0)
        self.critic.fit(state, value_target, epochs=1, verbose=0)

class FixedPlanPolicy(Policy):
    """A policy that blindly executes a fixed sequence of actions."""
    Node = namedtuple('Node', ('state', 'path', 'reward', 'done'))
    def __init__(self, plan, **kwargs):
        super().__init__(**kwargs)
        self._plan = plan

    def start_episode(self, state):
        super().start_episode(state)
        self.plan = iter(self._plan)
        # self.model = Model(self.env)

    def act(self, state):
        return next(self.plan)

class ValSearchPolicy(Policy):
    """Searches for the maximum reward path using a model."""
    def __init__(self, V, replan=False, epsilon=0, noise=1, anneal=1, **kwargs):
        super().__init__(**kwargs)
        self.V = V
        self.replan = replan
        self.epsilon = epsilon
        self.noise = noise
        self.anneal = anneal
        self.history = None
        self.model = None
        self.plan = None

    def start_episode(self, state):
        self.history = Counter()
        self.model = Model(self.env)
        self.plan = iter(())  # start with no plan

    def finish_episode(self, trace):
        self.ep_trace['berries'] = self.env._observe()[-1]

    def act(self, state):
        # return self.env.action_space.sample()
        self.history[state] += 1
        try:
            if self.replan:
                raise StopIteration()
            else:
                return next(self.plan)
        except StopIteration:
            self.plan = iter(self.make_plan(state))
            return next(self.plan)

    def make_plan(self, state, expansions=2000):

        Node = namedtuple('Node', ('state', 'path', 'reward', 'done'))
        env = self.env
        V = memoize(self.V.predict)
        self.node_history = []

        def eval_node(node, noisy=False):
            if not node.path:
                return np.inf  # the empty plan has infinite cost
            obs = env._observe(node.state)
            noise = np.random.rand() * (self.noise * self.anneal ** self.i_episode) if noisy else 0
            value = 0 if node.done else V(obs)[0]
            boredom = - 0.1 * self.history[obs]
            score = node.reward + value + noise + boredom
            return - score

        start = Node(env._state, [], 0, False)
        frontier = PriorityQueue(key=eval_node)
        frontier.push(start)
        reward_to_state = defaultdict(lambda: -np.inf)
        reward_to_state[start.state] = 0
        best_finished = start

        def expand(node):
            nonlocal best_finished
            best_finished = min((best_finished, node), key=eval_node)
            s0, p0, r0, _ = node
            for a, s1, r, done in self.model.options(s0):
                node1 = Node(s1, p0 + [a], r0 + r, done)
                if node1.reward <= reward_to_state[s1]:
                    continue  # cannot be better than an existing node
                self.node_history.append(
                    {'path': node1.path,
                     'r': node1.reward,
                     'b': self.env._observe(node1.state)[-1],
                     'v': -eval_node(node1)})
                reward_to_state[s1] = node1.reward
                if done:
                    best_finished = min((best_finished, node1), key=eval_node)
                else:
                    frontier.push(node1)

        for i in range(expansions):
            if frontier:
                expand(frontier.pop())
            else:
                break

        if frontier:
            plan = min(best_finished, frontier.pop(), key=eval_node)
        else:
            plan = best_finished
        # choices = concat([completed, map(get(1), take(100, frontier))])
        # plan = min(choices, key=eval_node(noisy=True))
        self.log(
            i,
            len(plan.path),
            -round(eval_node(plan, noisy=False), 2),
            plan.done,
        )
        # self._trace['paths'].append(plan.path)
        return plan.path

class Astar(Policy):
    """A* search finds the shortest path to a goal."""
    def __init__(self, heuristic):
        assert 0  # this implementation is incorrect
        super().__init__()
        self.heuristic = heuristic
        self.plan = iter(())

    def start_episode(self, state):
        self.history = Counter()
        self.model = Model(self.env)

    def act(self, state):
        # return self.env.action_space.sample()
        self.history[state] += 1
        try:
            return next(self.plan)
        except StopIteration:
            self.plan = iter(self.make_plan(state))
            return next(self.plan)

    def eval_node(self, node):
        if not node.path:
            return np.inf  # the empty plan has infinite cost
        obs = self.env._observe(node.state)
        value = 0 if node.done else self.heuristic(self.env, obs)
        boredom = - 0.1 * self.history[obs]
        score = node.reward + value + boredom
        return - score

    def make_plan(self, state, expansions=5000):

        Node = namedtuple('Node', ('state', 'path', 'reward', 'done'))
        eval_node = self.eval_node
        start = Node(self.env._state, [], 0, False)
        frontier = PriorityQueue(key=eval_node)
        frontier.push(start)
        reward_to_state = defaultdict(lambda: -np.inf)
        # import IPython; IPython.embed()
        best_finished = start

        def expand(node):
            # print(node.state, node.reward, self.rts[node.state], V(env._observe(node.state)))
            # time.sleep(0.1)
            nonlocal best_finished
            # best_finished = min((best_finished, node), key=eval_node)
            s0, p0, r0, _ = node
            for a, s1, r, done in self.model.options(s0):
                node1 = Node(s1, p0 + [a], r0 + r, done)
                if node1.reward <= reward_to_state[s1]:
                    # print('abandon')
                    pass
                    continue  # cannot be better than an existing node
                # self.save('node', node)
                reward_to_state[s1] = node1.reward
                if done:
                    best_finished = min((best_finished, node1), key=eval_node)
                else:
                    frontier.push(node1)

        for i in range(expansions):
            self.save('frontier', [n[1].state for n in frontier])
            if frontier:
                expand(frontier.pop())
            else:
                break

        if frontier:
            # plan = min(best_finished, frontier.pop(), key=eval_node)
            plan = frontier.pop()
            raise RuntimeError('No plan found.')
        else:
            plan = best_finished
        # choices = concat([completed, map(get(1), take(100, frontier))])
        # plan = min(choices, key=eval_node(noisy=True))
        # self.log(
        #     i,
        #     len(plan.path),
        #     -round(eval_node(plan, noisy=False), 2),
        #     plan.done,
        # )
        # self._trace['paths'].append(plan.path)
        self.save('plan', plan)
        return plan.path


import csv # csv파일을 이용하게 해주는 패키지
import requests
from bs4 import BeautifulSoup

## 네이버금용 코스피 상위종목 csv 저장
url = 'https://finance.naver.com/sise/sise_market_sum.nhn?sosok='

filename = '시가총액1-200.csv'
f = open(filename, 'w', encoding = 'utf-8-sig', newline= '') # newline=''이면 불필요한 줄바꿈을 안하게 해준다.
writer = csv.writer(f) # csv 파일 만들기

title = 'N	종목명	현재가	전일비	등락률	액면가	시가총액	상장주식수	외국인비율	거래량	PER	ROE'.split('\t')
# split('\t')으로 인해 탭으로 구분해서 리스트에 넣음
# ['N', '종목명', ...] list형
writer.writerow(title)

for page in range(1, 5):
    res = requests.get(url + str(page))
    res.raise_for_status()
    soup = BeautifulSoup(res.text, 'lxml')

    data_rows = soup.find('table', attrs = {'class':'type_2'}).find('tbody').find_all('tr')
    for row in data_rows:
        columns = row.find_all('td')
        if len(columns) <= 1:
            continue
        data = [column.get_text().strip() for column in columns]
        # print(data)
        writer.writerow(data) # 데이터를 writer에 한열씩 넣음


from __future__ import absolute_import
from __future__ import unicode_literals
import re
from httmock import HTTMock
from evesrp import db
from evesrp.models import Request
from evesrp.auth import PermissionType
from evesrp.auth.models import Pilot, Division, Permission
from evesrp import views
from ...util_tests import TestLogin, all_mocks

class TestSubmitRequest(TestLogin):

    def setUp(self):
        super(TestSubmitRequest, self).setUp()
        # Setup a bunch of divisions with varying permissions
        with self.app.test_request_context():
            d1 = Division('Division 1')
            d2 = Division('Division 2')
            d3 = Division('Division 3')
            d4 = Division('Division 4')
            d5 = Division('Division 5')
            d6 = Division('Division 6')
            user = self.normal_user
            db.session.add_all((d1, d2, d3, d4, d5, d6))
            # D1: submit, review
            # D2: review
            # D3: submit
            # D4: review, pay
            # D5: pay
            # D6: none
            db.session.add(Permission(d1, PermissionType.submit, user))
            db.session.add(Permission(d1, PermissionType.review, user))
            db.session.add(Permission(d2, PermissionType.review, user))
            db.session.add(Permission(d3, PermissionType.submit, user))
            db.session.add(Permission(d4, PermissionType.review, user))
            db.session.add(Permission(d4, PermissionType.pay, user))
            db.session.add(Permission(d5, PermissionType.pay, user))
            db.session.commit()
        # Python 3 and Python 2.7 have different names for the same method
        try:
            self.assertCountEqual = self.assertItemsEqual
        except AttributeError:
            pass

    def test_division_listing(self):
        client = self.login()
        resp = client.get('/request/add/')
        matches = re.findall(r'<option.*?>(?P<name>[\w\s]+)</option>',
                resp.get_data(as_text=True))
        self.assertEqual(len(matches), 2)
        self.assertCountEqual(matches, ('Division 1', 'Division 3'))

    def test_submit_divisions(self):
        client = self.login()
        with self.app.test_request_context():
            user = self.normal_user
            divisions = user.submit_divisions()
            division_names = [d[1] for d in divisions]
            self.assertEqual(len(division_names), 2)
            self.assertCountEqual(division_names, ('Division 1', 'Division 3'))

    def test_killmail_validation(self):
        # Need to be logged in so validation of permissions works.
        client = self.login()
        with client:
            client.get('/request/add/')
            # RequestsForm needs a list of divisions
            user = self.normal_user
            divisions = user.submit_divisions()
            # Tests
            # ZKillboard
            division = Division.query.filter_by(name='Division 1').one()
            zkb_form = views.requests.RequestForm(
                    url='https://zkillboard.com/kill/37637533/',
                    details='Foo',
                    division=division.id,
                    submit=True)
            zkb_form.division.choices = divisions
            # Fool InputRequired
            zkb_form.details.raw_data = zkb_form.details.data
            with HTTMock(*all_mocks):
                self.assertTrue(zkb_form.validate())
            # CREST
            crest_form = views.requests.RequestForm(
                    url=('https://esi.tech.ccp.is/v1/killmails/30290604/'
                         '787fb3714062f1700560d4a83ce32c67640b1797/'),
                    details='Foo',
                    division=division.id,
                    submit=True)
            crest_form.division.choices = divisions
            crest_form.details.raw_data = crest_form.details.data
            with HTTMock(*all_mocks):
                self.assertTrue(crest_form.validate())
            fail_form = views.requests.RequestForm(
                    url='http://google.com',
                    details='Foo',
                    division=division.id,
                    submit=True)
            fail_form.division.choices = divisions
            fail_form.details.raw_data = fail_form.details.data
            self.assertFalse(fail_form.validate())

    def test_submit_killmail(self):
        with self.app.test_request_context():
            user = self.normal_user
            pilot = Pilot(user, 'Paxswill', 570140137)
            db.session.add(pilot)
            db.session.commit()
            division = Division.query.filter_by(name='Division 1').one()
        client = self.login()
        with HTTMock(*all_mocks):
            resp = client.post('/request/add/', follow_redirects=True,
                    data=dict(
                        url='https://zkillboard.com/kill/37637533/',
                        details='Foo',
                        division=division.id,
                        submit=True))
        self.assertEqual(resp.status_code, 200)
        self.assertIn('37637533', resp.get_data(as_text=True))
        with self.app.test_request_context():
            request = Request.query.get(37637533)
            self.assertIsNotNone(request)

    def test_submit_non_personal_killmail(self):
        with self.app.test_request_context():
            user = self.normal_user
            pilot = Pilot(user, 'The Mittani', 443630591)
            db.session.add(pilot)
            db.session.commit()
            division = Division.query.filter_by(name='Division 1').one()
        client = self.login()
        with HTTMock(*all_mocks):
            resp = client.post('/request/add/', follow_redirects=True,
                    data=dict(
                            url='https://zkillboard.com/kill/37637533/',
                            details='Foo',
                            division=division.id,
                            submit=True))
        self.assertEqual(resp.status_code, 200)
        self.assertIn('You can only submit killmails of characters you',
                resp.get_data(as_text=True))
        with self.app.test_request_context():
            request = Request.query.get(37637533)
            self.assertIsNone(request)


import collections
from corehq import privileges, toggles
from corehq.apps.hqwebapp.templatetags.hq_shared_tags import toggle_enabled
from corehq.apps.userreports.const import REPORT_BUILDER_EVENTS_KEY
from django_prbac.utils import has_privilege

def localize(value, lang):
    """
    Localize the given value.

    This function is intended to be used within UCR to localize user supplied
    translations.

    :param value: A dict-like object or string
    :param lang: A language code.
    """
    if isinstance(value, collections.Mapping) and len(value):
        return (
            value.get(lang, None) or
            value.get(default_language(), None) or
            value[sorted(value.keys())[0]]
        )
    return value

def default_language():
    return "en"

def has_report_builder_add_on_privilege(request):
    return any(
        has_privilege(request, p) for p in privileges.REPORT_BUILDER_ADD_ON_PRIVS
    )

def has_report_builder_access(request):

    builder_enabled = toggle_enabled(request, toggles.REPORT_BUILDER)
    legacy_builder_priv = has_privilege(request, privileges.REPORT_BUILDER)
    beta_group_enabled = toggle_enabled(request, toggles.REPORT_BUILDER_BETA_GROUP)
    has_add_on_priv = has_report_builder_add_on_privilege(request)

    return (builder_enabled and legacy_builder_priv) or beta_group_enabled or has_add_on_priv

def add_event(request, event):
    events = request.session.get(REPORT_BUILDER_EVENTS_KEY, [])
    request.session[REPORT_BUILDER_EVENTS_KEY] = events + [event]

def has_report_builder_trial(request):
    return has_privilege(request, privileges.REPORT_BUILDER_TRIAL)

def can_edit_report(request, report):
    ucr_toggle = toggle_enabled(request, toggles.USER_CONFIGURABLE_REPORTS)
    report_builder_toggle = toggle_enabled(request, toggles.REPORT_BUILDER)
    report_builder_beta_toggle = toggle_enabled(request, toggles.REPORT_BUILDER_BETA_GROUP)
    add_on_priv = has_report_builder_add_on_privilege(request)
    created_by_builder = report.spec.report_meta.created_by_builder

    if created_by_builder:
        return report_builder_toggle or report_builder_beta_toggle or add_on_priv
    else:
        return ucr_toggle

def allowed_report_builder_reports(request):
    """
    Return the number of report builder reports allowed
    """
    builder_enabled = toggle_enabled(request, toggles.REPORT_BUILDER)
    legacy_builder_priv = has_privilege(request, privileges.REPORT_BUILDER)
    beta_group_enabled = toggle_enabled(request, toggles.REPORT_BUILDER_BETA_GROUP)

    if toggle_enabled(request, toggles.UNLIMITED_REPORT_BUILDER_REPORTS):
        return float("inf")
    if has_privilege(request, privileges.REPORT_BUILDER_30):
        return 30
    if has_privilege(request, privileges.REPORT_BUILDER_15):
        return 15
    if (
        has_privilege(request, privileges.REPORT_BUILDER_TRIAL) or
        has_privilege(request, privileges.REPORT_BUILDER_5) or
        beta_group_enabled or
        (builder_enabled and legacy_builder_priv)
    ):
        return 5

def number_of_report_builder_reports(domain):
    from corehq.apps.userreports.models import ReportConfiguration
    existing_reports = ReportConfiguration.by_domain(domain)
    builder_reports = filter(
        lambda report: report.report_meta.created_by_builder, existing_reports
    )
    return len(builder_reports)


import boto3
import json
import sys

"""
Module to help facilitate calls to AWS SNS/SQS
"""
class AWS(object):
    """Container to handle interactions with AWS"""
    def __init__(self):
        self.sns = boto3.client('sns', 'us-east-2')
        self.sqs = boto3.client('sqs', 'us-east-2')
        self.sqs_res = boto3.resource('sqs', 'us-east-2')
        # Placeholder to store player info
        self.players = {}

    def create_topic(self, topic_name):
        print("Creating topic: ", topic_name)
        self.topic = self.sns.create_topic(Name=topic_name)
        self.topic_arn = self.topic['TopicArn']
        print("Topic arn: ", self.topic_arn)
        self.topic_name = topic_name
        return True

    def create_queue(self, queue_name):
        self.queue = self.sqs.create_queue(QueueName=queue_name)
        self.sqs_arn = self.sqs.get_queue_attributes(QueueUrl=self.queue['QueueUrl'], AttributeNames=['QueueArn'])['Attributes']['QueueArn']

        return True

    def add_policy(self):
        """
        Create/Add security policy to queue to allow topics to get tied to them
        """
        self.policy = None
        try:
            self.policy = json.loads(self.get_policy())
            # Do not bother adding a new policy if there is one in place for this topic already
            if self.topic_name in [s['Sid'] for s in self.policy['Statement']]:
                return True
        except KeyError:
            pass

        if not self.policy:
            self.policy = {
                "Version": "2012-10-17",
                "Id": "{}/SQSDefaultPolicy".format(self.sqs_arn),
                "Statement": [],
            }

        #TODO - Add a check to make sure my ARN isn't already in the list
        #if not self.policy_has_permissions_for_topic ():
        #print ("Policy type: ", type(self.policy))
        self.policy['Statement'].append({
          "Sid": self.topic_name,
          "Effect": "Allow",
          "Principal": {
            "AWS": "*"
          },
          "Action": "SQS:SendMessage",
          "Resource": self.sqs_arn,
          "Condition": {
            "ArnEquals": {
              "aws:SourceArn": self.topic_arn
            }
          }
        })
        #print('Policy: ', json.dumps(self.policy))
        self.sqs.set_queue_attributes(QueueUrl=self.queue['QueueUrl'], Attributes={'Policy': json.dumps(self.policy)})
        return True

    def subscribe_to_topic(self):
        """Subscribe to the topic"""
        return self.sns.subscribe(TopicArn=self.topic_arn, Protocol='sqs', Endpoint=self.sqs_arn)

    def get_policy(self):
        return self.sqs.get_queue_attributes(QueueUrl=self.queue['QueueUrl'], AttributeNames=['Policy'])['Attributes']['Policy']

    def delete_policy(self):
        p = json.loads(self.get_policy())
        p['Statement'] = [s for s in p['Statement'] if not s['Condition']['ArnEquals']['aws:SourceArn'] == self.topic_arn]
        self.policy = p

        self.sqs.set_queue_attributes(QueueUrl=self.queue['QueueUrl'], Attributes={'Policy': json.dumps(self.policy)})
        return True

    def receive_message(self, MaxNumberOfMessages=1, WaitTimeSeconds=20, VisibilityTimeout=10):
        return self.sqs.receive_message(QueueUrl=self.queue['QueueUrl'],MaxNumberOfMessages=MaxNumberOfMessages, WaitTimeSeconds=WaitTimeSeconds, VisibilityTimeout=VisibilityTimeout)

    def send_message(self, topic, message):
        try:
            resp = self.sns.publish(TopicArn=self.players[topic], Message=message)
        except KeyError:
            return {'success': False, 'reason': 'Publishing to an unknown topic'}
        else:
            return {'success': True, 'reason': resp}

    def register_player(self, topic):
        # TODO - put Amazon Id and region in a config environment
        # determine arn
        arn = "arn:aws:sns:us-east-2:849664249614:{}".format(topic)
        self.players[topic] = arn

# TODO
# methods to be added:
#   * Delete Message


from tkinter import *

mw =Tk()
mw.title('vidya jyothi college')
mw.geometry('900x720')

#creating Freames:

frame1 = LabelFrame(mw,text='This is frame1',font=('',14),width=400,padx=10, pady=10) #no use of width operator ,size will increase only based on widgets like buttons
frame1.grid(row=0,column=0,padx=10,pady=10)

exit_btn = Button(frame1, text='Exit!',padx=60,pady=12,font=('',14),command=mw.quit)
exit_btn.pack()

#creating radio buttons:
#we want a func to be excuted when we select an option

def rbv_res():
    rbv_lbl.config(text=rbv.get())           # get() will fetch the value of rbv

rbv= StringVar()
rbv.set('chicken biryani')
Radiobutton(frame1,value='chicken biryani', variable=rbv, text='option 1', font=('',14),command=rbv_res).pack(pady=(20,10))
#variable=rbv , value='chicken biryani', we know that var=value ,so rbv='chicken biryani'
Radiobutton(frame1,value='veg biryani', variable=rbv, text='option 2', font=('',14),command=rbv_res).pack(pady=(0,20))
#variable=rbv , value='veg biryani', we know that var=value ,so rbv='veg biryani'

rbv_lbl = Label(frame1, text=rbv.get(),font=('',14))
rbv_lbl.pack()

#create check button/boxs:

def cbv_res():
    cbv_lbl.config(text=cbv.get())           # get() will fetch the value of rbv

cbv = StringVar()
cb = Checkbutton(frame1, onvalue='yes', offvalue='no', variable=cbv,text='Do you Want Parcle?',font=('',14),command=cbv_res)
cb.deselect()     #initally the button will be selected ,,by deselect() we make it unselected
cb.pack(pady=(30,10))

cbv1 = StringVar()
cb1 = Checkbutton(frame1, onvalue='yes', offvalue='no', variable=cbv1,text='Do you Want eat?',font=('',14),command=cbv_res)
cb1.deselect()     #initally the button will be selected ,,by deselect() we make it unselected
cb1.pack(pady=(30,10))

cbv_lbl = Label(frame1, text=cbv.get(),font=('',14))
cbv_lbl.pack(pady=(0,30))

#creating Drop Down Menus:
months=['january','february','march','april','may']
selected=StringVar()
selected.set('March')
opts= OptionMenu(frame1,selected,*months)     #opts = options                    # * is used to send multiple values
#varaiable is internally defined as 'selected' ie varaiable=selected

#dropdown display option font
opts.config(font=('',14))

#inside menu options font
options_menu =frame1.nametowidget(opts.menuname)             #here .menuname gives inbox options
options_menu.config(font=('',14))

opts.pack(pady=(0,20))

#creating sliders
#they are two types : vertical and horizontal

def box_ver(num_v):
    print(num_v)
def box_hor(num_h):
    print(num_h)

#creating Freame2:

frame2 = LabelFrame(mw,text='This is frame2',font=('',14),width=300,padx=10, pady=10) #no use of width operator ,size will increase only based on widgets like buttons
frame2.grid(row=0,column=1,padx=10,pady=10)

ver = Scale(frame2, from_=0, to=200, command=box_ver)
# scale command automatically send one value to function we dont want use lambda for sending parameters
ver.grid(row=0,column=0,pady=(0,20))

hor= Scale(frame2, from_=0, to=200, orient=HORIZONTAL,command=box_hor)   #orient is for direction
hor.grid(row=0,column=1,pady=(0,20))

mw.mainloop()


#!/usr/bin/python
# -*- coding: utf-8 -*-
from django.shortcuts import render, render_to_response
from base_api.full_views.helper import get_request_param_as_string
from base_api.models import *
from base_api.form import *
from django.http import *

def full_add_city(request):
    if not request.user.is_active:
        return HttpResponseRedirect('/login/')
    out = {}
    user_role = Roles.objects.get(id=request.user.id).role
    if user_role == 2:
        return HttpResponseRedirect('/oops/')
    else:
        out.update({'user_role': user_role})
    get_params = '?'
    get_params += get_request_param_as_string(request)
    if request.method == 'POST':
        form = CityForm(request.POST)
        if form.is_valid():
            name = request.POST['name']
            if Cities.objects.filter(name=name).count() == 0:
                new_city = Cities.objects.create(name=name)
                return HttpResponseRedirect('/' + get_params)
            else:
                out.update({"error": 1})
                out.update({'page_title': "Добавление города"})
        else:
            out.update({'page_title': "Добавление города"})
    else:
        form = CityForm()
    out.update({'form': form})
    return render(request, 'add_city.html', out)


#! /usr/bin/env python

"""
    How many total Characters are there?
    How many of each specific subclass?
    How many total Items?
    How many of the Items are weapons? How many are not?
    How many Items does each character have? (Return first 20 rows)
    How many Weapons does each character have? (Return first 20 rows)
    On average, how many Items does each Character have?
    On average, how many Weapons does each character have?
"""

import sqlite3

conn = sqlite3.connect('rpg_db.sqlite3')
curs = conn.cursor()

# How many total Characters are there? table: charactercreator_character
count_characters = 'SELECT COUNT(*) FROM charactercreator_character;'
print(curs.execute(count_characters).fetchall())

# How many of each specific subclass?
count_mages = 'SELECT COUNT(*) FROM charactercreator_mage;'
print(curs.execute(count_mages).fetchall())

# How many total Items?
count_items = 'SELECT COUNT(*) FROM armory_item;'
print(curs.execute(count_items).fetchall())

# How many of the Items are weapons? How many are not?
count_weapons = 'SELECT COUNT(*) FROM armory_item WHERE item like("%WEAPON%");'
print(curs.execute(count_weapons).fetchall())

# How many Items does each character have? (Return first 20 rows)
# How many Weapons does each character have? (Return first 20 rows)
# On average, how many Items does each Character have


from scipy import stats
from itertools import chain

df = [[15, 20], [17, 3]]

def check(df):
    if min(list(chain(*df))) < 5:
        fisher(df)
    else:
        pirson(df)

def fisher(df):
    print('fisher')
    odds_ratio, p_value = stats.fisher_exact(df)
    print(f'p-value = {p_value:.3f}')

def pirson(df):
    print('pirson')
    chi2_value, p_value, df_value, expected_array = stats.chi2_contingency(df, correction=True)
    print(f'Хи-квадрат = {chi2_value:.3f}, p-value = {p_value:.3f}, df = {df_value}')
    print(f'Ожидаемые значения:\n{expected_array}')

check(df)

--- Расчет по парсону или фишеру листа 2х2/den.py