Example #1
0
def send_chooser(wallet_obj):
    puts('What do you want to do?:')
    if not USER_ONLINE:
        puts("(since you are NOT connected to BlockCypher, many choices are disabled)")
    with indent(2):
        puts(colored.cyan('1: Basic send (generate transaction, sign, & broadcast)'))
        puts(colored.cyan('2: Sweep funds into bcwallet from a private key you hold'))
        puts(colored.cyan('3: Offline transaction signing (more here)'))

    choice = choice_prompt(
            user_prompt=DEFAULT_PROMPT,
            acceptable_responses=range(0, 5+1),
            quit_ok=True,
            default_input='1',
            show_default=True,
            )
    verbose_print('Choice: %s' % choice)

    if choice in ('q', 'Q'):
        return
    elif choice == '1':
        return send_funds(wallet_obj=wallet_obj)
    elif choice == '2':
        return sweep_funds_from_privkey(wallet_obj=wallet_obj)
    elif choice == '3':
        offline_tx_chooser(wallet_obj=wallet_obj)
Example #2
0
File: core.py Project: cwoebker/pen
def cmd_create(args):
    """Creates a list"""
    name = args.get(0)
    if name:
        penStore.createList(name)
    else:
        puts("not valid")
Example #3
0
    def post_process(self, session, meta):
        performers = ""
        for performer in meta["performers"]:
            performers += performer.name()+', '

        performers = performers.strip().rstrip(',')

        # write id3 data
        cmd = ['eyeD3',
              '--title',  meta["title"],
              '--artist', performers,
              '--album',  meta["album"]]

        if not meta['stared']:
            cmd += ['--track',         str(meta["number"]),
                    '--disc-num',      str(meta["disc"]),
                    '--release-year',  str(meta["year"]),
                    '--recording-date',str(meta["year"]),
                    '--add-image', 'cover.jpg:FRONT_COVER',
                    '--text-frame', 'TPE2:'+str(meta["artist"])]
        else:
            cmd += ['--text-frame',
                    'TPE2:Various Artists']

        cmd += ["%s.mp3" %meta["out_path_esc"]]
        print ''

        with indent(3, quote = colored.cyan(' # ')):
            try:
                puts('Executing %s' % cmd)
            except UnicodeEncodeError:
                sys.stdout.write(' # Executing %s\n' % cmd)

            return call(cmd) == 0
Example #4
0
def generate_offline_tx(wallet_obj):
    if not USER_ONLINE:
        puts(colored.red('BlockCypher connection needed to fetch unspents for signing.'))
        return

    # TODO: implement
    puts(colored.red('Feature Coming Soon'))
Example #5
0
File: core.py Project: cwoebker/pen
def cmd_all(args):
    """List everything recursively"""
    for penlist in penStore.data:
        puts(penlist)
        with indent(4, '  -'):
            for penfile in penStore.data[penlist]:
                puts(penfile)
Example #6
0
  def status(self, verbose=False):
    """Print process status."""
    main_proc = self._get_running_process_if_exists()
    listening_str = ''
    running_pid = ''
    if main_proc is not None:
      running_pid = main_proc.pid
      if verbose:
        listening = []
        for proc in [main_proc] + main_proc.get_children():
          listening.extend([conn.local_address
                            for conn in proc.get_connections()
                            if conn.status == 'LISTEN'])

        listening_str = [':'.join([ip, str(port)]) for ip, port in listening]
        listening_str = 'listening={}'.format(','.join(list(set(listening_str))))
    output = ''.join((self.name.ljust(20),
                      'running' if running_pid else 'stopped',
                      '={}'.format(running_pid).ljust(17) if running_pid else ''.ljust(17),
                      'enabled'.ljust(10) if self.enabled else 'disabled'.ljust(10),
                      listening_str))
    if running_pid:
      puts(colored.green(output))
    else:
      puts(output)
Example #7
0
    def do_create(self, s):
        """
        Create a new lucy user
        syntax : create [login] [password] [name] [email] [gpgkeyid]
        paul:user > create leo suchagoodpassword 'Léo Cavaillé' [email protected] 0x29948D7F1AC8586F
        The gpg key must be present in your home gpg keyring.
        """
        try:
            args = shlex.split(s)
        except:
            wrong_syntax('create')
        if len(args) != 5:
            wrong_syntax('create')

        login = args[0]
        password = args[1]
        name = args[2]
        email = args[3]
        gpgkeyid = args[4]
        
        # Try to fetch an armored ascii version of the key
        ascii_armored_key = paul.client.gpg.export_keys(gpgkeyid)
        user, reply = paul.client.proxy.create_user(login, password, name, email, ascii_armored_key)
        # TODO : could use user var to print some debug info on the created entity
        if user:
            puts(colored.green("Success : "+reply))
        else:
            puts(colored.red("Failed : "+reply))
 def __inner(*args, **kwargs):
     if args:
         manager = args[0]
         if not getattr(manager, 'db', None):
             puts(colored.yellow("DB needed for this operation: %s" % f))
             return
     return f(*args, **kwargs)
Example #9
0
 def test_py2_bytes_not_mangled(self):
     from clint.textui.colored import ColoredString
     # On python 2 make sure the same bytes come out as went in
     new_str = ColoredString('RED', '\xe4')
     assert '\xe4' in str(new_str)
     from clint.textui import puts
     puts(new_str)
Example #10
0
def _get_project_name(args):
        """Get project name"""
        name = args.get(0)
        puts("")
        while not name:
            name = raw_input("What is the project's short directory name? (e.g. my_project) ")
        return name
Example #11
0
def main(_, abbr):
    # try:
    #     patterns_module = __import__(abbr)
    # except:
    patterns_module = None
    actions = Actions(abbr, patterns_module)
    sys.ps1 = '(batshell) '
    banner = colored.yellow('''
      _==/           i     i           \==_
     /XX/            |\___/|            \XX\\
   /XXXX\            |XXXXX|            /XXXX\\
  |XXXXXX\_         _XXXXXXX_         _/XXXXXX|
 XXXXXXXXXXXxxxxxxxXXXXXXXXXXXxxxxxxxXXXXXXXXXXX
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX|
 XXXXXX/^^^^"\XXXXXXXXXXXXXXXXXXXXX/^^^^^\XXXXXX
  |XXX|       \XXX/^^\XXXXX/^^\XXX/       |XXX|
    \XX\       \X/    \XXX/    \X/       /XX/
       "\       "      \X/      "       /"
''')
    banner += colored.cyan('\n\nWelcome to bashell. '
                           'Type h for a list of commands.')
    shell = Shell(actions)
    import readline
    puts(banner)
    shell.interact(banner='')
Example #12
0
 def checkRange(self, split):
     try:
         int(split[0])
         int(split[1])
     except ValueError:
         puts(colored.red("Parameter sequence or format is wrong!"))
         sys.exit(1)
Example #13
0
def display_version():
    """Displays Tarbell version/release."""

    puts('{0} v{1}'.format(
        colored.yellow('Tarbell'),
        __version__
    ))
