How to import class data prior to instantiate the class - r

Assuming that the class and instantiation of class are held in 2 separate files, how would you import the class data prior to instantiate the class?
Below code works fine if held in one same file, but I suspect that as soon as the code base starts growing you would want to split the data into smaller code chunks.
Should I use [source], does it exist an autoloader or any another guideline?
File: _class_data.R
if (!"package:R6" %in% search()) {
library(R6)
}
# Class 1
Class_1 <- R6Class("Class_1",
public = list(
# Properties:
x = 0,
# Lists:
credentials = list(
user = "user",
password = "pass"
),
# Functions:
myFunction = function() {
return(self$x)
}
)
)
File: run.R
# Should I add a [source] path here to [ _class_data.R] ?
# Instantiate a class by creating an object.
class_1 <- Class_1$new()

If I understand your question, you should be creating a package say MyPackage (containing your classes Class_1) and other person would be consumer, they would need to do library(MyPackage) in their code, before consuming the class.
You can source it if all the consumers are part of the same package.

The most straightforward way is to first run or source the class file. In this case the result will be an environment object that is stored in R:s global environment. This is the class.
As a second step you create an object, by instantiate the same class.
If this instantation is kept within a separate file, you would have to run or source that file also.
Since both objects (class and object) will now exist in the Global environment you can now decide if you want to remove the class and just keep the object.
Following standard guidelines the only name convention difference between the 2 objects would be that the class name start with a capital letter, meanwhile the object holds same name but with all characters in lower case.
If the amount of classes grows it is of course unpractical to administrate the objects one-by-one, and you would probably need some autoload logics.

Related

Create groups of functions with same name within single module without classes

I am writing a card game simulator. During play, I want different players to have different strategies. My idea is to have 2 functions specified for a given agent than can be imported. These functions would have the same signatures. I know how to do this with classes and inheritance, but I'm trying to code this project entirely functionally. Here is what I have if I were to do it with classes:
class Agent:
def __init__(self,position):
self.pos = position
def flip_two(self,gs):
pass
def regular_move(self,gs):
pass
class Random_Agent(Agent):
def flip_two(self,gs):
#some code that alters gs randomly
def regular_move(self,gs):
#some code that alters gs randomly
class etc_Agents(Agent):
.
.
.
The best answer I can think of so far is to put each agent in a new file, since modules would be a way to group the functions.
Thanks for any insight!
If you wish to group related functions, you could place them in a dictionary like so:
options = {
'a' : {'sameName' : lambda x: x*2},
'b' : {'sameName' : lambda x: x**2}
}
print(options['a']['sameName'](5))
print(options['b']['sameName'](5))

How to call "public void" method through rJava

In testing a Java API, I need to change a default setting. According to the API's document, it should be done using a method defined within the class using "public void setType". Suppose the class name is 'Node', which is referred using
library(rJava)
.jinit(classpath=jarPath)
Node <- J("Node")
In an Java example from its documents, it's called as
Node nodeX = new Node("X", new Variable[]{x});
nodeX.setType(Type.TEMP);
The default type of nodeX is 'CONTEMP'. How the "setType" method can be called in R through rJava to change its default value to another one? Let's assume 'Type' is an enum variable which has several options, including "CONTEMP","TEMP", etc.
I think you want
library(rJava)
.jinit(classpath=jarPath)
variable <- .jarray(new(J("package.name.Variable", input_arg))
Node <- new(J("package.name.Node"), variable)
Then you can do
type <- J("package.name.Type")$TEMP
Node$setType(type)

Folio-Epicenter example (Julia + uibuilder)

I'm trying to get the basic Forio Epicenter example from the documentation to work, using Julia and the UI Builder. It looks like this:
#in MyModel.jl
module MyModel
# use the Epicenter Julia package
using Epicenter
# expose methods you want to call
# (e.g. using the Run API or Model Operation API,
# or the Model Operation property of a component in UI Builder)
export doubleIt
# expose variables you want to view or update
# (e.g. using the Run API or Model Variable API,
# or the Model Variable property of a component in UI Builder)
export parameters, result
# make exposed variables global
global parameters, result
# define variables that the end user will change as part of a complex type
type ParametersType
input1
input2
function ParametersType()
item = new()
item
end
end
function doubleIt()
global parameters
global result
result = parameters.input1 * 2
record(:result)
end
# other files in your model
include("Utils.jl")
include("OtherModelCalculations.jl")
end
I can't get any variables to connect. When I make a "Text Input" component and change the "Model Variable" property to match the Julia variable (exposed via "export" and "global"), loading the page gives me
400 Bad Request
Full JSON response:
{"status":400,
"errors":{"status":400,
"internal":{
"procedure":"push!(LOAD_PATH, string(ENV[\"HOME\"],
\"\/model\/\")); import Epicenter; using Juliet; using EpicenterSystem; EpicenterSystem.setup_idle_timeout
(1800); require(\"MyModel.jl\"); using MyModel","sessionId":"c5b8189b-4f4d-4377-87a9-ca8d154863c0","trace":""}
},
"message":"Bad Request."
}
I've tried every combination of the "Model Variable" I can think of, including "input1", "parameters", and "parameters.input1"; always comes back with a 400 error.
Forio Support here.
Two problems
a) since "input1" is a field in of variable parameters (type ParameterTypes), it must be referred to in the interface as "parameters.input1"
b) More importantly, the model attempts to include Utils.jl and OtherModelCalculations.jl, neither of which exist. Thus the model never loads.

