예제 #1
0
def get_hosts(ssh_config_file, c, argu=0):
    myfunc = sys._getframe().f_code.co_name
    logging.info("Calling function: " + myfunc)
    hosts = []
    if argu:
        return [c['host']]
    else:
        with open(ssh_config_file, 'r') as f:
            lines = filter(None, (line.rstrip() for line in f))
            for line in lines:
                if not line.startswith(";") and 'HostName' in line:
                    results = collections.Counter(line)
                    if results['='] <= 1:
                        (key, val) = line.split("=")
                        key = key.lstrip()
                        val = val.lstrip()
                        val = val.replace('"', '')
                        if 'HostName' in key:
                            if key.startswith("HostName"):
                                hosts.append(val)
        if hosts:
            #print 'hosts:', hosts
            logging.debug(hosts)
        else:
            logging.error("ERROR no host found")
            #print 'ERROR no host found'

            sys(exit())

        return hosts
예제 #2
0
def main(argv):
    run_once = False
    try:
        opts, args = getopt.getopt(argv, "horc",
                                   ["help", "once", "reset", "clear"])
    except:
        print("youtube2peertube.py [-o|--once]")
        sys(exit(2))

    for opt, arg in opts:
        if opt == '-h':
            print("youtube2peertube.py [-o|--once] [-r|--reset] [-c|--clear]")
            print(
                "reset will reset channels_timestamps.csv and force videos to be rechecked"
            )
            print(
                "clear will clear videos.log.csv so nothing will marked duplicate"
            )
            sys.exit()
        elif opt in ("-o", "--once"):
            run_once = True
        elif opt in ("-r", "--reset"):
            file = open("channels_timestamps.csv", "r+")
            file.truncate(0)
            file.close()
        elif opt in ("-R", "--Reset"):
            file = open("videos.log.csv", "r+")
            file.truncate(0)
            file.close()
    run(run_once)
예제 #3
0
def main():
	try:
		opList, args = getopt.getopt(sys.argv[1:], 'hn:v', ["help", "numdirs="]);
	except	getopt.GetoptError, err:
		print sys(err)
		usage()
		sys.exit(2)
예제 #4
0
def get_hosts_from_config(config_file, c, argu=0):
    myfunc = sys._getframe().f_code.co_name
    logging.info("Calling function: " + myfunc)
    hosts = []
    if argu:
        return [c['host']]
    else:
        #with open(ssh_config_file, 'r') as f:
        f = open(config_file, 'r')
        try:
            lines = filter(None, (line.rstrip() for line in f))
            for line in lines:
                if 'host' in line:
                    # results = collections.Counter(line)
                    # p results
                    #if results['='] <= 1:
                    #print 'results count: ', line.count('=')
                    if line.count('=') <= 1:
                        (key, val) = line.split("=")
                        key = key.lstrip()
                        val = val.lstrip()
                        if 'host' in key:
                            if key.startswith("host"):
                                hosts.append(val)
            if hosts:
                #print 'hosts:', hosts
                logging.debug(hosts)
            else:
                logging.error("ERROR no host found")
                #print 'ERROR no host found'
                sys(exit())
            return hosts
        finally:
            f.close()
예제 #5
0
    def __init__(self, inputArgs):
        self.feachStatusList = []
        self.assessmentTemplateID = inputArgs.assessmentTemplateID
        self.assessmentRegion = inputArgs.assessmentRegion if inputArgs.assessmentRegion else None
        self.assessmentCloudAccountType = inputArgs.assessmentCloudAccountType if inputArgs.assessmentCloudAccountType else None
        self.externalAccountNumber = inputArgs.externalAccountNumber if inputArgs.externalAccountNumber else None
        self.cloudAccountID = inputArgs.cloudAccountID if inputArgs.cloudAccountID else None

        if not self.cloudAccountID and not self.externalAccountNumber:
            sys("You must use on os the following: --cloudAccountId or --externalAccountNumber"
                )

        self.d9client = Dome9ApiClient(apiKeyID=inputArgs.apiKeyID,
                                       apiSecret=inputArgs.secretKey)

        if self.externalAccountNumber:
            self.accountId = self.d9client.getCloudAccountID(
                self.externalAccountNumber)['id']
            self.assessmentCloudAccountType = "AWS"
        if self.cloudAccountID:
            self.accountId = self.cloudAccountID
            if not self.assessmentCloudAccountType:
                sys.exit(
                    "cloudAccountID require using: --assessmentCloudAccountType"
                )
예제 #6
0
 def destroy_rds_instances(self):
     try:
         conn.delete_db_instance(
             DBInstanceIdentifier=self.db_instance_identifier,
             SkipFinalSnapshot=True)
     except botocore.exceptions.ClientError as err:
         print err
         sys(1)
 def instance_variables_without_at_sign(self):
     """
     Instance variables without an at sign
     :return:
     """
     if self.debug:
         print('instance_variables_without_at_sign' + lineno())
     # FIXME
     sys(exit)
예제 #8
0
def init_spotify_client():
    try:
        print('Initialising Spotify Client....')
        token = util.prompt_for_user_token(SPOTIFY_USERNAME, SCOPE,
                                           client_id=CLIENT_ID,
                                           client_secret=CLIENT_SECRET,
                                           redirect_uri='http://localhost/')
        spotify_client = spotipy.Spotify(auth=token)
        print('\nClient initialised!\n')
        return spotify_client
    except:
        sys('\nError initialising Spotify Client!\n')
예제 #9
0
def detachInstancefromELB(instance):
    try:
        print("Detaching Instance: " + attachedInstances[0] + "from ELB")
        detach = client.deregister_instances_from_load_balancer(
            LoadBalancerName=elbName, Instances=[
                {
                    'InstanceId': instance
                },
            ])
    except ValueError as err:
        print(err.args)
        sys(exit(1))
    print(detach)
