Esempio n. 1
0
class NPC(object):
	def __init__(self, name):
		self.stats = Stats()
		self.name = name

	def show_hp(self):
		print "HP:", self.stats.hit_points

	def attack(self, enemy):
		mod = np.random.uniform(0.9, 1, 1)[0]
		a = self.stats.level*0.3
		b = (float(self.stats.attack)*4/enemy.stats.defense)*4.0 
		c = mod
		damage = max(int(a*b*c), 1)
		enemy.stats.hit_points -= damage
		print "BAM!", enemy.name, "was hit for",  damage
		enemy.stats.hit_points = max(enemy.stats.hit_points, 0)
		return damage

	def level_up(self):
		if self.stats.level < 99:
			self.stats.level += 1
			self.stats.max_hit_points = self.stats.level*8 
			rem_points = 3 
			stat_selector = []
			stat_selector.extend(self.stats.stats_names)
			while(rem_points > 0):
				rand_stat = np.random.choice(stat_selector, 1)
				rand_stat_increase = np.random.randint(1,rem_points+1)
				self.stats.modify_stat(rand_stat, rand_stat_increase) 
				stat_selector.remove(rand_stat)
				rem_points -= rand_stat_increase

	def level_to(self, lvl):
		if lvl > 99:
			lvl = 99
		while(self.stats.level < lvl):
			self.level_up() 

	def show_stats(self):
		print "/"*20
		print self.name, " (LV. " , self.stats.level , ")"
		print self.stats.hit_points , "/", self.stats.max_hit_points
		aux_hp = int((float(self.stats.hit_points)/ self.stats.max_hit_points)*20)
		txt_hp = "+"*aux_hp
		print "[{0:20}]".format(txt_hp)
		print "Att: ", self.stats.attack
		print "Def: ", self.stats.defense
		print "Lck: ", self.stats.luck
		print "/"*20

	def cure(self, hp):
		a = self.stats.hit_points + hp
		if a > self.stats.max_hit_points:
			result = self.stats.max_hit_points - self.stats.hit_points 
			self.stats.hit_points = self.stats.max_hit_points
		else:
			result = hp
			self.stats.hit_points = a
		return result
Esempio n. 2
0
class Simulation(object):

    def __init__(self, aggregator, strategy, reserved_resources, sleep_time=0):


        self.aggregator = aggregator

        self.strategy = strategy
# 2 year warm up, and 10 year run
        self.stats = Stats(24, 120)
        self.company = Company(20, reserved_resources, self.strategy, self.stats)
        self.sleep_time = sleep_time
        self.reserved_resources = reserved_resources

        print(sim_to_key(self))

    def run(self):

        for t in range(self.stats.runs):

            self.stats.start_month()

            projects = [generate_project() for _ in range(sample.project_count())]
            self.company.decide_projects(projects)

            used_resources = self.company.workflow.work()

            self.stats.end_month(used_resources, self.company.workflow.average_workload())

            if self.sleep_time > 0:
                sleep(self.sleep_time)

            #print(self.stats.monthly_report())

        self.aggregator.add_result(self)
def process(infile, algorithm_name, support, confidence, m, random, partial):
    stats = Stats()
    transactions = TransactionsList(infile)
    stats.record_post_large_sets()
    stats.record_post_rules()
    last_total_time = stats.real_time
    last_user_time = stats.user_time
    stats = Stats()
    if algorithm_name == 'apriori':
        algorithm = Apriori(transactions, support)
    else:
        algorithm = Dic(transactions, support, m, random, partial)
    large_sets, counter = algorithm.get_large_sets_and_counter()
    stats.record_post_large_sets()
    rules = RulesGenerator.generate_rules(large_sets, confidence, counter, transactions)
    stats.record_post_rules()
    large_len = len(large_sets)
    total_time = stats.real_time - last_total_time
    user_time = stats.user_time - last_user_time
    large_sets_time = stats.set_gen_time - last_total_time
    last_total_time = stats.real_time
    last_user_time = stats.user_time
    memory = stats.memory_use
    rules_no = len(rules)

    print "{infile}\t{algorithm_name}\t{support}\t{confidence}\t{m}\t{rules_no}\t{large_len}\t{memory}\t{total_time}\t{user_time}\t{large_sets_time}\t{partial}\t{random}".format(**locals())
Esempio n. 4
0
    def do_mark(self, subcmd, opts, bamfile, amplicons):
        """${cmd_name}: Mark reads matching amplicons and optionally clip.
            
            Walk a BAM file and mark any matching amplicons using the AM tag.
            Outputs a modified BAM.  Use 'clip' if you want only reads matching 
            amplicons in the output.
            
            ${cmd_usage}
            BAMFILE: input reads (use - for stdin)
            AMPLICONS: a file listing amplicons and trim locations.
            
            ${cmd_option_list}
        """
        samfile = pysam.Samfile(bamfile, "rb")
        stats = Stats(" ".join(sys.argv))
        amplicons = load_amplicons(design, stats, opts, samfile=samfile)
        outfile = pysam.Samfile(opts.outfile, "wb", template=samfile)

        # we need to reopen the file here to get sequential access after computin the pileups
        samfile = pysam.Samfile(bamfile, "rb")
        for read in samfile:

            # TODO: optimisation of the list of amplicons that are considered
            for amp in amplicons:
                if amp.matches(read):
                    amp.clip(read)
                    amp.mark(read)
            outfile.write(read)

        stats.report(sys.stderr)
