Enumeration (enum in lua) .Want to use enum in lua5.2.4 - enums

I have a condition where in my lua script I want to use enum like for SUCCESS I can give 1 and for FAILURE I can give 0
I am using lua version 5.2.4
Can anyone please help me on how to use enum
I want to use enum
elseif(cc_config_cmd == "DELETE" and file_found==1)then
api:executeString("callcenter_config queue unload " .. queue_name)
stream:write("1")
else
stream:write("0")
end

There are no enums in Lua.
Simply define variables.
SUCCESS = "1"
FAILURE = "0"
stream:write(SUCCESS)
Or put it into a table which would be quite similar to enum style syntax.
Result = {SUCCESS = "1", FAILURE = "0"}
stream:write(Result.SUCCESS)

As far as I know, there is no enums in Lua, you can use strings such as your current code. The strings will be interned inside the Lua Virtual Machine, so in the memory the strings will not be duplicated.
Another option will be to use numbers in place of strings.
local COMMAND_DELETE = 1
local COMMAND_TEST_1 = 2
local COMMAND_TEST_2 = 3
Other options would be to use a third-party package such as the enum package or maybe go further and use a Lua Preprocessor

Related

Using one variable for multiple items data in descriptive programming

I know that with Descriptive programming you can do something like this:
Browser("StackOverflow").Page("StackOverflow").Link("text:=Go To Next Page ", "html tag:=A").Click
But is it possible to create some kind of string so I can assign more than one data value and pass it as single variable? I've tried many combinations using escape characters and I always get error.
For example in the case above, let's say I have more properties in the Page object, so I'd normally have to do something like this:
Browser("StackOverflow").Page("name:=StackOverflow", "html id:=PageID")...etc...
But I'd like to pass "name:=StackOverflow", "html id:=PageID" as a single variable, so when writing many objects I'd only have to write:
Browser(BrowserString).Page(PageString).WebEdit("name:=asdfgh")
And the first part would remain static, so if the parents' data needs to be modified I'd only have to modify two variables and not all the objects created in all libraries.
Is it possible?
If I was not clear enough please let me know.
Thank you in advance!
I think what you're looking for is UFT's Description object
This allows you finer grained control on the description since in descriptive programming all values are regular expressions but with Description you can turn the regular expression functionality off for a specific property.
Set desc = Description.Create()
desc("html tag").Value = "A"
desc("innertext").Value = "More information..."
desc("innertext").RegularExpression = False
Browser("Example Domain").Navigate "www.example.com"
Browser("Example Domain").Page("Example Domain").WebElement(desc).Click
If you want to represent this with plain string then it's a bit more of a problem, you can write a helper function but I'm not sure I would recommend it.
Function Desc(descString)
Set ret = Description.Create()
values = Split(descString, "::")
For Each value In values
keyVal = Split(value, ":=")
ret(keyVal(0)).Value = keyVal(1)
Next
Set Desc = ret
End Function
' Usage
Browser("StackOverflow").Page("StackOverflow").WebElement(Desc("html tag:=H2::innertext:=some text")).Click
Further reading about descriptive programming.
As an alternative to Motti's excellent answer, you could also Set a variable to match your initial descriptive object and then extend it as required:
Set myPage = Browser("StackOverflow").Page("name:=StackOverflow", "html id:=PageID")
after which you can then use
myPage.WebEdit("name:=asdfgh")
throughout the rest of the code, so long as the myPage object stays in scope...

Rails dynamic params.require(...).permit(...) syntax?

I can do this code:
params.require(:something).permit(:param_a,:param_b)
And this:
params.require(:something).permit(:param_a,:param_c_attributes:[])
My problem is that I need to select the permit parameters depending if some parameter exists. So I tried:
premit_params = {:param_a,:param_c_attributes:[]}
premit_params = {:param_a,:param_d} if params[:something] && params[:something][:param_d]
params.require(:something).permit(premit_params)
But it's not working.
BTW: Using Rails 5.1
It doesn't work because permit doesn't expect a hash as an argument, but a list of parameters.
Collect your arguments in an array and split that array with the splat operator (*) to list or arguments:
premit_params = [:param_a, { :param_c_attributes: [] }]
premit_params = [:param_a, :param_d] if params.dig(:something, :param_d)
params.require(:something).permit(*premit_params)
You can check if the parameter you want exits
For Example:
if (user_params.has_key?(:name))
end
Moreover, parameters are saved in hash so you have different methods you can use to apply your logic
https://ruby-doc.org/core-1.9.3/Hash.html

How to use polymorphism to remove a switch statement which compares strings?

