text:
anonymous one year ago Under what conditions would the length of a day be the same as the length of a night, year-round? A. if earth’s axis weren’t tilted B. if earth’s orbit were closer to the sun C. if earth had no moon D. if earth’s revolution were faster

• This Question is Open
1. anonymous

@texaschic101

2. anonymous

A tilt in the earth causes the day and night period to change.

3. anonymous

so? i dont get it

4. anonymous

ohh so the anwser is A?

5. anonymous

The question is asking which condition would day period=night period. If earth did not tilt then day period would equal the night period.

6. anonymous

If it did tilt it would change.

7. anonymous

ooh ok thanks can you help with more

8. anonymous

9. anonymous

What season does the southern hemisphere experience when it is tilted away from the sun? A. autumn B. spring C. winter D. summer

10. anonymous

i only have like 7 more

11. anonymous

Hint: if it is away from the sun then it is the opposite.

12. anonymous

winter right?

13. anonymous

yes.

14. anonymous

During which season in the Northern Hemisphere is the earth at its farthest distance from the sun? A. autumn B. summer C. spring D. winter

15. anonymous

Hint: when sun is farthest from earth that mean it is ___

16. anonymous

summer?

17. anonymous

Farthest is the keyword.

18. anonymous

ohh winter

19. anonymous

?

20. anonymous

Yes.

21. anonymous

Closest to which date is the Southern Hemisphere tilted most directly away from the sun? A. December 21 B. March 21 C. June 21 D. September 21

22. anonymous

When northern hemisphere is winter, southern hemisphere is summer Northern hemisphere winter is in Dec 21

23. anonymous

See if you can figure it out.

24. anonymous

sepember 21?

25. anonymous

why do you think it is?

26. anonymous

wait nvm its july cause in july northerny heme is summer soltice

27. anonymous

You mean June 21?

28. anonymous

yea

29. anonymous

Correct!

30. anonymous

Upon which does the amount of gravitational pull between two bodies depend? A. only the mass of the smallest body B. the masses of both bodies C. only the mass of the largest body D. the speed by which they orbit

31. anonymous

Gravitational pull formula is $\frac{ M1M2 }{ r^2}$ multiplied by 6.686 x 10^n power. Can you figure it out now?

32. anonymous

no thisa is the 1 problem i dont know or have an idea could you plz just gimme the solution for this one

33. anonymous

M1 is mass of first object M2 is mass of second object Gravitational pull or force=$\frac{ M1M2 }{R^2 }$ multiplied by a constant.

34. anonymous

R is just distance.

35. anonymous

so?

36. anonymous

what does gravity rely on based on those formula?

37. anonymous

M1 is mass of first body. M2 is mass of second body

38. anonymous

the mass? of both bodies?

39. anonymous

You need those formula to figure out the gravitational pull.

40. anonymous

Yes that is correct!

41. anonymous

Gravitation pull happens everywhere between every bodies.

42. anonymous

What is the name for galaxies held together by gravity? A. solar system B. constellation C. binary system D. cluster

43. anonymous

Solar system:consist of planets and the sun Constellation:see attachment Binary system:a system consisting of two parts. Cluster:a group of similar things or people positioned or occurring closely together.

44. anonymous

Gravity definition- a system of millions or billions of stars, together with gas and dust, held together by gravitational attraction.


text:
# Finding a function given its partial derivatives

I need to find/define a function $G(x_1(t),x_2(t)) : \mathbb{R} \times \mathbb{R} \to \mathbb{R}$ such that the following holds: $$\frac{\partial G(x_1(t),x_2(t))}{\partial x_1(t)} =u_1(t)$$ and $$\frac{\partial G(x_1(t),x_2(t))}{\partial x_2(t)} =u_2(t)$$ where $x_1(t) = f_1(u_1(t),u_2(t))$ and $x_2(t) = f_2(u_1(t),u_2(t))$ $$f_1,f_2: \mathbb{R} \times \mathbb{R} \to \mathbb{R}$$ How can I go about doing this?

Edit: $f_1$ and $f_2$ are bounded and continuously differentiable functions.

-
You write $f_1,f_2:\mathbb R\to\mathbb R$, but in the immediately preceding equations you're using them as if they are $\mathbb R^2\to\mathbb R$. – Henning Makholm Dec 15 '12 at 13:48
@HenningMakholm sorry, you are right, they are $\mathbb{R} \times \mathbb{R} \to \mathbb{R}$ – Sunny88 Dec 15 '12 at 13:50
Also, are all of $f_1$, $f_2$, $u_1$, $u_2$ given? – Henning Makholm Dec 15 '12 at 13:50
@HenningMakholm I am not sure what does "given" mean, but you can define G in terms of them. – Sunny88 Dec 15 '12 at 13:53
I mean, do you know what they are? – Henning Makholm Dec 15 '12 at 13:53

You can't find $G$ uniquely, since your equation tells you only about its behavior near points that are hit by $(x_1,x_2)$.

What we can do is compute $\frac{d}{dt}G(x_1,x_2)$ by the chain rule:

$$\frac{d}{dt}G(x_1,x_2) = u_1(t)\frac{d}{dt}x_1(t) + u_2(t)\frac{d}{dt}x_2(t)$$ where everything on the right is known. Arbitrarily setting $G(x_1(0),x_2(0))=0$ (any constant term can be added of course) we get $$G(x_1(s),x_2(s)) = \int_0^s \left[u_1(t)\frac{d}{dt}x_1(t)+u_2(t)\frac{d}{dt}x_2(t) \right] \, dt$$

This gives you some values of $G$, and you'd better hope that if $(x_1(t),x_2(t))=(x_1(s),x_2(s))$ for any $t,s$, the computed values of $G$ match -- otherwise there's no solution. Similarly, you must have $u(t)=u(s)$, since otherwise you'll have conflicting demands on the partial derivatives of $G$ at that point.

Afterwards you need to choose neighboring values of $G$ such that the partial derivatives are right. This can be done if the curve described by $(x_1,x_2)$ is smooth enough, but not at all uniquely, of course. The simplest solution may be to use make $G(p)$ vary linearly on a short perpendicular to the main curve at $(x_1(t),x_2(t))$, with a slope chosen to make the partial derivatives come out right.

-
I didn't quite understand this part: "This gives you some values of G, and you'd better hope that if $(x_1(t),x_2(t))=(x_1(s),x_2(s))$ for any t,s, the computed values of G match -- otherwise there's no solution." So how do I know whether my $G()$ is correct or not? – Sunny88 Dec 15 '12 at 16:08
@Sunny88: The integral tells you what $G(a,b)$ must be for every $(a,b)$ that can be written as $(x_1(t),x_2(t))$. If there's an $(a,b)$ that can be written like that in two different ways, then the values prescribed by the integral had better be the same; otherwise your equation cannot be solved. – Henning Makholm Dec 15 '12 at 16:20

format: plain


text:
# Ubuntu – How to rebuild/reconfigure the HTTP Apache server after upgrading to PHP 7.0.* on 64-bit Ubuntu 14.04 LTS

Previously I was using PHP 5.5.32 on my system, everything was working fine. All the PHP programs and projects were running successfully.

Today, I upgraded to PHP 7.0.4 and the trouble starts for me. Not a single 'Hello World' program is running, forget about the entire project.

Now if I type in the URL of a program in address bar to run in a browser(say"http://localhost/hello.php") I'm getting the PHP code as it is displayed in a browser, which was not happening previously when I was using PHP 5.5.32.

If I run the program from the command line(i.e. the terminal) I get the expected output which comes after execution of PHP code. I run the following command from the terminal and got the output.

$cd /var/www$ php hello.php

After googling a bit I came to know that Apache is the only issue responsible for this and for resolving it I have to "rebuild Apache" but no where I found how?

For reference and detailed understanding of the issue I'm facing you can refer the question below link :

Why after PHP upgrade the program runs from command line but displays the PHP code as it is when run in a browser?

• The php7.0 package does not automatically install the Apache module of PHP 7, which is necessary to execute PHP scripts in Apache. It can be installed from the package libapache2-mod-php7.0.


text:
## Artigo

• nova página do texto(beta)
• Inglês (pdf)
• Artigo em XML
• Como citar este artigo
• SciELO Analytics
• Curriculum ScienTI
• Tradução automática

## versão impressa ISSN 0103-8478versão On-line ISSN 1678-4596

### Cienc. Rural vol.50 no.3 Santa Maria  2020  Epub 13-Mar-2020

#### http://dx.doi.org/10.1590/0103-8478cr20190443

ANIMAL PRODUCTION

Economic analysis of the risk of replacing corn grains (Zea mays) with pearl millet grains (Pennisetum glaucum) in the diet of feedlot cattle

Análise econômica do risco da substituição de grãos de milho (Zea mays) por grãos de milheto (Pennisetum glaucum) na dieta de bovinos confinados

1Universidade Estadual de Goiás (UEG), Campus São Luís de Montes Belos, Anápolis, GO, Brasil.

2Universidade Federal de Goiás (UFG), Anápolis, GO, Brasil.

3Programa de Pós-graduação em Zootecnia, Universidade Federal de Santa Maria (UFSM), 97105-030, Santa Maria, RS, Brasil..

4Curso em Zootecnia, Universidade Federal de Santa Maria (UFSM), Santa Maria, RS, Brasil.

5Cooperativa Agroindustrial de Produtores Rurais do Sudoeste de Goiás, Rio Verde, GO, Brasil.

6 Departamento de Educação Agrícola e Extensão Rural, Universidade Federal de Santa Maria (UFSM), Santa Maria, RS, Brasil.

ABSTRACT:

The goal of the present study was to assess the economic viability relating to the risk of replacing corn with pearl millet in diets with 80% concentration for feedlot cattle confined for 89 days. Replacement levels were: 0, 33, 66, and 100%. The risk was estimated using Monte Carlo simulation, Spearman’s rank correlation test between input variables, stochastic dominance, and analysis of sensitivity. The expected average values ± standard deviation for net present value (R$/animal) were ± 71.74 ± 283.32, 91.23 ± 285.18, 196.05 ± 273.79, and 223.80 ± 267.96 for diets containing 0, 33, 66, and 100% of pearl millet, respectively. The probability of ≥0 net present value was 63.4, 66.1, 78.4, and 82.4%, respectively. The net present values were statistically different (P<0.05), and the higher levels dominated the lower values. The items that most influenced the net present values were, in descending order, prices of unfinished and finished cattle, initial and final weights, prices of concentrate and forage, concentrate and forage consumption. Based on the results of the simulation, diet of 100% pearl millet exhibited the best economic viability. Key words: investment analysis; probabilistic analysis; stochastic method; correlation of classification RESUMO: O objetivo do estudo foi avaliar a viabilidade econômica relacionada ao risco da substituição de milho por milheto em dietas com 80% de concentrado no confinamento de bovinos por 89 dias. Os níveis de substituição foram: 0, 33, 66 e 100%. O risco foi estimado usando simulação de Monte Carlo, correlação de Spearman entre as variáveis de entrada, dominância estocástica e análise de sensibilidade. Os valores médios esperados ± desvio padrão para o valor presente líquido (R$/animal) foram de ± 71,74 ± 283,32, 91,23 ± 285,18, 196,05 ± 273,79 e 223,80 ± 267,96 para dietas contendo 0, 33, 66 e 100% de milheto, respectivamente. A probabilidade de valor presente líquido ≥0 foi de 63,4, 66,1, 78,4 e 82,4%, respectivamente. Os valores presentes líquidos foram estatisticamente diferentes (p<0,05), e os níveis mais elevados dominaram os valores mais baixos. Os itens que mais influenciaram os valores presentes líquidos foram, em ordem decrescente, os preços de bovinos não terminados e acabados, pesos inicial e final, preços de concentrado e forragem, consumo de concentrado e forragem. Com base nos resultados da simulação, a dieta de 100% de milheto mostrou a melhor viabilidade econômica.

