def submit():
	if request.method == 'POST':
		file = open('input.txt', 'w')
		file.write(request.form['message'])
		file.close()
		Builder.create_new_page()
	return render_template('index.html')
Esempio n. 2
0
    def populate(self):
        FARMER_COUNT = 5
        VILLAGER_COUNT = 5
        BUILDER_COUNT = 1

        # adds all the people and make sure they don't go all ape shit
        lumber1 = LumberYard(self, self.lumberyard_img)
        lumber1.location = Vector2(self.w / 2, self.h / 2)
        lumber1.tile_x, lumber1.tile_y = 4, 4
        self.add_entity(lumber1)

        for Villager_no in xrange(VILLAGER_COUNT):  # Adds all Wood Cutters
            villager = Lumberjack(self, self.lumberjack_img)
            villager.location = lumber1.location.copy()
            villager.LastLumberYard = lumber1
            villager.brain.set_state("Searching")
            self.add_entity(villager)
            self.population += 1

        for Building_no in xrange(BUILDER_COUNT):
            builder = Builder(self, self.builder_img, lumber1)
            builder.location = lumber1.location.copy()
            builder.brain.set_state("Idle")
            self.add_entity(builder)
            self.population += 1

        for FARMER in xrange(FARMER_COUNT):  # Adds all the farmers
            farmer = Farmer(self, self.farmer_img)
            farmer.location = lumber1.location.copy()
            farmer.brain.set_state("Planting")
            self.add_entity(farmer)
            self.population += 1
    def on_data(self, data):
        filter_file = open("filter.txt", "r")
        filter_lines = [x.strip('\n') for x in filter_file.readlines()]
        if any(x in data for x in filter_lines):
            print "Data failed Check moving to next"
        else:
            print data
            #Editing to dump to text
            if 'media_url' in data:
                text_file = open("Output.txt", "a")
                text_file.write(data)
                text_file.close()
                self.num_tweets = self.num_tweets + 1
        if self.num_tweets < 8:
            return True
        else:
            text_file.close()
            filter_file.close()
            Builder.build_func()
            FtpPush.push_data()

            print('Starting Timer')
            time.sleep(300)
            print('Sleep Complete')
            main()
            return False
    def __init__(self,master):
        print ("room_gen_gui_002.py")
        print ("\nGUI FUNCTION: __init__")
        self.builder = Builder()
        frame=Frame(master)
        frame.pack()

        Label(frame,text='MINECRAFT ROOM GENERATOR').grid(row=0,columnspan=3)

        Button(frame,text='SET CORNER',command=self.btn_findgold).grid(row=1,column=1)
        Label(frame,text='Blocks x').grid(row=2,column=0)
        self.x_var = IntVar()
        Entry(frame, textvariable=self.x_var).grid(row=2,column=1)
        Label(frame,text='Blocks y').grid(row=3,column=0)
        self.y_var = IntVar()
        Entry(frame, textvariable=self.y_var).grid(row=3,column=1)
        Label(frame,text='Blocks z').grid(row=4,column=0)
        self.z_var = IntVar()
        Entry(frame, textvariable=self.z_var).grid(row=4,column=1)

        Button(frame,text='LIST',command=self.btn_list).grid(row=5,column=0)

        Button(frame,text='BUILD',command=self.btn_build).grid(row=5,column=1)

        Button(frame,text='QUIT',command=exit).grid(row=5,column=2)

        self.reset_interface()
Esempio n. 5
0
    def run(self, env):
        trusted_hosts = []
        # These are necessary for older hosts with out of date certs or pip
        if self.trust_hosts:
            trusted_hosts = ['--trusted-host', 'pypi.org', '--trusted-host', 'files.pythonhosted.org']

        # setuptools must be installed before packages that need it, or else it won't be in the
        # package database in time for the subsequent install and pip fails
        steps = []
        for deps in (self.core, self.deps):
            if deps:
                steps.append([self.python, '-m', 'pip', 'install', '--upgrade', *trusted_hosts, *deps])

        return Builder.Script(steps, name='install-python-reqs')
