def get_token(): log.info("%s" % dict(request.query)) code = request.query.get('code','') if memcache.get("oauth:%s" % request.query.get('state','')) != "session_id": abort(500, "Invalid state") token_url = "https://api.dropbox.com/1/oauth2/token" log.info(request.url) result = Struct(fetch(token_url, urllib.urlencode({ "code" : code, "grant_type" : "authorization_code", "client_id" : settings.dropbox.app_key, "client_secret": settings.dropbox.app_secret, "redirect_uri" : "http://localhost:8080/authorize/confirmation" }))) if result.status == 200: try: r = Struct(json.loads(result.data)) r.id = "default" log.info(r) t = DropboxToken(**r) t.put() except: log.error("%s", traceback.format_exc()) return result
def scene(): box1_instance = Struct(name='box1_instance', type='box', pos=Struct(x=6.0, y=6.0, z=1.0), color='red', size=2) box2_instance = Struct(name='box2_instance', type='box', pos=Struct(x=-5.0, y=4.0, z=1.0), color='blue', size=2) box3_instance = Struct(name='box3_instance', type='box', pos=Struct(x=-2, y=-8, z=1), color='green', size=2) box4_instance = Struct(name='box4_instance', type='box', pos=Struct(x=3, y=-7, z=1), color='red', size=1) #grid = [[None]*39 for i in range(30)] return Struct(robot1_instance=None, box1_instance=box1_instance, box2_instance=box2_instance, box3_instance=box3_instance, box4_instance=box4_instance) #, grid=grid)
def causalProcess(process): params = updated(self._cause, action = process.actionary.type()) if hasattr(process.causalAgent, 'referent') and process.causalAgent.referent.type(): params.update(causer = process.causalAgent.referent.type()) else: params.update(causer = get_objectDescriptor(process.causalAgent)) cp = params_for_simple(process.process1) ap = params_for_simple(process.process2) if cp is None or ap is None: return None params.update(causalProcess = Struct(cp)) params.update(affectedProcess = Struct(ap)) return params
def mock(): # return Struct(robot1_instance=Struct(name='robot1_instance', # pos=Struct(x=0.0, y=0.0, z=0.0)), # box1_instance=Struct(name='box1_instance', # pos=Struct(x=3.0, y=4.0, z=0.0)), # box2_instance=Struct(name='box2_instance', # pos=Struct(x=-2.0, y=-3.0, z=1.0)), # box3_instance=Struct(name='box3_instance', # pos=Struct(x=0, y=1, z=1))) robot1_instance = Struct(name='robot1_instance', pos=Struct(x=0.0, y=0.0, z=0.0)) world = Worlds.scene() setattr(world, 'robot1_instance', robot1_instance) return world
def as_struct(x): if '__JSON_Struct__' in x: return Struct(x['__JSON_Struct__']) elif '__JSON_Feature__' in x: return Feature(x['__JSON_Feature__']) else: return x
def params_for_motionPath(process, params): """ returns parameters for motion path process ("move to the box"). """ if hasattr(process, 'actionary'): params.update(action=process.actionary.type()) if hasattr(process, 'speed') and str( process.speed) != "None": # and process.speed.type(): params.update(speed=float(process.speed)) else: # Might change this - "dash quickly" (what should be done here?) s = self.get_actionDescriptor(process) if s is not None: params.update(speed=float(s)) # Is there a heading specified? if hasattr(process, 'heading'): if process.heading.type(): params.update(heading=process.heading.tag.type()) # Is a distance specified? if hasattr(process.spg, 'distance') and hasattr( process.spg.distance, 'amount'): d = process.spg.distance params.update(distance=Struct(value=int(d.amount.value), units=d.units.type())) # Is a goal specified? if hasattr(process.spg, 'goal'): params.update(goal=get_goal(process.spg, params)) if hasattr(process, 'direction'): params.update(direction=process.direction.type()) return params
def parse_example(example): features = Struct( tf.parse_single_example( serialized=example, features=dict(path=tf.FixedLenFeature([], dtype=tf.string), pitch=tf.FixedLenFeature([], dtype=tf.int64), source=tf.FixedLenFeature([], dtype=tf.int64)))) waveform = tf.read_file(features.path) # Decode a 16-bit PCM WAV file to a float tensor. # The -32768 to 32767 signed 16-bit values # will be scaled to -1.0 to 1.0 in float. waveform, _ = audio_ops.decode_wav(contents=waveform, desired_channels=1, desired_samples=64000) waveform = tf.squeeze(waveform) label = index_table.lookup(features.pitch) label = tf.one_hot(label, len(pitches)) pitch = tf.cast(features.pitch, tf.int32) source = tf.cast(features.source, tf.int32) return waveform, label, pitch, source
def __call__(self, xs): if xs not in self.cache: y = 0 for x in xs: y += x self.cache[xs] = Struct(y=y) return self.cache[xs]
def __call__(self, x, **kwargs): if x not in self.cache: m, v = tf.nn.moments(x, [0]) x_cen = (x - m) / (tf.sqrt(v) + 1e-4) y = x_cen * self.sigma + self.mu self.cache[x] = Struct(m=m, v=v, x_cen=x_cen, y=y) return self.cache[x]
def __init__(self, name): update(self, name=name, pos=Struct(x=0.0, y=0.0, z=0.0), simulator=Morse()) inst = getattr(self.simulator, self.name) inst.robot_pose.subscribe(self.setpos)
def move_old(self, inst, a, b, c=0, tolerance=3, speed=1.5, collide=False): #tolerance=1.5, speed=2.0): inst = getattr(self.world, inst) #carry out the move action tolerance = 3 robotloc = self.world.robot1_instance.pos if collide == True: inst.move_collide(x=a, y=b, z=c, tolerance=tolerance, speed=speed) else: inst.move(x=a, y=b, z=c, tolerance=tolerance, speed=speed) newworld = inst.get_world_info() #update the location of all objects in the world for obj in newworld: setattr( getattr(self.world, obj['name']), 'pos', Struct(x=obj['position'][0], y=obj['position'][1], z=obj['position'][2]))
def move(self, inst, a, b, c=0, tolerance=4, speed=1.5, collide=False): #tolerance=1.5, speed=2.0): inst = getattr(self.world, inst) #carry out the move action robotloc = self.world.robot1_instance.pos #print("printing avoidance") #print (self.avoid_obstacle( robotloc.x,robotloc.y , a, b)) #print("pritndone") #print(self.avoid_obstacle( robotloc.x,robotloc.y , a, b)) #print ("collide is") # print (collide) if collide == True: inst.move(x=a, y=b, z=0, tolerance=tolerance, speed=speed) else: for loc in self.avoid_obstacle(robotloc.x, robotloc.y, a, b): inst.move(x=loc[0], y=loc[1], z=0, tolerance=tolerance, speed=speed) newworld = inst.get_world_info() #update the location of all objects in the world for obj in newworld: setattr( getattr(self.world, obj['name']), 'pos', Struct(x=obj['position'][0], y=obj['position'][1], z=obj['position'][2]))
def __call__(self, logits, **kwargs): if logits not in self.cache: mu = tf.sigmoid(logits) noise = tf.random_uniform(tf.shape(logits)) sample = tf.cast(tf.less_equal(noise, mu), np.float32) log_prob = BernoulliLogits.BernoulliLogitsLogProb(logits) self.cache[logits] = Struct(logits=logits, mu=mu, noise=noise, y=sample, sample=sample, log_prob=log_prob) return self.cache[logits]
def make_move(self, move, state): if move not in state.moves: return state # Illegal move has no effect board = state.board.copy(); board[move] = state.to_move moves = list(state.moves); moves.remove(move) return Struct(to_move= ('O' if state.to_move == 'X' else 'X'), utility=self.compute_utility(board, move, state.to_move), board=board, moves=moves)
def __call__(self, mu_sigma, **kwargs): if mu_sigma not in self.cache: mu, sigma = mu_sigma noise = tf.random_normal(tf.shape(mu)) sample = mu + sigma * noise log_prob = DiagonalGaussian.DiagonalGaussianLogProb(mu, sigma) self.cache[mu_sigma] = Struct(mu=mu, sigma=sigma, noise=noise, y=sample, sample=sample, log_prob=log_prob) return self.cache[mu_sigma]
def __init__(self): self.board = [self.NUM_STONE] * self.NUM_SLOT self.board[self.MAX_MANCALA] = 0 self.board[self.MIN_MANCALA] = 0 self.moves = [i for i in range(0, self.NUM_SLOT)] self.initial = Struct(to_move=self.MAX, utility=0, board=self.board, moves=self.moves)
def __call__(self, x, deterministic=False, **kwrags): if (x, deterministic) not in self.cache: if deterministic: mask = None y = x * self.keep_rate + (1. - x) * (1. - self.keep_rate) else: mask = tf.cast(tf.less_equal(tf.random_uniform(tf.shape(x)), self.keep_rate), np.float32) y = x * mask + (1. - x) * (1. - mask) self.cache[x, deterministic] = Struct(mask=mask, y=y) return self.cache[x]
def __init__(self, heaps): no_of_heaps = 0 initial_board_config = {} for heap in heaps: initial_board_config[no_of_heaps] = heap no_of_heaps += 1 self.initial = Struct(to_move='P1', board=initial_board_config)
def make_move(self, move, state): """Given a move and a state, returns a representation of the new state that results after making the move.""" ## return the same state if the move suggested is not part of the legal moves for the state if move not in self.legal_moves(state): return state return Struct(to_move=if_(state.to_move=='P1','P2','P1'), board=move)
def __call__(self, x, deterministic=False, **kwrags): if (x, deterministic) not in self.cache: intermediate_outs = OrderedDict() y = x for layer in self.layers: out = layer(y, deterministic=deterministic, **kwrags) y = out.y intermediate_outs[layer] = out self.cache[x] = Struct(intermediate_outs=intermediate_outs, y=y, out=out) return self.cache[x]
def __init__(self): #Create a list of 14 elements with number of pieces self.board = [self.Num_Piece] * 14 #Set Players' macalas to 0 self.board[self.P0_mancala] = 0 self.board[self.P1_mancala] = 0 self.moves = [0, 1, 2, 3, 4, 5] self.start = Struct(to_move=self.P0, utility=0, board=self.board, moves=self.moves)
def parse_example(example): features = Struct( tf.parse_single_example( serialized=example, features=dict(path=tf.FixedLenFeature([], dtype=tf.string)))) image = tf.read_file(features.path) image = tf.image.decode_jpeg(image, 3) return image
def __call__(self, x, list_of_kwargs=None, **kwargs): if list_of_kwargs is None: list_of_kwargs = [] while len(list_of_kwargs) < len(self.functions): list_of_kwargs.append({}) assert len(list_of_kwargs) == len(self.functions), "more arguments than splits" if x not in self.cache: outs = [] for f, kwargs in zip(self.functions, list_of_kwargs): outs.append(f(x, **kwargs)) self.cache[x] = Struct(outs=outs, y=tuple([out.y for out in outs])) return self.cache[x]
def construct_condImp(): cond = list( params_for_compound(core.m.ed1.eventProcess) ) # Changed so that condition can be compound / cause ("If you pushed the box North, then...") params = updated(self._YN) action = list(params_for_compound(core.m.ed2.eventProcess) ) #params_for_compound(core.m.ed1.eventProcess) action2 = [] cond2 = [] if cond is None or None in action: return None for i in action: action2.append(Struct(i)) for i in cond: cond2.append(Struct(i)) params = [ updated(self._conditional, command=action2, condition=cond2) ] return params
def make_move(self, move, state): """Given a move and a state, returns a representation of the new state that results after making the move.""" """if move not in self.legal_moves(state): print "MALDI: ILLEGAL MOVE" return state""" #print "Player%d is making the move=" % state.to_move, ; print move return Struct(to_move=if_(state.to_move == '1', '2', '1'), board={"heaps": move}) print "MALDI: ILLEGAL MOVE SCENE" return state
def result(self, state, move): if move not in state.moves: print("Illegal Move") return state # Illegal move has no effect board = state.board.copy() cell = self.findTopOfColumn(board, move) board[cell] = state.to_move moves = state.moves.copy() if cell[1] == self.v: moves.remove(move) return Struct(to_move = oppPlayer(state.to_move), board = board, moves = moves, lastCell = cell)
def result(self, state, move): if move not in state.moves: print("Illegal Move") return state # Illegal move has no effect board = state.board.copy() board[move] = state.to_move moves = list(state.moves) moves.remove(move) if move[0] > 1: moves.append((move[0] - 1, move[1])) return Struct(to_move=if_(state.to_move == 'X', 'O', 'X'), utility=self.compute_utility(board, move, state.to_move), board=board, moves=moves)
def make_move(self, move, state): """Given a move and a state, returns a representation of the new state that results after making the move.""" ## if move not in self.legal_moves(state): ## return state ## ## return Struct(to_move=if_(state.to_move=='P1','P2','P1'), board=move) new_board = state.board new_board[move[0] - 1] -= move[1] new_state = Struct(to_move=if_(state.to_move == 'P1', 'P2', 'P1'), board=new_board) return new_state
def __init__(self): #Create 14 elements in a list representing pits in a Mancala layout self.board = [self.stones] * 14 #Setting both Mancalas empty initially self.board[self.Player1_Mancala] = 0 self.board[self.Player2_Mancala] = 0 #Create 6 possible moves self.moves = [0, 1, 2, 3, 4, 5] self.start = Struct(to_move=self.Player1, utility=0, board=self.board, moves=self.moves)
def move(self, inst, a, b, c=0, tolerance=2, speed=1.5, collide=False): #tolerance=1.5, speed=2.0): print("the world was:") pprint(self.world) print("robot is at:") print(a, b) #(self.world.) setattr(getattr(self.world, inst), 'pos', Struct(x=a, y=b, z=c)) print("the world is now:") pprint(self.world)
def __init__(self): self._NTUPLE_T = dict(predicate_type=None, parameters=None, # one of (_execute, _query) return_type='error_descriptor') # Basic executable dictionary self._execute = dict(kind='execute', control_state='ongoing', action=None, protagonist=None, distance=Struct(value=8, units='square'), goal=None, speed = .5, heading=None, #'north', direction=None) # TESTING: Causal dictionary: "Robot1, move the box to location 1 1!" self._cause = dict(kind = 'cause', causer = None, action = None) # Assertion: "the box is red" self._assertion = dict(kind='assertion', # might need to change parameters action=None, protagonist=None, predication=None) self._WH = dict(kind = 'query', protagonist = None, action = None, predication = None, specificWh = None) #Y/N dictionary: is the box red? self._YN = dict(kind = 'query', protagonist=None, action=None, predication=None) self._conditional = dict(kind='conditional', condition=None, # Maybe should be template for Y/N question? command = self._execute)
"""Contains the instantiation to collect data from Schneider Electric EM6400 smartmeter""" from __future__ import print_function import os from smart_meter import SmartMeter from utils import count_num_files, write_csv_header, find_param_numbers from utils import Struct from configuration import DATA_PATH # Change these two lines in accordance with your meter configuration from configuration import _6436 meter_config = Struct(**_6436) meter_config.param_indices = find_param_numbers( meter_config.params_provided, meter_config.params_to_record) # Find the CSV file to write in csv_file_number = count_num_files(DATA_PATH) csv_file_path = os.path.join(DATA_PATH, str(csv_file_number) + ".csv") # Instantiate smartmeter smart_meter = SmartMeter(meter_config.retries, meter_config.com_method, meter_config.baudrate, meter_config.stopbits, meter_config.parity, meter_config.bytesize, meter_config.timeout)
def endpoint(): result = Struct({'api_version':1, 'auth':0}) api_key = request.forms.get('api_key', None) if not api_key or 'api' not in request.query.keys(): log.debug("<- %s" % result) return result u = uc.get_user_by_api_key(api_key) if not u: log.debug("<- %s" % result) return result result.auth = 1 if len(request.query.keys()) == 1: # nothing requested result.last_refreshed_on_time = int(time.time()) log.debug("<- %s" % result) return result if 'groups' in request.GET: result.groups = uc.get_groups_for_user(u) result.feeds_groups = uc.get_feed_groups_for_user(u) log.debug("<- %s" % result) return result if 'feeds' in request.GET: result.feeds = uc.get_feeds_for_user(u) result.feeds_groups = uc.get_feed_groups_for_user(u) log.debug("<- %s" % result) return result if 'unread_item_ids' in request.GET: unread_items = uc.get_unread_items_for_user(u) if len(unread_items): result.unread_item_ids = ','.join(map(str,unread_items)) log.debug("<- %s" % result) return result if 'saved_item_ids' in request.GET: saved_items = uc.get_saved_items_for_user(u) if len(saved_items): result.saved_item_ids = ','.join(map(str,saved_items)) log.debug("<- %s" % result) return result if 'items' in request.GET: ids = [int(i) for i in request.query.get('with_ids','').split(',') if _digits.match(i)] since_id = int(request.query.get('since_id',0)) if len(ids): result.items = uc.get_items_for_user(u, ids) elif since_id: result.items = uc.get_items_for_user_since(u, int(since_id)) result.total_items = uc.get_item_count_for_user(u) log.debug("<- %s" % result) return result # Hot links if 'links' in request.GET: result.links = [] # stubbed out until we can index content log.debug("<- %s" % result) return result # TODO: handle mark, as, id log.debug(request.forms.keys())
settings = Struct({ "loglevel": logging.DEBUG, "content": { "path": "data/main", }, "cache": { "#": "In-worker memory cache", "worker_timeout": 60, "#": "memcache timeout", "cache_timeout": 300, "#":"HTTP Cache control", "cache_control": 3600 }, "theme": "ink", "wiki": { "#" : "Paths", "base" : "/space", "home" : "HomePage", "media" : "/media", "aliases" : "meta/Aliases", "acronyms" : "meta/Acronyms", "interwiki" : "meta/InterWikiMap", "plugins": { }, "markup_overrides": { "text/plain": "text/x-textile" } }, "dropbox": { "#": "Paths to preload", "preload": { "meta" : 100, "blog" : 100, "links": 100 }, "app_key": "********", "app_secret": "********", "root_path": "" } })