Example #14
0
def print_goals_for_tracked(tracked_id, achievement_or_iter=None, achieved=True, unachieved=False,
                            only_current=False, level=False, category=None, keywords=[],
                            indent=2, tracker=None):
    """
    Prints goals for a specific ``tracked_id`` from as tracked by a ``tracker``. By default, this
    will print out all achieved goals for every achievement in the ``tracker``.

    Arguments:

        achievment_or_iter
            If ``None``, this will print goals for all achievements registered with the ``tracker``.
            Otherwise an ``Achievement`` or list of achievements can be given to show goals for.

        achieved
            If True, prints out goals that have allready been achieved.

        unachieved
            If True, prints out goals that have not been achieved.

        only_current
            If True, only prints the goal currently being worked on (next to be achieved). This will
            override the ``achieved`` and ``unachieved`` options.

        category
            Category to filter achievements from the tracker.

        keywords
            Keywords to filter achievements from the tracker.

        level
            If True, show the current level with the achievements

        tracker
            The tracker to use for getting information about achievements and ``tracked_id``. If
            ``tracker`` is ``None``, this will default to using the default tracker.
    """
    from clint.textui import puts
    from clint.textui import indent as _indent
    from clint.textui.cols import console_width
    if tracker is None:
        tracker = _defaulttracker

    if achievement_or_iter is None:
        achievement_or_iter = tracker.achievements()
    elif _isclass(achievement_or_iter) and issubclass(achievement_or_iter, Achievement):
        achievement_or_iter = [achievement_or_iter]

    for achievement in achievement_or_iter:
        with _indent(indent):
            puts("{0}\n{1}\n".format(achievement.name, '='*(console_width({})-indent-2)))
        current = tracker.current(tracked_id, achievement)
        cl = None if not level else current[0]
        if only_current:
            print_goal(current[1], level=current[0], indent=indent)
        else:
            goals = tracker.achieved(tracked_id, achievement) if achieved else []
            goals += tracker.unachieved(tracked_id, achievement) if unachieved else []
            for goal in goals:
                print_goal(goal, current[0] >= goal['level'], level=cl, indent=indent)
                puts("\n")
Example #15
0
 def checkTestCase(self, key, value):
     if value:
         puts('Test case number ' + str(key) + ": " + colored.green("Passed!"))
         return True
     else:
         puts('Test case number ' + str(key) + ": " + colored.red("Failed!"))
         return False
Example #16
0
 def print_results(item):
     if isinstance(item, dict):
         puts(columns([item['id'].split('.')[-1], col],
                      [statused[item['status']], col]))
     else:
         puts(columns([item[0], col],
                      [statused.get(item[1], item[1]), col]))
Example #17
0
def print_goal(goal, achieved=False, level=None, indent=2):
    """ Print a goals description with its icon. Achieved (True/False) will choose the correct icon
    from the goal. If a level is specified, a tracker line will be added under the icon showing
    the current level out of the required level for the goal. If level is > the required level,
    achieved will be set to true.
    """
    from clint.textui import puts
    from clint.textui import indent as _indent
    from clint.textui.cols import columns, console_width
    if level is not None and level >= goal['level']:
        achieved = True
    icon = (goal['icon'].achieved() if achieved else goal['icon'].unachieved()).split('\n')
    maxiw = max([len(str(_)) for _ in icon])
    descw = console_width({})-maxiw-(indent + 4)
    desc = '{0}\n{1}\n\n{2}'.format(goal['name'], '-'*len(goal['name']),
                                    columns([goal['description'], descw])).split('\n')
    if level is not None:
        if level > goal['level']:
            level = goal['level']
        maxitw = max([len(_) for _ in icon])
        icon.append(("%d/%d" % (level, goal['level'])).center(maxitw))
    with _indent(indent):
        for i, d in _zip_longest(icon, desc):
            puts("{1:{0}}    {2}".format(maxiw, str(i) if i is not None else "",
                                         d.strip() if d is not None else ""))
Example #18
0
 def finalize(self):
     """Finalize this finish command.
     """
     self.github.add_labels(self.issue, "finished")
     self.github.remove_label(self.issue, "started")
     puts("Finished issue #{0:d}.".format(self.issue.number))
     super(FinishCommand, self).finalize()
Example #19
0
def do_all(scripts_folder):
    next_runs = get_next_run(scripts_folder)
    for index, action in enumerate(next_runs):
        action = action()
        run_action(action, extra="%d. %s - " % (index +1, action.check_name))
    if not next_runs:
        puts(colored.green("No check ready to be performed"))
Example #20
0
    def s3_upload(self, keyname, absolute_path):
        """
        Upload a file to s3
        """
        mimetype = mimetypes.guess_type(absolute_path)
        options = {'Content-Type': mimetype[0]}

        if mimetype[0] is not None and mimetype[0].startswith('text/'):
            upload = open(absolute_path, 'rb')
            options['Content-Encoding'] = 'gzip'
            key_parts = keyname.split('/')
            filename = key_parts.pop()
            temp_path = os.path.join(self.tempdir, filename)
            gzfile = gzip.GzipFile(temp_path, 'wb', 9, None, GZIP_TIMESTAMP)
            gzfile.write(upload.read())
            gzfile.close()
            absolute_path = temp_path

        hash = '"{0}"'.format(hashlib.md5(open(absolute_path, 'rb').read()).hexdigest())
        key = "{0}/{1}".format(self.bucket.path, keyname)
        existing = self.connection.get_key(key)

        if self.force or not existing or (existing.etag != hash):
            k = Key(self.connection)
            k.key = key
            puts("+ Uploading {0}/{1}".format(self.bucket, keyname))
            k.set_contents_from_filename(absolute_path, options, policy='public-read')
        else:
            puts("- Skipping  {0}/{1}, files match".format(self.bucket, keyname))
Example #21
0
    def execute(self):
        """Execute this start command.
        """
        if self.issue:
            puts("Issue: {0}".format(self.issue.title))
            user = self.github.get_user()

            if self.issue.assignee is None:
                self.issue = self.github.set_issue(self.issue.number,
                        assignee=user.login)

            # Verify that user got the issue.
            if self.issue.assignee == user:
                branch = super(StartCommand, self).execute()
                self.git.set_configuration("branch", branch,
                        issue=self.issue.number)
                self.github.add_labels(self.issue, "started")
            else:
                exit("Unable to update issue assignee.")
        else:
            if self.namespace.number and self.namespace.exclusive:
                exit("No available issue #{0} found assigned to you.".format(
                    self.namespace.number))
            elif self.namespace.number:
                exit("No available issue #{0} found.".format(
                    self.namespace.number))
            elif self.namespace.exclusive:
                exit("No available issues found assigned to you.")
            else:
                exit("No available issues found.")
Example #22
0
def show_all_data() :
    """showing all entries present in the data file"""
    loop = 1
    cwd = os.getcwd()
    file_path = cwd+"\DATA"
    file_content = open(file_path)
    users_list = file_content.read().split()
    puts(colored.green("List of entries present in data file."))
    space()
    for user in users_list :
        puts(colored.yellow(str(loop)+". "+user))
        loop = loop + 1
    if loop == 1 :
        puts(colored.cyan("message : No entries found!"))
    space()
    puts(colored.magenta("Note : press '1' to return back to menu."))
    puts(colored.magenta("Note : press '0' to exit."))
    space()
    x = int(raw_input("Action : "))
    if(x == 1) :
        flag = 0
        call_defined_function(menu(flag))
    elif(x == 0) :
        clear()
    else :
        flag = 1
        call_defined_function(menu(flag))
