Beispiel #1
0
 def fill_database(self):
     template_smartphone = self.env.find_template('smartphone')
     for idx, smartphone in self.smartphones.iterrows():
         fact = template_smartphone.new_fact()
         fact['id'] = clips.Symbol(str(idx))
         fact['valid'] = clips.Symbol("true")
         for key, value in smartphone.iteritems():
             if value is not None:
                 if isinstance(value, float) or isinstance(value, int):
                     fact[key] = value
                 else:
                     fact[key] = clips.Symbol(str(value))
             else:
                 fact[key] = clips.Symbol('unknown')  # needs any value to be excluded when searching
         fact.assertit()
 def setUp(self):
     """sets up the environment to work with."""
     id = 'tenantId'
     self.json_fact = '{"serverId": "serverId", "cpu": 90, "mem": 30, "hdd":70, "net":90}'
     clips.Reset()
     self.e1 = clips.Environment()
     eid = clips.Symbol(id)
     self.e1.Identifier = eid
Beispiel #3
0
class Boolean(Integer):
    PYTHON_TYPE = bool
    PYTHON_TYPE_CHECK = bool
    CLIPS_TYPE = 'SYMBOL'
    TRUE = clips.Symbol('TRUE')
    FALSE = clips.Symbol('FALSE')

    @classmethod
    def _to_clips_value(cls, x):
        if isinstance(x, clips.Symbol):
            return x
        elif x:
            return cls.TRUE
        else:
            return cls.FALSE

    @classmethod
    def _from_clips_value(cls, x):
        return str(x) == 'TRUE'
Beispiel #4
0
def filename_match(_str, _patt):
    from fnmatch import fnmatch
    if fnmatch(_str, _patt):
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')
Beispiel #5
0
def re_match(_str, _patt):
    import re
    if re.match(str(_patt), str(_str)) != None:
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')
Beispiel #6
0
 def env_id():
     return clips.Symbol(sys.argv[1])
def PrepareEnvironment(e, sid):
    eid = clips.Symbol("eid-" + sid)
    ENV_SPECIFIC_FUNCTIONS[eid] = {}
    e.Identifier = eid
Beispiel #8
0
 def put_request_binary(self, template_name, value):
     template = self.env.find_template(template_name)
     fact = template.new_fact()
     fact['has'] = clips.Symbol(str(value))
     fact.assertit()
Beispiel #9
0
 def put_request_multivalue(self, template_name, list_of_values):
     # pass list to multislot
     template = self.env.find_template(template_name)
     fact = template.new_fact()
     fact['multivalue'] = [clips.Symbol(str(i)) for i in list_of_values]
     fact.assertit()
Beispiel #10
0
 def put_request_quantitative(self, template_name, value, operation):
     template = self.env.find_template(template_name)
     fact = template.new_fact()
     fact['value'] = value
     fact['operation'] = clips.Symbol(str(operation))
     fact.assertit()
Beispiel #11
0
 def test(self):
     template_op_s_request = self.env.find_template('request_operating_system')
     fact = template_op_s_request.new_fact()
     fact['multivalue'] = [clips.Symbol('Android')]
     fact.assertit()
def answer(request):
    global next_index, questionLookup, lookupid, env, questionList
    answer = request.POST.get("answer")
    print('the answer is', answer)
    template = env.find_template(lookupid)
    new_fact = template.new_fact()
    new_fact[questionLookup[lookupid]['slot']] = clips.Symbol(answer)
    new_fact.assertit()
    next_index = next_index + 1
    for fact in env.facts():
        print(fact)

    if (next_index < len(questionList)):
        lookupid = questionList[next_index]
        question = questionLookup[lookupid]['question']
        inputType = questionLookup[lookupid]['type']
        options = questionLookup[lookupid]['options']
        return render(request,
                      'question.html',
                      context={
                          'question': question,
                          'type': inputType,
                          'options': options
                      })

    env._agenda.run()
    factList = []
    print('new facts...')
    for fact in env.facts():
        factList.append(fact)
    print(factList)
    for fact in factList:
        if 'qlist' in str(fact):
            string = str(fact)
    opening = string.find('(')
    string = string[opening:-1]
    questionList = string.split()
    print('the questions are')
    print(questionList)

    if (next_index < len(questionList)):
        lookupid = questionList[next_index]
        question = questionLookup[lookupid]['question']
        inputType = questionLookup[lookupid]['type']
        options = questionLookup[lookupid]['options']
        return render(request,
                      'question.html',
                      context={
                          'question': question,
                          'type': inputType,
                          'options': options
                      })
    df = pd.read_csv('result.csv')
    df['tag_list'] = df.apply(lambda x: x['tags'].split("|"), axis=1)
    env._agenda.run()
    factList = []
    print('new facts...')
    for fact in env.facts():
        factList.append(fact)
    print(factList)
    for fact in factList:
        if 'blist' in str(fact):
            string = str(fact)
    opening = string.find('(')
    string = string[opening:-1]
    bucketList = string.split()
    print('the buckets are')
    print(bucketList)
    places = []
    for bucket in bucketList:
        for i in range(len(df)):
            if bucket in df['tag_list'].iloc[i]:
                places.append(df['id'].iloc[i])
    places = np.unique(np.array(places))
    print(places)
    mask = df['id'].isin(places)
    df = df.loc[mask]
    locations = df.to_dict('records')
    for fact in factList:
        if 'noOfDays' in str(fact):
            string = str(fact)
    string = string[:-2]
    dayList = string.split()
    day = int(dayList[-1])
    print('no of days', day)
    json_data = {"days": day, "locations": locations}
    with open('test.json', 'w') as f:
        json.dump(json_data, f)
    try:
        http = httplib2.Http(timeout=40)
        plannerUrl = "http://127.0.0.1:8080/sangam/tour/planItinerary"
        headers = {'Content-type': 'application/json'}
        response, content = http.request(plannerUrl,
                                         'POST',
                                         headers=headers,
                                         body=json.dumps(json_data))
        if content is None or content == "":
            return HttpResponse('Please choose some categories')
        json_response = json.loads(content)

        return render(request,
                      'result.html',
                      context={'list_result': json_response})
    except:
        return render(request, 'error.html')
Beispiel #13
0
def _check_directory(_str):
    from zpp_lib import check_directory
    if check_directory(str(_str)) == True:
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')
Beispiel #14
0
def _check_file_write(_str):
    from zpp_lib import check_file_write
    if check_file_wrie(str(_str)) == True:
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')
Beispiel #15
0
        clips.RegisterPythonFunction(clips_match_re, "py-match-re")


## Extension functions
def _clips_bool(r):
    """
    Returns Clips TRUE or FALSE depending of value of r
    """
    if bool(r):
        return CLIPS_TRUE
    else:
        return CLIPS_FALSE


def clips_match_re(rx, s):
    """
    Check string matches regular expression
    Usage:
        (match-re "^\s+test" ?f)
    """
    logger.error("@@@@ MATCH RE: <%s> <%s> -> %s", rx, s,
                 bool(re.search(rx, s)))
    return _clips_bool(re.search(rx, s))


CLIPS_TRUE = clips.Symbol("TRUE")
CLIPS_FALSE = clips.Symbol("FALSE")

## Initialize environment
CLIPSEnv.prepare()
Beispiel #16
0
def fs_check_directory(_str):
    if globals()["m_globals"]["check_directory"](str(_str)) == True:
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')
Beispiel #17
0
def fs_check_file_write(_str):
    if globals()["m_globals"]["check_file_write"](str(_str)) == True:
        return clips.Symbol('TRUE')
    return clips.Symbol('FALSE')