Esempio n. 6
0
def switchHisTautomer(his=None):
	
	"""
	switches the histidine tautomer by changing the HNE to a HND or vice versa
	takes in a residue object
	"""

	if his.name != "HIS":
		return

	billder = Builder()
	# --- check to see if it's an HID or HIE --- #
	if his.atomExists(" HE2"):
		H = his.getAtom(" HE2")
		A = his.getAtom(" ND1")
		B = his.getAtom(" CG ")
		C = his.getAtom(" CD2")
		name = " HD1"
	elif his.atomExists(" HD1"):
		H = his.getAtom(" HD1")
		A = his.getAtom(" NE2")
		B = his.getAtom(" CD2")
		C = his.getAtom(" CG ")
		name = " HE2"
	else:
		return

	if H == None or A == None or B == None or C == None:
		print "cannot find base atoms for switching tautomer"
		return

	crd = billder.dbuildAtom(A, B, C, 1.01, 126, 180)
	H.coord.x = crd[0]
	H.coord.y = crd[1]
	H.coord.z = crd[2]
	H.name = name
Esempio n. 7
0
    def run(self, env):
        sh = env.shell
        clang_tidy = env.find_llvm_tool('clang-tidy')[0]
        if not clang_tidy:
            print("No clang-tidy executable could be found, installing...")
            sh.exec("sudo", "apt", "install", "-y", "clang-tidy-9")
            clang_tidy = env.find_llvm_tool('clang-tidy')[0]
            if not clang_tidy:
                print("No clang-tidy executable could be found")
                sys.exit(1)

        source_dir = sh.cwd()
        build_dir = os.path.join(source_dir, 'build')
        sources = [
            os.path.join(source_dir, file)
            for file in glob.glob('source/**/*.c')
            if not ('windows' in file or 'android' in file)
        ]

        return [
            Builder.DownloadDependencies(),
            Builder.CMakeBuild(),
            Builder.Script([[clang_tidy, '-p', build_dir] + sources])
        ]
Esempio n. 8
0
def main():
    Support.log(msg="# Parsing and checking the input arguments\n", level="STEP")
    args = Argparser.parse_mascotte_arguments()
    logArgs(args)
    if args['rndseed'] != None:
        random.seed(args['rndseed'])

    Support.log(msg="# Setting up for simulating human diploid genome\n", level="STEP")
    human = Genomics.HumanGenome(reference=args['reference'], snplist=args['snplist'], snpratio=args['snpratio'], HEHOratio=args['HEHOratio'], ignorelist=args['ignore'])
    maternalhuman = os.path.join(args['xdir'], 'human.maternal.fa')
    paternalhuman = os.path.join(args['xdir'], 'human.paternal.fa')
    Support.log(msg="# Simulating human diploid genome\n", level="STEP")
    human.buildGenome(maternalout=maternalhuman, paternalout=paternalhuman)
    Support.log('Chromosomes: {}\n'.format(', '.join(human.chromosomes)), level='INFO')
    Support.log('Number of simulated SNPs: {}\n'.format(human.numsnps), level='INFO')
    Support.log('Number of heterozygous SNPs: {}\n'.format(human.hetsnps), level='INFO')
    Support.log('Maternal chromosome of human genome written in {}\n'.format(maternalhuman), level='INFO')
    Support.log('Maternal chromosome of human genome written in {}\n'.format(paternalhuman), level='INFO')

    Support.log(msg="# Simulating tumor clones and their evolution through specified CNAs\n", level="STEP")
    tumor = Mutation.simulateEvolution(numclones=args['numclones'], humanGenome=human, binsize=args['binsize'], mutations=args['mutations'])
    Support.log('Simulated tumor clones: {}\n'.format(', '.join([clone.label for clone in tumor.clones])), level='INFO')
    Support.log('Founder tumor clone: {}\n'.format(tumor.root.label), level='INFO')
    with open(os.path.join(args['xdir'], 'tumor.dot'), 'w') as o: o.write("{}\n".format(tumor.draw()))
    Support.log('The resulting tumor evolution of clones and related CNAs have been drawn in {} as dot format\n'.format(os.path.join(args['xdir'], 'tumor.dot')), level='INFO')
    Support.log('Genome length of the various tumor clones:\n\t{}\n'.format('\n\t'.join(['{}: {}'.format(clone.label, clone.genomeLength()) for clone in tumor.clones])), level='INFO')
    Support.log('Computing and segmenting the copy-number profiles jointly for all tumor clones\n', level='INFO')
    segments = segmentation(evolution=tumor)
    Support.log('Total number of resulting segments= {}\n'.format(sum(len(segments[chro]) for chro in tumor.human.chromosomes)), level='INFO')
    segout = os.path.join(args['xdir'], 'copynumbers.csv')
    with open(segout, 'w') as o:
        o.write('\t'.join(['#CHR', 'START', 'END'] + [clone.label for clone in tumor.clones]) + '\n')
        o.write('\n'.join(['\t'.join(map(str, [chro, seg[0], seg[1]]+['{}|{}'.format(segments[chro][seg][clone.idx]['m'], segments[chro][seg][clone.idx]['p']) for clone in tumor.clones])) for chro in tumor.human.chromosomes for seg in sorted(segments[chro], key=(lambda x : x[0]))]))
        o.write('\n')
    Support.log('The allele-specific copy number profiles for every tumor clone has been written in {}\n'.format(segout), level='INFO')
    Support.log('Writing the FASTA-format genomes of tumor clones\n', level='INFO')
    if args['jobs'] == 1:
        for clone in tumor.clones:
            maternalout = os.path.join(args['xdir'], '{}.maternal.fa'.format(clone.label))
            paternalout = os.path.join(args['xdir'], '{}.paternal.fa'.format(clone.label))
            clone.buildGenome(maternalout, paternalout)
    else:
        builder = Builder.CloneGenomeBuilder(tumor, args['xdir'])
        builder.parallelbuild(args['jobs'])
    Support.log('Tumor-clone genomes wrote in:\n{}\n'.format('\n'.join(['\t{}: maternal > {} and paternal > {}'.format(clone.label, os.path.join(args['xdir'], '{}.maternal.fa'.format(clone.label)), os.path.join(args['xdir'], '{}.paternal.fa'.format(clone.label))) for clone in tumor.clones])), level='INFO')
    Support.log('KTHXBY!\n', level='STEP')
