Beispiel #1
0
    def run(self):

        print('old version: %s  new version: %s' %
              (metadata['version'], self.version))
        try:
            input('Press enter to confirm, or ctrl-c to exit >')
        except KeyboardInterrupt:
            raise SystemExit("\nNot proceeding")

        old = "__version__ = '%s'" % metadata['version']
        new = "__version__ = '%s'" % self.version
        module_file = read_module_contents()
        with open('errata_tool/__init__.py', 'w') as fileh:
            fileh.write(module_file.replace(old, new))

        old = 'Version:        %s' % metadata['version']
        new = 'Version:        %s' % self.version
        spec_file = read_spec_contents()
        with open('python-errata-tool.spec', 'w') as fileh:
            fileh.write(spec_file.replace(old, new))

        # Commit everything with a standard commit message
        cmd = ['git', 'commit', '-a', '-m', 'version %s' % self.version]
        print(' '.join(cmd))
        subprocess.check_call(cmd)
Beispiel #2
0
    def run(self):

        print('old version: %s  new version: %s' %
              (metadata['version'], self.version))
        try:
            input('Press enter to confirm, or ctrl-c to exit >')
        except KeyboardInterrupt:
            raise SystemExit("\nNot proceeding")

        old = "__version__ = '%s'" % metadata['version']
        new = "__version__ = '%s'" % self.version
        module_file = read_module_contents()
        with open('version.py', 'w') as fileh:
            fileh.write(module_file.replace(old, new))

        old = 'Version: %s' % metadata['version']
        new = 'Version: %s' % self.version
        spec_file = read_spec_contents()
        with open('tendrl-commons.spec', 'w') as fileh:
            fileh.write(spec_file.replace(old, new))

        # Commit everything with a standard commit message
        cmd = ['git', 'commit', '-a', '-m', 'version %s' % self.version]
        print(' '.join(cmd))
        subprocess.check_call(cmd)
Beispiel #3
0
def main (filepath):
    # abort if it is directory
    if os.path.isdir(filepath):
        sys.exit("azcat: '%s' is a directory. Aborted." % filepath)

    try:
        with open(filepath, "r") as f:
            s = f.read()
    except IOError as e:
        sys.exit("azcat: cannot open '%s': %s" % (f, str(e)))
    except UnicodeDecodeError:
        sys.exit("azcat: file seems a binary file. Aborted.")

    if s.find("\x00") != -1:
        sys.exit("azcat: file seems a binary file. Aborted.")

    # confirm if file size is larger than 1MB
    if os.path.getsize(filepath) > 1024*1024:
        if input("file size is big; do you continue? [Y/n]: ") == "n":
            sys.exit("aborted.")

    # if the number of lines is over 50, pipe to a pager
    if s.count("\n") > 50:
        p = Popen(["less", "-R", "-"], stdin=PIPE)
        try:
            out = p.stdin
            pretty_print(filepath, out)
            p.stdin = sys.stdin
            p.wait()
        except IOError: # this will raised after the pager existed
            pass
    else:
        out = sys.stdout.buffer
        pretty_print(filepath, out)
Beispiel #4
0
def _confirm(question, default, file=sys.stderr):
    """Prompt a yes/no question and convert the answer to a boolean value."""
    answers = {'': default, 'y': True, 'yes': True, 'n': False, 'no': False}
    suffix = '[Y/n] ' if default else ' [y/N] '
    while True:
        file.write(question + suffix)
        file.flush()
        ans = answers.get(input().lower())
        if ans is not None:
            return ans
def _confirm(question, default, file=sys.stderr):
    """Prompt a yes/no question and convert the answer to a boolean value."""
    answers = {'': default, 'y': True, 'yes': True, 'n': False, 'no': False}
    suffix = '[Y/n] ' if default else ' [y/N] '
    while True:
        file.write(question + suffix)
        file.flush()
        ans = answers.get(input().lower())
        if ans is not None:
            return ans
Beispiel #6
0
def prompt_new_action(old_action):
    prompt = 'Enter an action for this bug: >'
    if old_action:
        print('Old action was:')
        print(old_action)
        prompt = 'Enter to keep this action, or type a new one: >'
    try:
        new_action = input(prompt)
    except KeyboardInterrupt:
        raise SystemExit("\nNot proceeding")
    if new_action:
        return new_action
    return old_action
    def raise_warning():
        if not sys.stdin.isatty() or not sys.stdout.isatty():
            print("Destructive operations are not scriptable")
            " and should be run from the command line"
            sys.exit(1)

        print("You are operating on more than half of the objects, this is ")
        "potentially VERY DANGEROUS: do you want to continue?"
        print("If so, please type: 'Yes, I am sure of what I am doing.'")
        a = input("confctl>")
        if a == "Yes, I am sure of what I am doing.":
            return True
        print("Aborting")
        sys.exit(1)
