def print(self):
        away_report = TeamReport(self.dataset,
                                 self.team,
                                 self.all_opponents,
                                 filter_by='away')
        away_report.print()

        home_report = TeamReport(self.dataset,
                                 self.team,
                                 self.all_opponents,
                                 filter_by='home')
        home_report.print()

        top_6, top_4, = self.top6(), self.top4()
        top, relegation = self.league_top(), self.relegation_zone()

        color = lambda p_diff: 'green' if p_diff <= 0 else 'red'
        top_6 = colorize(top_6, color(top_6))
        top_4 = colorize(top_4, color(top_4))
        top = colorize(top, color(top))
        relegation = colorize(relegation, color(relegation))

        top_SR = self.top_table_success_rate()
        bottom_SR = self.bottom_table_success_rate()

        stats = SingleTable([[
            'League Position', 'To 1th', 'To 4th', 'To 6th',
            'To Relegation zone', 'Top table success rate',
            'Bottom table success rate'
        ], [
            self.team_pos + 1, top, top_4, top_6, relegation, top_SR, bottom_SR
        ]])
        print(stats.table)
Exemple #2
0
    def act_limits(self, act_limits):
        """Sets the action limits that are used for scaling the actions that are
        returned from the gaussian policy.
        """

        # Validate input
        missing_keys = [
            key for key in ["low", "high"] if key not in act_limits.keys()
        ]
        if missing_keys:
            warn_string = "WARN: act_limits could not be set as {} not found.".format(
                f"keys {missing_keys} were"
                if len(missing_keys) > 1 else f"key {missing_keys} was")
            print(colorize(warn_string, "yellow"))
        invalid_length = [
            key for key, val in act_limits.items() if len(val) != self._a_dim
        ]
        if invalid_length:
            warn_string = (
                f"WARN: act_limits could not be set as the length of {invalid_length} "
                + "{}".format("were" if len(invalid_length) > 1 else "was") +
                f" unequal to the dimension of the action space (dim={self._a_dim})."
            )
            print(colorize(warn_string, "yellow"))

        # Set action limits
        self._act_limits = {
            "low": act_limits["low"],
            "high": act_limits["high"]
        }
        self.ga.act_limits = self._act_limits
    def colorize_report(self, report):
        result = []

        for i, data in enumerate(report):
            result.append([data[0]])

            if self.team_index[i] == 0:
                _team, _opponent = 0, 1
            elif self.team_index[i] == 1:
                _team, _opponent = 1, 0

            for i in range(len(data) - 1):
                stats = data[i + 1].split('-')

                if len(stats) < 2:
                    if data[i + 1] == 'D':
                        col = 'white'
                    elif data[i + 1] == 'H':
                        col = self.color if _team == 0 else 'red'
                    elif data[i + 1] == 'A':
                        col = self.color if _team == 1 else 'red'

                    result[-1].insert(i + 1, colorize(data[i + 1], color=col))
                    continue

                team_stat = colorize(stats[_team].strip(), color=self.color)
                opponent_stat = stats[_opponent].strip()
                if _team == 0:
                    result[-1].insert(
                        i + 1, "{0} - {1}".format(team_stat, opponent_stat))
                elif _team == 1:
                    result[-1].insert(
                        i + 1, "{0} - {1}".format(opponent_stat, team_stat))

        return result
Exemple #4
0
def LogProgress(model, writer, test_loader, epoch):
    model.eval()
    sequential = test_loader
    sample_batched = next(iter(sequential))
    image = torch.autograd.Variable(sample_batched['image'].cuda())
    depth = torch.autograd.Variable(
        sample_batched['depth'].cuda(non_blocking=True))
    if epoch == 0:
        writer.add_image('Train.1.Image',
                         vutils.make_grid(image.data, nrow=6, normalize=True),
                         epoch)
    if epoch == 0:
        writer.add_image(
            'Train.2.Depth',
            colorize(vutils.make_grid(depth.data, nrow=6, normalize=False)),
            epoch)
    output = DepthNorm(model(image))
    writer.add_image(
        'Train.3.Ours',
        colorize(vutils.make_grid(output.data, nrow=6, normalize=False)),
        epoch)
    writer.add_image(
        'Train.3.Diff',
        colorize(
            vutils.make_grid(torch.abs(output - depth).data,
                             nrow=6,
                             normalize=False)), epoch)
    del image
    del depth
    del output
Exemple #5
0
	def logout(self):
		print utils.colorize('Logging out of ' + self.current_user.name + '. You can log in to a diferent account now.', "YELLOW")
		self.logged_in = False
		self.current_user = None
		self.display_name = ">"
		self.api = None
		self.auth = tweepy.OAuthHandler(utils.CONSUMER_KEY, utils.CONSUMER_SECRET)
Exemple #6
0
	def get_home_timeline(self):
		print utils.colorize("Fetching latests tweets, please wait.....", "YELLOW")
		statuses = self.api.home_timeline(count=20)
		statuses = reversed(statuses)
		print "Twitter timeline: last updated at " + datetime.now().strftime("%A, %d/%m/%Y %I:%M%p")
		for status in statuses:
			self.print_status(status)
		print "|" + "_"*78 + "|"
Exemple #7
0
	def print_status(self, status):
		print "|" + "_"*78 + "|"
		print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
		lines = utils.split_tweet(status.text)
		for line in lines:
			print line
		timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
		print utils.add_symbol(timestamp, 90)
Exemple #8
0
	def complete_login(self):
		self.logged_in = True
		self.auth.set_access_token(self.current_user.key, self.current_user.secret)
		self.api = tweepy.API(self.auth)
		self.display_name = self.current_user.name + " "
		self.clear()
		print_text.header_user(self.current_user.name)
		print utils.colorize("You have successfully logged in!", "GREEN")
