Rename Json field "LVL2" to "ORG_LVL_1" in JOLT

Question: Rename Json field "LVL2" to "ORG_LVL_1" in JOLT
<code>[
  {
    "LVL2": "Co0053",
    "status": "Active"
  },
  {
    "LVL2": "Co0054",
    "status": "Active"
  }
]
</code>
Desired Output where ORG_LVL_2 is the modified/renamed JSON field which was previously LVL2 :
<code>[
  {
    "ORG_LVL_2": "Co0053",
    "status": "Active"
  },
  {
    "ORG_LVL_2": "Co0054",
    "status": "Active"
  }
]
</code>
Answer: You can use either of the following transformation specs :
1.

<code>[
 { // generate new attribute, namely "ORG_LVL_2"
   "operation": "modify-overwrite-beta",
   "spec": {
     "*": {
       "ORG_LVL_2": "@(1,LVL2)"
     }
   }
 },
 { // delete the original attribute
   "operation": "remove",
   "spec": {
     "*": {
       "LVL2": ""
     }
   }
 }
]
</code>

or
2.

<code>[
 {
   "operation": "shift",
   "spec": {
     "*": {
       "*2": "[&1].ORG_&(0,1)_2", // use &(0,1) representation technique >to replicate the substring LVL; where 0 : the current level, 1 : the first >asterisk(indeed there's only single one)
       "*": "[&1].&" // keep the other attribute fixed
     }
   }
 }
]
</code>


Bounded weighted supremum norm and uniform integrability

Question: Let $g:\mathbf{X}\to\mathbb{R}_+$ be a positive continuous function where $\mathbf{X}\subseteq\mathbb{R}^d$. Let $f_n:\mathbf{X}\to\mathbb{R}$ where $n\in\mathbb{N}$ be a sequence of functions. Define the weighted supremum norm $\|\cdot\|_g$ by
$$
\|f_1\|_g := \sup_{x\in\mathbf{X}}\frac{|f_1(x)|}{g(x)}.
$$
Question: Let $Y$ be an integrable random variable taking values in $\mathbf{X}$. If $\|f_n\|_g < \infty$ for all $n$, is the family of random variables $(f_n(Y))_{n\in\mathbb{N}}$ uniformly integrable?
My thoughts: We know that if
$$
\sup_{n\in\mathbb{N}}\sup_{x\in\mathbf{X}}\frac{|f_n(x)|}{g(x)} < \infty.
$$
Then, with probability one:
$$
\sup_{n\in\mathbb{N}}\frac{|f_n(Y)|}{g(Y)} < \infty \implies \sup_{n\in\mathbb{N}} |f_n(Y)| < C g(Y)
$$
for some constant positive C. I know that if $g(Y)$ is integrable, then this implies $(f_n(Y))_{n\in\mathbb{N}}$ is uniformly integrable. So I am stuck here since I do not think the first inequality necessarily holds. Is there another way?
Answer: I don't think this is true but maybe I'm missing something.
Let's think about a very simple example: $g(x) = 1$, $f_n(x) = n$. Then, $\|f_n\|_g = n$ and $\|f_n\|_g < \infty$ for all $n$. Now, $(f_n(Y))_{n \in \mathbb{N}}$ does not depend on $Y$ and is clearly not uniformly integrable.


Probability related to circles

Question: There is a circle of radius 'r'. A chord is chosen at random, what is the probability that the chord is a diameter of the circle?
Comment: It should be zero.
Comment: How does time matter here?
Comment: "*A chord is chosen* **at random**"  You will need to be far more specific about the process of selection.  In any case, under most reasonable interpretations of the problem, such as both ends of the chord being chosen independently and uniformly at random, the probability that the cord is a diameter will indeed be zero.  This should be easy to see for the method of selection I describe as given any specific first selection of an endpoint, there are uncountably infinitely many selections for the second end point, only one of which results in the chord being a diameter.
Comment: You should read about [Bertrand's Paradox](https://en.wikipedia.org/wiki/Bertrand_paradox_(probability)), another probability problem related to chords on a circle where the answer to the probability problem changes depending on what method of selection you used which highlights and emphasizes the importance of adequately defining problems like this.
Comment: I thought the same but it can be chosen at any point is time
Comment: Why am I down voted for the question?
Comment: Suggested reasons to downvote: "*This question does not show any research effort; it is unclear or not useful.*"  Your question certainly fits those descriptions.  You showed no effort in having attempted the problem yourself, including but not limited to sharing your own thoughts or sharing what related information you've read.  Further, your question suffers the fatal flaw of being ill-defined, as mentioned earlier, and so is unclear.
Answer: This problem is similar (in a way) to Bertrand's Paradox: https://en.wikipedia.org/wiki/Bertrand_paradox_(probability).
This random selection is not clear as there any many different ways a chord can be randomly selected, leading to different weights on whether a chord will be a diameter or not. If there is more information to the problem that would be helpful, otherwise there is not enough information to give a clear answer.

Probability related to circles


Total time spent travelling, given distance and speed functions

Question: I have the following situtation:
An object is traveling a certain (known) distance in a straight line. The object starts at rest, accelerates to its preset maximum speed then spends some time cruising at that speed, and finally decelerates to a halt.
The object does not follow Newton's second law of motion, but rather obeys the following equations:
While cruising, it's moving normally, so d = v*t and while accelerating: d = e^(k*t) and v = k * e^(k*t), where e is the natural log base, t is time, k is a constant, d is distance traveled, and v is speed. When decelerating, the distance and speed equations are the same, but with a negative time component and are offset by the time and distance spent accelerating and cruising. The value of k for deceleration is also different from the value for acceleration (it's the acceleration k divided by 3, or just 2 if k/3 is greater than 2, if that's important).
I am trying to calculate the total travel time given the distance to travel, the maximum speed, and the acceleration and deceleration constants. The calculation is simple in the case when the distance is great enough that the object reaches its maximum speed - I can calculate t for how long it will take it to reach max speed and then back to 0 from the speed formula; then I get the distance traveled while accelerating and decelerating from the distance equation, with the remaining distance traveled at cruising speed.
I am having difficulties figuring out when the object will begin decelerating if the distance is smaller than the distance required to accelerate to max speed and decelerate back to zero.
So, how would one go about intersecting the speed graphs for acceleration and deceleration to figure out the highest speed it will achieve over such a run? (I think I can figure out the total time from there)
Comment: While accelerating, $d = e^{kt}$. So are you saying that the object started its travel at $d=1$ when $t=0$? Also, since $v=ke^{kt}$, are you saying the object was not accelerating from rest but had a sudden jump in speed?
Comment: Good point, I hadn't noticed that. The equations are true, however this mostly doesn't matter due to the size of the numbers involved. d is in m/s, but for most cases it will be several tens of AU, the max speed will be several AU/s and k will be the speed in AU (without the units). So the case of d=1 at t=0 is not significant. I didn't mention specific data cases to avoid someone bringing in relativity because the model I described is Eve Online's warp speed model, so it's hardly realistic.
Answer: Naturally, formalizing the question in a post helped me solve it. Here's what I came up with for posterity's sake:
ta = ln(Vm/ka) / ka
td = ln(Vm/kd) / kd

Vm = ((1/ka)+(1/kd)) * d

Where Vm is highest attained speed, ta, td, ka and kd are the time and k constants for acceleration and deceleration, and d is the distance to travel.
PS. If someone were kind enough to edit this stuff to use the fancy notation that would be great.


NullReferenceException Unity 3D

Question: Comecei um curso onde ensinam a criar um jogo 2D usando Unity3D, tentei adicionar coisas a mais no jogo mas estou falhando miseravelmente e então resolvi vir tentar uma ajudinha.
No caso, eu tentei criar um powerup onde quando o Player pega um buff, a velocidade do laser aumenta, mas nisso estou tendo o erro:

NullReferenceException: Object reference not set to an instance of an object
Powerup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Galaxy Shooter/Scripts/Powerup.cs:54)

Aqui vão os códigos:
Player
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

    public bool canTripleShoot = false;
    public bool movSpeedBoost = false;
    public bool shield = false;

    [SerializeField]
    private GameObject _laserPrefabs;

    [SerializeField]
    private GameObject _tripleShootPrefab;

    [SerializeField]
    private GameObject _shieldGameObject;

    [SerializeField]
    private GameObject _explosionPrefab;

    [SerializeField]
    private float _speed = 5.0f;

    [SerializeField]
    private GameObject[] _engines;

    [SerializeField]
    private float _fireRate = 0.25f;

    private float _canFire = 0.0f;
    public int playerHp = 3;
    public int _hitcount = 0;

    private UIManager _uiManager;
    private GameManager _gameManager;
    private SpawnManager _spawnManager;
    private AudioSource _audioSource;

    // Use this for initialization
    void Start () {
        _audioSource = GetComponent<AudioSource>();
        _spawnManager = GameObject.Find("Spawn_Manager").GetComponent<SpawnManager>();
        _uiManager = GameObject.Find("Canvas").GetComponent<UIManager>();
        _gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();

        transform.position = new Vector3(0, 0, 0);

        if(_uiManager != null)
        {
            _uiManager.UpdateLives(playerHp);
        }

        if(_spawnManager != null)
        {
            _spawnManager.StartSpawn();
        }

    }

    // Update is called once per frame
    void Update ()
    {
        Movement();
        //ativar ao pressionar espaço ou botão esquerdo do mouse
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0))
        {
            Shoot();
        }

    }

    //renderização e cooldown dos tiros
    private void Shoot()

    {

        if (Time.time > _canFire)
        {
            _audioSource.Play();
            if (canTripleShoot== true)
            {
                Instantiate(_tripleShootPrefab, transform.position, Quaternion.identity);

            }
            else
            {
                Instantiate(_laserPrefabs, transform.position + new Vector3(0, 0.95f, 0), Quaternion.identity);

            }
            _canFire = Time.time + _fireRate;

        }
    }
    //calculo de dano
    public void Damage()
    {
        if(shield == true)
        {
            shield = false;
            _shieldGameObject.SetActive(false);
            return;
        }

        _hitcount++;

        if(_hitcount == 1)
        {
            _engines[0].SetActive(true);
        }

        if(_hitcount == 2)
        {
            _engines[1].SetActive(true);
        }

        playerHp--;

        _uiManager.UpdateLives(playerHp);

        if(playerHp < 1)
        {
            Instantiate(_explosionPrefab, transform.position, Quaternion.identity);
            _gameManager.gameOver = true;
            _uiManager.ShowTitleScreen();
            Destroy(this.gameObject);
        }

    }

    public void ShieldUp()
    {
        shield = true;
        _shieldGameObject.SetActive(true);

    }
    //controle da velocidade de movimento e teleporte
    private void Movement()
    {
        float controleHorizontal = Input.GetAxis("Horizontal");
        float controleVertical = Input.GetAxis("Vertical");

        //velocidade de movimento
        if(movSpeedBoost == true)
        {
            transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime * 2.0f);
            transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime * 2.0f);
        }else
        {
            transform.Translate(Vector3.up * _speed * controleVertical * Time.deltaTime);
            transform.Translate(Vector3.right * _speed * controleHorizontal * Time.deltaTime);
        }

        //limita jogar até o centro da tela
        if (transform.position.y > 0)
        {
            transform.position = new Vector3(transform.position.x, 0, 0);
        }
        //limita jogar até a borda inferior
        else if (transform.position.y < -4.2f)
        {
            transform.position = new Vector3(transform.position.x, -4.2f, 0);
        }

        //teleporta jogar se sair da tela na horizontal
        else if (transform.position.x < -9.45f)
        {
            transform.position = new Vector3(9.45f, transform.position.y, 0);
        }
        else if (transform.position.x > 9.45f)
        {
            transform.position = new Vector3(-9.45f, transform.position.y, 0);
        }
    }
    //duração triple shot
    public IEnumerator TripleShotPowerDownRoutine()
    {
        yield return new WaitForSeconds(5.0f);
        canTripleShoot = false;
    }
    public void TripleShotPowerUpOn()
    {
        canTripleShoot = true;
        StartCoroutine(TripleShotPowerDownRoutine());

    }

    //duração boost de movimento
    public IEnumerator MovSpeedBoostDownRoutine()
    {
        yield return new WaitForSeconds(5.0f);
        movSpeedBoost = false;
    }
    //ativa boost de movimento e inicia contagem de duração
    public void MovSpeedBoost()
    {
        movSpeedBoost = true;
        StartCoroutine(MovSpeedBoostDownRoutine());
    }

}

