예제 #1
0
    def handle_input_files_disposition(self, disposition_type: int,
                                       sub_folder_name: str,
                                       descriptors: [FileDescriptor],
                                       console: Console):
        """
        Move the given files if the given disposition type requests it.
        Return a list of any files that were moved so the UI can be adjusted if necessary

        :param disposition_type:        Code for what to do with file after processing
        :param sub_folder_name:         Where to put file if we're moving it
        :param descriptors:             List of files for potential processing
        :param console:                 Redirectable console output option
        """
        if disposition_type == Constants.INPUT_DISPOSITION_NOTHING:
            # User doesn't want us to do anything with the input files
            return
        else:
            assert (disposition_type == Constants.INPUT_DISPOSITION_SUBFOLDER)
            console.message("Moving processed files to " + sub_folder_name, 0)
            # User wants us to move the input files into a sub-folder
            for descriptor in descriptors:
                if SharedUtils.dispose_one_file_to_sub_folder(
                        descriptor, sub_folder_name):
                    # Successfully moved the file;  tell the user interface
                    self.callback_method(descriptor.get_absolute_path())
예제 #2
0
 def __init__(self, output_callback: Callable[[str], None]):
     """
     Initialize this object by remembering the callback function for output messages
     :param output_callback:     Function to be called to output a message
     """
     Console.__init__(self)
     self._output_callback = output_callback
예제 #3
0
 def calibrate_with_file(
         self, file_data: [ndarray], calibration_file_path: str,
         console: Console,
         session_controller: SessionController) -> [ndarray]:
     """
     Calibrate given set of images by subtracting a fixed image file from each.
     (clipping at zero - no negative pixel values will be produced)
     Given calibration file must be the same size as all the images to be calibrated.
     :param file_data:               List of images' data. Each is 2d image matrix
     :param calibration_file_path:   Full path to calibration file
     :param console:                 Redirectable console output object
     :param session_controller:      Controller for this subtask
     :return:                        List of calibrated images
     """
     console.message(f"Calibrate with file: {calibration_file_path}", 0)
     result = file_data.copy()
     calibration_image = RmFitsUtil.fits_data_from_path(
         calibration_file_path)
     (calibration_x, calibration_y) = calibration_image.shape
     for index in range(len(result)):
         if session_controller.thread_cancelled():
             raise MasterMakerExceptions.SessionCancelled
         (layer_x, layer_y) = result[index].shape
         if (layer_x != calibration_x) or (layer_y != calibration_y):
             raise MasterMakerExceptions.IncompatibleSizes
         difference = result[index] - calibration_image
         result[index] = difference.clip(0, 0xFFFF)
     return result
예제 #4
0
def main():
    crtDir = os.getcwd()
    filePath = os.path.join(crtDir, 'data', 'hardE.txt')
    Repo = Repository(filePath)
    Repo.read_tsp_format()
    Serv=Service(Repo)
    Cons=Console(Serv)
    Cons.print_info(100,100)
예제 #5
0
    def process_one_group(self, data_model: DataModel,
                          descriptor_list: [FileDescriptor],
                          output_directory: str, combine_method: int,
                          disposition_folder_name, console: Console):
        """
        Process one group of files, output to the given directory
        Exceptions thrown:
            NotAllFlatFrames        The given files are not all flat frames
            IncompatibleSizes       The given files are not all the same dimensions

        :param data_model:                  Data model giving options for current run
        :param descriptor_list:             List of all the files in one group, for processing
        :param output_directory:            Path to directory to receive the output file
        :param combine_method:              Code saying how these files should be combined
        :param disposition_folder_name:     If files to be moved after processing, name of receiving folder
        :param console:                     Re-directable console output object
        """
        assert len(descriptor_list) > 0
        sample_file: FileDescriptor = descriptor_list[0]
        console.push_level()
        self.describe_group(data_model, len(descriptor_list), sample_file,
                            console)

        # Make up a file name for this group's output, into the given directory
        file_name = SharedUtils.get_file_name_portion(
            combine_method, sample_file, data_model.get_sigma_clip_threshold(),
            data_model.get_min_max_number_clipped_per_end())
        output_file = f"{output_directory}/{file_name}"

        # Confirm that these are all flat frames, and can be combined (same binning and dimensions)
        if self.all_compatible_sizes(descriptor_list):
            if data_model.get_ignore_file_type() \
                    or FileCombiner.all_of_type(descriptor_list, FileDescriptor.FILE_TYPE_FLAT):
                # Get (most common) filter name in the set
                # Get filter name to go in the output FITS metadata.
                # All the files should be the same filter, but in case there are stragglers,
                # get the most common filter from the set
                filter_name = SharedUtils.most_common_filter_name(
                    descriptor_list)

                # Do the combination
                self.combine_files(descriptor_list, data_model, filter_name,
                                   output_file, console)
                self.check_cancellation()
                # Files are combined.  Put away the inputs?
                # Return list of any that were moved, in case the UI needs to be adjusted
                self.handle_input_files_disposition(
                    data_model.get_input_file_disposition(),
                    disposition_folder_name, descriptor_list, console)
                self.check_cancellation()
            else:
                raise MasterMakerExceptions.NotAllFlatFrames
        else:
            raise MasterMakerExceptions.IncompatibleSizes

        console.pop_level()
