Exemple #1
0
def test_get_array(Property):
    a, b, c = some_zones()
    val = np.arange(a.manager.size) + 100
    p = Property()
    p[a] = val[a.content]
    arr = p.get_array(a & b)
    assert all(arr == val[(a & b).content])
Exemple #2
0
 def __init__(self, ts, prop_file="", prop=None, solver=None):
     self.transition_sys = ts
     if prop:
         self.prop = prop
     else:
         self.prop = Property(prop_file)
     self.solver = solver
     self.unroller = Unroller()
Exemple #3
0
def test_get_array_default(Property):
    a, b, c = some_zones()
    p = Property()
    p[...] = 99
    arr = p.get_array(a)
    assert len(a) == len(arr) and all(arr == 99)
    arr = p.get_array(b)
    assert len(b) == len(arr) and all(arr == 99)
    arr = p.get_array(c)
    assert len(c) == len(arr) and all(arr == 99)
Exemple #4
0
def test_get_array_multiple_manager(Property):
    a, b, c = some_zones()
    aa, bb, cc = some_zones()
    val = np.arange(a.manager.size) + 100
    vval = np.arange(aa.manager.size) + 200
    p = Property()
    p[a] = val[a.content]
    p[aa] = vval[aa.content]
    arr = p.get_array(a & b)
    assert all(arr == val[(a & b).content])
    arr = p.get_array(aa & bb)
    assert all(arr == vval[(aa & bb).content])
def gamesession_property(id):
    """
    Always check if the user who is doing this,
    is the host
    """
    form = request.get_json()
    user = current_user
    if form is None:
        return api_error("Invalid Request")

    schema = {
                'user_id':{'type':'integer','required':True},
                'propertydef_id':{'type':'integer','required':True},
                'value':{'required':True}
            }
    v = Validator(schema)
    if v.validate(form) is False:
        return api_validation_error(v.errors)   

    gs = GameSession.query.filter_by(id=id,host_id=user.id).first()
    if gs is None:
        return api_error("Unable to find a game session by that ID")

    propdef = PropertyDef.query.filter(PropertyDef.propdef_id == form['propertydef_id']).first()
    if propdef is None:
        return api_error("Unknown property definition")

    player = User.query.filter(User.id == form['player_id']).first()
    if player is None:
        return api_error("Unknown user")

    new_prop = Property()
    new_prop.propdef = propdef
    value_result = new_prop.set_value(form['value'])
    if value_result is False:
        return api_error("Invalid type or mismatching property type.")
    meeple.db.session.add(new_prop)

    gsp = GameSessionProperties()
    gsp.gamesession = gs
    gsp.user = player
    gsp.property = new_prop
    meeple.db.session.add(gsp)
    meeple.db.session.commit()
    return api_package()
Exemple #6
0
def test_set_one_value(Property):
    a, b, c = some_zones()
    val = np.arange(a.manager.size) + 100
    p = Property()
    p[a] = val[a.content]
    assert p._default is None
    assert p._data.keys() == {a}
    assert p._data[a][0] == a
    assert all(p._data[a][1] == val[a.content])
Exemple #7
0
def test_set_multiple_values(Property):
    a, b, c = some_zones()
    val = np.arange(a.manager.size) + 100
    p = Property()
    p[a] = val[a.content]
    p[b] = val[b.content]
    assert p._default is None
    assert p._data.keys() == {a - b, b}
    assert p._data[a - b][0] == a
    assert all(p._data[a - b][1] == val[a.content])
    assert p._data[b][0] == b
    assert all(p._data[b][1] == val[b.content])
Exemple #8
0
 def decorator(funcs):
     fulldoc = doc
     if default != None or generator == None:
         defaulting = defaulting_property(default=default,
                                          null=EMPTY,
                                          mutable_default=mutable)
         fulldoc += "\n\nThis property defaults to %s." % default
     if generator != None:
         cached = cached_property(generator=generator,
                                  initVal=EMPTY,
                                  mutable=mutable)
         fulldoc += "\n\nThis property is generated with %s." % generator
     if check_fn != None:
         fn_checked = fn_checked_property(value_allowed_fn=check_fn)
         fulldoc += "\n\nThis property is checked with %s." % check_fn
     if allowed != None:
         checked = checked_property(allowed=allowed)
         fulldoc += "\n\nThe allowed values for this property are: %s." \
                    % (', '.join(allowed))
     hooked = change_hook_property(hook=change_hook,
                                   mutable=mutable,
                                   default=EMPTY)
     primed = primed_property(primer=primer,
                              initVal=UNPRIMED,
                              unprimeableVal=EMPTY)
     settings = settings_property(name=name, null=UNPRIMED)
     docp = doc_property(doc=fulldoc)
     deco = hooked(primed(settings(docp(funcs))))
     if default != None or generator == None:
         deco = defaulting(deco)
     if generator != None:
         deco = cached(deco)
     if check_fn != None:
         deco = fn_checked(deco)
     if allowed != None:
         deco = checked(deco)
     return Property(deco)