Beispiel #8
0
def load_file (filepath):
    try:
        with open(filepath, "r") as f:
            s = f.read()
    except IOError as e:
        sys.exit("azcat: cannot open '%s': %s" % (filepath, str(e)))
    except UnicodeDecodeError:
        sys.exit("azcat: file seems a binary file.")

    if s.find("\x00") != -1 or s.find("\x1b") != -1:
        sys.exit("azcat: file seems a binary file.")

    # confirm if file size is larger than 1MB
    if os.path.getsize(filepath) > 1024*1024:
        if input("file size is big; do you continue? [Y/n]: ") == "n":
            sys.exit()
    return s
Beispiel #9
0
def answer_vm_question(virtual_machine):
    print("\n")
    choices = virtual_machine.runtime.question.choice.choiceInfo
    default_option = None
    if virtual_machine.runtime.question.choice.defaultIndex is not None:
        ii = virtual_machine.runtime.question.choice.defaultIndex
        default_option = choices[ii]
    choice = None
    while choice not in [o.key for o in choices]:
        print("VM power on is paused by this question:\n\n")
        print("\n".join(
            textwrap.wrap(virtual_machine.runtime.question.text, 60)))
        for option in choices:
            print("\t %s: %s " % (option.key, option.label))
        if default_option is not None:
            print("default (%s): %s\n" %
                  (default_option.label, default_option.key))
        choice = input("\nchoice number: ").strip()
        print("...")
    return choice
    def raise_warning(self, objects):
        tag_hosts = defaultdict(list)
        hosts_set = set()
        for obj in objects:
            path = os.path.dirname(obj.key).replace(self.entity.base_path(), '')
            tag_hosts[path].append(obj.name)
            hosts_set.add(obj.name)

        if self.args.host and len(hosts_set) <= 1:
            # The host option is set and all objects belong to the same host
            return

        print("The selector you chose has selected the following objects:")
        if self.args.yaml:
            print(yaml.dump(tag_hosts, default_flow_style=False))
        else:
            print(json.dumps(tag_hosts))
        print("Ok to continue? [y/N]")
        a = input("confctl>")
        if a.lower() != 'y':
            print("Aborting")
            sys.exit(1)
Beispiel #11
0
#!/usr/bin/python
from __builtin__ import input

from Adafruit_PWM_Servo_Driver import PWM
import time

# ===========================================================================
# Example Code
# ===========================================================================

print('informations::::::')
print('Angle Between 0-180 Deg')
b = (input('Cycle ? '))
a = (input('channel number ? '))
c = (input('Min Angle ? '))
d = (input('Max Angle ? '))

fmin = (150 + (c * 2.5))
fmax = (600 - (d * 2.5))

print('Fmin value : ', fmin)
print('Fmax value : ', fmax)

# Initialise the PWM device using the default address
pwm = PWM(0x40)
# Note if you'd like more debug output you can instead run:
#pwm = PWM(0x40, debug=True)

