from __future__ import print_function

import sys
import os
sys.path.append(os.path.abspath(".."))

from termux2d import Canvas, Palette, animate, COLOR_CYAN, COLOR_GREEN, COLOR_RED, COLOR_YELLOW
from termux2d import get_terminal_size_in_pixels, handle_input
from termux2d import KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT
from image2term import image2term
from snake import DIR_N,DIR_S,DIR_E,DIR_W,Snake

c = Canvas()
p = Palette()
t = 0

def set_pos(frame,xd,yd):
    return [(x+xd,y+yd,c) for (x,y,c) in frame]

def load_arena():
    arena = []
    baphomet_head = image2term('img/baphomet_head.gif', ratio=0.48, invert=True)
    tw,th = get_terminal_size_in_pixels()

    arena.extend(set_pos(baphomet_head,tw/2 - 105,th/2 - 105))
    arena.extend(image2term('img/arena.png',ratio=1.0))

    return arena

def __update__():
    t = 0
    snake1 = Snake(100,150,COLOR_YELLOW,DIR_E)
    snake2 = Snake(200,150,COLOR_RED,DIR_E)
    snake3 = Snake(100,200,COLOR_GREEN,DIR_E)
    snake4 = Snake(200,200,COLOR_CYAN,DIR_E)
    snakes = [snake1,snake2,snake3,snake4]

    while True:
        key = handle_input()
        if key == KEY_UP:
            snake1.head.dir = DIR_N
        elif key == KEY_DOWN:
            snake1.head.dir = DIR_S
        elif key == KEY_LEFT:
            snake1.head.dir = DIR_W
        elif key == KEY_RIGHT:
            snake1.head.dir = DIR_E

        frame = []
        for snake in snakes:
            frame.extend(snake.frame())

        yield frame
        t += 1
        for snake in snakes:
            snake.__update__()
            if t % 10 == 0 and snake is not snake1:
                snake.head.dir += 1
                if snake.head.dir == 4:
                    snake.head.dir = 0

if __name__ == '__main__':
    p.add_color(COLOR_CYAN)

    frame = []
    frame.extend(load_arena())
    c.set_static(frame)

    animate(c,p, __update__, 1./8)


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

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

wd = webdriver.Chrome(service=Service(r'E:\chromedriver\chromedriver.exe'))
wd.get('F:\自动化学习\selenium\自学\窗口切换\白月黑羽测试网页3.html')
wd.implicitly_wait(10)

elements = wd.find_elements(By.TAG_NAME, 'a')

for element in elements:
    element.click()

    # 获取当前窗口的句柄并保存，方便后续返回
    first_window = wd.current_window_handle

    # 获取当前页面所有的句柄
    for handle in wd.window_handles:
        # 根据句柄，切换到对应窗口
        wd.switch_to.window(handle)
        # 判断这个窗口是不是我们想要操作的窗口
        if '必应' in wd.title:
            break

    print(wd.title)

    # 根据提前保存的原窗口的句柄，切换回原窗口
    wd.switch_to.window(first_window)
    wd.switch_to.window(first_window)

    # 点击“功能按钮”，打印结果
    element_function_button = wd.find_element(By.ID, 'outerbutton')
    element_function_button.click()
    element_result = wd.find_element(By.TAG_NAME, 'li')
    print(element_result.text)

# wd.quit()
pass

窗口切换/窗口切换.py


import glob
import logging
import logging.handlers
import os
import stat
import subprocess
from pathlib import Path

import pyudev

from lava_common.constants import DISPATCHER_DOWNLOAD_DIR as JOBS_DIR
from lava_common.exceptions import InfrastructureError
from lava_common.yaml import yaml_safe_dump, yaml_safe_load
from lava_dispatcher_host.docker_devices import Device, DeviceFilter

context = pyudev.Context()

logger = logging.getLogger("lava-dispatcher-host")
logger.addHandler(logging.handlers.SysLogHandler(address="/dev/log"))
logger.setLevel(logging.INFO)

def get_mapping_path(job_id):
    return os.path.join(JOBS_DIR, job_id, "usbmap.yaml")

def add_device_container_mapping(job_id, device_info, container, container_type="lxc"):
    validate_device_info(device_info)
    item = {
        "device_info": device_info,
        "container": container,
        "container_type": container_type,
        "job_id": job_id,
    }
    mapping_path = get_mapping_path(job_id)
    data = load_mapping_data(mapping_path)

    # remove old mappings for the same device_info
    newdata = [old for old in data if old["device_info"] != item["device_info"]]
    newdata.append(item)

    os.makedirs(os.path.dirname(mapping_path), exist_ok=True)
    with open(mapping_path, "w") as f:
        f.write(yaml_safe_dump(newdata))

def remove_device_container_mappings(job_id):
    os.unlink(get_mapping_path(job_id))

def validate_device_info(device_info):
    if not device_info:
        raise ValueError("Addind mapping for empty device info: %r" % device_info)
    if not any(device_info.values()):
        raise ValueError(
            "Addind mapping for device info with empty keys: %r" % device_info
        )

def share_device_with_container(options):
    data, job_id = find_mapping(options)
    if not data:
        return
    container = data["container"]
    device = options.device
    if not device.startswith("/dev/"):
        device = "/dev/" + device
    if not os.path.exists(device):
        logger.warning(f"Can't share {device}: file not found")
        return

    container_type = data["container_type"]
    if container_type == "lxc":
        share_device_with_container_lxc(container, device, job_id=job_id)
    elif container_type == "docker":
        share_device_with_container_docker(container, device, job_id=job_id)
    else:
        raise InfrastructureError('Unsupported container type: "%s"' % container_type)

def find_mapping(options):
    for mapping in glob.glob(get_mapping_path("*")):
        data = load_mapping_data(mapping)
        for item in data:
            if match_mapping(item["device_info"], options):
                job_id = str(Path(mapping).parent.name)
                return item, job_id
    return None, None

def load_mapping_data(filename):
    try:
        with open(filename) as f:
            data = yaml_safe_load(f) or []
        if isinstance(data, dict):
            data = [data]
        return data
    except FileNotFoundError:
        return []

def match_mapping(device_info, options):
    matched = False
    for k, v in device_info.items():
        if v:
            if k in options and getattr(options, k) == v:
                matched = True
            else:
                return False
        else:
            matched = True
    return matched

def log_sharing_device(device, container_type, container):
    logger.info(f"Sharing {device} with {container_type} container {container}")

def share_device_with_container_lxc(container, node, job_id):
    device = pyudev.Devices.from_device_file(context, node)
    pass_device_into_container_lxc(container, node, device.device_links, job_id)
    for child in device.children:
        if child.device_node:
            pass_device_into_container_lxc(
                child.device_node, child.device_links, job_id
            )

def pass_device_into_container_lxc(container, node, links=[], job_id=None):
    try:
        nodeinfo = os.stat(node)
        uid = nodeinfo.st_uid
        gid = nodeinfo.st_gid
        mode = "%o" % (0o777 & nodeinfo.st_mode)
    except FileNotFoundError as exc:
        logger.warning(
            f"Cannot share {node} with lxc container {container}: {exc.filename} not found"
        )
        return
    subprocess.check_call(["lxc-device", "-n", container, "add", node])
    log_sharing_device(node, "lxc", container)

    set_perms = f"chown {uid}:{gid} {node} && chmod {mode} {node}"
    subprocess.check_call(["lxc-attach", "-n", container, "--", "sh", "-c", set_perms])

    for link in links:
        create_link = f"mkdir -p {os.path.dirname(link)} && ln -f -s {node} {link}"
        subprocess.check_call(
            ["lxc-attach", "-n", container, "--", "sh", "-c", create_link]
        )

def pass_device_into_container_docker(
    container, container_id, node, links=[], job_id=None
):
    try:
        nodeinfo = os.stat(node)
        major = os.major(nodeinfo.st_rdev)
        minor = os.minor(nodeinfo.st_rdev)
        nodetype = "b" if stat.S_ISBLK(nodeinfo.st_mode) else "c"

        state = Path(JOBS_DIR) / job_id / (container_id + ".devices")
        device_filter = DeviceFilter(container_id, state)
        device_filter.add(Device(major, minor))
        device_filter.apply()
        device_filter.save(state)

    except FileNotFoundError as exc:
        logger.warning(
            f"Cannot share {node} with docker container {container}: {exc.filename} not found"
        )
        return

    # it's ok to fail; container might have already exited at this point.
    nodedir = os.path.dirname(node)
    uid = nodeinfo.st_uid
    gid = nodeinfo.st_gid
    mode = "%o" % (0o777 & nodeinfo.st_mode)
    subprocess.call(
        [
            "docker",
            "exec",
            container,
            "sh",
            "-c",
            f"mkdir -p {nodedir} && mknod {node} {nodetype} {major} {minor} && chown {uid}:{gid} {node} && chmod {mode} {node}",
        ]
    )

    for link in links:
        subprocess.call(
            [
                "docker",
                "exec",
                container,
                "sh",
                "-c",
                f"mkdir -p {os.path.dirname(link)} && ln -f -s {node} {link}",
            ]
        )

def share_device_with_container_docker(container, node, job_id=None):
    log_sharing_device(node, "docker", container)
    try:
        container_id = subprocess.check_output(
            ["docker", "inspect", "--format={{.ID}}", container], text=True
        ).strip()
    except subprocess.CalledProcessError:
        logger.warning(
            f"Cannot share {node} with docker container {container}: container not found"
        )
        return

    device = pyudev.Devices.from_device_file(context, node)
    pass_device_into_container_docker(
        container, container_id, node, device.device_links, job_id
    )

    for child in device.children:
        if child.device_node:
            pass_device_into_container_docker(
                container, container_id, child.device_node, child.device_links, job_id
            )


class Piece:

    def __init__(self, name, left, right, bottom):
        self.name = name
        self.left = left
        self.right = right
        self.bottom = bottom
        self.top = None
        self.inverted = False
        self.rotations = 0  # rotations are always right
        self.corner_piece = False
        self.side_piece = False

    def rotate(self):
        if self.inverted:
            assert(self.bottom is None and self.top is not None),\
                "Piece is inverted and either has no top or has a bottom"
            self.bottom = self.right
            self.right = self.top
            self.top = None
            self.inverted = False
            self.rotations = 0 if ((self.rotations + 1) % 6 == 0) else self.rotations + 1

        else:
            assert(self.bottom is not None and self.top is None), \
                "Uninverted piece but either has a top or has no bottom"
            self.top = self.left
            self.left = self.bottom
            self.bottom = None
            self.inverted = True
            self.rotations = 0 if ((self.rotations + 1) % 6 == 0) else self.rotations + 1

    def __str__(self):
        return "{}, L:{}, R:{}, T:{}, B:{}, Rot:{}"\
            .format(self.name, self.left, self.right, self.top, self.bottom, self.rotations)

    def print_verbose(self):
        print("{}: left: {}, right: {}, top: {}, bottom: {}, rotations: {}" \
            .format(self.name, self.left, self.right, self.top, self.bottom, self.rotations))

    def count_zeros(self):
        """This helps determine if pieces are corner or side pieces. """
        zeros = 0
        if self.right == 0:
            zeros += 1
        if self.left == 0:
            zeros += 1
        if self.bottom == 0:
            zeros += 1
        if self.top == 0:
            zeros += 1
        return zeros


