def post(self): global space args = post_sequence_parser.parse_args() location = args['location'] # print(location) hubs_data = HubD.query.all() space = Space() space.init(hubs_data) sequence_layer = json.loads(args['sequence_layer'].replace("'", '"')) hub = space.getClosestHub(location) hub.updateLayer(sequence_layer["user_id"], sequence_layer["sound_id"], sequence_layer["rhythm"]) location = hub.getLocation() admin = HubD.query.filter_by(location=location).first() admin.sequence = json.dumps(json.loads(json.dumps(hub.getHubObject()))) db.session.commit() object2 = {"location": hub.getLocation()} response = app.response_class(response=json.dumps(object2), status=200, mimetype='application/json') print("POST output: ", object2) sys.stdout.flush() # save_json(str(hub.getLocation()) + ".hub", sequence_layer) return response
def train_translation_matrix(source_file, target_file, dict_file, out_file): """Trains a transltion matrix between the source and target languages, using the words in dict_file as anchor points and writing the translation matrix to out_file Note that the source language file and target language file must be in the word2vec C ASCII format :param source_file: The name of the source language file :param target_file: The name of the target language file :param dict_file: The name of the file with the bilingual dictionary :param out_file: The name of the file to write the translation matrix to """ log.info("Reading the training data") train_data = read_dict(dict_file) #we only need to load the vectors for the words in the training data #semantic spaces contain additional words source_words, target_words = zip(*train_data) log.info("Reading: %s" % source_file) source_sp = Space.build(source_file, set(source_words)) source_sp.normalize() log.info("Reading: %s" % target_file) target_sp = Space.build(target_file, set(target_words)) target_sp.normalize() log.debug('Words in the source space: %s' % source_sp.row2id) log.debug('Words in the target space: %s' % target_sp.row2id) log.info("Learning the translation matrix") log.info("Training data: %s" % str(train_data)) tm = train_tm(source_sp, target_sp, train_data) log.info("Printing the translation matrix") np.savetxt(out_file, tm)
def testExecute(self): from space import Space from player import Player from items.weapon import Weapon from commands.drop_command import DropCommand space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) dropCmd = DropCommand("drop", "Drops an object from inventory to space", player) weapon = Weapon("Dagger", "A trusty blade", 2, 2, 2) player.addToInventory(weapon) player.equip(weapon) #Asserts item in player inventory but not in space self.assertFalse(space.containsItem(weapon), "Space should not have item but does.") inventory = player.getInventory() self.assertTrue(inventory.containsItem(weapon), "Inventory should have item but does not.") #Assert item in space but not in player inventory and not in equipment rawInputMock = MagicMock(return_value="Dagger") with patch('commands.drop_command.raw_input', create=True, new=rawInputMock): dropCmd.execute() self.assertTrue(space.containsItemString("Dagger"), "Space should have item but does not.") inventory = player.getInventory() self.assertFalse(inventory.containsItem(weapon), "Inventory should not have item but does.") equipped = player.getEquipped() self.assertFalse(equipped.containsItem(weapon), "Equipment should not have item but does.")
def __init__(self, races, statistics=None): self._creature_counter = 0 self._races = races self._space = Space(ConfigPhysics.SPACE_SIZE) self._time = 0 self.statistics = statistics for race in races: num_fathers = ConfigPhysics.NUM_FATHERS fathers_locations_i = np.random.choice(ConfigPhysics.SPACE_SIZE, num_fathers) fathers_locations_j = np.random.choice(ConfigPhysics.SPACE_SIZE, num_fathers) ages = np.random.randint(low=0, high=ConfigBiology.BASE_LIFE_EXPECTANCY, size=num_fathers) for n in range(num_fathers): dna = Evolution.mutate_dna(race.race_basic_dna()) self.create_creature(race, id=self.allocate_id(), dna=dna, coord=(fathers_locations_i[n], fathers_locations_j[n]), age=ages[n], parents=None) self.give_food(ConfigPhysics.INITIAL_FOOD_AMOUNT)
def build_src_wrapper(self, source_file, test_wpairs): """ In the _source_ space, we only need to load vectors for the words in test. Semantic spaces may contain additional words. All words in the _target_ space are used as the search space """ source_words = set(test_wpairs.iterkeys()) if self.additional: #read all the words in the space lexicon = set(np.loadtxt(source_file, skiprows=1, dtype=str, comments=None, usecols=(0,)).flatten()) #the max number of additional+test elements is bounded by the size #of the lexicon self.additional = min(self.additional, len(lexicon) - len(source_words)) random.seed(100) logging.info("Sampling {} additional elements".format(self.additional)) # additional lexicon: lexicon = random.sample(list(lexicon.difference(source_words)), self.additional) #load the source space source_sp = Space.build(source_file, lexicon=source_words.union(set(lexicon)), max_rows=1000) else: source_sp = Space.build(source_file, lexicon=source_words, max_rows=1000) source_sp.normalize() return source_sp
def post_space_handler(environ, start_response): """ entry point for posting a new space name to TiddlyWeb """ space_name = environ['tiddlyweb.query']['name'][0] space = Space(environ) try: space.create_space(space_name, environ['tiddlyweb.config']['space']) except (RecipeExistsError, BagExistsError): raise HTTP409('Space already Exists: %s' % space_name) host = environ['tiddlyweb.config']['server_host'] if 'port' in host: port = ':%s' % host['port'] else: port = '' recipe = Recipe('%s_public' % space_name) new_space_uri = '%s/tiddlers.wiki' % recipe_url(environ, recipe) start_response('201 Created', [ ('Location', new_space_uri), ('Content-type', 'text/plain')]) return new_space_uri
def test_on_off(self): space = Space('hello world') test_fun = lambda: 'test' space.on('test', test_fun) self.assertIn('test', space._Space__events) space.off('test', test_fun) self.assertEqual(space._Space__events['test'], [])
def get(self): args = get_sequence_parser.parse_args() location = args['location'] hubs_data = HubD.query.all() space = Space() space.init(hubs_data) hub = space.getClosestHub(location) object = hub.getHubObject() # print(object) sys.stdout.flush() object2 = { "location": hub.getLocation(), "sequence": json.loads(json.dumps(object)) } response = app.response_class(response=json.dumps(object2), status=200, mimetype='application/json') print("GET output: ", object2) sys.stdout.flush() return response
class PackingGame(object): def __init__(self, box_creator=None, enable_give_up=False): self.box_creator = box_creator self.space = Space(10, 10, 10) self.can_give_up = enable_give_up self.next_box = None self.cur_observation = None self.data_name = 'cut_2.txt' if self.box_creator is None: self.box_creator = LoadBoxCreator(data_name=self.data_name) def reset(self): pass def step(self, action): idx = action[0] ratio = self.space.get_ratio() if idx >= self.space.get_action_space(): if self.can_give_up: observation = self.cur_observation reward = ratio done = True info = dict() info['counter'] = len(self.space.boxes) info['ratio'] = ratio return observation, reward, done, info else: raise Exception('out of the boundary of action space') succeeded = self.space.drop_box(self.next_box, idx) if not succeeded: observation = self.cur_observation reward = -1.0 done = True info = dict() info['counter'] = len(self.space.boxes) info['ratio'] = ratio return observation, reward, done, info ratio = self.space.get_ratio() self.box_creator.get_box_size() self.box_creator.generate_box_size() self.next_box = self.box_creator.preview(1)[0] observation = np.array([ *self.space.plain.reshape(shape=(self.space.get_action_space(), )), *self.next_box, ratio ]) self.cur_observation = observation reward = 0.0 done = False info = dict() info['counter'] = len(self.space.boxes) info['ratio'] = ratio return observation, reward, done, info def get_possible_position(self): pass
def testHeal(self): #Heal where healing amount is greater than total amount possible from player import Player from space import Space space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) maxHp = player._maxHp attackAmount = 2 healAmount = 3 player.takeAttack(attackAmount) player.heal(healAmount) self.assertEqual(player._hp, maxHp, "Healing testcase #1 failed.") #Heal where healing amount is less than total amount possible from player import Player from space import Space space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) maxHp = player._maxHp attackAmount = 3 healAmount = 2 player.takeAttack(attackAmount) player.heal(healAmount) self.assertEqual(player._hp, maxHp - 1, "Healing testcase #2 failed.")
def __init__(self): self.name = 'World' Space.__init__(self) if farm_config.DEBUG_WIN: debug_console.get()._print("World created.") self.house = House(1, 1, HOUSE_GRAPHIC, self) self.ship_box = Shipbox(4, 12, SHIP_BOX_GRAPHIC, self) self.pond = Pond(GAME_WIN_SIZE_Y - 5, GAME_WIN_SIZE_X - 16, POND_GRAPHIC, self ) self.seed(Cave_Entrance, CAVE_GRAPHICS_DIR + 'entrance_external', 1) self.seed(Tree, 'GRAPHICS/tree', NUMBER_TREES) self.seed(Rock, 'GRAPHICS/rock', NUMBER_ROCKS) self.seed(Bush, 'GRAPHICS/bush', NUMBER_BUSHES) if farm_config.DEBUG_WIN: debug_console.get()._print("World populated.") self.sort_contents() if farm_config.DEBUG_WIN: debug_console.get()._print("World contents sorted.")
def testExecute(self): from space import Space from player import Player from items.item import Item from commands.pick_up_command import PickUpCommand space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) item = Item("Dagger", "A trusty blade", 2) pickUpCmd = PickUpCommand("pick up", "Picks up an object", player) space.addItem(item) #Assert item in space but not in inventory and not in equipment self.assertTrue(space.containsItem(item), "Space should have item but does not.") inventory = player.getInventory() self.assertFalse(inventory.containsItem(item), "Player should not have item but does in inventory.") equipped = player.getEquipped() self.assertFalse(equipped.containsItem(item), "Player should not have item but does in equipment.") #Assert item in player inventory but not in space and not in equipment rawInputMock = MagicMock(return_value="Dagger") with patch('commands.pick_up_command.raw_input', create=True, new=rawInputMock): pickUpCmd.execute() self.assertFalse(space.containsItem(item), "Space should not have item but does.") equipped = player.getEquipped() self.assertFalse(equipped.containsItem(item), "Player should not have item in equipment.") inventory = player.getInventory() self.assertTrue(inventory.containsItem(item), "Player should have item but does not.")
def createGarage(garage): log("Storing garage entity: " + garage.name) client = getClient() entity = datastore.Entity(_load_key(client, _GARAGE_ENTITY, garage.name)) entity['Name'] = garage.name entity['numSpots'] = garage.numSpots entity['numHandicapSpots'] = garage.numHandicapSpots entity['Address'] = garage.address entity['Phone'] = garage.phone entity['Owner DL'] = garage.ownerDL # entity['user_id'] = garage.user_id # Added code for coords entity['latitude'] = garage.lat log('latitude ' + garage.lat) entity['longitude'] = garage.long log('longitude ' + garage.long) log('putting entity') client.put(entity) log('Saved new Garage. name: %s' % garage.name) totalNumSpots = garage.numHandicapSpots + garage.numSpots for i in range(0, totalNumSpots): log('creating new spot') newSpot = None if i < garage.numHandicapSpots: newSpot = Space(garage.name, i, True) else: newSpot = Space(garage.name, i, False) spaceData.createSpace(newSpot)
def train_wrapper(seed_fn, source_fn, target_fn, reverse=False, mx_path=None, train_size=5000): logging.info("Training...") seed_trans = read_dict(seed_fn, reverse=reverse) #we only need to load the vectors for the words in the training data #semantic spaces contain additional words source_words = set(seed_trans.iterkeys()) target_words = set().union(*seed_trans.itervalues()) source_sp = Space.build(source_fn, lexicon=source_words) source_sp.normalize() target_sp = Space.build(target_fn, lexicon=target_words) target_sp.normalize() logging.info("Learning the translation matrix") tm, used_for_train = train_tm(source_sp, target_sp, seed_trans, train_size) mx_path = default_output_fn(mx_path, seed_fn, source_fn, target_fn,) logging.info("Saving the translation matrix to {}".format(mx_path)) np.save('{}.npy'.format(mx_path), tm) pickle.dump(used_for_train, open('{}.train_wds'.format(mx_path), mode='w')) return tm, used_for_train
def create_room_elements(room_name): room_space = Space({'tiddlyweb.store': store}) this_room = ROOM.replace('ROOMNAME', room_name) this_room = json.loads(this_room) room_space.create_space(this_room)
def delete(space_name, application_name): """$ poof delete <space> [<application>]""" if application_name != None: application = Application() application.delete(space_name, application_name) else: the_space = Space() the_space.delete(space_name)
def get_my_space(self): space = Space() ifs = netifaces.interfaces() for if_ in ifs: addrs = netifaces.ifaddresses(if_) if 2 in addrs and addrs[2][0]['addr'][:2] == '1.': s = Space(match={'ipv4_dst': [addrs[2][0]['addr'], '255.255.255.0']}) space.plus(s) return space
def __init__(self, box_creator=None, enable_give_up=False): self.box_creator = box_creator self.space = Space(10, 10, 10) self.can_give_up = enable_give_up self.next_box = None self.cur_observation = None self.data_name = 'cut_2.txt' if self.box_creator is None: self.box_creator = LoadBoxCreator(data_name=self.data_name)
def main(): loader = Loader() camera = Camera(width=256, height=256) light = Camera() light.move(np.array([0, 0, -100])) visualizer = Visualizer() space = Space(camera, light, visualizer, loader) space.load(MODEL) window = Window(space)
def test_append(self): space = Space('hello world') space.append('foo', 'bar') space.set('foo2', 'bar') space.append('foo', 'two') self.assertEqual(space.get('foo'), 'bar') self.assertEqual(space.length(), 4)
class GravApp(App): def build(self): self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.draw_fps = True self.fps = Fps() self.time = 0. self.last_time = 0. self.time_mult = 1. Clock.schedule_interval(self.update, 0) self.root = Space() return self.root def update(self, dt): # self.dt = dt self.time += dt * self.time_mult if abs(self.time - self.last_time) >= abs(self.time_mult): self.last_time = self.time print Clock.get_fps() self.root.update(dt * self.time_mult, self.time) if self.draw_fps: self.fps.update(dt) self.fps.draw(self.root) def _keyboard_closed(self): self._keyboard.unbind(on_key_down=self._on_keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): # print keycode if keycode[1] == 'd' or keycode[0] == 100: self.root.show_acc = not self.root.show_acc self.root.show_vel = not self.root.show_vel if keycode[1] == 'escape' or keycode[0] == 27 or \ keycode[1] == 'q' or keycode[0] == 113: App.get_running_app().stop() if keycode[1] == 'left' or keycode[0] == 276: self.time_mult -= 0.1 print('{:.1f} mult'.format(self.time_mult)) if keycode[1] == 'right' or keycode[0] == 275: self.time_mult += 0.1 print('{:.1f} mult'.format(self.time_mult)) if keycode[1] == 'down' or keycode[0] == 274: self.root.set_vel([0.]) return True
def build_space(self): self.__rules_group_by_output = {} for rule in self.rules: if rule['action']['output'] not in self.__rules_group_by_output: self.__rules_group_by_output[rule['action']['output']] = Space() self.__rules_group_by_output[rule['action']['output']].plus(Space(match=rule['match'])) self.add_ec([platform.node()], self.get_my_space()) log('finish build ec') log(json.dumps(self.rules))
def main(): print('Reading ...') start = datetime.datetime.now() # data source name data_source_name = 'better-ball.d' # shading type: # 0 - no shading (framework) # 1 - constant shading # 2 - Gouraud shading # 3 - Phong shading shading = 3 world_space = Space() world_space.append_by_file(data_source_name + '.txt') # geometry data camera = Camera() camera.set_by_file(data_source_name + '.camera.txt') # camera profile light = Light() light.set_by_file(data_source_name + '.light.txt') # light profile material = Material() material.set_by_file(data_source_name + '.material.txt') # material profile illumination = Illumination() illumination.set(camera, light, material, shading) display = Display() display.set(800) # change window size cost = datetime.datetime.now() - start print('Finish. (cost = ' + str(cost) + ')\n') print('Calculating: transform ...') start = datetime.datetime.now() view_space = copy.deepcopy(world_space) view_space.transform(world_to_view, camera) screen_space = copy.deepcopy(view_space) screen_space.transform(view_to_screen, camera) device_space = copy.deepcopy(screen_space) device_space.transform(screen_to_device, display) cost = datetime.datetime.now() - start print('Finish. (cost = ' + str(cost) + ')\n') window = Window() window.set(world_space, device_space, illumination, display) window.show()
def __init__(self, clear): self.clear_term = clear self.space = Space() enterprise = Ship('Enterprise', 'Cpt. Pickard') enterprise.weapons = [ Weapon(name='Burst Laser II', dmg=(4, 6), acc=60), Weapon(name='Burst Laser II', dmg=(4, 6), acc=60) ] self.space.ships.append(enterprise) self.space.ships.append(Ship('Orion', 'Cpt. Clark')) self.space.ships.append(Ship('Deathstar', 'Darth Vader')) print self.space.ships
def addproject(args): """make a project space. <project_name>""" if len(args) != 1: print >> sys.stderr, ('usage: twanager addproject <project_name>') #replace PROJECT_NAME with the actual name of the project this_project = PROJECT.replace('PROJECT_NAME', args[0]) this_project = json.loads(this_project) #create the space project_space = Space({'tiddlyweb.store': get_store(config)}) project_space.create_space(this_project)
def test_trigger(self): space = Space('hello world') class Count(): def __init__(self): self.count = 0 def incr(self): self.count += 1 c = Count() space.on('change', c.incr) space.trigger('change') self.assertEqual(c.count, 1)
def reset(self): self.box_creator.reset() self.space = Space(10, 10, 10) self.box_creator.generate_box_size() self.next_box = self.box_creator.preview(1)[0] self.temp_box = deepcopy(self.next_box) self.cur_observation = np.array([ *np.reshape(self.space.plain, newshape=(self.space.get_action_space(), )), *self.next_box, self.space.get_ratio() ]) return np.append(self.cur_observation, self.get_possible_position(self.adjust_flag))
def eval_js_vm(js): a = ByteCodeGenerator(Code()) s = Space() a.exe.space = s s.exe = a.exe d = pyjsparser.parse(js) a.emit(d) fill_space.fill_space(s, a) # print a.exe.tape a.exe.compile() return a.exe.run(a.exe.space.GlobalObj)
class GravApp(App): time = NumericProperty(0) def build(self): Clock.schedule_interval(self.update, 0) self.root = Space() self.fps = Fps() return self.root def update(self, dt): self.dt = dt self.time += dt self.root.update(dt, self.time) self.fps.update(dt) self.fps.draw(self.root)
def __init__(self): self.spaces = [] self.communityChest = [] self.chance = [] # Create the players self.players = [ Player("Player 1"), Player("Player 2"), Player("Player 3") ] # Read spaces data from JSON with open('spaces.json') as space: spacesData = json.load(space) # Generate spaces for spaceData in spacesData: self.spaces.append( Space(spaceData["id"], spaceData["color"], spaceData["name"], spaceData["cost"], spaceData["rent"], SpaceType[spaceData["type"]])) # Generate community chest cards for i in range(17): self.communityChest.append(CommunityChest(i)) # Shuffle community chest deck random.shuffle(self.communityChest) # Generate chance cards for i in range(16): self.chance.append(Chance(i)) # Shuffle chance deck random.shuffle(self.chance)
def enter(): clear_canvas() global soldier, space, tutorial soldier = Soldier() space = Space() tutorial = Tutorial()
def test_wrapper(self): self.load_tr_mx() logging.info('The denominator of precision {} OOV words'.format( 'includes' if self.args.coverage else "doesn't include")) test_wpairs = read_dict(self.args.seed_fn, reverse=self.args.reverse, needed=1000 if self.args.coverage else -1, exclude=self.exclude_from_test) source_sp = self.build_src_wrapper(self.args.source_fn, test_wpairs) target_sp = Space.build(self.args.target_fn) target_sp.normalize() test_wpairs, _ = get_invocab_trans(source_sp, target_sp, test_wpairs, needed=1000) """ #turn test data into a dictionary (a word can have mutiple translation) gold = collections.defaultdict(set, test_wpairs) for sr, tg in test_wpairs: gold[sr].add(tg) """ logging.info( "Mapping all the elements loaded in the source space") mapped_source_sp = apply_tm(source_sp, self.tr_mx) if hasattr(self.args, 'mapped_vecs') and self.args.mapped_vecs: logging.info("Printing mapped vectors: %s" % self.args.mapped_vecs) np.savetxt("%s.vecs.txt" % self.args.mapped_vecs, mapped_source_sp.mat) np.savetxt("%s.wds.txt" % self.args.mapped_vecs, mapped_source_sp.id2word, fmt="%s") return score(mapped_source_sp, target_sp, test_wpairs, self.additional)
def build(cls, core_space, **kwargs): """ Reads in data files and extracts the data to construct a semantic space. If the data is read in dense format and no columns are provided, the column indexing structures are set to empty. Args: data: file containing the counts format: format on the input data file: one of sm/dm rows: file containing the row elements. Optional, if not provided, extracted from the data file. cols: file containing the column elements Returns: A semantic space build from the input data files. Raises: ValueError: if one of data/format arguments is missing. if cols is missing and format is "sm" if the input columns provided are not consistent with the shape of the matrix (for "dm" format) """ sp = Space.build(**kwargs) mat = sp._cooccurrence_matrix id2row = sp.id2row row2id = sp.row2id return PeripheralSpace(core_space, mat, id2row, row2id)
def pvv_server(self): ip_port = ('0.0.0.0', PORT) server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind(ip_port) while True: data, client = server.recvfrom(BUF_SIZE) if client[0] == self.ip: # ignore broadcast from myself continue print 'starttime: %d' % int(time.time() * 1000000) print('recv: ', len(data), client[0], data) msg = json.loads(data) if 'type' in msg and msg['type'] == 'request': for property in self.pm.entries: msg_to_send = { 'protocol': 'p1', # TODO: consider different protocol 'property': property, 'space': self.pm.union_space(property) } self.unicast(json.dumps(msg_to_send), self.get_node_by_ip(client[0])['ip']) else: space = Space(msg['space']) changed = self.cal_pm(msg['protocol'], msg['property'], space, self.get_node_by_ip(client[0])['name']) if changed: msg_to_send = { 'protocol': msg['protocol'], 'property': msg['property'], # 'action': msg['action'], 'space': self.pm.union_space(msg['property']) } self.flood(json.dumps(msg_to_send), client[0]) print 'endtime: %d' % int(time.time() * 1000000)
def testLevelUp(self): from player import Player from space import Space from math import floor import constants space = Space("Shire", "Home of the Hobbits.") player = Player("Frodo", space) #Increase player experience, run _updateLevel, and test if stats change to where they're intended originalExperience = player._experience experienceIncrease = 1000 player._experience = originalExperience + experienceIncrease player._updateLevel() self.assertEqual(player._experience, originalExperience + experienceIncrease, "Player experience did not increase.") self.assertEqual(player._level, floor(player._experience / 20) + 1, "Player did not level up.") self.assertEqual(player._maxHp, player._level * constants.HP_STAT, "Player Hp did not increase.") self.assertEqual(player._attack, player._level * constants.ATTACK_STAT, "Player damage did not increase.")
def __init__(self): #Set up the Board with SPACES! self.__myboard = [] for curY in range(self.maxY): curList = [] self.__myboard.append( [Space(curX, curY) for curX in range(self.maxX)])
def __init__(self, frame_width, frame_height, lim_x=1000, lim_y=1000, wrap_x=True, wrap_y=False, inc_x=1, inc_y=1): if frame_width > lim_x or frame_height > lim_y: raise Exception("Frame size smaller than x or y limits") self._space = Space(frame_width, frame_height, lim_x, lim_y) self._wrap_x = wrap_x self._wrap_y = wrap_y self._inc_x = inc_x self._inc_y = inc_y
def __init__(self, spaces): self._ticket_count = 0 self._total_spaces = spaces self._spaces = {} for index in range(1, self._total_spaces + 1): self._spaces[index] = Space(index)
def testInit(self): from player import Player from space import Space from cities.inn import Inn from cities.city import City testinn = Inn("Chris' testing Inn", "Come test here", "hi", 5) testcity = City("Test City", "testing city", "hello to testing city. see Chris' Inn", testinn) space = Space("Shire", "Home of the Hobbits.", city=testcity) player = Player("Frodo", space) #player's health is lowest possible to be alive player._hp = 1 #player's money is equal to 10 player._money = 10 #Player chooses to stay at the inn rawInputMock = MagicMock(return_value=1) with patch('cities.inn.raw_input', create=True, new=rawInputMock): testinn.execute(player) #player's money should decrease by the cost of the inn, in our case 5. self.assertEqual(player._money, 5, "Player's money not decreased by correct amount.") #player's health should increase to maximum. self.assertEqual(player._hp, player._maxHp, "Player's health not increased to full health.")
def testInit(self): from player import Player from space import Space from cities.square import Square from cities.city import City testsquare = Square( "Chris' testing Square", "testing square", "Come test here", { "Master Wang": "I am Master Wang, creator various things in this Lord of the Rings game", "Miles": "Hello, I am Miles, the cookie legend" }) testcity = City("Test City", "testing city", "hello to testing city. see Chris' Square", testsquare) space = Space("Shire", "Home of the Hobbits.", city=testcity) player = Player("Frodo", space) #Player chooses to: 1(talk), to Master Wang, 1(talk), to Miles, 2(Leave) the square rawInputMock = MagicMock(side_effect=[ "1", "Master Wang", "1", "Miles", "gobbledigook", "2" ]) with patch('cities.square.raw_input', create=True, new=rawInputMock): testsquare.execute(player) #if the code gets here, then it hasn't crashed yet; test something arbitrary here, like player's money. self.assertEqual(player._money, 20, "Why does player's money not equal 20?")
def new_space(self, constructor_args): """ Creates a new Space. :param constructor_args: dictionary with following structure:: {\ "space_name" : "example.py live_activity_group_name",\ "space_description" : "created by example.py",\ "live_activity_groups" : [{"live_activity_group_name" : "Media Services"}]\ } """ live_activity_group_ids = self._translate_live_activity_groups_names_to_ids( constructor_args['live_activity_groups']) unpacked_arguments = {} unpacked_arguments['space.name'] = constructor_args['space_name'] unpacked_arguments['space.description'] = constructor_args[ 'space_description'] unpacked_arguments['_eventId_save'] = 'Save' unpacked_arguments['liveActivityGroupIds'] = live_activity_group_ids if not self._api_object_exists(Space, constructor_args, self.get_space): space = Space().new(self.uri, unpacked_arguments) self.log.info("Master:new_space:%s" % space) return space else: return []
def build(self): self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.draw_fps = True self.fps = Fps() self.time = 0. self.last_time = 0. self.time_mult = 1. Clock.schedule_interval(self.update, 0) self.root = Space() return self.root
def main(): from space import Space import fill_space from pyjsparser import parse import json a = ByteCodeGenerator(Code()) s = Space() fill_space.fill_space(s, a) a.exe.space = s s.exe = a.exe con = get_file_contents('internals/esprima.js') d = parse(con+(''';JSON.stringify(exports.parse(%s), 4, 4)''' % json.dumps(con))) # d = parse(''' # function x(n) { # log(n) # return x(n+1) # } # x(0) # ''') # var v = 333333; # while (v) { # v-- # # } a.emit(d) print a.declared_vars print a.exe.tape print len(a.exe.tape) a.exe.compile() def log(this, args): print args[0] return 999 print a.exe.run(a.exe.space.GlobalObj)
def test_multiline(self): space = Space('my multiline\n string') self.assertEqual(space.get('my'), 'multiline\nstring') space2 = Space('my \n \n multiline\n string') self.assertEqual(space2.get('my'), '\n\nmultiline\nstring') space3 = Space('brave new\n world') self.assertEqual(space3.get('brave'), 'new\nworld', 'ml value correct') self.assertEqual(str(space3), 'brave new\n world\n', 'multiline does not begin with nl') space4 = Space('brave \n new\n world') self.assertEqual(space4.get('brave'), '\nnew\nworld', 'ml begin with nl value correct')
def __init__(self, clear): self.clear_term = clear self.space = Space() enterprise = Ship("Enterprise", "Cpt. Pickard") enterprise.weapons = [ Weapon(name="Burst Laser II", dmg=(4, 6), acc=60), Weapon(name="Burst Laser II", dmg=(4, 6), acc=60), ] self.space.ships.append(enterprise) self.space.ships.append(Ship("Orion", "Cpt. Clark")) self.space.ships.append(Ship("Deathstar", "Darth Vader")) print self.space.ships
def store(key, message, in_path, out_path): epub = Epub() epub.expand(in_path) space = Space(epub) binary_message = ''.join([format(ord(x), '0'+str(CHAR_BIT_SIZE)+'b') for x in message]) message_size = format(len(binary_message), 'b') header_size = format(len(message_size), '0'+str(HEADER_BIT_SIZE)+'b') bits_to_write = header_size + message_size + binary_message if (len(space)) < len(bits_to_write): print 'Error, not enough space on the epub file' line_order = LineOrder(key, len(space)) add_noise(space) for bit in bits_to_write: space[line_order.next()] = (bit == '1') space.commit() epub.contract(out_path)
class game: def __init__(self, clear): self.clear_term = clear self.space = Space() enterprise = Ship("Enterprise", "Cpt. Pickard") enterprise.weapons = [ Weapon(name="Burst Laser II", dmg=(4, 6), acc=60), Weapon(name="Burst Laser II", dmg=(4, 6), acc=60), ] self.space.ships.append(enterprise) self.space.ships.append(Ship("Orion", "Cpt. Clark")) self.space.ships.append(Ship("Deathstar", "Darth Vader")) print self.space.ships def run(self): while len(self.space.ships) > 1: ship1 = self.space.ships[0] ship2 = self.space.ships[1] self.space.combat(ship1, ship2) if not ship1.getAlive(): self.space.ships.remove(ship1) if not ship2.getAlive(): self.space.ships.remove(ship2)
def __init__(self): if farm_config.DEBUG_WIN: debug_console.get()._print("Cave created.") self.name = 'Cave' Space.__init__(self) # Used only by Astar self.closed_list = [] self.seed(Room, CAVE_GRAPHICS_DIR + 'room', 5) if farm_config.DEBUG_WIN: debug_console.get()._print("Rooms seeded.") entrance = Entrance(0, 10, CAVE_GRAPHICS_DIR + 'entrance_internal', self) rooms = self.contents['Room'] self.Astar = RoomWrapper(Astar) halls = self.Astar(rooms, self.closed_list) if farm_config.DEBUG_WIN: debug_console.get()._print("%d halls found." % len(halls)) for coor in halls: Hall.create(coor[0], coor[1], CAVE_GRAPHICS_DIR + 'hall', self) if farm_config.DEBUG_WIN: debug_console.get()._print("Halls created.")
def testMultiLine(self): string = 'user\n\ name Aristotle\n\ admin false\n\ stage\n\ name home\n\ domain test.test.com\n\ pro false\n\ domains\n\ test.test.com\n\ images\n\ blocks\n\ users\n\ stage home\n\ pages\n\ home\n\ settings\n\ data\n\ title Hello, World\n\ block1\n\ content Hello world\n' space = Space(string) self.assertEqual(space.get('domains test.test.com pages home settings data title'), 'Hello, World', 'Multiline creation shuold be OK')
def __init__(self): """Initialize game engine.""" pygame.init() self.screen = pygame.display.set_mode(Data.RESOLUTION) pygame.display.set_caption('PyFighter [using PyGame {0}]'.format(Data.PYGAME_INFO)) self.clock = pygame.time.Clock() self.space = Space() self.story = _Story() self.audio = _Audio() self.player = pygame.sprite.GroupSingle(Player()) self.aliens = pygame.sprite.Group() self.beams = pygame.sprite.Group() self.timer = 0
def testDeepCopy(self): space1 = Space('hello world') space2 = space1.clone() self.assertEqual(space2.get('hello'), 'world', 'Clone should work') space2.set('hello', 'mom') self.assertEqual(space1.get('hello'), 'world', 'Clone makes deep copy') space3 = space1 space3.set('hello', 'dad') self.assertEqual(space1.get('hello'), 'dad', '= makes shallow copy') space1.set('anotherSpace', Space('123 456')) self.assertEqual(space3.get('anotherSpace 123'), '456')
def testLength(self): space = Space('list\nsingle value') self.assertEqual(space.length(), 2, 'space should have 2 names') # 'name' here means 'key' self.assertTrue(isinstance(space.get('list'), Space), 'name without a trailing space should be name')
def testClear(self): space = Space('Hello world') self.assertEqual(space.length(), 1) self.assertTrue(isinstance(space.clear(), Space), 'clear returns Space so chainable') self.assertEqual(space.length(), 0)
def testClearWithSpaceArgument(self): space = Space("Hellow world") space.clear("hey there") self.assertEqual(space.length(), 1) self.assertEqual(space.get('hey'), 'there', 'Clear with a Space argument should deep copy the argument Space')
def testPathNotExist(self): space = Space('Hello\n one 1\n two 2') self.assertEqual(space.get('Hello world one'), None, 'Should return None if path does not exist')
print "Loading the translation matrix" tm = np.loadtxt(tm_file) print "Reading the test data" test_data = read_dict(test_file) # in the _source_ space, we only need to load vectors for the words in test. # semantic spaces may contain additional words, ALL words in the _target_ # space are used as the search space source_words, _ = zip(*test_data) source_words = set(source_words) print "Reading: %s" % source_file if not additional: source_sp = Space.build(source_file, source_words) else: # read all the words in the space lexicon = set(np.loadtxt(source_file, skiprows=1, dtype=str, comments=None, usecols=(0,)).flatten()) # the max number of additional+test elements is bounded by the size # of the lexicon additional = min(additional, len(lexicon) - len(source_words)) # we sample additional elements that are not already in source_words random.seed(100) lexicon = random.sample(list(lexicon.difference(source_words)), additional) # load the source space source_sp = Space.build(source_file, source_words.union(set(lexicon))) source_sp.normalize()
fpsClock = pygame.time.Clock() # Turn on development mode dev = True window_size = (640, 480) window = pygame.display.set_mode(window_size) pygame.display.set_caption("PyGame test") background = pygame.Color(10, 10, 10) greenColor = pygame.Color(128, 128, 128) basic_font = pygame.font.SysFont(None, 20) hero = Hero(window_size) space = Space((10000, 10000)) parallax = Space((7071, 7071)) # surface_objects = [hero, space] # star = Star(10, (10,10)) # Make a shitload of stars stars = [] starcount = 10000 for i in range(starcount): if i < 0.8 * starcount: stars.append(Star(randint(1, 3), (randint(0, 10000), randint(0, 10000)))) stars[i].render(parallax.surf())