servoMin = 150  # Min pulse length out of 4096   150
servoMax = 600  # Max pulse length out of 4096    650
Beispiel #12
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email', nargs='?', default=None,
                         help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password', nargs='?', default=None,
                         help='The password for your Mint.com account')
    cmdline.add_argument('--accounts', action='store_true', dest='accounts',
                         default=False, help='Retrieve account information'
                         ' (default if nothing else is specified)')
    cmdline.add_argument('--budgets', action='store_true', dest='budgets',
                         default=False, help='Retrieve budget information')
    cmdline.add_argument('--extended-accounts', action='store_true',
                         dest='accounts_ext', default=False,
                         help='Retrieve extended account information (slower, '
                         'implies --accounts)')
    cmdline.add_argument('--transactions', '-t', action='store_true',
                         default=False, help='Retrieve transactions')
    cmdline.add_argument('--filename', '-f', help='write results to file. can '
                         'be {csv,json} format. default is to write to '
                         'stdout.')
    cmdline.add_argument('--keyring', action='store_true',
                         help='Use OS keyring for storing password '
                         'information')

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:
        from __builtin__ import raw_input as input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: ")

    if options.keyring:
        # If keyring option is specified, save the password in the keyring
        keyring.set_password('mintapi', email, password)

    if options.accounts_ext:
        options.accounts = True

    if not (options.accounts or options.budgets or options.transactions):
        options.accounts = True

    mint = Mint.create(email, password)

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext)
            )
        except:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(
                get_detail=options.accounts_ext)
            )
        except:
            data = None
    elif options.transactions:
        data = mint.get_transactions()

    # output the data
    if options.transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dumps(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')
from __future__ import print_function, division, absolute_import, unicode_literals
try:  from __builtin__ import bytes, str, open, super, range, zip, round, int, pow, object, input
except ImportError:  pass
try:  from __builtin__ import raw_input as input
except:  pass
from getpass import getpass
from simplebitcoinfuncs import *
from simplebitcoinfuncs.hexhashes import *
from pybip38 import bip38decrypt


print()

while True:
    userseed = input("Please enter your user seed (begins with K or L) or your master xprv key:\n")
    userseed = normalize_input(userseed).replace('\r','').replace('\n','').replace(' ','')
    try:
        if userseed[0] == 'K' or userseed[0] == 'L':
            userseed = privtohex(userseed)
            assert len(userseed) == 64
        elif userseed[:4] != 'xprv':
            raise Exception(' ')
        userkey = BIP32(userseed)
    except:
        print("\nInvalid user seed entered.\n")
    else:
        break

print("\nExcellent! Your user public key appears to be:\n" + userkey.xpub)
Beispiel #14
0
def main(argv):
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email', nargs='?', default=None,
                         help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password', nargs='?', default=None,
                         help='The password for your Mint.com account')
    cmdline.add_argument('--filename', '-f', help='write results to file. can '
                         'be {csv,json} format. default is to write to '
                         'stdout.')
    cmdline.add_argument('--keyring', action='store_true',
                         help='Use OS keyring for storing password '
                         'information')

    options = cmdline.parse_args(argv)

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    if sys.version_info[0] == 2:
        from __builtin__ import raw_input as input
    else:
        # Seems like this shouldn't be necessary, but without this
        # the interpreter was treating 'input' as a local variable
        # in its first pass and throwing UnboundLocalError when calling
        # input()
        from builtins import input

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: ")

    if options.keyring:
        # If keyring option is specified, save the password in the keyring
        keyring.set_password('mintapi', email, password)

    info('Logging in')
    mint = mintapi.Mint.create(email, password, debug=False)

    data = {}

    info('Fetching account information')
    data['accounts'] = mintapi.api.make_accounts_presentable(
            mint.get_accounts(get_detail=False)
    )

    info('Downloading all transactions')
    txn_data = mint.get_transactions_json(include_investment=True,
                                          skip_duplicates=True,
                                          start_date=None)
    data['transactions'] = txn_data

    info('Fetching historical stats')
    data['net_worth'] = mint.get_net_worth()
    data['tags'] = mint.get_tags()

    nw_trends = mint.get_trends_history('NW')
    #print('networth trends: ' + str(nw_trends))
    data['nw_trends'] = nw_trends

    fname = 'mint-backup-{ts:s}.json'.format(ts=time.strftime('%Y%m%d-%H%M%S'))
    info('Saving data to {fname:s}'.format(fname=fname))
    with open(fname, 'w+') as f:
        json.dump(data, f, indent=2)
Beispiel #15
0
def input(prompt = ''):
    print(prompt)

    return __builtin__.input(">")
	except:
		print("Failed to import Python3 module!");
		exit();

else:
	print('Unknow Python version!');
	exit();

# specify the regular expression pattern
po = re.compile(r'''
	(?x)
	^(?P<speaker>[mv]{1}):(?P<first>[mv]{1})(?P<first_class>\d{1})
	(?P<second>[mv]{1})(?P<second_class>\d{1})$	
	''');

mo1 = po.match(input());
mo2 = po.match(input());

if mo1 and mo2:
	#print(mo1.group(0));
	#print(mo2.group(0));
	# first input line, ie m:m1v0; m1-->"m1"  v1-->"v0"
	if int(mo1.group('first_class')): # if mike is a knight, then "as is"
		m1 = 1;
		v1 = int(mo1.group('second_class'));
	else: # if mike is a knave, then victor is opposite of what's given
		m1 = 0;
		if int(mo1.group('second_class')):
			v1 = 0;
		else:
			v1 = 1;