def validate_req_sio(req_sio, sio_array, refs_array):
    """Validates whether the requested states of interest exists. Throws a warning
    message if a requested state is not found.

    Args:
        req_sio (list): The requested states of interest.

        sio_array (numpy.ndarray): The array with the states of interest.

        refs_array (numpy.ndarray): The array with the references.

    Returns:
        tuple: Lists with the requested states of interest and reference which are
            valid.
    """

    # Check if the requested states of interest and references are present
    req_sio = [sio - 1
               for sio in req_sio]  # Translate indices to python format
    valid_sio, invalid_sio = validate_indices(req_sio, sio_array)
    valid_refs, invalid_refs = validate_indices(req_sio, refs_array)
    valid_sio = [sio + 1
                 for sio in valid_sio]  # Translate back to hunan format
    invalid_sio = [sio + 1 for sio in invalid_sio]
    valid_refs = [ref + 1 for ref in valid_refs]
    invalid_refs = [ref + 1 for ref in invalid_refs]

    # Display warning if not found
    if invalid_sio and invalid_refs:
        warning_str = ("{} {} and {} {}".format(
            "states of interest"
            if len(invalid_sio) > 1 else "state of interest",
            invalid_sio,
            "references" if len(invalid_refs) > 1 else "reference",
            invalid_refs,
        ) + " could not be plotted as they did not exist.")
        print(colorize("WARN: " + warning_str.capitalize(), "yellow"))
    elif invalid_sio:
        warning_str = "WARN: {} {}".format(
            "States of interest"
            if len(invalid_sio) > 1 else "State of interest",
            invalid_sio,
        ) + " could not be plotted as {} does not exist.".format(
            "they" if len(invalid_sio) > 1 else "it", )
        print(colorize(warning_str, "yellow"))
    elif invalid_refs:
        warning_str = "WARN: {} {}".format(
            "References" if len(invalid_refs) > 1 else "Reference",
            invalid_refs,
        ) + " {} not be plotted as {} does not exist.".format(
            "could" if len(invalid_refs) > 1 else "can",
            "they" if len(invalid_refs) > 1 else "it",
        )
        print(colorize(warning_str, "yellow"))

    # Return valid states of interest and references
    return valid_sio, valid_refs
 def do_intro(self):
     """
     Does any start-of-game actions for the player. Initializing GameState variables
     should be done in the __init__ function
     """
     lines = [
         "Welcome to your text game!",
         "To view the help screen, type `h` or `help`."
     ]
     print colorize('\n'.join(lines), 'yellow')
Exemple #11
0
def log_images(img, depth, pred, args, step):
    depth = colorize(depth, vmin=args.min_depth, vmax=args.max_depth)
    pred = colorize(pred, vmin=args.min_depth, vmax=args.max_depth)
    wandb.log(
        {
            "Input": [wandb.Image(img)],
            "GT": [wandb.Image(depth)],
            "Prediction": [wandb.Image(pred)]
        },
        step=step)
Exemple #12
0
	def try_login(self, login_string):
		params = login_string.split(" ")
		if len(params) == 2:
			self.current_user = self.user_auth.login(params[1])
			if self.current_user:
				self.complete_login()
		elif params[0] == 'login':
			print utils.colorize('Command syntax incorrect. Please refer to "help" to see the correct syntax.', "B_RED")
		else:
			print utils.colorize('The command "' + login_string + '" was not recognized.', "B_RED")
Exemple #13
0
	def on_status(self, status):
		try:
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
			for line in self.status_wrapper.wrap(status.text):
				print utils.add_symbol_end(line, 80)
			timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
			print utils.add_symbol(timestamp, 90)
		except:
			print 'error'
Exemple #14
0
	def save_user(self, name, password, key, secret):
		if not self.username_exists(name):
			self.config.add_section(name)
			self.config.set(name, "password", self.encrypt_password(password))
			self.config.set(name, "key", key)
			self.config.set(name, "secret", secret)
			with open('config.cfg', 'wb') as configfile:
				self.config.write(configfile)
				print utils.colorize('User saved successfully!', "GREEN")
		else:
			print utils.colorize("User name already exists!", "RED")
Exemple #15
0
	def login(self, user_name):
		try:
			user = self.get_user(user_name)
			password = getpass.getpass('Password: '******'Username or password incorrect. Please try again.', "B_RED")
				return None
		except:
			print utils.colorize('An error ocurred. Please try again.', "RED")
			return None
Exemple #16
0
def get_away_team_stats(game):
    stats = game[[3, 5, 4, 6, 11, 13]]

    points = 0
    if stats[3] == 'H':
        stats[3] = colorize('L', 'red')
    elif stats[3] == 'A':
        stats[3] = colorize('W')
        points = 3
    else:
        points = 1

    return np.append(stats, [points])
Exemple #17
0
def get_home_team_stats(game):
    stats = game[[2, 4, 5, 6, 10, 12]]

    points = 0
    if stats[3] == 'H':
        stats[3] = colorize('W')
        points = 3
    elif stats[3] == 'A':
        stats[3] = colorize('L', 'red')
    else:
        points = 1

    return np.append(stats, [points])
Exemple #18
0
    def on_status(self, status):
        try:
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(status.author.screen_name, "B_CYAN"), 90)
			for line in self.status_wrapper.wrap(status.text):
				print utils.add_symbol_end(line, 80)
			timestamp = utils.colorize("at " + status.created_at.strftime("%A, %d/%m/%y, %H:%M:%S") + " from " + status.source, "CYAN")
			print utils.add_symbol(timestamp, 90)
            #print self.status_wrapper.fill(status.text)
            #print '\n %s  %s  via %s\n' % (status.author.screen_name, status.created_at, status.source)
        except:
            # Catch any unicode errors while printing to console
            # and just ignore them to avoid breaking application.
            print 'error'
    def run(self):
        """
        Runs a loop that accepts the user's input, executes the appropriate command, and
        exits the game with an exit message when finished.
        """
        while True:
            # print out location information
            print colorize('\n%s:' % self.curr_location.name, 'cyan')
            print colorize(self.curr_location.description, 'yellow')

            try:
                user_input = capture_input()
            except QuitGame:
                break

            # the primary command is the first word in the user input
            command = user_input[0]
            try:
                command_class = ALL_COMMANDS[command]
            except KeyError:
                print colorize("Command '%s' does not exist" % command, 'red')
                continue

            # call the appropriate function
            try:
                command_class.execute(user_input, self)
            except QuitGame:
                break

            if self.finished:
                self.do_finish()
                return

        print colorize('\nExiting the game...', 'red')