Laser
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Laser : MonoBehaviour {
    [SerializeField]
    public float _speed = 10.0f;
    [SerializeField]
    public bool _laserBoost = false;
    // Use this for initialization
    void Start () {
        _laserBoost = false;

        if (_laserBoost == true)
        {
            _speed = 100f;
        }
    }

    // Update is called once per frame
    void Update () {

        //código gigante e dificil de decifrar ~irony
        transform.Translate(Vector3.up * _speed * Time.deltaTime);
        if (transform.position.y > 6f)
        {
            if(transform.parent != null)
            {
                Destroy(transform.parent.gameObject);
            }
            Destroy(gameObject);
        }

    }
    public IEnumerator LaserBoostDuration()
    {
        yield return new WaitForSeconds(10f);
        _laserBoost = false;
    }
    public void LaserBoost()
    {
        _laserBoost = true;
        StartCoroutine(LaserBoostDuration());
    }

}

Powerup
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Powerup : MonoBehaviour
{
    [SerializeField]
    private float _speed = 3.0f;
    [SerializeField]
    private int powerupID;
    [SerializeField]
    private AudioClip _clip;

    // Update is called once per frame
    void Update ()
    {
        //movimenta o powerup para baixo
        transform.Translate(Vector3.down * _speed * Time.deltaTime);
        //destroy o power ao sair da tela
        if (transform.position.y <-7)
        {
            Destroy(this.gameObject);
        }
    }
    private void OnTriggerEnter2D(Collider2D other)
    {

        if(other.tag == "Player")
        {
            //acessa o player
            Player player = other.GetComponent<Player>();

            if(player != null)
            {
                if(powerupID == 0)
                {
                    //ativa tripleshoot
                    player.TripleShotPowerUpOn();
                }
                else if(powerupID == 1)
                {
                    //ativa speedboost
                    player.MovSpeedBoost();
                }
                else if(powerupID == 2)
                {
                    //ativar shield
                    player.ShieldUp();
                }
                else if (powerupID == 3)
                {
                    Laser laser = GameObject.Find("laser").GetComponent<Laser>();
                    laser.LaserBoost();
                }

            }

            //detroy powerup
            AudioSource.PlayClipAtPoint(_clip, transform.position);
            Destroy(this.gameObject);
        }
    }
}

O erro está apontando para
laser.LaserBoost();

Comment: `GetComponent()` não está gerando um objeto, agora você tem que ver porque.
Comment: Onde é o erro?.
Comment: Perdão, faltou informação, vou editar pra ficar mais claro. Mas o erro é aqui:         NullReferenceException: Object reference not set to an instance of an object
Powerup.OnTriggerEnter2D (UnityEngine.Collider2D other) (at Assets/Galaxy Shooter/Scripts/Powerup.cs:54)
Comment: Não temos como saber qual é a linha 54.
Comment: dentro do "else if (powerupID == 3)" A linha 54 é o "laser.LaserBoost();"
Answer: ok, bora la :

Laser laser = GameObject.Find("laser").GetComponent(); // aki o seu gameObject tem o nome "lazer"  sempre??
laser.LaserBoost();//isso aki da erro se o laser estiver null, que provavelmente é o caso

possível solução:

//assim vc vai saber onde ta dando ruim, isso não mudando a estrutura do codigo!!
GameObject laserGO = GameObject.Find("laser");
if(laserGO != null){
    Laser laser = laserGO.GetComponent()

    if(laser !- null){
        laser.LaserBoost();
    }
}

///Assim seria melhor >>
no Powerup >>

    if (powerupID == 3)
{
    if(_laserRef != null)
    {
        player._laserRef.LaserBoost();
    }
}

no player >>

public Lazer _laserRef;

private void Shoot()
{
    if (Time.time > _canFire)
    {
        _audioSource.Play();
        if (canTripleShoot== true)
        {
            Instantiate(_tripleShootPrefab, transform.position, Quaternion.identity);

        }
        else
        {

            _laserRef = Instantiate(_laserPrefabs, transform.position + new Vector3(0, 0.95f, 0), Quaternion.identity);

        }
        _canFire = Time.time + _fireRate;

        }
    }
}

NullReferenceException Unity 3D


Should I find correct MySQL query or optimize database structure?

Question: I have database of following structure:

TABLE ingredients (ingredient_name, color)
TABLE recipes (recipe_name)
TABLE recipes_ingredients_parts (recipe_name, ingredient_name, parts)

What I want is to get a recipe that corresponds with selected ingredients and their number. So what I`ve tried first was query:
SELECT rr.* FROM
  (SELECT r.* FROM receipes r
    INNER JOIN receipes_ingredients_parts ri
      ON r.receipe_name = ri.receipe_name
        AND ri.ingredient_name = 'espresso'
        AND ri.parts_number = '1') rr;

And what I get are {"Americano", "Espresso"}. But that should be "Espresso" only because for "Americano" there should be the query:
SELECT rr.* FROM
 (SELECT r.* FROM receipes r
   INNER JOIN receipes_ingredients_parts ri
     ON r.receipe_name = ri.receipe_name
       AND ri.ingredient_name = 'espresso'
       AND ri.parts_number = '1') rr
   INNER JOIN receipes_ingredients_parts ri
     ON rr.receipe_name = ri.receipe_name
       AND ri.ingredient_name = 'water'
       AND ri.parts_number = '4';

Next my idea was to alter recipe table and add columns for each ingredient to store it's quantity for the recipe. But it would be near 20 columns of that kind. So I'm confused with thought that I'm doing job in a bad style. Maybe I should use some good query for the purpose? Do you guys have any ideas about all the stuff?
Comment: Adding 20 columns would not be "optimizing" your db structure. Your first query is getting any recipe that has "espresso" as an ingredient; did you want it to get recipes that have "espresso" as the only ingredient? (If so, [this](http://stackoverflow.com/questions/33562341/mysql-select-items-what-have-all-the-values) might be the answer you're looking for.)
Comment: Oh, yeah, I guess that is not quite right either; it gives you things that have all items in the list, not the things have only the items in the list.
Answer: I think this is what you are looking for, it should find receipe_names that have all the ingredients in your list, and no other ingredients.
SELECT receipe_name
, SUM(CASE
      WHEN (ingredient_name, parts_number) IN (('espresso','1'))
      THEN 1 ELSE 0
      END
) AS matchedIngredients
, SUM(CASE
      WHEN (ingredient_name, parts_number) NOT IN (('espresso','1'))
      THEN 1 ELSE 0
      END
) AS otherIngredients
FROM receipes_ingredients_parts
GROUP BY receipe_name
HAVING matchedIngredients = 1 AND otherIngredients = 0

A more generalized version/template:
SELECT aField
, SUM(CASE
      WHEN someField IN ([matchList])
      THEN 1
      ELSE 0
      END
) AS matches
, SUM(CASE
      WHEN someField NOT IN ([matchList])
      THEN 1
      ELSE 0
      END
) AS others
FROM aTable
GROUP BY aField
HAVING matches = [# of values in matchlist]
   AND others = 0

Alternatively, if items in the matchlist might be repeated in the table for an "aField" value:
SELECT aField
, COUNT(DISTINCT CASE
      WHEN someField IN ([matchList])
      THEN someField
      ELSE NULL
      END
) AS matches
, COUNT(DISTINCT CASE
      WHEN someField NOT IN ([matchList])
      THEN someField
      ELSE NULL
      END
) AS others
FROM aTable
GROUP BY aField
HAVING matches = [# of values in matchlist]
   AND others = 0

Comment: It really is. Working perfect. Thank you very much.
Comment: Super! That`s what I was thinking on (generalizing in direction towards [matchList]) for the last minutes)
Comment: @IgorChernega As a small side note, I should mention the above assumes ingredient-part combinations are only once per receipe.
Comment: Or that's ok. This is for php query() purpose. And I'm going to POST valid data also in that meaning to the script. Anyway if needed I suppose one can extrapolate the idea you shared. Thx again for the help)


Is $A^TBA$ positive definite if and only if $A$ is nonsingular and $B$ is positive definite

Question: I hope I'm not repeating a question, but I couldn't find one like this.
Is this a valid proof? It seems straight forward. If its not, where did I go wrong and do you have any suggestions?
Proof:
Firstly, define: $A,B\in\mathbb{R}^{n \times n}$ and $x,y\in\mathbb{R}^n$
(If) Suppose $B$ is positive definite and A is nonsingular. By definition for a vector $y\neq0$, $y^TBy>0$. Let $y = Ax$. Since $A$ is nonsingular, for all $y\neq0$, $x\neq0$. Thus $x^TA^TBAx>0$. Thus $A^TBA$ is positive definite.
(Only if) Suppose $A^TBA$ is positive definite. Then for all vectors $x\neq0$, $x^TA^TBAx>0$. Let $y= Ax$. Then $y^TBy>0$ must also hold.  If $A$ is singular, then for $x\neq0$, $y=Ax=0$. Then $x^TA^TBAx=0$ for some $x\neq0$. Thus $A$ must be nonsingular and $B$ positive definite.
Thanks for checking
Comment: You have verified that $y^{T}By>0$ only for $y$ in the range of $A$. Use the fact that $Ax=0$ implies $A{T}BAx=0$ which implies that $x=0$. Now you know that $A$ is non-singular and hence its range is all of $\mathbb R^{n}$.
Comment: If $A$ is singular, then there may exist some $x$, for which $Ax=O$. So, non-singularity is essential condition.
Comment: Fixed (I think). The Only If part is now by contradiction.
Answer: Here is my solution for a more complete Theorem:
Theorem:
For $A,B\in\mathbb{R}^{n\times n}$ and $x,y\in\mathbb{R}^n$, $A^TBA$ is positive (negative) definite if and only if $A$ is nonsingular and $B$ is positive (negative) definite.
Proof:
($\Rightarrow$) Suppose $A$ is nonsingular and $B$ is positive (negative) definite. By definition for all $y\neq0$, $y^TBy>0$ ($y^TBy<0$). Let $y=Ax$. Since $A$ is nonsingular, for all $y\neq0$, we have $x\neq0$. Thus $x^TA^TBAx>0$ ($x^TA^TBAx<0$), so $A^TBA$ is positive (negative) definite.
($\Leftarrow$) Suppose $A^TBA$ is positive (negative) definite. Then for all $x\neq0$, $x^TA^TBAx>0$ ($x^TA^TBAx<0$). Fistly, assume $A$ is nonsingular. Then for all $x\neq0$, $y=Ax\neq0$ and so $x^TA^TBAx = y^TBy >0$ ($x^TA^TBAx = y^TBy <0$). Hence $B$ is positive (negative) definite. Proceed by contradiction. Assume $A$ is singular. Then there exists a $x\neq0$ such that $y=Ax=0$. Thus we have $x\neq0$ for which $x^TA^TBAx=0$, and so we have a contradiction. Therefore, $A$ must be nonsingular and $B$ must be positive (negative) definite.
This may be extended to positive (negative) semidefinite $B\Leftrightarrow $ positive (negative) semidefinite $A^TBA$  if $A$ can also be singular, since we will have $x^TA^TBAx=0$ in the null space of $A$ (ie: $y=Ax = 0$ for $x\neq0$).
Comment: I found a similar result in  Horn and Johnson "Matrix Analysis", (2nd Edition), Observation 7.1.8.


