コード例 #1
0
ファイル: Board.py プロジェクト: mittman/pycheckmate
    def ai_move(self, player):
        if player.id == "x":
            key = random.randint(0, 1)
            if key == 0 or "R" not in player.pieces:
                piece = player.pieces["K"]
            else:
                piece = player.pieces["R"]
        else:
            piece = player.pieces["K"]

        legal_moves = self.find_legal_moves(piece)

        ### if len(legal_moves) == 0: *CHECKMATE OR TIE* ###
        if len(legal_moves) == 0:
            File.prompt("game over")
            exit(0)
        if len(legal_moves) == 1:
            new_destination = legal_moves[0]
        else:
            new_destination = legal_moves[random.randint(0, len(legal_moves) - 1)]

            # move:
        self.make_move(player, piece, (new_destination[0], new_destination[1]))

        self.move_log = piece.player + piece.type + " to " + str(new_destination[0]) + "," + str(new_destination[1])
コード例 #2
0
ファイル: Index.py プロジェクト: csdms/cca-spec-babel
 def scanfile(self, filename):
     """Open a named file into symbol table"""
     if self.debug:
         print "INDEXING", filename
     rfile = File(filename)
     self.filelist[filename] = rfile
     rfile.domToSymtab(self. symtab)
     self.printIndex()
コード例 #3
0
ファイル: FileTestCase.py プロジェクト: tassia/DonkeySurvey
 def testInsert(self):
     fdao = FileDAO()
     file = File()
     file.hash = self.hash
     file.size = 555555 
     file.partialSize = 55555
     file.bestname = 'nomedoarquivonarede.ext'
     fid = fdao.insert(file)
     assert fid != -1, 'error inserting file'
コード例 #4
0
ファイル: Directory.py プロジェクト: bmi-forum/bmi-pyre
    def __init__(self, name, parent):
        File.__init__(self, name, parent)

        self._children = {}

        self._files = []
        self._subdirectories = []

        return
コード例 #5
0
ファイル: Sound.py プロジェクト: totorigolo/WiiQuizz
    def __init__(self, dirname):
        if dirname == 'ask':
            dirname = FSDialog.get_folder('./games/sounds/')
        dirname = "/games/sounds/" + dirname
        File.__init__(self, dirname)

        self.is_playing = False
        self.sound_changed()

        self.once = False
コード例 #6
0
def main():
	parser = argparse.ArgumentParser()
	parser.add_argument("input", type = str, help = "input file")
	parser.add_argument("ext1", type = str, help = "extension of input file")
	parser.add_argument("output", type = str, help = "output file")
	parser.add_argument("ext2", type = str, help = "extension of output file")
	parser.add_argument("-w", dest = "white_list", help = "set file witch keys needs to convert")
	parser.add_argument("-c", dest = "config_file", help = "file witch vaule needs to change")
	parser.add_argument("-v", dest = "det", action = "store_true", help = "high detalisation of procces")
	parser.add_argument("-vv", dest = "hdet", action = "store_true", help = "very high detalisation of procces")
	
	args = parser.parse_args()
	
	f = File(args.input, args.ext1)
	
	flag = str()
	if args.det == True:
		flag = "-v"
	elif args.hdet == True:
		flag = "-vv"

	f.make_dictionary(flag)

	if args.white_list != None:
		f.define_white_list(args.white_list, flag)
	if args.config_file != None:
		f.define_config_file(args.config_file, flag)
		
	f.convert_file_to(args.output, args.ext2, flag)
	
	if flag == "-v" or flag == "-vv":
		print "All done"
コード例 #7
0
ファイル: Board.py プロジェクト: mittman/pycheckmate
 def display(self):
     for p in self.player_x.pieces.values():
         self.state[p.row][p.col] = p.player + p.type
     for p in self.player_y.pieces.values():
         self.state[p.row][p.col] = p.player + p.type
     if self.move_log == "":
         self.state[0][3] = str(0)
     else:
         self.state[0][3] = str(self.player_x.turn)
     File.print("")
     File.print("\n".join("".join(["{:3}".format(item) for item in row]) for row in self.state))
コード例 #8
0
ファイル: Image.py プロジェクト: totorigolo/WiiQuizz
    def __init__(self, dirname):
        if dirname == 'ask':
            dirname = FSDialog.get_folder('./games/images/')
        dirname = "/games/images/" + dirname

        File.__init__(self, dirname)

        self.once = False
        self.showing = False
        self.is_paused = False
        self.image_changed()
 def __init__(self, directory_path, picture_destination_directory, movie_destination_directory):
     self.directory_path = File.check_directory_name(directory_path)
     self.picture_destination_directory = File.check_directory_name(picture_destination_directory)
     self.movie_destination_directory = File.check_directory_name(movie_destination_directory)
     self.directories = [ folder for folder in listdir(self.directory_path) if isdir(join(self.directory_path,folder)) ]
     self.directories.sort()
     self.file_count = 0
     self.files_copied = 0
     self.files_not_copied = 0
     self.files_with_date_found = 0
     self.files_without_date_found = 0
コード例 #10
0
ファイル: Dispatch.py プロジェクト: shaynekasai/cms
	def createRootPage(self, name):
		project_name = self.getProjectName()
		print "Adding a root page to %s" % project_name
		
		try:
			with open(project_name): 	
				objFile = File()
				objFile.createRootPage(name);
				
				
		except IOError:
			print 'Dang, make sure you\'re in the project folder'
コード例 #11
0
ファイル: Game.py プロジェクト: mittman/pycheckmate
	def parse_entry(self, entry, game, board, player_x, player_y, num):
		if re.match(r"x\.K\([1-8],[1-8]\)", entry):
			moveH, moveV = game.split_entry(entry)
			game.add_or_move(board, player_x, 'K', moveH, moveV, num)
		elif re.match(r"x\.R\([1-8],[1-8]\)", entry):
			moveH, moveV = game.split_entry(entry)
			game.add_or_move(board, player_x, 'R', moveH, moveV, num)
		elif re.match(r"y\.K\([1-8],[1-8]\)", entry):
			moveH, moveV = game.split_entry(entry)
			game.add_or_move(board, player_y, 'K', moveH, moveV, num)
		else:
			File.error("invalid entry from file")
コード例 #12
0
ファイル: Png.py プロジェクト: dburggie/pypng
 def read(self, ifname):
     """Returns new Png instance containing contents of png file on disk."""
     imagefile = File(ifname)
     chunks = imagefile.read()
     if len(chunks) != 3:
         print 'png file must consist exactly of',
         print 'IHDR, IDAT, and IEND chunks'
         return True
     for c in chunks:
         if self._parse_chunk(c):
             return True
     return False
コード例 #13
0
ファイル: Client.py プロジェクト: CristianDragu/Projects
def startTransfer():
  global users
  global transfers
  getUsers()
  User.printUsers(users)
  username = raw_input("From which user?").rstrip('\n')
  user = User.findUser(users, username)
  File.printFiles(user.files)
  filename = raw_input("Which file?").rstrip('\n')
  file = File.findFile(user.files, filename)
  transfer = Transfer(user, file)
  transfers.append(transfer)
  transfer.start()
