def test_pclink(self):
   entity1 = Entity()
   entity2 = Entity()
   assert len(entity1.children) == 0
   assert len(entity2.parents) == 0
   entity1.pclink(entity1, entity2)
   assert len(entity1.children) == 1
   assert len(entity2.parents) == 1
 def test_merge_rels(self):
   entity1 = Entity(serves=['a','b','c'])
   entity2 = Entity(serves=['c','d','e'])
   entity1.merge(entity2)
   serves = ['a', 'b', 'c', 'd', 'e']
   assert len(entity1.data['serves']) == 5
   for i in serves:
     assert i in entity1.data['serves']
 def test_merge_existing_pass(self):
   entity1 = Entity()
   entity1.add_identifier('abc')
   entity2 = Entity()
   entity2.add_identifier('abc')
   entity1.merge(entity2)
   assert len(entity1.identifiers()) == 1
   assert entity1.identifiers()[0] == 'abc'
 def test_merge_tags(self):
   entity1 = Entity()
   entity1.set_tag('foo','bar')
   entity2 = Entity()
   entity2.set_tag('cat','dog')
   entity1.merge(entity2)
   tags = entity1.tags()
   assert tags['foo'] == 'bar'
   assert tags['cat'] == 'dog'
 def test_merge(self):
   data = ['abc', 'def']
   entity1 = Entity()
   entity1.add_identifier('abc')
   entity2 = Entity()
   entity2.add_identifier('def')
   entity1.merge(entity2)
   assert len(entity1.identifiers()) == 2
   for i in entity1.identifiers():
     assert i in data
 def test_merge_2(self):
   data = ['abc', 'def']
   entity1 = Entity(
     name='abc',
     geometry=1
   )
   entity1.add_identifier('abc')
   entity2 = Entity(
     name='def',
     geometry=2
   )
   entity2.add_identifier('def')
   entity1.merge(entity2)
   assert entity1.name() == entity2.name()
   assert entity1.geometry() == entity2.geometry()
 def test_onestop_notimplemented(self):
   # requires geohash() to be implemented.
   entity = Entity(**self.expect)
   with self.assertRaises(NotImplementedError):
     entity.id()
   with self.assertRaises(NotImplementedError):
     entity.onestop()
Пример #8
0
 def get_multipart_body(self, body):
     content_type, type_parameters = self.get_header('content-type')
     boundary = type_parameters.get('boundary')
     boundary = '--%s' % boundary
     form = {}
     for part in body.split(boundary)[1:-1]:
         # Parse the entity
         entity = Entity(string=part)
         # Find out the parameter name
         header = entity.get_header('Content-Disposition')
         value, header_parameters = header
         name = header_parameters['name']
         # Load the value
         body = entity.get_body()
         if 'filename' in header_parameters:
             filename = header_parameters['filename']
             if filename:
                 # Strip the path (for IE).
                 filename = filename.split('\\')[-1]
                 # Default content-type, see
                 # http://tools.ietf.org/html/rfc2045#section-5.2
                 if entity.has_header('content-type'):
                     mimetype = entity.get_header('content-type')[0]
                 else:
                     mimetype = 'text/plain'
                 form[name] = filename, mimetype, body
         else:
             if name not in form:
                 form[name] = body
             else:
                 if isinstance(form[name], list):
                     form[name].append(body)
                 else:
                     form[name] = [form[name], body]
     return form
Пример #9
0
    def place_landmark(self):
        player_room = self.get_rooms()[0]

        farest_room = None
        farest_distance = 0

        for room in self.get_rooms():
            if room != player_room:
                distance = self.distance_room_to_room(player_room, room)
                if distance >= farest_distance:
                    farest_distance = distance
                    farest_room = room
            else:
                continue

        center_room_x, center_room_y = farest_room.center

        landmark_component = Landmark(self.dungeon.current_floor + 1)
        landmark = Entity(
            self.dungeon.game,
            center_room_x,
            center_room_y,
            ">",
            libtcod.yellow,
            "Landmark",
            render_order=RenderOrder.LANDMARK,
            landmark=landmark_component,
        )
        self.add_entity(landmark)
 def test_add_identifier(self):
   data = ['abc', 'def']
   entity = Entity()
   for k in data:
     entity.add_identifier(k)
   assert len(entity.identifiers()) == 2
   for i in entity.identifiers():
     assert i in data
 def test_geom_notimplemented(self):
   # requires geohash() and point() to be implemented.
   entity = Entity(**self.expect)
   with self.assertRaises(NotImplementedError):
     entity.geohash()
   with self.assertRaises(NotImplementedError):
     entity.point()
   with self.assertRaises(NotImplementedError):
     entity.bbox()