예제 #6
0
 def __init__(self):
     print "main"
     
     ecpu = Ecpu(Main.memory, Main.consoleRequests, Main.readyProcesses, Main.pcbs)
     ex = Exec(Main.memory, Main.partitions, Main.partitionLength, Main.pcbs, Main.readyProcesses)
     console = Console(Main.memory, Main.consoleRequests, ecpu)
     
     console.start()
     ecpu.start()
     ex.start()
예제 #7
0
def main(filename, second):
    c = Console(turnz=second)
    lst = []
    with open(filename) as f:
        for l in f.readlines():
            c.turn(l)

    ans = ""
    for num in c.code:
        ans += str(num)
    print "\nFirst Answer: %s" % ans
예제 #8
0
    def __init__(self):
        intro = '\nCBR tool\n'
        print intro
        Console.__init__(self)

        self.cases_flat = None
        self.cases_hierarchical = None
        self.memory = None
        self.solution = None
        self.label_name = None
        self.current_case = None
        self.K = 1
예제 #9
0
 def calibrate_with_auto_directory(self, file_data: [ndarray], auto_directory_path: str,
                                   sample_file: FileDescriptor, console: Console,
                                   session_controller: SessionController) -> [ndarray]:
     console.message(f"Selecting best calibration file from {auto_directory_path}", 0)
     calibration_file = self.get_best_calibration_file(auto_directory_path, sample_file,
                                                       session_controller)
     # Should never come back None because an exception will have handled failure
     assert calibration_file is not None
     if session_controller.thread_running():
         return self.calibrate_with_file(file_data, calibration_file, console, session_controller)
     else:
         return None
예제 #10
0
 def __init__(self) -> None:
     super().__init__()
     shipRepo0 = ShipRepo()
     shipRepo1 = ShipRepo()
     hitRepo = HitRepo()
     shipValidator = ShipValidator()
     hitValidator = HitValidator()
     shipService0 = ShipService(shipRepo0, shipValidator)
     shipService1 = ShipService(shipRepo1, shipValidator)
     gameService = GameService(shipRepo0, shipRepo1, hitRepo, shipValidator,
                               hitValidator)
     console0 = Console(shipService0, gameService)
     console1 = Console(shipService1, gameService)
예제 #11
0
 def calibrate_with_pedestal(self,
                             file_data: [ndarray],
                             pedestal: int,
                             console: Console,
                             session_controller: SessionController) -> [ndarray]:
     result = file_data.copy()
     console.message(f"Calibrate with pedestal = {pedestal}", 0)
     for index in range(len(result)):
         if session_controller.thread_cancelled():
             break
         reduced_by_pedestal: ndarray = result[index] - pedestal
         result[index] = reduced_by_pedestal.clip(0, 0xFFFF)
     return result
예제 #12
0
    def original_non_grouped_processing(self, selected_files: [FileDescriptor],
                                        data_model: DataModel,
                                        output_file: str, console: Console):
        console.push_level()
        console.message("Using single-file processing", +1)
        # We'll use the first file in the list as a sample for things like image size
        assert len(selected_files) > 0
        # Confirm that these are all dark frames, and can be combined (same binning and dimensions)
        if FileCombiner.all_compatible_sizes(selected_files):
            self.check_cancellation()
            if data_model.get_ignore_file_type() or FileCombiner.all_of_type(
                    selected_files, FileDescriptor.FILE_TYPE_DARK):
                # Get (most common) filter name in the set
                # Since these are darks, the filter is meaningless, but we need the value
                # for the shared "create file" routine
                filter_name = SharedUtils.most_common_filter_name(
                    selected_files)

                # Do the combination
                self.combine_files(selected_files, data_model, filter_name,
                                   output_file, console)
                self.check_cancellation()
                # Files are combined.  Put away the inputs?
                # Return list of any that were moved, in case the UI needs to be adjusted
                substituted_folder_name = SharedUtils.substitute_date_time_filter_in_string(
                    data_model.get_disposition_subfolder_name())
                self.handle_input_files_disposition(
                    data_model.get_input_file_disposition(),
                    substituted_folder_name, selected_files, console)
            else:
                raise MasterMakerExceptions.NotAllDarkFrames
        else:
            raise MasterMakerExceptions.IncompatibleSizes
        console.message("Combining complete", 0)
        console.pop_level()