Beispiel #17
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email', nargs='?', default=None,
                         help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password', nargs='?', default=None,
                         help='The password for your Mint.com account')
    cmdline.add_argument('--accounts', action='store_true', dest='accounts',
                         default=False, help='Retrieve account information'
                         ' (default if nothing else is specified)')
    cmdline.add_argument('--budgets', action='store_true', dest='budgets',
                         default=False, help='Retrieve budget information')
    cmdline.add_argument('--net-worth', action='store_true', dest='net_worth',
                         default=False, help='Retrieve net worth information')
    cmdline.add_argument('--extended-accounts', action='store_true',
                         dest='accounts_ext', default=False,
                         help='Retrieve extended account information (slower, '
                         'implies --accounts)')
    cmdline.add_argument('--transactions', '-t', action='store_true',
                         default=False, help='Retrieve transactions')
    cmdline.add_argument('--extended-transactions', action='store_true',
                         default=False,
                         help='Retrieve transactions with extra '
                         'information and arguments')
    cmdline.add_argument('--start-date', nargs='?', default=None,
                         help='Earliest date for transactions to be '
                         'retrieved from. Used with --extended-transactions. '
                         'Format: mm/dd/yy')
    cmdline.add_argument('--include-investment', action='store_true',
                         default=False,
                         help='Used with --extended-transactions')
    cmdline.add_argument('--skip-duplicates', action='store_true',
                         default=False,
                         help='Used with --extended-transactions')
# Displayed to the user as a postive switch,
# but processed back here as a negative
    cmdline.add_argument('--show-pending', action='store_false', default=True,
                         help='Exclude pending transactions from being '
                         'retrieved. Used with --extended-transactions')
    cmdline.add_argument('--filename', '-f', help='write results to file. can '
                         'be {csv,json} format. default is to write to '
                         'stdout.')
    cmdline.add_argument('--keyring', action='store_true',
                         help='Use OS keyring for storing password '
                         'information')
    cmdline.add_argument('--wait-for-account-refresh', action='store_true',
                         default=False, help='Initiate account refresh on '
                         'Mint.com and wait for refresh to finish before '
                         'executing other commands')

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:  # python 2.x
        from __builtin__ import raw_input as input
    except ImportError:  # python 3
        from builtins import input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        try:
            password = keyring.get_password('mintapi', email)
        except:
            print("Cannot access system keyring")
            options.keyring = False

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: ")

    if options.keyring:
        # If keyring option is specified, save the password in the keyring
        keyring.set_password('mintapi', email, password)

    if options.accounts_ext:
        options.accounts = True

    if not any([options.accounts,
                options.budgets,
                options.transactions,
                options.extended_transactions,
                options.net_worth]):
        options.accounts = True

    mint = Mint.create(email, password, ius_session=options.session, thx_guid=options.thx_guid)

    if options.wait_for_account_refresh:
        mint.refresh_accounts()

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext)
            )
        except:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(
                get_detail=options.accounts_ext)
            )
        except:
            data = None
    elif options.transactions:
        data = mint.get_transactions(include_investment=options.include_investment)
    elif options.extended_transactions:
        data = mint.get_detailed_transactions(
                start_date=options.start_date,
                include_investment=options.include_investment,
                remove_pending=options.show_pending,
                skip_duplicates=options.skip_duplicates
        )
    elif options.net_worth:
        data = mint.get_net_worth()

    # output the data
    if options.transactions or options.extended_transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')
def fmap(func, obj):
    """fmap(func, obj) creates a copy of obj with func applied to its contents.
    Override by defining obj.__fmap__(func)."""
    if _coconut.hasattr(obj, "__fmap__"):
        return obj.__fmap__(func)
    if obj.__class__.__module__ == "numpy":
        from numpy import vectorize
        return vectorize(func)(obj)
    return _coconut_makedata(
        obj.__class__,
        *(_coconut_starmap(func, obj.items()) if _coconut.isinstance(
            obj, _coconut.abc.Mapping) else _coconut_map(func, obj)))


def memoize(maxsize=None, *args, **kwargs):
    """Decorator that memoizes a function,
    preventing it from being recomputed if it is called multiple times with the same arguments."""
    return _coconut.functools.lru_cache(maxsize, *args, **kwargs)


