コード例 #1
0
ファイル: __init__.py プロジェクト: sandsy-cell23/URTale-RPG
def eval(source: _code, globals=None, locals=None):
    """evaluate Import Expression Python™ in the given globals and locals"""
    globals, locals = _parse_eval_exec_args(globals, locals)
    if _inspect.iscode(source):
        return _builtins.eval(source, globals, locals)
    return _builtins.eval(compile(source, constants.DEFAULT_FILENAME, 'eval'),
                          globals, locals)
コード例 #2
0
ファイル: views.py プロジェクト: ywlim7/courseai
def degree_plan(request):
    if request.method == "GET":
        try:
            code = request.GET['query']
            starting_year = request.GET['start_year_sem']
            return degree_plan_helper.generate_degree_plan(code, starting_year)
        except (Exception):
            return JsonResponse({"response": "null"})
    elif request.method == "PUT":
        data = request.body.decode('utf-8')
        code = eval(data)["code"]
        courses = eval(data)["courses"]
        prev = PreviousStudentDegree(code=code, courses_taken=courses)
        prev.save()
        degree_list = PreviousStudentDegree.objects.all()
        degree = Degree.objects.filter(code=code)[0]
        degree.number_of_enrolments += 1
        metrics = eval(degree.metrics)
        for course_code in josnhelper.parse_degree_json(data):
            if course_code == "Elective Course":
                continue
            metrics[course_code] = int(metrics[course_code]) + 1
        degree.metrics = str(metrics)
        degree.save()
        train_sample(Degree(code=code, requirements=courses))
        for degree in degree_list:
            print({"code": degree.code, "courses_taken": degree.courses_taken})
        return JsonResponse({"response": "Success"})
コード例 #3
0
ファイル: cli.py プロジェクト: danhalligan/rosalind
def seto(file: str):
    """Introduction to Set Operations"""
    n, s1, s2 = Parser(file).lines()
    n = int(n)
    s1 = builtins.eval(s1)
    s2 = builtins.eval(s2)
    s3 = set(range(1, n + 1))
    print(*[s1 | s2, s1 & s2, s1 - s2, s2 - s1, s3 - s1, s3 - s2], sep="\n")
コード例 #4
0
def exec(source, globals=None, locals=None):
    """execute Import Expression Python™ in the given globals and locals

	Note: unlike :func:`exec`, the default globals are *not* the caller's globals!
	This is due to a python limitation.
	Therefore, if no globals are provided, the results will be discarded!
	"""
    globals, locals = _parse_eval_exec_args(globals, locals)
    _builtins.eval(compile(source, constants.DEFAULT_FILENAME, 'exec'),
                   globals, locals)
コード例 #5
0
def eval(expression, _dict={}, **kw):
    """
    Evaluates an image expression.

    :param expression: A string containing a Python-style expression.
    :param options: Values to add to the evaluation context.  You
                    can either use a dictionary, or one or more keyword
                    arguments.
    :return: The evaluated expression. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.
    """

    # build execution namespace
    args = ops.copy()
    args.update(_dict)
    args.update(kw)
    for k, v in list(args.items()):
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    out = builtins.eval(expression, args)
    try:
        return out.im
    except AttributeError:
        return out
コード例 #6
0
ファイル: views.py プロジェクト: ZIFENGLIU828/courseai
def degree_plan(request):
    if request.method == "GET":
        try:
            code = request.GET['degree_code']
            year = request.GET['year']
            with open('static/json/study_options/{}.json'.format(code)) as f:
                study_options_str = f.read()
                study_options_dict = ast.literal_eval(study_options_str)
            return JsonResponse({"response": study_options_dict[year]})
        except Exception:
            res = JsonResponse({
                "response":
                "Default options of the requested degree-year combination could not be found. "
            })
            return HttpResponseBadRequest(res)
    elif request.method == "PUT":
        data = request.body.decode('utf-8')
        code = json.loads(data)["code"]
        courses = json.loads(data)["courses"]
        prev = PreviousStudentDegree(code=code, courses_taken=courses)
        prev.save()
        degree = Degree.objects.filter(code=code)[0]
        degree.number_of_enrolments += 1
        metrics = eval(degree.metrics)
        for course_code in jsonhelper.parse_degree_json(data):
            if course_code == "Elective Course":
                continue
            metrics[course_code] = int(metrics[course_code]) + 1
        degree.metrics = str(metrics)
        degree.save()
        # no training
        # train_sample(Degree(code=code, requirements=courses))
        # for degree in degree_list:
        #     print({"code": degree.code, "courses_taken": degree.courses_taken})
        return JsonResponse({"response": "Success"})