예제 #13
0
 def calibrate_with_file(self, file_data: [ndarray], calibration_file_path: str, console: Console,
                         session_controller: SessionController) -> [ndarray]:
     console.message(f"Calibrate with file: {calibration_file_path}", 0)
     result = file_data.copy()
     calibration_image = RmFitsUtil.fits_data_from_path(calibration_file_path)
     (calibration_x, calibration_y) = calibration_image.shape
     for index in range(len(result)):
         if session_controller.thread_cancelled():
             break
         (layer_x, layer_y) = result[index].shape
         if (layer_x != calibration_x) or (layer_y != calibration_y):
             raise MasterMakerExceptions.IncompatibleSizes
         difference = result[index] - calibration_image
         result[index] = difference.clip(0, 0xFFFF)
     return result
예제 #14
0
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame,
                                 text='редактировать код',
                                 width=25,
                                 command=self.new_window)
        self.button2 = tk.Button(self.frame,
                                 text='поставить стены',
                                 width=25,
                                 command=self.get_diff_mode)
        self.button3 = Button(self.frame,
                              text='сброс',
                              width=25,
                              command=self.from_start)
        self.button4 = Button(self.frame,
                              text='переместить',
                              width=25,
                              command=self.get_repl_mode)

        self.button1.pack()
        self.button2.pack()
        self.button4.pack()
        self.frame.pack()
        self.conf_canvas()
        self.button3.pack()
        hero = get_img(self.canv, pos=(300, 420))
        self.hero = Hero(self.canv, hero)
        self.cons = Console(self.hero)
        self.cons.txt.pack(side='bottom')
        self.hero.console = self.cons
예제 #15
0
def main():
    # Main function for the game
    board, console = Board(), Console()
    console.print("Welcome to TicTacToe!")
    player1Name = console.input("Insert Player 1's name")
    player2Name = console.input("Insert Player 2's name")
    player1 = Player(player1Name, "O")
    player2 = Player(player2Name, "X")
    game = Game(player1, player2, board, console)
    tictactoe = Menu(game)
    tictactoe.game.resetGame()

    wantsToExit = False
    while not wantsToExit:
        tictactoe.print(*[
            "What would you like to do?", "a - Play TicTacToe!",
            "b - Change board layout", "c - Change Player's name and symbol",
            "d - Exit the game"
        ])
        command = tictactoe.input().lower()
        if command in ("a", "play"):
            tictactoe.game.resetGame()
            tictactoe.playTicTacToe()
        elif command in ("b", "board"):
            tictactoe.changeKeyLayout()
        elif command in ("c", "player"):
            tictactoe.changePlayerData()
        elif command in ("d", "exit"):
            tictactoe.print("Thanks for playing!")
            sleep(1)
            wantsToExit = True
        else:
            tictactoe.print("Wrong command.")
예제 #16
0
 def build(self):
     boxlayout = BoxLayout(orientation='vertical')
     logDir = "/home/sensys/work/sensys/tests/Console"
     logFile = "test.log"
     self.console = Console(logDir, logFile)
     boxlayout.add_widget(self.console)
     return boxlayout
예제 #17
0
 def handle_input_files_disposition(self, disposition_type: int,
                                    sub_folder_name: str,
                                    descriptors: [FileDescriptor],
                                    console: Console):
     if disposition_type == Constants.INPUT_DISPOSITION_NOTHING:
         # User doesn't want us to do anything with the input files
         return
     else:
         assert (disposition_type == Constants.INPUT_DISPOSITION_SUBFOLDER)
         console.message("Moving processed files to " + sub_folder_name, 0)
         # User wants us to move the input files into a sub-folder
         for descriptor in descriptors:
             if SharedUtils.dispose_one_file_to_sub_folder(
                     descriptor, sub_folder_name):
                 # Successfully moved the file;  tell the user interface
                 self.callback_method(descriptor.get_absolute_path())