_coconut_MatchError, _coconut_count, _coconut_enumerate, _coconut_makedata, _coconut_map, _coconut_reversed, _coconut_starmap, _coconut_tee, _coconut_zip, TYPE_CHECKING, reduce, takewhile, dropwhile = MatchError, count, enumerate, makedata, map, reversed, starmap, tee, zip, False, _coconut.functools.reduce, _coconut.itertools.takewhile, _coconut.itertools.dropwhile

# Compiled Coconut: -----------------------------------------------------------

n = (int)(input())
count, divisor = 0, 5
while (n / divisor) >= 1:
    count += n // divisor
    divisor *= 5
print(count)
Beispiel #19
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email', nargs='?', default=None,
                         help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password', nargs='?', default=None,
                         help='The password for your Mint.com account')
    cmdline.add_argument('--accounts', action='store_true', dest='accounts',
                         default=False, help='Retrieve account information'
                         ' (default if nothing else is specified)')
    cmdline.add_argument('--budgets', action='store_true', dest='budgets',
                         default=False, help='Retrieve budget information')
    cmdline.add_argument('--net-worth', action='store_true', dest='net_worth',
                         default=False, help='Retrieve net worth information')
    cmdline.add_argument('--extended-accounts', action='store_true',
                         dest='accounts_ext', default=False,
                         help='Retrieve extended account information (slower, '
                         'implies --accounts)')
    cmdline.add_argument('--transactions', '-t', action='store_true',
                         default=False, help='Retrieve transactions')
    cmdline.add_argument('--filename', '-f', help='write results to file. can '
                         'be {csv,json} format. default is to write to '
                         'stdout.')
    cmdline.add_argument('--keyring', action='store_true',
                         help='Use OS keyring for storing password '
                         'information')

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:
        from __builtin__ import raw_input as input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: ")

    if options.keyring:
        # If keyring option is specified, save the password in the keyring
        keyring.set_password('mintapi', email, password)

    if options.accounts_ext:
        options.accounts = True

    if not any([options.accounts, options.budgets, options.transactions,
                options.net_worth]):
        options.accounts = True

    mint = Mint.create(email, password)

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext)
            )
        except:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(
                get_detail=options.accounts_ext)
            )
        except:
            data = None
    elif options.transactions:
        data = mint.get_transactions()
    elif options.net_worth:
        data = mint.get_net_worth()

    # output the data
    if options.transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')
    except:
        print("Failed to import Python3 module!")
        exit()

else:
    print('Unknow Python version!')
    exit()

# specify the regular expression pattern
po = re.compile(r'''
	(?x)
	^(?P<speaker>[mv]{1}):(?P<first>[mv]{1})(?P<first_class>\d{1})
	(?P<second>[mv]{1})(?P<second_class>\d{1})$	
	''')

mo1 = po.match(input())
mo2 = po.match(input())

if mo1 and mo2:
    #print(mo1.group(0));
    #print(mo2.group(0));
    # first input line, ie m:m1v0; m1-->"m1"  v1-->"v0"
    if int(mo1.group('first_class')):  # if mike is a knight, then "as is"
        m1 = 1
        v1 = int(mo1.group('second_class'))
    else:  # if mike is a knave, then victor is opposite of what's given
        m1 = 0
        if int(mo1.group('second_class')):
            v1 = 0
        else:
            v1 = 1
Beispiel #21
0
def main():
    import getpass
    import argparse

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument('email', nargs='?', default=None, help='The e-mail address for your Mint.com account')
    cmdline.add_argument('password', nargs='?', default=None, help='The password for your Mint.com account')

    options = cmdline.parse_args()

    try:  # python 2.x
        from __builtin__ import raw_input as input
    except ImportError:  # python 3
        from builtins import input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        if MINT_USER:
            email = MINT_USER
        else:
            email = input("Mint e-mail: ")

    if not password:
        # If we still don't have a password, prompt for it
        if MINT_PASS:
            password = MINT_PASS
        else:
            password = getpass.getpass("Mint password: "******"Creating mint object")
    mint = Mint.create(email, password)
    print("Refreshing mint account details")
    mint.initiate_account_refresh()
    atexit.register(mint.close)  # Ensure everything is torn down.

    try:
        print("Getting accounts data")
        data = make_accounts_presentable(mint.get_accounts(
            get_detail=False)
        )
    except Exception as e:
        print("get_accounts encountered exception: %s" % e)
        data = None

    # output the data
    findata = {}
    for dat in data:
        fintype = "%s: %s" % (dat['fiName'], dat['accountName'])
        findata[fintype] = abs(dat['value'])
    print("Retrieving robinhood portfolio")
    findata[u'Robinhood'] = get_robinhood_portfolio_value(ROBINHOOD_USER, ROBINHOOD_PASS)

    update_finances_sheet(MASTER_SHEET_ID, findata)
    mint.close()

    """ TO-DO: """