コード例 #14
0
ファイル: Image.py プロジェクト: totorigolo/WiiQuizz
    def draw_on(self, page_label):
        """
        Affiche les éléments sur la page
        Appelé à chaque tour de boucle
        :param page_label:
        :return:
        """
        # Use the draw_on version of the parent
        File.draw_on(self, page_label)

        if not self.once:
            self.win.add('game_img_mgr_num_page', 50, 'bottom - 140', page=page_label)
            self.win.add('game_img_mgr_num_version', 50, 'bottom - 100', page=page_label)
            self.once = True
コード例 #15
0
ファイル: Game.py プロジェクト: mittman/pycheckmate
	def add_or_move(self, board, player, piece_id, moveH, moveV, num):
		if num == 1:
			new_piece = Piece(player, piece_id, moveH, moveV)
			if player.id == 'x':
				player.add_piece(new_piece)
			elif player.id == 'y':
				player.add_piece(new_piece)
			else:
				File.error("invalid player")
		else:
			if board.state[moveH][moveV] != player.id + piece_id:
				print('\n\n')
				File.prompt("MOVE " + player.id + piece_id + " to " + str(moveH) + "," + str(moveV))
				board.player_move(player, piece_id, moveH, moveV)
コード例 #16
0
 def _send_file(self, file_path):
     fields = [("apikey", self._key)]
     target_file = File(file_path)
     content = target_file.read()
     del target_file
     
     files = [("file", os.path.basename(file_path), content)]
     json_str = postfile.post_multipart(self._host, self._url_scan, fields, files)
     if json_str == '':
         return False
     data = json.loads(json_str)
     if data['response_code'] == 1:
         return True
     else:
         return False
コード例 #17
0
ファイル: MultipleOuts.py プロジェクト: totorigolo/WiiQuizz
    def process_event(self, event, page_label):
        File.process_event(self, event, page_label)

        if event.type == pg.USEREVENT and event.wiimote_id == 'master' and event.pressed:
            if event.btn == 'DROITE':
                self.next_file()
            elif event.btn == 'GAUCHE':
                self.prev_file()
            elif event.btn == 'HAUT':
                self.prev_version()
            elif event.btn == 'BAS':
                self.next_version()
            elif event.btn == '1':
                self.showing = not self.showing
                self.__draw_questions()
コード例 #18
0
ファイル: Board.py プロジェクト: mittman/pycheckmate
    def player_move(self, player, piece_id, new_row, new_col):
        hero, opponent = self.identify_players(player)
        piece = hero.pieces[piece_id]
        self.state[piece.row][piece.col] = "*"

        if piece_id == "K" and not self.tile_is_safe(opponent, new_row, new_col):
            print("\n")
            File.error("Illegal move.")
            self.state[piece.row][piece.col] = piece.player + piece.type
        elif not self.legal_move(piece, new_row, new_col):
            print("\n")
            File.error("Illegal move.")
            self.state[piece.row][piece.col] = piece.player + piece.type
        else:
            self.make_move(player, piece, (new_row, new_col))

        self.move_log = piece.player + piece.type + " to " + str(new_row) + "," + str(new_col)
コード例 #19
0
    def scan_file(self, file_path):
        target_file = File(file_path)
        sha1 = target_file.get_sha1()
        del target_file

        # kiem tra file da co tren virustotal va rescan
        if self._rescan(sha1) is False:
            if self._send_file(file_path) is False:
                return

        self._report_ok = False
        for i in range(0, self._timeout / 5, 1):
            self._report_ok = self._get_report(sha1)
            if self._report_ok is True:
                break
            else:
                time.sleep(5)
コード例 #20
0
ファイル: Ai.py プロジェクト: mittman/pycheckmate
	def move(self, board, player):
		self.root_node = None
		if not board.find_legal_moves(board.player_y.pieces['K']):
			File.prompt("GAME OVER")
			exit(0)
		else:
			self.root_node = State(board)
			if player.id == 'x':
				self.create_state_tree(board, player, 0, self.root_node, True)
			else:
				self.create_state_tree(board, player, 0, self.root_node, False)
				
			best_state = self.root_node.children_nodes[0]
			if player.id == 'x':
				for s in self.root_node.children_nodes:
					if s.value <= best_state.value:
						best_state = s
			else:
				for s in self.root_node.children_nodes:
					if s.value >= best_state.value:
						best_state = s

			piece = player.pieces[best_state.piece_to_move.type]
			moveH = best_state.new_coords[0]
			moveV = best_state.new_coords[1]
			File.print('\n')
			File.prompt("Best move " + player.id + piece.type + " to " + str(moveH) + "," + str(moveV))
			board.make_move(player, piece, best_state.new_coords)
コード例 #21
0
ファイル: Game.py プロジェクト: mittman/pycheckmate
	def ask_piece(self, board, player_x, player_y, remain):
		File.prompt("ADD PIECE TO BOARD?")

		i = 0
		for p in remain:
			i += 1
			File.print(str(i) + ") " + p)

		n = len(remain)
		option = input("Select [1-" + str(n) + "]: ")
		try:
			option = int(option)
		except ValueError: self.ask_piece(board, player_x, player_y, remain)

		if option <= n and option > 0 and n > 1:
			piece_name = remain[option-1]
			self.insert_piece(board, piece_name, player_x, player_y)
			remain.pop(option-1)
			self.ask_piece(board, player_x, player_y, remain)
		elif option <= n and option > 0:
			piece_name = remain[option-1]
			self.insert_piece(board, piece_name, player_x, player_y)
			remain.pop(option-1)
		else:
			File.error("Try again")
			self.ask_piece(board, player_x, player_y, remain)
