示例#1
0
def main_email(name, total, answered, not_answered, declines, remaining):
    """ Main function for sending Email Updates """

    start = smtplib.SMTP(host=HOST, port=PORT)
    start.starttls()
    start.login(ADDRESS, PASSWORD)

    date = datetime.datetime.now()
    date_now = date.strftime("%m-%d-%Y")

    print_list, email_dict = simple_contacts('contacts.txt')

    emails = get_emails(print_list, email_dict)

    message_template = read_template()

    for mail in emails:
        pretty_print(f"Sending email to {mail}", "!")
        msg = MIMEMultipart()

        message = message_template.substitute(PERSON_NAME=name, DATE=date_now, TOTAL_CALLED=total, ANSWERED=answered, NOT_ANSWERED=not_answered, DECLINES=declines, REMAINING=remaining)

        msg['From'] = ADDRESS
        msg['To'] = mail
        msg['Subject'] = f"{name} - Calling Campaign Summary - {date_now}"

        msg.attach(MIMEText(message, 'plain'))
        start.send_message(msg)
        pretty_print(f"Mail sent to {mail}", "!")

        del msg

    start.quit()
示例#2
0
 def handle_scope_message(self, msg):
     message = STP_MSG % (msg[SERVICE], msg[COMMAND], msg[STATUS], msg[TAG],
                          msg[PAYLOAD])
     if self.debug:
         pretty_print("send to client:", msg, self.debug_format,
                      self.debug_format_payload)
     self.send_message(message)
示例#3
0
def get_hand_combinations(hand):
    hand_sorted = sorted(hand, key=lambda card: VALUES.get(card.get('value')))

    singles = hand_sorted

    pairs = _find_pairs(hand_sorted)

    triples = _find_triples(hand_sorted)
    fullhouses = _find_fullhouses(hand_sorted)
    steps = _find_steps(hand_sorted)
    straights = _find_straights(hand_sorted)
    print('hand')
    pretty_print(hand)
    print('hand_sorted')
    pretty_print(hand_sorted)
    print('singles')
    # pretty_print(singles)
    print('pairs')
    pretty_print(pairs)
    print('triples')
    # pretty_print(triples)
    print('fullhouses')
    # pretty_print(fullhouses)
    print('steps')
    pretty_print(steps)
    print('straights')
    pretty_print(straights)
    combinations = [singles, pairs, triples, fullhouses, steps]
    print('combinations')
    # pretty_print(combinations)
    return combinations
示例#4
0
    def call_result(self, row_list):
        """ Function to update call result """

        pretty_print("How was your call?", "*")
        pretty_print("If you talked to the student enter: 200", "-")
        pretty_print("If the call was not answered enter: 500", "-")
        pretty_print("If you did not call the person enter: 999", "-")
        pretty_print(
            "If the student wants to Decline/Withdraw application enter: 404",
            "-")

        again = True
        while again:
            result = get_int_input()
            if result == 200:
                self.called += 1
                again = False
                self.called_list.append(row_list)

            elif result == 500:
                self.not_answered += 1
                again = False
                self.no_answer_list.append(row_list)

            elif result == 999:
                again = False

            elif result == 404:
                self.declines += 1
                again = False
                self.decline_list.append(row_list)

            else:
                print("You can't get out of this! Enter a valid number!")
示例#5
0
    def train(self):
        images = os.listdir(
            config.DATA_ROOT
        )  # list semua path data wajah pada folder train data

        print("[INFO] Preparing Training Data...")
        image_arrays = []  # Containes semua array data wajah
        image_ids = []  # Container semua ID data wajah
        for i, image_path in enumerate(
                images):  # Looping semua path data wajah
            splitted_path = image_path.split(".")
            # print(splitted_path)
            image_id = int(splitted_path[1])  # Ambil ID data wajah

            image = cv2.imread(os.path.join(config.DATA_ROOT, image_path))
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            image_array = np.array(image, "uint8")  # Ambil array data wajah

            image_arrays.append(
                image_array)  # Store array data wajah ke list/container
            image_ids.append(image_id)  # Store ID data wajah ke list/container
            utils.pretty_print(len(images), i)

        print("[INFO] Training Start!")
        self.recognizer.train(image_arrays,
                              np.array(image_ids))  # Train recognizer
        self.recognizer.save(config.MODEL_PTH)  # Save model recognizer
        print("[INFO] TRAIN RECOGNIZER SUCCESS!")
示例#6
0
def simple_contacts(filename):
    """ Function to get contacts """

    try:
        file_path = open(filename, 'r', encoding='utf-8')

    except FileNotFoundError:
        pretty_print("Cannot open contacts.txt", ":")
        sleep(3)

    else:
        with file_path:
            print_list = []
            email_dict = {}
            for line in file_path:
                split_line = line.strip().split('|')

                if split_line[0].isnumeric():

                    command = int(split_line[0])
                    email = split_line[-1]
                    print_list.append(split_line)
                    email_dict[command] = email

    return print_list, email_dict