예제 #18
0
    def __createLayout(self):
        # Zoom items. The only place where the zoom items are specified!
        # self.zitems = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2.0, 3.0, 4.0, 8.0]

        # Set up the model for the Model Editor
        self.modelEditorDock = self.__createDockWindow("ModelEditor")

        self.modelEditorDock.setToggleFcn(self.toggleModelEditor)
        modelEditor = ModelEditor(self.modelEditorDock)

        # TODO
        # self.model = SimModel(QDomDocument(), self.modelEditorDock) # Do I need parent self.modelEditorDock
        self.model = SimModel(
            None,
            self.modelEditorDock)  # Do I need parent self.modelEditorDock
        modelEditor.setModel(self.model)  # Set the default model
        modelEditor.setItemDelegate(SimDelegate(self))
        modelEditor.setParams()
        modelEditor.setSelectionBehavior(QAbstractItemView.SelectItems)
        self.viewmanager.setModelEditor(
            modelEditor)  # Sets the Model Editor in the ViewManager
        self.__setupDockWindow(self.modelEditorDock, Qt.LeftDockWidgetArea,
                               modelEditor, "Model Editor")  # projectBrowser

        self.latticeDataDock = self.__createDockWindow("LatticeData")
        self.latticeDataDock.setToggleFcn(self.toggleLatticeData)
        self.latticeDataModelTable = LatticeDataModelTable(
            self.latticeDataDock, self.viewmanager)
        self.latticeDataModel = LatticeDataModel()
        self.latticeDataModelTable.setModel(self.latticeDataModel)

        # # self.cplugins.latticeDataModelTable()
        # #self.connect(self.cplugins, SIGNAL("doubleClicked(const QModelIndex &)"), self.__showPluginView)
        #
        self.__setupDockWindow(self.latticeDataDock, Qt.LeftDockWidgetArea,
                               self.latticeDataModelTable, "LatticeDataFiles")
        self.setCorner(Qt.TopLeftCorner, Qt.LeftDockWidgetArea)

        # Set up the console
        self.consoleDock = self.__createDockWindow("Console")

        self.consoleDock.setToggleFcn(self.toggleConsole)

        self.console = Console(self.consoleDock)
        self.consoleDock.setWidget(self.console)
        # self.consoleDock.setWindowTitle("Console")
        self.__setupDockWindow(self.consoleDock, Qt.BottomDockWidgetArea,
                               self.console, "Console")
        # self.viewmanager.addWidget(self.consoleDock)
        # self.viewmanager.setSizes([400, 50])
        # self.consoleDock.show()

        # rec = self.console.geometry()
        # rec.setHeight(300)
        # print rec.height()
        # self.console.setGeometry(rec)
        # """
        # Don't know why I need dockwindows
        self.dockwindows = {}
예제 #19
0
 def describe_group(data_model: DataModel, number_files: int,
                    sample_file: FileDescriptor, console: Console):
     binning = sample_file.get_binning()
     exposure = sample_file.get_exposure()
     temperature = sample_file.get_temperature()
     processing_message = ""
     if data_model.get_group_by_size():
         processing_message += f"binned {binning} x {binning}"
     if data_model.get_group_by_exposure():
         if len(processing_message) > 0:
             processing_message += ","
         processing_message += f" exposed {exposure} seconds"
     if data_model.get_group_by_temperature():
         if len(processing_message) > 0:
             processing_message += ","
         processing_message += f" at {temperature} degrees."
     console.message(
         f"Processing {number_files} files {processing_message}", +1)
예제 #20
0
    def __init__(self, name, device=None):
        self.name = name
        self._channels = {}

        if device is None:
            from Console import Console
            device = Console()
        self.device = device

        return
예제 #21
0
    def __init__(self, default=None):
        if default is None:
            from Console import Console
            default = Console()

        Facility.__init__(self,
                          name="device",
                          default=default,
                          binder=self.DeviceBinder())
        return
예제 #22
0
    def closest_match(self, descriptors: [FileDescriptor],
                      target_exposure: float, target_temperature: float,
                      console: Console) -> FileDescriptor:
        """
        Find the calibration file, from the given list of candidates, that is the best match for calibrating
        an image with the given exposure and temperature.  We have already ensured that the candidate calibration
        files are all the correct size, so we now try to match both the exposure time and the temperature,
        giving more weight to the exposure time.

        :param descriptors:             Descriptions of potential calibration files
        :param target_exposure:         Exposure time of the image to be calibrated
        :param target_temperature:      CCD temperature of the image to be calibrated
        :param console:                 Redirectable console output object
        :return:                        Description of the best-matching calibration file
        """

        # Assign a score to each possible calibration file, based on exposure and temperature
        f: FileDescriptor
        file_temperatures = numpy.array(
            [f.get_temperature() for f in descriptors])
        file_exposures = numpy.array([f.get_exposure() for f in descriptors])
        scores = numpy.abs(file_temperatures - target_temperature) \
                 + numpy.abs(file_exposures - target_exposure) * Constants.AUTO_CALIBRATION_EXPOSURE_WEIGHT
        # The score is the deviation from the target, so the smallest score is the best choice
        minimum_score = numpy.min(scores)
        indices = numpy.where(scores == minimum_score)
        assert len(
            indices
        ) > 0  # Min was from the list, so there must be at least one
        match_index = indices[0].tolist()[0]
        best_match = descriptors[match_index]

        if self._data_model.get_display_auto_select_results():
            console.message(
                f"Target {target_exposure:.1f}s at {target_temperature:.1f} C,"
                f" best match is {best_match.get_exposure():.1f}s at"
                f" {best_match.get_temperature():.1f} C: "
                f"{best_match.get_name()}",
                +1,
                temp=True)

        return best_match