I am new to Ruby, so let me describe the context of my problem first:
I have a json as input which has the following key / value pair:
{
"service": "update"
}
The value has many different values for example: insert,delete etc.
Next there is a method x which handles the different requests:
def x(input)
case input[:service]
services = GenericService.new
when "update"
result = services.service(UpdateService.new,input)
when "insert"
result = services.service(InsertService.new,input)
when "delete"
result = services.service(DeleteService.new,input)
....
....
else
raise "Unknown service"
end
puts JSON.pretty_generate(result)
end
What is bothering me is that I still need to use a switch statement to check the String values (reminds me of 'instance of' ugh..). Is there a cleaner way (not need to use a switch)?
Finally I tried to search for an answer to my question and did not succeed, if however I missed it feel free to comment the related question.
Update: I was thinking to maybe cast the string to the related class name as follows: How do I create a class instance from a string name in ruby? and then call result = services.services(x.constantize.new,input) , then the class names ofcourse needs to match the input of the json.
You can try something like:
def x(input)
service_class_name = "#{input[:service].capitalize}Service"
service_class = Kernel.const_get(service_class_name)
service_class.new(input).process
end
In addition you might want to check if this is a valid Service class name at all.
I don't understand why you want to pass the service to GenericService this seems strange. let the service do it's job.
If you're trying to instatiate a class by it's name you're actually speaking about Reflection rather than Polymorphism.
In Ruby you can achieve this in this way:
byName = Object.const_get('YourClassName')
or if you are in a Rails app
byName= 'YourClassName'.constantize
Hope this helps
Just first thoughts, but you can do:
eval(services.service("#{input[:service].capitalize}Service.new, #{input})") if valid_service? input[:service]
def valid_service?
w%(delete update insert).include? input[:service]
end
As folks will no doubt shout, eval needs to be used with alot of care

CAS registry to Pubchem cid identifier conversion in R

An annoying problem many chemists are faced with is to convert CAS registry numbers of chemical compounds (stored in some commercial database that is not readily accessible) to Pubchem identifiers (openly available). Pubchem kind of supports conversion between the two, but only through their manual web interface, and not their official PUG REST programmatic interface.
A solution in Ruby is given here, based on the e-utilities interface: http://depth-first.com/articles/2007/09/13/hacking-pubchem-convert-cas-numbers-into-pubchem-cids-with-ruby/
Does anybody know how this would translate into R?
EDIT: based on the answerbelow, the most elegant solution is:
library(XML)
library(RCurl)
CAStocids=function(query) {
xmlresponse = xmlParse( getURL(paste("http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&retmax=100&term=",query,sep="") ) )
cids = sapply(xpathSApply(xmlresponse, "//Id"), function(n){xmlValue(n)})
return(cids)
}
> CAStocids("64318-79-2")
[1] "6434870" "5282237"
cheers,
Tom
This how the Ruby code does it, translated to R, uses RCurl and XML:
> xmlresponse = xmlParse( getURL("http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&retmax=100&term=64318-79-2") )
and here's how to extract the Id nodes:
> sapply(xpathSApply(xmlresponse, "//Id"), function(n){xmlValue(n)})
[1] "6434870" "5282237"
wrap all that in a function....
convertU = function(query){
xmlresponse = xmlParse(getURL(
paste0("http://www.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pccompound&retmax=100&term=",query)))
sapply(xpathSApply(xmlresponse, "//Id"), function(n){xmlValue(n)})
}
> convertU("64318-79-2")
[1] "6434870" "5282237"
> convertU("64318-79-1")
list()
> convertU("64318-78-2")
list()
> convertU("64313-78-2")
[1] "313"
maybe needs a test if not found.
I think you should still be able to convert CAS numbers to PubChem ID's using the PUG where instead of the name of the compound you enter the CAS number. Of course this might not be as specific if the CAS numbers overlap. I haven't tested it.
An example with aspirin
https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/name/50-78-2/cids/JSON

How do I marshal a lambda (Proc) in Ruby?

Joe Van Dyk asked the Ruby mailing list:
Hi,
In Ruby, I guess you can't marshal a lambda/proc object, right? Is
that possible in lisp or other languages?
What I was trying to do:
l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
So, I'm sending BackgroundJob a lambda object, which contains the
context/code for what to do. But, guess that wasn't possible. I
ended up marshaling a normal ruby object that contained instructions
for what to do after the program ran.
Joe
You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)
As Gaius pointed out though, you can use ruby2ruby to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later.
you could also just enter your code as a string:
code = %{
lambda {"hello ruby code".split(" ").each{|e| puts e + "!"}}
}
then execute it with eval
eval code
which will return a ruby lamda.
using the %{} format escapes a string, but only closes on an unmatched brace. i.e. you can nest braces like this %{ [] {} } and it's still enclosed.
most text syntax highlighters don't realize this is a string, so still display regular code highlighting.
If you're interested in getting a string version of Ruby code using Ruby2Ruby, you might like this thread.
Try ruby2ruby
I've found proc_to_ast to do the best job: https://github.com/joker1007/proc_to_ast.
Works for sure in ruby 2+, and I've created a PR for ruby 1.9.3+ compatibility(https://github.com/joker1007/proc_to_ast/pull/3)
Once upon a time, this was possible using ruby-internal gem (https://github.com/cout/ruby-internal), e.g.:
p = proc { 1 + 1 } #=> #<Proc>
s = Marshal.dump(p) #=> #<String>
u = Marshal.load(s) #=> #<UnboundProc>
p2 = u.bind(binding) #=> #<Proc>
p2.call() #=> 2
There are some caveats, but it has been many years and I cannot remember the details. As an example, I'm not sure what happens if a variable is a dynvar in the binding where it is dumped and a local in the binding where it is re-bound. Serializing an AST (on MRI) or bytecode (on YARV) is non-trivial.
The above code works on YARV (up to 1.9.3) and MRI (up to 1.8.7). There's no reason why it cannot be made to work on Ruby 2.x, with a small amount of effort.
If proc is defined into a file, U can get the file location of proc then serialize it, then after deserialize use the location to get back to the proc again
proc_location_array = proc.source_location
after deserialize:
file_name = proc_location_array[0]
line_number = proc_location_array[1]
proc_line_code = IO.readlines(file_name)[line_number - 1]
proc_hash_string = proc_line_code[proc_line_code.index("{")..proc_line_code.length]
proc = eval("lambda #{proc_hash_string}")

Resources