def changeFullscreen():
    # Open file
    f = open("settings.txt", "r+")
    fl = list(f)

    # Check if fullscreen is True or False
    if fl[0] == "fullscreen=True\n":
        fs = True
    elif fl[0] == "fullscreen=False\n":
        fs = False

    # Close the file
    f.close()

    # Remove the file
    remove("settings.txt")

    # Make a new file
    if system == "nt":
        execute("type NUL > settings.txt")
    elif system == "posix":
        execute("touch settings.txt")
    nf = open("settings.txt", "r+")

    # Change fullscreen
    if fs:
        nf.write("fullscreen=False\n")
    elif not fs:
        nf.write("fullscreen=True\n")

    # Close the new file
    nf.close()
Exemple #2
0
def changeFullscreen():
    # Open file
    f = open("settings.txt", "r+")
    fl = list(f)

    # Check if fullscreen is True or False
    if fl[0] == "fullscreen=True\n":
        fs = True
    elif fl[0] == "fullscreen=False\n":
        fs = False

    # Close the file
    f.close()

    # Remove the file
    remove("settings.txt")

    # Make a new file
    if system == "nt":
        execute("type NUL > settings.txt")
    elif system == "posix":
        execute("touch settings.txt")
    nf = open("settings.txt", "r+")

    # Change fullscreen
    if fs:
        nf.write("fullscreen=False\n")
    elif not fs:
        nf.write("fullscreen=True\n")

    # Close the new file
    nf.close()
def resetPass(customCommand,test=False):
	from random import sample as randomize
	from random import random
	from os.path import exists
	# Opens the Adj, Adv, and Noun files as arrays
	av = open(sys.path[0]+"/Adv").read().splitlines()
	aj = open(sys.path[0]+"/Adj").read().splitlines()
	nn = open(sys.path[0]+"/Noun").read().splitlines()
	# Just for fun, some statistics!
	totalCombos = len(av)*len(aj)*len(nn)
	combosFormatted = "{:,}".format(totalCombos)
	avLengths=[]
	for item in av:
		avLengths.append(len(item))
	ajLengths=[]
	for item in aj:
		ajLengths.append(len(item))
	nnLengths=[]
	for item in nn:
		nnLengths.append(len(item))
	from statistics import mean,median,mode
	print("-"*25+"\n"+
		  "Total adverbs: "+str(len(av))+"\n"+
		  "Total adjectives: "+str(len(aj))+"\n"+
		  "Total nouns: "+str(len(nn))+"\n"+
		  "Total possible combinations: "+combosFormatted+" (not factoring in numbers)\n"+
		  "Shortest possible passphrase length: "+str(min(avLengths)+min(ajLengths)+min(nnLengths))+"\n"+
		  "Longest possible passphrase length: "+str(max(avLengths)+max(ajLengths)+max(nnLengths)+5)+"\n"+
		  "Mean passphrase length: "+str(int(mean(avLengths)+mean(ajLengths)+mean(nnLengths)+4))+"\n"+
		  "Median passphrase length: "+str(int(median(avLengths)+median(ajLengths)+median(nnLengths))+4)+"\n"+
		  "Mode passphrase length: "+str(int(mode(avLengths)+mode(ajLengths)+mode(nnLengths))+4)+"\n"+
		  "-"*25)
	# Randomize the order of the arrays
	av = randomize(av,len(av))
	aj = randomize(aj,len(aj))
	nn = randomize(nn,len(nn))
	# Pick a random word from each randomized array
	newAdverb = av[int(random()*len(av))].capitalize()
	newAdjective = aj[int(random()*len(aj))].capitalize()
	newNoun = nn[int(random()*len(nn))].capitalize()
	# Possibly add a random number from 1 to 10,000
	if maybeNumber():
		from math import ceil
		number = str(ceil(random()*10000))
	else:
		number = ''
	# Assemble the passphrase
	newPassphrase = number+newAdverb+newAdjective+newNoun
	#################################################################### Needs attention
	print("The new passphrase will be: "+newPassphrase)
	print("Total entropy: ~"+str(int(entropy(newPassphrase))))
	if customCommand == ' {PASSPHRASE}':
		print("Password display command not found. Aborting.")
		exit()
	if not test:
		import RouterPasswording
		RouterPasswording.newPassphrase(newPassphrase)
	from os import system as execute
	execute(customCommand.replace("{password}",newPassphrase).replace("{passphrase}",newPassphrase))