Пример #12
0
 def create_match(self):
     self.width = random.randint(25, 50)
     self.height = random.randint(25, 50)
     self.tiles = {}
     for y in range(self.height):
         for x in range(self.width):
             self.tiles[(x, y)] = 'grass'
     test_entity = Entity('test_ape', self, (0, 0), Item('bomb', self))
     test_entity.use()
Пример #13
0
def autoload_fields_by_row(entity, row, prefix=''):
    """
    Autoloads entity fields from imported data row.

    entity: core.importhandler.Entity
        entity, where we need add fields and subentities.
    row: dict
        data, loaded from datasource.
    prefix:  string
        prefix to be added to the name.
    """
    def getjson(x):
        try:
            res = json.loads(x)
        except:
            return None
        return res

    from entities import Entity, Field
    for key, val in row.iteritems():
        data_type = 'string'
        if key not in entity.fields:
            if isint(val):
                data_type = 'integer'
            elif isfloat(val):
                data_type = 'float'
            else:
                item_dict = getjson(val)
                if item_dict:
                    entity.fields[key] = Field(
                        {
                            'name': key,
                            'column': key,
                            'transform': 'json'
                        }, entity)
                    if key not in entity.nested_entities_field_ds:
                        json_entity = Entity(dict(name=key, datasource=key))
                        autoload_fields_by_row(json_entity,
                                               item_dict,
                                               prefix='{0}.'.format(key))
                        entity.nested_entities_field_ds[key] = json_entity
                    continue

            if prefix:
                field_config = {
                    'name': prefix + key,
                    'jsonpath': '$.{0}'.format('.'.join(key.split('-')))
                }
            else:
                field_config = {'name': key, 'type': data_type, 'column': key}
            entity.fields[key] = Field(field_config, entity)

    entity.fields_loaded = True
Пример #14
0
    def mockEntity(self, locale):
        """Mock an entity

        Args:
            locale (string): a locale string e.g: en, fr, ...

        Returns:
            A dict representing an entity
        """
        entity = Entity(content=None)
        entity.locale = locale
        return entity
Пример #15
0
def create_bomb(coord=None):
    return Entity(components=OrderedDict([
        (Component.LOCATION,
         components.location.StaticLocationComponent(coord=coord)),
        (Component.EXPLOSION,
         components.ExplosionComponent(power=2.0, time=3.0)),
        (Component.DRAW,
         components.draw.DrawCircleComponent(size=0.8,
                                             color=(255, 0, 0),
                                             color_by_state=OrderedDict([
                                                 ('flashing', (255, 128, 128)),
                                             ]))),
    ]))
Пример #16
0
def old_create_entity_item(game, item_defname, x, y, dict_attributes):
    name = dict_attributes.get("name", "?")
    appearance = dict_attributes.get("char", "?")
    color = dict_attributes.get("color", libtcod.red)
    use_function = dict_attributes.get("use_function", None)
    power = dict_attributes.get("power", 0)
    equippable = dict_attributes.get("equippable", False)
    target = dict_attributes.get("target", None)
    value = dict_attributes.get("value", 30)

    if equippable:
        equippable_slot = equippable.get("slot", EquipmentSlot.NONE)
        equippable_weapon_dmg = equippable.get("weapon_damage", (0, 2))
        equippable_dmg_bonus = equippable.get("physical_power_bonus", 0)
        equippable_might_bonus = equippable.get("might_bonus", 0)
        equippable_hp_bonus = equippable.get("hp_bonus", 0)
        equippable_vitality_bonus = equippable.get("vitality_bonus", 0)
        equippable_dexterity_bonus = equippable.get('dexterity_bonus', 0)
        equippable_armor_bonus = equippable.get('armor_bonus', 0)

        equippable_component = Equippable(
            equippable_slot,
            weapon_damage=equippable_weapon_dmg,
            physical_power_bonus=equippable_dmg_bonus,
            might_bonus=equippable_might_bonus,
            hp_bonus=equippable_hp_bonus,
            vitality_bonus=equippable_vitality_bonus,
            dexterity_bonus=equippable_dexterity_bonus,
            armor_bonus=equippable_armor_bonus)
    else:
        equippable_component = None

    item_component = Item(use_function=use_function,
                          power=power,
                          target_type=target,
                          value=value)
    item = Entity(
        game,
        x,
        y,
        appearance,
        color,
        name,
        item=item_component,
        equippable=equippable_component,
        render_order=RenderOrder.ITEM,
    )

    print("created item is {}, and equipable is {} ".format(
        item.name, item.equippable))
    return item
