Ejemplo n.º 1
0
def crear_tablas():
    init(autoreset=True)

    auth = app.auth
    if os.path.exists(DATABASE['name']):
        print Fore.GREEN  + 'Creando el archivo ' + DATABASE['name']
        os.remove(DATABASE['name'])

    # Crear tablas
    auth.User.create_table(fail_silently=True)

    def es_un_modelo(clase):
        return inspect.isclass(c) and issubclass(c, models.db.Model)

    for nombre, clase in [(n, c) for n, c in inspect.getmembers(models) if es_un_modelo(c)]:
        clase.create_table(fail_silently=True)
        print Fore.GREEN  + 'Creando tabla para ' + nombre

    #Crear usuario admin
    admin = auth.User(username='******', admin=True, active=True)
    admin.set_password('admin')
    admin.save()
    print Fore.GREEN + "Creando usuario admin"

    cargar_provincias()
Ejemplo n.º 2
0
def main():
    # log settings
    # log format
    # logging.basicConfig(level=logging.DEBUG, format='%(asctime)s [%(module)10s] [%(levelname)5s] %(message)s')

    colorama.init()

    config = init_config()
    if not config:
        return

    logger.log('[x] PokemonGO Bot v1.0', 'green')
    logger.log('[x] Configuration initialized', 'yellow')

    try:
        bot = PokemonGoBot(config)
        bot.start()

        logger.log('[x] Starting PokemonGo Bot....', 'green')

        while True:
            bot.take_step()

    except KeyboardInterrupt:
        logger.log('[x] Exiting PokemonGo Bot', 'red')
Ejemplo n.º 3
0
    def index(self):
        """arg list"""
        init(autoreset=True)

        parser = argparse.ArgumentParser(description=
                                         'Mongodb unauthorized access vulnerability PoC')
        group = parser.add_mutually_exclusive_group()
        group.add_argument('-i', help='IP', dest='ip')
        group.add_argument('-s', help='class C network segment', dest='segment')
        group.add_argument('-f', help='IP file', dest='ip_file')
        parser.add_argument('-n', help='thread num', dest='thread_num', default=10)
        args = parser.parse_args()

        q = Queue.Queue()

        if args.ip:
            self.connect_mongo(args.ip)
        elif args.segment:
            for i in xrange(0, 255):
                ip = args.segment.rpartition('.')[0] + '.' + str(i)
                q.put(ip)
            self.start_thread(q, args.thread_num)
        elif args.ip_file:
            with open(args.ip_file, 'r') as f:
                for ip in f:
                    q.put(ip)
            self.start_thread(q, args.thread_num)
Ejemplo n.º 4
0
 def __init__(self, *args, **kwargs):
     '''
     Constructor
     '''
     init(autoreset=True)
     self.unfinished_solicitations_by_sn = {}
     super(NsfSpider, self).__init__(*args, **kwargs)
Ejemplo n.º 5
0
def scan(only_changed_files=False, progress=True, stylo=False):
    # check config file for errors
    config_errors = check_config_file(CONFIG_FILE_PATH)
    # check directories contain expected files
    directory_errors = check_directory_files(config['check_ext'])
    # standard checks
    files_to_check = filter_files('.', only_changed_files and not stylo, progress)
    checking_functions = (check_flake8, check_lock, check_webidl_spec, check_json, check_yaml)
    line_checking_functions = (check_license, check_by_line, check_toml, check_shell,
                               check_rust, check_spec, check_modeline)
    file_errors = collect_errors_for_files(files_to_check, checking_functions, line_checking_functions)
    # check dependecy licenses
    dep_license_errors = check_dep_license_errors(get_dep_toml_files(only_changed_files), progress)
    # other lint checks
    lint_errors = run_lint_scripts(only_changed_files, progress, stylo=stylo)
    # chain all the iterators
    errors = itertools.chain(config_errors, directory_errors, lint_errors,
                             file_errors, dep_license_errors)

    error = None
    for error in errors:
        colorama.init()
        print "\r\033[94m{}\033[0m:\033[93m{}\033[0m: \033[91m{}\033[0m".format(*error)

    print
    if error is None:
        colorama.init()
        print "\033[92mtidy reported no errors.\033[0m"

    return int(error is not None)
Ejemplo n.º 6
0
def expire_files():
    '''
    FILE CLEANUP ROUTINE
    
    This function will run on a schedule set by FILE_CLEANUP SCHEDULE
    in config.py. 
    
    Running this function will delete all files that have expired as
    determined by EXPIRE_TIME in config.py
    '''

    colorama.init()
    green = colorama.Fore.GREEN
    yellow = colorama.Fore.YELLOW
    red = colorama.Fore.RED
    reset = colorama.Fore.RESET

    print(green + " -- FILE CLEANUP STARTED -- " + reset)
    for root, dirs, files in os.walk(config.UPLOAD_DIR):
        for name in files:
            file_time = os.path.getmtime(os.path.join(root, name)) 
            expire_time = file_time + config.EXPIRE_TIME * 60 * 60 
            current_time = time.time()
            if current_time > expire_time:
                os.remove(os.path.join(root, name))
                print(red + "removed: " + os.path.join(root, name) + reset)
        for name in dirs:
            try:
                os.rmdir(os.path.join(root, name))
                print(red + "Removed: " + os.path.join(root, name) + reset)       
            except OSError as e:
                if e.errno == errno.ENOTEMPTY:
                    print(yellow + os.path.join(root, name) + " is not empty" + reset)
    print(green + " -- FILE CLEANUP COMPLETED -- " + reset)
Ejemplo n.º 7
0
def dostatus(context, show_down_services):
    init()
    b = BColors()
    up_processes_table = PrettyTable()
    up_processes_table.field_names = ["name", "ppid", "pid", "uptime", "mem", "port", "test id", "run from", "features", "healthcheck"]
    up_processes_table.align = "r"
    up_processes_table.align["name"] = "l"
    up_processes_table.sortby = "name"
    up_processes_table.align["test id"] = "l"
    up_processes_table.align["run from"] = "l"
    up_processes_table.align["features"] = "l"

    down_processes_table = PrettyTable()
    down_processes_table.field_names = ["name", "healthcheck"]
    down_processes_table.align = "r"
    down_processes_table.align["name"] = "l"
    down_processes_table.sortby = "name"


    all_processes = context.process_manager.all_processes()
    for service in context.services():
        responses = service.status(all_processes)
        if responses:
            for response in responses:
                up_processes_table.add_row(_service_status_to_row(response))
        elif show_down_services:
            down_processes_table.add_row([service.service_name, b.bold + b.fail + "DOWN" + b.endc])

    result = ["Running:", str(up_processes_table)]
    if show_down_services:
        result.append("Down:")
        result.append(str(down_processes_table))
    return result
Ejemplo n.º 8
0
def main():
    init()
    ser = serial.Serial(COM, 19200)
    while True:
        schr = ser.read()
        char = c2ascii(schr)
        chx = c2hex(schr)
        if char == 'D':
            getparam(ser, 'D', 'Haaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah')
            getparam(ser, '_', 'hhhhahhhhhHhhhhh')
        elif char == 'S':
            getparam(ser, 'S', 'Hhhhh')
            getparam(ser, '_', 'hhhhahhhhhHhhhhh')
        elif char == 'R':
            getparam(ser, 'R', 'hhhhh')
        elif char == 'C':
            getparam(ser, 'C', 'hhhhhhhhhh')
        elif char == 'B':
            getparam(ser, 'B', 'hhh')
        #elif char == 'Z':
        #    getparam(ser, 'Z', 'h')
        #elif char == 'W':
        #    getparam(ser, 'W', 'H')
        elif char and ('A' <= char and char <= 'Z' or
                     'a' <= char and char <= 'z'):
            printc(char, Fore.WHITE, prepend = '  ')
        else:
            printc(chx, Fore.YELLOW)
Ejemplo n.º 9
0
  def Main(self):
    t1 = datetime.datetime.now()
    colorama.init()

    opt_parser = self._GetOptParser()
    options, dummy_args = opt_parser.parse_args()

    logging.basicConfig(level=options.log_level)

    # If no configurations are specified, run all configurations.
    if not options.configs:
      options.configs = ['Debug', 'Release']

    result = 0
    for config in set(options.configs):
      # We don't catch any exceptions that may be raised as these indicate
      # something has gone really wrong, and we want them to interrupt further
      # tests.
      if not self.Run(config, force=options.force):
        _LOGGER.error('Configuration "%s" of test "%s" failed.',
                      config, self._name)
        result = 1

    # Now dump all error messages.
    sys.stdout.write(self._GetStderr())

    t2 = datetime.datetime.now()
    _LOGGER.info('Unittests took %s to run.', t2 - t1)

    return result
Ejemplo n.º 10
0
def main():
    # Initialize color support
    colorama.init()
    try:
        run()
    except util.DeviceException as e:
        typ, val, tb = sys.exc_info()
        logging.debug("".join(traceback.format_exception(typ, val, tb)))
        print(colorama.Fore.RED + "There is a problem with your device"
                                  " configuration:")
        print(colorama.Fore.RED + e.message)
    except ConfigError as e:
        typ, val, tb = sys.exc_info()
        logging.debug("".join(traceback.format_exception(typ, val, tb)))
        print(colorama.Fore.RED +
              "There is a problem with your configuration file(s):")
        print(colorama.Fore.RED + e.message)
    except util.MissingDependencyException as e:
        typ, val, tb = sys.exc_info()
        logging.debug("".join(traceback.format_exception(typ, val, tb)))
        print(colorama.Fore.RED +
              "You are missing a dependency for one of your enabled plugins:")
        print(colorama.Fore.RED + e.message)
    except KeyboardInterrupt:
        colorama.deinit()
        sys.exit(1)
    except Exception as e:
        typ, val, tb = sys.exc_info()
        print(colorama.Fore.RED + "spreads encountered an error:")
        print(colorama.Fore.RED +
              "".join(traceback.format_exception(typ, val, tb)))
    # Deinitialize color support
    colorama.deinit()
Ejemplo n.º 11
0
def runExecutable(exe, number, threads):
    """
    Run <exe> <number> times, randomising the input parameters.
    Each execution is independent so allow <exe> to be run over <threads> threads

    @param: Executable to run
    @param: Number of times to run <exe>
    @param: Number of threads to concurrently use

    @return: Nothing
    """
    # We could read this from ../includes/inputs.h
    MAX_Z = 118
    # Set the minimum possible Z range
    MAX_LOW_Z = MAX_Z - 1

    colorama.init()
    print("\nUsing: "
          + colorama.Fore.GREEN + exe + colorama.Style.RESET_ALL
          + " to create "
          + colorama.Fore.GREEN + str(number) + colorama.Style.RESET_ALL
          + " chart(s)\n")
    colorama.deinit()

    Parallel(threads)(delayed(createSingleChart)(MAX_LOW_Z, MAX_Z) for i in range(0, number))

    print()
def main(args):
    # Window terminals need some customization to work out-of-the-box with unicode.  
    if 'win32' in sys.platform:
        # Must be a UTF-8 compatible codepage in the terminal or output doesn't work.
        with open(os.devnull, 'w') as null:
            subprocess.call(['chcp', '65001'], stdout=null, stderr=null, shell=True)
        
        # Optionally relaunch the application to let Python update the stdout encoding.
        try:
            print("…\r \r", end='')
        except UnicodeEncodeError:
            return os.spawnv(os.P_WAIT, sys.executable, [sys.executable] + args)

    # Use colored console output; required on Windows only, works by default elsewhere.
    try:
        import colorama; colorama.init(); del colorama
    except ImportError:
        pass

    # Fail if the user is running from a system-wide Python 3.4 installation.
    if not hasattr(sys, 'base_prefix'):
        display('ERROR: Please run this script from a virtual environment.\n', color=ansi.RED_B)
        executable = os.path.split(sys.executable)[1]
        display('  > {} -m venv pyenv\n'.format(executable), color=ansi.RED)
        return 1

    app = Application()
    return app.main(args[1:])
Ejemplo n.º 13
0
def main(argv=None):
    """
    The entry point of the application.
    """
    colorama.init()

    usage = __doc__[__doc__.find('Usage:'):]
    version = 'pytest-watch ' + __version__
    argv = argv if argv is not None else sys.argv[1:]
    args = docopt(usage, argv=argv, version=version)

    pytest_args = []
    directories = args['<directories>']
    if '--' in directories:
        index = directories.index('--')
        pytest_args = directories[index + 1:]
        directories = directories[:index]
    ignore = (args['--ignore'] or '').split(',')
    extensions = [('.' if not ext.startswith('.') else '') + ext
                  for ext in (args['--ext'] or '.py').split(',')]

    return watch(directories=directories,
                 ignore=ignore,
                 auto_clear=args['--clear'],
                 beep_on_failure=not args['--nobeep'],
                 onpass=args['--onpass'],
                 onfail=args['--onfail'],
                 beforerun=args['--beforerun'],
                 poll=args['--poll'],
                 extensions=extensions,
                 args=pytest_args,
                 spool=not args['--no-spool'],
                 verbose=args['--verbose'],
                 quiet=args['--quiet'])
Ejemplo n.º 14
0
	def printBoard(self, player, gettingDest=False, pieceRow=-1, pieceCol=-1, jumping=False):
		init(autoreset=True)
		padding = 2
		print("Current board state:")
		for i in range(len(self.square)):
			printRow = ''
			for j in range(len(self.square[i])):
				printValue = ''
				padding = 1
				if i % 2 != j % 2:
					printValue = printValue + Fore.BLACK											#Remove unusable squares
				if self.square[i][j].color != self.players[player].color and self.square[i][j].color != self.square[i][j].empty:
					printValue = printValue + Style.BRIGHT + Fore.RED								#Highlight opponent pieces
				if self.square[i][j].color == self.players[player].color:
					printValue = printValue + Style.DIM + Fore.GREEN								#Color and dim all player pieces
					if not gettingDest and self.hasValidMoves(i, j, player):
						printValue = printValue + Style.BRIGHT										#Highlight available player pieces
				if gettingDest:
					if pieceRow > -1 and pieceCol > -1 and pieceRow < len(self.square) and pieceCol < len(self.square[i]):	#Valid square
						if [i,j] in self.generateMoveList(pieceRow, pieceCol, jumping):
							printValue = printValue + Style.BRIGHT + Fore.YELLOW					#Highlight available destinations
						if i == pieceRow and j == pieceCol:	
							printValue = printValue + Style.BRIGHT + Fore.GREEN						#Highlight current piece [redundant, but available to be changed]
				printValue = printValue + (2-len(str((i*len(self.square[i]))+j)))*' ' + str((i*len(self.square[i]))+j) + ' '	#Include Legend
				if self.square[i][j].topDir in self.square[i][j].myDir and self.square[i][j].botDir in self.square[i][j].myDir:
					printValue = printValue + str(self.square[i][j].color) 							#King Piece, double print
					padding = 0
				printValue = printValue + str(self.square[i][j].color) + Fore.RESET
				printRow = printRow + Style.DIM + '[' + printValue + ' '*padding + Style.DIM +  ']' + Style.RESET_ALL
			print(printRow)	