Esempio n. 9
0
def generate(toBuild, automata, paint):
    postfixer = Postfixer()
    if (toBuild == "AFD"):
        inFixRegEx = "(" + automata + ")"
        inFixRegEx += ".#"
        inFixRegEx = postfixer.to_postfix(inFixRegEx)
        builder = Builder(inFixRegEx)
    else:
        postfixRegex = postfixer.to_postfix(automata)
        builder = Builder(postfixRegex)
    #paso de generar tokens
    builder.generator()
    #array de tokens devuelto por
    tokens = builder.getTokenArr()
    parser = Parser()

    return parser.parse(tokens, toBuild, paint)
Esempio n. 10
0
    def run(self, inState):
        inState.mBuilder = Builder.Builder(inState.getView())

        hierarchy = Trees.getMeshHierarchy(inState.getView().getOutputNode())
        hierarchy = hierarchy.filterByShape(['mesh'])
        if hierarchy is None:
            raise Exception(
                'Filtered hierarchy contains no valid mesh elements!')

        hierarchy.mDataBuilder = None

        # The pivot root isn't always going to be the primary root of the object, so ensure it's invalidated
        if len(hierarchy.mChildren) <= 1:
            hierarchy.mChildren[0].iterate(
                inState.getBuilder().fillHierarchyInfo)
        else:
            hierarchy.iterate(inState.getBuilder().fillHierarchyInfo)

        inState.mCachedHierarchy = hierarchy
Esempio n. 11
0
def run_clang_tidy(env):
    sh = env.shell
    toolchain = env.toolchain
    clang_tidy = Builder.Util.where('clang-tidy')
    if not clang_tidy:
        clang_tidy = toolchain.find_llvm_tool('clang-tidy')[0]
    if not clang_tidy:
        print("No clang-tidy executable could be found")
        sys.exit(1)

    sources = [
        os.path.join(env.source_dir, file)
        for file in glob.glob('source/**/*.c') + glob.glob('source/*.c')
        if not ('windows' in file or 'android' in file)
    ]

    return Builder.Script(
        [[clang_tidy, '-p',
          os.path.join(env.build_dir, env.project.name)] + sources])
Esempio n. 12
0
    def run(self, env):
        # allow custom python to be used
        parser = argparse.ArgumentParser()
        parser.add_argument('--python')
        args = parser.parse_known_args(env.args.args)[0]
        python = args.python if args.python else sys.executable

        actions = [
            InstallPythonReqs(deps=[], python=python),
            SetupForTests(),
            [python, '-m', 'pip', 'install', '--verbose', '.'],
            # "--failfast" because, given how our leak-detection in tests currently works,
            # once one test fails all the rest usually fail too.
            [python, '-m', 'unittest', 'discover', '--verbose', '--failfast'],
            # http_client_test.py launches external processes using the extra args
            [python, 'crt/aws-c-http/integration-testing/http_client_test.py',
                python, 'elasticurl.py'],
        ]

        return Builder.Script(actions, name='aws-crt-python')