示例#7
0
 def send_command_STP_1(self, msg):
     """ to send a message to scope
     message TransportMessage
     {
         required string service = 1;
         required uint32 commandID = 2;
         required uint32 format = 3;
         optional uint32 status = 4;
         optional uint32 tag = 5;
         required binary payload = 8;
     }
     """
     if self.debug and not self.debug_only_errors:
         pretty_print("send to host:", msg,
                         self.debug_format, self.debug_format_payload)
     stp_1_msg = "".join([
         self.STP1_PB_TYPE_COMMAND,
         self.STP1_PB_SERVICE, encode_varuint(len(msg[1])), msg[1],
         self.STP1_PB_COMMID, encode_varuint(msg[2]),
         self.STP1_PB_FORMAT, encode_varuint(msg[3]),
         self.STP1_PB_TAG, encode_varuint(msg[5]),
         self.STP1_PB_PAYLOAD, encode_varuint(len(msg[8])), msg[8]])
     self.out_buffer += (
         self.STP1_PB_STP1 +
         encode_varuint(len(stp_1_msg)) +
         stp_1_msg)
     self.handle_write()
def get_pruned_SANs_list(subdomain_list, ParentDomain, verbose):
    ''' This function does two things:
	1. Eliminates those items in the SANs list that
		a. Do not contain the parent domain
		b. Have an asterisk wildcard in them
	2. After filtering the subdomains based on the criteria above,
	   returns a list of sanitized subdomains '''

    result_list = []

    for k in subdomain_list:

        SANs_list = get_SANs_from_cert(k)
        if verbose:
            utils.pretty_print("Getting SANs for " + str(k),
                               len("Getting SANs for " + str(k)))
            print "SANs: ",
            print SANs_list
        if SANs_list is not None:
            for i in SANs_list:
                if i != ParentDomain and ParentDomain in i and '*' not in i:  # Get only those SANs that are non-wildcard/asterisk containing subdomains
                    result_list.append(i)
                    print i,
                    print " [SAN Name]"
        if verbose:
            print "\n"
    return result_list
示例#9
0
文件: main.py 项目: kekler/bottly
    def command_filter(self, user, msg_type, destination, command, arg):
        """
        command_filter attempts to determine the appropriate action(s) based on
        the supplied input and then execute it/them.
        """
        message = None
        if command is not None:
            trig_pass, command = self.trigger_check(command)
        else:
            trig_pass = False
            message = self.auto_commands(command, destination, user, arg)

        if trig_pass:
            log(self.logger, user, msg_type, destination, command, arg)
            if self.is_admin(destination, user):
                self.admin_only_commands(command, destination, user, arg)

            if self.is_trusted(destination, user):
                self.autotiny, self.hushed, message = self.trusted_commands(command, destination, user)

            if not self.hushed:
                message = self.user_commands(command, destination, user, arg)

        if len(message) > 0:
            utils.pretty_print(self.nick, msg_type, destination, message)
            if isinstance(message, tuple):
                for line in message:
                    self.send_message(destination, line)
            else:
                self.send_message(destination, message)
示例#10
0
def get_hand_combinations(hand):
    hand_sorted = sorted(hand, key=lambda card:  VALUES.get(card.get('value')))

    singles = hand_sorted

    pairs = _find_pairs(hand_sorted)

    triples = _find_triples(hand_sorted)
    fullhouses = _find_fullhouses(hand_sorted)
    steps = _find_steps(hand_sorted)
    straights = _find_straights(hand_sorted)
    print('hand')
    pretty_print(hand)
    print('hand_sorted')
    pretty_print(hand_sorted)
    print('singles')
    # pretty_print(singles)
    print('pairs')
    pretty_print(pairs)
    print('triples')
    # pretty_print(triples)
    print('fullhouses')
    # pretty_print(fullhouses)
    print('steps')
    pretty_print(steps)
    print('straights')
    pretty_print(straights)
    combinations = [singles, pairs, triples, fullhouses, steps]
    print('combinations')
    # pretty_print(combinations)
    return combinations
示例#11
0
    def command_filter(self, user, msg_type, destination, command, arg):
        message = None
        if command is not None:
            trig_pass, command = self.trigger_check(command)
        else:
            trig_pass = False
            message = self.auto_commands(command, destination, user, arg)

        if trig_pass:
            log(self.logger, user, msg_type, destination, command, arg)
            if self.is_admin(destination, user):
                self.admin_only_commands(command, destination, user, arg)

            if self.is_trusted(destination, user):
                self.autotiny, self.hushed, message = self.trusted_commands(command, destination, user)

            if not self.hushed:
                message = self.user_commands(command, destination, user, arg)

        if len(message) > 0:
            utils.pretty_print(self.nick, msg_type, destination, message)
            if isinstance(message, tuple):
                for line in message:
                    self.send_message(destination, line)
            else:
                self.send_message(destination, message)