Palavras-chave: análise de investimento; análise probabilística; método estocástico; correlação de classificação.

INTRODUCTION:

Alternative ingredients to corn (Zea mays) and sorghum are commonly used in cattle feedlots as concentrate components for diets. The use of pearl millet (Pennisetum glaucum) is an interesting alternative, considering its low cost in comparison with corn.

Among the crops used in succession to annual crops, pearl millet is one of the most important in the central-west and north regions of Brazil. It is usually seeded after the soybean cultivation and can be used for grazing and production of haystack, to produce grains for replacing corn crops (with higher risk during the interim-harvest), and/or for producing silage (BERGAMASCHINE et al., 2011).

Studies have demonstrated that animal performance was similar in cattle fed pearl millet (HILL et al., 1996; GONÇALVES et al., 2010; SILVA et al., 2014), even without compromising the characteristics of carcasses and meat (SILVA et al., 2015), when compared with diets containing corn.

However, SILVA et al. (2014) affirmed that pearl millet, despite its great potential for feeding ruminants, has been relatively little studied as a diet for beef cattle and, in addition, it has been used for diets with low concentrate contents.

Taking into consideration that the economic aspects involving the use of pearl millet in the diet of cattle have been less explored by the scientific community, the present study proposed the use of the Monte Carlo simulation technique (economic risk analysis) to assess whether replacing corn grains with pearl millet grains interfered with the economic viability of feedlot cattle.

MATERIALS AND METHODS:

The confinement was carried out in the Livestock Sector of the Technological Department of the Agroindustrial Cooperative for Rural Producers of Southwest Goiás (COMIGO), Rio Verde, State of Goiás, Brazil (17°46’22” S - 51°02’86” W), located at 815 meters above sea level. According to Köppen classification (ALVAREZ et al., 2014), the region has tropical savanna-type climate (Aw’), with rainfall concentrated in summer (October to April) and a dry season in winter (May to September). Data analysis and stochastic simulations were carried out at the Federal University of Santa Maria, State of Rio Grande do Sul, Brazil.

Economic viability was assessed using the probabilistic method via Monte Carlo simulation, replacing grinded corn grains with grinded pearl millet grains for the diet of feedlot calves with four content levels: 0, 33, 66, and 100%.

Details of the experimental procedure during the feeding phase to obtain zootechnical performance data have been previously described in the study conducted by SILVA et al. (2014). We used 89 non-castrated calves (European/zebu crossbreed cattle), of which 45 had predominance of European-zebu genotypes and 44 had predominance of zebu genotypes. The average initial weights were 318 and 321 kg, respectively. The average initial age was 21 months for both genotypes. The experimental design used was completely randomized with four replications.

At the beginning of the feeding period, the animals were identified, vaccinated, treated against endo-and ectoparasites, and allocated in 16 collective pens (10 x 7.70 m). The drinkers were equipped with float ball valves, concrete feeders, and gravel floor with a 5% slope. Four pens were used for each treatment. The animals were weighted individually after fasting for solids from 14 to 16 hours. The adaptation period was of seven days, and the feeding period lasted 89 days, totaling 96-day confinement. The proportion of ingredients in the diet and the performance characteristics of the animals are shown in table 1.

Table 1 Composition of diets expressed in dry matter and performance indicators according to the content of pearl millet.

 Pearl millet content (% dry matter) 0 33 66 100 ----------------------------------------------------------------Composition of the diet------------------------------------------------------------------------- Corn silage (kg) 20.00 20.02 20.00 20.02 Grinded corn grains (kg) 70.50 48.96 25.06 0.00 Grinded pearl millet grains (kg) 0.00 24.05 49.88 77.47 Soybean bran (kg) 8.02 5.49 3.61 1.19 Urea (kg) 0.62 0.63 0.60 0.49 Minerals (kg) * 0.86 0.85 0.85 0.83 -----------------------------------------------------------------Performance indicators **---------------------------------------------------------------------- Feeding time (days) 89 89 89 89 Initial weight (kg) 317 324 324 324 Final weight (kg) 473 465 480 463 Total weight gain (kg) 156 141 156 139 Daily dry matter consumption (kg) 8.9 8.5 9.3 8.7 Hot carcass weight (kg) 263 256 255 264 Subcutaneous fat depth (mm) 4.0 4.1 4.1 3.7

*Minimum contents (g/kg): Ca: 116; P: 61; S: 9; Na: 150; Mg: 0.69; Zn: 57.8 mg; Mn: 1; Cu: 1.88; Co: 0.16; I: 0.16; Se: 0.02; sodium monesin: 2.4.

**P>0.05.

Source: Adapted from Silva et al. (2014, 2015).

The methodologies of MATSUNAGA et al., (1976), RESENDE FILHO et al., (2001) and PACHECO et al., (2014b) were used to estimate costs and revenues for each animal, where: Total Cost represented the sum of depreciations (facilities, machinery, implements and equipment), purchase of the ‘thin’ animal, sanitary control, feeding (roughage and concentrate), labor and other operational expenses. Gross revenue consisted in the sale of the fat animal. Facilities (estimated for fixed capacity of 1,000 animals), machinery, implements and equipments depreciation were calculated for a planning horizon of one year. To calculate the production costs of corn silage, the yield of 45 tons of green matter/ha and DM content of 33% was considered. Details on the items that comprise the costs of silage making are included in PACHECO et al. (2006). For cost estimates of labor, was considered 1 man hired/300 feedlot cattle and three minimum wages/month/1,000 animals for technical assistance. Other operational expenses such as maintenance of facilities, machinery, implements and equipment, fuel, electricity, freight, taxes and meals for workers/human resources were estimated for the equivalent of 2.5% of operating costs. The risk assessment considered the methods of stochastic simulation, stochastic dominance and sensitivity, with the aid of Microsoft Excel®, @Risk® and SAS System® softwares. Initially the cost items of each year were deflated by the IGP-FGV (General Price Index Fundação Getulio Vargas - Anualpec 2016) for the year of 2015. Afterwards the type of probability distribution (Anderson-Darling statistic) of the following cost items, revenue and performance variables of the animals were determined: thin and fat cattle (R$/kg), minimum wage (R$/month), roughage (R$/kg DM), concentrate (R$/kg DM), facilities/equipment (R$/animal/day), machinery/ implements (R$/animal/day), health/vaccine (R$/ dose), health/deworming (R$/mL), initial and final weights (kg), average daily weight gain (kg), total weight gain (kg), roughage and concentrate intake (kg DM/day) and minimum rate of attractiveness (% per month).

Items used to estimate costs and revenues were obtained from 11 consecutive years of quotes (between 2005 and 2015). Costs of the facilities were estimated for a static capacity of 1,000 animals, with useful life of 10 years. Details of the estimation of depreciation, sanitary control, feeding cost, labor cost, and other operating expenses were previously described by PACHECO et al., (2014b).

The net present value (NPV, R$/animal) was used as a financial indicator. The NPV is one of the most commonly used indicators to evaluate capital investment proposals, according to the definition by SOUZA & CLEMENTE (2009). Its estimation method is considered the most well-known and widely used robust investment analysis technique and, as its name implies, is the concentration of all expected values of a cash flow on date zero using the TMA. This indicator reflects the return on monetary values of the investment measured by the difference between the present value of cash inflows and the present value of cash outflows, subject to a certain discount rate (KASSAI et al., 2007). According to SOUZA & CLEMENTE (2009), NPV can provide basically three answers to the investor: being less than zero indicates that the investment is not viable; being zero indicates that the initial investment was recovered and the remuneration was equal to the application in TMA; and if the indicator is positive, it shows the surplus obtained by the return on investment, in addition to the initial cost and TMA. The NPV was calculated by the equation =i=1nFCi(1+TMA)i , where n is the number of months, i is the n-th time period in which the money is invested in the project, TMA is the minimum acceptable rate of return, and FC represents the net revenue of each i-th period. Independent investment projects with one-year planning were considered fort the cash flow (prepared with a planning horizon of one year (RESENDE FILHO et al., 2001)) of each concentrate level. TMA was incorporated in the estimate of the NPV considering a triangular distribution with a minimum value of 5%, most likely 9% and 14% maximum value. In the simulation of the NPV, Latin Hypercube sampling was used, random generator number Mersenne Twister, with 2000 interactions, according ALBRIGHT et al., (2010), PALISADE 2010. For each content of pearl millet, this analysis was performed either with the Spearman correlation between the cost items that had their probability distribution determined (input variables) (Tables 3 and 4). The NPV simulations included probability distributions for all cost and revenue items, as well as for animal performance indicators. We used the simulation method with Latin hypercube sampling (MCKAY et al., 1979; IMAN et al., 1981) and Mersenne twister random number generator (MATSUMOTO & NISHIMURA, 1998) with 2,000 interactions. Spearman’s rank correlation coefficient was used to determine the associations between the input variables. All estimates were calculated per animal/year, monetarily corrected for 2015 by the general price index (internal availability calculated by Getúlio Vargas Foundation). Microsoft® Excel (Redmond, WA, USA), @ Risk® (Ithaca, NY, USA), and SAS® Studio (Cary, NC, USA) software programs were used to carry out risk assessments, following the methods described by Albright et al. (2010) and Pacheco et al. (2014b). The definitions of probability distribution (considering Anderson-Darling test) for the items of cost, revenue, and animal performance, and Spearman’s correlations between the input variables and statistics of variability are presented in tables 2, 3, 4, and 5. Table 2 Probability distributions for performance, costs, and revenues.  Item1 Pearl millet level Distributions (parameters)2 Item Pearl millet level Distributions (parameters) 1 All Logistics (0.68043; 3.3486; 6.5713) 8 0 Triangular (285.21; 316.90; 348.59) 2 All Laplace (4.0996; 0.59481) 33 Triangular (291.96; 324.40; 356.84) 3 All Exponential (0.058488; 0.269602) 66 Triangular (287.05; 318.95; 350.84) 4 0 Logistics (0.638602; 0.05152) 100 Triangular (287.55; 319.50; 351.45) 33 Pearson (15.512; 4.3005; 0.23748) 9 0 Triangular (425.43; 472.70; 519.97) 66 Gamma (4.8701; 0.03095; 0.271002) 33 Triangular (418.50; 465.00; 511.50) 100 Uniform (0.18508; 0.41087) 66 Triangular (423.54; 470.60; 517.66) 5 0 Triangular (1.61; 1.79; 1.97) 100 Triangular (423.02; 470.03; 517.03) 33 Triangular (1.53; 1.70; 1.87) 10 All Normal (747.59; 115.39) 66 Triangular (1.59; 1.76; 1.94) 11 All Extreme value (15468.4; 4033.1) 100 Triangular (1.58; 1.76; 1.93) 12 All Minimum extreme value (0.053934; 0.0056951) 6 0 Triangular (6.44; 7.15; 7.87) 13 All Exponential (0.016077; 0.03595) 33 Triangular (6.11; 6.79; 7.47) 14 All Extreme value (3.22429; 0.61856) 66 Triangular (6.35; 7.05; 7.76) 15 All Triangular (0.05; 0.095; 0.14) 100 Triangular (6.32; 7.03; 7.73) 7 0 Triangular (1.58; 1.75; 1.93) 33 Triangular (1.42; 1.58; 1.74) 66 Triangular (1.53; 1.70; 1.87) 100 Triangular (1.52; 1.69; 1.86) 11 = Unfinished cattle (R$/kg); 2 = Finished cattle (R$/kg); 3 = Forage (R$/kg dry matter); 4 = Concentrate (R$/kg dry matter); 5 = Forage consumption (kg dry matter/animal/day); 6 = Concentrate consumption (kg dry matter/animal/day); 7 = Weight gain (kg/animal/day); 8 = Initial weight (kg); 9 = Final weight (kg); 10 = Minimum wage (R$/month); 11 = Land (R$/ha); 12 = Facilities and equipment (R$/animal/day); 13 = Machines and supplies (R$/animal/day); 14 = Health (R$/animal); 15 = Minimum acceptable rate of return (%).

