def test_generated_7th_file_is_aggregate(self): Generate.dirpath = self.test_dir Generate.filename_prefix = "file" Generate.generate(7, "Hello") file_7_size = path.getsize(Generate.filename(7)) expected_size = 0 for i in range(6): filename = Generate.filename(i + 1) expected_size += path.getsize(filename) self.assertEquals(expected_size, file_7_size)
def menu(): #EasyButton easyButton = pygame.Rect(width - 450, height // 2 - 200, 150, 50) easyButtonText = font.render("Easy", False, BLACK) #mediumButton mediumButton = pygame.Rect(width - 450, height // 2 - 80, 150, 50) mediumButtonText = font.render("Medium", False, BLACK) #hardButton hardButton = pygame.Rect(width - 450, height // 2 + 50, 150, 50) hardButtonText = font.render("Hard", False, BLACK) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() #When the user clicks on a button a game is started with the corresponding difficulty if event.type == pygame.MOUSEBUTTONDOWN: pos = event.pos if easyButton.collidepoint(pos): main(Generate.createSudoku("easy")) if mediumButton.collidepoint(pos): main(Generate.createSudoku("medium")) if hardButton.collidepoint(pos): main(Generate.createSudoku("hard")) #drawing screen.fill(GREY) #Drawing buttons #Drawing buttons pygame.draw.rect(screen, [255, 0, 0], easyButton) screen.blit(easyButtonText, (easyButton.left + 30, easyButton.top + 10)) pygame.draw.rect(screen, [255, 0, 0], mediumButton) screen.blit(mediumButtonText, (mediumButton.left + 30, mediumButton.top + 10)) pygame.draw.rect(screen, [255, 0, 0], hardButton) screen.blit(hardButtonText, (hardButton.left + 30, hardButton.top + 10)) #Update pygame.display.update()
def test_generated_only_5th_file_contains_String(self): Generate.dirpath = self.test_dir Generate.filename_prefix = "file" file_5_addition = "Test String!" #test to check if 5th file contains the Test String! filename = Generate.filename(5) Generate.generate(5, file_5_addition) with open(filename) as fh: content = fh.read() self.assertTrue(file_5_addition in content) #test to check if non 5th file contains the Test String! filename = Generate.filename(3) with open(filename) as fh: content = fh.read() self.assertTrue(file_5_addition not in content)
def generate_phrase(self, algorithm, params): """Class method to generate Phrase - delegates to Generate. :return: Returns a Phrase object :rtype: Phrase """ self.set_phrase(Generate(algorithm, params).phrase)
def credentials(): ''' Function to assign username and password ''' generate = Generate() print '[+] Setting credentails' credentials = [ { 'username': '******', 'password': '******' }, #{'username': '******', 'password': ''} ] for credential in credentials: if not credential['password']: credential.update({'password': str(generate.password(6))}) return credentials
def __init__(self, rows, cols, width, height): initgrid=Generate() self.board=initgrid.board self.rows = rows self.cols = cols self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)] self.width = width self.height = height self.model = None self.selected = None
def rotation_view(generator: Generate, labels: np.ndarray, seed: int, label_version: str, interpolation_type: str, interpolation_space: str, size: int = 512, interpolation_steps: int = 45) -> Tuple[List, int]: json_list = [] if label_version in ['v7'] and interpolation_type == 'spherical': for i in range(len(labels)): image = generator.generate_image(label=labels[i], seed=seed, size=size) json_list.append(image) return json_list, len(labels) else: if interpolation_type == 'cubic': for i in range(8): interpolate_list, _ = interpolations_cubic( generator=generator, label_0=labels[(i - 1) % 8], label_1=labels[i], label_2=labels[(i + 1) % 8], label_3=labels[(i + 2) % 8], seed=seed, size=size, num_steps=interpolation_steps, interpolation_space=interpolation_space) json_list += interpolate_list return json_list, interpolation_steps * 8 if interpolation_type == 'linear': for i in range(8): interpolate_list, _, _ = interpolations( generator=generator, label_left=labels[i], label_right=labels[(i + 1) % 8], seed_right=seed, seed_left=seed, size=size, cache_size=interpolation_steps, interpolation_space=interpolation_space) json_list += interpolate_list return json_list, interpolation_steps * 8
def Main(): (major, minor, _, _, _) = sys.version_info if not(major == 2 and minor >= 7): print >> sys.stderr, "This needs at least version 2.7 of python" sys.exit(1) exceptions = readExceptions("mime.exceptions") root = readFile("magic", exceptions) root.pruneTree(exceptions) root.check() if OptDebug: root.printTree() gen = Generate() gen.putRoot(root) gen.writeToFile("mimemagic.c")
def generate_text(q, artist): gen = Generate(artist) q.put(gen.generated)
def main(): parser = argparse.ArgumentParser(description='Clip Identification system.') parser.add_argument('inputfile', metavar='file', type=str, nargs='?', help='File to process. If none passed then read from stdin.') parser.add_argument('--sourceid', '-srcid', type=str, required=False, default=None, help='SourceID, if present it\'s added to the Pusher notification (null otherwise).') parser.add_argument('--regionid', '-regid', type=str, required=False, default=None, help='RegionID, if present it\'s added to the Pusher notification (null otherwise).') parser.add_argument('--scheduleid', '-schid', type=str, required=False, default=None, help='ScheduleID, if present it\'s added to the Pusher notification (null otherwise).') parser.add_argument('--programid', '-prgid', type=str, required=False, default=None, help='ProgramID, if present it\'s added to the Pusher notification (null otherwise).') parser.add_argument('--programname', '-pn', type=str, required=False, default=None, help='Program Name, if present it\'s added to the Pusher notification (null otherwise).') parser.add_argument('--logfile', '-log', type=str, help='Log file path. If not defined it will default\ to the tvstation name.log') args=parser.parse_args() if args.inputfile is None: print "Reading from stdin..." recog = Recognize(None, sourceid=args.sourceid, region=args.regionid, programname=args.programname, programid=args.programid, scheduleid=args.scheduleid) recog.recognize() else: print "Reading from file: ", print args.inputfile, print "..." recog = Recognize(args.inputfile, sourceid=args.sourceid, region=args.regionid, programname=args.programname, programid=args.programid, scheduleid=args.scheduleid) recog.recognize() sys.exit(1) if len(sys.argv) == 1: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) elif sys.argv[1] == "-r": # if len(sys.argv) != 3: # print "Format is \n python main.py -[r/g/l] [labels_file] video_name" # raise Exception(INCORRECT_FORMAT_ERROR) # file_type = mimetypes.guess_type(sys.argv[2])[0] # if file_type[:3] != "vid":#The file is not a video file # print "Invalid video file" # raise Exception(INCORRECT_VIDEO_FILE_ERROR) # if len(sys.argv) == 3: print "Recognizing: ", sys.argv[2] recog = Recognize(sys.argv[2]) recog.recognize() if len(sys.argv) == 2: print "Recognizing from stdin" recog = Recognize(None) recog.recognize() else: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) elif sys.argv[1] == "-g": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex":#The file is not a labels file print "Invalid labels file" raise Exception(INCORRECT_LABEL_FILE_ERROR) if video_file_type[:3] != "vid":#The file is not a video file print "Invalid video file" raise Exception(INCORRECT_VIDEO_FILE_ERROR) print "Generating db for video: ", sys.argv[3], "\nwith labels file:", sys.argv[2] gen = Generate(sys.argv[2], sys.argv[3]) gen.run() elif sys.argv[1] == "-l": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex":#The file is not a labels file return INCORRECT_LABEL_FILE_ERROR if video_file_type[:3] != "vid":#The file is not a video file return INCORRECT_VIDEO_FILE_ERROR print "Learning for video: ", sys.argv[3] video_name = sys.argv[3] ffmpeg.convert_video(video_name) name, extension = video_name[-5:].split('.') name = video_name.split('/')[-1] name = name[:-len(extension)-1] os.system("cp " + sys.argv[2] + " " + WEB_LABELS) os.system("mv " + name + '.webm ' + 'web/output/static/output/' + WEB_VIDEO_NAME) print "Please go to the URL to edit labels" return SUCCESS
y/n on lines once quit, save lines in 'savedlines/' ''' conjunctions = [ 'and', 'but', 'yet', 'or', 'because', 'for', 'nor', 'so', 'rather than', 'as much as' ] compares = [ 'is better than', 'is worse than', 'could never defeat a', 'would win in a fight with a', 'could never f**k a', 'always made me feel like a', 'could never be as good as a' ] createstuff = Generate() createstuff.load_lines() lines = createstuff.lines save_lines = [] for l in lines: os.system("clear") rand_l = random.choice(lines) out_l = l + ' ' + random.choice(compares) + ' ' + rand_l print(out_l, '\n', 'y/n?', '\n')
def main(): if len(sys.argv) == 1: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) elif sys.argv[1] == "-r": if len(sys.argv) != 3: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) file_type = mimetypes.guess_type(sys.argv[2])[0] if file_type[:3] != "vid":#The file is not a video file print "Invalid video file" raise Exception(INCORRECT_VIDEO_FILE_ERROR) print "Recognizing: ", sys.argv[2] recog = Recognize(sys.argv[2]) recog.recognize() elif sys.argv[1] == "-g": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex":#The file is not a labels file print "Invalid labels file" raise Exception(INCORRECT_LABEL_FILE_ERROR) if video_file_type[:3] != "vid":#The file is not a video file print "Invalid video file" raise Exception(INCORRECT_VIDEO_FILE_ERROR) print "Generating db for video: ", sys.argv[3], "\nwith labels file:", sys.argv[2] gen = Generate(sys.argv[2], sys.argv[3]) gen.run() elif sys.argv[1] == "-l": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex":#The file is not a labels file return INCORRECT_LABEL_FILE_ERROR if video_file_type[:3] != "vid":#The file is not a video file return INCORRECT_VIDEO_FILE_ERROR print "Learning for video: ", sys.argv[3] video_name = sys.argv[3] ffmpeg.convert_video(video_name) name, extension = video_name[-5:].split('.') name = video_name.split('/')[-1] name = name[:-len(extension)-1] os.system("cp " + sys.argv[2] + " " + WEB_LABELS) os.system("mv " + name + '.webm ' + 'web/output/static/output/' + WEB_VIDEO_NAME) print "Please go to the URL to edit labels" return SUCCESS
random([adj, adv, verb]) + TopicWord once quit, save lines in 'saved/' Parameters ------- n_pairs: int - Number of pairs to generate - Ex: python make_pairs.py 420 ''' n_pairs = 100 if len(sys.argv) > 1: n_pairs = int(sys.argv[1]) pairs = Generate().pairs(n_pairs=n_pairs) pairs = [x[0] + ' ' + x[1] for x in pairs] pairs = list(sorted(pairs)) pairs.sort(key=len) save_lines = [] for p in pairs: os.system('clear') print(p, '\n', 'y/n?', '\n') inp = input() if inp == 'j': save_lines.append(p) os.system('clear') elif inp == 'q':
def test_generated_string_len_is_valid(self): s2 = Generate.str_generator(65) self.assertTrue(len(s2) > 1 and len(s2) <= 65)
print("Gerando csv detalhado (animal_train.csv) a partir do arquivo train.csv ......................... ") data = PrepareData(train) f = open('animal_train.csv', 'wb') for line in data.x: f.write((str(line)).split("[")[1].split("]")[0] + "\n") f.close() print("Gerando csv detalhado (animal_test.csv) a partir do arquivo test.csv ......................... ") t = open('animal_test.csv', 'wb') for line in data.PrepareTestFile(test): #f.write((str(line)).split("[")[1].split("]")[0] + "\n") t.write(str(line) + "\n") t.close() print("Trantando dados gerados ......................... ") geracao = Generate(data.x,data.y) if treino !=1: ## TRAIN PREDICT geracao.predict_class(data.x,data.y,"animal_test.csv",epocas,ciclos) if treino ==1: ## RANDOM lines=0 with open ('test.csv','rb') as f: for line in f: lines+=1 print ("Linhas: ",lines-1) geracao.random(lines-1)
from generate import Generate from solve import Solve print(""" =============+ * Suduku * =============+ """) suduku = Generate(Generate.EASY) suduku.generate_grid() suduku.setup_game_grid() print(f" {suduku.failures+1} attemps to generate the grid\n\n") for row in suduku.grid: print("|-----------|-----------|-----------|") print(f"| {' | '.join([str(i) if i != 0 else ' ' for i in row])} |") print("|-----------|-----------|-----------|") print(""" The Game """) for row in suduku.game_grid: print("|-----------|-----------|-----------|") print(f"| {' | '.join([str(i) if i != 0 else ' ' for i in row])} |") print("|-----------|-----------|-----------|")
from flask import Flask, render_template from flask_login import LoginManager from generate import Generate app = Flask(__name__, template_folder='templates') app.config.from_object('config') lm = LoginManager(app) lm.login_view = 'admin.login' lm.login_message = '请先登录,管理员' gen = Generate() # Generate类进行实例化 @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_error(e): return render_template('500.html'), 500 from . import main, api, admin # 在后面导入文件,并且注册蓝图 from .api import api from .admin import admin app.register_blueprint(api, url_prefix='/api') app.register_blueprint(admin, url_prefix='/admin')
def interpolation_graph(generator: Generate, label_left: np.ndarray, label_right: np.ndarray, seed_left: int, seed_right: int, num_steps: int, delta_magnitude: float, distance_measure: str, magnitude_sampling: str, normalize: bool) -> Tuple[str, float]: assert magnitude_sampling in ['linear', 'normal'] assert distance_measure in ['gradient', 'vgg16'] plt.figure() latent_left = utils.get_random_latent(seed_left) latent_right = utils.get_random_latent(seed_right) dlatent_left = generator.map_latent_and_label(latent_left, label_left) dlatent_right = generator.map_latent_and_label(latent_right, label_right) x_axis = [] y_axis = [] if magnitude_sampling == 'linear': magnitudes = np.linspace(0, 1, num_steps) if magnitude_sampling == 'normal': magnitudes = np.sort( np.clip(np.random.normal(0.5, 0.2, size=[num_steps]), 0, 1)) magnitudes[0] = 0 magnitudes[-1] = 1 for j in range(num_steps): current_magnitude = magnitudes[j] if distance_measure == 'gradient': grads = generator.gradient_delta_interpolate( dlatent_left=dlatent_left, dlatent_right=dlatent_right, magnitude=current_magnitude, delta_magnitude=delta_magnitude) sum_square_grads = np.sum(np.square(grads), axis=2) distance = np.sqrt(np.mean(sum_square_grads, axis=1))[0] if distance_measure == 'vgg16': distance = generator.vgg16_distance( dlatent_left=dlatent_left, dlatent_right=dlatent_right, magnitude=current_magnitude, delta_magnitude=delta_magnitude) x_axis.append(current_magnitude) y_axis.append(distance) y_axis = np.array(y_axis) linear_diff = [] linear_func = [] if normalize: y_axis = (y_axis - min([y_axis[0], y_axis[-1]])) / np.abs(y_axis[0] - y_axis[-1]) distance_start_end = np.abs(y_axis[0] - y_axis[-1]) for j in range(num_steps): x = magnitudes[j] f = y_axis[0] + x * (y_axis[-1] - y_axis[0]) / x_axis[-1] linear_func.append(f) linear_diff.append(np.square((y_axis[j] - f) * distance_start_end)) linear_diff = np.mean(linear_diff) plt.plot(x_axis, y_axis) plt.plot(x_axis, linear_func) plt.xlabel('interpolation magnitude') if distance_measure == 'gradient': plt.ylabel('gradient magnitude in W') if distance_measure == 'vgg16': plt.ylabel('perceptual distance') plt.xticks(np.arange(0.0, 1.1, 0.1)) buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) image_buf = Image.open(buf) graph_image = utils.convert_to_base64_str(image_buf) buf.close() plt.clf() return graph_image, float(linear_diff)
def main(): if len(sys.argv) == 1: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) elif sys.argv[1] == "-r": if len(sys.argv) != 3: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) file_type = mimetypes.guess_type(sys.argv[2])[0] if file_type[:3] != "vid": #The file is not a video file print "Invalid video file" raise Exception(INCORRECT_VIDEO_FILE_ERROR) print "Recognizing: ", sys.argv[2] recog = Recognize(sys.argv[2]) recog.recognize() elif sys.argv[1] == "-g": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex": #The file is not a labels file print "Invalid labels file" raise Exception(INCORRECT_LABEL_FILE_ERROR) if video_file_type[:3] != "vid": #The file is not a video file print "Invalid video file" raise Exception(INCORRECT_VIDEO_FILE_ERROR) print "Generating db for video: ", sys.argv[ 3], "\nwith labels file:", sys.argv[2] gen = Generate(sys.argv[2], sys.argv[3]) gen.run() elif sys.argv[1] == "-l": if len(sys.argv) != 4: print "Format is \n python main.py -[r/g/l] [labels_file] video_name" raise Exception(INCORRECT_FORMAT_ERROR) label_file_type = mimetypes.guess_type(sys.argv[2])[0] video_file_type = mimetypes.guess_type(sys.argv[3])[0] if label_file_type[:3] != "tex": #The file is not a labels file return INCORRECT_LABEL_FILE_ERROR if video_file_type[:3] != "vid": #The file is not a video file return INCORRECT_VIDEO_FILE_ERROR print "Learning for video: ", sys.argv[3] video_name = sys.argv[3] ffmpeg.convert_video(video_name) name, extension = video_name[-5:].split('.') name = video_name.split('/')[-1] name = name[:-len(extension) - 1] os.system("cp " + sys.argv[2] + " " + WEB_LABELS) os.system("mv " + name + '.webm ' + 'web/output/static/output/' + WEB_VIDEO_NAME) print "Please go to the URL to edit labels" return SUCCESS
data = PrepareData(train) f = open('animal_train.csv', 'wb') for line in data.x: f.write((str(line)).split("[")[1].split("]")[0] + "\n") f.close() print( "Gerando csv detalhado (animal_test.csv) a partir do arquivo test.csv ......................... " ) t = open('animal_test.csv', 'wb') for line in data.PrepareTestFile(test): #f.write((str(line)).split("[")[1].split("]")[0] + "\n") t.write(str(line) + "\n") t.close() print("Trantando dados gerados ......................... ") geracao = Generate(data.x, data.y) if treino != 1: ## TRAIN PREDICT geracao.predict_class(data.x, data.y, "animal_test.csv", epocas, ciclos) if treino == 1: ## RANDOM lines = 0 with open('test.csv', 'rb') as f: for line in f: lines += 1 print("Linhas: ", lines - 1) geracao.random(lines - 1)
from generate import Generate Generate()
#!/usr/bin/python # -*- coding:utf-8 -*- import time from staticblog import app from generate import Generate if __name__ == '__main__': gen = Generate() t = time.time() gen() print('生成完成!!!', time.time() - t) app.run()
def test_generated_string_is_random(self): s1 = Generate.str_generator() s2 = Generate.str_generator() self.assertNotEqual(s1, s2)