コード例 #1
0
ファイル: main.py プロジェクト: shumitu/15-puzzle-solver-SISE
def use_dfs(initial_state, order, solution_filename, additional_filename):
    dfs = Dfs(initial_state, order)
    result = dfs.run_search()

    print_result(result)

    save_final_data(result, solution_filename, additional_filename)
コード例 #2
0
    def startup(self):
        # Initialization
        self.dfs = Dfs()

        self.main_window = toga.MainWindow(title=self.name, size=(1366, 720))
        self.main_container = toga.SplitContainer(
            style=Pack(flex=1, padding=(0, 5, -62, 5)),
            direction=toga.SplitContainer.HORIZONTAL,
        )
        self.search_results_table = toga.Table(
            headings=["Name", "Size", "Hash"],
            on_select=self.download,
            data=[])
        self.logs_table = toga.Table(headings=["Category", "Detail"], data=[])
        self.search_query_input = toga.TextInput(placeholder="Search Query",
                                                 style=Pack(flex=1))
        box = toga.Box(
            children=[
                toga.Box(
                    children=[
                        self.search_query_input,
                        toga.Button(
                            "Search",
                            on_press=self.search,
                            style=Pack(width=80, padding_left=5),
                        ),
                    ],
                    style=Pack(direction=ROW,
                               alignment=CENTER,
                               padding=(70, 5, 5, 5)),
                ),
                self.main_container,
            ],
            style=Pack(direction=COLUMN),
        )
        self.main_container.content = [
            self.search_results_table, self.logs_table
        ]
        add_file_cmd = toga.Command(
            self.share,
            label="Add File",
            tooltip="Select file to share",
            icon=Path("./res/icons/baseline_add_black_18dp.png").absolute(),
        )
        add_folder_cmd = toga.Command(
            self.share,
            label="Add Folder",
            tooltip="Select folder to share",
            icon=Path("./res/icons/baseline_add_black_18dp.png").absolute(),
        )
        # self.commands.add(add_file_cmd)
        self.main_window.toolbar.add(add_file_cmd, add_folder_cmd)
        self.main_window.content = box
        self.main_window.show()
コード例 #3
0
ファイル: loop.py プロジェクト: tlhallock/billiardview
def listen_for_commands(mock_commands=None, mock_image_paths=None):
    gopro = create_gopro(mock_image_paths)
    r = sr.Recognizer()
    m = sr.Microphone(device_index=8)

    dfs = Dfs(gopro)

    if mock_commands is not None:
        mic = MockMicrophone(mock_commands)
        while mic.has_next():
            mock_command = mic.next_cmd()
            print(mock_command)
            dfs.receive(mock_command, mic.next_cmd)
        return

    for index, name in enumerate(sr.Microphone.list_microphone_names()):
        print(
            "Microphone with name \"{1}\" found for `Microphone(device_index={0})`"
            .format(index, name))

    try:
        print("A moment of silence, please...")
        with m as source:
            r.adjust_for_ambient_noise(source)
            print("Set minimum energy threshold to {}".format(
                r.energy_threshold))
        while True:
            print("Listening...")
            with m as source:
                audio = r.listen(source)
                print("Processing...")
                try:
                    value = '{}'.format(r.recognize_google(audio))
                    print(value)
                    if not dfs.receive(value, get_next_text(r, source)):
                        break
                except sr.UnknownValueError:
                    print("Oops! Didn't catch that")
                except sr.RequestError as e:
                    print(
                        "Uh oh! Couldn't request results from Google Speech Recognition service; {0}"
                        .format(e))
    except KeyboardInterrupt:
        pass
コード例 #4
0
ファイル: bfs.py プロジェクト: TheTweak/algs
            v = edge_to_v
        path.reverse()
        return path

if __name__ == "__main__":
    import time
    parser = argparse.ArgumentParser()
    parser.add_argument("-size", default=16, help="Grid size", type=int)
    parser.add_argument("-bs", default=3, help="Grid obstacle block size", type=int)
    args = parser.parse_args()
    s = time.time()
    grid = Grid(w=args.size, h=args.size, block_size=args.bs)
    print("Grid creation: %s s" % (time.time() - s))
    s = time.time()
    adjacent = Adjacent(grid.data)
    print("Adjacent structure: %s s" % (time.time() - s))
    s = time.time()
    dfs = Dfs(grid.data, adjacent=adjacent)
    print("Dfs: %s s" % (time.time() - s))
    bottom_right = len(grid.data)*len(grid.data[0])-1
    if not dfs.connected(bottom_right):
        print("Bottom right corner is not reachable")
        exit(1)
    s = time.time()
    bfs = Bfs(grid.data, adjacent=adjacent)
    shortest_path = bfs.shortest_path(bottom_right)
    print("Shortest path: %s s" % (time.time() - s))
    for v in shortest_path:
        grid.set_cell_color(v=v, color=[255, 255, 0])
    grid.show()
コード例 #5
0
ファイル: propDFA.py プロジェクト: Gaebuidhe/CSCE355Pr
r1.set_statesNo(int(flDfa.readline()[18:-1]))

r1.set_accepting(flDfa.readline()[18:-1])

r1.set_alphabet(flDfa.readline()[10:-1])

tempStates = []
for i in range(0, r1.statesNo):
    tempStates.append(flDfa.readline()[0:-1])

r1.set_states(tempStates)
flDfa.close()

