Exemple #1
0
def main():


    #main variables initalization
    args = Arguments()
    #polynomial

    controller = InputString('none')


    #beginning
    args.x = 2.0
    loop = 6
    #main game loop
    #print interface
    #ask for input
    #perform action
    #compute currency
    while controller.command is not 'stop':
        #print interface
        print_interface(args)
        print_polynomial(args)

        #asks for input
        print('')
        input_str = input('Controller:')
        controller.generate_command(input_str)

        actions(args,controller)

        #Time advances by itself now
        args.adv_time()
        args.currency += args.polynomial.compute_polynomial(args.x)
Exemple #2
0
def main():
    """ The main() function that starts the scraper. """
    iata_from = input('Enter depart city: ')
    iata_to = input('Enter arrive city: ')
    dep_date = input('Enter depart date (YYYY-MM-DD): ')
    ret_date = input("Enter return date (YYYY-MM-DD) or don't: ")
    arg = Arguments(iata_from, iata_to, dep_date, ret_date)
    marker = False
    choice = input('\nEnter "1" for Search flight' ' or "2" for Help: ')
    while marker is False:
        if choice == '1':
            args = arg.parse_arguments()
            start_scr = StartScraping(args.IATA_FROM, args.IATA_TO,
                                      args.DEP_DATE, args.RET_DATE)
            start_scr.print_flight_info()
            marker = True
        elif choice == '2':
            arg.print_help_info()
            action = input('\nDo you want to search flights? \n'
                           'Enter "y" for Search or '
                           'any character for Exit: ')
            if action == 'y':
                marker = False
                choice = '1'
            else:
                marker = True
        else:
            choice = input("\nYou didn't enter '1' or '2'. \n"
                           "Please re-enter: ")
    def __init__(self):

        self.arguments = Arguments()
        self.organization = self.arguments.get_organization()
        self.query = self.arguments.get_search_query()

        self.fyle = Fyle()
        self.process_timer = ProcessTimer()
        self.github_search = GithubSearch(self.organization, self.query)
    def decode_arguments(self) -> 'Arguments':
        """
        Method for decoding the arguments collected by the parser into an instance of `Arguments`, and then
        calling the `Arguments` validate() method.

        :return: A validated instance of `Arguments` corresponding with the terminal inputs.
        """
        args = Arguments(self.parser.parse_args())
        args.validate()
        return args