Ejemplo n.º 15
0
def get_device_manager():
    global _device_manager
    if _device_manager is None:
        from . import core
        try:
            import _frida
        except Exception as ex:
            import colorama
            from colorama import Back, Fore, Style
            import sys
            colorama.init(autoreset=True)
            print("")
            print("***")
            if str(ex).startswith("No module named "):
                print(Back.RED + Fore.WHITE + Style.BRIGHT + "Frida native extension not found")
                print(Fore.WHITE + Style.BRIGHT + "Please check your PYTHONPATH.")
            else:
                print(Back.RED + Fore.WHITE + Style.BRIGHT + "Failed to load the Frida native extension: %s" % ex)
                if sys.version_info[0] == 2:
                    current_python_version = "%d.%d" % sys.version_info[:2]
                else:
                    current_python_version = "%d.x" % sys.version_info[0]
                print(Fore.WHITE + Style.BRIGHT + "Please ensure that the extension was compiled for Python " + current_python_version + ".")
            print("***")
            print("")
            raise ex
        _device_manager = core.DeviceManager(_frida.DeviceManager())
        _device_manager.enumerate_devices() # warm up
    return _device_manager
Ejemplo n.º 16
0
def _handle_soft_error(exc_type, exc_value, exc_tb):
    colorama.init()
    err(Fore.LIGHTRED_EX + exc_type.__name__ + ": " + str(exc_value) + Style.RESET_ALL)

    # Convert to the list of frames
    tb = exc_tb
    frames = []
    while tb:
        frames.append(tb.tb_frame)
        tb = tb.tb_next

    i0 = len(frames) - 1 - getattr(exc_value, "skip_frames", 0)
    indent = " " * (len(exc_type.__name__) + 2)
    for i in range(i0, 0, -1):
        co = frames[i].f_code
        func = _find_function_from_code(frames[i - 1], co)
        fullname = _get_method_full_name(func) if func else "???." + co.co_name
        highlight = getattr(exc_value, "var_name", None) if i == i0 else None
        args_str = _get_args_str(func, highlight=highlight)
        indent_len = len(exc_type.__name__) + len(fullname) + 6
        line = Fore.LIGHTBLACK_EX + indent + ("in " if i == i0 else "   ")
        line += (Fore.CYAN + fullname + Fore.LIGHTBLACK_EX if i == i0 else fullname) + "("
        line += _wrap(args_str + ") line %d" % frames[i].f_lineno, indent=indent_len)
        line += Style.RESET_ALL
        err(line)
    err()

    colorama.deinit()
Ejemplo n.º 17
0
	def generateMoveList(self, row, col, needJump=False):
		init()
		if self.game == self.checkers:
			moveList = []
			if self.square[row][col].topDir in self.square[row][col].myDir:				#Top-style movement
				if not needJump:
					if col < len(self.square[row])-1 and row < len(self.square)-1:		#Down-right
						moveList.append([row+1, col+1])
					if col > 0 and row < len(self.square)-1:							#Down-left
						moveList.append([row+1, col-1])
				if row < len(self.square)-2 and col > 1:								#Top-style jumping (left)
					if self.square[row+1][col-1].color not in [self.square[row][col].color, self.square[row][col].empty]:
						moveList.append([row+2, col-2])
				if row < len(self.square)-2 and col < len(self.square[row])-2:			#Top-style jumping (right)
					if self.square[row+1][col+1].color not in [self.square[row][col].color, self.square[row][col].empty]:
						moveList.append([row+2, col+2])		
			if self.square[row][col].botDir in self.square[row][col].myDir:				#Bot-style movement
				if not needJump:
					if col < len(self.square[row])-1 and row > 0:						#Up-right
						moveList.append([row-1, col+1])
					if col > 0 and row > 0:												#Up-left
						moveList.append([row-1, col-1])
				if row > 1 and col > 1:													#Bot-style jumping (left)
					if self.square[row-1][col-1].color not in [self.square[row][col].color, self.square[row][col].empty]:
						moveList.append([row-2, col-2])
				if row > 1 and col < len(self.square[row])-2:							#Bot-style jumping (right)
					if self.square[row-1][col+1].color not in [self.square[row][col].color, self.square[row][col].empty]:
						moveList.append([row-2, col+2])
			
			validMoves = []
			for i in moveList:														#Is that square empty/on the board?
				if self.square[i[0]][i[1]].color == self.emptySpace:
					validMoves.append(i)
			return validMoves
Ejemplo n.º 18
0
def print_queue(sonos):
    queue = sonos.get_queue()

    ANSI_BOLD = '\033[1m'
    ANSI_RESET = '\033[0m'

    # colorama.init() takes over stdout/stderr to give cross-platform colors
    if colorama:
        colorama.init()

    current = int(sonos.get_current_track_info()['playlist_position'])

    queue_length = len(queue)
    padding = len(str(queue_length))

    for idx, track in enumerate(queue, 1):
        if (idx == current):
            color = ANSI_BOLD
        else:
            color = ANSI_RESET

        idx = str(idx).rjust(padding)
        print(
            "%s%s: %s - %s. From album %s." % (
                color,
                idx,
                track['artist'],
                track['title'],
                track['album']
            )
        )

    # Release stdout/stderr from colorama
    if colorama:
        colorama.deinit()
 def __enter__(self):
     if readline_loaded:
         if readline.__doc__ and 'libedit' in readline.__doc__:
             readline.parse_and_bind("bind '\t' rl_complete")  # Enable tab completions on MacOS
         else:
             readline.parse_and_bind("tab: complete")  # and on other OSs
         readline.parse_and_bind("set completion-ignore-case on")
         readline.parse_and_bind("set show-all-if-ambiguous on")
         readline.parse_and_bind("set completion-map-case on")
         readline.parse_and_bind("set show-all-if-unmodified on")
         readline.parse_and_bind("set expand-tilde on")
         history_file_dir = appdirs.user_data_dir(self.this_program_name, self.this_program_name)
         os.makedirs(history_file_dir, exist_ok=True)
         self.history_file_path = os.path.join(history_file_dir, "." + self.this_program_name + "_console_history")
         try:
             readline.read_history_file(self.history_file_path)
         except Exception:  # Corrupt or non existent history file might raise an exception
             try:
                 os.remove(self.history_file_path)
             except Exception:
                 pass  # if removing the file also fail - just ignore it
     if colorama_loaded:
         colorama.init()
     self.prompt = self.this_program_name + ": "
     self.save_dir = os.getcwd()
     return self
Ejemplo n.º 20
0
def main():
    arguments = docopt(__doc__, version=__version__)

    quantity = int(arguments['--quantity'])

    chain = MarkovChain(
        min_length=int(arguments['--min']),
        max_length=int(arguments['--max']),
    )

    if arguments['--json']:
        output = {'quantity': quantity}
        output['names'] = list(islice(chain.unique_word(), quantity))
        print(json.dumps(output))
    else:
        init(autoreset=True)

        for i, word in enumerate(chain.unique_word()):
            if i == quantity:
                break

            line = '{:>3}. {:<12}'.format(i + 1, word)

            if arguments['--nocolour']:
                print(line)
            else:
                # alternate row colours
                colour = Fore.BLUE if i % 2 == 0 else Fore.CYAN
                print(Style.BRIGHT + colour + line)
Ejemplo n.º 21
0
 def make_print():
     if(args.color):
         import colorama
         colorama.init()
         color_dict = {"default": "",
         "header": colorama.Back.WHITE + colorama.Fore.BLACK,
         "zebra_0": "",
         "zebra_1": colorama.Style.BRIGHT,
         "WARN": colorama.Fore.YELLOW,
         "ERROR": colorama.Fore.RED}
         def n_print(*args, **kwargs):
             """Print with colors"""
             try:
                 c = color_dict[kwargs.pop("color")]
                 args = (c + str(args[0]),) + args[1:] + (colorama.Style.RESET_ALL,)
             except KeyError as e:
                 pass
             except IndexError as e:
                 pass
             return __builtin__.print(*args, **kwargs)
     else:
         def n_print(*args, **kwargs):
             if("color" in kwargs):
                 kwargs.pop('color')
             return __builtin__.print(*args, **kwargs)
     return n_print
Ejemplo n.º 22
0
    def runtest(self):
        if not ChefTestItem.__initialized_logging__:
            colorama.init()
            hdl = logging.StreamHandler(stream=sys.stdout)
            logging.getLogger().addHandler(hdl)
            logging.getLogger().setLevel(logging.INFO)
            ChefTestItem.__initialized_logging__ = True

        fs = self._prepareMockFs()

        argv = self.spec['args']
        if isinstance(argv, str):
            argv = argv.split(' ')

        expected_code = self.spec.get('code', 0)
        expected_out = self.spec.get('out', '')

        with mock_fs_scope(fs):
            memstream = io.StringIO()
            hdl = logging.StreamHandler(stream=memstream)
            logging.getLogger().addHandler(hdl)
            try:
                from piecrust.main import PreParsedChefArgs, _run_chef
                pre_args = PreParsedChefArgs(
                        root=fs.path('/kitchen'))
                exit_code = _run_chef(pre_args, argv)
            finally:
                logging.getLogger().removeHandler(hdl)

            assert expected_code == exit_code
            assert expected_out == memstream.getvalue()
Ejemplo n.º 23
0
def main():
    usage = """\
    usage: hc [code] [options]

    code may contain regular expression or use 'x' to denote any digit
    code examples: 418, 30[12], 3.*, 1xx

    Without parameters lists all available
    HTTP status codes and their description
    """
    parser = optparse.OptionParser(usage=textwrap.dedent(usage))
    parser.add_option(
        '-s', '--search', dest='search',
        help=('Search for a code by name or description. '
              'Search text may contain regular expressions.')
        )
    options, args = parser.parse_args()

    # initialize colorama
    init()

    if options.search is not None:
        _print_search(options.search)
    elif args:
        code = args[0]
        if _IS_THREE_DIGIT_CODE(code):
            _print_code(int(code))
        else:
            _print_filtered_codes(code)
    else:
        _print_codes()
Ejemplo n.º 24
0
def main(args, app_dir=None):
    """Main entry points.

  Args:
    args: command line arguments excluding executable name.
    app_dir: directory with app.yaml, or None to autodiscover based on __file__.
  """
    # Search for app.yaml in parent directory. If found, it means gae.py was
    # symlinked to some GAE app directory. Such symlink allows to avoid typing
    # --app-dir parameter all the time.
    if app_dir is None:
        script_dir = os.path.dirname(os.path.abspath(__file__))
        app_yaml_path = gae_sdk_utils.find_app_yaml(script_dir)
        if app_yaml_path:
            app_dir = os.path.dirname(app_yaml_path)

    colorama.init()
    dispatcher = subcommand.CommandDispatcher(__name__)
    try:
        return dispatcher.execute(OptionParser(app_dir), args)
    except gae_sdk_utils.LoginRequiredError:
        print >>sys.stderr, "Login first using 'login' subcommand."
        return 1
    except KeyboardInterrupt:
        # Don't dump stack traces on Ctrl+C, it's expected flow in some commands.
        print >>sys.stderr, "\nInterrupted"
        return 1
Ejemplo n.º 25
0
def main():
    # Initialise colorama
    init()
    # Show title screen
    title()
    # Main game loop
    while True:
        # Check if the player's health is below zero and end the game
        if player["health"] <= 0:
            nice_print("You have died! Game over!", Fore.RED)
            quit()

        # Check if the player has met the victory condition and end the game    
        if item_fire in player["inventory"]:
            nice_print_line("Your fire now burns brightly on the top of the cliffs")
            nice_print_line("Any passing planes or ships are sure to see you on the island")
            nice_print_line("But will anyone arrive in time, or is it already too late for you?")
            nice_print_line("Only time will decide")
            credits(1)
            quit()

        # Display game status (location description, inventory etc.)
        print_location(player["current_location"])
        if player["current_location"]["enemy"]:
            combat(player["current_location"]["enemy"])
            print_location(player["current_location"])
        print_player(player)
        print_inventory_items(player["inventory"])

        # Show the menu with possible actions and ask the player
        command = menu(player["current_location"]["exits"], player["current_location"]["items"], player["inventory"])

        # Execute the player's command - repeat the options if the command cannot be performed
        while not execute_command(command):
            command = menu(player["current_location"]["exits"], player["current_location"]["items"], player["inventory"])
Ejemplo n.º 26
0
def main(args):
  # gae.py may be symlinked into app's directory or its subdirectory (to avoid
  # typing --app-dir all the time). If linked into subdirectory, discover root
  # by locating app.yaml. It is used for Python GAE apps and one-module Go apps
  # that have all YAMLs in app root dir.
  app_dir = None
  if IS_SYMLINKED:
    script_dir = os.path.dirname(os.path.abspath(__file__))
    app_dir = find_app_dir(script_dir)

  # If not symlinked into an app directory, try to discover app root starting
  # from cwd.
  app_dir = app_dir or find_app_dir(os.getcwd())

  colorama.init()
  dispatcher = subcommand.CommandDispatcher(__name__)
  try:
    return dispatcher.execute(OptionParser(app_dir), args)
  except gae_sdk_utils.BadEnvironmentConfig as e:
    print >> sys.stderr, str(e)
    return 1
  except gae_sdk_utils.LoginRequiredError:
    print >> sys.stderr, 'Login first using \'login\' subcommand.'
    return 1
  except KeyboardInterrupt:
    # Don't dump stack traces on Ctrl+C, it's expected flow in some commands.
    print >> sys.stderr, '\nInterrupted'
    return 1