示例#12
0
def main(args):
    gallery2 = utils.Gallery2(config.GALLERY_2_BASE_URL)
    koken = utils.Koken(config.KOKEN_BASE_URL)

    if args.http_debug:
        utils.setup_logging(debug=True)
    else:
        utils.setup_logging(debug=False)

    if args.gallery_login:
        gallery2.login()

    if args.gallery_fetch_albums:
        utils.pretty_print(gallery2.fetch_albums())

    if args.gallery_fetch_album_images:
        utils.pretty_print(gallery2.fetch_album_images(args.album_name))

    if args.gallery_fetch_album_image_files:
        gallery2.fetch_album_image_files(args.album_name)

    if args.gallery_migrate_albums_to_koken:
        gallery2.migrate_albums(koken)

    if args.koken_create_album:
        print "created album: %s" % koken.create_album(args.album_name)

    if args.koken_upload_photo:
        print "uploaded photo: %s" % koken.upload_photo(
            args.upload_koken_photo)

    if args.koken_reset_album_date:
        koken.reset_album_date(args.reset_koken_album_date)
示例#13
0
def get_pruned_SANs_list(subdomain_list,ParentDomain,verbose):
	''' This function does two things:
	1. Eliminates those items in the SANs list that
		a. Do not contain the parent domain
		b. Have an asterisk wildcard in them
	2. After filtering the subdomains based on the criteria above,
	   returns a list of sanitized subdomains '''
	
	result_list = []

	for k in subdomain_list:

		
		
		SANs_list = get_SANs_from_cert(k)
		if verbose:
			utils.pretty_print("Getting SANs for " + str(k), len("Getting SANs for " + str(k)))
			print "SANs: ",
			print SANs_list
		if SANs_list is not None:
			for i in SANs_list:
 				if i != ParentDomain and ParentDomain in i and '*' not in i: # Get only those SANs that are non-wildcard/asterisk containing subdomains
 					result_list.append(i)
 					print i,
					print " [SAN Name]"
		if verbose:
			print "\n"
	return result_list
示例#14
0
    def calling_campaign(self):
        """ Function for Calling Campaign Filters """

        pretty_print("CALLING CAMPAIGN FILTER", "*")
        pretty_print("To access data BEFORE last contact date: 1", "-")
        pretty_print("To access data AFTER last contact date press: 2", "-")
        pretty_print("To access data with no last contact date press: 3", "-")
        index = get_int_input()

        if index == 1:
            date_input = input("Enter a date: Format MM/DD/YY \n")
            try:
                date = pd.to_datetime(date_input)
            except ValueError:
                print("ERROR: Enter a valid date: Format MM/DD/YY ...")
                return

            self.excel.compare_date_before(date)
            self.save_quit()

        if index == 2:
            date_input = input("Enter a date: Format MM/DD/YY \n")
            try:
                date = pd.to_datetime(date_input)
            except ValueError:
                print("ERROR: Enter a valid date: Format MM/DD/YY ...")
                return

            self.excel.compare_date_after(date)
            self.save_quit()

        if index == 3:
            pretty_print("Filtering", "_")
            self.excel.no_last_contact()
            self.save_quit()
示例#15
0
def configure_pycharm(mode="dev"):
    """
    Configures PyCharm.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nConfiguring PyCharm ...")
    append = \
        " | sudo tee --append " + PROJECT_DIR + "/devops/config/.pycharmrc\n"
    command = (
        "touch " + PROJECT_DIR + "/devops/config/.pycharmrc\n"
        "echo \"source ~/.bashrc\"" + append +
        "echo \"\"" + append +
        "echo \"source " + VIRTUALENV_DIR + "/bin/activate\"" + append +
        "echo \"\"" + append +
        "echo \"alias run_pep8='cd " + PROJECT_DIR + "/devops && "
        "invoke local_development_task run_pep8;'\"" + append +
        "echo \"alias run_docs='cd " + PROJECT_DIR + "/devops && "
        "invoke local_development_task run_docs;'\"" + append +
        "echo \"alias run_tests='cd " + PROJECT_DIR + "/devops && "
        "invoke local_development_task run_tests;'\"" + append +
        "echo \"alias run_grunt='cd " + PROJECT_DIR + "/devops && "
        "invoke local_development_task run_grunt;'\"" + append +
        "echo \"alias run_server='cd " + PROJECT_DIR + "/devops && "
        "invoke local_development_task run_server;'\"" + append
    )
    return command
示例#16
0
def show_last_tips(mode="dev"):
    """
    Shows some steps that have to be done manually at the end.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nAutomatic setup is done. Do the following manually ...")
    command = (
        "echo '1) Open your virtual machine with user=pass="******" and set the language of the keyboard'\n"
        "echo '2) Open PyCharm and log in with your JetBrains account'\n"
        "echo '3) Open the project with PyCharm and configure the following "
        "settings:\n"
        "   3.1) Editor\n"
        "       3.1.1) Code Style > Right margin (columns): 79\n"
        "       3.1.2) General > Appearance > Show line numbers\n"
        "   3.2) Project\n"
        "       3.2.1) Project Interpreter\n"
        "       3.2.2) Project Structure > Root, src and templates\n"
        "   3.3) Languages & Frameworks > Django > Enable and set root\n"
        "   3.4) Tools > Terminal > Shell Path: /bin/bash --rcfile " +
        PROJECT_DIR + "/devops/config/.pycharmrc"
        "'\n"
        "echo '4) Restart PyCharm and press ALT+F12 to open a terminal'"
    )
    return command