from .private._concat import _concat
from .private._curry3 import _curry3

def inner_adjust(idx, fn, arr):
  length = len(arr)
  if idx >= length or idx < -length:
    return arr
  _idx = (length + idx) % length
  _arr = _concat(arr)
  _arr[_idx] = fn(arr[_idx])
  return _arr

adjust = _curry3(inner_adjust)


from django.shortcuts import render
from django.db.utils import IntegrityError

from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import status

from .models import Translation, Source
from .serializers import TranslationsSerializer

class ListCreateTranslationView(generics.ListCreateAPIView):

  queryset = Translation.objects.all()
  serializer_class = TranslationsSerializer

  def post(self, request, *args, **kwargs):
    createdSource = self.createSource(request)
    createdTranslation = Translation.objects.create(
      text = request.data['text'].strip(),
      translation = request.data['translation'].strip(),
      source = createdSource
    )
    return Response(
      data=TranslationsSerializer(createdTranslation).data,
      status=status.HTTP_201_CREATED
    )

  def createSource(self, request):
    try:
      return Source.objects.create(
        author=request.data['source']['author'].strip(),
        url=request.data['source']['url'].strip(),
        publisher=request.data['source']['publisher'].strip()
      )
    except IntegrityError:
      return Source.objects.get(
        author = request.data['source']['author'].strip(),
        url = request.data['source']['url'].strip(),
        publisher = request.data['source']['publisher'].strip())


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

# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

"""
Produce skeleton Performance Data Review Requests.

This was mostly copies from glean_parser, and should be kept in sync.
"""

import re
from pathlib import Path
from typing import Sequence

from glean_parser import parser, util

def generate(
    bug: str,
    metrics_files: Sequence[Path],
) -> int:
    """
    Commandline helper for Data Review Request template generation.

    :param bug: pattern to match in metrics' bug_numbers lists.
    :param metrics_files: List of Path objects to load metrics from.
    :return: Non-zero if there were any errors.
    """

    metrics_files = util.ensure_list(metrics_files)

    # Accept any value of expires.
    parser_options = {
        "allow_reserved": True,
        "custom_is_expired": lambda expires: False,
        "custom_validate_expires": lambda expires: True,
    }
    all_objects = parser.parse_objects(metrics_files, parser_options)

    if util.report_validation_errors(all_objects):
        return 1

    # I tried [\W\Z] but it complained. So `|` it is.
    reobj = re.compile(f"\\W{bug}\\W|\\W{bug}$")
    durations = set()
    responsible_emails = set()
    metrics_table = ""
    for category_name, metrics in all_objects.value.items():
        for metric in metrics.values():
            if not any([len(reobj.findall(bug)) == 1 for bug in metric.bugs]):
                continue

            metric_name = util.snake_case(metric.name)
            category_name = util.snake_case(category_name)
            one_line_desc = metric.description.replace("\n", " ")
            sensitivity = ", ".join([s.name for s in metric.data_sensitivity])
            last_bug = metric.bugs[-1]
            metrics_table += f"`{category_name}.{metric_name}` | "
            metrics_table += f"{one_line_desc} | {sensitivity} | {last_bug}\n"
            if metric.type == "event" and len(metric.allowed_extra_keys):
                for extra_name, extra_detail in metric.extra_keys.items():
                    extra_one_line_desc = extra_detail["description"].replace("\n", " ")
                    metrics_table += f"`{category_name}.{metric_name}#{extra_name}` | "
                    metrics_table += (
                        f"{extra_one_line_desc} | {sensitivity} | {last_bug}\n"
                    )

            durations.add(metric.expires)

            if metric.expires == "never":
                responsible_emails.update(metric.notification_emails)

    if len(durations) == 1:
        duration = next(iter(durations))
        if duration == "never":
            collection_duration = "This collection will be collected permanently."
        else:
            collection_duration = f"This collection has expiry '{duration}'"
    else:
        collection_duration = "Parts of this collection expire at different times: "
        collection_duration += f"{durations}"

    if "never" in durations:
        collection_duration += "\n" + ", ".join(responsible_emails) + " "
        collection_duration += "will be responsible for the permanent collections."

    if len(durations) == 0:
        print(f"I'm sorry, I couldn't find metrics matching the bug number {bug}.")
        return 1

    # This template is pulled from
    # https://github.com/mozilla/data-review/blob/main/request.md
    print(
        """
!! Reminder: it is your responsibility to complete and check the correctness of
!! this automatically-generated request skeleton before requesting Data
!! Collection Review. See https://wiki.mozilla.org/Data_Collection for details.

DATA REVIEW REQUEST
1. What questions will you answer with this data?

TODO: Fill this in.

2. Why does Mozilla need to answer these questions? Are there benefits for users?
   Do we need this information to address product or business requirements?

In order to guarantee the performance of our products, it is vital to monitor
real-world installs used by real-world users.

3. What alternative methods did you consider to answer these questions?
   Why were they not sufficient?

Our ability to measure the practical performance impact of changes through CI
and manual testing is limited. Monitoring the performance of our products in
the wild among real users is the only way to be sure we have an accurate
picture.

4. Can current instrumentation answer these questions?

No.

5. List all proposed measurements and indicate the category of data collection for each
   measurement, using the Firefox data collection categories found on the Mozilla wiki.

Measurement Name | Measurement Description | Data Collection Category | Tracking Bug
---------------- | ----------------------- | ------------------------ | ------------"""
    )
    print(metrics_table)
    print(
        """
6. Please provide a link to the documentation for this data collection which
   describes the ultimate data set in a public, complete, and accurate way.

This collection is Glean so is documented
[in the Glean Dictionary](https://dictionary.telemetry.mozilla.org).

7. How long will this data be collected?
"""
    )
    print(collection_duration)
    print(
        """
8. What populations will you measure?

All channels, countries, and locales. No filters.

9. If this data collection is default on, what is the opt-out mechanism for users?

These collections are Glean. The opt-out can be found in the product's preferences.

10. Please provide a general description of how you will analyze this data.

This will be continuously monitored for regression and improvement detection.

11. Where do you intend to share the results of your analysis?

Internal monitoring (GLAM, Redash, Looker, etc.).

12. Is there a third-party tool (i.e. not Telemetry) that you
    are proposing to use for this data collection?

No.
"""
    )

    return 0


import requests
import json

user = 'Sergei729'
url = f'https://api.github.com/users/{user}/repos'

response = requests.get(url).json()

with open('repos_names.json', 'w') as file:
    json.dump(response, file)

for repo_name in response:
    print(repo_name['name'])


# -*- coding: UTF-8 -*-

from db_entities.message.message import Message
from db_entities.message.rcp_list import Rcp_list
from sendmail.post_office import PostOffice
from google.appengine.ext import db
from tools.tag_processor import tag_processor

class Handler():

    def send(self, owner, rcp, title, body): #rcp must be a list!
        new_msg = Message()
        new_msg.owner = owner
        new_msg.title = tag_processor().mask_tags(title)
        new_msg.body = tag_processor().prepare(body)
        message = new_msg.put()

        for r in rcp:
            msg_r = Rcp_list()
            msg_r.rcp = r
            msg_r.message = message
            msg_r.put()

#        to = [r for r in rcp]  # generate list of rcp keys

        PostOffice().append_to_queue(rcp, title, body)

    def get_incoming(self, user):
        rcp_list = Rcp_list.gql("where rcp = :rcp", rcp = user)
        messages = []
        for entity in rcp_list:
            if entity.deleted: continue
            messages.append(entity.message)
        return self.__get_letters(messages)

    def get_outgoing(self, user):
        messages = Message.gql("where owner = :owner and deleted = :is_deleted", owner = user, is_deleted = False)
        return self.__get_letters(messages)

    def __get_letters(self, messages):
        formalized_messages = []
        for message in messages:
            owner = { 'login' : message.owner.login }
            rcp = []
            r_read = False
            rcp_list = Rcp_list.gql("where message = :message", message = message)
            for r in rcp_list:
                rcp.append({'login': r.rcp.login})
                r_read = r.read
            title = message.title
            o_read = message.read
            datetime = message.datetime
            formalized_messages.append({'key' : message.key(), 'r_read' : r_read, 'o_read' : o_read, 'owner':owner, 'rcp':rcp[:5], 'title':title[:32] + " ...", 'datetime': datetime})
            formalized_messages.sort(key=lambda k: k['datetime'])
        return formalized_messages

    def get_letter(self, letter, user):
        letter_ = db.get(letter)
        rcp = False
        try:
            rcp = Rcp_list.gql("where message = :letter and rcp = :user", letter = db.Key(letter), user = user)[0]
        except: pass
        if letter_.owner.key() == db.Key(user) or rcp:
            if rcp:
                rcp.read = True
                rcp.put()
            return letter_

    def delete(self, messages, user):
        messages_ = db.get(messages)
        for message in messages_:
            if message.owner == user:
                message.deleted = True
                message.read = True
                message.put()
            else:
                rcp = Rcp_list.gql("where message = :message and rcp = :rcp", message = message, rcp = user)[0]
                rcp.deleted = True
                rcp.read = True
                rcp.put()

    def has_unread_msg(self, user):
        try:
            return Rcp_list.gql("where rcp = :rcp and read = :read", rcp = user, read = False).count(1)
        except:
            return False


import pandas as pd
from pandas._libs import missing
import requests
from datetime import datetime, timedelta
import time

authors_papers_csv = "C:/Users/zeagle/scratch/Research/authors_papers.csv"
external_id_csv = "C:/Users/zeagle/scratch/Research/external_ids.csv"
papers = pd.read_csv(authors_papers_csv)

requestTiming = pd.DataFrame(columns=['request','timestamp'])
rateLimit = 75
#rate limit time in minutes
rateTime = 5

def checkRate():
    now = datetime.now()
    rateLimitBeginning = pd.Timestamp(now - timedelta(hours=0, minutes=rateTime,seconds=0))
    filtermask = requestTiming['timestamp'] > rateLimitBeginning
    filteredDf = requestTiming[filtermask]
    return filteredDf.shape[0]

def timeRemaining():
    now = datetime.now()
    rateLimitBeginning = pd.Timestamp(now - timedelta(hours=0, minutes=rateTime,seconds=0))
    filtermask = requestTiming['timestamp'] > rateLimitBeginning
    filteredDf = requestTiming[filtermask]
    sortedDf = filteredDf.sort_values(by='timestamp', ascending=True, na_position='last')
    timeleft = (now - sortedDf.iloc[1]['timestamp']).seconds
    timeleft = rateTime*60 - timeleft
    return timeleft