Ejemplo n.º 27
0
    def init(self):
        co.init()
        self.logwrite("\n\n" + time.strftime("%c"))

        self.lprint("Welcome to " + self.name + "!")

        if os.geteuid():
            self.print_err("You need to run this as root!")
            sys.exit(1)

        self.checkdep()

        if not re.match("^/dev/((h|s)d[a-z]+|mmcblk[0-9]+)$", self.sdcard):
            self.print_err("Wrong sdcard format! Should be in the form"
                           "/dev/[hdX|sdX|mmcblkX] eg. /dev/sda or"
                           "/dev/mmcblk0")
            sys.exit(1)

        if not os.path.exists(self.sdcard):
            self.print_err("SD card path does not exist.")
            sys.exit(1)

        self.lprint(co.Fore.RED + "This is your last chance to abort!" +
                    co.Fore.RESET)
        self.print_warn("Your sdcard is %s. Is that right? [yN] "
                        % self.sdcard)
        if input().lower() not in ["y", "yes"]:
            self.lprint("OK. Aborting ...")
            sys.exit(0)

        self.tmp = tm.mkdtemp()
Ejemplo n.º 28
0
    def __init__(self, logdir, logfile, logformat=None, datefmt=None, logfilemode='w',
                 verbose=False, interactive=False):
        init(autoreset=True)
        self.logdir = logdir
        self.logfile = logfile
        self.interactive = interactive
        self.verbose = verbose
        self.interactive_format = '{level:<8s} {msg:<1s}'

        if not os.path.exists(self.logdir):
            os.makedirs(self.logdir)

        if self.verbose:
            self.level = logging.DEBUG
        else:
            self.level = logging.INFO

        if logformat:
            self.format = logformat
        else:
            self.format = '%(asctime)s %(levelname)-8s %(message)s'

        if datefmt:
            self.datefmt = datefmt
        else:
            self.datefmt = '%Y-%m-%d %H:%M:%S'

        logging.basicConfig(level=self.level,
                            format=self.format,
                            datefmt=self.datefmt,
                            filename=os.path.join(self.logdir, self.logfile),
                            filemode=logfilemode)
Ejemplo n.º 29
0
def _get_color_printer(stream=sys.stdout, colors=True, rank=0):
    """
    Return a print function tied to a particular stream, along with coloring info.
    """
    try:
        from colorama import init, Fore, Back, Style
        init(autoreset=True)
    except ImportError:
        Fore = Back = Style = _NoColor()

    if not colors:
        Fore = Back = Style = _NoColor()

    if MPI and MPI.COMM_WORLD.rank != rank:
        if rank >= MPI.COMM_WORLD.size:
            if MPI.COMM_WORLD.rank == 0:
                print("Specified rank (%d) is outside of the valid range (0-%d)." %
                      (rank, MPI.COMM_WORLD.size - 1))
            sys.exit()
        def color_print(s, **kwargs):
            pass
    else:
        def color_print(s, fore='', color='', end=''):
            """
            """
            print(color + s, file=stream, end='')
            print(Style.RESET_ALL, file=stream, end='')
            print(end=end)

    return color_print, Fore, Back, Style
Ejemplo n.º 30
0
    def __init__(self, argv, root=False):

        if root:
            if getpass.getuser() != "root":
                print "Must run as root"
                exit(1)

        self.argv = argv
        self.optparser = OptionParser(version=RELEASE)
        self.opt = None
        self.args = None

        common_opts = OptionGroup(
            self.optparser, "Common options", "These options are common to all Globus Provision commands"
        )
        self.optparser.add_option_group(common_opts)

        common_opts.add_option("-v", "--verbose", action="store_true", dest="verbose", help="Produce verbose output.")

        common_opts.add_option(
            "-d", "--debug", action="store_true", dest="debug", help="Write debugging information. Implies -v."
        )

        common_opts.add_option(
            "-i",
            "--instances-dir",
            action="store",
            type="string",
            dest="dir",
            default=defaults.INSTANCE_LOCATION,
            help="Use this directory to store information about the instances "
            "(instead of the default ~/.globusprovision/instances/)",
        )

        colorama.init(autoreset=True)
Ejemplo n.º 31
0
        if not l:
            continue

        chunk = np.fromstring(data, dtype=np.int16)
        dom = dominant(frame_rate, chunk)

        if in_packet and match(dom, HANDSHAKE_END_HZ):
            print("Received End hand shake")
            byte_stream = extract_packet(packet)

            try:
                byte_stream = RSCodec(FEC_BYTES).decode(byte_stream)
                display(str(byte_stream))
                display("")
            except ReedSolomonError as e:
                print("{}: {}".format(e, byte_stream))

            packet = []
            in_packet = False
        elif in_packet:
            packet.append(dom)
        elif match(dom, HANDSHAKE_START_HZ):
            print("Received Start hand shake")
            in_packet = True

if __name__ == '__main__':
    colorama.init(strip=not sys.stdout.isatty())

    #decode_file(sys.argv[1], float(sys.argv[2]))
    listen_linux()
Ejemplo n.º 32
0
import xlrd
from colorama import init, Style, Fore
from getkey import getkey, keys

__version__ = "2019-7-18 version: 0.9"

IS_PY3 = sys.version_info > (3, 3)
IS_WIN = os.name == "nt"
# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') 

if not IS_PY3:
	reload(sys)
	sys.setdefaultencoding("utf-8")

osp = os.path
init(autoreset=True)

def get_str_bytes(s):
	# 从excel读取的内容(由于系统编码被设置为utf-8,所以内容为utf-8)
	try:
		return s.decode("utf-8")
	except:
		return s

def convert_to_utf8(s):
	# 从系统读取的文件名,例如:路径名
	try:
		if IS_WIN:
			return s.decode("gbk", "ignore")
		else:
			return s.decode("utf-8")
Ejemplo n.º 33
0
if (sys.version_info[0] != 2) or (sys.version_info[1] < 6):
    exit("\nYou're running Python version {0}.{1}.{2}.\nW.R.E.C.K. requires Python version 2.6.x or 2.7.x to run!\n".format(*sys.version_info[0:3]))
sys.dont_write_bytecode = True

from time import time as gettime
from os import makedirs

from traceback import extract_tb

# Color support
if 'bw' in sys.argv:
    COLORAMA = ('', '', '', '', '', '', '', '')
else:
    try:
        import colorama
        colorama.init()
        COLORAMA = ('\x1b[0m', '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[35m', '\x1b[36m', '\x1b[37m')
    except:
        COLORAMA = ('', '', '', '', '', '', '', '')

from compiler import *



write_id_files = "ID_%s.py" # Where the compiler will write new iteration ID-files.
show_performance_data = False # Set to true to display compiler performance data by default.
export_filename = '%s.txt' # How to name export files (only used for some debugging purposes).

WRECK.time_started = gettime()

Ejemplo n.º 34
0
import re
import typing
import warnings
from collections import defaultdict
from dataclasses import dataclass, field, fields
from statistics import median
from threading import Lock, RLock, Thread
from typing import List

import colorama
from colorama import Back, Fore, Style

from . import helpers
from .locks import SLock

colorama.init(autoreset=True)

COLORS = {
    "CRITICAL": Fore.RED,
    "WARNING": Fore.RED,
    "CAUTION": Fore.YELLOW,
    "IMPORTANT": Fore.CYAN,
    "GOOD": Fore.GREEN,
}


def getDimentions() -> typing.Tuple[int]:
    return (int(x) for x in os.popen("stty size", "r").read().split())


def getRows() -> int:
Ejemplo n.º 35
0
from dateClass import Date
from plateClass import Plate
from timeClass import Time
import datetime
from constantsClass import Constants
from colorama import Back, Fore, init, Style
init()

if __name__ == "__main__":
    print(
        Fore.BLUE +
        "Welcome, insert plate, time and date to consult if you are under restriction to circulate\n"
        + Style.RESET_ALL)
    """
    Receiving plate, input and date of user's vehicle
    For all of them, checking whether the info is in the right format
    """
    while True:
        plateInput = input(
            "Please, insert the plate number of your vehicle: ").upper()
        if not Constants.PLATEPATTERN.match(plateInput):
            print("Sorry, the correct format is: AAA111 or AAA1111")
            continue
        else:
            plate = Plate(plateInput)
            break

    while True:
        dateInput = input(
            "Please, insert the date (dd-mm-yyyy) you want to consult: ")
        try:
from lib.parser_html import Parsing
from lib.request import Browser
from colorama import Fore
import argparse
import colorama
import time
import os


colorama.init(True)


class Unactive:
    def __init__(self, ses=None) -> None:
        self._params = {}
        self.__ses = ses

    def login(self, session):
        data = Parsing(session.get('profile.php').text)
        if "mbasic_logout_button" in str(data.to_bs4):
            friends = data.find_url('friends?lst')
            self._params.update({'friends': friends})
            self.__ses = session
            return True

    def unfriend(self, user):
        link_unfriend = Parsing(self.__ses.get(
            user["url"]).content).find_url('removefriend')
        form = Parsing(self.__ses.get(
            link_unfriend).content).parsing_form('remove')
        action = form["action"]
Ejemplo n.º 37
0
    import threading
    import requests
except:
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])

try:
    import twint
except ImportError:
    subprocess.check_call([
        sys.executable, "-m", "pip", "install", "--user", "--upgrade",
        "git+https://github.com/twintproject/twint.git@origin/master#egg=twint"
    ])
    import twint

init(convert=True)


# Config class for retrieving Binance credentials from .toml file
class Config:
    def __init__(self):
        self.config = toml.load('data/config.toml')
        if self.config["binance"]:
            binance = self.config["binance"]
            self.api_key = binance["api_key"]
            self.secret_key = binance["secret_key"]

    def get_toml(self):
        self.config = toml.load('data/config.toml')
        binance = self.config["binance"]
        self.api_key = binance["api_key"]
Ejemplo n.º 38
0
                        "label": "Discord Server",
                        "url": "https://discord.gg/k48Ht5y"
                    },
                ],
            )
            debugOutput("Rich presence updated")
        except:  # Discord not launched
            if debug == "y":
                raise
        time.sleep(15)  # 15 seconds to respect Discord rate limit


if __name__ == "__main__":
    multiprocessing.freeze_support()
    cpu = cpuinfo.get_cpu_info()  # Processor info
    init(autoreset=True)  # Enable colorama
    title(getString("duco_python_miner") + str(minerVersion) + ")")

    try:
        loadConfig()  # Load config file or create new one
        debugOutput("Config file loaded")
    except:
        print(now().strftime(Style.DIM + "%H:%M:%S ") + Style.RESET_ALL +
              Style.BRIGHT + Back.GREEN + Fore.WHITE + " sys0 " +
              Style.RESET_ALL + Style.BRIGHT + Fore.RED +
              getString("load_config_error") + resourcesFolder +
              getString("load_config_error_warning") + Style.RESET_ALL)
        if debug == "y":
            raise
        time.sleep(10)
        os._exit(1)
Ejemplo n.º 39
0
def main():
    colorama.init()
    parser = argparse.ArgumentParser(epilog="supported data file formats:\n" +
                                     DataParser.format_parsers(),
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('filename',
                        type=str,
                        nargs='+',
                        help="filename of data file")
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%s v%s' % (parser.prog, __version__))
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help="enable debug logging")
    parser.add_argument('-uc',
                        '--unconfirmed',
                        action='store_true',
                        help="include unconfirmed transactions")
    parser.add_argument('-ca',
                        dest="cryptoasset",
                        type=str,
                        help="specify a cryptoasset symbol, if it cannot be identified "
                             "automatically")
    parser.add_argument('--duplicates',
                        action='store_true',
                        help="remove any duplicate input rows across data files")
    parser.add_argument('--format',
                        choices=[config.FORMAT_EXCEL, config.FORMAT_CSV, config.FORMAT_RECAP],
                        default=config.FORMAT_EXCEL,
                        type=str.upper,
                        help="specify the output format, default: EXCEL")
    parser.add_argument('-nh',
                        '--noheader',
                        action='store_true',
                        help="exclude header from CSV output")
    parser.add_argument('-a',
                        '--append',
                        action='store_true',
                        help="append original data as extra columns in the CSV output")
    parser.add_argument('-s',
                        '--sort',
                        action='store_true',
                        help="sort CSV output by timestamp")
    parser.add_argument('-o',
                        dest='output_filename',
                        type=str,
                        help="specify the output filename")

    args = parser.parse_args()
    config.debug = args.debug
    DataFile.remove_duplicates = args.duplicates

    if config.debug:
        sys.stderr.write("%s%s v%s\n" % (Fore.YELLOW, parser.prog, __version__))
        sys.stderr.write("%spython: v%s\n" % (Fore.GREEN, platform.python_version()))
        sys.stderr.write("%ssystem: %s, release: %s\n" % (
            Fore.GREEN, platform.system(), platform.release()))

    for filename in args.filename:
        pathnames = glob.glob(filename)
        if not pathnames:
            pathnames = [filename]

        for pathname in pathnames:
            try:
                do_read_file(pathname, args)
            except UnknownCryptoassetError as e:
                sys.stderr.write(Fore.RESET)
                parser.error("%s, please specify using the [-ca CRYPTOASSET] option" % e)
            except UnknownUsernameError as e:
                sys.stderr.write(Fore.RESET)
                parser.exit("%s: error: %s, please specify usernames in the %s file" % (
                    parser.prog, e, config.BITTYTAX_CONFIG))
            except DataFilenameError as e:
                sys.stderr.write(Fore.RESET)
                parser.exit("%s: error: %s" % (parser.prog, e))
            except DataFormatUnrecognised as e:
                sys.stderr.write("%sWARNING%s %s\n" % (
                    Back.YELLOW+Fore.BLACK, Back.RESET+Fore.YELLOW, e))
            except IOError as e:
                if e.errno == errno.ENOENT:
                    sys.stderr.write("%sWARNING%s File does not exist: %s\n" % (
                        Back.YELLOW+Fore.BLACK, Back.RESET+Fore.YELLOW, pathname))
                elif e.errno == errno.EISDIR:
                    sys.stderr.write("%sWARNING%s File is a directory: %s\n" % (
                        Back.YELLOW+Fore.BLACK, Back.RESET+Fore.YELLOW, pathname))
                else:
                    sys.stderr.write("%sWARNING%s File could not be read: %s\n" % (
                        Back.YELLOW+Fore.BLACK, Back.RESET+Fore.YELLOW, pathname))

    if DataFile.data_files:
        if args.format == config.FORMAT_EXCEL:
            output = OutputExcel(parser.prog, DataFile.data_files_ordered, args)
            output.write_excel()
        else:
            output = OutputCsv(DataFile.data_files_ordered, args)
            sys.stderr.write(Fore.RESET)
            sys.stderr.flush()
            output.write_csv()
Ejemplo n.º 40
0
Archivo: api.py Proyecto: hhy5277/pdir2
import inspect
from itertools import groupby
from sys import _getframe