Exemple #4
0
 def _raw(self):
     if self.data_split in ['train', 'val']:
         os.system('wget http://msvocds.blob.core.windows.net/coco2014/{}.zip -P {}'.format(self.split_name, self.dir_raw))
     elif self.data_split == 'test':
         os.execute('wget http://msvocds.blob.core.windows.net/coco2015/test2015.zip -P '+self.dir_raw)
     else:
         assert False, 'data_split {} not exists'.format(self.data_split)
     os.execute('unzip '+os.path.join(self.dir_raw, self.split_name+'.zip')+' -d '+self.dir_raw)
Exemple #5
0
def install_and_configure_yandex_disk():
    # installing yandex-disk
    execute(
        'echo "deb http://repo.yandex.ru/yandex-disk/deb/ stable main" '
        '| sudo tee -a /etc/apt/sources.list.d/yandex-disk.list > /dev/null '
        '&& wget http://repo.yandex.ru/yandex-disk/YANDEX-DISK-KEY.GPG -O- '
        '| sudo apt-key add - && sudo apt update '
        '&& sudo apt install -y yandex-disk')

    # setting up yandex-disk
    execute('yandex-disk setup')
Exemple #6
0
 def _raw(self):
     if self.data_split in ['train', 'val']:
         os.system(
             'wget http://images.cocodataset.org/zips/{}.zip -P {}'.format(
                 self.split_name, self.dir_raw))
     elif self.data_split == 'test':
         os.execute(
             'wget http://images.cocodataset.org/zips/test2015.zip -P ' +
             self.dir_raw)
     else:
         assert False, 'data_split {} not exists'.format(self.data_split)
     os.execute('unzip ' +
                os.path.join(self.dir_raw, self.split_name + '.zip') +
                ' -d ' + self.dir_raw)
Exemple #7
0
def relocate(timestamp):
	dateStamp = date.now()
	year = str(dateStamp.year)
	month = str(dateStamp.month)
	day = str(dateStamp.day)
	
	newDir = (archivesDirectory + year + "/" + month + "/" + day + "/" + timestamp + "/")
	
	dir = dirname(newDir)
	
	if not exists(dir):
		mkdir(dir)
	
	src = cwd + "*"
	dst = newDir
	copy = 'cp -R ' + src + ' ' + dst
	execute(copy)
Exemple #8
0
def startBackup():
    print(now + '- Backup is starting!')
    ### insert backup info:
    insert_backup_name = input(
        'Insert database name where you want to backup: ')
    backup_name = print(insert_backup_name + '.sql')
    insert_backup_dir = input(
        'Insert path to directory where you want to save backup: /tmp/...')
    backup_dir = print('/tmp/' + insert_backup_dir)

    ## backup info:
    backup_create_dir("mkdir" + backup_dir)
    backup_mysqldump = "mysqldump '" + backup_name + "'  > '" + backup_dir + "''" + backup_name + "'"
    os.system(backup_create_dir)
    os.execute(backup_cmd)

    ### backup/archive variables:
    archieve_name = backup_name
    backup_path = backup_dir + backup_name
    archieve_path = backup_dir + archieve_name

    ### backuping/archiving:
    print(now + ' - Creating archive for ' + backup_name)
    ## shutil copying and removal functions
    shutil.make_archive(archieve_path, 'gztar', backup_dir)
    print(now + ' - Completed archiving database')
    full_archive_file_path = archieve_path + ".tar.gz"
    full_archive_name = archieve_name + ".tar.gz"

    ### Connect to S3
    s3 = S3Connection(aws_access_key, aws_secret_access_key)
    bucket_name = s3.get_bucket(aws_bucket_name)

    ### Upload backup to S3
    print(now + '- Uploading file archive ' + full_archive_name + '...')
    s3_bucket = Key(bucket_name)
    s3_bucket.key = aws_folder_name + full_archive_name
    print(s3_bucket.key)
    s3_bucket.set_contents_from_filename(full_archive_file_path)
    s3_bucket.set_acl("public-read")

    print(now + '- Clearing previous archives ' + full_archive_name + '...')
    shutil.rmtree(backup_dir)
    print(now + '- Removed backup of local database')
    print(now + '- Backup job is done')
