In my app i need to allow the user to add their own math formulas, can use operators and call variables. There is anyway to validate if a user write wrong a variable or a unknown variable to show an error?
I have and example here, you have some scope variables in the top of the controller. A minor difference, if I insert an invalid variable in the example it shows null, but in my code appears in blank.
Any suggestions?
Well honestly, if you weren't lazily throwing this stuff in eval, you could easily parse it yourself I recon.
How about removing all whitespaces, and interating over every single character?
I mean as long as there are no variables like aa or ab, you can just check like.
for (var i = 0; i < answer.length ; i++) {
if (!isvalidParamOrOperator(answer[i])) {
//can show error at position i+1;
return false;
}
}
with isValidParamOrOperator being something like
function(str) {
return "1234567890ab".indexOf(str);
}
Of course it becomes a little bit more complicated at longer params, but you'd be able to create something that splits on all operators like + - spaces & numbers. And then you'll have a list of all params which you can check. which should probably be checked on an array instead of my current suggestion, but this shouldn't be hard after you implement something like this.
Related
Is there a way to use a for loop to automate a function? e.g
if i write..
def foo (a number):
return (a number)
for i in range(10):
print(foo('1{}').format(str(i))
Comes out with AttributeError: 'NoneType' object has no attribute 'format'
Well, I am changing this because it didn't really answer your question, but its a lot simpler than you are trying to make it. Really all it is, is a function that is called and updated by a loop. So, let's try that:
def foo(num):
print(num)
num = 0
for i in range(1,10,1):
foo(num + i)
So, what I've done here is taken your script and changed it. To start with, "a number" as a parameter will cause syntax errors while trying to define them. So I changed it to "num".
Then, I've used a simple print statement to print out the number that is coming in. This could be removed if you just wanted a loop with it cycling it through numbers. And of course changing "foo(num + i)" to "print(num + i)".
The "num = 0" sets a variable so we can use it later.
Regards,
Jerry
When I use the Execute Script operator, where there is one input arc and this input is of type ExampleSet and I run, for example, the one-line script return operator.getInput(ExampleSet.class), and then connect the output to an Extract Performance operator, which takes an ExampleSet as input, I get an error: Mandatory input missing at port Performance.example set.
My goal is to check a Petri-net for soundness via the Analyse soundness operator that comes with the RapidProm extension, and to take and change the first attribute on the first line to either 0 or 1 depending on whether this string matches "is sound", so I can then use Extract Performance and combine it with other performances using Average.
Is doing this with Execute Script the right way to do it, and if so, how should I fix this error?
Firstly: Don't bother about the error Mandatory input missing at port Performance.example set
It will be resolved when you run the model.
Secondly: It is indeed a bit ugly, the output of the operator that checks
the soundness of the model, since it is a very long string that looks like
Woflan diagnosis of net "d1cf46bd-15a9-4801-9f02-946a8f125eaf" - The net is sound End of Woflan diagnosis
You can indeed use the execute script to resolve this :)
See the script below!
The output is an example set that returns 1 if the model is sound, and 0 otherwise. Furthermore, I like to use some log operators to translate this to a nice table useful for documentation purposes.
ExampleSet input = operator.getInput(ExampleSet.class);
for (Example example : input) {
String uglyResult = example["att1"];
String soundResult = "The net is sound";
Boolean soundnessCheck = uglyResult.toLowerCase().contains(soundResult.toLowerCase());
if (soundnessCheck){
example["att1"] = "1"; //the net is sound :)
} else {
example["att1"] = "0"; //the net is not sound!
}
}
return input;
See also the attached example model I created.
RapidMiner Setup
I keep getting the same error in my program. I've written a method that takes some messy HTML and turns it into neater strings. This works fine on its own, however when I run the whole program I get the following error:
kamer.rb:9:in `normalise_instrumentation': undefined method `split' for #<Nokogiri::XML::NodeSet:0x007f92cb93bfb0> (NoMethodError)
I'd be really grateful for any info or advice on why this happens and how to stop it.
The code is here:
require 'nokogiri'
require 'open-uri'
def normalise_instrumentation(instrumentation)
messy_array = instrumentation.split('.')
normal_array = []
messy_array.each do |section|
if section =~ /\A\d+\z/
normal_array << section
end
end
return normal_array
end
doc = Nokogiri::HTML(open('http://www.cs.vu.nl/~rutger/vuko/nl/lijst_van_ooit/complete-solo.html'))
table = doc.css('table[summary=works] tr')
work_value = []
work_hash = {}
table.each do |row|
piece = [row.css('td[1]'), row.css('td[2]'), row.css('td[3]')].map { |r|
r.text.strip!
}
work_value = work_value.push(piece)
work_key = normalise_instrumentation(row.css('td[3]'))
work_hash[work_key] = work_value
end
puts work_hash
The problem is here:
row.css('td[3]')
Here's why:
row.css('td[3]').class
# => Nokogiri::XML::NodeSet < Object
You're creating your piece array which then becomes an array of NodeSets, which is probably not what you want, because text against a NodeSet often returns a weird String of concatenated text from multiple nodes. You're not seeing that happen here because you're searching inside a row (<tr>) but if you were to look one level up, in the <table>, you'd have a cocked gun pointed at your foot.
Passing a NodeSet to your normalise_instrumentation method is a problem because NodeSet doesn't have a split method, which is the error you're seeing.
But, it gets worse before it gets better. css, like search and xpath returns a NodeSet, which is akin to an Array. Passing an array-like critter to the method will still result in confusion, because you really want just the Node found, not a set of Nodes. So I'd probably use:
row.at('td[3]')
which will return only the node.
At this point you probably want the text of that node, something like
row.at('td[3]').text
would make more sense because then the method would receive a String, which does have a split method.
However, it appears there are additional problems, because some of the cells you want don't exist, so you'll get nil values also.
This isn't one of my better answers, because I'm still trying to grok what you're doing. Providing us with a minimal example of the HTML you need to parse, and the output you want to capture, will help us fine-tune your code to get what you want.
I had a similar error (undefined method) for a different reason, in my case it was due to an extra dot (put by mistake) like this:
status = data.css.("status font-large").text
where it was fixed by removing the extra dot after the css as shown below
status = data.css("status font-large").text
I hope this helps someone else
I have files in one folder with following naming convention
ClientID_ClientName_Date_Fileextension
12345_Dell_20110103.CSV
I want to extract ClientID from the filename and store that in a variable. I am unsure how I would do this. It seems that a Script Task would suffice but I am do not know how to proceed.
Your options are using Expressions on SSIS Variables or using a Script Task. As a general rule, I prefer Expressions but mentally, I can tell that's a lot of code, or a lot of intertwined variables.
Instead, I'd use the String.Split method in .NET. If you called the Split method for your sample data and provided a delimiter of the underscore _ then you'd receive a 3 element array
12345
Dell
20110103.CSV
Wrap that in a Try Catch block and always grab the second element. Quick and dirty but of course won't address things like 12345_Dell_Quest_20110103.CSV but you didn't ask that question.
Code approximate
string phrase = Dts.Variables["User::CurrentFile"].Value.ToString()
string[] stringSeparators = new string[] {"-"};
string[] words;
try
{
words = phrase.Split(stringSeparators, StringSplitOptions.None);
Dts.Variables["User::ClientName"].Value = words[1];
}
catch
{
; // Do something with this error
}
Clearly I have some mixed up, but I figured that by using something like this in "main.lua":
local module = require("module")
local var = "I should be global?"
printthis()
with module.lua containing something like:
function printthis()
print(var)
end
that printthis(var) would work fine, because now the module.lua code is inside main.lua, no? Instead, printthis has no idea what var is. I read it's good practice to use "local" on Lua variables when possible, but in this case, do I have to make var global or is there a way for module.lua's printthis() function to read var properly?
No. That's not at all how it works.
The Lua interpreter provides one global table, referred to as _G normally, unless you're doing something kinky.
function printthis()
print(var)
end
This translates to, in reality
_G.printthis = function()
_G.print(_G.var);
end
And your code in main is equal to
local module = _G.require("module")
local var = "I should be global?"
_G.printthis()
But when you call printthis- where did _G.var get set? Nowhere. So the variable is nil, like all other accesses to a table where there is nothing at that key.
It might be inconvenient, but it's a much better idea in the long run to pass arguments than to set global variables instead. Once you come to change anything about the program, it's going to be completely impossible to make any changes, as the logic has no structure and you have no idea what happens where without reading every single line of code and understanding it at once. In addition, you can only use each key in one place, because it's a global table- so I sure hope nobody else wanted to use "var" as a variable name and you don't mind your code silently failing because you got a global name wrong.
The other two answers gloss over an important thing: lexical scoping.
This means, roughly, that code can access local variables that are defined where the code is defined. That probably sounds vague, so I'll give an example:
local cheese = 'sandwich'
print(cheese) -- prints sandwich
do -- this begins an anonymous block
local cheese = 22
print(cheese) -- prints 22
end
print(cheese) -- prints sandwich
So what we have here is two different variables: the outer one is "shadowed" by the inner one.
Now, onto functions:
do
local hotdog = 'hot'
function nonsense()
print(hotdog)
end
end
print(hotdog) -- prints nil, since there is no variable called hotdog here
nonsense() -- prints hot
Functions can see the local variables from where they are defined, not from where they are called. This is very important and very useful, once you get the hang of it.
I'm no expert in lua, but shouldn't var be passed as variable. Something like this:
function printthis(var)
print(var)
end
You're missing your var in function header. And you're passing your var in main.lua as an argument to printthis() function.