def open_exisiting_file(file):
    try:
        exisiting_list = pd.read_csv(file, dtype="str")
    except FileNotFoundError:
        exisiting_list = pd.DataFrame()
    return exisiting_list

def save_file(new_item, existing_list, file):
    paper_list_to_save = existing_list.append(new_item, sort=False, ignore_index=True)
    paper_list_to_save = paper_list_to_save.drop_duplicates(ignore_index=True)
    paper_list_to_save.to_csv(file, index=False)

existing_ids = open_exisiting_file(external_id_csv)

#get list of papers from semantic scholar list
paper_list = open_exisiting_file(authors_papers_csv)
paper_list = paper_list[['paperId',]]
paper_list = paper_list.dropna()
print(paper_list)
#get existing list of cross ref
id_list = open_exisiting_file(external_id_csv)
id_list = id_list[['paperId',]]
print(id_list)

combined_list = pd.merge(paper_list, id_list, how='outer', indicator="Exists", left_on='paperId', right_on='paperId')
print(combined_list[combined_list['Exists'] != 'both'])
missing_details = combined_list[combined_list['Exists'] != 'both']
print(missing_details)
combined_list.to_csv('C:/Users/zeagle/scratch/Research/test.csv')
paperIds = missing_details['paperId']
print(paperIds)

externalIds_list = pd.DataFrame()
for paper in paperIds:
    request = 'https://api.semanticscholar.org/graph/v1/paper/'+paper+'?fields=externalIds'
    now = datetime.now()
    requestTiming = requestTiming.append({
        "request": request,
        "timestamp": pd.Timestamp(now.strftime("%m/%d/%Y %H:%M:%S"))
        }, ignore_index=True)
    while checkRate() > rateLimit:
        print("Sleeping for rate limit. Time remaining:" + str(timeRemaining()), end='\r')
        time.sleep(1)
    paperInfo = requests.get(request).json()
    externalIds = paperInfo['externalIds']
    externalIds["paperId"] = paper
    #externalIds_list = externalIds_list.append(externalIds, ignore_index=True)
    print(externalIds)
    existing_ids = open_exisiting_file(external_id_csv)
    save_file(externalIds, existing_ids, external_id_csv)


# 迭代器
## 定义一个迭代器
from collections.abc import Iterable

# 如果要对list实现类似Java那样的下标循环怎么办？Python内置的enumerate函数可以把一个list变成索引-元素对，这样就可以在for循环中同时迭代索引和元素本身
lista = [1, 2, 5, 7, 9, 2]
for index, value in enumerate(lista):
    print(f"索引值是：{index}", f"当前索引对应的值是：{value}")
# it = iter(lista)
# print(type(it))
# print(next(it))
# print(next(it))
'''for 循环遍历迭代器'''
# for i in it:
#     print(i, end=" ")
"""while 循环遍历迭代器"""
# n = len(lista)
# while n > 0:
#     print(next(it), end=" ")
#     n -= 1
a = {"name": "zhangsan", "data": 1, "msg": "ok"}
if isinstance(a, Iterable):
    print("这是一个可迭代对象")
    for x, y in a.items():
        print(x, y)
else:
    print("这不是一个可迭代对象")

import os

newlist = [d for d in os.listdir('../../')]
print(newlist)


# Messing with Pie Charts
# Author: Megan O'Donovan

import numpy as np
import matplotlib.pyplot as plt

fruit = np.array(['Apple', 'Orange', 'Banana'])
numbers = np.array([23,77,50])

plt.pie(numbers, labels = fruit)
plt.legend()
plt.show()


class TwoSum:
    def findTwoSum(self,nums,target):
        set = dict()

        for i in range(0,len(nums)):
            comp = target - nums[i]
            print(set[comp])
            if comp in set:
                return [set[comp],i]

            set[comp] = i

        return None

test = TwoSum()
res = test.findTwoSum([2,7,10,11,23],9)
print(res)


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

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import os
import json

class PoetryCrawlPipeline(object):
    def open_spider(self, spider):
        print("crawl start......")

    def close_spider(self, spider):
        print("crawl complete!")

    def process_item(self, item, spider):
        # convert to dict first
        i = dict(item)

        # dist/ is the output dir
        if not os.path.exists('./dist'):
            os.mkdir('./dist')

        dir_dynasty = './dist/' + i['dynasty']
        dir_file = './dist/' + i['dynasty'] + '/' + i['dynasty'] + '_' + i['author'] + '.json'

        if not os.path.exists(dir_dynasty):
            os.makedirs(dir_dynasty)

        if not os.path.exists(dir_file):
            f = open(dir_file, 'w+', encoding='utf-8')
            text = {
                "dynasty": i["dynasty"],
                "author": i["author"],
                "intro": i["intro"],
                "items": [
                    {
                        "title": i["title"],
                        "content": i["content"]
                    }
                ]
            }
            json.dump(text, f, ensure_ascii=False, indent=4)
            f.close()

        else:
            f = open(dir_file, 'r+', encoding='utf-8')
            text = json.load(f)
            text["items"].append(
                {
                    "title": i["title"],
                    "content": i["content"]
                }
            )
            f.close()

            f = open(dir_file, 'w+', encoding='utf-8')
            json.dump(text, f, ensure_ascii=False, indent=4)
            f.close()

        # stdout info
        print("已处理：" + i['dynasty'] + "_" + i['author'] + "_" + i["title"])

        return item


average=[]
descending_order=[]
average2=[]

print("-"*10+" Bowling Scores Statistics for each player "+"-"*10)
for p in range (3):
    score=[]
    highest_score= 0
    print("Player "+str(p+1))
    for game in range(5) :
        mark= input("Enter score for the game "+ str(game+1)+": ")
        score.append(mark)

    for i in range(5):
        if int(score[i])>highest_score:
            highest_score= int(score[i])
    lowest_score=int(score[0])
    for i in range(5):
        lowest_score= int(score[i])

    average_score=int(score[0])+int(score[1])+int(score[2])+int(score[3])+int(score[4])/5
    average.append(average_score)
    average2.append(average_score)

    print("Scores (5 games): "+ str(score))
    print("Average Score: "+str(average_score))
    print("Highest score: "+str(highest_score))
    print("Lowest score: "+ str(lowest_score))

print("")
print("-"*10+" Average scores of player in descending order "+"-"*10)

while len(average) > 0:
    highScore = average[0]
    for i in average:
        if i > highScore:
            highScore = i
    descending_order.append(highScore)
    average.remove(highScore)

'''
i= 3
while i > 0:
    larger_num= 0
    p = len(average)
    while p > 0:
        if average[p-1]> larger_num:
            larger_num = average[p-1]
            p = p - 1
    average.remove(larger_num)
    descending_order.append(larger_num)
    i = i -1
'''

print("Average scores of player is descending order: "+str(descending_order))
print(" ")
print("-"*10+" Player's Ranking "+"-"*10)
for i in range(3):
    print("Player " + str(i+1) + "'s average score [" + str(average2[i]) + "] is ranked " + str(descending_order.index(average2[i]) + 1))


from datetime import datetime

from django.shortcuts import render, get_object_or_404, redirect

from categories.models import Category
from comments.forms import CommentForm
from comments.models import PostComment
from core.views import get_posts
from posts.models import Post

def index(request):
    head_post = Post.objects.filter(status='published').filter(published__lte=datetime.now()).last()
    head_post_categories = head_post.category.all()
    all_categories = Category.objects.all()

    posts = Post.objects.filter(status='published').filter(published__lte=datetime.now()).order_by('-published')[1:]

    ctx = get_posts(request, queryset=posts)
    return render(request, 'posts/index.html',
                  {'head_post': head_post, 'head_post_categories': head_post_categories,
                   'all_categories': all_categories, **ctx})

def post_detail(request, year, month, day, slug):
    post = get_object_or_404(Post, slug=slug, status='published', published__year=year,
                             published__month=month, published__day=day)
    post_categories = post.category.all()
    post_comments = post.comments.filter(parent__isnull=True).order_by('-created')

    if request.method == 'POST':
        comment_form = CommentForm(request.POST)
        if comment_form.is_valid():
            parent_obj = None

            try:
                parent_id = int(request.POST.get('parent_id'))
            except:
                parent_id = None

            if parent_id:
                parent_obj = PostComment.objects.get(id=parent_id)
                if parent_obj:
                    replay_comment = comment_form.save(commit=False)
                    replay_comment.parent = parent_obj

            new_comment = comment_form.save(commit=False)
            new_comment.post = post
            new_comment.save()
            return redirect(request.path)
    else:
        comment_form = CommentForm()

    try:
        previous_post = post.get_previous_by_published()
    except post.DoesNotExist:
        previous_post = post

    try:
        next_post = post.get_next_by_published()
    except post.DoesNotExist:
        next_post = post

    return render(request, 'posts/post_detail.html', {'post': post, 'post_categories': post_categories,
                                                      'comment_form': comment_form, 'post_comments': post_comments,
                                                      'previous_post': previous_post, 'next_post': next_post})


"""Menu models"""

# Django
from django.db import models

class Option(models.Model):
    """Option model."""

    meal = models.CharField(
        'meal name',
        max_length=255,
        help_text=('meal option')
    )

class Menu(models.Model):
    """Menu model.

    Specific meals create a complete menu.
    """

    title_text = models.TextField(
        blank=True,
        null=True,
        help_text=(
            'greeting or menu description'
        )
    )

    option_meals = models.ManyToManyField(
        to='option',
        related_name='meals',
    )

    agreed_date = models.DateField(null=True, blank=True, default=None)

    create_date = models.DateTimeField(auto_now_add=True)

    updated_date = models.DateTimeField(auto_now=True)

    def __str__(self) -> str:
        """return username."""
        return self.agreed_date

    def get_short_name(self) -> str:
        """Return usermane."""
        return self.agreed_date


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 15:03:31 2020

