R automate testing? - arrays

Currently, I employ following script to test for something called Granger causality. Note: My main question is about the script structure, not the method.
#These values always have to be specified manually
dat <- data.frame(df[2],df[3])
lag = 2
# VAR-Model
V <- VAR(dat,p=lag,type="both")
V$var
summary(V)
wald.test(b=coef(V$var[[1]]), Sigma=vcov(V$var[[1]]), Terms=c(seq(2, by=2, length=lag)))
names(cof1[2])
wald.test(b=coef(V$var[[2]]), Sigma=vcov(V$var[[2]]), Terms=c(seq(1, by=2, length=lag)))
names(cof1[1])
Main issue is, that I always manually have to change the testing pair in dat <- data.frame(..). Further, I always manually enter "lag = x" after some tests on stationarity that can rather not be automated.
Let's say I would have to test following pairs:
df[2],df[3]
df[2],df[4]
df[2],df[5]
df[6],df[7]
df[8],df[9]
can I somehow state that in an array for the test? Assuming I would also know lag for each testing pair, could I also add that to it?
It would be perfect to directly output my test results into a table, instead of manually changing the data and then entering the result into an Excel/LaTeX.

Related

Behave BDD reusing steps from common step file

How do i re use steps from common_step.py
example:
common_feature:
Given log in with "abc" user
common_step:
#given('log in with "{user}" user')
anotherFile_feature
Given log in with "xyz" user
anotherFile_steps:
how do i pass that xyz user in here, can i get an example
thanks
If you need to reuse your user in another steps or parts of your code, shouldn't you just assign the value of the user to a variable?
#given('log in with "{user}" user')
def do_login(context, user)
context.user = user # the context variable will be accessible during execution time
First of all, I recommend that you post more documented questions, as it is difficult to understand what you are asking.
As #herickmota says, if you want to share values between different functions in your code you should use the context variable, which is shared by all the steps during the execution of the test, and in which you can store as many values as you want to be able to retrieve them wherever you want.
If, on the other hand, what you want is to call from a step to another step that you have already defined, you should use the context.execute_steps method, of which you have the documentation at https://behave.readthedocs.io/en/stable/api.html?=execute_steps#behave.runner.Context.execute_steps and you can see an example at https://jenisys.github.io/behave.example/tutorials/tutorial08.html.
I'll give you some examples:
This is the example of a valid directory tree. You must have the *.feature files inside a directory named "features" and also inside that directory you must have de "steps" directory with the steps definitions inside.
The second directory tree is an invalid directory tree, because the anohter_file_feature.feature file is unable to find the step definitions. In any case, I can't find any situation where you should separate the features in this way.
The last of the directory trees is the most commonly used sort, as it allows you to separate features into folders according to the criteria you see fit. This is the structure I would recommend to organise your Behave files.
Once we are clear about the valid distributions of the files in different folders, let's talk about how to call the methods from the different *.feature files.
To begin with, the first Scenario we have as an example would be the features/common_features/common_feature.feature, in which we make the most typical call to a step to which we pass a parameter, in this case the name "Manuel".
Feature: Common_feature
Scenario: Scenario number one
Given log in with "Manuel" user
The definition of the step is in the file features/steps/common_step.py
from behave import *
#given(u'log in with "{user}" user')
def step_impl(context, user):
print("I'm logging with the user: " + user)
The output if we run de command behave features/common_features/common_feature.feature is:
$ behave features/common_features/common_feature.feature
Feature: Common_feature # features/common_features/common_feature.feature:1
Scenario: Scenario number one # features/common_features/common_feature.feature:3
Given log in with "Manuel" user # features/steps/common_step.py:4
1 feature passed, 0 failed, 0 skipped
1 scenario passed, 0 failed, 0 skipped
1 step passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.001s
In another path, we have the file features/another_features/another_file_feature.feature in which we have defined the following two examples: one invoking again the step we already had declared in features/steps/common_step.py and another with a new step, which implicitly calls the step log in with "{user}" user:
Feature: Common_feature
Scenario: Scenario number two
Given log in with "José" user
Scenario: Scenario number three
Given calling indirectly with "Antonio" user
The definitions of the step we have in features/steps/another_file_steps.py is as follows:
from behave import *
#given(u'calling indirectly with {user} user')
def step_impl(context, user):
context.execute_steps("Given log in with " + user + " user")
And the output of running the command behave features/another_features/another_file_feature.feature is:
$ behave features/another_features/another_file_feature.feature
Feature: Common_feature # features/another_features/another_file_feature.feature:1
Scenario: Scenario number two # features/another_features/another_file_feature.feature:3
Given log in with "José" user # features/steps/common_step.py:4
Scenario: Scenario number three # features/another_features/another_file_feature.feature:7
Given calling indirectly with "Antonio" user # features/steps/another_file_steps.py:4
1 feature passed, 0 failed, 0 skipped
2 scenarios passed, 0 failed, 0 skipped
2 steps passed, 0 failed, 0 skipped, 0 undefined
Took 0m0.006s
As you can see, here are some basic examples of the file structure in Behave and how to call both directly and indirectly to the steps from the features.