how to run and get document stats from boilerpipe article extractor?

There's something I'm not quite understanding about the use of boilerpipe's ArticleExtractor class. Albeit, I am also very new to java, so perhaps my basic knowledge of this enviornemnt is at fault.
anyhow, I'm trying to use boilerpipe to extract the main article from some raw html source I have collected. The html source text is stored in a java.lang.String variable (let's call it htmlstr) variable that has the raw HTML contents of a webpage.
I know how to run boilerpipe to print the extracted text to the output window as follows:
java.lang.String htmlstr = "<!DOCTYPE.... ****html source**** ... </html>";
java.lang.String article = ArticleExtractor.INSTANCE.getText(htmlstr);
System.out.println(article);
However, I'm not sure how to run BP by first instantiating an instance of the ArticleExtractor class, then calling it with the 'TextDocument' input datatype. The TextDocument datatype is itself somehow constructed from BP's 'TextBlock' datatype, and perhaps I am not doing this correctly...
What is the proper way to construct a TextDocument type variable from my htmlstr string variable?
So my problem is then in using the processing method of BP's Article Extractor class aside from calling the ArticleExtractor getText method as per the example above. In other words, I'm not sure how to use the
ArticleExtractor.process(TextDocument doc);
method.
It is my understanding that one is required to run this ArticleExtractor process method to then be able to use the same "TextDocument doc" variable for getting document stats, using BP's
TextDocumentStatistics(TextDocument doc, boolean contentOnly)
method? I would like to use the stats to determine how good the filtering was estimated to be.
Any code examples someone could help me out with?
Code written in Jython (Conversion to java should be easy)
1) How to get TextDocument from a HTML String:
import org.xml.sax.InputSource as InputSource
import de.l3s.boilerpipe.sax.HTMLDocument as HTMLDocument
import de.l3s.boilerpipe.document.TextDocument as TextDocument
import de.l3s.boilerpipe.sax.BoilerpipeSAXInput as BoilerpipeSAXInput
import de.l3s.boilerpipe.extractors.ArticleExtractor as ArticleExtractor
import de.l3s.boilerpipe.estimators.SimpleEstimator as SimpleEstimator
import de.l3s.boilerpipe.document.TextDocumentStatistics as TextDocumentStatistics
import de.l3s.boilerpipe.document.TextBlock as TextBlock
htmlDoc = HTMLDocument(rawHtmlString)
inputSource = htmlDoc.toInputSource()
boilerpipeSaxInput = BoilerpipeSAXInput(inputSource)
textDocument = boilerpipeSaxInput.getTextDocument()
2) How to process TextDocument using Article Extractor (continued from above)
content = ArticleExtractor.INSTANCE.getText(textDocument)
3) How to get TextDocumentStatistics (continued from above)
content_list = [] #replace python 'List' Object with ArrayList in java
content_list.append(TextBlock(content)) #replace with arrayList.add(TextBlock(content))
content_td = TextDocument(content_list)
content_stats = TextDocumentStatistics(content_td, True)#True for article content statistics only
Note: The java docs accompanied with the boilerpipe 1.2.jar library should be somewhat useful for future reference

How to control inheritance when dynamically extending Reference Classes

In a webcrawler/webscraper-setting, I'd like to dynamically extend my base Reference Class URL in order to be able to write specific methods for respective hosts/domains. Just to be clear, by dynamically I mean something like "automatically generate class definitions as new domains are encountered (e.g. class URL_something.com which would inherit from class URL)".
Works a treat, the only problem is that my class WebPage expects the value of field url to be of class URL. It will accept objects of class URL_something.com as this inherits from class URL, but then actually turns the object into an instance of class URL. So I lose the information that it's actually of class URL_something.com.
Do you have any idea of how I can prevent losing that crucial information?
Code Example
setRefClass(Class="URL", fields=list(x="character"))
setRefClass(Class="WebPage", fields=list(url="URL"))
obj <- new("WebPage", url=new("URL", x="http://www.something.com/home/index.html"))
obj$url
# Method would recognize that there is no class 'URL_something.com'
# yet and thus create it:
setRefClass(Class="URL_something.com", contains="URL")
# Another method would take care of mapping field values to
# an instance of the new class:
> url.obj <- new("URL_something.com", x="http://www.something.com/home/index.html")
> inherits(url.obj, "URL")
[1] TRUE
> obj$url <- url.obj
> class(obj$url)
[1] "URL"
# So I lose the information that it was actually of class "URL_something.com"
Picking up on what Martin said (see comments above): R 2.14.0 fixes what I described above.

Resources