Пример #17
0
    def body(self):
        # Case 1: nothing
        body = self.soup_message.get_body()
        if not body:
            return {}

        # Case 2: urlencoded
        content_type, type_parameters = self.get_header('content-type')
        if content_type == 'application/x-www-form-urlencoded':
            return decode_query(body)

        # Case 3: multipart
        if content_type.startswith('multipart/'):
            boundary = type_parameters.get('boundary')
            boundary = '--%s' % boundary
            form = {}
            for part in body.split(boundary)[1:-1]:
                # Parse the entity
                entity = Entity(string=part)
                # Find out the parameter name
                header = entity.get_header('Content-Disposition')
                value, header_parameters = header
                name = header_parameters['name']
                # Load the value
                body = entity.get_body()
                if 'filename' in header_parameters:
                    filename = header_parameters['filename']
                    if filename:
                        # Strip the path (for IE).
                        filename = filename.split('\\')[-1]
                        # Default content-type, see
                        # http://tools.ietf.org/html/rfc2045#section-5.2
                        if entity.has_header('content-type'):
                            mimetype = entity.get_header('content-type')[0]
                        else:
                            mimetype = 'text/plain'
                        form[name] = filename, mimetype, body
                else:
                    if name not in form:
                        form[name] = body
                    else:
                        if isinstance(form[name], list):
                            form[name].append(body)
                        else:
                            form[name] = [form[name], body]
            return form

        # Case 4: This is useful for REST services
        # XXX Should just return the body as a string? deserialized?
        return {'body': body}
Пример #18
0
def create_entity(game, base_stats, entity_stats):
    if not entity_stats:
        entity_stats = base_stats

    name = entity_stats.get('name',
                            base_stats.get('name', game_config.DEFAULT_NAME))
    appearance = entity_stats.get(
        'char', base_stats.get('char', game_config.DEFAULT_APPEARANCE))
    color = entity_stats.get(
        'color', base_stats.get('color', game_config.DEFAULT_COLOR))

    entity = Entity(game, 0, 0, appearance, color, name)

    return entity
Пример #19
0
def create_coin(coord=None):
    return Entity(components=OrderedDict([
        (Component.LOCATION,
         components.location.StaticLocationComponent(coord=coord)),
        (Component.HEALTH, components.HealthComponent()),
        (Component.COLLECTABLE, components.CollectableComponent()),
        (
            Component.DRAW,
            components.draw.DrawCircleComponent(
                size=random.choice((0.4, 0.5, 0.6)),
                color=random.choice((
                    (255, 128, 32),  # Copper
                    (255, 255, 255),  # Silver
                    (255, 255, 0),  # Gold
                )))),
    ]))
Пример #20
0
def create_monster(coord=None):
    return Entity(components=OrderedDict([
        (Component.BEHAVIOR,
         components.behavior.AgressiveAIComponent(walk_distance=15,
                                                  attack_distance=10,
                                                  walk_speed=3,
                                                  attack_speed=5)),
        (Component.LOCATION,
         components.location.MovingLocationComponent(coord=coord, speed=3)),
        (Component.HEALTH, components.HealthComponent()),
        (Component.DRAW,
         components.draw.DrawRectangleComponent(size=0.8,
                                                color=(0, 128, 255),
                                                color_by_state=OrderedDict([
                                                    ('chasing', (255, 0, 255)),
                                                ]))),
    ]))