Exemple #20
0
	def get_user_profile(self, user_input):
		try:
			name = user_input.split(' ')[1]
			print "Loading user....."
			user = self.api.get_user(name)
			print "|" + "_"*78 + "|"
			print utils.add_symbol(utils.colorize(user.name, "B_YELLOW"), 90)
			print "|" + " "*78 + "|"
			print utils.add_symbol(utils.colorize(" Location: " +user.location, "YELLOW"), 90)
			lines = utils.split_user_bio("Bio: " + user.description)
			for line in lines:
				print line
			print "|" + " "*78 + "|"
			print utils.add_symbol(utils.colorize(" " + str(user.statuses_count) + " tweets", "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" Followers: " + str(user.followers_count), "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" Following: " + str(user.friends_count), "YELLOW"), 90)
			print utils.add_symbol(utils.colorize(" " + str(user.favourites_count) + " tweets favorited", "YELLOW"), 90)
			print "|" + "_"*78 + "|"
			print utils.add_symbol("Loading tweets.....", 80)
			statuses = self.api.user_timeline(screen_name=name, count=20)
			print utils.add_symbol("User tweets: last updated at " + datetime.now().strftime("%A, %d/%m/%Y %I:%M%p"), 80)
			for status in statuses:
				self.print_status(status)
			print "|" + "_"*78 + "|"
		except:
			print utils.colorize('User not found', "RED")
Exemple #21
0
 def changeAnswer(self):
     if not self.started and len(self.ui.lineAnswer.text()):
         self.started = True
         self.start_time = datetime.now()
     question = self.ui.lblQuestion.text()
     answer = self.ui.lineAnswer.text()
     result = ''
     for q, a in zip(question, answer):
         if q == a:
             result += colorize(a, True)
         else:
             result += colorize(a, False)
     self.ui.lblAnswer.setText(result)
     self.ui.lblAnswer.setEnabled(True)
Exemple #22
0
def lines(state: State, place: Place) -> Tuple[str, str]:
    """
    For given member place, get the tf status line strings (two lines per member)

    <player name> <hp>/<hpmax> <hpdiff to max>
    <player state> <ep> <sp>/<spmax> <* if player is cast target>

    For example:
         Ruska  408/ 445  -37
      ldr  224 1404/1404

    :param member: member data
    :returns: Tuple of two strings for tf status lines
    """

    if place not in state.places:
        return ("                        ", "                        ")

    member = state.places[place]
    name = colorize("{0: >9}".format(member.name[:8]), nameColor(member))
    hp = colorize(
        "{0: >4}".format(member.hp),
        greenRedGradient(member.hp, member.maxhp, 200, 0.2),
    )
    maxhp = "{0: >4}".format(member.maxhp)
    hpdiff = colorize(
        "{0: >5}".format(member.hp - member.maxhp or ""), Color(0xEA, 0x22, 0x22)
    )
    memberStateTuple = getMemberState(member)
    memberState = colorize("{0: >5}".format(memberStateTuple[0]), memberStateTuple[1])
    memberIsTarget = (
        colorize("{0:4}".format("*"), YELLOW) if state.target == member.name else "    "
    )

    return (
        "{0} {1}/{2}{3}".format(
            name,
            hp,
            maxhp,
            hpdiff,
        ),
        "{0} {1: >3} {2: >4}/{3: >4} {4}".format(
            memberState,
            member.ep if member.ep is not None else "?",
            member.sp if member.sp is not None else "?",
            member.maxsp if member.maxsp is not None else "?",
            memberIsTarget,
        ),
    )
Exemple #23
0
def make_scorer(args):
    bidirectional = args.bidirectional
    enc_hidden_size = hidden_size//2 if bidirectional else hidden_size
    feature_size = FEATURE_SIZE
    traj_encoder = try_cuda(SpeakerEncoderLSTM(action_embedding_size, feature_size,
                                          enc_hidden_size, dropout_ratio, bidirectional=args.bidirectional))
    scorer_module = try_cuda(DotScorer(enc_hidden_size, enc_hidden_size))
    scorer = Scorer(scorer_module, traj_encoder)
    if args.load_scorer is not '':
        scorer.load(args.load_scorer)
        print(colorize('load scorer traj '+ args.load_scorer))
    elif args.load_traj_encoder is not '':
        scorer.load_traj_encoder(args.load_traj_encoder)
        print(colorize('load traj encoder '+ args.load_traj_encoder))
    return scorer
    def save_result(self, path):
        """Saves current policy.

        Args:
            path (str): The path where you want to save the policy.
        """

        # Retrieve save
        save_path = osp.abspath(osp.join(path, "policy/model.pth"))

        # Create folder if not exist
        if osp.exists(osp.dirname(save_path)):
            print(
                colorize(
                    ("WARN: Log dir %s already exists! Storing info there anyway."
                     % osp.dirname(save_path)),
                    "red",
                    bold=True,
                ))
        else:
            os.makedirs(osp.dirname(save_path))

        # Create models state dictionary
        if self.use_lyapunov:
            models_state_save_dict = {
                "use_lyapunov": self.use_lyapunov,
                "ga_state_dict": self.ga.state_dict(),
                "lc_state_dict": self.lc.state_dict(),
                "ga_targ_state_dict": self.ga_.state_dict(),
                "lc_targ_state_dict": self.lc_.state_dict(),
                "log_alpha": self.log_alpha,
                "log_labda": self.log_labda,
            }
        else:
            models_state_save_dict = {
                "use_lyapunov": self.use_lyapunov,
                "ga_state_dict": self.ga.state_dict(),
                "ga_targ_state_dict": self.ga_.state_dict(),
                "q1_state_dict": self.q_1.state_dict(),
                "q2_state_dict": self.q_2.state_dict(),
                "q1_targ_state_dict": self.q_1_.state_dict(),
                "q2_targ_state_dict": self.q_2_.state_dict(),
                "log_alpha": self.log_alpha,
            }

        # Save model state dictionary
        torch.save(models_state_save_dict, save_path)
        print(colorize(f"INFO: Save to path: {save_path}", "cyan", bold=True))