Esempio n. 13
0
    def run(self, env):
        install_options = []
        if 'linux' == Builder.Host.current_os():
            install_options = [
                '--install-option=--include-dirs={openssl_include}',
                '--install-option=--library-dirs={openssl_lib}']

        actions = [
            InstallPythonReqs(deps=['boto3'], python=self.custom_python),
            [self.custom_python, '-m', 'pip', 'install', '.', '--install-option=--verbose',
                '--install-option=build_ext', *install_options],
            # "--failfast" because, given how our leak-detection in tests currently works,
            # once one test fails all the rest usually fail too.
            [self.custom_python, '-m', 'unittest', 'discover', '--verbose', '--failfast'],
            # http_client_test.py is python3-only. It launches external processes using the extra args
            [self.python3, 'aws-common-runtime/aws-c-http/integration-testing/http_client_test.py',
                self.custom_python, 'elasticurl.py'],
        ]

        return Builder.Script(actions, name=self.name)
Esempio n. 14
0
    def populate(self):
        """adds all the people and make sure they don't go all ape shit
        """
        FARMER_COUNT = 4
        VILLAGER_COUNT = 5
        BUILDER_COUNT = 1

        lumber1 = Building.LumberYard(self, self.lumberyard_img)
        lumber1.location = vector2.Vector2(self.w / 2, self.h / 2)
        lumber1.tile_x, lumber1.tile_y = 4, 4
        self.add_entity(lumber1)

        for Villager_no in xrange(VILLAGER_COUNT):
            """Adds all Wood Cutters
            """
            villager = Lumberjack.Lumberjack(self, self.lumberjack_img)
            villager.location = lumber1.location.copy()
            villager.LastLumberYard = lumber1
            villager.brain.set_state("Searching")
            self.add_entity(villager)
            self.population += 1

        for Building_no in xrange(BUILDER_COUNT):
            builder = Builder.Builder(self, self.builder_img, lumber1)
            builder.location = lumber1.location.copy()
            builder.brain.set_state("Idle")
            self.add_entity(builder)
            self.population += 1

        for FARMER in xrange(FARMER_COUNT):
            """Adds all the farmers
            """
            farmer = Farmer.Farmer(self, self.farmer_img)
            farmer.location = vector2.Vector2(20, 20)
            farmer.brain.set_state("Planting")
            self.add_entity(farmer)
            self.population += 1
Esempio n. 15
0
class App:
    def __init__(self, master):
        print("room_gen_gui_002.py")
        print("\nGUI FUNCTION: __init__")
        self.builder = Builder()
        frame = Frame(master)
        frame.pack()

        Label(frame, text='MINECRAFT ROOM GENERATOR').grid(row=0, columnspan=3)

        Button(frame, text='SET CORNER',
               command=self.btn_findgold).grid(row=1, column=1)
        Label(frame, text='Blocks x').grid(row=2, column=0)
        self.x_var = IntVar()
        Entry(frame, textvariable=self.x_var).grid(row=2, column=1)
        Label(frame, text='Blocks y').grid(row=3, column=0)
        self.y_var = IntVar()
        Entry(frame, textvariable=self.y_var).grid(row=3, column=1)
        Label(frame, text='Blocks z').grid(row=4, column=0)
        self.z_var = IntVar()
        Entry(frame, textvariable=self.z_var).grid(row=4, column=1)

        Button(frame, text='LIST', command=self.btn_list).grid(row=5, column=0)

        Button(frame, text='BUILD', command=self.btn_build).grid(row=5,
                                                                 column=1)

        Button(frame, text='QUIT', command=exit).grid(row=5, column=2)

        self.reset_interface()

    def btn_list(self):
        print("\nGUI FUNCTION: btn_list")
        self.builder.print_corners()

    def reset_interface(self):
        print("\nGUI FUNCTION: reset_interface")
        self.x_var.set(1)
        self.y_var.set(1)
        self.z_var.set(1)

    def btn_build(self):
        print("\nGUI FUNCTION: btn_build")
        #TODO is 'index' a member of room_gen_gui_002???
        #index defines which corner to build off of. THIS IS TEMPORARY. Eventually a selection
        # box will be included in the GUI to allow the user to select a specific index
        index = 0
        mode = self.builder.set_build_mode(index)
        if (mode != "default"):
            self.builder.set_dims(self.x_var.get(), self.y_var.get(),
                                  self.z_var.get())
            self.builder.set_materials(57, 35, 20, 5, 45, 246)
            #TODO put a list of constant variables with the names of the materials at the top.
            # NOTE: THE FOLLOWING HARDCODES THE BUILD TO HAPPEN AT THE FIRST
            # DEFINED CORNER
            self.builder.builder(index)

    def btn_findgold(self):
        print("\nGUI FUNCTION: btn_findgold")
        self.builder.find_gold()
