def test_date_not_exist(): p = Plan('12', '20', 'mock plans') calendar = {'2019-12-31': [p]} plan = Calendar.command_delete('2019-10-31', 12, calendar) assert "2019-10-31 is not a date in the calendar" == plan
if self.plan != None: self.dispatch(self.plan) while self.plan != None: if not self.cmds.empty(): cmd = self.cmds.get() self.deal_cmd(cmd) rate.sleep() if __name__ == '__main__': try: rospy.init_node('task_planner', anonymous=True) dirname, _ = os.path.split(os.path.abspath(__file__)) solver = Solver({ 'solver': '../res/solver/clingo', 'time_limit': 30, 'quiet': True, 'max_steps': 20 }) solver.solver = os.path.realpath(dirname + '/' + solver.solver) inst = [ '../res/domain/robot/kejia.lp', '../res/domain/inst/init.lp', '../res/domain/inst/goal.lp' ] inst = [os.path.realpath(dirname + '/' + f) for f in inst] example = Monitor() example.plan = Plan(solver.execute(inst)) example.run() except rospy.ROSInterruptException: pass
def setUp(self): self.single_plan = Plan('Single', 49, 1) self.plus_plan = Plan('Plus', 99, 3) self.renewal_date = datetime.datetime.today().date() self.subscription_1 = Subscription(self.single_plan, self.renewal_date)
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # Copyright © XYM # Last modified: 2016-08-27 13:29:08 import click from plan import Plan cron = Plan("bankeys", path='/home/apps/bankeys', environment={'DJANGO_SETTINGS_MODULE': 'config.settings.prod'}) # cron.script('manage.py runscript collect_liwushuo_items', every='9.hour') # cron.script('manage.py runjob collect_nanyibang_items', every='9.hour') # cron.script('manage.py runjob reward', every='1.day') # cron.script('manage.py runjob tmc', every='5.minute') # cron.script('manage.py runjob trend', every='16.hour') # cron.script('manage.py runjob n2oid', every='30.minute') # cron.script('manage.py runjob rand_rec', every='2.hour') # cron.command('/home/apps/stock/crontab/db_backup.sh', every='1.day') # cron.command('/usr/bin/rsync -av /home/apps/stock /home/apps/backups', every='15.day') @click.command() @click.argument('action', default='check') def execute(action): cron.run(action)
if (question == 'yes' or question == 'y'): saturday = 'Saturday: ' saturday += input("Please list the workouts ") else: saturday = "Saturday: nothing" question = input("Are there workouts on sunday? *yes/y or no/n* ") question = question.lower() if (question == 'yes' or question == 'y'): sunday = 'Sunday: ' sunday += input("Please list the workouts ") else: sunday = "Sunday: nothing" email = input( "Please list the email associated with the client to link the plan? " ) pl = Plan(name, monday, tuesday, wednesday, thursday, friday, saturday, sunday) insert_plan(pl, email) q = input( "Would you like to associate another client with this plan? *yes/y* *no/n*" ) while (q == 'yes' or q == 'y'): email = input( "Please list the email associated with the client to link the plan? " ) insert_plan(pl, email) q = input( "Would you like to associate another client with this plan? *yes/y* *no/n*" ) elif (answer == 'edit'): what = input( "Do you want to edit a client (client) or a plan (plan) ")
def test_repr_method(self): """test repr method""" plan = Plan('Test', '50', 5) self.assertEqual(f'< Plan {plan.limit}>', str(plan))
def __init__(self, options, *, seed=None): self.seed = seed self.plan = None if self.seed is None: self.seed = os.urandom(16) self.rnd = random.Random(self.seed) if options.race: self.rnd.random() # Just pull 1 random number so race seeds are different then from normal seeds but still stable. if options.goal == "random": options.goal = self.rnd.randint(-1, 8) if options.plan: assert options.multiworld is None self.plan = Plan(options.plan) if options.multiworld: self.__logic = logic.MultiworldLogic(options, self.rnd) else: world_setup = WorldSetup() world_setup.randomize(options, self.rnd) self.__logic = logic.Logic(options, world_setup=world_setup) if self.plan: for ii in self.__logic.iteminfo_list: item = self.plan.forced_items.get(ii.nameId.upper(), None) if isinstance(item, list): ii.OPTIONS = item else: ii.forced_item = item if not options.keysanity or options.forwardfactor: item_placer = ForwardItemPlacer(self.__logic, options.forwardfactor, options.accessibility_rule) else: item_placer = RandomItemPlacer(self.__logic, options.accessibility_rule) for item, count in self.readItemPool(options, item_placer).items(): if count > 0: item_placer.addItem(item, count) item_placer.run(self.rnd) if options.multiworld: z = None if options.output_filename is not None: z = zipfile.ZipFile(options.output_filename, "w") for n in range(options.multiworld): rom = generator.generateRom(options.multiworld_options[n], self.seed, self.__logic, multiworld=n) fname = "LADXR_Multiworld_%d_%d.gbc" % (options.multiworld, n + 1) if z: handle = z.open(fname, "w") rom.save(handle, name="LADXR") handle.close() else: rom.save(fname, name="LADXR") if options.spoilerformat != "none" and not options.race: extension = "json" if options.spoilerformat == "json" else "txt" sfname = "LADXR_Multiworld_%d_%d.%s" % (options.multiworld, n + 1, extension) log = spoilerLog.SpoilerLog(options, rom) log.output(sfname, z) else: rom = generator.generateRom(options, self.seed, self.__logic) filename = options.output_filename if filename is None: filename = "LADXR_%s.gbc" % (binascii.hexlify(self.seed).decode("ascii").upper()) rom.save(filename, name="LADXR") if options.spoilerformat != "none" and not options.race: log = spoilerLog.SpoilerLog(options, rom) log.output(options.spoiler_filename)
def maxfield(filename, num_agents=1, num_field_iterations=1000, num_cpus=1, max_route_solutions=1000, max_route_runtime=60, outdir='.', skip_plots=False, skip_step_plots=False, res_colors=False, google_api_key=None, google_api_secret=None, output_csv=False, verbose=False, max_outgoing_links=8, count_already_made_links=True): """ Given a portal list file, determine the optimal linking and fielding strategy to maximize AP, minimize walking distance, and minimize the number of keys needed. Inputs: filename :: string The filename containing the properly-formatted portal list. num_agents :: integer The number of agents in this fielding operation num_field_iterations :: integer The number of random field plans to generate before choosing the best. A larger number of iterations will mean the plan is more likely, or closer to, optimal, but it also increases runtime. num_cpus :: integer The number of CPUs used to generate field plans. If 1, do not use multiprocessing. If < 1, use maximum available CPUs. Otherwise, use this many CPUs. max_route_solutions :: integer The maximum number of agent routing solutions to generate before choosing the best. Once max_route_solutions or max_route_runtime is reached, the best routing plan is selected. max_route_runtime :: integer The maximum runtime of the agent routing algorithm (seconds). Once max_route_solutions or max_route_runtime is reached, the best routing plan is selected. outdir :: string The directory where results are stored. Created if it doesn't exist. Default is current directory. skip_plots :: boolean If True, don't generate any figures skip_step_plots :: boolean If True, don't generate link-by-link figures res_colors :: boolean If True, use resistance color scheme, otherwise enlightened google_api_key :: string If not None, use this as an API key for google maps. If None, do not use google maps. google_api_secret :: string If not None, use this as a signature secret for google maps. If None, do not use a google API signature. output_csv :: boolean If True, also output machine readable CSV files. verbose :: boolean If True, display helpful information along the way Returns: Nothing """ start_time = time.time() # # Read portal file # portals = read_portal_file(filename) if verbose: print("Found {0} portals in portal file: {1}". format(len(portals), filename)) print() # # Initialize Plan # plan = Plan(portals, num_agents=num_agents, verbose=verbose) # # Optimize Plan # plan.optimize(num_field_iterations=num_field_iterations, num_cpus=num_cpus, max_outgoing_links=max_outgoing_links) # # Determine agent link assignments # plan.route_agents(max_route_solutions=max_route_solutions, max_route_runtime=max_route_runtime) # # Generate plan output files and plots # results = Results(plan, outdir=outdir, res_colors=res_colors, google_api_key=google_api_key, google_api_secret=google_api_secret, output_csv=output_csv,verbose=verbose) results.key_prep() results.ownership_prep() results.agent_key_prep() results.agent_assignments() if not skip_plots: results.portal_map() results.link_map() if not skip_step_plots: results.step_plots() end_time = time.time() if verbose: print("Total maxfield runtime: {0:.1f} seconds". format(end_time-start_time))
# -*- coding: utf-8 -*- # Use this file to easily define all of your cron jobs. # # It's helpful to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # # Learn more: http://github.com/fengsp/plan import click from plan import Plan cron = Plan("surprise", path='/home/apps/surprise', environment={'DJANGO_SETTINGS_MODULE': 'config.settings.prod'}) cron.script('manage.py runscript collect_liwushuo_items', every='9.hour') # cron.script('manage.py runjob collect_nanyibang_items', every='9.hour') # cron.script('manage.py runjob n2oid', every='3.hour') cron.script('manage.py runjob tmc', every='5.minute') cron.script('manage.py runjob trend', every='16.hour') cron.script('manage.py runjob reward', every='1.day') cron.command('/home/apps/surprise/crontab/db_backup.sh', every='15.minute') cron.command('/usr/bin/rsync -av /home/apps/surprise /home/apps/backups', every='15.day') @click.command() @click.argument('action', default='check') def execute(action): cron.run(action)
def plan_probes(queue, periods, X, Y, tag=None): """ Parameters ---------- P : raggedarray of ints The period (in time-steps) of each probe """ assert len(X) == len(Y) assert len(X) == len(periods) N = len(X) cl_countdowns = to_device(queue, np.zeros(N, dtype='int32')) cl_bufpositions = to_device(queue, np.zeros(N, dtype='int32')) cl_periods = to_device(queue, np.asarray(periods, dtype='int32')) assert X.cl_buf.ocldtype == Y.cl_buf.ocldtype ### N.B. X[i].shape = (ndims[i], ) ### Y[i].shape = (buf_ndims[i], buf_len) for i in xrange(N): assert X.shape0s[i] == Y.shape1s[i] assert X.shape1s[i] == 1 assert X.stride0s[i] == 1 assert Y.stride1s[i] == 1 text = """ ////////// MAIN FUNCTION ////////// __kernel void fn( __global int *countdowns, __global int *bufpositions, __global const int *periods, __global const int *Xstarts, __global const int *Xshape0s, __global const ${Xtype} *Xdata, __global const int *Ystarts, __global ${Ytype} *Ydata ) { const int n = get_global_id(1); const int countdown = countdowns[n]; if (countdown == 0) { const int n_dims = Xshape0s[n]; __global const ${Xtype} *x = Xdata + Xstarts[n]; const int bufpos = bufpositions[n]; __global ${Ytype} *y = Ydata + Ystarts[n] + bufpos * n_dims; for (int ii = get_global_id(0); ii < n_dims; ii += get_global_size(0)) { y[ii] = x[ii]; } // This should *not* cause deadlock because // all local threads guaranteed to be // in this branch together. barrier(CLK_LOCAL_MEM_FENCE); if (get_global_id(0) == 0) { countdowns[n] = periods[n] - 1; bufpositions[n] = bufpos + 1; } } else { barrier(CLK_LOCAL_MEM_FENCE); if (get_global_id(0) == 0) { countdowns[n] = countdown - 1; } } } """ textconf = dict(N=N, Xtype=X.cl_buf.ocldtype, Ytype=Y.cl_buf.ocldtype) text = Template(text, output_encoding='ascii').render(**textconf) full_args = ( cl_countdowns, cl_bufpositions, cl_periods, X.cl_starts, X.cl_shape0s, X.cl_buf, Y.cl_starts, Y.cl_buf, ) _fn = cl.Program(queue.context, text).build().fn _fn.set_args(*[arr.data for arr in full_args]) max_len = min(queue.device.max_work_group_size, max(X.shape0s)) gsize = ( max_len, N, ) lsize = (max_len, 1) rval = Plan(queue, _fn, gsize, lsize=lsize, name="cl_probes", tag=tag) rval.full_args = full_args # prevent garbage-collection rval.cl_bufpositions = cl_bufpositions rval.Y = Y return rval
def _plan_template(queue, name, core_text, declares="", tag=None, n_elements=0, inputs={}, outputs={}, parameters={}): """Template for making a plan for vector nonlinearities. This template assumes that all inputs and outputs are vectors. Parameters ---------- n_elements: int If n_elements == 0, then the kernels are allocated as a block. This is simple, but can be slow for large computations where input vector sizes are not uniform (e.g. one large population and many small ones). If n_elements >= 1, then all the vectors in the RaggedArray are flattened so that the exact number of required kernels is allocated. Each kernel performs computations for `n_elements` elements. inputs: dictionary of CLRaggedArrays Inputs to the function. RaggedArrays must be a list of vectors. outputs: dictionary of CLRaggedArrays Outputs of the function. RaggedArrays must be a list of vectors. parameters: dictionary of CLRaggedArrays Parameters to the function. Each RaggedArray element must be a vector of the same length of the inputs, or a scalar (to be broadcasted). Providing a float instead of a RaggedArray makes that parameter constant. """ base = inputs.values()[0] # input to use as reference (for lengths) N = len(base) ### split parameters into static and updated params static_params = {} # static params (hard-coded) params = {} # variable params (updated) for k, v in parameters.items(): if isinstance(v, CLRaggedArray): params[k] = v else: try: static_params[k] = ('float', float(v)) except TypeError: raise avars = {} for vname, v in inputs.items() + outputs.items(): assert vname not in avars, "Name clash" assert len(v) == N assert all_equal(v.shape0s, base.shape0s) ### N.B. - we should be able to ignore ldas as long as all vectors assert all_equal(v.shape1s, 1) dtype = v.cl_buf.ocldtype offset = '%(name)s_starts[n]' % {'name': vname} avars[vname] = (dtype, offset) for vname, v in params.items(): assert vname not in avars, "Name clash" assert len(v) == N for i in xrange(N): assert v.shape0s[i] == base.shape0s[i] or v.shape0s[i] == 1, \ "%s.shape0s[%d] must be 1 or %d (not %d)" % \ (vname, i, base.shape0s[i], v.shape0s[i]) assert v.shape1s[i] == 1 dtype = v.cl_buf.ocldtype offset = '%(name)s_starts[n]' % {'name': vname} avars[vname] = (dtype, offset) ivars = dict((k, avars[k]) for k in inputs.keys()) ovars = dict((k, avars[k]) for k in outputs.keys()) pvars = dict((k, avars[k]) for k in params.keys()) textconf = dict(N=N, n_elements=n_elements, tag=str(tag), declares=declares, core_text=core_text, ivars=ivars, ovars=ovars, pvars=pvars, static_params=static_params) if n_elements > 0: ### Allocate the exact number of required kernels in a vector gsize = (int(np.ceil(np.sum(base.shape0s) / float(n_elements))), ) text = """ ////////// MAIN FUNCTION ////////// __kernel void fn( % for name, [type, offset] in ivars.items(): __global const int *${name}_starts, __global const ${type} *in_${name}, % endfor % for name, [type, offset] in ovars.items(): __global const int *${name}_starts, __global ${type} *in_${name}, % endfor % for name, [type, offset] in pvars.items(): __global const int *${name}_starts, __global const int *${name}_shape0s, __global const ${type} *in_${name}, % endfor __global const int *lengths ) { const int gid = get_global_id(0); int m = gid * ${n_elements}, n = 0; while (m >= lengths[n]) { m -= lengths[n]; n++; } if (n >= ${N}) return; % for name, [type, offset] in ivars.items(): __global const ${type} *cur_${name} = in_${name} + ${offset} + m; % endfor % for name, [type, offset] in ovars.items(): __global ${type} *cur_${name} = in_${name} + ${offset} + m; % endfor % for name, [type, offset] in pvars.items(): __global const ${type} *cur_${name} = in_${name} + ${offset}; int ${name}_isvector = ${name}_shape0s[n] > 1; if (${name}_isvector) cur_${name} += m; % endfor % for name, [type, offset] in ivars.items() + ovars.items() + pvars.items(): ${type} ${name}; % endfor % for name, [type, value] in static_params.items(): const ${type} ${name} = ${value}; % endfor ////////////////////////////////////////////////// //vvvvv USER DECLARATIONS BELOW vvvvv ${declares} //^^^^^ USER DECLARATIONS ABOVE ^^^^^ ////////////////////////////////////////////////// % for ii in range(n_elements): ////////////////////////////////////////////////// ////////// LOOP ITERATION ${ii} % for name, [type, offset] in ivars.items(): ${name} = *cur_${name}; % endfor % for name, [type, offset] in pvars.items(): if ((${ii} == 0) || ${name}_isvector) ${name} = *cur_${name}; % endfor /////vvvvv USER COMPUTATIONS BELOW vvvvv ${core_text} /////^^^^^ USER COMPUTATIONS ABOVE ^^^^^ % for name, [type, offset] in ovars.items(): *cur_${name} = ${name}; % endfor % if ii + 1 < n_elements: m++; if (m >= lengths[n]) { n++; m = 0; if (n >= ${N}) return; % for name, [type, offset] in ivars.items() + ovars.items() + pvars.items(): cur_${name} = in_${name} + ${offset}; % endfor % for name, [type, offset] in pvars.items(): ${name}_isvector = ${name}_shape0s[n] > 1; if (!${name}_isvector) ${name} = *cur_${name}; % endfor } else { % for name, [type, offset] in ivars.items() + ovars.items(): cur_${name}++; % endfor % for name, [type, offset] in pvars.items(): if (${name}_isvector) cur_${name}++; % endfor } % endif % endfor } """ else: ### Allocate more than enough kernels in a matrix gsize = (int(np.max(base.shape0s)), int(N)) text = """ ////////// MAIN FUNCTION ////////// __kernel void fn( % for name, [type, offset] in ivars.items(): __global const int *${name}_starts, __global const ${type} *in_${name}, % endfor % for name, [type, offset] in ovars.items(): __global const int *${name}_starts, __global ${type} *in_${name}, % endfor % for name, [type, offset] in pvars.items(): __global const int *${name}_starts, __global const int *${name}_shape0s, __global const ${type} *in_${name}, % endfor __global const int *lengths ) { const int m = get_global_id(0); const int n = get_global_id(1); const int M = lengths[n]; if (m >= M) return; % for name, [type, offset] in ivars.items(): ${type} ${name} = in_${name}[${offset} + m]; % endfor % for name, [type, offset] in ovars.items(): ${type} ${name}; % endfor % for name, [type, offset] in pvars.items(): const ${type} ${name} = (${name}_shape0s[n] > 1) ? in_${name}[${offset} + m] : in_${name}[${offset}]; % endfor % for name, [type, value] in static_params.items(): const ${type} ${name} = ${value}; % endfor ////////////////////////////////////////////////// //vvvvv USER DECLARATIONS BELOW vvvvv ${declares} //^^^^^ USER DECLARATIONS ABOVE ^^^^^ ////////////////////////////////////////////////// /////vvvvv USER COMPUTATIONS BELOW vvvvv ${core_text} /////^^^^^ USER COMPUTATIONS ABOVE ^^^^^ % for name, [type, offset] in ovars.items(): in_${name}[${offset} + m] = ${name}; % endfor } """ text = Template(text, output_encoding='ascii').render(**textconf) if 0: for i, line in enumerate(text.split('\n')): print "%3d %s" % (i + 1, line) full_args = [] for vname, v in inputs.items() + outputs.items(): full_args.extend([v.cl_starts, v.cl_buf]) for vname, v in params.items(): full_args.extend([v.cl_starts, v.cl_shape0s, v.cl_buf]) full_args.append(base.cl_shape0s) full_args = tuple(full_args) _fn = cl.Program(queue.context, text).build().fn _fn.set_args(*[arr.data for arr in full_args]) rval = Plan(queue, _fn, gsize, lsize=None, name=name, tag=tag) rval.full_args = full_args # prevent garbage-collection return rval
def test_is_true(): p = Plan('15', '20', 'mock plans') calendar = {'2019-10-31': [p]} plan = Calendar.command_delete('2019-10-31', 15, calendar) assert True is plan
def test_add_new_date_with_same_starttime_resulting_in_overwrite(): calendar = {'2019-12-12': [Plan('12', '15', 'existing plans')]} Calendar.command_add('2019-12-12', calendar, Plan('12', '14', 'replaced plans')) result = Calendar.command_show(calendar) assert "\n2019-12-12 : \n start : 12:00,\n end : 14:00,\n title : replaced plans" == result
def test_add_new_date(): calendar = {} plan = Calendar.command_add('2019-11-01', calendar, Plan('09', '14', 'mock plans')) assert True is plan
def load_calendar(): """ () -> dict Load calendar from 'calendar.txt'. If calendar.txt does not exist, create and return an empty calendar. For the format of calendar.txt see save_calendar() above. return: calendar. """ if os.path.exists("calendar.txt"): with open("calendar.txt", "r") as file: reader = file.readlines() calendar = {} for daily_schedule in reader: daily_schedule = daily_schedule.replace("\n", "") date = daily_schedule[:10] plans = [] if '\t' in daily_schedule: # more than 2 plans on the day plans_on_the_day = daily_schedule[11:].split('\t') for i in range(len(plans_on_the_day)): index_of_first_space = plans_on_the_day[i].index(" ") # if time is full length if index_of_first_space == 5: start = plans_on_the_day[i][0:2] end = plans_on_the_day[i][3:5] title = plans_on_the_day[i][6:] plan = Plan(start, end, title) plans.append(plan) # if time is NOT full length elif index_of_first_space == 4: start = plans_on_the_day[i][0:1] end = plans_on_the_day[i][2:4] title = plans_on_the_day[i][5:] plan = Plan(start, end, title) plans.append(plan) elif index_of_first_space == 3: start = plans_on_the_day[i][0:1] end = plans_on_the_day[i][2:3] title = plans_on_the_day[i][4:] plan = Plan(start, end, title) plans.append(plan) calendar[date] = plans else: item_str = daily_schedule[11:] index_of_first_space = daily_schedule[11:].index(" ") # if time is full length if index_of_first_space == 5: start = item_str[0:2] end = item_str[3:5] title = item_str[6:] plan = Plan(start, end, title) plans.append(plan) # if time is NOT full length if index_of_first_space == 4: start = item_str[0:1] end = item_str[2:4] title = item_str[5:] plan = Plan(start, end, title) plans.append(plan) if index_of_first_space == 3: start = item_str[0:1] end = item_str[2:3] title = item_str[4:] plan = Plan(start, end, title) plans.append(plan) calendar[date] = plans else: file = open('calendar.txt', 'w') file.close() calendar = {} return calendar
# http://en.wikipedia.org/wiki/Cron # # Learn more: http://github.com/fengsp/plan import sys import os import shutil import subprocess from plan import Plan from utils.config import get_environment, get_task_specs config = get_environment('plan') config['environment'] = dict(config['environment']) cron = Plan(**config) log_path = os.path.abspath(os.path.join(config.path,'logs')) modules_path = os.path.abspath(os.path.join(config.path,'modules')) for task in get_environment('tasks'): task_specs = get_task_specs(task['name']) cron.script(**task_specs) if __name__ == "__main__": command = sys.argv[1] if command == 'write': if not os.path.exists('logs'): os.makedirs('logs') c = subprocess.Popen("crabd-check", stdout=subprocess.PIPE, shell=True) print(c) elif command == 'clear':
def test_create_plan(self): """Test creating a Plan object""" plan = Plan('Test', 50, 5) self.assertEqual('Test', plan.name) self.assertEqual(50, plan.price) self.assertEqual(5, plan.limit)
possible_colors = ['blue', 'red', 'cyan', 'green', 'black', 'magenta', 'white', 'yellow'] if re.match('[Cc][oO][mM][Pp][Uu][Tt][Ee][Rr]', name): is_smart = input('Should be computer be smart? *Yes (1) or No (0). ') or 1 while True: color = input('Player color: ') if color in possible_colors: break else: print('Wrong color, try again. ') return name, color, is_smart == 1 def size_of_plan(): while True: size = input('Size of plan (n m): ') try: return int(size.split()[0]), int(size.split()[1]) except ValueError: print('Invalid input.') if __name__ == '__main__': n, m = size_of_plan() name, color, is_smart = get_players_info() player1 = Player(name, 1, color, is_smart) name, color, is_smart = get_players_info() player2 = Player(name, 2, color, is_smart) plan = Plan(n, m, player1, player2) strategy = Strategy(plan) game = Controller(plan, strategy) game.game()
from math import pi from tool import maps import numpy as np fig, ax = plt.subplots() w = 640 h = 480 cam = Camera(position=[10, 0, 0], rotation=[0, 0, 0], focale=20, resolution=[w, h], pitch=[1, 1]) sph = Sphere(position=[0, 0, 12], radius=5, color=[125, 0, 200]) sph2 = Sphere(position=[0, 5, 10], radius=3, color=[200, 123, 50]) pla = Plan(arg=[1, 0, 0, 50], color=[0, 0, 225]) scene = [pla, sph, sph2] l = 0 frame = 0 def update(frame, l): cam.position[2] = frame cam.rotation = [0, 0, 0] image = [[(0, 0, 0) for i in range(w)] for j in range(h)] rays = [] for i in range(h): for j in range(w): alphamax = float("inf") rays.append(Ray(0, 0, 0))
def make_and_execute_plan(self, r_init, r_goal, blocked_obstacles): r_cur = r_init is_manip_success = True blocked_obstacles = blocked_obstacles eu_cost_l, min_cost_l = SortedDict(), SortedDict() map_cur = self.map_manager.get_init_map() p_opt = [ Plan([ Path.from_path( self.global_planner.make_plan(map_cur, r_cur, r_goal), False, self.MOVE_COST) ]) ] Utils.publish_plan(p_opt[0]) pass while not self._is_same_pose(r_cur, r_goal): map_cur = self.map_manager.get_map_copy() if map_cur.has_free_space_been_created(): min_cost_l.clear() obstacles = map_cur.obstacles is_push_pose_valid = True is_obstacle_same = True if p_opt[0].obstacle is not None: is_obstacle_same = p_opt[0].obstacle.compare( obstacles[p_opt[0].obstacle.obstacle_id]) if not is_obstacle_same: p_opt[0].obstacle = obstacles[ p_opt[0].obstacle.obstacle_id] p_opt[0].safe_swept_area = self._get_safe_swept_area( p_opt[0].obstacle, p_opt[0].translation_vector, map_cur.merged_occ_grid) if p_opt[0].next_step_component == Plan.C1 and not p_opt[ 0].obstacle.is_obstacle_push_pose( p_opt[0].push_pose): is_push_pose_valid = False is_plan_not_colliding = not p_opt[0].is_plan_colliding(map_cur) is_plan_valid = is_plan_not_colliding and is_push_pose_valid and is_manip_success if not is_plan_valid: p_opt = [ Plan([ Path.from_path( self.global_planner.make_plan( map_cur, r_cur, r_goal), False, self.MOVE_COST) ]) ] Utils.publish_plan(p_opt[0]) self.make_plan(r_cur, r_goal, map_cur, obstacles, blocked_obstacles, p_opt, eu_cost_l, min_cost_l) Utils.debug_erase_partial_paths() Utils.publish_plan(p_opt[0]) pass # Stop condition if no plan is found if p_opt[0].cost >= float("inf"): return False is_manip_success = True r_next = p_opt[0].get_next_step() c_next = p_opt[0].next_step_component is_manipulation = c_next == Plan.C2 r_real = self.robot_goto(r_next, is_manipulation) if is_manipulation and not self._is_same_pose(r_real, r_next): is_manip_success = False blocked_obstacles.add(p_opt[0].obstacle.obstacle_id) r_cur = r_real self.debug_rate.sleep() # Endwhile return True
def setUp(self): self.plus_plan = Plan('Plus', 99, 3)
def plan_for_obstacle(self, obstacle, p_opt, map_cur, r_cur, r_goal, blocked_obstacles): if obstacle.obstacle_id in blocked_obstacles: return None paths = SortedDict() for push_pose in obstacle.push_poses: push_pose_yaw = Utils.yaw_from_geom_quat( push_pose.pose.orientation) push_pose_unit_direction_vector = (math.cos(push_pose_yaw), math.sin(push_pose_yaw)) c1 = Path.from_path( self.global_planner.make_plan(map_cur, r_cur, push_pose, True), False, self.MOVE_COST) Utils.debug_publish_path(c1, "/simulated/debug_c1") # If c1 does not exist if not c1.path.poses: continue seq = 1 translation_vector = (push_pose_unit_direction_vector[0] * self.ONE_PUSH_DISTANCE * float(seq), push_pose_unit_direction_vector[1] * self.ONE_PUSH_DISTANCE * float(seq)) safe_swept_area = self._get_safe_swept_area( obstacle, translation_vector, map_cur.merged_occ_grid) obstacle_sim_pose = self._apply_translation_to_pose( push_pose, translation_vector) c3_est = Path.from_poses(obstacle_sim_pose, r_goal, False, self.MOVE_COST, push_pose_unit_direction_vector, self.ONE_PUSH_DISTANCE, map_cur.frame_id) Utils.debug_publish_path(c3_est, "/simulated/debug_c3") # TODO Make PUSH_COST an attribute of the object that is initialized to 1.0 until object is identified. c_est = c1.cost + c3_est.cost + self.PUSH_COST * Utils.euclidean_distance( translation_vector, (0.0, 0.0)) while c_est <= p_opt[0].cost and safe_swept_area is not None: c2 = Path.from_poses(push_pose, obstacle_sim_pose, True, self.PUSH_COST, push_pose_unit_direction_vector, self.ONE_PUSH_DISTANCE, map_cur.frame_id) Utils.debug_publish_path(c2, "/simulated/debug_c2") map_mod = copy.deepcopy(map_cur) map_mod.manually_move_obstacle(obstacle.obstacle_id, translation_vector) c3 = Path.from_path( self.global_planner.make_plan(map_mod, obstacle_sim_pose, r_goal), False, self.MOVE_COST) Utils.debug_publish_path(c3, "/simulated/debug_c3") # If c3 exists if c3.path.poses: p = Plan([c1, c2, c3], obstacle, translation_vector, safe_swept_area, push_pose) paths[p] = p.cost if p.cost < p_opt[0].cost: p_opt[0] = p seq = seq + 1 translation_vector = (push_pose_unit_direction_vector[0] * self.ONE_PUSH_DISTANCE * float(seq), push_pose_unit_direction_vector[1] * self.ONE_PUSH_DISTANCE * float(seq)) safe_swept_area = self._get_safe_swept_area( obstacle, translation_vector, map_cur.merged_occ_grid) obstacle_sim_pose = self._apply_translation_to_pose( push_pose, translation_vector) c3_est = Path.from_poses(obstacle_sim_pose, r_goal, False, self.MOVE_COST, push_pose_unit_direction_vector, self.ONE_PUSH_DISTANCE, map_cur.frame_id) Utils.debug_publish_path(c3_est, "/simulated/debug_c3") c_est = c1.cost + c3_est.cost + self.PUSH_COST * Utils.euclidean_distance( translation_vector, (0.0, 0.0)) # Return path with lowest cost : the first in the ordered dictionnary # If there is none, return None try: return paths.peekitem(0)[0] except IndexError: return None
def plan_lif(queue, V, RT, J, OV, ORT, OS, dt, tau_rc, tau_ref, V_threshold, upsample): L, = V.shape config = { 'tau_ref': tau_ref, 'tau_rc_inv': 1.0 / tau_rc, 'V_threshold': V_threshold, 'upsample': upsample, 'upsample_dt': dt / upsample, 'upsample_dt_inv': upsample / dt, } for vname in 'V', 'RT', 'J', 'OV', 'ORT', 'OS': v = locals()[vname] config[vname + 'type'] = v.ocldtype config[vname + 'offset'] = 'gid+%s' % int(v.offset // v.dtype.itemsize) assert v.shape == (L, ) assert v.strides == (v.dtype.itemsize, ) text = """ __kernel void foo( __global const ${Jtype} *J, __global const ${Vtype} *voltage, __global const ${RTtype} *refractory_time, __global ${Vtype} *out_voltage, __global ${RTtype} *out_refractory_time, __global ${OStype} *out_spiked ) { const int gid = get_global_id(0); ${Vtype} v = voltage[${Voffset}]; ${RTtype} rt = refractory_time[${RToffset}]; ${Jtype} j = J[${Joffset}]; char spiked = 0; ${Vtype} dV, overshoot; ${RTtype} post_ref, spiketime; % for ii in range(upsample): dV = ${upsample_dt} * ${tau_rc_inv} * (j - v); post_ref = 1.0 - (rt - ${upsample_dt}) * ${upsample_dt_inv}; v += dV; v = v > 0 ? v * (post_ref < 0 ? 0.0 : post_ref < 1 ? post_ref : 1.0) : 0; spiked |= v > ${V_threshold}; overshoot = (v - ${V_threshold}) / dV; spiketime = ${upsample_dt} * (1.0f - overshoot); rt = (v > ${V_threshold}) ? spiketime + ${tau_ref} : rt - ${upsample_dt}; v = (v > ${V_threshold}) ? 0.0f: v; % endfor out_voltage[${OVoffset}] = v; out_refractory_time[${ORToffset}] = rt; out_spiked[${OSoffset}] = spiked ? 1.0f : 0.0f; } """ text = Template(text, output_encoding='ascii').render(**config) build_options = [ '-cl-fast-relaxed-math', '-cl-mad-enable', #'-cl-strict-aliasing', ] fn = cl.Program(queue.context, text).build(build_options).foo fn.set_args(J.data, V.data, RT.data, OV.data, ORT.data, OS.data) return Plan(queue, fn, (L, ), None, name='lif')
def test_update2(self): p = Plan("today") p.update("07:00 aufstehen") self.assertEqual(p.step_list[0],Entry("00:00","aufstehen"))
if var in os.environ: ENVIRONMENT[var] = os.environ[var] class DjangoJob(Job): def task_template(self): return 'cd %s && python {task} >> {output}' % (SITE_ROOT) # Allows you to regularly run django commands: manage.py task class DjangoCommandJob(Job): def task_template(self): # return 'source ~/.bashrc && workon %s && cd %s && python manage.py {task} >> %s' % (VIRTUALENV, MANAGE_ROOT, LOG_PATH) return 'cd %s && {environment} %s manage.py {task} >> {output}' % (MANAGE_ROOT, PYTHON_EXECUTABLE) cron = Plan(environment=ENVIRONMENT, output=LOG_PATH, user=CRON_USER) # This tells crontab to email admins if any cron job failed. cron.env('MAILTO', ADMIN_EMAIL) #################################### Job definitions ################################### job = DjangoJob(task='task.py', every='1.day', at='02:00') cron.job(job) for day in ('sunday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'): absentee_report_job = DjangoCommandJob( task='send_absentee_roster_emails', every=day, at='08:00' )
def test_doesAddingFirstEntryChangeStart(self): p = Plan("h") p.add(Entry("00:00","h",start="10:00")) self.assertEqual(p.start,"10:00") p.add(Entry("01:00","h",start="12:00")) self.assertEqual(p.end,"11:00")
# -*- coding: utf-8 -*- # Use this file to easily define all of your cron jobs. # # It's helpful to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # # Learn more: http://github.com/fengsp/plan from plan import Plan cron = Plan() # register one command, script or module # cron.command('command', every='1.day') # cron.script('script.py', path='/web/yourproject/scripts', every='1.month') # cron.module('calendar', every='feburary', at='day.3') if __name__ == "__main__": cron.run()
from utils.db import database from user import User from plan import Plan single_plan = Plan('Single', 49, 1) plus_plan = Plan('Plus', 99, 3) infinite_plan = Plan('Infinite', 249, None) def register_user(name, email, password): if email in database['users']: raise ValueError('Email Already exists') new_user = User(name, email, password) new_user.save() return new_user def login_user(email, password): if email not in database['users']: raise ValueError('User does not exist') user = database['users'].get(f'{email}') user.authenticate(password) return user # new_user = User('tony', '*****@*****.**', 'password') # new_user.add_site('google.com') # user = register_user('tony', '*****@*****.**', 'password') # user = login_user('*****@*****.**', 'password') # user.subsrcibe_to_plan(single_plan) # user.change_plan(plus_plan)
# -*- coding: utf-8 -*- # Use this file to easily define all of your cron jobs. # # It's helpful to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # # Learn more: http://github.com/fengsp/plan from plan import Plan cron = Plan("scripts", path='/web/yourproject/scripts', environment={'YOURAPP_ENV': 'production'}) cron.script('script.py', every='1.day') cron.script('script_2.py', every='1.month', at='hour.12 minute.0') # more scripts here if __name__ == "__main__": cron.run('update')
def test_date_exists_but_start_time_not_exists(): p = Plan('12', '20', 'mock plans') calendar = {'2019-12-31': [p]} plan = Calendar.command_delete('2019-12-31', 10, calendar) assert "There is no event with start time of 10 on date 2019-12-31 in the calendar" == plan