def AgentProgram(N): state = Initialize(N) total_conflicts = 0 for col in range(N): row = np.where(state[:, col] == 1)[0][0] conflicts = np.sum(state[row, :]) k = col - row conflicts += np.sum(np.diag(state, k)) k = N - 1 - col - row conflicts += np.sum(np.diag(np.fliplr(state), k)) conflicts -= 3 total_conflicts = total_conflicts + conflicts col = 0 no_update = 0 for i in range(1000): if GoalTest(state): return total_conflicts row = np.where(state[:, col] == 1)[0][0] total_conflicts = Update(state, col, total_conflicts) if no_update == N: total_conflicts = RandomRestart(state=state,col=col,\ total_conflicts=total_conflicts) no_update = 0 else: if row == np.where(state[:, col] == 1)[0][0, 0]: no_update += 1 else: no_update = 0 col = (col + 1) % N return total_conflicts
def main(): logging.basicConfig(filename="manager.log", format="%(levelname)s: %(message)s", level=logging.INFO) logging.info('====================================================') logging.info(' %s', datetime.now().strftime("%Y-%m-%d %H:%M:%S")) logging.info('====================================================') parser = argparse.ArgumentParser(description='database manager') parser.add_argument('--update', help='update data') parser.add_argument('--calc', help='data visualization') args = parser.parse_args() if args.update: from PyQt5.QtWidgets import QApplication from update import Update if args.update in ['marketinfo', 'OHLC', 'minute']: app = QApplication(sys.argv) kiwoom = Update(args.update) kiwoom.CommConnect(0) sys.exit(app.exec_()) else: raise NameError(args.update) elif args.calc: from calc import Calc calc = Calc() if args.calc == 'density': calc.density()
def update(jdID, content): time1, date1, detail1, selftime1 = content['oSTime'], content['oDate'], content['oEvent'], content['oSeTime'] time2, date2, detail2, selftime2 = content['nSTime'], content['nDate'], content['nEvent'], content['nSeTime'] year1, month1, day1, hour1, minute1, __, detail1 = get_properties(date=date1, time=time1, detail=detail1) year2, month2, day2, hour2, minute2, __, detail2 = get_properties(date=date2, time=time2, detail=detail2) endtime = content['nETime'] selftime1 = None if 'value' not in selftime1 else selftime1['value'] selftime2 = None if 'value' not in selftime2 else selftime2['value'] detail2 = detail1 if detail2 is None else detail2 hour2 = hour1 if hour2 is None else hour2 minute2 = minute1 if minute2 is None else minute2 duration2 = get_duration(endate=date2, endtime=endtime, year=year2, month=month2, day=day2, hour=hour2, minute=minute2) e1 = Event(jdID=jdID, year=year1, month=month1, day=day1, hour=hour1, minute=minute1, isUpdate=True, event_detail=detail1) e2 = Event(jdID=jdID, year=year2, month=month2, day=day2, hour=hour2, minute=minute2, isUpdate=True, duration=duration2, event_detail=detail2) update = Update(db=db, jdID=jdID, old_event=e1, new_event=e2, old_selftime=selftime1, new_selftime=selftime2) rst = update.update() return rst
def update(): now = datetime.now() q = Update.query().order(-Update.order) q2 = q.fetch() last = q2[0].order new = Update(price=get_all(), time=now, order=last + 1) key = new.put()
def __init__(self): """ Pull all variables from config.py file. """ self.player = Player() self.database = config.database self.Max_point_tournament = config.Max_point_tournament self.BotNet_update = config.BotNet_update self.joinTournament = config.joinTournament self.tournament_potator = config.tournament_potator self.booster = config.booster self.Use_netcoins = config.Use_netcoins self.attacks_normal = config.attacks_normal self.updates = config.updates self.updatecount = config.updatecount self.maxanti_normal = config.maxanti_normal self.active_cluster_protection = config.active_cluster_protection self.mode = config.mode self.stat = "0" self.wait_load = config.wait_load self.c = Console(self.player.username, self.player.password) self.u = Update(self.player.username, self.player.password) self.b = Botnet(self.player) self.ddos = ddos.Ddos() self.init()
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 __init__(self): """ Pull all variables from config.py file. """ self.player = Player() self.database = config.database self.Max_point_tournament = config.Max_point_tournament self.BotNet_update = config.BotNet_update self.joinTournament = config.joinTournament self.tournament_potator = config.tournament_potator self.booster = config.booster self.Use_netcoins = config.Use_netcoins self.attacks_normal = config.attacks_normal self.updates = config.updates self.updatecount = config.updatecount self.maxanti_normal = config.maxanti_normal self.active_cluster_protection = config.active_cluster_protection self.mode = config.mode self.number_task = config.number_task self.min_energy_botnet = config.minimal_energy_botnet_upgrade self.stat = "0" self.wait_load = config.wait_load self.c = Console(self.player) self.u = Update(self.player) # disable botnet for > api v13 self.b = Botnet(self.player) self.ddos = ddos.Ddos(self.player) self.m = Mails(self.player) self.init()
def calc_img(self, ut, imgstring, uhash, hostname, max, mode, api): ut = Utils() pic = cStringIO.StringIO() image_string = cStringIO.StringIO(base64.b64decode(imgstring)) image = Image.open(image_string) # Overlay on white background, see http://stackoverflow.com/a/7911663/1703216 #bg = Image.new("RGB", image.size, (255,255,255)) #bg.paste(image,image) if "Hatched by the FBI" in pytesseract.image_to_string( image) or "Watched by the FBI" in pytesseract.image_to_string( image): print "Matched FBI" return 1, hostname else: firewall = pytesseract.image_to_string(image).split(":") try: if int(firewall[2].strip()) < max: try: time.sleep(random.randint(1, 3)) temp = ut.requestStringNoWait( "user::::pass::::uhash::::hostname", self.api.getUsername() + "::::" + self.api.getPassword() + "::::" + str(uhash) + "::::" + str(hostname), "vh_scanHost.php") jsons = json.loads(temp) if not ".vHack.cc" in str(jsons['ipaddress']) and int( jsons['vuln']) == 1: if mode == "Secure": time.sleep(random.randint(1, 3)) elif mode == "Potator": time.sleep(random.randint(0, 1)) result = self.attackIP(jsons['ipaddress'], max, mode) # remove spyware u = Update(api) spyware = u.SpywareInfo() if int(spyware[0].split(":")[-1]) > 0 and not int( spyware[0].split(":")[-1]) == 0: u.removeSpyware() print "I'm remove " + str(spyware[0].split( ":")[-1]) + " Spyware for your account." return result, jsons['ipaddress'] #else: # temp = ut.requestString("user::::pass::::uhash::::hostname", self.api.getUsername() + "::::" + self.api.getPassword() + "::::" + str(uhash) + "::::" + jsons['ipaddress'], "vh_scanHost.php") # if not ".vHack.cc" in str(jsons['ipaddress']) and int(jsons['vuln']) == 1: # time.sleep(1) # self.attackIP(jsons['ipaddress'], max, mode) except TypeError: return 0, 0 else: print "Firewall is to Hight" return 0, 0 except ValueError: return 0, 0
def main(): """ Runs the program """ config = get_config() scanners = [] if config['enabled']['openports']: scanners.append(OpenPorts(config)) if config['enabled']['root']: scanners.append(Root(config)) if config['enabled']['ssh']: scanners.append(Ssh(config)) if config['enabled']['umask']: scanners.append(Umask(config)) if config['enabled']['update']: scanners.append(Update(config)) if config['enabled']['worldwritable']: scanners.append(WorldWritable(config)) for scanner in scanners: print('-' * 79) print('Running:', scanner.__class__.__name__) result = scanner.scan() print('Status:', result[0]) print('Message:', result[1]) print()
def __init__(self, address): super().__init__(address) self.about = About(self) self.access = Access(self) self.adjustment = Adjustment(self) self.axis = Axis(self) self.displacement = Displacement(self) self.ecu = Ecu(self) self.functions = Functions(self) self.manual = Manual(self) self.network = Network(self) self.nlc = Nlc(self) self.pilotlaser = Pilotlaser(self) self.realtime = Realtime(self) self.system = System(self) self.system_service = System_service(self) self.update = Update(self) try: self.streaming = Streaming(self) except NameError as e: if "Streaming" in str(e): print("Warning: Streaming is not supported on your platform") else: raise e
def get_updates(offset=0): if os.path.exists(CURRENT_OFFSET_FILE) and os.path.isfile( CURRENT_OFFSET_FILE): with open(CURRENT_OFFSET_FILE) as f: read_current_offset_id = f.read() if read_current_offset_id and read_current_offset_id.isdigit( ) and int(read_current_offset_id) > offset: offset = int(read_current_offset_id) url = URL + 'getupdates?offset={}'.format(offset) r = requests.get(url) data = r.json() if data['ok']: updates = list() for update in data['result']: updates.append( Update({ "update_id": update['update_id'], "chat_id": update['message']['chat']['id'], "text": update['message']['text'], "user_id": update['message']['from']['id'], "first_name": update['message']['from']['first_name'], "last_name": update['message']['from']['last_name'] })) return updates
def POST(self): if self.input['oper'] == 'del': d = Delete(self.input) return d.delete() elif self.input['oper'] == 'edit': u = Update(self.input) return u.update()
def create_tree(file, tree, prep, ns): for i in file: prefix = i.find(ns('{prep}rt-destination')).text mask = i.find(ns('{prep}rt-prefix-length')).text key = (ip_to_int(prefix), mask) kwargs = {} kwargs['nh'] = i.find(ns('{prep}rt-entry/{prep}nh/{prep}to')).text kwargs['nh'] = 'self' if key[0] > 4294967295: kwargs['nh'] = '::ffff:172.30.152.20' asp = i.find(ns('{prep}rt-entry/{prep}as-path')).text.rstrip() asp = get_as_path_origin_atomic(asp) community = '' for comm in i.findall( ns('{prep}rt-entry/{prep}communities/{prep}community')): community += comm.text + ' ' kwargs['community'] = community if len(asp) == 2: kwargs['as_path'] = asp[0] kwargs['origin'] = asp[1] else: kwargs['as_path'] = asp[0] kwargs['origin'] = asp[1] kwargs['aggregator'] = asp[3] med = i.find(ns('{prep}rt-entry/{prep}med')) lp = i.find(ns('{prep}rt-entry/{prep}local-preference')) if med is not None: kwargs['med'] = med.text if lp is not None: kwargs['lp'] = lp.text update = Update(prefix, mask, **kwargs) tree.insert(key, update)
def update_screen(self): """ 更新画布界面 :return: """ self.cells.cells = Update(self.cells.cells) self.draw_cells() self.canvas.after(100, self.update_screen)
def update(self): Popen('clear'.split()).wait() print 'Updating System ...' Update().rewrite() Popen('apt-get update -qq', shell=True).wait() Popen('clear'.split()).wait() print 'Upgrading System ...\n\n' Popen('apt-get dist-upgrade -y', shell=True).wait()
def scheduled_job(): print("Updated Started") #TODO: send a discord message u = Update() u.saveExpValues() u.saveStats() t = Util() print("Update Finished: "+str(t.getGMTTime()))
def Process(path, filename): #crawler(sum=1000) sort2txt(path) fenci() delspace() calres_big() merge() Update(filename)
def get_fantasy_league_info(self): print "*get_fantasy_league_info(self)" connection = self.connect() try: with connection.cursor() as cursor: sql = "SELECT * FROM `df_league_{}`".format( self.week_corrected) cursor.execute(sql) df = pd.DataFrame(cursor.fetchall(), columns=[ 'name', 'rank', 'w-l-t', 'points', 'trades', 'moves', 'draft_pos', 'team_key' ]) # rename the columns for aesthetics df = df.rename( columns={ 'name': 'Name', 'rank': 'Rank', 'w-l-t': 'Wins-Losses-Ties', 'points': 'Points', 'trades': 'Trades', 'moves': 'Moves', 'draft_pos': 'Draft Position', 'team_key': 'Key' }) proj_points = {} try: for key in df['Key']: print " Key to get projected points for:", key proj_points[key] = [self.get_projected_points(key)] df_points = pd.DataFrame.from_dict(proj_points, orient='index') df_points = df_points.rename( columns={0: 'Projected_Points'}) print df_points df = df.merge(df_points, left_on=df.Key, right_on=df_points.index.values) print df except Exception as e: print e else: print " success appending Projected_Points to league dataframe" # return df except: print " don't have current week info so get it" update = Update(self.week, self) return update.main() else: print " successfully got current week fantasy league info from the database" return df finally: connection.close()
def test_scan_redhat(self): # Prepare data and mocks update = Update(None) # Run test scenario result = update.scan_redhat() # Assertions self.assertEqual(result[0], ScanStatus.unknown)
def scheduled_job(): print("Updated Started") #TODO: send a discord message u = Update() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(u.saveExpValues()) loop.run_until_complete(u.saveStats()) t = Util() print("Update Finished: " + str(t.getGMTTime()))
def test_get_pacman_last_update_date_when_not_found(self): # Prepare data and mocks file_contents_list = ['no such lines here'] # Run test scenario last_update_date = Update(None).get_pacman_last_update_date( file_contents_list) # Assertions self.assertIsNone(last_update_date)
def test_scan_when_unknown(self): # Prepare data and mocks with patch('platform.linux_distribution', lambda: ('Unknown linux distribution', None, None)): update = Update(None) # Run test scenario result = update.scan() # Assertions self.assertEqual(result[0], ScanStatus.unknown)
def main(self): Update().check() if (self.params["browse"] == "True"): th1 = threading.Thread(target=self.websock) th1.start() th2 = threading.Thread(target=self.flask) th2.start() os.system("cls") th3 = threading.Thread(target=self.trans) th3.start() th3.join()
def test_get_apt_last_update_date_when_file_does_not_exist(self): # Prepare data and mocks with patch('builtins.open', raise_file_not_found_error): update = Update(None) # Run test scenario result = update.get_apt_last_update_date( '/tmp/this/file/does/not/exist') # Assertions self.assertIsNone(result)
def load_run_and_attach_gain(runfile, updlens, nuggets, matches, useAverageLengths, track, query_durns): """ This function attaches gain (nuggets) to sentences of a run, on the fly """ run = {} with open(runfile) as rf: for line in rf: if len(line.strip()) == 0: continue qid, teamid, runid, docid, sentid, updtime, confidence = line.strip( ).split() if track == 'ts14': qid = 'TS14.' + qid updid = docid + '-' + sentid updtime = float(updtime) - query_durns[qid][ 0] # timestamps to start from 0 confidence = float(confidence) updlen = 30 if not useAverageLengths else updlens[qid][ "topic.avg.update.length"] #default updlen is 30 if updid in updlens[qid]: updlen = updlens[qid][updid] else: pass #print >> sys.stderr, 'no length for ', updid if qid not in run: run[qid] = [] #gain for update ngtstr = "" num_ngts = 0 matching_nuggets = [] if updid in matches[qid]: #update is relevant ngts_in_upd = matches[qid][updid] for ngtid in ngts_in_upd: if ngtid not in nuggets[ qid]: # there are 2 nuggets not in nuggets.tsv continue num_ngts += 1 ngt_gain, ngt_time = nuggets[qid][ngtid] # ngtstr += ','.join([ str(s) for s in [ngtid, ngt_gain, ngt_time] ]) # ngtstr += ' ' matching_nuggets.append( Nugget(ngtid, ngt_gain, ngt_time)) #run[qid].append( [updtime, confidence, updid, updlen, num_ngts, ngtstr] ) updobj = Update(qid, updid, updtime, confidence, updlen, num_ngts, ngtstr) updobj.nuggets = matching_nuggets if qid not in run: run[qid] = [] run[qid].append(updobj) return run
def test_scan_debian_when_last_update_date_not_found(self): # Prepare data and mocks config = {'update': {'warn_last_update_interval_days': '2'}} update = Update(config) update.get_apt_last_update_date = MagicMock(return_value=None) # Run test scenario result = update.scan_debian() # Assertions self.assertEqual(result[0], ScanStatus.unknown) update.get_apt_last_update_date.assert_called_once_with( '/var/lib/apt/periodic/update-success-stamp')
def test_scan_debian_when_is_newer(self): # Prepare data and mocks config = {'update': {'warn_last_update_interval_days': '2'}} update = Update(config) update.get_apt_last_update_date = MagicMock( return_value=datetime.today() - timedelta(days=1)) # Run test scenario result = update.scan_debian() # Assertions self.assertEqual(result[0], ScanStatus.success) update.get_apt_last_update_date.assert_called_once_with( '/var/lib/apt/periodic/update-success-stamp')
def test_scan_when_redhat(self): # Prepare data and mocks with patch('platform.linux_distribution', lambda: ('redhat', None, None)): update = Update(None) update.scan_redhat = MagicMock(return_value=(ScanStatus.unknown, 'message')) # Run test scenario result = update.scan() # Assertions self.assertEqual(result, (ScanStatus.unknown, 'message')) update.scan_redhat.assert_called_once_with()
def test_scan_arch_when_last_update_date_not_found(self): # Prepare data and mocks with patch('builtins.open', mock_open()) as mock_file: config = {'update': {'warn_last_update_interval_days': '2'}} update = Update(config) update.get_pacman_last_update_date = MagicMock(return_value=None) # Run test scenario result = update.scan_arch() # Assertions self.assertEqual(result[0], ScanStatus.unknown) mock_file.assert_called_once_with('/var/log/pacman.log') update.get_pacman_last_update_date.assert_called_once_with([])
def test_scan_arch_when_is_newer(self): # Prepare data and mocks with patch('builtins.open', mock_open()) as mock_file: config = {'update': {'warn_last_update_interval_days': '2'}} update = Update(config) update.get_pacman_last_update_date = MagicMock( return_value=datetime.today() - timedelta(days=1)) # Run test scenario result = update.scan_arch() # Assertions self.assertEqual(result[0], ScanStatus.success) mock_file.assert_called_once_with('/var/log/pacman.log') update.get_pacman_last_update_date.assert_called_once_with([])