2Uniform (minimum; maximum); Exponential (beta); Extreme value (alpha; beta); Minimum extreme value (alpha; beta); Gamma (alpha, beta); Laplace (average; standard deviation); Logistics (alpha; beta); Normal (average; standard deviation); Pearson (alpha, beta); Triangular (minimum; most likely; maximum).

Table 3 Spearman’s rank correlation coefficients of costs, revenue, and zootechnical performance for 0% (below the diagonal) and 33% (above the diagonal) of pearl millet.

 Items 1 2 3 4 5 6 7 8 9 10 1 Unfinished cattle (R$/kg) 0.76 0.71 0.77 -0.78 0.21 -0.67 0.78 -0.75 -0.76 2 Finished cattle (R$/kg) 0.74 0.76 0.78 -0.79 -0.23 -0.71 0.50 -0.75 -0.79 3 Wage (R$/month) 0.70 0.73 0.97 -0.98 -0.29 -0.95 0.75 -0.97 -0.96 4 Land (R$/ha) 0.78 0.73 0.97 -0.99 -0.12 -0.92 0.81 -0.98 -0.99 5 Forage (R$/kg MS) -0.77 -0.76 -0.99 -0.99 0.17 0.94 -0.80 0.99 0.98 6 Concentrate (R$/kg MS) 0.20 -0.22 -0.24 -0.04 0.14 0.33 0.30 0.15 0.13 7 Health (R$/animal) -0.67 -0.69 -0.96 -0.93 0.95 0.27 -0.64 0.92 0.93 8 Land opportunity (R$/animal) 0.80 0.45 0.73 0.80 -0.77 0.34 -0.62 -0.82 -0.80 9 Facilities/equipment (R$/animal/day) -0.76 -0.69 -0.97 -0.99 0.99 0.07 0.93 -0.80 0.96 10 Machines/supplies (R$/animal/day) -0.74 -0.73 -0.97 -0.97 0.98 0.08 0.93 -0.78 0.95

Table 4 Spearman’s rank correlation coefficients of cost, revenue, and zootechnical performance for 66% (below the diagonal) and 100% (above the diagonal) of pearl millet.

 Items 1 2 3 4 5 6 7 8 9 10 1 Unfinished cattle (R$/kg) 0.76 0.71 0.77 -0.78 0.05 -0.67 0.78 -0.75 -0.76 2 Finished cattle (R$/kg) 0.76 0.76 0.78 -0.79 -0.44 -0.71 0.50 -0.75 -0.79 3 Wage (R$/month) 0.71 0.76 0.97 -0.98 -0.48 -0.95 0.75 -0.97 -0.96 4 Land (R$/ha) 0.77 0.78 0.97 -0.99 -0.36 -0.92 0.81 -0.98 -0.99 5 Forage (R$/kg MS) -0.78 -0.79 -0.98 -0.99 0.38 0.94 -0.80 0.99 0.98 6 Concentrate (R$/kg MS) 0.15 -0.32 -0.37 -0.22 0.26 0.46 0.05 0.37 0.38 7 Health (R$/animal) -0.67 -0.71 -0.95 -0.92 0.94 0.39 -0.64 0.92 0.93 8 Land opportunity (R$/animal) 0.78 0.50 0.75 0.81 -0.80 0.22 -0.64 -0.82 -0.80 9 Facilities/equipment (R$/animal/day) -0.75 -0.75 -0.97 -0.98 0.99 0.24 0.92 -0.82 0.96 10 Machines/supplies (R$/animal/day) -0.76 -0.79 -0.96 -0.99 0.98 0.24 0.93 -0.80 0.96

Table 5 Variability statistics of input variables and descriptive statistics for simulated net present value (R$/animal), for all levels of pearl millet.  Input variables Standard deviation Coefficient of variation (%) Concentrate consumption, kg dry matter/day 0.288 4.0 Concentrate, R$/kg dry matter 0.078 17.2 Unfinished cattle, R$/kg 0.98 422.0 Initial weight, kg 13.092 4.0 Finished cattle, R$/kg 0.60 686.9 Final weight, kg 19.222 4.0 Daily average gain, kg 0.067 4.0 Minimum acceptable rate of return (%) 0.018 19.2 Forage consumption, kg dry matter/day 0.072 4.0 Forage, R$/kg dry matter 0.058 17.9 We used the stochastic dominance analysis to compare the pairs of cumulative probability distribution of NPV simulated for different levels of concentrate according to the first-and second-order criteria (HADAR & RUSSELL, 1969; HANOCH & LEVY, 1969). In the criterion of stochastic dominance of first order, there are selected investments for investors who prefer a higher return investment, and the stochastic dominance of second-order, are selected investments for investors who prefer a higher return and either are averse to the risk. Significant differences were found using Kolmogorov-Smirnov test (CONOVER, 1999), using software SAS® University Edition. For the analysis of sensitivity, we used stepwise multivariate multiple regression with standardized regression coefficients (ALBRIGHT et al., 2010; PALISADE, 2010). Standardized multivariate regression coefficients indicate the number of NPV standard deviations that will change with each change of one standard deviation in the input variables, considering that the other input variables remain constant (ALBRIGHT et al., 2010). In figure 1, the flowchart illustrates the steps taken during the deterministic and probabilistic phases of the adopted methodology. RESULTS AND DISCUSSION: Monte Carlo simulation technique is considered of great value in decision making, mostly used in administration, management, and economics (ALBRIGHT et al., 2010). However, studies using this method have been recently oriented to the field of agribusiness (PACHECO et al., 2014a, 2014b, 2017). Specifically, about feedlot beef cattle, ROSA et al., (2017) and SILVA et al., (2017) have used Monte Carlo simulation to assess the economic viability of using different concentrate levels in the diets. Conversely, PACHECO et al., (2014a, 2017) and FABRICIO et al., (2017) have used this technique to assess different slaughter weights, and Pacheco et al. (2014b) to assess different categories of calves. SILVA et al., (2017) stated that, from an economic point of view, studies involving stochastic simulation in livestock production systems are limited, specially with respect to the refinement of methods aimed to improve the quality of simulations results. ROSA et al., (2017) draw attention to the fact that feedlot beef cattle require high volume of financial resources at the beginning of the investment project implementation, which justifies the use of simulation techniques to help in decision making on the part of investors. An important aspect of the present study is the fact of using high level of concentrate in the diets, representing the current reality of feedlots in Brazil, which has been demonstrated in studies conducted by MILLEN et al., (2009) and COSTA JUNIOR et al., (2013), who applied questionnaires to nutritionists responsible for the development of diets for feedlot cattle in several Brazilian states. Table 6 shows the positive expected values for NPV at all levels of replacement of corn with pearl millet (0 to 100%), increasing linearly from R$ 71.74 to R$223.80/animal, respectively. Table 6 Descriptive statistics for simulated net present value (R$/animal), according to the level of pearl millet.

 Pearl millet level (%) 0 33 66 100 Minimum -1,330.21 -2,214.07 -2,159.66 -1,389.29 Maximum 1,250.65 1,086.53 1,508.27 1,170.67 Average 71.74 91.23 196.05 223.80 Standard deviation 283.32 285.18 273.79 267.96 Coefficient of variation (%) 394.9 312.6 139.7 119.7 NPV ≥0 63.4% 66.1% 78.4% 82.4%

The statistics of minimum and maximum values, standard deviation, and coefficients of variation allowed the quantification of the variability simulated for several scenarios, considering indicators of zootechnical performance, costs, and revenues at the same time. Although, the standard deviation was slightly reduced with increasing replacement level, it was observed that when expressed as a percentage of the average (coefficient of variation), there was linear increase from 25.3 to 83.5% and 0 to 100% of replacement, respectively.

With respect to the likelihood of NPV ≥0, representing the percentage of viability of an investment project, there was linear increment with increased percentage of replacement of corn with pearl millet in the diet, i.e., from 63.4% at 0% level to 82.4% at 100% level.

The graphical representation of the cumulative probability distribution of 2,000 simulated values of NPV for each replacement level is shown in figure 2. This plot showed the NPV (x-axis) in terms of cumulative probability (y-axis), enabling the visualization of simulated cumulative values above and below zero, i.e., probability of viability and loss, respectively. It can be observed that the curve to the right moved to 100% of pearl millet, thus representing greater occurrence of simulated values for NPV above zero.

In addition, the probability distributions of the simulated NPV for different levels of replacement of corn with pearl millet could be statistically compared in the present study using the Kolmogorov-Smirnov test, as shown in table 7.

Table 7 Stochastic dominance and domain type, according to the Kolmogorov-Smirnov test (KS) and comparing pairs of probability distributions of pearl millet levels for the simulated net present value.

 Pairs of pearl millet levels Statistics KS Pr > KS Dominance1 Domain type2 0 vs. 33 1.37 0.0456 F < 0 vs. 66 6.01 0.0001 F < 0 vs. 100 7.08 0.0001 F < 33 vs. 66 5.09 0.0001 F < 33 vs. 100 6.07 0.0001 F < 66 vs. 100 1.37 0.0456 F <

1F = first-order stochastic dominance.

2< = higher levels of pearl millet dominated lower levels of pearl millet.

As shown in table 6, the expected average NPV values showed optimistic results for the viability of feedlot technology, considering the high probability of losses reported in several studies cited by Pacheco et al. (2014a, 2014b, 2014c, 2017). It is worth mentioning the flexibility of the Monte Carlo simulation technique, which can estimate several alternatives applied in feedlots, as is the case of the present study replacing an energetic ingredient with other for the diets.