Esempio n. 16
0
 def GetBuilderByName(self, name):
     '''返回的是基类实例'''
     for i in self.builders:
         if i["name"] == name:
             return Builder.Builder(i)
     return None
Esempio n. 17
0
 def __init__(self, **kwargs):
     super(KivyCamera, self).__init__(**kwargs)
     self.capture = None
     self.builder = builder.FaceDetBuilder()
     self.director = builder.Director(self.builder)
    return net

def improve_weights(net,learning_rate,size):
    net.weight_layers = [w-(learning_rate/size)*nw
                        for w, nw in zip(net.weight_layers, net.weight_errors)]
    return net

def cost_funcion(prediction, answer):
    return (1/2)(answer-prediction)**2

def derivative_cost(prediction, answer):
    return (prediction-answer)
    
if __name__ == "__main__":
    layers = [3,3,3]
    builder = Builder(layers)
    net = builder.generate_net()

    num = 300
    size = 100
    
    for i in range(num):
        for j in range(size):
            lst = [0,0,0]
            lst[0] = random.randint(0,1)
            lst[1] = random.randint(0,1)
            lst[2] = random.randint(0,1)
            net.set_inputs(lst)
            net = propagate(net)
            net = output_error(net,np.array(lst))
            net = hidden_error(net)
Esempio n. 19
0
def newGameState(player):
    state = GameState()
    Builder.buildWorld(state)
    state.addPlayer(player)
    return state
Esempio n. 20
0
import Builder

builder = Builder.SaltWaterBuilder()
salt = builder.get_result().salt
print(salt)
def run_exp(pop_start_size=10, pop_max_size=1280, n_iters=25, string_length=100,\
            value_func=Builder.counting_ones_fitness_func, global_optimum = 100,\
                crossover_operator=2, max_gens=100, n_cores=1):

    global_res = {
        key: []
        for key in ['res_dict', 'iter', 'max_fitness', 'cpu_time']
    }

    for x in range(n_iters):
        start = time.time()

        res = {
            key: []
            for key in [
                'Pop_size', 'best_fitness', 'generation_iter', 'proportions',
                'eval_functions'
            ]
        }

        N = pop_start_size
        optimum_found = False

        while N <= pop_max_size and not optimum_found:
            props = []
            counter = []
            num_gens = 1

            sols = create_solutions(N, string_length)

            # Build first gen and find its fitness
            first_gen = Builder.Population(solutions_list=sols,
                                           previous_iter=0)
            optimum_found, current_optimum = first_gen.get_fitness(
                global_optimum, value_func)

            # Create and select offspring
            best_offspring = first_gen.step_gen(crossover_operator,
                                                value_func,
                                                cores=n_cores)

            # Build new generation and check fitness
            new_gen = Builder.Population(solutions_list=best_offspring,
                                         previous_iter=1)
            optimum_found, next_optimum = new_gen.get_fitness(
                global_optimum, value_func)

            props.append(next_optimum)
            counter.append(num_gens)
            gen_x = new_gen
            num_gens += 1

            while not optimum_found and current_optimum <= next_optimum and num_gens <= max_gens:
                current_optimum = next_optimum

                # Create and select offspring
                best_offspring = gen_x.step_gen(crossover_operator,
                                                value_func,
                                                cores=n_cores)

                # Build new generation and check fitness
                new_gen = Builder.Population(solutions_list=best_offspring,
                                             previous_iter=gen_x.current_iter)
                optimum_found, next_optimum = new_gen.get_fitness(
                    global_optimum, value_func)

                props.append(next_optimum)
                counter.append(num_gens)
                gen_x = new_gen
                num_gens += 1

            res['Pop_size'].append(N)
            res['best_fitness'].append(next_optimum)
            res['generation_iter'].append(num_gens)
            res['eval_functions'].append(num_gens * N)

            #            plt.plot(counter, props)
            #            plt.title('N={}'.format(N))
            #            plt.show()

            last_N = N
            N *= 2

        ##############################################
        ### Optimum was found. Do bisection search ###
        ##############################################
        if optimum_found:
            stepsize = (last_N - last_N / 2) / 2
            N = last_N - stepsize

            while stepsize >= pop_start_size:
                props = []
                counter = []
                num_gens = 1
                last_N = N

                # Do generations until optimum is found or not
                sols = create_solutions(int(N), string_length)
                first_gen = Builder.Population(solutions_list=sols,
                                               previous_iter=0)
                optimum_found, current_optimum = first_gen.get_fitness(
                    global_optimum, value_func)

                best_offspring = first_gen.step_gen(crossover_operator,
                                                    value_func,
                                                    cores=n_cores)

                new_gen = Builder.Population(solutions_list=best_offspring,
                                             previous_iter=1)
                optimum_found, next_optimum = new_gen.get_fitness(
                    global_optimum, value_func)

                props.append(next_optimum)
                counter.append(num_gens)
                gen_x = new_gen
                num_gens += 1

                while not optimum_found and current_optimum <= next_optimum and num_gens < max_gens:
                    current_optimum = next_optimum
                    best_offspring = gen_x.step_gen(crossover_operator,
                                                    value_func,
                                                    cores=n_cores)

                    new_gen = Builder.Population(
                        solutions_list=best_offspring,
                        previous_iter=gen_x.current_iter)
                    optimum_found, next_optimum = new_gen.get_fitness(
                        global_optimum, value_func)

                    props.append(next_optimum)
                    counter.append(num_gens)
                    gen_x = new_gen
                    num_gens += 1

                # Write to dict
                res['Pop_size'].append(N)
                res['best_fitness'].append(next_optimum)
                res['generation_iter'].append(num_gens)
                res['eval_functions'].append(num_gens * N)

                # plt.plot(counter, props)
                # plt.title('N={}'.format(N))
                # plt.show()

                if optimum_found:
                    N -= stepsize
                else:
                    N += stepsize

                # Change stepsize
                stepsize /= 2

        fitness = (max(res['best_fitness']) / global_optimum) * 100
        mean_gens = sum(res['generation_iter']) / len(res['generation_iter'])

        end = time.time()
        print(
            '{0}: Found global fitness max of {1:.0f}%, N={2} ({3:.2f}s, {4:.2f} gens)'
            .format(x + 1, fitness, int(last_N), end - start, mean_gens))

        global_res['res_dict'].append(res)
        global_res['iter'].append(x)
        global_res['max_fitness'].append(max(res['best_fitness']))
        global_res['cpu_time'].append(end - start)

    return global_res