Create a setting.*.php file for every stage of the website

Question: I understand that my question could be opition-based and that it depends on the comfort of every drupal developer so please do not flag it as so !
For every Drupal 8 website i start, i use the below steps from creating/installing the website to configure it to be used in two stages (Dev & Prod)
On my Local server:
On my Windows 10, i have installed Git, Composer and Drush.
Step 1:
I download drupal 8 and its dependencies using the famous command:
Composer create-project...

Step 2:
I point Acuia Dev Desktop to my new Drupal 8 composer website by choosing the import local drupa site option with below:

select the /web folder
create a new database

Step 3:
I launch my drupal 8 composer website using acquia dev desktop and go through the default drupal 8 installer.
Step 4:
I copy default.settings.local.php from sites folder and I paste it into site/default folder and then rename it to settings.dev.php
Step 5:
I go to the include file (loc_sitename_dd.inc) created by default by Acquia Dev desktop to store the database credentials and other specific configurations and I copy all its contents to settings.dev.php file.
Step 6:
I go to settings.php file and:

Delete the code within in the  tag created by Acquia dev desktop at the bottom of the file.
Add the below lines to the bottom of the file to activate two files settings.dev.php and settings.prod.php
if (file_exists(DIR . '/settings.dev.php')) {
  include DIR . '/settings.dev.php';
}
if (file_exists(DIR . '/settings.prod.php')) {
  include DIR . '/settings.prod.php';
}

Step 7
I go to the .gitignore file located one folder above the web folder (../sitename) and:

Remove the line mentioning the settings.php file so it will NOT be ignored.
Add the settings.dev.php file to be ignored.

Finally
The settings.dev.php file will have configuration such as:

Site name.
Database credentials/configuration.
Disable Caches.
Enable rebuild.php
and many more which are specific only to my LOCAL HOST (Dev website)

and will only be available on my Local Server.
On my Web server
Step 1
I create a the Production Database with a permissions granted user.
Step 2
I upload only one time the settings.dev.php file to my web server and I rename it to settings.prod.php
Step 3
I edit the *settings.prod.php** file and:

Change the Site name
Change the database credentials.
Enable caches.
and many more configurations related only to the production (online) website.

Step 4
I go to the .gitignore file located one folder above the web folder (../sitename) and:

Remove the line mentioning the settings.php file so it will NOT be ignored.
Add the settings.prod.php file to be ignored.

Finally
The settings.prod.php will only be available on my production (online) website.
After all of the above, I start developing my website and push every changes to/from Webserver/Localhost.
Does what i am doing is right/correct ?
Maybe it is not the best method but i would like to ask the experts in this subject about their opinion on my method ?!
Thank you,
Comment: How attached are you to DevDesktop? I really enjoyed it for Drupal 7 sites, but I've  moved away from it for Drupal 8 sites (in favor of Lando). Even on phone calls with Acquia, they didn't seem to recommend it anymore.
Comment: I am not completely attached to DevDesktop but I prefer it compared to MAMP or XAMP because it much easier in install, setup and I really had no problems/errors with it at all ! I just heard about Lando from you so i will give it a shot ! Why not ?!
Answer: Im not sure what's the goal you're trying to achieve with all of those steps? The normal process is for the settings.php not to be in your git repo and then you manually upload the settings.php file to each environment and change the database/other configs in the file. It sounds like you're doing all of these steps to get the settings.php file into git, but whats the benefit?
For example you mention about having caching disabled on your dev server. To achieve this you can uncomment very last few lines in settings.php that says to use a settings.local.php file (Which along with the development.services.yml will disable caches and enable rebuild) Those lines can be uncommented on both dev and prod versions of your settings.php and you just dont upload the settings.local.php to your prod server (It would be ignored by the standard .gitignore that comes with drupal)
Comment: _The normal process is for the settings.php not to be in your git repo_ That's the opposite of what my normal process is. If you're on one of the usual suspects for hosting (Acquia/Pantheon), that's also how they expect you to do it too
Comment: I suppose "normal" is a relative term to each person. What I mean is the default/recommended drupal process
Comment: Any chance you have a reference for that? I've been working with Drupal for about 8 years and I haven't seen that advice before! I would imagine if that was a recommended approach settings.php would be excluded via the default .gitignore, but I'm quite sure it isn't
Comment: There's many ways of doing it really. If you have server control to set the config file outside of project root, go for it. If not, you have to commit it so it gets up there. Acquia provides an include path that goes in settings.php which pulls in connection info, so it must be committed for it to function.
Comment: @Clive, download drupal from https://www.drupal.org/download and you'll see the example.gitignore has sites/*/settings*.php and sites/*/services*.yml
Comment: @Leigh Mason the reason to put my **settings.php** in my git repo is that the settings.php file will hold all configuration which are common to all stages and so if for any reason in the futur I updated/added/removed any configuration from the settings.php file i won't have to remember to update the same configuration in all other stages because **git** will take care of the changes.
Comment: @ElieMasaad And that's a perfectly reasonable approach, if it fits your needs. That's the point - there isn't a right or wrong answer, as long as your process is validated in and of itself, and does what you need it to, then it's correct
Comment: @LeighMason Funny, I must never have looked in that file before. I'm not sure I agree with it as a recommendation, but as I mentioned to Elie, that's kind of the point of something like this - no right or wrong
Comment: Also it is worth mentioning that it is not advisable to add settings.php to the git repo only for the reason that such file might include sensitive information like DB credentials but in my case, the DB Credentials are located in settings.*.dev file so it will be totally safe to add settings.php to the git repo.
Comment: @kevin As i mentioned in my question, i deleted the include path added by Acquia Dev Desktop and copy all the include file contents into the settings.*.php and i am doing so because with the include path in the settings.php, drush does not find a connection to the database when used from a Git Bash. (So i had to create the database connection directly into the settings.*.php to help drush connect to the database with no errors.)
Comment: This isn't a problem, I can use drush just fine with settings connections being included to the file without literally being in the file itself. Otherwise Drush wouldn't work on setups like Acquia. So that must be something else.
Comment: @Kevin i have tried many solution when drush was throwing me an error similar to this: **the command xxx cannot be executed, drush was unable to execute a query to the database, no connection was found** the only workaround is to have the database credential inside **settings.php** or **settings.*.php** that solved my problem
Comment: It is worth mentioning that inside the include file, there was a setup for the **$settings['hash_salt']** by also Drush was unable to locate them by throwing the error **Missing $settings['hash_salt'] in settings.php**, once i copied all codes from the include file to the *settings.local.php** file and activate it, all errors gone and Drush is working perfectly.... Note: i am using Drush from Git Bash and not from the ugly built-in command line tool provided by Aqcuia desktop
Answer: I don't see anything wrong about this. Do whatever fits your needs. I do it somehow similar in my multi-site setups:
I have one global settings.php file that's the same across all multi-site instances (I version track this one). Then every instance has its own settings.site.php (I version track this one as well). And last but not least every instance has its own settings.local.php (that's the only one that's ignored by Git as it holds sensitive and environment-specific information). Both of the latter are included by the global settings.php:
/**
 * Load site-specific override configuration, if available.
 */
if (file_exists($app_root . '/' . $site_path . '/settings.site.php')) {
  include $app_root . '/' . $site_path . '/settings.site.php';
}

/**
 * Load local development override configuration, if available.
 */
if (file_exists($app_root . '/' . $site_path . '/settings.local.php')) {
  include $app_root . '/' . $site_path . '/settings.local.php';
}

I also make heavy use of the ScriptHandler.php that's included into drupal-composer/drupal-project. I edited it so it iterates through all multi-site instances and creates a copy of my global settings.php in its createRequiredFiles() function. And stuff like that. Pretty handy.


Error when running database update: "DatabaseSchemaObjectExistsException: Cannot add field redirect.status: field already exists."

Question: I'm getting the following error when attempting to run a database update:
<code>Update #7101
Failed: DatabaseSchemaObjectExistsException: Cannot add field redirect.status:
field already exists. in DatabaseSchema_mysql->addField()
(line 336 of /var/www/sitename/drupal/web/includes/database/mysql/schema.inc).
</code>
It looks like the database update it do to some redirects I added. How do I go about solving this?
Answer: Most probably you are on Redirect 7.x-1.0-rc3 which was released back on 8 July 2015. It has been fixed on https://www.drupal.org/project/redirect/issues/2541304, so just update your Redirect module to 7.x-1.x-dev.
Comment: That solved it. I didn't even think about it, because I had the latest recommended release.


Prove that $Fonk(I,G)$ is a group under $*$

Question:
Let $I$ be any set and $G$ be a group. Let $Fonk(I,G)$ be set of functions from $I$ to $G.$ Let $e$ be identity element of $G$. If $f,g\in Fonk(I,G)$ then, for $i\in I$
$$(f*g)(i)=f(i)*g(i).$$
Prove that $Fonk(I,G)$ is a group under $*$.