We did not find studies in the literature assessing the probability of economic viability in feedlot cattle fed pearl millet. However, there are reports with values for NPV ≥0 oscillating from 18.7% (PACHECO et al., 2017) to 80.4% (PACHECO et al., 2014b), which demonstrates the possible extent according to the technology used, time of year for marketing, race, age, sex, initial weight, slaughter weight, concentrate level, Brazilian states, etc.

The present study demonstrated the great alternative that pearl millet represents in place of corn relating to zootechnical performance (Table 1) and, especially, economic viability (Table 6).

According to Kolmogorov-Smirnov test, it was observed that the differences in simulated NPVs were significant (P<0.05) in all pairs of pearl millet levels. In this way, as the level of replacement increased, there was a correspondingly significant higher NPV.

All the probability distribution curves were classified as first-order stochastic dominance, i.e., characterizing investors who preferred investment projects with higher returns. In addition, higher levels of replacement dominated lower levels in all comparisons of distribution pairs. In this way, it was possible to observe that 100% replacement of corn with pearl millet was the best investment project, because, statistically, it promoted the highest return in comparison to other replacement levels.

The last method of quantification of the risk involved in the economic viability presented in the present study was the probabilistic sensitivity analysis using standardized regression coefficients (Figure 3). This method allowed the comparison of inputs with different units of measurement.

The most important items that influenced the financial indicator (NPV) were, in descending order, the prices of unfinished and finished cattle, final weight, initial weight, price of concentrate, price of forage, concentrate consumption, and forage consumption.

With respect to the prices of unfinished and finished cattle, it was observed that the higher the level of replacement, the higher the relevance of these two inputs to influence NPV. The opposite occurred with concentrate and forage consumption, i.e., the higher the level of replacement, the lower the standardized regression coefficients.

Considering the risk indicated by the analysis of sensitivity (Figure 3), it was observed that among the items of the experimental diet components, only the price of concentrate exhibited higher relevance influencing NPV, which was equivalent to initial weight.

Prices of unfinished and finished cattle and final weight were the most important items. This finding was in line with other probabilistic sensitivity analyses of feedlot cattle (PACHECO et al., 2014a, 2014b, 2014c, 2017; ROSA et al., 2017; SILVA et al., 2017).

In the present study, prices of unfinished and finished cattle were up to six times more relevant to influence NPV than the price of concentrate. For example, every increase of R$0.01 in the price of unfinished cattle caused a reduction of R$ -3.33 in NPV for 100% replacement level. This result was obtained using the information of standard deviation of the inputs in table 5, associated with the data of standard deviation of NPV in table 6, and regression coefficients in figure 3, as follows according to Pacheco et al. (2014c): each unit of standard deviation in the price of unfinished cattle (R$0.98/kg live weight) resulted in -1.22 standard deviation units in NPV output (1 standard deviation of NPV for 100% = R$ 267.96/confined animal), and the other input items remained constant. Therefore, R$0.98 of change in price of unfinished cattle = R$ -326.91 of change in NPV (= -1.22*267.96), and R$0.01 of change in price of unfinished cattle = R$ -3.33 of change in NPV (= -326.91*0.01/0.98).

These calculations can facilitate the decision-making process on the part of the investors/managers. LOPES et al., (2011) reported the influence established by the best strategies for purchasing grains and dietary ingredients, unfinished cattle, finished cattle, and monitoring of price volatility of grains and cattle to obtain the best results of economic viability.

CONCLUSION:

Based on the simulated results for the financial indicator NPV, the diet with 100% of pearl millet exhibited the best economic viability. The items that most influenced the financial indicator were, in descending order, prices of unfinished and finished cattle, initial and final weights, prices of concentrate and forage, and concentrate and forage consumption.

ACKNOWLEDGEMENTS

The authors are thankful to Coordenação de Aperfeiçoamento de Pessoal de Nível Superior (CAPES) and Conselho Nacional de Desenvolvimento Científico e Tecnológico (CNPq). This study was financed in part by the Coordenação de Aperfeiçoamento de Pessoal de Nível Superior (CAPES), Brasil - Finance code 001.

REFERENCES

ALBRIGHT, S. C. et al. Data analysis and decision making. 4.ed. Mason: South-Western Cengage Learning, 2010. 1080p. [ Links ]

ANUALPEC 2016. Anuário da pecuária brasileira, Informa Economics FNP, São Paulo, SP, Brasil, 272p. [ Links ]

CONOVER, W. J. Practical nonparametric statistics. 3.ed. New York: John Wiley and Sons, 1999. 592p. [ Links ]

COSTA JUNIOR, C. et al. Brazilian beef cattle feedlot manure management: a country survey. Journal Animal Science, v.91, n.4, p.1811-1818, 2013. Available from: <Available from: http://bit.ly/2MGoXja >. Accessed: Dec. 05, 2019. doi: 10.2527/jas2012-5603. [ Links ]

FABRICIO, E. A. et al. Financial indicators to evaluate the economic performance of feedlot steers with different slaughter weights. Ciência Rural, v.47: 03, e20160516, 2017. Available from: <Available from: http://bit.ly/2MJyK7Y >. Accessed: Dec. 05, 2019. doi: 10.1590/0103-8478cr20160516. [ Links ]

GONÇALVES, J. R. S. et al. Replacement of corn grain by pearl millet grain in diets containing corn or elephant grass silage fed beef cattle. Revista Brasileira Zootecnia, v.39, n.9, p.2032-2039, 2010. Available from: <Available from: http://bit.ly/36fmjbN >. Accessed: Dec. 05, 2019. doi: 10.1590/S1516-35982010000900023. [ Links ]

HADAR, J.; RUSSELL, W. R. Rules for ordering uncertain prospects. The American Economic Review, v.59, n.1, p.25-34, 1969. Available from: <Available from: https://www.jstor.org/stable/1811090 >. Accessed: Dec. 09, 2019. [ Links ]

HANOCH, J.; LEVY, H. The efficiency analysis of choices involving risk. The American Economic Review, v.74, p.335-346, 1969. Available from: <Available from: http://bit.ly/2MEGPen >. Accessed: Dec. 09, 2019. doi: 10.1016/B978-0-12-780850-5.50015-0. [ Links ]

HILL, G. M. et al. Digestibility and utilization of pearl pearl millet diets fed to finishing beef cattle. Journal Animal Science, v.74, n.7, p.1728-1735, 1996. Available from: <Available from: http://bit.ly/369DsDQ >. Accessed: Dec. 09, 2019. doi: 10.2527/1996.7471728x. [ Links ]

IMAN, R. L. et al. An approach to sensitivity analysis of computer models, Part 1. Introduction, input variable selection and preliminary variable assessment. Journal of quality technology, v.13, n.3, p.174-183, 1981. Available from: <Available from: http://bit.ly/2ZEFFEQ >. Accessed: Dec. 09, 2019. doi: 10.1080/00224065.1981.11978748. [ Links ]

KASSAI, J. R. et al. Retorno de investimento: Abordagens matemática e contábil do lucro empresarial. 3. ed. São Paulo: Editora Atlas S.A., 2007. [ Links ]

LOPES, L. S. et al. Viabilidade econômica da terminação de novilhos nelore e red norte em confinamento na região de Lavras-MG. Ciência e Agrotecnologia, v.35, n.4, p.774-780, 2011. Available from: <Available from: http://bit.ly/35ieGQV >. Accessed: Dec. 14, 2019. doi: 10.1590/S1413-70542011000400017. [ Links ]

MATSUMOTO, M.; NISHIMURA, T. Mersenne twister: a 623-dimensionally equidistributed uniform pseudo-random number generator. ACM Transactions on Modeling and Computer Simulation, v.8, n.1, p.3-30, 1998. Available from: <Available from: http://bit.ly/2QBdgLH >. Accessed: Dec. 14, 2019. doi: 10.1145/272991.272995. [ Links ]

MCKAY, M. D. et al. A Comparison of three methods for selecting values of input variables in the analysis of output from a computer code. Technometrics, v.21, n.2, p.239-245, 1979. Available from: <Available from: http://bit.ly/357PJY8 >. Accessed: Dec. 14, 2019. doi: 10.1080/00401706.1979.10489755. [ Links ]

MILLEN, D. D. et al. A snapshot of management practices and nutritional recommendations used by feedlot nutritionists in Brazil. Journal Animal Science, v.87, p.3427-3439, 2009. Available from: <Available from: http://bit.ly/2Qzg9Nl >. Accessed: Dec. 14, 2019. doi: 10.2527/jas.2009-1880. [ Links ]

PACHECO, P. S. et al. Risk assessment of finishing beef cattle in feedlot: slaughter weights and correlation amongst input variables. Revista Brasileira de Zootecnia, v.43, p.92-99, 2014a. Available from: <Available from: http://bit.ly/2u9uEjl >. Accessed: Dec. 14, 2019. doi: 10.1590/S1516-35982014000200007. [ Links ]

PACHECO, P. S. et al. Use of the correlation between input variables in estimating the risk of feedlot finishing of steers and young steers. Anais da Academia Brasileira de Ciências, v.86, p.945-954, 2014b. Available from: <Available from: http://bit.ly/37jIa1Y >. Accessed: Dec. 14, 2019. doi: 10.1590/0001-37652014110012. [ Links ]

PACHECO, P. S. et al. Correlation and slaughter weight on sensitivity analysis of charolais steers feedlot finished. American International Journal Contemporary Research, v.4, p.28-34, 2014c. Available from: <Available from: http://bit.ly/2ZGIDIQ >. Accessed: Dec. 14, 2019. [ Links ]

PACHECO, P. S. et al. Stochastic simulation of the economic viability of feedlot finishing steers slaughtered at different weights in southern Brazil. Bioscience Journal, v.33, n.3, 2017. Available from: <Available from: http://bit.ly/35iBaBi >. Accessed: Dec. 14, 2019. doi: 10.14393/BJ-v33n3-34110. [ Links ]

PALISADE RISK SOFTWARE - @RISK. Risk analysis and simulation add-in for Microsoft® Excel. Ithaca: Palisade, 2010. 739p. [ Links ]

ROSA, J. R. P. et al. Risk analysis of the economic viability of feedlot aberdeen angus steers fed with different proportions of concentrate. Bioscience Journal, v.33, n.3, p.660-669, 2017. Available from: <Available from: http://bit.ly/39pbmXr >. Accessed: Dec. 30, 2019. doi: 10.14393/BJ-v33n3-34547. [ Links ]

SOUZA, A.; CLEMENTE, A. Decisões financeiras e análise de investimentos: fundamentos, técnicas e aplicações. 6. ed. São Paulo: Atlas, 2009. [ Links ]

SILVA, R. M. et al. Características físico-químicas da carne de tourinhos zebuínos e europeus alimentados com níveis de grão de milheto na dieta. Ciência Animal Brasileira, v.15, p.20-31, 2014. Available from: <Available from: http://bit.ly/36dlErj >. Accessed: Dec. 30, 2019. doi: 10.5216/cab.v15i1.25777. [ Links ]

