Пример #1
0
def VStats(infile, axis='x', rmax=10.):

  # Read in data from file
  time, total, data = read(infile)

  # Limit selection to bulge particles
  ind = np.where(data == 3)[0]
  bulge = data[ind]

  # Compute center-of-mass position and velocity
  time, com, vcom = COM(infile, 3, tol=0.5)

  # Calibrate position and velocity relative to COM
  pos = bulge[:, 2:5] - com
  vel = bulge[:, 5:8] - vcom

  # Select only particles within rmax
  r = np.sqrt(np.sum(pos**2, axis=1))
  ind = np.where(r <= rmax)[0]
  vel = abs(vel[ind])

  # Compute mean velocity and dispersion along specified axis
  if axis == 'x':
    mean = np.mean(vel[:, 0])
    sigma = np.std(vel[:, 0])
  elif axis == 'y':
    mean = np.mean(vel[:, 1])
    sigma = np.std(vel[:, 1])
  else:
    mean = np.mean(vel[:, 2])
    sigma = np.std(vel[:, 2])
  print mean, sigma

  # Return results
  return mean, sigma
Пример #2
0
async def on_member_join(member):
    global member_join_time
    member_join_time = time()
    json_file = loads(read('config.json'))
    black_lista = [
        json_file['black_list'][key] for key in json_file['black_list']
    ]
    if member.id in black_lista:
        await member.ban()
        json_rem('config.json', ['black_list', str(member.id)])
        return
    image = discord_file('resources/join.gif', 'Witamy.gif', False)
    await vrb.ver_chan.send(
        f"Witamy serdecznie {member.display_name} na serwerze FurHeaven. Celem tego miejsca jest zrzeszanie osob interesujacych sie tematyka furry. Jest tu sporo osob z ktorymi mozna pogadac na przerozne tematy. Mamy nadzieje, ze bedzie Ci tu z nami milo :grin:\nOdpowiedz tylko na  pięć pytań.\n1. Ile masz lat?\n2. Czy jestes futrzakiem?\n3. Czy przeczytales regulamin i bedziesz go przestrzegac?\n4. Mężczyzna/Kobieta?\n5. Skąd masz zaproszenie?\n\nJeżeli odpowiedziałeś/aś na pytania a nikt z moderacji ani administracji jeszcze nic nie zrobił, oznacz kogoś z nich, na pewno od razu przeprowadzą weryfikację :3",
        file=image)
    image = discord_file('resources/join.mp4', 'Witamy.mp4', False)
    await vrb.main_chan.send(
        f"<@{member.id}> wlasnie wbil/a na serwer! Zaraz powinien/na do nas dolaczyc.",
        file=image)
    for role in vrb.dividing_roles:
        await member.add_roles(role)
    await vrb.commands_chan.send(embed=user_info(vrb.host, member, True))
    sleep(5)
    await vrb.ver_chan.send(f'<@{member.id}>')
    msg = await vrb.ver_chan.send(vrb.host.mention)
    await msg.delete()
Пример #3
0
async def on_raw_reaction_remove(payload):

    json_file = loads(read('config.json'))
    single_roles_orientations = json_file['autoroles'][
        'single_roles_orientations']

    guild = client.get_guild(payload.guild_id)
    channel = client.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    member = guild.get_member(payload.user_id)

    if not channel == vrb.autoroles_chan1 and not channel == vrb.autoroles_chan2 or member == client.user:
        return
    if len(message.content.split('\n')) > 1:
        role_name = message.content.split('\n')[-1].split(' - ')[0][2:-2]
    elif len(message.embeds) == 0:
        role_name = message.content.split(' - ')[0][2:-2]
    else:
        role_name = message.embeds[0].fields[0].name
    role = get(guild.roles, name=role_name)

    await member.remove_roles(role)

    if role.id in single_roles_orientations and not chk_list_cohesion(
        [role.id for role in member.roles], single_roles_orientations):
        await member.add_roles(vrb.nie_zarucham)
Пример #4
0
async def rment(ctx, *, role: Role):
    if not ctx.channel == vrb.game_chan:
        await ctx.send('To nie jest kanał od gier')
        return

    if not role in search_in_list(ctx.guild.roles[::-1], vrb.dividing_games, vrb.dividing_channels)[2:-1]:
        await ctx.send('To nie jest rola od gier')
        return

    await ctx.message.delete()

    roles = loads(read('commands/role_mentions.json'))['roles']
    c_time = time()

    if not str(role.id) in list(roles):
        json_add('commands/role_mentions.json', ['roles'], {str(role.id): c_time})
        await role.edit(mentionable = True)
        await ctx.send(f'{ctx.author.mention} wzmienia {role.mention}')
        await role.edit(mentionable = False)
        return

    for r_id in roles:
        if r_id == str(role.id):
            if c_time - roles[r_id] >= 3600:
                json_add('commands/role_mentions.json', ['roles'], {r_id: c_time})
                await role.edit(mentionable = True)
                await ctx.send(f'{ctx.author.mention} wzmienia {role.mention}')
                await role.edit(mentionable = False)
                return
            else: 
                how_long = int((3600 - (c_time - roles[r_id])) / 60)
                await ctx.send(f'Musisz jeszcze poczekać {how_long} minut aby znów oznaczyć tą rolę')
                return
Пример #5
0
async def exclude(ctx, *, role: Role):
    if not vrb.adm_role in ctx.author.roles: return
    json_file = loads(read('config.json'))
    excluded = json_file['autoroles']['excluded']
    excluded.append(role.id)
    json_add('config.json', ['autoroles'], {'excluded': excluded}, True)
    await ctx.send('Pomyślnie dodałem rolę do wykluczonych')