예제 #10
0
 def read_write_binlog_file(self, start_time):
     try:
         rds = self.get_rds_db_conn()
         rds_cursor = rds.cursor()
         bin_log_files = rds_cursor.execute("SHOW BINARY LOGS")
         bin_log_files = bin_log_files.fetchall()[0]
         start_file = bin_log_files["Log_name"]
         rds_cursor.close()
         rds.close()
     except _mysql_exceptions, err:
         print(err)
         rds_cursor.close()
         rds.close()
         sys(1)
 def input_check(self, StationFrom, StationTo):
     
     if  not (StationFrom in self.G.nodes):
         print("First input is incorrect. Check for spelling and try again. \n\nProgram will exit now.")
         sys(exit)
         
     elif not (StationTo in self.G.nodes):
         print("Second input is incorrect. Check for spelling and try again. \n\nProgram will exit now.")
         sys.exit()
     
     else:
         print("Inputs found. \nProceeding to plot your shortest recommended path from " + StationFrom + " to " + StationTo + ".")
         
     return
예제 #12
0
def get_params(config_file, argu=0):
    myfunc = sys._getframe().f_code.co_name
    logging.info("Calling function: " + myfunc)
    # hardcoded default values
    params = {#'host': '',
              'email': '',
              'timeout': '',
              'sendPacket': '',
              'receivePacket': '',
              'port': '',
              'ssh_client_path': '',
              }
    #with open(config_file, 'r') as f:
    f = open(config_file, 'r')
    try:
        lines = filter(None, (line.rstrip() for line in f))
        for line in lines:
            if not line.startswith("#") and '=' in line:
                #results = collections.Counter(line)
                #if results['='] <= 1:
                if line.count('=') <= 1:
                    (key, val) = line.split("=")
                    if val and params.has_key(key):
                        params[key] = val
                    if 'timeout' in key:
                        if key.startswith("timeout"):
                            params['timeout'] = int(val)
                    if 'ssh_client_path' in key:
                        if key.startswith("ssh_client_path"):
                            params['ssh_client_path'] = val
    finally:
        f.close()

    if params.values():
        #print 'Configurations:'
        #print '==============='
        logging.info('Configurations:')
        logging.info('===============')
        for k, v in params.items():
            # Display key and value.
            #print k, '=', v
            logging.info(str(k) + "=" + str(v))
        logging.debug(params)
        return params
    else:
        print 'ERROR Missing Configuration', params
        logging.error("ERROR Missing Configuration")
        logging.error(params)
        sys(exit())
def main(argv):
    run_once = False
    try:
        opts, args = getopt.getopt(argv, "ho", ["help", "once"])
    except:
        print("youtube2peertube.py [-o|--once]")
        sys(exit(2))

    for opt, arg in opts:
        if opt == '-h':
            print("youtube2peertube.py [-o|--once]")
            sys.exit()
        elif opt in ("-o", "--once"):
            run_once = True

    run(run_once)
예제 #14
0
 def __call__(self):
     """
     Call each callable subsystem in turn and concatenate the results.
     """
     call_iter = it.ifilter(callable, self._subsystems)
     return tuple(
              it.chain.from_iterable(
                sys() for sys in call_iter))
    def input_check(self):

        self.allKeys_P = {}
        self.allKeys_R = {}

        self.allKeys_R = self.create_allKeys(self.ListofDict_R)
        self.allKeys_P = self.create_allKeys(self.ListofDict_P)

        if not (self.allKeys_R == self.allKeys_P):

            print(
                "Input entered is incorrect. Please re-enter data.\nProgram will exit now."
            )
            sys(exit)

        else:

            print("Input entered has been parsed, loading your input now.")
예제 #16
0
def main():
    ADDRESS, PORT, CONNECTIONS = parse_comm_line()
    database = ServerDatabase()
    server_main = Server(ADDRESS, PORT, CONNECTIONS, database)
    server_main.daemon = True
    server_main.start()
    server_app = QApplication(sys.argv)
    main_window = MyWindow()
    main_window.show()
    main_window.statusBar().showMessage('Server working')
    main_window.tableView.setModel(main_window.gui_create_model(database))
    main_window.tableView.resizeColumnsToContents()
    main_window.tableView.resizeRowsToContents()

    def list_update():
        global new_connection
        if new_connection:
            main_window.tableView.setModel(
                main_window.gui_create_model(database))
            main_window.tableView.resizeColumnsToContents()
            main_window.tableView.resizeRowsToContents()
            with conflag_lock:
                new_connection = False

    def show_statistics():
        global stat_window
        stat_window = HistoryWindow()
        stat_window.history_table.setModel(
            stat_window.create_stat_model(database))
        stat_window.history_table.resizeColumnsToContents()
        stat_window.history_table.resizeRowsToContents()
        stat_window.show()

    timer = QTimer()
    timer.timeout.connect(list_update)
    timer.start(1000)
    main_window.refresh_list.triggered.connect(list_update)
    main_window.history_list.triggered.connect(show_statistics)
    sys(server_app.exec_())

    def show_statistics():
        global stat_window
        config_window = ConfigWindow()
예제 #17
0
def mainmenu():
    while True:
        os.system('cls')
        menu = """What du you want to do?

1) Convert digital to binary
2) Convert binary to digital
3) Credits
4) Exit

pick choice [1-4] : """
        choice = raw_input(menu)
        if choice == "1":
            digitalToBinary()
        if choice == "2":
            binaryToDigital()
        if choice == "3":
            credit()
        if choice == "4":
            sys(exit)
예제 #18
0
def main():
    try:
        file_name = open(get_file(),'r')
    except FileNotFoundError:
        print("File is not found in the current directory")
        print(os.listdir())
        sys(exit(0))
        
    input_lines_list = load_test_cases(file_name)

    if len(input_lines_list) == 0:
        print("File is empty, exiting.")
        sys(exit(0))

    for input_line in input_lines_list:
         customer_list, product_list = parse_input_line(input_line)
         customer_product_entries, total_suitability_score = SuitabilityScore.get_suitability_score(customer_list,product_list)
         print_entries(customer_product_entries,total_suitability_score)

    file_name.close()
예제 #19
0
def getattr(attr):
    ''' get "attr" from the topmost object '''
    return [
        put(0x80),
        # sys.modules['sys'] = obj
        get(0),
        pstr('sys'),
        get(0x80),
        SETITEM,
        sys(attr)
    ]