from colorama import init

from .constants import ATTR_MAP, CLASS, DEFAULT_CATEGORY, FUNCTION
from .format import format_category

init()  # To support Windows.


class PrettyDir(object):
    """Class that provides pretty dir and search API."""

    def __init__(self, obj=None):
        self.obj = obj
        self.attrs = []
        if obj is None:
            source = _getframe(1).f_locals
        else:
            source = {name: self.__getattr(name) for name in dir(obj)}
        self.__inspect_category(source)

    def __repr__(self):
        output = []
        for category, attrs in groupby(self.attrs, lambda x: x.category):
            output.append(format_category(category, attrs))

        output.sort(key=lambda x: x[0])
        return '\n'.join(category_output[1] for category_output in output)
#This code was written by Kalen Willits
import os  #Uses the operating system's clear screen funtion to refresh the terminal
import time  #Allows the use of time.sleep funtion to delay a refresh
import keyboard  #Listens to keyboard events -> Also can generate keyboard events
from colorama import init, deinit, Fore, Back, Style  #Allows the use of different colors
init()  #Initializes colorama, this is only required for windows OS.
print(Fore.BLACK + Back.BLACK
      )  #Sets the default color to all black. This hides keyboard inputs
import cursor
cursor.hide()  #hides the blinking cursor
##################################Variable Library##############################
menu = ['Option Zero', 'Option One', 'Option Two', 'Exit']


################################################################################
def navigate(idx):
    key = keyboard.read_key()
    key = keyboard.read_key()

    if key == 'up':
        idx -= 1

    if key == 'down':
        idx += 1

    if key == 'enter':
        page_fuction(idx)

    return idx  #listens to keyboard inputs and changes the index(idx).

Ejemplo n.º 42
0
from bs4 import BeautifulSoup
import requests
import lxml
import replit
import colorama as cr
replit.clear()

cr.init(autoreset=True)

SubReddit = input(
    "Which subreddit would you like to see popular posts for? r/").lower()

print("wait for the posts to load...")

url = ('https://www.reddit.com/r/' + SubReddit + '/top/?t=all')

headers = {
    'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9'
}

response = requests.get(url, headers=headers)

soup = BeautifulSoup(response.content, 'lxml')

Title = soup.title

print(url)
print('')
print('')
print(f"{cr.Fore.GREEN}there are no ads on this version of reddit!")
Ejemplo n.º 43
0
def main():
    # Colorama module's initialization.
    init(autoreset=True)

    version_string = f"%(prog)s {__version__}\n" +  \
                     f"{requests.__description__}:  {requests.__version__}\n" + \
                     f"Python:  {platform.python_version()}"

    parser = ArgumentParser(
        formatter_class=RawDescriptionHelpFormatter,
        description=f"{module_name} (Version {__version__})")
    parser.add_argument("--version",
                        action="version",
                        version=version_string,
                        help="Display version information and dependencies.")
    parser.add_argument("--verbose",
                        "-v",
                        "-d",
                        "--debug",
                        action="store_true",
                        dest="verbose",
                        default=False,
                        help="Display extra debugging information.")
    parser.add_argument("--quiet",
                        "-q",
                        action="store_false",
                        dest="verbose",
                        help="Disable debugging information (Default Option).")
    parser.add_argument(
        "--tor",
        "-t",
        action="store_true",
        dest="tor",
        default=False,
        help=
        "Make requests over TOR; increases runtime; requires TOR to be installed and in system path."
    )
    parser.add_argument(
        "--unique-tor",
        "-u",
        action="store_true",
        dest="unique_tor",
        default=False,
        help=
        "Make requests over TOR with new TOR circuit after each request; increases runtime; requires TOR to be installed and in system path."
    )

    args = parser.parse_args()

    # Load the data
    data_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  "data.json")
    with open(data_file_path, "r", encoding="utf-8") as raw:
        site_data_all = json.load(raw)

    #Setup logging to show informational messages.
    logging.basicConfig()
    logging.getLogger().setLevel(logging.INFO)

    result_summary = []
    site_data = {
        site: site_data_all[site]
        for site in ['Twitter', 'eBay'] if site in site_data_all
    }
    result_summary.append(
        sherlock_test(['hoadlck'], ['hoadlckblah'], site_data, args.verbose,
                      args.tor, args.unique_tor))

    if all(result_summary):
        logging.info(f"All tests succeeded!")
    else:
        logging.error(f"One of more tests failed!")

    return
Ejemplo n.º 44
0
        return "%s%s%s" % (colorama.Fore.WHITE, text, colorama.Style.RESET_ALL)

    def blue(text):
        return "%s%s%s" % (colorama.Fore.BLUE, text, colorama.Style.RESET_ALL)

    def red(text):
        return "%s%s%s" % (colorama.Fore.RED, text, colorama.Style.RESET_ALL)

    def green(text):
        return "%s%s%s" % (colorama.Fore.GREEN, text, colorama.Style.RESET_ALL)

    def yellow(text):
        return "%s%s%s" % (colorama.Fore.YELLOW, text,
                           colorama.Style.RESET_ALL)

    sys.platform == "win32" and colorama.init()
except ImportError:

    def bright(text):
        return text

    def dim(text):
        return text

    def white(text):
        return text

    def blue(text):
        return text

    def red(text):
import gym
from gym.envs.registration import register
from colorama import init
from kbhit import KBHit

init(autoreset=True)  # Reset the terminal mode to display ansi color

register(id='FrozenLake-v3',
         entry_point='gym.envs.toy_text:FrozenLakeEnv',
         kwargs={
             'map_name': '4x4',
             'is_slippery': False
         })

env = gym.make('FrozenLake-v3')
env.render()

key = KBHit()

while True:

    action = key.getarrow()
    if action not in [0, 1, 2, 3]:
        print("Game aborted!")
        break

    state, reward, done, info = env.step(action)
    env.render()
    print("State: ", state, "Action: ", action, "Reward: ", reward, "Info: ",
          info)
Ejemplo n.º 46
0
 def __init__(self):
     # `autoreset` allows us to not have to sent reset sequences for every
     # string. `strip` lets us preserve color when redirecting.
     colorama.init(autoreset=True, strip=False)
Ejemplo n.º 47
0
    try:
        _unicode = unicode
    except NameError:
        _unicode = str

    try:
        if IS_WIN:
            import colorama
        else:
            raise ImportError
    except ImportError:
        colorama = None
    else:
        try:
            colorama.init(strip=False)
        except TypeError:
            colorama.init()

    try:
        from weakref import WeakSet
    except ImportError:
        WeakSet = set

    try:
        _basestring = basestring
    except NameError:
        _basestring = str

    try:  # py>=2.7,>=3.1
        from collections import OrderedDict as _OrderedDict
Ejemplo n.º 48
0
def run_pattern2(sql_sentence):
    colorama.init()
    result = parse_sql(sql_sentence)
    if result[0] == 1:
        print(Fore.BLUE + sql_sentence[:result[1]], end='')
        print(Fore.WHITE + sql_sentence[result[1]:])
    elif result[0] == 2:
        # {keywords: [], runstreams: [], runningstream: []}
        # 运行的数据流绿色, 关键字黄色, 正在运行的数据流
        # 红色
        keywords = result[1]["keywords"]
        runstreams = result[1]["runstreams"]
        runningstreams = result[1]["runningstreams"]
        for i in range(len(sql_sentence)):
            yellow = False
            for keyword in keywords:
                if keyword[0] <= i <= keyword[1]:
                    yellow = True
                    break
            green = False
            for runstream in runstreams:
                if runstream[0] <= i <= runstream[1]:
                    green = True
                    break
            red = False
            for runningstream in runningstreams:
                if runningstream[0] <= i <= runningstream[1]:
                    red = True
                    break
            if yellow:
                print(Fore.YELLOW + sql_sentence[i], end='')
            elif green:
                print(Fore.GREEN + sql_sentence[i], end='')
            elif red:
                print(Fore.RED + sql_sentence[i], end='')
            else:
                print(Fore.WHITE + sql_sentence[i], end='')
        print()
    elif result[0] == 3:

        data = result[1]
        list_maxchar = []
        for i in range(len(data[0])):
            list_maxchar.append(10)

        for i in range(len(data)):
            each_line = data[i]
            for j in range(len(each_line)):
                content = str(data[i][j])
                _len = 0
                for ch in content:
                    if '\u4e00' <= ch <= '\u9fff':
                        _len += 2
                    else:
                        _len += 1
                if _len > list_maxchar[j]:
                    list_maxchar[j] = (int((_len - 1) / 10) + 1) * 10

        # 打印最后结果

        for i in range(len(data)):
            each_line = data[i]
            for j in range(len(each_line)):
                content = str(data[i][j])
                _len = 0
                for ch in content:
                    if '\u4e00' <= ch <= '\u9fff':
                        _len += 1
                content_print = content.rjust(list_maxchar[j] - _len, ' ')
                print(content_print, end='|')
            print()
Ejemplo n.º 49
0
    __version__ = qsharp.version.version
except ImportError:
    __version__ = "<unknown>"

# CLR Imports #

import clr

import System.Threading.Tasks
import Microsoft.Quantum.Simulation.Simulators as mqss

# External Python Imports #

try:
    import colorama as ca
    ca.init()

    SIMULATOR_COLOR = ca.Fore.BLUE + ca.Back.WHITE
    RESET_COLOR = ca.Style.RESET_ALL
except:
    ca = None
    SIMULATOR_COLOR = ""
    RESET_COLOR = ""

try:
    import qutip as qt
except:
    qt = None

try:
    from IPython.display import display
Ejemplo n.º 50
0
# Communicating with Benchtop YOKOGAWA dc-power supply
# Communicating with Benchtop PSG
from colorama import init, Fore, Back

init(autoreset=True)  #to convert termcolor to wins color

from os.path import basename as bs

mdlname = bs(__file__).split('.')[
    0]  # model's name e.g. ESG, PSG, AWG, VSA, ADC
debugger = 'debug' + mdlname

import visa
from functools import wraps
from time import sleep, time
from contextlib import suppress
from pyqum.instrument.logger import address, set_status, status_code
from pyqum.instrument.toolbox import waveform


def debug(state=False):
    exec('%s %s; %s = %s' % ('global', debugger, debugger, 'state'), globals(),
         locals())  # open global and local both-ways channels!
    if state:
        print(Back.RED + '%s: Debugging Mode' % debugger.replace('debug', ''))
    return


debug()  # declare the debugger mode here