Esempio n. 5
0
    def on_shutter(self, state):
        print '-----'

        print 'Time to Start'
        total = Stats()
        for method_name, stats in state.time_to_start.items():
            print "%s avg:%.2fs, max:%.2fs, min: %.2fs" % (method_name, stats.average() or -1.0 , stats.maximum or -1.0, stats.minimum or -1.0)
            total += stats

        print ''
        print 'Time to Process'
        total = Stats()
        for method_name, stats in state.time_to_process.items():
            print "%s avg:%.2fs, max:%.2fs, min: %.2fs" % (method_name, stats.average() or -1.0, stats.maximum or -1.0, stats.minimum or -1.0)
            total += stats
        print "Total: avg:%.2fs, max:%.2fs, min: %.2fs" % (total.average() or -1.0, total.maximum or -1.0, total.minimum or -1.0)

        print ''
        print 'Event Totals'
        for method_name, totals in state.totals.items():
            for total_name, total in totals.items():
                print "%s[%s]: %d" % (method_name, total_name, total)

        print ''
        print 'Queue Sizes'
        print 'Waiting Tasks: %d' % len(state.waiting_tasks)
        print 'Running Tasks: %d' % len(state.running_tasks)

        print ''
        print ''
Esempio n. 6
0
File: main.py Progetto: aandrea/TDA1
def main():

    filename = sys.argv[1]

    graph = Graph()
    parser = Parser()

    #parse gdf file
    parser.parse(filename, graph)
#    print graph.__str__()

    stats = Stats(graph)

    #compute popularity
    popularities = stats.computePopularity()
    print "Popularidad"
    print "********************************"
    stats.showPopularities(popularities)

    #compute influences
    influences = stats.computeInfluences()
    print ""
    print "Influencias"
    print "********************************"
    stats.showInfluences(influences)

    #obtain recomendations
    print ""
    print "Recomendaciones"
    print "********************************"
    recommendations = stats.computeRecommendations()
    stats.showRecommendations(recommendations)
Esempio n. 7
0
	def __init__(self, ciphertext, stats_filenames, dict_file, max_pop = 10, params = default_params, alphabet = default_alphabet, stat_file = None, naive_key = True):
	
		self.params = params
		self.alphabet = alphabet
		self.single_stats_filename, self.double_stats_filename = stats_filenames
		self.ciphertext = ciphertext
		self.max_pop = max_pop
		
		self.exp_stats = Stats(self.alphabet)
		self.exp_stats.load_singlef_from_file(self.single_stats_filename)
		self.exp_stats.load_doublef_from_file(self.double_stats_filename)

		self.ciph_stats = Stats(self.alphabet)
		self.ciph_stats.process_text(self.ciphertext)
		
		self.initialize(naive_key)
		self.stat_file = None
				
		if stat_file != None:
			self.stat_file = open(stat_file, "w")
			self.stat_file.write("gen\tworst\tavg\tbest\tderiv\n")
			
		self.sliding_table = []
		self.end = False
		
		self.dictionary = Dictionary(dict_file)
		self.temp_stats = Stats(self.alphabet)
		
		signal.signal(signal.SIGINT, self.signal_handler)
Esempio n. 8
0
 def __getattr__(self, name):
         if name == 'stats':
                 stats = Stats()
                 for effect in self.effects:
                         stats.add_stats(effect.stats)
                 return stats
         else:
                 raise AttributeError
Esempio n. 9
0
 def setUp(self):
     self.st = Stats()
     
     self.expect = Stats()
     self.expect.sumsq = 425.1641
     self.expect.sum = 55.84602
     self.expect.min = 0.333
     self.expect.max = 9.678
     self.expect.n = 10
 def test_tb(self):
     """
     Total bases test
     :return:
     """
     # ichiro suzuki(2004)
     single = Stats.single(262, 8, 24, 5)
     tb = Stats.tb(single, 8, 24, 5)
     self.assertEqual(tb, 320)
Esempio n. 11
0
 def __getattr__(self, name):
         if name == 'stats':
                 stats = Stats()
                 for item in self.equipment:
                         if self.equipment[item]:
                                 stats.add_stats(self.equipment[item].stats)
                 return stats
         else:
                 raise AttributeError
 def test_rc(self):
     """
     Run created test
     :return:
     """
     # ichiro suzuki(2004)
     single = Stats.single(262, 8, 24, 5)
     rc = Stats.rc(262, 49, 4, 11, 6, 3, 2, 36, 63, 704, 19, single, 24, 5, 8)
     self.assertEqual(rc, 136.5)
Esempio n. 13
0
    def possible(self, row, col):
        if (row == col):
            return Stats.possible(self, row, col) & self.diag0

        elif (row + col) == 8:
            return Stats.possible(self, row, col) & self.diag8

        else:
            return Stats.possible(self, row, col)