Пример #6
0
async def loop_10m():
    now = datetime.now().timestamp()
    json_file = loads(read('events.json'))
    events = json_file['all']['events']
    for event in events:
        print(now, float(event), now > float(event))
        if now > float(event):
            temp = 0
            chan = client.get_channel(events[event]['cid'])
            msg = await chan.fetch_message(events[event]['mid'])
            opis = events[event]['desc']
            embed = Embed(title='Przypominajka o evencie!',
                          timestamp=datetime.utcnow())
            embed.add_field(name=opis.split(' /// ')[0],
                            value=' '.join(opis.split(' /// ')[1:]))
            react_num = len(msg.reactions)
            for react in msg.reactions:
                async for user in react.users(limit=None, after=None):
                    if user == client.user: continue
                    try:
                        await user.send(embed=embed)
                        temp += 1
                    except:
                        pass
            json_rem('events.json', ['all', 'events', event])
        await vrb.host.send(
            f'Wysłano wiadomości przypominające do {temp} osób, zareagowało {react_num} osób\n**Nie zapomnij pousuwać 3 części kodu z tej komendy po przeprowadzeniu testu!**'
        )
Пример #7
0
    def test_get_data(self, obj):
        a = Mock()
        a.keys.return_value = ["student1", "student2"]
        a.lrange.return_value = ["subject1", "rate1"]

        obj.return_value = a

        self.assertEqual(read(), [['student1', 'student2'], [['subject1', 'rate1'], ['subject1', 'rate1']]])
Пример #8
0
def search_file(p_path, p_file_name):
    try:
        print(f'\nLog: looking for file in {p_path}')
        with open(rf"{p_path}\\" + f"{p_file_name}", "r+") as f:
            print('Log: file was found successfully!\n')
            return f.read()
    except IOError:
        print('ERROR: file was not found\n')
        exit(0)
Пример #9
0
def index():
    ser_values = func.read()
    ver = ser_values[0]
    hor = ser_values[1]
    step = ser_values[2]
    data = {"ver": ver, "hor": hor, "step": step}
    print("vertikální osa: " + str(ver))
    print("horizontální osa: " + str(hor))
    return render_template("camera.html", data=data)
Пример #10
0
async def loop_1():
    json_file = loads(read('config.json'))
    invitki = json_file['user_invs']

    #reset zaproszen
    if datetime.now().strftime('%H') == '05':
        for i in invitki:
            json_rem('config.json', ['user_invs', i])   
    
    #zapisywanie permisji kanałów
    for channel in vrb.guild.text_channels:
        if loads(read('commands/for_host/silence.json'))['silenced'] != True:
            json_add('commands/for_host/silence.json', ['saved_perms'], {str(channel.id): {}}, True)
            for role in channel.changed_roles:
                perms = dict(channel.overwrites_for(role))
                sorted_perms = {}
                for perm in perms:
                    if perms[perm] != None:
                        sorted_perms[perm] = perms[perm]
                json_add('commands/for_host/silence.json', ['saved_perms', str(channel.id)], {str(role.id): sorted_perms}, True)
Пример #11
0
 def InitTimezone(self):
     langlist = []
     f = open('/opt/installer/zone.csv')
     lines = f.read().split('\n')
     for line in lines:
         words = line.split("\"")
         if len(words) >= 5:
             langlist.append(words[5])
     langlist.sort()
     for lang in langlist:
         self.Timezone.Append(lang)
     f.close()
Пример #12
0
 def loadBadCh(self):
     filename = os.path.join(self.pathName, 'Artifacts', 'badChannels.txt')
     if os.path.exists(filename):
         with open(filename) as f:
             badChannels = f.read()
             print 'Bad Channels : {}'.format(badChannels)
     else:
         os.mkdir(os.path.join(self.pathName, 'Artifcats'))
         with open(filename, 'w') as f:
             f.write('')
             f.close()
         badChannels = []
     return badChannels
Пример #13
0
async def zw(ctx, *, info):
    if info == 'delete':
        try:
            json_rem('commands/zw.json', ['dnd', str(ctx.author.id)])
            await ctx.send('Pomyślnie usunąłem twoje zw')
        except:
            await ctx.send('Aktualnie nie masz żadnego ustawionego zw')
    elif info == 'check':
        try:
            user_zw = loads(read('commands/zw.json'))['dnd'][str(
                ctx.author.id)]
            await ctx.send(f'Oto twoje obecne zw```{user_zw}```')
        except:
            await ctx.send('Aktualnie nie masz żadnego ustawionego zw')
    else:
        json_add('commands/zw.json', ['dnd'], {str(ctx.author.id): info}, True)
        await ctx.send('Pomyślnie zaktualizowałem twoje zw')
Пример #14
0
async def putinbox(ctx, *, member: Member):
    json_file = loads(read('config.json'))
    put_in_box = json_file['put_in_box']
    if ctx.author.id in [put_in_box[key] for key in put_in_box]:
        await ctx.send(
            'Wyczerpałeś swój limit wkładania futrzaków do pudełek na dziś')
        return
    if member.bot:
        if member.id == client.user.id:
            await ctx.send('Ja ne ce do pudeuka :<')
        else:
            await ctx.send(
                'Nie wsadzaj bota do pudełka :< on sam potem z niego nie umie wyjść'
            )
        return
    json_add('config.json', ['put_in_box', str(ctx.author.id)], ctx.author.id)
    await ctx.send(f'*<@{ctx.author.id}> wkłada <@{member.id}> do pudełka* uwu'
                   )
    await member.edit(nick=f'{member.display_name} in a box')