Example #23
0
def rename(fp, dry_run=False):
    """
    renames the file / folder intelligently
    dry_run determines if the actual rename is performed
    """
    if not fp.isdir():
        #file extension
        ext = fp.ext.lower()
        #do not touch files that might be downloaded
        IGNORE_EXTS = (".rar", ".part", ".iso", ".torrent", ".added")
        if ext in IGNORE_EXTS:
            return

    name = fp.namebase
    renamed = name.strip().replace("!", '').strip("_ ").strip(".")

    #is it an anime?
    if ANIME_RE.search(renamed):
        renamed = rename_anime(renamed)
    else:
        renamed = rename_episode(renamed)

    #is it a youtube video?
    res = YOUTUBE_RE.search(renamed)
    if res:
        renamed = re.sub(YOUTUBE_RE, '', renamed).strip("_ ")
        renamed = re.sub(r"(\S)_\s", r"\1 - ", renamed)
        renamed = re.sub(r"\b_", '', renamed)

    #is it a vimeo video?
    res = VIMEO_RE.search(renamed)
    if res:
        renamed = res.groupdict()["filename"].strip("_")
        renamed = renamed.replace("_", " ")

    # #is it a movie downloaded from the web?
    # res = MOVIE_RE.search(renamed)
    # if res:
    #     renamed = res.groupdict()['movie']
    #     renamed = renamed.replace(".", " ")

    #title case!
    renamed = smart_title(renamed)

    # #super specific replacements
    # renamed = renamed.replace("Greys Anatomy", "Grey's Anatomy")
    # renamed = renamed.replace("Chihayafuru 2", "Chihayafuru S2")

    #print and rename output if unchanged
    if fp.isdir():
        target = fp.dirname().joinpath(renamed)
    else:
        target = fp.dirname().joinpath(renamed + ext)
    if renamed != name:
        print "%s => " % name,
        puts(colored.green(renamed))
        if not dry_run:
            fp.rename(target)
    print target
    return target
Example #24
0
def start_server():
    checkpath = os.path.dirname(os.path.realpath(__file__)) + "\Server2232"
    loginpath = os.path.dirname(os.path.realpath(__file__)) + "\Server2232\Account and Login\RF_Bin"
    zonepath = os.path.dirname(os.path.realpath(__file__)) + "\Server2232\Zone Server\RF_Bin"
    os.chdir(loginpath)
    if os.path.isdir(checkpath):
        print("Starting AccountServer...")
        time.sleep(2)
        args1 = loginpath + "\AccountServerSD.exe"
        subprocess.Popen(args1)
        print("Starting BillingAgent...")
        time.sleep(2)
        args2 = loginpath + "\BillingAgentSD.exe"
        subprocess.Popen(args2)
        print("Starting LoginServer...")
        time.sleep(2)
        args3 = loginpath + "\LoginServerSD.exe"
        subprocess.Popen(args3)
        path = zonepath
        os.chdir(path)
        print("Starting ZoneServer...")
        time.sleep(2)
        args4 = zonepath + "\ZoneServerUD_x64.exe"
        with indent(4, quote=">>>"):
            puts(colored.red("Important: ") + "Type /open to LoginServer to enable normal account login.")
            subprocess.Popen(args4)
            time.sleep(20)
    else:
        print("Run Server Setup first.")
Example #25
0
def cmd_upload(args):
    # TODO: fix upload to web interface
    if not os.path.exists(COMO_BATTERY_FILE):
        error("No como database.")
    else:
        if is_osx:
            url = SERVER_URL + "/upload"
            cmd = "ioreg -l | awk '/IOPlatformSerialNumber/ " + \
                  "{ split($0, line, \"\\\"\"); printf(\"%s\\n\", line[4]); }'"
            computer_serial = subprocess.check_output(
                cmd, shell=True).translate(None, '\n')
            bat = get_battery()
            model = subprocess.check_output(
                "sysctl -n hw.model", shell=True).rstrip("\n")
            data = {
                'computer': hashlib.md5(computer_serial).hexdigest(),
                'model': model,
                'battery': hashlib.md5(bat['serial']).hexdigest(),
                'design': bat['designcap'],
                'age': get_age()
            }
            files = {'como': open(COMO_BATTERY_FILE, 'rb')}
            response = requests.post(url, files=files, data=data)
            if response.status_code == requests.codes.ok:
                puts("data uploaded")
            else:
                puts("upload failed")
        else:
            message("no uploading on this operating system")
Example #26
0
def print_path_info(address, path, coin_symbol, wif=None):

    assert path, path
    assert coin_symbol, coin_symbol
    assert address, address

    if wif:
        address_formatted = '%s/%s' % (address, wif)
    else:
        address_formatted = address

    if USER_ONLINE:
        addr_balance = get_total_balance(
                address=address,
                coin_symbol=coin_symbol,
                )

        with indent(2):
            puts(colored.green('%s (%s) - %s' % (
                path,
                address_formatted,
                format_crypto_units(
                    input_quantity=addr_balance,
                    input_type='satoshi',
                    output_type=UNIT_CHOICE,
                    coin_symbol=coin_symbol,
                    print_cs=True,
                    ),
                )))
    else:
        with indent(2):
            puts(colored.green('%s (%s)' % (
                path,
                address_formatted,
                )))
Example #27
0
def setup_jvm():
    puts(colored.yellow("Starting JVM..."))
    print()

    import jnius

    javasys = jnius.autoclass("java.lang.System")
    classpath = javasys.getProperty("java.class.path")

    puts(colored.cyan("Classpath:"))
    puts(colored.cyan(classpath))
    print()

    amended_cp = ":".join(
        [
            classpath,
            jarpath("ae-awt.jar"),
            jarpath("javax-imageio.jar"),
            jarpath("commons-codec-1.9.jar"),
            jarpath("lire.jar"),
        ]
    )

    javasys.setProperty("java.class.path", amended_cp)

    puts(colored.cyan("Classpath (amended):"))
    puts(colored.cyan(amended_cp))
    print()

    return jnius
Example #28
0
 def start_feature(self, feature):
     with indent(self.current_indent):
         puts("Feature: %s" % feature.name)
     with indent(self.current_indent + 2):
         puts(feature.description)
     print ""
     self.indent()
Example #29
0
def broadcast_signed_tx(wallet_obj):
    if not USER_ONLINE:
        puts(colored.red('BlockCypher connection needed to broadcast signed transaction.'))
        return

    # TODO: implement
    puts(colored.red('Feature Coming Soon'))
Example #30
0
def uninstall(packages, globally):
    required = requirements.load()
    
    for name in packages:
        if name in required:
            required.remove(name)

    if globally:
        uninstalled = []
        response = 'No uninstallation needed.'
        
        spin = spinner()
        spin.start()
        for name in packages:
            try:
                cmd = ['pip', 'uninstall', name, '-y']
                output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
                uninstalled += [name]
            except subprocess.CalledProcessError as e:
                notinstalled = 'Cannot uninstall requirement %s, not installed' % name
                if not e.output.startswith(notinstalled):
                    error(e.output)
                    response = 'No uninstallation performed.'
        spin.stop()
        
        if len(uninstalled) > 0:
            echo('\nUninstalled packages: ')
            with indent(4, quote='  -'):
                for name in uninstalled:
                    puts(name)
        else:
            echo('\n' + response)

    required.show()