My Proof-trying. Let $f,g,h\in Fonk(I,G).$ Then
$G1.$ $((f*g)(i))*h(i)=f(i)*g(i)*h(i)$ and similarly $f(i)*((g(i)*h(i))=f(i)*g(i)*h(i).$
$G2$. $(f*e)(i)=f(i)*e(i)=f(i)$ because $f(i)\in G$ and $e$ is identity element of $G$ and similarly $(e*f)(i)=e(i)*f(i)=f(i).$
$G3.$ Let $f^{-1}$ be inverse element of $f$ in $G$. Then $(f*f^{-1})(i)=f(i)*f^{-1}(i)=e$ because $f(i),f^{-1}(i)\in G$ and $f^{-1}$ is inverse element of $f$.
Can you check my answer? Thanks...
Answer: Requires the definition of the inverse of such a function $f$:
$g(i) = f(i)^{-1}$ for all $i\in I$.
Then $g$ is the inverse of $f$, written $g=f^{-1}$ as its unique.


Testability versus Over-Design?

Question: Here is the situation actually posed by a co-worker that pegged my interest:
public DoSomething()
{
    //Do Stuff
    var assembly = Assembly.LoadFrom("Path");
    //Do More Stuff
}

So, in order to mock this you have two options
Create an internal virtual method:
internal virtual IAssembly LoadAssembly(String path){...Load Here...}

Or, add a new class that can be passed in
public class AssemblyLoader
{
    public virtual IAssembly LoadAssembly(String path){...Load here...}
}

Both options seem to be a problem as the first seems that it should be a private method, and the second seems to be an over-design of creating a wrapper for a simple static call?
So, I thought I would take it to the community. I am looking for the most pragmatic approach, while remaining unit-testable.
This is similar to this SO question, however I would like to dig deeper into it really.
Comment: @AlG, using Assembly.LoadFrom *as an example* does not make this a duplicate of a question *that was actually trying to deal with Assembly.LoadFrom.*
Comment: @JustinPihony, you could probably do some searches over at [Programmers.SE](http://programmers.stackexchange.com), as I believe there have been a few similar topics over there with a diverse range of opinions. I, for one, would go for dependency injection. You know the [adapted] adage, "all problems in computer science can be solved by another level of abstraction... except for the problem of too many layers of abstraction."
Comment: Couldn't you implement *Dependency Injection*? If you structure it in that manner it will remain both Testable and Maintainable.  Though it will be slightly hard to read.
Comment: The better question is, how much logic are you putting in your constructor? If you need to unit test your constructor it sounds more like a code smell to me.
Comment: Voting for the second option. It does create overhead, but it isn't huge, and it serves a "greater purpose". It's clean and comprehensible, and with an auto-registered DI container, you don't even have to care about it any further outside of unit testing.
Comment: @AlG If you read the full question, I even mention this question and feel that this is not a duplicate. I am asking for a deeper answer.
Comment: @Greg The second option is using Dependency Injection
Comment: Adding the word deeper doesn't make it a new question.
Comment: @JustinPihony I didn't read that far, my apologies for quick commenting.
Answer: The question is too general, so it's hard to answer.
To speak generally, I think your problem is artificial. You posit that creating a wrapper for a 3rd party service is over-design, but at the same time say this wrapper is a solution to a real problem. If it solves a real problem, that doesn't sound like over-design, a wrapper actually sounds like good design.
Creating wrappers for 3rd party services is often smart when you need configure state on code you don't control. It doesn't smell as bad as you think. In fact, I don't see another way to do this. No matter how you slice it, whether you're mocking with some 3rd party library, using some reflection magic, or using your purposed solutions, it all boils down to wrapping the real 3rd party api.
If your gut still says wrapping this external api is over-design, maybe you need to re-frame your question. Ask yourself, Should this code be tested?
Comment: Yah, I agree. I guess the problem comes from the fact that normally I would not mock a static method. However, this method has external dependencies on the file system. The real problem to me is that this probably should have been an instance object to begin with, and that is the problem...I have to wrap something for the sake of testability and that is why I don't like it. It is changing my code only for the sake of testability, but that is only due to bad design by the 3rd party....
Comment: @JustinPihony "but that is only due to bad design by the 3rd party". Yup, that's exactly the thing you want to abstract yourself from. Changing code for the sake of test-ability is _not_ a bad thing. If you care about testing, changing code to support it is just making your code "more right" given your requirements.
Answer: It's hard to make a generalization here, but the comments before and after loading the assembly(s) suggest that the DoSomething method may be violating the Single Responsibility Principle. That is, the code does too many things. There are a number of ways to write the code such that you'll avoid this, and you mention two of them in your question. I think I'd follow Greg's advice and implement Dependency Injection here. It's difficult for me to say what is and isn't overdesign based on this example.

Testability versus Over-Design?


Poisson normal approximation for comparing means of count data

Question: I'm trying to compare the values of two counts from an A/B test, $c_1$ and $c_2$.
If I assume the data is Poisson distributed then the mean and variance are $\lambda$ and the standard error is $\frac {\lambda}{n}$.  Since we only have one observation for each count the means and SE are just $c_1$ and $c_2$ for each.  If $\lambda$ is sufficiently large, I can assume that the Poisson distribution approximates a normal distribution.  I'm therefore creating a test statistic which is $\frac{c2-c1}{\sqrt{c1+c2}}$, and comparing this to 1.96 to check the significance of the difference.
Is this a valid procedure?
Comment: This sounds reasonable so long as lambda is large enough for the approximation to be good.  A quick simulation in R shows that the test has the appropriate false positive rate.
Answer: The generally accepted way of comparing 2 samples from Poisson distributions, to see if they have the same mean, is to note that the sum of 2 Poisson random variables $X_1$ and $X_2$ with means $\lambda_1$ and $\lambda_2$ is Poisson with mean $\lambda_1 + \lambda_2$; and the conditional distribution of $X_1$ given $X_1 + X_2 = n$ is $Binomial(n, \lambda_1 / (\lambda_1 + \lambda_2))$.
So you would compute the probability of observing $X_2 = c_2$ under that.
See http://www.biostat.jhsph.edu/~bcaffo/651_2006/files/lecture27.pdf


Find the parameterization of shadow cast on plane

Question:
Suppose there is a light source at $(0, 0, 8)$. Consider the line segment $r(t) = \langle 3-3t, 1+t, 2+2t\rangle, 0\le t\le1$. Find the shadow cast by the line segment on the plane $x+y-2z=8$

I have never encountered this type of problem before, but nevertheless I gave it a try. I would imagine that we would first find the plane that the point's shadow draws. This seems to be the plane passing through $(3, 1, 2)$, $(0, 2, 4)$, and $(0, 0, 8)$. This gives me the plane equation $4x+6y+3z=24$.
The intersection of the two planes is $(x, y, z) = (13t+16, -11t-8, t)$
But now I don't know how to account for the line segment's ends.
How would I continue, and is there a better method?
Thanks
Comment: For endpoints, find where the lines through light source and each end of the segment meet the plane (or the line you found, which is a bit more work). Come to think of it, find those two points in the first place then create your line segment on the plane from there.
Answer: Based on the comment, we can do as follows.
Since the line segment ends at $(3, 1, 2)$ and $(0, 2, 4)$, we can construct two lines from the light source, which will be the edges of our "shadow".
These, namely, are
$$\text{line1}(t) = \langle 3t, t, 8-6t \rangle$$
$$\text{line2}(t) = \langle 0, 2t, 8-4t \rangle$$
We solve for the intersection of the plane by substituting the entire line into the plane equation and solving for $t$, which give us $t=\frac32\Longleftrightarrow (\frac92, \frac32, -1)$ for line $1$ and $t=\frac{12}5 \Longleftrightarrow (0, \frac{24}5, -\frac85)$ for line $2$.
Parameterizing this gives
$$\text{shadow}(t) = \left\langle \frac92 - \frac92 t, \frac32 + \frac{33}{10} t, -1-\frac35 t\right\rangle$$
for $0<= t<= 1$
Comment: [+1] But you should give names in order **one follows in a better way** your (good and direct) proof :  $A,B$ for the endpoints of initial line segment and $A',B'$ for the image of this line segment by the central projection. Besides, it should also be said that the image of a line segment [A,B] by a central projection f is $[f(A),f(B)]$.
Comment: @JeanMarie Thanks for the feedback. I'll keep this in mind for the future :)


What does $f$ continue on $\mathbb S^1$ mean?

Question: Let $\mathbb S^1:=\mathbb R/\mathbb Z$. What does $f$ continuous on $\mathbb S^1$ mean ? That it's continuous over $[0,1)$ or $[0,1]$ ? I would say $[0,1)$ but I have doubt since we sometimes take the norm $\|f\|_{L^\infty }$ and if $\lim_{x\to 1}f(x)$ doesn't exist, the norm $l^\infty $ wouldn't be defined. By the way, sometimes we prolonge $f$ to $\mathbb R$ by $1-$periodicity, and thus, $f$ must be continuous on each point of $\mathbb Z$, which is often not the case. What do you think ?
Comment: $S^1$ is a manifold, and continuity is a local property.
Comment: @anomaly: I'm sorry, I don't know what is a manifold. Is it $[0,1)$ or $[0,1]$ ?
Comment: $S^1$ is not an interval. It inherits the metric from $\mathbb{R}$, and that defines continuity on it.
Answer: You need to think of $\mathbb{S}^1$ as a topological space, and use the definition of continuous maps from topology.
Using the formula $\mathbb{S}^1 = \mathbb{R} / \mathbb{Z}$ you can use the quotient topology on $\mathbb{S}^1$. In this case you would have to prove that the periodic function on $\mathbb{R}$ that you get from $f$ is a continuous function on $\mathbb{R}$.
Alternatively, you could use the formula $\mathbb{S}^1 = \{(x,y) \in \mathbb{R}^2 \,\bigm|\, x^2 + y^2 = 1\}$ and use the subspace topology on $\mathbb{R}^1$ relative to $\mathbb{R}^2$.
There is a third option, where you can think of $\mathbb{S}^1$ as the quotient space obtained from the interval $[0,1]$ by identifying the points $0$ and $1$ to a single point. In this case a continuous function on $\mathbb{S}^1$ is the same as a continuous function on $[0,1]$ whose values at $0$ and at $1$ are equal to each other.
Comment: It is neither $[0,1)$ nor $[0,1]$. It is $\mathbb{S}^1$.
Comment: The first function, extended by 1-periodicity, is indeed a function on the circle...but not a *continuous* function. Same for the second one. But if you took $h(x) = \tan(\pi x)$, then you'd have a function on $S^1$ that's actually continuous on $S^1$.
Comment: so is it $[0,1)$ or $[0,1]$ ?
Comment: But, when we write $\int_{S^1}f$, we write $\int_0^1 f$, is it false ? And on this space, $L^\infty $ norm is always well defined ?
Comment: I added another paragraph to address your question.
Comment: Just to be sure, the function f(x)=x on $[0,1)$ extend on all $\mathbb R$ by $1-$ periodicity is not a function on the circle, is it? And what about $f(x)=\tan(\frac{\pi}{2}x)$ on $[0,1)$ extend by $1-$periodicity ?
Answer: Since $f$ is defined on $\mathbb R / \mathbb Z$, you can think of a new function $g$ defined on all of $\mathbb R$ via $f$: simply define $g(x)$ to be $f(t)$, where $t$ is the fractional part of $x$.
Now we say that $f$ is continuous if this "lift" $g$ is a continuous function from the reals to the reals (and do the same for "differentiable", etc.)
Comment: So is it $[0,1)$ or $[0,1]$ ?
Comment: @MathBeginner Try $(-\epsilon, 1)$ instead
Comment: To be honest, an element of $\mathbb R / \mathbb Z$ is a set of the form $\{r + n \mid n \in \mathbb Z\}$, called a "coset." Each such set contains a single element $x$ with $0 \le x < 1$; it also contains a single element $u$ with $0 < u \le 1$. So either $x$ or $u$ will serve as an identifier for the coset. For the coset whose $x$ value is $0$, the $u$-value is 1. I personally tend to favor the "x" definition: for a given element $r \in \mathbb R$, the associated $x$ value is $x = floor(r)$. And I'm saying to define $g(x) = f( C)$, where $C_x$ is the (unique) coset containing $x$.


Aggregate multiple upstream SCM changes in downstream job

Question: On my current project, I have several dozen "sub-projects", each with trunk and branches (legacy setup, can't change it)
There are multiple commits on a branch, let's say 5, and then a branch is reintegrated to trunk. When a branch is reintegrated to trunk, it triggers trunk build as a downstream job.
I need this downstream trunk build to show all upstream SCM changes since last reintegration
I've used Display Upstream Changes plugin, however that only displays the last upstream commit in corresponding trunk build.
I've also used All Changes plugin. It does allow me to see "aggregate" list of upstream commits (either by date, promotion or number), but I cannot post these to downstream job.
Note: using SVN for SCM
Alternatively
Alternatively, if there is a way to include "merged revisions" in the SCM changelist, that would solve my issue as well
Comment: Hi @slav, would appreciate if you could accept my answer.
Answer: Jenkins naturally shows changes on a job.
A downstream job is linked only in a workflow sense.  Do Job B after Job A.  Linking two jobs in this way does not extend to showing changes.
Option 1
MultiJob Plugin
Option 2
You could get the list of changes in job A using groovy like this and pass it to Job B as a parameter to do something with. (Like print out to an HTML file and publish to the dashboard of Job B with the HTMLPublisher plugin).
Comment: I've looked at both of your suggestions. The problem is I need Job A's changes from build- to build-. That Option 2 example only does it for 1 build (not a range). Unfortunately I cannot wrap my head around groovy (and/or what methods it exposes in jenkins and in what data structure formats), so I cannot extrapolate from that to reach what I need.
Comment: From a shared library you can execute custom code and if you import relevant Jenkins Object Model classes into your library you can loop through the range of builds you are interested in and collect this information and return it to your Pipeline from there you do what you want with the information.


adding extra tab to user's profile using hook

Question: I am trying to add a Send email tab to all user's profile using hook_menu(). However, it's not working. My custom module name is page_callback_test and here's the code in it.
function page_callback_test_menu() {
$items['/user/%user/email_user'] = array(
    'title' => t('Send email'),
    'page callback' => '_send_email_touser',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_LOCAL_TASK,
    );

return $items;

}
function _send_email_touser(){
    return t("let's send email to this user");
}

Answer: Your code works - just remove the first forward-slash from the URL you are passing to hook_menu().
Correct: $items['user/%user/email_user'] = array(
Not correct: $items['/user/%user/email_user'] = array(
Be sure to clean cache after you update this.


How to generate integer sequence with macro only?

Question: As we know, c++ has std::make_integer_sequence, which can be used to generate integer sequence: std::make_index_sequence<size_t, N> => (0, ..., N-1).
I hope to have a macro MAKE_INTEGER_SEQUENCE(N) and MAKE_INTEGER_SEQUENCE(3) will return (0)(1)(2)
How can we implement it with macro only? boost.preprocesser solution also welcome!
I have tried BOOST_PP_SEQ_FOR_EACH_I(macro, data, seq) with macro(r, data, i, elem) (i)

This macro is a repetition construct.  If seq is (a)(b)(c), it expands to the sequence:
  macro(r, data, 0, a) macro(r, data, 1, b) macro(r, data, 2, c)

But I have to provide a N-elems seq(like (a)(b)(c) above), which is pretty redundant for this feature.
The reason why I hope it to be a macro is I need such sequenses to generate multiple lines codes, like:
        ...... //primiary template above, specialize below, codes are from libcxx: https://github.com/llvm-mirror/libcxx/blob/master/include/__tuple#L130
        template<>
        struct parity<0>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type>
            {};
        };
        template<>
        struct parity<1>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type, Tp - 1>
            {};
        };
        template<>
        struct parity<2>
        {
            template<size_t Tp>
            struct pmake : repeat<typename make<Tp / 8>::type, Tp - 2, Tp - 1>
            {};
        };
        template<>
        struct parity<3>
        {
            template<size_t Tp>
            struct pmake
                : repeat<typename make<Tp / 8>::type, Tp - 3, Tp - 2, Tp - 1>
            {};
        };
....

so, macro is the only choice here
Comment: *macro is the only choice here* --> Quite the opposite, this is some standard task for template, you just need some decent metaprogramming library, you can also write your own tools for those routines. [A simple solution with `boost::hana`](https://wandbox.org/permlink/i8FjtxALRPedmBYo).
Comment: Have you upgraded to C++17?
Comment: @TedLyngmo c++17/20 features are also welcome. But, iirc, the new features do nothing with macro.
Comment: Perhaps not, but ... is the macro solution (whatever it may be) the superior one?
What is the situation you are in to want this?
Comment: IMO, this is a superior one here. Because I have to much similar codes rely on sequences, what I paste above is just a small part of them.
Comment: Now I don't understand the question at all - I am just curious.
Comment: While I gave a PP answer, I'm not convinced that the question requires it. The code sample you show doesn't compile and uses the same name for the struct type, so it's hard to tell. If your goal is to produce something like `foo<0, 1, 2, ...>`, that can be done without macros.
Comment: OP: What's the purpose of this? The macro constraint feels strange.
Comment: @liliscent Thanks, man! hana is pretty awesome! I never image meta template programming can do such thing. I'll dig it into later!
Answer: You can do this easily with BOOST_PP_REPEAT (live example):
#include <boost/preprocessor.hpp>

#define TO_SEQ_ELEM(z, n, data) (n)
#define MAKE_INTEGER_SEQUENCE(n) BOOST_PP_REPEAT(n, TO_SEQ_ELEM, )

MAKE_INTEGER_SEQUENCE(10) // (0) (1) (2) (3) (4) (5) (6) (7) (8) (9)

Do take note that there is a repetition limit, BOOST_PP_LIMIT_REPEAT, which was 256 when I tested it, so this is the maximum possible value for n.


R Durbin Watson Test for a list of lm objects

Question: I have a list with two (or more) lm objects. Now I want to execute a Durbin-Watson test either with dwtest or durbinWatsonTest from lmtest or car respectively on both lm objects at once, ie. I would like to do
dwtest(reg_objects)
durbinWatsonTest(reg_objects)

When I do this, I get the following: using dwtest: values are NA. Using durbinWatsonTest:
Error in durbinWatsonTest.default(reg_1y$call) :
requires vector of residuals

To facilitate the idea, I have generated a list object of 5 lm objects:
#  non-sensical lm!
set.seed(123)
y <- 1 + rnorm(10)

#  this makes a list of 5 lm's using the response data 'y'
data <- replicate( 5 , lm(  y ~ 1 + rnorm(10) ) , simpl = FALSE )

Can you help me with this issue?
Andreas
Edit: same question for bgtest, bptest and sctest. Note: sctest is from strucchange.
Comment: well both take one model at a time, so you'd have to write some kind of loop: `lapply(1:5, function(x) car::dwt(eval(data[[x]]$call)))`
Comment: so `reg_objects` is a list of models? did you read the help pages to those functions or at least look at the examples?
Comment: Sure I did and I also tried, see above error messages. Interestingly, I could not find any example in any of the cases for more than one regression object in one go. So I believe this is a fairly interesting general question.
Answer: Try this:
my_dw_stat <- list()

for(dw in seq(data)) {

  my_dw_stat[[dw]] <- dwtest(data[[dw]]$model[, 1] ~ data[[dw]]$model[, 2])

}


Algorithm for checking if an Array with n-elements is a minimum heap

Question: I'm trying to outline an algorithm to determine if my array is a minimum heap. Is there any documentation out there that could help me with this? I found a function for it on Apache's website, but it doesn't show exactly how the function works; just that there exists a function (BinaryHeap(boolean isMinHeap)).
Answer: The Wikipedia article should help you.
Here are some questions to get you thinking about the solution:

What must be true about the root of a heap, assuming the heap is a min heap?
If the root of the heap satisfies the min heap property, how do you ensure that the subtrees of the root also hold the property?
What if the root of the tree has no children?  Is it a min heap?
Answer: I think this will work !
bool checkminheap(int arr[],root)
{
     if(root>=sizeof(arr)/sizeof(arr[0])-1)
         return 1;
     if(arr[root]>arr[2*root] || arr[root]>arr[2*root+1])  //check root is the smallest element
      return 0;
    if(!checkminheap(arr,2*root))//check leftsubtree
      return 0;
    if(!checkminheap(arr,2*root+1))//check rightsubtree
      return 0;

     return 1;
}

Answer: Adding a verbose solution with java generics support, it is relatively easier to follow.
public static <T extends Comparable<T>> boolean isMinHeap(T arr[], int rootIndex) {
  boolean isMaxH = true;
  int lChild = 2 * rootIndex + 1;
  int rChild = 2 * rootIndex + 2;

  // Nothing to compare here, as lChild itself is larger then arr length.
  if (lChild >= arr.length) {
    return true;
  }

  if (arr[rootIndex].compareTo(arr[lChild]) > 0) {
    return false;
  } else {
    isMaxH = isMaxH && isMinHeap(arr, lChild);
  }

  // rChild comparison not needed, return the current state of this root.
  if (rChild >= arr.length) {
    return isMaxH;
  }

  if (arr[rootIndex].compareTo(arr[rChild]) > 0) {
    return false;
  } else {
    isMaxH = isMaxH && isMinHeap(arr, rChild);
  }

  return isMaxH;
}


How do we know that Loader is bigger or grows faster than TREE or SSCG?

Question: From what I have gathered online about these numbers, they say that Loader's Number is larger than TREE(3) or SSCG(3) or similar. The reasoning I have seen goes is that Loader's Number is the largest computable number and TREE(3) and SSCG(3) are ostensibly computable numbers. But how do we know that:

Loader's Number is larger than TREE(3) or SSCG(3) (to which we have only a weak lower bound of 187196 nested Ackermann functions) assuming they are computable?
TREE(3) or SSCG(3) are computable in the first place? As far as I can tell these are just the longest potential game one could play given a certain number of node colors or maximum nodes. How do we know that these are computable functions? How could we solve the numbers besides brute forcing every possible game which would make them noncomputable functions?
Comment: @JeanMarie I added some wiki links.
Comment: There is a similar problem with the Busy Beaver function, where there is no way to brute-force all the n-state Turing machines even though there are comparatively few of them, because you'd have to throw out the non-halting ones in advance before trying to find their halting time - but that would require knowing whether a Turing machine halts in advance.
Comment: "Loader's number, TREE, SSCG, ..." : don't you think you could at least give some references for poor beotians like me ?
Comment: Since all games must be of length at most TREE(3), and there are finitely many three-colored trees of a given node count, there are finitely many games. This makes algorithmic brute force possible and not noncomputable
Comment: @C7X But then why is Rayo's number considered noncomputable? You can brute force every possible combination of 1 googol first order set theory symbols and see which ones give the biggest result.
Comment: @user16217248 There is a computable predicate for checking if a TREE game is valid, but Rayo's function isn't computable because the [Entscheidungsproblem](https://en.wikipedia.org/wiki/Entscheidungsproblem#Negative_answer) has a negative answer: there is no computable predicate for determining if a given first-order formula is true. In particular there is no algorithm to determine if "φ defines the number N" is true, nor is there a way to throw out the φ that don't define any natural number because that would require deciding "φ defines a natural number at all".
Answer: More or less, the reasoning is that all both $\mathrm{TREE}(3)$ and $\mathrm{SSCG}(3)$ are about finite objects, thus you can enumerate all these objects.
For $\mathrm{TREE}(3)$, you can test all possible sequences of length $n$ for the desired property, and if such a sequence exists, determine that $\mathrm{TREE}(3) \ge n$. This makes them computable. Since the calculus of constructions is quite strong, the tree theorem (hopefully, I doubt anyone has checked) holds within it, and thus the $\mathrm{TREE}$ function is definable within, say, $10^9$ symbols. Since Loader's number is defined to be the largest one definable in the calculus of constructions in so-and-so ($> 10^9$) many symbols, so is $\mathrm{TREE}(3)$ and more generally, $\mathrm{TREE}(n)$ for some very large $n$.


What is the meaning of the notation $cf(add(\mathcal I))$?

Question: I am trying to prover the following claim:
Assume that $\mathcal I$ is an ideal over some infinite set $X$. Then, $cf(add(\mathcal I))=add(\mathcal I)$.
Doe anyone know what is the meaning of the notation $cf(add(\mathcal I))$?
For a set $A$, what is $cf(A)$?
Thank you!
Comment: If I recall correctly, $\operatorname{add}(\mathcal I)$ is a cardinal, not just any set.
Answer: The additivity of an ideal $\def\I{\mathcal I}$, is the smallest cardinal $\kappa$ such that there are $\kappa$ elements $\left<A_i\mid i < \kappa\right>$, $A_i \in \I$ of $I$ with $\bigcup_{i<\kappa} A_i \not\in \I$.
The cofinality of an cardinal $\kappa$ is the smallest cardinal of a cofinal set in $\kappa$, that is the smallest $\lambda$, such set there are $\left<\alpha_i \in \kappa \mid i < \lambda\right>$ with $\sup_{i<\lambda} \alpha_i = \kappa$.
A cardinal is called regular, if ${\rm cf}(\kappa) = \kappa$, so you have to prove that the additivity of an ideal is always a regular cardinal.


Relacionamento belongsTo

Question: Gostaria de saber se é possível fazer este tipo de relacionamento na Model do cakephp, se é possível, me mostrem como, pois não estou conseguindo.
Maneira que eu preciso:
<code>    public $belongsTo = array(
         Status => array(
            'className' => 'Status',
            'foreignKey' => 'status_id_origem', 'status_id_destino',
            'dependent' => false,
         ),
    );
</code>
Maneira normal:
<code>    public $belongsTo = array(
         Status => array(
            'className' => 'Status',
            'foreignKey' => 'status_id_origem',
            'dependent' => false,
         ),
    );
</code>
Especificando melhor o que eu preciso:
executo a seguinte query:
<code>    SELECT Historico.*, Status.descricao
       FROM historicos as Historico
             LEFT JOIN statuses as Status
                     ON (Status.id = Historico.status_id_origem)
</code>
Logo essa query me retorna o seguinte:
<code>     id integer|status_id_origem integer|status_id_destino integer|descricao
     ----------|------------------------|-------------------------|---------
          44   |        1               | 2                       | Aguardando embarque
          43   |        1               | 2                       | Aguardando embarque
</code>
Mas o que eu realmente preciso que ela me retorne é o seguinte:
<code>     id integer|status_id_origem integer|status_id_destino integer|descricaoIdOrigem varchar|descricaoIdDestino varchar
     ----------|------------------------|-------------------------|-------------------------|------------------------
          44   |        1               | 2                       | Aguardando embarque     |    Embarcado
          43   |        1               | 2                       | Aguardando embarque     |    Embarcado
</code>
Comment: As duas maneiras postadas são idênticas, qual é o problema? (tem um erro também)
Comment: Opa, desculpa @VirgilioNovic, falha minha, saí na correria aqui e acabei colocando duas vezes o mesmo código, é que na maneira que eu preciso eu coloco duas referências na ForeignKey e na maneira normal, deve-se colocar apenas uma, poderia me ajudar nesta questão?
Comment: (Já editei a pergunta)
Comment: Bem vindo ao StackOverflow em Português. Editei sua pergunta para remover as saudações, pois costumamos mantê-las o mais limpo possível para focar na sua dúvida sobre programação. Caso tenha interesse em visitar uma parte do site que não é voltado para tirar dúvidas pode conhecer o [chat]. Se tiver dúvidas quanto ao funcionamento, regras e procedimentos do site visite o [meta] :)
Comment: Ok @diegofm, muito obrigado!
xD
Answer: Resolvido da seguinte maneira:
Realmente permaneceu da mesma forma:
<code>    public $belongsTo = array(
         Status => array(
            'className' => 'Status',
            'foreignKey' => 'status_id_origem',
            'dependent' => false,
         ),
    );
</code>
Maneira que eu estava fazendo:
<code>    SELECT Historico.*, Status.descricao
       FROM historicos as Historico
             LEFT JOIN statuses as Status
                     ON (Status.id = Historico.status_id_origem)
</code>
Logo essa query me retorna o seguinte:
<code>     id integer|status_id_origem integer|status_id_destino integer|descricao
     ----------|------------------------|-------------------------|---------
          44   |        1               | 2                       | Aguardando embarque
          43   |        1               | 2                       | Aguardando embarque
</code>
Maneira que achei o que eu precisava:
<code>    SELECT Historico.*, Status.descricao, Statuse.descricao
       FROM historicos as Historico
             LEFT JOIN statuses as Status
                     ON (Status.id = Historico.status_id_origem)
             LEFT JOIN statuses as Statuse
                     ON (Statuse.id = Historico.status_id_destino):
</code>
Logo essa query me retorna o seguinte:
<code>     id integer|status_id_origem integer|status_id_destino integer|  descricao  varchar  |  descricao  varchar
     ----------|------------------------|-------------------------|----------------------|---------------------
          44   |        1               |          2              | Aguardando embarque  |    Embarcado
          43   |        1               |          2              | Aguardando embarque  |    Embarcado
</code>

Relacionamento belongsTo


HEAP CORRUPTION DETECTED: after Normal block(#151) at 0x00DB4E70

Question: I have implemented a List for my class Word, and have HEAP CORRUPTION DETECTED, when program trying to delete my List. It goes into loop in destructor and delete first element, then when he goes second time, and trying to destroy "new" head I get Heap Corruption Error. I don't understand why it's going wrong. Any help would be much appreciated.
Word.h:
#include <cstring>
class Word
{
protected:
  char* word;
  char* type;
public:
  Word();
  Word(char );
  Word(char *);
  Word(char *, int);
  Word(const Word&);

  Word& operator=(const Word &);

  void setWord(char);
  void setWord(char *);
  void setWord(char*, int);

  void setType(char);
  void setType(char*);
  void setType(char*, int);

  ~Word();
};

WordList.h:
#include "Word.h"
#include <cstdlib>

class WordList
{
public:
 struct Node
 {
    Word data;
    Node  *next, *prev;
    //~Node();
 };
 Node *head;
 Node *tail;
 WordList();
 ~WordList();
 void add(Word &d);

};

WordList.cpp:
#include "WordList.h"

WordList::WordList(void)
{
head = nullptr;
tail = nullptr;
}

WordList::~WordList(void)
{
   while(head != nullptr)
   {
    Node *n = head->prev;
    delete head;
    head = n;
   }
}

void WordList::add(Word &d)
{
  Node *n = new Node;
  n->data = d;   // I overload =, and it copies information from d to data
  n->next = head;
  if (head!=nullptr)
    head->prev = n;
  if(head == nullptr){
    head = n;
    tail = head;
  } else
    head = n;
}

Comment: Try running it under the Application Verifier - you might hit a breakpoint when the corruption occurs.
Answer: In the destructor
 Node *n = head->prev;

needs to be
 Node *n = head->next;

If you'll follow you add method, you'll see that you never set n with a prev value, thus head->prev has the same value that n->prev had, which you've never set (to null), leaving head->prev with a junk value, deleting that address won't be pretty.
Comment: Oh it has one; Take a closer look a how a new node is added. Specifically pay attention to the *lack* of nullifying the `prev` pointer of a new node. IOW, it is indeterminate and therefore subject to spawn sewer monkeys.
Comment: @WhozCraig You are correct of course. My terminology was not clear enough, I'll edit.
Comment: A problem that can be easily rectified by having a constructor for class `Node`, something like : `Node(const Word& val) : data(val), next(), prev() {}`
Comment: And +1 on the pickup for using prev instead of next in the first place, btw.


comparing ARIMA and AR with external regressor

Question: Consider the following models fitted to the same time series:

ARIMA(0,1,1)
ARIMA(1,0,0) (that is, AR(1)) with an external regressor

Can I use the AIC (or any other information criteria) to decide which one is better?
I know that in order to use the AIC to compare models these have to be fitted to the same dataset. Does this hold when I = 1? Does this hold when I use an external regressor in my model?
Comment: No, the AICs on differenced model cant be compared to AR
Comment: Thanks! Is there any other way I can compare these models then?
Answer: You can't compare AIC of IMAX(1,1) and ARX(1), because in the former there's a differencing and in the latter there is none.
You could go for $R^2$ like measure called FVU. Make sure you apply it on the dependent variable itself, not the differences. This is a "mechanical" approach. I'd hold off on this one though.
The real problem is that you're comparing very different specifications: non-stationary (unit root) and stationary. They're fundamentally different. For instance, if the constant is significant in IMAX(1,1) then your process will wander away from where it starts, while ARX(1) will be jumping around the unconditional mean, i.e. mean-reverting.
You have to make up your mind as to which approach to use using other means than in-sample fit statistics such as AIC. For instance, you may examine the autoregressive coefficient in ARX(1), whether it's close to 1 or not. If it's close then maybe ARX(1) is not a good fit at all. On the other hand, if the residuals from IMAX(1) have very strong negative autocorrelation at lag 1 this may indicate over-differencing etc.
Comment: Thank you for your answer, if I understand you think that $R^2$ like measures wouldn't be good on this case as well, is that right? I'll take a look at the autoregressive coefficients and residuals...
I'm aware that comparing $I = 1$ with $I = 0$ isn't ideal, but in my specific case I'm getting different results depending on which unit root test I use, so I can't quite accept / reject the presence of an unit root...
Comment: You don't have $R^2$ for MA models, generally, they can't be estimated by linear regression function.


SQL: compare multiple tables with common many-to-many relationship

Question: two material Tables:
MaterialA
ID  Name
------------
1   Steel
2   Wood
3   Concrete
4   Gold

and
MaterialB
ID  Name
------------
1   Oil
2   Glass
3   Copper
4   Water

and a table with some notes:
Note
ID  Property
------------
1   hard
2   liquid
3   flammable
4   heavy
5   metal
6   lighter than water

so all materials can have zero or all notes (many-to-many relationship).
therefore the table attribution:
Attribution
ID  Table   Mat_ID  Note_ID
---------------------------
1   A       1       1
2   A       1       4
3   A       1       5
4   A       2       3
5   A       2       6
6   A       3       1
7   A       4       4
8   A       4       5
9   B       1       2
10  B       1       3
11  B       1       6
12  B       2       1
13  B       3       4
14  B       3       5
15  B       4       2

just for a better view, the material tables with note-id's:
MaterialA
ID  Name        Notes
---------------------
1   Steel       1, 4, 5
2   Wood        3, 6
3   Concrete    1
4   Gold        4, 5

and
MaterialB
ID  Name        Notes
---------------------
1   Oil         2, 3, 6
2   Glass       1
3   Copper      4, 5
4   Water       2

how is the query to get materials from MaterialA which have the same notes like any material in MaterialB.
So the result should be:
Result
ID  Name
------------
3   Concrete
4   Gold

I'm using SQLite
Answer: use this
select MaterialA.ID, MaterialA.Name
from (
    select "Table", mat_ID, group_concat(Note_ID) notes from Attribution where "Table"='A' group by "Table", mat_ID ) ta
join (
    select "Table", mat_ID, group_concat(Note_ID) notes from Attribution where "Table"='B' group by "Table", mat_ID )tb on ta.notes=tb.notes
join MaterialA on ta.mat_id=MaterialA.ID

if you need order by in Attribution table, you must first do your order by and then use group_concat(). for example:
select MaterialA.ID, MaterialA.Name
from (
    select "Table", mat_ID, group_concat(Note_ID) notes from (
        select "Table", mat_ID, note_id from test where "Table"='A' order by ID desc  )t1
    group by "Table", mat_ID ) ta
join (
    select "Table", mat_ID, group_concat(Note_ID) notes from (
        select "Table", mat_ID, note_id from test where "Table"='B' order by ID desc  )t2
    group by "Table", mat_ID )tb on ta.notes=tb.notes
join MaterialA on ta.mat_id=MaterialA.ID

Comment: I just tried this with inverted Order (4   Gold    5, 4) than I just get concrete as result. ORDER BY within group_concat() does not work for SQLite. any other options?


How do i repeat the game on a loop?

Question: import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
if guess > 100:
    print("your guess is too high")
elif guess < 1:
    print("your guess is too low")
elif guess==computer:
    print("well done!")
else:
    print("you\'re wrong, guess again")

This is my current code. it's game where the computer randomly chooses a number and the player has to guess it. i have tried but i don't know how to ask the player if they want to play again and if they say yes how to restart it.
Answer: Wrap the game code to function and use while True to call it again and again
import random

def play():
    computer=random.randint(1, 100)
    guess=int(input("guess the number"))
    if guess > 100:
        print("your guess is too high")
    elif guess < 1:
        print("your guess is too low")
    elif guess==computer:
        print("well done!")
    else:
        print("you\'re wrong, guess again")

while True:
    answer = input("do you want to play?")
    if answer == 'yes':
        play()
    elif answer == 'no':
        break
    else:
        print("dont understand")

Answer: Put all the if-else statements within one big while loop that keeps looping until the user guesses the number correctly. Then, after each losing outcome, give the user another chance to guess the number so that the loop has a chance to reevaluate the guess with the next iteration. In my modification below I decided to leave the last if-else statement outside of the loop because when the user guesses correctly, the code will break out of the loop to check if the guess is correct. Of course in this scenario it has to be correct so the user is told that he or she is right and the program terminates.
import random
computer=random.randint(1, 100)
guess=int(input("guess the number\n"))
while(guess != computer):
    if guess > 100:
        print("your guess is too high\n")
        guess=int(input("guess the number again\n"))
    elif guess < 1:
        print("your guess is too low\n")
        guess=int(input("guess the number again\n"))
if guess==computer:
    print("well done!\n")

Answer: Just an overview of how you can do it.
initialize a variable play_again = "yes"
Place a while check on play_again:
while play_again == "yes":

Enclose all if statements and guess input in the while loop
Read the user input in a variable within but at the end of the loop:
play_again = raw_input("\n\nWant to play again?: ")

Answer: You can use a while loop for multiple iterations
import random
computer=random.randint(1, 100)
guess=int(input("guess the number"))
play_again = 'y'
while play_again == 'y':
    if guess > 100:
        print("your guess is too high")
    elif guess < 1:
        print("your guess is too low")
    elif guess==computer:
        print("well done!")
    else:
        print("you\'re wrong, guess again")
    play_again = input("Want to play again(y/n): ")

Answer: You should put your code in while loop. Then after game ask user if they want to continue with input() function. If they say 'no' you can break the loop or set argument of while to False.

How do i repeat the game on a loop?


o erro "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type" qndo já defini a operação como number

Question: Estou usando o angular pela primeira vez e fazendo uma lista de cursos e eles tem pontuações, e estou tentando colocar estrelas de acordo com suas pontuações.
Pra isso, criei  com o component.
No html está dando esse erro do título, mas eu especifiquei o rating como number. Ainda tem um segundo erro dizendo que a propriedade rating não existe, mas existe. rs "Property 'rating' does not exist on type 'CourseListComponent'"
Segue o código HTML

Course List

    Image
    Name
    Price
    Code
    Rating
    Options

      {{ course.imageUrl }}
      {{ course.name }}
      {{ course.price }}
      {{ course.code }}

        <app-star [rating]="course - rating"></app-star>

Agora, o código typescript

    import { identifierModuleUrl } from '@angular/compiler';

export class Course {
  id: number;
  name: string;
  imageUrl: string;
  price: number;
  code: string;
  duration: number;
  rating: number;

  constructor(
    id: number,
    name: string,
    imageUrl: '',
    price: number,
    code: string,
    duration: number,
    rating: number
  ) {
    this.id = id;
    this.name = name;
    this.imageUrl = imageUrl;
    this.price = price;
    this.code = code;
    this.duration = duration;
    this.rating = rating;
  }
}

A classe course é instanciada em

import { Component, OnInit } from '@angular/core';
import { Course } from './course';

@Component({
  selector: 'app-course-list',
  templateUrl: './course-list.component.html',
})
export class CourseListComponent implements OnInit {
  courses: Course[] = [];

  ngOnInit(): void {
    this.courses = [
      {
        id: 1,
        name: 'angular-forms',
        imageUrl: '',
        price: 99.99,
        code: 'XPS-8967',
        duration: 120,
        rating: 4.6,
      },

      {
        id: 2,
        name: 'java-iniciante',
        imageUrl: '',
        price: 99.99,
        code: 'XPS-7799',
        duration: 120,
        rating: 4.0,
      },
    ];
  }
}

eu criei esse componente app-star pra tentar colocar as estrelas de acordo com a classificação, o código ficou assim

import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'app-star',
  templateUrl: './star.component.html',
  styleUrls: ['./star.component.css'],
})
export class StarComponent implements OnChanges {
  @Input()
  rating: number = 0;

  starWidth!: number;

  constructor() {
    this.starWidth = this.starWidth;
  }

  ngOnChanges(): void {
    this.starWidth = (this.rating * 94) / 5;
  }
}
Comment: Nossa, confuso demais isso aí, pq está inicializando as propriedades no construtor? Está instanciando essa classe onde? O que seria isto ``???
Comment: Ei lê, to inicializando elas no construtor porque antes dava o seguinte erro pra cada uma delas "Property 'id' has no initializer and is not definitely assigned in the constructor.". vou colocar onde estou instanciando a classe no post. Esse app-star é uma tag que eu criei com o angular pra colocar estrelas de acordo com a classificação.
Comment: Ainda está confuso, mas, pelo que vi a classe **Course** poderia ser uma `interface` ou uma `classe abstrata (melhor pq dá para ser instanciada)`, para não ter que ficar definindo valores nela, apenas sendo um modelo. Dito isto, não vi relação com o erro da pergunta e o código apresentado na mesma, a única coisa que me vem a cabeça é o problema estar em `[rating]="course - rating"` qual tipo de dado que esse **`[rating]`** aceita?
Comment: o rating aceita a classificação dos cursos, ou seja, números. percebi que não tinha mostrado essa parte do código e adicionei a pergunta, veja lá. tentei tornar a classe abstrata e continuou dando o mesmo erro de antes! ):
Comment: Então minha querida, se aceita números, pq, está passando **string**??
Answer: Na classe Course a propriedade RATING é do tipo NUMBER e você está passando um tipo STRING, por isso não consegue instanciá-la no component.
class Course {
  id: number;
  name: string;
  imageUrl: string;
  price: number;
  code: string;
  duration: number;
  rating: number;
}

[rating]="course - rating"
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: Tente [rating]="couses.rating" . Assim o rating vai receber o valor do atributo da lista de courses.


IBM Watson Speech to Text Only Returning First Word With Java SDK

Question: I'm using the IBM Watson speech to text Java SDK, and when I upload the .wav file the response JSON only contains the first transcribed word. When I upload the same file to the web demo, I get the full response.
Very simple implementation with the SDK:
SpeechToText service = new SpeechToText();
service.setUsernameAndPassword("<username>", "<password>");

File audio = new File("src/test/resources/sample1.wav");

SpeechResults transcript = service.recognize(audio, HttpMediaType.AUDIO_WAV);
System.out.println(transcript);

Answer: The recognize() signature you are using will return after the first pause. To see all of the results do this:
RecognizeOptions options = new RecognizeOptions();
options = options.continuous(true)
          .contentType(HttpMediaType.AUDIO_WAV)
          .interimResults(false)
          .inactivityTimeout(10)
          .maxAlternatives(1)
          .wordConfidence(false)
          .timestamps(true)
          .model("en-US_BroadbandModel");
SpeechResults transcript = service.recognize(audio, options);

This works for me using the following maven dependency:
<dependency>
  <groupId>com.ibm.watson.developer_cloud</groupId>
  <artifactId>java-sdk</artifactId>
  <version>2.8.0</version>
</dependency>

Comment: This wasn't explained in the answer, but setting the `continuous` option to `true` is the key to retrieving all of the results, not only the results after the first pause.
Comment: Nice, didn't see that documented anywhere.
Answer: I am trying quite the same thing, using the same parameters described by Chris K. (except for "interim results = true")
    FileInputStream audio = new FileInputStream("/home/leoks/BM/ws/mp32wav/out.wav");

    RecognizeOptions options = new RecognizeOptions();
    options = options.continuous(true)
              .contentType(HttpMediaType.AUDIO_WAV)
              .interimResults(true)
              .inactivityTimeout(10)
              .maxAlternatives(1)
              .wordConfidence(false)
              .timestamps(true)
              .model("en-US_BroadbandModel");

    api.stt.recognizeUsingWebSockets(audio, options, new BaseRecognizeDelegate() {
      @Override
      public void onMessage(SpeechResults speechResults) {
        System.out.println(speechResults);
        try{
            if (speechResults != null && speechResults.isFinal()){
              lock.countDown();
            }
        }catch(java.lang.IndexOutOfBoundsException ignored){
        }
      }
    });

    lock.await(5, TimeUnit.SECONDS);

However, it still throws an exception
java.lang.NullPointerException
    at java.io.StringReader.<init>(StringReader.java:50)
    at com.google.gson.JsonParser.parse(JsonParser.java:45)
    at com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.WebSocketSpeechToTextClient$WebSocketListener.onTextMessage(WebSocketSpeechToTextClient.java:66)
    at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:233)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:211)
    at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:910)
    at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:693)
    at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:102)
    at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:61)