Пример #15
0
def add_body(name,col1,col2,path,mass,pos,hv,vv):
    bodies["name{0}".format(bodies["num"])] = name
    bodies["mass{0}".format(bodies["num"])] = mass
    bodies["color{0}".format(bodies["num"])] = col1
    bodies["text{0}".format(bodies["num"])] = {}
    bodies["pos{0}".format(bodies["num"])] = pos
    bodies["hv{0}".format(bodies["num"])] = hv
    bodies["vv{0}".format(bodies["num"])] = vv

    bodies["rot{0}".format(bodies["num"])] = 0
    if path != "":
        text = read("\Textures" + path).split("\n")
        for i in range(len(text)):
            bodies["text{0}".format(bodies["num"])][i] = []
            for j in text[i]:
                if j == "#": bodies["text{0}".format(bodies["num"])][i].append(col2)
                elif j == "'": bodies["text{0}".format(bodies["num"])][i].append(col1)
    
    bodies["num"] += 1
Пример #16
0
def PhaseDiagram(infile, ptype=3, p_axis='x', v_axis='y'):

  # Read in data from file
  time, total, data = read(infile)

  # Select particles of specified type
  ind = np.where(data == ptype)[0]
  data = data[ind]

  # Normalize positions and velocities
  time, com, vcom = COM(infile, ptype, tol=0.1)
  pos = data[:, 2:5] - com
  vel = data[:, 5:8] - vcom

  # Extract relevant columns
  if p_axis == 'x':
    pos = pos[:, 0]
  elif p_axis == 'y':
    pos = pos[:, 1]
  else:
    pos = pos[:, 2]

  if v_axis == 'x':
    vel = vel[:, 0]
  elif v_axis == 'y':
    vel = vel[:, 1]
  else:
    vel = vel[:, 2]

  # Set plot limits
  p_lim, v_lim = 50., 450.

  # Plot phase diagram
  from matplotlib.colors import LogNorm
  plt.hist2d(pos, vel, range=[[-p_lim, p_lim], [-v_lim, v_lim]], bins=100, norm=LogNorm())
  p_label = p_axis+' distance (kpc)'
  v_label = v_axis+' velocity (km/s)'
  plt.xlabel(p_label)
  plt.ylabel(v_label)
  ax = plt.gca()
  ax.set_axis_bgcolor('black')
  plt.show()