Exemple #9
0
def test_set_default(Property):
    p = Property()
    p[...] = 99
    assert p._default == 99
    assert p._data == {}
Exemple #10
0
def test_base_init(Property):
    p = Property()
    assert p._default is None
    assert p._data == {}
Exemple #11
0
class BMC():
    def __init__(self, ts, prop_file="", prop=None, solver=None):
        self.transition_sys = ts
        if prop:
            self.prop = prop
        else:
            self.prop = Property(prop_file)
        self.solver = solver
        self.unroller = Unroller()

    def load_prop(self):
        """
        Load prop from file
        """
        pass

    def step_invariant(self, t) -> bool:
        """
        Check that property p holds at time t. Does not assume holds at time 1:t-1
        """
        self.solver.clear()  # new query
        # assert that state begins in init set
        self.solver.assert_init(
            self.unroller.at_time_init(self.transition_sys.initial_set))

        # unroll transition relation for time 0 to t
        for j in range(t):
            self.solver.assert_constraints(
                self.unroller.at_time_relation(
                    self.transition_sys.transition_relation, j))

        # assert complement(property) at time t
        self.prop.complement()
        self.solver.mark_outputs(timer_helper(self.prop.outputs,
                                              t))  # mark the outputs
        self.solver.assert_constraints(
            self.unroller.at_time_property(self.prop, t))

        return self.solver.check_sat()  # result, values, stats

    def check_invariant_until(self, time):
        """
        Check invariant property p holds until time t
        """
        # For now "incremental" sort of.
        values, stats = None, None
        for i in range(time):
            result, values, stats = self.step_invariant(
                i)  # checks that property holds at i
            if not (result == Result.UNSAT):
                print("Property may not hold at time ", i)
                return result, values, stats
            else:
                print("Property holds at time ", i)
        return Result.UNSAT, values, stats  ## TODO: make sure this is correct

    def step_invariant_assume(self, t):
        """
        Check that property p holds at time t. Assumes it holds at 1:t-1, for performance
        """
        pass

    def check_invariant_until_assume(self, time):
        """
        Check invariant property p holds until time t, by checking it holds for 1:2, 1:3, ... 1:t
        """
        # For now "incremental" sort of.
        for i in range(time):
            if not self.step_invariant_assume(
                    i):  # checks that property holds at i
                print("Property does not hold at time ", i)
                return Result.SAT
        return Result.UNSAT  ## TODO: make sure this is correct
