问:
discord.py bot crashes after a few hours
it crashes with a very long error message about the token but the token isnt the problem as it worked for the past couple of hours, when it crashes i go to the console and type kill 1, it work fine after that but after a few hours it does it again. this is a bot that is written on replit.

i was wondering if there was a way to make it stay online without crashing (i am using uptimerobot already)

here is the code

```#imports#######################################################################################################################imports#
import discord
from discord.ext import commands, tasks
from discord.utils import get
from replit import db
import random
from itertools import cycle
import keep_alive
import os

#starting#####################################################################################################################starting#

status = cycle(['.help', '..help'])
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=discord.Intents.all())
client.remove_command('help')

async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))

@client.event
async def on_ready():
    client.loop.create_task(change_status())
    print("CYKLERBOT is ready, you can now leave the tab")

#member-update###########################################################################################################member-update#

@client.event
async def on_member_join(member):
    print(f'{member} has joined a server.')

@client.event
async def on_member_remove(member):
    print(f'{member} has left a server')

#economy###################################################################################################################economy#

@client.command()
async def balance(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    await ctx.send(f'{user}, your balance is ${value}')
    print(value)
    print(user)

@client.command(aliases=['create'])
@commands.has_permissions(administrator=True)
async def createwallet(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db["m" + user] = 0
    await ctx.send(f'{user}s wallet has been created')

@client.command(aliases=['add'])
@commands.has_permissions(administrator=True)
async def addmoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    db["m" + user] = value + amount
    await ctx.send(f'{amount} has been added to {user}s wallet')

@client.command(aliases=['set'])
@commands.has_permissions(administrator=True)
async def setmoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    db["m" + user] = amount
    await ctx.send(f'{user}s wallet had been set to {amount}')

@client.command(aliases=['remove'])
@commands.has_permissions(administrator=True)
async def removemoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    db[user + 'm'] = value - amount
    await ctx.send(f'{amount} has been removed from {user}s wallet')

@client.command()
@commands.has_permissions(administrator=True)
async def delete(ctx, *, user):
    await ctx.channel.purge(limit=1)
    del db[user]
    await ctx.send(f'{user}s account has been deleted')

@client.command(aliases=['wkeys'])
@commands.has_permissions(administrator=True)
async def walletkeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("m")
    await ctx.send(f'{matches}')

#inventory###################################################################################################################inventory#

@client.command(aliases=['createi'])
@commands.has_permissions(administrator=True)
async def createinventory(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db['i' + user] = []
    await ctx.send(f'{user}s inventory has been created')

@client.command(aliases=['inv'])
async def inventory(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    await ctx.send(f'{user}s inventory contains {value}')

@client.command(aliases=['give'])
@commands.has_permissions(administrator=True)
async def giveitem(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    value.append(item)
    await ctx.send(f'{item}, has been added to {user}s inventory')

@client.command(aliases=['take'])
@commands.has_permissions(administrator=True)
async def takeitem(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    value.remove(item)
    await ctx.send(f'{item}, has been removed from {user}s inventory')

@client.command(aliases=['ikeys'])
@commands.has_permissions(administrator=True)
async def inventorykeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("i")
    await ctx.send(f'{matches}')
#warnings###################################################################################################################warnings#

@client.command(aliases=['createww'])
@commands.has_permissions(administrator=True)
async def createwarnwallet(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db['ww' + user] = []
    await ctx.send(f'{user}s warn wallet has been created')

@client.command()
async def warnings(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    await ctx.send(f'{user}s warn wallet contains {value}')

@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    value.append(item)
    await ctx.send(f'{user} has been warned with {item}')

@client.command()
@commands.has_permissions(administrator=True)
async def dewarn(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    value.remove(item)
    await ctx.send(f'{user}s warning ({item}) has been removed')

@client.command(aliases=['warncount'])
@commands.has_permissions(administrator=True)
async def warningcount(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]

    await ctx.send(f'{user} has {len(value)} warnings')

@client.command(aliases=['wwkeys'])
@commands.has_permissions(administrator=True)
async def warningkeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("ww")
    await ctx.send(f'{matches}')

#polls###########################################################################################################################polls#

@client.command()
async def poll(ctx, *, message):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title=f"{message}",
                        description=f"asked by @{ctx.message.author}",
                        colour=random.choice(rcolor))
    msg = await ctx.channel.send(embed=emb)
    await msg.add_reaction('')
    await msg.add_reaction('')

@client.command()
async def mpoll(ctx, *, message):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title=f"{message}",
                        description=f"asked by @{ctx.message.author}",
                        colour=random.choice(rcolor))
    msg = await ctx.channel.send(embed=emb)
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')

#fun###############################################################################################################################fun#

@client.command()
async def ping(ctx):
    await ctx.channel.purge(limit=1)
    await ctx.send(f'Pong! {round(client.latency * 1000)}ms')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    await ctx.channel.purge(limit=1)
    responces = [
        'It is certain', 'It is decidedly so', 'Without a doubt',
        'Yes definitely', 'You may rely on it', 'As I see it, yes',
        'Most likely', 'Outlook good', 'Yes', 'Signs point to yes',
        'Reply hazy, try again', 'Ask again later', 'Better not tell you now',
        'Cannot predict now', 'Concentrate and ask again', 'Dont count on it',
        'My reply is no', 'My sources say no', 'Outlook not so good',
        'Very doubtful'
    ]
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responces)}')

@client.command()
async def coinflip(ctx):
    responces2 = [
        'heads',
        'tails',
    ]
    await ctx.send(random.choice(responces2))

@client.command()
async def roll(ctx, amount1: int):
    await ctx.channel.purge(limit=1)
    await ctx.send(f'you rolled a {random.randrange(1, amount1 + 1)}')

#admin###########################################################################################################################admin#

@client.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount: int):
    await ctx.channel.purge(limit=amount)

@client.command()
@commands.has_permissions(manage_messages=True)
async def undo(ctx):
    await ctx.channel.purge(limit=2)

@purge.error
async def purge_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify an amount of messages to delete||')
    if isinstance(error, commands.MissingPermissions):
      await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    await ctx.channel.purge(limit=1)
    await user.remove_roles("manager")
    await member.kick(reason=reason)
    await ctx.send(f'Kicked {member.mention} Reason: {reason}')

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to kick followed by the reason||')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    await ctx.channel.purge(limit=1)
    await user.remove_roles("manager")
    await member.ban(reason=reason)
    await ctx.send(f'Banned {member.mention} Reason: {reason}')

@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to ban followed by the reason||')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def unban(ctx, *, member):
    await ctx.channel.purge(limit=1)
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name,
                                               member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

@unban.error
async def unban_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to unban followed by the tag||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command(pass_context = True)
@commands.has_permissions(manage_roles=True)
async def role(ctx, user : discord.Member, *, role : discord.Role):
    await ctx.channel.purge(limit=1)
    if role in user.roles:
        await ctx.send(f'{user.mention} already had that role, {role}')
    else:
        await user.add_roles(role)
        await ctx.send(f'{role} has been added to {user.mention}')

@role.error
async def role_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the @ that you would like to role followed by the role that you would like to give||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command(pass_context = True)
@commands.has_permissions(manage_roles=True)
async def derole(ctx, user : discord.Member, *, role : discord.Role):
    await ctx.channel.purge(limit=1)
    if role in user.roles:
        await user.remove_roles(role)
        await ctx.send(f'{role} has been removed from {user.mention}')
    else:
        await ctx.send(f'{user.mention} does not have this role{role}')

@derole.error
async def derole_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the @ that you would like to derole followed by the role that you would like to remove||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

#help command#############################################################################################################help command#

rcolor = [
    discord.Colour.purple(),
    discord.Colour.orange(),
    discord.Colour.green(),
    discord.Colour.blue(),
    discord.Colour.red(),
    discord.Colour.teal(),
    discord.Colour.dark_teal(),
    discord.Colour.dark_green(),
    discord.Colour.dark_blue(),
    discord.Colour.dark_purple(),
    discord.Colour.magenta(),
    discord.Colour.dark_magenta(),
    discord.Colour.gold(),
    discord.Colour.dark_gold(),
    discord.Colour.dark_orange(),
    discord.Colour.dark_red(),
    discord.Colour.lighter_gray(),
    discord.Colour.dark_gray(),
    discord.Colour.light_gray(),
    discord.Colour.darker_gray(),
    discord.Colour.blurple(),
    discord.Colour.greyple()
]

@client.command(pass_context=True)
async def help(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.ping',
                    value='Returns Pong! + the response time',
                    inline=False)
    embed.add_field(name='.8ball [insert question here]',
                    value='returns a random yes/no type answer',
                    inline=False)
    embed.add_field(name='.coinflip',
                    value='Returns heads or tails',
                    inline=False)
    embed.add_field(
        name='.roll [insert value here]',
        value='Returns a random value from 1 to the specified number',
        inline=False)
    embed.add_field(name='.ping',
                    value='Returns Pong! + the response time',
                    inline=False)
    embed.add_field(name='.poll, [insert question here]',
                    value='outputs an embed pole with automatic reactions',
                    inline=False)
    embed.add_field(
        name='.mpoll, [inset question here]',
        value='outputs an embed pole with 7 automatic reactions',
        inline=False)

    embed.add_field(name='.balance [insert wallet user here]',
                    value='Returns the amount of money the wallet user has',
                    inline=False)
    embed.add_field(name='.inventory [insert inventory user here]',
                    value='Returns all items that the user has',
                    inline=False)
    embed.add_field(name='MOD ONLY!!! .modhelp',
                    value='hows .help with moderator commands',
                    inline=False)
    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelp(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.ban [insert @ here], [insert reason here]',
                    value='bans specified member/bot for the specified reason',
                    inline=False)
    embed.add_field(name='.unban [insert name here + tag]',
                    value='unbans specified member/bot',
                    inline=False)
    embed.add_field(name='.purge [insert value here]',
                    value='removes the specified amount of messages (-1)',
                    inline=False)
    embed.add_field(name='.undo',
                    value='removes the previous message',
                    inline=False)
    embed.add_field(name='.kick [insert @ here], [insert reason here]',
                    value='kicks specified member/bot for the specified reason',
                    inline=False)
    embed.add_field(name='.role [insert @ here], [insert role here]',
                    value='adds the specified role to the specified user',
                    inline=False)
    embed.add_field(name='.derole [insert @ here], [insert role here]',
                    value='removes the specified role from the specified user',
                    inline=False)
    embed.add_field(name='.delete [insert user here]',
                    value='deletes the users wallet/inventory',
                    inline=False)
    embed.add_field(name='.modhelpwarnings',
                    value='shows all moderator warning commands',
                    inline=False)
    embed.add_field(name='.modhelpwallet',
                    value='shows all moderator warning commands',
                    inline=False)
    embed.add_field(name='.modhelpinventory',
                    value='shows all moderator warning commands',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpwarnings(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.createwarnwallet [insert warning user here]',
                    value='creates a warning wallet for the specified user',
                    inline=False)
    embed.add_field(name='.warnings [insert warning user here]',
                    value='gives all the warnings of the specified user',
                    inline=False)
    embed.add_field(name='.warn [insert warning user here] [insert violation here]',
                    value='adds the warning to the specified users wallet',
                    inline=False)
    embed.add_field(name='.dewarn [insert warning user here] [insert violation here',
                    value='removes the specified warning from the specified user',
                    inline=False)
    embed.add_field(name='.warncount [insert warning user here]',
                    value='give the amount of warnings the specified user has',
                    inline=False)
    embed.add_field(name='.warningkeys',
                    value='gives all users that have a warning account',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpwallet(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.create [insert wallet user here]',
                    value='creates a wallet for the specified user',
                    inline=False)
    embed.add_field(name='.set [insert wallet user here], [insert amount here]',
                    value='sets the user wallet to given amount',
                    inline=False)
    embed.add_field(name='.add [insert wallet user here], [insert amount here]',
                    value='adds the amount to the users wallet',
                    inline=False)
    embed.add_field(name='.remove [insert wallet user here], [insert amount here]',
                    value='removes the amount from ths users wallet',
                    inline=False)
    embed.add_field(name='.wkeys',
                    value='shows all users which have a wallet',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpinventory(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.createi [insert inventory user here]',
                    value='creates an inventory for the specified user',
                    inline=False)
    embed.add_field(name='.give [insert inventory user here]',
                    value='gives an item to the specified user',
                    inline=False)
    embed.add_field(name='.take [insert inventory user here]',
                    value='removes an item from the specified user',
                    inline=False)
    embed.add_field(name='.ikeys',
                    value='shows all users which have an inventory',
                    inline=False)

    await ctx.send(embed=embed)

#end###############################################################################################################################end#

keep_alive.keep_alive()
client.run("TOKEN")
```