java.lang.NullPointerException
    at java.io.StringReader.<init>(StringReader.java:50)
    at com.google.gson.JsonParser.parse(JsonParser.java:45)
    at com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.WebSocketSpeechToTextClient$WebSocketListener.onTextMessage(WebSocketSpeechToTextClient.java:66)
    at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:233)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:211)
    at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:910)
    at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:693)
    at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:102)
    at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:61)
java.lang.NullPointerException
    at java.io.StringReader.<init>(StringReader.java:50)
    at com.google.gson.JsonParser.parse(JsonParser.java:45)
    at com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.WebSocketSpeechToTextClient$WebSocketListener.onTextMessage(WebSocketSpeechToTextClient.java:66)
    at com.neovisionaries.ws.client.ListenerManager.callOnTextMessage(ListenerManager.java:352)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:233)
    at com.neovisionaries.ws.client.ReadingThread.callOnTextMessage(ReadingThread.java:211)
    at com.neovisionaries.ws.client.ReadingThread.handleTextFrame(ReadingThread.java:910)
    at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:693)
    at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:102)
    at com.neovisionaries.ws.client.ReadingThread.run(ReadingThread.java:61)

which seems to be related to this issue
https://github.com/watson-developer-cloud/java-sdk/issues/205
that is set to be reached in milestone 2.9.0 (current is 2.8.0)
Comment: It works for me with interim results true. You shouldn't do `lock.countDown()` on `speechResults.isFinal()` though - there are multiple messages that are final (this occurs every time there is a pause in the speech).