Ejemplo n.º 51
0
def run_cash_show_assistant(
    nom_jeu, num_quest
):  #num_quest pour ouvrir onglet avec la recherche de la question ouverte pour la dernière question de QUIDOL

    f_debug = 2  #activation du log 0/1/2 => 2 Détaillé avec horodatages

    #Fonction de récupération de la fenêtre
    def _get_windows_bytitle(title_text, exact=True):
        def _window_callback(hwnd, all_windows):
            all_windows.append((hwnd, win32gui.GetWindowText(hwnd)))

        windows = []
        win32gui.EnumWindows(_window_callback, windows)
        if exact:
            return [hwnd for hwnd, title in windows if title_text == title]
        else:
            return [hwnd for hwnd, title in windows if title_text in title]

    #Fonction de screenshot de la fenêtre complète
    def screenshot(hwnd=None):
        if not hwnd:
            hwnd = win32gui.GetDesktopWindow()

        l, t, r, b = win32gui.GetWindowRect(hwnd)

        win32gui.SetForegroundWindow(hwnd)
        sleep(0.1)  #lame way to allow screen to draw before taking shot

        return grab_part(l, t, r, b)

    #Fonction de grab V2
    def grab_part(left, top, right, bottom):
        width = right - left
        height = bottom - top
        with mss.mss() as sct:
            # The screen part to capture
            monitor = {
                'top': top,
                'left': left,
                'width': width,
                'height': height
            }
            # Grab the data
            sct_img = sct.grab(monitor)
            # Create an Image
            img = ImageScreen.frombytes('RGB', sct_img.size, sct_img.bgra,
                                        'raw', 'BGRX')
            #img.show()  #debug pour afficher l'image découpée
            img.save('ecranfull.png')
            return img

    def crop_zones(image, coord):
        left, top, right, bottom = coord.replace(" ", "").split(",")
        box = (int(left), int(top), int(right), int(bottom))
        im = image.crop(box)
        #zone.show()
        return im

    #Fonction de preprocessing de l'image
    def pre_process_image(img):
        img = img.convert('L')
        enhancer = ImageEnhance.Contrast(img)
        img = enhancer.enhance(2)
        if nom_jeu == 'FLASHBREAK':
            enhancer = ImageEnhance.Sharpness(img)
            img = enhancer.enhance(2.5)
            img = img.resize(tuple([3 * x for x in img.size]),
                             ImageScreen.LANCZOS)  #LANCZOS ou ANTIALIAS
        else:
            enhancer = ImageEnhance.Sharpness(img)
            img = enhancer.enhance(2.5)
            img = img.resize(tuple([3 * x for x in img.size]),
                             ImageScreen.LANCZOS)  #LANCZOS ou ANTIALIAS
        enhancer = ImageEnhance.Sharpness(img)
        img = enhancer.enhance(2)
        #img.show()      #debug pour afficher l'image après traitement
        return img

    #Fonction de lecture OCR
    def convert_image_to_text(img, file):
        img.save(file +
                 ".png")  #debug pour afficher l'image avant traitement OCR
        if langue == 'german':
            text = pytesseract.image_to_string(ImageScreen.open(file + ".png"),
                                               config='--psm 6 -l deu')
        else:
            text = pytesseract.image_to_string(ImageScreen.open(file + ".png"),
                                               config='--psm 6 -l fra+eng')
        text = text.replace("\n", " ")
        return text

    def trt_img(indice):
        csAnswer[indice] = pre_process_image(
            crop_zones(image, str(coord[indice])))
        temp = convert_image_to_text(csAnswer[indice],
                                     "r" + str(indice)).strip().lower()
        if langue != 'german':
            if indice == 0:
                temp = unidecode(temp.split("?", 1)[0])
            else:
                temp = unidecode(temp)
                temp = re.sub(r'[^\w\s]', ' ', temp)
        answer[indice] = temp

    #Fonction du suppression des caractères superflus
    def clean_html(html):
        # Change HTML to punctuation encoding to actul punctuation
        html = h.unescape(html)
        html = clean_me(html)
        # Get rid of HTML tags in HTML output
        cleanr = re.compile('<.*?>')
        html = re.sub(cleanr, '', html)
        html = re.sub(r'[^\w\s]', '', html)
        return html

    #Fonction de netoyage des informations reçues
    def clean_me(html):
        soup = Soup(
            html,
            "html.parser")  # create a new bs4 object from the html data loaded
        for script in soup(["script", "style"
                            ]):  # remove all javascript and stylesheet code
            script.extract()
        # get text
        text = soup.get_text()
        # break into lines and remove leading and trailing space on each
        lines = (line.strip() for line in text.splitlines())
        # break multi-headlines into a line each
        chunks = (phrase.strip() for line in lines
                  for phrase in line.split("  "))
        # drop blank lines
        text = '\n'.join(chunk for chunk in chunks if chunk)
        return text

    #Fonction de comptage des réponses dans le flux reçu
    def hash_count(html_str, answer):
        #filter out stop words in answers
        stop_words = stopwords.words(langue)
        counter = 0
        answer_arr = answer.split()
        answer_arr = [w for w in answer_arr if not w in stop_words]
        for word in answer_arr:
            if len(word) == 1 and len(
                    answer_arr
            ) == 1:  #La réponse ne contient qu'un caractère, on recherche le caractère seul
                counter = counter + html_str.count(
                    " " + word + " ")  #pour ne pas compter les fins de mots
                counter = counter + html_str.count(
                    "\n" + word + " "
                )  #pour prendre en compte les débuts de lignes de la recherche HTML
            else:
                if len(
                        word
                ) != 1:  #La réponse contient plusieurs mots, on ne recherche pas les caractères seuls
                    counter = counter + html_str.count(
                        " " + word)  #pour ne pas compter les fins de mots
                    counter = counter + html_str.count(
                        "\n" + word
                    )  #pour prendre en compte les débuts de lignes de la recherche HTML
                    if len(word) > 3 and word[
                            0] == 'l':  #cas d'une lecture erronée de l'apostrophe, on exclue le L de debut de la recherche
                        if word[0:2] == "l'":
                            counter = counter + html_str.count(word[2:])
                        else:
                            counter = counter + html_str.count(word[1:])
        return counter

    #Fonction de recherche de négation
    def is_negative():
        if langue == 'french':
            #list_neg=["pas","est+pas","a+pas","a+jamais","existe+pas","sera+pas","on+pas","il+pas"]
            list_neg = ["+pas", "jamais", "aucun"]

        if langue == 'english':
            list_neg = ["+not", "never", "none"]

        if langue == 'german':
            list_neg = ["kein", "keine", "nicht", "niemals", "+nie"]

        for i in list_neg:
            if answer[0].lower().find(i + '+') != -1:
                print("NEGATION DETECTEE AVEC '" + i + "' - A CONFIRMER")
                add_log("NEGATION DETECTEE AVEC '" + i + "' - A CONFIRMER\n",
                        1)
                return True

        return False  #pas de negation definie pour cette langue

    def is_which():
        #return False   #Comme ça ne marche pas terrible pour le moment, on désactive hors tests
        if langue == 'french':
            list_which = [
                "lequel", "laquelle", "lesquels", "lesquelles", "aucun"
            ]

        if langue == 'english':
            list_which = ["which"]

        if langue == 'german':
            list_which = ["welche"]

        for i in list_which:
            if answer[0].lower().find(i) != -1:
                return True

        return False  #pas de negation definie pour cette langue

    #Fonction de log. Verbosité 1 = court, 2 = plus détaillé (si f_debug=2)
    def add_log(mess, verb):
        if f_debug > 0:
            if verb == 1 or (verb == 2 and f_debug == 2):
                text_file.write(mess)
            #if verb == 2 and f_debug == 2 :
        #		text_file.write(mess)

    #Fonction de lecture des coordonnées des Q/R
    def lect_info_jeu():
        #lecture des coordonnées
        for ind in list_full:
            csAnswer.append(" ")
            answer.append(" ")
            if ind == 0:  #c'est la question
                box = cfg.get(nom_jeu, 'quest')
            else:
                box = cfg.get(nom_jeu, 'r' + str(ind))
            coord.append(box)

    """def lect_ini_liste_jeux():
		cfg = ConfigParser.ConfigParser()
		cfg.read('param_games.ini')
		fenetre = Tk()  #fenetre
		# liste des jeux
		liste = Listbox(fenetre)
		mylist = [1,2,3,4,5,6,7,8,9]
		for ind in mylist:
			try:
				jeu = cfg.get('JEUX', 'jeu'+str(ind))
				jeu_lib = cfg.get(jeu,'libelle')
				liste.insert(ind, str(ind)+' - '+jeu_lib)
			except:
				break;
			print(jeu_lib)
		
		liste.pack()
		fenetre.mainloop()
		print(liste.curselection())"""

    #Début effectif du programme
    reload(sys)
    sys.setdefaultencoding("UTF-8")

    if nom_jeu == 'bidon':  #bidouille pour permettre le lancement de cashAssistant en solo sans passer par le menu
        #nom_jeu = 'CS_FR'
        #nom_jeu = 'FLASHBREAK'
        #nom_jeu = 'QUIDOL'
        #nom_jeu = 'WLQ'
        #nom_jeu = 'CCL'
        #nom_jeu = 'HQ'
        #nom_jeu = 'CS_DE'
        nom_jeu = 'CS_EN'  #Cash Show Anglophones (US/UK/AU)

    #Ouverture du fichier de log (au moins pour les debut/fin)
    if f_debug >= 1:
        text_file = open("Output" + nom_jeu + ".txt", "a")
        add_log("\n==== lancement " + str(datetime.now()) + " ====\n", 1)  #log

    coord = []  #Cette liste contiendra les coordonnées des différentes Q/R
    csAnswer = []  #Liste des images des réponses
    answer = []  #Liste des textes des réponses (après passage OCR)
    count = []  #Liste des scores
    rep_exact = []  #Liste de nombre de réponses exactes
    init(autoreset=True)

    #Ouverture et lecture du fichier de paramétrage
    cfg = ConfigParser.ConfigParser()
    cfg.read('param_gamesv2.ini')
    nb_rep = int(cfg.get(nom_jeu, 'nb_rep'))
    langue = cfg.get(nom_jeu, 'langue')
    list_full = range(0, nb_rep + 1)  #liste avec la question en arg 0
    list_rep = range(1, nb_rep + 1)  #liste de réponses seulement

    print("Jeu en Cours : " + cfg.get(nom_jeu, 'libelle'))
    lect_info_jeu()

    #Screenshots
    start_time = time()
    add_log("===== debut screenshot " + str(datetime.now()) + " ====\n",
            2)  #log
    window_handle = _get_windows_bytitle("ApowerMirror")[0]
    image = screenshot(window_handle)

    add_log("===== fin screenshot " + str(datetime.now()) + " ====\n", 2)  #log

    #Traitement des Q/R (decoupage+preprocess+lecture OCR)
    add_log("===== debut traitment Q/R " + str(datetime.now()) + " ====\n",
            2)  #log

    NUM_WORKERS = nb_rep + 1
    with concurrent.futures.ThreadPoolExecutor(
            max_workers=NUM_WORKERS) as executor:
        futures = {executor.submit(trt_img, ind) for ind in range(NUM_WORKERS)}
        concurrent.futures.wait(futures)
    """with closing(multiprocessing.Pool(processes=NUM_WORKERS)) as pool:
		pool.map_async(trt_img, list_full)
		#results.wait()"""

    for ind in list_full:
        if ind == 0:
            entete = 'Q : '
        else:
            entete = 'R' + str(ind) + ': '

        print(entete + answer[ind])
        if f_debug >= 1:
            add_log(entete + answer[ind] + "\n", 1)  #log

    end_time = time()
    print("Duree grab + OCR concurrent : %ssecs" % (end_time - start_time))
    add_log("===== fin traitment Q/R " + str(datetime.now()) + " ====\n",
            2)  #log

    #exit() #pour ne pas faire la recherche web

    # -------------- Testing -----------------
    """
	question = "Which of these US states does NOT contain a town called Springfield"
	answer[1] = "montana"
	answer[2] = "maine"
	answer[3] = "michigan"
	#answer[4] = "don camillo contre peppone"
	"""
    # ---------------------------------------
    #Gérer les STOPWORDS sur la question pour simplifier la rechercher ?
    # Write to logfile to see HTML
    #add_log(question+"\n",2)    #log

    start_time2 = time()

    answer[0] = answer[0].replace("&", "%26")

    if is_which():  #Question du type "Lequel"
        print("question lequel")
        add_log("question lequel", 1)
        stop_words = stopwords.words(langue)
        quest_arr = answer[0].split()
        quest_arr = [w for w in quest_arr if not w in stop_words]
        quest_light = '+'.join(quest_arr)

        answer[0] = answer[0].replace(" ", "+")
        #for ind in list_rep:
        #	responseFromQuestion = get("https://google.com/search?q=" + question + "&num=30")

        # Count instances of answer and lower-case answer
        count.append(
            int(0))  #enregistrement vide pour ne pas utiliser l'index 0
        rep_exact.append(int(0))
        total = 0
        for ind in list_rep:
            responseFromQuestion = get("https://google.com/search?q=" +
                                       quest_light + " " + answer[ind] +
                                       "&num=5")
            h = HTMLParser()
            html = responseFromQuestion.text.lower()
            html = clean_html(html)

            count.append(hash_count(
                html,
                answer[ind]))  #Si réponse exacte trouvée, on la met en avant !
            if count[ind] > 2000:  #Si un gros score lors du hash_count, peut être un problème de recherche (réponse composée de plusieurs mots)
                count[ind] = 0
            rep_exact.append(html.count(answer[ind]))
            count[ind] = count[ind] + rep_exact[ind]
            total = total + count[ind]  #comptage total
    else:  #question classique
        answer[0] = answer[0].replace(" ", "+")

        #webbrowser.open("https://google.com/search?q=" + question,new=1)
        responseFromQuestion = get("https://google.com/search?q=" + answer[0] +
                                   "&num=25")
        h = HTMLParser()
        html = responseFromQuestion.text.lower()
        html = clean_html(html)
        #add_log("\n\n\n"+html+"\n\n\n",2)   #log

        # Count instances of answer and lower-case answer
        count.append(
            int(0))  #enregistrement vide pour ne pas utiliser l'index 0
        rep_exact.append(int(0))
        total = 0
        for ind in list_rep:
            count.append(hash_count(
                html,
                answer[ind]))  #Si réponse exacte trouvée, on la met en avant !
            if count[ind] > 2000:  #Si un gros score lors du hash_count, peut être un problème de recherche (réponse composée de plusieurs mots)
                count[ind] = 0
            rep_exact.append(html.count(answer[ind]))
            count[ind] = count[ind] + rep_exact[ind]
            total = total + count[ind]  #comptage total

    #Affichage des scores des différentes réponses
    print("=============================")
    for ind in list_rep:
        if rep_exact[ind] == 0:
            print("Score pour R" + str(ind) + " : " + str(count[ind]))
        else:
            print("Score pour R" + str(ind) + " : " + str(count[ind]) +
                  " dont " + str(rep_exact[ind]) + " rep EXACTE(S) trouvee(s)")
    print(
        "ATTENTION SI QUESTION AVEC NEGATION PRIVILEGIER LE SCORE LE PLUS BAS OU A ZERO"
    )
    print("=============================")
    if f_debug >= 1:
        for ind in list_rep:
            if rep_exact[ind] == 0:
                add_log("Score pour R" + str(ind) + " : " + str(count[ind]) +
                        "\n", 1)  #log
            else:
                add_log("Score pour R" + str(ind) + " : " + str(count[ind]) +
                        " dont " + str(rep_exact[ind]) +
                        " rep EXACTE(S) trouvee(s)\n", 1)  #log

    #Affichage de la meilleure réponse
    if total == 0:
        print("Il n'y a aucune reponse trouvee. Probleme de lecture Q/R ?")
        add_log("Il n'y a aucune réponse trouvée. Problème de lecture Q/R ? " +
                str(datetime.now()) + " ====\n", 1)  #log
    else:
        del count[
            0]  #suppression de l'index 0 le temps de récupérer le meilleur score
        minCount = min(count)
        maxCount = max(count)
        count.insert(0, 0)  #on remet l'index 0

        del rep_exact[
            0]  #suppression de l'index 0 le temps de récupérer le meilleur score exacte
        minCount_exact = min(rep_exact)
        maxCount_exact = max(rep_exact)
        rep_exact.insert(0, 0)  #on remet l'index 0

        #Test d'une négation
        if is_negative():
            for ind in list_rep:
                if minCount_exact == rep_exact[ind] and minCount == count[
                        ind] and maxCount_exact >= 0:  #Minimum exact ET Minimum hash c est la bonne réponse
                    print(
                        colored(
                            "La reponse est : " + str(ind) + " - " +
                            answer[ind], 'green'))
                    add_log("La reponse est : " + str(ind) + " - " +
                            answer[ind] + "\n", 1)  #log
                else:
                    if minCount_exact == rep_exact[ind]:  #Minimum exact
                        print(
                            colored(
                                "La reponse est : " + str(ind) + " - " +
                                answer[ind], 'yellow'))
                        add_log("La reponse est : " + str(ind) + " - " +
                                answer[ind] + "\n", 1)  #log
                    else:
                        if minCount == count[ind]:  #Minimum hash
                            print(
                                colored(
                                    "La reponse est : " + str(ind) + " - " +
                                    answer[ind], 'red'))
                            add_log("La reponse est : " + str(ind) + " - " +
                                    answer[ind] + "\n", 1)  #log
        else:
            for ind in list_rep:
                if maxCount_exact == rep_exact[ind] and maxCount == count[
                        ind] and maxCount_exact >= 0:  #Maximum exact ET Maximum hash c est la bonne réponse
                    print(
                        colored(
                            "La reponse est : " + str(ind) + " - " +
                            answer[ind], 'green'))
                    add_log("La reponse est : " + str(ind) + " - " +
                            answer[ind] + "\n", 1)  #log
                else:
                    if maxCount_exact == rep_exact[
                            ind] and maxCount_exact >= 0:  #Maximum exact
                        print(
                            colored(
                                "La reponse est : " + str(ind) + " - " +
                                answer[ind], 'yellow'))
                        add_log("La reponse est : " + str(ind) + " - " +
                                answer[ind] + "\n", 1)  #log
                    else:
                        if maxCount == count[ind]:  #Maximum hash
                            print(
                                colored(
                                    "La reponse est : " + str(ind) + " - " +
                                    answer[ind], 'red'))
                            add_log("La reponse est : " + str(ind) + " - " +
                                    answer[ind] + "\n", 1)  #log

    end_time2 = time()
    print("Duree recherche : %ssecs" % (end_time2 - start_time2))
    print("Duree totale    : %ssecs" % (end_time2 - start_time))

    #Fermeture du fichier de log
    if f_debug >= 1:
        add_log("===== fermeture " + str(datetime.now()) + " ====\n", 1)  #log
        text_file.close