Пример #17
0
def meniu():
    optiuni()
    opt = int(input("Optiune:\n"))

    while opt != 0:
        if opt == 1:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-5.txt")
            algoritm.kSolutions(k, obj, nr_executii, "solutiiCA5.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
        if opt == 2:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-20.txt")
            algoritm.kSolutions(k, obj, nr_executii, "solutiiCA20.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
        if opt == 3:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-200.txt")
            algoritm.kSolutions(k, obj, nr_executii, "solutiiCA200.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
        if opt == 4:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-5.txt")
            algoritm.hillClimbing(k, obj, nr_executii, "solutiiHC5.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
        if opt == 5:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-20.txt")
            algoritm.hillClimbing(k, obj, nr_executii, "solutiiHC20.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
        if opt == 6:
            k = int(input("Numarul solutiilor (k):\n"))
            nr_executii = int(input("Numarul de executii:\n"))
            obj = functions.read("rucsac-200.txt")
            algoritm.hillClimbing(k, obj, nr_executii, "solutiiHC200.txt")
            print("done\n")
            opt = int(input("Optiune:\n"))
Пример #18
0
async def inv(ctx):
    json_file = loads(read('config.json'))
    user_invs = json_file['user_invs']
    await ctx.message.delete()
    if ctx.author.id in [user_invs[key] for key in user_invs]:
        await ctx.send(
            'Już dziś prosiłeś o jedno zaproszenie\nJeżeli chcesz więcej, poproś o nie kogoś z zarządu'
        )
        return
    await ctx.channel.create_invite(max_age=1800, max_uses=1)
    zapki = await ctx.channel.invites()
    for i in zapki:
        if i.inviter == client.user and i.created_at.strftime(
                '%M') == datetime.now().strftime('%M'):
            inv = i.code
    json_add('config.json', ['user_invs', str(ctx.author.id)], ctx.author.id)
    await ctx.author.send(
        f'Oto zaproszenie dla ciebie https://discord.gg/{inv}\nWażne 30 minut, jedno użycie'
    )
    await vrb.tech_chan.send(
        f'Wysłałem zaproszenie do {ctx.author.name} aka {ctx.author.display_name}'
    )
Пример #19
0
        print('Conversion succeed.')

        try:
            file = docx.Document(filename)
        except:
            print('Converting "' + filename + '" into "' + filename +
                  'x" file...')
            filename = doc2docx(filename)
            print('Conversion succeed.')
            file = docx.Document(filename)

        try:
            answer = docx.Document(answer_name)
        except:
            print('Converting "' + answer_name + '" into "' + answer_name +
                  'x" file...')
            answer_name = doc2docx(answer_name)
            print('Conversion succeed.')
            answer = docx.Document(answer_name)

        ws, wb, y, m, l = f.add_sheet(file.paragraphs[0].text, output_name)
        mark = f.check_type(filename)
        answer_list = f.read_answer(answer, ws)
        f.read(file, answer_list[-5:], ws, wb, y, m, l, mark, output_name)
        f.replace(ws, ['_', '_'], '<under2></under2>')
        wb.save(output_name)
        print('The database is successfully output to "' + output_name + '".')
        input('Press any key to exit')
    except Exception as e:
        print(traceback.format_exc())
Пример #20
0
def DiskStatPlot(galaxy, snap, dirname='.', fnum=0, rmax=50):

  # Construct filename
  infile = galaxy + '_%03d.txt' % snap

  # Read in data from file
  time, total, data = read(infile)

  # Compute COM and shift to COM frame
  time, com, vcom = COM(infile, 3, tol=0.5)
  pos = data[:, 2:5] - com
  vel = data[:, 5:8] - vcom

  # Select only disk particles
  ind = np.where(data == 2)[0]
  pos, vel = pos[ind], vel[ind]

  # Select region for plotting
  r = np.sqrt(np.sum(np.square(pos), axis=1))
  ind = np.where(r < rmax)[0]
  pos, vel = pos[ind], vel[ind]

  # Rotate coordinate system to angular momentum frame
  pos, vel = AngMomShift(pos, vel)

  # Plot disk with statistics
  from matplotlib.colors import LogNorm
  plt.subplot(221) # xy-plane
  plt.hist2d(pos[:, 0], pos[:, 1], range=[[-rmax, rmax], [-rmax, rmax]], bins=100, norm=LogNorm())
  ax = plt.gca()
  ax.set_axis_bgcolor('black')
  ax.set_aspect('equal', adjustable='box')
  plt.xlabel('x (kpc)')
  plt.ylabel('y (kpc)')
  title = 't = ' + '%d' % time + ' Myr'
  ax.set_title(title)

  plt.subplot(223) # xz-plane
  plt.hist2d(pos[:, 0], pos[:, 2], range=[[-rmax, rmax], [-rmax, rmax]], bins=100, norm=LogNorm())
  ax = plt.gca()
  ax.set_ylim([-rmax, rmax])
  ax.set_axis_bgcolor('black')
  ax.set_aspect('equal', adjustable='box')
  plt.xlabel('x (kpc)')
  plt.ylabel('z (kpc)')

  plt.subplot(222) # z histogram
  z_disp = np.std(pos[:, 2])
  zrange = 3*z_disp
  plt.hist(pos[:, 2], bins=100, range=[-zrange, zrange])
  plt.xlabel('z (kpc)')
  ax = plt.gca()
  ax.set_xlim([-zrange, zrange])

  plt.subplot(224) # vz histogram
  vz_disp = np.std(vel[:, 2])
  vzrange = 3*vz_disp
  plt.hist(vel[:, 2], bins=100, range=[-vzrange, vzrange])
  plt.xlabel(r'v$_z$ (km s$^{-1}$)')
  ax = plt.gca()
  ax.set_xlim([-vzrange, vzrange])

  # Save plot
  frame = '%03d' % fnum
  if '/' in galaxy:
    fgalaxy = galaxy.split('/')[-1]
  else:
    fgalaxy = galaxy
  figname = dirname + '/' + fgalaxy + '_' + frame + '.png'
  plt.savefig(figname)
  plt.clf()

  # Return time and dispersion values
  return time, z_disp, vz_disp
Пример #21
0
def DiskRange(galaxy, first, last, rmax=50, axes='xy'):

  print galaxy, first, last, axes

  # Create subfolder in which to place images
  firststr, laststr = '%03d' % first, '%03d' % last
  if '/' in galaxy:
    fgalaxy = galaxy.split('/')[-1]
  else:
    fgalaxy = galaxy
  dirname = fgalaxy + '_' + firststr + '_' + laststr + '_' + axes
  print dirname
  import os
  if not os.path.isdir(dirname):
    os.makedirs(dirname)

  # Loop over snap range
  i = 0
  for snap in range(first, last+1):

    # Construct file name
    snapstr = '%03d' % snap
    infile = galaxy + '_' + snapstr + '.txt'
    print infile

    # Read in data from file
    time, total, data = read(infile)

    # Compute COM and shift to COM frame
    time, com, vcom = COM(infile, 3, tol=0.5)
    pos = data[:, 2:5] - com
    vel = data[:, 5:8] - vcom

    # Select region for plotting
    r = np.sqrt(np.sum(np.square(pos), axis=1))
    pos = pos[np.where(r < rmax and data == 2)[0]]
    vel = vel[np.where(r < rmax and data == 2)[0]]

    # Rotate coordinate system to angular momentum frame
    pos, vel = AngMomShift(pos, vel)

    # Select axes
    if axes == 'xy':
      x1 = pos[:, 0]
      x2 = pos[:, 1]
    elif axes == 'xz':
      x1 = pos[:, 0]
      x2 = pos[:, 2]
    else:
      x1 = pos[:, 1]
      x2 = pos[:, 2]

    # Plot disk and plane
    from matplotlib.colors import LogNorm
    plt.hist2d(x1, x2, bins=100, range=[[-rmax, rmax], [-rmax, rmax]], norm=LogNorm())
    ax = plt.gca()
    ax.set_axis_bgcolor('black')
    plt.gca().set_aspect('equal', adjustable='box')

    # Save figure
    frame = '%03d' % i
    figname = dirname + '/' + fgalaxy + '_' + frame + '.png'
    plt.savefig(figname)

    # Increment frame number
    i += 1
Пример #22
0
import functions as func

inputpath = 'inventory.csv'
func.read(inputpath)
Пример #23
0
import functions as fun
import warnings

if __name__ == "__main__":

    warnings.filterwarnings("ignore")
    LABELS = True

    #Wczytanie danych
    data = fun.read("all_summary.txt",";")
    test_data = fun.read("test_data.txt",",")

    #filtrowanie danych
    data = fun.filter_data(data,["DA","DC","DT","DU","DG", "DI","UNK","UNX","UNL","PR","PD","Y1","EU","N","15P","UQ","PX4", "NAN"])

    if(LABELS):
        labels = fun.read("labels.txt",",")
        data['res_name']=labels['res_name_group']

    #uczenie
    fun.learn(data,test_data)



Пример #24
0
##############################################
### Get time, score & fouls from API based on
### gameId in gameId.txt
##############################################

# import modules
import websocket
import json
import time
from functions import read, write, format_timeRemaining, initial_call

# setup variables
path = 'data/'
url = read('apiURL.txt')
gameId = ''
timeRemaining = 600000

# make subscribe message
subscribe = {}
subscribe['apiName'] = "TvFeedApiV3"
subscribe['apiCommand'] = "subscribe"
subscribe['apiKey'] = read('apiKey.txt')
subscribe['requestId'] = "test connection"
subscribe['eventId'] = read('eventId.txt')

# setup WebSocket
ws = websocket.WebSocket()
ws.connect(url)
ws.send(json.dumps(subscribe))

# main loop
Пример #25
0
async def silence(ctx, arg):
    if ctx.author != vrb.host or not vrb.kanclerz in ctx.author.roles:
        await ctx.send('Nie masz uprawnień')
        return

    if arg == 'on':
        letters = ascii_letters
        safety_string = ''.join(choice(letters) for i in range(6))
        await ctx.send(
            f'Wpisz ten ciąg znaków aby potwierdzić decyzję o zablokowaniu wszystkich kanałów serwera\n``{safety_string}``'
        )

        def check(m):
            return m.content == safety_string and m.author == ctx.author and m.channel == ctx.channel

        try:
            await client.wait_for('message', timeout=15.0, check=check)
        except TimeoutError:
            await ctx.channel.send('Czas minął')
            return

        loading = await ctx.send('``Wyciszanie trwa\n' + 25 * '-' + '``')
        loading_counter = 0
        json_add('commands/for_host/silence.json', ['silenced'], True)
        for channel in ctx.guild.text_channels:
            loading_progress = int(loading_counter / len(ctx.guild.channels) *
                                   25)
            for role in channel.changed_roles:
                await channel.set_permissions(role, overwrite=None)
            await channel.set_permissions(ctx.guild.default_role,
                                          read_messages=False)
            await loading.edit(content='``Wyciszanie trwa\n' +
                               loading_progress * '#' +
                               (25 - loading_progress) * '-' + '``')
            loading_counter += 1
        silenced = await ctx.guild.create_text_channel(
            name='inf kryzysowa',
            overwrites={
                ctx.guild.default_role:
                PermissionOverwrite(send_messages=False)
            })
        await silenced.send(
            'Przepraszamy ale wystąpiła sytuacja kryzysowa i serwer będzie niedostępny przez pewien okres czasu.\nAdministracja zajmuje się sytuacją i powinna wam przekazać więcej informacji.'
        )
        await loading.edit(content='``Done\n' + 25 * '#' + '``')

    if arg == 'off':
        all_chans = loads(
            read('commands/for_host/silence.json'))['saved_perms']
        loading = await ctx.send('``Odciszanie trwa\n' + 25 * '-' + '``')
        loading_counter = 0
        for chan_id in all_chans:
            channel = client.get_channel(int(chan_id))
            await channel.set_permissions(ctx.guild.default_role,
                                          overwrite=None)
            for role_id in all_chans[chan_id]:
                perms = all_chans[chan_id][role_id]
                role = ctx.guild.get_role(int(role_id))
                if len(perms) == 0: continue
                await channel.set_permissions(role, **perms)
            loading_progress = int(loading_counter / len(ctx.guild.channels) *
                                   25)
            await loading.edit(content='``Odciszanie trwa\n' +
                               loading_progress * '#' +
                               (25 - loading_progress) * '-' + '``')
            loading_counter += 1
        await loading.edit(content='``Done\n' + 25 * '#' + '``')

        json_add('commands/for_host/silence.json', ['silenced'], False)
Пример #26
0
async def loop_6():
    json_file = loads(read('config.json'))
    put_in_box = json_file['put_in_box']
    for i in put_in_box:
        json_rem('config.json', ['put_in_box', i])
Пример #27
0
# -*- coding: utf-8 -*-
"""
By replacing each of the letters in the word CARE with 1, 2, 9, and 6 respectively, we form a square number: 1296 = 362. What is remarkable is that, by using the same digital substitutions, the anagram, RACE, also forms a square number: 9216 = 962. We shall call CARE (and RACE) a square anagram word pair and specify further that leading zeroes are not permitted, neither may a different letter have the same digital value as another letter.

Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, find all the square anagram word pairs (a palindromic word is NOT considered to be an anagram of itself).

What is the largest square number formed by any member of such a pair?

NOTE: All anagrams formed must be contained in the given text file.
"""
import sys
sys.path.append("../")
import functions as f

with open('words.txt') as f:
    w = list(map(lambda x: x.replace('"', ''), f.read().strip().split(',')))

w = sorted(w, key=len)
print(w[-1], len(w[-1]))

#sys.exit()

for x in range(1, 1000):
    print(x**2)
Пример #28
0
     if not re.match("[0-9]+", numPosts):
         print("You must specify a number.")
         continue
     print("")
     listReturn = api.listUnreadPosts(
         UserID, numPosts, None, mycursor, mydb)
     if listReturn < 0:
         continue
 while True:
     PostID = input(
         "Which post do you want to read? (B = Go Back) PostID: "
     )
     print("")
     if PostID.upper() == 'B':
         break
     readResult = api.read(PostID, UserID, mycursor,
                           mydb, 0)
     if readResult < 0:
         continue
     PostIDStack = []
     while True:
         if len(PostIDStack) == 0:
             print(
                 "Menu for PostID " + PostID +
                 ": V = Upvote/Downvote, C = Comment, P = Preview comments, B = Go Back"
             )
         else:
             print(
                 "Menu for CommentID " + PostID +
                 ": V = Upvote/Downvote, C = Comment, P = Preview Comments, B = Go Back"
             )
         postaction = input(
Пример #29
0
def PlotBulge(infile="M31_000.txt", plane="xy", contours=0, ellipse=0):

  import numpy as np
  import matplotlib.pyplot as plt
  from functions import read
  from functions import COM

  # Read in particle data
  time, total, data = read(infile)
  index = np.where(data == 3)[0]
  bulge = data[index]

  # Compute center of mass
#  time, com, vcom = COM(infile, 3, tol=0.1)

  # Correct to center-of-mass frame
  com = np.array([-377.1, 611.05, -284.5])
  print com
  pos = bulge[:, 2:5] - com

  # Project to specified plane
  if plane == 'xy':
    x1 = pos[:, 0]
    x2 = pos[:, 1]
    x = 'x'
    y = 'y'
  elif plane == 'xz':
    x1 = pos[:, 0]
    x2 = pos[:, 2]
    x = 'x'
    y = 'z'
  else:
    x1 = pos[:, 1]
    x2 = pos[:, 2]
    x = 'y'
    y = 'z'

  # Plot disk particles
  from matplotlib.colors import LogNorm
  r = 5.
  plt.hist2d(x1, x2, range=[[-r, r], [-r, r]], bins=100, norm=LogNorm())
  plt.xlabel(x+' (kpc)')
  plt.ylabel(y+' (kpc)')
  plt.colorbar()

  # Overplot contours
  if contours:
    angle = np.linspace(0, 2*np.pi, 100)
    r = np.array([0.5, 1.0, 1.5, 2.0, 3.0, 4.0])
    if plane == 'xy' and ellipse:
      e = np.array([0.06, 0.24, 0.28, 0.28, 0.23, 0.18])
      q = -1*e + 1.
      print q
      k = -0.3
    elif plane == 'xz' and ellipse:
      e = np.array([0.06, 0.22, 0.28, 0.28, 0.19, 0.18])
      q = -1*e + 1.
      print q
      k = -0.32
    elif ellipse:
      e = np.zeros(6)
      k = 0.
    for i in range(0, len(r)):
      if ellipse:
        a = r[i]/np.sqrt(1. - e[i])
        b = r[i]*np.sqrt(1. - e[i])
      else:
        a, b = r[i], r[i]
      x1, x2 = a*np.cos(angle), b*np.sin(angle)
      if ellipse:
        x1_r = x1*np.cos(k) - x2*np.sin(k)
        x2_r = x2*np.cos(k) + x1*np.sin(k)
        x1, x2 = x1_r, x2_r
      plt.plot(x1, x2, linewidth=2.0, color='k')
    for r in [0.5, 1.0, 1.5, 2.0, 3.0, 4.0]:
      a, b = r, r
      plt.plot(a*np.cos(angle), b*np.sin(angle), linewidth=2.0, color='k')

  # Show plot
  r = 5.0
  plt.axis([-r, r, -r, r])
  ax = plt.gca()
  ax.set_axis_bgcolor('black')
  plt.gca().set_aspect('equal', adjustable='box')
  plt.show()
Пример #30
0
def server_get():
    return {'info': read()}
Пример #31
0
                xs = ox - sqrt(rad*rad - pow(y - oy,2))
                xe = x
                horizontal_line = pygame.Surface((abs(xe - xs), 1), pygame.SRCALPHA)
                horizontal_line.fill((0, 0, 0, 240))
                screen.blit(horizontal_line, (xs,y))
                
                #pygame.draw.line(screen,col,(xs,y),(xe,y))
        except: pass

#----------------------Main Loop----------------------#
q = [50,50,50]
w = [110,110,110]
q = [75,116,41]
w = [37,78,124]

text = read("\Textures\Text_Earth.txt").split("\n")

texture = {}

for i in range(len(text)):
    texture[i] = []
    for j in text[i]:
        if j == "q": texture[i].append(q)
        elif j == "w": texture[i].append(w)

r = 50
ox, oy = 300, 300

clock = pygame.time.Clock()
frameCount = 0
done = False
Пример #32
0
                want = checkin(['y', 'n'])
                if want == 'y':
                    register()
                elif want == 'n':
                    close(
                        None
                    )  #процедура, которая закрывает программу. в качестве аргумента принимает строку(желательно строку, потому что проверку типа переменной я не реализовывал, ибо она еще принимает None), которую выведет при закрытии. если передаёться None - выполняет выход по стандарту.
                else:
                    pass

            print(
                Fore.GREEN + '[ID FOUND]\n', '[' +
                datetime.datetime.now().strftime('%d.%m.%Y %H:%M%S') + ']',
                'sy$tem: enter your password' + Fore.BLUE)
            nov = checkfor(
                read(client, 9), client
            )  #это максимально криво, но исправлять мне пока лень. просто объяснить, как она работает я не могу, потому что и сам понятия не имею. вообще, она проверяет пароль для входа, ну да ладно. посмотри fynctions.py, там я хотя-бы объясню, что я пытался написать. функцию read смотри в functions.py
            nov.append(
                tid
            )  #nov - список, который содержит данные о пользователе, в качестве собственных элементов: 1 - подтверждён ли вход(хз зачем, он по-любому будет подтверждён, в другой ситуации, этот блок просто не выполнится), 2 - ник пользователя(именно ник), 3 - id пользователя. (пока без понятия зачем, но не буду же я каждый раз вытаскивать это из файла, если понадобиться.)
            if nov[0]:  #наконец-то, осле горы всего тог говна, что ты повидал выше, ты добрался до клиента. именно здесь должна быть та часть программы, которая должна якобы что-то делать, но на самом деле, она будет крать пароли.пока что я еще ничего не придумал.была идея с чатом, но там столько ошибок, что мне лучше заново что-то придумать, чем исправить их.
                '''print(Fore.GREEN + '{ YOU ARE WELCOME! :) }\n\n' + '1>start_chat()\n2>my_profile()')
                col = checkin(['1', '2'])
                if col == '1':
                    print('\n\n1>run_server()\n2>run_client()')
                    rel = checkin(['1', '2'])
                    if rel == '1':
                        server()
                    elif rel == '2':
                        client()
                    else:
Пример #33
0
        x = x + (0 - z) * (x - e.x) / (z - e.z)
    except:
        x = c.x
    try:
        y = y + (0 - z) * (y - e.y) / (z - e.z)
    except:
        y = c.y

    x += xSize / 2
    y = ySize / 2 - y

    if z <= e.z: return "error"
    return int(x), int(y)


stars_txt = read("\Stars.txt").split("\n")

stars = {}
stars["num"] = 0

for txt in stars_txt:
    stars["name{0}".format(stars["num"])] = txt[:12]
    stars["mag{0}".format(stars["num"])] = float(txt[35:39])
    stars["ra{0}".format(stars["num"])] = int(
        txt[40:42]) + int(txt[43:46]) / 60 + float(txt[49:54]) / 3600
    stars["dec{0}".format(stars["num"])] = float(txt[56:59]) + float(
        txt[56] + txt[61:63]) / 60 + float(txt[56] + txt[65:69]) / 3600
    stars["dist{0}".format(stars["num"])] = float(txt[71:])
    stars["num"] += 1

#print(stars["name0"],stars["mag0"],stars["ra0"],stars["dec0"],stars["dist0"])
Пример #34
0
##############################################
### Read values from files and print these
### continues to the terminal for monitoring
##############################################

import time as timeModule
import os
import pandas as pd
from functions import read

path = 'data/'

# main loop
while (True):
    time = read(path + 'time.txt')
    gameName = read(path + 'gameName.txt')
    homeTeamName = read(path + 'homeTeamName.txt')
    awayTeamName = read(path + 'awayTeamName.txt')
    homeScore = read(path + 'homeScore.txt')
    awayScore = read(path + 'awayScore.txt')
    homeFouls = read(path + 'homeFouls.txt')
    awayFouls = read(path + 'awayFouls.txt')

    df = pd.DataFrame([
        gameName, time, homeTeamName, awayTeamName, homeScore, awayScore,
        homeFouls, awayFouls
    ])
    df.index = [
        'Game', 'Time', 'Home team', 'Away team', 'Home score', 'Away score',
        'Home fouls', 'Away fouls'
    ]
Пример #35
0
        cond = input()

        # asking whether user wants to provide the key with time-to-live property or not
        if cond == 'y':
            print(
                "Enter how long should the key be active (time in seconds) : ")
            time = int(input())
            functions.create(key, value, time)
        else:
            functions.create(key, value)
        functions.save()

    elif operation == 2:
        print("Enter the Key to read the value : ")
        key = input()
        print(functions.read(key))
        functions.save()

    elif operation == 3:
        print("Enter the Key to be deleted : ")
        key = input()
        functions.delete(key)
        functions.save()

    elif operation == 4:
        functions.save()

    elif operation == 5:
        functions.save()
        functions.printData()
Пример #36
0
##############################################
### Get gameId from API. Save it to gameId.txt
##############################################

# import modules
import websocket
import json
import time
from functions import read, write, reset_score, initial_call

initial_call()

# setup variables
path = 'data/'
url = read('apiURL.txt')
gameId = ''
ignorList = []
singleCourt = True

# make subscribe message
subscribe = {}
subscribe['apiName'] = "TvFeedApiV3"
subscribe['apiCommand'] = "subscribe"
subscribe['apiKey'] = read('apiKey.txt')
subscribe['requestId'] = "test connection"
subscribe['eventId'] = read('eventId.txt')

# setup WebSocket
ws = websocket.WebSocket()

# start ws connection
Пример #37
0
from functions import read
from pyperclip import copy
'''ещё один инструмент разработчика.
ты просто вводишь нужный id, а он копирует тебе пароль.
снова, для тесто самое то.'''
copy(read('users/' + input() + '.txt', 9))
Пример #38
0
async def atrol(ctx):
    await ctx.message.delete()
    if not vrb.adm_role in ctx.author.roles:
        await ctx.send('Nie masz uprawnień')
        return

    json_file = loads(read('config.json'))
    excluded = json_file['autoroles']['excluded']

    def send(upper, lower, embed=False, funkcyjne=False):
        embeds = []
        desc_counter = 0
        for i in search_in_list(ctx.guild.roles[::-1], upper, lower)[1:-1]:
            if i.id in excluded: continue
            if embed:
                e = Embed(color=i.color,
                          name=i.name,
                          timestamp=datetime.utcnow())
                e.add_field(name=i.name,
                            value=f'*hex* - ``{str(i.color).upper()}``')
                e.set_footer(text=f'-={i.name}=-', icon_url=ctx.guild.icon_url)
            else:
                if funkcyjne:
                    if desc_counter == 0:
                        e = f'Rola pokazująca twoją przynależność do grupy dzidowców\n**{i.name}** - *{i.color}*'
                    if desc_counter == 1:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -hug\n**{i.name}** - *{i.color}*'
                    if desc_counter == 2:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -kiss\n**{i.name}** - *{i.color}*'
                    if desc_counter == 3:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -boop\n**{i.name}** - *{i.color}*'
                    if desc_counter == 4:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -pat\n**{i.name}** - *{i.color}*'
                    if desc_counter == 5:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -lick\n**{i.name}** - *{i.color}*'
                    if desc_counter == 6:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć komendy -nom\n**{i.name}** - *{i.color}*'
                    if desc_counter == 7:
                        e = f'Jeżeli masz tą rolę, nie można na tobie użyć żadnej z komend <@614628305047388161>a\n**{i.name}** - *{i.color}*'
                    if desc_counter == 8:
                        e = f'Jeżeli masz tą rolę, osoby przeciwnej płci nie mogą na tobie użyć <@614628305047388161>a\n**{i.name}** - *{i.color}*'
                    if desc_counter == 9:
                        e = f'Jeżeli masz tą rolę, osoby tej samej płci nie mogą na tobie użyć <@614628305047388161>a\n**{i.name}** - *{i.color}*'
                    if desc_counter == 10:
                        e = f'Weź tą rolę jeżeli jesteś rysownikiem, czasem jest pingowana gdy ktoś chce kupić arta\n**{i.name}** - *{i.color}*'
                    if desc_counter == 11:
                        e = f'Jeżeli posiadasz Fursuita, ta rola jest dla ciebie :3\n**{i.name}** - *{i.color}*'
                    if desc_counter == 12:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#531261766634831873>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 13:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#531261813749448755>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 14:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#531261855302418433>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 15:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#531268391760297995>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 16:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#531268417811120148>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 17:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#541394633306144781>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 18:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#672514951704870932>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 19:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#541395282336808994>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 20:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#542336916973027341>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 21:
                        e = f'Rola ta daje dostęp do kanału **NSFW** <#622056811440242698>\n**{i.name}** - *{i.color}*'
                    if desc_counter == 22:
                        e = f'Rola ta daje dostęp do WSZYSTKICH kanałów **NSFW**\n**{i.name}** - *{i.color}*'
                    if desc_counter == 23:
                        e = f'Role poniżej odnoszą się do twojej orientacji seksualnej, jeżeli nie chcesz jej specjalnie ujawniać weź "I tak nie zarucham"\n**{i.name}** - *{i.color}*'
                    if desc_counter == 24: e = f'**{i.name}** - *{i.color}*'
                    if desc_counter == 25: e = f'**{i.name}** - *{i.color}*'
                    if desc_counter == 26: e = f'**{i.name}** - *{i.color}*'
                    if desc_counter == 27: e = f'**{i.name}** - *{i.color}*'
                    desc_counter += 1
                else:
                    e = f'**{i.name}** - *{i.color}*'
            embeds.append(e)
        return embeds

    chan = ctx.channel
    await chan.send(
        '``==================``\n   **Pokaż w co grasz**\n``==================``'
    )
    upper = vrb.dividing_games
    lower = vrb.dividing_channels
    embed = False

    embeds = send(upper, lower)
    for e in embeds:
        if embed: message = await chan.send(embed=e)
        else: message = await chan.send(e)

        await message.add_reaction('☑')
        try:
            await client.wait_for('reaction_add', timeout=5.0)
        except:
            await message.add_reaction('☑')

    await chan.send(
        '``================``\n  **Role od kolorów**\n``================``')
    upper = vrb.dividing_colors
    lower = vrb.dividing_forfun
    embed = True

    embeds = send(upper, lower, embed)
    for e in embeds:
        if embed: message = await chan.send(embed=e)
        else: message = await chan.send(e)

        await message.add_reaction('☑')
        try:
            await client.wait_for('reaction_add', timeout=5.0)
        except:
            await message.add_reaction('☑')

    await chan.send(
        '``========================================``\n   **Role funkcyjne, dające dostęp do kanałów\n           lub pozwalające na ich oznaczenie**\n``========================================``'
    )
    upper = vrb.dividing_channels
    lower = get(ctx.guild.roles, name='@everyone')
    embed = False

    embeds = send(upper, lower, funkcyjne=True)
    for e in embeds:
        if embed: message = await chan.send(embed=e)
        else: message = await chan.send(e)

        await message.add_reaction('☑')
        try:
            await client.wait_for('reaction_add', timeout=5.0)
        except:
            await message.add_reaction('☑')
Пример #39
0
    login_ui.btn_login.clicked.connect(f.login_click)

    #--------------chat window
    ui.btn_send.clicked.connect(f.send_click)
    ui.btn_voip.clicked.connect(f.voip_click)
    ui.input_space.pressed.connect(f.input_space)
    ui.input_space.released.connect(f.input_space_released)


#------------initial parameter
run = True
pressed = False
#------------setting up UI/UI functions
app = QtWidgets.QApplication(sys.argv)
login_window = QtWidgets.QMainWindow()
login_ui = Ui_login_window()
login_ui.setupUi(login_window)

window = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(window)

f.draw_chatlog()
connect_functions()

#------------instantiate
client = Client()

with open('32byteskey.pem', mode='rb') as f:
    key = f.read()
aes = AES.new(key, AES.MODE_ECB)
Пример #40
0
async def wulg(ctx):
    json_file = loads(read('config.json'))
    wulg = json_file['counters']['bad_words']
    await ctx.send(f'Ilość wulgaryzmów jakie udało mi się odnotować to {wulg}')