예제 #20
0
 def install(self):
   while True:
     system=sys()
     os.system("clear")
     logo.ins_tnc()
     inp=input("\033[1;33m Do you want to install Tool-X [Y/n]> \033[00m")
     if inp=="y" or inp=="Y":
       os.system("clear")
       logo.installing()
       if system.sudo is not None:
         #require root permission
         if os.path.exists(system.conf_dir+"/Tool-X"):
           pass
         else:
           os.system(system.sudo+" mkdir "+system.conf_dir+"/Tool-X")
         os.system(system.sudo+" cp -r modules core Tool-X.py "+system.conf_dir+"/Tool-X")
         os.system(system.sudo+" cp -r core/Tool-X "+system.bin)
         os.system(system.sudo+" cp -r core/toolx "+system.bin)
         os.system(system.sudo+" chmod +x "+system.bin+"/Tool-X")
         os.system(system.sudo+" chmod +x "+system.bin+"/toolx")
         os.system("cd .. && "+system.sudo+" rm -rf Tool-X")
         if os.path.exists(system.bin+"/Tool-X") and os.path.exists(system.conf_dir+"/Tool-X"):
           os.system("clear")
           logo.ins_sc()
           tmp=input("\033[1;36m ##> \033[00m")
           break
         else:
           os.system("clear")
           logo.not_ins()
           tmp=input("\033[1;36m ##> \033[00m")
           break
       else:
         if os.path.exists(system.conf_dir+"/Tool-X"):
           pass
         else:
           os.system("mkdir "+system.conf_dir+"/Tool-X")
         os.system("cp -r modules core Tool-X.py "+system.conf_dir+"/Tool-X")
         os.system("cp -r core/Tool-X "+system.bin)
         os.system("cp -r core/toolx "+system.bin)
         os.system("chmod +x "+system.bin+"/Tool-X")
         os.system("chmod +x "+system.bin+"/toolx")
         os.system("cd .. && rm -rf Tool-X")
         if os.path.exists(system.bin+"/Tool-X") and os.path.exists(system.conf_dir+"/Tool-X"):
           os.system("clear")
           logo.ins_sc()
           tmp=input("\033[1;36m ##> \033[00m")
           break
         else:
           os.system("clear")
           logo.not_ins()
           tmp=input("\033[1;36m ##> \033[00m")
           break
     else:
       break
예제 #21
0
def main():
    try:
        file_name = open(get_file(), 'r')
    except FileNotFoundError:
        print("File is not found in the current directory")
        print(os.listdir())
        sys(exit(0))

    input_lines_list = load_test_cases(file_name)

    if len(input_lines_list) == 0:
        print("File is empty, exiting.")
        sys(exit(0))

    for input_line in input_lines_list:
        customer_list, product_list = parse_input_line(input_line)
        customer_product_entries, total_suitability_score = SuitabilityScore.get_suitability_score(
            customer_list, product_list)
        print_entries(customer_product_entries, total_suitability_score)

    file_name.close()
예제 #22
0
def attachInstancetoELB(instance):
    time.sleep(5)
    print("Attaching Instance: " + attachedInstances[0] + "to ELB")
    try:
        attach = client.register_instances_with_load_balancer(
            LoadBalancerName=elbName, Instances=[
                {
                    'InstanceId': instance
                },
            ])
    except ValueError as err:
        print(err.args)
        sys(exit(1))
    healthy = client.describe_instance_health(LoadBalancerName=elbName, )
    # print(healthy)
    for status in healthy['InstanceStates']:
        print("InstanceId : " + status['InstanceId'] + " " + "State : " +
              status['State'])
        while (status['State'] != 'InService'):
            print("waiting for instance")

    print(attach)
예제 #23
0
def get_MySQL(url, mount=True):
	sys('wget ', url)
	MOUNT_POINT = "hdiutil attach -noautoopen " +
	"'/mysql-5.7.15-osx10.11-x86_64.dmg' | egrep 'Volumes' " +
	"| grep -o '/Volumes/.*'"
	if mount==True:
		sys(MOUNT_POINT)
	else:
		sys("hdiutil detach ", MOUNT_POINT)
예제 #24
0
def run(data):
	filename,content,command = data[0],data[1],data[2]
	command = command.replace('[space]',' ')
	try:
		cont = binascii.b2a_hex(open(content).read())
	except:
		from core import start
		sys.exit(color.color('red')+'Error, Cannot find/open the file %s'%(content)+color.color('reset'))
	l = len(cont) -1
	n = 0
	c = '\\x'
	for word in cont:
		c += word
		n+=1
		if n is 2:
			n = 0
			c += '\\x'
	c = c[:-2]
	command = 'echo -e "%s" > %s ; chmod 777 %s ; %s'%(str(c),str(filename),str(filename),str(command))
	return sys(stack.generate(command.replace('[space]',' '),'%ecx','string'))
예제 #25
0
def run(data):
    filename, content, command = data[0], data[1], data[2]
    command = command.replace('[space]', ' ')
    try:
        cont = binascii.b2a_hex(open(content).read())
    except:
        from core import start
        sys.exit(
            color.color('red') + 'Error, Cannot find/open the file %s' %
            (content) + color.color('reset'))
    l = len(cont) - 1
    n = 0
    c = '\\x'
    for word in cont:
        c += word
        n += 1
        if n is 2:
            n = 0
            c += '\\x'
    c = c[:-2]
    command = 'echo -e "%s" > %s ; chmod 777 %s ; %s' % (
        str(c), str(filename), str(filename), str(command))
    return sys(
        stack.generate(command.replace('[space]', ' '), '%ecx', 'string'))