Ejemplo n.º 52
0
def main():
    colorama.init() #turn colorama ANSII conversion on
    #wrkr, wrkst, temp, humid, str_start, str_end = gather_info()
    wrkr = 'wb'
    wrkst = 'wsb-001'
    temp = 72.0
    humid = 20.0
    str_start = 'ST00001'
    str_end = 'ST00024'
	
    straw_dict = {}
    save_dict = {}
    for value in straw_nums:
        save_dict[value+'ii'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'io'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'oi'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'oo'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]

    #print('Using first calibration file...\n')
    repeat = True
    while(repeat == True):
        input("Press enter to measure resistance...")
        straw_dict = measure_resistance(avg_method, meas_cycles,
                                        str_start, str_end,calib_file)
        i = 0
        for key, value in sorted(save_dict.items()):
            if value[6] != 'pass': #and straw_dict[key][6] == 'pass':
                value[0] = straw_dict[key][0]
                value[1] = straw_dict[key][1]
                value[2] = straw_dict[key][2]
                value[3] = straw_dict[key][3]
                value[4] = straw_dict[key][4]
                value[5] = straw_dict[key][5]
                value[6] = straw_dict[key][6]
                i += 1
        if i == 0:
            repeat = False
        display_resistance(save_dict)
        #repeat = check_repeat()
        repeat = False
    save_resistance(wrkr, wrkst, temp, humid, save_dict,dataFile,str_start,str_end)
    input('Press enter to exit...')

    ''' This section was used in testing different calibration methods
    print('Now using adjusted calibration file...\n')
    straw_dict = {}
    save_dict = {}
    for value in straw_nums:
        save_dict[value+'ii'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'io'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'oi'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
        save_dict[value+'oo'] = [0,0,'',0,0,0,'fail']  #[% error, device resistance, pass/fail]
    repeat = True
    while(repeat == True):
        input("Press enter to measure resistance...")
        straw_dict = measure_resistance(avg_method, meas_cycles,
                                        str_start, str_end,calib_file_adjusted)
        i = 0
        for key, value in sorted(save_dict.items()):
            if value[6] != 'pass': #and straw_dict[key][6] == 'pass':
                value[0] = straw_dict[key][0]
                value[1] = straw_dict[key][1]
                value[2] = straw_dict[key][2]
                value[3] = straw_dict[key][3]
                value[4] = straw_dict[key][4]
                value[5] = straw_dict[key][5]
                value[6] = straw_dict[key][6]
                i += 1
        if i == 0:
            repeat = False
        display_resistance(save_dict)
        repeat = check_repeat()
    save_resistance(wrkr, wrkst, temp, humid, save_dict,dataFile_adjusted)
    '''
    
    colorama.deinit()  #turn colorama ANSII conversion off
Ejemplo n.º 53
0
def main():
    # Colorama module's initialization.
    init(autoreset=True)

    version_string = f"%(prog)s {__version__}\n" +  \
                     f"{requests.__description__}:  {requests.__version__}\n" + \
                     f"Python:  {platform.python_version()}"

    parser = ArgumentParser(
        formatter_class=RawDescriptionHelpFormatter,
        description=f"{module_name} (Version {__version__})")
    parser.add_argument("--version",
                        action="version",
                        version=version_string,
                        help="Display version information and dependencies.")
    parser.add_argument(
        "--verbose",
        "-v",
        "-d",
        "--debug",
        action="store_true",
        dest="verbose",
        default=False,
        help="Display extra debugging information and metrics.")
    parser.add_argument(
        "--rank",
        "-r",
        action="store_true",
        dest="rank",
        default=False,
        help=
        "Present websites ordered by their Alexa.com global rank in popularity."
    )
    parser.add_argument(
        "--folderoutput",
        "-fo",
        dest="folderoutput",
        help=
        "If using multiple usernames, the output of the results will be saved at this folder."
    )
    parser.add_argument(
        "--output",
        "-o",
        dest="output",
        help=
        "If using single username, the output of the result will be saved at this file."
    )
    parser.add_argument(
        "--tor",
        "-t",
        action="store_true",
        dest="tor",
        default=False,
        help=
        "Make requests over Tor; increases runtime; requires Tor to be installed and in system path."
    )
    parser.add_argument(
        "--unique-tor",
        "-u",
        action="store_true",
        dest="unique_tor",
        default=False,
        help=
        "Make requests over Tor with new Tor circuit after each request; increases runtime; requires Tor to be installed and in system path."
    )
    parser.add_argument("--csv",
                        action="store_true",
                        dest="csv",
                        default=False,
                        help="Create Comma-Separated Values (CSV) File.")
    parser.add_argument(
        "--site",
        action="append",
        metavar='SITE_NAME',
        dest="site_list",
        default=None,
        help=
        "Limit analysis to just the listed sites.  Add multiple options to specify more than one site."
    )
    parser.add_argument(
        "--proxy",
        "-p",
        metavar='PROXY_URL',
        action="store",
        dest="proxy",
        default=None,
        help="Make requests over a proxy. e.g. socks5://127.0.0.1:1080")
    parser.add_argument(
        "--json",
        "-j",
        metavar="JSON_FILE",
        dest="json_file",
        default="data.json",
        help="Load data from a JSON file or an online, valid, JSON file.")
    parser.add_argument(
        "--proxy_list",
        "-pl",
        metavar='PROXY_LIST',
        action="store",
        dest="proxy_list",
        default=None,
        help=
        "Make requests over a proxy randomly chosen from a list generated from a .csv file."
    )
    parser.add_argument(
        "--check_proxies",
        "-cp",
        metavar='CHECK_PROXY',
        action="store",
        dest="check_prox",
        default=None,
        help="To be used with the '--proxy_list' parameter. "
        "The script will check if the proxies supplied in the .csv file are working and anonymous."
        "Put 0 for no limit on successfully checked proxies, or another number to institute a limit."
    )
    parser.add_argument(
        "--print-found",
        action="store_true",
        dest="print_found_only",
        default=False,
        help="Do not output sites where the username was not found.")
    parser.add_argument(
        "username",
        nargs='+',
        metavar='USERNAMES',
        action="store",
        help="One or more usernames to check with social networks.")

    args = parser.parse_args()

    print(Fore.WHITE + Style.BRIGHT + BANNER)

    # Argument check
    # TODO regex check on args.proxy
    if args.tor and (args.proxy != None or args.proxy_list != None):
        raise Exception("Tor and Proxy cannot be set in the meantime.")

    # Proxy argument check.
    # Does not necessarily need to throw an error,
    # since we could join the single proxy with the ones generated from the .csv,
    # but it seems unnecessarily complex at this time.
    if args.proxy != None and args.proxy_list != None:
        raise Exception("A single proxy cannot be used along with proxy list.")

    # Make prompts
    if args.proxy != None:
        print("Using the proxy: " + args.proxy)

    global proxy_list

    if args.proxy_list != None:
        print_info("Loading proxies from", args.proxy_list)

        proxy_list = load_proxies_from_csv(args.proxy_list)

    # Checking if proxies should be checked for anonymity.
    if args.check_prox != None and args.proxy_list != None:
        try:
            limit = int(args.check_prox)
            if limit == 0:
                proxy_list = check_proxy_list(proxy_list)
            elif limit > 0:
                proxy_list = check_proxy_list(proxy_list, limit)
            else:
                raise ValueError
        except ValueError:
            raise Exception(
                "Prameter --check_proxies/-cp must be a positive intiger.")

    if args.tor or args.unique_tor:
        print("Using Tor to make requests")
        print(
            "Warning: some websites might refuse connecting over Tor, so note that using this option might increase connection errors."
        )

    # Check if both output methods are entered as input.
    if args.output is not None and args.folderoutput is not None:
        print("You can only use one of the output methods.")
        sys.exit(1)

    # Check validity for single username output.
    if args.output is not None and len(args.username) != 1:
        print("You can only use --output with a single username")
        sys.exit(1)

    response_json_online = None
    site_data_all = None

    # Try to load json from website.
    try:
        response_json_online = requests.get(url=args.json_file)
    except requests.exceptions.MissingSchema:  # In case the schema is wrong it's because it may not be a website
        pass

    # Check if the response is appropriate.
    if response_json_online is not None and response_json_online.status_code == 200:
        # Since we got data from a website, try to load json and exit if parsing fails.
        try:
            site_data_all = response_json_online.json()
        except ValueError:
            print("Invalid JSON from website!")
            sys.exit(1)
            pass

    data_file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                  args.json_file)
    # This will be none if the request had a missing schema
    if site_data_all is None:
        # Check if the file exists otherwise exit.
        if not os.path.exists(data_file_path):
            print("JSON file at doesn't exist.")
            print(
                "If this is not a file but a website, make sure you have appended http:// or https://."
            )
            sys.exit(1)
        else:
            raw = open(data_file_path, "r", encoding="utf-8")
            try:
                site_data_all = json.load(raw)
            except:
                print("Invalid JSON loaded from file.")

    if args.site_list is None:
        # Not desired to look at a sub-set of sites
        site_data = site_data_all
    else:
        # User desires to selectively run queries on a sub-set of the site list.

        # Make sure that the sites are supported & build up pruned site database.
        site_data = {}
        site_missing = []
        for site in args.site_list:
            for existing_site in site_data_all:
                if site.lower() == existing_site.lower():
                    site_data[existing_site] = site_data_all[existing_site]
            if not site_data:
                # Build up list of sites not supported for future error message.
                site_missing.append(f"'{site}'")

        if site_missing:
            print(
                f"Error: Desired sites not found: {', '.join(site_missing)}.")
            sys.exit(1)

    if args.rank:
        # Sort data by rank
        site_dataCpy = dict(site_data)
        ranked_sites = sorted(
            site_data,
            key=lambda k:
            ("rank" not in k, site_data[k].get("rank", sys.maxsize)))
        site_data = {}
        for site in ranked_sites:
            site_data[site] = site_dataCpy.get(site)

    # Run report on all specified users.
    for username in args.username:
        print()

        if args.output:
            file = open(args.output, "w", encoding="utf-8")
        elif args.folderoutput:  # In case we handle multiple usernames at a targetted folder.
            # If the folder doesnt exist, create it first
            if not os.path.isdir(args.folderoutput):
                os.mkdir(args.folderoutput)
            file = open(os.path.join(args.folderoutput, username + ".txt"),
                        "w",
                        encoding="utf-8")
        else:
            file = open(username + ".txt", "w", encoding="utf-8")

        # We try to ad a random member of the 'proxy_list' var as the proxy of the request.
        # If we can't access the list or it is empty, we proceed with args.proxy as the proxy.
        try:
            random_proxy = random.choice(proxy_list)
            proxy = f'{random_proxy.protocol}://{random_proxy.ip}:{random_proxy.port}'
        except (NameError, IndexError):
            proxy = args.proxy

        results = {}
        results = sherlock(username,
                           site_data,
                           verbose=args.verbose,
                           tor=args.tor,
                           unique_tor=args.unique_tor,
                           proxy=args.proxy,
                           print_found_only=args.print_found_only)

        exists_counter = 0
        for website_name in results:
            dictionary = results[website_name]
            if dictionary.get("exists") == "yes":
                exists_counter += 1
                file.write(dictionary["url_user"] + "\n")
        file.write("Total Websites : {}".format(exists_counter))
        file.close()

        if args.csv == True:
            with open(username + ".csv", "w", newline='',
                      encoding="utf-8") as csv_report:
                writer = csv.writer(csv_report)
                writer.writerow([
                    'username', 'name', 'url_main', 'url_user', 'exists',
                    'http_status', 'response_time_ms'
                ])
                for site in results:
                    writer.writerow([
                        username, site, results[site]['url_main'],
                        results[site]['url_user'], results[site]['exists'],
                        results[site]['http_status'],
                        results[site]['response_time_ms']
                    ])