コード例 #7
0
def generate_degree_plan(code, start_year_sem):
    degree = Degree.objects.filter(code=code)[0]
    reqs = degree.requirements
    if (reqs == "{}"):
        reqs = dict()
        final_year = 3
        if ("Honours" in degree.name):
            final_year = 4
        for i in range(1, final_year + 1):
            for j in range(1, 3):
                reqs[str(i) + "." + str(j)] = [{"title": 'Elective Course'}]
    to_return = []
    year, sem = start_year_sem.split('S')
    year, sem = int(year), int(sem)
    for year_sem, courses in sorted(eval(str(reqs)).items(),
                                    key=lambda session: float(session[0])):
        print(len(courses))
        for c in courses:
            update_elective_code(c)
            if (c['code'] == "OR"):
                c['code'] = 'Elective Course'
        if (len(courses) < 4):
            for i in range(4 - len(courses)):
                courses.append({"code": 'Elective Course'})
        to_return.append({'{}S{}'.format(year, sem): courses[0:4]})
        year, sem = advance_sem(year, sem)
    return JsonResponse({"response": to_return})
コード例 #8
0
def eval(expression, _dict={}, **kw):
    """
    Evaluates an image expression.

    :param expression: A string containing a Python-style expression.
    :param options: Values to add to the evaluation context.  You
                    can either use a dictionary, or one or more keyword
                    arguments.
    :return: The evaluated expression. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.
    """

    # build execution namespace
    args = ops.copy()
    args.update(_dict)
    args.update(kw)
    for k, v in list(args.items()):
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    out = builtins.eval(expression, args)
    try:
        return out.im
    except AttributeError:
        return out
コード例 #9
0
    def process(self, input):
        input = eval(input)

        input = '{:.15f}'.format(float(input)).rstrip(
            '0')  # Forces precision to 15 digits and remove trailing 0s
        if input[-1] == '.':
            input = input[:-1]

        return input
コード例 #10
0
ファイル: main.py プロジェクト: CyborgVillager/calculatorios
 def eval_number(self, text):
     try:
         input = self.ids.input
         expression = input.text
         eva = eval(expression)  # perform math operations
         input.text = str(eva)
         equalsound.play()
     except:
     # error plays and display error message
        errorsound.play()
        input.text = 'Error! \(x_x\) Tap Ca'
コード例 #11
0
ファイル: course_data_helper.py プロジェクト: ywlim7/courseai
def get_data(code):
    q = MultiMatch(query=code, fields=['code^4'])
    client = Elasticsearch()
    s = Search(using=client, index='courses')
    response = s.query(q).execute()

    try:
        hit = response['hits']['hits'][0]
    except IndexError:
        return None
    course_data = {
        "course_code": hit['_source']['code'],
        "id": hit["_id"],
        "title": hit['_source']['title'],
        "description": hit['_source']['description'],
        "learning_outcomes": hit['_source']['outcome'],
        "prerequisite_text": hit['_source']['prereq_text'],
        "prerequisites": eval(str(hit['_source']['pre_req_cnf'])),
        "semester": eval(str(hit['_source']['semester']))
    }
    return course_data
コード例 #12
0
ファイル: course_data_helper.py プロジェクト: ywlim7/courseai
def get_prereqs(codes):
    course_data = {}
    codes = json.loads(codes)
    for code in codes:

        q = MultiMatch(query=code, fields=['code^4'])
        client = Elasticsearch()
        s = Search(using=client, index='courses')
        response = s.query(q).execute()

        try:
            hit = response['hits']['hits'][0]
        except IndexError:
            continue

        course_data[hit['_source']['code']] = {
            "course_code": hit['_source']['code'],
            "prerequisite_text": hit['_source']['prereq_text'],
            "prerequisites": eval(str(hit['_source']['pre_req_cnf'])),
            "semester": eval(str(hit['_source']['semester']))
        }
        pass
    return course_data