예제 #26
0
def main(t):
    now = datetime.utcnow()
    mainsys = sys('status')
    if mainsys[0] == 'failed' and t=='start' :
        print time.strftime('%H:%M:%S') + ' GAME SERVER IS UNREACHABLE NOW'
        ss = ( 30 - (now.minute %30 )) *60 - now.second
    elif mainsys[0] == 'failed' and t=='loop' :
        ss = ( 30 - (now.minute %30 )) *60 - now.second
    elif mainsys[0] == 'closed':
        sysTime = sys('time')
        sysOpenTime = localtime(sysTime[1])
        print time.strftime('%H:%M:%S') + ' REGULAR MAINTENANCE TILL ' + datetime.strftime(sysOpenTime,'%H:%M')
        ss = ( 30 - (now.minute %30 )) *60 - now.second
    elif mainsys[0] == 'closing':
        sysTime = sys('time')
        sysCloseTime = localtime(sysTime[0])
        print time.strftime('%H:%M:%S') + ' REGULAR MAINTENANCE WILL START AT ' + time.strftime(sysCloseTime,'%H:%M')
        ss = now.minute *60 - now.second
    elif mainsys[0] == 'normal':
        mainpre = pre()
        if mainpre:
            preData = mainpre[1]
            preTime = preData[0]
            prePrint = ['pre',preData]
            if t == 'loop':
                soundalert()
            questcheck(prePrint,'get')
            ssInt = ( preTime.hour - now.hour)*3600 - (preTime.minute + now.minute) * 60 - now.second
            if ssInt > 1800:
                print time.strftime('%H:%M:%S') + ' NOTIFY MESSAGE WILL BE RECIVED AT 30 MINNTES BEFORE EVENT START'
                time.sleep(ssInt - 1800)
                soundalert()
                print time.strftime('%H:%M:%S') + ' ANNOUNCED EVENT WILL START AT ' + datetime.strftime(localtime(preTime),'%H:%M')
                ss = 3600
            else :
                ss = ssInt + 3600
                print ''
        else:
            mainraw = raw(t)
            if mainraw[0] == 'newevent':
                rawData = mainraw[1]
                rawTime = rawData[0]
                if t == 'loop':
                    soundalert()
                rawPrint = ['raw',rawData]
                questcheck(rawPrint,'get')
                ssInt = ( rawTime.hour - now.hour)*3600 - now.minute * 60 - now.second
                if ssInt > 1800:
                    print time.strftime('%H:%M:%S') + ' NOTIFY MESSAGE WILL BE RECIVED AT 30 MINNTES BEFORE EVENT START'
                    time.sleep(ssInt - 1800)
                    soundalert()
                    print time.strftime('%H:%M:%S') + ' EVENT WILL START AT ' + datetime.strftime(localtime(rawTime),'%H:%M')
                    ss = 3600
                else:
                    ss = ( ssInt + 3600)
                print ''
            else :
                if t == 'start' :
                    print time.strftime('%H:%M:%S') + ' NO EVENT FOUND'                    
                if now.minute < 10 :
                    ss = 60 - now.second
                elif now.minute >= 10 and now.minute < 45:
                    ss = ( 15 - (now.minute % 15 )) *60 - now.second
                elif now.minute == 45:
                    print time.strftime('%H:%M:%S') + ' NO EVENT FOUND FORM PSO2 ES'
                    ss = 60 - now.second
                elif now.minute > 45 and now.minute < 55:
                    ss = 60 - now.second
                elif now.minute >= 55 :
                    print time.strftime('%H:%M:%S') + ' NO EVENT FOUND'
                    ss = ( 5 - (now.minute % 5 )) *60 - now.second
    return ss
예제 #27
0
 def install(self):
     while True:
         system = sys()
         os.system("clear")
         logo.ins_tnc()
         inp = quo.prompt("Do you want to install sashay? [y/n]")
         if inp == "y" or inp == "Y" or inp == "Yes" or inp == "yes":
             os.system("clear")
             logo.installing()
             if system.sudo is not None:
                 #require root permission
                 if os.path.exists(system.conf_dir + "/sashay"):
                     pass
                 else:
                     os.system(system.sudo + " mkdir " + system.conf_dir +
                               "/sashay")
                 os.system(system.sudo + " cp -r src assets sashay.py " +
                           system.conf_dir + "/sashay")
                 os.system(system.sudo + " cp -r assets/sashay " +
                           system.bin)
                 os.system(system.sudo + " cp -r assets/sshy " + system.bin)
                 os.system(system.sudo + " chmod +x " + system.bin +
                           "/sashay")
                 os.system(system.sudo + " chmod +x " + system.bin +
                           "/sshy")
                 os.system("cd .. && " + system.sudo + " rm -rf sashay")
                 if os.path.exists(system.bin +
                                   "/sashay") and os.path.exists(
                                       system.conf_dir + "/sashay"):
                     os.system("clear")
                     logo.ins_sc()
                     tmp = input("\033[1;36m ##> \033[00m")
                     break
                 else:
                     os.system("clear")
                     logo.not_ins()
                     tmp = input("\033[1;36m ##> \033[00m")
                     break
             else:
                 if os.path.exists(system.conf_dir + "/sashay"):
                     pass
                 else:
                     os.system("mkdir " + system.conf_dir + "/sashay")
                 os.system("cp -r src assets sashay.py " + system.conf_dir +
                           "/sashay")
                 os.system("cp -r assets/sashay " + system.bin)
                 os.system("cp -r assets/sshy " + system.bin)
                 os.system("chmod +x " + system.bin + "/sashay")
                 os.system("chmod +x " + system.bin + "/sshy")
                 os.system("cd .. && rm -rf sashay")
                 if os.path.exists(system.bin +
                                   "/sashay") and os.path.exists(
                                       system.conf_dir + "/sashay"):
                     os.system("clear")
                     logo.ins_sc()
                     tmp = input("\033[1;36m ##> \033[00m")
                     break
                 else:
                     os.system("clear")
                     logo.not_ins()
                     tmp = input("\033[1;36m ##> \033[00m")
                     break
         else:
             break
예제 #28
0
               'leftHip_y', 'rightHip_score', 'rightHip_x', 'rightHip_y', 'leftKnee_score', 'leftKnee_x', 'leftKnee_y',
               'rightKnee_score', 'rightKnee_x', 'rightKnee_y', 'leftAnkle_score', 'leftAnkle_x', 'leftAnkle_y',
               'rightAnkle_score', 'rightAnkle_x', 'rightAnkle_y']
    data = json.loads(open(path_to_video, 'r').read())
    csv_data = np.zeros((len(data), len(columns)))
    for i in range(csv_data.shape[0]):
        one = []
        one.append(data[i]['score'])
        for obj in data[i]['keypoints']:
            one.append(obj['score'])
            one.append(obj['position']['x'])
            one.append(obj['position']['y'])
        csv_data[i] = np.array(one)
    pd.DataFrame(csv_data, columns=columns).to_csv(/home/ubuntu/VaishDir/Testing Data/ + 'key_points.csv', index_label='Frames#')
