What is the result of String.fromCharCode(17)?

Question: I am confused about this static method. When using the 17 char code (control key), I can't find a way to compare it to anything.
Chrome console:

It looks like a regular empty string.
The mdn says

This method returns a string and not a String object.

so I was thinking that
String.fromCharCode(17) === "" would return true. But it returns false.
Why?

typeof(String.fromCharCode(17)) returns "string"
String.fromCharCode(17) === null returns false
String.fromCharCode(17) === undefined returns false
Also, just to be sure, I did String.fromCharCode(17) === new String() and it returned false too...

I don't understand...
Comment: @BoltClock I don't expect it to print anything. I just expect "anything" to be consistent accross its representations :)
Comment: char code 17 is [Ctrl](http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes) and can't be cout-ed I suppose.
Comment: Since you know 17 represents the control key, what makes you think it should print anything?
Comment: @Sebas If you want consistency, front-end web development may not be your flavour ;)
Comment: It seems to only print ASCII chars for parameter values `33` - `126`.
Answer:
so I was thinking that String.fromCharCode(17) === "" would return true. But it returns false. Why?

String.fromCharCode(17) returns device control 1, which seems to be an unprintable character. The reason it fails the condition is because it is not an empty string.
String.fromCharCode(17) === String.fromCharCode(17) would return true.
Comment: @Sebas: No, that's why it's called "unprintable".
Comment: You mean it is a console behavior issue? I would think the unprintable character would translate to something if its type is actually a string
Comment: Nope. It's normal JavaScript behaviour. The two strings aren't equivalent, firstly because they have different lengths.
Comment: to me there's a contradiction. The console should show a symbol dedicated to unprintable characters, not an empty string. Actually I see above that IE does show something else...
Comment: @Sebas How do you print ' '? What about ASCII-8 (Backspace)?
Comment: Hi @ElliottFrisch, backspace is not a string... it should return that same unprintable symbol I guess...
Answer: When I tried it's showing "" (non-printing character) so, it's not an empty string. See below image for a proof:

Which is why String.fromCharCode(17) === "" would return false.
Comment: That's the this font set doesn't include that glyph glyph.
Answer: The mdn for String.fromCharCode() quote is incomplete,

returns a string created by using the specified sequence of Unicode values.

In this case, a non-printable character - ASCII 17 - or Device Control 1.
Answer: String.fromCharCode() method returns a string created by using the specified sequence of Unicode values. KeyChar 17 actually represents the CTR key of our keyboard. So when you are writing
String.fromCharCode(17) ,

It actually representing characters that cannot be represented into one 16-bit number. hence, its not empty string , something that can't be displayed as it takes more than one 16-bit numbers unicode values.


Is any Gauss-Markov assumption violated by the simple OLS regression transformation?

Question: I am creating a simple linear model with the following form:
$$ y_i/x_i = \alpha + \beta x_i + u_i $$
The response variable has different name other than $y/x$, but it is essentially normalized by X as shown above.
So if the response, by definition includes part of the predictor can I regress this response on X, without introducing problems of bias or inefficiency? If no, can I have help with the intuition?
Comment: Depends. Look at the data. The model could make sense for e.g. does a rate depend on size, or does shape depend on size. In general ratios can be very problematic because division by small  numbers can impart skewness or create outliers -- or ratios can be entirely appropriate because scaling by a denominator creates the outcome measure you do want.
Comment: thanks Nick, but looking at my question more the specification seems a little strange. If y is say market returns and X is its volatility it seems that increases in volatility will guarantee a smaller normalized returns and vice versa. I assume that the coefficient would be near -1. So although the model makes sense, I feel like its cheating in some way. I suspect that this one predictor would absorb all the predictive power if I added other predictors of market returns. The point about outliers and skewness is very helpful. thanks
Comment: I am sure there is an interesting specific question in there about returns but in essence you need to spell it out and pitch it at like-minded economists.
Comment: Note that we often dive straight into this model. If you regress pandemic death counts scaled by population against population that is a different and more challenging hypothesis than whether pandemic death counts are affected by population size, to which the answer is Yes, of course they do.
Answer: Your model is equivalent to:
$$y_i=\alpha x_i+ \beta x_i^2+u_i x_i .$$
Note $\varepsilon_i = u_i x_i$, such that this model rewrites:
$$y_i = \alpha x_i + \beta x_i^2 + \varepsilon_i .$$
So the two differences with a usual linear regression model are:

you don't have a constant term,
the errors $\varepsilon_i$ are proportional to the covariates $x_i$.

I don't think that the absence of constant term is a big deal (maybe I'm wrong...), but the other point is.
To have Gauss-Markov theorem, you want the $\varepsilon_i$ to have:

null expectation,
constant variance,
null covariance.