コード例 #13
0
ファイル: nn.py プロジェクト: ywlim7/courseai
def get_prediction(degree, number_of_recommendations):
    network = joblib.load("network/" + degree.code + ".pkl")

    #print(type(network_dict[degree]))
    reqs = dict()
    for semester in eval(str(degree.requirements)):
        for sem in semester.items():
            reqs[sem[0]] = sem[1]
    x_array = create_vector(str(reqs))

    ratings = np.sort(
        network.predict(x_array)[0])[::-1][:number_of_recommendations]
    ids = np.argsort(
        network.predict(x_array)[0])[::-1][:number_of_recommendations]
    return (ids, ratings)
コード例 #14
0
def eval(expression, _dict={}, **kw):

    # build execution namespace
    args = ops.copy()
    args.update(_dict)
    args.update(kw)
    for k, v in list(args.items()):
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    out = builtins.eval(expression, args)
    try:
        return out.im
    except AttributeError:
        return out
コード例 #15
0
ファイル: nn.py プロジェクト: ZIFENGLIU828/courseai
def create_vector(degree_requirements):
    reqs = list(eval(degree_requirements).items())
    ave_vec = []
    for j in range(len(reqs)):
        k, v = reqs[j]
        for i in range(len(v)):
            d = v[i]
            if "code" in d:
                if d["code"] == "Elective Course":
                    break
                if get_course_vector(d["code"]) is not None:
                    if not ave_vec:
                        ave_vec = np.array(get_course_vector(d["code"])[0])
                    else:
                        ave_vec += np.array(get_course_vector(d["code"])[0])
    return np.array(ave_vec)
コード例 #16
0
ファイル: nn.py プロジェクト: ywlim7/courseai
def create_vector(degree_requirements):
    reqs = list(eval(degree_requirements).items())
    ave_vec = []
    for j in range(len(reqs)):
        k, v = reqs[j]
        for i in range(len(v)):
            d = v[i]
            if ("code" in d):
                if (d["code"] == "Elective Course"):
                    break
                if (get_course_vector(d["code"]) != None):
                    if ave_vec == []:
                        ave_vec = np.array(get_course_vector(d["code"])[0])
                    else:
                        ave_vec += np.array(get_course_vector(d["code"])[0])
    return np.array(ave_vec)
コード例 #17
0
ファイル: vim.py プロジェクト: paul-ollis/vim-vpe
def exists(expr):
    """Test whether a Vim object, file, *etc.* exists."""
    if expr.startswith(':'):
        return '2'
    if expr.startswith('+'):
        # pylint: disable=protected-access
        return '1' if options._knows(expr[1:]) else '0'
    if expr.startswith('*'):
        name = expr[1:]
        try:
            value = builtins.eval(name)
        except NameError:
            return '0'
        return '1' if callable(value) else '0'

    return '0'
コード例 #18
0
ファイル: vim.py プロジェクト: tejasvi/vim-vpe
def eval(expr: str) -> Any:  # pylint: disable=redefined-builtin
    """Emulate vim eval method."""
    m = r_varname.match(expr.strip())
    if m:
        amp, vtype, vname = m.groups()
        if vtype in ('g:', ''):
            if amp:
                return options[vname]
            return vars[vname]
        if vtype == 'v:':
            return vvars[vname]
        # print(f'EVAL FAIL for buf var: {expr!r}')
        return ''

    try:
        return builtins.eval(expr)
    except Exception:  # pylint: disable=broad-except
        return ''
コード例 #19
0
ファイル: nn.py プロジェクト: ZIFENGLIU828/courseai
def train_sample(degree):
    try:
        network = joblib.load("network/" + degree.code + ".pkl")
    except:
        # print("no network found")
        network = MLPRegressor(hidden_layer_sizes=(1000, ), activation='tanh')
    reqs = dict()
    for semester in eval(str(degree.requirements)):
        for sem in semester.items():
            reqs[sem[0]] = sem[1]

    x_array, y_array = create_training_arrays(str(reqs))
    network.fit(x_array, y_array)
    test_data = list(
        np.argmax(network.predict(x_array), axis=1) == np.argmax(y_array,
                                                                 axis=1))
    # print("Accuracy:", sum(test_data) / len(test_data))
    joblib.dump(network, "network/" + degree.code + ".pkl")