Rails update remove number from an array attribute?

Is there a way to remove a number from an attibute array in an update? For example, if I want to update all of an alchy's booze stashes if he runs out of a particular type of booze:
Alchy has_many :stashes
Stash.available_booze_types = [] (filled with booze.ids)
Booze is also a class
#booze.id = 7
if #booze.is_all_gone
#alchy.stashes.update(available_booze_types: "remove #booze.id")
end
update: #booze.id may or may not be present in the available_booze_types array
... so if #booze.id was in any of the Alchy.stash instances (in the available_booze_types attribute array), it would be removed.
I think you can do what you want in the following way:
if #booze.is_all_gone
#alchy.stashes.each do |stash|
stash.available_booze_types.delete(#booze.id)
end
end
However, it looks to me like there are better ways to do what you are trying to do. Rails gives you something like that array by using relations. Also, the data in the array will be lost if you reset the app (if as I understand available_booze_types is an attribute which is not stored in a database). If your application is correctly set up (an stash has many boozes), an scope like the following in Stash class seems to me like the correct approach:
scope :available_boozes, -> { joins(:boozes).where("number > ?", 0) }
You can use it in the following way:
#alchy.stashes.available_boozes
which would only return the ones that are available.

Efficiently Creating Multiple Variables Using apply in R

I have a data frame DF which contains numerous variables. Each variable is present twice because I am conducting an analysis of "couples".
Among others, DF has a series of indicators of diversity :
DF$div1.1, DF$div2.1, .... , DF$divN.1, DF$div.1.2, ..., DF$divN.2
Similarly, it has a series of indicators of another characteristic:
DF$char1.1, DF$char2.1, .... , DF$charM.1, DF$char.1.2, ..., DF$charM.2
Here's a link to an example of DF: http://shorttext.com/5d90dd64
Each time the ".1", ".2" stand for the couple member considered.
My goal:
For each indicator divI and charJ, I want to create another variable DF$divchar that takes the value DF$divI.1 when DF$charJ.1>DF$charJ.2; and DF$divI.2 when DF$charJ.1<DF$charJ.2.
Here is the solution I came up with, it seems somehow very intricate and sometimes behaves in strange ways:
I created a series of binary variables that take the value one if DF$charJ.1>DF$charJ.2. The are stored under DF$CharMax.1.
Here's how I created it:
DF$CharMax.1 <- as.data.frame(
sapply(1:length(nam),
function(n)
as.numeric(DF[names(DF)==names.1[n]]
>DF[names(DF)==names.2[n]])
))
I created the function BinaryExtract:
BinaryExtract <- function(var1, var2, extract) {var1*extract +var2*(1-extract)}
I created the matrix NameFull that contains all the possible combinations of div and char, separated with "YY"
NameFull <- sapply(c("div1",...,"divN")
, function(nam) paste(nam, names(DF$YMax.1), sep="YY")
And then I create all my variables:
DF[, as.vector(NameFull)] <- lapply(as.vector(NameFull), function(e)
BinaryExtract(DF[,paste0(unlist(strsplit(e,"YY"))[1],".1")]
, DF[, paste0(unlist(strsplit(e,"YY"))[1],".1")]
, DF$charMax.1[unlist(strsplit(e,"YY"))[2]]))
My Problem
A. It looks like a very complicated solution for something that simple. What am I missing?
B. Moreover, when I print DF, just typing DF in the command window, I do not see the variables NameFull. They seem to appear with the names of char.
Here's what I get: http://shorttext.com/5d9102c
Similarly, I have tried to change all their names to get rid of the "YY" and it does not seem to work:
names(DF[, as.vector(NameFull)]) <- as.vector(c("div1",...,"divN"), sapply(, function(nam)
paste(nam, names(DF$YMax.1), sep=".")))
When I look at names(DF), I keep getting the old names with the "YY"
However, I do get a result if I explicitly call for them
> DF[,"divIYYcharJ"]
I would really appreciate any suggestion, comment and explanation. I am quite new to R ad was more used to Stata. I feel there is something deeply inefficient here. Thanks

Select random item from an array with certain probabilities and add it to the stage

Its quite a big task but ill try to explain.
I have an array with a list of 200 strings and I want to be able to randomly select one and add it to the stage using code. I have movieclips exported for actionscript with the same class name as the strings in the array. Also, if it is possible, would I be able to select the strings with predictability such as the first has a 0.7 chance the second a 0.1 etc. Here is what i have currently
var nameList:Array=["Jimmy","Bob","Fred"]
var instance:DisplayObject = createRandom(nameList);
addChild(instance);
function createRandom(typeArray:Array):*
{
// Select random String from typeArray.
var selection:String = typeArray[ int(Math.random() * typeArray.length) ];
// Create instance of relevant class.
var Type:Class = getDefinitionByName(selection) as Class;
// Return created instance.
return new Type();
}
All this throws me this error
ReferenceError: Error #1065: Variable [class Jimmy] is not defined.
Ive searched for other threads similar but none combine the three specific tasks of randomisation, predictability and addChild().
I think that you've got two problems: a language problem and a logic problem. In the .fla connected to your code above, in the Library find each symbol representing a name and write into the 'AS linkage' column for that symbol the associated name -- e.g., 'Bob,' 'Fred' -- just the name, no punctuation.
Now getDefinitionByName() will find your 'Class'
If you put a different graphic into each MovieClip -- say, a piece of fruit or a picture of Bob,Jim, Fred -- and run your program you'll get a random something on stage each time.
That should solve your language problem. But the logic problem is a little harder, no?
That's why I pointed you to Mr. Kelly's solution (the first one, which for me is easier to grasp).

NDB query giving different results on local versus production environment

I am banging my head into a wall over this and hoping you can tell me the very simple thing I have overlooked in my sleep deprived/noob state.
Very simply I am doing a query and the type of object returned is different on my local machine than what gets returned once I deploy the application.
match = MatchRealTimeStatsModel.queryMatch(ancestor_key)[0]
On my local machine the above produces a MatchRealTimeStatsModel object. So I can run the following to lines without a problem:
logging.info(match) # outputs a MatchRealTimeStatsModel object
logging.info(match.match) # outputs a dictionary from json data
When the above two lines are run on Goggles machines I get the following though:
logging.info(match) # outputs a dictionary from json data
logging.info(match.match) # AttributeError: 'dict' object has no attribute 'match'
Any suggestions as to what might be causing this? I cleared the data store and did everything I could think of to clean the GAE environment.
Edit #1: Adding MatchRealTimeStatsModel code:
class MatchRealTimeStatsModel(ndb.Model):
match = ndb.JsonProperty()
#classmethod
def queryMatch(cls, ancestor_key):
return cls.query(ancestor=ancestor_key).fetch()
And here is the actual call:
ancestor_key = ndb.Key('MatchRealTimeStatsModel', matchUniqueUrl)
match = MatchRealTimeStatsModel.queryMatch(ancestor_key)[0]
Perhaps you are using different versions of your code locally than in prod? Try to reset your copy of the source code in both places.

Resources