Ejemplo n.º 54
0
def main():
    colorama.init(autoreset=True)
    c1 = colorama.Fore.BLUE + colorama.Back.LIGHTCYAN_EX
    c5 = colorama.Fore.RED + colorama.Back.LIGHTYELLOW_EX
    c7 = colorama.Fore.BLACK + colorama.Back.MAGENTA
    cr = colorama.Style.RESET_ALL
    basic = False
    help_me = False
    error_msg = None
    invalid_cmd = None
    language = "English"

    command_args = sys.argv[2:]
    file_name = command_args[0]
    if not file_name.endswith(".py"):
        error_msg = 'File Name must end with ".py"!'
    elif "*" in file_name or len(str(file_name)) < 4:
        error_msg = 'Invalid File Name!'
    elif "/" in str(file_name) or "\\" in str(file_name):
        error_msg = 'File must be created in the current directory!'
    elif os.path.exists(os.getcwd() + '/' + file_name):
        error_msg = ('File "%s" already exists in the current path!' %
                     file_name)
    if error_msg:
        error_msg = c5 + error_msg + cr
        invalid_run_command(error_msg)

    if len(command_args) >= 2:
        options = command_args[1:]
        for option in options:
            option = option.lower()
            if option == "help" or option == "--help":
                help_me = True
            elif option == "-b" or option == "--basic":
                basic = True
            elif option == "--en" or option == "--english":
                language = "English"
            elif option == "--zh" or option == "--chinese":
                language = "Chinese"
            elif option == "--nl" or option == "--dutch":
                language = "Dutch"
            elif option == "--fr" or option == "--french":
                language = "French"
            elif option == "--it" or option == "--italian":
                language = "Italian"
            elif option == "--ja" or option == "--japanese":
                language = "Japanese"
            elif option == "--ko" or option == "--korean":
                language = "Korean"
            elif option == "--pt" or option == "--portuguese":
                language = "Portuguese"
            elif option == "--ru" or option == "--russian":
                language = "Russian"
            elif option == "--es" or option == "--spanish":
                language = "Spanish"
            else:
                invalid_cmd = "\n===> INVALID OPTION: >> %s <<\n" % option
                invalid_cmd = invalid_cmd.replace('>> ', ">>" + c5 + " ")
                invalid_cmd = invalid_cmd.replace(' <<', " " + cr + "<<")
                invalid_cmd = invalid_cmd.replace('>>', c7 + ">>" + cr)
                invalid_cmd = invalid_cmd.replace('<<', c7 + "<<" + cr)
                help_me = True
                break
    if help_me:
        invalid_run_command(invalid_cmd)

    if language != "English" and sys.version_info[0] == 2:
        print("")
        msg = 'Multi-language support for "sbase mkfile" '
        msg += 'is not available on Python 2!'
        msg = "\n" + c5 + msg + cr
        msg += '\nPlease run in "English" mode or upgrade to Python 3!\n'
        raise Exception(msg)

    dir_name = os.getcwd()
    file_path = "%s/%s" % (dir_name, file_name)

    body = "html > body"
    para = "body p"
    hello = "Hello"
    goodbye = "Goodbye"
    class_name = "MyTestClass"
    if language == "Chinese":
        hello = "你好"
        goodbye = "再见"
        class_name = "我的测试类"
    elif language == "Dutch":
        hello = "Hallo"
        goodbye = "Dag"
        class_name = "MijnTestklasse"
    elif language == "French":
        hello = "Bonjour"
        goodbye = "Au revoir"
        class_name = "MaClasseDeTest"
    elif language == "Italian":
        hello = "Ciao"
        goodbye = "Addio"
        class_name = "MiaClasseDiTest"
    elif language == "Japanese":
        hello = "こんにちは"
        goodbye = "さようなら"
        class_name = "私のテストクラス"
    elif language == "Korean":
        hello = "여보세요"
        goodbye = "안녕"
        class_name = "테스트_클래스"
    elif language == "Portuguese":
        hello = "Olá"
        goodbye = "Tchau"
        class_name = "MinhaClasseDeTeste"
    elif language == "Russian":
        hello = "Привет"
        goodbye = "До свидания"
        class_name = "МойТестовыйКласс"
    elif language == "Spanish":
        hello = "Hola"
        goodbye = "Adiós"
        class_name = "MiClaseDePrueba"
    url = ""
    if basic:
        url = "about:blank"
    elif language not in ["English", "Dutch", "French", "Italian"]:
        url = "data:text/html,<meta charset='utf-8'><p>%s <input>" % hello
    else:
        url = "data:text/html,<p>%s<br><input></p>" % hello

    import_line = "from seleniumbase import BaseCase"
    parent_class = "BaseCase"
    class_line = "class MyTestClass(BaseCase):"
    if language != "English":
        from seleniumbase.translate.master_dict import MD_F
        import_line = MD_F.get_import_line(language)
        parent_class = MD_F.get_lang_parent_class(language)
    class_line = "class %s(%s):" % (class_name, parent_class)

    data = []
    data.append("%s" % import_line)
    data.append("")
    data.append("")
    data.append("%s" % class_line)
    data.append("")
    data.append("    def test_base(self):")
    data.append('        self.open("%s")' % url)
    if not basic:
        data.append('        self.assert_element("%s")  # selector' % body)
        data.append('        self.assert_text("%s", "%s")'
                    '  # text, selector' % (hello, para))
        data.append('        self.type("input", "%s")'
                    '  # selector, text' % goodbye)
        data.append('        self.click("%s")  # selector' % para)
    data.append("")

    new_data = []
    if language == "English":
        new_data = data
    else:
        from seleniumbase.translate.master_dict import MD
        from seleniumbase.translate.master_dict import MD_L_Codes
        md = MD.md
        lang_codes = MD_L_Codes.lang
        nl_code = lang_codes[language]
        dl_code = lang_codes["English"]
        for line in data:
            found_swap = False
            replace_count = line.count("self.")  # Total possible replacements
            for key in md.keys():
                original = "self." + md[key][dl_code] + "("
                if original in line:
                    replacement = "self." + md[key][nl_code] + "("
                    new_line = line.replace(original, replacement)
                    found_swap = True
                    replace_count -= 1
                    if replace_count == 0:
                        break  # Done making replacements
                    else:
                        # There might be another method to replace in the line.
                        # Example: self.assert_true("Name" in self.get_title())
                        line = new_line
                        continue
            if found_swap:
                if new_line.endswith("  # noqa"):  # Remove flake8 skip
                    new_line = new_line[0:-len("  # noqa")]
                new_data.append(new_line)
                continue
            new_data.append(line)
    data = new_data
    file = codecs.open(file_path, "w+", "utf-8")
    file.writelines("\r\n".join(data))
    file.close()
    success = ('\n' + c1 + '* Test file: "' + file_name + '" was created! *'
               '' + cr + '\n')
    print(success)
Ejemplo n.º 55
0
def check_args():
    init(autoreset=True)
    global CONNECTION_TIMEOUT
    global CONNECTION_RETRIES
    global SIZE
    global INDEXES
    global DUMP_INDEXES
    global OUTPUT
    global STDOUT
    global YARA

    pars = argparse.ArgumentParser(
        description=Fore.GREEN + Style.BRIGHT +
        'Search for elasticsearch on the Internet. \nDisplay all Indexes and dump the Indexes.'
        + Style.RESET_ALL)

    pars.add_argument('-t',
                      '--timeout',
                      nargs='?',
                      type=int,
                      default=30,
                      help='Connection Timeout, Default = 30s')
    pars.add_argument('-r',
                      '--retries',
                      nargs='?',
                      type=int,
                      default=False,
                      help='Connection Retries, Default = 0')
    pars.add_argument('-s',
                      '--size',
                      nargs='?',
                      type=int,
                      default=1,
                      help='Define Scroll Size, Default = 1')
    pars.add_argument(
        '-v',
        '--verbose',
        type=int,
        nargs='?',
        help=
        'Increase verbosity level 0:INFO, 1:DEBUG, 2:WARNING, 3:ERROR, 4:CRITICAL',
        default=None)
    pars.add_argument(
        '-i',
        '--indexes',
        type=str,
        nargs='*',
        help='Give known indexes : index1 index2 indexn, Default = *',
        default='*')
    pars.add_argument('-d',
                      '--dump',
                      type=bool,
                      nargs='?',
                      help='Dump indexes of target. Default = False',
                      default=False,
                      const=True)
    pars.add_argument(
        '-o',
        '--output',
        type=str,
        choices=('csv', 'json'),
        help='Output File: out/ip/indexname, csv=only _source, json=all',
        default=None)
    pars.add_argument('-std',
                      '--stdout',
                      type=bool,
                      nargs='?',
                      help='Display DUMP to stdout, Default = False',
                      default=False,
                      const=True)
    pars.add_argument('-y',
                      '--yara',
                      type=bool,
                      nargs='?',
                      help='Turn on yara rule search, Default = False',
                      default=False,
                      const=True)

    pars.add_argument('--ip', nargs='?', help='Target IP:PORT')
    pars.add_argument('-f', '--filename', nargs='?', help='File with IP:PORT')

    args = pars.parse_args()

    CONNECTION_TIMEOUT = args.timeout
    CONNECTION_RETRIES = args.retries
    SIZE = args.size
    INDEXES = args.indexes
    DUMP_INDEXES = args.dump
    OUTPUT = args.output
    STDOUT = args.stdout
    YARA = args.yara
    set_debug_level(args.verbose)

    print_settings()

    if args.ip is None and args.filename is None:
        pars.error(Fore.RED + '-f/--filename or --ip required')
    elif args.ip and args.filename is None:
        return args.ip, True
    elif args.ip is None and args.filename:
        return args.filename, False
    elif args.ip and args.filename:
        pars.error(Fore.RED +
                   'To many Parameters, please choose -f/--filename or --ip')
Ejemplo n.º 56
0
def main():
    arguments = __get_arguments()

    path = arguments.path
    pattern = arguments.pattern

    if path and isfile(path):
        path, pattern = split(path)
    if not path:
        path = os.curdir

    if arguments.no_color:
        for color_name, value in inspect.getmembers(Fore):
            if not color_name.startswith('_'):
                setattr(Fore, color_name, '')

    if arguments.cover and COVERAGE_AVAILABLE:
        cov = coverage(source=arguments.cover_package, omit=arguments.cover_omit)
        cov.erase()
        cov.start()

    verbosity = len(arguments.verbosity) if arguments.verbosity else 2
    result, reporter = run(path, pattern, verbosity, arguments.progress)

    if result.successful and arguments.cover:
        if COVERAGE_AVAILABLE:
            cov.stop()

            print
            print

            xml = ''
            with tempfile.NamedTemporaryFile() as tmp:
                cov.xml_report(outfile=tmp.name)
                tmp.seek(0)
                xml = tmp.read()

            if arguments.cover_report:
                with open(arguments.cover_report, 'w') as report:
                    report.write(xml)

            reporter.print_coverage(xml, arguments.cover_threshold)

        else:

            init(autoreset=True)
            print
            print Fore.YELLOW + "WARNING: Cover disabled because coverage or lxml could not be found."
            print Fore.YELLOW + "Make sure both are installed and accessible"
            print

    reporter.pretty_print()

    if arguments.xunit_output:
        xunit = XUnitReporter(result)
        xunit.write_report(arguments.xunit_file)

    if arguments.profile:
        reporter.print_profile()

    sys.exit(result.errored_tests)
Ejemplo n.º 57
0
    def run(self):
        """
        descrambles tcpdump-binary files, save to h5 in DLSraw standard format

        Here is how data are scrambled:

        1a) the chips send data out interleaving RowGroups
            (7row x (32 Col x 45 pads) ) from Sample/Reset, as:
            Smpl, Smpl,   Smpl, Rst, Smpl, Rst, ... , Smpl, Rst,   Rst, Rst
        1b) the position of pixels (pix0/1/2 in the next point) is mapped to
            the (7row x 32 Col) block according to the adc_cols lost
        1c) inside a (7row x 32 Col) block, the data are streamed out as:
            bit0-of-pix0, bit0-of-pix1, bit0-of-pix2, ... , bit0-of-pix1, ...
        1d) all the data coming from the sensor are bit-inverted: 0->1; 1->0
        2a) the mezzanine takes the data coming from each (7 x 32) block,
            and add a "0" it in front of every 15 bits:
            xxx xxxx xxxx xxxx  yyy ... => 0xxx xxxx xxxx xxxx 0yyy ...
        2b) the mezzanine takes the data coming from a 44x (7 x 32) blocks
            (this corresponds to a complete RowCrp, ignoring RefCol )
            and interleaves 32 bits at a time:
            32b-from-pad1, 32b-from-pad2, ... , 32b-from-pad44,
            next-32b-from-pad1, next-32b-from-pad2, ...
        2c) the mezzanine packs the bits in Bytes, and the Bytes in UDPackets
            4 UDPackets contain all the bits of a 44x (7 x 32) Rowgrp.
            A complete image (Smpl+Rst) = 1696 UDPackets
            each UDPack has 4928Byte of information, and 112Byte of header.
            each UDPack is univocally identified by the header:
            - whether it is part of a Smpl/Rst
            - which Img (frame) the packet belongs to
            - its own packet number (0:1696), which determines the RowGrp the
            packet's data goes into
        3a) the packets are sent from 2 mezzanine links (some on one link, some
            on the other), and are saved a 2 binary files by tcpdump
            24Bytes are added at the start of each file

        Args:
            filenamepath_in0/1/2: name of tcpdump scrambled binary files
                Might exist or not
            output_fname: name of h5 descrambled file to generate
            save_file/debugFlag/clean_memory/verbose: no need to explain

        Returns:
            creates a h5 file (if save_file) in DLSraw standard format
                no explicit return()
        """

        init(autoreset=True)

        start_time = time.strftime("%Y_%m_%d__%H:%M:%S")
        print(Fore.BLUE + "Script beginning at {}".format(start_time))
        self._report_arguments()

        file_content = self._reading_file_content()

        n_packets = [len(content) // self._fullpack_size
                     for content in file_content]

        if self._verbose:
            print(Fore.GREEN +
                  ("data read from files ({} packets)"
                   .format("+".join([str(n) for n in n_packets]))))

        # search for 1st & last image: this is needed to resort the data from
        # the file in a proper array of (n_img, n_pack)
        # also scan for fatal packet error: if a packet has a number > 1695
        # then the data is corrupted
        if self._verbose:
            print(Fore.BLUE + "scanning files for obvious packet errors")

        first_img, last_img = self._scanning_files(n_packets, file_content)

        # if needed, reduce Img2show to the 1st image
        # (the 1st img in the sequence might have a Img_counter number >0)
        imgs_tcpdump = np.arange(first_img, last_img + 1)
        n_img = len(imgs_tcpdump)

        msg = (("The lowest-numbered Img of the sequence is: "
                "tcpdump-Image {}\n"
                "The highest-numbered Img of the sequence is: "
                "tcpdump-Image {}").format(first_img, last_img))
        print(Fore.GREEN + msg)

        # solving the 2c-part of scrambling
        # resort data from files (assign pack to its Img,Smpl/Rst)
        if self._verbose:
            print(Fore.BLUE + "resorting packages")

        data, _, pack_check = self._resorting_data(n_img,
                                                   imgs_tcpdump,
                                                   file_content)

        if self._verbose:
            print(Fore.BLUE + " ")

        if self._clean_memory:
            del file_content

        # missing package detail: (pack,Img) not flagged as good, are missing
        for i, img in enumerate(imgs_tcpdump):
            if self._verbose:
                missing_packages = np.sum(np.logical_not(pack_check[i, :]))

                if missing_packages < 1:
                    print(Fore.GREEN +
                          "All packets for image {} are there".format(img))
                else:
                    print(Fore.MAGENTA +
                          ("{} packets missing from image {}"
                           .format(missing_packages, img)))

        # at this point the dsata from the 2 files is ordered in a array of
        # dinesion (n_img, n_pack)

        # 1 rowgrp = 4 packets
        # when a packet is missing, the whole rowgrp is compromised
        # if so, flag the 4-tuple of packets (i.e. the rowgrp), as bad
        rowgrp_check = (pack_check[:, 0::4]
                        & pack_check[:, 1::4]
                        & pack_check[:, 2::4]
                        & pack_check[:, 3::4])
        # - - -

        if self._verbose:
            print(Fore.BLUE + "descrambling images")

        descrambled_data = self._descrambling_images(n_img,
                                                     imgs_tcpdump,
                                                     data)

        if self._verbose:
            print(Fore.BLUE + " ")

        # solving the 1b-part of scrambling:
        # reorder pixels and pads
        if self._verbose:
            print(Fore.BLUE + "reordering pixels")

        self._result_data = self._reordering_pixels(n_img,
                                                    imgs_tcpdump,
                                                    descrambled_data,
                                                    rowgrp_check)

        # save data to single file
        if self._save_file:
            self._save_data()

        # save data to multiple file
        if self._multiple_save_files:
            if self._verbose:
                print(Fore.BLUE + "saving to multiple files")

            if os.path.isfile(self._multiple_metadata_file) is False:
                msg = "metafile file does not exist"
                print(Fore.RED + msg)
                raise Exception(msg)

            meta_data = np.genfromtxt(self._multiple_metadata_file,
                                      delimiter='\t',
                                      dtype=str)
            fileprefix_list = meta_data[:, 1]

            aux_n_of_files = len(fileprefix_list)

            if (aux_n_of_files * self._multiple_imgperfile) != n_img:
                msg = ("{} != {} x {} ".format(n_img,
                                               aux_n_of_files,
                                               self._multiple_imgperfile))
                print(Fore.RED + msg)

                msg = ("n of images != metafile enties x Img/file ")
                print(Fore.RED + msg)
                raise Exception(msg)
            # ...

            (sample, reset) = utils.convert_gncrsfn_to_dlsraw(self._result_data,
                                                              self._err_int16,
                                                              self._err_dlsraw)
            (aux_nimg, aux_nrow, aux_ncol) = sample.shape
            shape_datamultfiles = (aux_n_of_files,
                                   self._multiple_imgperfile,
                                   aux_nrow,
                                   aux_ncol)
            sample = sample.reshape(shape_datamultfiles).astype('uint16')
            reset = reset.reshape(shape_datamultfiles).astype('uint16')

            for i, prefix in enumerate(fileprefix_list):

                filepath = os.path.dirname(self._output_fname)+'/'+prefix + ".h5"

                with h5py.File(filepath, "w", libver='latest') as my5hfile:
                    my5hfile.create_dataset('/data/', data=sample[i, :, :, :])
                    my5hfile.create_dataset('/reset/', data=reset[i, :, :, :])

                if self._verbose:
                    print(Fore.GREEN + "{0} Img saved to file {1}".format(
                        self._multiple_imgperfile, filepath))


        # that's all folks
        print("------------------------")
        print("done")
        stop_time = time.strftime("%Y_%m_%d__%H:%M:%S")
        print(Fore.BLUE + "script ended at {}".format(stop_time))
        print("------------------------\n" * 3)