コード例 #20
0
ファイル: vim.py プロジェクト: tejasvi/vim-vpe
def command(cmd: str) -> None:
    """Emulate vim command function."""
    m = r_assign.match(cmd.strip())
    if m:
        amp, vtype, vname, expr = m.groups()
        v = builtins.eval(expr)
        if amp == '&':
            options._set(vname, v)  # pylint: disable=protected-access
        elif vtype in ('g:', '', None):
            vars[vname] = v
        elif vtype == 'v:':
            vvars._set(vname, v)  # pylint: disable=protected-access
        else:
            # print("SKIP SET", m.groups())
            pass

    else:
        if command_callback:
            command_callback(cmd)
コード例 #21
0
ファイル: nn.py プロジェクト: ZIFENGLIU828/courseai
def create_training_arrays(degree_requirements):
    global leave_out
    leave_out = 0
    reqs = list(eval(degree_requirements).items())
    if not reqs:
        return np.array([]), np.array([])

    X = []
    Y = []
    left_out = []
    while leave_out < 8 * len(reqs):
        global training_vector
        training_vector = []
        ave_vec = []
        for j in range(len(reqs)):
            k, v = reqs[j]
            for i in range(len(v)):
                d = v[i]
                if "code" in d:
                    if d["code"] == "Elective Course":
                        break
                    if not ave_vec:
                        if leave_out == 4 * j + i + 1:
                            training_vector = d["code"]
                            left_out.append(d["code"])
                            break
                        if get_course_vector(d["code"]) is not None:
                            ave_vec = np.array(get_course_vector(d["code"])[0])
                    else:
                        if leave_out == 4 * j + i + 1:
                            training_vector = d["code"]
                            left_out.append(d["code"])
                            break
                        if get_course_vector(d["code"]) is not None:
                            ave_vec += np.array(
                                get_course_vector(d["code"])[0])
        if not (training_vector == []):
            if get_course_data([training_vector]) is not None:
                X.append(ave_vec)
                Y.append(course_ids[int(
                    get_course_data([training_vector])['id'])])
        leave_out += 1
    return np.array(X), np.array(Y)
コード例 #22
0
ファイル: ImageMath.py プロジェクト: Kanyandula/BlogPost
def eval(expression, _dict={}, **kw):
    """
    Evaluates an image expression.

    :param expression: A string containing a Python-style expression.
    :param options: Values to add to the evaluation context.  You
                    can either use a dictionary, or one or more keyword
                    arguments.
    :return: The evaluated expression. This is usually an image object, but can
             also be an integer, a floating point value, or a pixel tuple,
             depending on the expression.
    """

    # build execution namespace
    args = ops.copy()
    args.update(_dict)
    args.update(kw)
    for k, v in list(args.items()):
        if hasattr(v, "im"):
            args[k] = _Operand(v)

    compiled_code = compile(expression, "<string>", "eval")

    def scan(code):
        for const in code.co_consts:
            if type(const) == type(compiled_code):
                scan(const)

        for name in code.co_names:
            if name not in args and name != "abs":
                raise ValueError(f"'{name}' not allowed")

    scan(compiled_code)
    out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
    try:
        return out.im
    except AttributeError:
        return out
コード例 #23
0
ファイル: vim.py プロジェクト: tejasvi/vim-vpe
 def __call__(self, *args):
     func = builtins.eval(self.name)
     return func(*args)
コード例 #24
0
    elif hasattr(var, "__len__"):
        try:
            return _VSCODE_builtins.len(var)
        except TypeError:
            return 0


# First check to see if we are a supported type, this prevents us from adding types that are not supported
# and also keeps our types in sync with what the variable explorer says that we support
if _VSCODE_targetVariable["type"] not in _VSCode_supportsDataExplorer:
    del _VSCode_supportsDataExplorer
    print(_VSCODE_json.dumps(_VSCODE_targetVariable))
    del _VSCODE_targetVariable