@author: shubham
"""

import numpy as np
import pandas as pd
a = np.arange(0,11)
#m = (a > 2) & (a < 9)
#a[m] *= -1
#print(a)
for i in a:
    if i>2 and i<9:
        a[i]*=-1
print(a)

Basic Python case study/case_4/case_m4_1_10.py


import tensorflow as tf
#import tensorflow.contrib as tfcontrib

class KimCNN(object):
    def __init__(self,
                 sequence_length,
                 filter_sizes,
                 num_filters,
                 pretrained_word_embeddings,
                 sentence_embedding_size,
                 word_embedding_static):
        # Placeholders for input, dropout and pretrained_embedding
        self.input_x = tf.placeholder(tf.int32, [None, sequence_length], name="input_x")
        self.dropout_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

        self.l2_loss = tf.constant(0.0)

        word_embedding_size = len(pretrained_word_embeddings[0])
        # Embedding layer
        self.word_embedding_w = tf.Variable(
            initial_value=tf.constant(0.0, shape=[len(pretrained_word_embeddings), word_embedding_size]),
            trainable=(not word_embedding_static), name="word_embedding_w")
        self.word_embedding_init = self.word_embedding_w.assign(pretrained_word_embeddings)

        embedded_words = tf.nn.embedding_lookup(self.word_embedding_w, self.input_x)
        embedded_words_expanded = tf.expand_dims(embedded_words, -1)

        # Create a convolution + maxpool layer for each filter size
        pooled_outputs = []
        for i, filter_size in enumerate(filter_sizes):
            with tf.name_scope("conv-maxpool-%s" % filter_size):
                # Convolution Layer
                filter_shape = [filter_size, word_embedding_size, 1, num_filters]
                weight = tf.Variable(tf.truncated_normal(filter_shape, stddev=0.1), name="weight")
                bias = tf.Variable(tf.constant(0.1, shape=[num_filters]), name="bias")
                conv = tf.nn.conv2d(input=embedded_words_expanded,
                                    filter=weight,
                                    strides=[1, 1, 1, 1],
                                    padding="VALID",
                                    name="conv")
                # Apply nonlinearity
                activation = tf.nn.relu(tf.nn.bias_add(conv, bias), name="relu")
                # Maxpooling over the outputs
                pooled = tf.nn.max_pool(
                    activation,
                    ksize=[1, sequence_length - filter_size + 1, 1, 1],
                    strides=[1, 1, 1, 1],
                    padding='VALID',
                    name="pool")
                pooled_outputs.append(pooled)

                self.l2_loss += tf.nn.l2_loss(weight)
                self.l2_loss += tf.nn.l2_loss(bias)

        # Combine all the pooled features
        num_filters_total = num_filters * len(filter_sizes)
        h_pool = tf.concat(pooled_outputs, 3)
        h_pool_flat = tf.reshape(h_pool, [-1, num_filters_total])

        # Add dropout
        with tf.name_scope("dropout"):
            h_drop = tf.nn.dropout(h_pool_flat, self.dropout_keep_prob)

        # Final normalized sentence embedding
        with tf.name_scope("output"):
            weight = tf.Variable(
                initial_value=tf.truncated_normal([num_filters_total, sentence_embedding_size], stddev=0.1),
                name="weight")
            bias = tf.Variable(tf.constant(0.1, shape=[sentence_embedding_size]), name="bias")
            sentence_embeddings = tf.nn.xw_plus_b(h_drop, weight, bias, name="sentence_embeddings")
            self.normalized_sentence_embeddings = tf.nn.l2_normalize(
                sentence_embeddings, 1, 1e-10, name="normalized_sentence_embeddings")

            self.l2_loss += tf.nn.l2_loss(weight)
            self.l2_loss += tf.nn.l2_loss(bias)


import glob
import os
import subprocess

def get_filenames(path, extension):
    file_pattern = f'*.{extension}'
    path_pattern = os.path.join(path, file_pattern)
    filenames = []
    for filepath in glob.glob(path_pattern):
        if not os.path.isfile(filepath):
            continue
        filenames.append(os.path.split(filepath)[1])
    return filenames

def get_filenames_gen(path, extension):
    file_pattern = f'*.{extension}'
    path_pattern = os.path.join(path, file_pattern)
    for filepath in glob.iglob(path_pattern):
        if not os.path.isfile(filepath):
            continue
        yield os.path.split(filepath)[1]

def ping_localhost():
    ping_command = 'ping -c 4 localhost'.split()
    with open('ping.txt', 'wb') as f:
        subprocess.run(ping_command, stdout=f)

if __name__ == '__main__':
    filenames = get_filenames(os.getcwd(), 'py')
    print(filenames)

    filenames = get_filenames_gen(os.getcwd(), 'py')
    print(filenames)
    for filename in filenames:
        print(filename)

    ping_localhost()


# permutation 직접 구현

def permutations(n, m):
    check = [0] * (n + 1)
    perm_list = []
    perm = []
    def permutation():
        if len(perm) == m:
            perm_list.append(perm.copy())
            return
        for i in range(1, n + 1):
            if check[i] == 1: continue
            check[i] = 1
            perm.append(i)
            permutation()
            check[i] = 0
            del perm[-1]
    permutation()
    return perm_list

N, M = map(int, input().split())
perm_list = permutations(N, M)
for perm in perm_list:
    for p in perm:
        print(p, end=' ')
    print()


from enum import Enum

class PortType(Enum):
    PORT_INPUT = 'input';
    PORT_OUTPUT= 'output';

    def code(self):
        if self == PortType.PORT_INPUT:
            return 0
        else:
            return 1

class PortName(str,Enum):
    IN0 = "in0"
    IN1 = "in1"
    OUT0 = "out0"
    OUT1 = "out1"
    OUT2 = "out2"

    def code(self):
        data = {
            PortName.IN0:0,
            PortName.IN1:1,
            PortName.OUT0:2,
            PortName.OUT1:3,
            PortName.OUT2:4,
        }
        return data[self]

    @staticmethod
    def from_code(v):
        data = [PortName.IN0, PortName.IN1, PortName.OUT0,
                PortName.OUT1, PortName.OUT2]
        return data[int(v)]

    def __lt__(self,other):
        return str(self) < str(other)

class BlockType(str,Enum):
    DAC = 'dac';
    ADC = 'adc';
    CHIP_INPUT = 'chip_input';
    CHIP_OUTPUT = 'chip_output';
    TILE_INPUT = "tile_input";
    TILE_OUTPUT = "tile_output";
    MULT = "mult";
    INTEG = "integ";
    FANOUT = "fanout";
    LUT = "lut";
    NONE = "<none>";

    def code(self):
        mapping = {
            BlockType.DAC: 0,
            BlockType.MULT: 5,
            BlockType.INTEG: 6,
            BlockType.FANOUT: 7,
            BlockType.LUT: 8,
            BlockType.ADC: 9
        }
        return mapping[self]

class CircCmdType(Enum):
    USE_DAC = 'use_dac';
    USE_MULT = 'use_mult';
    USE_FANOUT = 'use_fanout';
    USE_INTEG = 'use_integ';
    USE_LUT = 'use_lut';
    USE_ADC = 'use_adc';
    DISABLE_DAC = 'disable_dac';
    DISABLE_MULT = 'disable_mult';
    DISABLE_INTEG = 'disable_integ';
    DISABLE_FANOUT = 'disable_fanout';
    DISABLE_LUT = 'disable_lut';
    DISABLE_ADC = 'disable_adc';
    CONNECT = 'connect';
    BREAK = 'break';
    CALIBRATE = 'calibrate';
    GET_INTEG_STATUS = 'get_integ_status';
    GET_ADC_STATUS = 'get_adc_status';
    WRITE_LUT = "write_lut";
    GET_STATE = "get_state";
    SET_STATE = "set_state";
    MEASURE = "measure";
    TUNE = "tune";
    DEFAULTS = "defaults";
    PROFILE = "profile";

class ExpCmdType(Enum):
    RESET = 'reset';
    USE_ANALOG_CHIP = 'use_analog_chip';
    SET_SIM_TIME= 'set_sim_time';
    USE_OSC = 'use_osc';
    RUN = 'run';

class CmdType(Enum):
    CIRC_CMD = 'circ_cmd';
    EXPERIMENT_CMD = 'exp_cmd';
    FLUSH_CMD = 'flush_cmd';


import sys
from collections import deque

INPUT = sys.stdin.readline
DIRECTIONS = ((0, 1), (0, -1), (1, 0), (-1, 0))

def bfs() -> str | int:
    while QUEUE_FIRES:
        x, y = QUEUE_FIRES.popleft()

        for dx, dy in DIRECTIONS:
            nx, ny = x + dx, y + dy

            if 0 <= nx < C and 0 <= ny < R:
                if not VISIT_F[ny][nx] and MAZE[ny][nx] != "#":
                    VISIT_F[ny][nx] = VISIT_F[y][x] + 1
                    QUEUE_FIRES.append((nx, ny))

    while QUEUE_JIHOON:
        x, y = QUEUE_JIHOON.popleft()

        for dx, dy in DIRECTIONS:
            nx, ny = x + dx, y + dy

            if 0 <= nx < C and 0 <= ny < R:
                if MAZE[ny][nx] != "#" and not VISIT_J[ny][nx]:
                    if not VISIT_F[ny][nx] or VISIT_F[ny][nx] > VISIT_J[y][x] + 1:
                        VISIT_J[ny][nx] = VISIT_J[y][x] + 1
                        QUEUE_JIHOON.append((nx, ny))
            else:
                return VISIT_J[y][x]

    return "IMPOSSIBLE"

if __name__ == "__main__":
    R, C = map(int, INPUT().split())
    QUEUE_JIHOON, QUEUE_FIRES, MAZE = deque(), deque(), []
    VISIT_J = [[0 for _ in range(C)] for __ in range(R)]
    VISIT_F = [[0 for _ in range(C)] for __ in range(R)]
    for Y in range(R):
        tmp = list(INPUT().rstrip().strip())
        for X in range(C):
            if tmp[X] == "J":
                QUEUE_JIHOON.append((X, Y))
                VISIT_J[Y][X] = 1
            elif tmp[X] == "F":
                QUEUE_FIRES.append((X, Y))
                VISIT_F[Y][X] = 1
        MAZE.append(tmp)
    print(bfs())


"""
Inputs:
    - data: Source data in the form of dataframe
    - column: Name of the column to be moved
    - reference_column: Reference column with respect to which the column will be moved
    - position: Position in which the column will move wrt the reference column ('Before'(default)/'After')
Output:
    - Data in the form of dataframe with the moved column