Exemple #9
0
def ssl_fingerprint(ip):
    spacer = "============================================="
    print spacer
    x = execute("openssl x509 -fingerprint -in {0}.pem -pubkey -noout".format(ip)).read()
    nn = "[{0}.pem]: {1}".format(ip,x)
    r = redis.StrictRedis(host='localhost', port=6379, db=0)
    r.set(name=ip,value=x)
    print nn
    print spacer
Exemple #10
0
def relocate(timestamp):
    dateStamp = date.now()
    year = str(dateStamp.year)
    month = str(dateStamp.month)
    day = str(dateStamp.day)

    newDir = (archivesDirectory + year + "/" + month + "/" + day + "/" +
              timestamp + "/")

    dir = dirname(newDir)

    if not exists(dir):
        mkdir(dir)

    src = cwd + "*"
    dst = newDir
    copy = 'cp -R ' + src + ' ' + dst
    execute(copy)
Exemple #11
0
def install_and_configure_git():
    execute('sudo apt install git')

    username = input(
        'username (leave empty for default value): ') or 'yalexaner'
    email = input('email (leave empty for default value): '
                  ) or '*****@*****.**'

    execute(f'git config --global user.name {username}')
    execute(f'git config --global user.email {email}')
    execute('git config --global user.editor vim')
Exemple #12
0
def download_file(tracks, storage):
    original_path = storage
    for track in tracks:
        if track[0] == "#":
            track = track.replace("#", "")
            comment_text = f"[{c.MAGENTA}#{c.WHITE}] ~> {c.MAGENTA}{track}{c.WHITE}"
            print(comment_text)
        elif track[0] == "[":
            track = track.replace("[", "")
            track = track.replace("]", "")
            playlist_text = f"[{c.YELLOW}*{c.WHITE}] >>> {c.YELLOW}{track}{c.WHITE}"
            storage = original_path + track
            print(playlist_text)
            if path.exists(storage) is False:
                execute(f"mkdir {storage}")
        else:
            download_track = f"[{c.GREEN}+{c.WHITE}] Downloading: {c.GREEN}{track}{c.WHITE}"
            command = f"cd {storage} && youtube-dl -qx --audio-format mp3 {track}"
            execute(command)
Exemple #13
0
def getMPremote():
	url = MPURL
	mpconf = getMPconf()
	gpu = getGPU()
	s = string.Template(MPURL)
	mpurl = s.substitute(U=mpconf["user"],W=mpconf["worker"],G=gpu)
	print("Requesting URL %s" %mpurl)
	print(getURL(mpurl))
	try:
		data = json.loads(getURL(mpurl))
	except:
		print("ERROR: Cannot decode the magicpool json response")
		sys.exit(1)
	if 'ERROR' in data:
		print("ERROR: Some error in magicpool web server")
		sys.exit(1)
	if 'REBOOT' in data:
		os.execute("sudo reboot")
		sys.exit(2)
	return data
Exemple #14
0
def privcheck():
    x = execute("whoami").read()
    if "root" in x:
        pass
    if "root" not in x:
        print "Run as root"
        z = raw_input("Run Data Analytics: [Y/N]")
        if "Yy" in z:
            pass
        if "Nn" in z:
            Exit()
Exemple #15
0
def privcheck():
    x = execute("whoami").read()
    if "root" in x:
        pass
    if "root" not in x:
        print "Run as root"
        z = raw_input("Run Data Analytics: [Y/N]")
        if "Yy" in z:
            pass
        if "Nn" in z:
            Exit()