else:
    del _VSCode_supportsDataExplorer
    _VSCODE_evalResult = _VSCODE_builtins.eval(_VSCODE_targetVariable["name"])

    # Figure out shape if not already there. Use the shape to compute the row count
    _VSCODE_targetVariable["rowCount"] = _VSCODE_getRowCount(
        _VSCODE_evalResult)

    # Turn the eval result into a df
    _VSCODE_df = _VSCODE_evalResult
    if isinstance(_VSCODE_evalResult, list):
        _VSCODE_df = _VSCODE_pd.DataFrame(_VSCODE_evalResult)
    elif isinstance(_VSCODE_evalResult, _VSCODE_pd.Series):
        _VSCODE_df = _VSCODE_pd.Series.to_frame(_VSCODE_evalResult)
    elif isinstance(_VSCODE_evalResult, dict):
        _VSCODE_evalResult = _VSCODE_pd.Series(_VSCODE_evalResult)
        _VSCODE_df = _VSCODE_pd.Series.to_frame(_VSCODE_evalResult)
    elif _VSCODE_targetVariable["type"] == "ndarray":
コード例 #25
0
ファイル: helpers.py プロジェクト: silentrob/brackets
def eval(code, *args, **kwargs):
    code, debug, original = translate(code)
    try:
        return __builtins__.eval(code, *args, **kwargs)
    except Exception as e:
        exception_handler(e, debug, original)
コード例 #26
0
ファイル: builtins.py プロジェクト: BlackHC/implicit_lambda
    lambda *args, **kwargs: builtins.dir(*args, **kwargs), builtins.dir)
dir._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.dir)(*args, **kwargs), builtins.dir)
divmod = functools.update_wrapper(
    lambda *args, **kwargs: builtins.divmod(*args, **kwargs), builtins.divmod)
divmod._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.divmod)(*args, **kwargs),
    builtins.divmod)
enumerate = functools.update_wrapper(
    lambda *args, **kwargs: builtins.enumerate(*args, **kwargs),
    builtins.enumerate)
enumerate._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.enumerate)(*args, **kwargs),
    builtins.enumerate)
eval = functools.update_wrapper(
    lambda *args, **kwargs: builtins.eval(*args, **kwargs), builtins.eval)
eval._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.eval)(*args, **kwargs),
    builtins.eval)
exec = functools.update_wrapper(
    lambda *args, **kwargs: builtins.exec(*args, **kwargs), builtins.exec)
exec._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.exec)(*args, **kwargs),
    builtins.exec)
float = functools.update_wrapper(
    lambda *args, **kwargs: builtins.float(*args, **kwargs), builtins.float)
float._ = functools.update_wrapper(
    lambda *args, **kwargs: wrap(builtins.float)(*args, **kwargs),
    builtins.float)
format = functools.update_wrapper(
    lambda *args, **kwargs: builtins.format(*args, **kwargs), builtins.format)
コード例 #27
0
ファイル: in-built.py プロジェクト: sancharibasak/tusk
from builtins import eval

print(abs(-4))
print(bool(None))
print(dir(4))
s = "hello"
print(s.upper())
print(s.splitlines())

s1 = 'print("Hi")'
print(eval(s1))

print(exec(s1))

b = 1
print(str(b))
print(float(b))


コード例 #28
0
ファイル: bpipe.py プロジェクト: mavnt/bpipe
def eval(expression=None, *args):
    if expression is not None:
        return builtins.eval(expression, *args)
    else:
        return bpipe(eval, eval_args=args)
コード例 #29
0
ファイル: example_macros.py プロジェクト: mk12/zendown
def eval(ctx: Context, arg: str) -> str:
    return ctx.render(raw_text(str(builtins.eval(arg))))
コード例 #30
0
ファイル: CodeExecution.py プロジェクト: raulgarciamsft/ql
# without this, `eval("print(42)")` becomes invalid syntax in Python 2, since print is a
# statement
from __future__ import print_function

import sys

if sys.version_info[0] == 3:
    import builtins
if sys.version_info[0] == 2:
    import __builtin__ as builtins

exec("print(42)")  # $getCode="print(42)"
eval("print(42)")  # $getCode="print(42)"

builtins.eval("print(42)")  # $getCode="print(42)"

cmd = compile("print(42)", "<filename>", "exec")
exec(cmd)  # $getCode=cmd

cmd = builtins.compile("print(42)", "<filename>", "exec")
exec(cmd)  # $getCode=cmd

# ------------------------------------------------------------------------------
# taint related


def test_additional_taint():
    src = TAINTED_STRING

    cmd1 = compile(src, "<filename>", "exec")
    cmd2 = compile(source=src, filename="<filename>", mode="exec")