Example #31
0
def kubectl_print(k_out, k_err, k_mode, k_lead):
    with indent(2):

        if k_out:
            puts(colored.white('\n'))
            if k_mode == 'active':
                puts(colored.green('✔  command output: \n'))
            else:
                puts(colored.green('✔  found, printing output:\n'))

            with indent(2):
                puts(colored.green(k_out.decode()))

                if k_lead:
                    puts(colored.cyan("Leading to technique id: %s" % k_lead))

        elif k_err:
            puts(colored.white('\n'))
            puts(colored.red(k_err.decode()))

        else:
            puts(colored.white('\n'))
            puts(colored.red('✘  none found\n'))
Example #32
0
def print_logo():
    text_art = text2art("RED   KUBE")
    print(termcolor.colored(text_art, 'red'))
    puts(colored.white("            +++ WELCOME TO RED-KUBE +++\n\n"))
Example #33
0
        scan_mode = cmd_args.mode

    if cmd_args.tactic:
        scan_tactic = cmd_args.tactic

    if cmd_args.show_tactics:
        get_mitre_tactics()
        sys.exit()

    if cmd_args.cleanup:
        cleanup()
        sys.exit()

    if scan_tactic in mitre_tactics:
        print_logo()
        scan_tactic = scan_tactic
        with indent(4):
            puts(colored.red("MITRE ATT&CK Tactic %s chosen " % scan_tactic))

        with open('attacks/%s.json' % scan_tactic) as tactic_file:
            tactic_data = json.load(tactic_file)

            for technique in tactic_data:
                run_kubectl(technique, scan_mode)
                time.sleep(1)

    else:
        print_logo()
        puts(colored.red("Please choose a tactic using --tactic TACTIC_NAME"))
        sys.exit()
Example #34
0
def process_soundcloud(vargs):
    """
    Main SoundCloud path.
    """

    artist_url = vargs['artist_url']
    track_permalink = vargs['track']
    keep_previews = vargs['keep']
    folders = vargs['folders']

    id3_extras = {}
    one_track = False
    likes = False
    client = get_client()
    if 'soundcloud' not in artist_url.lower():
        if vargs['group']:
            artist_url = 'https://soundcloud.com/groups/' + artist_url.lower()
        elif len(track_permalink) > 0:
            one_track = True
            track_url = 'https://soundcloud.com/' + artist_url.lower(
            ) + '/' + track_permalink.lower()
        else:
            artist_url = 'https://soundcloud.com/' + artist_url.lower()
            if vargs['likes'] or 'likes' in artist_url.lower():
                likes = True

    if 'likes' in artist_url.lower():
        artist_url = artist_url[0:artist_url.find('/likes')]
        likes = True

    if one_track:
        num_tracks = 1
    else:
        num_tracks = vargs['num_tracks']

    try:
        if one_track:
            resolved = client.get('/resolve', url=track_url, limit=200)

        elif likes:
            userId = str(client.get('/resolve', url=artist_url).id)

            resolved = client.get('/users/' + userId + '/favorites',
                                  limit=200,
                                  linked_partitioning=1)
            next_href = False
            if (hasattr(resolved, 'next_href')):
                next_href = resolved.next_href
            while (next_href):

                resolved2 = requests.get(next_href).json()
                if ('next_href' in resolved2):
                    next_href = resolved2['next_href']
                else:
                    next_href = False
                resolved2 = soundcloud.resource.ResourceList(
                    resolved2['collection'])
                resolved.collection.extend(resolved2)
            resolved = resolved.collection

        else:
            resolved = client.get('/resolve', url=artist_url, limit=200)

    except Exception as e:  # HTTPError?

        # SoundScrape is trying to prevent us from downloading this.
        # We're going to have to stop trusting the API/client and
        # do all our own scraping. Boo.

        if '404 Client Error' in str(e):
            puts(
                colored.red("Problem downloading [404]: ") +
                colored.white("Item Not Found"))
            return None

        message = str(e)
        item_id = message.rsplit(
            '/', 1)[-1].split('.json')[0].split('?client_id')[0]
        hard_track_url = get_hard_track_url(item_id)

        track_data = get_soundcloud_data(artist_url)
        puts_safe(
            colored.green("Scraping") +
            colored.white(": " + track_data['title']))

        filenames = []
        filename = sanitize_filename(track_data['artist'] + ' - ' +
                                     track_data['title'] + '.mp3')

        if folders:
            name_path = join(vargs['path'], track_data['artist'])
            if not exists(name_path):
                mkdir(name_path)
            filename = join(name_path, filename)
        else:
            filename = join(vargs['path'], filename)

        if exists(filename):
            puts_safe(
                colored.yellow("Track already downloaded: ") +
                colored.white(track_data['title']))
            return None

        filename = download_file(hard_track_url, filename)
        tagged = tag_file(filename,
                          artist=track_data['artist'],
                          title=track_data['title'],
                          year='2016',
                          genre='',
                          album='',
                          artwork_url='')

        if not tagged:
            wav_filename = filename[:-3] + 'wav'
            os.rename(filename, wav_filename)
            filename = wav_filename

        filenames.append(filename)

    else:
        aggressive = False

        # This is is likely a 'likes' page.
        if not hasattr(resolved, 'kind'):
            tracks = resolved
        else:
            if resolved.kind == 'artist':
                artist = resolved
                artist_id = str(artist.id)
                tracks = client.get('/users/' + artist_id + '/tracks',
                                    limit=200)
            elif resolved.kind == 'playlist':
                id3_extras['album'] = resolved.title
                if resolved.tracks != []:
                    tracks = resolved.tracks
                else:
                    tracks = get_soundcloud_api_playlist_data(
                        resolved.id)['tracks']
                    tracks = tracks[:num_tracks]
                    aggressive = True
                    for track in tracks:
                        download_track(track,
                                       resolved.title,
                                       keep_previews,
                                       folders,
                                       custom_path=vargs['path'])

            elif resolved.kind == 'track':
                tracks = [resolved]
            elif resolved.kind == 'group':
                group = resolved
                group_id = str(group.id)
                tracks = client.get('/groups/' + group_id + '/tracks',
                                    limit=200)
            else:
                artist = resolved
                artist_id = str(artist.id)
                tracks = client.get('/users/' + artist_id + '/tracks',
                                    limit=200)
                if tracks == [] and artist.track_count > 0:
                    aggressive = True
                    filenames = []

                    data = get_soundcloud_api2_data(artist_id)

                    for track in data['collection']:

                        if len(filenames) >= num_tracks:
                            break

                        if track['type'] == 'playlist':
                            track['playlist']['tracks'] = track['playlist'][
                                'tracks'][:num_tracks]
                            for playlist_track in track['playlist']['tracks']:
                                album_name = track['playlist']['title']
                                filename = download_track(
                                    playlist_track,
                                    album_name,
                                    keep_previews,
                                    folders,
                                    filenames,
                                    custom_path=vargs['path'])
                                if filename:
                                    filenames.append(filename)
                        else:
                            d_track = track['track']
                            filename = download_track(
                                d_track, custom_path=vargs['path'])
                            if filename:
                                filenames.append(filename)

        if not aggressive:
            filenames = download_tracks(client,
                                        tracks,
                                        num_tracks,
                                        vargs['downloadable'],
                                        vargs['folders'],
                                        vargs['path'],
                                        id3_extras=id3_extras)

    if vargs['open']:
        open_files(filenames)