Exemple #5
0
    def __init__(self, content):

        self.fyle = Fyle()
        self.arguments = Arguments()

        self.search_query = self.arguments.get_search_query()
        self.regex = self.format_regex()

        self.content = self.decode_base64(content)
        self.matches = []
    def __init__(self,
                 images_dir,
                 picture_amount_threshold,
                 feature_method_list,
                 row_threshold,
                 column_threshold,
                 picture_resolution,
                 label_threshold,
                 ground_truth_dir,
                 abs_flag,
                 log_flag,
                 grey_picture=False,
                 auto_canny=True,
                 auto_canny_sigma=0.33):

        saved_args = locals()
        Arguments.logArguments('FeatureDataSet', saved_args)

        self.create_grey_dir = False
        self.images_dir = images_dir
        self.picture_amount_threshold = picture_amount_threshold  # number of pictures
        self.grey_picture = grey_picture  # load picture as grey/color
        self.feature_method_list = feature_method_list  # list of feature extraction method
        self.row_threshold = row_threshold
        self.column_threshold = column_threshold
        self.picture_resolution = picture_resolution
        self.label_threshold = label_threshold  # min amount of label 1 percentage
        self.ground_truth_dir = ground_truth_dir  # dir of ground true pictures - extract only high class 1 percent
        self.abs_flag = abs_flag
        self.log_flag = log_flag

        self.images_pixel_dict = dict()  # contain images and their pixels
        self.images_name_list = list()  # contain pic name in data set
        self.X = list()  # list of ndarray - feature format
        self.X_sobelx = list()
        self.X_sobely = list()
        self.X_laplacian = list()
        self.X_canny = list()
        self.X_scharrx = list()
        self.X_scharry = list()
        self.X_sobelx_final = list()
        self.X_sobely_final = list()
        self.X_laplacian_final = list()
        self.X_canny_final = list()
        self.X_scharrx_final = list()
        self.X_scharry_final = list()

        self.auto_canny = auto_canny
        self.auto_canny_sigma = auto_canny_sigma
        if self.auto_canny_sigma < 0 or self.auto_canny_sigma > 1:
            raise 'Illegal value for auto Canny Sigma parameter - need to be 0<=..<=1'

        self.kepsilon = 1e-8

        return
    def __init__(self,
                 crf,
                 w,
                 image_name_list,
                 X,
                 ground_truth_dir,
                 pixel_frame,
                 evaluation_visualisation_flag,
                 dir_visualization_name,
                 model_name,
                 feature_data_set_obj,
                 baseline_features=None):

        saved_args = locals()
        del saved_args['X']  # preventing from logging
        Arguments.logArguments('Evaluate', saved_args)

        self.crf = crf
        self.w = w
        self.X = X
        self.image_name_list = image_name_list
        self.ground_truth_dir = ground_truth_dir
        self.pixels_frame = pixel_frame
        self.evaluation_visualisation_flag = evaluation_visualisation_flag
        self.dir_visualization_name = dir_visualization_name
        self.model_name = model_name

        self.baseline_features_dict = dict()
        if len(baseline_features) > 0:
            for f in baseline_features:
                attr = getattr(feature_data_set_obj, 'X_{}_final'.format(f))
                self.baseline_features_dict[f] = attr

        self.all_f1_avg = list()  # avg f1 (between all gt)
        self.all_f1 = list()  # max f1 (max per gt)
        self.all_recall = list()
        self.all_precision = list()

        self.all_super_f1_avg = list()
        self.all_super_f1 = list()
        self.all_super_recall = list()
        self.all_super_precision = list()

        self.canny_f1_avg = list()
        self.canny_f1 = list()
        self.canny_recall = list()
        self.canny_precision = list()

        self.canny_super_f1_avg = list()
        self.canny_super_f1 = list()
        self.canny_super_recall = list()
        self.canny_super_precision = list()
        return
Exemple #8
0
def main():
    __Arguments = Arguments()
    args = __Arguments.getArgs()

    __VHCreator = VHCreator(args.conf,args.directory)
    __VHCreator.addVirtualHost(args.servername)

    if(args.host):
        __VHCreator.addHostName(args.servername)

    if(args.repo):
        Git(args.repo,args.foldername,args.directory)
Exemple #9
0
def main():
    print("== DevOps: git-label ==\nCreate common label upon project setup.\n")

    args = Arguments()
    if not args.load(sys.argv[1:]):
        exit(0)
    if args.help:
        args.print_help()
        exit(0)

    github = GithubIssueCreator(args.github_token,
                                args.slug,
                                verbose=args.verbose)
    github.create_labels(args.labels)
    print("OK")
    def __init__(self, ground_truth_dir, images_name_list, row_threshold, column_threshold, X, pixels_frame):

        saved_args = locals()
        del saved_args['X']  # preventing from logging
        Arguments.logArguments('TargetDataSet', saved_args)
        self.ground_truth_dir = ground_truth_dir
        self.images_name_list = images_name_list
        self.row_threshold = row_threshold
        self.column_threshold = column_threshold
        self.pixels_frame = pixels_frame
        self.y = list()
        self.X = X

        self.delete_indexes = list()

        return
def show_rotated(load_path, args=None, indices='all'):
    '''
    ...
    Args:
        load_path:
        args:
        indices:

    Returns:

    '''
    if args is None:
        args = Arguments()
    for i, file in enumerate(os.listdir(load_path)):
        if file.endswith('.jpg') and (indices == 'all' or i in indices):
            file_path = os.path.join(load_path, file)
            img = processing.load_img(file_path)
            components = find_blobs(img, args)
            boxes = components.bboxes()
            stencil = components.get_stencil()
            angle, labels = correction_angle(components, args, False)
            rotated_img = rotate(img, angle * 180 / np.pi)
            plt.imshow(rotated_img)
            plt.grid(True)
            plt.show()
            get_rotation_corrected_blobs(components, angle, labels, args)