Esempio n. 22
0
def newSimulationState(player):
    state = GameState()
    Builder.buildCombatSimulator(state)
    state.addPlayer(player)
    return state
Esempio n. 23
0
def generate(generation, optimum, fitness_func, crossover_operator):
    best_offspring = generation.step_gen(crossover_operator, fitness_func, cores=n_cores)
    new_gen = builder.Population(solutions_list=best_offspring, previous_iter=generation.current_iter)
    return new_gen
Esempio n. 24
0
    best_offspring = generation.step_gen(crossover_operator, fitness_func, cores=n_cores)
    new_gen = builder.Population(solutions_list=best_offspring, previous_iter=generation.current_iter)
    return new_gen
    
    
N = 40
glob_opt = 100
max_gen_iters = 100
n_cores = 1
fitness_function = builder.counting_ones_fitness_func
optimum_found = False
cross_over_operator = 2

while True:
    random_start_pop = helper.create_solutions(n=N, string_length=100)
    random_start_pop = builder.Population(random_start_pop,0)
    
    gen_x = random_start_pop
    
    
    for n in range(max_gen_iters):
        optimum_reached, best_fitness = evaluate_generation(gen_x, glob_opt, fitness_func=builder.counting_ones_fitness_func)
        if optimum_reached:
            print('found optimum of {} for generation {} and N of {}'.format(glob_opt, gen_x.current_iter, N))
            break
        new_gen = generate(gen_x,glob_opt,fitness_function, cross_over_operator)
        gen_x = new_gen
    if not optimum_reached:
        N = N * 2
        if N > 1280:
            N = 1280
Esempio n. 25
0
meta = pd.read_csv('/home/bigpandas/nba_meta.csv')
series = pd.read_csv('/home/bigpandas/nba_series.csv')

nba_df = ingames.merge(lastmeeting,
                       on='GAME_ID').merge(meta,
                                           on='GAME_ID').merge(series,
                                                               on='GAME_ID')

nbadict = process_data(nba_df)
model_training_input = np.array(nbadict['model_input'])[:30076]
model_testing_input = np.array(nbadict['model_input'])[30076:]
nbadict['model_input']

model_training_output = np.array(nbadict['labels'])[:30076]
model_testing_output = np.array(nbadict['labels'])[30076:]
grant_model_test = Builder.BuildNeuralNet(model_training_input,
                                          model_training_output)

# In[3]:

nba_scrape = NBAScraper
nbadict = process_data(nba_df)
model_training_input = np.array(nbadict['model_input'])[:30076]
model_testing_input = np.array(nbadict['model_input'])[30076:]

model_training_output = np.array(nbadict['labels'])[:30076]
model_testing_output = np.array(nbadict['labels'])[30076:]
grant_model_test.evaluate(model_testing_input, model_testing_output)

# In[4]:

Builder.Predict(model_testing_input[4], grant_model_test)
Esempio n. 26
0
    def run(self, env):
        def _doit(env):
            sh = env.shell
            sh.exec('true', retries=3)

        return Builder.Script([_doit])
Esempio n. 27
0
    def _try_setup_pkcs11(self):
        """Attempt to setup for PKCS#11 tests, but bail out if we can't get SoftHSM2 installed"""

        # currently, we only support PKCS#11 on unix
        if sys.platform == 'darwin' or sys.platform == 'win32':
            print(f"PKCS#11 on '{sys.platform}' is not currently supported. PKCS#11 tests are disabled")
            return

        # try to install SoftHSM2, so we can run PKCS#11 tests
        try:
            softhsm2_install_action = Builder.InstallPackages(['softhsm'])
            softhsm2_install_action.run(self.env)
        except Exception:
            print("WARNING: SoftHSM2 could not be installed. PKCS#11 tests are disabled")
            return

        softhsm2_lib = self._find_softhsm2_lib()
        if softhsm2_lib is None:
            print("WARNING: libsofthsm2.so not found. PKCS#11 tests are disabled")
            return

        # put SoftHSM2 config file and token directory under the temp dir.
        softhsm2_dir = os.path.join(tempfile.gettempdir(), 'softhsm2')
        conf_path = os.path.join(softhsm2_dir, 'softhsm2.conf')
        token_dir = os.path.join(softhsm2_dir, 'tokens')
        if os.path.exists(token_dir):
            self.env.shell.rm(token_dir)
        self.env.shell.mkdir(token_dir)
        self.env.shell.setenv('SOFTHSM2_CONF', conf_path)
        pathlib.Path(conf_path).write_text(f"directories.tokendir = {token_dir}\n")

        # print SoftHSM2 version
        self._exec_softhsm2_util('--version')

        # create token
        token_label = 'my-token'
        pin = '0000'
        init_token_result = self._exec_softhsm2_util('--init-token', '--free', '--label', token_label,
                                                     '--pin', pin, '--so-pin', '0000')

        # figure out which slot the token ended up in.
        #
        # older versions of SoftHSM2 (ex: 2.1.0) make us pass --slot number to the --import command.
        # (newer versions let us pass --label name instead)
        #
        # to learn the slot of our new token examine the output of the --show-slots command.
        # we can't just examine the output of --init-token because some versions
        # of SoftHSM2 (ex: 2.2.0) reassign tokens to random slots without printing out where they went.
        token_slot = self._find_sofhsm2_token_slot()

        # add private key to token
        # key must be in PKCS#8 format
        # we have this stored in secretsmanager
        key_path = self._tmpfile_from_secret('unit-test/privatekey-p8', 'privatekey.p8.pem')
        key_label = 'my-key'
        self._exec_softhsm2_util('--import', key_path, '--slot', token_slot,
                                 '--label', key_label, '--id', 'BEEFCAFE', '--pin', pin)

        # set env vars for tests
        self.env.shell.setenv('AWS_TEST_PKCS11_LIB', softhsm2_lib)
        self.env.shell.setenv('AWS_TEST_PKCS11_PIN', pin)
        self.env.shell.setenv('AWS_TEST_PKCS11_TOKEN_LABEL', token_label)
        self.env.shell.setenv('AWS_TEST_PKCS11_KEY_LABEL', key_label)