import sys
testing_data = sys(argv[1])
convert_to_csv(testing_data)
test_data = makeMatrix('/home/ubuntu/VaishDir/Testing Data/' + 'key_points.csv')

# In[5]:


def makeMatrix(input):
    with open(input, newline='') as csvfile:
        data = list(csv.reader(csvfile))
        columns = ['rightWrist_x', 'rightWrist_y']
        dataMatrix = np.zeros((len(data)-1, len(columns)))
        for i in range(dataMatrix.shape[0] + 1):
            dataRow = []
            if(data[i][33] != 'rightWrist_x'):
                dataRow.append(data[i][33])
예제 #29
0
      windows = windows_apps,
      options = {'py2exe': py2exe_opts},
      data_files = mpl_data_files)

for fname in extra_files:
    path, name = os.path.split(fname)
    print fname, name
    try:
        shutil.copy(fname, os.path.join('dist', name))
    except:
        pass



def sys(cmd):
    print ' >> ', cmd
    os.system(cmd)

try:
    os.makedirs("dist/tdl/")
    os.makedirs("dist/tdl/modules")
except:
    pass
sys("cp -pr ../modules   dist/tdl/." )
sys("cp -pr ../pds/startup.pds   dist/tdl/." )
sys("cp -pr ../dlls/win32/* dist/.")

if __name__ == '__main__':
    print 'usage:  python py2exe_build.py py2exe'

예제 #30
0
import sys
def dekor(func):
    print('START')
    def new_func():
        print('до')
        func()
        print('после')
    return new_func
    print('END')

sys()

dekor()


@dekor

def some_func():
    for a in  range(10):
        print(a)

some_func()





sys.exit(0)


@now_time
예제 #31
0
M = np.random.randn(1, 256)
x = t.dot(M)
bias = 0.05 * np.random.randn(1, 256)
expo = [([1] * 11 + range(5)) * 16]
zeros = np.where(np.random.rand(256, 1) > prob_n_itter)[0]


def sys(x, bias, expo, zeros):
    y = x**expo + bias
    y[:, 1:10] = np.sin(2 * np.pi * 3 * y[:, 1:10])
    for i in zeros:
        y[:, i] = 0
    return y


y = sys(t, bias, expo, zeros)
K = np.random.randn(256, 1)
z = np.hstack((y.dot(K[::-1]), x.dot(K[::-1])))
score = []
for i in xrange(1000):
    t_ = t + 0.05 * np.random.randn(t.shape[0], t.shape[1])
    x_ = t_.dot(M)
    zeros = np.where(np.random.rand(256, 1) > prob_n_itter)[0]
    y_ = sys(t_, bias, expo, zeros)
    liquid._realtime_learn(x_, y_, z)
    score.append([
        liquid._regressor["input"].score(x_, z),
        liquid._regressor["output"].score(y_, z)
    ])
    print np.sum(liquid.CovMatrix["output"])
예제 #32
0
파일: bootstrap.py 프로젝트: ccpgames/esky
    class sys:
        platform = _sys.platform
        executable = _sys.executable
        argv = _sys.argv
        version_info = _sys.version_info
        modules = {}
        builtin_module_names = _sys.builtin_module_names

        def exit(self, code):
            _exit_code[0] = code
            raise SystemExit(code)

        def exc_info(self):
            return None, None, None

    sys = sys()
    sys.modules["sys"] = sys

    #  RPython doesn't provide the sorted() builtin, and actually makes sorting
    #  quite complicated in general.  I can't convince the type annotator to be
    #  happy about using their "listsort" module, so I'm doing my own using a
    #  simple insertion sort.  We're only sorting short lists and they always
    #  contain (list(str),str), so this should do for now.
    def _list_gt(l1, l2):
        i = 0
        while i < len(l1) and i < len(l2):
            if l1[i] > l2[i]:
                return True
            if l1[i] < l2[i]:
                return False
            i += 1
            if True == palindrome_map[offset][i]:
                current_node = tree.setdefault(input_string[offset:i + 1], dict())
                buildSeperationTree(input_string, palindrome_map, current_node, i + 1)
    return tree

def findMinHeight(tree):
    if '_END' in tree.keys():
        height = 0
    else:
        height = min([findMinHeight(tree[k]) for k in tree]) + 1        

    return height

def findMinSeperation(input_string):
    result = {'result_string':'', 'count':0}
    
    pmap = markPalindromes(input_string)
    tree = buildSeperationTree(input_string, pmap)
      
    result['count'] = findMinHeight(tree)      
    return result

def main():
    test_string = 'ababbbabbababa'    
    result = findMinSeperation(test_string)
    print result
       
if __name__ == '__main__':
    cProfile.run('main()')
    sys(exit(main()))
예제 #34
0
            f.write("</sources>\n")

    def read_providers(self, providerfile):
        # Check we have data
        try:
            if not os.path.getsize(providerfile):
                raise Exception, "Providers file is empty"
        except Exception, e:
            raise (e)
        f = open(providerfile, "r")
        for line in f:
            if line == "400: Invalid request\n":
                print(
                    "Providers download is invalid please resolve or use URL based setup"
                )
                sys(exit(1))
            PROVIDERS.append({
                'name': line.split(',')[0],
                'm3u': line.split(',')[1],
                'epg': line.split(',')[2],
                'delimiter_category': int(line.split(',')[3]),
                'delimiter_title': int(line.split(',')[4]),
                'delimiter_tvgid': int(line.split(',')[5]),
                'delimiter_logourl': int(line.split(',')[6])
            })
        f.close()

    def process_provider(self, provider, username, password):
        supported_providers = ""
        for line in PROVIDERS:
            supported_providers += " " + line['name']
예제 #35
0
import sys

sys = sys.stdin.readline

n = int(sys())
cookies = [sys().strip() for _ in range(n)]

answer = []
heart_idx = (-1, -1)

# 머리 -> 심장 좌표
for i in range(len(cookies)):
    if '*' in cookies[i]:
        heart_idx = (i + 1, cookies[i].index('*') + 1)
        answer.append([heart_idx[0] + 1, heart_idx[1]])  # 심장 위치
        break

# 팔 길이
left_arm_len = (heart_idx[1] - 1) - cookies[heart_idx[0]].find('*')
right_arm_len = cookies[heart_idx[0]].rfind('*') - (heart_idx[1] - 1)
answer.append([left_arm_len, right_arm_len])

