How to return a value from a closure function which returns itself? - return

How to return the variables "OurMin" and "counter" without passing by a global variable declaration like below, from a curried function which returns itself ?
"use strict";
let counter, OurMin;
function getMinimum(m) {
counter=1;
function fmin(v) {
m = Math.min(m, v);
/*****/ OurMin=m,++counter;
return fmin;
}
// The line of code below, What is it for ?
// It seems to absolutely do nothing !
// fmin.toString = _ => m;
return fmin;
}
/*** Added ***/ let dString='console.log("Minimum des "+counter + " nombres = " + OurMin)';
getMinimum(5)(2)(6);
/*** Added ***/ eval(dString);
getMinimum(7)(1)(4)(-1000);
getMinimum(-100)(17)(3)(10)(-5)(7)(-10);
I tried the cumbersome method below, it seems to work fine.
But I am sure you have a better, strait and lighter solution.
WITH ARRAY AS RETURN VALUE.
"use strict";
function getMinimum(m) {
let counter=1, OurMin;
function fmin(v) {
m = Math.min(m, v);
OurMin=m,++counter;
return [fmin,counter,OurMin];
}
return fmin;
}
let dString='console.log("Minimum des "+r[1] + " nombres = " + r[2])';
let r=getMinimum (5) (2) [0](6);
eval(dString);
// Minimum des 3 nombres = 2
r=getMinimum (7) (1) [0](4) [0](-10);
eval(dString);
// Minimum des 4 nombres = -10
r=getMinimum(10) (-1700) [0](3) [0](17) [0](-5) [0](7) [0](-10);
eval(dString);
// Minimum des 3 nombres = 2
WITH OBJECT AS RETURN VALUE.
IT SEEMS TO ME WORTH AND MORE PLEASANT THAN THE ABOVE.
"use strict";
function getMinimum(m) {
let counter=1, OurMin;
function fmin(v) {
m = Math.min(m, v);
OurMin=m , ++counter;
return {fmin:fmin,counter:counter,OurMin:OurMin};
}
return fmin;
}
let dString2="console.log(`Minimum des ${r2['counter']} nombres = ${r2['OurMin']}`)";
let r2=getMinimum (5) (2)["fmin"] (6);
eval(dString2);
// Minimum des 3 nombres = 2
r2=getMinimum (7) (1)["fmin"] (4)["fmin"] (-10);
eval(dString2);
// Minimum des 4 nombres = -10
r2=getMinimum(10) (-1700)["fmin"] (3)["fmin"] (17)["fmin"] (-5)["fmin"] (7)["fmin"] (-10);
eval(dString2);
// Minimum des 7 nombres = -1700
At last, what is the particular importance of such a long and cumbersome development over using directly the Math method "Math.min()", for example Math.min(5,3,2,0,-3,100,7), and which is the importance of sending only one argument a time ?

Related

NEAT - population number varies every generation

I'm trying to implement my own neat implementation and I can't get myself to understand how speciation works
I tried my best to follow the pesudocode I found in this paper (start of page 13)
but I'm think I'm doing it really wrong but I don't understand the right way to do it, here is my code
the sepciate function that splits the population into species:
function speciate(population, species=[]) {
let newSpecies = [...species];
for(const net of population) {
let placed = false;
for(const s of newSpecies) {
for(const member of s) {
if(sh(net, member)) {
s.push(net);
placed = true;
break;
}
}
if(placed) break;
}
if(!placed) {
newSpecies.push([net]);
}
}
return newSpecies;
}
the repopulation function that generates a new population using the number of offsprings:
function repopulate(popCount, species) {
let globalAvg = 0;
species.forEach(s => {
globalAvg += s.reduce((P, net) => P + net.genome.fitness, 0) / s.length;
});
let newPop = [];
for(const s of species) {
let N = popCount;
let sAvg = s.reduce((P, net) => P + net.genome.fitness, 0) / s.length;
let offspringCount = (sAvg / globalAvg) * N;
for(let i = 0; i < offspringCount; i++) {
let parent1 = wheelSelect(s);
let parent2 = wheelSelect(s);
let child = parent1.genome.crossover(parent2.genome);
child.mutateAddNeuron(0.01);
child.mutateAddConnection(0.01);
child.mutateWeight(0.01);
child.mutateEnabledToggle(0.01);
child.layerNeurons();
let net = new NeuralNetwork();
net.wireUsingGenome(child);
newPop.push(net);
}
}
return newPop;
}
the problem I'm facing is that the population number seems to change every new generation sometimes it goes up and sometimes down, so I'm gussing I'm calculating the offspring count wrong or my speciation isn't working correctly but I can't figure it out
any help is appreciated!