예제 #23
0
def remote(port, host="localhost", mode="udp"):

    if mode == "udp":
        from UDPDevice import UDPDevice
        device = UDPDevice(port, host)
    else:
        from Console import Console
        device = Console()

    journal().device = device
    return device
예제 #24
0
    def process_one_group(self, data_model: DataModel,
                          descriptor_list: [FileDescriptor],
                          output_directory: str, combine_method: int,
                          disposition_folder_name, console: Console):
        assert len(descriptor_list) > 0
        sample_file: FileDescriptor = descriptor_list[0]
        console.push_level()
        self.describe_group(data_model, len(descriptor_list), sample_file,
                            console)

        # Make up a file name for this group's output, into the given directory
        file_name = SharedUtils.get_file_name_portion(
            combine_method, sample_file, data_model.get_sigma_clip_threshold(),
            data_model.get_min_max_number_clipped_per_end())
        output_file = f"{output_directory}/{file_name}"

        # Confirm that these are all dark frames, and can be combined (same binning and dimensions)
        if self.all_compatible_sizes(descriptor_list):
            if data_model.get_ignore_file_type() \
                    or FileCombiner.all_of_type(descriptor_list, FileDescriptor.FILE_TYPE_DARK):
                # Get (most common) filter name in the set
                # Since these are darks, the filter is meaningless, but we need the value
                # for the shared "create file" routine
                filter_name = SharedUtils.most_common_filter_name(
                    descriptor_list)

                # Do the combination
                self.combine_files(descriptor_list, data_model, filter_name,
                                   output_file, console)
                self.check_cancellation()
                # Files are combined.  Put away the inputs?
                # Return list of any that were moved, in case the UI needs to be adjusted
                self.handle_input_files_disposition(
                    data_model.get_input_file_disposition(),
                    disposition_folder_name, descriptor_list, console)
                self.check_cancellation()
            else:
                raise MasterMakerExceptions.NotAllDarkFrames
        else:
            raise MasterMakerExceptions.IncompatibleSizes
        console.pop_level()
예제 #25
0
    def _getBuiltInDefaultValue(self, instance):
        
        import pyre.parsing.locators
        locator = pyre.parsing.locators.default()

        import sys
        if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
            from os import environ
            term = environ.get('TERM', 'console')
            component = instance.retrieveComponent(term, factory=self.family, vault=self.vault)
            if component is None:
                from Console import Console
                component = Console()
            else:
                component.aliases.append(self.name)
                locator = pyre.parsing.locators.chain(component.getLocator(), locator)
        else:
            from Stream import Stream
            component = Stream(sys.stdout, "stdout")

        return component, locator
예제 #26
0
    def calibrate_with_pedestal(
            self, file_data: [ndarray], pedestal: int, console: Console,
            session_controller: SessionController) -> [ndarray]:
        """
        'Pedestal-calibrate' given set of images by subtracting a fixed amounnt from each pixel
        (clipping at zero - no negative pixel values will be produced)
        :param file_data:           List of images' data. Each is 2d image matrix
        :param pedestal:            Fixed amount to subtract from each pixel
        :param console:             Redirectable console output object
        :param session_controller:  Controller for this subtask
        :return:                    List of calibrated images
        """

        result = file_data.copy()
        console.message(f"Calibrate with pedestal = {pedestal}", 0)
        for index in range(len(result)):
            if session_controller.thread_cancelled():
                raise MasterMakerExceptions.SessionCancelled
            reduced_by_pedestal: ndarray = result[index] - pedestal
            result[index] = reduced_by_pedestal.clip(0, 0xFFFF)
        return result