async def backup(_, message: Message):
    if message.chat.type != "private":
        return await message.reply("This command can only be used in private")

    m = await message.reply("Backing up data...")

    code = execute(f'mongodump --uri "{MONGO_URL}"')
    if int(code) != 0:
        return await m.edit(
            "Looks like you don't have mongo-database-tools installed " +
            "grab it from mongodb.com/try/download/database-tools")

    code = execute("zip backup.zip -r9 dump/*")
    if int(code) != 0:
        return await m.edit(
            "Looks like you don't have `zip` package installed, BACKUP FAILED!"
        )

    await message.reply_document("backup.zip")
    await m.delete()
    remove("backup.zip")
Exemple #17
0
def Zmaptcpscan(output, port, ip=0, count=0):
    if count > 0 and ip == 0:
        privcheck()
        x = execute(
            "sudo {0} -M tcp_synscan -N {1} -p {2} -O json -o {3}.json --output-filter='success = 1 && repeat = 0' -f saddr,success"
            .format(prefix, count, port, output)).read()
        return x
    if count > 0 and ip > 0:
        privcheck()
        x = execute(
            "sudo {0} -M tcp_synscan -N {1} -p {2} {3} -O json -o {4}.json".
            format(prefix, count, port, ip, output)).read()
        return x
    if ip > 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan {1} -p {2} -O json -o -".format(
            prefix, ip, port)).read()
        return x
    if ip == 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan -p {1}".format(prefix,
                                                            port)).read()
        return x
Exemple #18
0
def Zmaptcpscan(output,port,ip=0,count=0):
    if count > 0 and ip == 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan -N {1} -p {2} -O json -o {3}.json --output-filter='success = 1 && repeat = 0' -f saddr,success".format(prefix,
                                                                                       count,
                                                                                       port,
                                                                                       output)).read()
        return x
    if count > 0 and ip > 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan -N {1} -p {2} {3} -O json -o {4}.json".format(prefix,
                                                                                           count,
                                                                                           port,
                                                                                           ip,
                                                                                           output)).read()
        return x
    if ip > 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan {1} -p {2} -O json -o -".format(prefix, ip, port)).read()
        return x
    if ip == 0:
        privcheck()
        x = execute("sudo {0} -M tcp_synscan -p {1}".format(prefix,port)).read()
        return x
Exemple #19
0
def ssh_check(ip):
    try:
        r = redis.StrictRedis(host='localhost', port=6379, db=0)
        import GIS
        GIS.GIS(ip)
        x = execute("ssh-keyscan {0}".format(ip)).read()
        r.set(name=ip, value=x)
        print x
        return x
    except KeyboardInterrupt:
        z = raw_input("Quit Scan [Y/N]: ")
        if "Yy" in z:
            Exit() and exit()
        if "Nn" in z:
            pass
Exemple #20
0
def ssh_check(ip):
    try:
        r = redis.StrictRedis(host='localhost', port=6379, db=0)
        import GIS
        GIS.GIS(ip)
        x = execute("ssh-keyscan {0}".format(ip)).read()
        r.set(name=ip,value=x)
        print x
        return x
    except KeyboardInterrupt:
        z = raw_input("Quit Scan [Y/N]: ")
        if "Yy" in z:
            Exit() and exit()
        if "Nn" in z:
            pass
Exemple #21
0
def install_applications():
    # Vivaldi
    execute(
        'wget "https://downloads.vivaldi.com/stable/vivaldi-stable_3.3.2022.45-1_amd64.deb" -O /tmp/vivaldi.deb '
        '&& sudo dpkg -i /tmp/vivaldi.deb')

    # Stremio
    execute(
        'wget "https://dl.strem.io/shell-linux/v4.4.116/stremio_4.4.116-1_amd64.deb" -O /tmp/stremio.deb '
        '&& sudo dpkg -i /tmp/stremio.deb')

    # VK Messenger
    execute(
        'wget "https://desktop.userapi.com/get_last?platform=linux64&branch=master&packet=deb" -O /tmp/vk.deb '
        '&& sudo dpkg -i /tmp/vk.deb')

    # apts: Spotify, Telegram, Zeal, mpv, GParted, Vim, Vim GTK (for external clipboard)
    execute(
        'sudo apt install spotify-client telegram-desktop zeal mpv gparted vim vim-gtk'
    )