Exemple #25
0
    def compose_line(self, color=True, exclusions=None, reorder=None):
        """convert task object into a string for display or writing"""

        if exclusions is None:
            exclusions = []
        self.num = reorder or self.num

        parts = [
            ('n', 'gray', self.num_string),
            ('x', 'gray', self.x),
            ('pr', 'red', self.priority),
            ('dn', 'gray', self.done_string),
            ('d', 'orange', self.due_string),
            ('t', 'white', self.text),
            ('p', 'blue', self.projects_string),
            ('c', 'yellow', self.contexts_string),
            ('r', 'magenta', self.repeat_string),
            ('a', 'green', self.added_string),
            ('o', 'gray', self.order_string),
            ('p_id', 'gray', self.parent_id_string),
            ('c_id', 'gray', self.child_id_string),
            ]

        if color:
            parts = [utils.colorize(s, c) for l, c, s in parts
                     if l not in exclusions and s]
        else:
            parts = [s for l, c, s in parts if l not in exclusions and s]
        return ' '.join(parts)
Exemple #26
0
 def invoke(self, args, from_tty):
     if "--help" in args or "--h" in args:
         self.usage()
         return
     else:
         try:
             arena = GlibcArena("main_arena")
         except:
             self.msg(
                 colorize("Error: Could not find Glibc main arena", "red"))
         while True:
             self.msg(colorize("%s" % (arena, ), "purple"))
             arena = arena.get_next()
             if arena is None:
                 break
         return
Exemple #27
0
 def invoke(self, args, from_tty):
     if "--help" in args or "--h" in args:
         self.usage()
         return
     _arena = self.get_main_arena()
     self.msg(colorize("{0}".format(_arena), "blue"))
     return
Exemple #28
0
 async def confirm_equipment(ctx, profile):
     weapon = profile.weapon
     pet = profile.pet
     return await ctx.prompt(embed=Embed(
         ctx=ctx, title='Is this the correct equipment?'
     ).add_field(
         name='⚔️\tWeapon', value=f'```{weapon}```', inline=False
     ).add_field(
         name=
         f'{PET_EMOJIS[pet.internal_name] if pet and pet.internal_name in PET_EMOJIS else "🐣"}\tPet',
         value=f'```{format_pet(pet) if pet else None}```',
         inline=False).add_field(
             name='💎\tPet Item',
             value=f'```{pet.item_name if pet else None}```',
             inline=False).add_field(
                 name='⛑️\tHelmet',
                 value=f'```{profile.armor["helmet"]}```',
                 inline=False).add_field(
                     name='👚\tChestplate',
                     value=f'```{profile.armor["chestplate"]}```',
                     inline=False).add_field(
                         name='👖\tLeggings',
                         value=f'```{profile.armor["leggings"]}```',
                         inline=False).add_field(
                             name='👞\tBoots',
                             value=f'```{profile.armor["boots"]}```',
                             inline=False).add_field(
                                 name='🏺\tTalismans',
                                 value=''.join(
                                     colorize(
                                         f'{amount} {name.capitalize()}',
                                         RARITY_COLORS[name])
                                     for name, amount in
                                     profile.talisman_counts.items())))
Exemple #29
0
def categoryBindHelp(category: Category, categoryBinds: CategoryBinds) -> str:
    getCatStr: Callable[[CategoryBind], str] = (
        lambda cb: colorize(cb.explanation, YELLOW)
        if cb.category == category
        else cb.explanation
    )
    return "\n".join(map(lambda cbs: " ".join(map(getCatStr, cbs)), categoryBinds))
Exemple #30
0
    def saveConfig(self, config, stdout=True):
        """
        Log an experiment configuration.

        Call this once at the top of your experiment, passing in all important
        config vars as a dict. This will serialize the config to JSON, while
        handling anything which can't be serialized in a graceful way (writing
        as informative a string as possible). 

        Example use:

        .. code-block:: python

            logger = EpochLogger(**logger_kwargs)
            logger.save_config(locals())
        """
        config_json = convertJson(config)
        if self.exp_name is not None:
            config_json['exp_name'] = self.exp_name
        output = json.dumps(config_json,
                            separators=(',', ':\t'),
                            indent=4,
                            sort_keys=True)
        if stdout:
            print(colorize('Saving config:\n', color='cyan', bold=True))
            print(output)
        with open(osp.join(self.output_dir, "config.json"), 'w') as out:
            out.write(output)
Exemple #31
0
def copy_image(origin_folder, target_folder):
    """
    Find original screening in origin_folder and copy it to target_folder.
    """

    # Define path to all png files in the folder
    path = origin_folder + "/*.png"

    # Create list with addresses of all files in the folder
    addrs = sorted(glob.glob(path))

    # Get screenings path
    all_images = re.compile(".*_[0-9].png")
    image_list = list(filter(all_images.match, addrs))
    number_of_images = len(image_list)

    # If no images
    if number_of_images == 0:
        all_images = re.compile(".*_[0-9][0-9].png")
        image_list = list(filter(all_images.match, addrs))

    # Copy to new folder
    for image in image_list:

        # Check if image is RGB or 8bit
        img = np.array(Image.open(image))

        if len(img.shape) != 2:
            print(img.shape)
            print(colorize("{}".format(origin_folder), "red"))

        shutil.copy(image, target_folder)
def validate_req_costs(req_costs, costs_array):
    """Validates whether the requested observations exists. Throws a warning
    message if a requested state is not found.

    Args:
        req_costs (list): The requested observations.

        costs_array (numpy.ndarray): The array with the costs.

    Returns:
        list: The requested observations which are valid.
    """

    # Check if the requested observations are present
    req_costs = [cost - 1
                 for cost in req_costs]  # Translate indices to python format
    valid_costs, invalid_costs = validate_indices(req_costs, costs_array)
    valid_costs = [cost + 1
                   for cost in valid_costs]  # Translate back to hunan format
    invalid_costs = [cost + 1 for cost in invalid_costs]

    # Display warning if req obs were not found
    if invalid_costs:
        warning_str = ("WARN: {} {}".format(
            "Costs" if len(invalid_costs) > 1 else "Cost",
            invalid_costs,
        ) + " could not be plotted as they does not exist.")
        print(colorize(warning_str, "yellow"))

    # Return valid costs
    return valid_costs