Beispiel #22
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument(
        'email',
        nargs='?',
        default=None,
        help='The e-mail address for your Mint.com account')
    cmdline.add_argument(
        'password',
        nargs='?',
        default=None,
        help='The password for your Mint.com account')

    cmdline.add_argument(
        '--accounts',
        action='store_true',
        dest='accounts',
        default=False,
        help='Retrieve account information'
        '(default if nothing else is specified)')
    cmdline.add_argument(
        '--budgets',
        action='store_true',
        dest='budgets',
        default=False,
        help='Retrieve budget information')
    cmdline.add_argument(
        '--net-worth',
        action='store_true',
        dest='net_worth',
        default=False,
        help='Retrieve net worth information')
    cmdline.add_argument(
        '--extended-accounts',
        action='store_true',
        dest='accounts_ext',
        default=False,
        help='Retrieve extended account information (slower, '
        'implies --accounts)')
    cmdline.add_argument(
        '--transactions',
        '-t',
        action='store_true',
        default=False,
        help='Retrieve transactions')
    cmdline.add_argument(
        '--extended-transactions',
        action='store_true',
        default=False,
        help='Retrieve transactions with extra information and arguments')
    cmdline.add_argument(
        '--start-date',
        nargs='?',
        default=None,
        help='Earliest date for transactions to be retrieved from. '
        'Used with --extended-transactions. Format: mm/dd/yy')
    cmdline.add_argument(
        '--include-investment',
        action='store_true',
        default=False,
        help='Used with --extended-transactions')
    cmdline.add_argument(
        '--skip-duplicates',
        action='store_true',
        default=False,
        help='Used with --extended-transactions')
    # Displayed to the user as a postive switch, but processed back
    # here as a negative
    cmdline.add_argument(
        '--show-pending',
        action='store_false',
        default=True,
        help='Exclude pending transactions from being retrieved. '
        'Used with --extended-transactions')
    cmdline.add_argument(
        '--filename', '-f',
        help='write results to file. can '
        'be {csv,json} format. default is to write to '
        'stdout.')
    cmdline.add_argument(
        '--keyring',
        action='store_true',
        help='Use OS keyring for storing password '
        'information')
    cmdline.add_argument(
        '--headless',
        action='store_true',
        help='Whether to execute chromedriver with no visible window.')
    cmdline.add_argument(
        '--mfa-method',
        default='sms',
        choices=['sms', 'email'],
        help='The MFA method to automate.')

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:  # python 2.x
        from __builtin__ import raw_input as input
    except ImportError:  # python 3
        from builtins import input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: ")

    if options.keyring:
        # If keyring option is specified, save the password in the keyring
        keyring.set_password('mintapi', email, password)

    if options.accounts_ext:
        options.accounts = True

    if not any([options.accounts, options.budgets, options.transactions,
                options.extended_transactions, options.net_worth]):
        options.accounts = True

    mint = Mint.create(email, password,
                       mfa_method=options.mfa_method,
                       headless=options.headless)
    atexit.register(mint.close)  # Ensure everything is torn down.

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext)
            )
        except:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(
                get_detail=options.accounts_ext)
            )
        except:
            data = None
    elif options.transactions:
        data = mint.get_transactions(
            include_investment=options.include_investment)
    elif options.extended_transactions:
        data = mint.get_detailed_transactions(
            start_date=options.start_date,
            include_investment=options.include_investment,
            remove_pending=options.show_pending,
            skip_duplicates=options.skip_duplicates)
    elif options.net_worth:
        data = mint.get_net_worth()

    # output the data
    if options.transactions or options.extended_transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')