示例#17
0
def create_postgresql_user_and_db(mode):
    """
    Generates the commands needed to create the database and its owner.

    Args:
        mode(str): Must be either 'dev' or 'prod', or the program will exit.

    Returns(str): The command to be executed.
    """
    chosen_config = check_mode(mode)
    pretty_print("\nCreating postgresql user and database ...")
    command = (
        "sudo -u postgres psql -c \\\"DROP DATABASE IF EXISTS " +
        chosen_config.DB_NAME + ";\\\" &&"
        "sudo -u postgres psql -c \\\"DROP ROLE IF EXISTS " +
        chosen_config.DB_USER + ";\\\" &&"
        "sudo -u postgres psql -c \\\"CREATE USER " +
        chosen_config.DB_USER + " WITH PASSWORD '" +
        chosen_config.DB_PASSWORD + "';\\\" &&"
        "sudo -u postgres psql -c \\\"CREATE DATABASE " +
        chosen_config.DB_NAME + " OWNER " +
        chosen_config.DB_USER + ";\\\" &&"
        "sudo -u postgres psql -c \\\"ALTER USER " +
        chosen_config.DB_USER + " CREATEDB;\\\""
    )
    return command
示例#18
0
def get(client, dataset, pathElts, resType="gd"):
    ''' Returns a query on a path element
    resType can be gd - generator dict
                   gl - generator list
                   nd  - dict
                   nl  - list'''
    if "d" in resType.lower():
        result = {}
    else:
        result = []
    query = [create_query([(pathElts, [])], dataset)]
    for batch in client.get(query):
        for notif in batch["notifications"]:
            if debug:
                pretty_print(notif["updates"])
            if "d" in resType.lower():
                result.update(notif["updates"])
            elif "l" in resType.lower():
                result.append(notif["updates"])
            else:
                return (f"Unknown resType: {resType}")
    if "g" in resType.lower():
        yield result
    elif "n" in resType.lower():
        return result
    else:
        return (f"Unknown resType: {resType}")
示例#19
0
 def handle_scope_message(self, msg):
     message = STP_MSG % (msg[SERVICE], msg[COMMAND], msg[STATUS], msg[TAG], msg[PAYLOAD])
     if self.debug:
         pretty_print("send to client:",
                      msg,
                      self.debug_format,
                      self.debug_format_payload)
     self.send_message(message)
示例#20
0
 def view_sql_start(self, view_name):
     # view_name = viewnameify(
     #     view_name, self.table_prefix, self.translations)
     pretty_print(f"Making View {view_name}", True)
     return (
         f"CREATE OR REPLACE VIEW {self.db_schema}.\"{view_name}\"\n\tAS\n"
         "\tSELECT\n"
         "\t\t" + self.primary_key + " AS " + self.primary_key + ",\n")
示例#21
0
 def recognize(self, path):
    figure = parse(path, '*')
    res = self.netw.recognize(normalize(figure))
    if res[0]:
        print "%s[ok] in %d iters" % (path, res[2])
        pretty_print(denormalize(res[1], self.m, self.n))
    else:
        print "%s[fail]" % path
        pretty_print(denormalize(res[1], self.m, self.n))
示例#22
0
    def looping(self):
        """ Function to loop again """

        pretty_print("To Exit enter: 101", ":")
        pretty_print("To continue press any number key:", ":")
        decision = get_int_input()

        if decision == 101:
            self.again = False
示例#23
0
 def handle_connect_client(self, msg):
     if self.debug and not self.debug_only_errors:
         pretty_print("client connected:", msg, self.debug_format, self.debug_format_payload)
     if msg[SERVICE] == "scope" and msg[COMMAND] == 3 and msg[STATUS] == 0:
         self.handle_stp1_msg = self.handle_stp1_msg_default
         self.connect_client_callback()
         self.connect_client_callback = None
     else:
         print "conection to host failed in scope.handle_connect_callback"
示例#24
0
def prepare_data(input_train, input_test, num_neighbors, num_points):
    utils.pretty_print("PREPARING THE DATA...")
    scaled_laplacian_train = prepare_graph(input_train, num_neighbors,
                                           num_points)
    scaled_laplacian_test = prepare_graph(input_test, num_neighbors,
                                          num_points)
    utils.save_numpy([scaled_laplacian_train, scaled_laplacian_test],
                     ['scaled_laplacian_train', 'scaled_laplacian_test'])
    return scaled_laplacian_train, scaled_laplacian_test