Exemple #12
0
    def eval_compare(self, node):
        """
        x < y > z is equivalent to (x < y) and (y > z), so the methods __lt__,
        __gt__, and __and__ and will need to be called for each appropriate
        instance.

        Returns:
            set[PyType]
        """
        left = node.left
        if len(node.ops) == 1:
            # Equivalent to just calling one of the comparison magic methods
            # No conjunctions
            return self.eval_single_compare(left, node.ops[0],
                                            node.comparators[0])

        results = set()
        comp_results = [
        ]  # Save the comparisons for testing the overall conjunction
        for i, op in enumerate(node.ops):
            right = node.comparators[i]
            comp_results.append(self.eval_single_compare(left, op, right))
            left = right

        # Perform the and-ing
        for i in range(len(comp_results) - 1):
            result_types = comp_results[i]  # set[pytype.Pytype]
            for t in result_types:
                results |= t.call_and(Arguments([comp_results[i + 1]]))

        return results
Exemple #13
0
    def _call_numeric_op(self, method, args, aug=False):
        from arguments import Arguments

        if aug:
            i_meth = self._imethod(method)
            return self.call_attr(i_meth, args)

        if self.has_attr(method):
            return self.call_attr(method, args)
        else:
            # Get the reflected magic method
            r_meth = self._rmethod(method)

            # Get the right side typs
            pos_args = args.pos_args()
            if len(pos_args) != 1:
                raise RuntimeError("Expected 1 argument for numeric operation")
            right_types = pos_args.pop()

            results = set()
            for t in right_types:
                if t.has_attr(r_meth):
                    results |= t.call_attr(r_meth, Arguments([self]))
                else:
                    raise RuntimeError("No support for {} or {} on types '{}' and '{}'".format(method, r_meth, self, t))
            return results
def get_rescaled_chars(components, args=None, separate_lines=False):
    '''
    ...
    Args:
        components:
        args:
        separate_lines:

    Returns:

    '''

    if args is None:
        args = Arguments()
    char_res = args.input_shape

    angle, labels = correction_angle(components, args, False)
    lines = get_rotation_corrected_blobs(components, angle, labels, args)

    rescaled_lines = []
    for line in lines:
        n_chars = len(line)
        chars = np.empty((n_chars, char_res, char_res), dtype=np.float32)
        for i, char in enumerate(line):
            chars[i] = processing.rescale(char, args)
        rescaled_lines.append(chars)

    if separate_lines:
        return rescaled_lines
    else:
        return np.concatenate(rescaled_lines, axis=0)
Exemple #15
0
    def __init__(self, default_params_filename='params.yaml', *args, **kwargs):
        # Extend the dictionary with the values passed in arguments.
        # Call the Dictionary constructor once the parameters file is set.
        arguments = Arguments(args, kwargs)
        if arguments.args.config_file is not None:
            parameters_file = arguments.args.config_file[0]
        else:
            parameters_file = default_params_filename
        super().__init__(parameters_file, **kwargs)

        if arguments.args.file is not None:
            setattr(self, 'file', arguments.args.file[0])
        else:
            setattr(self, 'file', None)
        setattr(self, 'symbol', arguments.args.symbol[0])

        #
        # Set log_level and start the logger
        #
        setattr(self, 'log_level',
                arguments.args.debug[0] if arguments.args.debug is not None \
                    else 3)
        if 'log_level' not in self:
            self.log_level = 3  # default value = WARNING
        self.log = Logger(self.log_level)

        self.log.info(
            'Using configuration parameters from: {}'.format(parameters_file))
Exemple #16
0
 def get_args(self, kwargs={}):
     args = {}
     args.update(self.extra_args)
     args.update(kwargs)
     return Arguments(self._species,
                      self._geometry,
                      self._numerical,
                      extra_args=args)
Exemple #17
0
def main():
    args = Arguments.get_arguments()
    rsa = RSACalc(args.pprime, args.qprime)
    user_text = get_input_from_user()
    text_to_list = list(user_text)
    print(f'List of Characters ={text_to_list}')
    cipher = encrypt_input(text_to_list, rsa)
    separator = " "
    print(f'your cipher is: {separator.join(map(str, cipher))}')