Example #35
0
def tag_file(filename,
             artist,
             title,
             year=None,
             genre=None,
             artwork_url=None,
             album=None,
             track_number=None,
             url=None):
    """
    Attempt to put ID3 tags on a file.

    Args:
        artist (str):
        title (str):
        year (int):
        genre (str):
        artwork_url (str):
        album (str):
        track_number (str):
        filename (str):
        url (str):
    """

    try:
        audio = EasyMP3(filename)
        audio.tags = None
        audio["artist"] = artist
        audio["title"] = title
        if year:
            audio["date"] = str(year)
        if album:
            audio["album"] = album
        if track_number:
            audio["tracknumber"] = track_number
        if genre:
            audio["genre"] = genre
        if url:  # saves the tag as WOAR
            audio["website"] = url
        audio.save()

        if artwork_url:

            artwork_url = artwork_url.replace('https', 'http')

            mime = 'image/jpeg'
            if '.jpg' in artwork_url:
                mime = 'image/jpeg'
            if '.png' in artwork_url:
                mime = 'image/png'

            if '-large' in artwork_url:
                new_artwork_url = artwork_url.replace('-large', '-t500x500')
                try:
                    image_data = requests.get(new_artwork_url).content
                except Exception as e:
                    # No very large image available.
                    image_data = requests.get(artwork_url).content
            else:
                image_data = requests.get(artwork_url).content

            audio = MP3(filename, ID3=OldID3)
            audio.tags.add(
                APIC(
                    encoding=3,  # 3 is for utf-8
                    mime=mime,
                    type=3,  # 3 is for the cover image
                    desc='Cover',
                    data=image_data))
            audio.save()

        # because there is software that doesn't seem to use WOAR we save url tag again as WXXX
        if url:
            audio = MP3(filename, ID3=OldID3)
            audio.tags.add(WXXX(encoding=3, url=url))
            audio.save()

        return True

    except Exception as e:
        puts(
            colored.red("Problem tagging file: ") +
            colored.white("Is this file a WAV?"))
        return False
Example #36
0
	def handler(msg):
	puts(colored.yellow(msg.channel), newline=False)
	puts(" [", newline=False)
	puts(colored.green(msg.datetime), newline=False)
	puts("] ", newline=False)
	if msg.response:
			puts(colored.red(msg.text))
	else:
		puts(msg.text)
		if 'CFS' not in msg.channel: # Add agancy here e.g CFS, SES, MFS
			return
		if ('' not in msg.channel # add Filter here e.g Bridgewater (Will look for Info and Response)
			and '' not in msg. # More filters
			and '' not in msg.channel
			and '' not in msg.channel
			and '' not in msg.channel):
			return
		if ('Ops' in msg.channel # add things we want to skip e.g this will skip STURT GROUP OPS if Sturt Group is set above
			or 'Operations Support' in msg.channel
			or 'Officers Response' in msg.channel
			or 'Officers Info' in msg.channel
			or 'HQ' in msg.channel
			or 'Headquarters' in msg.channel
			or 'Person' in msg.channel
			or 'John Hutchins' in msg.channel):
			return
		for x in range(0, len(msg.text), 150):
			for phone_number in numbers:
			ser.write('ATZ\r')
			time.sleep(1)
			ser.write('AT+CMGF=1\r')
			time.sleep(1)
			ser.write('AT+CMGS="%s"\r' % str(phone_number))
			time.sleep(1)
			ser.write(msg.text[x:x+150] + '\r' + chr(26))
			time.sleep(1)
			print "Sent message to %r:" % (phone_number)
	scraper.run()
Example #37
0
def run_kubectl(rk_technique, rk_scan_mode):
    technique_command = rk_technique.get('command')
    technique_id = rk_technique['id']
    technique_leading_to = rk_technique['leading_to']
    technique_mode = rk_technique['mode']
    technique_args = rk_technique['args']
    technique_arg_list = rk_technique.get('arg_list')
    technique_multistep = rk_technique.get('multistep')
    technique_steps = rk_technique.get('commands')
    puts(colored.white('\n'))

    with indent(4):
        puts(colored.yellow("ID:        "), newline=False), puts(colored.white("%s" % technique_id))
        puts(colored.yellow("Technique: "), newline=False), puts(colored.white("%s" % rk_technique['name']))
        puts(colored.yellow("Command:   "), newline=False), puts(colored.white("%s" % technique_command))

        if rk_scan_mode == 'all' or technique_mode == rk_scan_mode:
            if not technique_args:

                if not technique_multistep:

                    out, err = kubectl_subproc(technique_command)
                    kubectl_print(out, err, technique_mode, technique_leading_to)

                else:
                    for cmd_step in technique_steps:

                        out, err = kubectl_subproc(cmd_step)
                        kubectl_print(out, err, technique_mode, technique_leading_to)
                        time.sleep(2)

            else:
                with indent(4):

                    puts(colored.white('\n'))
                    puts(colored.red("✘  The command requires specific parameters:"))
                    puts(colored.white('\n'))

                    for arg in technique_arg_list:
                        x = input("         %s:" % arg)
                        technique_command = technique_command.replace("$%s" % arg, x)

                    puts(colored.green("✔  command updated, running: ", technique_command))
                    out, err = kubectl_subproc(technique_command)
                    kubectl_print(out, err, technique_mode, technique_leading_to)
                    time.sleep(2)

        else:
            with indent(4):
                puts(colored.red("✘  This command mode does not match your scan mode."))
                time.sleep(2)
Example #38
0
def error(message):
    '''Nice little error message for the user that causes a quit'''
    puts(colored.red('\n !!! ' + message))
    sys.exit(1)
from google.cloud import bigquery
from jinja2 import Template, FileSystemLoader, Environment
from os import path
from pygments import highlight
from pygments.lexers.sql import SqlLexer
from pygments.formatters import TerminalFormatter
from pyfiglet import Figlet

# Configuration load
try:
    with open(path.join(".", "configuration",
                        "configuration.json")) as json_config:
        config_dict = json.load(json_config)
except (OSError, IOError) as e:
    with indent(4, quote="* "):
        puts(
            colored.red("Please create configuration.json. It doesn't exist."))
        sys.exit()


def create_view(dataset_name, view_name, project, viewSQL):

    f = Figlet(font="slant")
    print(f.renderText(view_name.replace("_", " ")))

    view_description = get_view_description(view_name)

    bigquery_client = bigquery.Client(project=project)

    job_config = bigquery.CopyJobConfig()
    job_config.write_disposition = "WRITE_TRUNCATE"
Example #40
0
def cleanup():
    out, err = kubectl_subproc("kubectl delete pods trivy awscli")

    with indent(2):
        puts(colored.green(out.decode()))
        puts(colored.red(err.decode()))
Example #41
0
                colored.red(
                    'Not a app dir (or any of the parent directories)'))
        sys.exit(1)
    global_conf['app_root'] = app_root

    # 读取static.json
    try:
        static_conf = get_static_conf(app_root)
        static_conf = static_conf['staticpy']
    except json.decoder.JSONDecodeError, e:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('JSONDecodeError in static.json: %s' % e))
        sys.exit(1)
    except KeyError:
        with indent(8, quote=colored.clean('#')):
            puts(colored.red('"staticpy" key not in static.json'))
        sys.exit(1)

    global_conf['host_dict'] = defaultHostDict
    if 'hostDict' in static_conf:
        for k, v in static_conf['hostDict'].iteritems():
            global_conf['host_dict'].setdefault(k, v + '%s.git')
        del static_conf['hostDict']

    # 遍历repo
    for repo_name, conf_json in static_conf.iteritems():
        with indent(4, quote=colored.clean('#')):
            puts(colored.clean('** ' * 10))
            puts(colored.yellow('Processing %s' % repo_name))

        # 继承缺省静态文件路径