示例#25
0
    def get_ordered_zero(self):
        self.zero = None
        self.firste = None
        self.le = None
        res = []
        for g in self.curr._globals:
            gstr = pretty_print_str(g)
            if gstr == "zero":
                gt = g.symbol_type()
                assert (gt in self._enumsorts)
                domain = self._enumsorts[gt]
                eq = EqualsOrIff(g, domain[0])
                res.append(eq)
                self.zero = (domain[0], g)
            elif gstr == "firste":
                gt = g.symbol_type()
                assert (gt in self._enumsorts)
                domain = self._enumsorts[gt]
                eq = EqualsOrIff(g, domain[1])
                res.append(eq)
                self.firste = (domain[1], g)

        for pre in self.curr._le:
            pret = pre.symbol_type()
            orderedt = pret.param_types[0]
            if orderedt in self._enumsorts:
                self._ordered_sorts[orderedt] = pre
                self.le = pre
                domain = self._enumsorts[orderedt]
                #                 end = 2
                end = len(domain)
                for i in range(end):
                    for j in range(i, end):
                        arg1 = domain[i]
                        arg2 = domain[j]
                        rel1 = Function(pre, [arg1, arg2])
                        rel2 = Function(pre, [arg2, arg1])
                        if (i == j):
                            res.append(rel1)
                        elif (i < j):
                            res.append(rel1)
                            res.append(Not(rel2))
                        elif (i > j):
                            res.append(Not(rel1))
                            res.append(rel2)
                        else:
                            assert (0)

        if len(res) == 0:
            return TRUE()
        else:
            print("\nZero axiom: ")
            for v in res:
                print("\t", end="")
                pretty_print(v)
            return And(res)
示例#26
0
def run_file(f):
	sections,factory_defs = section(f.readlines())

	if DETAILED_DEBUG:
		print("sections=",sections)
		print("factory defs=",factory_defs)

	global_constants = parse_constants(sections[0])
	global_rules = parse_rules(sections[1])

	global env
	env = standard_env()
	env = import_special(env,sections[2])

	internal_facts = []
	if DETAILED_DEBUG:
		print("global rules =",global_rules)
		print("global constants = ",global_constants,'\n')

	for f_name, (f_constants,f_rules,f_imports)in zip(factory_defs.keys(),factory_defs.values()):
		if DETAILED_DEBUG:
			print("-"*10 + "setting up factory f_name=",f_name,"-"*10)
		const = parse_constants(f_constants,True)
		#print(f_constants)
		rules = parse_rules(f_rules,True)
		#env = utils.add_factory(env,f_name)
		if DETAILED_DEBUG:
			print("factory constants",const)
			print("factory rules",rules,'\n')
		#uhh not sure what to do about the env right now...
		#probably just don't allow local only imports?

		#create the portable factory
		facts, storage, in_out_ports = generate_encap_IR(rules,const, internal_facts) #F**K IT CAN'T RECURSE IF I DO IT LIKE THIS F**K FUCKFUCKITY F**K
		#print("list of internal factories",facts)
		if DETAILED_DEBUG:
			utils.pretty_print(facts,storage)
			print("internal factory is waiting for ",in_out_ports['in'])
			print("internal factory is sending to ",in_out_ports['out'],'\n')
			print("-"*40)

		internal_fact = {
			'name':f_name+"()",
			'in_id':in_out_ports['in'],
			'out_id':in_out_ports['out']
		}
		internal_facts.append(internal_fact)

		env[f_name] = (facts,storage,in_out_ports),1,True

	#print("list of internal facts:",internal_facts)

	global_facts,global_storage = generate_IR(global_rules,global_constants, internal_facts)

	print("-"*10+"starting evalutation"+"-"*10)
	eval(global_facts,global_storage)
示例#27
0
    def save_quit(self):
        """ Function to save and quit """

        file_name = get_file_name()
        self.excel.save(file_name)
        for log in self.excel.stack:
            pretty_print(log, "/")

        pretty_print(f"File Saved as {file_name}_(date).xlsx", ":")
        raise SystemExit
示例#28
0
    def school_filter(self):
        """ Function to filter through school """

        pretty_print("SCHOOL FILTER", "*")
        pretty_print("To get SOB Applications press: 1", "-")
        pretty_print("To get SES Applications press: 2", "-")
        pretty_print("To get SSE Applications press: 3", "-")
        pretty_print("To continue press any number key:", "-")
        school_options = get_int_input()
        self.excel.school_info(school_options)
示例#29
0
def main(apiserverAddr, token=None, certs=None, key=None, ca=None):
    pathElts = ["DatasetInfo", "Devices"]
    query = [create_query([(pathElts, [])], "analytics")]

    with GRPCClient(apiserverAddr, token=token, key=key, ca=ca,
                    certs=certs) as client:
        for batch in client.get(query):
            for notif in batch["notifications"]:
                pretty_print(notif["updates"])
    return 0
示例#30
0
 def send_command_STP_1(self, msg):
     if self.debug and not self.debug_only_errors:
         pretty_print("send to host:", msg, self.debug_format, self.debug_format_payload)
     stp_1_cmd = STP1_COMMAND % (encode_varuint(len(msg[SERVICE])), msg[SERVICE],
                                 encode_varuint(msg[COMMAND]),
                                 encode_varuint(msg[FORMAT]),
                                 encode_varuint(msg[TAG]),
                                 encode_varuint(len(msg[PAYLOAD])), msg[PAYLOAD])
     self.out_buffer += STP1_MSG % (encode_varuint(len(stp_1_cmd)), stp_1_cmd)
     self.handle_write()