Exemple #18
0
    def __init__(self, X, y, learners, learners_parameters, models, models_parameters, total_label_one_avg, row_threshold):

        saved_args = locals()
        del saved_args['X']     # preventing from logging
        del saved_args['y']     # preventing from logging
        Arguments.logArguments('Model', saved_args)

        self.X = X
        self.y = y
        self.learners = learners
        self.learners_parameters = learners_parameters
        self.models = models
        self.models_parameters = models_parameters
        self.total_label_one_avg = total_label_one_avg
        self.row_threshold = row_threshold              # needed to define graph model

        self.total_accuracy_list = list()               # each image and relevance accuracy
        return
Exemple #19
0
    def eval_bin_op_from_types(self, left, op, right, aug=False):
        results = set()
        if isinstance(op, ast.Add):
            for t in left:
                results |= t.call_add(Arguments([right]), aug=aug)
        elif isinstance(op, ast.Sub):
            for t in left:
                results |= t.call_sub(Arguments([right]), aug=aug)
        elif isinstance(op, ast.Mult):
            for t in left:
                results |= t.call_mul(Arguments([right]), aug=aug)
        elif isinstance(op, ast.Div):
            for t in left:
                results |= t.call_truediv(Arguments([right]), aug=aug)
        else:
            raise NotImplementedError(
                "No logic for handling operation {}".format(op))

        return results
Exemple #20
0
def main():
    parser = Arguments.create_parser()
    args = parser.parse_args()
    arguments = Arguments(args.json, args.patterns, args.inference,
                          args.services, args.progress, args.output)

    sonarwan = SonarWan(arguments)
    sonarwan.run(args.files)
    sonarwan.print_info()
    logger.info('SonarWAN ended succesfully')
def interface():
    '''provides a terminal interface to execute the read function with an image path.
    It prints out the result in the terminal and optionally extracts an IBAN.'''

    path = input(
        'please provide a path to an image containing text relative to this directory [example]\n> '
    )
    if path == '':
        path = ('example.jpg')
    while not os.path.exists(path):
        path = input(
            'This path doesn\'t exist. please provide a valid one [example]\n> '
        )

    args = Arguments()
    img = load_img(path, args)

    results = read(img, args)
    out = ''
    for line in results:
        out += line + '\n'

    print('\nFrom the provided image the following could be read:\n')
    print(out)

    get_iban = input('Do you want to extract an IBAN? y/n? [y] > ')

    if get_iban == 'y' or get_iban == '':
        ibans = detect_iban.find_iban(out)
        if len(ibans) == 0:
            print('No IBAN could be extracted.')
        elif len(ibans) == 1:
            copy = input(
                'found the following IBAN: {} \n Do you want to copy it y/n? [y] > '
                .format(ibans[0]))
            if copy == '' or copy == 'y':
                pyperclip.copy(ibans[0])
                print('\nCopied {} to the clipboard'.format(ibans[0]))
        else:
            print('\nThe following IBANs were found:')
            for i, iban in enumerate(ibans):
                print(i, ':', iban)
            idx = input(
                '\nIf you want to copy any of these type its number > [0]')
            if idx == '':
                pyperclip.copy(ibans[0])
                print('\nCopied {} to the clipboard'.format(ibans[0]))
            elif int(idx) in range(len(ibans)):
                pyperclip.copy(ibans[int(idx)])
                print('\nCopied {} to the clipboard'.format(ibans[int(idx)]))
            else:
                print('\nThe input was not understood.')

    print('\nexit')
Exemple #22
0
 def eval_single_compare(self, left, op, right):
     """
     Perform a comparison on a single node
     """
     results = set()
     left_types = self.eval(left)
     right_types = self.eval(right)
     if isinstance(op, ast.Eq):
         for t in left_types:
             results |= t.call_eq(Arguments([right_types]))
     elif isinstance(op, ast.Lt):
         for t in left_types:
             results |= t.call_lt(Arguments([right_types]))
     elif isinstance(op, ast.In):
         for t in left_types:
             results |= t.call_contains(Arguments([right_types]))
     else:
         raise NotImplementedError(
             "No logic for comparing with operation {}".format(op))
     return results
Exemple #23
0
    def eval_subscript(self, node):
        key_types = self.eval(node.slice)
        values = self.eval(node.value)

        ret_types = set()
        for value in values:
            args = Arguments([key_types])
            print(args)
            print(value)
            ret_types |= value.call_getitem(args)
        return ret_types
