def assert_parsed_code_equals_result(self): parsed_result = parse(InputPort(self.code)) if isinstance(parsed_result, list): self.assertListEqual(parsed_result, self.result) else: self.assertEqual(parsed_result, self.result)
def __init__(self, config): self.config = config self.content = parse() self.rules = self.content["rules"] self.data = dict.fromkeys(string.ascii_uppercase, 0) self.queries = dict.fromkeys(list(self.content["queries"]), 0) self.facts = dict.fromkeys(list(self.content["facts"]), 1) for i in self.facts: self.data[i] = 1 self._is_valid()
def parseRules(self): ''' parse the rules file as input for us to use. For simplicity of parsing, the format of the rules should be of the follows: DO/DONT $deviceMethod THE $device AFTER/FOR $duration SECONDS/MINUTES/HOURS WHEN $attribute OF $devicename IS $value FOR/AFTER $duration SECONDS/MINUTES/HOURS AND $attri..... DO/DONT $deviceMethod .... WHEN LOCATION MODE IS $mode DO/DONT SET LOCATION MODE TO $mode WHEN ... where we use the capital letters to distinguish tokens from names Note we can't have DO SOMETHING FOR $duration or DONT DO SOMETHING AFTER $duration Since they can be easily converted to other rules by our syntax. For Time duration, the smallest unit is seconds, the biggest unit is hours. ''' with open(self.rules, 'r') as rules: for lines in rules: req, conds = parse(lines) (do, method, device) = req[ 0] #in case for location mode, device = Mode, method = 'location' time = req[1] if do == "DONT": addRuleP(self.dontdict, device, method, conds, time) print("Rule gets added to DONT dictionary:") print("\tDevice: {0}, Method: {1}, Conditions: {2}".format( device, method, conds)) if req[1]: print("\tDuration: {0}, Unit: {1}, Query: {2}".format( time[0], time[1], time[2])) else: print("No time constraint") else: addRuleP(self.dodict, device, method, conds, time) print("Rule gets added to Do dictionary") print("\tDevice: {0}, Method: {1}, Conditions: {2}".format( device, method, conds)) if req[1]: print("\tDuration: {0}, Unit: {1}, Query: {2}".format( time[0], time[1], time[2])) else: print("No time constraint") for itt in conds: #list of (conditions. timeconstraint) result from OR keyword for it in itt: a, d, v = it[0] addRule( self.tempdict, d, a, v, ([(method, device)], time), it[1] ) #add a reverse dictionary for easy lookup
def normalize(self, text): """ Accepts a string containing a multi-receiver specification in logical form, e.g., "Ka | (L & S)" or "Q" (using receiver abbreviations) and returns a list of lists in CNF, e.g., [['Ka', 'L'], ['Ka', 'S']] and [['Q']] respectively. Note that 'and' may be represented by '&' or '^' and 'or' may be represented by '|' or 'v'. """ if text is not None: text = text.strip() if text is None or text == "": return [] if isinstance(text, unicode): text = text.encode("ascii") prop = parse(scan('(' + text + ')')) rcvr_grps = cnf(prop) self.checkAbbreviations(rcvr_grps) return rcvr_grps
from parse.Jmtaobao import exports as Jmtaobao # 代码星冰乐 from parse.Hchstudio import exports as Hchstudio # 程序羊 from parse.CodeSheep import exports as CodeSheep if __name__ == '__main__': blogActions = [ { 'url': 'http://www.jackpu.com/', 'handler': parseJackPuBlog }, { 'url': 'http://makaiqian.com/', 'handler': parseMaKaiQian }, { 'url': 'https://www.byvoid.com/blog/list', 'handler': parseBYVoid }, { 'url': 'http://yuanhehe.cn/archives/', 'handler': parseYuanHeHe }, { 'url': 'https://blog.thankbabe.com/archive/', 'handler': parseThankbabe }, { 'url': 'https://littlewin.wang/', 'handler': parseLittleWin }, { 'url': 'https://coolshell.cn/', 'handler': parseCoolShell }, { 'url': 'http://tuobaye.com/#blog', 'handler': parseTuobaye }, { 'url': Jilinwula.get('url'), 'handler': Jilinwula.get('parser') }, { 'url': Ruanyifeng.get('url'), 'handler': Ruanyifeng.get('parser') }, { 'url': Jmtaobao.get('url'), 'handler': Jmtaobao.get('parser') }, { 'url': Hchstudio.get('url'), 'handler': Hchstudio.get('parser') }, { 'url': CodeSheep.get('url'), 'handler': CodeSheep.get('parser') } ] date = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) print('+' + '--' * 6 + date + '--' * 6 + '+') for blogAction in blogActions: try: content = NetUtils.get(blogAction.get('url')) parse(content, blogAction.get('handler')) except Exception as e: print(e) print(blogAction.get('url') + '访问失败')
return k, cls Internal.internals['compFunc'] = compFunc if __name__ == '__main__': import sys, traceback, builtins from Preprocess import preprocess from Tokenize import tokenize from Parse import parse for parm in sys.argv[1:]: setattr(builtins, parm, True) fin = open(sys.argv[1], 'r') tree = parse(tokenize(preprocess(fin.read()), sys.argv[1]), sys.argv[1]) fin.close() #print(tree) # def disp(x): # print(len(traceback.extract_stack()), x) # raise Internal.Halt() #This is dumb. newTree = [] for xpr in tree: if isa(xpr, KlipList): if len(xpr) and xpr[0] == Sym('include'): fin = open(xpr[1], 'r') newTree += parse(tokenize(preprocess(fin.read()), xpr[1]), xpr[1])
def create_dataset(player, start, end): white, black = parse(start, end) data = white if player == 1: data = black x = [] y = [] for game in data: if len(game) < 2: continue shifts = [random.choice(find_max_min(game)), (0, 0)] for shift in shifts: empty = np.array([[0] * board_size for _ in range(board_size)]) black_pos = deepcopy(empty) white_pos = deepcopy(empty) turn = np.array([[1] * board_size for _ in range(board_size) ]) # 1 for black, -1 for white hist_1_black = deepcopy(empty) hist_1_white = deepcopy(empty) hist_2_black = deepcopy(empty) hist_2_white = deepcopy(empty) hist_3_black = deepcopy(empty) hist_3_white = deepcopy(empty) hist_4_black = deepcopy(empty) hist_4_white = deepcopy(empty) is_black = True for k, move in enumerate(game): if player == is_black: x.append( torch.from_numpy( np.stack((black_pos, white_pos, turn, hist_1_black, hist_1_white, hist_2_black, hist_2_white, hist_3_black, hist_3_white, hist_4_black, hist_4_white)))) y.append((move[0] - 1 + shift[0]) * 15 + move[1] - 1 + shift[1]) turn *= -1 hist_4_black = deepcopy(hist_3_black) hist_4_white = deepcopy(hist_3_white) hist_3_black = deepcopy(hist_2_black) hist_3_white = deepcopy(hist_2_white) hist_2_black = deepcopy(hist_1_black) hist_2_white = deepcopy(hist_1_white) hist_1_black = deepcopy(black_pos) hist_1_white = deepcopy(white_pos) if is_black: black_pos[move[0] - 1 + shift[0]][move[1] - 1 + shift[1]] = 1 else: white_pos[move[0] - 1 + shift[0]][move[1] - 1 + shift[1]] = 1 is_black = not is_black X = [np.array(x[i]) for i in range(len(x))] data_x = torch.stack( [torch.from_numpy(i).cuda().type(torch.FloatTensor) for i in X]) del X Y = [y[i] for i in range(len(y))] data_y = torch.stack([torch.tensor(i) for i in Y]) del Y dataset = utils.data.TensorDataset(data_x, data_y) del data_x del data_y return dataset