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 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 __init__(self): print(protologue) self.inp = Input() self.upd = Update() self.world = World(3,4) self.player1 = Player(self.world) self.out = Output()
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 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 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 __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): """ 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 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 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 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 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_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)
class Game: def __init__(self): self.inp = Input() self.upd = Update() self.player1 = Player() self.out = Output() def update(self): self.inp.update(self.upd) self.upd.update(self.player1, self.out) self.out.update()
def test_get_apt_last_update_date_when_file_exists(self): # Prepare data and mocks with patch('builtins.open', raise_file_not_found_error), NamedTemporaryFile() as temp_file: update = Update(None) seconds_epoch_in_1999 = 923398970 os.utime(temp_file.name, (seconds_epoch_in_1999, seconds_epoch_in_1999)) # Run test scenario result = update.get_apt_last_update_date(temp_file.name) # Assertions self.assertEqual(result.timestamp(), seconds_epoch_in_1999)
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 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')
class Game: 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 update(self): self.inp.update(self.upd) self.upd.update(self.player1, self.out, self.world) self.out.update()
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_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_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([])
def test_get_apt_last_update_date_when_file_exists(self): # Prepare data and mocks with patch( 'builtins.open', raise_file_not_found_error), NamedTemporaryFile() as temp_file: update = Update(None) seconds_epoch_in_1999 = 923398970 os.utime(temp_file.name, (seconds_epoch_in_1999, seconds_epoch_in_1999)) # Run test scenario result = update.get_apt_last_update_date(temp_file.name) # Assertions self.assertEqual(result.timestamp(), seconds_epoch_in_1999)
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 test_updater(env): targetdir = os.path.join(env.workdir, "target_updater") targetversion = env.VERSIONS[-1] for v in env.VERSIONS[:-1]: shutil.copytree(os.path.join(env.workdir, v), targetdir) manifestPath = os.path.join(env.workdir, "test-%s-%s-delta-from-%s-manifest.xml.bz2" % (targetversion, env.PLATFORM, v)) print "trying %s" % manifestPath um = Update.parse(BZ2File(manifestPath).read()) cmd = ["../build/src/updater", "--install-dir=%s" % targetdir, "--package-dir=%s" % env.workdir, "--auto-close", "--script=%s" % manifestPath] print "running: %s" % (" ".join(cmd)) res = subprocess.call(cmd) assert res == 0 for f in um.manifest: fpath = os.path.join(targetdir, f.name) assert os.path.exists(fpath) assert env.get_sha1(fpath) == f.fileHash fmap = um.get_filemap() for root, dirs, files in os.walk(targetdir): for f in files: fname = os.path.join(root, f) fname = fname.replace(targetdir + "/", "") assert fname in fmap shutil.rmtree(targetdir)
def __init__(self, update, parent = None): QtGui.QDialog.__init__(self, parent) self.setupUi(self) self.hours.setSingleStep(0.25) self.message.setText(update.message) self.started_at.setDateTime(Update.to_local_timezone(update.started_at)) self.tzinfo = update.started_at.tzinfo # store initial tzinfo to be able to convert back if update.finished_at is not None: self.finished_at.setDateTime(Update.to_local_timezone(update.finished_at)) self.hours.setValue(update.hours) else: self.finished_at.setEnabled(False) self.hours.setEnabled(False)
def test_patch_delta(env): # first make a copy of the version we want to patch targetdir = os.path.join(env.workdir, "target") patchdir = os.path.join(env.workdir, "patches") shutil.copytree(os.path.join(env.workdir, "v1.0"), targetdir) os.makedirs(patchdir) zf = zipfile.ZipFile(env.get_deltaZipPaths()[0]) zf.extractall(patchdir) zf.close() deltamanifest = Update.parse( BZ2File(env.get_deltaManifestPaths()[0], "r").read()) for p in deltamanifest.patches: cmd = [ "../build/external/bsdiff/bspatch-endsley", os.path.join(targetdir, p.name), os.path.join(targetdir, p.name + ".new"), os.path.join(patchdir, p.patchName) ] print cmd res = subprocess.call(cmd) assert res == 0 assert file(os.path.join( targetdir, p.name + ".new")).read() == "This file changes with versions v3.0" shutil.rmtree(targetdir) shutil.rmtree(patchdir)
def mainMenu(): print('''Main Menu -------------------------------------------- 1. View Data 2. Create Data 3. Update Data --------------------------------------------''') mainMenuInput = input("Input choice(q to Quit): ") mainMenuInput = mainMenuInput.lower() if mainMenuInput == "1": viewMenuOutput = View.viewMenu() if viewMenuOutput == "b": ProgramUI.mainMenu() elif viewMenuOutput == "q": return viewMenuOutput elif mainMenuInput == "2": createMenuOutput = Create.createMenu() if createMenuOutput == "b": ProgramUI.mainMenu() elif createMenuOutput == "q": return createMenuOutput elif mainMenuInput == "3": updateMenuOutput = Update.updateMenu() if updateMenuOutput == "b": ProgramUI.mainMenu() elif updateMenuOutput == "q": return updateMenuOutput elif mainMenuInput == "q": return mainMenuInput else: print("Wrong input, try again") ProgramUI.mainMenu()
def verify_directory(manifestPath, directory): u = None try: u = Update.parse(file(manifestPath).read()) except: print "Failed to parse manifest: " + manifestPath return False if not os.path.isdir(directory): print "%s is not a directory" % directory return False filemap = u.get_filemap() for root, dirs, files in os.walk(directory): for f in files: fullpath = os.path.join(root, f) fpath = fullpath.replace(directory + "/", "") if not fpath in filemap: print "Could not find file %s in manifest" % fpath return False ufe = filemap[fpath] fe = hashutils.get_file((fullpath, directory + "/")) if not fe == ufe: print "Could not match %s to the manifest: %s" % (fpath, ",".join(fe.whyneq(ufe))) return False return True
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 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 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 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 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_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([])
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 exec_update(self, target): print 'Please be aware that an update will replace anything you have done to the files.' ack = raw_input('Continue: yes/[no] ') if ack != 'yes': print 'Canceling update.' sys.exit() if self._module is not None: try: u = getattr(self._module.plugin, 'Update')(self._config, target) except AttributeError: u = Update(self._config, self._update_test, target) else: u = Update(self._config, self._update_test, target) u.run() print 'Successfully updated the project.'
def exec_update(self, plugin, target): print 'Please be aware that an update will replace anything you have done to the files.' ack = raw_input('Continue: yes/[no] ') if ack != 'yes': print 'Canceling update.' sys.exit() try: update = Update(self._config, plugin, self._update_test) if target is not None: if target is 'libs': print 'Updating libs directory ...' update.update_libs() if target is 'html': print 'Updating index.html file ...' update.update_html() if target is 'config': print 'Update project.cfg file ...' update.update_config() if target is 'javascript': print 'Update JavaScript files ...' update.update_javascript() if target is 'css': print 'Update css files ...' update.update_css() else: print 'Do you really want to update all files? Changes to any files you might have done will be lost in the process!' ack = raw_input('Continue: yes/[no] ') if ack != 'yes': print 'Canceling update.' sys.exit() print 'Updating everything ...' update.update_all() except: raise print 'Successfully updated the project.'
def __init__(self): QtGui.QMainWindow.__init__(self) self.setupUi(self) # init subsystems self.config = Config() self.config.read() self.config.set_defaults() self.remote = Remote(self.config) self.updates_layout = QtGui.QVBoxLayout(self.scrollAreaWidgetContents) self.updates_layout.setMargin(1) self.storage = UpdatesStorage(os.path.expanduser(self.config['qttt']['db_path']), self.updates_layout, self.remote) # gui options self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.tray = QtGui.QSystemTrayIcon(self) icon = QtGui.QIcon(os.path.join(os.path.dirname(__file__), 'icon.png')) self.tray.setIcon(icon) self.setWindowIcon(icon) self.tray.show() self.gb_current.hide() self.move( self.config['qttt']['geometry']['left'], self.config['qttt']['geometry']['top'] ) self.resize(self.config['qttt']['geometry']['width'], self.config['qttt']['geometry']['height'] ) self.setWindowTitle('QTTT - %s' % self.config['site']['base_url']) self.lb_current.setWordWrap(True) # connections self.connect(self.action_Qt, QtCore.SIGNAL('activated()'), QtGui.qApp.aboutQt) self.connect(self.pb_update, QtCore.SIGNAL('clicked()'), self.sendUpdate) self.connect(self.le_update, QtCore.SIGNAL('returnPressed()'), self.sendUpdate) self.connect(self.pb_stop, QtCore.SIGNAL('clicked()'), self.finishLast) self.connect(self.tray, QtCore.SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), self.trayActivated) self.connect(QtGui.qApp, QtCore.SIGNAL('lastWindowClosed()'),self.writeConfig) self.refresh_timer = QtCore.QTimer() self.refresh_timer.setInterval(5*60*1000) # 5 minutes self.connect(self.refresh_timer, QtCore.SIGNAL('timeout()'), self.getUpdates) self.refresh_timer.start() self.last_update_timer = QtCore.QTimer() self.last_update_timer.setInterval(1000) # 1 second self.connect(self.last_update_timer, QtCore.SIGNAL('timeout()'), self.refreshLastUpdateTime) # retrieve data try: user = self.remote.getUser() except: QtGui.QMessageBox.warning(self, u"Ошибка", u"Не могу соединиться с сервером") # it's hard but it's WORKING! :) exit() if user.get('error') is not None: QtGui.QMessageBox.warning(self, u"Ошибка", u"Неверный api-key указан в .tttrc файле") # it's hard but it's WORKING! :) exit() Update.set_current_user(user['nickname']) self.storage.loadUpdatesFromDB() self.getUpdates() self.getProjects()
if args.delete > 0 : params["action"] = "delete" if args.update : params["execute"] = True params["ip"] = [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1] services = [] linuxInstance = Linux(params) services.append(linuxInstance) if args.update : updateInstance = Update(params) updateInstance.update() exit() if args.withsql > 0 or args.delete > 0 : mysqlInstance = Mysql(params,linuxInstance) services.append(mysqlInstance) if args.withftp > 0 or args.delete > 0 : if args.withsql == 0 : mysqlInstance = Mysql(params,linuxInstance) pureftpInstance = Pureftp(params,mysqlInstance,linuxInstance) services.append(pureftpInstance) if args.withssh > 0 or args.delete > 0 : sshInstance = Ssh(params,linuxInstance)
def changed_update(self): return {"message" : self.message.text(), "started_at" : Update.from_local_timezone(self.started_at.dateTime().toPyDateTime(), self.tzinfo), "finished_at" : Update.from_local_timezone(self.finished_at.dateTime().toPyDateTime(), self.tzinfo) if self.finished_at.isEnabled() else None, "hours" : self.hours.value() if self.hours.isEnabled() else None}