Exemple #24
0
def main():
    args = Arguments.get_arguments()
    rsa = RSACalc(args.pprime, args.qprime)
    private_key = rsa.private_key
    public_key = rsa.public_key

    cipher_string = get_input_from_user()
    raw_cipher_list = cipher_string.split()  # get rid of commas
    clean_cipher_list = convert_str_list_to_int_list(raw_cipher_list)
    decrypted_str = decrpyt_cipher(clean_cipher_list, private_key, public_key,
                                   rsa)
    print(f'is this your string?: {decrypted_str}')
def generate_char_data(load_path, args=None):
    '''
    ...
    '''
    if args is None:
        args = Arguments()

    if args.method == 'threshold':
        method = blob_extraction.find_blobs
    elif args.method == 'mser':
        method = mser_extraction.extract_mser
    else:
        assert False

    # load alphabet
    char_dict = args.char_dict

    # load truth
    with open(os.path.join(load_path, 'truth.txt')) as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    truth_blocks = []
    current_block = []
    for line in content:
        if line == '':
            truth_blocks.append(current_block)
            current_block = []
        else:
            current_block.append(
                np.array([char_dict[char] for char in line], dtype=np.int32))

    # process images
    char_images = []
    char_truths = []
    for i in range(args.n):
        file = str(i) + '.jpg'
        if file.endswith('.jpg'):
            file_path = os.path.join(load_path, file)
            img = processing.load_img(file_path, args)
            components = method(img, args)
            components = rotation_correct_and_line_order(components)
            chars = components.extract(args)

            # check if number of detected chars conicides with groundtruth
            diff = sum(len(line) for line in truth_blocks[i]) - len(chars)
            print(f'image {i}: #gt chars - #detected chars: {diff}')
            if diff == 0:
                char_images.append(chars)
                char_truths.append(np.concatenate(truth_blocks[i]))
                #print('image is valid')

    return np.concatenate(char_images, axis=0), np.concatenate(char_truths,
                                                               axis=0)
def save_char_data(args=None):
    '''...'''
    if args is None:
        args = Arguments()
    load_path = args.image_path
    save_path = args.train_path
    if not (os.path.exists(save_path)):
        os.mkdir(save_path)
    char_images, char_truth = generate_char_data(load_path, args)
    print(f'saving {len(char_truth)} images')
    np.save(os.path.join(save_path, 'images.npy'), char_images)
    np.save(os.path.join(save_path, 'gt.npy'), char_truth)
Exemple #27
0
    def __init__(self, default_params_filename='params.yaml', *args, **kwargs):

        # Extend the dictionary with the values passed in arguments.
        # Call the Dictionary constructor once the parameters file is set.
        arguments = Arguments(args, kwargs)
        if arguments.args.config_file is not None:
            parameters_file = arguments.args.config_file[0]
        else:
            parameters_file = default_params_filename
        super().__init__(parameters_file, *args)

        for possible_action in arguments.possible_actions:
            setattr(self, possible_action, False)
        setattr(self, arguments.args.action, True)

        # setattr(self, 'do_plot', arguments.args.plot)
        self.do_plot = arguments.args.plot
        self.save_predictions = arguments.args.save
        self.input_file = arguments.args.file[0]
        if arguments.args.window is not None:
            self.window_size = arguments.args.window[0]
        else:
            self.window_size = 10
        if arguments.args.epochs is not None:
            self.epochs = arguments.args.epochs[0]
        else:
            self.epochs = 1

        # Output filename specified
        if arguments.args.output is not None:
            self.output = arguments.args.output[0]
        else:
            self.output = None

        #
        # Extend the dictionary with custom meta-parameters
        #
        self.ohlc_tags = list(list(self.csv_dict.keys())[1:])

        #
        # Set log_level and start the logger
        #
        setattr(self, 'log_level',
                arguments.args.debug[0] if arguments.args.debug is not None \
                    else 3)
        if 'log_level' not in self:
            self.log_level = 3  # default value = WARNING
        self.log = Logger(self.log_level)

        self.log.info(
            'Using configuration parameters from: {}'.format(parameters_file))