Exemple #22
0
    def execute_commad(self):
        try:
            actions = ["pull", "push"]
            if not self.options["action"]:
                raise ValueError('can not be empty', 'action')
            if self.options["action"] not in actions:
                raise ValueError('can only be `push` or `pull`',
                                 '--action/ -a')
            # if self.options["action"] == "push" and not self.options["branch"]:
            #     raise ValueError('please enter branch name to do the `push`', '--branch/ -b')

            if not self.options["commit"] or self.options["commit"] == "auto":
                random_string = ''.join(
                    random.choice(string.lowercase) for i in range(10))
                request = urllib2.Request("http://www.whatthecommit.com/?r=" +
                                          random_string)
                response = urllib2.urlopen(request)
                html = response.read()

                html_parser = ResponseParser()
                html_parser.feed(html)
                html_parser.close()
                self.options["commit"] = html_parser.data[0].replace("\n", "")

            # repo = "https://%s:%[email protected]" % (USERNAME, PASSWORD)
            repo = "https://%s:%[email protected]/%s/Hellrazor.js.git/" % (
                USERNAME, PASSWORD, USERNAME)

            if self.options["action"] == "push":
                execute("git add .")
                execute("git commit -m '%s'" % (self.options["commit"], ))
                execute("git %s --repo %s" % (self.options["action"], repo))
            elif self.options["action"] == "pull":
                execute("git %s %s %s" %
                        (self.options["action"], self.options["branch"], repo))
        except ValueError as e:
            print(e[1] + ": " + e[0])
Exemple #23
0
def open_workbook_file(filename: str, window=None):
    """
    Função que abre o arquivo passado com o programa padrão definido no
    sistema operacional.

    Arguments:
        filename (str): caminho absoluto para o arquivo ou apenas nome,
                        caso o arquivo esteja na raiz do projeto
    """
    from platform import system as system_name
    from os import system as execute

    print('Abrindo arquivo...')
    window_updater.update(window)

    if system_name() == 'Linux':
        execute(f'xdg-open "{filename}"')

    elif system_name() == 'Windows':
        execute(f'powershell start "{filename}"')

    elif system_name() == 'Darwin':
        execute(f'open "{filename}"')
Exemple #24
0
def Zmaplistprobes():
    x = execute("{0} --list-probe-modules".format(prefix)).read()
    return x
			if opts.sub_filename is None:
				submit_file = open('%s/lalinference_mcmc_%d.sub' % (os.getcwd(), cid),'w')
			else: 
				submit_file = open(opts.sub_filename,'w')

			submit_str ="""
universe = parallel
environment=CONDOR_MPI_PATH=/usr/lib64/openmpi
getenv = True
executable = /archive/home/vivien/condor_mpirun
arguments = --verbose --stdout cluster$(CLUSTER).proc$(PROCESS).mpiout --stderr cluster$(CLUSTER).proc$(PROCESS).mpierr /archive/home/vivien/master/bin/lalinference_mcmc -- %s
machine_count = 8
log = cluster$(CLUSTER).proc$(PROCESS).log
output = cluster$(CLUSTER).proc$(PROCESS).subproc$(NODE).out
error = cluster$(CLUSTER).proc$(PROCESS).subproc$(NODE).err
notification = Always
on_exit_remove = (ExitBySignal == True) || (ExitCode != 143)
rank = (40 - (2.0 * TotalCondorLoadAvg))
queue
""" % command
			submit_file.write(submit_str)

		elif opts.nest:
			# TODO: Make submit file for lalapps_nest_pipe
			command = 'lalapps_nest_pipe --coinc-triggers %s --run-path %s --ini-file %s --condor-submit --ignore-science-mode --coherence-test' % (arg, os.getcwd(), opts.nest_ini_file)
			retcode = os.execute(command)
			if retcode != 0:
				sys.exit("Failed to call lalapps_nest_pipe, check arguments.")

