def handler(self,matchlist): host = matchlist[0] target = matchlist[1] if matchlist[1] != self.head.nickname else nick(host) text = matchlist[2] t = matchlist[2].split(" ") if (t[0] == "tikkle"): if (len(t) > 2): if (t[1] == "hi"): try: r = re.match(list2string(t[2:]),"") except Exception as inst: self.head.sendErr(target,inst) else: if nick(host) in self.tikklers: x = self.tikklers[nick(host)] x.regex = list2string(t[2:]) self.head.sendNotice(nick(host),"Ok "+ x.name + ", regex updated.") else: self.tikklers[nick(host)] = tikkleuser(nick(host),list2string(t[2:])) self.head.sendNotice(nick(host),"Welcome to tikkle.") if (t[1] == "friend"): try: if (self.tikklers[t[2]] not in self.tikklers[nick(host)].friendlist): self.tikklers[nick(host)].friendlist.append(self.tikklers[t[2]]) self.head.sendNotice(nick(host),"Friend added.") else: self.tikklers[nick(host)].friendlist.remove(self.tikklers[t[2]]) self.head.sendNotice(nick(host),"Friend deleted.") except KeyError: self.head.sendNotice(nick(host),"Couldn't befriend you. Either you or " + t[2] + " isn't registered.") if (t[1] == "tikkle"): try: self.tikklers[t[2]].mailbox.append([datetime.datetime.now(),"<" + nick(host) + "> " + list2string(t[3:]) if len(t) > 2 else "*tikkle*"]) self.head.sendNotice(nick(host),"Message sent.") except Exception: self.head.sendNotice(nick(host),"Couldnt send message. Either you or the target isnt registered.") if nick(host) in self.tikklers: x = self.tikklers[nick(host)] if re.match(x.regex,text) and (x.name in nick(host)): target = nick(host) self.head.sendNotice(nick(host),"Hi.") x.greet(text) for y in x.friendlist: self.head.sendNotice(nick(host),y.greettime.strftime("%A@%H:%M") + " <" + y.name + "> " + y.greeting) for y in x.mailbox: self.head.sendNotice(target,y[0].strftime("%d %b@%H:%M") + " " + y[1]) x.mailbox = [] self.exportconf()
def handler(self, matchlist): self.head.sendMsg( matchlist[1], "Du solltest dich " + self.regexdecide(list2string(matchlist[2:]), num=asciicount("*!*" + ident(matchlist[0]))) + " entscheiden.", )
def saveParam(x, indGen, indX, standard=False): """Save the variable vector X as a delimited textfile This keeps the full record of the optimisation process and allows the multi-processing for each individual in a single generation. """ x = mirrorX(x) if standard == False: folderName = "result/optimizerCPG/" + "G" + str(indGen) + "/X" + str(indX) os.mkdir(folderName) else: folderName = 'param' operatorStr = list2string(x[0]) + "\n" + list2string(x[1]) + "\n" + list2string(x[2]) with open(folderName+"/operators.txt", "w") as outFile: outFile.write(operatorStr) if __OP_BETA__ == True: return pdStr = list2string(x[3]) + "\n" + list2string(x[4]) with open(folderName+"/pd.txt", "w") as outFile: outFile.write(pdStr)
def role_abusers(channel, max_roles=max_roles_allowed_default): abusers = [] for member in channel.members: if len(member.roles) > max_roles: print('a role abuser! %s' % member) abusers.append(member.id) if len(abusers) > 0: msg = 'The role abusers that can view this channel are: ' msg += list2string(abusers, prefix='<@', suffix='>') return msg else: return 'No abusers here!'
def multiping(self, roles, author=None): must_ping = [] if author is None: author_tag = 'Unknown' else: author_tag = '<@%s>' % author.id for member in self.guild.members: member_counter = 0 member_tagable = '<@%s>' % member.id for role in member.roles: # if the member owns one of the roles if str(role).upper() in roles: member_counter += 1 if member_counter == len(roles): # if the member has ALL the required roles must_ping.append(member_tagable) if len(must_ping) != 0: response = '%s has pinged %s' % (author_tag, list2string(must_ping)) else: response = 'Didnt find anyone with those roles' return response
def dlsplot(filenames, fitfun, start=0, fallOff=0, log=False, noPlot=False, plotCorr=True, plotMeanCR=True, plotCoherence=True, plotGamma=True, plotHydroR=True, plotmode=plt.plot): """ Wraps up all plotting functions into one interface. Attention: Setting no-plot to true overrides all plotting options. """ if noPlot: plotCorr = False plotMeanCR = False plotCoherence = False plotGamma = False sample = readElementsAndProcess(filenames, fitfun, start, fallOff, plotCorr) sample.changePlotMode(plotmode) print(sample.coeffs) if plotMeanCR: sample.plotMeanCRsDLS() if plotCoherence: sample.plotCoherenceFactor() if plotGamma: rad = sample.plotGammaAndFit() print("Hydrodynamic Radius by linear fit:", rad) if plotHydroR: sample.plotHydrodynRadius() # Logging Mechanism: Prepares results for reading out via origin/other # data evaulation programs if log: txpath = sample.path + PSEP + sample.samplename + "log.asc" with open(txpath, "w+") as txfile: # Writes Header, containing information about sample angles = ut.list2string(sample.angles) qSqu = ut.list2string(sample.qSqu) columnTitles = "Delay Time\t" + "Autocorrelation g2-1\n" txfile.write(columnTitles) comments = "# Parameters: Wavelength Viscosity Temperature" \ + " Ref. Ind Angles q^2\n" txfile.write(comments) header = str(sample.wavelength) + "\n" \ + str(sample.visc) + "\n" \ + str(sample.temp) + "\n" \ + str(sample.refInd) + "\n" header += "\\\t" + "\t".join(angles) + "\n" \ + "\\\t" + "\t".join(qSqu) + "\n" # + "q^2\t" + ut.list2string(sample.qSqu) + "\n" txfile.write(header) # assumes delay times are equal for every data entry in the sample delayTimes = ut.list2string(sample.dataObjs[0].delay) for i in range(len(delayTimes)): entry = [str(data.akf[i]) for data in sample.dataObjs] txfile.write(delayTimes[i] + "\t" + "\t".join(entry) + "\n") # writes mean Countrate data to separate file pathmeanCR = sample.path + PSEP + sample.samplename + "CR.asc" with open(pathmeanCR, "w+") as crfile: angles = ut.list2string(sample.angles) columnTitles = "\t".join(angles) + "\n" crfile.write(columnTitles) print(sample.meanCRs) crs = ut.list2string(sample.meanCRs) crfile.write("\t".join(crs) + "\n") return sample
def handler(self,matchlist): host = matchlist[0] target = matchlist[1] if matchlist[1] != self.head.nickname else nick(host) text = matchlist[2] t = matchlist[2].split(" ") matches = [] # factoid-matching :s if (t[0] == "factoid"): if (len(t) > 2): if ((t[1] == "set") and (t[1] == "add")): try: r = re.match(list2string(t[2]),"") except Exception as inst: self.head.sendErr(target,inst) else: # add factoid try: mm = re.match("factoid set \/(.+)\/ (.+)",list2string(t[0:])) regex = mm.group(1) reaction = mm.group(2) cre = re.compile(regex) self.factoids.append( (cre, reaction ) ) if (self.head.mainchannel.isOp(nick(host))): self.head.sendMsg(target,"Okay, "+ nick(host)+".") else: self.head.sendMsg(self.head.mainchannel.name, "Added [%s] %s »%s« via non-op" % ((len(self.factoids)-1), t[2], list2string(t[3:])) ) except: self.head.sendMsg(target,"Invalid Regex, "+ nick(host)+" :<") elif (t[1] == "get"): gets = [ "[%s] %s -> %s" % (i, cre.pattern, subst) for i, (cre, subst) in enumerate(self.factoids) if t[2] in cre.pattern ] if len(gets): answer = list2string(gets,', ') if (len(answer) > 300): answerlist = textwrap.wrap(answer,300) for ans in answerlist: self.head.sendMsg(target, ans) else: self.head.sendMsg(target, answer ) else: self.head.sendMsg(target, "No match..") elif (t[1] == "find"): gets = [ "[%s] %s -> %s" % (i, cre.pattern, subst) for i, (cre, subst) in enumerate(self.factoids) if t[2] in subst ] if len(gets): answer = list2string(gets,', ') if (len(answer) > 300): answerlist = textwrap.wrap(answer,300) for ans in answerlist: self.head.sendMsg(target, ans) else: self.head.sendMsg(target, answer ) else: self.head.sendMsg(target, "No match..") elif (t[1] == "num"): if (int(t[2]) <= len(self.factoids)): f = self.factoids[int(t[2])] gets = "[%s] %s -> %s" % (t[2], f[0].pattern, f[1]) self.head.sendMsg(target, gets) else: self.head.sendMsg(target, "No match..") elif (t[1] == "list"): # 400 max., so we should split here :< self.head.sendMsg(target, "I know %s factoids:" % (len(self.factoids)) ) gets = list2string ( [ "[%s] %s -> %s" % (i, cre.pattern, subst) for i, (cre, subst) in enumerate(self.factoids) ] ) self.head.sendMsg(target, gets) elif ((t[1] == "del") or (t[1] == "rem")) and (self.head.mainchannel.isOp(nick(host))) and (int(t[2]) <= len(self.factoids)) : del(self.factoids[int(t[2])]) self.head.sendMsg(target, "Done.") elif (randint(0,100) < self.factoidprobability): # give factoid for cre, subst in self.factoids: m = cre.search(text) if m: tmp = cre.sub(subst, m.group(0)) matches.append( tmp ) if (len(matches) > 0): # and (len(t[1:]) > 15) and (len(t) > 3): rply = matches[randint(0,len(matches)-1)].replace("$who", nick(host)) # choose random factoid, regard replacement of $who rply = rply.replace("$someone",random.choice(bot.mainchannel.nicklist.keys())) # replace $someone with ..someone ;) rply = rply.replace("\n","\\n") # output validation :) if rply.startswith("A:"): # reactions starting with "A:" will be send as /me self.head.sendAction(target, rply[2:]) # strip first two chars else: self.head.sendMsg(target, rply) # except ValueError: # pass #print(list2string(matches,",")) matches = [] self.exportconf()
def readFramesSquare(directory, squareSize=10, logging=True, skipStart=(0, 0), skipEnd=(0, 0)): """ Accepts directory as input, reads out all the frames in the folder, divides the frame evenly into squares (1 square = 1 speckle), then reads out the mean intensity of the square. Writes the Intensity of every speckle in every frame in a log file (if log is true) and outputs an Ensemble object containing the found speckles. input: directory: string, Directory containing the frames. squareSize: int, Length of each square side in pixel. skipStart: tuple consisting of int, skips the first squares in (x, y) direction. skipEnd: tuple, consisting of int, skips the last squares in (x, y) direction. logging: controls creating a log file output: ens: Ensemble object, containing the speckles found in the picture. """ # Sorts frames by frame number. Frame numbers equals to timestep number. # Frames have to be sorted in order to correctly order akf. frames = [ frame for frame in os.listdir(directory) if ut.match(r"\.bmp$", frame) ] frames = sorted(frames, key=keyfunc) if frames == []: raise ValueError("Error: Could not find any frames in the given" + "directory. Aborting.") print("Found data: \n" + "\n".join(frames)) # is used in the for loop for initiliation steps. assumes all frames # have equal dimensions (which they should have!) firstFlag = True count = 0 xskipStart, yskipStart = skipStart xskipEnd, yskipEnd = skipEnd # processing of each frame for f in frames: # count used to show processing progress and to number the images count += 1 print("Reading Frame No." + str(count) + "...") # reads image out to a numpy matrix, dimensions are img length path = os.path.join(directory, f) imgMat = cv2.imread(path, 0) # ----------------------------------------------------------------------------- # Initiliazing log data headers and the lists that hold the data. if firstFlag: width = len(imgMat) height = len(imgMat[1]) if width % squareSize != 0 or height % squareSize != 0: raise TypeError("Detector not divisble into even squares. " + "Change Square Size to proceed.") # Determines the number of squares in both horizontal and vertical # direction numSquaresWidth = width // squareSize - xskipStart - xskipEnd numSquaresHeight = height // squareSize - yskipStart - yskipEnd # Initiliazes numpy array that later holds the intensity values for # every speckle. Weird notation: simply creates a numpy array # with dimensions of number of squares, every single element # being an empty list. speckleInt = np.empty((numSquaresWidth, numSquaresHeight), dtype=np.object_) speckleInt.fill([]) speckleInt = np.frompyfunc(list, 1, 1)(speckleInt) # writes header for log data. Array filled with empty lists. # Log data is not meant to be human readable, but rather for use # with table calculation programs such as origin if logging: # log data for time intensity of every speckle numSpeckles = numSquaresWidth * numSquaresHeight logfilename = directory + ".asc" with open(logfilename, "w+") as log: speckleString = "\t".join( ["Speckle %d" % i for i in range(numSpeckles)]) log.write("Im. No." + "\t" + speckleString + "\n") # initializing finished firstFlag = False # ----------------------------------------------------------------------------- # prepares list of intensities so writing to log is easier intensityList = [] # divides the frame into squares and writes # the mean intensity of the square into the speckleInt matrix for x in range(xskipStart, numSquaresWidth - xskipEnd): for y in range(yskipStart, numSquaresHeight - yskipEnd): pixelInts = imgMat[x * squareSize:(x + 1) * squareSize, y * squareSize:(y + 1) * squareSize] meanInt = pixelInts.mean() speckleInt[x, y].append(meanInt) intensityList.append(meanInt) if logging: with open(logfilename, "a") as log: intensityString = str(count) + "\t" \ + "\t".join(ut.list2string(intensityList)) \ + "\n" log.write(intensityString) # speckleInt now contains the intensity lists of every speckle in x,y # directions. An Ensemble can be initiliazed and then filled with # all the speckles, that are created with the speckle intensities and then # accumulated in a list. speckleList = [] speckleIAKFS = [] print("Creating Speckles...") for x in range(xskipStart, numSquaresWidth - yskipEnd): for y in range(yskipStart, numSquaresHeight - yskipEnd): speck = Speckle(speckleInt[x, y]) speckleList.append(speck) if logging: speckleIAKFS.append(ut.list2string(speck.getTimeIAKF())) # print("Writing logs...") # if logging: # # log data for IAKF of every speckle # logfilenameIAKF = directory + "IAKF.asc" # with open(logfilenameIAKF, "w+") as log: # speckleString = "\t".join(["Speckle %d" % i # for i in range(numSpeckles)]) # log.write("Im. No." + "\t" + speckleString + "\n") # numbering = [str(i) for i in range(len(speckleIAKFS[0]))] # speckleIAKFS.insert(0, numbering) # log.write(ut.alternateWrite(speckleIAKFS)) print("Creating Ensemble...") ens = Ensemble() ens.addSpeckle(speckleList) print("Calculating Ensemble AKFs...") ens.updateEnsemble() print("Finished.") return ens
async def on_message(self, message): channel = message.channel me = message.guild.me if message.author.id == owner_id: print('The boss spoke!', message.content) self_chat = False elif message.author.id == bot_id: print('I sent something in chat:{0.author}@{0.guild}: {0.content}'.format(message)) self_chat = True else: print('{0.author}@{0.guild}: {0.content}'.format(message)) self_chat = False if message.content.upper().startswith('-K HELP'): embed = discord.Embed(title='HELP!', description='Use -k [command], it is **not** case sensitive, ignore the brackets', color=embed_color(90, 2, 153)) embed.add_field(name='Roll me d[number], d[number]', value='Rolls dice for you') embed.add_field(name='Hit or Miss', value="I guess they never miss, huh") embed.add_field(name='Role abusers', value='Pings those pesky role abusers') embed.add_field(name='Multiping [role name], [role name] : [optional message]', value='Pings only the users which have all the roles specified, please dont @the role, that defeats the purpouse of the command') embed.add_field(name='Everyone is a [name]', value='Makes everyone\'s nicknames be whatever you want them to be') embed.add_field(name='Remove all nicknames', value='Removes everyone\'s nicknames') embed.add_field(name='Leave this server', value='Makes 10.000 copies of itself and crashes your pc') embed.set_author(name=owner_name, icon_url=owner_icon) embed.set_footer(text="do -k info for information of the bot and it's owner") await channel.send(embed=embed) if message.content.upper().startswith('-K ROLL ME '): await channel.send(roll_me(message.content)) if message.content.upper().startswith('-K ROLE ABUSERS'): await channel.send(role_abusers(channel)) if message.content.upper().startswith('-K HIT OR MISS') and not self_chat: # to prevent feedback loop embed = discord.Embed(color=embed_color(90, 2, 153)) embed.add_field(name='Hit or miss, I guess they never miss, huh?', value="You got a boyfriend, I bet he doesn't kiss ya (Mwah!)\n" "He gon' find another girl and he won't miss ya\n" "He gon' skrt and hit the dab like Wiz Khalifa") embed.set_image(url='https://media.discordapp.net/attachments/556724686986412062/617090967593287681/69374585_2564780656920223_5606205212147580928_n.png?width=298&height=364') await channel.send(embed=embed) if message.content.upper().startswith('-K INFO'): permission_names = '\n'.join(perm for perm, value in channel.permissions_for(me) if value) print('-k info has been called, here are my creds: in %s\n' % message.guild.name, permission_names) embed = discord.Embed(title='Information about me:', description=kurko_info, color=embed_color(90, 2, 153)) embed.add_field(name='Social media', value=owner_info) embed.add_field(name='Invite me!', value='[Link](%s)' % invite_link) embed.set_image(url=owner_icon) embed.set_footer(text='do -k help for command information') embed.set_author(name=owner_name, icon_url=owner_icon) await channel.send(embed=embed) if message.author.id == owner_id: print('calling http_send') http_send() if message.content.upper().startswith('-K REMOVE ALL NICKNAMES') and \ message.author.guild_permissions.administrator: permission_names = '\n'.join(perm for perm, value in channel.permissions_for(me) if value) print('been asked to remove all nicknames, here are my creds: \n', permission_names) over_me = [] for member in message.guild.members: print('checking', member) if member.nick: try: await member.edit(nick=None, reason='been asked by %s' % message.author) print(member, 'nickname removed') except discord.errors.Forbidden: print(member.nick, " is over me!, can't do it!") over_me.append(member.name) print('ppl over me', over_me) await channel.send( 'All nicknames have been removed, except those of who are above me: ' + list2string(over_me)) if message.content.upper().startswith('-K EVERYONE IS A ') and \ message.author.guild_permissions.administrator: everyone_is_a = message.content[17:] over_me = [] for member in message.guild.members: print('doing', member) try: await member.edit(nick=everyone_is_a, reason='been asked by %s' % message.author) except discord.errors.Forbidden: print(member.nick, " is over me!, can't do it!") over_me.append(member.name) print('ppl over me', over_me) await channel.send(f'Indeed, everyone is a {everyone_is_a}, except {list2string(over_me)}') print('everyone is a %s' % everyone_is_a) if message.content.upper().startswith('-K MULTIPING '): addendum_marker = len(message.content) + 1 for i in range(len(message.content)): if message.content[i] == ':': addendum_marker = i if addendum_marker != len(message.content) + 1: addendum = message.content[addendum_marker:] else: addendum = '' print(addendum) roles_pinged = message.content[13:addendum_marker-1].upper() roles_pinged = roles_pinged.split(', ') current_guild = None for guild in kurko_guilds: if guild.name == str(message.guild): current_guild = guild response = current_guild.multiping(roles_pinged, author=message.author) await channel.send(response + addendum) if message.content.upper() == '-K LEAVE THIS SERVER': if message.author.id == owner_id or message.author.guild_permissions.administrator: print('I have been asked to leave the guild %s' % message.guild) await channel.send('Goodbye!') await message.guild.leave()