Can't get Indicator pivot points to match on EA code

I've been messing around with the Camarilla Indicator and I wanted to get the main pivot values for my EA, can I use iCustom() for that? or should I just pass the code to the EA? but where exactly would I place it? I tried to place it on the onTick() but with a condition of only calculating the pivots when there is a new daily candle, but the values most of the times don't match.
void OnTick()
{
static datetime today;
if (today != iTime (Symbol(), PERIOD_D1, 0))
{
today = iTime (Symbol(), PERIOD_D1, 0);
int counted_bars=IndicatorCounted();
//---- TODO: add your code here
int cnt=720;
//---- exit if period is greater than daily charts
if(Period() > 1440)
{
Print("Error - Chart period is greater than 1 day.");
}
//---- Get new daily prices & calculate pivots
day_high=0;
day_low=0;
yesterday_open=0;
today_open=0;
cur_day=0;
prev_day=0;
while (cnt!= 0)
{
if (TimeDayOfWeek(Time[cnt]) == 0)
{
cur_day = prev_day;
}
else
{
cur_day = TimeDay(Time[cnt]- (GMTshift*3600));
}
if (prev_day != cur_day)
{
yesterday_close = Close[cnt+1];
today_open = Open[cnt];
yesterday_high = day_high;
yesterday_low = day_low;
day_high = High[cnt];
day_low = Low[cnt];
prev_day = cur_day;
}
if (High[cnt]>day_high)
{
day_high = High[cnt];
}
if (Low[cnt]<day_low)
{
day_low = Low[cnt];
}
cnt--;
}
H3 = ((yesterday_high - yesterday_low)* D3) + yesterday_close;
H4 = ((yesterday_high - yesterday_low)* D4) + yesterday_close;
L3 = yesterday_close - ((yesterday_high - yesterday_low)*(D3));
L4 = yesterday_close - ((yesterday_high - yesterday_low)*(D4));
L5 = yesterday_close - (H5 - yesterday_close);
H5 = (yesterday_high/yesterday_low)*yesterday_close;
Print ("H3: " + DoubleToStr(H3));
Print ("H4: " + DoubleToStr(H4));
Print ("H5: " + DoubleToStr(H5));
Print ("L3: " + DoubleToStr(L3));
Print ("L4: " + DoubleToStr(L4));
Print ("L5: " + DoubleToStr(L5));
}

How to make my go parser code more readable

I'm writing a recursive descent parser in Go for a simple made-up language, so I'm designing the grammar as I go. My parser works but I wanted to ask if there are any best practices for how I should lay out my code or when I should put code in its own function etc ... to make it more readable.
I've been building the parser by following the simple rules I've learned so far ie. each non-terminal is it's own function, even though my code works I think looks really messy and unreadable.
I've included the code for the assignment non-terminal and the grammar above the function.
I've taken out most of the error handling to keep the function smaller.
Here's some examples of what that code can parse:
a = 10
a,b,c = 1,2,3
a int = 100
a,b string = "hello", "world"
Can anyone give me some advice as to how I can make my code more readable please?
// assignment : variable_list '=' expr_list
// | variable_list type
// | variable_list type '=' expr_list
func (p *Parser) assignment() ast.Noder {
assignment := &ast.AssignmentNode{}
assignment.Left = p.variable_list()
// This if-statement deals with rule 2 or 3
if p.currentToken.Type != token.ASSIGN {
// Static variable declaration
// Could be a declaration or an assignment
// Only static variables can be declared without providing a value
assignment.IsStatic = true
assignment.Type = p.var_type().Value
assignment.Right = nil
p.nextToken()
// Rule 2 is finished at this point in the code
// This if-statement is for rule 3
if p.currentToken.Type == token.ASSIGN {
assignment.Operator = p.currentToken
p.nextToken()
assignment.Right = p.expr_list()
}
} else {
// This deals with rule 1
assignment.Operator = p.currentToken
p.nextToken()
assignment.Right = p.expr_list()
}
if assignment.Right == nil {
for i := 0; i < len(assignment.Left); i++ {
assignment.Right = append(assignment.Right, nil)
}
}
if len(assignment.Left) != len(assignment.Right) {
p.FoundError(p.syntaxError("variable mismatch, " + strconv.Itoa(len(assignment.Left)) + " on left but " + strconv.Itoa(len(assignment.Right)) + " on right,"))
}
return assignment
}
how I can make my code more readable?
For readability, a prerequisite for correct, maintainable code,
// assignment : variable_list '=' expr_list
// | variable_list type
// | variable_list type '=' expr_list
func (p *Parser) assignment() ast.Noder {
assignment := &ast.AssignmentNode{}
// variable_list
assignment.Left = p.variable_list()
// type
if p.currentToken.Type != token.ASSIGN {
// Static variable declaration
// Could be a declaration or an assignment
// Only static variables can be declared without providing a value
assignment.IsStatic = true
assignment.Type = p.var_type().Value
p.nextToken()
}
// '=' expr_list
if p.currentToken.Type == token.ASSIGN {
assignment.Operator = p.currentToken
p.nextToken()
assignment.Right = p.expr_list()
}
// variable_list [expr_list]
if assignment.Right == nil {
for i := 0; i < len(assignment.Left); i++ {
assignment.Right = append(assignment.Right, nil)
}
}
if len(assignment.Left) != len(assignment.Right) {
p.FoundError(p.syntaxError(fmt.Sprintf(
"variable mismatch, %d on left but %d on right,",
len(assignment.Left), len(assignment.Right),
)))
}
return assignment
}
Note: This likely inefficient and overly complicated:
for i := 0; i < len(assignment.Left); i++ {
assignment.Right = append(assignment.Right, nil)
}
What is the type of assignment.Right?
As far as how to make your code more readable, there is not always a cut and dry answer. I personally find that code is more readable when you can use function names in place of comments in the code. A lot of people like to recommend the book "Clean Code" by Robert C. Martin. He pushes this throughout the book, small functions that have one purpose and are self documenting (via the function name).
Of course, as I said before this is a subjective topic. I took a crack at it, and came up with the code below, which I personally feel is more readable. It also uses the function names to document what is going on. That way the reader doesn't necessarily need to dig into every single statement in the code, but rather just the high level function names if they don't need all of the details.
// assignment : variable_list '=' expr_list
// | variable_list type
// | variable_list type '=' expr_list
func (p *Parser) assignment() ast.Noder {
assignment := &ast.AssignmentNode{}
assignment.Left = p.variable_list()
// This if-statement deals with rule 2 or 3
if p.currentToken.Type != token.ASSIGN {
// Static variable declaration
// Could be a declaration or an assignment
// Only static variables can be declared without providing a value
p.parseStaticStatement(assignment)
} else {
p.parseVariableAssignment(assignment)
}
if assignment.Right == nil {
assignment.appendDefaultValues()
}
p.checkForUnbalancedAssignment(assignment)
return assignment
}
func (p *Parser) parseStaticStatement(assignment *ast.AssingmentNode) {
assignment.IsStatic = true
assignment.Type = p.var_type().Value
assignment.Right = nil
p.nextToken()
// Rule 2 is finished at this point in the code
// This if-statement is for rule 3
if p.currentToken.Type == token.ASSIGN {
a.parseStaticAssignment()
}
}
func (p *Parser) parseStaticAssignment(assignment *ast.AssignmentNode) {
assignment.Operator = p.currentToken
p.nextToken()
assignment.Right = p.expr_list()
}
func (p *Parser) parseVariableAssignment(assignment *ast.AssignmentNode) {
// This deals with rule 1
assignment.Operator = p.currentToken
p.nextToken()
assignment.Right = p.expr_list()
}
func (a *ast.AssignmentNode) appendDefaultValues() {
for i := 0; i < len(assignment.Left); i++ {
assignment.Right = append(assignment.Right, nil)
}
}
func (p *Parser) checkForUnbalancedAssignment(assignment *ast.AssignmentNode) {
if len(assignment.Left) != len(assignment.Right) {
p.FoundError(p.syntaxError("variable mismatch, " + strconv.Itoa(len(assignment.Left)) + " on left but " + strconv.Itoa(len(assignment.Right)) + " on right,"))
}
}
I hope that you find this helpful. I am more than willing to answer any further questions that you may have if you leave a comment on my response.

AdWords Script With Divergent Data from Webview

I have the following code on an AdWords script:
var campanha = 'xyz';
function main() {
campanhas = AdWordsApp.campaigns().withCondition("CampaignName = '" + campanha + "'").withCondition('Status = ENABLED').get();
while(campanhas.hasNext()) {
campanha = campanhas.next();
if(campanha.getBiddingStrategyType() != 'ENHANCED_CPC') {
Logger.log('Ajuste de lance da campanha inválido: ' +campanha.getBiddingStrategyType());
continue;
}
palavras = campanha.keywords().withCondition('Status = ENABLED').forDateRange("YESTERDAY").get();
while(palavras.hasNext()) {
palavra = palavras.next();
estatisticas = palavra.getStatsFor('YESTERDAY');
lances = palavra.bidding();
estimativa_primeira = Math.max(palavra.getTopOfPageCpc(), palavra.getFirstPageCpc());
posicao = estatisticas.getAveragePosition();
if (posicao > 1) {
Logger.log(palavra.getText() +" = " +" "+palavra.getTopOfPageCpc()+" "+palavra.getFirstPageCpc());
}
//Logger.log(palavra.getText() + ' = '+lances.getCpc()+" = "+estatisticas.getAveragePosition());
}
}
I expected to retrieve the estimated first page CPC and estimated first position CPC. But the values that I received are diferente from the AdWords webinterface. For exemple, for a given keyword the script returned +xxx +yyyy = 0.12 0.05, when I look those keywords on webinterface I have the following values for 0.12 for estimated first page CPC and 0.41 for estimated first position CPC.

Program doesn't work without an initial value

The program works fine with var dig = 0 and it doesn't work with var dig:Int I get an error: Variable "dig" used before being initialized Could you explain me why?
func myFunc(a:Int, b:Int) {
var c = a / b
var o = a % b
var v = 0
var dig = 0
if o != 0 {println("\(a)/\(b) = \(c) и \(o)/\(b)")}
else {println("\(a)/\(b) = \(c)")}
if a > b {
v = b
}
else {
v = a
}
for var i = 1; i <= v; ++i {
if a % i == 0 && b % i == 0 {dig = i}
}
println("\(dig) -  greatest common denominator of \(a) and \(b)")
}
myFunc(27,81)
The only place you set the value of dig is inside of an if statement that is inside of a for loop. The Swift compiler does not know if the body of the for loop will be executed, and it doesn't know if the if statement will ever be true, so it has to assume that there is a path in which dig is not initialized.
Consider this simpler example:
func myFunc(a:Int, b:Int) {
var dig: Int
if a >= b {
dig = 3
}
if a < b {
dig = 4
}
println("\(dig) - greatest common denominator of \(a) and \(b)")
}
This example also gives the same error, because Swift considers each if separately. It is obvious to us that a is either greater than or equal to b or it is less than b, but Swift doesn't go that far in evaluating the situation. It just considers that each if may not be true, and dig is only set inside of ifs, so it is possible (as far as Swift is concerned) that dig may not be set.
func myFunc(a:Int, b:Int) {
var dig: Int
if a >= b {
dig = 3
} else {
dig = 4
}
println("\(dig) - greatest common denominator of \(a) and \(b)")
}
If you change the second condition to an else, Swift is then happy because it can reason that the if must be true or false and dig is set in each path, so it will certainly have a value before the println statement.
The compiler does not know mathematics good enough to
recognize that the statement
if a % i == 0 && b % i == 0 {dig = i}
is actually executed at least once (for i == 1). Therefore
the compiler assumes that dig might be undefined at
println("\(dig) - greatest common denominator of \(a) and \(b)")
Assigning an initial value in
var dig = 0
is the correct solution.
Btw., the Euclidean Algorithm is a much more effective method to
compute the greatest common divisor, see for example
http://rosettacode.org/wiki/Greatest_common_divisor#Swift.

Resources