Exemple #28
0
def main():
    print("== DevSecOps: ignore ==\nScan github repositories for misconfigured ignore files.\n")

    args = Arguments()
    if not args.load(sys.argv[1:]):
        exit(0)
    if args.help:
        args.print_help()
        exit(0)

    github = Github(args.github_token)
    crawler = GithubCrawler(github, args.organization)
    results = ScanResults()
    try:
        crawler.scan(results)
    except KeyboardInterrupt:
        print("\n\n*****************************\n[W] User aborted with CTRL-C.\n*****************************\n")
        pass
    Reporting(verbose=args.verbose).print(results)
    GitIssueCreator(github,
                    verbose=args.verbose,
                    create_issue=args.create_issue,
                    create_pr=args.create_pr).create_issues(results)
Exemple #29
0
    def __init__(self, args=None):
        '''initializes the NN.'''

        super(ConvolutionalNN, self).__init__()
        if args == None:
            args = Arguments()
        self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84,
                             63)  # 2 * 26 characters + 10 numbers + 1 trash
        self.fc4 = nn.Linear(63, len(
            args.alphabet))  # 26 characters + 10 numbers + 1 trash
Exemple #30
0
def main():
    options = Arguments().get_args()
    binary = Binary(options)

    exec_sections = binary.get_exec_sections()
    data_sections = binary.get_data_sections()

    gadgets = Gadgets(exec_sections, options)
    gadgets.pretty_print_gadgets()

    strings = Strings(exec_sections + data_sections)
    strings.pretty_print_strings()

    ropchain = Ropchain(gadgets.get_gadgets(), binary.get_data_section_offset())
    ropchain.pretty_print_chain()
Exemple #31
0
class Fyle:


    def __init__(self):

        self.arguments = Arguments()

        self.filename = self.arguments.get_organization()


    def write(self, content):

        file = open(f'{self.filename}.txt', 'a')
        file.write(f'{content}\n')  # python will convert \n to os.linesep
        file.close()
Exemple #32
0
def main():
    args = Arguments()
    with open('/home/pi/os/rover/config.json') as f:
        config = json.load(f)

    rover = Rover(config, args.bt_flag, args.xbox_flag, args.unix_flag)

    while True:
        try:
            rover.drive()
            time.sleep(0.1)

        except Exception as e:
            print e
            rover.cleanup()
            time.sleep(0.5)
            rover.connectController()
Exemple #33
0
def main():
    """!
    @brief Puts the bits and pieces together.
    Uses the available classes from the imported modules to carry
    out the functionality specified by the assignment. For more
    information, consult the enclosed documentation.
    """
    ### INITIATING NEEDED OBJECTS ###
    arguments = Arguments()
    arguments.get_args()
    parser = Parser()
    parser.get_all_filepaths(arguments.args_dict)
    ### END INITIATING NEEDED OBJECTS ###

    ### CLEANING THE OUTPUT FILE ###
    if arguments.args_dict['output_file'] is not None:
        try:
            open(arguments.args_dict['output_file'], 'w').close()
        except:
            sys.stderr.write('The output file ' + arguments.args_dict['output_file'] +
                             ' cannot be opened.')
            sys.exit(3)
    ### END CLEANING THE OUTPUT FILE ###

    ### GETTING THE FINAL NUMBER OF OCCURRENCES ###
    total_num = 0
    for file in parser.files_list:
        num = parser.process_file(file, arguments.args_dict)
        total_num += num
    ### END GETTING THE FINAL NUMBER OF OCCURRENCES ##

    ### ALIGNING THE TOTAL NUMBER ###
    total_text = 'CELKEM: '
    total_num_padding = ''
    total_padding = ''.join([' ' for s in range(parser.maxlen - len(total_text))])
    total_num_padding = ''.join([' ' for s in range(parser.maxlen_num - len(str(total_num)))])
    ### END ALIGNING THE TOTAL NUMBER ###

    ### SORTING THE RESULTS ###
    results = parser.result_strings
    results.sort()
    ### END SORTING THE RESULTS ###

    ### PRINTING THE SEMI-RESULTS ###
    for item in sorted(results):
        if arguments.args_dict['output_file'] is not None:
            with open(arguments.args_dict['output_file'], 'a', encoding='iso-8859-2') as output_file_handle:
                output_file_handle.write(item)
        else:
            sys.stdout.write(item)
    ### END PRINTING THE SEMI-RESULTS ###

    ### PRINTING THE TOTAL NUMBER ###
    if arguments.args_dict['output_file'] is not None:
        with open(arguments.args_dict['output_file'], 'a', encoding='iso-8859-2') as output_file_handle:
            output_file_handle.write(total_text + total_padding + total_num_padding + str(total_num) + '\n')
    else:
        if len(str(total_num)) == 2 and parser.maxlen_num != 1:
            sys.stdout.write(total_text + total_padding + ' ' + total_num_padding + str(total_num) + '\n')
        else:
            sys.stdout.write(total_text + total_padding + total_num_padding + str(total_num) + '\n')
    ### END PRINTING THE RESULTS ###

    if arguments.args_dict['output_file'] is not None:
        output_file_handle.close()