Beispiel #23
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument("email", nargs="?", default=None, help="The e-mail address for your Mint.com account")
    cmdline.add_argument("password", nargs="?", default=None, help="The password for your Mint.com account")
    cmdline.add_argument(
        "--accounts",
        action="store_true",
        dest="accounts",
        default=False,
        help="Retrieve account information" " (default if nothing else is specified)",
    )
    cmdline.add_argument(
        "--budgets", action="store_true", dest="budgets", default=False, help="Retrieve budget information"
    )
    cmdline.add_argument(
        "--net-worth", action="store_true", dest="net_worth", default=False, help="Retrieve net worth information"
    )
    cmdline.add_argument(
        "--extended-accounts",
        action="store_true",
        dest="accounts_ext",
        default=False,
        help="Retrieve extended account information (slower, " "implies --accounts)",
    )
    cmdline.add_argument("--transactions", "-t", action="store_true", default=False, help="Retrieve transactions")
    cmdline.add_argument(
        "--filename", "-f", help="write results to file. can " "be {csv,json} format. default is to write to " "stdout."
    )
    cmdline.add_argument("--keyring", action="store_true", help="Use OS keyring for storing password " "information")

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error("--keyring can only be used if the `keyring` " "library is installed.")

    try:
        from __builtin__ import raw_input as input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password("mintapi", email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: "******"mintapi", email, password)

    if options.accounts_ext:
        options.accounts = True

    if not any([options.accounts, options.budgets, options.transactions, options.net_worth]):
        options.accounts = True

    mint = Mint.create(email, password)

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(mint.get_accounts(get_detail=options.accounts_ext))
        except:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except:
            budgets = None

        data = {"accounts": accounts, "budgets": budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(get_detail=options.accounts_ext))
        except:
            data = None
    elif options.transactions:
        data = mint.get_transactions()
    elif options.net_worth:
        data = mint.get_net_worth()

    # output the data
    if options.transactions:
        if options.filename is None:
            print(data.to_json(orient="records"))
        elif options.filename.endswith(".csv"):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith(".json"):
            data.to_json(options.filename, orient="records")
        else:
            raise ValueError("file extension must be either .csv or .json")
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith(".json"):
            with open(options.filename, "w+") as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError("file type must be json for non-transaction data")
Beispiel #24
0
def main():
    import getpass
    import argparse

    try:
        import keyring
    except ImportError:
        keyring = None

    # Parse command-line arguments {{{
    cmdline = argparse.ArgumentParser()
    cmdline.add_argument(
        'email',
        nargs='?',
        default=None,
        help='The e-mail address for your Mint.com account')
    cmdline.add_argument(
        'password',
        nargs='?',
        default=None,
        help='The password for your Mint.com account')

    home = os.path.expanduser("~")
    default_session_path = os.path.join(home, '.mintapi', 'session')
    cmdline.add_argument(
        '--session-path',
        nargs='?',
        default=default_session_path,
        help='Directory to save browser session, including cookies. '
        'Used to prevent repeated MFA prompts. Defaults to '
        '$HOME/.mintapi/session.  Set to None to use '
        'a temporary profile.')
    cmdline.add_argument(
        '--accounts',
        action='store_true',
        dest='accounts',
        default=False,
        help='Retrieve account information'
        '(default if nothing else is specified)')
    cmdline.add_argument(
        '--budgets',
        action='store_true',
        dest='budgets',
        default=False,
        help='Retrieve budget information')
    cmdline.add_argument(
        '--net-worth',
        action='store_true',
        dest='net_worth',
        default=False,
        help='Retrieve net worth information')
    cmdline.add_argument(
        '--credit-score',
        action='store_true',
        dest='credit_score',
        default=False,
        help='Retrieve current credit score')
    cmdline.add_argument(
        '--credit-report',
        action='store_true',
        dest='credit_report',
        default=False,
        help='Retrieve full credit report')
    cmdline.add_argument(
        '--extended-accounts',
        action='store_true',
        dest='accounts_ext',
        default=False,
        help='Retrieve extended account information (slower, '
        'implies --accounts)')
    cmdline.add_argument(
        '--transactions',
        '-t',
        action='store_true',
        default=False,
        help='Retrieve transactions')
    cmdline.add_argument(
        '--extended-transactions',
        action='store_true',
        default=False,
        help='Retrieve transactions with extra information and arguments')
    cmdline.add_argument(
        '--start-date',
        nargs='?',
        default=None,
        help='Earliest date for transactions to be retrieved from. '
        'Used with --extended-transactions. Format: mm/dd/yy')
    cmdline.add_argument(
        '--include-investment',
        action='store_true',
        default=False,
        help='Used with --extended-transactions')
    cmdline.add_argument(
        '--skip-duplicates',
        action='store_true',
        default=False,
        help='Used with --extended-transactions')
    # Displayed to the user as a postive switch, but processed back
    # here as a negative
    cmdline.add_argument(
        '--show-pending',
        action='store_false',
        default=True,
        help='Exclude pending transactions from being retrieved. '
        'Used with --extended-transactions')
    cmdline.add_argument(
        '--filename', '-f',
        help='write results to file. can '
        'be {csv,json} format. default is to write to '
        'stdout.')
    cmdline.add_argument(
        '--keyring',
        action='store_true',
        help='Use OS keyring for storing password '
        'information')
    cmdline.add_argument(
        '--headless',
        action='store_true',
        help='Whether to execute chromedriver with no visible window.')
    cmdline.add_argument(
        '--mfa-method',
        default='sms',
        choices=['sms', 'email'],
        help='The MFA method to automate.')
    cmdline.add_argument(
        '--imap-account',
        default=None,
        help='IMAP login account')
    cmdline.add_argument(
        '--imap-password',
        default=None,
        help='IMAP login password')
    cmdline.add_argument(
        '--imap-server',
        default=None,
        help='IMAP server')
    cmdline.add_argument(
        '--imap-folder',
        default="INBOX",
        help='IMAP folder')
    cmdline.add_argument(
        '--imap-test',
        action='store_true',
        help='Test imap login and retrieval.')
    cmdline.add_argument(
        '--no_wait_for_sync',
        action='store_true',
        default=False,
        help=('By default, mint api will wait for accounts to sync with the '
              'backing financial institutions. If this flag is present, do '
              'not wait for them to sync.'))

    options = cmdline.parse_args()

    if options.keyring and not keyring:
        cmdline.error('--keyring can only be used if the `keyring` '
                      'library is installed.')

    try:  # python 2.x
        from __builtin__ import raw_input as input
    except ImportError:  # python 3
        from builtins import input
    except NameError:
        pass

    # Try to get the e-mail and password from the arguments
    email = options.email
    password = options.password

    if not email:
        # If the user did not provide an e-mail, prompt for it
        email = input("Mint e-mail: ")

    if keyring and not password:
        # If the keyring module is installed and we don't yet have
        # a password, try prompting for it
        password = keyring.get_password('mintapi', email)

    if not password:
        # If we still don't have a password, prompt for it
        password = getpass.getpass("Mint password: "******"MFA CODE:", mfa_code)
        sys.exit()

    data = None
    if options.accounts and options.budgets:
        try:
            accounts = make_accounts_presentable(
                mint.get_accounts(get_detail=options.accounts_ext)
            )
        except Exception:
            accounts = None

        try:
            budgets = mint.get_budgets()
        except Exception:
            budgets = None

        data = {'accounts': accounts, 'budgets': budgets}
    elif options.budgets:
        try:
            data = mint.get_budgets()
        except Exception:
            data = None
    elif options.accounts:
        try:
            data = make_accounts_presentable(mint.get_accounts(
                get_detail=options.accounts_ext)
            )
        except Exception:
            data = None
    elif options.transactions:
        data = mint.get_transactions(
            include_investment=options.include_investment)
    elif options.extended_transactions:
        data = mint.get_detailed_transactions(
            start_date=options.start_date,
            include_investment=options.include_investment,
            remove_pending=options.show_pending,
            skip_duplicates=options.skip_duplicates)
    elif options.net_worth:
        data = mint.get_net_worth()
    elif options.credit_score:
        data = mint.get_credit_score()
    elif options.credit_report:
        data = mint.get_credit_report(details=True)

    # output the data
    if options.transactions or options.extended_transactions:
        if options.filename is None:
            print(data.to_json(orient='records'))
        elif options.filename.endswith('.csv'):
            data.to_csv(options.filename, index=False)
        elif options.filename.endswith('.json'):
            data.to_json(options.filename, orient='records')
        else:
            raise ValueError('file extension must be either .csv or .json')
    else:
        if options.filename is None:
            print(json.dumps(data, indent=2))
        elif options.filename.endswith('.json'):
            with open(options.filename, 'w+') as f:
                json.dump(data, f, indent=2)
        else:
            raise ValueError('file type must be json for non-transaction data')
Beispiel #25
0
def print_wait(n):
    print(n)
    input()