def EvaluateMap(chromosome=[0.00, 0.10, 0.10, 0.00], economy=Economy(50)): # Init economy and map economy = Economy(50) gameMap = gamemap.GameMap(economy, 10, 10, *chromosome) output = Output() times = 30 mapcopy = copy.deepcopy(gameMap) armies = [ Game.selectArmy( economy, mapcopy, armyColor="white", output=Output(), aUnitPool=['SoldierClass', 'TechnicianClass', 'MageClass']) for _ in range(times) ] score = sum( [Game(economy, mapcopy, army, output, 0.0).run() for army in armies]) print(score / times) return score / times,
def send(self, blockChain, users, confirmedTransactions, unconfirmedTransactions, transactionsInOrder, to_user, amount): utxo = self.get_owned_utxo(confirmedTransactions, unconfirmedTransactions) index = -1 while True: outputForInput = utxo[random.randint(0, len(utxo) - 1)] for i in range(len(confirmedTransactions[outputForInput].outputs)): if confirmedTransactions[outputForInput].outputs[i].values['amount'] > amount: index = i break if index != -1: break for transaction in confirmedTransactions: if not transaction.verify(users): raise Exception("Fatal error transaction is invalid/modified.") print("Transactions are verified for 'send' transaction.") for i in range(len(blockChain)): if not blockChain[i].validate(confirmedTransactions, transactionsInOrder[i]): raise Exception("Fatal error blockchain is in invalid state.") print("BlockChain validation successful for 'send' transaction.") unconfirmedTransactions.append( Transaction( inputs=[ Input( prevTx=confirmedTransactions[outputForInput].get_txid().hex(), signature=to_user.sign(confirmedTransactions[outputForInput].get_txid()).hex(), index=index, publicKey=to_user.verifyingKey.to_string().hex() ) ], outputs=[ Output( amount=amount ) ] ) ) if amount != confirmedTransactions[outputForInput].outputs[index].values['amount']: unconfirmedTransactions.append( Transaction( inputs=[ Input( prevTx=confirmedTransactions[outputForInput].get_txid().hex(), signature=self.sign(confirmedTransactions[outputForInput].get_txid()).hex(), index=index, publicKey=self.verifyingKey.to_string().hex() ) ], outputs=[ Output( amount=confirmedTransactions[outputForInput].outputs[index].values['amount'] - amount ) ] ) )
def normalize_per_sample(data_feature, data_attribute, data_feature_outputs, data_attribute_outputs): # assume all samples have maximum length data_feature_min = np.amin(data_feature, axis=1) data_feature_max = np.amax(data_feature, axis=1) additional_attribute = [] additional_attribute_outputs = [] dim = 0 for output in data_feature_outputs: if output.type_ == OutputType.CONTINUOUS: for _ in range(output.dim): max_ = data_feature_max[:, dim] min_ = data_feature_min[:, dim] additional_attribute.append((max_ + min_) / 2.0) additional_attribute.append((max_ - min_) / 2.0) additional_attribute_outputs.append( Output(type_=OutputType.CONTINUOUS, dim=1, normalization=output.normalization, is_gen_flag=False)) additional_attribute_outputs.append( Output(type_=OutputType.CONTINUOUS, dim=1, normalization=Normalization.ZERO_ONE, is_gen_flag=False)) max_ = np.expand_dims(max_, axis=1) min_ = np.expand_dims(min_, axis=1) data_feature[:, :, dim] = \ (data_feature[:, :, dim] - min_) / (max_ - min_) if output.normalization == Normalization.MINUSONE_ONE: data_feature[:, :, dim] = \ data_feature[:, :, dim] * 2.0 - 1.0 dim += 1 else: dim += output.dim real_attribute_mask = ([True] * len(data_attribute_outputs) + [False] * len(additional_attribute_outputs)) additional_attribute = np.stack(additional_attribute, axis=1) data_attribute = np.concatenate([data_attribute, additional_attribute], axis=1) data_attribute_outputs.extend(additional_attribute_outputs) return data_feature, data_attribute, data_attribute_outputs, \ real_attribute_mask
def __init__(self, api_uri, debug=False): self.output = Output() self.api_uri = api_uri self.debug = debug if self.debug: self.set_debug()
def __init__(self): print(protologue) self.inp = Input() self.upd = Update() self.world = World(3,4) self.player1 = Player(self.world) self.out = Output()
def from_json(self, json): required = ['inputs', 'outputs', 'duration', 'timestamp'] if not all(k in json for k in required): logging.warning(f'value missing in {required}') return False if not isinstance(json['inputs'], list) or not isinstance(json['outputs'], list) \ or not isinstance(json['timestamp'], float): logging.warning("inputs and outputs should be both type<list> and timestamp should be type<float>") return False for input in json['inputs']: # print(json['inputs']) i = Input() if not i.from_json(input): return False self.add_input(i) for output in json['outputs']: o = Output() if not o.from_json(output): return False self.add_output(o) if not self._duration.from_json(json['duration']): return False self._timestamp = json['timestamp'] return True
def main(send=False): key = get_value('key') html = None # get movie info for all categories for cat in CATEGORIES: td = Tmdb(key, cat) movies = td.get_movies(NUM_RES) ca = Cache(os.path.basename(cat)) ca.shelve_results(movies) newMovies = ca.shelve_results(movies) movieObjects = ca.shelve_get_items(newMovies) # only new ones op = Output(movieObjects) if html is None: html = [op.generate_header()] catPrettified = cat.title().replace("_", " ") html.append(op.generate_category_title(catPrettified)) html.append(op.generate_movie_html_div()) # save html f = open(OUTFILE, "w") f.write("\n".join(html)) f.close() # email if send: subject = "Sharemovi.es / %s movies / week %s" % ( ", ".join(CATEGORIES), str(THIS_WEEK)) sender = get_value('sender') recipients = load_emails('recipients') ma = Mail(sender) ma.mail_html(recipients, subject, "\n".join(html))
def EvaluateUnit(chromosome=[0.00, 0.10, 0.10, 0.00], currentUnit=None, currenArmy=None, gameMap=None, economy=None, unitIdx=None): # Create an instance of our army, based on the original army, which we will use in a given game fodderArmy = copy.deepcopy(currenArmy) # Create a (changeable) map, based on the original map changeableMap = copy.deepcopy(gameMap) currentUnit.strategy.curiosity = chromosome[0] currentUnit.strategy.groupSpirit = chromosome[1] currentUnit.strategy.riskiness = { "SoldierClass": chromosome[2], "TrapClass": chromosome[3], "TowerClass": chromosome[4] } # Base probability to get closer to interact currentUnit.strategy.fasting = chromosome[5] # Base probability to return if hungry currentUnit.strategy.greed = chromosome[6] # Base probability to reach for loot, when not enough has been collected # Update the fodder army with the altered unit fodderArmy[unitIdx] = currentUnit updateArmyWithCurrentMap(fodderArmy, changeableMap) # We create a new game, with the changeable map output = Output() g = Game(economy, changeableMap, fodderArmy, output, 0.0) score = g.run() return score,
def create_source(self, objects=[]): """Create report from objects (list of DNs).""" tmpfile = self.__create_tempfile() admin.set_format(self._type == Document.TYPE_LATEX) parser = Parser(filename=self._template) parser.tokenize() tokens = parser._tokens fd = codecs.open(tmpfile, 'wb+', encoding='utf8') if parser._header: fd.write(parser._header.data) elif self._header: self.__append_file(fd, self._header) for dn in objects: if isinstance(dn, basestring): obj = admin.get_object(None, dn) else: obj = admin.cache_object(dn) if obj is None: print >> sys.stderr, "warning: dn '%s' not found, skipped." % dn continue tks = copy.deepcopy(tokens) interpret = Interpreter(obj, tks) interpret.run() output = Output(tks, fd=fd) output.write() if parser._footer: fd.write(parser._footer.data) elif self._footer: self.__append_file(fd, self._footer) fd.close() return tmpfile
def fcfs(x): x.sort(key=get_arrival) count_done = 0 count_processes = len(x) cpu_time = 0 index = 0 end_time = -1 while count_done != count_processes: process = x[index] if cpu_time < process.arrival_time: cpu_time = process.arrival_time process.start_time = cpu_time cpu_time = cpu_time + process.remain_time process.remain_time = 0 index = index + 1 count_done = count_done + 1 if process.remain_time == 0: process.end_time = cpu_time if end_time < process.end_time: end_time = process.end_time print_process(x) output = Output(cal_awt(x), cal_art(x), cal_att(x), cal_utilization(x, end_time), cal_through_put(x, end_time)) output.print() return output
def run_inverse(): """Invert the remote measurement""" # Configure the surface/atmosphere/instrument model config = load_config('config_inversion.json') fm = ForwardModel(config['forward_model']) iv = Inversion(config['inversion'], fm) out = Output(config, iv) geom = None # Get our measurement from the simulation results, and invert rdn_meas, wl = spectrumLoad(config['input']['measured_radiance_file']) state_est = iv.invert(rdn_meas, geom, out) # Calculate uncertainties at the solution state, write result rfl_est, rdn_est, path_est, S_hat, K, G =\ iv.forward_uncertainty(state_est, rdn_meas, geom) out.write_spectrum(state_est, rfl_est, rdn_est, path_est, rdn_meas, rdn_sim=None, geom=geom) assert True return state_est
def hand_list(self, player, args): if (len(player.hand.cards) == 0): output = "You don't have any cards." else: output = "```\n{0}\n```".format(str(player.hand)) return Output(True, output)
def sort_ph3(test_case_removal): current_date = str(datetime.datetime.now().strftime("%Y-%m-%d")) ph = Phase3(bool(test_case_removal),concat=True) ph.filterPhaseReports() redo_index = ph.redoScoreIndices() ph.percent_difference(redo_index) df= ph.report redo_sum = df[df['redo'].notnull()]['emq'].sum() non_redo_sum = df[df['redo'].isnull()]['emq'].sum() ph.report=ph.sort_repo('email') df=ph.consolidate_repo() output = Output(df,'3') output.do_it_all() writer = pd.ExcelWriter('/var/www/html/flaskapp/Output/No_Phase '+current_date+'.xlsx',engine='xlsxwriter') output.df.to_excel(writer,startcol = 0, startrow = 10,index=False) worksheet = writer.sheets['Sheet1'] worksheet.write_string(0, 0, 'EmQ No Phase/Redo Export – '+current_date) worksheet.write_string(1, 0, "Number of Redo Participants") worksheet.write_string(1, 1, str(len(redo_index))) worksheet.write_string(2, 0, "Sum of all redo participants ") worksheet.write_string(2, 1, str(redo_sum)) worksheet.write_string(3, 0, "Sum of all non-phase participants (except redo) ") worksheet.write_string(3, 1, str(non_redo_sum)) worksheet.write_string(4, 0, "Average % Difference ") worksheet.write_string(4, 1, str('Insert number here')) writer.save()
def main(): (opts, args) = cli() key = get_value('key') td = Tmdb(key, opts.category) if opts.listing: li = Listing(opts.category) movies = li.get_movies() prefix = "list_" subject = "Week %s: %s" % (THIS_WEEK, li.title) else: movies = td.get_movies(opts.numres) prefix = "" subject = "%s movies - week %s" % (opts.category.title().replace("_", " "), THIS_WEEK) ca = Cache(prefix + os.path.basename(opts.category)) newMovies = ca.shelve_results(movies) if opts.listing: movieObjects = ca.shelve_get_items(movies) # allow dups else: movieObjects = ca.shelve_get_items(newMovies) # only new ones op = Output(movieObjects) html = [op.generate_header()] html.append(op.generate_movie_html_div()) if opts.printres: print "\n".join(html) if opts.mailres: sender = get_value('sender') recipients = load_emails('recipients') ma = Mail(sender) ma.mail_html(recipients, subject, "\n".join(html))
def main(): # python driver.py bfs 0,8,7,6,5,4,3,2,1 arguments = sys.argv search_type = arguments[1] # create a list of initial states from arguments[2] initial_state_list = [int(x) for x in arguments[2].split(',')] # now use this list to create initial_state object from State class initial_state = State(initial_state_list) # let's use time var to time execution start_time = time.time() # create output Object from Output class output = Output() if search_type == 'bfs': output = BFS(initial_state) elif search_type == 'dfs': output = DFS(initial_state) # elif search_type == 'ast': # output = solve_ast(initial_state) else: print('Invalid search_type: {}'.format(search_type)) # Let's add max ram uage and running time to output object output.max_ram_usage = resource.getrusage( resource.RUSAGE_SELF).ru_maxrss / 1024 output.running_time = time.time() - start_time f = open('output.txt', 'w') f.write(str(output)) f.close()
def test_most_common_words(self): out = Output() lorem_ipsum = "a testcase is created by subclassing unittest.TestCase. The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests. The crux of each test is a call to assertEqual() to check for an expected result; assertTrue() or assertFalse() to verify a condition; or assertRaises() to verify that a specific exception gets raised. These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report. The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. They are covered in more detail in the section Organizing test code. The final block shows a simple way to run the tests. unittest.main() provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:" words_html = out._most_common_words(lorem_ipsum) self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) words_html = out._most_common_words(None) self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) words_html = out._most_common_words("") self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) words_html = out._most_common_words(" ") self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) words_html = out._most_common_words("a a a") self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) words_html = out._most_common_words("\n") self.assertNotEqual(words_html, None) self.assertTrue(len(words_html) > 0) s = time.time() * 1000 words_html = out._most_common_words(lorem_ipsum * 5) e = time.time() * 1000 - s self.assertTrue(e < 50)
def hand_play(self, player, args): card = player.hand.play(args.play) targetDeck = TABLETOP.decks[card.deck_index] targetDeck.discard.append(card) output = "{0} played {1}! *({2})*".format(player.display_name, card, card.description) return Output(False, output)
def main(): # Get the command line args args = sys.argv[1:] # Check to make sure correct number of args were added if len(args) != 3: print "Usage: python main.py <inputFile.ext> <min_support(int)> <outputFile.ext>" sys.exit() # Initialize Data class with the input file data_class = Data(args[0]) # Get the data as 2D array print "Getting Data from file..." start = time.time() data_array = data_class.get_data() end = time.time() print "Done - Took %1.1f seconds" % (end - start) min_support = int(args[1]) a = Apriori(min_support) print "Performing Apriori Algorithm..." start = time.time() results = a.apriori(data_array) end = time.time() print "Done - Took %1.1f seconds" % (end - start) print "Writing to " + args[2] + "..." start = time.time() Output(results, args[2]) end = time.time() print "Done - Took %1.1f seconds" % (end - start)
def test_format_table_with_sparse_columns(): """Test table where rows have different heading names""" class TestItem1: def __init__(self, name, age, num_pets): self.name = name self.age = age self.num_pets = num_pets class TestItem2: def __init__(self, name, age, num_computers): self.name = name self.age = age self.num_computers = num_computers # Arrange items = [ TestItem1("Ann", 21, 1), TestItem2("Bob", 45, 2), TestItem1("Cath", 52, 4) ] output = Output() # Act output.format_table(items) # Assert verify(output.report)
def __init__(self, config): super(SimpleModule, self).__init__() self.memory_attention = MemoryAttention(config) self.reasoning = Reasoning(config) self.question_attend = QuestionAttend(config) self.forget_gate = ForgetGate(config) self.confidence = Confidence(config) self.output = Output(config)
def simulate(LG, model, interventions, max_time, observers=None): """ One simulation run with the model model on the multilayered graph LG max_time denotes the end of the simulation observers get notified when events happen """ output = Output() global_clock = 0.0 PQ = PriorityQueue() if observers is None: observers = [] for observer in observers: observer.start(LG) # Initialize Eventqueue: for node in LG.nodes(): # Initialize model events: push_model_event(PQ, LG, node, global_clock, model) # Initialize intervention events: check_and_push_interventions(PQ, LG, global_clock, interventions) # Handle events in queue: while global_clock <= max_time and not PQ.is_empty(): event, valid = PQ.pop_event() global_clock = event.time # Model event: if valid and isinstance(event, ModelEvent): if model.check_condition(LG): for observer in observers: observer.before_model_event(LG, event) model.perform_statuschanges(LG, event.node, event.state) for observer in observers: observer.after_model_event(LG, event) update_nodes(PQ, LG, [event.node], global_clock, model) output.add_event(event) # Intervention event: elif valid and isinstance(event, InterventionEvent): if event.intervention.check_condition(LG): for observer in observers: observer.before_intervention_event(LG, event) changed_nodes = event.intervention.perform_intervention(LG) for observer in observers: observer.after_intervention_event(LG, event) update_nodes(PQ, LG, changed_nodes, global_clock, model) output.add_event(event) elif not valid: push_model_event(PQ, LG, event.node, global_clock, model) # check for new possible interventions: check_and_push_interventions(PQ, LG, global_clock, interventions) for observer in observers: observer.end(LG) return output
def __init__(self): self.headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36', 'Cookie': 'T=TI155408291269051088271180464414101876800319121371635764130475883158; SN=2.VI0E6DB9FB64384AF09CEB0245DA5DFDBF.SIDBBCFC31EB314B9C8B650462E0480F8E.VS04109302537046BC9DC7ADA675D5512C.1555660730' } self.base_url = "https://www.flipkart.com" self.output = Output()
def setup_output(self): """ Create Output object and write header line to csv file """ self.output = Output(self._OUTPUT_PATH) self.output.write([ "timestamp", str(self.data.headers[1]), "scaled_score", "anomaly_score" ])
def main(): economy = Economy() output = Output() curmap = GameMap(economy) myevol = RandomUnitEvolution() print( myevol.evolveEachUnit( economy, curmap, Game.selectArmy(economy, curmap, "white", output)))
def add_gen_flag(data_feature, data_gen_flag, data_feature_outputs, sample_len): """ -adds generation flags to the end of original data features -adds an additional output to the data_feature_outputs list Args: data_feature: original data feature data_gen_flag: original data gen flag data_feature_outputs: list that describes original feature output type, dimension, normalization sample_len: max sequence length of time series Returns: data_feature: original data feature + gen flag data_feature_outputs: original data_feature_output + output type, dimension and normalization of gen flag """ for output in data_feature_outputs: if output.is_gen_flag: raise Exception("is_gen_flag should be False for all" "feature_outputs") if (data_feature.shape[2] != np.sum([t.dim for t in data_feature_outputs])): raise Exception("feature dimension does not match feature_outputs") if len(data_gen_flag.shape) != 2: raise Exception("data_gen_flag should be 2 dimension") num_sample, length = data_gen_flag.shape data_gen_flag = np.expand_dims(data_gen_flag, 2) # (num_sample, seq_len, 1) data_feature_outputs.append( Output(type_=OutputType.DISCRETE, dim=2, is_gen_flag=True)) shift_gen_flag = np.concatenate( [data_gen_flag[:, 1:, :], np.zeros((data_gen_flag.shape[0], 1, 1))], axis=1) # (num_samples, seq_len, 1) if length % sample_len != 0: raise Exception("length must be a multiple of sample_len") data_gen_flag_t = np.reshape( data_gen_flag, [num_sample, int(length / sample_len), sample_len ]) # (num_sample, 1, seq_len) data_gen_flag_t = np.sum(data_gen_flag_t, 2) data_gen_flag_t = data_gen_flag_t > 0.5 data_gen_flag_t = np.repeat(data_gen_flag_t, sample_len, axis=1) data_gen_flag_t = np.expand_dims(data_gen_flag_t, 2) # add the gen_flag and inverse of gen_flag to data_feature data_feature = np.concatenate( [data_feature, shift_gen_flag, (1 - shift_gen_flag) * data_gen_flag_t], axis=2) # (num_sample, seq_len, num_features + 2) return data_feature, data_feature_outputs
def write(self, outputFile=None): if outputFile: # new output file given if self.output: self.output.close() self.output = Output(outputFile, outputFile.split('.')[1]) self.output.write(self.dataList) else: # Single file (or screen) output case self.output.write(self.dataList)
def test_format_table_not_collection(): # Arrange items = "not an array" output = Output() # Act output.format_table(items) # Assert verify(output.report)
def test_format_table_with_list_of_primitives(): # Arrange items = [1, 2000, 3, 4] output = Output() # Act output.format_table(items) # Assert verify(output.report)
def get_output(self): out = Output() out.stopwords = [] out.remove_divs = False out.gridView = True out.scale = 1.0 out.fields_to_hide_in_results = dict() out.edited = [] out.lastResDict = {} out.hideSidebar = False return out
def __init__(self, arguments): self.lnd = Lnd(arguments.lnddir, arguments.grpc, arguments.network) self.output = Output(self.lnd) self.min_amount = arguments.min_amount self.arguments = arguments self.first_hop_channel_id = self.parse_channel_id( vars(arguments)["from"]) self.last_hop_channel_id = self.parse_channel_id(arguments.to) self.first_hop_channel = None self.last_hop_channel = None self.min_local = arguments.min_local self.min_remote = arguments.min_remote