Exemple #34
0
def main():
    print(sys.argv)

    phi = 42.3583 * math.pi / 180
    lw = 0;

    a = Arguments(sys.argv)

    if a.has_errors():
        a.print_error()
        return

    if a.is_lat_given():
        phi = a.latitude * math.pi / 180

    if a.is_long_given():
        lw = a.longitude * math.pi / 180        

    if a.is_date_given():
        delta_t = a.date_arg - J2000_DATE
        d = delta_t.days - 1
        day_of_year = a.date_arg.timetuple().tm_yday - 1
        t0_utc = utils.t0_utc(d)
        lambda_s = orbit.lambda_s(t0_utc)
        cel_coords = celestial_coords.from_ecliptic_coords(lambda_s)
        delta = cel_coords[0]
        alpha = cel_coords[1]
        t_rise_utc = horizon_coords.t_rise_utc(cel_coords, phi, lw, t0_utc)
        t_set_utc = horizon_coords.t_set_utc(cel_coords, phi, lw, t0_utc)
        print_str = "day: " + str(day_of_year)
        print_str += ", sunrise: " + str(utils.hours(t_rise_utc)) + ":" + str(round(utils.minutes(t_rise_utc) + float(utils.seconds(t_rise_utc))/60, 3))
        print_str += ", sunset: " + str(utils.hours(t_set_utc)) + ":" + str(utils.minutes(t_set_utc)) + ":" + str(utils.seconds(t_set_utc))
        print(print_str) 
        return

    # Calculate rise set times for latitudes ranging from -65 to 65 degrees at 5 degree increments
    rs = [[]]
    for p in range(-13, 14):
        i = 0
        phi = (p * 5) * math.pi / 180
        rs.append([])
        while i < 366:
            delta_t = JAN_1_2012 - J2000_DATE + datetime.timedelta(1)*i
            d = delta_t.days
            t0_utc = utils.t0_utc(d)
            lambda_s = orbit.lambda_s(t0_utc)
            cel_coords = celestial_coords.from_ecliptic_coords(lambda_s)
            delta = cel_coords[0]
            alpha = cel_coords[1]
            t_rise_utc = horizon_coords.t_rise_utc(cel_coords, phi, lw, t0_utc)
            t_set_utc = horizon_coords.t_set_utc(cel_coords, phi, lw, t0_utc)
            date1 = J2000_DATE + delta_t
            
            rs_current = RiseSet(date1, t_rise_utc, t_set_utc)
            rs[p + 13].append(rs_current)
            day_of_year = date1.timetuple().tm_yday - 1
            print_str = str(rs_current.get_day_of_year())
            print_str += ", sunrise: " + str(utils.hours(t_rise_utc)) + ":" + str(round(utils.minutes(t_rise_utc) + float(utils.seconds(t_rise_utc))/60, 3))
            print_str += ", sunset: " + str(utils.hours(t_set_utc)) + ":" + str(round(utils.minutes(t_set_utc) + float(utils.seconds(t_set_utc))/60, 3))
            i = i + 1

    with open("rise_set_data.js", mode="w") as f:
        json.dump(rs, f, indent=2, cls=RiseSetUTCJsonEncoder)

    print("Calculated rise/set times, placed in rise_set_data.js.")