FAQ Database Discussion Community


Format both an expression and its result without eval

common-lisp,eval
I am trying to format an arbitrary expression, say (+ 2 3), and at the same time, its result, 5. I have the following: (defun expr-and-result (expr) (format t "~a returns ~a~%" expr (eval expr))) CL-USER> (expr-and-result '(+ 2 3)) (+ 2 3) returns 5 Though it's a simple matter...

What is an alternative to using 'eval' to accessing a variable by name to “sync” it with another?

javascript,eval
I want to keep two JavaScript variables in sync when I run a function. The variable that is to be pointed to is in an object. The code I have so far is this: var myname = "bob"; var thevar = ""; var varobj = {tvar: "myname"}; var syncvar =...

Python parse mathematical text expression

python,regex,math,eval
I was wondering if anyone knew of a good python library for evaluation text-based mathematical expressions. So for example, >>> evaluate("Three plus nine") 12 >>> evaluate("Eight + two") 10 I've seen similar examples that people have done for numeric values and operators in a string. One method used eval to...

`instance_eval` and scopes

ruby,eval,instance-eval
I have the following code: class A def self.scope yield end def self.method_added method self.instance_eval %{ # do something involving the added method } end end class B < A scope do def foo end end end When the method_added hook is fired, will the code inside instance_eval run within...

Alternative for eval() function for this codeblock

javascript,jquery,html,html5,eval
I am working on a HTML code editor like JSBin. I am using eval() to evaluate the JavaScript in a JS textbox of the editor. However, I came to know that I can't use it online due to security issues. Please help me in finding the alternative. Here's my code....

Custom directive: How evaluate bindings with dynamic HTML

javascript,angularjs,angularjs-directive,eval
Setup: Very simplified HTML: <td ng-repeat="col in cols"> <div ng-bind-html="col.safeHTML"></div> </td> JS controller: $scope.cols = [ { field : 'logo', displayName : 'Logo', cellTemplate: '<div style="color:red">{{col}}</div>' }, { field : 'color', displayName : 'Color', cellTemplate: '<div style="color:green">{{col}}</div> } ]; JS link directive link function: for (var i = 0, j...

How to execute JavaScript function in an Ajax() Response

javascript,jquery,ajax,function,eval
I have a home page that load the ajax() response and post it to UL as LI content, with the same page I have script function that can select the LI content with trigger for another function, but isn’t working. PAGE 1 HTML <ul id="feature-deals" class="list-products allShopping-deals"> </ul> SCRIPT $(document).ready(function(){...

<%#Eval %> in asp.net to move page

html,asp.net,http,hyperlink,eval
Like other 'List' page, I'm making a <a> tag on td, and 3buttons 'Go up','Go down','Go list'. I succeed after click this link, go another page. <a href="NoticeDetail.aspx?seq=<%#Eval("Seq") %>"><%#Eval("Title")%></a> Now, the problem is here. To make Go up/down pages, I guess put the number +1 on the link to calculate...

Dynamically created layer names, problems with eval()

eval,layer,openlayers-3
I want to create some layers with names taken from database. "Trees" in database becomes a "Layer_Trees" openlayers layer. I tried many things with eval function, yet with no success. Seems like its completely uncapable of defining new variables. function addLayer_ImageWMS(SourceName,SourceLayerName) { LayerName="Layer_" + SourceLayerName; eval(LayerName) = new ol.layer.Image({ title:...

Execute external Javascript NodeJS

javascript,node.js,buffer,eval,external
I would like to execute an JS file passed in argument in my NodeJS app (without require each others) Example : $ node myapp test.js test.js console.log("Do some work") test(); myapp.js var test = function(){ console.log("Test working"); here_execute_js_in_process.argv[2](); I tried the simplest option, read file thanks to fs.readFile and eval...

How to evalulate xml literal using scala.tools.reflect.ToolBox in runtime?

xml,scala,reflection,eval
Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_25). Type in expressions to have them evaluated. Type :help for more information. scala> import scala.reflect.runtime.currentMirror import scala.reflect.runtime.currentMirror scala> import scala.tools.reflect.ToolBox import scala.tools.reflect.ToolBox scala> def eval(code: String) = { | val toolbox = currentMirror.mkToolBox() | toolbox.eval(toolbox.parse(code)) | } eval:...

R convert character to dataframe column name and then replace values in a column

r,eval,assign
I was able to get content of the column pointed by character variable b. But i want to make column emp 0. How could i do that? emp=c(1,2,30) abc=data.frame(emp) b="emp" #below line gives content of column emp eval(parse(text=paste("abc$", b, sep = ""))) #how can i replace each value in column...

Issue with Expression in For Loop - Bash

bash,for-loop,expression,eval
I am trying to loop through a list of servers and rather than manually enter each one in a text file, I wanted to use an expression. Example: [[email protected] ~]$ for i in server{001..010} ; do echo $i ; done server001 server002 server003 server004 server005 server006 server007 server008 server009 server010...

ast.literal_eval not working (python string of list to list)

python,string,list,eval,abstract-syntax-tree
I am trying to convert the following string of a list back to a list. [('zX7XjZ1Vwai5UbqNDDJ1NQ', 570512, [155])] I have tried both eval() and ast.literal_eval but for some reason when I print the type of my converted string it is still a string (but with the quotations removed) I have...

In Node, how do I require files inside eval?

javascript,node.js,eval,require
I have two files test.js and x.js, in the same directory: test.js: console.log(eval( "require('x.js')" )); x.js is empty. Expected: require returns undefined, so nothing is logged. Actual: node test.js gives me Error: Cannot find module 'x.js' (stack-trace omitted for brevity). The situation sounds similar to this other question, with the...

Using eval to print an array value

php,arrays,eval
$cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) ); $key = '[1][0]'; $str = '$cars'.$key; echo $str."\n"; eval($str); Output: $cars[1][0] PHP Parse error: syntax error, unexpected end of file in ... : eval()'d code on line 1 I'm expecting it to print the value, i.e BMW...

User specified function with operators in R

r,function,functional-programming,operators,eval
I want to use a user-specified function and apply the function to a list of values. I envision that the user will give a 'formula' as a character string containing the names of variable and operators, e.g. "a * b %% c - d / e ^ f + g...

converting string to tuple in python

python,string,tuples,eval
I have a string returnd from a software like "('mono')" from that I needed to convert string to tuple . that I was thinking using ast.literal_eval("('mono')") but it is saying malformed string....

JS - Call function by name (in object notation)

javascript,window,eval,object-notation
I want to clean up some old code and optimize it, which often uses the same code. (with only different names of functions to call) I make a easier example and no, I don't write on a game. But this example looks more comprehensible to explaination of my issue. character.sleep(1);...

Why can you use eval() with the function repr(y) inside and not str(y)?

python,string,eval,repr
Here is some code that I've found and would like for someone to explain. If I assign a string to the variable y, evaluate it with the eval function and assign the content to the variable y2, the interpreter returns true. >>> y = 'a string' >>> y2 = eval(repr(y))...

Using Javascript's eval() on HTML Text

javascript,html,eval
I am toying around with some basic constructs in HTML and Javascript (i.e., I am a HTML/Javascript n00b), and there is a feature I simply cannot seem to implement properly. In a nutshell, I'd like to grab text from the body of an HTML page and evaluate it using Javascript...

How to use this javascript code with eval or in a iim file?

javascript,eval,imacros
I want to use this code with eval or in a iim file without using js file.I tried for using it into eval but didn't work.Or is there any other way that can allow this code into iim file directly? please help me! do { do { iimPlay("CODE:ondialog pos=1 button=ok...

Parse a string expression

python,regex,parsing,expression,eval
I need to parse a string which contains an expression. The language is proprietary and I am not sure I know the complete syntax but essentially an example expression looks like this: "some_name+(some_other_name * 4 * different_name)+ 'h40028" There are various names i've illustrated as some_name etc above which I...

Not able to do Class(argument) with eval in ruby

ruby,eval,metaprogramming
I have a function like this: def check_if_correct_type(type, value) # nil.test! # eval(type.classify(value)) rescue return false # true case type when "integer" !!Integer(value) rescue return false when "float" !!Float(value) rescue return false else return true end true end A sample would be check_if_correct_type("integer", "a") I tried changing the function like...

Using eval() to check if global variable isset

php,eval,constants
I am trying to check defined variables based on passing a single portion of the variable. (The rest of the variable is static and all other portions of it are the same), so I made a test to find out if this is possible. It does not work, but perhaps...

Remove quotation marks from an object

ruby,string,eval
I want to call User.first, but I get it like "User.first". How can I strip the quotation marks so I can call User? Using a regex like this: gsub!(/\A"|"\Z/, "") returns nil instead of the expression.

Eval alternatives for array creation

php,eval
I am storing an array in string form in a database for later retrieval: The value of the array happens to be parameters for a filter_val call. $str = 'array("options" => array("min_range" => 4))'; I know I can use eval('$options = ' . $str . ';'); to prepare this value...

How to convert a statement in a string into a format that can be evaluated (Ruby)

ruby,string,eval
I am writing a quiz program where I need to store boolean statements as strings in an array and output them to the terminal as part of a question. I then want to evaluate the contents of these strings and return the value so that I can test whether I...

Eval not working on multi-line string

python,eval
I am having issues with executing a multi-line string with the python eval function/ code = ''' def main(): print "this is a test" main() ''' eval(code) Traceback (most recent call last): File "<pyshell#12>", line 1, in <module> eval(code) File "<string>", line 3 def main(): ^ SyntaxError: invalid syntax ...

How could I change this Maths quiz in order to not use eval to find the answer in Python?

python,eval
I heard eval was very bad practice in Python because of security issues. So I was wondering if there is a way I could not use eval in this program. for _ in range(10): n1 = random.randint(1, 10) n2 = random.randint(1, 10) operator = random.choice("+-*") question = (n1,operator,n2) questionNo +=1...

Evaluating text in data table

r,eval,data.table
I'm trying to aggregate a lot of variables in a very large data table by a single variable. The issue I'm having is with eval(parse(text=...)) which I believe is because I'm evaluating several expressions rather than just one. Here is a quick example: library(data.table) data(mtcars) mtcars<-as.data.table(mtcars) mtcars[,j=list( eval(parse(text='mean_mpg=mean(mpg), sum_mpg=sum(mpg)')) ),by=gear]...

How does str(list) work?

python,string,list,eval,python-internals
Why does str(list) returns how we see list on the console? How does str(list) work? (any reference to the CPython code for str(list))? >>> x = ['abc', 'def', 'ghi'] >>> str(x) "['abc', 'def', 'ghi']" To get the original list back from the str(list) I have to: >>> from ast import...

in R, what is the difference between get(“abc”) and eval(parse(text=“abc”))

r,parsing,eval
I'd like to know the difference(s) between those two operations; in this example, they seem to work the same, but there must be situations where one will work and the other not. I just can't figure out when this would be the case. > a <- 298 > eval(parse(text =...

Emacsclient crashes when evaluating window functions

emacs,window,eval
To not bore anyone here with specifics, whenever I evaluate an expression similar to this one: emacsclient -t -e '(set-buffer *scratch*)' the client will flash up on the terminal and crash. This seems to be happening with all window-changing functions. Is the client not supposed to work like that? Running...

eval string as an array

php,arrays,eval
I have a .html file which contains the following: array('1', '786286', '45626'); That is literally all it contains. In my code, I want to eval this and then print it: $code = file_get_contents('array.html'); $nums = eval($code); print_r($nums); However, it is not printing anything. Any help would be greatly appreciated....

combine multiple expressions in R into one big expression

r,expression,eval
I am new to R expression handling. I am stuck with below problem. Any input is appreciated. I am trying to generate two individual equations and combine them into one expression and pass it to an algorithm to find optimal value. OLD_PRICE ELAST Units 1 59.98 1.3 151 2 59.98...

How to use Eval() data in a method within a repeater

c#,asp.net,eval,repeater
I've written a method that checks and returns the status code of a URL. Then I used a repeater to grab rows from my db. What I'm trying to figure out is how to use the data returned in the repeater in a method called within the repeater. Here's the...

is there a way to avoid eval() to accomplish dynamic dispatch of a function specified in a list in python

python,eval
I have a list as defined here: header_fields = [ ['delim',0,4,'strip()'], ['qual',4,5,None], ['NLS_CODE',6,25,'strip()'], ['source_system_id',26,45,'strip()'], ['extract_name',46,65,'strip()'], ['extract_serial_number',66,85,'strip()'], ['file_counter',86,88,"lstrip('0')"], ['total_file_count',89,91,'strip()'], ['extract_run_date_time',92,126,'strip()'], ['from_date',127,161,'strip()'], ['thru_date',162,196,'strip()'], ['number_of_rows',197,216,'strip()'], ['data_recons1',217,246,'strip()'],...

How can I create an array assignment from HEREDOC text using PHP?

php,arrays,eval,variable-assignment,heredoc
I have a list of strings I need to convert into an array assignment eg lets say I have a set of lines like this: ctools_export_ui_list_form masquerade_block_1 switchtheme_switch_form backup_migrate_ui_manual_backup_load_profile_form backup_migrate_ui_manual_backup_form I need to create a variable assignment like this: $conf['journal_form_ids'] = array( 'ctools_export_ui_list_form' => 0, 'masquerade_block_1' => 0, 'switchtheme_switch_form' =>...

Use of eval when building a dict in a for loop. Name is not defined

python,dictionary,eval
Mostly curious why this syntax isn't behaving in the way I would expect it to. Inside of a class's init which accepts multiple parameters (id, departmentId, active), I have the following variable: attributes = [ {'id': 5}, {'departmentId': 10}, {'active': True} ] Essentially, I'm trying to build a dictionary where...

using Eval of ASP Listview as an inline CSS value

asp.net,listview,warnings,eval
my code is : <asp:ListView ID="lst1" runat="server"> <ItemTemplate> <div style="width:<%#Eval("Rating")%>%"> </div> </ItemTemplate> </asp:ListView> It works great, but in VisualStudio editor it's considered as invalid. Is there any way to make it valid? I know that I can create the whole ' style="width:xxx%" ' in the Eval but I'm looking for...

Calculate Dice Roll from Text Field

java,random,eval,jtextfield,dice
QUESTION: How can I read the string "d6+2-d4" so that each d# will randomly generate a number within the parameter of the dice roll? CLARIFIER: I want to read a string and have it so when a d# appears, it will randomly generate a number such as to simulate a...

How can I use vim regex to replace text when math divide is involved in the expression

regex,vim,eval
I am using vim to process text like the following 0x8000 INDEX1 .... 0x8080 INDEX2 .... .... 0x8800 INDEXn .... I want to use regular expression to get the index number of each line. that is 0x8000 ~ 0 0x8080 ~ 1 .... 0x8800 ~ n The math evaluation should...

Perl sigdie handler and eval

perl,eval,log4perl
I am overriding my SIG die handler as below inside my Logger module. # Catch die messages and log them with logdie $SIG{__DIE__} = \&logdie; Now below program run as expected and post processing will be called. use strict; use warnings; use File::Path; # use MyLogger; my $dir="/random"; eval {...

Is this eval() in python safe?

python,eval,code-injection
consider this code: from re import sub input = request.POST['input'] sub_pattern = {'1':"sub('pattern1','txt1',input)", '2':"sub('pattern2','txt2',input)", } eval(sub_pattern['1']) is there code-injection in this code? can you provide POC on this code injection?...

Is there a better alternative to eval() for my function checking algorithm

javascript,jquery,eval,jquery-mask
I have the following code below designed to check that a function exists at anytime. This code does not have any errors currently. I'm using this because my javascript files load in arbitrary orders and is necessary for my project its done that way. Since my javascript files are separated...

How can I break out segments of a 'PHP' file into raw PHP, -and- possible raw HTML -in order-

php,html,regex,eval,output-buffering
So I've got a concept of how to do this - but actually implementing me is a bit of a stumper for myself; mostly due to my lack of regex experience - but let's get into it. I'd like to 'parse' through a 'php' file that could contain something like...

How to call code behind function from label.text in asp.net

c#,asp.net,eval,code-behind
I am trying to call a function defined in code behind from Label.Text but it's not working. Here is the code... code in .aspx file <asp:Label runat="server" Text='<%# GetPagingCaptionString() %>' ID="pagenumberLabel"></asp:Label> code block from code behind public string GetPagingCaptionString() { int currentPageNumber = Convert.ToInt32(txtHidden.Value); int searchOrderIndex; if (int.TryParse(Convert.ToString(Session["searchOrderIndex"]), out searchOrderIndex))...

clojure quoting inside let

clojure,macros,eval
Quoting (both syntax and non-syntax) seems to fail to detect vars inside a let statement: (let [foo 1] (eval `(print foo))) This will generate an error or use whatever prior value bound was bound to foo in (def foo bar). Is there a way to make the syntax quote use...

Parse Perl range string such as “1,4..7,10,11” [duplicate]

perl,parsing,eval
This question already has an answer here: Is there a Perl module for parsing numbers, including ranges? 1 answer Given a string such as 1,4..7,10,11, is there a neat way to parse it into the list (1,4,5,6,7,10,11)? The string is given as a command-line argument. My plan is ensure...

How to concatenate period in eval ASP.net

html,asp.net,eval
I have a ASP.net Label whose Text is defined as follows Text='<%# Eval("Price", "{0:&pound;0.00 ex. VAT}") %>' This displays the label as follows ignoring the 'period' between ex and VAT. How do i handle this? £99.99 ex VAT...

Dynamically Generating Code

ruby,dynamic,methods,eval
I have a whole bunch of similarly-structured methods, each of which look something like this: def my_method_1 if params[:user_id] #code that stays the same across my_method_1, 2, 3, 4, etc. #code that varies across my_method_1, 2, 3, 4, etc. elsif params[:tag_id] #code that stays the same across my_method_1, 2, 3,...

How can I de-obfuscate or decode this Perl code?

perl,eval
I found this code and I think it's encoded. I tried to understand how it's encoded or how can read it. Does anyone have an idea to decode this code? #!/usr/bin/perl eval unpack...

Javascript Eval overwriting variable

javascript,eval
Don't understand why the code below is overwriting my var arr. Any help appreciated. var arr = [1,2,3] var string = "function swap(arr) { var newarr = arr; var temp = arr[0]; newarr[0] = arr[arr.length-1]; newarr[arr.length-1] = temp; return newarr }" var test = eval("[" + string + "]")[0]; test(arr);...

Evaluate expression in R data.table

r,eval,data.table
I have the following data.table: > dt = data.table(expr = c("a + b", "a - b", "a * b", "a / b"), a = c(1,2,3,4), b = c(5,6,7,8)) > dt expr a b 1: a + b 1 5 2: a - b 2 6 3: a * b 3...

appending multiple similar functions to protoype

javascript,node.js,eval
I want to avoid redundant code for one of my projects, which is a simple logger. This logger needs functions like *.alert, *.notice, etc. and I also decided to assign aliases to them (.alert = .al, etc.). This leads to multiple similar functions, that only differ by one number, and...

How to avoid using JavaScript eval() in user-defined function

javascript,json,eval
I'm trying to make a generic table-top RPG helper web app. It has to be generic because Wizards of the Coast is very protective of their copyrights. So, in order to avoid cease-and-desists, the system has to be capable of loading arbitrary rules. That said, my buddies and I (along...

How to return a random show function effect with javascript

javascript,jquery,arrays,random,eval
I'm trying to show some element with a random effect. I store those functions in an array and try to get a random function from that array, but the functions seem to rum at the same time. $.random_show = function(){ (function($) { $.rand = function(arg) { if ($.isArray(arg)) { return...

How to evaluate custom javascript expression with the context in strict mode?

javascript,properties,scope,this,eval
Update I've come up with a concise solution to this problem, that behaves similar to node's vm module. var VM = function(o) { eval((function() { var src = ''; for (var prop in o) { if (o.hasOwnProperty(prop)) { src += 'var ' + prop + '=o[\'' + prop + '\'];';...

Can an inserted