# 허리 길이
waist_len = 0
leg_idx = -1
for i in range(heart_idx[0] + 1, len(cookies)):
    if cookies[i].count('*') == 1:
        waist_len += 1
        leg_idx = i + 1
    else:
        break
예제 #36
0
##output: <split region file> 

import os,getopt
import sys

argv = sys.argv[1:]
input = ''
output = ''
usage = 'python " + sys.argv[0] + " -i <input>  -o <output>'
example = 'python " + sys.argv[0] + " -i <input>  -o <output>'
try:
  opts,args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
  print usage + "\n" + example 
  sys.exit(2)
for opt, arg in opts:
  if opt == '-h':
    print usage + "\n" + example 
    sys.exit()
  elif opt in ("-i","--ifile"):
    input = arg
  elif opt in ("-o","--ofile"):
    output = arg
    outlog = output + ".log"
print ('Script path'+ sys.argv[0])
print('Input file:' + input)
print('Output file:'+ output)
print('Log file:'+ outlog)

sys("samtools view -H bamfile")
예제 #37
0
            # 'iconfile': 'GSEMap.icns',
            }

appname = 'GSEMapViewer'
appvers = '1.2'
setup(name = appname,
      version = appvers,
      description = "GSECARS XRM MapViewer",
      options = {'build_exe': exe_opts},
      data_files = mpl_data_files + dll_files, ##  + plugin_files
      executables = [Executable('../bin/GSE_MapViewer', base=None)])

contents = 'build/%s-%s.app/Contents' % (appname, appvers)
contents = contents.replace(' ', '\ ')

def sys(cmd):
    print(' >> %s' % cmd)
    os.system(cmd)

sys("cp -pr GSEMap.icns  %s/Resources/." % contents)
sys("cp -pr ../dlls/darwin/* %s/MacOS/." % contents)

try:
    os.makedirs("%s/Resources/larch/" % contents)
except:
    pass

for subdir in ('modules', 'plugins', 'dlls'):
    sys("cp -pr ../%s   %s/Resources/larch/." % (subdir, contents))

예제 #38
0
파일: install.py 프로젝트: hadiislam/CAT
    def install(self):
        while True:
            system = sys()
            os.system("clear")
            logo.ins_tnc()
            inp = input(
                "\033[32m Do you want to install CyberCat [Y/n]> \033[m")
            if inp == "y" or inp == "Y":
                os.system("clear")
                logo.installing()
                if system.sudo is not None:

                    #require root permission
                    if os.path.exists(system.conf_dir + "/CAT"):
                        pass
                    else:
                        os.system(system.sudo + " mkdir " + system.conf_dir +
                                  "/CAT")
                    os.system(system.sudo + " cp -r modules core CAT.py " +
                              system.conf_dir + "/CAT")
                    os.system(system.sudo + " cp -r core/CAT " + system.bin)

                    os.system(system.sudo + " chmod +x " + system.bin + "/CAT")

                    os.system("cd .. && " + system.sudo + " rm -rf CAT")
                    if os.path.exists(system.bin + "/CAT") and os.path.exists(
                            system.conf_dir + "/CAT"):
                        os.system("clear")
                        logo.ins_sc()
                        tmp = input(
                            "\033[m[\033[32m*\033[m]\033[32m Choose :\033[m ")
                        break
                    else:
                        os.system("clear")
                        logo.not_ins()
                        tmp = input("")
                        break
                else:
                    if os.path.exists(system.conf_dir + "/CAT"):
                        pass
                    else:
                        os.system("mkdir " + system.conf_dir + "/CAT")
                    os.system("cp -r modules core CAT.py " + system.conf_dir +
                              "/CAT")
                    os.system("cp -r core/CAT " + system.bin)
                    os.system("cp -r core/CAT " + system.bin)
                    os.system("chmod +x " + system.bin + "/CAT")
                    os.system("cd .. && rm -rf CAT")
                    if os.path.exists(system.bin + "/CAT") and os.path.exists(
                            system.conf_dir + "/CAT"):
                        os.system("clear")
                        logo.ins_sc()
                        tmp = input(
                            "\033[m[\033[32m*\033[m]\033[32m Choose :\033[m")
                        break
                    else:
                        os.system("clear")
                        logo.not_ins()
                        tmp = input(
                            "\033[m[\033[32m*\033[m]\033[32m Choose :\033[m")
                        break
            else:
                break
예제 #39
0
파일: backup.py 프로젝트: akula/python
                    old_backup = '%s.%2.2d' %(destpath, index-1)
                    if not os.path.exists(old_backup): break
                    abspath = os.path.abspath(old_backup)

                    try:
                        if os.path.isfile(abspath) and filecmp.cmp(abspath,filepath, shallow=False:
                            continue
                        except OSERROR:
                              pass
                    try:
                    if not os.path.exists(backup):
                    print 'Copying %s to %s ...' %filepath, backup)
                            shutil.copy(filepath, backup)
                    except (OSError, IOError), e:
                        pass


if __name__=='__main__'

   if len(sys(sys.argv)<2:
   sys.exit("Usage: %s [dirctory] [backup directory]" %sys.argv[0])

   tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))
   if len(sys.argv) >=3:
   bakfolder = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[2])))
   else:
       bakfolder = BAKFOLDER

   if os.path.isdir(tree_top):
       backup_files(tree_top, bakfolder)
예제 #40
0
exe_opts['includes'].extend(pycard_incs)

appname = 'PythonDataShell'
appvers = '0.1'
setup(name = appname,
      version = appvers,
      description = "GSECARS PythonDataShell",
      options = {'build_exe': exe_opts},
      data_files = mpl_data_files + dll_files, ##  + plugin_files
      executables = [Executable('runpds.py', base=None),
                     ])


contents = 'build/%s-%s.app/Contents' % (appname, appvers)
contents = contents.replace(' ', '\ ')

def sys(cmd):
    print ' >> ', cmd
    os.system(cmd)

# sys("cp -pr TDL.icns  %s/icons.icns" % contents)

try:
    os.makedirs("%s/Resources/tdl/" % contents)
except:
    pass
