def plotX(X, mu, M, N, K, r, ax): for i in range(M): if plotX.px[i]: plotX.px[i].remove() if N == 2: plotX.px[i] = ax.scatter(X[i, 0], X[i, 1], color=get_color(r[i]), marker="o") else: plotX.px[i] = ax.scatter(X[i, 0], X[i, 1], X[i, 2], color=get_color(r[i]), marker="o") for i in range(K): if plotX.pmu[i]: plotX.pmu[i].remove() if N == 2: plotX.pmu[i] = ax.scatter(mu[i, 0], mu[i, 1], color=get_color(i + K), marker="*", linewidths=5) else: plotX.pmu[i] = ax.scatter(mu[i, 0], mu[i, 1], mu[i, 2], color=get_color(i + K), marker="*", linewidths=5)
def training_function(transaction_list, players): end_of_game = is_game_finished(transaction_list) if end_of_game is True: winner = get_winner(transaction_list) else: winner = False new_state_to_remember = { 'transaction_list': transaction_list, 'color': get_color(), 'player_bids': initialize_player_bids(players) } for player in filter(lambda player: player.is_rl(), players): if end_of_game and winner == player.name: # print("player %s is winner, rewarding! " % player.name) reward = 1 elif end_of_game and winner != player.name: # print("player %s is losing, penalising! " % player.name) reward = -1 else: reward = 0 player.remember(new_state_to_remember, reward, end_of_game) player.replay() player.target_train()
def _depgraph_all(self, req): """ Produces a dependency graph including all tickets, even those which do not block other tickets and are not blocked by other tickets """ result = "" db = self.env.get_db_cnx() cursor = db.cursor() sql = "SELECT id, priority, summary FROM ticket WHERE status != 'closed' ORDER BY id DESC;" cursor.execute(sql) tickets = cursor.fetchall() for ticket in tickets: bgcolor, border = get_color(str(ticket[1]).decode('ascii','ignore')) result += "\"" + str(ticket[0]) + "\" [ URL=\"" \ + req.href.ticket(int(ticket[0])) \ + "\" fontcolor=\"#bb0000\" fillcolor=\"" + bgcolor \ + "\" color=\"" + border \ + "\" tooltip=\"" \ + ticket[2].encode('ascii', 'xmlcharrefreplace') + "\" ]\n" # Use blocked_by() from mastertickets.util blockers = blocked_by(self.env, int(ticket[0])) for blocker in blockers: # result += "\"%s\" -> \"%s\"" % (str(ticket[0]), str(blocker)) result += "\"%s\" -> \"%s\"" % (str(blocker), str(ticket[0])) return result
def priceimg(price_usd=None, color='0'): """Serve the image. The StringIO trick is from here: http://stackoverflow.com/a/10170635/576932 """ try: price_usd = float(price_usd) except ValueError: return "Error: bad USD price argument" try: color = util.get_color(color) except ValueError: return "Error: bad color argument" try: usd_per_btc = util.get_usd_per_btc() except Exception: return "Error: Mt Gox error" price_btc = price_usd / usd_per_btc img_io = util.get_image_io(price_btc, 'BTC', color) return send_file(img_io, attachment_filename='img.png')
def _depgraph_all(self, req): """ Produces a dependency graph including all tickets, even those which do not block other tickets and are not blocked by other tickets """ result = "" db = self.env.get_db_cnx() cursor = db.cursor() sql = "SELECT id, priority, summary FROM ticket WHERE status != 'closed' ORDER BY id DESC;" cursor.execute(sql) tickets = cursor.fetchall() for ticket in tickets: bgcolor, border = get_color( str(ticket[1]).decode('ascii', 'ignore')) result += "\"" + str(ticket[0]) + "\" [ URL=\"" \ + req.href.ticket(int(ticket[0])) \ + "\" fontcolor=\"#bb0000\" fillcolor=\"" + bgcolor \ + "\" color=\"" + border \ + "\" tooltip=\"" \ + ticket[2].encode('ascii', 'xmlcharrefreplace') + "\" ]\n" # Use blocked_by() from mastertickets.util blockers = blocked_by(self.env, int(ticket[0])) for blocker in blockers: # result += "\"%s\" -> \"%s\"" % (str(ticket[0]), str(blocker)) result += "\"%s\" -> \"%s\"" % (str(blocker), str(ticket[0])) return result
def test4(name): """Render results""" rcParams['figure.figsize'] = 40, 15 input_shape = [None, 176, 608, 3] dr = DataReader(*datareader_params) x = dr.get_image_data() y = dr.get_image_labels() func = np.vectorize(original_to_label) y = func(y) n, _, _, _ = x.shape model = GenSeg(input_shape=input_shape, num_classes=num_classes, load_model=name) #fourcc = cv2.VideoWriter_fourcc(*'MJPG') #out = cv2.VideoWriter('out.avi', fourcc, 20.0, tuple(input_shape[1:-1])) f = None for i in range(0, n, batch_size): batch_data = x[i:i + batch_size, :, :, :] batch_labels = y[i:i + batch_size, :, :] results = model.apply(batch_data) results = np.argmax(results, axis=-1) for img in results: colored = np.empty(input_shape[1:], dtype=np.uint8) for (idx, idy), value in np.ndenumerate(img): colored[idx, idy, :] = get_color(label_to_original(value)) if f is None: f = plt.imshow(colored) else: f.set_data(colored) plt.pause(.05) plt.draw()
def get_floor_color(self, img): flag = get_color(img, self.display) if(len(self.floor_color_buf) > 10): self.floor_color_buf.pop(0) #print(self.floor_color_buf) self.floor_color_buf.append(flag) for i in self.floor_color_buf : if(i == False): return False return True
def balimg(address=None, color='0'): """Serve image with address balance.""" try: address = float(util.get_balance(address)) except: return "Error: bad address argument" try: color = util.get_color(color) except: return "Error: bad color argument" img_io = util.get_image_io(address, 'BTC', color) return send_file(img_io, attachment_filename='img.png')
def test2(name): """Test on selected testing images""" filenames = [ 'data/image_data/testing/0000/000000.png', 'data/image_data/testing/0000/000040.png', 'data/image_data/testing/0004/000000.png', 'data/image_data/testing/0005/000020.png', 'data/image_data/testing/0005/000240.png' ] shape = (len(filenames), 176, 608, 3) n, h, w, c = shape image_data = np.zeros((n, h, w, c)) i = 0 for f in filenames: image = normalize_img(imread(f)) # Fix brightness and convert to lab colorspace image_data[i, :, :, :] = image[:h*2:2, :w*2:2, :] '''plt.figure() plt.imshow(image_data[i]) plt.figure() plt.imshow(lab2rgb(image_data[i])) plt.show()''' i += 1 model = GenSeg(input_shape=[None, h, w, c], num_classes=num_classes, load_model=name) result = model.apply(image_data) result = np.argmax(result, axis=-1) '''for img in result: plt.figure() plt.imshow(img.astype(np.uint8)) plt.show()''' colored = np.empty(shape) for (i, x, y), value in np.ndenumerate(result): colored[i, x, y] = get_color(label_to_original(value)) i = 0 for img in colored: img = img.astype(np.uint8, copy=False) imsave('%d.png' % i, img, 'png') '''plt.figure() plt.imshow(img) plt.show()''' i += 1
def as_embed(self, guild): embed = discord.Embed(color=get_color(guild.me)) embed.add_field(name="Channel", value=f"<#{self.post_channel}>") guild_roles = {i.id for i in guild.roles} roles = [f"<@&{i}>" for i in self.roles if i in guild_roles] roles = "\n".join(roles) if roles else "None" embed.add_field(name="Roles", value=roles) option_text = f"{'✅' if self.options.reveal_invites else '❎'} **Reveal Invites**" option_text += f"\n{'✅' if self.options.ping_target else '❎'} **Ping Target**" embed.add_field(name="Options", value=option_text) embed.add_field(name="Custom Prefix", value=self.prefix) embed.add_field(name="Count Offset", value=self.offset + 1) return embed
def run(self, training_function=None): transaction_list = [] players = self.players end_of_game = False if len(players) > 0 else True while not end_of_game: color = get_color() transaction_list = self.play_round(players, color, transaction_list) end_of_game = is_game_finished(transaction_list) if end_of_game is True: winner = get_winner(transaction_list) else: winner = False if training_function is not None: training_function(transaction_list, players) return {'transaction_list': transaction_list, 'winner': winner}
def priceimgadv(): """Serve the image, with advanced options. The StringIO trick is from here: http://stackoverflow.com/a/10170635/576932 """ price_usd = request.args.get('price') currency = request.args.get('currency', 'BTC').upper() color = request.args.get('color', '0') try: price_usd = float(price_usd) except: return "Error: bad USD price argument" try: color = util.get_color(color) except: return "Error: bad color argument" if currency == 'BTC': try: usd_per_coin = util.get_usd_per_btc() except: return "Error: Mt Gox error" elif currency == 'LTC': try: usd_per_coin = util.get_usd_per_ltc() except: return 'Error: BTC-e error' else: return 'Error: unsupported currency: ' + currency price = price_usd / usd_per_coin img_io = util.get_image_io(price, currency, color) return send_file(img_io, attachment_filename='img.png')
def _depgraph(self, req, ticket, depth): self.log.debug('called depgraph(%s, %s)' % (str(ticket), str(depth))) if ticket in self._seen_tickets: return "" self._seen_tickets.append(ticket) db = self.env.get_db_cnx() cursor = db.cursor() sql = ("SELECT summary, priority FROM ticket WHERE id = %s;" \ % (str(ticket))) cursor.execute(sql) summary, priority = cursor.fetchone() if depth == 0: bgcolor = "#cceecc" border = "#00cc00" else: bgcolor, border = get_color(str(priority)) result = "\"" + str(ticket) + "\" [ URL=\"" \ + req.href.ticket(int(ticket)) \ + "\" fillcolor=\"" + bgcolor + "\" color=\"" + border \ + "\" fontcolor=\"#bb0000\" tooltip=\"" \ + summary.encode('ascii', 'xmlcharrefreplace') + "\" ]\n" if self._maxdepth > 0 and depth >= self._maxdepth: return result # Use blocked_by() from mastertickets.util blockers = blocked_by(self.env, ticket) for blocker in blockers: result += self._depgraph(req, int(blocker), depth + 1) # result += "\"%s\" -> \"%s\"\n" % (str(ticket), str(blocker)) result += "\"%s\" -> \"%s\"\n" % (str(blocker), str(ticket)) return result
def _depgraph(self, req, ticket, depth): self.log.debug('called depgraph(%s, %s)' % (str(ticket), str(depth))) if ticket in self._seen_tickets: return "" self._seen_tickets.append(ticket) db = self.env.get_db_cnx() cursor = db.cursor() sql = ("SELECT summary, priority FROM ticket WHERE id = %s;" \ % (str(ticket))) cursor.execute(sql) summary, priority = cursor.fetchone() if depth == 0: bgcolor = "#cceecc" border = "#00cc00" else: bgcolor, border = get_color(str(priority)) result = "\"" + str(ticket) + "\" [ URL=\"" \ + req.href.ticket(int(ticket)) \ + "\" fillcolor=\"" + bgcolor + "\" color=\"" + border \ + "\" fontcolor=\"#bb0000\" tooltip=\"" \ + summary.encode('ascii', 'xmlcharrefreplace') + "\" ]\n" if self._maxdepth > 0 and depth >= self._maxdepth: return result # Use blocked_by() from mastertickets.util blockers = blocked_by(self.env, ticket) for blocker in blockers: result += self._depgraph(req, int(blocker), depth+1) # result += "\"%s\" -> \"%s\"\n" % (str(ticket), str(blocker)) result += "\"%s\" -> \"%s\"\n" % (str(blocker), str(ticket)) return result
def affiliation_color(self): #return get_color(self.affiliation) for group in self.groups_list: if group.name.startswith(Group.tag_prefix): return get_color(group.name[len(Group.tag_prefix):]) return None
async def setup(message, args, **kwargs): if not message.author.guild_permissions.manage_guild: await message.channel.send( "You require the `MANAGE_GUILD` permission to use this command!" ) return configs = await get_guild_configs(message.guild.id) if not args: if not ( message.channel.permissions_for(message.guild.me).embed_links and message.channel.permissions_for(message.guild.me).attach_files ): await message.channel.send( "I require the `EMBED_LINKS` and `ATTACH_FILES` permissions to use this command!" ) return embed = discord.Embed(color=util.get_color(message.guild.me)) config_export = "None generated." files = [] if configs.guild_id: config_export = configs.export() if len(config_export) > 1024: b = BytesIO() b.write(config_export.encode("utf-8")) b.seek(0) config_export = ( "This string was too long to send. Please check the uploaded file." ) files += [discord.File(b, "config_export.txt")] embed.add_field(name="Config Export", value=config_export) guild_file = None guild_export = { "roles": [ [i.name, str(i.id), str(i.color)] for i in sorted( message.guild.roles, key=lambda x: x.position, reverse=True ) if i.id != message.guild.id ], "channels": [ [i.name, str(i.id)] for i in message.guild.text_channels if i.permissions_for(message.guild.me).send_messages ], } guild_export = encode(json.dumps(guild_export)) full_guild_export = guild_export if len(guild_export) > 2048: b = BytesIO() b.write(guild_export.encode("utf-8")) b.seek(0) guild_export = ( "This string was too long to send. Please check the uploaded file." ) files += [discord.File(b, "guild_data_export.txt")] elif len(guild_export) > 1024: embed.title = "Guild Data Export (Full code)" embed.description = guild_export guild_export = "This string was too long to put in here. Please check the long bit of text above." embed.add_field(name="Guild Data Export", value=guild_export) ret = "Welcome to the ⌚ setup!\nPlease go to https://sink.discord.bot/⌚ to generate an import code!\nRun this command with the Import config to set up the bot on this guild." if len(full_guild_export) <= 2000 and message.author.is_on_mobile(): ret += "\n\nI am detecting that you are currently on a mobile device. React to this message with ☎ (`telephone`) to receive a DM with the data that can easily be copied." msg = await message.channel.send(ret, embed=embed, files=files) if len(full_guild_export) <= 2000: def check(reaction, user): return ( reaction.message.id == msg.id and reaction.emoji.strip("\uFE0F\uFE0E") == "☎" and user.id == message.author.id ) try: reaction, user = await bot.wait_for("reaction_add", check=check) except asyncio.TimeoutError: return if reaction: try: await message.author.send(full_guild_export) except: await message.channel.send( "DM failed. Please ensure your DMs are enabled and run the command again." ) return True else: if not ( message.channel.permissions_for(message.guild.me).embed_links and message.channel.permissions_for(message.guild.me).add_reactions ): await message.channel.send( "I require the `EMBED_LINKS` and `ADD_REACTIONS` permissions to use this command!" ) return channel = None try: args = json.loads(decode(args)) args["guild_id"] = message.guild.id args["post_channel"] = configs.post_channel args["special_roles"] = [int(r) for r in args["roles"]] args["prefix"] = args["prefix"].strip()[:32] if args["prefix"] else None args["options"] = int(args["options"]) offset = 0 if not args["offset"] else args["offset"] args["_offset"] = max(0, min(2147483647, int(offset)) - 1) if not configs.guild_id: args["post_channel"] = int(args["channel"]) channel = message.guild.get_channel(args["post_channel"]) if not channel: raise ValueError except: await message.channel.send("Invalid input!") return if configs: args["offset"] = configs.offset emotes = ["✅", "❎"] args = Configs.from_row(args) msg = await message.channel.send( "Here are your imported settings! Please react with ✅ to confirm them. (You can check then again later with the `settings` command)", embed=args.as_embed(message.guild), ) for e in emotes: await msg.add_reaction(e) def check(reaction, user): return ( reaction.message.id == msg.id and reaction.emoji in emotes and user.id == message.author.id ) try: reaction, user = await bot.wait_for("reaction_add", check=check) except asyncio.TimeoutError: return if reaction.emoji == "✅": await bot.db.execute( """ INSERT INTO guild_configs ( guild_id, post_channel, prefix, options, latest_event_count, special_roles, recent_events, _offset ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT (guild_id) DO UPDATE SET prefix = EXCLUDED.prefix, options = EXCLUDED.options, special_roles = EXCLUDED.special_roles ;""", *args.db_insert(), ) bot._guild_prefix_cache[message.guild.id] = args.prefix await message.channel.send("Your settings have been updated.") else: await message.channel.send("Process aborted.") return True
async def recall(message, args, **kwargs): if not args: return configs = await get_guild_configs(message.guild.id) channel = message.guild.get_channel(configs.post_channel) if not ( configs.guild_id and channel and channel.permissions_for(message.guild.me).send_messages ): return num = configs.latest_event_count try: num = get_case_number( args, num, configs.offset ) # , allow_case_range=is_mod(message.author)) except ValueError as e: await message.channel.send(str(e)) return # if not is_mod(message.author): num = [num] resp = {} embed = None for n in num: event = await bot.db.fetchrow( "SELECT * FROM events WHERE guild_id = $1 AND event_id = $2;", message.guild.id, n, ) if not event: resp[ n ] = "!!! That event doesn't exist. You shouldn't be seeing this. Please contact the bot maintainer." continue new_entry = Event.from_row(event) entry_text = generate_entry(new_entry, configs) msg = event.get("message_id") if msg: msg = await util.get_message(bot, channel, msg) ret = None if not msg: ret = "This entry has been deleted. Please ask a mod to run this command to reinstate it." if is_mod(message.author): ret = "This entry has been reinstated." actor = await util.get_member(bot, event.get("actor")) new_entry.set_actor(actor) msg = await post_entries([new_entry], channel, configs) msg = msg[0] if msg: if (not is_mod(message.author)) or entry_text == msg.content: if len(num) == 1: embed = discord.Embed( title=ret, color=util.get_color(message.guild.me), description="\n".join( [ e if i != 0 else " | ".join( [ v if u != e.count(" | ") else f"[{v}]({msg.jump_url})" for u, v in enumerate(e.split(" | ")) ] ) for i, e in enumerate(msg.content.split("\n")) ] ), # this is so bad aaaaaaaaaaa timestamp=new_entry.timestamp, ) await message.channel.send(embed=embed) return elif is_mod(message.author): actor = await util.get_member(bot, event.get("actor")) new_entry.set_actor(actor) await update_entry(msg, new_entry, configs) ret = "This entry has been updated" if ret: resp[n] = ret if embed: await message.channel.send(embed=embed) else: await message.channel.send(resp) return True
def plot_ego_communities(graph_dict_list): for item in graph_dict_list: graph_stat_dict_list = [] for i in [-1, -2, -3, -4, -5, -6, -7]: node_and_degree = item["graph"].degree() (largest_hub, degree) = sorted(node_and_degree, key=itemgetter(1))[i] hub_ego = nx.ego_graph(item["graph"], largest_hub) temp_dict = { "pos": (i * -1), "largest_hub": largest_hub, "degree": degree } pos = nx.spring_layout(hub_ego, k=0.1) plt.rcParams.update({'figure.figsize': (15, 10)}) nx.draw_networkx(hub_ego, pos=pos, node_size=0, edge_color="#444444", alpha=0.05, with_labels=False) communities = sorted( community.greedy_modularity_communities(hub_ego), key=len, reverse=True) temp_dict["communities"] = len(communities) graph_stat_dict_list.append(temp_dict) set_node_community(hub_ego, communities) set_edge_community(hub_ego) external = [(v, w) for v, w in hub_ego.edges if hub_ego.edges[v, w]['community'] == 0] internal = [(v, w) for v, w in hub_ego.edges if hub_ego.edges[v, w]['community'] > 0] internal_color = ["yellow" for e in internal] node_color = [ get_color(hub_ego.nodes[v]['community']) for v in hub_ego.nodes ] # external edges nx.draw_networkx(hub_ego, pos=pos, node_size=0, edgelist=external, edge_color="blue", node_color=node_color, alpha=0.2, with_labels=False) # internal edges nx.draw_networkx(hub_ego, pos=pos, edgelist=internal, edge_color=internal_color, node_color=node_color, alpha=0.05, with_labels=False) print(f"Ego network for {item['name']} and {i}") plt.title(f"Ego network {largest_hub} of {item['name']}") plt.show() plt.close() json_fd = open(f"./results/communities/{item['name']}.json", "w") json.dump(graph_stat_dict_list, json_fd)