def main(argv):
    pattern = "/scratch/nharness/Library/RAW/*TIF"
    files = glob(pattern)
    assert len(files) > 0
    assert len(files) < 1000000, len(files)
    shuffle(files)

    outfile = '/home/nharness/idcgans/datasets/patents' + str(IMSIZE) + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(outfile)

    for i, f in enumerate(files):
        print i
        image = get_image(f, IMSIZE, is_crop=True, resize_w=IMSIZE)
        image = colorize(image)
        assert image.shape == (IMSIZE, IMSIZE, 3)
        image += 1.
        image *= (255. / 2.)
        image = image.astype('uint8')
        #print image.min(), image.max()
        # from pylearn2.utils.image import save
        # save('foo.png', (image + 1.) / 2.)
        image_raw = image.tostring()
        label = 0
        if i % 1 == 0:
            print i, '\t',label
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(IMSIZE),
            'width': _int64_feature(IMSIZE),
            'depth': _int64_feature(3),
            'image_raw': _bytes_feature(image_raw),
            'label': _int64_feature(label)
            }))
        writer.write(example.SerializeToString())

    writer.close()
Exemple #34
0
def main(argv):
    pattern = "/gdata/CelebA/Img/img_align_celeba/*.jpg"
    files = glob(pattern)
    assert len(files) > 0

    shuffle(files)

    outfile = './data/CelebA_train_' + str(IMSIZE) + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(outfile)

    for i, f in enumerate(files):
        print(i)
        image = get_image(f, IMSIZE, is_crop=True, resize_w=IMSIZE)
        image = colorize(image)
        assert image.shape == (IMSIZE, IMSIZE, 3)
        image += 1.
        image *= (255. / 2.)
        image = image.astype('uint8')

        image_raw = image.tostring()

        label = 0
        if i % 1 == 0:
            print(i)
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(IMSIZE),
            'width': _int64_feature(IMSIZE),
            'depth': _int64_feature(3),
            'image_raw': _bytes_feature(image_raw),
            'label': _int64_feature(label)
        }))
        writer.write(example.SerializeToString())

    writer.close()
Exemple #35
0
def plot_single_flux_impl(h, flux, log=True):
	from matplotlib.gridspec import GridSpec
	from matplotlib.ticker import NullFormatter
	
	h._h_binedges[0] /= (numpy.pi/180)
	
	depths = lambda: list(range(1, 19, 2))
	
	fig = pylab.figure()
	grid = GridSpec(2,1,height_ratios=[2,1], hspace=0.05)
	ax1 = pylab.subplot(grid[0])
	for color, di in colorize(depths()):
		sub = h[:,di]
		depth = h._h_bincenters[1][di-1]
		sub.scatter(color=color, label='%d m' % (numpy.round(depth*1000)))
		coszen = numpy.cos(numpy.pi*sub.bincenters/180)
		pylab.plot(sub.bincenters, numpy.array([flux(depth, ct, 1) for ct in coszen]), color=color)
	if log:
		pylab.semilogy()
		pylab.ylim((1e-12, 1e-2))
	pylab.ylabel('$\Phi \, [1/(m^2 sr \, s)]$')
	pylab.legend(prop=dict(size='medium'), loc='best', ncol=2)
	pylab.grid()
	pylab.title('Single-muon flux at various depths')
	ax1.get_xaxis().set_major_formatter(NullFormatter())
	
	ax2 = pylab.subplot(grid[1])
	coszen = numpy.cos(numpy.pi*h._h_bincenters[0]/180)
	for color, di in colorize(depths()):
		sp = h[:,di].points()
		depth = h._h_bincenters[1][di-1]
		curve = numpy.array([flux(depth, ct, 1) for ct in coszen])
		chi2 = ((sp.y-curve)/sp.yerr)**2
		chi2 = chi2[numpy.isfinite(chi2)].sum()
		# print chi2
		sp.y /= curve
		sp.yerr /= curve
		mask = numpy.isnan(sp.y)
		sp.y[mask] = 1
		sp.yerr[mask] = 1
		sp.scatter(color=color, label='%d m' % (numpy.round(depth*1000)))
	pylab.ylim((0.95, 1.05))
	pylab.ylabel('ratio MC/fit')
	pylab.grid()
	pylab.xlabel('Zenith angle [degree]')
	
	return ax1, ax2
Exemple #36
0
 def execute(user_input, game_state):
     user_input = capture_input(
         colorize('Are you sure you would like to quit? (y/n) ', 'red')
     )
     if user_input[0] == 'y':
         raise QuitGame
     else:
         print 'Aborting quit'
Exemple #37
0
 def execute(user_input, game_state):
     user_input = capture_input(
         colorize('Are you sure you would like to overwrite any saved games? (y/n) ', 'red')
     )
     if user_input[0] == 'y':
         game_state.save()
     else:
         print 'Aborting save'
Exemple #38
0
 def get_video(self, tensor, matrix_bin, cmap='binary'):
     tensor = np.transpose(tensor, axes=(2, 0, 1))
     tensor_col = colorize(tensor, cmap=cmap)
     tensor = np.where(np.stack([tensor for _ in range(4)], axis=-1),
                       tensor_col, matrix_bin)
     tensor = np.transpose(tensor, axes=(0, 3, 1, 2))
     tensor = np.expand_dims(tensor, axis=0)
     return tensor
Exemple #39
0
def getStaticEnvironment():
    environment = Environment(ENV = os.environ)
    peg_color = 'light-cyan'
    environment['PAINTOWN_PLATFORM'] = ['osx']
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = True
    environment['PAINTOWN_NETWORKING'] = True
    environment.Append(CPPDEFINES = ['HAVE_NETWORKING'])
    environment.Append(CPPDEFINES = ['MACOSX'])
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    # environment.Append(CCFLAGS = Split("-arch i386 -arch x86_64"))
    # print environment['CCCOM']
    # I don't know why appending -arch to ccflags doesn't work, but whatever
    environment['CCCOM'] = '$CC -arch i386 -arch x86_64 $CFLAGS $CCFLAGS $_CCCOMCOM $SOURCES -c -o $TARGET'
    environment['CXXCOM'] = '$CXX -arch i386 -arch x86_64 -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM $SOURCES'
    environment['LINKCOM'] = '$CXX $LINKFLAGS -arch i386 -arch x86_64 $SOURCES $_FRAMEWORKS -Wl,-all_load $ARCHIVES $_LIBDIRFLAGS $_LIBFLAGS -o $TARGET'

    # Default preference for a graphics renderer / input system
    backends = ['SDL', 'Allegro4', 'Allegro5']

    if utils.useAllegro4():
        backends = ['Allegro4', 'SDL', 'Allegro5']

    if utils.useAllegro5():
        backends = ['Allegro5', 'SDL', 'Allegro4']

    #environment.ParseConfig('freetype-config --libs --cflags')
    #environment.ParseConfig('libpng-config --libs --cflags')

    if utils.useLLVM():
        llvm(environment)

    custom_tests = {"CheckCompiler": utils.checkCompiler,
                    "CheckSDL" : checkStaticSDL,
                    "CheckOgg" : checkStaticOgg,
                    "CheckFreetype" : checkStaticFreetype,
                    "CheckMalloc" : checkMallocH,
                    "CheckZ" : checkStaticZ,
                    "CheckPng" : checkStaticPng,
                    "CheckMpg123" : checkStaticMpg123,
                    "CheckAllegro4" : checkStaticAllegro4,
                    "CheckAllegro5" : checkStaticAllegro5}

    config = environment.Configure(custom_tests = custom_tests)
    config.CheckZ()
    config.CheckOgg()
    config.CheckMpg123()
    config.CheckFreetype()
    config.CheckPng()
    # config.CheckMalloc()
    environment = config.Finish()

    return utils.configure_backend(environment, backends, custom_tests)
