def register(): if request.method == "GET": return render_template("register.html") else: username = request.form['username'] password = request.form['password'] if util.registerCheck(username): util.register(username, password) return redirect(url_for("login")) else: flash("Please choose a different Username") return redirect(url_for("register"))
def register(): if request.method=="GET": return render_template("register.html") else: username = request.form['username'] password = request.form['password'] if util.registerCheck(username): util.register(username,password) return redirect(url_for("login")) else: flash("Please choose a different Username") return redirect(url_for("register"))
def __init__(self): self.id = util.register(self,'actor') self.name = "Placeholder Man" self.reaction_base = [] self.reaction_actv = [] tourism.generate_random_amenity_prefs(self) self.reaction_base.append( {'Name':'Clutter', 'Inputs':{}, 'Outputs':{'SanitationJob': .05 } } ) self.skill = job.generate_random_skillset() self.mass = 80 self.financial_account = 0 _weights = [ random.random(), random.random() ] #recreation, savings _sum = sum(_weights) self.financial_priorities = {'Recreation':_weights[0]/_sum, 'Savings':_weights[1]/_sum} self.home_station = None self.home_relationship = None self.role = 'Staff' #also: Freelancer, Tourist self.priority = 0.5
def __init__(self,name='Place Holder',station=None, logger=None): self.my_tasks = TaskTracker() self.id = util.register(self) self.name = name if logger: self.logger = logging.getLogger(logger.name + '.' + self.name) elif station: self.logger = logging.getLogger(station.logger.name + '.' + self.name) else: self.logger = logging.getLogger(util.generic_logger.name + '.' + self.name) self.loggername = self.logger.name self.needs = dict() self.needs['Idle Curiosity']=Need('Idle Curiosity', self, 100, 0, 0, self.new_idle_task, None) self.task = None #currently active task self.action = None #placeholder for graphical animation or tweening or w/e self.task_abandon_value = 5 #if a task's importance outweighs the current task by this much, we drop and switch self.location = None self.station = station self.inventory = Stowage(0.5) self.path=None self.held=None self.sprite=None self.xyz = np.array([ 0, 0, 0 ]) self.orientation = np.array([ 0, 0, 0 ]) self.speed = 1.0 #meter per second travel time, "A leisurely float" if self.station is not None: self.station.actors[self.id] = self self.location = self.station.random_location()[1] self.xyz = self.station.loc_to_xyz(self.location) self.refresh_image()
def __init__(self, installed=None, logger=None, name='UnspecifiedEquipment'): self.id=util.register(self) self.components = [] #list of items used to build this equipment self.installed=None #pointer to module if installed, none if loose self.mass=100 self.task=None self.power_usage = 0 #in kilowatts self.powered = False self.idle_draw = 0 #in kilowatts self.in_vaccuum = False #if True, requires EVA to service self.volume = 1.3 #m^3 self.broken = False self.name = name self.type = 'Misc' self.satisfies = dict() #what qualities can this equipment provide? self.logger = logging.getLogger(logger.name + '.' + self.name) if logger else util.generic_logger self.loggername = self.logger.name self.visible = True self.local_coords = 0.75*np.array([random.uniform(-1,1),random.uniform(-1,1),0]) self.sprite=None #basic health stats and such go here, as well as hooking into the task system #if not hasattr(self,'imgfile'): self.imgfile = "images/placeholder_equipment.tif" self.refresh_image()
def __init__(self, logger=None): self.id = util.register(self) print self.id if not hasattr(self,'size'): self.size = np.array([ 3 , 2 , 2 ]) self.stowage = Stowage(10) #things floating around in the module self.exterior_stowage = Stowage(0) #things strapped to the outside of the module self.sprite = None self.gravity = np.array([ 0 , 0 , 0 ]) self.max_gravity = 0.01 self.min_gravity = 0 self.orientation = np.array([ math.pi/4 , 0 ]) self.location = np.array([ 0 , 0 , 0 ]) self.composition = {'Al' : 14500} self.package_material = [] #if a list of filters, material put in this will not be removed self.station = None self.manifest=None self.logger = logging.getLogger(logger.name + '.' + self.name) if logger else util.generic_logger self.loggername = self.logger.name self.atmo = Atmosphere() self.atmo.volume= math.pi * 2*self.size[0] * pow (self.size[1], 2) self.atmo.initialize('Air') self.equipment=dict() #miscellaneous (or unremovable) non-rack equipment self.player_installable = True self.paths = nx.Graph() self.nodes=dict() self.touched = False self.refresh_image()
def __init__(self, name): self.id = util.register(self) self.name = name self.amount = 0 self.supply = 1. self.demand = 1. self.price = 1. self.tc = 3600.
def __init__(self,name): self.id = util.register(self) self.name = name self.amount = 0 self.supply = 1. self.demand = 1. self.price = 1. self.tc = 3600.
def register(): if request.method == 'POST': data={k:'"'+v[0]+'"' for k,v in dict(request.form).items()} print data res = util.register(data) if res['code'] == 0: return redirect('/login/') elif res['code'] == 1: print res['msg'] return render_template("register.html",res=res) else: res={'msg':''} return render_template("register.html",res=res)
def register(): if request.method == "GET": return render_template("register.html") if request.method == "POST": form = request.form uname = form['username'] pword = form['password'] button = form['button'] if util.register(uname,pword): session['log'] = 'verified' session['username'] = uname return redirect(url_for('home')) else: return render_template('register.html',err="That username is taken!")
def register(): if request.method == "GET": return render_template("register.html") if request.method == "POST": form = request.form uname = form['username'] pword = form['password'] button = form['button'] if button == 'Login': return redirect(url_for('login')) if util.register(uname,pword): session['log'] = 'verified' session['username'] = uname return redirect(url_for('home')) else: return render_template('register.html',err="That username is taken!")
def register(): if request.method == "GET": return render_template("register.html") if request.method == "POST": form = request.form uname = form['username'] pword = form['password'] button = form['button'] if button == 'Login': return redirect(url_for('login')) if util.register(uname, pword): #Registes username but also has to return a boolean if successful. See Authenticate session['log'] = 'verified' session['username'] = uname return redirect(url_for('home')) else: return render_template('register.html', err="That username is taken!")
def __init__(self,**kwargs): self.built=False self.recipe = None self.composition = resource.Resource() self.occupation_level = 1 if 'site' in kwargs: self.site = kwargs['site'] self.site.stuff.append(self) else: self.site = None self.image = None self.imagename = kwargs['imagename'] if 'imagename' in kwargs else 'Default' self.id = util.register(self) self.generate_image()
def __init__(self, **kwargs): self.id = util.register(self) size = kwargs['size'] if 'size' in kwargs else default_size self.mapsize_x = size[0] self.mapsize_y = size[1] self.elevation = Layer([self.mapsize_x,self.mapsize_y]) self.vegetation = Layer([self.mapsize_x,self.mapsize_y]) self.ownership = Layer([self.mapsize_x,self.mapsize_y],dtype=np.uint16) self.layer = dict() self.layer['Pixies'] = ScentLayer([self.mapsize_x,self.mapsize_y]) #super(Map, self).__init__(**kwargs) '''self.rows = self.mapsize_y
def __init__(self, **kwargs): self.id = util.register(self) size = kwargs['size'] if 'size' in kwargs else default_size self.mapsize_x = size[0] self.mapsize_y = size[1] self.elevation = Layer([self.mapsize_x, self.mapsize_y]) self.vegetation = Layer([self.mapsize_x, self.mapsize_y]) self.ownership = Layer([self.mapsize_x, self.mapsize_y], dtype=np.uint16) self.layer = dict() self.layer['Pixies'] = ScentLayer([self.mapsize_x, self.mapsize_y]) #super(Map, self).__init__(**kwargs) '''self.rows = self.mapsize_y
def __init__(self,_map,name='Gabby'): self.map = _map self.myimage = None self.id = util.register(self) pos = np.array(_map.elevation.data.shape) /2 pos[0] += random.randint(-30,30) pos[1] += random.randint(-30,30) self.pos = [ int(pos[0]),int(pos[1]) ] #fiscal data self.wealth = 0.0 #money owed by/to the larger community self.credit_limit = 0.0 #amount self.labor = random.random() #stored workload #skills self.skills = { 'Strength': random.randint(1,3), 'Subtlety': random.randint(1,3), 'Smarts': random.randint(1,3), 'Speed': random.randint(1,3) }
def __init__(self, _map, name='Gabby'): self.map = _map self.myimage = None self.id = util.register(self) pos = np.array(_map.elevation.data.shape) / 2 pos[0] += random.randint(-30, 30) pos[1] += random.randint(-30, 30) self.pos = [int(pos[0]), int(pos[1])] #fiscal data self.wealth = 0.0 #money owed by/to the larger community self.credit_limit = 0.0 #amount self.labor = random.random() #stored workload #skills self.skills = { 'Strength': random.randint(1, 3), 'Subtlety': random.randint(1, 3), 'Smarts': random.randint(1, 3), 'Speed': random.randint(1, 3) }
def __init__(self,initial_module=None, name=None, logger=None, mission_control = None): self.modules=dict() self.id = util.register(self) self.exterior_objects=[] self.resources=ResourceBundle() self.paths=nx.Graph() self.tasks=TaskTracker() self.actors=dict() self.name = name if name else "GenericStation" self.logger = logging.getLogger(logger.name + '.' + self.name) if logger else util.generic_logger self.loggername = self.logger.name self.docked_stations = [] self.location = 'LEO' self.position = 'Approach' self.mission_control = mission_control self.sprite = None self.refresh_image() if initial_module: self.dock_module(None,None,initial_module,None)
def test_register(): util.register(token=env.env_var['USER_1_TOKEN']) util.register(token=env.env_var['USER_2_TOKEN']) util.register(token=env.env_var['USER_3_TOKEN'])
import util def tell(bot, args): if len(args) >= 4 and args[2] == "about": what = ' '.join(args[3:]).lower() library = { 'yourself': "I'm an awesome lil bot n.n", 'irc': "IRC stands for Internet Relay Chat, and you're using it this very minute! :O", 'enter': "Stop pressing the Enter key so much! Grrrrr. Rage rage rage.", 'sleep': "Sleep's pretty good, yep. You should do it sometime.", 'bacon': "Lemme tell you something. Bacon, is good for you. (see http://www.youtube.com/watch?v=2T_obaO46Bo for details.)", 'cubestormer': "The CubeStormer II is an awesome LEGO Mindstorms\x99 NXT robot that can solve Rubik's Cubes in a matter of seconds. See http://www.youtube.com/watch?v=_d0LfkIut2M for a video demonstration.", 'ql': "Quantum Levitation is fecking awesome. See http://www.youtube.com/watch?v=Ws6AAhTw7RA and http://www.youtube.com/watch?v=VyOtIsnG71U" } if library.get(what): if bot.inv['rooms'].get(bot.remote['receiver']): if args[1].lower() in [nick.lower() for nick in bot.inv['rooms'].get(bot.remote['receiver'])]: util.answer(bot, "%s: %s" % (args[1], library[what])) else: util.answer(bot, "%s: %s isn't in this channel." % (bot.remote['nick'], args[1])) else: util.answer(bot, "Triggering this command privately is not allowed.") else: util.answer(bot, "Dunno about that, n***a.") else: util.give_help(bot, args[0], "<nick> about <item>") util.register(tell, "common", "tell")
else: wordcount = float(doc.xpath('user_wordcount')[0].text) bot._debug("Word count: %d" % wordcount) percentage = (wordcount / 50000) * 100 bot._debug("Percentage: %d" % percentage) days = doc.xpath('wordcounts')[0] bot._debug("Length of days list: %d" % len(days)) today = int(days[-1][0].text) bot._debug("Word count for today: %d" % today) # this is commented out because man it doesn't work properly #util.answer(bot, "Word count for %s: %s (%d%% of 50K)\n%s has written %d words today." % (args[1], int(wordcount), percentage, args[1], today)) util.answer(bot, "Word count for %s: %s (%d%% of 50K)\n" % (args[1], int(wordcount), percentage)) else: util.give_help(bot, args[0], "<NaNoWriMo.org username>") util.register(nano_wordcount, "common", "wc") def write(bot, args): responses = [ "Only if you do!", "After you get 100 more words~~~", "Talk less, write more!" ] util.answer(bot, __import__('random').choice(responses)) util.register(write, "common", "write") def write_scan(bot): if re.search('edit', bot.remote['message'].lower()): bot._debug('Edit!') util.answer(bot, "\x01ACTION licks %s's face\x01" % bot.remote['nick'])
def mishimmie(bot, args): if len(args) >= 2: url = ""; if re.match("id:", args[1]): terms = re.sub('id:', '', args[1]) url = "http://shimmie.katawa-shoujo.com/post/view/%s" % urllib2.quote(terms) else: terms = ' '.join(args[1:]) url = "http://shimmie.katawa-shoujo.com/post/list/%s/1" % urllib2.quote(terms) res = miscan(bot, url) if res: util.answer(bot, "\x02Mishimmie:\x02 %s // %s" % (res['desc'], res['url'])) else: util.answer(bot, "\x02Mishimmie:\x02 No results.") else: util.give_help(bot, args[0], "<query> -- search the Mishimmie for <query>") util.register(mishimmie, "common", "mi", "mishimmie") def og_miscan(bot, url): res = miscan(bot, url) if res: util.answer(bot, "\x02Mishimmie:\x02 %s" % res['desc']) else: util.answer(bot, "\x02Mishimmie:\x02 No results.") util.register(og_miscan, "url", "shimmie.katawa-shoujo.com")
import util from pubsub import pub import re import urllib2 import json def yt_scan(bot, url): if bot.config.get("module: open_graph", "youtube") == "off": return None url = re.sub("http(s)?://", "", url) regex = "^(?:www\\.)?(?:(?:youtube\\.com/(?:watch)?(?:[?&][a-z]+=[a-z_]+)?(?:[?&]v=))|(?:youtu\\.be\\/))([a-zA-Z0-9-_]+)" apiurl = "http://gdata.youtube.com/feeds/api/videos/%s?v=2&alt=jsonc" % re.findall(regex, url)[0] bot._debug("API URL: %s" % apiurl) result = urllib2.urlopen(apiurl) jsondata = json.load(result) title = jsondata['data']['title'] author = jsondata['data']['uploader'] length = util.time_metric(secs=jsondata['data']['duration']) likes = util.metric(int(jsondata['data']['likeCount'])) dislikes = util.metric(int(jsondata['data']['ratingCount']) - int(jsondata['data']['likeCount'])) views = util.metric(int(jsondata['data']['viewCount'])) fmt = "\x02You\x034Tube\x0f: \x02%s\x0f by %s [%s] [\x033+%s\x0f \x035-%s\x0f] [%sv]" % (title, author, length, likes, dislikes, views) util.answer(bot, fmt.encode('utf-8')) util.register(yt_scan, 'url', 'youtube.com') util.register(yt_scan, 'url', 'youtu.be')
import numpy from util import register pm = dict() def accuracy(out, lab): """ Computes Accuracy. Expects labels and predictions to be integers """ return numpy.mean(out == lab) register(pm, 'Accuracy', accuracy) def error(out, lab): """ Computes Error Rate. Expects labels and predictions to be integers """ return numpy.mean(out != lab) register(pm, 'Error', error)
from argparse import ArgumentParser from util import register if __name__ == '__main__': parser = ArgumentParser(description="Add User") parser.add_argument('-u', '--username', type=str, required=True) parser.add_argument('-p', '--password', type=str, required=True) args = parser.parse_args() error = register(args.username, args.password) if error: print('Error: ' + error)
import util from pubsub import pub library = { 'admin': [], 'common': [] } def update(lib): global library library = lib pub.subscribe(update, 'library') def show_help(bot, args): can_do = bot.remote['host'] in [host.strip() for host in bot.config.get(bot.network, 'admin_hostnames').split(',')] #can_do = can_do or bot.remote['nick'] in [nick.strip() for nick in bot.config.get(bot.network, 'admin').split(',')] if can_do: if len(args) == 2 and args[1] == "admin": coms = library['admin'] else: coms = library['common'] else: coms = library['common'] util.answer(bot, "Available commands: %s" % ', '.join(sorted(coms))) util.register(show_help, "common", "help", "help")
if services: for service in services: dt_shd = datetime.datetime.strptime(service['scheduledDeparture'], '%Y-%m-%dT%H:%M:%S.000Z') dt_est = datetime.datetime.strptime(service['estimatedDeparture'], '%Y-%m-%dT%H:%M:%S.000Z') dt_dif = dt_est - datetime.datetime.utcnow() dt_dly = dt_est - dt_shd delay = dt_dly.seconds / 60 departure = dt_dif.seconds / 60 if dt_dif.seconds > 3600: continue if dt_dly.seconds > 3600: delay = 1440 - delay offset = '(%d %s early)' % (delay, plural('minute', delay)) else: if delay != 0: offset = '(%d %s late)' % (delay, plural('minute', delay)) else: offset = '(on schedule)' results.append(("%s: %s %s %s" % (service['route'], service['toLocation'], ('in %d %s' % (departure, plural('minute', departure))) if departure != 0 else 'is DUE', offset)).encode('utf-8')) util.answer(bot, '\n'.join(results) or "No buses imminent.") else: util.give_help(bot, args[0], "<bus stop number>") util.register(times, "common", "maxx")
'Names and airport codes', 'Latest recorded weather *', 'Series information', 'Latest trade', 'Definitions of *', 'Possible interpretation*', 'Lifespan', 'Cipher text', 'Statement', 'Events on *', 'Time span', 'Unicode block', 'Eclipse date', 'Total eclipse*', 'Solar wind', 'Weather forecast for *', 'Notable events in *', 'Events on *', 'Possible sequence identification', 'Length of data', 'Properties', 'Approximate results', 'Summary', 'Nearest named HTML colors' ] for title in acceptable: success = xml(result, title) if success: break failure = result.xpath("/queryresult[@success='false']") if success: success = unicode(success.replace("\:", "\u")) util.answer(bot, success.encode('utf-8').replace("Wolfram|Alpha", bot.name).replace("Stephen Wolfram", "Milos Ivanovic").strip()) elif failure: alternatives = result.xpath("/queryresult/relatedexamples/relatedexample[@input]") if alternatives: util.answer(bot, "Query not understood; suggestion%s: %s" % ('s' if len(alternatives) > 1 else '', ' | '.join([alt.values()[0].strip() for alt in alternatives]))) else: util.answer(bot, __import__('random').choice(['Are you a wizard?', 'You must be a wizard.', "Plong.", "I like bytes.", "Mmmm... chocolate...", "Oooh look, a boat.", 'Boob.'])) else: util.answer(bot, "No acceptable mathematical result.") else: util.give_help(bot, args[0], "<mathematical query>") util.register(wa, "common", "calc") def xml(result, title): if '*' in title: return '\n'.join(result.xpath("/queryresult[@success='true']/pod[contains(@title, '%s')]/subpod/plaintext/text()" % title.replace("*", ""))) else: return '\n'.join(result.xpath("/queryresult[@success='true']/pod[@title='%s']/subpod/plaintext/text()" % title))
quotes = Quote.select().where(Quote.channel == channel, Quote.nick != re.escape(bot.nick)) regexp = search[1:-1] else: type = "keywords" quotes = Quote.select().where(Quote.channel == channel, Quote.nick != re.escape(bot.nick), Quote.message ** ("%%%s%%" % search[1:-1])) if type == "regexp": util.answer(bot, output_quote(bot, quotes, regexp)) else: util.answer(bot, output_quote(bot, quotes)) else: util.answer(bot, "Nah. My own quotes are too contaminated.") else: util.give_help(bot, args[0], "<nick|*> [<keywords|/regexp/>]") util.register(get_quote, "common", "quotes") def output_quote(bot, quotes, regexp = False): import scanner ids = [] if regexp != False: regexp = re.compile(regexp, re.L | re.M | re.U) for q in quotes.naive(): if regexp != False and regexp.search(q.message) == None: continue ids.append(q.id) if len(ids) == 0: return "No matching quotes were found."
def __init__(self,mass=None,sun=None,orbit=None,name=None, logger=None): self.id = util.register(self) self.is_sun = False self.mass = mass if mass else 1E24*random.random() self.name = name if name else util.planet_name(self) self.primary=sun self.orbit = orbit #estimate radius, based off Earth self.radius = 6400000 *pow(self.mass/6E24,0.3) #calculate orbital period #T = 2pi*sqrt(a^3/u) mu = 6.674E-11 * self.primary.mass mmu = 6.674E-11 * self.mass a = self.orbit * 149597870700. self.orbital_period = 2 * math.pi * pow(pow(a,3)/mu,0.5) #self.launch_dv = pow( mmu/ (self.radius + 500000) , 0.5 ) if logger: self.logger = logging.getLogger(logger.name + '.' + self.name) else: self.logger = logging.getLogger(util.generic_logger.name + '.' + self.name) self.color = None #assign color to enable tinting self.img_name = 'generic_sun.png' self.img_radius = 0.25 if self.mass > 1E29: self.type = 'INVALID' #actually a sun. Throw an error, this shouldnt happen elif self.mass > 1E28: self.type = 'Brown dwarf' #counting this as a planet, since they have negligible radiation self.img_radius = 0.5 elif self.mass > 1E26: self.type = 'Gas giant' self.img_radius = 0.5 '''if self.orbit < self.sun.ice_line: self.type = 'Gas giant' saturation = 255.0 self.color = random.choice([np.array([255, 141, 110,255])/saturation, np.array([255, 198, 110,255])/saturation]) #self.radius = else: saturation = 255.0 self.type = 'Ice giant' self.color = random.choice([np.array([228, 250, 250,255])/saturation, np.array([11, 41, 255, 255])/saturation]) self.img_name = 'generic_sun.png''' elif self.mass > 1E23: self.type = 'Planet' #rocky world, but capable of retaining an atmosphere, even if barely elif self.mass > 1E21: self.type = 'Dwarf planet' #larger moons and asteroids, rounded self.img_radius = 0.2 else: self.type = 'Planetoid' #small moons, asteroids, rocks, etc self.img_name = 'generic_asteroid.png' self.img_radius = 0.10 self.explored = 0.0 self.resources = planetresources.PlanetResources(self) self.occupied = 0 self.initialize_sites() self.orbiting_bodies = [] self.orbit_pos = random.random()*2*3.14159 self.image = planetimages.random_image(self) #self.generate_primary_image() self.generate_orbital_image() #self.view = systempanel.SystemView(primary=self) self.view = systempanel.SystemScreen(name=util.short_id(self.id)+"-system",primary=self)
def __init__(self, solar_masses, name=None, logger=None): self.is_sun = True self.id = util.register(self) self.primary = None self.solar_masses = solar_masses self.mass = self.solar_masses*2E30 self.name = name if name else util.star_name(self) if logger: self.logger = logging.getLogger(logger.name + '.' + self.name) else: self.logger = logging.getLogger(util.generic_logger.name + '.' + self.name) #current assumption: main sequence star. May want to simulate lifetimes and do giants in the future # reference: https://en.wikipedia.org/wiki/Stellar_classification saturation = 200.0 if self.solar_masses < 0.5: self.type = 'M' self.radius = 0.7 self.luminosity = 0.08 self.color_name = 'Red' self.color = np.array([255,204,111,255])/saturation elif self.solar_masses < 0.8: frac = (self.solar_masses - 0.5)/0.3 self.type = 'K' self.radius = 0.7 + 0.26*frac self.luminosity = 0.08 + 0.52*frac self.color_name = 'Orange' self.color = np.array([255,210,161,255])/saturation elif self.solar_masses < 1.04: frac = (self.solar_masses - 0.8)/0.24 self.type = 'G' self.radius = 0.96 + (1.15-0.96)*frac self.luminosity = 0.6 + (1.5 - 0.6)*frac self.color_name = 'Yellow' self.color = np.array([255, 244, 234,255])/saturation elif self.solar_masses < 1.4: frac = (self.solar_masses - 1.04)/0.36 self.type = 'F' self.radius = 1.15 + (1.4-1.15)*frac self.luminosity = 1.5 + (5 - 1.5)*frac self.color_name = 'Yellow-White' self.color = np.array([248, 247, 255,255])/saturation elif self.solar_masses < 2.1: frac = (self.solar_masses - 1.4)/0.7 self.type = 'A' self.radius = 1.4 + (1.8-1.4)*frac self.luminosity = 5 + (25 - 5)*frac self.color_name = 'White' self.color = np.array([202, 215, 255,255])/saturation elif self.solar_masses < 16: frac = (self.solar_masses - 2.1)/(16-2.1) self.type = 'B' self.radius = 1.8 + (6.6-1.8)*frac self.luminosity = 25 + (30000 - 25)*frac self.color_name = 'Blue-White' self.color = np.array([170, 191, 255,255])/saturation else: # self.solar_masses > 16: frac = (self.solar_masses - 2.1)/(16-2.1) self.type = 'O' self.radius = 8 #arbitrary self.luminosity = 50000 #arbitrary self.color_name = 'Blue' self.color = np.array([155, 176, 255,255])/saturation self.habitable_start = 0.80 * pow( self.luminosity ,0.5) self.habitable_end = 1.4 * pow( self.luminosity ,0.5) self.snow_line = 3 * pow( self.luminosity ,0.5) self.ice_line = 10 * pow( self.luminosity ,0.5) self.explored = 0.0 self.orbiting_bodies = [] self.view = systempanel.SystemScreen(name=util.short_id(self.id)+"-system",primary=self)
else: util.give_help(bot, args[0], "[-6 (IPv6), -r (rDNS)] <server>") return None if addresses != -1: if addresses: plural = "others" if len(addresses) > 2 else "other" others = " (%s %s)" % (len(addresses), plural) if len(addresses) > 1 else '' util.answer(bot, "Address: %s%s" % (addresses[0] if not str(addresses[0]).endswith(".") else str(addresses[0])[:-1], others)) else: util.answer(bot, "%s: NXDOMAIN" % host) else: answer("Invalid host for this type of lookup.") else: util.give_help(bot, args[0], "[-6 (IPv6), -r (rDNS)] <server>") util.register(lookup, "common", "lookup", "dns_lookup") def wiki(bot, args): if len(args) > 1: result = lookitup('%s.wp.dg.cx' % '_'.join(args[1:]), 'TXT') if result: bot._sendq(("NOTICE", bot.remote['nick']), ''.join(str(result[0]).split('"'))) return None else: util.answer(bot, "No such article found.") else: util.give_help(bot, args[0], "<article>") util.register(wiki, "common", "wiki", "wiki_lookup")
import util import subprocess import re def parse(bot, args): command = ' '.join([arg for arg in args[1:]]) arguments = ['python2', '-c', command] result = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] if len(result.split('\n')) > 4 or len(result) > 445: service = ['wgetpaste'] for n in range(2): p = subprocess.Popen(service, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) paste = p.communicate(input=">>> %s\n\n%s" % (command, result))[0] try: return re.findall('(http://.*)', paste, re.S)[0] except IndexError: service = ['curl', '-F', 'sprunge=<-', 'http://sprunge.us'] return "%s%s: error pasting output." % (bot.prefix, args[0]) else: return result def _eval(bot, args): util.answer(bot, parse(bot, args)) util.register(_eval, "admin", "eval", "eval")
pub.subscribe(lib_register, 'register') pub.subscribe(lib_deregister, 'deregister') def reset(bot, args): if len(args) > 1: if args[1] in library['reset']: pub.sendMessage("func.reset.%s" % library['reset'][args[1]], bot=bot, args=args[2:]) return None if len(library['reset']) > 0: util.give_help(bot, args[0], '|'.join(library['reset'])) else: util.answer(bot, "No resets registered.") util.register(reset, "admin", "reset") def autojoin(): channels = Bot.config.get(Bot.network, 'channels').split(",") for channel in channels: join(Bot, [None, channel.strip()]) Bot.init['joined'] = True def ctcp(type, args): if type == "VERSION": write(("NOTICE", Bot.remote['nick']), "\x01VERSION %s:%s:%s\x01" % (Bot.name, str(Bot.version), Bot.env)) elif type == "PING": write(("NOTICE", Bot.remote['nick']), "\x01PING %s\x01" % args[0]) def write(args, message = None): Bot._sendq(args, message)
import util import urllib, urllib2 import json def info(bot, args): if len(args) > 1: title = ' '.join(args[1:]) data = json.load(urllib2.urlopen('http://www.imdbapi.com/?%s' % urllib.urlencode({'t': title}), timeout = 45)) if 'Plot' in data: response = "%s (%s): %s\n%s, %s/10, %s. %s" % (data['Title'], data['Year'], data['Plot'], data['Rated'] if data['Rated'] != 'N/A' else 'Unrated', data['imdbRating'] if data['imdbRating'] != 'N/A' else '?', data['Genre'], 'http://www.imdb.com/title/%s/' % data['imdbID']) util.answer(bot, response.encode('utf-8')) else: util.answer(bot, '%s%s: No such movie found.' % (bot.prefix, args[0])) else: util.give_help(bot, args[0], "<movie title>") util.register(info, "common", "imdb")
service = ['curl', '-F', 'sprunge=<-', 'http://sprunge.us'] for n in range(2): p = subprocess.Popen(service, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) paste = p.communicate(input="/* >>> %s\n<<< */\n\n%s" % (command, result))[0] try: util.answer(bot, "%s?js" % re.findall('(http://.*)', paste, re.S)[0].strip()) return None except IndexError: pass util.answer(bot, "!%s: error pasting output." % args[0]) else: bot._debug('Returning locally...') message = "\n".join([("\x01ACTION %s\x01" % re.sub("^\\/me ","", r) if re.match("^\\/me ", r) else r) for r in result.split("\n")]) util.answer(bot, message) else: util.give_help(bot, args[0], "[FILTERS:] <expr>") util.answer(bot, "\tAvailable filters: pretty, coffee, http, gist.") util.answer(bot, "\tE.g. %s%s pretty,coffee: <coffee_expr>" % (bot.prefix, args[0])) util.answer(bot, "\t %s%s http: <url>" % (bot.prefix, args[0])) util.answer(bot, "\t %s%s gist: <gist_id>" % (bot.prefix, args[0])) util.register(js_run, "common", "js") def js_reset(bot, args): bot._debug('Destroying JS context...') del bot.inv['js'] util.answer(bot, "Success: Javascript context reset.") util.register(js_reset, "reset", "js")
{ 'userid': bot.config.get('module: usage', 'td_login'), 'password': bot.config.get('module: usage', 'td_pass'), 'hdnAction': 'login', 'hdnAuthenticationType': 'M' } )).read() remaining = lxml.html.fromstring(account).xpath("//td[@class='tableBillamount']/text()") if not remaining: result += "2degrees: Error, cannot get remaining data.\n" else: result += "3G: %s remaining\n" % ', '.join(remaining).encode('utf-8') if not re.match("(off|false|disabled|n)", bot.config.get('module: usage', 'orcon')): orcon = lxml.html.fromstring(opener.open('http://www.orcon.net.nz/modules/usagemeter/view/CosmosController.php').read()).xpath('//dd[last()]/text()') if not orcon: result += "Orcon: Error, cannot fetch details." else: result += "ADSL: %s used" % orcon[0].encode('utf-8') if len(result) > 0: util.answer(bot, result) else: util.answer(bot, "%s%s: Not configured." % (bot.prefix, args[0])) else: util.give_help(bot, args[0], "") util.register(usage, "common", "usage")
import util def twss(bot, args): if len(args) > 1: quote = ' '.join(args[1:]) if quote.startswith('"') and quote.endswith('"'): util.answer(bot, "%s <- that's what she said." % quote) else: util.give_help(bot, args[0], "<quote>") else: util.answer(bot, "That's what she said.") util.register(twss, "common", "twss") def spin(bot, args): nicks = bot.inv['rooms'].get(bot.remote['receiver']) if nicks: if len(nicks) > 2: message = ' '.join(args[1:]) if not message: message = "nothing" if message.lower() != bot.nick.lower(): _nicks = list(nicks) _nicks.remove(bot.remote['nick']) _nicks.remove(bot.nick) winner = __import__('random').choice(_nicks) util.answer(bot, "The winner of %s is %s. Congratulations %s!" % (message, winner, winner)) else: util.answer(bot, "You want to spin me? Ok. Wheeeeeeee~") else: util.answer(bot, "Not enough winrars!")
url = ""; if re.match("id:", args[1]): terms = re.sub('id:', '', args[1]) url = "http://shimmie.katawa-shoujo.com/post/view/%s" % urllib2.quote(terms) else: terms = ' '.join(args[1:]) url = "http://shimmie.katawa-shoujo.com/post/list/%s/1" % urllib2.quote(terms) rawres = urllib2.urlopen(url, timeout = 5) result = rawres.read().encode('utf8') doc = html.document_fromstring(result) try: posturl = "" postdesc = "" bot._debug('URL: %s' % rawres.geturl()) if re.search('/post/view/', rawres.geturl()): bot._debug('On a post page.') posturl = rawres.geturl() postdesc = doc.get_element_by_id('imgdata').xpath('form')[0].xpath('table')[0].xpath('tr')[0].xpath('td')[1].xpath('input')[0].get('value') else: bot._debug('On a search result page.') posturl = "http://shimmie.katawa-shoujo.com%s" % doc.find_class('thumb')[0].xpath('a')[0].get('href') postdesc = doc.find_class('thumb')[0].xpath('a')[0].xpath('img')[0].get('alt').partition(' // ')[0] posturl = re.sub('\?.*', '', posturl) util.answer(bot, "\x02Mishimmie:\x02 %s // %s" % (postdesc, posturl)) except IndexError: util.answer(bot, "\x02Mishimmie:\x02 No results.") else: util.give_help(bot, args[0], "<query> -- search the Mishimmie for <query>") util.register(mishimmie, "common", "mi", "mishimmie")