def main():

    DATASET = ""
    PROJECT = ""

    parser = argparse.ArgumentParser()

    parser.add_argument(
        "-m",
        "--metric_file",
        metavar="METRIC",
        action="store",
        help="the metric filename to process",
    )
    parser.add_argument("-o",
                        "--output_file",
                        metavar="OUTPUTFILE",
                        action="store")
    parser.add_argument("-v",
                        "--create_view",
                        action="store_true",
                        help="create a view from the metric")
    parser.add_argument("-a",
                        "--all_metrics",
                        action="store_true",
                        help="deploy all views")
    parser.add_argument(
        "-d",
        "--dataset",
        metavar="DATASET",
        action="store",
        help="deploy views to this dataset",
    )
    parser.add_argument(
        "-p",
        "--project",
        metavar="PROJECT",
        action="store",
        help="deploy views to a dataset in this project",
    )

    args = parser.parse_args()

    if not (args.all_metrics or args.metric_file):
        parser.print_usage()
        sys.exit(1)

    if not args.all_metrics:
        with indent(4, quote="* "):
            puts(
                colored.green("Metric file is ['{}']".format(
                    args.metric_file)))
            if args.output_file:
                puts(
                    colored.green("Output file is ['{}']".format(
                        args.output_file)))
            puts(
                colored.blue("Rendering ['{}']".format(
                    args.metric_file.replace(".j2", ""))))

        finalSQL = render_template(args.metric_file, args.output_file)

        if args.create_view:
            view_sql = finalSQL
            view_name = args.metric_file.split(".")[0]
            create_view(args.dataset, view_name, args.project, view_sql)

        if args.output_file:
            print("...SQL File built at ./build/{}".format(args.output_file))
    else:
        deploy_all(args.dataset)

    with indent(4, quote="* "):
        puts(colored.yellow("Finished!"))
Example #43
0
def start():
    if args.flags.contains(('--version', '--ver', '-v')):
        show_version()
        sys.exit(2)

    elif args.flags.contains(('-h', '--help')):
        show_usage()
        sys.exit(2)

    username = args.get(0)
    if not username:
        show_about()
        puts('')
        show_usage()
        sys.exit(1)

    user = core.get_info_for(username)

    if user:
        user_info = ' - '.join(
            (str(colored.cyan(username)),
             '{0} followers'.format(str(user.followers_count)),
             '{0} public repositories'.format(str(user.public_repo_count))))
        puts(user_info)

        for repo in core.get_repos_for(username):

            # NAME

            c = [
                [colored.yellow(repo[u'name']), 38],
            ]

            # WATCHERS

            watchers = repo[u'watchers']

            watchers_s = ''
            if watchers > 1:
                watchers_s += 's'

            c.append(['{0} watcher{1}'.format(watchers, watchers_s), 14])

            # FORKS

            forks = repo[u'forks']

            forks_s = ''
            if forks > 1:
                forks_s += 's'

            c.append(['{0} fork{1}'.format(forks, forks_s), 10])

            # FORK

            if repo.get('fork', False):
                fork = colored.red('(FORK)')
            else:
                fork = ''

            c.append([fork, 10])

            # print the column
            puts(columns(*c))

    else:
        puts('Please provide a valid username')
        sys.exit(1)
Example #44
0
def sms(msg):
	if c.get("SMS", "COM") == "":
		print "No SMS Settings Found"
		return
	else:
		com = c.get("SMS", "COM")
		ser = serial.Serial(com, 460800, timeout=5)
		for x in range(0, len(msg.text), 150):
			for phone_number in numbers:
			ser.write('ATZ\r')
			sleep(1)
			ser.write('AT+CMGF=1\r')
			sleep(1)
			ser.write('AT+CMGS="%s"\r' % str(phone_number))
			sleep(1)
			ser.write(msg.text[x:x+150] + '\r' + chr(26))
			sleep(1)
			print "Sent message to %r:" % (phone_number)
def send(msg):
		app = ""# app ID
		for k in usr:
		user = k
		params = {
		'token': app,
		'user': user,
		'title': msg.channel,
		'message': msg.text,
		'retry': 30, 
		'expire': 180,
		'priority': 2 if msg.response else 0,
		}
		if msg.response: params['sound'] = 'updown'
		urllib3.disable_warnings()
		requests.post('https://api.pushover.net/1/messages.json', data=params, verify=False)
		name = usr[k]
		print "POSTed message to " + name
 
if __name__ == "__main__":
	scraper = Scraper(5, recent_messages=True)
	@scraper.register_handler
	def handler(msg)
	puts(" [", newline=False)
	puts(colored.green(msg.datetime), newline=False)
	puts("] ", newline=False)
	if msg.response:
			puts(colored.red(msg.text))
	else:
		puts(msg.text)
		# Copy and paste below as many times as you have filters 
		#---------------Start Here-----------------
		if '' in msg.channel: # add filter here 
			my_thread = threading.Thread(target=email, args=(msg,))
			my_thread2 = threading.Thread(target=sms, args=(msg,))
			my_thread3 = threading.Thread(target=send, args=(msg,))
			my_thread.start()
			my_thread2.start()
			my_thread3.start()
			my_thread.join()
			my_thread2.join()
			my_thread3.join()
			return
		#-------------Stop Here ------------------
		else:
			return
Example #45
0
def show_usage():
    puts('Usage: ' + colored.cyan('humble <username>'))
Example #46
0
    def getImage(self):

        # VERIFICAMOS SI LA CAMARA ESTA HABILITADA EN LA CONFIGURACION DEL ARCHIVO config.ini
        if self.enable:
            self.isWorking = True
            puts(colored.cyan('[GET IMAGE: ' + str(self.cameraName) + ' >> ' + str(self.url)))

            # CONTRASTAMOS QUE LA HORA ACTUAL NO SE ENCUENTRE EN EL RANGO DE LAS RESTRICCIONES
            isRestrict, hourRestrict = self.restrictHour()
            if isRestrict:
                self.isWorking = False
                puts(colored.yellow('     - Hora restringida -> ' + str(hourRestrict[0]) + ' - ' + str(hourRestrict[1])))
            else:

                # GENERAMOS EL PATH DE SALIDA PARA LA NUEVA IMAGEN
                self.generateDatePath()
                toPath = self.GLOBALPATH + str(self.directory) + self.filenamePath
                if not os.path.exists(toPath):
                    os.makedirs(toPath)
                toPathFilename = toPath + str(self.filename)
                puts(colored.yellow('     - to path >> ' + toPathFilename))
                # ------------------------------------------------

                # VALIDAMOS QUE LA CONEXION CON EL SERVICIO REQUIERE AUTENTICACION
                if self.auth:
                    cen = self.saveImage(toPathFilename)
                else:
                    cen = self.saveImage_urllib2(toPathFilename)
                # ----------------------------------------------------------------

                self.isWorking = False

                # CONDICIONAL PARA AGREGAR MARCA DE AGUA CON LOGOTIPO INSTITUCIONAL Y CABECERA
                if cen and self.watermark:
                    self.pasteLogo(toPathFilename)
                # -----------------------------------------------------------------------------

                # CONDICIONAL: SI CONFIGURAMOS UN URLUP SUBIREMOS LA IMAGEN MEDIANTE UN SERVICIO WEB
                if cen and self.urlUp is not False:
                    try:
                        files = {'file': open(toPathFilename, 'rb')}
                        puts(colored.cyan('     - uploading image...'))
                        puts(colored.yellow('         [' + self.urlUp + ']'))
                        response = requests.post(self.urlUp, files=files)
                        puts(colored.green('     - uploaded image!! ' + str(response.status_code)))
                    except:
                        puts(colored.green('     - upload Error!! '))
                # -----------------------------------------------------------------------------

            puts(colored.cyan(' END]'))
            print
        else:
            self.isWorking = False