예제 #27
0
 def combine_median(cls, file_names: [str], calibrator: Calibrator,
                    console: Console,
                    session_controller: SessionController) -> ndarray:
     """
     Combine the files in the given list using a simple median
     Check, as reading, that they all have the same dimensions
     :param file_names:          Names of files to be combined
     :param calibrator:          Calibration object, abstracting precalibration operations
     :param console:             Redirectable console output handler
     :param session_controller:  Controller for this subtask, checking for cancellation
     :return:                    ndarray giving the 2-dimensional matrix of resulting pixel values
     """
     assert len(
         file_names
     ) > 0  # Otherwise the combine button would have been disabled
     console.push_level()
     console.message("Combine by simple Median", +1)
     descriptors = RmFitsUtil.make_file_descriptions(file_names)
     file_data = RmFitsUtil.read_all_files_data(file_names)
     cls.check_cancellation(session_controller)
     file_data = calibrator.calibrate_images(file_data, descriptors,
                                             console, session_controller)
     cls.check_cancellation(session_controller)
     median_result = numpy.median(file_data, axis=0)
     console.pop_level()
     return median_result
예제 #28
0
 def describe_group(data_model: DataModel, number_files: int,
                    sample_file: FileDescriptor, console: Console):
     """
     Display, on the console, a descriptive text string for the group being processed, using a given sample file
     :param data_model:      Data model giving the processing options
     :param number_files:    Number of files in the group being processed
     :param sample_file:     Sample file, representative of the characterstics of files in the group
     :param console:         Redirectable output console
     """
     binning = sample_file.get_binning()
     temperature = sample_file.get_temperature()
     message_parts: [str] = []
     if data_model.get_group_by_size():
         message_parts.append(f"binned {binning} x {binning}")
     if data_model.get_group_by_filter():
         message_parts.append(
             f"with {sample_file.get_filter_name()} filter")
     if data_model.get_group_by_temperature():
         message_parts.append(f"at {temperature} degrees")
     processing_message = ", ".join(message_parts)
     console.message(
         f"Processing {number_files} files {processing_message}.", +1)
예제 #29
0
    def __init__(self):
        self.instances_dict = OrderedDict([("Config", Config()),
                                           ("Console", Console()),
                                           ("Plugins", Plugins()),
                                           ("ProxyHandler", ProxyHandler()),
                                           ("ProxyMemory", ProxyMemory()),
                                           ("ClientHandler", ClientHandler()),
                                           ("Utils", Utils())])

        for instance in self.instances_dict:
            self.instances_dict[instance].set_instances(self.instances_dict)

        for instance in self.instances_dict:
            self.instances_dict[instance].run_on_start()
 def config(self):
     '''
     :return: The game settings
     '''
     ui = None
     oponent = None
     board = Board(int(self.__settings['width']),
                   int(self.__settings['height']))
     gm = GameManager(board, int(self.__settings['difficulty']))
     if self.__settings['ui'] == Constants.CONSOLE:
         ui = Console(gm)
     if self.__settings['ui'] == Constants.GUI:
         ui = GUI(gm)
     return ui
예제 #31
0
    def do_loadCase(self, arg):
        """
        Load a case to classify.

        loadCase                            Show loaded case
        loadCase manual <SL> <SW> <PL> <PW>    Load a case manually specifying the 4 values of a case
        loadCase automatic <file>           Load a case from a file
        """

        if arg in '':
            print 'Current Load Case:'
            try:
                self.load_case
            except AttributeError:
                print 'No case was loaded'
            else:
                print self.load_case
        elif len(arg) > 1:
            if 'manual' in arg:
                params = arg.split(' ')[1:]
                if len(params) == 4:
                    item = {
                        'SepalLength': params[0],
                        'SepalWidth': params[1],
                        'PetalLength': params[2],
                        'PetalWidth': params[3],
                        'IrisClass': 'null'
                    }
                    self.load_case = Case(item)
                else:
                    print 'Unrecognized Parameters'
                    Console.do_help(self, 'loadCase')

        else:
            print 'Unrecognized Parameters'
            Console.do_help(self, 'loadCase')
예제 #32
0
from Globals import *
from Console import Console
import os

# Initialize the console and go!
if __name__ == '__main__':
    if not os.path.exists(TEMP_DIR):
        os.makedirs(TEMP_DIR)
    logging.basicConfig(filename=LOGGER_FILENAME, 
                        format='[%(asctime)s][%(levelname)s]   %(message)s',
                        level=logging.DEBUG)
    logging.info("Logger started.")
    console = Console()
    console.init()
    console.run()
예제 #33
0
from ClientManager import ClientManager
from UpdateServer import UpdateServer
from AnimationManager import AnimationManager
from Config import Config
from Console import Console
from LedBulb import LedBulbs