static const Color not fully working with Allegro5

Question: I'm relatively new to C++, recently moved from C# and Java (and before that, used to work in pure Lua environment). I've been trying to solve this issue I came across, but did not succeed. Basically, I created a class named Color and added static consts as shortcuts for various colors and it is used for the text writing using allegro (I am creating my own game engine for internal use and am creating one API in C++ for all the libraries the engine uses). What happens is that when I define a color using the static const, the text does not appear, while if I use the constructor, everything works as expected. The printf() function in main_menu returns proper results in both cases, so the local variables are being set in either cases. So the problem is really with the allegro part of the "equation".
Also, if any of this is malformed, like if there are any bad practices or anything like, I would appreciate tips on how to improve it.
Thank you in advance.

color.hpp
<code>#pragma once
#include "allegro5/color.h"
#include "onidrive/vector2.hpp"

namespace oni {
  enum Align: int;
  class Font;

  class Color {
    public:
      Color(unsigned char r = 0xFF, unsigned char g = 0xFF, unsigned char b = 0xFF, unsigned char a = 0xFF);
      ~Color();
      unsigned char r;
      unsigned char g;
      unsigned char b;
      unsigned char a;

      static const Color white;
      static const Color black;
      static const Color red;
      static const Color green;
      static const Color blue;
      static const Color yellow;
      static const Color magenta;
      static const Color cyan;