示例#31
0
def connect_to_db(url):
    try:
        engine = create_engine(url)
        engine.connect()
        pretty_print("Connected to DB", True)
        return engine
    except Exception as e:
        print("ERROR! Unable to Connect to database with", url)
        print(e)
        return False
示例#32
0
 def handle_connect_client(self, msg):
     if self.debug and not self.debug_only_errors:
         pretty_print("client connected:", msg, self.debug_format,
                      self.debug_format_payload)
     if msg[SERVICE] == "scope" and msg[COMMAND] == 3 and msg[STATUS] == 0:
         self.handle_stp1_msg = self.handle_stp1_msg_default
         self.connect_client_callback()
         self.connect_client_callback = None
     else:
         print "conection to host failed in scope.handle_connect_callback"
示例#33
0
def setup_db():
    try:
        engine = create_engine(DB_URL)
        engine.connect()
        pretty_print(f"Connected to DB at {DB_URL}", True)
        return engine
    except Exception as e:
        print("ERROR! Unable to Connect to database with", DB_URL)
        print(e)
        return False
def get(client, dataset, pathElts):
    ''' Returns a query on a path element'''
    result = {}
    query = [create_query([(pathElts, [])], dataset)]

    for batch in client.get(query):
        for notif in batch["notifications"]:
            if debug:
                pretty_print(notif["updates"])
            result.update(notif["updates"])
    return result
示例#35
0
def match_next(opcode, conn):
    received_bytes = conn.recv(2)
    expected_bytes = constant_to_bytes(opcode)

    if received_bytes != expected_bytes:
        logger.error("Unexpected opcode: "
                     "expected {}, received {}".format(
                         pretty_print(expected_bytes),
                         pretty_print(received_bytes)))
    else:
        pass  # logger.info("Received expected opcode {}".format(opcode))
示例#36
0
def install_unity(mode="dev"):
    """
    Installs Unity.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling Unity ...")
    command = "sudo apt-get -y install ubuntu-desktop"
    return command
示例#37
0
文件: transfer.py 项目: mrkgnao/refl
def match_next(opcode, conn):
    received_bytes = conn.recv(2)
    expected_bytes = constant_to_bytes(opcode)

    if received_bytes != expected_bytes:
        logger.error("Unexpected opcode: "
                     "expected {}, received {}"
                     .format(
                      pretty_print(expected_bytes),
                      pretty_print(received_bytes)))
    else:
        pass  # logger.info("Received expected opcode {}".format(opcode))
示例#38
0
def install_virtualenv(mode=None):
    """
    Generates the commands needed to install virtualenv.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling virtualenv ...")
    command = "sudo apt-get -y install python-virtualenv"
    return command
示例#39
0
def install_ruby_and_sass(mode="dev"):
    """
    Installs front-end packages.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling ruby and sass ...")
    command = "sudo su -c 'gem install sass'"
    return command
示例#40
0
def update_repositories(mode=None):
    """
    Generates the commands needed to update the repositories.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nUpdating repositories ...")
    command = "sudo apt-get -y update"
    return command
示例#41
0
 def send_command_STP_1(self, msg):
     if self.debug and not self.debug_only_errors:
         pretty_print("send to host:", msg, self.debug_format,
                      self.debug_format_payload)
     stp_1_cmd = STP1_COMMAND % (
         encode_varuint(len(msg[SERVICE])), msg[SERVICE],
         encode_varuint(msg[COMMAND]), encode_varuint(
             msg[FORMAT]), encode_varuint(
                 msg[TAG]), encode_varuint(len(msg[PAYLOAD])), msg[PAYLOAD])
     self.out_buffer += STP1_MSG % (encode_varuint(
         len(stp_1_cmd)), stp_1_cmd)
     self.handle_write()