Пример #21
0
def create_player(coord=None):
    return Entity(components=OrderedDict([
        (Component.BEHAVIOR, components.behavior.HumanPlayerInputComponent()),
        (Component.LOCATION,
         components.location.MovingLocationComponent(coord=coord, speed=10.0)),
        ('mining', components.MiningComponent()),
        (Component.COLLECTOR, components.CollectorComponent()),
        (Component.DRAW,
         components.draw.DrawRectangleComponent(size=0.8,
                                                color=(0, 196, 0),
                                                color_by_state=OrderedDict([
                                                    ('colliding', (255, 255,
                                                                   0)),
                                                    ('moving', (128, 255,
                                                                128)),
                                                ]))),
    ]))
Пример #22
0
    def __init__(self, config, is_file=True):
        if is_file:
            if os.path.isfile(config):
                with open(config, 'r') as fp:
                    config = fp.read()
            else:
                raise ImportHandlerException("import handler file '%s' not "
                                             "found" % config)

        if not config:
            raise ImportHandlerException('import handler file is empty')

        try:
            self.data = objectify.fromstring(config)
        except etree.XMLSyntaxError as e:
            raise ImportHandlerException(
                "Valid XML is expected for import handler. "
                "Parse error: {0}".format(e),
                e
            )

        if not self.is_valid():
            raise ImportHandlerException(
                "There is an error in the import handler's XML, "
                "line {0}. {1}".format(self.error.line, self.error.message))

        self.inputs = {}
        self.load_inputs(self.data)

        self.datasources = {}
        self.load_datasources(self.data)

        self.scripts = []
        self.script_manager = ScriptManager()
        self.load_scripts(self.data)

        # Loading import section
        self.entity = Entity(self.data['import'].entity)

        # Predict section
        self.predict = Predict(self.data.predict) if \
            hasattr(self.data, 'predict') else None
Пример #23
0
    def populate_tiles(self):
        mapContainer = [
            x.strip() for x in open('src/map/MAPS.txt', encoding='utf-8-sig')
        ]

        for i in range(int(self.gameMap.mapHeight /
                           self.gameMap.entityHeight)):
            for j in range(
                    int(self.gameMap.mapWidth / self.gameMap.entityWidth)):
                temp = Entity()
                temp.positionWidth = self.gameMap.mapOffSetWidth + (
                    j * self.gameMap.entityWidth)
                temp.positionHeight = self.gameMap.mapOffSetHeight + (
                    i * self.gameMap.entityHeight)

                if mapContainer[i][j] == '1':
                    self.entityContainer.append(temp)
                else:
                    temp.canBePassed = False
                    self.entityContainer.append(temp)
Пример #24
0
    def test_doorbell_unset_locale(self):
        """Test doorbell filter with an entity without locale
        """

        # Test with no locale defined
        content = self.getContent()
        result = self.getExpected('en')
        context = {
            'entity': Entity(content=None),
            'DOORBELL_API': DOORBELL_API,
        }

        rendered = self.renderString(content, context,
                                     self.generateEnvironment())

        self.assertEqual(rendered.strip(), result.strip())

        # Test with locale as None
        context['entity'].locale = None
        rendered = self.renderString(content, context,
                                     self.generateEnvironment())

        self.assertEqual(rendered.strip(), result.strip())
snake = Snake(-40, -40, 100, 2000, 10)
snakes = pygame.sprite.Group()
snakes.add(snake)

# SNAKE HEALTH SET UP
snake_health = Snake(-40, -40, 0, 0, 10)
snakes_health = pygame.sprite.Group()
snakes_health.add(snake_health)

snake_body_collisions = []