コード例 #22
0
ファイル: Client.py プロジェクト: CristianDragu/Projects
def comm():
  global users
  while True:
    inp = raw_input("Enter desired command:\n")
    inp = inp.rstrip('\n')
    if inp == "users":
      users = getUsers()
      User.printUsers(users)
    elif inp == "files":
      username = raw_input("Enter username:"******"discn":
      discn()
      return
    elif inp == "updat":
      updateFiles()
    elif inp == "transfer":
      startTransfer()
    else:
      print "Dafuq is this m8?"
コード例 #23
0
ファイル: main.py プロジェクト: mark-ross/two-opt
def main():

    f = "tsp-medium.tsp"
    j = File.read(f)  # to generate data, use the R_File.read access
    t = TwoOpt(j)  # returns an object ready to sort

    pylab.show()
    pylab.waitforbuttonpress()

    t.sort()  # one round of sorting

    # finally, once it's finished, just wait for button press
    pylab.waitforbuttonpress()
    pylab.close()
コード例 #24
0
ファイル: Interface.py プロジェクト: jcampbellco/ImageMover
    def set_image(self, file: File):
        if file is None:
            self.clear_image()
            return

        size = (self.image_preview.winfo_width(), self.image_preview.winfo_height())

        image = file.get_thumbnail(size)
        thumb = ImageTk.PhotoImage(image)

        self.image = file
        self.thumb = thumb
        self.image_preview.configure(image=thumb)

        self.wm_title(self.filesystem.get_filename(self.filesystem.current_filename))
コード例 #25
0
ファイル: MultipleOuts.py プロジェクト: totorigolo/WiiQuizz
    def __init__(self, dirname):
        if dirname == 'ask':
            dirname = FSDialog.get_folder('./games/mult_outs/')
        dirname = "/games/mult_outs/" + dirname
        File.__init__(self, dirname)

        self.win.new_color('black')
        self.win.new_color((80, 100, 255), 'blue_options')
        self.win.new_color((30, 255, 60), 'green_buzz')

        self.once = False
        self.showing = False
        self.is_paused = False

        self.question_text = ""
        self.answers = []
        self.good_answer_index = -1

        self.who_buzzed = None
        self.which_buzzed = None
        self.team_mgr = TeamMgr.Instance()
        self.team_mgr.set_buzz_fun(self.buzz_fun)

        self.question_changed()
コード例 #26
0
    def _save_report(self, file_path, file_scan=None):
        if self._report_ok is False:
            return

        content = ''

        if file_scan is not None:
            content += 'Filename:      ' + file_scan + '\r\n'

        content += 'MD5:           ' + self._report['md5'] + '\r\n'
        content += 'SHA1:          ' + self._report['sha1'] + '\r\n'
        content += 'SHA256:        ' + self._report['sha256'] + '\r\n'
        content += 'Permalink:     ' + self._report['permalink'] + '\r\n'
        content += '\r\n'

        long_white_space = '                                '

        for key, value in self._report['scans'].items():
            if value['detected'] is True:
                content += key + ': ' + long_white_space[len(key):] + value['result'] + '\r\n'

        target_file = File(file_path)
        target_file.write(content)
        del target_file
コード例 #27
0
ファイル: Board.py プロジェクト: mittman/pycheckmate
    def make_move(self, player, piece, new_coords, testing=False):
        new_row = new_coords[0]
        new_col = new_coords[1]
        # If playerY eats playerX's rook:
        if (
            "R" in self.player_x.pieces
            and new_row == self.player_x.pieces["R"].row
            and new_col == self.player_x.pieces["R"].col
        ):
            del self.player_x.pieces["R"]
            if not testing:
                File.prompt("PlayerX rook captured")
                File.prompt("Stalemate")
                exit(0)

        self.state[piece.row][piece.col] = "*"
        piece.prev_coords = (piece.row, piece.col)
        piece.row = new_coords[0]
        piece.col = new_coords[1]
        self.state[0][0] = "player" + piece.player.upper()
        self.state[piece.row][piece.col] = piece.player + piece.type
        self.piece_positions = self.new_positions()
        player.turn += 1
        self.move_log = piece.player + piece.type + " to " + str(new_row) + "," + str(new_col)
コード例 #28
0
ファイル: FileDAO.py プロジェクト: tassia/DonkeySurvey
 def find(self, id):
     self.cursor.execute("""SELECT * FROM """+self.tablename+""" WHERE id = %s""", (id,))
     rs = self.cursor.fetchall()
     if not rs:
         return None
     file = File()
     for row in rs:
         file.id = row[0]
         file.hash = row[1] 
         file.size = row[2] 
         file.partialSize = row[3] 
         file.bestName = row[4] 
     return file
コード例 #29
0
ファイル: FileDAO.py プロジェクト: tassia/DonkeySurvey
 def findByHash(self, hash):
     query = "SELECT * FROM %s WHERE hash = '%s'" % (self.tablename, hash)
     self.cursor.execute(query)
     rs = self.cursor.fetchall()
     if not rs:
         return None
     file = File()
     for row in rs:
         file.id = row[0]
         file.hash = row[1] 
         file.size = row[2] 
         file.partialSize = row[3] 
         file.bestName = row[4] 
     return file
コード例 #30
0
ファイル: Download.py プロジェクト: olesmith/SmtC
    if (re.search('\.pdf$', fname)):
        header = "pdf"
    elif (re.search('\.jpg$', fname)):
        header = "jpg"
    elif (re.search('\.png$', fname)):
        header = "png"
    elif (re.search('\.svg$', fname)):
        header = "svg"

    elif (re.search('\.tex$', fname)):
        header = "tex"
    elif (re.search('\.(tgz|tar.gz)$', fname)):
        header = "tgz"

    return header


if (get.has_key("File")):
    fname = get["File"]
    header = Header(fname)
    for base_path in base_paths:
        fobj = File()
        if (fobj.File_Exists(base_path + fname)):

            cgiobj.CGI_HTTP_Header_Print(header, fname)
            print fobj.File_Read(base_path + fname)
            exit()

    cgiobj.CGI_HTTP_Header_Print()
    print fname, "non-existent"
コード例 #31
0
 def dl_service(self, req, user):
     path = self.get_file_path(req, user)
     file = File(path)
     self.check_athor(req, user)
     self.check_accounting(user, file)
     return Res(226, file=file)
コード例 #32
0
    def restore_files(self, ds, files):
        """Open data files"""
        for file_dic in files.values():
            fname = file_dic['fname']
            is_active = file_dic['is_active']
            fparams = file_dic['fparam'] # dict
            ftable = np.asarray(file_dic['ftable'])

            
            f_ext = fname.split('.')[-1]
            ft = ds.parent_application.filetypes[f_ext]
            f = File(fname, ft, ds, ds.parent_application.axarr)
            f.data_table.num_rows, f.data_table.num_columns = ftable.shape
            f.data_table.data = ftable

            ds.files.append(f)
            ds.current_file = f
            f.active = is_active
            for pname in fparams:
                f.file_parameters[pname] = fparams[pname]
            try:
                f.with_extra_x = bool(file_dic['with_extra_x'])
                f.theory_xmin = file_dic['theory_xmin']
                f.theory_xmax = file_dic['theory_xmax']
                f.theory_logspace = bool(file_dic['theory_logspace'])
                f.th_num_pts = file_dic['th_num_pts']
                f.nextramin = file_dic['nextramin']
                f.nextramax = file_dic['nextramax']
            except KeyError:
                pass # backward compatibility

            ds.parent_application.addTableToCurrentDataSet(f, f_ext)
            ds.do_plot()
            ds.parent_application.update_Qplot()
            ds.set_table_icons(ds.table_icon_list)
コード例 #33
0
 def list_handler(self, file):
     f = File()
     f.load(file)
     print(f)
コード例 #34
0
 def __init__(self, leaf):
     self.file = File(leaf)
     self.legend = Legend(leaf)
     self.contour = Contour(leaf)
     self.title = Title(leaf)
     self.uv = UV(leaf)
コード例 #35
0
import os
from CommandFunctions import *
from Terminal import Terminal
from Folder import Folder
from File import File
from art import art

terminal = Terminal()
folder = Folder()
file = File()


def run():
    while True:
        folder.setPath(terminal.getPath())
        file.setPath(terminal.getPath())

        print(terminal.getPath() + '>', end='')
        string = input('')
        stringList = string.split(' ')

        if stringList[0] == 'change':
            terminal.changePath(stringList[1])

        elif stringList[0] == 'back':
            terminal.backPath()

        elif stringList[0] == 'help':
            commandsHelp('Help')

        elif stringList[0] == 'list':
コード例 #36
0
import lxml
import time

from Tokenize import Tokenize
from bs4 import BeautifulSoup
from Dictionary import Dictionary
from File import File
from Posting import Posting
from Location import Location
from DataParser import DataParser
from Counter import Counter

fileDirectory = os.path.dirname(
    os.path.abspath(inspect.getfile(inspect.currentframe())))

f = File(fileDirectory,
         "/WEBPAGES_RAW/bookkeeping.json")  #locate the json file
jsonData = f.readJson()  # read the json file

myCounter = Counter(len(jsonData))

# loop through the location:url from the bookkeeping.json file
for location, urlLink in jsonData.items():

    wPost = Posting()  # create posting
    wDict = Dictionary()  # create dictionary

    fileName = "/WEBPAGES_RAW/" + location  # generate a new location
    data = File(
        fileDirectory,
        fileName).readText()  # looking to the file and return html text
コード例 #37
0
def assign(fileNameExperts, fileNameClients):
    """
    Assign given experts given to given clients.
    Requires: fileNameExperts, fileNameClients are str
    """
    inFileExperts = File(fileNameExperts)
    inFileExpertsHeader, inFileExpertsContent = inFileExperts.readFileExpert()

    inFileClients = File(fileNameClients)
    inFileClientsHeader, inFileClientsContent = inFileClients.readFileClient()


inputFileName1 = "2019y02m15clients10h30.txt"
inputFileName2 = "2019y02m15experts10h30.txt"

inFileExperts = File(inputFileName2)
inFileExpertsHeader, inFileExpertsContent = inFileExperts.readFileExpert()

inFileClients = File(inputFileName1)
inFileClientsHeader, inFileClientsContent = inFileClients.readFileClient()

teste = Scheduler.assignTasks(inFileExpertsContent, inFileClientsContent,
                              inFileClientsHeader.getHeaderTime())
for t in teste:
    print(t)

#inputFileName1, inputFileName2 = sys.argv[1:]

#assign(inputFileName1, inputFileName2)

######## TEST
コード例 #38
0
ファイル: tests.py プロジェクト: dh256/adventofcode
def test_decompress(file, decompressed_length):
    file = File(file)
    assert (len(file.decompress()) == decompressed_length)
コード例 #39
0
ファイル: tests.py プロジェクト: dh256/adventofcode
def test_decompress2(file, decompressed_length):
    file = File(file)
    assert (file.decompress2() == decompressed_length)
コード例 #40
0
#!/usr/bin/env python
from File import File
from LSA import LSA
from Set import Set
from NaiveBayesClassifier import NaiveBayesClassifier
import numpy
import datetime
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure

###############################################################################
#  Initializing
###############################################################################

f = File()

print("Data imported.")

MIN_FREQ = 3
MAX_GRAM = 5
P_EIG = 0.5
time_score = []
lsa = []
min_freq = [1, 2, 3, 4, 5, 6]
max_gram = [1, 2, 3, 4, 5, 6]
p_eig = [
    0.1, 0.2, 0.3, 0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9,
    0.95, 1
]
y = []
yerrormin = []
コード例 #41
0
ファイル: main.py プロジェクト: dl57934/hoony_blog_Data
from Directory import Directory
from File import File

if __name__ == "__main__":
    root = Directory("root")
    bin = Directory("bin")
    tmp = Directory("tmp")
    usr = Directory("usr")

    root.add(bin)
    root.add(tmp)
    root.add(usr)

    bin.add(File("vi", 10000))
    bin.add(File("latex", 20000))
    root.print_line()
コード例 #42
0
 def dl_handler(self, file):
     f = File()
     f.load(file)
     print(f)
     f.save()
コード例 #43
0
 def test_add(self):
     first = "/path/to/first/file"
     file1 = File(first, 0, 0, "image/jpg")
     self.fileStore.addFile(file1)
     self.assertEqual(len(self.fileStore.getFilesForName(first)), 1)
コード例 #44
0
from Searches import depth_search, breadth_search, a_star
from Variable import *

__author__ = 'ryuzakinho'
from File import File

cnf_file = File("uf20-0348.cnf")
clause_list = cnf_file.get_clause_info
print cnf_file.get_file_info
print clause_list
print Variable.where_is_the_variable(clause_list, 1)
tup = depth_search(clause_list, cnf_file.get_file_info['nbr_variable'])
print tup[0].already_assigned_variables
print tup[1]
print tup[2]
print tup[3]

tup = breadth_search(clause_list, cnf_file.get_file_info['nbr_variable'])
print tup[0].already_assigned_variables
print tup[1]
print tup[2]
print tup[3]

tup = a_star(clause_list, cnf_file.get_file_info['nbr_variable'], 1)
print tup[0].already_assigned_variables
print tup[1]
print tup[2]
print tup[3]

etat = a_star(clause_list, cnf_file.get_file_info['nbr_variable'], 2)
print tup[0].already_assigned_variables
コード例 #45
0
    def search_updates(self, directory):
        # scan recursively all files & directories in the root directory
        for path_file, dirs, files in os.walk(directory):

            for dir_name in dirs:
                folder_path = os.path.join(path_file, dir_name)

                # get depth of the current directory by the count of the os separator in a path
                # and compare it with the count of the root directory
                if self.is_superior_max_depth(folder_path) is False:
                    self.paths_explored.append(folder_path)

                    # a folder can't be updated, the only data we get is his creation time
                    # a folder get created during running time if not present in our list

                    if folder_path not in self.synchronize_dict.keys():
                        # directory created
                        # add it to dictionary
                        self.synchronize_dict[folder_path] = Directory(
                            folder_path)

                        # create it on FTP server
                        split_path = folder_path.split(self.root_directory)
                        srv_full_path = '{}{}'.format(self.ftp.directory,
                                                      split_path[1])
                        directory_split = srv_full_path.rsplit(os.path.sep,
                                                               1)[0]
                        if not self.ftp.if_exist(
                                srv_full_path,
                                self.ftp.get_folder_content(directory_split)):
                            # add this directory to the FTP server
                            while len(self.thread_pool) >= self.max_thread_num:
                                pass  # Wait for thread releasing
                            self.ftp = TalkToFTPThreadify(self.ftp_website)
                            self.ftp.connect()
                            t = Thread(self.thread_pool,
                                       self.ftp.create_folder_threadify,
                                       (srv_full_path))
                            self.thread_pool.append(t)
                            # self.ftp.create_folder(srv_full_path)
                            t.start()

            for file_name in files:
                file_path = os.path.join(path_file, file_name)

                # get depth of the current file by the count of the os separator in a path
                # and compare it with the count of the root directory
                if self.is_superior_max_depth(file_path) is False and \
                        (self.contain_excluded_extensions(file_path) is False):

                    self.paths_explored.append(file_path)
                    # try if already in the dictionary
                    if file_path in self.synchronize_dict.keys():

                        # if yes and he get updated, we update this file on the FTP server
                        if self.synchronize_dict[file_path].update_instance(
                        ) == 1:
                            # file get updates
                            split_path = file_path.split(self.root_directory)
                            srv_full_path = '{}{}'.format(
                                self.ftp.directory, split_path[1])
                            self.ftp = TalkToFTPThreadify(self.ftp_website)
                            self.ftp.connect()
                            t = Thread(self.thread_pool,
                                       self.ftp.remove_file_threadify,
                                       (srv_full_path))
                            self.thread_pool.append(t)
                            #self.ftp.remove_file(srv_full_path)
                            t.start()
                            # update this file on the FTP server
                            t = Thread(self.thread_pool,
                                       self.ftp.file_transfer_threadify,
                                       (path_file, srv_full_path, file_name))
                            self.thread_pool.append(t)
                            #self.ftp.file_transfer(path_file, srv_full_path, file_name)
                            t.start()

                    else:

                        # file get created
                        self.synchronize_dict[file_path] = File(file_path)
                        split_path = file_path.split(self.root_directory)
                        srv_full_path = '{}{}'.format(self.ftp.directory,
                                                      split_path[1])
                        # add this file on the FTP server
                        while len(self.thread_pool) >= self.max_thread_num:
                            pass  # Wait for thread releasing
                        self.ftp = TalkToFTPThreadify(self.ftp_website)
                        self.ftp.connect()
                        t = Thread(self.thread_pool,
                                   self.ftp.file_transfer_threadify,
                                   (path_file, srv_full_path, file_name))
                        self.thread_pool.append(t)
                        # self.ftp.file_transfer(path_file, srv_full_path, file_name)
                        t.start()
コード例 #46
0
    def __init__(self, parent=None):
        """
        Konstrukotr der Klasse MyController
        """

        super().__init__(parent)
        self.myForm = View.Ui_MainWindow()
        self.dbcon = view_database.Ui_MainWindow()

        self.myForm.setupUi(self)
        self.model = QtGui.QStandardItemModel(self)

        self.centralwidget = QtGui.QWidget(self)
        self.centralwidget.setObjectName("centralwidget")
        self.tableView = QtGui.QTableView(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(0, 0, 981, 581))
        self.tableView.setModel(self.model)
        self.tableView.setObjectName("tableView")
        self.setCentralWidget(self.centralwidget)

        self.undoStack = QUndoStack()

        self.copyAct = CopyAction("&Copy", self.tableView,
                               shortcut=QKeySequence.Copy,
                               undoStack=self.undoStack,
                               statusTip="Kopieren")
        self.pasteAct = PasteAction("&Paste", self.tableView,
                                 shortcut=QKeySequence.Paste,
                                 undoStack=self.undoStack,
                                 statusTip="Einfügen")
        self.cutAct = CutAction("&Cut", self.tableView,
                                 shortcut=QKeySequence.Cut,
                                 undoStack=self.undoStack,
                                 statusTip="Ausschneiden")
        self.rowAct = AddRowAction("&Add Row", self.tableView,
                                 shortcut='',
                                 undoStack=self.undoStack,
                                 statusTip="Zeile Einfügen")
        self.delAct = DeleteAction("&Delete Row", self.tableView,
                                 shortcut='',
                                 undoStack=self.undoStack,
                                 statusTip="Zeile Löschen")
        self.dupAct = DuplicateAction("&Duplicate Row", self.tableView,
                                 shortcut='',
                                 undoStack=self.undoStack,
                                 statusTip="Zeile Duplizieren")

        self.undoAction = self.undoStack.createUndoAction(self, self.tr("&Undo"))
        self.undoAction.setShortcuts(QKeySequence.Undo)
        self.undoAction.setStatusTip("undo the last action")
        self.redoAction = self.undoStack.createRedoAction(self, self.tr("&Redo"))
        self.redoAction.setShortcuts(QKeySequence.Redo)
        self.redoAction.setStatusTip("redo the last action")


        self.f = File(self,self.model)
        QtCore.QObject.connect(self.myForm.actionOpen, QtCore.SIGNAL("activated()"), self.f.openFile)
        QtCore.QObject.connect(self.myForm.actionSave, QtCore.SIGNAL("activated()"), self.f.safeFile)
        QtCore.QObject.connect(self.myForm.actionSave_As, QtCore.SIGNAL("activated()"), self.f.safeFileAs)
        QtCore.QObject.connect(self.myForm.actionNew, QtCore.SIGNAL("activated()"), self.f.newFile)
        QtCore.QObject.connect(self.myForm.actionConnect, QtCore.SIGNAL("activated()"),self.db)




        self.myForm.menuEdit.addAction(self.undoAction)
        self.myForm.menuEdit.addAction(self.redoAction)
        self.myForm.menuEdit.addSeparator()
        self.myForm.menuEdit.addAction(self.cutAct)
        self.myForm.menuEdit.addAction(self.copyAct)
        self.myForm.menuEdit.addAction(self.pasteAct)
        self.myForm.menuEdit.addSeparator()
        self.myForm.menuEdit.addAction(self.rowAct)
        self.myForm.menuEdit.addAction(self.delAct)
        self.myForm.menuEdit.addAction(self.dupAct)
コード例 #47
0
class Game(object):
    def __init__(self, width, height):
        pygame.init()
        self.width = width
        self.height = height
        self.__set_screen_up()
        self.ladybugs = []
        self.player = Player((self.width - 30) / 2, (self.height - 30) / 2, 0,
                             0)
        self.FPS = config.fps
        self.clock = pygame.time.Clock()
        self.highscores = File(config.highscores_filename)
        self.mixer = Music('Objects/music/MoonlightSonata.mp3')

    def run(self):
        run = True
        while run:
            menu = self.Menu(self.width, self.height, self.__screen,
                             self.mixer)
            self.mixer.play_from(-1, 360)
            run = menu.run()
            if run == 1:
                self.mixer.play_from(-1, 1)
                menu.open_highscores()
            elif run == 2:
                self.mixer.play_from(-1, 486)
                start = Caption("WCIŚNIJ SPACJĘ ABY ROZPOCZĄĆ", 30,
                                config.colors.get("White"))
                start.x = (self.width - start.text.get_width()) / 2
                start.y = int(self.height * 0.7)
                self.__screen_update([start])
                game = self.__get_space()
                while game:
                    run = True
                    collision = False
                    self.player.score = 0
                    start.y = int(self.height * 0.7)
                    self.__set_difficulty(config.difficulty)
                    self.__reset_player()
                    while run and not collision:
                        self.__screen_update()
                        self.clock.tick(self.FPS)
                        self.player.move(-self.player.x_speed / 10,
                                         -self.player.y_speed / 10)
                        collision = self.__update_enemies_movements()
                        self.player.score += config.difficulty
                        pygame.event.get()
                        self.__handle_keys(pygame.key.get_pressed())
                    if collision:
                        result = Caption(
                            "Twój wynik: " + str(self.player.score), 50)
                        result.x = int(
                            (self.width - result.text.get_width()) / 2)
                        result.y = int(
                            (self.height - result.text.get_height()) / 2)
                        start.y = result.y + result.text.get_height() + 10
                        self.__remove_ladybugs()
                        self.__reset_player(
                            (self.width - self.player.width) / 2,
                            int(self.height / 3))
                        self.__screen_update([result, start])
                        self.__update_highscores()
                        game = self.__get_space()

        pygame.quit()

    def __set_difficulty(self, num_of_ladybugs=config.default_level):
        for i in range(num_of_ladybugs):
            x_pos = random.choice((random.randint(0, self.width / 2 - 60),
                                   random.randint(self.width / 2 + 30,
                                                  self.width - 30)))
            y_pos = random.choice((random.randint(0, self.height / 2 - 60),
                                   random.randint(self.height / 2 + 30,
                                                  self.height - 30)))
            self.ladybugs.append(
                Ladybug(x_pos, y_pos,
                        random.randint(1, 5) / 1000,
                        random.randint(1, 5) / 1000))

    def __screen_update(self, added_captions=None):
        if added_captions is None:
            added_captions = []
        self.__screen.fill((0, 0, 0))
        self.__screen.blit(self.player.img, (self.player.x, self.player.y))
        for ladybug in self.ladybugs:
            self.__screen.blit(ladybug.img, (ladybug.x, ladybug.y))
        self.caption = Caption(str(self.player.score), 20)
        self.__screen.blit(self.caption.text, (10, 10))
        if len(added_captions) > 0:
            for caption in added_captions:
                self.__screen.blit(caption.text, (caption.x, caption.y))
        pygame.display.update()

    def __update_enemies_movements(self):
        for ladybug in self.ladybugs:
            if self.player.collides_with(ladybug):
                return True
            x_dir = random.choice((-1, 1))
            y_dir = random.choice((-1, 1))
            ladybug.move(x_dir * random.randint(1, 5) / 25,
                         y_dir * random.randint(1, 5) / 25)
        return False

    def __handle_keys(self, keys):
        if keys[pygame.K_w] or keys[pygame.K_UP]:
            self.player.move(0, -config.player_movespeed)
        if keys[pygame.K_s] or keys[pygame.K_DOWN]:
            self.player.move(0, config.player_movespeed)
        if keys[pygame.K_a] or keys[pygame.K_LEFT]:
            self.player.move(-config.player_movespeed, 0)
        if keys[pygame.K_d] or keys[pygame.K_RIGHT]:
            self.player.move(config.player_movespeed, 0)

    def __remove_ladybugs(self):
        self.ladybugs.clear()

    def __reset_player(self, x_pos=0, y_pos=0):
        if not x_pos or not y_pos:
            self.player = Player((self.width - 30) / 2, (self.height - 30) / 2,
                                 0, 0)
        else:
            self.player.x = x_pos
            self.player.y = y_pos

    def __get_space(self, space=True):
        while space:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return False
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        space = False
                    if event.key == pygame.K_ESCAPE:
                        return False
        return True

    def __update_highscores(self):
        self.highscores.open()
        i = len(self.highscores.data) - 1
        if self.player.score <= self.highscores.data[i].score:
            return
        self.highscores.data[i] = Score(self.player.name, self.player.score)
        while i > 0 and self.highscores.data[i] > self.highscores.data[i - 1]:
            temp = self.highscores.data[i]
            self.highscores.data[i] = self.highscores.data[i - 1]
            i -= 1
            self.highscores.data[i] = temp
        self.highscores.save()

    def __set_default_highscores(self):
        self.highscores.open()
        default_points = 100000
        highscores = []
        for i in range(10):
            highscores.append(Score(config.player_name, default_points))
            default_points -= 10000
        self.highscores.data = highscores
        self.highscores.save()

    def __set_screen_up(self):
        pygame.init()
        pygame.display.set_icon(icon)
        pygame.display.set_caption('Ladybug v1.1')
        self.__screen = pygame.display.set_mode((self.width, self.height))

    class Menu:  ############# MENU HANDLER #################
        def __init__(self, width, height, screen, mixer):
            self.__screen = screen
            self.logo = logo
            self.buttons = Buttons(
                [[
                    Caption("QUIT", 30, config.colors.get("Grey")),
                    Caption("HIGHSCORES", 30, config.colors.get("Grey")),
                    Caption("START", 30)
                ],
                 [
                     Caption("PLAYER NAME: ", 30, config.colors.get("Grey")),
                     Caption(config.player_name, 30, config.colors.get("Grey"))
                 ],
                 [
                     Caption("DIFFICULTY: ", 30, config.colors.get("Grey")),
                     Caption(str(config.difficulty), 30,
                             config.colors.get("Grey"))
                 ], [Caption("MUSIC: ON", 30, config.colors.get("Grey"))]])
            self.width = width
            self.height = height
            self.selection = Caption("QUIT")
            self.mixer = mixer

        def run(self):
            run = True
            while run:
                self.selection = self.buttons.handle_events()
                if self.selection is not None:
                    if self.selection == Caption("QUIT"):
                        return 0
                    elif self.selection == Caption("HIGHSCORES"):
                        return 1
                    elif self.selection == Caption("START"):
                        return 2
                    elif self.selection == Caption(
                            "PLAYER NAME: "
                    ) or self.selection == self.buttons.buttons[1][1]:
                        self.selection = self.buttons.buttons[1][1]
                        self.buttons.row = 1
                        self.buttons.col = 1
                        self.__get_playername()
                        # let the user type in the name
                    elif self.selection == Caption(
                            "DIFFICULTY: "
                    ) or self.selection == self.buttons.buttons[2][1]:
                        self.selection = self.buttons.buttons[2][1]
                        self.buttons.row = 2
                        self.buttons.col = 1
                        self.__get_difficulty()
                        # let the user change difficulty
                    elif self.selection == Caption("MUSIC: ON") or Caption(
                            "MUSIC: OFF"):
                        if self.mixer.is_on():
                            self.buttons.buttons[3][0] = Caption(
                                "MUSIC: OFF", 30)
                        else:
                            self.buttons.buttons[3][0] = Caption(
                                "MUSIC: ON", 30)
                        self.mixer.change_mode()
                self.update()
            return self.selection

        def update(self):
            self.__screen.fill((0, 0, 0))
            self.__screen.blit(self.logo,
                               ((self.width - self.logo.get_width()) / 2,
                                self.height - self.logo.get_height() - 50))
            self.buttons.update(self.__screen)
            pygame.display.update()

        def open_highscores(self):
            run = True
            highscores = File(config.highscores_filename)
            highscores.open()
            title = Caption("HIGHSCORE TABLE", 30)
            x_pos = int((self.width - title.get_width()) / 2)
            while run:
                y_pos = 40
                self.__screen.fill((0, 0, 0))
                self.__screen.blit(title.text, (x_pos, y_pos))
                y_pos += title.get_height()
                for score in highscores.data:
                    player = (Caption(score.player_name,
                                      20), Caption(": ", 20),
                              Caption(score.score, 20))
                    y_pos += int((player[0].get_height() / 2) * 3)
                    for caption in player:
                        self.__screen.blit(caption.text, (x_pos, y_pos))
                        x_pos += caption.get_width()
                    x_pos = int((self.width - title.get_width()) / 2)

                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        pygame.quit()
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_ESCAPE:
                            return False

                pygame.display.update()

        def __get_playername(self):
            player_name = ""
            run = True
            while run:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        run = False
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_BACKSPACE:
                            if len(player_name):
                                player_name = player_name[:-1]
                        elif event.key == pygame.K_ESCAPE:
                            player_name = config.player_name
                            self.buttons.buttons[1][1] = Caption(
                                player_name, 30)
                            run = False
                        elif event.key == pygame.K_RETURN:
                            config.player_name = player_name
                            run = False
                        elif len(player_name) < 16:
                            player_name += event.unicode
                self.buttons.buttons[1][1] = Caption(player_name, 30)
                self.update()
            self.selection = self.buttons.buttons[1][0]
            self.buttons.row = 1
            self.buttons.col = 0

        def __get_difficulty(self):
            difficulty = config.difficulty
            run = True
            while run:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        run = False
                    if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_w or event.key == pygame.K_UP:
                            if difficulty < config.max_level:
                                difficulty += 1
                        elif event.key == pygame.K_s or event.key == pygame.K_DOWN:
                            if difficulty > config.min_level:
                                difficulty -= 1
                        elif event.key == pygame.K_ESCAPE:
                            difficulty = config.difficulty
                            self.buttons.buttons[2][1] = Caption(
                                config.difficulty, 30)
                            run = False
                        elif event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
                            config.difficulty = difficulty
                            run = False
                self.buttons.buttons[2][1] = Caption(difficulty, 30)
                self.update()
            self.selection = self.buttons.buttons[2][0]
            self.buttons.row = 2
            self.buttons.col = 0
コード例 #48
0
def file(name, parent):
    from File import File
    return File(name, parent)
コード例 #49
0
ファイル: __init__.py プロジェクト: Dor-Ron/CSc_365
from File import File
from Sort import Sort

from timeit import timeit, Timer

if __name__ == "__main__":

    file = File()
    sort = Sort()

    # write random numbers to file
    file.write_ten_random_arrays()

    # read file and save locally
    numbers = file.read_ten_random_arrays()

    template = """Original array: {}

    optimized bubble sort: {} \t {} 
    insertion sort: {} \t {}
    quick sort: {} \t {} 
   
    """

    for arr in numbers:
        ori = " ".join([str(num) for num in arr])
        t1 = Timer(lambda: sort.bubble(arr))
        t2 = Timer(lambda: sort.insertion(arr))
        t3 = Timer(lambda: sort.quick(arr))
        print(
            template.format(ori.split(" "), sort.bubble(arr),
コード例 #50
0
from File import File

if __name__ == '__main__':
    plik = File()

    plik.Close()
    plik.Read()
    plik.Write()
    plik.Open()
    plik.Open()
    plik.Read()
    plik.Write()
    plik.Close()
    plik.Close()
コード例 #51
0
class MainWindow(tkinter.Tk):
    def __init__(self):
        super().__init__()
        self.geometry(f'{WIDTH}x{HEIGHT}')
        self.config(bg='black')
        self.title("ZIP_CRAKER 2.0")
        self.resizable(False, False)
        self.thread = None

    def createButtons(self):
        self.button_list = []
        for i in range(0, 3):
            self.button_list.append(Button(self))
            self.button_list[i].setWidth(25)
            self.button_list[i].setHeight(2)
            self.button_list[i].setBackgroundColor('black')
            self.button_list[i].setForegroundColor('white')
            self.button_list[i].place(x=160, y=100 + (i * 50))

    def setTextToButtons(self):
        self.button_list[0].setText("Select zip file")
        self.button_list[1].setText("Select wordlist file")
        self.button_list[2].setText("Crack!")

    def setCommandsToButtons(self):
        self.FileChecker = File()
        self.button_list[0].setCommand(self.FileChecker.setArchiveFile)
        self.button_list[1].setCommand(self.FileChecker.setDicFile)
        self.button_list[2].setCommand(self.startCrack)

    def startCrack(self):

        if not self.FileChecker.isArchiveEmpty(
        ) and not self.FileChecker.isDictionaryEmpty():

            if self.FileChecker.isArchiveRAR():

                MessageBox.ShowError(
                    "Error",
                    "This is a RAR file(If you want to use this just uncomment code in Zip_Cracker.py file)"
                )
                #Uncomment this if you have linux :/
                #if not self.FileChecker.RequiresPassword():
                #    Cracker=RARCracker(self.FileChecker.getArchiveFilePath(),self.FileChecker.getDictionaryPath())
                #else:
                #    messagebox.showinfo("WAIT WHAT?","RAR archive doesn't have any password")
                #    return
            else:

                Cracker = ZIPCracker(self.FileChecker.getArchiveFilePath(),
                                     self.FileChecker.getDictionaryPath(),
                                     self.ProgressBar)
                self.ProgressBar.setMaxValue(Cracker.countPasswords())
                # I'm f*****g lazy to create a special class for two lines of code  :/
                self.thread = threading.Thread(target=Cracker.TryBruteForce())
                self.thread.start()
        else:
            MessageBox.ShowError("Error", "You didn't choose all options")

    def createProgressBar(self):
        self.ProgressBar = GreenProgressBar(self, 200,
                                            'green.Horizontal.TProgressbar')
        self.ProgressBar.place(x=160, y=400)

    def startWindow(self):
        self.mainloop()
コード例 #52
0
# -*- coding:utf-8 -*-
import sys
import json
import io
import random
from Practice import Practice
from User import User
from File import File
import re

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

if __name__ == '__main__':
    user = User()
    practice = Practice()
    file = File()
    school = {"primary": "小学", "middle": "初中", "high": "高中"}
    while 1:
        string = input("name and passwd: ")
        arr = re.split(r" +", string)  # 根据空格截取name passwd
        name = arr[0]
        passwd = arr[1]
        # name = input("name and passwd: ")
        # passwd = input("passwd: ")
        mold = user.validate(name, passwd)
        if mold != False:
            print("当前选择为{mold}出题".format(mold=school[mold]))
            break
        else:
            print("请输入正确的用户名和密码")
            continue
コード例 #53
0
ファイル: main.py プロジェクト: Kishinskiy/Python_File
from File import File

f = File("myFile.bin", "Some Content bin data\n")

if __name__ == '__main__':
    # print(f.read())

    f.write_byte()
    f.add_byte()
    print(f.read())

コード例 #54
0
 def setCommandsToButtons(self):
     self.FileChecker = File()
     self.button_list[0].setCommand(self.FileChecker.setArchiveFile)
     self.button_list[1].setCommand(self.FileChecker.setDicFile)
     self.button_list[2].setCommand(self.startCrack)
コード例 #55
0
 def create_file(self, file_name, size):
     self.add_size(size)
     self.files[file_name] = File(file_name, '', size)
コード例 #56
0
from File import File
from LSA import LSA
from Set import Set
from NaiveBayesClassifier import NaiveBayesClassifier
import numpy
import math
import datetime
from itertools import groupby
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure

###############################################################################
#  Initializing
###############################################################################

f = File()

print("Data imported.")

MIN_FREQ = 3
MAX_GRAM = 5
P_EIG = 0.95
ALPHA = 1e-10
test_score  = []

###########################
# LSA
l = LSA(MAX_GRAM, MIN_FREQ, P_EIG, f.x)
print("Parameters: Min_freq =", l.min_freq,"NGram_max =", l.ngram_max, "P_eig =", l.p_eig*100)
human_keywords = l.manage_keywords(f.keywords)
lsa_results = l.train_phrases(human_keywords)
コード例 #57
0
    def calculateCosts(self,
                       output: str = None,
                       quiet: bool = False,
                       policy: Policy = None):
        """Model the usability costs needed to reach found communities."""
        if not self.clusters:
            raise ValueError("Clusters for a graph must be computed "
                             "before calculating its cost.")

        msg = ""
        appStore = ApplicationStore.get()

        crossing = self.clusters.crossing()
        grantingCost = 0
        isolationCost = 0
        splittingCost = 0
        for (index, x) in enumerate(crossing):
            if not x:
                continue

            edge = self.g.es[index]
            source = self.g.vs[edge.source]
            target = self.g.vs[edge.target]
            sourceType = source.attributes()['type']
            targetType = target.attributes()['type']
            sourceName = source.attributes()['name']
            targetName = target.attributes()['name']

            # Case where a file-file node was removed. Should normally not
            # happen so we will not write support for it yet.
            if sourceType == "file":
                if targetType == "app":
                    grantingCost += 1
                    if policy:
                        app = appStore.lookupUid(targetName)
                        policy.incrementScore('graphGrantingCost', None, app)
                else:
                    # Check if an app co-accessed the files. If so, increase the
                    # cost of splitting that app instance into two.
                    sAccessors = []
                    for n in source.neighbors():
                        if n.attributes()['type'] == 'app':
                            sAccessors.append(n)
                    tAccessors = []
                    for n in target.neighbors():
                        if n.attributes()['type'] == 'app':
                            tAccessors.append(n)

                    inter = intersection(sAccessors, tAccessors)

                    for i in inter:
                        splittingCost += 1
                        if policy:
                            app = appStore.lookupUid(sourceName)
                            policy.incrementScore('graphSplittingCost', None,
                                                  app)
                    if not inter:
                        print(
                            "Warning: file-file node removed by graph "
                            "community finding algorithm. Not supported.",
                            file=sys.stderr)
                        print(source, target)
                        raise NotImplementedError
            elif targetType == "file":  # sourceType in "app", "appstate"
                grantingCost += 1
                if sourceType == "app" and policy:
                    app = appStore.lookupUid(sourceName)
                    policy.incrementScore('graphGrantingCost', None, app)
                elif policy:
                    policy.incrementScore('graphGranting', None, None)
            else:
                # app-app links are just noise in the UnifiedGraph
                if sourceType != "app" and targetType == "app":
                    isolationCost += 1
                    if policy:
                        app = appStore.lookupUid(targetName)
                        policy.incrementScore('graphIsolationCost', None, app)
                elif sourceType == "app" and targetType != "app":
                    isolationCost += 1
                    if policy:
                        app = appStore.lookupUid(sourceName)
                        policy.incrementScore('graphIsolationCost', None, app)

        editCount = grantingCost + isolationCost + splittingCost
        msg += ("%d edits performed: %d apps isolated, %d apps split and "
                "%d accesses revoked.\n" %
                (editCount, isolationCost, splittingCost, grantingCost))

        if not quiet:
            tprnt(msg)

        if output:
            path = self.outputDir + "/" + output + ".graphstats.txt"
            os.makedirs(File.getParentNameFromName(path), exist_ok=True)
            with open(path, "w") as f:
                print(msg, file=f)

        self.editCount = editCount
コード例 #58
0
ファイル: Folder.py プロジェクト: dmsovetov/pygling
    def addFile(self, fileName):
        if self._find_file_by_name(fileName):
            print 'Warning: duplicated file reference', fileName
            return

        self._files.append(File(self._target, self, fileName))
コード例 #59
0
ファイル: Test.py プロジェクト: stevdrey/phycalc
while loop == 1:
    # Print what options you have
    print "Please choose from the following menu:"
    print "1) Move File "
    print "2) Calculator"
    print " "
    choice = int(raw_input("Choose your option:").strip())
    if choice == 1:
        opsys = platform.system()
        sourcePath = r"C:\Users\achock\PythonDev"
        destPath = r"C:\Users\achock\PythonDev"
        print "Welcome"
        print "Current working dir : %s" % os.getcwd()
        print "Please name your file"
        fname = raw_input("Enter name of file\n")
        file = File(sourcePath, destPath, fname)
        fnew = os.path.isfile(fname)  # checks to see if the file exist on curdirectory
        file.exists(fnew)  # gives message if exists
        destPath = raw_input(
            "Enter the directory in which you would like to copy file. \n For example C:\Users\achock\PythonDev\n"
        )
        ndir = os.path.isdir(destPath)
        file.verDir(ndir)
        file.moveFile(fname, destPath, opsys)
    elif choice == 2:
        print "Your options are:"
        print " "
        print "1) Addition"
        print "2) Subtraction"
        print "3) Multiplication"
        print "4) Division"
コード例 #60
0
    def calculateReachability(self,
                              output: str = None,
                              quiet: bool = False,
                              nodeCount: int = 0):
        """Model the reachability improvement of community finding."""
        if self.clusters is None:
            raise ValueError("Clusters for a graph must be computed "
                             "before modelling how community isolation "
                             "decreases its average reachability.")
        if self.editCount is None:
            raise ValueError("Costs for a graph must be calculated "
                             "before modelling how community isolation "
                             "decreases its average reachability.")

        msg = ""

        def _print(clusters, header, tag):
            msg = "\nGraph statistics %s:\n" % header

            if len(clusters) == 0:
                msg += "no clusters for this graph."
                return (msg, 0, 1)

            sizes = [
                x for x in sorted(list((len(x) for x in clusters))) if x != 0
            ]
            vertexSum = sum(sizes)
            isolatedNC = nodeCount - self.docCount
            msg += ("* %s-size distribution: %s\n" % (tag, sizes.__str__()))
            msg += ("* %s-cluster count: %d\n" % (tag, len(sizes)))
            msg += ("* %s-isolated nodes: %d\n" % (tag, isolatedNC))
            msg += ("* %s-smallest cluster: %d\n" % (tag, min(sizes)))
            msg += ("* %s-largest cluster: %d\n" % (tag, max(sizes)))
            avgSize = vertexSum / len(sizes)
            msg += ("* %s-average size: %f\n" % (tag, avgSize))

            reach = sum([i**2 for i in sizes]) / vertexSum
            msg += ("* %s-average reachability: %f\n" % (tag, reach))

            reach = (sum([i ** 2 for i in sizes]) + isolatedNC) / \
                    (vertexSum + isolatedNC)
            msg += ("* %s-adjusted reachability: %f\n" % (tag, reach))

            return (msg, avgSize, reach)

        def _printAndSum(g, editCount, tagPrefix=None):
            msg = "\n"

            preTag = tagPrefix + "-pre" if tagPrefix else "pre"
            _m, avgPreSize, preReach = _print(g.g.clusters(),
                                              "pre community finding", preTag)
            msg += _m

            postTag = tagPrefix + "-post" if tagPrefix else "post"
            _m, avgPostSize, postReach = _print(g.clusters,
                                                "post community finding",
                                                postTag)
            msg += _m

            if avgPreSize:
                deltaSize = 1 - (avgPostSize / avgPreSize)
                sizeEfficiency = deltaSize / editCount if editCount else 1
                msg += "\nEvol. of avg. cluster size: {:.2%}\n".format(
                    deltaSize)
                msg += ("Efficiency of edits wrt. average size: %f\n" %
                        sizeEfficiency)
            else:
                msg += "\nEvol. of avg. cluster size: N/A\n"

            if preReach:
                deltaReach = 1 - (postReach / preReach)
                reachEfficiency = deltaReach / editCount if editCount else 1
                msg += "\nEvol. of reachability: {:.2%}\n".format(deltaReach)
                msg += ("Efficiency of edits wrt. adj. reachability: %f\n" %
                        reachEfficiency)
            else:
                msg += "\nEvol. of adj. reachability: N/A\n"

            return msg

        if not quiet:
            tprnt("\t\tPrinting statistics on whole graph...")
        msg += _printAndSum(self, self.editCount)

        if not quiet:
            tprnt("\t\tBuilding flat file graph...")
        fg = FlatGraph(parent=self, quiet=quiet)
        if not plottingDisabled():
            if not quiet:
                tprnt("\t\tPlotting flat file graph...")
            fg.plot(output=output)
        if not quiet:
            tprnt("\t\tPrinting statistics on flat file graph...")
        msg += _printAndSum(fg, self.editCount, tagPrefix="flat")

        if not quiet:
            tprnt(msg)

        if output:
            path = self.outputDir + "/" + output + ".graphstats.txt"
            os.makedirs(File.getParentNameFromName(path), exist_ok=True)
            with open(path, "a") as f:
                print(msg, file=f)