Exemple #40
0
    def invoke(self, args, from_tty):
        if "--help" in args or "--h" in args:
            self.usage()
            return

        self.msg(colorize("all bins:", "green"))
        for i in range(128):  #128个bins
            GlibcHeapBinsCommand.pprint_bin(i)
        return
Exemple #41
0
def getEnvironment():
    import utils
    environment = Environment(ENV=os.environ)
    environment['PAINTOWN_PLATFORM'] = ['wii', 'sdl']
    peg_color = 'light-cyan'
    environment['PAINTOWN_BACKEND'] = 'sdl'
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = False
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize(
        'Creating peg parser',
        peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS={'Peg': utils.pegBuilder(environment)})
    environment.Append(CPPPATH=['#src', '#src/util/network/hawknl'])
    environment.Append(CPPDEFINES=['USE_SDL'])

    return utils.lessVerbose(wii(environment))
def LogProgress(model, writer, test_loader, epoch, device):
    """To record intermediate results of training"""

    model.eval()
    sequential = test_loader
    sample_batched = next(iter(sequential))

    image = torch.Tensor(sample_batched["image"]).to(device)
    depth = torch.Tensor(sample_batched["depth"]).to(device)

    if epoch == 0:
        writer.add_image(
            "Train.1.Image",
            vision_utils.make_grid(image.data, nrow=6, normalize=True),
            epoch,
        )
    if epoch == 0:
        writer.add_image(
            "Train.2.Image",
            colorize(
                vision_utils.make_grid(depth.data, nrow=6, normalize=False)),
            epoch,
        )

    output = DepthNorm(model(image))

    writer.add_image(
        "Train.3.Ours",
        colorize(vision_utils.make_grid(output.data, nrow=6, normalize=False)),
        epoch,
    )
    writer.add_image(
        "Train.4.Diff",
        colorize(
            vision_utils.make_grid(torch.abs(output - depth).data,
                                   nrow=6,
                                   normalize=False)),
        epoch,
    )

    del image
    del depth
    del output
Exemple #43
0
def getEnvironment():
    import utils
    environment = Environment(ENV=os.environ)
    peg_color = 'light-cyan'
    environment['MUGEN_PLATFORM'] = ['unix']
    environment['MUGEN_USE_PRX'] = False
    environment['MUGEN_TESTS'] = {'CheckPython': checkPython}
    environment['MUGEN_COLORIZE'] = utils.colorize
    environment['MUGEN_NETWORKING'] = True
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize(
        'Creating peg parser',
        peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS={'Peg': utils.pegBuilder(environment)})
    environment.Append(CPPPATH=['#src', '#src/util/network/hawknl'])
    environment[
        'LINKCOM'] = '$CXX $LINKFLAGS $SOURCES -Wl,--start-group $ARCHIVES $_LIBDIRFLAGS $_LIBFLAGS -Wl,--end-group -o $TARGET'

    # Default preference for a graphics renderer / input system
    backends = ['SDL', 'Allegro4', 'Allegro5']

    if utils.useAllegro4():
        backends = ['Allegro4', 'SDL', 'Allegro5']

    if utils.useAllegro5():
        backends = ['Allegro5', 'SDL', 'Allegro4']

    environment.ParseConfig('freetype-config --libs --cflags')
    environment.ParseConfig('libpng-config --libs --cflags')

    if utils.useLLVM():
        llvm(environment)

    custom_tests = {
        "CheckCompiler": utils.checkCompiler,
        "CheckSDL": checkSDL,
        "CheckAllegro4": checkAllegro4,
        "CheckAllegro5": checkAllegro5
    }

    return utils.configure_backend(environment, backends, custom_tests)
Exemple #44
0
	def update_status(self):
		success = False
		print utils.colorize( 'What\'s happening?\n (type "\cancel" to cancel)' + ' '*(99) + '140char limit -->|', "YELLOW")
		while not success:
			message = raw_input('  > ')
			if message == '\cancel':
				return success
			elif len(message) <= 140 and len(message) > 0:
				self.api.update_status(message)
				print utils.colorize('Tweet sent succefully!', "GREEN")
				success = True
			elif len(message) > 140:
				print utils.colorize('Your message had ' + str(len(message)) + ' characteres, please reduce it to a maximum of 140 and try again.', "RED")
			elif len(message) == 0:
				print utils.colorize('You must say something!', "RED")
Exemple #45
0
def getEnvironment():
    import utils
    environment = Environment(ENV = os.environ)
    environment['PAINTOWN_PLATFORM'] = ['wii', 'sdl']
    peg_color = 'light-cyan'
    environment['PAINTOWN_BACKEND'] = 'sdl'
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = False
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    environment.Append(CPPDEFINES = ['USE_SDL'])

    return utils.lessVerbose(wii(environment))