Ejemplo n.º 58
0
def buysell(key, secret, redis_password):
  
  import time, json, sys, redis
  from pprint import pprint
  from time import gmtime, strftime
  from bittrex import bittrex
  from colors import white, red, green, yellow
  from colorama import Fore, Back, Style, init
  init()

  try:
    r = redis.Redis(host='redis.pontstrader.com', port=6380, db=0, password=redis_password)
  except:
    white('Unable to connect to redis.pontstrader.com, trying redis2.pontstrader.com...')
    try:
      r = redis.Redis(host='redis2.pontstrader.com', port=6380, db=0, password=redis_password)
    except:
      white('Unable to connect to redis2.pontstrader.com... I am sorry but you can not continue now, please contact p0nts!')
  
  while True:
    try:
      api = bittrex(key, secret)
      currencies = api.getcurrencies()
      markets = api.getmarkets()
    except:
      white('Bittrex API error: {0}'.format(api))
      white('Going back to Main Menu')
      time.sleep(2)
      break
  
    white((30 * '-'))
    green('   B U Y  A N D  S E L L')
    white((30 * '-'))
    white('Market?')
    yellow('1. BTC')
    yellow('2. ETH')
    yellow('3. USDT')
    red('4. Back to Main Menu')
    try:
      trade = raw_input(Fore.WHITE+'Enter your choice [1-4] : ')
      trade = int(trade)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if trade == 1:
      trade = 'BTC'
    elif trade == 2:
      trade = 'ETH'
    elif trade == 3:
      trade = 'USDT'
    elif trade == 4:
      break
    else:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      currency = raw_input(Fore.WHITE+'Currency? (e.g. LTC / NEO / OMG) : ').upper()
    except:
      white('Invalid currency... going back to Main Menu')
      time.sleep(1)
      break
    try:
      market = '{0}-{1}'.format(trade, currency)
      available = api.getbalance(trade)
    except:
      print available
      white('\nGoing back to Main Menu')
      time.sleep(2)
      break
    try:
      values = r.hmget(market, 'Last', 'Bid', 'Ask')
      last = float(values[0])
      bid = float(values[1])
      ask = float(values[2])
      white((30 * '-'))
      white('- Price (Last): {0:.8f} {1}'.format(last, trade))
      white('- Price (Bid): {0:.8f} {1}'.format(bid, trade))
      white('- Price (Ask): {0:.8f} {1}'.format(ask, trade))
    except:
      white('Unable to retrieve latest pricing from redis.pontstrader.com')
      white('Going back to Main Menu')
      time.sleep(2)
      break
    for f in currencies:
      if f['Currency'] == currency:
        fee = f['TxFee']
        trade_fee = last * fee
        white('- Fee {0:.8f} {1} ({2:.8f} {3})'.format(fee, currency, trade_fee, trade))
    for m in markets:
      if m['MarketCurrency'] == currency and m['BaseCurrency'] == trade:
        minimum = m['MinTradeSize']
        white('- Minimum ({0}): {1:.8f}'.format(currency, minimum))
    white('- Minimum ({0}): 0.00100000'.format(trade))
    enough = trade_fee + 0.00100000 + last
    if available['Available'] < 0.00100000:
      red('You dont have enough {0} ({1:.8f}) to buy anything!'.format(trade, available['Available']))
      time.sleep(1)
      break
    else:
      available_after_fee = available['Available'] - trade_fee
      yellow('You have {0:.8f} {1} available in total'.format(available['Available'], trade))
      yellow('Which is {0:.8f} {1} exclusive required fee'.format(available_after_fee, trade))
      can_buy_last = available_after_fee / last
      can_buy_bid = available_after_fee / bid
      can_buy_ask = available_after_fee / ask
      green('You can buy up to {0:.8f} {1} for \'Last\' price'.format(can_buy_last, currency))
      green('You can buy up to {0:.8f} {1} for \'Bid\' price'.format(can_buy_bid, currency))
      green('You can buy up to {0:.8f} {1} for \'Ask\' price'.format(can_buy_ask, currency))
      white((30 * '-'))
      white('Buyprice?')
      yellow('1. Last ({0:.8f} {1})'.format(last, trade))
      yellow('2. Bid ({0:.8f} {1})'.format(bid, trade))
      yellow('3. Ask ({0:.8f} {1})'.format(ask, trade))
      yellow('4. Custom')
      red('5. Back to Main Menu')
      try:
        buyprice = raw_input(Fore.WHITE+'Enter your choice [1-5] : ')
        buyprice = int(buyprice)
      except:
        white('ERROR: Please select a number!')
        break
      if buyprice == 1:
        buy_for = last
        white('Selected \'Last\': {0:.8f} {1}'.format(last, trade))
      elif buyprice == 2:
        buy_for = bid
        white('Selected \'Bid\': {0:.8f} {1}'.format(bid, trade))
      elif buyprice == 3:
        buy_for = ask
        white('Selected \'Ask\': {0:.8f} {1}'.format(ask, trade))
      elif buyprice == 4:
        try:
          buy_for = raw_input(Fore.WHITE+'Buyprice? e.g. [0.00000001] : ')
          buy_for = float(buy_for)
          white('Selected \'Custom\': {0:.8f} {1}'.format(buy_for, trade))
        except:
          white('Please provide a proper buyprice! (e.g. {0:.8f})'.format(last))
          break
      elif buyprice == 5:
        break
      else:
        white('\nInvalid number... going back to Main Menu')
        time.sleep(1)
        break
    try:
      amount = raw_input(Fore.WHITE+'Amount? : ')
      amount = float(amount)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    try:
      multiplier = float(raw_input(Fore.WHITE+'Multiplier? [1.1 / 1.3] (1.1 = 10%) : '))
      multiprice = round(buy_for*multiplier, 8)
      multitotal = float(amount) * float(multiprice)
      total = float(amount) * float(buy_for)
      print (30 * '-')
      green('Going to add a buy order for {0:.8f} {1} at {2:.8f} {3} each (total: {4:.8f} {3})'.format(amount, currency, buy_for, trade, total))
      green('Going to add a sell order for {0:.8f} {1} at {2:.8f} {3} each (total: {4:.8f} {3})'.format(amount, currency, multiprice, trade, multitotal))
    except:
      white('ERROR: Amount must be a number!')
  
    white((30 * '-'))
    white('Proceed?')
    green('1. yes')
    red('2. no (Back to Main Menu)')
    try:
      yes_no = raw_input(Fore.WHITE+'Enter your choice [1-2] : ')
      yes_no = int(yes_no)
    except:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
    if yes_no == 1:
      try:
        apicall = api.buylimit(market, amount, buy_for)
        print apicall['uuid']
        uuid = apicall['uuid']
        total = amount * buy_for
        green('Added a buy order for {0:.8f} {1} at {2:.8f} {3} each which is {4:.8f} {3} total'.format(amount, currency, buy_for, trade, total))
      except:
        white('Bittrex API error: {0}'.format(apicall))
        white('Going back to Main Menu')
        time.sleep(2)
        break
      yellow('Waiting up to 60 seconds for the buy order to be filled...')
      yellow('If the buy order will not be filled for 100% I am unable to add the sell order...')
      t_end = time.time() + 60
      orderstatus = api.getorder(uuid=uuid)
      while orderstatus['QuantityRemaining'] != 0.0 and time.time() < t_end:
        orderstatus = api.getorder(uuid=uuid)
        if orderstatus['QuantityRemaining'] == 0.0:
          white('Great, order is completely filled!')
          try:
            apicall = api.selllimit(market, amount, multiprice)
          except:
            white('Bittrex API error: {0}'.format(apicall))
            white('Going back to Main Menu')
            time.sleep(2)
            break
          print apicall['uuid']
          total = amount * multiprice
          green('Added a sell order for {0:.8f} {1} at {2:.8f} {3} each which is {4:.8f} {3} total'.format(amount, currency, multiprice, trade, total))
          white('Returning to Main Menu in 2 seconds...')
          time.sleep(2)
          break
        else:
          time.sleep(10)
      red('Unable to add a sell order, because the buy order is not \'completely\' filled, You will have to do this manually as soon as the buy order is completely filled!')
      yellow('Please keep in mind the buy order remains untill cancelled or filled!')
      white('Returning to Main Menu in 2 seconds...')
      time.sleep(2)
      break
    elif yes_no == 2:
      white('\nCancelled... going back to Main Menu')
      time.sleep(1)
      break
    else:
      white('\nInvalid number... going back to Main Menu')
      time.sleep(1)
      break
Ejemplo n.º 59
0
                            LIGHTBLUE_EX='',
                            LIGHTCYAN_EX='',
                            LIGHTGREEN_EX='',
                            LIGHTMAGENTA_EX='',
                            LIGHTRED_EX='',
                            LIGHTWHITE_EX='',
                            LIGHTYELLOW_EX='')
DummyStyle = SimpleNamespace(
    RESET_ALL='', BRIGHT='', DIM='', NORMAL=''
)  #, BOLD='', ITALIC='', UNDERLINE='', BLINKING='', INVERSE='', INVISIBLE='', STRIKETHROUGH='')

# normal color namespaces
try:
    import colorama
    from colorama import Fore, Back, Style
    colorama.init(
    )  # comment out init if extended color support is needed in Windows Terminal
except ImportError:
    # colorama not installed. fine, I'll do it myself
    # this expects Windows Terminal or equivalent terminal color code support
    Fore = SimpleNamespace(RESET='\x1b[39m',
                           BLACK='\x1b[30m',
                           BLUE='\x1b[34m',
                           CYAN='\x1b[36m',
                           GREEN='\x1b[32m',
                           MAGENTA='\x1b[35m',
                           RED='\x1b[31m',
                           WHITE='\x1b[37m',
                           YELLOW='\x1b[33m',
                           LIGHTBLACK_EX='\x1b[90m',
                           LIGHTBLUE_EX='\x1b[94m',
                           LIGHTCYAN_EX='\x1b[96m',
Ejemplo n.º 60
0
def main():

    global rn  # Result number (for -r arg)
    global ir  # interactive mode off (for -i arg)
    global tag  # tag based search (for -t arg)
    global query  # query variable
    colorama.init()  # for colorama support in windows
    fixCodePage()  # For fixing codepage errors in windows

    # IF there is no command line options or if it is help argument:
    if (len(sys.argv) == 1) or ((sys.argv[1] == "-h") or
                                (sys.argv[1] == "--help")):
        helpman()
        sys.exit(0)
    else:
        try:
            options, rem = getopt.getopt(
                sys.argv[1:], "nit:r:q:",
                ["query=", "res=", "interactive", "new", "tag="])
        except getopt.GetoptError:
            helpman()
            sys.exit(1)

        # Gets the CL Args
        if 'options' in locals():
            for opt, arg in options:
                if opt in ("-i", "--interactive"):
                    ir = 1  # interactive mode on
                if opt in ("-r", "--res"):
                    try:
                        rn = int(arg)
                    except ValueError:
                        print_warning("Wrong syntax...!\n")
                        helpman()
                        sys.exit(0)
                if opt in ("-t", "--tag"):
                    if len(arg) == 0:
                        print_warning("Wrong syntax...!\n")
                        helpman()
                        sys.exit(0)
                    tag = arg
                    hastags()
                if opt in ("-q", "--query"):
                    query = arg
                    if len(rem) > 0:
                        query = query + " " + " ".join(rem)
                if opt in ("-n", "--new"):
                    import webbrowser
                    print_warning("Opening stack overflow in your browser...")
                    webbrowser.open(sourl + "/questions/ask")
                    sys.exit(0)
        if tag != "":
            wrongsyn(query)
        if (rn == -1) and (ir == 0) and tag == "":
            if sys.argv[1] in ['-q', '--query']:
                socli(" ".join(sys.argv[2:]))
            else:
                socli(" ".join(sys.argv[1:]))
        elif (rn > 0):
            wrongsyn(query)
            socl_manusearch(query, rn)
            sys.exit(0)
        elif (rn == 0):
            print_warning(
                "Count starts from 1. Use: \"socli -i 2 -q python for loop\" for the 2nd result for the query"
            )
            sys.exit(0)
        elif (ir == 1):
            wrongsyn(query)
            socli_interactive(query)
            sys.exit(0)
        elif query != "":
            socli(query)
            sys.exit(0)
        else:
            print_warning("Wrong syntax...!\n")
            helpman()
            sys.exit(0)