Example #47
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

sys.path.insert(0, os.path.abspath('..'))

from clint.textui import puts, colored
from clint.textui import columns

lorem = 'Lorem ipsum dolor sit amet, consehdfhdfhdfhdfhdfhctetur adi pisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'

if __name__ == '__main__':
    # puts(min_width('test\nit', 20) + ' me')
    # puts(max_width(lorem, 20) + ' me')

    # print max_width(lorem, 45)

    col = 60

    puts(
        columns([(colored.red('Column 1')), col],
                [(colored.green('Column Two')), None],
                [(colored.magenta('Column III')), col]))
    puts(
        columns(['hi there my name is kenneth and this is a columns', col],
                [lorem, None], ['kenneths', col]))
Example #48
0
def show_about():
    puts('{0} {1}'.format(colored.yellow(core.__title__), PROJECT_BYLINE))
    puts(PROJECT_URL)
Example #49
0
def main():
    """
    Initializes a project to work with snake
    """
    if not os.path.exists('.git'):
        repo = git.Repo.init(os.path.abspath('.'))
    else:
        repo = git.Repo('.')
    git_ignore = os.path.abspath('./.gitignore')
    git_updated = False
    # generate .gitignore file
    updated = False
    if os.path.exists(git_ignore):
        with open(git_ignore, 'a') as handle:
            for ignore in ignore_list:
                try:
                    subprocess.check_call(['grep', '-q', ignore, git_ignore])
                except subprocess.CalledProcessError:
                    updated = True
                    handle.write(ignore)
                    git_updated = True
    else:
        updated = True
        with open(git_ignore, 'w') as handle:
            for ignore in ignore_list:
                handle.write(ignore)
        git_updated = True

    if updated:
        repo.index.add(['.gitignore'])
    # make test and doc directories
    for path in paths:
        if not os.path.exists(os.path.abspath(path)):
            os.mkdir(path)
            with open(os.path.join(path, 'README'), 'w') as handle:
                handle.write(readme_strings[path])
            repo.index.add([path])
            git_updated = True

    # Create the metadata files
    if not os.path.exists(os.path.abspath('snake.cfg')):
        parser = ConfigParser.RawConfigParser()
        parser.add_section('release')
        if os.path.exists(os.path.abspath('setup.py')):
            get_meta = lambda field: subprocess.check_output(
                ['python', 'setup.py', '--{0}'.format(field)]).strip()
            metadata = [(field, get_meta(field)) for field in meta_fields]
            metadata = dict(metadata)
            puts(
                colored.yellow("""
The snake.cfg file has been created, but because you already have
a setup.py, the file is not being used.  Please update your
setup.py to pull in the snake.cfg details.  Here is an example:

{0}""".format(setup_py_template)))

        else:
            metadata = {}
            for field in meta_fields:
                msg = 'What is the {0} for this project? '.format(field)
                metadata[field] = raw_input(msg)
            with open('setup.py', 'w') as handle:
                handle.write(setup_py_template)
        for field in meta_fields:
            parser.set('release', field, metadata[field])
        with open('snake.cfg', 'w') as handle:
            parser.write(handle)
        git_updated = True
    if not os.path.exists(os.path.abspath('MANIFEST.in')):
        with open('MANIFEST.in', 'w') as handle:
            handle.write(manifest_in_template)
        git_updated = True
    else:
        write = False
        with open('MANIFEST.in', 'r') as handle:
            if 'snake.cfg' not in handle.read():
                write = True
        if write:
            with open('MANIFEST.in', 'a') as handle:
                handle.write(manifest_in_template)
            git_updated = True

    if not os.path.exists('requirements.txt'):
        with open('requirements.txt', 'w') as handle:
            handle.write(
                '# Created by Gitsnake. HISSSSSSSSSSSSSSSSSSSSSSSSS\n')

    for path in files:
        repo.index.add([path])

    if git_updated:
        print "A number of resources have been added to your git repo."
        print "Don't forget to commit them"
Example #50
0
def show_version():
    puts('{0} v{1}.'.format(colored.yellow(core.__title__), core.__version__))
Example #51
0
# Parse args flags
args = Args()
flags = set()

# remove flags from args
for flag in args.flags.all:
    if flag[:2] == '--':
        continue

    args.remove(flag)
    flags = flags.union(flag[1:])

# if verbose mode is on, print args
if 'v' in flags:
    puts(colored.blue('Grouped Arguments: ') + str(dict(args.grouped)))
    puts(colored.blue('Flags: ') + str(flags))
    print()

# get first arg
ARG0 = args.grouped.get('_')[0]

# get config file location
CFG_FILE = get_arg('--cfg', 'dgc.json')

# get number of threads
THREADS = int(get_arg('--threads', 32))

# first, check for init
if ARG0 == 'init':
    dgc = diggicamp.new(args.grouped.get('_')[1], CFG_FILE)
Example #52
0
def bankofamerica(user=None, quit_when_finished=True, browser=None, index=None):

    if not user:
        # Get the username from the command line arguments.
        user = args.get(0)

    # Must supply username.
    if user is None:
        puts(colored.red('You must supply a username like "python bankofamerica.py nick"'))
        sys.exit()

    # Get the user's password from the password backend.
    key = keyring.get_password('bankofamerica.com', user)

    # If the key doesn't exist in the password backend.
    if key is None:
        puts(colored.red("You must store the password for {} in your keyring's backend.".format(user)))
        puts('See: http://pypi.python.org/pypi/keyring/#configure-your-keyring-lib')
        sys.exit()

    # Log what we're currently working on.
    puts(colored.blue('\nBank of America ({})'.format(user)))

    if not browser:
        # Init the WebDriver.
        b = webdriver.Firefox()
    else:
        b = browser

    b.get('https://www.bankofamerica.com/')

    # Find the username field on the page.
    username = b.find_element_by_css_selector('input#id')
    username.send_keys(user)

    # Get the state out of the user's config.
    state_config = config._sections['bankofamerica']['state']

    # Select the correct state.
    state = b.find_element_by_css_selector('option[value="{}"]'.format(state_config))
    state.click()

    username.submit()

    # If we have a password field, continue. Otherwise, wait to see if we are
    # being asked a security question.
    try:
        WebDriverWait(b, timeout=10).until(_element_available(b, 'input#tlpvt-passcode-input'))
    except TimeoutException:
        WebDriverWait(b, timeout=10).until(_element_available(b, 'input#tlpvt-challenge-answer'))

    # If we have a password field now, fill it with the key and submit the form.
    try:
        password = b.find_element_by_css_selector('input#tlpvt-passcode-input')
        password.send_keys(key)
        password.submit()
    except NoSuchElementException:

        # We need to hit the keychain for the security question.
        answer = b.find_element_by_css_selector('input#tlpvt-challenge-answer')
        question = b.find_element_by_css_selector('label[for="tlpvt-challenge-answer"]').text.strip()

        # The keychain name should be "username What is your mother's middle name", for example.
        keyAnswer = keyring.get_password('bankofamerica.com', '{} {}'.format(user, question))

        # Make sure we have an answer for the question.
        if keyAnswer is None:
            puts(colored.red("We couldn't find an answer for the question '{}' in your keyring's backend".format(question)))
            b.quit()
            sys.exit()

        # Fill the answer and submit.
        answer.send_keys(keyAnswer)
        answer.submit()

        # If we've answered correctly, now we have to wait for the password field.
        WebDriverWait(b, timeout=10).until(_element_available(b, 'input#tlpvt-passcode-input'))

        # Fill the password and submit.
        password = b.find_element_by_css_selector('input#tlpvt-passcode-input')
        password.send_keys(key)
        password.submit()

    # Wait until we have a link with the account text, and click it.
    accounts = config._sections['bankofamerica']['account'].split(',')
    account = accounts[index]
    WebDriverWait(b, timeout=10).until(_element_available(b, 'a[id="{}"]'.format(account)))
    account_link = b.find_element_by_css_selector('a[id="{}"]'.format(account))
    account_link.click()

    print 'Bank of America ({}): {}'.format(user, amount.text)

    if quit_when_finished:
        b.quit()

    return b