Esempio n. 28
0
def main():
    """
solvates a histidine
	"""

    parser = OptionParser()
    parser.add_option("-p", dest="pdbfile", help="pdbfile")
    parser.add_option("-P", dest="pdblist", help="pdblist")
    parser.add_option("-o", dest="outfile", help="outfile")
    parser.add_option("-O", dest="outlist", help="outlist")
    parser.add_option("-r",
                      dest="replace",
                      help="replace",
                      action="store_true")
    parser.add_option("-c", dest="catalytic", help="catalytic")
    parser.set_description(main.__doc__)
    (options, args) = parser.parse_args()

    pdbfiles = []
    if options.pdblist:
        pdbfiles = files_from_list(options.pdblist)
    elif options.pdbfile:
        pdbfiles.append(options.pdbfile)
    else:
        parser.print_help()
        sys.exit()

    outfiles = []
    if options.outlist:
        outfiles = files_from_list(options.outlist)
    elif options.outfile:
        outfiles.append(options.outfile)
    elif options.replace:
        for file in pdbfiles:
            outfiles.append(file)
    else:
        parser.print_help()
        sys.exit()

    if len(outfiles) != len(pdbfiles):
        print "number of input and output files differ"
        sys.exit()

    if not options.catalytic:
        parser.print_help()
        sys.exit()

    icat = int(options.catalytic) - 1
    protein = Enzyme()
    for i in range(len(pdbfiles)):
        protein.readPDB(pdbfiles[i])
        if icat < 0 or icat >= len(protein.catalytic):
            print "accessing catalytic residue out of bounds"
            sys.exit()

        cat = protein.catalytic[icat]
        if cat.name != "HIS":
            print "catalytic residue is not a histidine"
            sys.exit()

        # check protonation state
        if cat.getAtom(" HD1") != None:
            A = cat.getAtom(" NE2")
            B = cat.getAtom(" CD2")
            C = cat.getAtom(" CG ")
        elif cat.getAtom(" HE2") != None:
            A = cat.getAtom(" ND1")
            B = cat.getAtom(" CE1")
            C = cat.getAtom(" NE2")
        else:
            print "unable to determine protonation state"
            sys.exit()

        if A == None or B == None or C == None:
            print "cannot find all 3 atoms"
            sys.exit()

        length = 2.98
        ang = 125.0
        tor = 180.0

        billder = Builder()
        crd = billder.dbuildAtom(A, B, C, length, ang, tor)
        newres = protein.chain[1].newResidue()
        newres.name = "LG2"

        newatm = newres.newAtom()
        newatm.coord.x = crd[0]
        newatm.coord.y = crd[1]
        newatm.coord.z = crd[2]
        newatm.name = "HOH "
        newatm.kind = "HETATM"

        protein.writePDB(outfiles[i])
        protein.clear()
Esempio n. 29
0
def getTree(path):

    Scanner.buildLog(path)
    return Builder.buildTree()
Esempio n. 30
0
class App:
    def __init__(self,master):
        print ("room_gen_gui_002.py")
        print ("\nGUI FUNCTION: __init__")
        self.builder = Builder()
        frame=Frame(master)
        frame.pack()

        Label(frame,text='MINECRAFT ROOM GENERATOR').grid(row=0,columnspan=3)

        Button(frame,text='SET CORNER',command=self.btn_findgold).grid(row=1,column=1)
        Label(frame,text='Blocks x').grid(row=2,column=0)
        self.x_var = IntVar()
        Entry(frame, textvariable=self.x_var).grid(row=2,column=1)
        Label(frame,text='Blocks y').grid(row=3,column=0)
        self.y_var = IntVar()
        Entry(frame, textvariable=self.y_var).grid(row=3,column=1)
        Label(frame,text='Blocks z').grid(row=4,column=0)
        self.z_var = IntVar()
        Entry(frame, textvariable=self.z_var).grid(row=4,column=1)

        Button(frame,text='LIST',command=self.btn_list).grid(row=5,column=0)

        Button(frame,text='BUILD',command=self.btn_build).grid(row=5,column=1)

        Button(frame,text='QUIT',command=exit).grid(row=5,column=2)

        self.reset_interface()

    def btn_list(self):
        print ("\nGUI FUNCTION: btn_list")
        self.builder.print_corners()

    def reset_interface(self):
        print ("\nGUI FUNCTION: reset_interface")
        self.x_var.set(1)
        self.y_var.set(1)
        self.z_var.set(1)

    def btn_build(self):
        print ("\nGUI FUNCTION: btn_build")
        #TODO is 'index' a member of room_gen_gui_002???
        #index defines which corner to build off of. THIS IS TEMPORARY. Eventually a selection
        # box will be included in the GUI to allow the user to select a specific index
        index = 0
        mode = self.builder.set_build_mode(index)
        if (mode != "default"):
            self.builder.set_dims(self.x_var.get(),self.y_var.get(),self.z_var.get())
            self.builder.set_materials(57,35,20,5,45,246)
            #TODO put a list of constant variables with the names of the materials at the top.
            # NOTE: THE FOLLOWING HARDCODES THE BUILD TO HAPPEN AT THE FIRST
            # DEFINED CORNER
            self.builder.builder(index)

    def btn_findgold(self):
        print ("\nGUI FUNCTION: btn_findgold")
        self.builder.find_gold()