      friend void draw_text(Font *font, Color *color, Vector2<float> position, Align align, std::string text);

    private:
      ALLEGRO_COLOR color;

  };
}
</code>

color.cpp
<code>#include "onidrive/color.hpp"
#include "allegro5/allegro.h"

oni::Color::Color(unsigned char r, unsigned char g, unsigned char b, unsigned char a) : r(r), g(g), b(b), a(a) {
  this->color = al_map_rgba(r, g, b, a);
}

oni::Color::~Color() {

}

const oni::Color oni::Color::white(  0xFF, 0xFF, 0xFF, 0xFF);
const oni::Color oni::Color::black(  0x00, 0x00, 0x00);
const oni::Color oni::Color::red(    0xFF, 0x00, 0x00);
const oni::Color oni::Color::green(  0x00, 0xFF, 0x00);
const oni::Color oni::Color::blue(   0x00, 0x00, 0xFF);
const oni::Color oni::Color::yellow( 0xFF, 0xFF, 0x00);
const oni::Color oni::Color::magenta(0xFF, 0x00, 0xFF);
const oni::Color oni::Color::cyan(   0x00, 0xFF, 0xFF);
</code>

main_menu.cpp
<code>...
void MainMenu::draw_ui() {

  //when this is used, compiling, text is invisible
  oni::Color color = oni::Color::red;

  //when this is used, compiling, text is visible, correct color, works as expected
  oni::Color color = oni::Color(0xFF, 0x00, 0x00, 0xFF);

  printf("color(%X, %X, %X, %X);\n", color.r, color.g, color.b, color.a);

  oni::draw_text(font, &color, Vector2<float>(32, 32), oni::ALIGN_LEFT, "Hello World");

}
...
</code>