sys("cp -pr ../modules   %s/Resources/tdl/." % (contents))
sys("cp -pr ../pds/startup.pds   %s/Resources/tdl/." % (contents))
#
sys("cp -pr ../dlls/darwin/* %s/MacOS/." % contents)
def sys(message, cmd):
    print message
    subprocess.call(shlex.split(cmd))
    time.sleep(5)

def checkRootUser():
    if os.geteuid() != 0:
	print "Please execute this script as root!"
	sys.exit(1)

########
# main #
########
checkRootUser()
configureAuthHttpProcess()
sys("0. Using yum to install several useful packages for debugging ML issues", "yum -y install glibc.i686 redhat-lsb pstack sysstat psutils")
sys("1. Downloading ML binary from developer.marklogic.com", "wget " + BINARY_PATH + BINARY_FILENAME)
sys("2. Installing ML from binary", "rpm -i " + BINARY_FILENAME)
sys("3. Starting MarkLogic Instance", "/etc/init.d/MarkLogic start")
httpProcess("4. Configuring licence details", "license-go.xqy", LICENCE_ARGS)
httpProcess("5. Accepting EULA", "agree-go.xqy", EULA_ARGS)
httpProcess("6. Triggering initial application server config", "initialize-go.xqy")
sys("7. Restarting Server", "/etc/init.d/MarkLogic restart")
httpProcess("8. Configuring Admin user (security)", "security-install-go.xqy", SECURITY_ARGS)
httpProcess("9. Testing Admin Connection", "default.xqy")
sys("10. Moving booster to ML Admin", "cp booster-0.2b.xqy /opt/MarkLogic/Admin/booster.xqy")
httpProcess("12. Configuring XDBC Server on port " + BASE_XDBC_PORT, "booster.xqy", BOOSTER_XDBC_ARGS)
sys("11. Cleaning up", "rm " + BINARY_FILENAME)
sys("12. Updating user permissions for home folder(s) where Modules are hosted (+x)", "chmod go+x /home/username")
httpProcess("13. Creating main appserver", "booster.xqy", BOOSTER_HTTP_MAIN_ARGS)
appserverSetTemplate("http-9997", "authentication", "application-level")
	
LOCALHOST = "localhost" 
BASE_HREF = "http://" + LOCALHOST + ":8001/"
 
LICENCE_ARGS = { 'license-key':LICENSE_KEY, 'licensee':LICENSEE }
SECURITY_ARGS = { 'auto':'true', 'user':ADMIN_USER_NAME, 'password1':ADMIN_PASSWORD, 'password2':ADMIN_PASSWORD, 'realm':'public' }
EULA_ARGS = { 'accepted-agreement':ACCEPTED_AGREEMENT,"ok.x":1 }
   
def checkRootUser():
	if os.geteuid() != 0:
		print("Please execute this script as root!")
	sys.exit(1)
 
configureAuthHttpProcess(LOCALHOST)
sys("2. Installing", INSTALL_CMD)
sys("3. Starting MarkLogic Instance", START_CMD)
httpProcess("4. Configuring licence details", BASE_HREF + "license-go.xqy", LICENCE_ARGS)
httpProcess("5. Accepting EULA", BASE_HREF +"agree-go.xqy", EULA_ARGS)
httpProcess("6. Triggering initial application server config", BASE_HREF +"initialize-go.xqy")
sys("7a. Restarting Server", STOP_CMD)
sys("7b. Restarting Server", START_CMD)
httpProcess("8. Configuring Admin user (security)", BASE_HREF +"security-install-go.xqy", SECURITY_ARGS)
httpProcess("9. Testing Admin Connection", BASE_HREF +"default.xqy")
sys("Move set host name script",COPY_CMD)
HOST_ARGS = { 'HOST-NAME':getEC2Name() }
httpProcess("Setting host name",BASE_HREF +"set-host-name.xqy", HOST_ARGS)
print("Script completed, visit http://"+getEC2Name()+":8001 to access the admin interface.")


예제 #43
0
 def install(self):
     while True:
         system = sys()
         clear()
         logo.ins_tnc()
         session = Prompt(bottom_toolbar=Text(
             ' <b>Install</b> <style bg="red">sashay</style>'),
                          placeholder=Text(' <gray>([y/n])</gray>'))
         inp = session.prompt("Do you want to install sashay?:")
         if inp == "y" or inp == "Y" or inp == "Yes" or inp == "yes":
             clear()
             logo.installing()
             if system.sudo is not None:
                 #require root permission
                 if os.path.exists(system.conf_dir + "/sashay"):
                     pass
                 else:
                     os.system(system.sudo + " mkdir " + system.conf_dir +
                               "/sashay")
                 os.system(system.sudo + " cp -r src assets sashay.py " +
                           system.conf_dir + "/sashay")
                 os.system(system.sudo + " cp -r assets/sashay " +
                           system.bin)
                 os.system(system.sudo + " cp -r assets/sshy " + system.bin)
                 os.system(system.sudo + " chmod +x " + system.bin +
                           "/sashay")
                 os.system(system.sudo + " chmod +x " + system.bin +
                           "/sshy")
                 os.system("cd .. && " + system.sudo + " rm -rf sashay")
                 if os.path.exists(system.bin +
                                   "/sashay") and os.path.exists(
                                       system.conf_dir + "/sashay"):
                     clear()
                     logo.ins_sc()
                     tmp = session.prompt("|>>")
                     # tmp=input("\033[1;36m ##> \033[00m")
                     break
                 else:
                     clear()
                     logo.not_ins()
                     tmp = session.prompt("|>>")
                     #   tmp=input("\033[1;36m ##> \033[00m")
                     break
             else:
                 if os.path.exists(system.conf_dir + "/sashay"):
                     pass
                 else:
                     os.system("mkdir " + system.conf_dir + "/sashay")
                 os.system("cp -r src assets sashay.py " + system.conf_dir +
                           "/sashay")
                 os.system("cp -r assets/sashay " + system.bin)
                 os.system("cp -r assets/sshy " + system.bin)
                 os.system("chmod +x " + system.bin + "/sashay")
                 os.system("chmod +x " + system.bin + "/sshy")
                 os.system("cd .. && rm -rf sashay")
                 if os.path.exists(system.bin +
                                   "/sashay") and os.path.exists(
                                       system.conf_dir + "/sashay"):
                     clear()
                     logo.ins_sc()
                     tmp = session.prompt("|>>")
                     # tmp=input("\033[1;36m ##> \033[00m")
                     break
                 else:
                     clear()
                     logo.not_ins()
                     tmp = session.prompt("|>>")
                     #    tmp=input("\033[1;36m ##> \033[00m")
                     break
         else:
             break