"""
import pandas as pd
from dft.base_execution_handler import BaseExecutionHandler

class ExecutionHandler(BaseExecutionHandler):
    def execute(self, data: pd.DataFrame, column, reference_column, position='Before'):
        if position == 'Before':
            column_to_move = data.pop(column)
            loc = data.columns.get_loc(reference_column)
            data.insert(loc, column, column_to_move)
        elif position == 'After':
            loc = data.columns.get_loc(reference_column)
            if loc + 1 < len(data.columns):
                column_to_move = data.pop(column)
                data.insert(loc + 1, column, column_to_move)
            else:
                column_to_move = data.pop(column)
                data.insert(loc, column, column_to_move)
        else:
            raise ValueError('position can be either Before or After')

        return data


from util import capture_results
from base import BaseTest
from ipaplatform.paths import paths
from ipahealthcheck.core import config, constants
from ipahealthcheck.ipa.plugin import registry
from ipahealthcheck.ipa.certs import IPACertmongerExpirationCheck
from unittest.mock import Mock
from mock_certmonger import create_mock_dbus, _certmonger
from mock_certmonger import get_expected_requests, set_requests

from datetime import datetime, timedelta, timezone

class TestExpiration(BaseTest):
    patches = {
        'ipahealthcheck.ipa.certs.get_expected_requests':
        Mock(return_value=get_expected_requests()),
        'ipalib.install.certmonger._cm_dbus_object':
        Mock(side_effect=create_mock_dbus),
        'ipalib.install.certmonger._certmonger':
        Mock(return_value=_certmonger())
    }

    def test_expiration(self):
        set_requests()

        framework = object()
        registry.initialize(framework)
        f = IPACertmongerExpirationCheck(registry)

        f.config = config.Config()
        f.config.cert_expiration_days = 7
        self.results = capture_results(f)

        assert len(self.results) == 2

        result = self.results.results[0]
        assert result.result == constants.ERROR
        assert result.source == 'ipahealthcheck.ipa.certs'
        assert result.check == 'IPACertmongerExpirationCheck'
        assert result.kw.get('key') == '1234'
        assert result.kw.get('msg') == 'Request id 1234 expired on ' \
                                       '19700101001704Z'

        result = self.results.results[1]
        assert result.result == constants.SUCCESS
        assert result.source == 'ipahealthcheck.ipa.certs'
        assert result.check == 'IPACertmongerExpirationCheck'
        assert result.kw.get('key') == '5678'

    def test_expiration_warning(self):
        warning = datetime.now(timezone.utc) + timedelta(days=20)
        replaceme = {
            'nickname': '7777',
            'cert-file': paths.RA_AGENT_PEM,
            'key-file': paths.RA_AGENT_KEY,
            'ca-name': 'dogtag-ipa-ca-renew-agent',
            'not-valid-after': int(warning.timestamp()),
        }

        set_requests(remove=0, add=replaceme)

        framework = object()
        registry.initialize(framework)
        f = IPACertmongerExpirationCheck(registry)

        f.config = config.Config()
        f.config.cert_expiration_days = 30
        self.results = capture_results(f)

        assert len(self.results) == 2

        result = self.results.results[0]
        assert result.result == constants.SUCCESS
        assert result.source == 'ipahealthcheck.ipa.certs'
        assert result.check == 'IPACertmongerExpirationCheck'
        assert result.kw.get('key') == '5678'

        result = self.results.results[1]
        assert result.result == constants.WARNING
        assert result.source == 'ipahealthcheck.ipa.certs'
        assert result.check == 'IPACertmongerExpirationCheck'
        assert result.kw.get('key') == '7777'
        assert 'expires in 19 days' in result.kw.get('msg')


import sqlite3
import datetime
import logging
import config

def db_connect():
	try:
		con = sqlite3.connect(config.FILE_DB)
		return con
	except sqlite3.Error as e:
		logging.critical(e)

def create_tables():
	con = db_connect()
	cur = con.cursor()

	cur.execute('''
		CREATE table if not exists referendums(
			chat_id integer,
			msg_id integer,
			title text,
			rfr_type integer,
			status integer,
			game_cost integer,
			max_players integer,
			user_id integer,
			user_name text,
			datum text,
			primary key(chat_id, msg_id))
	''')

	cur.execute('''
		CREATE table if not exists rfr_buttons(
			chat_id integer,
			msg_id integer,
			button_id integer,
			button_text text,
			primary key(chat_id, msg_id, button_id))
	''')

	cur.execute('''
		CREATE table if not exists rfr_log(
			chat_id integer,
			msg_id integer,
			button_id integer,
			user_id integer,
			user_name text,
			datum text,
			button_status integer,
			primary key(chat_id, msg_id, button_id, user_id, user_name, datum))
	''')

	cur.execute('''
		CREATE table if not exists regular_players(
			chat_id integer,
			user_id integer,
			user_name text,
			player_type integer,
			primary key(chat_id, user_id))
	''')

	cur.execute('''
		CREATE table if not exists timers(
			chat_id integer,
			msg_id integer,
			datum text,
			period integer,
			status integer,
			primary key(chat_id, msg_id))
	''')

	con.commit()
	con.close()

def exec_sql(sql, vals):
	con = db_connect()
	cur = con.cursor()

	try:
		rows = cur.executemany(sql, vals).fetchall()
		con.commit()
		con.close()
		return rows
	except sqlite3.Error as e:
		logging.warning(e)

def create_referendum_db(chat_id, msg_id, user_id, user_name, rfr_type, args):
	game_cost = args[0]
	max_players = args[1]
	title = args[2]
	buttons = args[3:]

	sql = '''
		INSERT into referendums(chat_id, msg_id, title, rfr_type, status, game_cost, max_players, user_id, user_name, datum)
			values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
	'''
	row = [(chat_id, msg_id, title, rfr_type, 1, game_cost, max_players, user_id, user_name, datetime.datetime.now())]
	exec_sql(sql, row)

	sql = '''
		INSERT into rfr_buttons(chat_id, msg_id, button_id, button_text)
			values(?, ?, ?, ?)
	'''
	rows = []
	for button_id in range(1, len(buttons) + 1):
		rows.append((chat_id, msg_id, button_id, buttons[button_id - 1]))
	exec_sql(sql, rows)

def get_referendums_by_user_id_db(chat_id, user_id, status = -1):
	referendums = []

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	if status == -1:
		sql = '''
			SELECT *
				from referendums
				where
					referendums.chat_id = {} and
					referendums.user_id = {}
		'''.format(chat_id, user_id)
	else:
		sql = '''
			SELECT *
				from referendums
				where
					referendums.chat_id = {} and
					referendums.status = {} and
					referendums.user_id = {}
		'''.format(chat_id, status, user_id)

	rows = cur.execute(sql).fetchall()
	con.close()

	for row in rows:
		referendum = {}

		referendum['msg_id'] = row['msg_id']
		referendum['title'] = row['title']
		referendum['rfr_type'] = row['rfr_type']
		referendum['status'] = row['status']
		referendum['game_cost'] = row['game_cost']
		referendum['max_players'] = row['max_players']
		referendum['user_id'] = row['user_id']
		referendum['user_name'] = row['user_name']
		referendum['datum'] = row['datum']

		referendums.append(referendum)

	return referendums

def get_referendum_db(chat_id, msg_id):
	referendum = {}

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT *
			from referendums
			where
				referendums.chat_id = {} and
				referendums.msg_id = {}
	'''.format(chat_id, msg_id)

	row = cur.execute(sql).fetchone()
	con.close()

	if row:
		referendum['title'] = row['title']
		referendum['rfr_type'] = row['rfr_type']
		referendum['status'] = row['status']
		referendum['game_cost'] = row['game_cost']
		referendum['max_players'] = row['max_players']
		referendum['user_id'] = row['user_id']

	return referendum

def update_referendum_db(chat_id, args):
	msg_id = int(args[0])

	if len(args) >= 2:
		game_cost = int(args[1])

		sql = '''
			UPDATE referendums
				set game_cost = ?
				where
					chat_id = ? and
					msg_id = ?
		'''
		row = [(game_cost, chat_id, msg_id)]
		exec_sql(sql, row)

	if len(args) >= 3:
		max_players = int(args[2])

		sql = '''
			UPDATE referendums
				set max_players = ?
				where
					chat_id = ? and
					msg_id = ?
		'''
		row = [(max_players, chat_id, msg_id)]
		exec_sql(sql, row)

	if len(args) >= 4:
		title = args[3]

		sql = '''
			UPDATE referendums
				set title = ?
				where
					chat_id = ? and
					msg_id = ?
		'''
		row = [(title, chat_id, msg_id)]
		exec_sql(sql, row)

	if len(args) >= 5:
		buttons = args[4:]
		button_id = 1

		for button in buttons:
			sql = '''
				UPDATE rfr_buttons
					set button_text = ?
					where
						chat_id = ? and
						msg_id = ? and
						button_id = ?
			'''
			row = [(button, chat_id, msg_id, button_id)]
			exec_sql(sql, row)

			button_id += 1

def set_referendum_status_db(chat_id, msg_id, status):
	sql = '''
		UPDATE referendums
			SET status = ?
			WHERE
				chat_id = ? and
				msg_id = ?
	'''
	row = [(status, chat_id, msg_id)]
	exec_sql(sql, row)

def get_last_button_add(chat_id, msg_id, user_id, button_id):
	last_button_add = {}

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT user_id, user_name, button_status, max(datum) as datum
			from rfr_log
			where
				chat_id = {} and
				msg_id = {} and
				button_id = {} and
				user_id = {} and
				button_status = 1
			group by user_id, user_name

	'''.format(chat_id, msg_id, config.BUTTON_ID_ADD, user_id)

	row = cur.execute(sql).fetchone()
	con.close()

	if row:
		last_button_add['user_id'] = row['user_id']
		last_button_add['user_name'] = row['user_name']
		last_button_add['button_status'] = row['button_status']
		last_button_add['datum'] = row['datum']

	return last_button_add

def set_vote_db(chat_id, msg_id, user_id, user_name, button_id):
	action = ''
	button_old = 0
	datum = datetime.datetime.now()
	referendum = get_referendum_db(chat_id, msg_id)
	votes = get_votes_db(chat_id, msg_id)

	if referendum['rfr_type'] in (config.RFR_GAME, config.RFR_GAME2):
		if button_id == config.BUTTON_ID_ADD:
			sql = '''
				INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
					values(?, ?, ?, ?, ?, ?, ?)
			'''
			row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 1)]
			exec_sql(sql, row)

			action = 'added friend'
		elif button_id == config.BUTTON_ID_DEL:
			friends = get_friends_db(chat_id, msg_id)

			if user_id in friends:
				sql = '''
					INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
						values(?, ?, ?, ?, ?, ?, ?)
				'''
				row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 0)]
				exec_sql(sql, row)

				last_button_add = get_last_button_add(chat_id, msg_id, user_id, config.BUTTON_ID_ADD)
				if last_button_add:
					sql = '''
						UPDATE rfr_log
							SET button_status = ?
							WHERE
								chat_id = ? and
								msg_id = ? and
								button_id = ? and
								user_id = ? and
								user_name = ? and
								datum = ?
					'''
					row = [(0, chat_id, msg_id, config.BUTTON_ID_ADD, user_id, user_name, last_button_add['datum'])]
					exec_sql(sql, row)

				action = 'removed friend'
			else:
				action = 'tried to remove 0 friends'
		elif button_id == config.BUTTON_ID_OPT:
			sql = '''
				INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
					values(?, ?, ?, ?, ?, ?, ?)
			'''

			for usr in votes[button_id]['players']:
				if usr['user_id'] == user_id:
					row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 0)]
					action = 'unvoted'
				else:
					action = ''
			if action == '':
				row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 1)]
				action = 'voted'

			exec_sql(sql, row)

		else:
			for btn_id in (config.BUTTON_ID_YES, 2, 3):
				for usr in votes[btn_id]['players'] + votes[btn_id]['queue']:
					if usr['user_id'] == user_id:
						sql = '''
							INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
								values(?, ?, ?, ?, ?, ?, ?)
						'''
						row = [(chat_id, msg_id, btn_id, user_id, user_name, datum, 0)]
						exec_sql(sql, row)

						button_old = btn_id
						action = 'unvoted'

			if button_old != button_id:
				sql = '''
					INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
						values(?, ?, ?, ?, ?, ?, ?)
				'''
				row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 1)]
				exec_sql(sql, row)

				if action:
					action = 'revoted'
				else:
					action = 'voted'
	elif referendum['rfr_type'] == config.RFR_SINGLE:
		for btn_id in votes:
			for usr in votes[btn_id]['players'] + votes[btn_id]['queue']:
				if usr['user_id'] == user_id:
					sql = '''
						INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
							values(?, ?, ?, ?, ?, ?, ?)
					'''
					row = [(chat_id, msg_id, btn_id, user_id, user_name, datum, 0)]
					exec_sql(sql, row)

					button_old = btn_id
					action = 'unvoted'

		if button_old != button_id:
			sql = '''
				INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
					values(?, ?, ?, ?, ?, ?, ?)
			'''
			row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 1)]
			exec_sql(sql, row)

			if action:
				action = 'revoted'
			else:
				action = 'voted'
	elif referendum['rfr_type'] == config.RFR_MULTI:
		for btn_id in votes:
			for usr in votes[btn_id]['players'] + votes[btn_id]['queue']:
				if usr['user_id'] == user_id and btn_id == button_id:
					sql = '''
						INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
							values(?, ?, ?, ?, ?, ?, ?)
					'''
					row = [(chat_id, msg_id, btn_id, user_id, user_name, datum, 0)]
					exec_sql(sql, row)

					button_old = btn_id
					action = 'unvoted'

		if action == '':
			sql = '''
				INSERT into rfr_log(chat_id, msg_id, button_id, user_id, user_name, datum, button_status)
					values(?, ?, ?, ?, ?, ?, ?)
			'''
			row = [(chat_id, msg_id, button_id, user_id, user_name, datum, 1)]
			exec_sql(sql, row)

			action = 'voted'

	return action

def get_votes_db(chat_id, msg_id):
	referendum_log = []

	referendum = get_referendum_db(chat_id, msg_id)
	buttons = get_buttons_db(chat_id, msg_id)

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT rfr_buttons.button_id, user_id, user_name, max(datum) as datum, button_status
			from rfr_buttons
			left outer join rfr_log
			on
				rfr_buttons.chat_id = rfr_log.chat_id and
				rfr_buttons.msg_id = rfr_log.msg_id and
				rfr_buttons.button_id = rfr_log.button_id
			where
				rfr_buttons.chat_id = {} and
				rfr_buttons.msg_id = {}
			group by
				rfr_buttons.button_id, user_id, user_name
			order by
				rfr_buttons.button_id, datum
	'''.format(chat_id, msg_id)
	rows = cur.execute(sql).fetchall()
	con.close()

	for row in rows:
		if(row['button_status']):
			referendum_log.append({'button_id': row['button_id'], 'user_id': row['user_id'], 'user_name': row['user_name'], 'datum': row['datum']})

	referendum_log = sorted(referendum_log, key = lambda x: x['datum'])
	players_queue = get_players_queue(referendum_log, buttons, referendum['rfr_type'], referendum['max_players'])

	return players_queue

def get_buttons_db(chat_id, msg_id):
	buttons = {}

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT button_id, button_text
			from rfr_buttons
			where
				chat_id = {} and
				msg_id = {}
	'''.format(chat_id, msg_id)
	rows = cur.execute(sql).fetchall()
	con.close()

	for row in rows:
		buttons[row['button_id']] = {'button_text': row['button_text']}

	return buttons

def drop_tables():
	con = db_connect()
	cur = con.cursor()

	cur.execute('drop table if exists referendums')
	cur.execute('drop table if exists rfr_buttons')
	cur.execute('drop table if exists rfr_log')
	cur.execute('drop table if exists regular_players')

	con.commit()
	con.close()

def extend_table():
	con = db_connect()
	cur = con.cursor()

	cur.execute('drop table if exists _referendums_old')
	cur.execute('ALTER table referendums rename to _referendums_old')
	cur.execute('''
		CREATE table referendums(
			chat_id integer,
			msg_id integer,
			title text,
			rfr_type integer default 0,
			status integer,
			game_cost integer default 0,
			max_players integer,
			user_id integer,
			user_name text,
			datum text,
			primary key(chat_id, msg_id))''')

	cur.execute('''
		INSERT into referendums(
					chat_id, msg_id, title, status, game_cost, max_players, user_id, user_name, datum)
			select chat_id, msg_id, title, status, game_cost, max_players, user_id, user_name, datum
			from _referendums_old
	''')
	cur.execute('drop table _referendums_old')

	con.commit()
	con.close()

def drop_table_column():
	con = db_connect()
	cur = con.cursor()

	cur.execute('drop table if exists _rfr_buttons_old')
	cur.execute('ALTER table rfr_buttons rename to _rfr_buttons_old')
	cur.execute('''
		CREATE table rfr_buttons(
			chat_id integer,
			msg_id integer,
			button_id integer,
			button_text text,
			primary key(chat_id, msg_id, button_id))
	''')

	cur.execute('''
		INSERT into rfr_buttons(
					chat_id, msg_id, button_id, button_text)
			select chat_id, msg_id, button_id, button_text
			from _rfr_buttons_old''')
	cur.execute('drop table _rfr_buttons_old')

	con.commit()
	con.close()

def select_all(tab):
	con = db_connect()
	cur = con.cursor()

	rows = []
	for row in cur.execute(f'select * from {tab}'):
		rows.append(row)
	con.close()

	return rows

def print_tabs(*args):
	if(args):
		for arg in args:
			print(arg)
			rows = select_all(arg)
			for row in rows:
				print(row)
	else:
		print('referendums')
		rows = select_all('referendums')
		for row in rows:
			print(row)

		print('rfr_buttons')
		rows = select_all('rfr_buttons')
		for row in rows:
			print(row)

		print('rfr_log')
		rows = select_all('rfr_log')
		for row in rows:
			print(row)

		print('regular_players')
		rows = select_all('regular_players')
		for row in rows:
			print(row)

def is_free_slots(players_queue, buttons, max_num):
	busy_slots = 0

	for button in buttons:
		if button == 1:
			busy_slots += len(players_queue[button]['players'])

	if busy_slots + 1 <= max_num:
		return True
	else:
		return False

def get_players_queue(referendum_log, buttons, rfr_type, max_num):
	players_queue = {}

	for button in buttons:
		players_queue[button] = {'players': [], 'queue': []}

	for r in referendum_log:
		button_id = r['button_id']

		if rfr_type in (config.RFR_GAME, config.RFR_GAME2) and button_id == 1 and max_num > 0:
			if is_free_slots(players_queue, buttons, max_num):
				players_queue[r['button_id']]['players'].append(r)
			else:
				players_queue[r['button_id']]['queue'].append(r)
		elif rfr_type in (config.RFR_GAME, config.RFR_GAME2) and button_id in (4, 5):
			pass
		else:
			players_queue[r['button_id']]['players'].append(r)

	return players_queue

def check_user_id(chat_id, msg_id, user_id):
	referendum = get_referendum_db(chat_id, msg_id)

	if user_id == referendum['user_id']:
		return True
	else:
		return False

def check_msg_id(chat_id, msg_id):
	referendum = get_referendum_db(chat_id, msg_id)

	if referendum:
		return True
	else:
		return False

def get_regular_players_db(chat_id , player_type = -1):
	players = []

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	if player_type == -1:
		sql = '''
			SELECT *
				from regular_players
				where chat_id = {}
		'''.format(chat_id)
	else:
		sql = '''
			SELECT *
				from regular_players
				where chat_id = {} and
					player_type = {}
		'''.format(chat_id, player_type)

	rows = cur.execute(sql).fetchall()
	con.close()

	for row in rows:
		players.append({'chat_id': row['chat_id'], 'user_id': row['user_id'], 'user_name': row['user_name'], 'player_type': row['player_type']})

	return players

def is_regular_players_used_db(chat_id):
	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT *
			from regular_players
			where
				chat_id = {} and
				player_type = 1
	'''.format(chat_id)

	row = cur.execute(sql).fetchone()

	if row:
		return True
	else:
		return False

def get_regular_player_db(chat_id, user_id):
	player = {}

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT *
			from regular_players
			where
				chat_id = {} and
				user_id = {}
	'''.format(chat_id, user_id)

	row = cur.execute(sql).fetchone()

	if row:
		player['chat_id'] = row['chat_id']
		player['user_id'] = row['user_id']
		player['user_name'] = row['user_name']
		player['player_type'] = row['player_type']

	return player

def set_regular_player_db(chat_id, user_id, user_name, player_type):
	sql = '''
		INSERT or replace
			into regular_players(chat_id, user_id, user_name, player_type)
			values(?, ?, ?, ?)
	'''
	row = [(chat_id, user_id, user_name, player_type)]

	exec_sql(sql, row)

def del_regular_player_db(chat_id, user_id):
	sql = '''
		DELETE
			from regular_players
			where
				chat_id = {} and
				user_id = {}
	'''.format(chat_id, user_id)

	con = db_connect()
	cur = con.cursor()
	cur.execute(sql)
	con.commit()
	con.close()

def is_regular_player(chat_id, user_id):
	player = get_regular_player_db(chat_id, user_id)

	if player:
		return player['player_type']
	else:
		return 0

def get_friends_db(chat_id, msg_id):
	friends = {}

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT user_id, user_name, sum(button_status) as friends, min(datum) as datum
			from rfr_log
			where
				chat_id = {} and
				msg_id = {} and
				button_id = 4 and
				button_status = 1
			group by user_id, user_name
			order by datum
	'''.format(chat_id, msg_id)
	rows = cur.execute(sql).fetchall()
	con.close()

	for row in rows:
		if row['friends'] > 0:
			friends[row['user_id']] = {'user_name': row['user_name'], 'friends': row['friends'], 'datum': row['datum']}

	return friends

def add_button(chat_id, msg_id, button_text):
	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT max(button_id) as button_id
			from rfr_buttons
			where
				chat_id = {} and
				msg_id = {}
	'''.format(chat_id, msg_id)

	row = cur.execute(sql).fetchone()
	con.close()

	if row:
		button_id = row['button_id'] + 1

		sql = '''
			INSERT into rfr_buttons(chat_id, msg_id, button_id, button_text)
				values(?, ?, ?, ?)
		'''
		row = [(chat_id, msg_id, button_id, button_text)]
		exec_sql(sql, row)

def get_silent_members_db(chat_id, msg_id):
	chat_members = []
	active_members = []
	silent_members = []

	con = db_connect()
	con.row_factory = sqlite3.Row
	cur = con.cursor()

	sql = '''
		SELECT user_id
			from regular_players
			where chat_id = {}
	'''.format(chat_id)
	rows = cur.execute(sql).fetchall()
	for row in rows:
		chat_members.append({'user_id': row['user_id']})

	buttons = get_buttons_db(chat_id, msg_id)
	votes = get_votes_db(chat_id, msg_id)

	for button_id in buttons:
		for usr in votes[button_id]['players']:
			active_members.append({'user_id': usr['user_id']})
		for usr in votes[button_id]['queue']:
			active_members.append({'user_id': usr['user_id']})

	silent_members = [p for p in chat_members if p not in active_members]

	return silent_members


from conans import ConanFile, Meson, tools
import os
import shutil

class LibnameConan(ConanFile):
    name = "libdrm"
    description = "User space library for accessing the Direct Rendering Manager, on operating systems that support the ioctl interface"
    topics = ("conan", "libdrm", "graphics")
    url = "https://github.com/bincrafters/conan-libdrm"
    homepage = "https://gitlab.freedesktop.org/mesa/drm"
    license = "MIT"

    settings = "os", "arch", "compiler", "build_type"
    options = {
        "shared": [True, False],
        "fPIC": [True, False],
        "libkms": [True, False],
        "intel": [True, False],
        "radeon": [True, False],
        "amdgpu": [True, False],
        "nouveau": [True, False],
        "vmwgfx": [True, False],
        "omap": [True, False],
        "exynos": [True, False],
        "freedreno": [True, False],
        "tegra": [True, False],
        "vc4": [True, False],
        "etnaviv": [True, False],
        "valgrind": [True, False],
        "freedreno-kgsl": [True, False],
        "udev": [True, False]
    }
    default_options = {
        "shared": True,
        "fPIC": True,
        "libkms": True,
        "intel": True,
        "radeon": True,
        "amdgpu": True,
        "nouveau": True,
        "vmwgfx": True,
        "omap": False,
        "exynos": False,
        "freedreno": True,
        "tegra": False,
        "vc4": True,
        "etnaviv": False,
        "valgrind": False,
        "freedreno-kgsl": False,
        "udev": False
    }

    _source_subfolder = "source_subfolder"
    _build_subfolder = "build_subfolder"

    def build_requirements(self):
        if not tools.which("meson"):
            self.build_requires("meson/0.59.3")
        if not tools.which('pkg-config'):
            self.build_requires('pkgconf/1.7.4')

    def requirements(self):
        if self.options.intel:
            self.requires("libpciaccess/0.16@bincrafters/stable")

    def config_options(self):
        if self.settings.os == 'Windows':
            del self.options.fPIC

    def configure(self):
        del self.settings.compiler.libcxx
        del self.settings.compiler.cppstd

    def source(self):
        tools.get(**self.conan_data["sources"][self.version])
        extracted_dir = self.name + "-" + self.version
        os.rename(extracted_dir, self._source_subfolder)

    def _configure_meson(self):
        meson = Meson(self)

        defs={
            "cairo-tests" : "false",
            "install-test-programs": "false"
        }
        for o in ["libkms", "intel", "radeon", "amdgpu","nouveau", "vmwgfx", "omap", "exynos",
                  "freedreno", "tegra", "vc4", "etnaviv", "valgrind", "freedreno-kgsl", "udev"]:
            defs[o] = "true" if getattr(self.options, o) else "false"

        meson.configure(
            defs = defs,
            source_folder=self._source_subfolder,
            build_folder=self._build_subfolder)
        return meson

    def build(self):
        def _get_pc_files(package):
            if package in self.deps_cpp_info.deps:
                lib_path = self.deps_cpp_info[package].rootpath
                for dirpath, _, filenames in os.walk(lib_path):
                    for filename in filenames:
                        if filename.endswith('.pc'):
                            shutil.copyfile(os.path.join(dirpath, filename), filename)
                            tools.replace_prefix_in_pc_file(filename, lib_path)
                for dep in self.deps_cpp_info[package].public_deps:
                    _get_pc_files(dep)
        _get_pc_files('libpciaccess')
        meson = self._configure_meson()
        meson.build()

    def package(self):
        meson = self._configure_meson()
        meson.install()

    def package_info(self):
        self.cpp_info.includedirs.append(os.path.join('include', 'libdrm'))
        self.cpp_info.includedirs.append(os.path.join('include', 'libkms'))
        self.cpp_info.libs = tools.collect_libs(self)


from docx import Document
from docx.shared import Mm
from docx.text.paragraph import Paragraph
from docx.oxml.xmlchemy import OxmlElement
from pandas import DataFrame
import logging
import re

class DocxTemplate:
    """
    The DocxTemplate class makes use of python-docx to modify a word document.
    """

    def __init__(self, filename: str):
        '''constructs the object with the word document.
        Parameters
        ----------
        filename: file name that points on a valide >2007 MS Word document'''
        self.doc = Document(filename)

    def replaceKeywordByString(self, keyword: str, replacement: str):
        '''replace a keyword by the given replacement string, whatever its position is in the document
        Parameters
        ----------
        keyword: keyword to search for
        replacement: replacement string
        '''
        paragraphs = self._find_paragraphs(keyword)
        self._replaceKeyword(paragraphs, keyword, replacement)

    def replaceKeywordByImages(self, keyword, images, width=None, height=None):
        '''replace a keyword in a paragraph by the given images
        Parameters
        ----------
        keyword: keyword to search for
        images: list of images
        width: expected width of images in the document
        height: expected height of images in the document
        '''
        paragraphs = self._find_paragraphs(keyword)
        self._replaceKeyword(paragraphs, keyword, '')
        first_image = images[0]
        other_images = images[1:] if len(images) >1 else []
        for paragraph in paragraphs:
            run = paragraph.add_run()
            self._add_image_in_paragraph(first_image, width, height, run)
            for image in other_images:
                new_paragraph = self._insert_paragraph_after(paragraph, ' ')
                new_run = new_paragraph.add_run()
                self._add_image_in_paragraph(image, width, height, new_run)

    def _add_image_in_paragraph(self, image, width, height, run):
        if width and height:
            run.add_picture(image, width=Mm(
                width), height=Mm(height))
        elif width:
            run.add_picture(image, width=Mm(width))
        elif height:
            run.add_picture(image, height=Mm(height))
        else:
            run.add_picture(image)

    def _insert_paragraph_after(self, paragraph, text=None, style=None):
        """Insert a new paragraph after the given paragraph."""
        new_p = OxmlElement("w:p")
        paragraph._p.addnext(new_p)
        new_para = Paragraph(new_p, paragraph._parent)
        if text:
            new_para.add_run(text)
        if style is not None:
            new_para.style = style
        return new_para

    def findTableByKeyword(self, keyword: str):
        '''find a table in a document by finding a keyword in its cells
        Parameters
        ----------
        keyword: keyword to be found in the table cells
        return the first found table
        '''
        for table in self.doc.tables:
            for row in table.rows:
                for cell in row.cells:
                    if keyword in cell.text.strip():
                        return table

    def findTableByHeader(self, match: list):
        '''find a table in a document by looking at its first row (header) and by checking if it complies with the colum description
        Parameters
        ----------
        match: colum description = a list describing each column with a regex that should match the column title
        return the first table that complies with the description
        '''

        for table in self.doc.tables:
            found = True
            header = table.rows[0].cells
            if len(match) != len(header):
                continue
            for i in range(0, len(match)):
                if not re.match(match[i], header[i].text.strip(), re.IGNORECASE):
                    found = False
                    break
            if found:
                logging.info('expected table found')
                return table
        logging.info("no table found with the given description")
        return None

    def dropTableContent(self, table):
        '''drop table content
        Parameters
        ----------
        table: python-docx table to empty'''
        for row in table.rows:
            table._element.remove(row._element)

    def dropTableExceptHeader(self, table):
        '''drop table content except its first row which is called the header
        and return header as a list
        Parameters
        ----------
        table: python-docx table to empty'''
        for row in table.rows[1:]:
            table._element.remove(row._element)

        return [cell.text for cell in table.rows[0].cells]

    def addTableHeader(self, table, header: list):
        '''add a header to the table. This table must be empty.
        Parameters
        ----------
        table: empty python-docx table
        header: list of header names
        '''
        if not table.rows:
            table.add_row().cells
        headercells = table.rows[0].cells
        for colindex, cell in enumerate(headercells):
            cell.text = str(header[colindex])

    def fillTableWithData(self, table, data: DataFrame, from_row: int = 0):
        '''fill the given table with the associated data
        Parameters
        ----------
        table: python-docx table to fill in
        data: pandas Dataframe with the same column number et names than the table to fill in
        from_row: start filling at this given row index (first row is from_row=0)
        '''
        table.autofit = True
        # table.style = 'Table Grid'

        count = from_row
        for _, row in data.iterrows():
            if count <= len(table.rows)-1:
                row_cells = table.rows[count].cells
            else:
                row_cells = table.add_row().cells
            count += 1
            for colindex, cell in enumerate(row_cells):
                if colindex < len(row):
                    cell.text = str(row[colindex])

    def save(self, filename: str):
        '''save the document
        Parameters
        ----------
        filename: file name of the destination file
        '''
        self.doc.save(filename)

    def _find_paragraphs(self, keyword):
        paragraphs = self._findKeywordInSections(keyword)
        paragraphs += self._findKeywordInParagraphs(
            keyword, self.doc.paragraphs)
        paragraphs += self._findKeywordInTables(keyword, self.doc.tables)
        return paragraphs

    def _findKeywordInSections(self, keyword):
        paragraphs = []
        for section in self.doc.sections:
            elements = [section.header, section.footer, section.even_page_header,
                        section.even_page_footer, section.first_page_footer, section.first_page_header]
            for element in elements:
                paragraphs += (self._findKeywordInParagraphs(
                    keyword, element.paragraphs))
                paragraphs += self._findKeywordInTables(
                    keyword, element.tables)
        return paragraphs

    def _findKeywordInParagraphs(self, keyword, paragraphs):
        found = []
        for paragraph in paragraphs:
            if keyword in paragraph.text.strip():
                found.append(paragraph)
        return found

    def _findKeywordInTables(self, keyword, tables):
        paragraphs = []
        for table in tables:
            for row in table.rows:
                for cell in row.cells:
                    for paragraph in cell.paragraphs:
                        if keyword in paragraph.text.strip():
                            paragraphs.append(paragraph)
        return paragraphs

    def _replaceKeyword(self, paragraphs, keyword, replacement):
        for paragraph in paragraphs:
            paragraph.text = paragraph.text.replace(keyword, replacement)


import json
import copy
import sys
sys.path.append('/Library/Python/2.7/site-packages')
import requests
import geopy
from geopy.distance import vincenty

urlbiz = 'http://fyndo.herokuapp.com/api/selectBizInfos'
bizresp = requests.get(urlbiz)
biz = bizresp.json()

bdic = {}

for y in range(len(biz)):
    bdic[biz[y]['bizId']] = biz[y]['bizName']

urlfeed = 'http://fyndox.herokuapp.com/api/selectFeeds'
feedresp = requests.get(urlfeed)
feedsmain = feedresp.json()

urlupdate = 'http://fyndox.herokuapp.com/api/updateFeed'

def feedsupdate():
    x = input('Enter starting feeds id: ')
    y = input('Enter ending feed id: ')
    notupdatedfeeds = []
    feeds = []
    for i in range(len(feedsmain)):
        if int(feedsmain[i]['feedId']) >= int(x) and int(feedsmain[i]['feedId']) <= int(y):
            feeds.append(feedsmain[i])

    for i in range(len(feeds)):
        d = {}
        t=0
        results = {}

        if feeds[i]['shopName'] != "":

            for j in range(len(biz)):
                feedshop = []
                bizshop = []
                fscore = 0.0000
                bscore = 0.0000
                fdltlg = (feeds[i]['gpsLatitude'],feeds[i]['gpsLongitude'])
                bzltlg = (biz[j]['gpsLatitude'],biz[j]['gpsLongitude'])

                if feeds[i]['shopName'] is None:
                    feedshop = []
                else:
                    feedshop = feeds[i]['shopName'].lower().split(" ")

                if biz[j]['bizName'] is None:
                    bizshop = []
                else:
                    bizshop = biz[j]['bizName'].lower().split(" ")

                try:
                    feedshop.remove('')
                    feedshop.remove(' ')
                    bizshop.remove('')
                    bizshop.remove(' ')

                except:
                    mmmm = 0

                for k in range(len(feedshop)):
                    if feedshop[k] in bizshop:
                        fscore = fscore + 1

                for p in range(len(bizshop)):
                    if bizshop[p] in feedshop:
                        bscore = bscore + 1

                if len(feedshop) == 0:
                    fscore = 0.0000
                else:
                    fscore = fscore/int(len(feedshop))

                if len(bizshop) == 0:
                    bscore = 0.0000
                else:
                    bscore= bscore/int(len(bizshop))

                if fscore > 0.5 or bscore > 0.5 and int(vincenty(fdltlg,bzltlg).meters)<=25:
                    results[biz[j]['bizId']] = fscore + bscore

            if int(len(results)) >= 1:
                kh = sorted(results, key = results.__getitem__, reverse = True)
                print(feedshop)
                print(bdic[kh[0]])
                print('The biz is - ' + str(kh[0]) + ' total score is - ' + str(results[kh[0]]))
                d['feedId'] = feeds[i]['feedId']
                d['bizId'] = kh[0]
                d['userCatLevel1'] = feeds[i]['userCatLevel1']
                d['userCatLevel2'] = feeds[i]['userCatLevel2']
                d['title'] = feeds[i]['title']
                d['textContent'] = feeds[i]['textContent']
                d['sourceDevice'] = feeds[i]['sourceDevice']

                fdup = requests.post(urlupdate, data = json.dumps(d), headers = {'Content-type': 'application/json'})
                if fdup.status_code == 200:
                    print('Successfully updated - ' + str(feeds[i]['feedId']))
                    t=1
                else:
                    print(' Update unsuccessful - ' + str(feeds[i]['feedId']))
                    notupdatedfeeds.append(feeds[i])
        else:
            notupdatedfeeds.append(feeds[i])

        if t == 0:
            notupdatedfeeds.append(feeds[i])

    if int(len(notupdatedfeeds)) >= 1:
        print('Feeds not updated are - \n')
        for i in range(len(notupdatedfeeds)):
            print(str(notupdatedfeeds[i]['feedId']))


class Solution:
    def rowAndMaximumOnes(self, mat: List[List[int]]) -> List[int]:

        maxRow = 0
        maxCount = 0

        for i in range(len(mat)):
            currCount = 0
            for j in range(len(mat[0])):
                if mat[i][j] == 1:
                    currCount +=1
                if currCount > maxCount:
                    maxRow = i
                maxCount = max(maxCount,currCount)

        return [maxRow,maxCount]


#  create file, if it doesnt't exist and write text into it
#  w+  read and write (overwrites existinf file or create a new file)
#  w   only write
#  r   only read
#  a   adding more lines to the end of file
f = open("test.txt","w+")
f.write("Hello this is a text file\n")
f.write("this is a second line\n")
f.write("this is a third line")
#  returns everything from a file as a big string
f.close()
f = open("/Users/akozyreva/projects/python-learning/test.txt")
print(f.read())
# in order to put cursor in the beginning of file after reading, run the following
f.seek(0)

content = f.read()
#  shows all content of file
print(content)
f.seek(0)

# return text as list, where every element is a line in file
print(f.readlines())

# with special key with, I don't need to close session with file every time
with open("test.txt") as my_new_file:
    content = my_new_file.read()
    print(content)

# example of append mode - when we add text in the end of file
with open("test.txt", "a") as my_new_file:
    my_new_file.write('\nfour line')

with open("test.txt", "r") as my_new_file:
    content = my_new_file.read()
    print(content)


import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from generic_tasks import answer

question = "Where do I work?"
context = "My name is Sylvain and I work at Hugging Face in Brooklyn"

answer, confidence = answer(question, context)
percentage = round(confidence * 100, 2)

print(f"Question: {question}")
print(f"Answer: {answer} (Confidence: {percentage}%)")


import os
import sys

# take a look at bufferreader in fd-io-demos repository
# check out write file as well and the while loop. Index slicing till we get all the buffer
# do this ^

def mytar(file_names, target_file):
    # open the tar_file for storing
    tar_fd = os.open(target_file,  os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
    # looking through all files provided
    for file_name in file_names:
        # setting the file descriptor equal to the # current file
        fd = os.open(file_name, os.O_RDONLY)
        # getting file information
        file_info = os.stat(file_name)
        # obtaiing file size
        file_size = file_info.st_size
        # reading the file descriptor and size
        file_content = os.read(fd, file_size)
        # write file contents to tar descriptor
        os.write(tar_fd, file_content)
        # close current file descriptor
        os.close(fd)
    # close tar descriptor
    os.close(tar_fd)
    sys.stdout.write("success\n")

def extract_tar(target_file):
    # traverse the tar files
    tar_name = target_file
    # open the tar file
    tar_fd = os.open(tar_name, os.O_RDONLY)
    file_info = os.stat(tar_name)
    file_size = file_info.st_size
    # read the file content
    file_content = os.read(tar_fd, file_size).decode()
    # print out the file contents
    os.close(tar_fd)
    sys.stdout.write(file_content)

if __name__ == '__main__':
    mode = sys.argv[1]
    target_file = sys.argv[-1]
    if mode == 'c':
        file_names = sys.argv[2:-1]
        mytar(file_names, target_file)
    elif mode == 'x':
        extract_tar(target_file)
    else:
        sys.stdout.write("Usage: mytar.py c|x <file1> <file2> ... <fileN>")
        sys.exit(1)


import os
from discord.ext import commands
from constants import PREFIX, TOKEN, OWNER_IDS

class Bot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix=commands.when_mentioned_or(PREFIX))
        self.token = TOKEN
        self.owner_ids = OWNER_IDS
        for file in os.listdir('cogs'):
            if file.endswith('.py'):
                try:
                    print(f"Loading {file}")
                    self.load_extension(f'cogs.{file[:-3]}')
                except Exception as e:
                    print(f"Failed to load extension {file}\n{type(e).__name__}: {e}")

    def run(self):
        super().run(self.token, reconnect=True)

    async def on_ready(self):
        print(f"{self.user.name} is now online!")

if __name__ == '__main__':
    Bot().run()


from z3 import *

Jug, (Big, Small) = EnumSort(
    'Jug', ['Big', 'Small'])
Act, (FillBig, FillSmall, EmptyBig, EmptySmall, BigToSmall, SmallToBig) = EnumSort(
    'Act', ['FillBig', 'FillSmall', 'EmptyBig', 'EmptySmall', 'BigToSmall', 'SmallToBig'])

#m = 10
for n in range(5, 10):
    print("n = {}".format(n))
    # create variables for jugs' volume and actions taken, at each time step
    big = []
    small = []
    actions = []
    for t in range(n):
        big.append(Int('big{}'.format(t)))
        small.append(Int('small{}'.format(t)))
        actions.append(Const('act{}'.format(t), Act))

    s = Solver()

    # empty at t = 0
    s.add(big[0] == 0)
    s.add(small[0] == 0)
    s.add(actions[0] == EmptyBig)

    # 6 constraints, from 6 actions, at each step t < n
    for t in range(1, n):
        s.add(Or(
            actions[t] == BigToSmall,
            actions[t] == SmallToBig,
            actions[t] == FillBig,
            actions[t] == FillSmall,
            actions[t] == EmptyBig,
            actions[t] == EmptySmall))

        s.add(
            Or(
                And(actions[t] == FillBig,
                    big[t] == 5, small[t] == small[t-1]),

                And(actions[t] == FillSmall,
                    small[t] == 3, big[t] == big[t-1]),

                And(actions[t] == EmptyBig,
                    big[t] == 0, small[t] == small[t-1]),

                And(actions[t] == EmptySmall,
                    small[t] == 0, big[t] == big[t-1]),

                And(actions[t] == BigToSmall,
                    If(big[t-1] + small[t-1] > 3,
                       And(small[t] == 3,
                           big[t] == big[t-1] + small[t-1] - 3),
                       And(small[t] == big[t-1] + small[t-1], big[t] == 0))
                    ),

                And(actions[t] == SmallToBig,
                    If(big[t-1] + small[t-1] > 5,
                       And(big[t] == 5, small[t]
                           == big[t-1] + small[t-1] - 5),
                       And(big[t] == big[t-1] + small[t-1], small[t] == 0))
                    )))

    # can we end up with 4 litres in big jug ?
    s.add(big[t] == 4)

    if s.check() == sat:
        print("SAT")
        m = s.model()
        for i in range(n):
            print("{}: {} {}".format(m.evaluate(
                actions[i]), m.evaluate(small[i]), m.evaluate(big[i])))
        exit(0)
    else:
        print("UNSAT")


import math, struct

fsample = 44100.
fwave = 440.

f=file( "sinus.wav", "w" )

t=0
while t<10:
  v = 25000*math.sin( t * 2 * math.pi * fwave )
  s = struct.pack( "hh", v,v )
  f.write( s )
  t=t + 1/fsample

f.close()