function draw_text
<code>void oni::draw_text(Font *font, Color *color, Vector2<float> position, oni::Align align, std::string text) {
  al_draw_text(font->font, color->color, position.x, position.y, (int)align, text.c_str());
}
</code>
Comment: pro tip: you can put `namespace oni { /* ... */ }` in the .cpp file as well
Comment: @Brian that's so much easier, thank you, I missed that one out.
Answer: Your static const Color objects are created in the global namespace. This means any code in their constructor runs before al_init is called in main. There are only a few allegro functions that can be called before al_init, and al_map_rgb is not one of them.
That is why it works when you create a new Color object after al_init but not when you use your static Color objects.


Creating multivariable functions

Question: Getting ready to go into multivariable calculus and I have a problem given to me by one of the teachers that will be teaching it next year. So here it is!
Write a multivariable function (i.e $z=f(x,y)$) for a linear function that contains the points $(-1,0), (0,2), (1,-1)$. I've calculated the lines that intersect each other and they are as follows $y=2x+2$ , $y=-3x+2$ , $y=-0.5x-0.5$. But now I need to create a multivariable function with domain $[-1,1]$ and range $[-1,2]$.
The 2nd part is creating a hypocycloid with points at $(1,0) , (0,1) , (-1,0) , (0,-1)$.
Comment: Please consider using a more descriptive title.
Comment: I don't know what this means. If you want $z=f(x,y)$, shouldn't we have ordered triples $(x,y,z)$ rather than ordered pairs? The hypocycloid is a nice question (if you know what that is). Related to it is the classic question: If you roll a coin of radius $1$ (without slipping) around a coin of radius $3$, how many complete turns does its head make?
Comment: @Ted Shifrin I know what a hypocycloid is but I'm wondering if I need to find an equation starting in polar and convert that into cartesian.
Answer: Hint
The general form of a linear function of two variables is given by
$$
f(x,y) = Ax + By +C
$$
Plugging in the points you were given should give you three equations in the three unknowns $(A,B,C)$, which you can then solve.

Creating multivariable functions


Springboot @ConfigurationProperties Not Injecting

Question: I am having trouble getting my property file (export-fields.yml) to inject to a map. I've created the properties file in the resources folder, linked to the property source, created a configuration for the property object, and generated getters and setters with lombok, but still not getting anything populated into the fields map (fields = null). Is there something I'm missing? Here is the code I have so far
FieldReplacerProperties.java
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "export")
@PropertySource("classpath:export-fields.yml")
public class FieldReplacerProperties {
    private Map<String, String> fields;

public List<String> columnsToFields(List<String> columns){
        columns.parallelStream().forEach(column -> fields.get(column));
        return columns;
    }

}
FieldReplacerConfiguration.java
@Getter
@Setter
@Configuration
@EnableConfigurationProperties(FieldReplacerProperties.class)
public class FieldReplacerConfiguration {

    @Autowired
    private FieldReplacerProperties fieldReplacerProperties;

    public List<String> columnsToFields(List<String> columns){
        return fieldReplacerProperties.columnsToFields(columns);
    }
}

export-fields.yml
export:
  fields:
    id: number
    name: programName
    type: contractType
    term: contractTerm
    ...

How I'm accessing it
@Autowired
private FieldReplacerConfiguration fieldReplacerConfiguration;
//replace columns with fields
fieldReplacerConfiguration.columnsToFields(columns);

Comment: Does this answer your question? [spring boot read properties from yml file](https://stackoverflow.com/questions/56939406/spring-boot-read-properties-from-yml-file)
Comment: @SachithDickwella yes it does thank you. I needed a PropertySourceFactory for the yml file.
Answer: Spring loads properties from application.properties (or yml). Try moving properties from export-fields.yml to application.yml
Comment: Have a lot going on in the application.yml so wanted to move this outside to make things easier to maintain. Managed to solve the issue with a PropertySourceFactory
Comment: Understood, another option to avoid implementing PropertySourceFactory and load custom yml is follow a convention like application-.yml.  Example application-fields-yml.
Answer: Added a PropertySourceFactory and this fixed the issue.
@PropertySource Change
@PropertySource(value = "classpath:export-fields.yml", factory = YamlPropertySourceFactory.class)

YML Factory
public class YamlPropertySourceFactory implements PropertySourceFactory {

@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(encodedResource.getResource());

Properties properties = factory.getObject();

return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);

}

}


How to implement LogisticRegressionCv on flutter

Question: i have LogisticRegressionCv model it's .pkl file and import data as images but i don't know how to get it on flutter please help me If you know how or if I must to convert my model to other file formats.
please help me.
Thank you for your help.
Comment: Here is an [article](https://betterprogramming.pub/how-to-make-a-cross-platform-image-classifying-app-with-flutter-and-fastai-2a6af6701535) that might help you
Comment: @AtharvaGundawar I have tried his model is cnn but my model is logistic regression When I try to deploy on render it throws an error.
Comment: Whats your error ?
Comment: @AtharvaGundawar it's  `RuntimeError: Invalid magic number; corrupt file?`
Comment: PyTorch uses a magic number to identify the file format or protocol, Could you try to use `torch.save` instead of `pickle.dump`?
Answer: as you've trained your model in python and stored it in pkl file. One method is in your flutter background, call python3 predict_yourmodel.py your_model_params and after the run, it will give your the model result.
Another way is implement a logisticRegressionCv in Flutter as it is a simple model, and easily be implemented. you can store all your params and l1 or l2 etc super-params in a txt instead of pkl file for readility.
Comment: How do I save the model as a txt file, do you have a way?
Comment: you can print attributes of your logres_cv, such as `print(lr_cv.coef_)`, and Cs_ if you have used regularization in your model. have a reference on [sklearn-lr_cv](https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html#sklearn.linear_model.LogisticRegressionCV)


CKEditor Toolbar Configuration

Question: I would like to use CKEditor on my Drupal website. But the toolbar is not showing up when I go to edit appearance on any profile (full or advanced). Although, when I add or edit any type of content, the toolbar is shown correctly and I don't have any problems there. Just when I try to configure the toolbar.
I took a picture so that you can see exactly what I have:

I also have these errors:

It seems that the problem might have something to do with JQueryUI according to the errors I have. I use JQueryUpdate  to manage my JQuery version (which is 1.10).
I tried uninstalling CKEditor, clearing caches but it's not doing anything.
I use Drupal 7.41.
I know that this question has already been posted on this website, but after having read the answers it got I still have my problem so, sorry for the duplicate...
Thanks a lot for your answers  :)
Answer: Ok I've just found the error. It seems that when I extracted my compressed version of my website, it renamed every folder in lowercase. So Drupal couldn't find jqueryUI folder, because it was renamed jqueryui.

CKEditor Toolbar Configuration