Example #53
0
def cmd_logs(opts):
    """Fetch the logs of a container
    """
    config = load_config(opts.config)
    b = get_blockade(config, opts)
    puts(b.logs(opts.container).decode(encoding='UTF-8'))
Example #54
0
def main(argv=None, stdin=None):
    stdin = stdin or sys.stdin
    argv = (argv or sys.argv)[1:]

    parser = argparse.ArgumentParser(usage=("%(prog)s [build | apply | startproject | startapp]"))
    subparsers = parser.add_subparsers()

    def add_default_arguments(p):
        p.add_argument("--region",
                       dest="region",
                       help="AWS region where this project should be applied")

        p.add_argument("--debug",
                       dest="debug",
                       action="store_true",
                       help="Verbose output for debugging purpouses.")

    startproject_parser = subparsers.add_parser('startproject', description='Start a new project')
    add_default_arguments(startproject_parser)
    startproject_parser.set_defaults(cls=Bootstrap)
    startproject_parser.set_defaults(func="startproject")
    startproject_parser.add_argument("project_name",
                                     type=str,
                                     help="Name of the project.")

    startapp_parser = subparsers.add_parser('startapp', description='Start a new app')
    add_default_arguments(startapp_parser)
    startapp_parser.set_defaults(cls=Bootstrap)
    startapp_parser.set_defaults(func="startapp")
    startapp_parser.add_argument("app_name",
                                 type=str,
                                 help="Name of the application.")
    startapp_parser.add_argument("--runtime",
                                 dest="runtime",
                                 default='py',
                                 type=str,
                                 choices=('py', 'js', 'java'),
                                 help="App runtime")

    build_parser = subparsers.add_parser('build', description='Build')
    add_default_arguments(build_parser)
    build_parser.set_defaults(cls=ProjectBuild)
    build_parser.set_defaults(func="build")

    apply_parser = subparsers.add_parser('apply', description='Build')
    add_default_arguments(apply_parser)
    apply_parser.set_defaults(cls=ProjectApply)
    apply_parser.set_defaults(func="apply")
    apply_parser.add_argument("-s", "--stage",
                              dest="stage",
                              type=str,
                              default='dev',
                              help="Stage where to apply this project")
    apply_parser.add_argument("--cf-timeout",
                              dest="timeout_in_minutes",
                              type=int,
                              default=15,
                              help="CloudFormation timeout.")

    run_parser = subparsers.add_parser('run', description='Run lambda locally')
    add_default_arguments(run_parser)
    run_parser.set_defaults(cls=ProjectRun)
    run_parser.set_defaults(func="run")
    run_parser.add_argument("lambda_name",
                            type=str,
                            help="Lambda you want to run locally in the format APP.LAMBDA_NAME")

    delete_parser = subparsers.add_parser('delete', description='Delete this project stacks')
    add_default_arguments(delete_parser)
    delete_parser.set_defaults(cls=ProjectDelete)
    delete_parser.set_defaults(func="delete")
    delete_parser.add_argument("-s", "--stage",
                               dest="stage",
                               type=str,
                               default='dev',
                               help="Stage where to apply this project")
    delete_parser.add_argument("--confirm",
                               dest="dry_run",
                               action="store_false",
                               help="Confirm the deletion of the resources")

    options, args = parser.parse_known_args(argv)

    path = os.getcwd()
    try:
        obj = options.cls(path=path, stdin=stdin, **vars(options))
        getattr(obj, options.func)()
    except BaseGordonException as exc:
        puts(colored.red("\n{}".format(exc.get_hint())))
        return exc.code
    except Exception:
        raise

    return 0
Example #55
0
def bar():
    puts(colored.blue("Nice to meet you, I am bar."))
    sys.exit(1)
Example #56
0
def cmd_version(opts):
    """Show the Blockade version information
    """
    import blockade.version
    puts("Blockade " + blockade.version.__version__)
Example #57
0
__FILENAME__ = main
#!/usr/env/bin python

from clint.textui import puts, colored
import sys

def foo():
    puts(colored.red("I am a mighty foo function!"))
    sys.exit(0)

def bar():
    puts(colored.blue("Nice to meet you, I am bar."))
    sys.exit(1)

if __name__ == "__main__":
    puts("Running as a script!")
    sys.exit(2)

########NEW FILE########
__FILENAME__ = bootstrapper
#!/usr/bin/env python

# Copyright (c) 2013 John Sullivan
# Copyright (c) 2013 Other contributers as noted in the CONTRIBUTERS file
#
# This file is part of superzippy
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#
# You may obtain a copy of the License at
#!/usr/bin/env python
# process_monitorUI.py
# Copyright Xemplar Biometrics, 2011
#
# Monitors processes via zeroMQ comm channels outputs via textUI

from clint.textui import progress
from clint.textui import puts, colored
from clint.textui import columns
import random
import os
import time

col1 = 5
col2 = 30
col3 = 5
col4 = 30

while True:
    puts(
        columns([(colored.red('Core')), col1], [('Load'), col2],
                [colored.red('Core'), col3], ['Load', col4]))
    for l in range(32):
        puts(
            columns([(colored.red(str(l + 1))), col1],
                    [('>' * random.randint(0, 29)), col2],
                    [colored.red(str(l + 33)), col3],
                    ['>' * random.randint(0, 29), col4]))
    time.sleep(.5)
    os.system('clear')
Example #59
0
 def start(self):
     vm = Vmrun(self.vmx, debug=self.debug)
     if self.gui:
         vm.start(gui=True)
     else:
         vm.start()
     if vm.check_tools() is True:
         puts(colored.yellow("Getting IP address..."))
         ip = vm.ip()
         puts(colored.green("VM started on {}".format(ip)))
         puts(colored.yellow("Sharing current folder..."))
         vm.enableSharedFolders()
         cwd = os.getcwd()
         vm.addSharedFolder('mech', cwd)
         puts(
             colored.green(
                 "Added shared folder 'mech' for current folder: {}".format(
                     cwd)))
     else:
         puts(colored.yellow("VMWare Tools is not installed or running..."))
         puts(colored.green("VM started"))
Example #60
0
def foo():
    puts(colored.red("I am a mighty foo function!"))
    sys.exit(0)