def main(argv):
    pattern = "/home/ian/imagenet/ILSVRC2012_img_train_t1_t2/n*/*JPEG"
    files = glob(pattern)
    assert len(files) > 0
    assert len(files) > 1000000, len(files)
    shuffle(files)

    dirs = glob("/home/ian/imagenet/ILSVRC2012_img_train_t1_t2/n*")
    assert len(dirs) == 1000, len(dirs)
    dirs = [d.split('/')[-1] for d in dirs]
    dirs = sorted(dirs)
    str_to_int = dict(zip(dirs, range(len(dirs))))


    outfile = '/media/NAS_SHARED/imagenet/imagenet_train_labeled_' + str(IMSIZE) + '.tfrecords'
    writer = tf.python_io.TFRecordWriter(outfile)

    for i, f in enumerate(files):
        print i
        image = get_image(f, IMSIZE, is_crop=True, resize_w=IMSIZE)
        image = colorize(image)
        assert image.shape == (IMSIZE, IMSIZE, 3)
        image += 1.
        image *= (255. / 2.)
        image = image.astype('uint8')
        #print image.min(), image.max()
        # from pylearn2.utils.image import save
        # save('foo.png', (image + 1.) / 2.)
        image_raw = image.tostring()
        class_str = f.split('/')[-2]
        label = str_to_int[class_str]
        if i % 1 == 0:
            print i, '\t',label
        example = tf.train.Example(features=tf.train.Features(feature={
            'height': _int64_feature(IMSIZE),
            'width': _int64_feature(IMSIZE),
            'depth': _int64_feature(3),
            'image_raw': _bytes_feature(image_raw),
            'label': _int64_feature(label)
            }))
        writer.write(example.SerializeToString())

    writer.close()