SILVA, R. M. et al. Características de carcaça e carne de novilhos de diferentes predominâncias genéticas alimentados com dietas contendo níveis de substituição do grão de milho pelo grão de milheto. Semina: Ciências Agrárias, v.36, p.943-959, 2015. Available from: <Available from: http://bit.ly/2ZHjRZ7 >. Accessed: Dec. 30, 2019. doi: 10.5433/1679-0359.2015v36n2p943. [ Links ]

SILVA, R. M. et al. Stochastic simulation of the economic viability of feedlot steers fed with different proportions of concentrate. Bioscience Journal, v.33, n.1, 2017. Available from: <Available from: http://bit.ly/2u0AX8C >. Accessed: Dec. 30, 2019. doi: 10.14393/BJ-v33n1a2017-33608. [ Links ]

0CR-2019-0443.R1

BIOETHICS AND BIOSSECURITY COMMITTEE APPROVAL

The present study was approved by the Research Ethics Committee and Animal Experimentation Ethics Committee of the Federal University of Goiás (CEEA/COEP/UFG), Protocol No. 101/2011.

Received: June 12, 2019; Accepted: December 04, 2019; Revised: February 05, 2020

E-mail: edomfabricio@gmail.com. *Corresponding author

DECLARATION OF CONFLICT OF INTERESTS

The authors declare no conflict of interest. The founding sponsors had no role in the design of the study; in the collection, analyses, or interpretation of data; in the writing of the manuscript, and in the decision to publish the results.

CONTRIBUITION OF AUTHORS

The authors contributed equally to the manuscript.

This is an open-access article distributed under the terms of the Creative Commons Attribution License


text:
# Solve for: 48/64=x/124

## Expression: $48\div64=x\div124$

Divide the numbers

$0.75=x\div124$

Write the division as a fraction

$0.75=\frac{ 1 }{ 124 }x$

Swap the sides of the equation

$\frac{ 1 }{ 124 }x=0.75$

Multiply both sides of the equation by $124$

$x=93$

Random Posts
Random Articles


text:
### Graphical proof that the sum of angles in a triangle is 180deg.

 Consider the following diagram: 1.  Start with the vertical vector along the line that connects angles a and c.  Rotate counter-clockwise* until the vector is parallel with the side connecting angles b and a.  The vector has now been rotated through an angle equal to a. 2. Now rotate the vector through an angle equal to b, making it parallel to the side connecting angles b and c. 3.  Finally, rotate the vector through an angle equal to c, so that it will be pointing in exactly the opposite direction from its original position. $\therefore a+b+c=180^{o}=\pi radians$ *  "counter-clockwise": An ancient term which dates back to a time when clocks had rotating pointers called "hands".  There were two hands, one long and one short.  The short hand had the longest period, (12 hours); The long hand had the shorter period, (1 hour).  (Some clocks had a third hand called a "second" hand which had a period of one minute.)  By convention, the tips of the hands would be moving to the right when the hands were pointing straight up - this defined clockwise rotation.  Counter-clockwise is rotation in the opposite direction. **  The hands of the clock, by the way, rotated in front of a circular scale on a fixed plane surface called the "face".  The circular scale was divided into twelve major divisions, and each major division was divided into five minor divisions.  Be thankful that you live in the digital age.


text:
# Getting Started With End-to-End Testing in Angular Using Protractor

Protractor is a popular end-to-end test framework that lets you test your Angular application on a real browser simulating the browser interactions just the way that a real user would interact with it. End-to-end tests are designed to ensure that the application behaves as expected from a user's perspective. Moreover, the tests are not concerned about the actual code implementation.

Protractor runs on top of the popular Selenium WebDriver, which is an API for browser automation and testing. In addition to the features provided by Selenium WebDriver, Protractor offers locators and methods for capturing the UI components of the Angular application.

In this tutorial, you will learn about:

• setting up, configuring and running Protractor
• writing basic tests for Protractor
• page objects and why you should use them
• guidelines to be considered while writing tests
• writing E2E tests for an application from start to finish

Doesn't that sound exciting? However, first things first.

## Do I Need to Use Protractor?

If you've been using Angular-CLI, you might know that by default, it comes shipped with two frameworks for testing. They are:

• unit tests using Jasmine and Karma
• end-to-end tests using Protractor

The apparent difference between the two is that the former is used to test the logic of the components and services, while the latter is used to ensure that the high-level functionality (which involves the UI elements) of the application works as expected.

If you are new to testing in Angular, I'd recommend reading the Testing Components in Angular Using Jasmine series to get a better idea of where to draw the line.

In the former's case, you can leverage the power of Angular testing utilities and Jasmine to write not just unit tests for components and services, but basic UI tests also. However, if you need to test the front-end functionality of your application from start to end, Protractor is the way to go. Protractor's API combined with design patterns such as page objects make it easier to write tests that are more readable. Here's an example to get things rolling.

## Configuring Protractor

Setting up Protractor is easy if you are using Angular-CLI to generate your project. The directory structure created by ng new is as follows.

The default project template created by Protractor depends on two files to run the tests: the spec files that reside inside the e2e directory and the configuration file (protractor.conf.js). Let's see how configurable protractor.conf.js is:

If you are ok with running the test on Chrome web browser, you can leave this as is and skip the rest of this section.

### Setting Up Protractor With Selenium Standalone Server

The directConnect: true lets Protractor connect directly to the browser drivers. However, at the moment of writing this tutorial, Chrome is the only supported browser. If you need multi-browser support or run a browser other than Chrome, you will have to set up Selenium standalone server. The steps are as follows.

Install Protractor globally using npm:

This installs the command-line tool for webdriver-manager along with that of protractor. Now update the webdriver-manager to use the latest binaries, and then start the Selenium standalone server.

Finally, set the directConnect: false and add the seleniumAddress property as follows:

The config file on GitHub provides more information about the configuration options available on Protractor. I will be using the default options for this tutorial.

## Running the Tests

ng e2e is the only command you need to start running the tests if you are using Angular-CLI. If the tests appear to be slow, it's because Angular has to compile the code every time you run ng e2e. If you want to speed it up a bit, here's what you should do. Serve the application using ng serve.

Then fire up a new console tab and run:

The tests should load faster now.

## Our Goal

We will be writing E2E tests for a basic Pastebin application. Clone the project from the GitHub repo.

Both the versions, the starter version (the one without the tests) and the final version (the one with the tests), are available on separate branches. Clone the starter branch for now. Optionally, serve the project and go through the code to get acquainted with the application at hand.

Let's describe our Pastebin application briefly. The application will initially load a list of pastes (retrieved from a mock server) into a table. Each row in the table will have a View Paste button which, when clicked on, opens up a bootstrap modal window. The modal window displays the paste data with options to edit and delete the paste. Towards the end of the table, there is a Create Paste button which can be used to add new pastes.

The rest of the tutorial is dedicated to writing Protractor tests in Angular.

## Protractor Basics

The spec file, ending with .e2e-spec.ts, will host the actual tests for our application. We will be placing all the test specs inside the e2e directory since that's the place we've configured Protractor to look for the specs.

There are two things you need to consider while writing Protractor tests:

• Jasmine Syntax
• Protractor API

### Jasmine Syntax

Create a new file called test.e2e-spec.ts with the following code to get started.

This depicts how our tests will be organized inside the spec file using Jasmine's syntax. describe(), beforeEach() and it() are global Jasmine functions.

Jasmine has a great syntax for writing tests, and it works just as well with Protractor. If you are new to Jasmine, I would recommend going through Jasmine's GitHub page first.

The describe block is used to divide the tests into logical test suites. Each describe block (or test suite) can have multiple it blocks (or test specs). The actual tests are defined inside the test specs.

"Why should I structure my tests this way?" you may ask. A test suite can be used to logically describe a particular feature of your application. For instance, all the specs concerned with the Pastebin component should ideally be covered inside a describe block titled Pastebin Page. Although this may result in tests that are redundant, your tests will be more readable and maintainable.

A describe block can have a beforeEach() method which will be executed once, before each spec in that block. So, if you need the browser to navigate to a URL before each test, placing the code for navigation inside beforeEach() is the right thing to do.

Expect statements, which accept a value, are chained with some matcher functions. Both the real and the expected values are compared, and a boolean is returned which determines whether the test fails or not.

### Protractor API

Now, let's put some flesh on it.

browser.get('/') and element(by.css('.pastebin')).getText() are part of the Protractor API. Let's get our hands dirty and jump right into what Protractor has to offer.

The prominent components exported by Protractor API are listed below.

1. browser(): You should call browser() for all the browser-level operations such as navigation, debugging, etc.
2. element(): This is used to look up an element in the DOM based on a search condition or a chain of conditions. It returns an ElementFinder object, and you can perform actions such as getText() or click() on them.
3. element.all(): This is used to look for an array of elements that match some chain of conditions. It returns an ElementArrayFinder object. All the actions that can be performed on ElementFinder can be performed on ElementArrayFinder also.
4. locators: Locators provide methods for finding an element in an Angular application.

Since we will be using locators very often, here are some of the commonly used locators.

• by.css('selector-name'): This is by far the commonly used locator for finding an element based on the name of the CSS selector.
• by.name('name-value'): Locates an element with a matching value for the name attribute.
• by.buttonText('button-value'): Locates a button element or an array of button elements based on the inner text.

Note: The locators by.model, by.binding and by.repeater do not work with Angular 2+ applications at the time of writing this tutorial. Use the CSS-based locators instead.

Let's write more tests for our Pastebin application.

The code above works, and you can verify that yourself. However, wouldn't you feel more comfortable writing tests without the Protractor-specific vocabulary in your spec file? Here's what I am talking about:

The specs appear more straightforward without the extra Protractor baggage. How did I do that? Let me introduce you to Page Objects.

## Page Objects

Page Object is a design pattern which is popular in the test automation circles. A page object models a page or part of an application using an object-oriented class. All the objects (that are relevant to our tests) like text, headings, tables, buttons, and links can be captured in a page object. We can then import these page objects into the spec file and invoke their methods. This reduces code duplication and makes maintenance of code easier.

Create a directory named page-objects and add a new file inside it called pastebin.po.ts. All the objects concerned with the Pastebin component will be captured here. As previously mentioned, we divided the whole app into three different components, and each component will have a page object dedicated to it. The naming scheme .po.ts is purely conventional, and you can name it anything you want.

Here is a blueprint of the page we are testing.

Here is the code.

#### pastebin.po.ts

Let's go over what we've learned thus far. Protractor's API returns objects, and we've encountered three types of objects thus far. They are:

• promise.Promise
• ElementFinder
• ElementArrayFinder

In short, element() returns an ElementFinder, and element().all returns an ElementArrayFinder. You can use the locators (by.css, by.tagName, etc.) to find the location of the element in the DOM and pass it to element() or element.all()

ElementFinder and ElementArrayFinder can then be chained with actions, such as isPresent(), getText(), click(), etc. These methods return a promise that gets resolved when that particular action has been completed.

The reason why we don't have a chain of then()s in our test is because Protractor takes care of it internally. The tests appear to be synchronous even though they are not; therefore, the end result is a linear coding experience. However, I recommend using async/await syntax to ensure that the code is future proof.