every time it crashes i type kill 1 in the console and it works. but it crashes again after a few hours.

i just hope that i can get it working 24/7 because the people on my server are getting annoyed

Body:
it crashes with a very long error message about the token but the token isnt the problem as it worked for the past couple of hours, when it crashes i go to the console and type kill 1, it work fine after that but after a few hours it does it again. this is a bot that is written on replit.

i was wondering if there was a way to make it stay online without crashing (i am using uptimerobot already)

here is the code

#imports#######################################################################################################################imports#
import discord
from discord.ext import commands, tasks
from discord.utils import get
from replit import db
import random
from itertools import cycle
import keep_alive
import os

#starting#####################################################################################################################starting#

status = cycle(['.help', '..help'])
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix='.', intents=discord.Intents.all())
client.remove_command('help')

async def change_status():
    await client.change_presence(activity=discord.Game(next(status)))

@client.event
async def on_ready():
    client.loop.create_task(change_status())
    print("CYKLERBOT is ready, you can now leave the tab")

#member-update###########################################################################################################member-update#

@client.event
async def on_member_join(member):
    print(f'{member} has joined a server.')

@client.event
async def on_member_remove(member):
    print(f'{member} has left a server')

#economy###################################################################################################################economy#

@client.command()
async def balance(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    await ctx.send(f'{user}, your balance is ${value}')
    print(value)
    print(user)

@client.command(aliases=['create'])
@commands.has_permissions(administrator=True)
async def createwallet(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db["m" + user] = 0
    await ctx.send(f'{user}s wallet has been created')

@client.command(aliases=['add'])
@commands.has_permissions(administrator=True)
async def addmoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    db["m" + user] = value + amount
    await ctx.send(f'{amount} has been added to {user}s wallet')

@client.command(aliases=['set'])
@commands.has_permissions(administrator=True)
async def setmoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    db["m" + user] = amount
    await ctx.send(f'{user}s wallet had been set to {amount}')

@client.command(aliases=['remove'])
@commands.has_permissions(administrator=True)
async def removemoney(ctx, user, *, amount: int):
    await ctx.channel.purge(limit=1)
    value = db["m" + user]
    db[user + 'm'] = value - amount
    await ctx.send(f'{amount} has been removed from {user}s wallet')

@client.command()
@commands.has_permissions(administrator=True)
async def delete(ctx, *, user):
    await ctx.channel.purge(limit=1)
    del db[user]
    await ctx.send(f'{user}s account has been deleted')

@client.command(aliases=['wkeys'])
@commands.has_permissions(administrator=True)
async def walletkeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("m")
    await ctx.send(f'{matches}')

#inventory###################################################################################################################inventory#

@client.command(aliases=['createi'])
@commands.has_permissions(administrator=True)
async def createinventory(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db['i' + user] = []
    await ctx.send(f'{user}s inventory has been created')

@client.command(aliases=['inv'])
async def inventory(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    await ctx.send(f'{user}s inventory contains {value}')

@client.command(aliases=['give'])
@commands.has_permissions(administrator=True)
async def giveitem(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    value.append(item)
    await ctx.send(f'{item}, has been added to {user}s inventory')

@client.command(aliases=['take'])
@commands.has_permissions(administrator=True)
async def takeitem(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['i' + user]
    value.remove(item)
    await ctx.send(f'{item}, has been removed from {user}s inventory')

@client.command(aliases=['ikeys'])
@commands.has_permissions(administrator=True)
async def inventorykeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("i")
    await ctx.send(f'{matches}')
#warnings###################################################################################################################warnings#

@client.command(aliases=['createww'])
@commands.has_permissions(administrator=True)
async def createwarnwallet(ctx, *, user):
    await ctx.channel.purge(limit=1)
    db['ww' + user] = []
    await ctx.send(f'{user}s warn wallet has been created')

@client.command()
async def warnings(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    await ctx.send(f'{user}s warn wallet contains {value}')

@client.command()
@commands.has_permissions(administrator=True)
async def warn(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    value.append(item)
    await ctx.send(f'{user} has been warned with {item}')

@client.command()
@commands.has_permissions(administrator=True)
async def dewarn(ctx, user, *, item):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]
    value.remove(item)
    await ctx.send(f'{user}s warning ({item}) has been removed')

@client.command(aliases=['warncount'])
@commands.has_permissions(administrator=True)
async def warningcount(ctx, *, user):
    await ctx.channel.purge(limit=1)
    value = db['ww' + user]

    await ctx.send(f'{user} has {len(value)} warnings')

@client.command(aliases=['wwkeys'])
@commands.has_permissions(administrator=True)
async def warningkeys(ctx):
    await ctx.channel.purge(limit=1)
    matches = db.prefix("ww")
    await ctx.send(f'{matches}')

#polls###########################################################################################################################polls#

@client.command()
async def poll(ctx, *, message):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title=f"{message}",
                        description=f"asked by @{ctx.message.author}",
                        colour=random.choice(rcolor))
    msg = await ctx.channel.send(embed=emb)
    await msg.add_reaction('')
    await msg.add_reaction('')

@client.command()
async def mpoll(ctx, *, message):
    await ctx.channel.purge(limit=1)
    emb = discord.Embed(title=f"{message}",
                        description=f"asked by @{ctx.message.author}",
                        colour=random.choice(rcolor))
    msg = await ctx.channel.send(embed=emb)
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')
    await msg.add_reaction('')

#fun###############################################################################################################################fun#

@client.command()
async def ping(ctx):
    await ctx.channel.purge(limit=1)
    await ctx.send(f'Pong! {round(client.latency * 1000)}ms')

@client.command(aliases=['8ball'])
async def _8ball(ctx, *, question):
    await ctx.channel.purge(limit=1)
    responces = [
        'It is certain', 'It is decidedly so', 'Without a doubt',
        'Yes definitely', 'You may rely on it', 'As I see it, yes',
        'Most likely', 'Outlook good', 'Yes', 'Signs point to yes',
        'Reply hazy, try again', 'Ask again later', 'Better not tell you now',
        'Cannot predict now', 'Concentrate and ask again', 'Dont count on it',
        'My reply is no', 'My sources say no', 'Outlook not so good',
        'Very doubtful'
    ]
    await ctx.send(f'Question: {question}\nAnswer: {random.choice(responces)}')

@client.command()
async def coinflip(ctx):
    responces2 = [
        'heads',
        'tails',
    ]
    await ctx.send(random.choice(responces2))

@client.command()
async def roll(ctx, amount1: int):
    await ctx.channel.purge(limit=1)
    await ctx.send(f'you rolled a {random.randrange(1, amount1 + 1)}')

#admin###########################################################################################################################admin#

@client.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx, amount: int):
    await ctx.channel.purge(limit=amount)

@client.command()
@commands.has_permissions(manage_messages=True)
async def undo(ctx):
    await ctx.channel.purge(limit=2)

@purge.error
async def purge_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify an amount of messages to delete||')
    if isinstance(error, commands.MissingPermissions):
      await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def kick(ctx, member: discord.Member, *, reason=None):
    await ctx.channel.purge(limit=1)
    await user.remove_roles("manager")
    await member.kick(reason=reason)
    await ctx.send(f'Kicked {member.mention} Reason: {reason}')

@kick.error
async def kick_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to kick followed by the reason||')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def ban(ctx, member: discord.Member, *, reason=None):
    await ctx.channel.purge(limit=1)
    await user.remove_roles("manager")
    await member.ban(reason=reason)
    await ctx.send(f'Banned {member.mention} Reason: {reason}')

@ban.error
async def ban_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to ban followed by the reason||')
    if isinstance(error, commands.MissingPermissions):
        await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command()
@commands.has_permissions(administrator=True)
async def unban(ctx, *, member):
    await ctx.channel.purge(limit=1)
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split('#')

    for ban_entry in banned_users:
        user = ban_entry.user

        if (user.name, user.discriminator) == (member_name,
                                               member_discriminator):
            await ctx.guild.unban(user)
            await ctx.send(f'Unbanned {user.mention}')
            return

@unban.error
async def unban_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the person to unban followed by the tag||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command(pass_context = True)
@commands.has_permissions(manage_roles=True)
async def role(ctx, user : discord.Member, *, role : discord.Role):
    await ctx.channel.purge(limit=1)
    if role in user.roles:
        await ctx.send(f'{user.mention} already had that role, {role}')
    else:
        await user.add_roles(role)
        await ctx.send(f'{role} has been added to {user.mention}')

@role.error
async def role_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the @ that you would like to role followed by the role that you would like to give||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

@client.command(pass_context = True)
@commands.has_permissions(manage_roles=True)
async def derole(ctx, user : discord.Member, *, role : discord.Role):
    await ctx.channel.purge(limit=1)
    if role in user.roles:
        await user.remove_roles(role)
        await ctx.send(f'{role} has been removed from {user.mention}')
    else:
        await ctx.send(f'{user.mention} does not have this role{role}')

@derole.error
async def derole_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send('ERROR MSG: ||please specify the @ that you would like to derole followed by the role that you would like to remove||')
    if isinstance(error, commands.MissingPermissions):
            await ctx.send("ERROR MSG: ||You do not have the permission to use that command!||")

#help command#############################################################################################################help command#

rcolor = [
    discord.Colour.purple(),
    discord.Colour.orange(),
    discord.Colour.green(),
    discord.Colour.blue(),
    discord.Colour.red(),
    discord.Colour.teal(),
    discord.Colour.dark_teal(),
    discord.Colour.dark_green(),
    discord.Colour.dark_blue(),
    discord.Colour.dark_purple(),
    discord.Colour.magenta(),
    discord.Colour.dark_magenta(),
    discord.Colour.gold(),
    discord.Colour.dark_gold(),
    discord.Colour.dark_orange(),
    discord.Colour.dark_red(),
    discord.Colour.lighter_gray(),
    discord.Colour.dark_gray(),
    discord.Colour.light_gray(),
    discord.Colour.darker_gray(),
    discord.Colour.blurple(),
    discord.Colour.greyple()
]

@client.command(pass_context=True)
async def help(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.ping',
                    value='Returns Pong! + the response time',
                    inline=False)
    embed.add_field(name='.8ball [insert question here]',
                    value='returns a random yes/no type answer',
                    inline=False)
    embed.add_field(name='.coinflip',
                    value='Returns heads or tails',
                    inline=False)
    embed.add_field(
        name='.roll [insert value here]',
        value='Returns a random value from 1 to the specified number',
        inline=False)
    embed.add_field(name='.ping',
                    value='Returns Pong! + the response time',
                    inline=False)
    embed.add_field(name='.poll, [insert question here]',
                    value='outputs an embed pole with automatic reactions',
                    inline=False)
    embed.add_field(
        name='.mpoll, [inset question here]',
        value='outputs an embed pole with 7 automatic reactions',
        inline=False)

    embed.add_field(name='.balance [insert wallet user here]',
                    value='Returns the amount of money the wallet user has',
                    inline=False)
    embed.add_field(name='.inventory [insert inventory user here]',
                    value='Returns all items that the user has',
                    inline=False)
    embed.add_field(name='MOD ONLY!!! .modhelp',
                    value='hows .help with moderator commands',
                    inline=False)
    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelp(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.ban [insert @ here], [insert reason here]',
                    value='bans specified member/bot for the specified reason',
                    inline=False)
    embed.add_field(name='.unban [insert name here + tag]',
                    value='unbans specified member/bot',
                    inline=False)
    embed.add_field(name='.purge [insert value here]',
                    value='removes the specified amount of messages (-1)',
                    inline=False)
    embed.add_field(name='.undo',
                    value='removes the previous message',
                    inline=False)
    embed.add_field(name='.kick [insert @ here], [insert reason here]',
                    value='kicks specified member/bot for the specified reason',
                    inline=False)
    embed.add_field(name='.role [insert @ here], [insert role here]',
                    value='adds the specified role to the specified user',
                    inline=False)
    embed.add_field(name='.derole [insert @ here], [insert role here]',
                    value='removes the specified role from the specified user',
                    inline=False)
    embed.add_field(name='.delete [insert user here]',
                    value='deletes the users wallet/inventory',
                    inline=False)
    embed.add_field(name='.modhelpwarnings',
                    value='shows all moderator warning commands',
                    inline=False)
    embed.add_field(name='.modhelpwallet',
                    value='shows all moderator warning commands',
                    inline=False)
    embed.add_field(name='.modhelpinventory',
                    value='shows all moderator warning commands',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpwarnings(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.createwarnwallet [insert warning user here]',
                    value='creates a warning wallet for the specified user',
                    inline=False)
    embed.add_field(name='.warnings [insert warning user here]',
                    value='gives all the warnings of the specified user',
                    inline=False)
    embed.add_field(name='.warn [insert warning user here] [insert violation here]',
                    value='adds the warning to the specified users wallet',
                    inline=False)
    embed.add_field(name='.dewarn [insert warning user here] [insert violation here',
                    value='removes the specified warning from the specified user',
                    inline=False)
    embed.add_field(name='.warncount [insert warning user here]',
                    value='give the amount of warnings the specified user has',
                    inline=False)
    embed.add_field(name='.warningkeys',
                    value='gives all users that have a warning account',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpwallet(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.create [insert wallet user here]',
                    value='creates a wallet for the specified user',
                    inline=False)
    embed.add_field(name='.set [insert wallet user here], [insert amount here]',
                    value='sets the user wallet to given amount',
                    inline=False)
    embed.add_field(name='.add [insert wallet user here], [insert amount here]',
                    value='adds the amount to the users wallet',
                    inline=False)
    embed.add_field(name='.remove [insert wallet user here], [insert amount here]',
                    value='removes the amount from ths users wallet',
                    inline=False)
    embed.add_field(name='.wkeys',
                    value='shows all users which have a wallet',
                    inline=False)

    await ctx.send(embed=embed)

@client.command(pass_context=True)
@commands.has_permissions(manage_messages=True)
async def modhelpinventory(ctx):
    await ctx.channel.purge(limit=1)

    embed = discord.Embed(colour=random.choice(rcolor))

    embed.add_field(name='.createi [insert inventory user here]',
                    value='creates an inventory for the specified user',
                    inline=False)
    embed.add_field(name='.give [insert inventory user here]',
                    value='gives an item to the specified user',
                    inline=False)
    embed.add_field(name='.take [insert inventory user here]',
                    value='removes an item from the specified user',
                    inline=False)
    embed.add_field(name='.ikeys',
                    value='shows all users which have an inventory',
                    inline=False)

    await ctx.send(embed=embed)

#end###############################################################################################################################end#

keep_alive.keep_alive()
client.run("TOKEN")

every time it crashes i type kill 1 in the console and it works. but it crashes again after a few hours.

i just hope that i can get it working 24/7 because the people on my server are getting annoyed


来源: stackexchange

问:
Self-hosted ASP.NET Core as udp server in Winforms
I have an Winforms app that host an ASP.NET Core Web API.

The main idea of the project is that from the winforms textbox I pass a database connection string to the dbContext of the ASP.NET Core API, and I start the IWebHost with the Startup so on..

I need this ASP.NET Core to be a datagram listener to when I start the host any idea or approach can help me to achieve this ?

ContentLicense: CC BY-SA 4.0


问:
Pandas dataframe in the current loop retains content from previous loop which messes up frequency count
I have a for loop where I'm creating a dataframe called rel.
The rel from the first loop is fine but I noticed that my second and third rel contain the contents of the rel from previous iterations
Since I'm using the information contained in each rel for a frequency count, I would prefer the rel in each iteration to only contain data from that iteration.

Here's a snippet of my code:

```<code>for var in range(1,3):
    df = pd.DataFrame(rows, columns=cols)

    rels = df.loc[df['location2'].isin(array)]
    rel = rels.assign(Index = range(len(rels))).set_index('Index')
    print(rel)
</code>```

I have a large .xml file which I'm storing in df. Then I'm taking a subset of df {specifically rows that contain the values specified in array in its location2 column]

I've tried clearing the dataframe at the end of each loop but that didn't work.
I tried putting a del rel and del rels before and after print rel which deleted the dataframe but that didn't resolve the problem

This is my output:
As you can see the second dataframe is about double the size of the first when it should be about the same

I encounter this problem on the third and fourth iterations as well, the dataframe is triple or quadruple expected length

Body:
I have a for loop where I'm creating a dataframe called rel.
The rel from the first loop is fine but I noticed that my second and third rel contain the contents of the rel from previous iterations
Since I'm using the information contained in each rel for a frequency count, I would prefer the rel in each iteration to only contain data from that iteration.

Here's a snippet of my code:

for var in range(1,3):
    df = pd.DataFrame(rows, columns=cols)

    rels = df.loc[df['location2'].isin(array)]
    rel = rels.assign(Index = range(len(rels))).set_index('Index')
    print(rel)

I have a large .xml file which I'm storing in df. Then I'm taking a subset of df {specifically rows that contain the values specified in array in its location2 column]

I've tried clearing the dataframe at the end of each loop but that didn't work.
I tried putting a del rel and del rels before and after print rel which deleted the dataframe but that didn't resolve the problem

This is my output:
As you can see the second dataframe is about double the size of the first when it should be about the same

I encounter this problem on the third and fourth iterations as well, the dataframe is triple or quadruple expected length


问:
Code showing "TypeError: string indices must be integers" overflow but still producing output. Something to do with json file
I'm new to python, and have a function (A) that pulls dictionaries from a list and converts them into a legible format. It was running perfectly fine but now when I run it I get a Type error after it spits out the formatted messages. This only happens when I try to utilize the json file I'm attempting to use to save the data I input.

I've isolated the function (B) that is causing the problem (it runs before function A so A can access all saved data), given it's the one that imports saved data from the json file my guess is that I'm doing that wrong in some way.

Here's the function that formats the data (function A):

```<code>def print_anomaly(anomaly):
    print(
        "---------------------------------------------------------------------------------------------------------------------------------------------")
    print(color.BOLD + "Anomaly Codename: " + anomaly['name'] + color.END)
    print("Anomaly Room #: " + anomaly['room'])
    print("Behavior: " + anomaly['type'])
    print("Threat Type:", end=' ')
    for threat in anomaly['threat class']:
        print(threat, end=' ')
    print("\n"
          "Anomaly Description: " + anomaly['properties'])
</code>```

(the sub function is the one having issues but it does run through this one to form a list)

```<code>def list_anomalies(filter = ''):
    if filter:
        print("Feature in progress")
    else:
        for anomaly in set(anomaly_bank):
            print_anomaly(anomaly)
</code>```

Here's the function that seems to be messing with it (Function B):

```<code>def load():
    with open('anomaly_data.json') as json_file:
        data = json.load(json_file)
        anomaly_bank.append(data)

</code>```

Here's what it spits out after being prompted

```<code>---------------------------------------------------------------------------------------------------------------------------------------------
Anomaly Codename: The Feild
Anomaly Room #: 0
Behavior: Anomaly is consistently passive
Threat Type: None
Anomaly Description: Presence felt within the bounds of the research facility since inception. Source and cause unknown.
---------------------------------------------------------------------------------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\JSF71\python_attempts\anomaly_bank.py", line 125, in <module>
    print_anomaly(anomaly)
  File "C:\Users\JSF71\python_attempts\anomaly_bank.py", line 55, in print_anomaly
    print(color.BOLD + "Anomaly Codename: " + anomaly['name'] + color.END)
TypeError: string indices must be integers
</code>```

Body:
I'm new to python, and have a function (A) that pulls dictionaries from a list and converts them into a legible format. It was running perfectly fine but now when I run it I get a Type error after it spits out the formatted messages. This only happens when I try to utilize the json file I'm attempting to use to save the data I input.

I've isolated the function (B) that is causing the problem (it runs before function A so A can access all saved data), given it's the one that imports saved data from the json file my guess is that I'm doing that wrong in some way.

Here's the function that formats the data (function A):

def print_anomaly(anomaly):
    print(
        "---------------------------------------------------------------------------------------------------------------------------------------------")
    print(color.BOLD + "Anomaly Codename: " + anomaly['name'] + color.END)
    print("Anomaly Room #: " + anomaly['room'])
    print("Behavior: " + anomaly['type'])
    print("Threat Type:", end=' ')
    for threat in anomaly['threat class']:
        print(threat, end=' ')
    print("\n"
          "Anomaly Description: " + anomaly['properties'])

(the sub function is the one having issues but it does run through this one to form a list)

def list_anomalies(filter = ''):
    if filter:
        print("Feature in progress")
    else:
        for anomaly in set(anomaly_bank):
            print_anomaly(anomaly)

Here's the function that seems to be messing with it (Function B):

def load():
    with open('anomaly_data.json') as json_file:
        data = json.load(json_file)
        anomaly_bank.append(data)

Here's what it spits out after being prompted

---------------------------------------------------------------------------------------------------------------------------------------------
Anomaly Codename: The Feild
Anomaly Room #: 0
Behavior: Anomaly is consistently passive
Threat Type: None
Anomaly Description: Presence felt within the bounds of the research facility since inception. Source and cause unknown.
---------------------------------------------------------------------------------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Users\JSF71\python_attempts\anomaly_bank.py", line 125, in <module>
    print_anomaly(anomaly)
  File "C:\Users\JSF71\python_attempts\anomaly_bank.py", line 55, in print_anomaly
    print(color.BOLD + "Anomaly Codename: " + anomaly['name'] + color.END)
TypeError: string indices must be integers


问:
Cannot execute multiple block of query in Mysql of NodeJS Server
I have data like below :

Target to show in clients :

My SQL like below :

```<code>SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
                  FROM history
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt
</code>```

Above coding can running on Toad and return to data but when I applied to query of Nodejs It stopped in  INTO @sql

Please help me if you have any solution .

Thanks

Data table :

```<code>DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);

INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);
</code>```

Nodejs module

const sql = require('../config/db')

exports.getreportsheet = (req, res) => {
  let sqlstring = `SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
                  FROM history
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt `
sql.query(sqlstring,
        ['Page', 20],
        function (err, results) {
            console.log('Loading data', results, sqlstring);
            return res.status(200).json({
                data: results
            })
        }
    );
};```

Body:
I have data like below :

Target to show in clients :

My SQL like below :

SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
                  FROM history
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt

Above coding can running on Toad and return to data but when I applied to query of Nodejs It stopped in  INTO @sql

Please help me if you have any solution .

Thanks

Data table :

DROP TABLE IF EXISTS history;
CREATE TABLE history
(hostid INT,
itemname VARCHAR(5),
itemvalue INT);

INSERT INTO history VALUES(1,'A',10),(1,'B',3),(2,'A',9),
(2,'C',40),(2,'D',5),
(3,'A',14),(3,'B',67),(3,'D',8);

Nodejs module

const sql = require('../config/db')

exports.getreportsheet = (req, res) => {
  let sqlstring = `SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'ifnull(SUM(case when itemname = ''',
      itemname,
      ''' then itemvalue end),0) AS `',
      itemname, '`'
    )
  ) INTO @sql
FROM
  history;
SET @sql = CONCAT('SELECT hostid, ', @sql, '
                  FROM history
                   GROUP BY hostid');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt `
sql.query(sqlstring,
        ['Page', 20],
        function (err, results) {
            console.log('Loading data', results, sqlstring);
            return res.status(200).json({
                data: results
            })
        }
    );
};


问:
How to combine multiple column by specific symbols followed in each column?
I have recently been using TOMST data logger to measure air temperature, soil temperature and humidity, but the original data csv output is pretty dirty...for example, the whole data was split either by two (row6), three(row5,7), or four columns(row1-4), which make combining data and separate them by each category difficult.

What I would need help is to 1) combine these separated forms of columns by 2)making those not ended with ";" to combine with its next column with a "." (this will become correct temperature reading)

Sample file from TOMST data*

So that for example, the raw 1 will change from

```<code>0;2022.12.23 00:00;4;19   75;19    75;19    625;483;202;0;
</code>```

to

```<code>0;2022.12.23 00:00;4;19.75;19.75;19.625;483;202;0;
</code>```

Body:
I have recently been using TOMST data logger to measure air temperature, soil temperature and humidity, but the original data csv output is pretty dirty...for example, the whole data was split either by two (row6), three(row5,7), or four columns(row1-4), which make combining data and separate them by each category difficult.

What I would need help is to 1) combine these separated forms of columns by 2)making those not ended with ";" to combine with its next column with a "." (this will become correct temperature reading)

Sample file from TOMST data*

So that for example, the raw 1 will change from

0;2022.12.23 00:00;4;19   75;19    75;19    625;483;202;0;

to

0;2022.12.23 00:00;4;19.75;19.75;19.625;483;202;0;


问:
Speed of updating MySQL InnoDB data tables correlated with total number of records in table
I am using MySQL 8.0.30 to build a database, and created several InnoDB data tables. These tables have the same table design (columns and column types), but contain different number of records. Now I need to add a new column for all tables, and update that column one record by one record since every record has different value of that column.

I used peewee 3.15.1 to perform the update. I only used two columns related to update, one is column id which is the primary key, the other one is the column col_a which needs to be updated. The col_a column has no index, and each table also does not have join relationships.

```<code>+--------------+--------------------+------+-----+---------+----------------+
| Field        | Type               | Null | Key | Default | Extra          |
+--------------+--------------------+------+-----+---------+----------------+
| id           | int                | NO   | PRI | NULL    | auto_increment |
| col_a        | varbinary(1024)    | NO   |     | NULL    |                |
+--------------+--------------------+------+-----+---------+----------------+
</code>```

I performed the update in chuncks. let's say, variable MYSQLDB is peewee database object, table is peewee data table object which needs to be updated, and num is the total number of records in that table.

batch_size = 1e5
count = ceil(num / batch_size)

for i in tqdm(range(count)):
    this_min = int(i * batch_size)
    this_max = int((i+1) * batch_size)

    query = (table.select(table.id,
                          table.col_a)
                  .where(table.id > this_min,
                         table.id <= this_max))

    for j in range(len(query)):
        query[j].col_a = <corresponding binary string for that row>

    with MYSQLDB.atomic():
        table.bulk_update(query, fields=[table.col_a])
```

In each iteration, peewee will fetch 100K records and then update column col_a. I found the running time per iteration was highly correlated with the number of records in table.

Data Tables
#Records
Rough estimated running time per iteration (seconds)

table 1
60,329,700
227.75

table 2
4,325,292
108.48

table 3
3,433,891
101.94

table 4
18,787,232
147.28

table 5
25,605,277
168.04

table 6
8,042,938
128.80

table 7
10,652,355
135.54

table 8
1,068,277
107.63

table 9
1,189,886
117.33

table 10
1,926,438
115.07

table 11
7,590,218
118.50

table 12
9,404,617
133.26

table 13
1,033,066,290
5147.33

After exclude table 13, the Pearson correlation coefficient between running time per iteration and number of records in data table is 0.9815 (p-value = 1.649e-08).

I am new to MySQL, and my questions are:

Why the running time of updating the same number of records is correlated with the number of total records in that table? Is it because the time for locking rows increases along with the table size?

For updating table 13, the running time is not acceptable. In order to add the new column and fill corresponding values, should I dump all rows by mysqldump to a CSV file, then insert them back into a new table together with the new column?

Body:
I am using MySQL 8.0.30 to build a database, and created several InnoDB data tables. These tables have the same table design (columns and column types), but contain different number of records. Now I need to add a new column for all tables, and update that column one record by one record since every record has different value of that column.

I used peewee 3.15.1 to perform the update. I only used two columns related to update, one is column id which is the primary key, the other one is the column col_a which needs to be updated. The col_a column has no index, and each table also does not have join relationships.

+--------------+--------------------+------+-----+---------+----------------+
| Field        | Type               | Null | Key | Default | Extra          |
+--------------+--------------------+------+-----+---------+----------------+
| id           | int                | NO   | PRI | NULL    | auto_increment |
| col_a        | varbinary(1024)    | NO   |     | NULL    |                |
+--------------+--------------------+------+-----+---------+----------------+

I performed the update in chuncks. let's say, variable MYSQLDB is peewee database object, table is peewee data table object which needs to be updated, and num is the total number of records in that table.

batch_size = 1e5
count = ceil(num / batch_size)

for i in tqdm(range(count)):
    this_min = int(i * batch_size)
    this_max = int((i+1) * batch_size)

    query = (table.select(table.id,
                          table.col_a)
                  .where(table.id > this_min,
                         table.id <= this_max))

    for j in range(len(query)):
        query[j].col_a = <corresponding binary string for that row>

    with MYSQLDB.atomic():
        table.bulk_update(query, fields=[table.col_a])

In each iteration, peewee will fetch 100K records and then update column col_a. I found the running time per iteration was highly correlated with the number of records in table.

Data Tables
#Records
Rough estimated running time per iteration (seconds)

table 1
60,329,700
227.75

table 2
4,325,292
108.48

table 3
3,433,891
101.94

table 4
18,787,232
147.28

table 5
25,605,277
168.04

table 6
8,042,938
128.80

table 7
10,652,355
135.54

table 8
1,068,277
107.63

table 9
1,189,886
117.33

table 10
1,926,438
115.07

table 11
7,590,218
118.50

table 12
9,404,617
133.26

table 13
1,033,066,290
5147.33

After exclude table 13, the Pearson correlation coefficient between running time per iteration and number of records in data table is 0.9815 (p-value = 1.649e-08).

I am new to MySQL, and my questions are:

Why the running time of updating the same number of records is correlated with the number of total records in that table? Is it because the time for locking rows increases along with the table size?

For updating table 13, the running time is not acceptable. In order to add the new column and fill corresponding values, should I dump all rows by mysqldump to a CSV file, then insert them back into a new table together with the new column?


问:
Measure to display value based on amount conditions
Could you help me design a DAX measure for displaying value based on conditions like:

(By selected date)

The measure will display "GREEN" if:

RESULT is "pass"

The measure will display "RED" if:

RESULT is "fail" and is the first time (from the selected dated).

RESULT is "fail" after continuously 9 times of pass.

The measure will display "BLUE" if:

RESULT is "fail" before continuously 9 times of pass.

For example from day 1 - 15, if day 1 was pass then the measure showed GREEN, after that day 3 was fail then showed RED (first time failed) and then had a continuous pass (GREEN) until day 13 was fail (RED, after continuously day 4-12 passes). Lastly, day 14 was pass then it was GREEN but day 15 was fail so the measure displayed BLUE.

The data looks like this below:   (MEASURE_COLOUR is the measure I want)

enter image description here


问:
Downloaded a open source program, but cant find the design
I am very new to this. But I have made some simple programs before.

I would like to use a open source project to make my own smaller version. It also help me understand what does what and why.

So, this is where I got the open source....
https://github.com/mikebb203/IPC-Hammer

The problem is when I open it up in Visual Studios 2015, I cant find the design, or even how to open it. Which I really do need. When I click on the button it brings me to the code then helps me understand what's happening.

How do I open the design to view the program design?
Thank you in advance :)

I down loaded the open source, but the design is missing. I would like to be able to open the design to help me understand the coding better.


问:
How to use new_version plugin
I tried using the new_version plugins, but why does it always get a redline when it says NewVersion. please help how to solve it.

This is my code:

```<code>import 'dart:async';

import 'package:flutter/material.dart';
import 'package:new_version/new_version.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    final newVersion = NewVersion(
      androidId: "com.snapchat.android",
    );
Timer(
      const Duration(milliseconds: 2000),
      () {
        checkNewVersion(newVersion);
      },
    );
    super.initState();
  }
//this is void check version

void checkNewVersion(NewVersion newVersion) async {
    final status = await newVersion.getVersionStatus();
    if (status?.canUpdate == true) {
      newVersion.showUpdateDialog(
          context: context,
          versionStatus: status!,
          allowDismissal: false,
          dialogTitle: "UPDATE!",
          dialogText:
              "UPDATE NOW ${status.localVersion}to${status.storeVersion}");
    }

  }
</code>```

Title: How to use new_version plugin

Body:
I tried using the new_version plugins, but why does it always get a redline when it says NewVersion. please help how to solve it.

This is my code:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:new_version/new_version.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    final newVersion = NewVersion(
      androidId: "com.snapchat.android",
    );
Timer(
      const Duration(milliseconds: 2000),
      () {
        checkNewVersion(newVersion);
      },
    );
    super.initState();
  }
//this is void check version

void checkNewVersion(NewVersion newVersion) async {
    final status = await newVersion.getVersionStatus();
    if (status?.canUpdate == true) {
      newVersion.showUpdateDialog(
          context: context,
          versionStatus: status!,
          allowDismissal: false,
          dialogTitle: "UPDATE!",
          dialogText:
              "UPDATE NOW ${status.localVersion}to${status.storeVersion}");
    }

  }


问:
Get related user model field using drf-writable-nested serializer in django
I'm a little stuck with something that might be very simple.

I have a model that is related to a user:

```<code>class Cheatsheet(VoteModel, models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=500, null=True, blank=True, default="")
    description = models.CharField(
        max_length=500, null=True, blank=True, default="")
    tags = TaggableManager(blank=True)

    def __str__(self):
        return self.title
</code>```

I have the following serializer, I'm using drf-writable-nested because I have deeply nested models and it eases creation and updates.

```<code>class CheatsheetSerializer(TaggitSerializer, WritableNestedModelSerializer):
    sections = SectionSerializer(many=True, required=False)
    tags = TagListSerializerField(required=False)

    class Meta:
        model = Cheatsheet
        fields = ("id", "sections", "tags", "vote_score", "title", "description", "user")
</code>```

And the following View

```<code>class CheatsheetViewSet(viewsets.ModelViewSet, VoteMixin):
    queryset = Cheatsheet.objects.all()
    serializer_class = CheatsheetSerializer
    http_method_names = ['get', 'post', 'retrieve', 'put', 'patch', 'delete']
</code>```

When I do GET: /cheatsheets/14/ I get the following response:

```<code>{
  "id": 14,
  "sections": [],
  "tags": [
    "css",
    "javascript"
  ],
  "vote_score": 0,
  "title": "New Cheatsheet",
  "description": "description test",
  "user": 1
}
</code>```

I want to receive the username aswell in my response.
So I proceded to create a UserSerializer

```<code>from django.contrib.auth.models import User

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    id = serializers.IntegerField()

    class Meta:
        model = User
        fields = ['id', 'username']
</code>```

and modified my CheatsheetSerializer:

```<code>user = UserSerializer()
</code>```

Now I get the username aswell, but POST and PUT request don't work anymore.

I want to send a "user" dict to create a new cheatsheet:

POST cheatsheets/

```<code>{
  "title": "New Cheatsheet3",
  "description": "asdf",
  "user": {
    "username": "admin",
    "id": 1
  }
}
</code>```

But I get the following error:

```<code>Write an explicit `.create()` method for serializer `api.serializers.CheatsheetSerializer`, or set `read_only=True` on nested serializer fields.
</code>```

I want to avoid writing a custom create() method because of the complexity of my models. (That's why I'm using drf-writable-nested).

I also tried setting read_only=True but then user ends up being null on my response. Same when setting depth = 1

How can I get the username inside my response while also allowing to send a "user" dict to POST requests and without writing custom serializer methods?

Body:
I'm a little stuck with something that might be very simple.

I have a model that is related to a user:

class Cheatsheet(VoteModel, models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    title = models.CharField(max_length=500, null=True, blank=True, default="")
    description = models.CharField(
        max_length=500, null=True, blank=True, default="")
    tags = TaggableManager(blank=True)

    def __str__(self):
        return self.title

I have the following serializer, I'm using drf-writable-nested because I have deeply nested models and it eases creation and updates.

class CheatsheetSerializer(TaggitSerializer, WritableNestedModelSerializer):
    sections = SectionSerializer(many=True, required=False)
    tags = TagListSerializerField(required=False)

    class Meta:
        model = Cheatsheet
        fields = ("id", "sections", "tags", "vote_score", "title", "description", "user")

And the following View

class CheatsheetViewSet(viewsets.ModelViewSet, VoteMixin):
    queryset = Cheatsheet.objects.all()
    serializer_class = CheatsheetSerializer
    http_method_names = ['get', 'post', 'retrieve', 'put', 'patch', 'delete']

When I do GET: /cheatsheets/14/ I get the following response:

{
  "id": 14,
  "sections": [],
  "tags": [
    "css",
    "javascript"
  ],
  "vote_score": 0,
  "title": "New Cheatsheet",
  "description": "description test",
  "user": 1
}

I want to receive the username aswell in my response.
So I proceded to create a UserSerializer

from django.contrib.auth.models import User

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    id = serializers.IntegerField()

    class Meta:
        model = User
        fields = ['id', 'username']

and modified my CheatsheetSerializer:

user = UserSerializer()

Now I get the username aswell, but POST and PUT request don't work anymore.

I want to send a "user" dict to create a new cheatsheet:

POST cheatsheets/

{
  "title": "New Cheatsheet3",
  "description": "asdf",
  "user": {
    "username": "admin",
    "id": 1
  }
}

But I get the following error:

Write an explicit `.create()` method for serializer `api.serializers.CheatsheetSerializer`, or set `read_only=True` on nested serializer fields.

I want to avoid writing a custom create() method because of the complexity of my models. (That's why I'm using drf-writable-nested).

I also tried setting read_only=True but then user ends up being null on my response. Same when setting depth = 1

How can I get the username inside my response while also allowing to send a "user" dict to POST requests and without writing custom serializer methods?


问:
What is the common condition while meeting the "*** stack smashing detected ***: terminated"?
While debugging the homework, I came across "*** stack smashing detected ***: terminated".
My question is how to solve it? and why this happens?

main.cpp

```<code>//
// Created by tseyu on 1/1/23.
// Define a function whose prototype is char* match(char* s, char ch);
// s is a C-style string, ch is a character.
// If the ch is in the s, return the position of s at ch;
// if the ch is not in the s, return NULL.

#include "matchCh.h"
#include <iostream>

int main(){

    char ch{};
    char mystring[]{};
    std::cout << "Please input a string: \n";
    std::cin.getline (mystring, 20);

    std::cout << "Please input a character: \n";
    std::cin >> ch;

    char* mych = match(mystring,ch);
    if (mych){
        std::cout << mych << std::endl;
    }else{
        std::cout << "Not found.\n";
    }

    return 0;
}

</code>```

match.cpp

```<code>//
// Created by tseyu on 1/1/23.
//
#include "matchCh.h"

char* match(char* s, char ch){
    char *pchar = s;
    while (*pchar != 0){
        if (*pchar == ch){
            return pchar;
        }
        pchar++;
    }
    return nullptr;
}
</code>```

matchCh.h

```<code>//
// Created by tseyu on 1/1/23.
//

#ifndef EXERCISE2_MATCHCH_H
#define EXERCISE2_MATCHCH_H
char* match(char* s, char ch);
#endif //EXERCISE2_MATCHCH_H

</code>```

I tried to find if there was an out of bound.
I expected to figured out what happens?

Body:
While debugging the homework, I came across "*** stack smashing detected ***: terminated".
My question is how to solve it? and why this happens?

main.cpp

//
// Created by tseyu on 1/1/23.
// Define a function whose prototype is char* match(char* s, char ch);
// s is a C-style string, ch is a character.
// If the ch is in the s, return the position of s at ch;
// if the ch is not in the s, return NULL.

#include "matchCh.h"
#include <iostream>

int main(){

    char ch{};
    char mystring[]{};
    std::cout << "Please input a string: \n";
    std::cin.getline (mystring, 20);

    std::cout << "Please input a character: \n";
    std::cin >> ch;

    char* mych = match(mystring,ch);
    if (mych){
        std::cout << mych << std::endl;
    }else{
        std::cout << "Not found.\n";
    }

    return 0;
}

match.cpp

//
// Created by tseyu on 1/1/23.
//
#include "matchCh.h"

char* match(char* s, char ch){
    char *pchar = s;
    while (*pchar != 0){
        if (*pchar == ch){
            return pchar;
        }
        pchar++;
    }
    return nullptr;
}

matchCh.h

//
// Created by tseyu on 1/1/23.
//

#ifndef EXERCISE2_MATCHCH_H
#define EXERCISE2_MATCHCH_H
char* match(char* s, char ch);
#endif //EXERCISE2_MATCHCH_H

I tried to find if there was an out of bound.
I expected to figured out what happens?


问:
How to redirect a click into a widget to the QMainWindow?
How I could redirect the click inside a determined widget to the QMainWindow?

When 'redirected' the click would not be executed into the widget, only in the QMainWindow.

Some things I tried:

```<code>   void mousePressEvent(QMouseEvent* event)
    {
        if (x)
            // process the click into the widget
        else
        {
            // Redirect the click in the same position to the QMainWindow
            QMainWindow *mainWindow = qobject_cast<QMainWindow*>(window());
            if (mainWindow)
                  mainWindow->raise();

            setAttribute( Qt::WA_TransparentForMouseEvents );
            qApp->processEvents();
            setAttribute( Qt::WA_TransparentForMouseEvents, false );
        }
    }
</code>```

Body:
How I could redirect the click inside a determined widget to the QMainWindow?

When 'redirected' the click would not be executed into the widget, only in the QMainWindow.

Some things I tried:

   void mousePressEvent(QMouseEvent* event)
    {
        if (x)
            // process the click into the widget
        else
        {
            // Redirect the click in the same position to the QMainWindow
            QMainWindow *mainWindow = qobject_cast<QMainWindow*>(window());
            if (mainWindow)
                  mainWindow->raise();

            setAttribute( Qt::WA_TransparentForMouseEvents );
            qApp->processEvents();
            setAttribute( Qt::WA_TransparentForMouseEvents, false );
        }
    }


问:
os.rename() says file already exists, but it doesn't
Full error:

FileExistsError: [WinError 183] Cannot create a file when that file already exists:
'C:\\Users\\unit0\\OneDrive\\Documentos\\EA Games\\The Sims™ 2 Ultimate Collection\\Downloads\\
test\\[Lilith] Hairs (Coolsims and Newsea)\\[Lilith] Hairs (Coolsims and Newsea)
\\\\[Lilith] Coolsims 109 3t2 DigitalAngels - Io+Pooklet'
->
'C:\\Users\\unit0\\OneDrive\\Documentos\\EA Games\\The Sims™ 2 Ultimate Collection\\Downloads\\
test\\[Lilith] Hairs (Coolsims and Newsea)\\[Lilith] Hairs (Coolsims and Newsea)
\\\\LilithCoolsims1093t2DigitalAngels-IoPooklet'
```

os.rename() will give me this error even though source and destination names are different. I've tried removing a dash from the path generator (so that \\\\ -> \\), but it didn't work.

shutil.move() will do the same, so I'm guessing this could have something to do with the directory's path formatting? Honestly at a loss right now.

I hope this is enough information, but I'll obviously provide more if necessary. Thanks in advance.

Body:
Full error:

FileExistsError: [WinError 183] Cannot create a file when that file already exists:
'C:\\Users\\unit0\\OneDrive\\Documentos\\EA Games\\The Sims™ 2 Ultimate Collection\\Downloads\\
test\\[Lilith] Hairs (Coolsims and Newsea)\\[Lilith] Hairs (Coolsims and Newsea)
\\\\[Lilith] Coolsims 109 3t2 DigitalAngels - Io+Pooklet'
->
'C:\\Users\\unit0\\OneDrive\\Documentos\\EA Games\\The Sims™ 2 Ultimate Collection\\Downloads\\
test\\[Lilith] Hairs (Coolsims and Newsea)\\[Lilith] Hairs (Coolsims and Newsea)
\\\\LilithCoolsims1093t2DigitalAngels-IoPooklet'

os.rename() will give me this error even though source and destination names are different. I've tried removing a dash from the path generator (so that \\\\ -> \\), but it didn't work.

shutil.move() will do the same, so I'm guessing this could have something to do with the directory's path formatting? Honestly at a loss right now.

I hope this is enough information, but I'll obviously provide more if necessary. Thanks in advance.


问:
Gitlab Template Plain HTML Not Working After Deployed Pipeline
I’m new to Gitlab, I have created a project name “gitlab-pages-plain-html” from Gitlab template: pages/plain HTML, and the gitlab pipeline to deploy the plain web site to the gitlab pages.

Template example that I get from: Plain HTML site using GitLab Pages

When I went to the Settings/Pages menu, it says Your pages are served under: http://example-group.swaggerui-poc.abc.com/gitlab-pages-plain-html,
and when clicked the link, error of “this site can’t be reached” will be displayed.

I have also check the public folder is there, inside public folder also has index.html

Kindly advise, thanks.


问:
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'LpVariable'
sorry I am new to Python pulp. I encounter the error TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'LpVariable' when running the script.

```<code>from pulp import *

problem = LpProblem('CASA Optimization', LpMaximize)

A1 = LpVariable('Option A1', lowBound=0 , cat=LpInteger)
A2 = LpVariable('Option A2', lowBound=0 , cat=LpInteger)
B1 = LpVariable('Option B1', lowBound=0 , cat=LpInteger)
C1 = LpVariable('Option C1', lowBound=0 , cat=LpInteger)
C2 = LpVariable('Option C2', lowBound=0 , cat=LpInteger)
D1 = LpVariable('Option D1', lowBound=0 , cat=LpInteger)
D2 = LpVariable('Option D2', lowBound=0 , cat=LpInteger)
E1 = LpVariable('Option E1', lowBound=0 , cat=LpInteger)
E2 = LpVariable('Option E2', lowBound=0 , cat=LpInteger)

problem += 15*A1 + 18*A2 + 9.6*B1 + 9.5*C1 + 17*C2 + 1*D1 + 1.5*D2 + 0.9*E1 + 0.6*E2 , 'Objective Function'
#Constraints
problem += 100*A1 + 130*A2 + 80*B1 + 80*C1 + 130*C2 + 10*D1 + 20*D2 + 8*E1 + 5*E2 <= 200 , 'Total Fund Constrain'
problem += 1**A1 + 1**A2 <= 1, 'Probability Constrain'
problem += 1**B1 <= 1, 'Probability Constrain'
problem += 1**C1 + 1**C2 <= 1, 'Probability Constrain'
problem += 1**D1 + 1**D2 <= 1, 'Probability Constrain'
problem += 1**E1 + 1**E2 <= 1, 'Probability Constrain'

problem.solve()
print("A1 value: ", A1.varValue)
print("A2 value: ", A2.varValue)
print("B1 value: ", B1.varValue)
print("C1 value: ", C1.varValue)
print("C2 value: ", C2.varValue)
print("D1 value: ", D1.varValue)
print("D2 value: ", D2.varValue)
print("E1 value: ", E1.varValue)
print("E2 value: ", E2.varValue)
</code>```

Please advise me how to solve the issue

Body:
sorry I am new to Python pulp. I encounter the error TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'LpVariable' when running the script.

from pulp import *

problem = LpProblem('CASA Optimization', LpMaximize)

A1 = LpVariable('Option A1', lowBound=0 , cat=LpInteger)
A2 = LpVariable('Option A2', lowBound=0 , cat=LpInteger)
B1 = LpVariable('Option B1', lowBound=0 , cat=LpInteger)
C1 = LpVariable('Option C1', lowBound=0 , cat=LpInteger)
C2 = LpVariable('Option C2', lowBound=0 , cat=LpInteger)
D1 = LpVariable('Option D1', lowBound=0 , cat=LpInteger)
D2 = LpVariable('Option D2', lowBound=0 , cat=LpInteger)
E1 = LpVariable('Option E1', lowBound=0 , cat=LpInteger)
E2 = LpVariable('Option E2', lowBound=0 , cat=LpInteger)

problem += 15*A1 + 18*A2 + 9.6*B1 + 9.5*C1 + 17*C2 + 1*D1 + 1.5*D2 + 0.9*E1 + 0.6*E2 , 'Objective Function'
#Constraints
problem += 100*A1 + 130*A2 + 80*B1 + 80*C1 + 130*C2 + 10*D1 + 20*D2 + 8*E1 + 5*E2 <= 200 , 'Total Fund Constrain'
problem += 1**A1 + 1**A2 <= 1, 'Probability Constrain'
problem += 1**B1 <= 1, 'Probability Constrain'
problem += 1**C1 + 1**C2 <= 1, 'Probability Constrain'
problem += 1**D1 + 1**D2 <= 1, 'Probability Constrain'
problem += 1**E1 + 1**E2 <= 1, 'Probability Constrain'

problem.solve()
print("A1 value: ", A1.varValue)
print("A2 value: ", A2.varValue)
print("B1 value: ", B1.varValue)
print("C1 value: ", C1.varValue)
print("C2 value: ", C2.varValue)
print("D1 value: ", D1.varValue)
print("D2 value: ", D2.varValue)
print("E1 value: ", E1.varValue)
print("E2 value: ", E2.varValue)

Please advise me how to solve the issue


问:
How to solve Airflow module import issue?
I am getting ModuleNotFoundError: No module named error in my Airflow DAG file. Directory structure is below. According to my understanding of Python packages and Airflow module management, I added the project_dir to sys.path in DAG file. What should I fix to make the imports work?

```<code>dags
  |
  | organization_dir
            |
            | project_dir
                      |
                      | __init__.py
                      | common_package
                                |
                                | __init__.py
                                | dag_pipeline_module.py
                                | subpackage
                                        |
                                        | __init__.py
                                        | sub_pkg_module.py
                      |
                      | configs
                                |
                                | __init__.py
                                | table_config.py
                      |
                      | __init__.py
                      | ci_config.py
                      | factory_config.py
                      | project_dag.py
</code>```

project_dag.py

Imports here are working fine.

```<code>import os
import sys

from airflow import DAG

import_path = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, import_path)

from factory_config import var1,var2
from common_package import DagPipelineFactory    # from dag_pipeline_module.py
</code>```

factory_config.py

This is giving an error. If I use full path, then it works fine.

```<code>import os

import configs as table_configs
from ci_config import var3      # error

# from organization_dir.project_dir.ci_config import var3     # no error
</code>```

ci_config.py

```<code>var3 = None
</code>```

Error Details

```<code>Broken DAG: [/home/airflow/gcs/dags/organization_dir/project_dir/factory_config.py] Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/airflow/gcs/dags/organization_dir/project_dir/factory_config.py", line 4, in <module>
    from ci_config import var3
ModuleNotFoundError: No module named 'ci_config'
</code>```

Body:
I am getting ModuleNotFoundError: No module named error in my Airflow DAG file. Directory structure is below. According to my understanding of Python packages and Airflow module management, I added the project_dir to sys.path in DAG file. What should I fix to make the imports work?

dags
  |
  | organization_dir
            |
            | project_dir
                      |
                      | __init__.py
                      | common_package
                                |
                                | __init__.py
                                | dag_pipeline_module.py
                                | subpackage
                                        |
                                        | __init__.py
                                        | sub_pkg_module.py
                      |
                      | configs
                                |
                                | __init__.py
                                | table_config.py
                      |
                      | __init__.py
                      | ci_config.py
                      | factory_config.py
                      | project_dag.py

project_dag.py

Imports here are working fine.

import os
import sys

from airflow import DAG

import_path = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, import_path)

from factory_config import var1,var2
from common_package import DagPipelineFactory    # from dag_pipeline_module.py

factory_config.py

This is giving an error. If I use full path, then it works fine.

import os

import configs as table_configs
from ci_config import var3      # error

# from organization_dir.project_dir.ci_config import var3     # no error

ci_config.py

var3 = None

Error Details

Broken DAG: [/home/airflow/gcs/dags/organization_dir/project_dir/factory_config.py] Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/home/airflow/gcs/dags/organization_dir/project_dir/factory_config.py", line 4, in <module>
    from ci_config import var3
ModuleNotFoundError: No module named 'ci_config'


问:
How to config health-check for ECS with multiple target groups using cdk
I'm using cdk to create an ecs service which will expose multiple ports.

Then I'm using ApplicationMultipleTargetGroupsEc2Service construct like this:

```<code>listener_1, listener_2

alb_props = ecs_patterns.ApplicationLoadBalancerProps(
            name="custom-alb-name",
            domain_name="*.example.com",
            domain_zone=route53.HostedZone.from_hosted_zone_attributes(
                self, "HostedZone",
                hosted_zone_id="xxxxxx",
                zone_name="example.com"
            ),
            listeners=[
                listener_1, listener2
            ],
            public_load_balancer=False
        )

target_props_1 = ecs_patterns.ApplicationTargetProps(
            container_port=8001,
            protocol=ecs.Protocol.TCP,
            listener=listener_1.name
        )

target_props_2 = ecs_patterns.ApplicationTargetProps(
            container_port=8444,
            protocol=ecs.Protocol.TCP,
            listener=listener_2.name
        )

ecs_service = ecs_patterns.ApplicationMultipleTargetGroupsEc2Service(
            self, "ECS-ID",
            service_name="service-name",
            cluster=cluster-name-ref,
            task_definition=task_definition,
            load_balancers=[alb_props],
            target_groups=[target_props_1, target_prop_2],
            cpu=1024,
            memory_reservation_mib=2048,
            desired_count=1
        )
</code>```

The default health check for target groups (1 and 2) :

path: /

code: 200

How can i config the health check of target groups using cdk (I'm using Python but i think it's similar for other languages)

Another problem, I already provided the name of load balancer while creating ecs service (custom-alb-name) but this is not working. The load balancer is auto-generated. I'm not sure if i config it right way or this is a bug of the cdk lib

Thank you all guys!!

Body:
I'm using cdk to create an ecs service which will expose multiple ports.

Then I'm using ApplicationMultipleTargetGroupsEc2Service construct like this:

listener_1, listener_2

alb_props = ecs_patterns.ApplicationLoadBalancerProps(
            name="custom-alb-name",
            domain_name="*.example.com",
            domain_zone=route53.HostedZone.from_hosted_zone_attributes(
                self, "HostedZone",
                hosted_zone_id="xxxxxx",
                zone_name="example.com"
            ),
            listeners=[
                listener_1, listener2
            ],
            public_load_balancer=False
        )

target_props_1 = ecs_patterns.ApplicationTargetProps(
            container_port=8001,
            protocol=ecs.Protocol.TCP,
            listener=listener_1.name
        )

target_props_2 = ecs_patterns.ApplicationTargetProps(
            container_port=8444,
            protocol=ecs.Protocol.TCP,
            listener=listener_2.name
        )

ecs_service = ecs_patterns.ApplicationMultipleTargetGroupsEc2Service(
            self, "ECS-ID",
            service_name="service-name",
            cluster=cluster-name-ref,
            task_definition=task_definition,
            load_balancers=[alb_props],
            target_groups=[target_props_1, target_prop_2],
            cpu=1024,
            memory_reservation_mib=2048,
            desired_count=1
        )

The default health check for target groups (1 and 2) :

path: /

code: 200

How can i config the health check of target groups using cdk (I'm using Python but i think it's similar for other languages)

Another problem, I already provided the name of load balancer while creating ecs service (custom-alb-name) but this is not working. The load balancer is auto-generated. I'm not sure if i config it right way or this is a bug of the cdk lib

Thank you all guys!!


问:
samesite none without secure browser
I'm developing with React and Django.
The original plan was to send api requests from the front to the Django server to manage sessions and read data, but it seems that cookies cannot be stored in the browser due to the samesite problem on the localhost used as a test during development. (It works in postman)
And when React and Django are run on the server, there is no problem with the session, so samesite=none that can be tested during development, but an environment that does not require secure is required.

Try:

Use old version firefox

Django - check cookies's "SameSite" attribute

```<code>CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
</code>```

Use axios proxy

https://pypi.org/project/django-samesite-none/  (django middleware)

Title: samesite none without secure browser

Body:
I'm developing with React and Django.
The original plan was to send api requests from the front to the Django server to manage sessions and read data, but it seems that cookies cannot be stored in the browser due to the samesite problem on the localhost used as a test during development. (It works in postman)
And when React and Django are run on the server, there is no problem with the session, so samesite=none that can be tested during development, but an environment that does not require secure is required.

Try:

Use old version firefox

Django - check cookies's "SameSite" attribute

CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'

Use axios proxy

https://pypi.org/project/django-samesite-none/  (django middleware)


问:
The method 'play' isn't defined for the type 'AudioCache'
this is the code please help me with this error,
i want to remove the   The method 'play' isn't defined for the type 'AudioCache' and i dont know to fix it. if someone could help me i appreciated it. Thank you so much

import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:sixam_mart_delivery/controller/order_controller.dart';
import 'package:sixam_mart_delivery/util/dimensions.dart';
import 'package:sixam_mart_delivery/util/images.dart';
import 'package:sixam_mart_delivery/util/styles.dart';
import 'package:sixam_mart_delivery/view/base/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class NewRequestDialog extends StatefulWidget {
  final bool isRequest;
  final Function onTap;
  NewRequestDialog({@required this.isRequest, @required this.onTap});

  @override
  State<NewRequestDialog> createState() => _NewRequestDialogState();
}

class _NewRequestDialogState extends State<NewRequestDialog> {
  Timer _timer;

  @override
  void initState() {
    super.initState();

    _startAlarm();
  }

  @override
  void dispose() {
    super.dispose();

    _timer?.cancel();
  }

  void _startAlarm() {
    AudioCache _audio = AudioCache();
    _audio.play('notification.mp3');
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      _audio.play('notification.mp3');
    });
  }
```

I want to fix the error i am having rn.

Body:
this is the code please help me with this error,
i want to remove the   The method 'play' isn't defined for the type 'AudioCache' and i dont know to fix it. if someone could help me i appreciated it. Thank you so much

import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:sixam_mart_delivery/controller/order_controller.dart';
import 'package:sixam_mart_delivery/util/dimensions.dart';
import 'package:sixam_mart_delivery/util/images.dart';
import 'package:sixam_mart_delivery/util/styles.dart';
import 'package:sixam_mart_delivery/view/base/custom_button.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class NewRequestDialog extends StatefulWidget {
  final bool isRequest;
  final Function onTap;
  NewRequestDialog({@required this.isRequest, @required this.onTap});

  @override
  State<NewRequestDialog> createState() => _NewRequestDialogState();
}

class _NewRequestDialogState extends State<NewRequestDialog> {
  Timer _timer;

  @override
  void initState() {
    super.initState();

    _startAlarm();
  }

  @override
  void dispose() {
    super.dispose();

    _timer?.cancel();
  }

  void _startAlarm() {
    AudioCache _audio = AudioCache();
    _audio.play('notification.mp3');
    _timer = Timer.periodic(Duration(seconds: 3), (timer) {
      _audio.play('notification.mp3');
    });
  }

I want to fix the error i am having rn.


问:
Error unzipping archive created by truezip which contains files greater than 2 GB
I was using java.util.zip to archive files until I encountered problems for large size files (> 2 GB). I tried switching to truezip. I was able to successfully archive the files but while extracting I get 'File fails CRC check' error.
Here is the code used to archive the files.</p>

```<code>int BUFF_MAX_SIZE = 524288;
    byte[] buf = new byte[BUFF_MAX_SIZE];
    long time;
    long size;
    File fp;
    String[] filenames = {"D:\\abc", "D:\\large file", "D:\\xyz"};
    int n = filenames.length;
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("archive.zip")), Charset.forName("UTF-8"));
    for (int i = 0; i < n; i++) {
        fp = new File(filenames[i]);
        time = fp.lastModified();
        size = fp.length();
        try {
            TFileInputStream in = new TFileInputStream(filenames[i]);
            ZipEntry ze = new ZipEntry(filenames[i]);
            ze.setTime(time);
            ze.setSize(size);
            out.putNextEntry(ze);
            TFile.getDefaultArchiveDetector();
            int len = 0;
            collectCnt = 0;
            while ((len = in.read(buf, 0, BUFF_MAX_SIZE)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.closeEntry();

        } catch (Exception ex) {
            //
        }
    }
    try{
        out.close();
    } catch (Exception ex){
        // error closing outout stream.
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was using java.util.zip to archive files until I encountered problems for large size files (> 2 GB). I tried switching to truezip. I was able to successfully archive the files but while extracting I get 'File fails CRC check' error.
Here is the code used to archive the files.

int BUFF_MAX_SIZE = 524288;
    byte[] buf = new byte[BUFF_MAX_SIZE];
    long time;
    long size;
    File fp;
    String[] filenames = {"D:\\abc", "D:\\large file", "D:\\xyz"};
    int n = filenames.length;
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("archive.zip")), Charset.forName("UTF-8"));
    for (int i = 0; i < n; i++) {
        fp = new File(filenames[i]);
        time = fp.lastModified();
        size = fp.length();
        try {
            TFileInputStream in = new TFileInputStream(filenames[i]);
            ZipEntry ze = new ZipEntry(filenames[i]);
            ze.setTime(time);
            ze.setSize(size);
            out.putNextEntry(ze);
            TFile.getDefaultArchiveDetector();
            int len = 0;
            collectCnt = 0;
            while ((len = in.read(buf, 0, BUFF_MAX_SIZE)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.closeEntry();

        } catch (Exception ex) {
            //
        }
    }
    try{
        out.close();
    } catch (Exception ex){
        // error closing outout stream.
    }


问:
Is there an option to check the sequence of the function that is running using Trace 32
I am trying to check the order or sequence in which the functions are being called after i flash using trace 32. Can anyone help me know if there is an option to check this and where can i find it?

I tried a graphical method which i saw online but it wasn't showing me the expected result


问:
I was wondering if we can target a specfic BottomNavigationBar page from a different page in flutter
I was looking for a way to target the cart screen from items details page. The carts screen is on one of the tabs on the home screen's BottomNavigationBar.

I am new to flutter and was just trying to see if it is possible or not.