Exemple #26
0
def Zmaplistoutput():
    x = execute("{0} --list-output-modules".format(prefix)).read()
    return x
Exemple #27
0
def clear():
    if osname() == "Windows":
        execute("cls")
    else:
        execute("clear")
Exemple #28
0
def Zmaplistprobes():
    x = execute("{0} --list-probe-modules".format(prefix)).read()
    return x
 def view(self, diagram_files):
     for f in diagram_files:
         execute(f.name)
Exemple #30
0
def Zmaplistoutput():
    x = execute("{0} --list-output-modules".format(prefix)).read()
    return x
Exemple #31
0
            if (err.error.is_path() and
                    err.error.get_path().error.is_insufficient_space()):
                sys.exit("ERROR: Cannot back up; insufficient space.")
            elif err.user_message_text:
                print(err.user_message_text)
                sys.exit()
            else:
                print(err)
                sys.exit()

if __name__ == '__main__':
    # Check for an access token
    if (len(TOKEN) == 0):
        sys.exit("ERROR: Looks like you didn't add your access token. Open up backup-and-restore-example.py in a text editor and paste in your token in line 14.")
    
    os.execute("7z a /home/haynes/vmware-tools-distrib "+LOCALFILE);
    
    # Create an instance of a Dropbox class, which can make requests to the API.
    print("Creating a Dropbox object...")
    dbx = dropbox.Dropbox(TOKEN)

    # Check that the access token is valid
    try:
        dbx.users_get_current_account()
    except AuthError as err:
        sys.exit("ERROR: Invalid access token; try re-generating an access token from the app console on the web.")
    
    backup();
    
    os.execute("pause");
Exemple #32
0
def call_neo4j(network):
    os.execute(f"python neo4j_loader_and_queries/main.py {network}")
Exemple #33
0
import os


def call_neo4j(network):
    os.execute(f"python neo4j_loader_and_queries/main.py {network}")


# choose network to generate
argument = "glucose"
if argument == "glucose":
    # glucose network
    os.execute("mod -f main/main.py")
    call_neo4j(network="glucose")
elif argument == "radicals":
    # radicals network
    os.execute("mod -f radicals/all7/all7.py")
            if opts.sub_filename is None:
                submit_file = open(
                    '%s/lalinference_mcmc_%d.sub' % (os.getcwd(), cid), 'w')
            else:
                submit_file = open(opts.sub_filename, 'w')

            submit_str = """
universe = parallel
environment=CONDOR_MPI_PATH=/usr/lib64/openmpi
getenv = True
executable = /archive/home/vivien/condor_mpirun
arguments = --verbose --stdout cluster$(CLUSTER).proc$(PROCESS).mpiout --stderr cluster$(CLUSTER).proc$(PROCESS).mpierr /archive/home/vivien/master/bin/lalinference_mcmc -- %s
machine_count = 8
log = cluster$(CLUSTER).proc$(PROCESS).log
output = cluster$(CLUSTER).proc$(PROCESS).subproc$(NODE).out
error = cluster$(CLUSTER).proc$(PROCESS).subproc$(NODE).err
notification = Always
on_exit_remove = (ExitBySignal == True) || (ExitCode != 143)
rank = (40 - (2.0 * TotalCondorLoadAvg))
queue
""" % command
            submit_file.write(submit_str)

        elif opts.nest:
            # TODO: Make submit file for lalapps_nest_pipe
            command = 'lalapps_nest_pipe --coinc-triggers %s --run-path %s --ini-file %s --condor-submit --ignore-science-mode --coherence-test' % (
                arg, os.getcwd(), opts.nest_ini_file)
            retcode = os.execute(command)
            if retcode != 0:
                sys.exit("Failed to call lalapps_nest_pipe, check arguments.")