# LEVEL / MENU SETUP (LIST OF LAYOUTS)
menus = (
    Layout("Menu", -40, -40, 1,
        (
            Entity("Panel", 80, 120, 400, 280, 400, 280, True, ("Normal", "Title")),
            Entity("Panel", 520, 40, 40, 40, 400, 440, True, ("Normal", "Normal")),
            Entity("Button", 560, 80, 80, 80, 80, 80, True, ("Level", 1)),
            Entity("Button", 680, 80, 80, 80, 80, 80, True, ("Level", 2)),
            Entity("Button", 800, 80, 80, 80, 80, 80, True, ("Level", 3)),
            Entity("Button", 560, 200, 80, 80, 80, 80, True, ("Level", 4)),
            Entity("Button", 680, 200, 80, 80, 80, 80, True, ("Level", 5)),
            Entity("Button", 800, 200, 80, 80, 80, 80, True, ("Level", 6)),
        )
    ),
    Layout("Menu", -40, -40, 1,
        (
            Entity("Panel", 320, 160, 360, 200, 360, 200, True, ("Normal", "Pause")),
            Entity("Button", 360, 200, 120, 40, 120, 40, True, ("Resume", "Normal")),
            Entity("Button", 360, 240, 120, 40, 120, 40, True, ("Restart", "Normal")),
            Entity("Button", 360, 280, 120, 40, 120, 40, True, ("Exit", "Normal"))
 def test_merge_existing(self):
   entity1 = Entity()
   entity1.add_identifier('abc')
   entity2 = Entity()
   entity2.add_identifier('abc')
Пример #27
0
    def read_annotations(self):
        tree = ET.parse(self.xml_file)
        root = tree.getroot()

        # Reading Entities and DocTimeRel
        for e in root.iter('entity'):
            e_type, e_id, string, span, text_id, doctimerel, e_subtype, e_degree, e_polarity, e_ContextualModality, e_Class = None, None, None, None, self.id, None, None, None, None, None, None
            for child in e.getchildren():
                if child.tag == 'id':
                    e_id = child.text
                if child.tag == 'span':
                    span = [(int(s1), int(s2)) for (
                        s1,
                        s2) in [s.split(',') for s in child.text.split(';')]]
                    string = ' '.join(self.text[s1:s2] for (s1, s2) in span)
                if child.tag == 'type':
                    e_type = child.text
                if child.tag == 'properties':
                    for doctime_child in child.iter('DocTimeRel'):
                        doctimerel = doctime_child.text
                    for e_subtype_child in child.iter('Type'):
                        e_subtype = e_subtype_child.text
                    for e_degree_child in child.iter('Degree'):
                        e_degree = e_degree_child.text
                    for e_polarity_child in child.iter('Polarity'):
                        e_polarity = e_polarity_child.text
                    for e_ContextualModality_child in child.iter(
                            'ContextualModality'):
                        e_ContextualModality = e_ContextualModality_child.text
                    for e_Class_child in child.iter('Class'):
                        e_Class = e_Class_child.text

            if e_type == 'EVENT' and doctimerel:
                self.events[e_id] = Entity(e_type,
                                           e_id,
                                           string,
                                           span,
                                           text_id,
                                           doctimerel,
                                           etree=e)
                self.events[e_id].attributes = {
                    'EVENT_Type': e_subtype,
                    'EVENT_Polarity': e_polarity,
                    'EVENT_Degree': e_degree,
                    'EVENT_CONTEXTUAL_MODALITY': e_ContextualModality
                }
                #print(self.events[e_id].attributes)
            if e_type in set(['TIMEX3', 'SECTIONTIME', 'DOCTIME']):
                self.timex3[e_id] = Entity(e_type,
                                           e_id,
                                           string,
                                           span,
                                           text_id,
                                           doctimerel,
                                           etree=e)
                self.timex3[e_id].attributes = {'TIMEX_Class': e_Class}
                #print(self.timex3[e_id].attributes)
        # Reading Relations (TLINKS)
        for r in root.iter('relation'):
            source, target, relation = None, None, None
            for child in r.getchildren():
                if child.tag == 'properties':
                    for properties_child in child:
                        if properties_child.tag == 'Source':
                            if properties_child.text in self.events:
                                source = self.events[properties_child.text]
                            elif properties_child.text in self.timex3:
                                source = self.timex3[properties_child.text]
                        if properties_child.tag == 'Target':
                            if properties_child.text in self.events:
                                target = self.events[properties_child.text]
                            elif properties_child.text in self.timex3:
                                target = self.timex3[properties_child.text]
                        if properties_child.tag == 'Type':
                            relation = properties_child.text

            if relation in set(
                ['CONTAINS', 'BEFORE', 'OVERLAP', 'BEGINS-ON', 'ENDS-ON']):
                tlink_id = source.ID() + '-' + target.ID()
                self.tlinks[tlink_id] = TLink(source, target, relation)

        print(self.id, '\t', 'events:', len(self.events), '\ttimex3:',
              len(self.timex3), 'tlink:', len(self.tlinks))
Пример #28
0
    def setUp(self):
        entities = {}

        hh_link = links.Many2One('household', 'hh_id', 'household')
        mother_link = links.Many2One('mother', 'mother_id', 'person')
        child_link = links.One2Many('children', 'mother_id', 'person')
        persons_link = links.One2Many('persons', 'hh_id', 'person')

        dt = np.dtype([('period', int), ('id', int), ('age', int),
                       ('dead', bool),  ('mother_id', int), ('hh_id', int)])
# TODO: I can't use an EntityContext with an array containing several periods
#      of data
#        persons = array([(2000, 0, 53, False, -1, 0),
#                         (2000, 1, 23, False,  0, 1),
#                         (2000, 2, 20, False,  0, 2),
#                         (2000, 3, 43, False, -1, 3), 
#                         (2001, 0, 54,  True, -1, 0),
#                         (2001, 1, 24, False,  0, 1),
#                         (2001, 2, 21, False,  0, 2),
#                         (2001, 3, 44, False, -1, 0), # they got married 
#                         (2001, 4,  0, False,  2, 2),
        persons = array([(2002, 0, 55,  True, -1, 0),
                         (2002, 1, 25, False,  0, 1),
                         (2002, 2, 22, False,  0, 2),
                         (2002, 3, 45, False, -1, 0),
                         (2002, 4,  1, False,  2, 2)],
                        dtype=dt)
        person = Entity('person',
                        links={'household': hh_link,
                               'mother': mother_link,
                               'children': child_link},
                        array=persons)

        dt = np.dtype([('period', int), ('id', int)])
#        households = array([(2000, 0),
#                            (2000, 1),
#                            (2000, 2),
#                            (2000, 3),
#                             
#                            (2001, 0),
#                            (2001, 1),
#                            (2001, 2),
                            
        households = array([(2002, 0),
                            (2002, 1),
                            (2002, 2)],
                           dtype=dt)
        household = Entity('household',
                           links={'persons': persons_link},
                           array=households)
        entities['person'] = person
        entities['household'] = household
        self.entities = entities

        parse_ctx = {'__globals__': {}, '__entities__': entities,
                     '__entity__': 'person'}
        parse_ctx.update((entity.name, entity.all_symbols(parse_ctx))
                         for entity in entities.itervalues())
        self.parse_ctx = parse_ctx
        self.eval_ctx = EvaluationContext(entities=entities, period=2002,
                                          entity_name='person')
Пример #29
0
TRAY_ICON_PATH = resource_path("assets/tray.ico")

# Load config from yaml
try:
    with open(r'hataskbar.yaml') as file:
        config = yaml.safe_load(file)

        SERVER_URL = config['desktop']['server_url']
        ACCESS_TOKEN = config['desktop']['access_token']
        if 'icon' in config['desktop']:
            TRAY_ICON_PATH = config['desktop']['icon_path']

        # Load entities
        entities = [
            Entity(entity['entity_id'],
                   DeviceType.get_from_string(entity['device_type']),
                   entity['name']) for entity in config['entities']
        ]
except FileNotFoundError:
    print("hataskbar.yaml not found; creating one...")
    with open(r'hataskbar.yaml', 'w') as file:
        file.writelines([
            'desktop:\n', '    server_url: \n', '    access_token: \n',
            'entities:\n',
            '  # TODO: Eventually, I\'ll pull name and device_type from HA\n',
            '  - entity_id: light.desk_lamp\n', '    name: Desk Lamp\n',
            '    device_type: light\n', '  - entity_id: light.other_lamp\n',
            '    name: Other Lamp\n', '    device_type: light\n', ''
        ])
Пример #30
0
 def _place_bomb(self, entity):
     bomb = Entity('bomb', self.game, entity.pos)
     entity.appendages.append(bomb)
     print('DEBUG: Placed bomb')