def main(args): params = {} util.update(params, **args.__dict__) print(params) if params['gui']: params['dolphin'] = True if params['user'] is None: params['user'] = tempfile.mkdtemp() + '/' print("Creating cpu.") cpu = CPU(**params) params['cpus'] = cpu.pids if params['dolphin']: dolphinRunner = DolphinRunner(**params) # delay for a bit to let the cpu start up time.sleep(5) print("Running dolphin.") dolphin = dolphinRunner() else: dolphin = None return cpu, dolphin
def __init__(self, load=None, **kwargs): if load is None: args = {} else: args = util.load_params(load, 'train') util.update(args, mode=RL.Mode.TRAIN, **kwargs) print(args) Default.__init__(self, **args) if self.init: self.model.init() self.model.save() else: self.model.restore() context = zmq.Context.instance() self.experience_socket = context.socket(zmq.PULL) experience_addr = "tcp://%s:%d" % (self.dump, util.port(self.model.name + "/experience")) self.experience_socket.bind(experience_addr) self.params_socket = context.socket(zmq.PUB) params_addr = "tcp://%s:%d" % (self.dump, util.port(self.model.name + "/params")) print("Binding params socket to", params_addr) self.params_socket.bind(params_addr) self.sweep_size = self.batches * self.batch_size print("Sweep size", self.sweep_size) self.buffer = util.CircularQueue(self.sweep_size) self.last_save = time.time()
def run(self): count = 0 while self.running: # Update sensor values util.update() self.encoders.update() front, rear = util.sensors() r = self.sensor.right #if count < 5000: # if front not in [-1, 255]: # print str(count) + "," + str(abs(int(self.encoders.actual[0])/2)) + "," + str(front) # count += 1 self.state.update(self.encoders.actual) # Get recieved commands sensing = self.comm.recieve.sensing power = self.comm.recieve.power rotate = self.comm.recieve.rotate self.running = self.comm.recieve.running # Update robot based on commands if sensing and self.sensor.paused: self.sensor.resume() elif (not sensing) and (not self.sensor.paused): self.sensor.pause() util.move(power, rotate) # Send data self.comm.send(self.state.x, self.state.y, self.state.heading, self.encoders.actual[0], front, rear) # Sleep so sensors have time to update time.sleep(.02) self.sensor.stop() self.comm.stop()
def __init__(self, id, args=None): MetaDataRecord.__init__(self, path=self.shape_template) # make a copy so we don't stomp default_shape_args opts = copy.deepcopy(self.default_shape_args) if args is not None: util.update(opts, args) # define all attributes to match xpath mapping above. # the xpath mappings determine what attributes are written to DOM. self.ID = id self.Name = opts['name'] self.Type = "Shape" self.PinX = opts['x'] self.PinY = opts['y'] self.Width = opts['width'] self.Height = opts['height'] self.ObjType = 1 self.LineWeight = util.pt2in(opts['line']['weight']) #from px to inch self.LineColor = opts['line']['color'] self.CharSize = util.pt2in(opts['label']['size']) self.CharColor = opts['label']['color'] self.Text = opts['label']['text'] self.addCustomAttrs(opts) # inject components self.components = ComponentRecord(path=self.component_xml) try: # assigns components record as side effect self.injectComponents() except KeyError, msg: raise Exception, "ERROR: cannot inject component: %s" % msg
def main(): memory = read() intcode = IntCodeComputer(memory) white_tiles = set() painted = set() curr = [0, 0] turn_to_paint = True face = 0 directions = ['U', 'R', 'D', 'L'] while not intcode.completed: intcode.run() while not intcode.output.empty(): value = intcode.output.get() if turn_to_paint: if value == 1: white_tiles.add(tuple(curr)) elif value == 0 and tuple(curr) in white_tiles: white_tiles.remove(tuple(curr)) painted.add(tuple(curr)) else: if value == 1: face = (face + 5) % 4 elif value == 0: face = (face + 3) % 4 update(curr, directions[face]) turn_to_paint = not turn_to_paint intcode.read(int(tuple(curr) in white_tiles)) print(len(painted)) # output
def evaluate(inp, client, l, DBlocation): inp = inp.split(' ') status = client.status() if len(inp) > 1 and not str(inp[1]): inp.pop() if inp[0] == 'p' or 'play' == (inp[0]): try: if not status['state'] == 'stop': if len(inp) == 1: util.pause(client) else: util.play(client, int(inp[1])) else: if len(inp) == 1: util.play(client, 0) else: util.play(client, int(inp[1])) except: print('mpd error: bad song index') elif inp[0] == 'pause': util.pause(client) elif inp[0] == 'next' or inp[0] == 'n': util.next(client) elif inp[0] == 'previous' or inp[0] == 'ps': util.previous(client) elif inp[0] == 'stop': util.stop(client) elif inp[0] == 'pl' or inp[0] == 'playlist': util.print_playlist(client) elif inp[0] == 'update' or inp[0] == 'u': util.update(client) elif inp[0] == 'clear': util.clear(client) elif inp[0] == 'random': util.mpdrandom(client, inp[1]) elif inp[0] == 'shuffle': util.shuffle(client) elif inp[0] == 'consume': util.consume(client, inp[1]) elif inp[0] == 'swap': util.swap(client, int(inp[1]) - 1, int(inp[2]) - 1) elif inp[0] == 'single': util.single(client, inp[1]) elif inp[0] == 'search' or inp[0] == 's': if '-f' in inp or '--filter' in inp: l = util.mpdsearch(inp[1], inp, DBlocation, True) else: l = util.mpdsearch(inp[1], inp, DBlocation, False) elif inp[0] == 'a' or inp[0] == 'add': if l: for line in l: client.add(line) else: print('You have to search first!') elif inp[0] == 'q' or inp[0] == 'quit': quit() return l
def gengxin(): info = ['username', 'passwd', 'sex', 'age', 'phone', 'email', 'role', 'id'] a = [] for n in info: a.append(request.form.get(n)) update(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]) usera = cha() return render_template('log.html', usera=usera)
def label(self, label_thunk, reserves=0): assert isinstance(label_thunk, intbv), repr(label_thunk) assert label_thunk == 0, repr(label_thunk) name = self._name_of_address_thunk(label_thunk) print 'label %s => %#06x' % (name, self.here) update(label_thunk, self.here) if reserves: assert reserves > 0, repr(reserves) self.here += reserves
def grade(assignment_def_id, account_id): # CALLS ML models print("GRADING stub: 95 assigned as grade") util.update( 'Assignment', {'graded':True,'grade':50}, {'assignment_def_id':assignment_def_id,'account_id':account_id}, classname=Assignment.__name__ )
def upd(): if request.method == 'GET': uid = request.args.get('id') userinfo = cha_uid(uid) print "upd" ,userinfo return render_template('upd.html',n = userinfo) else : users = request.form.to_dict() #users = { k:v[0] for k,v in dict(request.form).items() } 等价与上面的 users = { k:v.replace("管理员","0").replace('普通用户','1') for k,v in users.items() } if len(users.get('passwd')) < 90 : users = passwd_hash.set_password(users) #修改的密码重新加密 print "upd :" ,users update(users) return redirect(url_for('userlist'))
def upd(): if request.method == 'GET': uid = request.args.get('id') userinfo = cha_uid(uid) return render_template('upd.html', n=userinfo) else: keys = [ 'uid', 'username', 'passwd', 'passwd1', 'age', 'sex', 'phone', 'email', 'role' ] users = {} for key in keys: users[key] = request.form.get(key) update(users) userinfos = chaxun() return render_template('index.html', users=userinfos)
def __init__(self, args): cmd.Cmd.__init__(self) self.intro = 'Welcome to BlooClient-cli.\n' \ 'Type help or ? for a list of commands.\n' self.debug = args.debug self.client = core.Client_Connection(args.ip, args.port, args.timeout) if not self.debug: if util.update(self.__module__): print 'Client has been updated. Please restart!\n' if self.client.update(): print 'The core module has been updated! Please restart!\n' if util.update(util.__name__): print 'The util module has been updated! Please restart!\n' self.prompt = 'BlooClient: ' if not self.client.has_bloostamp(): print 'No bloostamp found, creating one!' self.client.register() self.do_addr('')
def cmd_update(bot, user, text, command, parameter): global log if bot.is_admin(user): bot.mumble.users[text.actor].send_text_message(tr('start_updating')) msg = util.update(bot.version) bot.mumble.users[text.actor].send_text_message(msg) else: bot.mumble.users[text.actor].send_text_message(tr('not_admin'))
def __init__(self, lang, seed_fname, extend_seeds): def tag_ext(pos): return lambda words: extended(tagged(words, pos)) def tag(pos): return lambda words: tagged(words, pos) noun_fn, verb_fn = cluster(lang) with uopen(seed_fname) as lines: seeds = read_seed(l.rstrip().split() for l in lines) op = tag_ext if extend_seeds else tag with uopen(noun_fn) as nlines, uopen(verb_fn) as vlines: nclusters = read_clusters((l.rstrip().split() for l in nlines), op(N)) vclusters = read_clusters((l.rstrip().split() for l in vlines), op(V)) update(self, mbuilder=MetaphorBuilder(lang, nclusters, vclusters, seeds))
def cmd_update(bot, user, text, command, parameter): if bot.is_admin(user): bot.mumble.users[text.actor].send_text_message( "Starting the update") # Need to be improved msg = util.update(version) bot.mumble.users[text.actor].send_text_message(msg) else: bot.mumble.users[text.actor].send_text_message( var.config.get('strings', 'not_admin'))
def file_summary_handle(section): """ Extract the file summary information for a given file :param section: sequence of lines :return: dictionary """ fs_dict = dict() for line in section: if line.startswith('File:'): fs_dict = util.update(fs_dict, {'name': parsers.file_name_parser(line)}) if line.startswith('File duration:'): fs_dict = util.update( fs_dict, {'duration': parsers.file_duration_parser(line)}) fs_dict = util.update( fs_dict, {'percentage': parsers.file_percentage_parser(line)}) yield stuff_in_dict(fs_dict, 'file_summary')
def main(): w1 = sys.stdin.readline().strip().split(",") w2 = sys.stdin.readline().strip().split(",") points = set() min_distance = 10e9 curr = [0, 0] for path in w1: length = int(path[1:]) for i in range(length): update(curr, path[0]) points.add(tuple(curr)) curr = [0, 0] # reset the central port for path in w2: length = int(path[1:]) for i in range(length): update(curr, path[0]) if tuple(curr) in points: min_distance = min(abs(curr[0]) + abs(curr[1]), min_distance) print(min_distance) # output
def main(): memory = read() intcode = IntCodeComputer(memory) white_tiles = set() curr = [0, 0] white_tiles.add(tuple(curr)) turn_to_paint = True face = 0 directions = ['U', 'R', 'D', 'L'] min_x = 10e9 min_y = 10e9 max_x = -10e9 max_y = -10e9 while not intcode.completed: intcode.run() while not intcode.output.empty(): value = intcode.output.get() if turn_to_paint: if value == 1: white_tiles.add(tuple(curr)) elif value == 0 and tuple(curr) in white_tiles: white_tiles.remove(tuple(curr)) min_x = min(min_x, curr[0]) min_y = min(min_y, curr[1]) max_x = max(max_x, curr[0]) max_y = max(max_y, curr[1]) else: if value == 1: face = (face + 5) % 4 elif value == 0: face = (face + 3) % 4 update(curr, directions[face]) turn_to_paint = not turn_to_paint intcode.read(int(tuple(curr) in white_tiles)) for j in range(max_y, min_y - 1, -1): for i in range(min_x, max_x + 1): draw((i, j) in white_tiles) print()
def set_answer_key(assignment_def_id, answer_key_fpath): db_read = util.select( 'Answer_key', ('answer_key_id'), {'assignment_def_id':assignment_def_id}, classname='AssignmentDefinition' ) if len(db_read) > 0: # case that Answer Key already exists for Assignment Def answer_key_id = db_read[0][0] util.update( 'Answer_key', {'answer_key_id':answer_key_id}, {'answer_key_file_path':answer_key_fpath}, classname='AssignmentDefinition' ) else: util.insert( 'Answer_key', ('assignment_def_id','answer_key_file_path'), (assignment_def_id,answer_key_fpath), classname=AssignmentDefinition.__name__ )
def summary_handler(section): """ Extract the information from the PProfile summary section :param section: sequence of lines :return: dictionary """ summary_dict = dict() for section_dict in itertools.chain.from_iterable( parse_section(section, (command_line_handler, total_duration_handler))): summary_dict = util.update(summary_dict, section_dict) yield {'summary': summary_dict}
def main(): w1 = sys.stdin.readline().strip().split(",") w2 = sys.stdin.readline().strip().split(",") points = {} min_steps = 10e9 curr = [0, 0] count = 0 for path in w1: length = int(path[1:]) for i in range(length): update(curr, path[0]) count += 1 points[tuple(curr)] = count curr = [0, 0] # reset the central port count = 0 # reset the counter for path in w2: length = int(path[1:]) for i in range(length): update(curr, path[0]) count += 1 if tuple(curr) in points: min_steps = min(points[tuple(curr)] + count, min_steps) print(min_steps) # output
def update(): if request.method == 'POST': data = {k: v[0] for k, v in dict(request.form).items()} print data res = util.update(data) if res['code'] == 0: return redirect('/userlist') else: return render_template('update.html', res=res) else: uid = request.args.get('id') data = {'id': uid} res = util.getuser(data) print res return render_template('update.html', res=res)
def file_handler(section): """ Extract the information for a single file in the profile :param section: sequence of lines :return: dictionary """ file_dict = {} for file_section in split_sections(section, section_marker='-----'): for fdict in itertools.chain.from_iterable( parse_section(file_section, (file_summary_handle, line_handler))): file_dict = util.update(file_dict, fdict) yield stuff_in_dict( file_dict, util.hashkey(file_dict['file_summary']['name']) if file_dict else '')
def modity(): if not session: return redirect('/login/') if request.method == 'POST': data = dict(request.form) data = {k: v[0] for k, v in data.items()} result = update('user', filed, data) if result['code'] == 0: return redirect("/userlist/") else: return render_template('update.html', result=result) else: uid = request.args.get('id', "") data = {'id': uid} result = getone('user', filed, data) if result['code'] == 0: result = result['msg'] return render_template('update.html', result=result)
def get_profile_dict(stream): """ Consumes the `stream` containing the pprofile output and returns a dictionary containing the parsed profile information :param stream: stream :return: dictionary """ lines = (line.rstrip('\n') for line in stream) profile_dict = dict() for section in handlers.split_sections(lines): for section_dict in itertools.chain.from_iterable( handlers.parse_section( section, (handlers.summary_handler, handlers.file_handler))): profile_dict = util.update(profile_dict, section_dict) return profile_dict
def __init__(self, **kw): update(self, kw)
import excel import util import time import xlwings # global variables url = "http://api.openweathermap.org/data/2.5/weather?q=" apikey = "&appid=" # put your api key after = sign update = True update_freq = 3 # set update frequency filename = "data.xlsx" # provide the file location here wb = xlwings.Book(filename) sheet1 = wb.sheets['sheet1'] while update: data = [] # read sheet row-wise for i, row in excel.get_excel_sheet(filename): temp = util.get_temperature_in_kelvin(row[0], url, apikey) temp = util.convert_temperature(temp, row[2]) row[1] = temp data.append([i + 2, row]) # iterate over data and fill the excel sheet in real time for dat in data: # print("B{}".format(dat[0]), dat[1][1]) util.update(sheet1, "B{}".format(dat[0]), dat[1][1]) time.sleep(update_freq)
def org(self, address): address = ibv(address) print 'setting org to %#06x' % (address,) update(self.here, address)
def __init__(self, **kw): """:param **kw: it assumes the following keys: command, Translator. """ update(self, kw, debug=kw['debug'] if 'debug' in kw else False)
df_data = { 'Index': F"{measurement}-None-constant-OLS", 'Measurement': measurement, 'Weight': 'None', 'Std': 'constant', 'Model': 'OLS', 'Params': (pld0_ols, n_ols, sigma_ols), 'PLm': plm, 'NumBins': num_bins, 'Distances': d_plot_uncensored, 'TwoSigmaBound': two_sigma_bound, "Censored": "Uncensored", "MLValue": None, } result_df = util.update(result_df, df_data) print(result_df.iloc[-1, :]) for (i, (sigma, sigma_name)) in enumerate(zip([sigma_ols], ["constant"])): # for (i, (sigma, sigma_name)) in enumerate(zip([sigma_ols, [0, sigma_ols]], ["constant", "distant_dependent"])): for weight_type, weight_name in zip( [None, w_lin, w_log, w_sq], ["No", "Linear", "Log10", "Square"]): res = model.ml_with_constraints(d0=1, d=d_uncensored, pld=pld_uncensored, c=c_uncensored, pld0=pld0_ols,
def __init__(self, lang, nclusters, vclusters, seeds): metaphors, orphans = build_metaphors(seeds, nclusters, vclusters) update(self, metaphors=metaphors, orphans=orphans)