def test_issue_18(): import sexpdata sexp = "(foo)' " with assert_raises(ExpectSExp) as raised: sexpdata.parse(sexp) msg = raised.exception.args[0] eq_(msg, 'No s-exp is found after an apostrophe at position 5') sexp = "' " with assert_raises(ExpectSExp) as raised: sexpdata.parse(sexp) msg = raised.exception.args[0] eq_(msg, 'No s-exp is found after an apostrophe at position 0')
def __init__(self): vocab = {} with open('cls2_data/data/vocab.csv') as fh: for line in fh: word, id = line.split(',') vocab[word] = id self._vocab = vocab data = [] m1 = 0. m2 = 0. count = 0. with open('cls2_data/data/metadata.csv') as fh: #lines = list(fh) #for line in lines[:100]: for line in fh: i, lf = line.strip().split(',') i = int(i) lf = _clean_sexp(sexpdata.parse(lf)[0]) tr_a = scipy.misc.imread('cls2_data/data/%d_train_a.jpg' % i) tr_b = scipy.misc.imread('cls2_data/data/%d_train_b.jpg' % i) te_p = scipy.misc.imread('cls2_data/data/%d_test_pos.jpg' % i) te_n = scipy.misc.imread('cls2_data/data/%d_test_neg.jpg' % i) tr_a, tr_b, te_p, te_n = ( im.transpose(2, 0, 1).astype(np.float32) / 256. for im in (tr_a, tr_b, te_p, te_n)) m1 += tr_a m2 += tr_a**2 count += 1 tr = np.asarray([tr_a, tr_b]) data.append(Datum(tr, te_p, te_n, lf)) self._data = data assert len(data) == 10000 # for determinism lfs = sorted(list(set([d.lf for d in data])), key=str) np.random.shuffle(lfs) hold_lfs = lfs[:30] hold_ids = [i for i in range(len(data)) if data[i].lf in hold_lfs] rest_ids = [i for i in range(len(data)) if i not in hold_ids] self._train_ids = rest_ids[:-500] self._val_ids = rest_ids[-500:] self._cval_ids = hold_ids #self._train_ids = self._val_ids = list(range(10)) m1 /= count m2 /= count self._mean = m1 self._std = np.sqrt(m2 - m1**2)
def _findModel(self): self.solver.push() exprbuilder = ExprBuilder(self.asserts, self.query, self.solver) self.solver.assertFormula(exprbuilder.query.cvc_expr) smtlib = CVCWrapper._serialize(exprbuilder.query, exprbuilder.cvc_vars) transformed_smtlib = [ self._transform(s) for s in sexpdata.parse(smtlib) ] z3str2 = "" for line in transformed_smtlib: z3str2 += sexpdata.dumps(line, none_as='').strip().replace( '\\\\', '\\') + "\n" rawoutput = None with NamedTemporaryFile(mode='w', suffix=".smt2") as f: f.write(z3str2) f.flush() startime = time.clock() try: rawoutput = str( check_output([ "timeout", str(self.solvetimeout), "z3-str", "-f", f.name ], universal_newlines=True)) except CalledProcessError as e: if e.returncode == 124: return "UNKNOWN", None endtime = time.clock() log.debug("Solver time: {0:.2f} seconds".format(endtime - startime)) self.solvertime += endtime - startime if ">> SAT" not in rawoutput: return "UNSAT", None model = {} for name in exprbuilder.cvc_vars: patterns = { "{} : int -> (-?\d+)": int, "{} : string -> \"([\S \\\\]*)\"": str } for pattern, constructor in patterns.items(): match = re.search(pattern.format(name), rawoutput) if match is not None: if constructor == str: model[name] = bytes(constructor(match.group(1)), "utf-8").decode("unicode_escape") else: model[name] = constructor(match.group(1)) return "SAT", model
def main(): fname = sys.argv[1] r = sexpdata.parse(open(fname).read()) if str(r[0][0].value()) == "kicad_pcb": for i in r[0]: if type(i) == list: if i[0].value() == "net": nets[i[1]] = {'name': pun(i[2])} if i[0].value() == "segment": add_segment(i) if i[0].value() == "via": pass # print map(pun, i) # print nets # print segs for k in nets.keys(): nets[k]["length"] = 0 for g in segs: if g.net == k: nets[k]["length"] = nets[k]["length"] + g.len() for p in nets.keys(): print "%d: %s len = %f" %(p, nets[p]["name"], nets[p]["length"])
def main(): global _print_wrapper global _header global _recursion_limit global _footer fun_defs = [_print_wrapper] if len(sys.argv) != 2: print("Usage: python3 translate.py <file>", file=sys.stderr) sys.exit(1) with open(sys.argv[1], "r") as lamc_src,\ open("%s.py" % ".".join(sys.argv[1].split(".")[:-1]), "w") as py_out: py_out.write("%s\n" % _header) py_out.write("%s\n" % _recursion_limit) py_out.write("def main():\n return %s\n\n"\ % translate(parse(lamc_src.read().strip()))) for fun_def in fun_defs: py_out.write("%s\n" % fun_def) py_out.write(_footer)
def test_no_eol_after_comment(): eq_(parse('a ; comment'), [Symbol('a')])
def test_not_enough_brackets(): parse("(a (b)")
def test_too_many_brackets(): parse("(a b))")
def assert_parse(self, string, obj): """`string` must be parsed into `obj`.""" self.assertEqual(parse(string)[0], obj)
def compare_parsed(sexp, obj): eq_(parse(sexp), obj)
def sexp2json(file, out, recursionlimit): sys.setrecursionlimit(recursionlimit) for path in file: with open(path) as f: json.dump(tojsonable(sexpdata.parse(f.read())), out, indent=2)
def check_identity(obj): eq_(parse(tosexp(obj))[0], obj)