You can chain multiple ElementFinder objects, as shown below. This is particularly helpful if the DOM has multiple selectors of the same name and we need to capture the right one.

Now that we have the code for the page object ready, let's import it into our spec. Here's the code for our initial tests.

## Organizing Tests and Refactoring

Tests should be organized in such a way that the overall structure appears meaningful and straightforward. Here are some opinionated guidelines that you should keep in mind while organizing E2E tests.

• Separate E2E tests from unit tests.
• Group your E2E tests sensibly. Organize your tests in a way that matches the structure of your project.
• If there are multiple pages, page objects should have a separate directory of their own.
• If the page objects have some methods in common (such as navigateToHome()), create a base page object. Other page models can inherit from the base page model.
• Make your tests independent from each other. You don't want all your tests to fail because of a minor change in the UI, do you?
• Keep the page object definitions free of assertions/expectations. Assertions should be made inside the spec file.

Following the guidelines above, here's what the page object hierarchy and the file organization should look like.

We've already covered pastebin.po.ts and mainPage.e2e-spec.ts. Here are the rest of the files.

## Exercises

There are a couple of things missing, though: the tests for the View Paste button and the modal window that pops up after clicking the button. I am going to leave this as an exercise for you. However, I will drop you a hint.

The structure of the page objects and the specs for the ViewPastePage are similar to that of the AddPastePage.

Here are the scenarios that you need to test:

1. ViewPaste Page should have a button, and on click, it should bring up a modal window.
2. The modal window should display the paste data of the recently added paste.
3. The modal window should let you update values.
4. The delete button should work.

Try to stick to the guidelines wherever possible. If you're in doubt, switch to the final branch to see the final draft of the code.

## Wrapping It Up

So there you have it. In this article, we've covered writing end-to-end tests for our Angular application using Protractor. We started off with a discussion about unit tests vs. e2e tests, and then we learned about setting up, configuring and running Protractor. The rest of the tutorial concentrated on writing actual tests for the demo Pastebin application.

Please let me know your thoughts and experiences about writing tests using Protractor or writing tests for Angular in general. I would love to hear them. Thanks for reading!


text:
# GNAT Programming Studio (GPS) on GitHub

## by Emmanuel Briot – Sep 12, 2016

As we mentioned in an earlier post, AdaCore is busy making the source code for its tools available on GitHub. This is not a simple process. Some of the projects first had to be converted to git (from our historical use of subversion), and we needed to make sure that the tools can indeed be built with what is already available out there.

We started with a few libraries and tools, like GtkAda and gprbuild.

We have now managed to make the GNAT Programming Studio (also known as GPS) available. This is a large project that depends on a large number of libraries.

### Getting the sources

To download the sources (in fact, to download the whole history of the 16 year old project), head to the GPS GitHub repository. As always on GitHub, you can explore the code online. But the more convenient approach is to click on the green button at the top of the page:

Copy the URL, and in your terminal you can then type:

    git clone https://github.com/AdaCore/gps

to get the sources locally. Take a look at the INSTALL file for build instructions. Beware that you will need to first download and compile a number of other dependencies, like gprbuild, GtkAda and GnatColl. That most likely should not be the first project you try to compile.

### What you can contribute

We have of course multiple reasons to make our sources available on a day to day basis. The most important is perhaps to help build communities around those tools. This is a great way to make sure they actually fulfill your expectations, and give you a chance to contribute ideas and code if you can.

In the specific case of GPS, we believe we have a great Integrated Development Environment, which can be used in a large number of settings - whether you are developing a multi-million line project, or getting started with your first embedded software, or programming in other languages like C, C++ or Python. We also try to welcome people coming from other environments by taking a look at what exists and when possible, providing similar features.

Such work can be done in GPS via the use of Python plugins, which have a great flexibility nowadays. Take a look at the GPS documentation and the existing plugins for examples.

Unfortunately, we can't do it all and you might be able to help. We have been talking for years of setting up a repository of useful plugins written by people outside of the main GPS developers. And we believe GitHub is a great step forward in that direction.

### How you can contribute

The way this works on GitHub is the following:

1. Create a GitHub account if you do not have one already
2. Go to the GitHub page for GPS
3. Click on the Fork button at the top-right corner. A window will pop up that lets you specify where to work. Select your account. Github clones the repository to your own copy.
5. Modify the sources or add new files with standard git commands, in particular "git add" and "git commit"
6. When you are ready, type "git push" to contribute your changes to your own repository on GitHub.
To make things simpler in the case of trivial changes, steps 4, 5 and 6 can be done directly from the GitHub interface by editing files in place.
7. You can now let us, the GPS developers, know that you have made the ultimate, ground breaking and fabulous change (or, if you prefer, that you have done a small minor fix). Click on the New Pull Request button. In the resulting dialog, you can leave most of the settings with their default value (which will basically try to merge your master branch into the official GPS master branch). When you press Create Pull Request, the GPS developers will receive a notification that a change is ready for adding to GPS.
8. We will then do code reviews and comments on your patch and, I am sure, ultimately integrate it in the official GPS sources. At this stage, you have become a GPS contributor!


text:
Question

# Question 4 (v) Form the pair of linear equations in the following problems and find their solutions (if they exist) by any algebraic method: The area of a rectangle gets reduced by 9 square units, if its length is reduced by 5 units and breadth is increased by 3 units. If we increase the length by 3 units and the breadth by 2 units, the area increases by 67 square units. Find the dimensions of the rectangle.

Solution

## Let length and breadth of rectangle be x unit and y unit respectively. Area = xy According to the question, (x - 5) (y + 3) = xy - 9 ⇒ 3x - 5y - 6 = 0 ... (i) (x + 3) (y + 2) = xy + 67 ⇒ 2x - 3y - 61 = 0 ... (ii) By cross multiplication, we get x305−(−18)=y−12−(−183)=19−(−10) x323=y171=119 x = 17, y = 9 Hence, the length of the rectangle = 17 units and breadth of the rectangle = 9 units

Suggest corrections


text:
Suggested languages for you:

Q. 38

Expert-verified
Found in: Page 625

Physics for Scientists and Engineers: A Strategic Approach with Modern Physics

Book edition 4th
Author(s) Randall D. Knight
Pages 1240 pages
ISBN 9780133942651

A Van de Graaff generator is a device that accumulates electrons on a large metal sphere until the large amount of charge causes sparks. As you’ll learn in Chapter , the electric field of a charged sphere is exactly the same as if the charge were a point charge at the center of the sphere. Suppose that a diameter sphere has accumulated extra electrons and that a small ball 50 cm from the edge of the sphere feels the force , away from sphere). What is the charge on the ball?

The charge of the ball is .

See the step by step solution

Step 1: Equations

As two cosmic rays, one with a charge and the other with a charge , are separated by a radius , they exert forces upon one another, with the force diminishing as the distance grows and increasing as the magnitude of the charges increases. This force is described by Coulomb, which is expressed as equation () in the form

Equation

Where is the electrostatic constant, which is equal to The charge of the metal sphere is , while the charge of the ball is .To derive the form, solve equation () for .

Equation

The distance between the sphere's centre and the ball is called . As a result, it might be calculated using

Step 2: Explanation

The number of electrons on the metal sphere is , and each photon's charge is , and thus the total charges on the ball are

To find the magnitude of the charge on the ball, put the values for , , , and into equation ().

The charge of is


text:
Share

Books Shortlist

# Solution for In triangleAbc, D and E Are the Mid-points of Ab and Ac Respectively. Find the Ratio of the Areas of δAde and δAbc - CBSE Class 10 - Mathematics

#### Question

In ΔABC, D and E are the mid-points of AB and AC respectively. Find the ratio of the areas of ΔADE and ΔABC

#### Solution

We have, D and E as the mid-points of AB and AC

So, according to the mid-point theorem

DE || BC and DE =1/2BC            ...(i)

∠A = ∠A [Common]

Then, ΔADE ~ ΔABC [By AA similarity]

By area of similar triangle theorem

("Area"(triangleADE))/("Area"(triangleABC))="DE"^2/"BC"^2

=(1/2BC)^2/"BC"^2               [From (i)]

=(1/4BC^2)/"BC"^2

=1/4

Is there an error in this question or solution?

#### Video TutorialsVIEW ALL [1]

Solution In triangleAbc, D and E Are the Mid-points of Ab and Ac Respectively. Find the Ratio of the Areas of δAde and δAbc Concept: Areas of Similar Triangles.
S


text:
# How do you write y=2x^2-5x into vertex form?

##### 1 Answer
Jun 19, 2018

$y = 2 {\left(x - \frac{5}{4}\right)}^{2} + \left(- \frac{25}{8}\right)$

#### Explanation:

Here is one way to approach converting the given form $y = 2 {x}^{2} - 5 x$ into vertex form: $m {\left(x - a\right)}^{2} + b$

$y = 2 {x}^{2} - 5 x$

$\Rightarrow \frac{y}{2} = {x}^{2} - \frac{5}{2} x$

Remember that the expansion perfect square binomial will have the form ${x}^{2} + 2 a x + {a}^{2}$

If ${x}^{2} - \frac{5}{2} x$ are the first two terms of the expansion of a perfect square binomial, then
$\textcolor{w h i t e}{\text{XXX}} a = - \frac{5}{4}$
and
$\textcolor{w h i t e}{\text{XXX}} {a}^{2} = {\left(- \frac{5}{4}\right)}^{2}$

So we will need to add ${\left(- \frac{5}{4}\right)}^{2}$ to "complete the square" (of course if we add this to one side we will also need to add it to the other to keep the equation valid).

$\frac{y}{2} + {\left(- \frac{5}{4}\right)}^{2} = {x}^{2} - \frac{5}{2} x + {\left(- \frac{5}{4}\right)}^{2}$

$\textcolor{w h i t e}{\text{XXXXXXXX}} = {\left(x - \frac{5}{4}\right)}^{2}$

To get this into its proper form we need to isolate the $y$ on the left side:
Subtracting ${\left(- \frac{5}{4}\right)}^{2} = \frac{25}{16}$ from both sides:
$\textcolor{w h i t e}{\text{XXX}} \frac{y}{2} = {\left(x - \frac{5}{4}\right)}^{2} - \left(\frac{25}{16}\right)$
then multiplying both sides by $2$
$\textcolor{w h i t e}{\text{XXX}} y = 2 {\left(x - \frac{5}{4}\right)}^{2} + \left(- \frac{25}{8}\right)$

Here is the graph of $y = 2 {x}^{2} - 5 x$ to indicate that this result is reasonable:
graph{2x^2-5x [-3.03, 5.742, -4.165, 0.217]}


text:
# HMM with GP

Hello Everyone,

I am trying to implement a model that combines a Gaussian Process with HMM. Specifically, it assumes that the observations are generated through a process as follows:

Obs ~ GP + \alpha_s

where the \alpha_s is a state dependent intercept is emitted by a Gaussian HMM process and GP is a Gaussian process with SE kernel.
I am trying to implement it in Stan. While checking the model with simulated data, the estimated HMM means are equally shifted by a random amount. For example, in the following sample output each estimated mean is shifted approximately by an amount -0.74:

Warning messages:

1: There were 1000 transitions after warmup that exceeded the maximum treedepth. Increase max_treedepth above 10. See

http://mc-stan.org/misc/warnings.html#maximum-treedepth-exceeded

True Transition Matrix

      [,1]       [,2]      [,3]

[1,] 0.64 0.05 0.30

[2,] 0.10 0.06 0.83

[3,] 0.14 0.20 0.64

Estimated Transition Matrix

      [,1]           [,2]                 [,3]

[1,] 0.67 0.06 0.26

[2,] 0.11 0.22 0.65

[3,] 0.24 0.15 0.59

True State Means

[1] 1.30 1.94 2.05

Estimated State Means

[1] 0.56 1.16 1.28

The amount of shift randomly differs every time I run the code with different test conditions. The mixing in the trace-plots seem to be very poor. It seems that there is an identification issue and I am not sure how to resolve that.

I have imposed ordering constraint on the HMM means. I have also tried Non-centered parameterizations for both GP and HMM parameters. Even set the initial value to zero for the latent function in GP. But, nothing seems to work.

data {
int<lower=1> N;
real x[N];
vector[N] y;
int<lower=1> S;
}

transformed data {
real delta = 1e-9;
}

parameters {
vector[N] eta;

real rho_tilde;
real<lower=0> rho_m;
real<lower=0> rho_s;

real alpha_tilde;
real<lower=0> alpha_m;
real<lower=0> alpha_s;

real sigma_tilde;
real<lower=0> sigma_m;
real<lower=0> sigma_s;

vector[S] muH_tilde;
vector<lower=0>[S] muH_s;
vector<lower=0>[S] muH_m;

simplex[S] A[S];
simplex[S] pi1;

real<lower=0> sigmaH[S];
real alphaH[N];
vector[N-1] free_pnum;
}

transformed parameters {
vector[N] f;
vector[1] z;
matrix[N, N] L_K;
real<lower=0> rho;
real<lower=0> alpha;
real<lower=0> sigma;
vector[S] muH;
vector[S] muTemp;

rho = exp(log(rho_m) + rho_s * rho_tilde);
alpha = exp(log(alpha_m) + alpha_s * alpha_tilde);
sigma = exp(log(sigma_m) + sigma_s * sigma_tilde);

for (i in 1:S)
muTemp[i] = exp(log(muH_m[i]) + muH_s[i] * muH_tilde[i]);

muH = sort_asc(muTemp);

z[1] = 0;
f = append_row(z,free_pnum);
{
matrix[N, N] K = cov_exp_quad(x, alpha, rho);
for (n in 1:N)
K[n, n] = K[n, n] + delta;

L_K = cholesky_decompose(K);
f = L_K * eta;
}
}

model {
vector[N] theta;
vector[S] logalpha[N];

target += inv_gamma_lpdf(rho_m    | 2, 0.5);
target += normal_lpdf(alpha_m     | 0, 2.0);
target += normal_lpdf(sigma_m     | 0, 1.0);
target += normal_lpdf(muH_m       | 0, 1.0);

target += normal_lpdf(rho_s       | 0, 0.5);
target += normal_lpdf(alpha_s     | 0, 0.5);
target += normal_lpdf(sigma_s     | 0, 0.5);
target += normal_lpdf(muH_s       | 0, 0.5);

target += normal_lpdf(rho_tilde   | 0, 1.0);
target += normal_lpdf(alpha_tilde | 0, 1.0);
target += normal_lpdf(sigma_tilde | 0, 1.0);
target += normal_lpdf(muH_tilde   | 0, 1.0);

target += normal_lpdf(eta         | 0, 1.0);
target += gamma_lpdf(sigmaH       | 2, 2.0);

// Forward algorithm
{
real accumulator[S];

logalpha[1] = log(pi1) + normal_lpdf(alphaH[1] | muH, sigmaH);

for (t in 2:N) {
for (j in 1:S) {
for (i in 1:S) {
accumulator[i] = logalpha[t-1, i] + log(A[i, j]) + normal_lpdf(alphaH[t] | muH[j], sigmaH[j]);
}
logalpha[t, j] = log_sum_exp(accumulator);
}
}
}

target += log_sum_exp(logalpha[N]);

for (n in 1:N)
theta[n] = f[n] + alphaH[n];

target += normal_lpdf(y | theta, sigma);

}

Data generation Code in R

library(rstan)
library(ggplot2)
library(shinystan)

set.seed(123456789)

logit <- function(x){1/(1+exp(-x))}

runif_simplex <- function(T) {
x <- -log(runif(T))
x / sum(x)
}

hmm_generate <- function(K, T) {
# 1. Parameters
pi1   <- runif_simplex(K)
A     <- t(replicate(K, runif_simplex(K)))
mu    <- sort(rnorm(K, 1.0 * 1:K, 1))
sigma <- 0.01

# 2. Hidden path
z <- vector("numeric", T)

z[1] <- sample(1:K, size = 1, prob = pi1)
for (t in 2:T)
z[t] <- sample(1:K, size = 1, prob = A[z[t - 1], ])

# 3. Observations
y <- vector("numeric", T)
for (t in 1:T)
y[t] <- rnorm(1, mu[z[t]], sigma)

list(y = y, z = z,
theta = list(pi1 = pi1, A = A, mu = mu, sigma = sigma))
}