Exemple #47
0
	def edit_user_name(self, current_user):
		try:
			print 'Type in your new user name:'
			print '(type "\cancel" to cancel)'
			sucess = False
			while not sucess:
				new_name = raw_input('Username: '******'\cancel':
					return ''
				elif ' ' in new_name:
					print utils.colorize("User name cannot contain any spaces.", "RED")
				elif len(new_name) == 0:
					print utils.colorize("User name cannot be empty!", "RED")
				elif self.username_exists(new_name):
					print utils.colorize("User name already exists.", "RED")
				else:
					sucess = True
			self.remove_user(current_user.name)
			self.save_user(new_name, current_user.password, current_user.key, current_user.secret)
			return new_name
		except:
			print utils.colorize('An error occurred while saving your new username, sorry.', "B_RED")
			return ''
Exemple #48
0
def getEnvironment():
    import utils
    environment = Environment(ENV = os.environ)
    peg_color = 'light-cyan'
    environment['PAINTOWN_PLATFORM'] = ['unix']
    environment['PAINTOWN_USE_PRX'] = False
    environment['PAINTOWN_TESTS'] = {'CheckPython': checkPython}
    environment['PAINTOWN_COLORIZE'] = utils.colorize
    environment['PAINTOWN_NETWORKING'] = True
    environment['LIBS'] = []
    environment['PEG_MAKE'] = "%s %s" % (utils.colorize('Creating peg parser', peg_color), utils.colorize('$TARGET', 'light-blue'))
    environment.Append(BUILDERS = {'Peg' : utils.pegBuilder(environment)})
    environment.Append(CPPPATH = ['#src', '#src/util/network/hawknl'])
    environment['LINKCOM'] = '$CXX $LINKFLAGS $SOURCES -Wl,--start-group $ARCHIVES $_LIBDIRFLAGS $_LIBFLAGS -Wl,--end-group -o $TARGET'

    # Default preference for a graphics renderer / input system
    backends = ['SDL', 'Allegro4', 'Allegro5']

    if utils.useAllegro4():
        backends = ['Allegro4', 'SDL', 'Allegro5']

    if utils.useAllegro5():
        backends = ['Allegro5', 'SDL', 'Allegro4']

    environment.ParseConfig('freetype-config --libs --cflags')
    environment.ParseConfig('libpng-config --libs --cflags')

    if utils.useLLVM():
        llvm(environment)

    custom_tests = {"CheckCompiler": utils.checkCompiler,
                    "CheckSDL" : checkSDL,
                    "CheckAllegro4" : checkAllegro4,
                    "CheckAllegro5" : checkAllegro5}

    return utils.configure_backend(environment, backends, custom_tests)
Exemple #49
0
	def parse_commands(self):
		try:
			while True:
				user_input = raw_input(self.display_name + '> ')
				if len(user_input.strip()) == 0:
					print utils.colorize("Type in a command!", "RED")
				elif user_input == 'exit':
					print_text.exit()
					return
				elif self.logged_in:
					if user_input == 'help':
						print_text.help_user()
					elif user_input == 'update':
						self.update_status()
					elif user_input == 'timeline':
						self.get_home_timeline()
					elif user_input == 'logout':
						self.logout()
					elif user_input == 'edit name':
						new_name = self.user_auth.edit_user_name(self.current_user)
						if len(new_name) > 0:
							self.current_user.name = new_name
							self.display_name = new_name + " "
					elif user_input == 'edit password':
						self.user_auth.edit_password(self.current_user)
					elif 'user' in user_input:
						self.get_user_profile(user_input)
					elif user_input == 'stream':
						self.start_streaming()
					else:
						print utils.colorize('The command "' + user_input + '" was not recognized.', "B_RED")
				else:
					if user_input == 'help':
						print_text.help_guest()
					elif 'login' in user_input:
						self.try_login(user_input)
					elif user_input == 'create':
						self.user_auth.create_user(self.auth)
					else:
						print utils.colorize('The command "' + user_input + '" was not recognized.', "B_RED")
		except KeyboardInterrupt:
			print ''
			print_text.exit()
Exemple #50
0
	def edit_password(self, current_user):
		try:
			sucess = False
			while not sucess:		
				print 'Type in your new password:'******'(type "\cancel" to cancel)'
				password = getpass.getpass('Password: '******'\cancel':
					return ''
				elif len(password) == 0:
					print utils.colorize("Password cannot be empty!", "RED")
				double_check = ''
				print 'Say your new password again:'
				double_check = getpass.getpass('Password: '******'t match, please try again.", "RED")
				else:
					sucess = True
			self.remove_user(current_user.name)
			self.save_user(current_user.name, password, current_user.key, current_user.secret)
		except:
			print utils.colorize('An error occurred while saving your new password, sorry.', "B_RED")
			return ''
Exemple #51
0
        return (err, None, None) if err \
            else (None, mouvements, cube_lu)

if __name__=="__main__":
    """
    :Example:
        python poqb.py
        python poqb.py -cYYYYYYYYYOOOBBBRRRGGGOOOBBBRRRGGGOOOBBBRRRGGGWWWWWWWWW
        python poqb.py --cube=YYYYYYYYYOOOBBBRRRGGGOOOBBBRRRGGGOOOBBBRRRGGGWWWWWWWWW
    """

    #On récupère le cube en paramètre ou on utilise celui par défaut
    params = readArgs()
    cube = str(params['cube']) if 'cube' in params else DEFAULT_CUBE

    err, resolution, cube_lu = solve_full(cube)
    if err:
        print("Erreur dans la lecture du cube : " + err)
    else:
        #L'utilisateur a demandé la résolution pas à pas
        if 'tuto' in params:
            print('Résolution de :', "".join([colorize(x) for x in cube]))
            tuto(cube_lu, resolution)

        print('Résolution de :', "".join([colorize(x) for x in cube]) +'\n')
        resolution = " ".join([translate_mvt(x) for x in resolution])
        print('Positionnez la face bleue face à vous et la face blanche face au sol\n')
        print("Puis exécutez la manoeuvre : {}".format(resolution) +'\n')


Exemple #52
0
        c.rot_UF() #on descend la face blanche sur D

        #on place la face bleue
        #si elle était sur U, elle est à la bonne place maintenant
        if v[1] == 5: #si elle était sur D, elle est sur B maintenant
            c.rot_FR()
            c.rot_FR()
        #on s'intéresse aux cas pù la face bleue est sur L ou R
        #cas où on est sur R maintenant
        elif v[1] == v[0] + 1 or (v[0], v[1]) == (4, 1):
            for x in range(3):
                c.rot_FR()
        #cas où on est sur L maintenant
        elif v[1] == v[0] - 1 or (v[0], v[1]) == (1, 4):
            c.rot_FR()

    return (False, c)

if __name__ == "__main__":

    print('\nExemple lecture_cube()')
    print('====================')

    exemple = 'OGRBWYBGBGYYOYOWOWGRYOOOBGBRRYRBWWWRBWYGROWGRYBRGYWBOG'
    print('input :', ''.join([colorize(c) for c in exemple]))
    error, cube = lecture_cube(exemple)
    if not error:
        print('output:', cube.to_line())
        print(cube)
    print('Erreur :', error)
Exemple #53
0
def build_faces(cube, colors=False, space=False):
    """
    build_faces

    Constructions de la représentation des faces du rubik's cube

    :Args:
        cube    {Cube}      Un rubik's cube
        colors  {Boolean}   Utilisation de couleurs pour les terminal ?
                            Defaut False. (mettre à True pour Cube.__str__())
        space   {Boolean}   Espaces entre les facettes ?
                            Defaut False. (mettre à True pour Cube.__str__())

    :Returns:
        {List,List,List,List,List,List,List,List}
                            up, left, front, right, back, down
    """

    up = [
        [cube.cubes['BLU'][2], cube.cubes['BU'][1], cube.cubes['RBU'][2]],
        [cube.cubes['LU'][1],  5,                   cube.cubes['RU'][1]],
        [cube.cubes['LFU'][2], cube.cubes['FU'][1], cube.cubes['FRU'][2]],
    ]

    left = [
        [cube.cubes['BLU'][1], cube.cubes['LU'][0], cube.cubes['LFU'][0]],
        [cube.cubes['BL'][1],  4,                   cube.cubes['FL'][1]],
        [cube.cubes['BLD'][1], cube.cubes['LD'][0], cube.cubes['LFD'][0]],
    ]

    front = [
        [cube.cubes['LFU'][1], cube.cubes['FU'][0], cube.cubes['FRU'][0]],
        [cube.cubes['FL'][0],  1,                   cube.cubes['FR'][0]],
        [cube.cubes['LFD'][1], cube.cubes['FD'][0], cube.cubes['FRD'][0]],
    ]

    right = [
        [cube.cubes['FRU'][1], cube.cubes['RU'][0], cube.cubes['RBU'][0]],
        [cube.cubes['FR'][1],  2,                   cube.cubes['BR'][1]],
        [cube.cubes['FRD'][1], cube.cubes['RD'][0], cube.cubes['RBD'][0]],
    ]

    back = [
        [cube.cubes['RBU'][1], cube.cubes['BU'][0], cube.cubes['BLU'][0]],
        [cube.cubes['BR'][0],  3,                   cube.cubes['BL'][0]],
        [cube.cubes['RBD'][1], cube.cubes['BD'][0], cube.cubes['BLD'][0]],
    ]

    down = [
        [cube.cubes['LFD'][2], cube.cubes['FD'][1], cube.cubes['FRD'][2]],
        [cube.cubes['LD'][1],  0,                   cube.cubes['RD'][1]],
        [cube.cubes['BLD'][2], cube.cubes['BD'][1], cube.cubes['RBD'][2]],
    ]

    #On convertit tous les entiers en la couleur qui leur correspond
    for face in (up, left, front, right, back, down):
        for ligne in range(3):
            for c in range(3):
                #pour chaque case de chaque ligne de chaque face
                if colors:
                    face[ligne][c] = colorize(
                            codeToColor(face[ligne][c]),
                            COULEURS_SPACE if space else None
                        )
                else:
                    face[ligne][c] = codeToColor(face[ligne][c])

    return (up, left, front, right, back, down)
Exemple #54
0
#!/usr/bin/env python
#from distutils.core import setup
from setuptools import setup, find_packages
import os
import utils

print utils.colorize("Starting installation of Tweet Bash...", "CYAN")

setup(name="tweet-bash",
      version=utils.app_version,
      description="Twitter app for Ubuntu's bash terminal",
      license="MIT",
      install_requires="tweepy >=1.7.1",
      author="Rodrigo Castro",
      author_email="*****@*****.**",
      url="http://github.com/roooodcastro/tweet-bash",
      packages = find_packages(),
      keywords= "twitter terminal",
      zip_safe = True)
Exemple #55
0
	def on_timeout(self):
		print utils.colorize('Connection lost due to timeout.', "RED")
Exemple #56
0
	def on_error(self, status_code):
		print utils.colorize('An error has occurred! Status code = %s' % status_code, "B_RED")