if __name__ == "__main__":

    config = Config();

    try:
        animations = AnimationManager(config)

        ledBulbs = LedBulbs()
        console = Console(config, ledBulbs, animations)
        clients = ClientManager(config, console, animations, ledBulbs)
        update = UpdateServer(config)

        clients.run()

        try:
            update.run()
        except FileNotFoundError:
            # No update files found.
            pass

        console.start()

    except KeyboardInterrupt:
        os._exit(1)
예제 #34
0
 def __init__(self):
     # note that Python3 does not read the html code as string
     # but as html code bytearray, convert to string with
     self.maxTries = 5
     self.console = Console()
     print("Initialize Network")
예제 #35
0
def test_draw_score():
    c = Console()
    c.draw_score(5)
    assert c.score_line == '     5'
예제 #36
0
def test_draw_spare():
    c = Console()
    for i in range(4):
        c.draw_spare()
    assert c.pins_line == '  /  /  /  /'
예제 #37
0
	def __init__(self):
		self.webservice = Webservice
		self.console = Console()
		self.constants = Constants()
		self.started = False
		self.menu()
예제 #38
0
def test_draw_stirke():
    c = Console()
    for i in range(4):
        c.draw_strike()
    assert c.pins_line == '  X  X  X  X'
예제 #39
0
 def __init__(self, manga):
     self.downloadDirectory = "/media/DATA/Linux/personnel/Mangas"
     self.manga = manga
     self.mangaPretty = self.makePretty(manga)
     self.numberImage = 0
     self.console = Console()   
예제 #40
0
class Network:
    def __init__(self):
        # note that Python3 does not read the html code as string
        # but as html code bytearray, convert to string with
        self.maxTries = 5
        self.console = Console()
        print("Initialize Network")

    def getUrlContentUtf8(self, url):
        htmlByteArray = self.getUrlContent(url)
        return htmlByteArray.decode("utf8")

    def getUrlContent(self, url):
        """Returns the content of a webpage at the given url"""
        self.console.printNormal("Donwloading " + url)
        tries = 0
        downloaded = False
        while tries < self.maxTries and downloaded == False:
            try:
                ret = urllib.request.urlopen(url)
                downloaded = True
            except(IOError, socket.error):
                tries += 1
                if tries == self.maxTries:
                    self.console.printError("Maximum tries number reached exiting...")
                    exit(1)
                else:
                    self.console.printError("Failed download, retrying...")
                self.console.printError("Failed download, retrying...")
        self.console.printSuccess("Downloaded!")
        return ret.read()

    def downloadFile(self, url, localName):
        """Retrieves a file"""
        tries = 0
        downloaded = False
        while tries < self.maxTries and downloaded == False:
            try:
                urllib.request.urlretrieve(url, localName)
                downloaded = True
            except HTTPError as e:
                self.console.printError("HTTP Error:", e.code , url)
                tries += 1
            except URLError as e:
                self.console.printError("URL Error:", e.reason , url)
                tries += 1
            if(tries == self.maxTries):
                self.console.printError("Maximum tries number reached exiting...")
                exit(1)
                  
            self.console.printSuccess(url + " downloaded to " + localName)

#net = Network()
#net.downloadFile(http://i13.mangareader.net/7th-period-is-a-secret/2/7th-period-is-a-secret-402446.jpg"), "test.jpg")
예제 #41
0
def test_draw_frame_no():
    c = Console()
    for i in range(5):
        c.draw_index(i + 1)
    assert c.frame_no_line == '     1     2     3     4     5'
예제 #42
0
class Directory:
    def __init__(self, manga):
        self.downloadDirectory = "/media/DATA/Linux/personnel/Mangas"
        self.manga = manga
        self.mangaPretty = self.makePretty(manga)
        self.numberImage = 0
        self.console = Console()   
        
    def createDownloadDirectory(self, manga):
        # Create the download directory
        try:
            if (os.path.isdir(self.downloadDirectory) == False):
                os.mkdir(self.downloadDirectory)
            if (os.path.isdir(self.downloadDirectory + self.mangaPretty) == False):
                os.mkdir(self.downloadDirectory + self.mangaPretty)
        except OSError:
            self.console.printError("Unable to create the download directory")
            exit(1)
   
    def makePretty(self, name):
        """Returns the chain given, in order to have a normal name"""
        return str(name).capitalize().replace("/", "").replace("_", " ")

    def chapterDirectoryName(self, number):
        """Returns the name of the directory of the chapter.
           It is useful in order to organize the mass of chapters.
           example:
           500 chaps in the manga,��directory named "001" instead of "1" """
        number = str(number)
        return (mangaNumberLenght - len(number)) * "0" + number


        mangaDirectory = downloadDirectory + self.mangaPretty + "/" + self.chapterDirectoryNname(number)
        if (os.path.isdir(mangaDirectory) == False):
            os.mkdir(mangaDirectory)
        os.chdir(mangaDirectory)



    def lastChapter(self, mangaDirectory):
        """Return the last chapter directory of the manga"""
        return max(float(os.listdir(mangaDirectory)))

    def chapterMissing(self, mangaDirectory):
      """ Returns a list of local missing chapters """
      missing = []
      i = 1
      for chapter in os.listdir(mangaDirectory):
          if chapter != i or len(os.listdir(chapter)) == 0:
              missing = range(i, chapter) + missing
              i = chapter
          i += 1
      return missing



    def mangaDownloaded(self, mangaDirectory):
      """search if the manga directory exist"""
      for manga in os.listdir(downloadDirectory):
          if manga == mangaDirectory:
              return True
      print("The Manga does not exist in the directory!")
      return False