예제 #44
0
                def do_use(self, comando):
                    "comandos"
                    if comando and comando in self.comandos:
                        if comando == "encode16":
                            encode16()
                        elif comando == "encode32":
                            encode32()
                        elif comando == "encode64":
                            encode64()
                        elif comando == "decode16":
                            decode16()
                        elif comando == "decode32":
                            decode32()
                        elif comando == "decode64":
                            decode64()
                        elif comando == "baixar":
                            baixarU()
                        elif comando == "gera_payload":
                            payloads()
                        elif comando == "encode_sha3_256":
                            sha3_256()
                        elif comando == "encode_sha256":
                            sha256()
                        elif comando == "encode_blake2b":
                            blake2b()
                        elif comando == "encode_sha384":
                            sha384()
                        elif comando == "encode_md5":
                            md5()
                        elif comando == "encode_sha3_512":
                            sha3_512()
                        elif comando == "encode_sha512":
                            sha512()
                        elif comando == "encode_sha1":
                            sha1()
                        elif comando == "encode_sha3_224":
                            sha3_224()
                        elif comando == "encode_sha3_384":
                            sha3_384()
                        elif comando == "encode_sha224":
                            sha224()
                        elif comando == "wordlist_especial":
                            especial()
                        elif comando == "wordlist_int":
                            _int()
                        elif comando == "wordlist_int_especial":
                            int_especial()
                        elif comando == "wordlist_str":
                            _str()
                        elif comando == "wordlist_str_especial":
                            str_especial()
                        elif comando == "wordlist_str_int_especial":
                            str_int_especial()
                        elif comando == "wordlist_str_int_up":
                            str_int_up()
                        elif comando == "wordlist_str_up":
                            str_up()
                        elif comando == "wordlist_str_up_especial":
                            str_up_especial()
                        elif comando == "clear":
                            from os import system as sys
                            sys("clear")

                    elif comando:
                        saida = "[+]comando incompleto=> [%s]" % comando
                    elif comando:
                        saida = "[+]comando incompleto=> [%s]" % comando
                    else:
                        saida = '[+]comando errado...'
               debuff2id='%s', debuff3id='%s', debuff4id='%s', debuff5id='%s', debuff6id='%s', iscomplete='%s', \
               nummembers='%s', maxattackers='%s', summonerid='%s', raid_boss_human='%s' WHERE id='%s';" \
              % ( table, update_time,
                  raid_info['currenthealth'], raid_info['enragehealth'], raid_info['maxhealth'],
                  raid_info['debuff1id'], raid_info['debuff2id'], raid_info['debuff3id'],
                  raid_info['debuff4id'], raid_info['debuff5id'], raid_info['debuff6id'],
                  raid_info['iscomplete'], raid_info['nummembers'], raid_info['maxattackers'],
                  raid_info['summonerid'], raid_info['raid_boss_human'],
                  id
                 )

        cursor.execute(sql)
        conn.commit()

# main

if len(sys.argv) != 5:
    print "Usage: self {table_name} {game} {platform} {serverid}"
    print "Example: " + sys(argv[0]) + "dawn_shared_raids dawn facebook 1"
    exit()
else:
    if config['verbose_mode']:
        print "Working on: " + str(sys.argv)
    ugup_request( str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]), int(sys.argv[4]) )

    cursor.close()
    conn.close()

    if config["verbose_mode"]:
        print "Job's Done!"
예제 #46
0
파일: bootstrap.py 프로젝트: ccpgames/esky
    # RPython doesn't have access to the "sys" module, so we fake it out.
    # The entry_point function will set these value appropriately.
    _sys = sys
    class sys:
        platform = _sys.platform
        executable = _sys.executable
        argv = _sys.argv
        version_info = _sys.version_info
        modules = {}
        builtin_module_names = _sys.builtin_module_names
        def exit(self,code):
            _exit_code[0] = code
            raise SystemExit(code)
        def exc_info(self):
            return None,None,None
    sys = sys()
    sys.modules["sys"] = sys

    #  RPython doesn't provide the sorted() builtin, and actually makes sorting
    #  quite complicated in general.  I can't convince the type annotator to be
    #  happy about using their "listsort" module, so I'm doing my own using a
    #  simple insertion sort.  We're only sorting short lists and they always
    #  contain (list(str),str), so this should do for now.
    def _list_gt(l1,l2):
        i = 0
        while i < len(l1) and i < len(l2):
            if l1[i] > l2[i]:
               return True
            if l1[i] < l2[i]:
               return False
            i += 1
예제 #47
0
liquid = L.Lsm() #init liquid state machine
prob_n_itter = 0.8;
t = np.linspace (0,1,1e3)[:,None]
M = np.random.randn(1,256)
x = t.dot(M)
bias = 0.05*np.random.randn(1,256)
expo = [([1]*11+range(5))*16]
zeros = np.where(np.random.rand(256,1)>prob_n_itter)[0]
def sys (x,bias,expo,zeros): 
    y = x**expo + bias
    y[:,1:10] = np.sin (2*np.pi*3*y[:,1:10]) 
    for i in zeros:
        y[:,i] = 0
    return y

y = sys (t,bias,expo,zeros)
K = np.random.randn(256,1)
z = np.hstack((y.dot(K[::-1]), x.dot(K[::-1])))
score = []
for i in xrange(1000):
    t_ = t + 0.05*np.random.randn(t.shape[0],t.shape[1])
    x_ = t_.dot(M)
    zeros = np.where(np.random.rand(256,1)>prob_n_itter)[0]
    y_ = sys (t_,bias,expo,zeros)
    liquid._realtime_learn (x_,y_,z)
    score.append([liquid._regressor["input"].score(x_,z), liquid._regressor["output"].score(y_,z)])
    print np.sum(liquid.CovMatrix["output"])

t_ = t + 0.05*np.random.randn(t.shape[0],t.shape[1])
x_ = t_.dot(M)
zeros = np.where(np.random.rand(256,1)>1)[0]