示例#42
0
def install_supervisor(mode="prod"):
    """
    Generates the commands needed to install supervisor.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling supervisor ...")
    command = "sudo apt-get -y install supervisor"
    return command
示例#43
0
def setup_development_machine():
    """
    Creates remotely a new ubuntu virtual machine ready to work on the project.

    Returns:
        None
    """
    try:
        print()
        info_print("You need to have Vagrant installed in your host machine.")
        warning_print(
            "This process will clean all data on your previous virtual "
            "machine and build it again from scratch."
        )
        option = input("Do you want to continue? (y/n)\n")
        if option != "y" and option != "Y":
            sys.exit()
        t0 = time.time()
        pretty_print("\nCleaning previous installation ...")
        os.chdir("vagrant")
        run("vagrant destroy --force")
        run("vagrant box update")
        run("vagrant up")
        os.chdir("../")
        remote_development_task("update_repositories")
        remote_development_task("create_app_group_and_user")
        remote_development_task("install_postgresql")
        remote_development_task("create_postgresql_user_and_db")
        remote_development_task("install_jpeg_libraries_for_pillow")
        remote_development_task("install_git")
        remote_development_task("download_project")
        remote_development_task("install_virtualenv")
        remote_development_task("create_virtualenv")
        remote_development_task("export_project_keys")
        remote_development_task("install_python_requirements")
        remote_development_task("make_migrations")
        remote_development_task("migrate")
        remote_development_task("install_npm_and_grunt")
        remote_development_task("install_npm_packages")
        remote_development_task("install_ruby_and_sass")
        remote_development_task("install_unity")
        remote_development_task("create_test_data")
        remote_development_task("install_pycharm")
        remote_development_task("configure_pycharm")
        os.chdir("vagrant")
        run("vagrant halt")
        os.chdir("../")
        local_development_task("show_last_tips")
        t1 = time.time()
        show_time(t0, t1)
    except KeyboardInterrupt:
        error_print("Process aborted. Bye!")
        sys.exit()
示例#44
0
def n_permute_r(n, r, circular=False):
    elements = LETTERS[:n]
    perm_evol_dict = {0: elements}

    pretty_print(n, 1, len(perm_evol_dict[0]), perm_evol_dict[0])

    for i in range(1, r):
        perm_evol_dict[i] = \
            two_list_permutation(perm_evol_dict[i - 1], elements,
                                 circular=circular)

        pretty_print(n, i + 1, len(perm_evol_dict[i]), perm_evol_dict[i])
示例#45
0
def setup_schema(engine, schema):
    with engine.connect() as conn:
        has_schema = conn.execute(
            text(
                f"SELECT schema_name FROM information_schema.schemata WHERE schema_name = '{schema}';"
            ))

        if not has_schema.scalar():
            conn.execute(CreateSchema(schema))

        conn.execute(DropSchema(schema, None, True))
        conn.execute(CreateSchema(schema))
        pretty_print(f"Created Schema {schema}", True)
示例#46
0
    def get_ordered_le(self):
        self.reset_ordered_sort()
        for g in self.curr._globals:
            gstr = pretty_print_str(g)
            print(gstr)
            if gstr == "zero":
                gt = g.symbol_type()
                if gt in self._enumsorts:
                    self._ordered_min[gt] = g
            elif gstr == "max":
                gt = g.symbol_type()
                if gt in self._enumsorts:
                    self._ordered_max[gt] = g
        res = []
        for pre in self.curr._le:
            pret = pre.symbol_type()
            orderedt = pret.param_types[0]
            if orderedt in self._enumsorts:
                self._ordered_sorts[orderedt] = pre
                domain = self._enumsorts[orderedt]
                for i in range(len(domain)):
                    for j in range(i, len(domain)):
                        arg1 = domain[i]
                        arg2 = domain[j]
                        rel1 = Function(pre, [arg1, arg2])
                        rel2 = Function(pre, [arg2, arg1])
                        if (i == j):
                            res.append(rel1)
                        elif (i < j):
                            res.append(rel1)
                            res.append(Not(rel2))
                        elif (i > j):
                            res.append(Not(rel1))
                            res.append(rel2)
                        else:
                            assert (0)

#                 for i in range(len(domain)-1, 0, -1):
#                     arg1 = domain[i]
#                     arg2 = domain[i-1]
#                     rel = Function(pre, [arg1, arg2])
#                     res.append(Not(rel))

        if len(res) == 0:
            return TRUE()
        else:
            print("\nOrdering axiom: ")
            for v in res:
                print("\t", end="")
                pretty_print(v)
            return And(res)
示例#47
0
def get_emails(print_list, email_dict):
    """ Function to get emails """

    email_list = []
    again = True
    contact_table = PrettyTable()
    contact_table.field_names = ["Command", "Advisor Name", "Email"]

    for row in print_list:
        contact_table.add_row(row)

    while again:
        print(contact_table)
        pretty_print(email_list, ":")
        pretty_print("To Add Receiving Emails Enter the corresponding command number", "-")
        pretty_print("To Send Mail press any number key:", "-")
        choice = get_int_input()
        if choice in email_dict.keys():
            email_list.append(email_dict[choice])

        else:
            if len(email_list) != 0:
                again = False

            else:
                again = True
                pretty_print("No Email Added", "-")

        clear()

    return email_list
示例#48
0
 def handle_scope_message(self, msg):
     message = '["%s",%s,%s,%s,%s]' % (
         msg[1], # service
         msg[2], # command
         msg[4], # status
         msg[5], # tag
         msg[8], # payload
     )
     if self.debug:
         pretty_print("send to client:", 
                       msg, 
                       self.debug_format, 
                       self.debug_format_payload)
     self.send_message(message)
def main(apiserverAddr, dId, token=None, certs=None, ca=None, key=None):
    pathElts = [
        "Sysdb", "interface", "status", "eth", "phy", "slice", "1",
        "intfStatus",
        Wildcard()
    ]
    query = [create_query([(pathElts, ["active"])], dId)]

    with GRPCClient(apiserverAddr, token=token, key=key, ca=ca,
                    certs=certs) as client:
        for batch in client.get(query):
            for notif in batch["notifications"]:
                pretty_print(notif["updates"])
    return 0
示例#50
0
    def save_quit(self):

        if len(self.not_called_list) != 0:
            not_called_df = pd.DataFrame(self.not_called_list,
                                         columns=self.col)
            not_called_df.to_excel(f"{self.ga_name}-not-called.xlsx",
                                   index=False)
            pretty_print(
                f"Excel File with Not Called Students Data Saved as {self.ga_name}-not-called.xlsx",
                "-")

        if len(self.called_list) != 0:
            called_df = pd.DataFrame(self.called_list, columns=self.col)
            called_df.to_excel(f"{self.ga_name}-called.xlsx", index=False)
            pretty_print(
                f"Excel File with Called Students Data Saved as {self.ga_name}-called.xlsx",
                "-")

        if len(self.no_answer_list) != 0:
            no_answer_df = pd.DataFrame(self.no_answer_list, columns=self.col)
            no_answer_df.to_excel(f"{self.ga_name}-no-answer.xlsx",
                                  index=False)
            pretty_print(
                f"Excel File with No Answers Saved as {self.ga_name}-no-answer.xlsx",
                "-")

        if len(self.decline_list) != 0:
            decline_df = pd.DataFrame(self.decline_list, columns=self.col)
            decline_df.to_excel(f"{self.ga_name}_declines.xlsx", index=False)
            pretty_print(
                f"Excel File with Declines saved as {self.ga_name}_declines.xlsx",
                "-")

        raise SystemExit
示例#51
0
def run_grunt(mode="dev"):
    """
    Launches grunt task manager.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nRunning grunt ...")
    command = (
        "cd " + PROJECT_DIR + "\n"
        "grunt start"
    )
    return command