def storeFullListing(listing_id):
    try:
        #Get thje listingObject via the getListing Function
        listingObject = getListing(listing_id)
        #Once we've obtained the listingObject, store it.
        new_listing_id = StoreListings(listingObject)
        DB_Agent_ID = []
        #If the listing is successfully stored...
        #Check to see if it was advertised by an agency, and if it was, check to see if that agency and its agents have already been stored.
        if 'advertiserIdentifiers' in listingObject and listingObject[
                'advertiserIdentifiers']['advertiserType'] == 'agency':
            new_agency = False
            #Get the Agents who organized the listing and place it into a seperate array.
            agent_listings_ids = listingObject['advertiserIdentifiers'].get(
                'contactIds')
            advertiserObject = listingObject['advertiserIdentifiers']
            if not checkRowExists(
                    f"SELECT 1 FROM agencies WHERE domain_agency_id = {advertiserObject['advertiserId']} "
            ):
                #Create a new Agency Object here.
                agencyObject = getAgency(advertiserObject['advertiserId'])
                #Seperate parts of the agency object into several different dictionaries to make life easier.
                agencyProfile = agencyObject['profile']
                listingAgency = Agency(
                    agencyProfile.get('agencyBanner'),
                    agencyProfile.get('agencyWebsite'),
                    agencyProfile.get('agencyLogoStandard'),
                    agencyProfile['mapLongitude'],
                    agencyProfile['mapLatitude'],
                    agencyProfile['agencyDescription'],
                    agencyProfile['numberForSale'],
                    agencyProfile['numberForRent'], agencyObject['name'],
                    agencyObject['id'],
                    agencyObject['details']['principalName'], agencyObject,
                    agencyObject['contactDetails'],
                    agencyObject['details']['streetAddress1'],
                    agencyObject['details']['streetAddress2'],
                    agencyObject['details']['suburb'], None, None, None,
                    agencyObject['details']['state'],
                    agencyObject['details']['postcode'])
                new_agency_id = listingAgency.storeAgency()
                if new_agency_id is None:
                    raise RuntimeError(
                        "Error in Function storeAgency for Agency " +
                        agencyObject['name'])
                if 'agents' in agencyObject:
                    for agent in agencyObject['agents']:
                        #Check to see if the Agent has already been stored.
                        if not checkRowExists(
                                f"SELECT 1 FROM agents WHERE domain_agent_id = {agent['id']}"
                        ):
                            agentObject = Agent(agent['email'],
                                                agent['firstName'],
                                                agent['lastName'],
                                                agent.get('profileText'),
                                                agent.get('mugshot_url'),
                                                agent['id'], new_agency_id,
                                                agent.get('facebook_url'),
                                                agent.get('twitter_url'),
                                                agent.get('phone'),
                                                agent.get('photo'))
                            new_agent_id = agentObject.storeAgent(False)
                            if new_agent_id is None:
                                raise RuntimeError(
                                    "Error in Function storeAgent for Agent " +
                                    agent['firstName'] + " " +
                                    agent['lastName'])
                            #We only need to do this if there was Agency that created this listing.
                            if agent_listings_ids is not None and agent[
                                    'id'] in agent_listings_ids:
                                DB_Agent_ID.append(new_agent_id)
                        elif agent_listings_ids is not None and agent[
                                'id'] in agent_listings_ids:
                            #Get the ID of the Agent and append it to the DB_Agent_ID Contact
                            cur.execute(
                                """ SELECT a.agent_id 
                                             FROM agents a 
                                             WHERE a.domain_agent_id = %s
                                                AND a.cnewrev IS NULL """,
                                (agent['id']))
                            agent_id = cur.fetchone()
                            DB_Agent_ID.append(agent_id)
                new_agency = True
            #If we are here, that means that the listing was advertised by an Agency.
            if not new_agency:
                #If we didn't save a new_agency, we need to get the agency_id/agent_ids from the database/
                cur.execute(
                    """ SELECT a.agency_id
                                 FROM agencies a
                                 WHERE a.domain_agency_id = %s 
                                        AND a.cnewrev IS NULL """,
                    (advertiserObject['advertiserId'], ))
                new_agency_id = cur.fetchone()[0]
                if agent_listings_ids is not None:
                    for agent in agent_listings_ids:
                        #Agency acquired, now we need to copy the query from before and get the agentids
                        cur.execute(
                            """ SELECT a.agent_id
                                        FROM agents a
                                        WHERE a.domain_agent_id = %s """,
                            (agent, ))
                        holder_value = cur.fetchone()
                        if holder_value is not None:
                            agent_id = holder_value[0]
                        else:
                            #We need to create a new Agent in that case.
                            new_agent_object = getAgent(agent)
                            if new_agent_object is not None:
                                newAgentObject = Agent(
                                    new_agent_object['email'],
                                    new_agent_object['firstName'],
                                    new_agent_object['lastName'],
                                    new_agent_object.get('profileText'),
                                    new_agent_object.get('mugshot_url'),
                                    new_agent_object['agencyId'],
                                    new_agency_id,
                                    new_agent_object.get('facebook_url'),
                                    new_agent_object.get('twitter_url'),
                                    new_agent_object.get('phone'),
                                    new_agent_object.get('photo'))
                                agent_id = newAgentObject.storeAgent(False)
                            else:
                                raise Exception(
                                    "Unable to get New Agent Data for Agent " +
                                    str(agent))

                        DB_Agent_ID.append(agent_id)

            if DB_Agent_ID is None:
                cur.execute(
                    """ INSERT INTO agent_listings( agency_id, listings_id, entered_when )
                                 VALUES( %s, %s, current_timestamp )""",
                    (new_agency_id, new_listing_id))
            else:
                for agent_id in DB_Agent_ID:
                    cur.execute(
                        """ INSERT INTO agent_listings( agency_id, agent_id, listings_id, entered_when )
                                     VALUES( %s, %s, %s, current_timestamp ) """,
                        (new_agency_id, agent_id, new_listing_id))

        #Once the advertiser has been saved, you want to store any linked property details inside the propery table.
        listing_address = listingObject['addressParts']['displayAddress']
        #We don't want to store the address against the listing. Instead, we want to store it to the property that is linked to the listing.
        propertyObject = getPropertyFromListing(listing_address)
        if len(propertyObject) != 0:
            #We need to get the first property object when this returns...
            propertyStore = Property.initFromObject(
                getPropertyInfo(propertyObject[0]['id']))
            new_property_id = propertyStore.saveProperty(False)
            cur.execute(
                """ INSERT INTO properties_listings( property_id, listings_id, entered_when )
                            VALUES( %s, %s, current_timestamp ) """,
                (new_property_id, new_listing_id))
        return True
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
        print("Original Exception Message" +
              (error.__cause__ or error.__context__))
        return False