In order to have that, you need assumptions on you $x_i$ (which you don't need to have Gauss-Markov theorem for a classical linear regression).
Such assumption could be that the $x_i$ are independent from the $u_i$ and have constant mean and variance. Then you'll have that the $\varepsilon_i$ satisfying the three conditions.
So, as Nick Cox commented, the answer is: it depends.
If you have a fixed design ($x_i$ are constant), then no (the $\varepsilon_i$ won't have constant variance). If you suspect the $u_i$ not to be independent from $x_i$, then no again.
But if the $x_i$ are i.i.d. and independent from the $u_i$, then I think yes.
Comment: I think this is misleading. By your logic, equivalent representations of the same model yield different conclusions. This should not happen. What if (1) $y$ actually is defined as $y:=zx$, meaning $z_i=\alpha+\beta x_i+u_i$ and (2) all of the Gauss-Markov assumptions are satisfied in this model which also happens to be the data generating process?
Comment: Hm... I do agree with you with your comment, but I cannot see where I wen't wrong in my reasoning.
Your representation with $z_i = y_i / x_i$ and mine with $\varepsilon_i = u_i x_i$ clearly yield different conclusions.. Do they differ by some hidden assumption ?

I'm a bit lost now...
Comment: @Pohoua It seems to me your general logic is right but the last bit about when this is fulfilled may not be. It seems you (additionally) need $\epsilon_i=u_ix_i$ to be independent of $x_i$, which is not normally fulfilled if $u_i$ and $x_i$ are independent, but is fulfilled in Richard Hardy's case.
Comment: @Pohoua, in the second part of my point (2) I made an explicit assumption  regarding what the DGP is. You made an implicit one. If you state it explicitly, your argumentation would be justified. However, there is nothing in the OPs setup that justifies such an assumption. I am not saying that mine is justified either, but that only illustrates the problem with your answer in its current shape.
Comment: Sorry I still have difficulties to understand. If we have random variable $X$, $Y$ and $U$, saying that $Y/X = \alpha + \beta X + U$ is equivalent to saying that $Y= \alpha + \beta X +UX$. The assumed  data generating processes are the same..
Comment: But I'm quite convinced now that there is something fishy with my answer. Your argument is straightforward clearly right..
Comment: You have to add the assumption about the error term. E.g. I said "all of the Gauss-Markov assumptions are satisfied" for the model $z_i=\alpha+\beta x_i+u_i$. Also, please include @RichardHardy so that I get notified.
Comment: @RichardHardy I think I found what was puzzling me.
I do think that the models $Y/X = \alpha + \beta X + u$ and $Y = \alpha X + \beta X^2 + u X$ are equivalent, and I couldn't understand why the second model requires more restrictive assumptions for the Gauss-Markov theorem to hold and have that the OLS estimator is BLUE.
But the OLS estimators for the two models aren't the same! In particular they are not linear with respect to the same response.
Comment: @RichardHardy
OLS of the first model is linear in $Z = Y/X$, and it's the best unbiased among estimators linear in $Z$.
The OLS estimator of the second model is linear with respect to $Y$ and is the best unbiased among estimators linear in $Y$ (if more restrictive aszumptions are made).

As any estimator linear in $Z$ is also linear in $Y$, the class of estimator linear in $Y$ is wider. So OLS of the second model is best in a wider class, but at the cost of more restrictive assumptions!


Axios auto refresh every 60 seconds with Reactjs

Question: I'm using ReactJS as a javascript library and I am getting the data in componentDidMount() using axios. These received data must be taken again every 60 seconds. What is the most efficient and good way to do this?
componentDidMount() {
  const newGteeChartSeries = [];
  const newGteeChartCategories = [];
  const newmultiSelectOption = [];

  axios.get(`http://www.xxxxxxx:xxxx/api/groupdata`).then(res => {
    this.state.gteeChartSeries.map(() => {
      const data = [];

      res.data.map((item, index) => {
        data.push(item.gtee);
        newGteeChartCategories.push(item.isyeri);
        newmultiSelectOption.push({ id: item.id, isyeri: item.isyeri });
      });
      newGteeChartSeries.push({ name: "GTEE", data });
    });

    this.setState({
      teeTableData: res.data,
      gteeChartSeries: newGteeChartSeries,
      multiSelectOptions: newmultiSelectOption,
      gteeChartoptions: {
        ...this.state.options,
        xaxis: {
          categories: newGteeChartCategories
        }
      }
    });
  });
}

Answer: One way of going about it is to move the data fetching logic to a separate method and create an interval that will invoke this method every 60 seconds.
Make sure you store the number returned from setInterval on the component instance so you can use clearInterval in componentWillUnmount.
Example
class MyComponent extends React.Component {
  interval = null;

  componentDidMount() {
    this.interval = setInterval(this.getData, 60000);
    this.getData();
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  getData = () => {
    const newGteeChartSeries = [];
    const newGteeChartCategories = [];
    const newmultiSelectOption = [];

    axios.get(`http://www.xxxxxxx:xxxx/api/groupdata`).then(res => {
      this.state.gteeChartSeries.forEach(() => {
        const data = [];

        res.data.forEach((item, index) => {
          data.push(item.gtee);
          newGteeChartCategories.push(item.isyeri);
          newmultiSelectOption.push({ id: item.id, isyeri: item.isyeri });
        });
        newGteeChartSeries.push({ name: "GTEE", data });
      });

      this.setState({
        teeTableData: res.data,
        gteeChartSeries: newGteeChartSeries,
        multiSelectOptions: newmultiSelectOption,
        gteeChartoptions: {
          ...this.state.options,
          xaxis: {
            categories: newGteeChartCategories
          }
        }
      });
    });
  };
}

Answer: You can wrap all in a function.
Call that function in ComponentDidMount(), and use setInterval(myFunction(), 60000) to call that function every 60 seconds
Below works without syntax error.Call that function without parenthesis
``componentDidMount() {
    this.interval = setInterval( this.props.Details, 6000);
    this.props.Details()
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }``

Answer: I would suggest abstracting the api request into its own function
componentDidMount(){
 setInterval(yourApiCallFn(),60000)
}

Answer: Well let's do that with a normal javascript setTimeInterval.

let intervalLoop = null; // a class variable
componentDidMount() {
  const newGteeChartSeries = [];
  const newGteeChartCategories = [];
  const newmultiSelectOption = [];

  this.intervalLoop = setInterval(()=>{
  axios.get(`http://www.xxxxxxx:xxxx/api/groupdata`).then(res => {
    this.state.gteeChartSeries.map(() => {
      const data = [];

      res.data.map((item, index) => {
        data.push(item.gtee);
        newGteeChartCategories.push(item.isyeri);
        newmultiSelectOption.push({
          id: item.id,
          isyeri: item.isyeri
        });
      });
      newGteeChartSeries.push({
        name: "GTEE",
        data
      });
    });

    this.setState({
      teeTableData: res.data,
      gteeChartSeries: newGteeChartSeries,
      multiSelectOptions: newmultiSelectOption,
      gteeChartoptions: {
        ...this.state.options,
        xaxis: {
          categories: newGteeChartCategories
        }
      }
    });
  });
  }, 60000);
}
// need to cleanup the timeinterval whenever we destroy the component
componentWillUnmount(){
clearInterval(this.intervalLoop)
}


I can't concatenate elements to a string, when I use a sentence

Question: Well, I have a little problem, but First, I'll try to explain my program:
The user write a sentence, and it's saved in the char array FileContent[100]. Then, the user have to write five letters that is stored in the char array LE[5][2];. This letters are organized alphabetically by the program, and then, the user's sentence is printed originally and later without spaces. Here begins the problem...
If the user write only one word, the program works successfully, and in another array are stored the letters adequately depending on the letter being handled in the variable cont2. Are like coordinates.
But, when the user write a sentence, using spaces, the program doesn't work like I need to. The last process it is not carried out.
I hope it is understood, my English is not very good.
Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main()
    {
    char FileName[25], FileContent[100], FileChanged[210]={" "}, FileContentFixed[100];
    char Table[6][6][6] =
            {
                {"","","","","","",},
                {"","A","B","C","D","E",},
                {"","F","G","H","IJ","K",},
                {"","L","M","N\xA5","O","P",},
                {"","Q","R","S","T","U",},
                {"","V","W","X","Y","Z",}
            };

char LE[5][2];

char temp[6];
int i, j, k;
int l=0;

char chara;

int a=0, cont, b, exit;

int cont2=0, cont3=0;

printf("\n Ahora escriba el contenido: ");
scanf(" %[^\n]",&FileContent);
fflush(stdin);

printf("\n Ahora digite EXCLUSIVAMENTE 5 letras, separadas con ENTER: \n");
do
    {
    gets(LE[l]);
    l++;
    fflush(stdin);
    }while(l<5);

for(i=0; i<l-1; i++)
{
    k=i;
    strcpy(temp, LE[i]);
    for(j=i+1; j<l; j++)
    {
        if(strcmp(LE[j], temp)<0)
        {
            k=j;
            strcpy(temp, LE[j]);
        }
    }
    strcpy(LE[k],LE[i]);
    strcpy(LE[i],temp);
}

printf(" Las letras, en orden, son: ");
for(i=0; i<l; i++)
    {
    printf(" %s ",LE[i]);
    }

strcpy(Table[0][1], LE[0]); //lE1 HORI
strcpy(Table[1][0], LE[0]); //LE1 VER

strcpy(Table[0][2], LE[1]); //LE2 HORI
strcpy(Table[2][0], LE[1]); //LE2 VER

strcpy(Table[0][3], LE[2]); //LE3 HORI
strcpy(Table[3][0], LE[2]); //LE3 VER

strcpy(Table[0][4], LE[3]); //LE4 HORI
strcpy(Table[4][0], LE[3]); //LE4 VER

strcpy(Table[0][5], LE[4]); //LE5 HORI
strcpy(Table[5][0], LE[4]); //LE5 VER

fflush(stdin);
printf("\n\n El contenido del archivo de texto (.txt), digitado por el usuario, es: %s",FileContent);
/*  while((chara = fgetc(File1)) != EOF)
    {
    printf("%c",chara);
    }*/

while(FileContent[a] != '\0')
    {
    if(FileContent[a]== ' ')
        {
        b=a;
        exit=1;
        while(exit==1)
            {
            fflush(stdin);
            FileContent[b]=FileContent[b+1];

            FileContent[b+1]=' ';
            b++;
            if(FileContent[b]=='\0')
                {
                exit=0;
                }
            }
        }
    a++;
    }
    printf("\n\n El contenido, sin espacios, es: %s",FileContent);

cont3=strlen(FileContent);
printf("\n\nHay %i caracteres en el arreglo.\n",cont3);

    while(cont2<cont3)
        {
            printf("\n %i. %c",cont2,FileContent[cont2]);
            printf(" %i\n",cont3);

            switch(FileContent[cont2])
                {
                case 'a': printf("\n a: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'A': printf("\n A: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'b': printf("\n b: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'B': printf("\n B: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'c': printf("\n c: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'C': printf("\n C: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'd': printf("\n d: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'D': printf("\n D: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'e': printf("\n e: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'E': printf("\n E: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[1][0]); printf("%s",FileChanged); break;
                case 'f': printf("\n f: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'F': printf("\n F: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'g': printf("\n g: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'G': printf("\n G: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'h': printf("\n h: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'H': printf("\n H: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'i': printf("\n i: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'I': printf("\n I: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'j': printf("\n j: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'J': printf("\n J: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'k': printf("\n k: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'K': printf("\n K: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[2][0]); printf("%s",FileChanged); break;
                case 'l': printf("\n l: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'L': printf("\n L: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'm': printf("\n m: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'M': printf("\n M: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'n': printf("\n n: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'N': printf("\n N: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'o': printf("\n o: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'O': printf("\n O: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'p': printf("\n p: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'P': printf("\n P: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[3][0]); printf("%s",FileChanged); break;
                case 'q': printf("\n q: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'Q': printf("\n Q: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'r': printf("\n r: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'R': printf("\n R: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 's': printf("\n s: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'S': printf("\n S: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 't': printf("\n t: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'T': printf("\n T: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'u': printf("\n u: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'U': printf("\n U: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[4][0]); printf("%s",FileChanged); break;
                case 'v': printf("\n r: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'V': printf("\n r: "); strcat(FileChanged,Table[0][1]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'w': printf("\n w: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'W': printf("\n W: "); strcat(FileChanged,Table[0][2]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'x': printf("\n x: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'X': printf("\n X: "); strcat(FileChanged,Table[0][3]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'y': printf("\n y: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'Y': printf("\n Y: "); strcat(FileChanged,Table[0][4]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'z': printf("\n z: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                case 'Z': printf("\n Z: "); strcat(FileChanged,Table[0][5]); strcat(FileChanged,Table[5][0]); printf("%s",FileChanged); break;
                default: printf("\n Espaciooo ");
                }
            cont2=cont2+1;
        }

getchar();
return 0;
}

Comment: The code is very long. Please reduce it to a [mre]
Comment: Does this answer your question? [How do you allow spaces to be entered using scanf?](https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf)
Answer: In the space-stripping code:
while(FileContent[a] != '\0')
    {
    if(FileContent[a]== ' ')
        {
        b=a;
        exit=1;
        while(exit==1)
            {
            fflush(stdin);

fflush(stdin); is undefined behavior, but let's ignore that for now.
            FileContent[b]=FileContent[b+1];

            FileContent[b+1]=' ';
            b++;
            if(FileContent[b]=='\0')

FileContent[b] will never be a null terminator here because you overwrote it with a space in the previous lines.
                {
                exit=0;
                }
            }
        }
    a++;
    }

The code is also a bit inefficient. Here is a more efficient version:
b = a;
while (1)
    {
    while (FileContent[b] == ' ')
        {
        b++;
        }
    if ((FileContent[a] = FileContent[b]) == '\0')
        {
        break;
        }
    a++;
    b++;
    }


adapting a function by a linear regression

Question: I am wondering if it is possible to adapt the function $$y=a\cdot \ln(x)+\frac{b}{x}+x$$ by a linear regression to fit experimental data? If yes, how could this be done?
Thank you!
Comment: It wouldn't be "linear" regression. But yes, it's possible to fit other types of functions.
Answer: Yes, it is OK. The requirement is to have the function you are estimating "linear in parameters" - your parameters are $a$ and $b$ (and perhaps $c$ if you have forgotten it but it works without it as well) and these parameters enter the function in a linear fashion: $y = a\cdot f_1(x)+b\cdot f_2(x) + f_3(x).$
As far as terminology is concerned, I would say that this is still called "linear regression".
It might be instructive to think about a function that would not be linear in parameters. For instance, $y=\frac{1}{a\cdot x + b}.$ In this regression function, we can't neatly separate the parameters and so can't use linear regression.
How to estimate your function? $y-x=a*log(x)+b*\frac{1}{x}$ and run OLS in some program without intercept ($y-x$ will be dependent variable, $log(x)$ is one independent and $\frac{1}{x}$ is second independent variable).
Answer: You can use linear methods if you are willing to fit a multivariate linear regression:
Let Y=ln(x), Z=1/x, X=x, then your equation becomes:
f(X,Y,Z) = aY + bZ + X; as you can see, it has a linear form.
Now, you just calculate X, Y, Z and fit a multivariate normal to the data.
The downside is that your "independent" variables are not really independent, so you may have multicolinnearity. You can calculate the correlations between each pair of variables, e.g., Corr(X,Y), Corr(Y,Z), Corr(X,Z), to verify that your variable are sufficiently linearly independent. If not, you will have one of your variables have an elevated standard error, and hence may"drop out" as it will not offer enough information to justify its inclusion. If so, remove one of them and refit.
Anyway, that's one possible way to use a linear model to fit your data. You can also just use a brute force "least squares" numerical algorithm to directly select parameters that minimize sum of squared error.


Lax-Wendroff method for nonlinear hyperbolic systems of conservation laws

Question: In page 127 of R.J. LeVeque's "Numerical Methods for conservation laws" (Birkhäuser, 1992),

There are various ways that [the Lax-Wendroff method for constant-coefficient linear hyperbolic systems] can be extended to give a second order method for nonlinear conservation laws. If we let $A(u) = f'(u)$ be the Jacobian matrix, then a conservative form of Lax-Wendroff is
  $$
U_j^{n+1} = U_j^n - \frac{k}{2h}(f(U_{j+1}^n - f(U_{j-1}^n)) + \frac{k^2}{2h^2} \big[ A_{j+1/2} (f(U_{j+1}^n) - f(U_j^n)) \\
- A_{j-1/2} (f(U_{j}^n) - f(U_{j-1}^n)) \big] \, ,
\tag{12.25}
$$
  where $A_{j\pm1/2}$ is the Jacobian matrix evaluated at $\frac12 (U_j^n + U_{j\pm 1}^n)$.

I am trying to understand the paragraph above, which is pretty much the same as in the Wikipedia article. First of all, how was this derived and how is it in conservative form? Moreover, Why are we evaluating a jacobian at $\frac12 (U_j^n + U_{j \pm 1}^n )$? Isnt this the value of the solution $u= u(x)$ evaluated at some discrete point? Im confused by this notation. Can someone clarify this?
My question is related to an exercise of this book:

EXERCISE 12.3. [The method] $(12.25)$ reduces to [the classical linear Lax-Wendroff method] in the constant coefficient linear case and is second order accurate on smooth solutions (to nonlinear problems) and conservative. Verify these statements for at least [$(12.25)$] and write it in conservation form, determining the numerical flux function.
Comment: [This question](https://math.stackexchange.com/q/2886452/418542) is closely related: only the computation of the Jacobian at the cell interface differs. For the first part, the conservative form is given in [this post](https://math.stackexchange.com/q/3222792/418542).
Answer: Start with the Taylor expansion
$$
u(x,t+k)=u(x,t)+u_t(x,t)k+\frac12u_{tt}(x,t)k^2+...
$$
Use the PDE to convert time into space derivatives, $u_t=-[f(u)]_x$, then
\begin{align}
u_{tt}&=-[f(u)]_{xt}=-[f'(u)u_t]_x\\
&=[f'(u)[f(u)]_x]_x\\
\end{align}
Now realize this derivative structure using symmetric divided differences and a half-step scheme. Let the index denote the offset in $x$ direction in units of $h$
$$
[f'(u)[f(u)]_x]_x=\frac{f'(u_{+1/2})[f(u_{+1/2})]_x-f'(u_{-1/2})[f(u_{-1/2})]_x}h
$$
The $x$ derivatives at the half-steps are again approximated using central divided differences with step size $h/2$,
$$
[f'(u)[f(u)]_x]_x=\frac{f'(u_{+1/2})\frac{f(u_{+1})-f(u)}h-f'(u_{-1/2})\frac{f(u)-f(u_{-1})}h}h
$$
and finally the midpoint arguments of the derivative of $f$ by $u$ can be approximated by the mean of the neighboring integer grid values, $u_{\pm 1/2}=\frac12(u+u_{\pm 1})$.
If one inserts this in backwards, using the full-step central derivative for the degree-1 term, $[f(u)]_x=\frac{f(u_{+1})-f(u_{-1})}{2h}$ one gets back to the given formula of the method.
Comment: Could you check your equations please! I think it should be $\frac{f(u)-f(u_{-1})}h$ for $[f'(u)[f(u)]_x]_x$. Or am I wrong?
Comment: @jan.sende : Thank you, that was correct, the index was not shifted after copying the expression.
Answer: Just one more comment, which you probably know. The problem of the Lax-Wendroff scheme is that it contains zero numerical viscosity and therefore it cannot filter out oscillation which the scheme produces due to its second order approximation. For the practical use I recommend the TVD or ENO schemes, which are more sofisticated.
Comment: Are you missing a factor in your original equation? $u_t=-f'(u)u_x$
Comment: What wikipedia writes could be shortened as $u_t=-[f(u)]_x$. What you wrote reads as $u_t=-\frac{df}{du}(u)$, which is not the same.
Comment: You are right, I have to adapt the derivation a bit.


php create certificate signing request into file error/warning

Question: I need to create a certificate signing request to file but last line give error when run:
Warning: openssl_csr_export_to_file() expects parameter 1 to be resource, boolean given

Any idea? this is the code, it's php 7.04 - wamp.

    <?php
    $subject = array(
    "commonName" => "example.com",
    );
    $private_key = openssl_pkey_new(array(
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
    ));

    $csr = openssl_csr_new($subject, $private_key, array('digest_alg' =>
    'sha384') );
     openssl_pkey_export_to_file($private_key, 'example-priv.key');
     // Along with the subject, the CSR contains the public key corresponding to
     // the private key
    openssl_csr_export_to_file($csr, 'example-csr.pem');

Comment: Look at the manual for `openssl_csr_new`. It returns `false` if it fails. You haven't checked for that so later calls get a Boolean when they expect a resource.
Answer: Corrected:
$subject = array(
    "commonName" => "example.com",
);

// vars to make private key
$private_key = openssl_pkey_new(array(
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA
));

// in config you put path to openssl.cnf
$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$csr = openssl_csr_new($subject , $private_key,  $Configs );

openssl_pkey_export_to_file($private_key, 'priv.key');

// openssl_csr_export_to_file($csr, 'example-csr.pem');
// better to specify path
openssl_csr_export_to_file($csr, 'C:/wamp/example-csr.pem' );

/*
or view it:
openssl_csr_export($csr, $csrout);  //  and var_dump($csrout);
echo $csrout;
*/

Answer: Improved but not sure yet if all steps result in correct keys/files (someone can look at it?):
<?php
echo '
'; error_reporting(E_ALL); ini_set('display_errors', '1');

$dn = array(
    "countryName" => "GB",
    "stateOrProvinceName" => "Greater London",
    "localityName" => "London",
    "organizationName" => "XY Ltd",
    "emailAddress" => "email@example.com"
);

$Configs = array(
    'config' => 'C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf',
    'digest_alg' => 'sha2',
    'x509_extensions' => 'v3_ca',
    'req_extensions' => 'v3_req',
    'encrypt_key' => true,
    'encrypt_key_cipher' => OPENSSL_CIPHER_3DES
);

$privateKey = openssl_pkey_new([
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
    "private_key_bits" => 2048,
    "private_key_type" => OPENSSL_KEYTYPE_RSA,
]);

openssl_pkey_export($privateKey, $privKey, null, [
    "config" => "C:/wamp/bin/php/php7.0.4/extras/ssl/openssl.cnf",
]);

$a_key = openssl_pkey_get_details($privateKey);

// print_r($a_key);
// print_r($privKey); // Just to test output

file_put_contents('keys/public.key', $a_key['key']);
file_put_contents('keys/private.pem', $privKey);

$csr = openssl_csr_new($dn, $private_key, $Configs);
// var_dump($csr);

openssl_csr_export_to_file($csr, 'C:/wamp/www/php/keys/public.csr' );

openssl_free_key($privateKey);


$A$, $B$ and $C$ can do a ...

Question: $A$, $B$ and $C$ can do a piece of work in $30$, $40$ and $50$ days respectively. If $A$ and $B$ work in alternate days started by $A$ and they get the assistance of $C$ all the days, find in how many days the whole work will be finished?
My Attempt:
In $30$ days, $A$ does $1$ work.
In $1$ day, $A$ does $\frac {1}{30}$ work.
In $40$ days, $B$ does $1$ work.
In $1$ day, $B$ does $\frac {1}{40}$ work.
In $50$ days, $C$ does $1$ work.
In $1$ day, $C$ does $\frac {1}{50}$ work.
In $1$ day, $(A+C)$ do $\frac {4}{75}$ work.
In $1$ day, $(B+C)$ do $\frac {9}{200}$ work.
I could not solve from here. Please help.
Answer: Suppose there are $\;x\;$ days $\;A+C\;$ work together, and $\;y\;$ days $\;B+C\;$ work together, then
$$\frac{4x}{75}+\frac{9y}{200}=1\stackrel{\cdot600}\implies 32x+27y=600$$
There are, of course, infinite solutions, but we'd like $\;x,y\;$ to be positive integers, and this restricts seriously the possibilities: $\;x=12\;,\;\;y=8\;$ fulfill the conditions.
Further explanation: since $\;32x\;$ is always even, observe that $\;y\;$ must be even too.
I'm now paying attention to the data that the working days are alternating, and thus Pieter21's solution is the way to go, though there is no "exact* number of full work days.
Comment: Could you please explain.how did you get the values of $x$ and $y$?
Comment: @user354073 In this particular case, by try and error...and some estimation. As we need that $\;32x=600-27y\;$, check the very first **even** values of $\;y\;$ .... Observe that you won't have to go very high as the values wanted are *positive* , and $\;27\cdot22\;$ is close already to $\;600\;$ , so at most you'll need to check $\;\frac{22}2=11\;$ multiples of $\;27\;$ .
Answer: Divide the work in $600$ pieces (the least common multiple of the dividers).

$A$ does $\frac{600}{30} = 20$ pieces a day every other day.
$B$ does $\frac{600}{40} = 15$ pieces a day every other day.
$C$ does $\frac{600}{50} = 12$ pieces each day.

So alternating, $32 = 20+12 = A + C$, and $27 = 15+12 = B + C$ pieces of work get done each day.
We need to get $600$ pieces of work done, and because of the alternation, we get $59 = 32+27$ pieces done in two days.
After $\lfloor{\frac{600}{59}}\rfloor = 10$ alternations ($20$ days), $10$ pieces are left ($600 - 59 \times 10$).
The final $10$ pieces get done in $1$ day, as it is less than $32$.
So in total: $21$ days.
Comment: I did not understand? Could you please clarify a bit more?
Comment: I edited the answer. If still not clear, please try to explain which part is not clear.
Comment: How did you get: Adoes 20 a day every other day,B
does 15 a day every other day, and C
does 12 each day.?
Comment: @Pieter21 You've been a member for over two years and have posted some 139 answers. I think it is about time to learn how to type with MathJax, lest your answers will go unappreciated because it is hard to read them.
Answer: A takes-> 30 days, B takes-> 40 days, C takes-> 50 days
Total unit of work they have to finish is(LCM of 30,40,50) i.e 600 units
It means
A does -> 20 unit of work in 1 day, B does -> 15 unit in 1 day and C does 12 units in 1 day.
On 1st day A+C does 32 units out of 600, On 2nd day B+C does next 27 units of remaining work.
It means they do 59 unit of work in 2 days. In 20 days 590 units will be done by them. Remaining 10 units are done by A+C in \frac{10}{32}$$ days.
Total days they took to finish the work 600/59 =10 \frac{5}{16}$$ = 20 \frac{5}{16}$$ days.

$A$, $B$ and $C$ can do a ...


criar barra de menu no topo fixa

Question: Queria saber como faço para criar uma barra de menu fixa no topo, ao lado de um menu lateral, que quando rolar a div do conteudo tanto o menu lateral quando o do topo continuem fixos. Segue o html e css de modelo.

@charset "UTF-8";

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  font-family: 'Arial', sans-serif;
}

body{
   background-color: #f3f5f9;
}

.wrapper{
  display: flex;
  position: relative;
}

.wrapper .sidebar{
  width: 250px;
  height: 100%;
  background: #363636;
  position: fixed;
}

.wrapper .sidebar h2{
  color: #fff;
  text-transform: uppercase;
  text-align: center;
  padding: 15px;
}

.wrapper .sidebar ul li{
  padding: 15px;
  border-bottom: 1px solid #bdb8d7;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  border-top: 1px solid rgba(255,255,255,0.05);
}

.wrapper .sidebar ul li a{
  color: #bdb8d7;
  display: block;
}

.wrapper .sidebar ul li a .fas{
  width: 25px;
}

.wrapper .sidebar ul li:hover{
  background-color: #594f8d;
}

.wrapper .sidebar ul li:hover a{
  color: #fff;
}

.wrapper .sidebar .social_media{
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}

.wrapper .sidebar .social_media a{
  display: block;
  width: 40px;
  background: #594f8d;
  height: 40px;
  line-height: 45px;
  text-align: center;
  margin: 0 5px;
  color: #bdb8d7;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.wrapper .main_content{
  width: 100%;
  margin-left: 200px;
}

.wrapper .main_content .header{
  padding: 21px;
  background: #4169E1;
  color: #fff;
  border-bottom: 1px solid #e0e4e8;
  position: fixed;
  width: 100%;
}

.wrapper .main_content .info{
  margin: 20px;
  color: #717171;
  line-height: 25px;
}

.wrapper .main_content .info div{
  margin-bottom: 20px;
}

@media (max-height: 500px){
  .social_media{
    display: none !important;
  }
}
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="css/menu-principal.css">

  <title></title>

Logo

Home

Ativos

About

portfolio

Blogs

Contact

Map

Welcome!! Have a nice day.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Comment: Importante você [edit] seu post e explicar detalhadamente o problema, descrevendo o que tentou e onde está a dificuldade atual, de preferência com um [mcve]. Estudar a postagem disponível neste link pode fazer uma diferença muito positiva no seu aproveitamento do site: [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70)
Answer: Cara tem várias formas de fazer a mais prática é colocar positin:fixed na sidebar, isso já deixa ela fixa na rolagem.
Depois na navbar vc coloca position:sticky e top:0 para ela ficar fixa na rolagem, basicamente é isso. Tb tem que dar um padding-top: 60px; na classe .info para o conteúdo não ficar por baixo da navbar.

Código da imagem acima

  @charset "UTF-8";

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
  text-decoration: none;
  font-family: 'Arial', sans-serif;
}

body{
   background-color: #f3f5f9;
}

.wrapper{
  display: flex;
  position: relative;
}

.wrapper .sidebar{
  width: 250px;
  height: 100%;
  background: #363636;
  position: fixed;
}

.wrapper .sidebar h2{
  color: #fff;
  text-transform: uppercase;
  text-align: center;
  padding: 15px;
}

.wrapper .sidebar ul li{
  padding: 15px;
  border-bottom: 1px solid #bdb8d7;
  border-bottom: 1px solid rgba(0,0,0,0.05);
  border-top: 1px solid rgba(255,255,255,0.05);
}

.wrapper .sidebar ul li a{
  color: #bdb8d7;
  display: block;
}

.wrapper .sidebar ul li a .fas{
  width: 25px;
}

.wrapper .sidebar ul li:hover{
  background-color: #594f8d;
}

.wrapper .sidebar ul li:hover a{
  color: #fff;
}

.wrapper .sidebar .social_media{
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
}

.wrapper .sidebar .social_media a{
  display: block;
  width: 40px;
  background: #594f8d;
  height: 40px;
  line-height: 45px;
  text-align: center;
  margin: 0 5px;
  color: #bdb8d7;
  border-top-left-radius: 5px;
  border-top-right-radius: 5px;
}

.wrapper .main_content{
  width: 100%;
  margin-left: 250px;
  position: sticky;
  top: 0;
}
.sidebar{
  position: fixed;
}

.wrapper .main_content .header{
  padding: 21px;
  background: #4169E1;
  color: #fff;
  border-bottom: 1px solid #e0e4e8;
  position: fixed;
  width: 100%;
}

.wrapper .main_content .info{
  margin: 20px;
  color: #717171;
  line-height: 25px;
  padding-top: 60px;
}

.wrapper .main_content .info div{
  margin-bottom: 20px;
}

@media (max-height: 500px){
  .social_media{
    display: none !important;
  }
}

Logo

Home

Ativos

About

portfolio

Blogs

Contact

Map

Welcome!! Have a nice day.

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Lorem ipsum dolor sit, amet consectetur adipisicing elit. A sed nobis ut exercitationem atque accusamus sit natus officiis totam blanditiis at eum nemo, nulla et quae eius culpa eveniet voluptatibus repellat illum tenetur, facilis porro. Quae fuga odio perferendis itaque alias sint, beatae non maiores magnam ad, veniam tenetur atque ea exercitationem earum eveniet totam ipsam magni tempora aliquid ullam possimus? Tempora nobis facere porro, praesentium magnam provident accusamus temporibus! Repellendus harum veritatis itaque molestias repudiandae ea corporis maiores non obcaecati libero, unde ipsum consequuntur aut consectetur culpa magni omnis vero odio suscipit vitae dolor quod dignissimos perferendis eos? Consequuntur!

Comment: perfeito cara, muito obrigado pela explicação, sou novo com programação web e entendo muito pouco de css,mas eu necessito aprender para desenvolver um projeto pra facul, aproveitando o post você sabe como posso me aperfeiçoar em css, alguma fonte boa pra estudos..
Comment: @Rickkdinho cara se a resposta resolveu seu problema considere marca-la como aceita nesse ícone ✔ abaixo das setinhas do lado da minha resposta, assim ela não fica aberta mesmo já tendo sido resolvida. Estude sobre `position` vai te ajudar muito!
Comment: Feito amigo, tbm não sabia da setinha, sou novo aqui tbm hehe, vlws!!!
Comment: @Rickkdinho sem problemas vlw a força

criar barra de menu no topo fixa


link and Id compare

Question: When C=0 the line block, is there other way to compare Id than Id.ToString().Contains(Id.Tostring())
if (events_sL.Count != 0)
{
    int c;
    for (c = 0; c < events_sL.Count; c++)
    {
        var a = (from s in db.Booked_s
                 where s.IdEvent.ToString().Contains(events_sL[c].EventId.ToString())
                 select s).ToList();
    }
}

Throws error as

Linq to Entities doesn t recognized, the method
  WebApplication.Models.Event get_Item(Int32)
Comment: is there any error getting?
Comment: the error say: Linq to Entities doesn t recognized, the method WebApplication.Models.Event get_Item(Int32).
Comment: one more thing, you have one events_sL[c].eventId at the time but many s.IdEvent=events_sL[c].eventId
Comment: What exactly are you trying to compare? What is `s.IdEvent`? What is `events_sL[c].EventId`? Are you trying to see if one is a substring of the other?
Comment: many users can booked a event. So i try to get the booked in relation to one or many event. s.IdEvent = book.IdEvent
Comment: That still doesn't make any sense. What is `s.IdEvent`? Why are you trying to compare it by converting it to a string? What is `event_sl[c]` and why are you trying to determine if it's a substring of the `s.IdEvent`? How is your data actually structured? Are you trying to join two tables?
Comment: ok, i just want to compare two tables of guid and get the object if the guid is the same.
Answer: As it is, you're trying to have events_sL[c].EventId.ToString() converted into SQL, but the LINQ provider doesn't know how to do that.  You want to just evaluate that value in memory, and then use the result in the query:
var foo = events_sL[c].EventId.ToString();//todo give better name
var a = (from s in db.Booked_s
         where s.IdEvent.ToString().Contains(foo)
         select s).ToList();

link and Id compare


Prefill taxonomy term reference field while in term page

Question: I have a content type A with a required term reference field (vocabulary: category, widget: radios). I would like to accomplish the following:
In every term page (of this specific vobaulary) i will have an "add type A" link.
When the node/add form appears (upon clicking on this link) i want the value of taxonomy term reference field to already be chosen as the category term which corresponds to the specific term page. Ideally i would like the above and also to dissapear this field from the form.
Any help?
Answer: There is a module for this and it's called Entity reference prepopulate.
Comment: I checked this module, but it does not seems to support term reference fields. Am I missing something?
Answer: When you define the field for the content type, you can set a default. Then you can use the Fields Permissions module to restrict access to the field the the admin role. If the user does not possess the required role, they will not have access to the field on the edit form.
Comment: Hi thanks for your answer although i believe you haven't understood my requirement. It's not a matter of defining a default value nor accessing the field afterwards. My main goal is: the value of the term ref. field to automatically be chosen when adding a node, depending on the url (basically the tid) of the term page. Secondary i would like this field not to show up at all in the node form since it's already predefined. Hope i explained it thorough enough for you.
Comment: Field Permissions is the only way to hide the field from users (user 1 will always see it). If you are not working with a fixed default, you migh either use a PHP snippet to enter the default, or define a Rule to grab the required term when the node is created.


How to extract a table from a website using BeautifulSoup?

Question: I'm wanting to extract the FIPS code for each county in Louisiana from this website using beautiful soup and create a Pandas Dataframe: https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697
The columns would be FIPS, Name, and State. I've tried finding by tr, td, and table when I inspect the element, but I don't know how to single out just the main data and then put it into a pandas dataframe. Once I find the specific table, it should be easy to do something like:
if state == 'LA':
     # put data into a dataframe

import requests
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'html.parser')
# print(soup)
for county in soup.find_all('table'):
    print(county.text)

Answer: You can select
 with class="data" and then use pd.read_html. For example:
import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
df = pd.read_html(str(soup.select_one(".data")))[0]
# filter State == 'LA'
print(df[df.State == "LA"].head())

Prints:
       FIPS        Name State
1109  22001      Acadia    LA
1110  22003       Allen    LA
1111  22005   Ascension    LA
1112  22007  Assumption    LA
1113  22009   Avoyelles    LA

Answer: There is one table so can iterate over the
 elements in that one table.
If want a data frame to include only one particular state then can filter it before adding to a data frame, or filter the data frame of all data for a subset data frame.
import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://www.nrcs.usda.gov/wps/portal/nrcs/detail/la/technical/cp/?cid=nrcs143_013697"
html_text = requests.get(url).text
soup = BeautifulSoup(html_text, 'html.parser')
data = []
for tr in soup.find('table', class_='data').find_all('tr'):
    row = [td.text for td in tr.find_all('td')]
    # If want to filter out all except LA then can do that here
    if len(row) == 3 and row[2] == 'LA':
        data.append(row)
df = pd.DataFrame(data, columns=['FIPS', 'Name', 'State'])
print(df)

Output:
     FIPS          Name State
0   22001        Acadia    LA
1   22003         Allen    LA
2   22005     Ascension    LA
3   22007    Assumption    LA
4   22009     Avoyelles    LA
..    ...           ...   ...
63  22127          Winn    LA

Comment: Perfect. Thanks! I've used beautifulsoup a lot, but I feel like I've never be able to quickly solution things like this.


Centered Grid - Inner Grid align left - NO Javascript - NO Medias Queries

Question: [EDIT]
I'm looking for a solution without javascript, and without medias queries (user can change the container size).
[/EDIT]
I need to create a grid of items.

The container has a flexible width.
The grid is always centered
Items inside the grid need to be left aligned

Pretty simple, but I can't find the solution !!
Here is an image that present what I need:

And here is a jsfiddle : http://jsfiddle.net/5e4bcc9L/1/
HTML :

CSS :
.container {
    width: 100%;
    background-color:#CCC;
    text-align: center;
}
.grid {
    background-color:#999;
    display: inline-block;
    text-align: left;
}
a {
    display:inline-block;
    height: 100px;
    width: 100px;
    background-color:#000;
    margin: 5px;
}

Comment: possible duplicate of [Center grid of inline-block elements in div, but last row is aligned with left edge of grid](http://stackoverflow.com/questions/19527104/center-grid-of-inline-block-elements-in-div-but-last-row-is-aligned-with-left-e) <-- provides CSS and JS solution to your issue.
Comment: Forgot to mention that i'm looking for a No Javascript, No Medias Queries (user can change my container width).
But maybe it's just not possible ?
Answer: Given that you don't want to use JavaScript or media queries, this is tough to achieve exactly the way you want. The problem lies in the fact that you're setting exact heights and widths of your blocks within the grid. I'll explain more:
Centered grid with left alignment
CSS (keeping HTML the same)
.container{
    width: 100%;
    height:100%;
    background-color:#CCC;
    text-align:center;
}

.grid{
    background-color:#999;
    display: inline-block;
    position:relative;
    width: 80%;
    border:1px solid black;
}

.grid a{
    display:inline-block;
    height: 100px;
    width: 100px;
    background-color:#000;
    margin: 5px;
    float:left;
}

.ghost{clear: both;}

If you look at the fiddle, it works the way you described...until you resize the window. That's because the blocks in the grid can't float until there's enough space for them to do so, which leaves you with an "incorrectly" (to you) sized block.
If the left alignment standard can be dropped, you get a much more pleasant experience as far as centered content is concerned as demonstrated here. Simply comment out the float in the CSS above to see what I mean.
Otherwise, the link web-tiki gave above is probably the best option.


How to configure nginx docker image to serve angular and allow page refresh?

Question: I have seen countless examples of people saying just paste
location / {
        try_files $uri $uri/ /hockey/index.html =404;
    }

or
location / {
        try_files $uri $uri/ /index.html =404;
    }

...or some other combination such as using $args etc, to get angular routes to load on page refresh. But none of these solutions are working for me.
Can someone tell me if I am doing something wrong? The page loads initally. Here's an example request from the console log:
"GET /login HTTP/1.1" 404

Snippet from nginx.conf, literally only change is the added line:
server {
    listen       80 default_server;
    listen       [::]:80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        try_files $uri $uri/ /hockey/index.html =404;
    }

[snipped]
I have also omitted the /hockey and done a bunch of other things...
Dockerfile
FROM node:14.4.0-alpine3.12 AS builder
COPY . ./hockey
WORKDIR /hockey
RUN npm install
RUN npm install -g @firstname.lastname@example.com
RUN ng build --aot=false --prod --build-optimizer=false --base-href=/

FROM nginx:1.17.1-alpine
COPY ./nginx.conf /etc/nginx/nginx.conf
COPY --from=builder /hockey/dist/hockey/ /usr/share/nginx/html

If anyone has any idea what combination I need (is my base-href correct etc?) please let me know!
Answer: Maybe try something like
location / {
  root /usr/share/nginx/html;
  index index.html index.htm;
  try_files $uri $uri/ /index.html =404;
}


AngularJS + Domain/URL Redirect not working well together

Question: I got a small angularJS based website.
I am hosting it via the service OpenShift on some domain like:
bla-blubb.rhcloud.com

Which is of course not that pretty, so I ordered a TLD:
www.supercoolsite.com

from www.united-domains.de. There I habe three possibilities to achieve my goal, see the screen (sorry it is in German - it is: 1) Header redirect, 2) Frame-redirect or 3) URL-Hiding)

But none of these seem to work like I want:
1) Simply redirects the user, so the ugly URL is shown again.
2) Shows my pretty URL, BUT I can't type in like /#/stuff/some/page, it simply does nothing and remains on the start screen. My ngRoute $routeProvider's .when() doesn't trigger that URL like it normally does.
3) Here everything works just fine. I can use Angualr as I'm used to, the above error disappears + the URL is still pretty. BUT: Now I can't send POST Requests with payload to my Java Spring MVC Backend. I get an 415 Error (See second Screen). When using the ugly URL it works perfectly (Everything). It also works using GET methods.

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Does anyone might have an idea? How can I get 2) or 3) working? I don't get what's going wrong.
If code (angular or Spring Controller) is needed, tell me - but as said, it works under DEV and when using the ugly URL.
Thanks!!
Answer: A solution for me was to use another (sub) domain like admin.supercoolsite.com, which does a frame redirect to the /#/stuff/some/page URL, automatically triggering my intended behavior.


Rotate SVG gradient based on mouse position

Question: I'd like to rotate the gradient of an svg based on the mouse position.
The mechanic should be as followed, where [0,0] is the mouse being in the upper left corder of the window, [100%,0] should be the mouse in the upper right corner of the window etc.

What I have so far is that the angle changes on mouse position (only mouseX) but not based on my desired mechanic:
https://codepen.io/magglomag/pen/YzKYLaa
The svg gradient is defined like this:
<defs>
    <linearGradient gradientTransform="rotate( X, 0.5, 0.5 )" id="gradient" gradientUnits="objectBoundingBox">
      <stop offset="0.4" style="stop-color:#33FF8F"/>
      <stop offset="0.6" style="stop-color:#5A33FF"/>
    </linearGradient>
</defs>

The manipulation of the angle is realized by changing the X in the gradientTransform attribute with JS:
$( 'body' ).mousemove( function( e ) {

    mouseX = e.pageX - this.offsetLeft;
    mouseY = e.pageY - this.offsetTop;

    xy = mouseX;

    $( 'svg defs' ).html( '<linearGradient gradientTransform="rotate(' + xy + ', 0.5, 0.5 )"  id="gradient" gradientUnits="objectBoundingBox"><stop offset="0.4" stop-color="#33FF8F"/><stop offset="0.6" stop-color="#5A33FF"/></linearGradient>' );

});

Besides I'd like to add a bit of easing so the change is not that hard. Here's an example I found which uses easing. Not in combination with a gradient angle change but with a movement but perhaps the underlying code might be helpful: https://www.kirupa.com/canvas/mouse_follow_ease.htm
Any help is much appreciated.
Comment: Could you create an interactive example? Surely the SVG is not so big as to not fit in the question or on jsFiddle.
Comment: Hi @TomášZato, there's already one on Codepen: https://codepen.io/magglomag/pen/YzKYLaa
Answer: All you need is a bit of math. You need center point of the SVG image and then angle between the mouse and that point:
Relative to <svg>
  // position of mouse
  mouseX = e.pageX - this.offsetLeft;
  mouseY = e.pageY - this.offsetTop;
  // client rect of the gear
  const svgRoot = document.querySelector("#mysvg");
  const rect = svgRoot.getBoundingClientRect();
  // center point is x+width/2 and y+height/2
  const midx = rect.left + (rect.right - rect.left)/2;
  const midy = rect.top + (rect.bottom - rect.top)/2;
  // angle
  const angle = Math.atan2(midy - mouseY, midx - mouseX);
  // The transform uses degrees (0-365), not radians (0 - 2PI)
  const angleDeg = angle* 180 / Math.PI

Demo: https://codepen.io/MXXIV/pen/OJLzEOV
Relative to window
  // position of mouse
  mouseX = e.pageX - this.offsetLeft;
  mouseY = e.pageY - this.offsetTop;
  // center point is x+width/2 and y+height/2
  const midx = window.innerWidth/2;
  const midy = window.innerHeight/2;
  // angle
  const angle = Math.atan2(midy - mouseY, midx - mouseX);
  const angleDeg = angle* 180 / Math.PI

Demo: https://codepen.io/MXXIV/pen/eYOyjdP
Comment: Well, all you need is to set `midx = window.innerWidth/2`
Comment: Nah. No `rect` needed at all, that was for angle from the svg center. Think about it, the left side of the window is `x=0`, the right one is `x=window.innerWidth` so the middle is `window.innerWidth/2`. Same for height.
Comment: @shrys Check the updated example to see it work. Note that `innerWidth` is needed, not outer. Otherwise it wouldn't work in iframes and the likes.
Comment: @user1706680 I'd just extract the code from my answer into some function, then call it from the code copied from the article you linked. Try to play around with it, if it doesn't work, you can ask another question and somebody, maybe me, will help you fix it. But I think you can do it.
Comment: Thanks a lot for that! I just realized I was kind of imprecise regarding the mouse position. In your solution the gradient directly reacts to the mouse's angle towards the gear (which is also a nice mechanic) but I meant the mouse position in relation to the whole viewport. So when the mouse is in the upper left corner the gradient's angle is 45deg, in the upper right corner of the viewport it is 135deg, in the lower right corner 225deg and in the lower left corner 315deg.
Comment: Hi @TomášZato, shouldn't it be `window.innerWidth/rect.width`, as the distances need to be scaled?
Comment: Not that you did not already helped me lots but do you also have a clue about the easing I mentioned in my original post?
Answer: You could use atan2 as follows to get the angle in radians and convert it into degrees by multiplying 180 / Math.PI:

$('body').mousemove(function(e) {
  var {
    left: offsetX,
    top: offsetY
  } = $('svg').offset();
  centerX = $('svg').width() / 2 + offsetX;
  centerY = $('svg').height() / 2 + offsetY;
  mouseX = e.pageX - centerX;
  mouseY = e.pageY - centerY;

  xy = Math.atan2(mouseY, mouseX) * (180 / Math.PI);
  $('svg defs').html('<linearGradient gradientTransform="rotate(' + xy + ', 0.5, 0.5)"  id="gradient" gradientUnits="objectBoundingBox"><stop offset="0.4" stop-color="#33FF8F"/><stop offset="0.6" stop-color="#5A33FF"/></linearGradient>');

});
svg {
  width: 150px;
  height: 150px;
}

body {
  height: 100vw;
  width: 100vw;
}

<svg x="0px" y="0px" viewBox="0 0 150 150">

  <defs>
    <linearGradient gradientTransform="rotate( 0, 0.5, 0.5 )" id="gradient" gradientUnits="objectBoundingBox">
   <stop  offset="0.4" style="stop-color:#33FF8F"/>
   <stop  offset="0.6" style="stop-color:#5A33FF"/>
    </linearGradient>
  </defs>

  <path class="st0" d="M149.3,89.5l0.7-24.6l-15.7-0.5c-1-5.4-2.8-10.8-5.3-16l12.4-9.7l-15.4-19.3l-12.4,9.7 c-4.4-3.6-9.3-6.6-14.5-8.8L102.2,5L77.9,0l-3.2,15.3c-5.6,0-11.3,0.8-16.8,2.4L50.4,4L28.5,15.6L36,29.4 c-4.4,3.7-8.2,7.9-11.3,12.6L10,36.2L0.8,59.1l14.7,5.8c-1,5.5-1.2,11.2-0.5,16.8L0,86.5l7.8,23.4l15-4.9c2.9,5,6.5,9.4,10.5,13.2 L25,131.5l21.2,12.9l8.3-13.3c5.3,1.9,10.9,3.1,16.6,3.4l2.3,15.4l24.6-3.6L95.7,131c2.6-1,5.2-2.1,7.8-3.5c2.5-1.4,4.9-2.9,7.2-4.5 l11.8,10.4L139,115l-11.8-10.4c2.8-4.9,4.9-10.2,6.3-15.6L149.3,89.5z M90,102.7c-15.4,8.2-34.7,2.5-43.1-12.8 c-8.3-15.3-2.5-34.4,12.9-42.6c15.4-8.2,34.7-2.5,43,12.8C111.2,75.3,105.4,94.4,90,102.7z"/>
</svg>
Comment: Thanks a lot for that! I just realized I was kind of imprecise regarding the mouse position. In your solution the gradient directly reacts to the mouse's angle towards the gear (which is also a nice mechanic) but I meant the mouse position in relation to the whole viewport. So when the mouse is in the upper left corner the gradient's angle is 45deg, in the upper right corner of the viewport it is 135deg, in the lower right corner 225deg and in the lower left corner 315deg.


Displaying nhiberbate components in asp.net

Question: I'm working on an ASP.NET/C#/fluent nHibernate project and have recently discovered the Component mapping feature that I would like to implement.  I believe I have my class definitions and mapping file correct, but I am having difficulty retrieving the component information with my service and/or repository layers to display it in a DetailsView or FormView.
When I use an ObjectDataSource to retrieve the information, the aspx code that is generated in the corresponding view puts the whole component in a TextBox:
<asp:TextBox ID="extraTextBox" runat="server" Text='<%# Bind("extra") %>' />

I have found numerous resources online of how to do the mapping itself, but haven't been able to find more guidance on properly displaying the component pieces.  Any guidance would be appreciated!
// Stripped down classes
public partial class ProjectExtra
{
    private int _test1;
    private int _test2;

    public ProjectExtra() {}

    public virtual int test1 { get { return this._test1; } set { this._test1 = value; } }
    public virtual int test2 { get { return this._test2; } set { this._test2 = value; } }
}

public partial class Project
{
    private int _pkProjectID;
    private ProjectExtra _extra;

    public Project() {}

    public virtual ProjectExtra extra
    {
        get
        {
            return this._extra;
        }
        set
        {
            this._extra = value;
        }
    }
    public virtual int pkProjectID
    {
        get
        {
            return this._pkProjectID;
        }
        set
        {
            this._pkProjectID = value;
        }
    }
}

// stripped down mapping
public class ProjectMap : ClassMap<Project>
{
    public ProjectMap()
    {
        Table(@"Project");
        LazyLoad();
        Id(x => x.pkProjectID)
          .Column("pkProjectID")
          .Access.Property()
          .Not.Nullable()
          .GeneratedBy.Identity();

        Component<ProjectExtra>(x => x.extra, m =>
        {
            // JobsCreatedActual and JobsCreatedEstimate are two integer columns
            // in the Project database table
            m.Map(x => x.test1).Column("JobsCreatedActual");
            m.Map(x => x.test2).Column("JobsCreatedEstimate");
            Not.LazyLoad();
        });
    }
}

Answer: To do this, I ended up using the following format:
<asp:TextBox ID="extraTextBox" runat="server"
Text='<%# Eval("extra.test1") %>' />

I have seen other resources using the full DataBinder, though the results seem to be the same:
<asp:TextBox ID="extraTextBox" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "test1"))%>' />

Unfortunately, Bind does not work with subclasses, so they still need to be constructed in code-behind using TextBox values, etc.


Views: displaying related (referenced) content in a block

Question: I tried solving the following with "node_reference" and "entityreference" modules but failed.
I have the content types recipe and cook. A recipe has a mandatory field which points to a cook.
When Drupal renders a recipe I want to have a block on the sidebar (implemented via "views") which will be displaying info on the recipe's cook.
How can the block know which recipe is being rendered on screen in order to use the relationship and pull the cook's data as fields which I'll use for display within the block?
thanks
More info: The problem is that in the block I'm getting all referenced (from recipes) cooks and not just the one cook for the specific recipe. So for the following data:
recipe#1 -> cook#1
recipe#2 -> cook#1
recipe#3 -> cook#1
recipe#4 -> cook#2

When I visit any of the recipes the block displays data from:
cook#1
cook#1
cook#1
cook#2

Answer: You would need to add a relationship from the reference field in views (under advanced > relationships). This will extend the scope of fields available to the view include those of the referenced node (Cook).
However this will as you state show all cooks as it will come from all recipes. In order for the block to know how to filter out all irrelevant cooks (ones not referenced) you will need a contextual filter which knows what recipe you are currently on.
On this contextual filter you can specify the relationship to the one you have already created, then you will need to let the block view know which recipe you are on. You do this with the setting "provide default value" and "Content ID from URL". This will tell the view which content you are on and hopefully apply the filter. Sorry I do not have access to D7 right now for a better explanation
Comment: The problem is that in the block I'm getting all referenced cooks and not the cook for the specific recipe. Would I need anything special in the "Filter Criteria" section?
Comment: How many recipes do you have referencing a cook? Because the view might need some filtering of the actual recipes if there are too many. Try filter down to a single recipe and you should then ONLY have the cook from which this single recipe refers to.
Answer:
Create a Block views display.
Add "Filter Criteria" of Content: Type and select (tick) your "Recipe" content type.
Add "Relationship" (may need to expand "Advanced" fieldset on your Views edit screen), and for your Cook reference field that exists in your "Recipe" node type. Afterwards, any fields such as Content: Title should have a Relationship dropdown on their settings screen. Make them use this new Relationship you just added. (I beleive you got up to this part judging from other answers' comments. Here's the key part:)
Add "Contextual Filter" and select Content: Nid field, and on the field settings set "WHEN THE FILTER VALUE IS NOT AVAILABLE" to "Provide default value" and set the "Type" to "Content ID from URL".

Now when you visit a Recipe page that has this block somewhere, or if you put a Recipe content's Nid into the Views preview arguments box you should get the Cooks for that Recipe.
Comment: YES! That's it. Thanks a lot. I knew I was somehow missing the "current node" filtering.


AWS Fargate networking - port 80: Connection refused

Question: I'm trying to communicate two services in Fargate, and when service A calls service B using the Route 53 name (not the IP) it says port 80: Connection refused.
In order to see what is going on I connected through SSH to an EC2 instance in the same vpc and everything works when I do the request using the private IP:port, but fails when I use the Route 53 name.
To me looks like I'm missing a step to either link the Route 53 name to the private IP:8080 instead of private IP:80 or, more likely, to redirect from port 80 to 8080 within the service B host.
Any idea on how to solve this?
Thanks!
Comment: So far it sounds like you're trying to communicate between ECS services without going over the internet. And from what you explained you want to do the ECS equivalent of docker links. Is that correct? I'm pretty sure that the docker link route won't work unless the containers are within the same task. https://stackoverflow.com/questions/34517265/linking-containers-between-task-definitions-in-aws-ecs
Comment: @JaronF Thanks for the link. The approved answer there says "ECS also has integration with Route 53 Auto Naming for DNS-based service discovery using A and SRV records. Your service's tasks can be automatically entered into and removed from DNS records." I want something like that, as for me would be important that both services work independently and don't need to be in the same host, so in the same task.
Answer: Is service B running on port:8080? If so, then you might have to set that in the dns record type field when adding the service autodiscovery. Put your record type as srv & select either just the port or both the container and the port here. This should allow you to connect to service B.
Another way you could do this is by using a load balancer to your service. Now you can access the service B using the load balancer DNS and potentially use route53 to map the load balancer url to some domain you have. Since you can make a load balancer internal this can be entirely private.
Comment: Hi @MasterFowl, thanks. I tried already adding the SRV record and then I can access service B as desired if I use , but this makes service A aware of the port (8080) in which service B runs. I would like to use just .
Comment: It doesn't look like there is a way to configure the port mapping in route 53. If you want to make a clean call (without the port) to the container, why not use a load balancer. Map the load balancer URL to a domain which you can create. You can then have a port which the load balancer is listening (80) and communicate with the task using some other port (8080).
Also, do you have any idea which tasks your requests go to if you use service discovery on a service with multiple tasks?


Get image's URL as a token for use in Views' replacement pattern

Question: I need to get an image's full URL path as a token that I can use as a replacement pattern in Views.
I'm trying to have one thumbnail image link to a larger image.  I have the larger image excluded from view so I can use it as a token.  When I try to export the thumbnail image as a link using the larger image's token, the token is apparently the  tag instead of the path.
I think I can do this if I change the field type of the larger image to a File, but I want the benefits that come with the Image type (cropping, scaling, etc).
Answer: I ended up using a module to create a custom formatter.  Image URL Formatter http://drupal.org/project/image_url_formatter .  It created a new formatter option called "Image URL," and I can use that as a token.
Answer: Old, but I think:
[node:IMAGEFIELD_TOKEN:file:url]

would do it
of in case of a multiple image field:
[node:IMAGEFIELD_TOKEN:IMAGEFIELD_IDX:file:url]

Where

IMAGEFIELD_TOKEN is your image field token, like field-image, field-images, etc.
IMAGEFIELD_IDX (for multiple fields) is your 0-based index. 0 for the first image, 1 for the second and so on.
Comment: Found it when doing this with media entity you need to replace underscores with hyphens: https://www.drupal.org/project/metatag/issues/1334256#comment-10418391
Answer: The contents of the token in this case is controlled by the formatter that renders the image. Perhaps the formatter has a setting to render the image as a direct link instead? I haven't tried doing this in Drupal 7, but with imagefield in D6 there was a direct link option.
If not, the best way to solve this is to add such a formatter.
Comment: Great, thanks for the tip.  I ended up using a module to do this.  Image URL Formatter (http://drupal.org/project/image_url_formatter).  It created a new Formatter option called "Image URL," and I can use that as a token.
Comment: Glad you got it working. :) You should post that as an answer though, so you can accept it and the question becomes answered. Or it will remain in the "unanswered questions" queue forever.
Comment: Ha, gotcha.  I was just wondering if I did that right...
Comment: It certainly sounds right, and the answer that works for _you_ is by definition the one you should accept. I would just have thought no extra module was necessary.
Comment: From what I've read, I believe they took the image path formatter option away in Drupal 7?  The only option under "Formatter" that I saw was "Image."  I wasn't sure how to manually create a custom formatter, so I went with the module.


Por que fatorial acima de 170 retorna infinito?

Question: Fiz este código php para calcular o fatorial de números inteiros positivos , porém , para números a partir de 170 o resultado é sempre infinito e gostaria de entender o porque disso.

    ex3

 $numero_usuario = isset($_POST['a'])?$_POST['a']:0;
 $fatorial = $numero_usuario;

 if($numero_usuario == 0){
   echo $numero_usuario;
 }
 if($numero_usuario > 0){
   while($fatorial!=1){
       $fatorial--;
       $numero_usuario *= $fatorial;

   }
   echo $numero_usuario;
 }
 ?>

Comment: Porque os tipos numéricos tem um limite máximo, e se o cálculo ultrapassa esse limite, o resultado é "infinito"
Comment: 171! = 1.2 × 10^309 > 1.8e308 (o máximo valor de double) (https://www.wolframalpha.com/). Se você precisa calcular fatoriais grandes, vai precisar de número de ponto flutuante com precisão arbitrária. Mas se você está calculando arranjos e combinações, calcule os quocientes primeiro.
Comment: (e adicione um epsilon no final para corrigir o arredondamento do processador).
Answer: No SOen você pode encontrar uma resposta sobre isso, que eu adaptei e adicionei algumas coisas que encontrei pesquisando:
O que acontece é que você está ultrapassando a precisão de um double em um sistema 64bits. Essa precisão varia entre 10^−308 e 10^308. Em valores aproximados:

Fatorial de 170: 7.25741562 * 10^307 (dentro do limite de precisão)
Fatorial de 171: 1.24101807 * 10^309 (fora do limite de precisão, então "infinito")

Então é recomendado você utilizar uma extensão capaz de fazer esse tipo de multiplicação. Uma das possibilidades é a BCMath (BCMath Arbitrary Precision Mathematics), que foi a que encontrei o pessoal utilizando para multiplicação de valores grandes (com a função bcmul).
Adaptando seu código:
while($fatorial!=1){
    $fatorial--;
    $numero_usuario = bcmul($numero_usuario, $fatorial);
}

Fato interessante: pesquise pelo fatorial de 170 no Google e depois pelo fatorial de 171:
Comment: Muito obrigado!!!!
Answer: O fatorial com um valor baixo já retorna um valor muito alto, veja
10! = 3.628.800
170 está ultrapassando o limite de memória de alocação estipulado pela Linguagem de Programação.
Veja o exemplo da Linguagem C:
pt.wikibooks.org/wiki/Programar_em_C/Tipos_de_dados
As demais linguagens seguem da mesma maneira, mas cada uma com o seu tamanho de alocação específico.
Comment: `170!` Não ultrapassa o limite de memória da máquina, não faz nem cosquinha(diminutivo de cosca, forma sincopada de cócega).
Comment: É isso que tem que ser explicado na resposta. Da maneira que escreveu dá a entender que o fatorial consumiu toda a RAM.
Comment: Pode até ser que o da memória RAM não, mas excede o espaço do tamanho que a Linguagem de Programação usa para alocar a variável na memória. Cada tipo variável tem um tamanho máximo suportado.

Veja um exemplo da linguagem C:
https://pt.wikibooks.org/wiki/Programar_em_C/Tipos_de_dados

No entanto, todas as linguagens possuem as suas limitações.
Comment: Sim, me expressei errado. Obrigado pela comentário Augusto Vasques. Informação corrigida.


Can you use relative prediction intervals to compare models trained on a different response

Question: Is there a reason not to use a relative prediction interval ( PI/target_value, for a constant PICP) to compare models with different target variables?
Answer: This is perfectly fine since the information given by the interval is not changed by this transformation.


How do i obtain foreign table field using string value for fieldname with reflection and entity framework

Question: I have 2 tables.  An asset table that links using a foreign key to a device table.
To get the device_name field of the asset, in linq i would use:
dim device as string = result.device.device_name

The Result object contains the unique record from an earlier linq to entity framework command.
Now I have a need to allow end users to specify their fields they want in a report.  I will end up having a string name of the field, so tried using reflection
dim name as string = result.GetType().GetProperty("asset_name").GetValue(result)

This returns the asset_name field so i thought great, i should be able to get the relating foreign table field value.
dim device = result.GetType().GetProperty("device").GetValue(result).GetType.GetProperty("device_name").GetValue(result.device)

This works however i had to specify the object.  As i will have other tables linking to the first table, would i have to write additional code to check what object and manually specify?  Or am i going into this wrongly?  Any help and advice appreciated.
Answer: I couldn't find a cleaner solution, so this is how i did it:
dim field as string ="device.device_name"
dim output as string =""
dim subtable as string =""

If field.Contains(".") Then
    subtable = field.Substring(0, field.IndexOf("."))
    field = field.Substring(field.IndexOf(".") + 1)
End If
If subtable <> "" Then
  Select case subtable
    Case "device"
        If Not IsNothing(result.device.GetType().GetProperty(field)) Then
            output = result.device.GetType().GetProperty(field).GetValue(result.device)
        End If
  End Select
Else
    If Not IsNothing(result.GetType().GetProperty(field)) Then
        output= result.GetType().GetProperty(field).GetValue(reult)
    End If
End If
Return output


$(\mathbb{Z}_{n}^{*},.)$ is a group $\iff n$ is prime.

Question: Here $\mathbb{Z}_{n}^{*}$ means $\mathbb{Z}_{n}-{[0]_{n}}$
My attempt:
$(\leftarrow )$
$p$ is a prime, then, for every $[x]_{n},[y]_{n},[z]_{n}$ $\in (\mathbb{Z}_{n}^{*},.)$ are verified the following:
1) $[x]_{n}.([y]_{n}.[z]_{n}) = ([x]_{n}.[y]_{n}).[z]_{n}$, since from the operation . we have $[a]_{n}.[b]_{n}=[a.b]_{n}$ and . is associative in $\mathbb{Z}$.
2) There is an element $e$ such that $[x]_{n}.e = e.[x]_{n} = [x]_{n}$, since $ [x]_{n}.[1]_{n} = [x.1]_{n} = [x]_{n} = [x.1]_{n} = [x]_{n}[1]_{n}$
But I don't know how to check the inverse property, neither how to do the $(\rightarrow)$ part.
Thanks!
Comment: For the inverse use euclidian algortihm, it gives for $gcd(x,y)=1$ an equation $ax+by=1$. For the $\rightarrow$ part suppose $n$ isn't prime, $d\mid n$ and calculate $d\cdot n/d$.
Answer: Assume $n$ is composite.
Then $n=ab$ for some $a,b\in\{2,\dots,n-1\}$.
Take one of them, for example $a$.
Consider the residue class $[a]$.
If $\mathbb{Z}_n^*$ was a multiplicative group, then $[a][c]=[1]$ for some $c$.
It means that $ac\equiv 1\pmod{n}$, but since $n=ab$, it implies that $1$ is divisible by $a$.
Contradiction!
Answer: $\impliedby$ If $n$ is prime, then it is coprime to every non-zero element, hence $gcd(a, n) = 1$ for all $a \in \mathbb{Z}\setminus\{0\}$. This implies $as + nt = 1$ for some $s, t \in \mathbb{Z}$ by Bézout's identity. It follows that $[a][s] = [1]$, hence every non-zero element in $\mathbb{Z}_n$ is invertible.
$\implies$ If $n$ is not prime, then it has a positive divisor $x$ which is neither $1$ nor $n$. We then have $xy = n$ for some $y \in \mathbb{N}, y < n$, so $[y] \neq [0]$. This means $[x][y] = [0]$. Now assume, $[x]$ had an inverse $[x]^{-1}$. Then we have $[x]^{-1}([x][y]) = [0]$ and by the associative law $[y] = [0]$, which is a contradiction.


TypeError: SET_NULL() missing 4 required positional arguments: 'collector', 'field', 'sub_objs', and 'using'

Question: How do i solve the above error which shows up not during the makemigrations but during migrate in Django.
<code>class Comment(models.Model):
    #comment_id=models.IntegerField(primary_key=True)
    name=models.CharField(max_length=100, default="No Comment Added")
    comment_created=models.DateTimeField(auto_now_add=True)
    task=models.ForeignKey(task_check, on_delete=models.SET_NULL, null=True )
    task_records=models.ForeignKey(task_check_Records, on_delete=models.CASCADE, null=True, default=models.SET_NULL)
    def __str__(self):
        return self.name
</code>
Comment: Probably you want to set your FK field to a **`null`**, if so, set **`default=None`** instead of **`default=models.SET_NULL`**
Comment: if you need to deal with it, set `blank=True` too
Comment: @ArakkalAbu You got me right, I tried that , still the error prevails. Also if I set default=None  while filling the form it still asks me for a value to be filled for task_records.
Answer: Remove files from app_name/migrations and migrate after makemigrations again.
Comment: Is there anyway you can clarify your answer and/or possibly include command line examples?


How to implement a scratch card / view in react-native?

Question: I'm looking for a package to implement a scratch card in react-native. I have found this library https://github.com/thebylito/react-native-scratch-card but the problem is that it works only on android. Is there a library that works on both iOS and android, or can I implement this in pure javascript?
Answer: You can use a library I made: react-native-scratch
npm install react-native-scratch --save

This library supports both Android and iOS and enables you to use multiple scratch views in your app, for example - a FlatList with scratch cards.
Other functionality includes:

Autofill the containing view to cover its content until you scratch
User defined background color to use while the image is loading
You can set an image from a url or from a resource file in your application (or no
image at all)
Image resize modes are supported (stretch/cover/contain)
User defined brush size and scratch threshold
Touch events (to stop a ScrollView/FlatList from scrolling while scratching)
Progress report while scratching
Fade animation (optional) when the scratch view reaches its
scratch threshold
Comment: can you send the link to this repo?
Comment: him can you send a link please? i am having trouble using https://github.com/Vivify-Ideas/react-native-scratch in a scroll view
Comment: This is the link github:
https://github.com/ConduitMobileRND/react-native-scratch
Answer: UPD 2022
Try this library https://www.npmjs.com/package/rn-scratch-card
It's implemented for Android and iOS.
Answer: You can use this https://github.com/romangua/react-native-scratch-view library to implement the scratch card for both iOS and android.
Install it by running
npm install react-native-scratch-view --save

After that link it
react-native link react-native-scratch-view

In case if you get 404 not Found error in your terminal after running the install command. You can do this:
1- Open your package.json file
2- In your dependencies do something like this:
"dependencies":{
    "react-native-scratch-view": "romangua/react-native-scratch-view",
}

3- Run npm install after this and you can use it directly in your project by using import ScratchImageView from 'react-native-scratch-view';
I am using the same library for both Android and iOS and it's working on both.
Hope this helps!!
Comment: that's great thank you. I had tried previously to npm install this package and I was getting the 404 Error, and I had even opened an issue about it on their GitHub repo. It didn't come to my mind to change it from the package.json file.

Another workaround to download this package which I did was:

`npm install romangua/react-native-scratch-view --save`
Comment: locate the package.json file in your project and just paste the dependencies line like above in that file and then run npm install it will be installed automatically