def test_create_users_table(): """Assert the correct contents of the users table table.""" # Create database. db_filename = 'test_create_users_table.sqlite' test_database = sqlite3.connect(db_filename) cursor = test_database.cursor() users_filename = 'test_user_data.txt' user_data_packages = read_file.get_data(users_filename, package_size=3) user_data_rows = [create_database.unpack_user_data(user_data_package) for user_data_package in user_data_packages] create_database.create_users_table(cursor, user_data_rows) # Check users table. statement = """SELECT * FROM users WHERE username =?""" assert database.query(statement, 'coit125', cursor) == (u'coit125', u'american', u'01/25/1984') assert database.query(statement, 'bcummberbatch', cursor) == (u'bcummberbatch', u'british', u'04/21/1978') assert database.query(statement, 'orangelover1107', cursor) == (u'orangelover1107', u'south korean', u'11/07/1983') test_database.close()
def main(cursor): team = int(common.get_val("team", 0)) name = common.get_val("name", 0) city_location = common.get_val("city_location", 0) text_location = common.get_val("text_location", "") army_type = int(common.get_val("type", 0)) actual_x = 0 actual_y = 0 if text_location != "": actual_x = re.search(r"(-?[0-9]+)[,:] ?(-?[0-9]+)", text_location).groups()[0] actual_y = re.search(r"(-?[0-9]+)[,:] ?(-?[0-9]+)", text_location).groups()[1] else: the_city = city_q.get_one_city(city_location) actual_x = the_city['x'] actual_y = the_city['y'] database.query(cursor, army_f.new_army(name, team, actual_x, actual_y, army_type=army_type)) # Redirect page_data['Redirect'] = 'list_armies&team={0:d}'.format(team) return ""
def main(cursor): city_id = int(common.get_val('city', -1)) the_city = city_q.get_one_city(cursor, city_id) database.query(cursor, city_f.delete_city(city_id)) # Redirect page_data['Redirect'] = 'list_cities&team={0:d}'.format(the_city.team)
def main(cursor): unit_id = int(common.get_val('unit', -1)) the_unit = unit_q.get_one_unit(cursor, unit_id) database.query(cursor, unit_f.delete_unit(unit_id)) # Redirect page_data['Redirect'] = 'list_units&team={0:d}'.format(the_unit.team)
def LoadFoldersAndFeeds(self): try: database.lock() folders = database.query("select id, parent, name from folders order by ordering") self.folder_mapping = mapping = { } noparent = [ ] for folder in folders: if folder[2] == None: mapping[folder[0]] = self.feed_root else: noparent.append(folder) while len(noparent) > 0: stillnoparent = [ ] for folder in noparent: if mapping.has_key(folder[1]): self.AddFolderToTree(*folder) else: stillnoparent.append(folder) noparent = stillnoparent feeds = database.query("select id, folder, name, url from feeds order by ordering") for feedinfo in feeds: self.AddFeedToTree(*feedinfo) finally: database.unlock()
def main(cursor): army_id = int(common.get_val("army", -1)) the_army = army_q.get_one_army(cursor, army_id) database.query(cursor, army_f.make_delete_query(army_id)) # Redirect page_data["Redirect"] = "list_armies&team={0:d}".format(the_army.team)
def test_create_date_formats_table(): """Assert the correct contents of the users table table.""" # Create database. db_filename = 'test_create_date_formats_table.sqlite' test_database = sqlite3.connect(db_filename) cursor = test_database.cursor() date_formats_filename = 'test_date_formats.txt' date_format_data_packages = read_file.get_data(date_formats_filename, package_size=1) date_format_data_rows = [create_database.unpack_date_format_data(date_format_data_package) for date_format_data_package in date_format_data_packages] create_database.create_date_formats_table(cursor, date_format_data_rows) # Check date_formats table. statement = """SELECT * FROM date_formats WHERE nationality =?""" assert database.query(statement, 'american', cursor) == (u"american", u"{month}/{day}/{year}") assert database.query(statement, 'british', cursor) == (u"british", u"{day}/{month}/{year}") assert database.query(statement, 'south korean', cursor) == (u"south korean", u"{year}/{month}/{day}") test_database.close()
def main(cursor): campaign = int(common.get_val("campaign", 0)) location = common.get_val("location", "") team = int(common.get_val("team", 0)) # Get location result = battle.battle_coords.search(location) if result != None: x = int(result.groups()[0]) y = int(result.groups()[1]) else: # Get it from the last battle last_battle = battle_q.get_last_battle_from_campaign(cursor, campaign) if last_battle == None: return "" x = last_battle.x y = last_battle.y # Get armies armies = campaign_q.get_armies_from_campaign_from_team(cursor, campaign, team) # Move them database.query(cursor, army_f.move_armies(armies, (x, y))) page_data['Redirect'] = "list_battles&campaign={0}".format(campaign) return ""
def add_file_cert_mapping(filename, certname): query( ''' insert into {} values ("{}", "{}") '''.format(DB_TABLENAME_FILES, filename, certname) )
def main(cursor): team_id = int(common.get_val("team", 0)) default_border = int(common.get_val("default_border_state", 0)) team_dict = team_q.get_real_active_teams(cursor, skip_irs=False) the_team = team_dict[team_id] queries = [ "DELETE FROM team_borders WHERE host = %d" % team_id, "UPDATE teams SET default_borders = %d WHERE id = %d;" % (default_border, team_id), ] insertions = [] # Get a list of states for t, other_team in team_dict.items(): if t == the_team.id: continue state = int(common.get_val("border_state_%d" % t, -1)) if state >= 0: insertions.append("(%d, %d, %d)" % (team_id, t, state)) # Add insertions to list if len(insertions) > 0: queries.append("INSERT INTO team_borders (host, visitor, state) values %s;" % ",".join(insertions)) # print("") # print(common.print_post_data()) # print("<br /><br />") # print("<br />".join(queries)) # exit() database.query(cursor, queries) page_data['Redirect'] = 'view_borders&team={0:d}'.format(team_id) return ""
def main(cursor): op_id = int(common.get_val('operative', -1)) the_op = operative_q.get_one_operative(cursor, op_id) database.query(cursor, operative_f.kill_operative(op_id)) # Redirect page_data['Redirect'] = 'list_operatives&team={0:d}'.format(the_op.team)
def record_resources(the_world, the_team): """Records the end of turn resources for the team""" the_team.get_resources(the_world.cursor, force_requery=True) strings = [] for res_id, r in enumerate(resource_list.data_list): if res_id not in the_team.resources.value: continue if the_team.resources.value[res_id] == 0: continue if r.reset: continue res_value = the_team.resources.value[res_id] # Typecast if we can if res_value == int(res_value): res_value = int(res_value) strings.append("%s:%s" % (r.name, res_value)) # Log previous resources database.query(the_world.cursor, log_f.new_log("team_f.record_resources", ",".join(strings), "", team = the_team.id) ) query = """UPDATE teams SET previous_resources = '%s' WHERE id = %d;""" % (database.escape(",".join(strings)), the_team.id) try: the_world.cursor.execute(query) except Exception as e: raise Exception("Database error: %s\nQuery: %s" % (str(e.args[0]).replace("\n",""), query))
def next_func(args,u413): context=u413.user.context.split(' ') if context[0]=='BOARD': if context[1]=='ALL': context[1]=0 pages=int(db.query("SELECT COUNT(*) FROM posts WHERE topic=TRUE AND parent IN (SELECT id FROM boards WHERE onall=TRUE);")[0]["COUNT(*)"]) if pages==0: pages=1 else: pages=math.ceil(pages/10.0) page=1 if len(context)>2: page=int(context[2]) if page<pages: page+=1 command.respond(context[0]+' '+str(context[1])+' '+str(page),u413) return if context[0] in ['BOARD','TOPIC']: pages=int(db.query("SELECT COUNT(*) FROM posts WHERE parent=%i;"%int(context[1]))[0]["COUNT(*)"]) if pages==0: pages=1 else: pages=math.ceil(pages/10.0) page=1 if len(context)>2: page=int(context[2]) if page<pages: page+=1 command.respond(context[0]+' '+str(context[1])+' '+str(page),u413) else: u413.type('"NEXT" is not a valid command or is not available in the current context.')
def add_file_key_mapping(filename, key_hash): query( ''' insert into {} values ("{}", "{}") '''.format(DB_TABLENAME_KEYS, filename, key_hash) )
def produce_resources(the_world, the_team): """Produces resources for the coming turn""" # Get production upkeep_cost = get_upkeep(the_team, the_world) database.query(the_world.cursor, log_f.new_log("team_f.get_upkeep", "Upkeep: %s" % upkeep_cost, "", team = the_team.id) ) produced_resources, new_resources = rules.team_rules.produce_resources( the_world.cursor, the_team, the_world=the_world ) # Log production database.query(the_world.cursor, log_f.new_log("team_f.produce_resources", "Produced: %s\nNew: %s" % (str(produced_resources), str(new_resources)), "", team = the_team.id) ) # Apply upkeep new_resources -= "Materials:%s" % upkeep_cost queries = new_resources.make_set_queries(the_team.id) from functions import queries_f for q in queries: try: queries_f.log_query(the_world.cursor, q, subject="Pre orders resources") the_world.cursor.execute(q) except Exception as e: print("Query: %s\n" % q) raise e return queries
def add_filesize(filename, filesize): query( ''' insert into {} values ("{}", "{}") '''.format(DB_TABLENAME_SIZES, filename, filesize) )
def main(cursor): squad_id = int(common.get_val('squad', -1)) the_squad = squad_q.get_one_squad(cursor, squad_id) database.query(cursor, squad_f.make_delete_query(squad_id)) # Redirect page_data['Redirect'] = 'edit_army&army={0:d}'.format(the_squad.army)
def topic_func(args,u413): params=args.split(' ',2) if len(params)==0 or not util.isint(params[0]): u413.type("Invalid topic ID.") return topic=int(params[0]) if len(params)==1: page=1 output_page(topic,1,u413) elif len(params)==2: if params[1].upper()=="REPLY": u413.j["Command"]="REPLY" u413.cmddata["topic"]=topic u413.continue_cmd() else: page=1 if util.isint(params[1]): page=int(params[1]) elif params[1].upper()=='LAST': page=db.count_posts(topic) if page==0: page=1 else: page=math.ceil(page/10.0) output_page(topic,page,u413) elif params[1].upper()=="REPLY": db.query("INSERT INTO posts (topic,title,parent,owner,editor,post,locked,edited,posted) VALUES(FALSE,'',%i,%i,0,'%s',FALSE,NULL,NOW());"%(topic,u413.user.userid,db.escape(util.htmlify(params[3])))) u413.type("Reply made successfully.")
def main(cursor): battle_id = int(common.get_val('battle', -1)) the_battle = battle_q.get_one_battle(cursor, battle_id) database.query(cursor, battle_f.make_delete_query(battle_id)) # Redirect page_data['Redirect'] = 'list_battles&campaign={0:d}'.format(the_battle.campaign)
def handle_change(self, thread_name, check_id, check_name, lock_uid, status, check_result): if status == 'offline': updown = 'down' elif status == 'online': updown = 'up' safe_print("[%s] ... confirmed, target is %s state now", (thread_name, status)) update_result = database.query("UPDATE checks SET status = %s, confirmations = 0, `lock` = '', last_checked = NOW() WHERE id = %s AND `lock` = %s", (status, check_id, lock_uid)) if update_result.rowcount == 1: # we still had the lock at the point where status was toggled # then, send the alert alert_result = database.query("SELECT contacts.id, contacts.type, contacts.data FROM contacts, alerts WHERE contacts.id = alerts.contact_id AND alerts.check_id = %s AND alerts.type IN ('both', %s)", (check_id, updown)) for alert_row in alert_result.fetchall(): safe_print("[%s] ... alerting contact %d", (thread_name, alert_row['id'])) alert_func = getattr(alerts, alert_row['type'], None) if not alert_func: util.die("Invalid alert handler [%s]!" % (alert_row['type'])) # build context context = {} context['check_id'] = check_id context['check_name'] = check_name context['contact_id'] = alert_row['id'] context['title'] = "Check %s: %s" % (status, check_name) context['status'] = status context['updown'] = updown context['message'] = check_result['message'] alert_func(util.decode(alert_row['data']), context) # also add an event database.query("INSERT INTO check_events (check_id, type) VALUES (%s, %s)", (check_id, updown))
def update_file_cert_mapping(filename, new_certname): query( ''' update {} set attr = "{}" where filename = "{}" '''.format(DB_TABLENAME_FILES, new_certname, filename) )
def getAll(lector = None): if lector: c = query('SELECT * FROM lectures WHERE lector = ?', (lector,) ) else: c = query('SELECT * FROM lectures WHERE 1' ) for row in c.fetchall(): yield Model(row)
def mute_func(args,u413): muted=bool(ord(db.query("SELECT muted FROM users WHERE id=%s;"%u413.user.userid)[0]["muted"])) db.query("UPDATE users SET muted=%s;"%str(not muted).upper()) u413.mute=not muted if muted: u413.type("Terminal unmuted.") else: u413.type("Terminal muted.")
def list_(refresh = False, bootstrap = True, sort = False, \ fixed_list = None): """ Collect a list of all loaded plugins. During the bootstrap, return only vital plugins. See bootstrap.inc @param refresh Whether to force the plugin list to be regenerated (such as after the administrator has changed the system settings). @param bootstrap Whether to return the reduced set of plugins loaded in "bootstrap mode" for cached pages. See bootstrap.inc. @param sort By default, plugins are ordered by weight and filename, settings this option to True, plugin list will be ordered by plugin name. @param fixed_list (Optional) Override the plugin list with the given plugins. Stays until the next call with refresh = True. @return An associative array whose keys and values are the names of all loaded plugins. """ php.static(list_, 'list_', {}) php.static(list_, 'sorted_list') if (refresh or fixed_list): list_.sorted_list = None list_.list_ = {} if (fixed_list): for name,plugin in fixed_list.items(): lib_bootstrap.drupal_get_filename('plugin', name, plugin['filename']) list_.list_[name] = name else: if (bootstrap): result = lib_database.query(\ "SELECT name, filename FROM {system} " + \ "WHERE type = 'plugin' AND status = 1 AND " + \ "bootstrap = 1 ORDER BY weight ASC, filename ASC") else: result = lib_database.query(\ "SELECT name, filename FROM {system} " + \ "WHERE type = 'plugin' AND status = 1 " + \ "ORDER BY weight ASC, filename ASC") while True: plugin_ = lib_database.fetch_object(result) if (plugin_ == None or plugin_ == False): break if (DrupyImport.exists(plugin_.filename)): lib_bootstrap.drupal_get_filename('plugin', \ plugin_.name, plugin_.filename) list_.list_[plugin_.name] = plugin_.name if (sort): if (list_.sorted_list == None): list_.sorted_list = plugin_list.list_ p.ksort(list_.sorted_list) return list_.sorted_list return list_.list_
def refund_losses(cursor, battle_id): losses = get_all_battle_losses_by_squad(cursor, battle_id) queries = [] for s, a in losses.items(): queries.append("UPDATE squads SET amount = amount + %d WHERE id = %d" % (a, s)) queries.append("DELETE FROM squad_battle_history WHERE squad = %d AND battle = %d" % (s, battle_id)) database.query(cursor, *queries)
def main(cursor): campaign = int(common.get_val("campaign")) team = int(common.get_val("team")) side = int(common.get_val("side")) database.query(cursor, campaign_f.remove_team_from_campaign(campaign, side, team)) return ""
def saveSettings(timezone, theme): database.query(sql=""" UPDATE settings SET timezone=%s , themeName=%s """, parameters=( timezone, theme, ))
def main(cursor): monster_id = int(common.get_val('monster', 0)) army_id = int(common.get_val('army', 0)) amount = int(common.get_val('amount', 0)) database.query(cursor, monster_f.alter_army_monster_size(army_id, monster_id, amount)) page_data['Redirect'] = "list_squads&army={0}".format(army_id) return ""
def main(cursor): name = common.get_val("name", "") city = int(common.get_val("city", 0)) point_cost = int(common.get_val("point_cost", 0)) material_cost = int(common.get_val("material_cost", 0)) description = common.get_val("description", "") database.query(cursor, wonder_f.new_wonder(name, city, point_cost, material_cost, description))
def main(cursor): unit = int(common.get_val("unit", 0)) item = int(common.get_val("item", 0)) database.query(cursor, unit_f.add_equipment(unit=unit, item=item)) # Redirect page_data['Redirect'] = 'edit_unit&unit={0:d}'.format(unit) return ""
qc = QueryConstructor() qc.setGroupOrderSelectBy("device","androidversion") qc.addSelectMedian("ping","avg") qc.addSelectPercentile("ping","avg",25) qc.addSelectPercentile("ping","avg",75) qc.addSelectField("count(*)") qc.addWhereEqualsString("device","networkcountry",networkcountry) qc.addWhereNotEqualsString("network","networktype","") qc.addWhereEqualsString("network","networktype","UMTS") qc.addWhereEqualsString("device","networkname","AT&T") qc.applyMobileClauses() qc.applyLatencyClauses("www.google.com") #qc.addWhereEqualsString("device","networkname",'AT&T') result = database.query(qc.toString()) pprint.pprint(result) plot = SimpleBarPlot() plot.addMapping(MappingWithBounds(result,0,1,2,3,"Type")) plot.setYLabel("ms") plot.setXLabel("Android Version") plot.setTitle("3G RTT latency for different Android Versions in US for AT&T with UMTS") #plot.setLegend("ms") plot.construct() plot.save(filename) plot.show()