K <- 3
N <- 100
dataset  <- hmm_generate(K, N)
dataset
f <- function(x) x^2 + x
x <- rnorm(N, mean = 0, sd = 0.5)
yhmm <-  rnorm(length(x), mean=f(x)+ dataset$y, sd=0.1) plot(x,yhmm) stan_data = list(N=N, x=x, y=yhmm, S=K) fit_hmm <- stan(file = "HMMGp.stan", data=stan_data, verbose = F, chains = 1, control = list(adapt_delta = 0.99)) muH <- extract(fit_hmm, pars = 'muH')[[1]] A <- extract(fit_hmm, pars = 'A')[[1]] sigmaH <- extract(fit_hmm, pars = 'sigmaH')[[1]] hmat = c() for(i in 1:3){ for(j in 1:3)hmat=c(hmat,mean(A[][,i,][,j])) } A = t(matrix(hmat, nrow=3,ncol=3)) dataset$theta$A A mH = c() for(i in 1:3){mH=c(mH,mean(muH[,i]))} mH dataset$theta$mu sH = c() for(i in 1:3){sH=c(sH,mean(sigmaH[,i]))} sH dataset$theta$sigma  Is it even possible to estimate this model? Please have a look at the code and kindly guide me. Thank you so much. 1 Like Are there correlations between corresponding elements of alphaH and muH? If that leads nowhere, have you tried a simpler version of this model with the various standard deviation parameters fixed? Hi Ben, Thank you for responding! I did check the correlations between elements of alphaH and muH, but they are hardly correlated. Yes, I did run the simpler versions with fixed SD first. I am attaching the stan code for the simplest version (fixed SD and just the ordering constraint on muH) here data { int<lower=1> N; real x[N]; vector[N] y; int<lower=1> S; } transformed data { real delta = 1e-9; } parameters { real<lower=0> rho; real<lower=0> alpha; real<lower=0> sigma; vector[N] eta; simplex[S] A[S]; simplex[S] pi1; ordered[S] muH; real<lower=0> sigmaH[S]; real alphaH[N]; } transformed parameters { vector[N] f; matrix[N, N] L_K; { matrix[N, N] K = cov_exp_quad(x, alpha, rho); for (n in 1:N) K[n, n] = K[n, n] + delta; L_K = cholesky_decompose(K); f = L_K * eta; } } model { vector[N] theta; vector[S] logalpha[N]; target += inv_gamma_lpdf(rho | 2, 0.5); target += normal_lpdf(alpha | 0, 2); target += normal_lpdf(sigma | 0, 1); target += normal_lpdf(eta | 0, 1); { // Forward algorithm real accumulator[S]; logalpha[1] = log(pi1) + normal_lpdf(alphaH[1] | muH, sigmaH); for (t in 2:N) { for (j in 1:S) { for (i in 1:S) { accumulator[i] = logalpha[t-1, i] + log(A[i, j]) + normal_lpdf(alphaH[t] | muH[j], sigmaH[j]); } logalpha[t, j] = log_sum_exp(accumulator); } } } // Forward target += log_sum_exp(logalpha[N]); for (n in 1:N) theta[n] = f[n] + alphaH[n]; target += normal_lpdf(y | theta, sigma); }  But the problems were there also … Hi Ben, Once again I checked the correlations between muH and alphaH, this time for the most basic model (with just the ordering constraint on muH and fixed SD). In this case you are absolutely right … they are highly correlated !!! This is what the correlations look like … [1] 0.9933211 [1] 0.9942825 [1] 0.9894899 [1] 0.9941154 [1] 0.9900316 [1] 0.9933434 [1] 0.9901557 [1] 0.9712893 [1] 0.9895402 [1] 0.9900569 [1] 0.9890224 I am attaching the replication code here (the corresponding Stan code is already shared in my previous reply) library(rstan) library(ggplot2) library(shinystan) set.seed(900) logit <- function(x){1/(1+exp(-x))} runif_simplex <- function(T) { x <- -log(runif(T)) x / sum(x) } hmm_generate <- function(K, T) { # 1. Parameters pi1 <- runif_simplex(K) A <- t(replicate(K, runif_simplex(K))) mu <- sort(rnorm(K, 1.0 * 1:K, 1)) sigma <- 0.01 # 2. Hidden path z <- vector("numeric", T) z[1] <- sample(1:K, size = 1, prob = pi1) for (t in 2:T) z[t] <- sample(1:K, size = 1, prob = A[z[t - 1], ]) # 3. Observations y <- vector("numeric", T) for (t in 1:T) y[t] <- rnorm(1, mu[z[t]], sigma) list(y = y, z = z, theta = list(pi1 = pi1, A = A, mu = mu, sigma = sigma)) } K <- 3 N <- 100 dataset <- hmm_generate(K, N) f <- function(x) x^2 + x x <- rnorm(N, mean = 0, sd = 0.5) yhmm <- rnorm(length(x), mean=f(x)+ dataset$y, sd=0.1)
plot(x,yhmm)

stan_data = list(N=N, x=x, y=yhmm, S=K)
fit_hmm <- stan(file = "stan/HMMGp3.stan", data=stan_data, verbose = T, chains = 1)
muH   <- extract(fit_hmm, pars = 'muH')[[1]]
A   <- extract(fit_hmm, pars = 'A')[[1]]

hmat = c()
for(i in 1:3){for(j in 1:3)hmat=c(hmat,mean(A[][,i,][,j]))}
A = t(matrix(hmat, nrow=3,ncol=3))
dataset$theta$A
A
mH = c()
for(i in 1:3){mH=c(mH,mean(muH[,i]))}
mH
dataset$theta$mu

alphaH   <- extract(fit_hmm, pars = 'alphaH')[[1]]
aH = c()
for(i in 1:N){aH=c(aH,mean(alphaH[,i]))}
aH

for(j in 1:K){
for(i in 1:N){
print(cor(muH[,j],alphaH[,i]))
}
}

This is what the muH[1] trace looks like

The autocorrelation plot:

So what should be the next step ?

This probably means that, while you’re estimating alphaH and muH, you don’t have the data to estimate them both.

Back to the model, you’re saying:

\mu_1 \sim GP(t)\\ \mu_2 \sim HMM(t)\\ y \sim \text{normal}(\mu_1 + \mu_2, \sigma)

Something like this? And you wanna estimate \mu_1, \mu_2, and all the parameters of the GP and HMM?

That’s correct … I want to estimate the parameters of GP and HMM … Is there a way to do that ?

The variables \mu_1 and \mu_2 are probly gonna be super unidentified. Either the GP or HMM can explain the output, and both of those models are pretty flexible.

Without heavily constraining the problem, you’re probably gonna have lots of trouble.

Did this start as an HMM and add the GP? Or did this start as a GP and add an HMM? Either way, what was the motivation for the second model? Maybe there’s a different assumption to be made there.

I understand … It started as a GP and HMM came later. The idea is as follows: suppose we are looking at a flexible pattern, e.g. we read book for a certain random period of time every day and the duration is generally higher on the weekends. This is a regular pattern, but sometimes our reading time significantly goes up for a few consecutive days (e.g. when we are approaching the climax of the current book and just can’t leave it whether its weekend or not). After this heightened period of action we again go back to the original pattern till we hit the next climax. So the idea was to model the regular pattern with a GP but add a HMM component (say normal vs climax state) to capture the periods of heightened activity.

Oooh, okay. Do you have this much structure in your actual problem? If so, then maybe just encoding things with covariates is the way to go.

Something like:

\mu_1 \sim GP \\ y \sim \text{normal}(\mu_1 + a x)

where x is a 0 and 1 indicator (0 on weekdays, 1 on weekends) and then a represents the weekend effect

This’ll be a much simpler model to interpret/fit.

Facebook prophet does this sorta thing if you’re actually dealing with data that has weekly, seasonal, and holiday trends or whatnot: Prophet | Forecasting at scale.

That’s right … the temporal periodicities can be accounted for by the GP … but the focus is on these heightened activity periods that occur randomly


text:
# Hire Me (as a Data Scientist!), Part IV

Since this is my last post in the beer review series, I’ll keep this short and sweet in terms of analysis. Having done all of this, I do have a few reflections I would like to share after doing the One-Size-Fits-All-Data-Science Interview that I have included at the end.

Our final question to answer is:

Lastly, if I typically enjoy a beer due to its aroma and appearance, which beer style should I try?

This is a pretty broad question and should be able to be answered without many pitfalls, so let’s get started.

library(ggplot2)
library(data.table)
beer <- fread("data/beer_reviews.csv")

From a bird’s eye view, it seems like the most sensible thing to do would be to look at our data from the highest level, then just zoom in until we have the level of granularity we feel answers the question well. Let’s first average all the beer styles to get a rough estimate of how a beer style fairs on the variables we are interested in, and additionally see how much variability is associated with that measurement.

sem <-function(x) {sd(x)/sqrt(length(x))}

question4.means <- beer[, .(mean_aroma = mean(review_aroma), mean_appearance = mean(review_appearance), mean_overall = mean(review_overall),
sem_aroma = sem(review_aroma), sem_appearance = sem(review_appearance), sem_overall = sem(review_overall),
sd_aroma = sd(review_aroma), sd_appeareance = sd(review_appearance),sd_overall = sd(review_overall)),
by = beer_style]
question4.means
##                           beer_style mean_aroma mean_appearance mean_overall
##   1:                      Hefeweizen   3.761735        3.828293     3.929626
##   2:              English Strong Ale   3.749427        3.852469     3.783288
##   3:          Foreign / Export Stout   3.828366        4.039015     3.877679
##   4:                 German Pilsener   3.387159        3.572444     3.731573
##   5:  American Double / Imperial IPA   4.097782        4.078916     3.998017
##  ---
## 100:                          Gueuze   4.117574        4.034864     4.086287
## 101:                            Gose   3.783528        3.908163     3.965015
## 102:                        Happoshu   2.595436        2.925311     2.914938
## 103:                           Sahti   3.827992        3.655985     3.700283
## 104: Bière de Champagne / Bière Brut   3.734704        4.045889     3.648184
##        sem_aroma sem_appearance sem_overall  sd_aroma sd_appeareance sd_overall
##   1: 0.003668940    0.003595729 0.004051038 0.6129217      0.6006912  0.6767538
##   2: 0.008118012    0.007674182 0.009323636 0.5623738      0.5316275  0.6458931
##   3: 0.007222404    0.006830955 0.008163490 0.5581381      0.5278874  0.6308640
##   4: 0.004611304    0.004323963 0.005097580 0.6863721      0.6436027  0.7587521
##   5: 0.001937927    0.001600133 0.002171618 0.5682357      0.4691883  0.6367582
##  ---
## 100: 0.007225256    0.006450020 0.008273156 0.5600855      0.4999910  0.6413163
## 101: 0.019413627    0.015860893 0.023754558 0.5084740      0.4154222  0.6221699
## 102: 0.048722437    0.051373864 0.063538226 0.7563756      0.7975368  0.9863785
## 103: 0.019516104    0.017677122 0.021691778 0.6356980      0.5757968  0.7065662
## 104: 0.021782360    0.018920362 0.026781986 0.7044834      0.6119209  0.8661809

Knowing how each beer style fluctuates on our variables of interest (with our overall score thrown in for good measure!), let’s plot our results. Note that I have included standard error of the mean error bars as a sanity check to make sure that each beer’s ratings is not going to bleed into the others’ dimensions. By doing this, we can have a bit more confidence that we are looking at actually has some meaning. This plot shows the standard error on each of the two variables we are interested in, and for the most part it looks as if they are relatively well contained.

ggplot(question4.means, aes(x = mean_aroma, y = mean_appearance, color = beer_style)) +
geom_point() +
geom_errorbar(aes(ymin=mean_appearance-sem_appearance, ymax=mean_appearance+sem_appearance), width=.1) +
geom_errorbarh(aes(xmin=mean_aroma-sem_aroma, xmax=mean_aroma+sem_aroma)) + theme(legend.position="none") +
labs(title = "Mean Appearance and Aroma", y = "Mean Aroma", x = "Mean Appearance")

This graph has a lot of beers, but what we are interested in is that top right quadrant where both the average appearance and aroma are maxed out. Let’s zoom in on it and throw in a sizing variable of the overall rating and inspect our graph.

ggplot(question4.means[mean_appearance > 4 & mean_aroma > 4],
aes(x = mean_aroma, y = mean_appearance, color = beer_style, size = mean_overall)) +
geom_point() + xlim(4,4.2) + ylim(4,4.25) +  theme(legend.position="none") +
# geom_errorbar(aes(ymin=mean_appearance-sem_appearance, ymax=mean_appearance+sem_appearance), width=.1) +
#  geom_errorbarh(aes(xmin=mean_aroma-sem_aroma, xmax=mean_aroma+sem_aroma)) + theme(legend.position="none") +
labs(title = "Mean Appearance and Aroma", y = "Mean Aroma", x = "Mean Appearance") +
geom_text(aes(label=beer_style, hjust = .5, vjust = -.75))

Looking at this subsection, it appears we have a few choices for beers that score highly on both Appearance and Aroma. The American Double / Imperial Stout looks like a good option as it scores higher on how it looks, but our Russian Imperial Stout has a higher Aroma score. We could start crunching more numbers here to find “the best” option, or at this point we could take off our data science hats and put our psychology ones back on (assuming that’s what we were wearing…) and run some double-blind experiments on ourselves to make sure that our data is actually lining up with something in the real world.

## Reflections

What started out as a fun weekend project actually turned into a really great learning experience. I’ve definitely put a few solid hours into this and have gotten a lot out of it. I learned that my friends actually know a TON about beer and data science, that git-lfs is something I wish I would have known about earlier, and that I’m actually looking forward to doing more blogging in the future.

I will probably have to go MIA for the next two weeks since my General Exams are coming up in early February, but I’m sure I will be back at it come late March. Until then, all I can hope for is that someone who is looking to hire a junior data scientist over the summer will come across these posts and think I might be a good temporary addition to their team.


text:
1

1

1

1

1

1

1

# GCSE Maths Quiz

Quiz by , created over 2 years ago

## Are you smarter than a 16 year old? Try this GCSE Maths quiz to find out!

455
6
1
 Created by andrea.leyden over 2 years ago Copied by mia.rigby over 2 years ago


text:
# Conditional expectation of an unbiased and sufficent statistic

I'm having some trouble understanding the following equality from my course book.

Some background:

Let $$X_1,...,X_n$$ be n independent Bernoulli r.v's with unknow parameter $$\theta$$. $$X_1$$ is an unibased estimator for $$\theta$$ and $$T(X) = \sum_{i=1}^n X_i$$ is a sufficent statistic.

Now to derive an estimator with a smaller variance one can use Rao-Blackwell's theorem and calculate the conditional expectation of the unbiased estimator and the sufficent statistic.

The following is written in my book which I do not understand.

$$E_\theta (X_1|\sum_{i=1}^n X_i =t) = P_\theta (X_1 =1|\sum_{i=1}^n X_i = t)$$

I tried to compute using some conditional expectation properties but I feel like the course book is skipping a lot of steps or that I might be missing something. Also, why is $$X_1 = 1$$ in the probability function?

I would appreciate if anyone could explain to me what is going on here.

Since $$X_1$$ bernoulli, it can only take on values 0,1. Explicitely write out the expectation. For computing the probability, you have to use a combinatorics argument. It's something like this: given that out of n coins, t are heads, there is a total of nCt ways this could happen. Now, say the first coin was a head. Then there are (n-1)C(t-1) ways to have t heads out of n coins with the first being head. Take ratio and you should get $$\frac{t}{n}$$.

This is reasonable because given that you've seen t heads out of n, your natural guess at the true probability of heads is $$\frac{t}{n}$$.

• Oh, man I completely forgot that it could only take on values (0,1). thank you very much! – Carl Näsvall Sindeby Nov 27 '18 at 15:39

Note that $$\mathbb E_{\theta}\left(X_1\mid \sum_{i=1}^n X_i=t\right)=1\cdot P_{\theta}\left(X_1=1\mid \sum_{i=1}^n X_i=t\right)+0\cdot P_{\theta}\left(X_1=0\mid \sum_{i=1}^n X_i=t\right)=$$$$P_{\theta}\left(X_1=1\mid \sum_{i=1}^n X_i=t\right)$$

Observe that under condition $$\sum_{i=1}^n X_i=t$$ exactly $$t$$ of the $$X_i$$ give value $$1$$ and that all $$X_i$$ have equal probability to do that.

So the probability that $$X_1$$ is one of them is $$\frac{t}n$$.

This tells us that: $$P_{\theta}\left(X_i=1\mid \sum_{i=1}^n X_i=t\right)=\frac{t}n$$

Actually this together justifies the conclusion that: $$\mathbb E_{\theta}(X_1\mid \sum_{i=1}^n X_i)=\frac1n \sum_{i=1}^n X_i=\frac1nT(X)$$(so does not depend on $$\theta$$).

Does this help?