# sets up reachable states from 0
depth = Dfs(r1.states, r1.accepting)
reachable = depth.DFS(0)

# determines if accepting states are reachable
for i in range(0, len(list(r1.accepting))):
    tempaccepting = list(r1.accepting)
    if tempaccepting[i] in reachable:
        properties = properties + "nonempty"
        empNonemp = True  # if true dfa is nonempty
        break
    if i == (len(r1.accepting) - 1):
        properties = properties + "empty"

# determines if there is a cycle that reaches a finalstate
# if there is a cycle and start reaches final state declares infinite
if empNonemp and depth.isCyclic():
コード例 #6
0
ファイル: scc.py プロジェクト: rmallermartins/graphun
 def execute(self, G):
     dfs = Dfs()
     dfs.executeNormal(G)
     G.buildTranspGraph()
     dfs.executeTransp(G)
     self.printScc(G, dfs.getSccList())
コード例 #7
0
class DfsApp(toga.App):
    def startup(self):
        # Initialization
        self.dfs = Dfs()

        self.main_window = toga.MainWindow(title=self.name, size=(1366, 720))
        self.main_container = toga.SplitContainer(
            style=Pack(flex=1, padding=(0, 5, -62, 5)),
            direction=toga.SplitContainer.HORIZONTAL,
        )
        self.search_results_table = toga.Table(
            headings=["Name", "Size", "Hash"],
            on_select=self.download,
            data=[])
        self.logs_table = toga.Table(headings=["Category", "Detail"], data=[])
        self.search_query_input = toga.TextInput(placeholder="Search Query",
                                                 style=Pack(flex=1))
        box = toga.Box(
            children=[
                toga.Box(
                    children=[
                        self.search_query_input,
                        toga.Button(
                            "Search",
                            on_press=self.search,
                            style=Pack(width=80, padding_left=5),
                        ),
                    ],
                    style=Pack(direction=ROW,
                               alignment=CENTER,
                               padding=(70, 5, 5, 5)),
                ),
                self.main_container,
            ],
            style=Pack(direction=COLUMN),
        )
        self.main_container.content = [
            self.search_results_table, self.logs_table
        ]
        add_file_cmd = toga.Command(
            self.share,
            label="Add File",
            tooltip="Select file to share",
            icon=Path("./res/icons/baseline_add_black_18dp.png").absolute(),
        )
        add_folder_cmd = toga.Command(
            self.share,
            label="Add Folder",
            tooltip="Select folder to share",
            icon=Path("./res/icons/baseline_add_black_18dp.png").absolute(),
        )
        # self.commands.add(add_file_cmd)
        self.main_window.toolbar.add(add_file_cmd, add_folder_cmd)
        self.main_window.content = box
        self.main_window.show()

    def share(self, widget):
        target_type = widget.label.split()[1].lower()
        print(f"_{target_type}_")
        try:
            if target_type == "folder":
                target = self.main_window.select_folder_dialog("Select Folder")
            else:
                target = self.main_window.save_file_dialog(
                    "Select File", "none")
            print(f"Sharing {target}")
            if self.dfs.share(target):
                self.main_window.info_dialog(
                    "Success!", f"Shared {target} successfully!!")
            self.log(f"Shared {target_type}", target)
        except ValueError:
            self.error(f"No {target_type} selected!")

    def download(self, table, row):
        print(f"Downloading {row.name}")
        if self.main_window.confirm_dialog(
                "Confirm Download", f"Do you want to download {row.name}?"):
            self.log("Download started", row.name)
            try:
                self.dfs.download(row.hash, row.name)
            except:
                self.error(f"Failed to download {row.name}!")
                self.log("Download failed", row.name)
                traceback.print_exc()
            self.log("Download completed", row.name)

    def search(self, widget):
        try:
            subprocess.check_output(CONNECT_COMMAND,
                                    shell=True,
                                    stderr=open(os.devnull, "w"))
        except:
            self.error("No peers found!")
        self.search_results_table.data = []
        query = self.search_query_input.value
        print(f"Searching for {query}")
        self.log("Searched for", query)
        search_results = self.dfs.search(query)
        print(f"\n\nresults: {search_results}\n\n")
        # TODO: Handle duplicates.
        for search_result in search_results:
            self.search_results_table.data.append(search_result["name"],
                                                  search_result["size"],
                                                  search_result["hash"])
        self.log("Search results",
                 f"{len(search_results)} results for {query}")

    def error(self, message):
        self.main_window.error_dialog("Error!", message)

    def log(self, category, detail):
        self.logs_table.data.append(category, detail)
コード例 #8
0
def dfs_worker(single_list):
    res_dfs = [(Dfs(single_state, order).run_search(), order)
               for order in direction_orders for single_state in single_list]
    return res_dfs
コード例 #9
0
def test_share():
    # TODO: complete this
    dfs_instance = Dfs()
    test_path = os.path.abspath("test/test_dir")
    dfs_instance.share(test_path)
    dfs_instance.cleanup(TEST_LIFE)
コード例 #10
0
def test_download(file_hash):
    dfs_instance = Dfs()
    ss = dfs_instance.download(file_hash, "hello.txt")
    print(ss)
コード例 #11
0
def test_search(query):
    dfs_instance = Dfs()
    results = dfs_instance.search(query)
    print(results)
    dfs_instance.cleanup(TEST_LIFE)