示例#52
0
def run_pep8(mode="dev"):
    """
    Checks for pep8 syntax errors. Empty output means everything is ok.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nChecking for pep8 syntax errors ...")
    command = (
        "cd " + PROJECT_DIR + "\n"
        "flake8 .\n"
    )
    return command
示例#53
0
def install_npm_packages(mode="dev"):
    """
    Installs front-end packages.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling npm packages ...")
    command = (
        "cd " + PROJECT_DIR + "\n"
        "sudo npm install"
    )
    return command
示例#54
0
def install_nginx(mode="prod"):
    """
    Generates the commands needed to install nginx.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling nginx ...")
    command = (
        "sudo apt-get -y install nginx\n"
        "sudo service nginx start"
    )
    return command
示例#55
0
def install_jpeg_libraries_for_pillow(mode=None):
    """
    Generates the commands needed to configure jpeg libs for Pillow package.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling jpeg libraries for pillow ...")
    command = (
        "sudo apt-get -y install libjpeg8-dev\n"
        "test -f /usr/lib/libjpeg.so || "
        "sudo ln -s /usr/lib/x86_64-linux-gnu/libjpeg.so /usr/lib"
    )
    return command
示例#56
0
def install_pycharm(mode="dev"):
    """
    Installs PyCharm.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling PyCharm ...")
    command = (
        "sudo add-apt-repository -y ppa:mystic-mirage/pycharm\n"
        "sudo apt-get -y update\n"
        "sudo apt-get -y install pycharm"
    )
    return command
示例#57
0
def update_project(mode):
    """
    Generates the commands needed to update the project from github.

    Args:
        mode(str): Must be either 'dev' or 'prod', or the program will exit.

    Returns(str): The command to be executed.
    """
    chosen_config = check_mode(mode)
    pretty_print("\nUpdating the project ...")
    command = (
        "cd " + chosen_config.PROJECT_DIR + "\n"
        "git pull origin master"
    )
    return command
示例#58
0
def create_virtualenv(mode):
    """
    Generates the commands needed to create the virtual environment.

    Args:
        mode(str): Must be either 'dev' or 'prod', or the program will exit.

    Returns(str): The command to be executed.
    """
    chosen_config = check_mode(mode)
    pretty_print("\nCreating virtualenv ...")
    command = (
        "virtualenv --no-site-packages -p /usr/bin/python3.4 " +
        chosen_config.VIRTUALENV_DIR
    )
    return command
示例#59
0
def install_postgresql(mode=None):
    """
    Generates the commands needed to install postgresql.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling postgresql ...")
    command = (
        "sudo apt-get -y install build-essential postgresql "
        "postgresql-client postgresql-doc postgresql-contrib pgadmin3 "
        "libpq-dev python-dev python3-dev python3.4-dev"
    )
    return command
示例#60
0
def install_git(mode=None):
    """
    Generates the commands needed to install git.

    Args:
        mode(str): It's irrelevant here.

    Returns(str): The command to be executed.
    """
    pretty_print("\nInstalling git ...")
    command = (
        "sudo apt-get -y install git\n"
        "git config --global user.email '*****@*****.**'\n"
        "git config --global user.name 'Carlos Ruiz Lantero Server'"
    )
    return command