def main(args):
    states = read_states(args.input)

    stats = Stats(sys.argv)
    cipher = Spritz()

    settings = Settings(args)

    prompt_step = max(1, len(states) // 20)
    i = 0
    for initial_state, revealed_state, prefix_length in states:
        if args.verbosity > 1 and i % prompt_step == 0:
            print('test #:', i)
        i += 1

        KNOWN_KEYSTREAM_SIZE = 3 * initial_state.size
        cipher.initialize_state(initial_state.state)
        known_keystream = cipher.keystream(prefix_length + KNOWN_KEYSTREAM_SIZE)
        settings.prefix_length = prefix_length

        # in case we want to skip less keystream than revealed_state is
        # generate in, we cut off beginning of keystream and move 
        # initial_state apropriatelly
        if args.input and args.force_prefix_length and args.force_prefix_length < prefix_length:
            new_prefix_length = args.force_prefix_length
            new_start_offset = prefix_length - new_prefix_length
            settings.prefix_length = new_prefix_length
            known_keystream = known_keystream[new_start_offset:]   
            cipher.initialize_state(initial_state.state)
            cipher.keystream(new_start_offset)
            initial_state = SpritzState(cipher.state)

        cipher.initialize_state(initial_state.state)
        cipher.keystream(prefix_length)
        found_state, round_stats = backtrack.kpa(
            known_keystream,
            revealed_state,
            settings,
        )

        if found_state and initial_state != found_state:
            print('incorrect result, this should not happen')
            assert False

        stats.add(round_stats)

    stats.print_stats(args.verbosity)
    # dump pickled stats object
    if not args.no_stats_log:
        timestamp = datetime.datetime.today().strftime('%y%m%d_%H%M%S_%f')
        os.makedirs('stats/', exist_ok=True)
        with open('stats/' + timestamp, 'wb') as f:
            pickle.dump(stats, f)
Esempio n. 15
0
def home(request):
    log.info('Request: home')

    stats = Stats()

    return render(request, 'binary/home.html', {
        'q_values': stats.q.data,
        'runs_latest': stats.runs[-30:],
        'time_frames': stats.summarizeTimeFrames(),
        'trade_bases': stats.summarizeTradeBases(),
        'trade_aims': stats.summarizeTradeAims(),
    })
Esempio n. 16
0
def operations_test():
    st = Stats()

    for sample in samples:
        st.sample(sample)

    print st

    assert_float_equal(expect.sum, st.sum)
    assert_float_equal(expect.sumsq, st.sumsq)
    assert_equal(expect.n, st.n)
    assert_float_equal(expect.min, st.min)
    assert_float_equal(expect.max, st.max)
 def __init__(self, data):
     quartiles = data[:]
     quartiles.sort()
     
     middle = Stats.median(quartiles)
     split = ListUtils.middleSplit(quartiles)
     
     leftBound = Stats.median(split[0])
     rightBound = Stats.median(split[1])
     self.__quartileBounds = [leftBound, middle, rightBound]
     
     leftSplit = ListUtils.middleSplit(split[0])
     rightSplit = ListUtils.middleSplit(split[1])
     self.__quartiles = [leftSplit[0], leftSplit[1], rightSplit[0], rightSplit[1]]
Esempio n. 18
0
    def test_edges(self):
        s = Stats('[%s/%f/%t/%r/%p]', None, None)
        self.assertEqual(s.format(), '[0/0/0/0/ --- ]')
        s.started = 3
        s.total = 5
        s.finished = 1
        self.assertEqual(s.format(), '[3/1/5/2/ 60.0]')

        s.started = 5
        s.finished = 5
        self.assertEqual(s.format(), '[5/5/5/0/100.0]')
Esempio n. 19
0
def delete_node(sender, **kwargs):
    """ update user node count when a node is deleted """
    node = kwargs['instance']
    Stats.update_or_create(node.user, 'nodes')

# email notifications
#@receiver(node_status_changed)
#def notify_status_changed(sender, **kwargs):
#    """ TODO: write desc """
#    node = sender
#    old_status = kwargs['old_status']
#    new_status = kwargs['new_status']
#    notification_type = EmailNotification.determine_notification_type(old_status, new_status, 'Node')
#    EmailNotification.notify_users(notification_type, node)
#node_status_changed.connect(notify_status_changed)
Esempio n. 20
0
 def __init__(self, fight, src = None):
     ''' Конструктор.
         Fight fight - битва, в которой участвует файтер.
         src - документ.
     '''
     if src:
         self.__dict__.update(src)
         self.deck = [Card.js_load(c) for c in self.deck]
         self.hand = [Card.js_load(c) for c in self.hand]
         self.stats = Stats(self.stats)
         self.effects = [Effect.js_load(eff, self) for eff in self.effects]
     else:
         self.id = unique_id()
         self.stats = Stats()
     self.fight = fight
Esempio n. 21
0
    def run_sim(self):
        histories = map(lambda i: self.run_sim_once(), 
                        range(self.config.iters))
        logging.warning("======== SUMMARY STATS ========")
        
        uploaded_blocks = map(
            lambda h: Stats.uploaded_blocks(self.peer_ids, h),
            histories)
        completion_rounds = map(
            lambda h: Stats.completion_rounds(self.peer_ids, h),
            histories)

        def extract_by_peer_id(lst, peer_id):
            """Given a list of dicts, pull out the entry
            for peer_id from each dict.  Return a list"""
            return map(lambda d: d[peer_id], lst)

        uploaded_by_id = dict(
            (p_id, extract_by_peer_id(uploaded_blocks, p_id))
            for p_id in self.peer_ids)

        completion_by_id = dict(
            (p_id, extract_by_peer_id(completion_rounds, p_id))
            for p_id in self.peer_ids)

        logging.warning("Upload bandwidth: avg (stddev)")
        for p_id in sorted(self.peer_ids,
                           key=lambda id: mean(uploaded_by_id[id])):
            us = uploaded_by_id[p_id]
            logging.warning("%s: %.1f  (%.1f)" % (p_id, mean(us), stddev(us)))

        logging.warning("Completion rounds: avg (stddev)")

        def optionize(f):
            def g(lst):
                if None in lst:
                    return None
                else:
                    return f(lst)
            return g

        opt_mean = optionize(mean)
        opt_stddev = optionize(stddev)
        
        for p_id in sorted(self.peer_ids,
                           key=lambda id: opt_mean(completion_by_id[id])):
            cs = completion_by_id[p_id]
            logging.warning("%s: %s  (%s)" % (p_id, opt_mean(cs), opt_stddev(cs)))
Esempio n. 22
0
 def test_stats_formating(self):
     stats_ = Stats()
     stats_.set_members([User("On", 1), User("Teo", 2), User("olej", 3)])
     stats_["on"]["bodiky"] += 1
     expected = "```python\n  bodiky = 1\n```"
     self.assertEqual(stats_.get_user_stats_str("On"), expected)
     stats_["on"]["n"] += 8
     self.assertIn("  n = 8\n", stats_.get_user_stats_str("On"))
     self.assertIn("```", stats_.get_user_stats_str("On"))
     stats_["teo"]["bodiky"] += 9
     self.assertIn("Teo:", stats_.get_all_stats_str())
     self.assertIn("  bodiky = 9", stats_.get_all_stats_str())
Esempio n. 23
0
    def run_sim(self):
        histories = map(lambda i: self.run_sim_once(),
                        range(self.config.iters))
        logging.warning("======== SUMMARY STATS ========")

        uploaded_blocks = map(
            lambda h: Stats.uploaded_blocks(self.peer_ids, h),
            histories)
        completion_rounds = map(
            lambda h: Stats.completion_rounds(self.peer_ids, h),
            histories)

        def extract_by_peer_id(lst, peer_id):
            """Given a list of dicts, pull out the entry
            for peer_id from each dict.  Return a list"""
            return map(lambda d: d[peer_id], lst)

        uploaded_by_id = dict(
            (p_id, extract_by_peer_id(uploaded_blocks, p_id))
            for p_id in self.peer_ids)

        completion_by_id = dict(
            (p_id, extract_by_peer_id(completion_rounds, p_id))
            for p_id in self.peer_ids)

        logging.warning("Uploaded blocks: avg (stddev)")
        for p_id in sorted(self.peer_ids,
                           key=lambda id: mean(uploaded_by_id[id])):
            us = uploaded_by_id[p_id]
            logging.warning("%s: %.1f  (%.1f)" % (p_id, mean(us), stddev(us)))

        logging.warning("Completion rounds: avg (stddev)")

        def optionize(f):
            def g(lst):
                if None in lst:
                    return None
                else:
                    return f(lst)
            return g

        opt_mean = optionize(mean)
        opt_stddev = optionize(stddev)

        for p_id in sorted(self.peer_ids,
                           key=lambda id: opt_mean(completion_by_id[id])):
            cs = completion_by_id[p_id]
            logging.warning("%s: %s  (%s)" % (p_id, opt_mean(cs), opt_stddev(cs)))
    def get_stats(self,verbose=False):
        '''
        return most important stats into dict
        
        @type  verbose: bool
        @param verbose: [optional]. if set to True, general stats
        are send to stdout.
        '''
        Stats.__init__(self)
        
        num_rels,none_targets = self.stats_rels()
        tops                  = self.tops()
        with open( os.path.join(self.cwd,'resources','tops.bin'),'wb') as outfile:
            pickle.dump(tops,outfile)
        empty_synsets         = self.stats_empty_synsets() 
        average_polysemy, polysemy_dict = self.polysemy_dict()
        self.stats_large_synsets()

        self.stats = {'num_synsets'               : self.stats_num_synsets(),
                      'num_lexical_entries'       : self.stats_num_les(),
                      'num_empty_pwn_synsets'     : empty_synsets['num_empty_pwn_synsets'],
                      'num_empty_odwn_synsets'    : empty_synsets['num_empty_odwn_synsets'],
                      'empty_leave_odwn_synsets'  : empty_synsets['leave_empty_odwn_synsets'],
                      'num_relations'             : num_rels,
                      'impossible_rels'           : none_targets,
                      'empty_lemmas'              : self.empty_lemmas(),
                      'tops'                      : tops,
                      'sy_no_gloss,empty_glosses,one_word' : self.no_gloss(),
                      'pos_counts'                : self.count_pos(),
                      'provenance'                : self.resources_check(),
                      'polysemy_dict'             : polysemy_dict,
                      'average_polysemy'          : average_polysemy,
                      'bidirectional_relations'   : self.missing_bidirectional_relations("has_hyponym","has_hyperonym"),
                      'no_rels'                   : self.sy_no_rels(),
                      'contradicting'             : self.contradicting_rels()
                     }

        
        if verbose:
            print('general stats for input file:')
            print(os.path.basename(self.path_wn_grid_lmf))
            for key,value in sorted(self.stats.items()):

                if key in ["bidirectional_relations","polysemy_dict",'empty_leave_odwn_synsets',
                           "impossible_rels","tops","no_rels","contradicting"]:
                    print(key,len(value))     
                else:                
                    print(key,value)
Esempio n. 25
0
class Intelligence(object):
    """
    Emotion Intelligence of an entity
    Based on Lövheim Cube of emotion:

    Shame/humiliation	Low	Low	Low
    Distress/anguish	Low	Low	High
    Fear/terror	Low	High	Low
    Anger/rage	Low	High	High
    Contempt/disgust	High	Low	Low
    Surprise	High	Low	High
    Enjoyment/Joy	High	High	Low
    Interest/excitement	High	High	High
    """

    def __init__(self, name, emotion_parser):
        self.name = name
        self.parser = emotion_parser
        self.threshold = 1.0
        self.stats = Stats()

    def update(self, text):
        """
        Update emotional state of an entity

        :param text: Emotionally charged text that entity produced
        :return: self
        """

        for emoji, power in self.parser.get_emojis(text):
            emoji_dir = np.array(emoji.dim)
            self.stats.update(power * emoji_dir / np.linalg.norm(emoji_dir))

        return self

    def emotions(self):
        emo = []

        emo_point = np.array(self.stats.mean)

        for k, emotion in self.parser.known_emotions.iteritems():
            emo_origin = np.array(emotion.dim)
            dist = np.linalg.norm(emo_point - emo_origin)
            if dist < self.threshold:
                emo.append((emotion,
                            dist))

        return emo
Esempio n. 26
0
 def reset(self, seed=None):
     self.feq = FutureEventsQueue()
     self.clock = Clock()
     self.stats = Stats()
     if seed is not None:
         random.seed(seed)
     self.initialize()
Esempio n. 27
0
def get_data_fromDict(dict, flags):
    _stats = Stats.makeEmpy()
    """Adds data read from line (String) to maps"""
    if flags is None or flags.all_per_min:
        _stats.accessesPerMinute[dict.get("universalMinute")] = 1
    ipFrom = dict.get("ip_from")
    if flags is None or flags.top_url_per_top_ip or flags.top_ips:  # avoid consuming op
        _stats.ipToNumberOfAccesses[ipFrom] += 1
    urlWithParamters = dict.get("url")
    questionMarkPosition = urlWithParamters.find("?")
    if ~questionMarkPosition:
        justTheUrl = urlWithParamters[0:questionMarkPosition]
    else:
        justTheUrl = urlWithParamters
    justTheUrl = re.sub(r"[/]+", r"/", justTheUrl)
    if _stats.ipToPages.get(ipFrom) is None:
        _stats.ipToPages[ipFrom] = Counter()
    _stats.ipToPages[ipFrom][justTheUrl] += 1

    if flags is None or flags.top_req_pages:  # avoid consuming op
        _stats.pagesToNumberOfAccesses[justTheUrl] += 1  # removing repeated forward slashes
    responseTime = dict.get("responseTime")
    if int(responseTime) >= 200 and int(responseTime) <= 300:
        _stats.successful += 1
    else:
        _stats.unsuccessful += 1
        if flags is None or flags.top_uns_pages:  # avoid consuming op
            _stats.unsuccessfulPages[justTheUrl] += 1
    if logEnabled:
        print ("Just the url: " + justTheUrl)
    return _stats
Esempio n. 28
0
 def _cumulative_stats_from_roster_entries(self, entries,
                                           scoring_period_id):
     """
     Takes a list of roster entries and reconstitutes the cumulative stats produced by that
     roster.
     :param list entries: the entries produced
     :param int scoring_period_id: the scoring period for which stats are being accumulated
     :return Stats: the sum total of stats produced by starters on that roster
     """
     total_stats = Stats({}, self._stat_enum())
     for e in filter(self.is_starting, entries):
         entry_stats_list = e["playerPoolEntry"]["player"]["stats"]
         stats_dict = next(
             filter(
                 lambda d: d["scoringPeriodId"] == scoring_period_id and d[
                     "statSourceId"] == 0 and d["statSplitTypeId"] == 5,
                 entry_stats_list,
             ),
             None,
         )
         if stats_dict is None:
             name = e["playerPoolEntry"]["player"]["fullName"]
             LOGGER.warning(
                 f"{name} has no stats matching scoring period {scoring_period_id} "
                 f"found in entry {e}")
             continue
         stats = self.create_stats(stats_dict["stats"])
         total_stats += stats
     return total_stats
Esempio n. 29
0
    def __init__(self):
        pygame.init()
        self.settings = st()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        self.surf_rect = self.screen.get_rect()
        self.ship = Spaceship(self.screen, self.settings)
        self.bullets = Group()
        self.aliens = Group()
        self.create_aliens_flot()
        self.stats = Stats(self.settings)
        self.button = Button(self.settings, self.screen,
                             'To start new game press "n" button')

        self.active_game = True
Esempio n. 30
0
	def __init__(self, path):
		self.filename = path.split('/')[-1]
		self.filepath = path
		self.monitor = TrafficMonitor()
		self.parser = LogParser()
		self.stats = Stats(self.filename)
		self.stats.stats_timer()
Esempio n. 31
0
    def get_stats(self):
        """Retrieves statistics about the queue"""
        href = proc_template(self._conn.stats_href, queue_name=self._name)

        hdrs, body = self._conn._perform_http(href=href, method='GET')

        return Stats(body)
Esempio n. 32
0
    def __init__(self):
        with open("properties.json") as fp:
            config = json.load(fp)

        # self.q = Queue.Queue()
        # # current completion time of a queue
        policy = config["server"]["allocationPolicy"]
        self.allocation_policy = AllocationPolicy.get_policy(policy)
        self.stat = Stats()

        # TODO : Use this code if we want to use multiple queues
        self.write_server = config["server"]["writeServer"]
        self.read_server = config["server"]["readServer"]
        self.no_of_read_response_required = config["server"][
            "noOfReadResponse"]
        self.no_of_write_response_required = config["server"][
            "noOfWriteResponse"]

        self.server_queues = []
        self.completion_time = []

        for i in range(0, config["server"]["numberOfServers"]):
            self.server_queues.append(Queue.PriorityQueue())
            self.completion_time.append(0)

        self.dist = Distribution.get_distribution(
            config["request"]["distribution"], rate=1)
    def _cumulative_stats(self, lineup: Lineup):
        """
        Calculates an approximation of the final statistics of this lineup, assuming
        ideal management (setting lineups daily, etc.)
        :param Lineup lineup: the lineup to examine and use to calculate stats
        :return Stats: the accumulated, year-end total stats
        """
        total_stats = Stats({}, BaseballStat)
        for p in lineup.starters():
            total_stats += self._get_projection(p.name) or Stats({},
                                                                 BaseballStat)
        for p in lineup.benched():
            total_stats += self._get_projection(p.name) or Stats(
                {}, BaseballStat) * self.likelihood(p, lineup)

        return total_stats
Esempio n. 34
0
 def get_stats(self, itr=0):
     self.stats = Stats()  # Clean stats
     self.set_iteration(itr)
     self.read_meminfo()
     self.read_slabinfo()
     self.read_cpuinfo()
     return self.stats
Esempio n. 35
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    #Record game stas
    stats = Stats(ai_settings)

    #Build a ship
    ship = Ship(ai_settings, screen)
    #Build bullets group
    bullets = Group()
    #Build aliens group
    aliens = Group()
    gf.create_fleet(ai_settings, aliens, screen)
    #create play button
    play_button = Button(ai_settings, screen, "PLAY")
    score_button = Game_Score(ai_settings, screen)
    while True:
        gf.check_events(ai_settings, aliens, bullets, play_button, screen,
                        ship, stats)
        if stats.game_active:
            #Check if collision happened
            gf.bullets_update(ai_settings, aliens, bullets, screen, stats)
            gf.aliens_ship_update(ai_settings, aliens, bullets, screen, ship,
                                  stats)
            ship.update()
            gf.aliens_update(ai_settings, aliens, bullets, screen, ship, stats)

        gf.update_screen(ai_settings, aliens, bullets, play_button,
                         score_button, screen, ship, stats)
Esempio n. 36
0
class Race(metaclass=utilities.StrMeta):
    starting_stats = Stats(0, 0, 0, 0)

    def __init__(self, str, agi, int, con):
        if not self.starting_stats.validStart():
            raise InvalidStartingStats("Unbalanced starting stats: %d" %
                                       self.starting_stats.sum())
Esempio n. 37
0
    def send_command(self, command):
        """
        Send a command to the Tello and wait for a response.

        :param command: Command to send.
        :return (str): Response from Tello.

        """
        self.log.append(Stats(command, len(self.log)))
        print(">> send cmd: {}".format(command))
        #self.abort_flag = False
        #timer = threading.Timer(self.command_timeout, self.set_abort_flag)

        self.socket.sendto(command.encode('utf-8'), self.tello_address)
        start = time.time()
        while not self.log[-1].got_response():
            now = time.time()
            diff = now - start
            if diff > self.MAX_TIME_OUT:
                print("Max timeout exceeded... command %s" % command)
                break
            time.sleep(0.01)
            # TODO: is timeout considered failure or next command still get executed
            # now, next one got executed

        print("Command completed: %s to %s" % (command, self.tello_ip))
        return self.log[-1].got_response()
Esempio n. 38
0
 def __init__(self, config, hq):
   self.config = config
   self.ident = config.ident
   self.hq = hq
   self.state = 0
   self.perm8_state = 0
   self.stats = Stats(config, hq)
Esempio n. 39
0
  def __init__(self, env, network, session, replay_memory, config,
               enable_summary=True):
    self.env = env
    self.network = network
    self.session = session
    self.replay_memory = replay_memory
    self.config = config

    self.training_steps = 0 # Keeps count of learning updates
    self.stats = Stats()

    self.random_action_prob = config.init_random_action_prob
    self.random_action_prob_decay = utils.decay_per_step(
      init_val=self.config.init_random_action_prob,
      min_val=self.config.min_random_action_prob,
      steps=self.config.random_action_explore_steps,
    )

    self.summary_writer = None
    if enable_summary:
      self.summary_writer = tf.train.SummaryWriter(config.logdir, session.graph)

    self.frame_buffer = FrameBuffer(
      frames_per_state=config.frames_per_state,
      preprocessor=self._get_frame_resizer(env, config),
    )

    # Prefill the replay memory with experiences based on random actions
    self._prefill_replay_memory(self.config.replay_start_size)

    # Initialize the target network
    self._update_target_network()
Esempio n. 40
0
 def reset(self, seed=None):
     self.feq = FutureEventsQueue()
     self.clock = Clock()
     self.stats = Stats()
     if seed is not None:
         random.seed(seed)
     self.initialize()
Esempio n. 41
0
 def year_stats(self):
     teams = self.all_info().json()['teams']
     team_to_stats = dict()
     for t in teams:
         stats = Stats(t['valuesByStat'])
         team_to_stats[t['id']] = stats
     return team_to_stats
Esempio n. 42
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    screen = pygame.display.set_mode((630, 800))
    pygame.display.set_caption("PACMAN")

    # Draw maze
    mazefile = 'maze.txt'
    maze = Maze(screen, mazefile)

    # Pacman
    pm = PM(screen, maze)

    # Stats
    stats = Stats()

    # Ghosts
    red = Red(screen, maze)
    blue = Blue(screen, maze)
    pink = Pink(screen, maze)
    orange = Orange(screen, maze)
    cherry = Cherry(screen)

    display = Display(screen, pm)

    while True:
        if stats.game_active:
            gf.check_events(screen, pm, maze, red, blue, pink, orange, stats,
                            display)

            gf.update_screen(screen, pm, maze, red, blue, pink, orange, cherry,
                             stats, display)

            pygame.display.flip()
    def find_avaliable_tello(self, num):
        """
        Find avaliable tello in server's subnets
        :param num: Number of Tello this method is expected to find
        :return: None
        """
        print '[Start_Searching]Searching for %s available Tello...\n' % num

        networks = self.get_ipv4_networks()
        possible_addr = []

        for network in networks:
            for ip in network.iter_hosts():
                if str(network.ip) != str(ip):
                    possible_addr.append(str(ip))

        while len(self.tello_ip_list) < num:
            print '[Still_Searching]Trying to find Tello in subnets...\n'

            # delete already fond Tello
            for tello_ip in self.tello_ip_list:
                if tello_ip in possible_addr:
                    possible_addr.remove(tello_ip)
            # send each of the addresses a command.
            for ip in possible_addr:
                # record this command
                self.log[ip].append(Stats('command', len(self.log[ip])))
                self.socket.sendto(b'command', (ip, 8889))
            time.sleep(5)

        # filter out non-tello addresses in log
        temp = defaultdict(list)
        for ip in self.tello_ip_list:
            temp[ip] = self.log[ip]
        self.log = temp
Esempio n. 44
0
def run_game():
    #initialize pygame, settings and screen object
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("PONG!")

    rpaddle = Rpaddle(game_settings, screen)
    lpaddle = Lpaddle(game_settings, screen)
    ball = Ball(game_settings, screen)
    play_button = Button(screen, "Play")
    stats = Stats()
    scoreboard = Scoreboard(game_settings, screen, stats)
    winner_msg = Winnermsg(game_settings, screen)

    #start main loop
    while True:

        #watch for keyboard and mouse events
        gf.check_events(rpaddle, lpaddle, stats)
        if stats.game_active:
            gf.update_rpaddle(game_settings, rpaddle)
            gf.update_lpaddle(game_settings, lpaddle)
            gf.update_ball(game_settings, rpaddle, lpaddle, ball, stats,
                           scoreboard, winner_msg)

        #update screen
        gf.update_screen(game_settings, screen, rpaddle, lpaddle, ball,
                         play_button, stats, scoreboard, winner_msg)
Esempio n. 45
0
 def collision_car(self, drones, bullets):
     stats = Stats(self.settings, drones, bullets)
     for drone in drones:
         if self.car_rect.colliderect(drone):
             stats.settings.lives -= 1
             time.sleep(self.settings.sleep_time)
             drones.remove(drone)
Esempio n. 46
0
class Ultra3Upgrade(AddBuildingUpgrade):
    name = "b_ultra3"
    resource_type = "gas"
    category = "buildings"
    title = "Proximity Mines"
    description = "Make a line of Mines between two of your planets"
    icon = "proximitymines"
    cursor = ["allied_planet", "allied_planet"]
    family = {'tree': 'ultra', 'parents': ['b_ultra2a', 'b_ultra2b']}
    requires = lambda x: 'b_ultra1' in x and ('b_ultra2a' in x or 'b_ultra2b'
                                              in x)
    building = make_simple_stats_building(stats=Stats(), shape="ultra")

    def apply(self, to, second):
        if to == second:
            return False

        scene = to.scene
        if scene.flowfield.has_field(second):
            pass

        delta = second.pos - to.pos
        dn = helper.try_normalize(delta)
        pos = to.pos + dn * (to.get_radius() + 10)
        i = 0
        while (pos - second.pos).length_squared() > (10 +
                                                     second.get_radius())**2:
            sm = SpaceMine(scene, pos, to.owning_civ, i / 9)
            scene.game_group.add(sm)
            step = scene.flowfield.get_vector(pos, second, 0) * 15
            pos += step
            i += 1

        return super().apply(to)
Esempio n. 47
0
 def __init__(self,size,caption, world_size = (100,100), fps=30,seed=1000):
     random.seed(seed)
     pygame.init()
     self.gameDisplay = pygame.display.set_mode(size)
     pygame.display.set_caption(caption)
     self.size=size
     self.stats = Stats()
     self.clock = pygame.time.Clock()
     self.world = World(world_size[0],world_size[1])
     self.af = AnimalFactory(self.world,self.gameDisplay)
     self.pf = PlantFactory(self.world,self.gameDisplay)
     self.pause = False
     self.state = 1  
     self.fps = fps
     self.frame=0
     initPopulation(self.pf, self.af, world_size, 20,800, 10 , 9, 200)
Esempio n. 48
0
    def __init__(self, x, y, song=None, color=[255,0,0], width=32, height=32,
                 name='Creature',txt="A creature aproaches. He doesn't \
look too happy to see you.", element=Non()):
        
 
        # Call the parent class (Sprite) constructor
        super().__init__()
 
        # Create an image of the block, and fill it with a color.
        # This could also be an image loaded from the disk.
        self.image = pygame.Surface([width, height])
        self.image.fill(color)
 
        # Fetch the rectangle object that has the dimensions of the image
        # image.
        # Update the position of this object by setting the values
        # of rect.x and rect.y
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.changeX = 0
        self.changeY = 0
        
        #player stats
        self.name = name
        self.txt = txt
        self.stats = Stats()
        self.element = element
        self.dead = False
        #print(self.stats)
        
        #for special ones*****
        self.song = song
Esempio n. 49
0
    def __init__(self, **kwargs):

        super(JournalInterfaceManager, self).__init__(**kwargs)
        self.windows = {}
        self.current_window = None


        # initially load the journal window as main window
        journal_menu = Journal()
        self.add_window("home", journal_menu)
        self.load_window("home")
        self.windows['home'].get_top_mistakes()


        omission = Omission()
        self.add_window("omission", omission)

        commission = Commission()
        self.add_window("commission", commission)

        archive = Archive()
        self.add_window("archive", archive)

        stats = Stats()
        self.add_window("stats", stats)
Esempio n. 50
0
 def __init__(self):
   f = open(self.ad_db_filename);
   self.ad_db = json.load(f);
   f.close();
   f = open(self.redirection_db_filename);
   self.redirection_db = json.load(f);
   f.close();
   f = open(self.ad_providers_filename);
   self.ad_providers = json.load(f);
   f.close();
   
   f = open(self.category_mapping_alexa_filename);
   self.category_mapping_alexa = json.load(f);
   f.close();
   f = open(self.category_mapping_yahoo_filename);
   self.category_mapping_yahoo = json.load(f);
   f.close();
   f = open(self.category_mapping_alchemy_filename);
   self.category_mapping_alchemy = json.load(f);
   f.close();
   f = open(self.category_mapping_bluecoat_filename);
   self.category_mapping_bluecoat = json.load(f);
   f.close();
   
   self.stats = Stats('Ad Extracting Statistics');
Esempio n. 51
0
    def fit(self, data):
        X, y = data
        X = X.values.transpose()

        self.classifier = RandomForestClassifier(kernel='linear', verbose=False)

        results = cross_validate(self.classifier.fit(X, y), X, y,
                                 scoring=self.conf_matrix_score, cv=5)

        result = np.array([[np.sum(results['test_tn']), np.sum(results['test_fp'])], \
                           [np.sum(results['test_fn']), np.sum(results['test_tp'])]])

        stat = Stats()
        stat.set_confusion_matrix(result)

        return stat
Esempio n. 52
0
def run_game():
    eg_settings = Settings()
    pygame.init()
    screen = pygame.display.set_mode(
        (eg_settings.screen_width, eg_settings.screen_height))

    virus = Virus(eg_settings, screen)
    pygame.display.set_caption("virus human")
    humans = Group()
    bullets = Group()
    stats = Stats(eg_settings)
    buttons = Button(eg_settings, screen, stats, virus, bullets, gf)
    sb = Score_Board(eg_settings, screen, stats)

    while True:
        gf.check_event(eg_settings, screen, virus, bullets, humans, buttons,
                       stats, sb)

        if stats.active_game:
            virus.update()

            gf.update_bullet(screen, bullets, humans, eg_settings, virus,
                             stats, sb)
            gf.update_human(humans, virus, stats, bullets, eg_settings, screen,
                            sb)
            if virus.flag:
                gf.fire_humans(eg_settings, screen, humans, virus)

        gf.update_screen(eg_settings, screen, virus, bullets, humans, buttons,
                         stats, sb)
Esempio n. 53
0
class Mechanics2aUpgrade(Upgrade):
    name = "t_mechanics2a"
    resource_type = "iron"
    category = "tech"
    title = "Decommission"
    description = "[!Destroy] 2 random [Fighters] you control. Gain [^5] population among random planets."
    icon = "decommission"
    stats = Stats()
    family = {'tree':'t_mechanics', 'parents':['t_mechanics1']}
    requires = ('t_mechanics1',)

    def apply(self, to):
        all_fighters = to.get_all_fighters()
        random.shuffle(all_fighters)
        for f in all_fighters[:2]:
            if f['type'] == 'ship':
                f['object'].kill()
            elif f['type'] == 'planet':
                f['object'].ships['fighter'] -= 1
                f['object'].needs_panel_update = True

        my_planets = to.scene.get_civ_planets(to)
        for i in range(5):
            random.choice(my_planets).population += 1

        return super().apply(to)
Esempio n. 54
0
def game():
    pygame.init()       #Initialize Pygame
    pygame.mixer.pre_init(44100, -16, 2, 2048)  # Reduce Lagging for the Music
    pygame.mixer.init()     #Initialize Mixer for Background Music
    pygame.mixer.music.load('bgm.wav')      #Load the BGM File
    pygame.mixer.music.play(-1)     #Play the BGM Infinitely
    screen=pygame.display.set_mode((500,650))       #Set the Pygame Window
    pygame.display.set_caption("STARHEAD EXTERMINATOR")     #Set the Window Caption

    #Call All the Classes
    txt = "DONT SHOOT THE GREEN ONE"
    button = Button(screen,txt)
    stats = Stats()
    gun = Gun(screen)
    enemy = Enemy(screen,stats)
    host = Hostage(screen,stats)
    score = Score(screen, stats)
    enemies = Group()
    hostage = Group()
    #Start the Game Loop
    while True:
        gf.firstscreen(screen,button,stats,gun,enemies,hostage,score)      #First Display of the Game 
        if stats.game_active:       #Start when the Player Click the Button
            gf.gametrue(screen,stats,gun,enemies,hostage,score)     #Update and Behaviour of Objects in the Game
        gf.update_screen(screen,gun,enemies,hostage,button,stats)       #Update the Screen and Flip
Esempio n. 55
0
def run_game():
    # initialize game and create screen object
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(settings.screen_res)
    pygame.display.set_caption("Alien Invasion")
    stats = Stats()
    ship = Ship(screen)
    bullets = Group()
    aliens = Group()
    play_button = Button(settings, screen, 'Play')
    scoreboard = Scoreboard(settings, screen, stats)
    fun.create_fleet(settings, screen, aliens, ship.rect.height, stats)

    # start the main loop for the game
    while True:
        fun.check_events(settings, screen, ship, bullets, stats, aliens, play_button, scoreboard)
        if stats.game_active:
            ship.update()
            bullets.update()
            aliens.update()
            fun.drop_aliens(aliens)
            fun.collide(ship, aliens, bullets, settings, stats)
            fun.delete_bullets(bullets)
        fun.update_screen(screen, settings, ship, bullets, aliens, stats, play_button, scoreboard)
Esempio n. 56
0
def rungame():
	#初始化
	pygame.init()
	al_setting = Settings()
	#创建窗口
	screen = pygame.display.set_mode((al_setting.screen_width,
	al_setting.screen_height))
	pygame.display.set_caption("catch the ball")
	stats = Stats(al_setting)
	#创建角色
	people = People(al_setting,screen)
	#创建球组
	balls = Group()
	#创建角色组
	peoples = Group()
	peoples.add(people)
	while True:
		#鼠标键盘相应事件
		gf.check_event(people)
		if stats.game_active:	
			#更新角色位置
			people.update()
			#更新球的位置
			gf.ball_update(al_setting,screen,balls,peoples,stats)
			#刷新界面
		gf.screen_update(al_setting,screen,balls,people)
Esempio n. 57
0
    def _initStats(self, season=None, perMode='PerGame'):
        '''
		Constructs a Stats object with a given season
		:param season: 	A valid season string (ex. '2015-16'), default the Player's season
		:param perMode: How the averages are displayed, 'PerGame', 'Per36', etc.
		:return:		***IMPORTANT*** Returns a tuple of a seasonStats list along with a statsHeaders list
		'''
        if not season:
            season = self.season()

        loadSuccess = True

        stats_url = helpers.get_url('playercareerstats',
                                    PerMode=perMode,
                                    PlayerID=self.playerID())

        try:
            allStats = Series(
                requests.get(stats_url, headers=USER_AGENT).json())
        except ValueError as e:
            loadSuccess = False
            print 'Could not load stats for player "' + self.name() + '"'
            print 'Error:', e.message
            print 'URL:', stats_url
        if loadSuccess:
            statsHeaders = allStats['resultSets'][0]['headers']
            for obj in allStats['resultSets'][0]['rowSet']:
                if season in obj:
                    seasonStats = obj
            self._stats = Stats(
                Series(dict(zip(statsHeaders, seasonStats)), name=self._name))

        else:
            self._stats = None
Esempio n. 58
0
    def send_command(self, command):
        """
        Send a command to the ip address. Will be blocked until
        the last command receives an 'OK'.
        If the command fails (either b/c time out or error),
        will try to resend the command
        :param command: (str) the command to send
        :param ip: (str) the ip of Tello
        :return: The latest command response
        """
        self.log.append(Stats(command, len(self.log)))

        self.socket.sendto(command.encode('utf-8'), self.tello_adderss)
        print 'sending command: %s to %s' % (command, self.tello_ip)

        start = time.time()
        while not self.log[-1].got_response():
            now = time.time()
            diff = now - start
            if diff > self.MAX_TIME_OUT:
                print 'Max timeout exceeded... command %s' % command
                # TODO: is timeout considered failure or next command still get executed
                # now, next one got executed
                return
        print 'Done!!! sent command: %s to %s' % (command, self.tello_ip)
Esempio n. 59
0
def start_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))

    pygame.display.set_caption("Alien Attack")

    play_button = Button(settings, screen, "Play")

    stats = Stats(settings)
    sb = ScoreBoard(settings, screen, stats)

    ship = Ship(settings, screen)
    bullets = Group()
    aliens = Group()

    gf.create_fleet(settings, screen, ship, aliens)

    while True:
        gf.check_events(settings, screen, stats, sb, play_button, ship, aliens,
                        bullets)

        if stats.game_active:
            update_elements(settings, screen, stats, sb, ship, aliens, bullets)

        gf.update_screen(settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
 def test_avg(self):
     """
     Batting average test
     :return:
     """
     # Barry bonds(2004)
     avg = Stats.avg(135, 373)
     self.assertEqual(avg, 0.362)