예제 #43
0
PRODUCT_VERSION = "1.01";

from Connection import Connection;
from Console import Console;
from time import time, sleep;
from threading import Thread, Timer;
from Settings import Settings;
import random;

print "Welcome to "+PRODUCT_NAME+" (version "+PRODUCT_VERSION+")";
print "Written and created by Matthew Kloster";
print "Command console ready. Send commands to cmd.txt.\n";

random.seed(time());

console = Console(PRODUCT_NAME+".log");
console.adjustDate(time());
console.sessionStart(time());

if (Settings.AUTO_CONNECT):
	console.createConnection();
	console.threads["connect"] = Thread(target=console.connection.IRCConnect);
	console.threads["connect"].setDaemon(1);
	console.threads["connect"].start();

while (console.active):
	fp = open("cmd.txt","r");
	command = fp.read();
	fp.close();
	command = command.replace("\n","");
	if (command != ""):
예제 #44
0
def test_draw_blank():
    c = Console()
    for i in range(4):
        c.draw_blank()
    assert c.pins_line == '            '
예제 #45
0
class Server:
	def __init__(self):
		self.webservice = Webservice
		self.console = Console()
		self.constants = Constants()
		self.started = False
		self.menu()
		
	def menu(self):
		while self.started == False:
			self.process(input("[" + datetime.datetime.fromtimestamp(time.time()).strftime('%H:%M:%S') + "] " + ">>: "))
			
	def process(self, cmd):
		cmds = cmd.split()
		action = cmds[0]
		parameter = -1
		if len(cmds) > 1:
			parameter = cmds[1]
		if action == "start":
			self.started = True
			self.start()
		elif parameter != -1:
			if action == "port":
				self.constants.port = int(parameter)
				self.console.output("Port set to: " + str(self.constants.port))
			elif action == "root":
				self.constants.root = str(parameter)
				self.console.output("Root directory set to: " + self.constants.root)
			elif action == "address":
				self.constants.address = str(parameter)
				self.console.output("Address set to: " + self.constants.address)
		else:
			self.console.output("Unknown command")
	
	def start(self):
		try:
			self.server = CustomHTTPServer(("127.0.0.1", self.constants.port), self.webservice, self.constants, self.console)
			self.console.output("Server started. Ctrl + C to stop.")
			self.console.output("Port: " + str(self.server.server_port))
			self.console.output("Address: " + self.constants.address)
			self.console.output("Root: " + self.constants.root)
			self.server.serve_forever()
		except KeyboardInterrupt:
			self.console.output("Server has stopped")
			self.menu()
예제 #46
0
def test_draw_pins():
    c = Console()
    for i in range(4):
        c.draw_pins(i + 1)
    assert c.pins_line == '  1  2  3  4'
예제 #47
0
import libtcodpy
import random
from Console import Console
from Panel import Panel


test = Console(20, 20, 'test')
test.set_fps(10)
ptest = Panel(0, 0, 20, 20)
ptest.set_default_foreground(libtcodpy.light_gray)
pshade = Panel(-1, -1, 10, 10)
random.seed(222)
fade = 0.1

while not test.is_window_closed:
    for x in range(0, 20):
        for y in range(0, 20):
            if random.randint(0, 2):
                ptest.write(x, y, '.')
                if not random.randint(0, 5):
                    ptest.set_default_background(libtcodpy.red)
                elif not random.randint(0, 5):
                    ptest.set_default_background(libtcodpy.blue)
                elif not random.randint(0, 5):
                    ptest.set_default_background(libtcodpy.yellow)
                else:
                    ptest.set_default_background(libtcodpy.black)
            else:
                ptest.write(x, y, '#')
                if not random.randint(0, 3):
                    ptest.set_default_foreground(libtcodpy.red)