Assess density of a function in non-closed form

Question: I am working with Rice's Mathematical Statistics and Data Analysis and on page 179 it introduces Monte Carlo integration. This question is a smallish revision based on comments from @Iterator (in R chatroom on stackoverflow.com).
What I'm trying to show the law of large numbers
$I(f) = E[f(X)]$
where $I(f) = \frac{1}{\sqrt{2 \pi}} \int_{0}^1 e^{-\frac{x^2}{2}}$
and
$f(X) = \frac{1}{n} \frac{1}{\sqrt{2 \pi}} \sum_{i=1}^{n} e^{- \frac{x^2}{2}}$.
 Note that this is a normal distribution.
I am thus trying to estimate integral of $I(f)$ on the interval $[0, 1]$, which yields
integrate(dnorm, lower = 0, upper = 1)
0.3413447 with absolute error < 3.8e-15

and compare that to $E[f(X)]$, which gives similar results
mean(sapply(1:1000, function(z, n = 1000) {
        randn <- runif(n = n, min = 0, max = 1)
        ihat <- (1/n) * (1/sqrt(2 * pi)) * sum(exp(-(randn^2)/2))
        return(ihat)
    }))
[1] 0.3413853

So I wanted to give the above function for calculating $E[f(X)]$ a field test. Density of the normal distribution on $[0, 1.96]$ is about $0.475$ (95% CI)
integrate(dnorm, lower = 0, upper = 1.96)
0.4750021 with absolute error < 5.3e-15

times $2$ gives roughly $0.95$. Check!
When I try to apply similar logic for $f(X)$, my function squats and returns something else
mean(sapply(1:1000, function(z, n = 1000) {
        randn <- runif(n = n, min = 0, max = 1.96)
        ihat <- (1/n) * (1/sqrt(2 * pi)) * sum(exp(-(randn^2)/2))
        return(ihat)
    }))
[1] 0.24224

I'm not exactly sure what's going on here. Any tips on what am I doing wrong, failing to get ~$0.475$ for the last expression?
Comment: Imagine you try to integrate the constant function $f(x) = 1$ on the interval $[0, 1.96]$. You will sample 1000 values $x_1, \dots, x_n$ in this interval, compute the mean of the $f(x_i)$, which is 1. The value of the integral is 1.96! Do you see now what's going on?
Answer: It's a bit late (Henry's answer has been accepted!), but I'll aggregate my comments in one answer, with one additional comment on the use of standard error.

The simplest thing to integrate is a constant function $f(x) = 1$, let's say on $[0, 1.96]$. You will sample $n=1000$ values $x_1,\dots,x_n$ uniformly in this interval, and compute the mean of the $f(x_i)$, which is 1. But you want to compute $\int_0^{1.96} 1 \mathrm dx = 1.96$...
In fact you've been computing [an approximation of]
$$ E\left( f(X) \right) = \int_{-\infty}^{+\infty} f(x) \phi(x) \mathrm dx,$$
where $\phi(x)$ is the density of the sampling distribution; here $\phi(x)$ is
$$\phi(x) = \left\{ \begin{array}{ll}0 &\text{if } x\notin [0,1.96] \\
{1\over 1.96} &\text{if } x\in [0,1.96], \end{array}\right.$$
hence you've been computing ${1\over 1.96} \int_0^{1.96} f(x) \mathrm dx$. This shows you how to rectify your computation, just multiply by 1.96.
Consider the random variables $Y_i = f(X_i)$. They are independent, identically distributed; by the central limit theorem, their mean (your estimation of $E(Y)$ which is, up to multiplication by a constant, the quantity of interest) are normally distributed. You can thus get a confidence interval on $E(Y)$ using the sample standard error
$s$: the standard deviation of the mean is $\simeq s/\sqrt n$.

Illustration with a piece of R code (for 95% CI).
> x <- runif(10000, 0, 1.96)
> y <- dnorm(x)
> 1.96*mean(y)
[1] 0.4744983
> 1.96*(mean(y) + c(-1,1)*1.96*sd(y)/sqrt(length(y)) )
[1] 0.4701337 0.4788629

Comment: Both are great answers, too bad I can't accept both. Thank you.
Answer: Your code returns an estimate of the average density over the interval.  The average density is not the integral, unless the interval is of length 1 as in the first example.
To emphasis Elvis's point, note
> 0.24224*1.96
[1] 0.4747904

Comment: Explicitely, you're computing $$ \int_0^{1.96} f(x) \phi(x) \mathrm d x$$ where $\phi(x)$ is the density of the uniform distribution on $[0, 1.96]$; so you compute
$$ {1\over 1.96}  \int_0^{1.96} f(x) \mathrm d x.$$


What music theory do I need to play the piano

Question: Hope you had a blessed Christmas.
I am 60 and started learning the piano 5 years ago. I have a full time demanding job so have little time, but manage to practice about an hour a day. I always believed I was too old to learn but now know this isn't the case but recognise my restrictions.
Can someone advise as to what theory I would benefit from learning in addition to learning my classical pieces. I don't want to compose or give recitals. I play for my own pleasure.
Peaceful New year to you.
Comment: What theory do you **need**? None. What theory would be **helpful**? Any and all of it. I've yet to discover a downside to learning theory.
Comment: As you learn to play, you pick up an intuitive grasp of concepts for which you'll learn theory has names. A keyboard instrument is ideal for learning and applying theory, since it is designed to play chords, melody and harmony, and makes it easy to visualize intervals, study patterns and scales, etc.
Comment: Difficult to point out specifics, but have a look at ABRSM grades, theory. They sort of follow the practical side of the exams, so things that crop up will align with where you are playing-wise. I guess you're in U.K.
Comment: My grandmother started playing piano by ear at the age of 85 or something. AFAIK she didn't know any music theory, and didn't ask anyone for help, she just sat down and started to play. It wasn't about reading, just playing melodies of songs she knew. What do you want to achieve? Do you want to perform pieces to an audience... to get social status? Or do you want to make sounds that make you feel good? Do you want to express yourself? Accompany songs and sing together with someone? The piano keyboard comes with a lot of theory built in - the arrangement of white and black keys.
Comment: @chembluebtinternetcom - what activities do you actually want to do? e.g. do you want to play by studying scores? Sight-read? Improvise? compose? There are lots of different things you can do on the piano - different parts of theory might help more (or less) with each.
Answer: The simple answer is: none.  Music theory describes the patterns in which music is created and manipulated.  If you are playing from score sheets, those patterns are relevant in how scales are built up, but the mapping from scales to fingers is practised in scale exercises and as long as they are spelt out (not containing "etc" or "go through all keys" or similar instructions), that does not concern you.
You need to look at sightreading skills, of course, like remembering how accidentals are written down and how long they last.  That is not strictly music theory, but the patterns of possible key signatures you need to recognise are limited again because of music theoretical reasons.
Things are entirely different if you are not (solely) playing from score sheets but are trying to play by ear, or by changing stuff like transposing or accompanying in a different way or filling in material from chord symbols.  In that case, the patterns that music theory describe are not something that you will eventually get a bit of a hang of just by playing but are something that you need to acquire as a separate skill.
In a way, a statement like "I don't know any music theory, I just play by ear" is a contradiction, particularly when accompaniment comes into play.  The actual skill allowing you to gloss over music theory a lot is sightreading.
Comment: Bit of a Catch 22. There are theory facts that need to be known in order to sight-read properly. And sight-reading helps learn pieces, but is only a small part of that learning.


Unique solution of the Cauchy problem in the neighbourhood of the given set $\Gamma$

Question: The Cauchy problem $ \begin{cases}y\frac{\partial u}{\partial x}-x\frac{\partial u}{\partial y}=0 \\
u=g  \;on \;\Gamma \end{cases}$
has a unique solution in a neighbourhood of $\Gamma$ for every differentiable function $g:\Gamma \to R\; if \\ 1. \Gamma =\{(x,0):x\gt 0\} \\ 2. \Gamma =\{(x,y):x^2 +y^2=1\} \\3.\Gamma =\{(x,y):x+y=1,x\gt 1\}\\4. \Gamma =\{(x,y):y=x^2,x\gt 0\}$
My Attempt: I solved the pde by taking $\frac{dx}{y}=\frac{dy}{-x}=\frac{du}{0}\\ u(x,y)=F(x^2+y^2)$
I don't know how to check the uniqueness in the neighbourhood of the given set. Thanks
Comment: Are your sets $\Gamma$ correct? I guess the $(x,0)$ should be $(x,y)$ for 2,3,4. Moreover, in case 2. the solution is not unique.
Comment: yes thanks. now i corrected it
Comment: @stb2084 how to check the uniqueness of the solution in the neighbourhood of $\Gamma$. i don't know about this.
Answer: In case 1. , you've derived
\begin{eqnarray}
g(x,0) = u(x,0) = F(x^2 + 0^2) = F(x^2).
\end{eqnarray}
Hence $F(w) = g(\sqrt{w})$ ($w>0$). Therefore
\begin{eqnarray}
u(x,y) = F(x^2 + y^2) = g\left(\sqrt{x^2 + y^2}\right).
\end{eqnarray}
Comment: For $r>0$ let $t(r)$ be the positive solution of the equation $t^2 + t^4 = r$ of $t$. Then $u(x,y) = g\left( t(x^2 + y^2), t(x^2 + y^2)^2 \right)$.
Comment: Then in case 2. g(x,y)=F(1). hence it do not have unique solution. What about case 4? I am not getting case 4.


Selecionar apenas um RadioButton com Razor

Question: Tenho 2 Radio Buttons, e gostaria que quando eu marcasse um, o outro desmarcasse.
Segue a imagem do que está ocorrendo:

Código:
@Html.RadioButton("teste", "teste", true) Teste
@Html.RadioButton("concessionaria", "concessionaria", false) Concessionária

Comment: Voce pode usar o attr('checked', true) true ou false no caso.
Answer: Coloque assim:
@Html.RadioButton("teste", "teste", true)
@Html.RadioButton("teste", "concessionaria")

Porque os input type radio devem possuir o mesmo nome, sendo a sua diferença pelo value.
Exemplo com form:
<form action="/Estudo/Post" method="post" enctype="multipart/form-data">
        @Html.RadioButton("teste", "teste", true)
        @Html.RadioButton("teste", "concessionaria")
        <button>Enviar</button>
</form>

Renderizado Html:
<form action="/Estudo/Post" method="post" enctype="multipart/form-data">
        <input checked="checked" id="teste" name="teste" type="radio" value="teste" />
        <input id="teste" name="teste" type="radio" value="concessionaria" />
        <button>Enviar</button>
</form>

Observe que os dois possui o mesmo nome com value diferentes que podem ser recuperados pela método Post.
Recuperando pelo Método Post
public ActionResult Post(string teste)
{
      return View();
}

Debug:


shell script read arrays and parse the array value to a function

Question: I have 2 arrays as follows:
Array1 -  ( val1 val2 val3 val4 val5 )
Array2 -  ( user1 user2 user3 user4 user5 )

I have one function for each value in array1. ex: Functionval1, Functionval2, Functionval3...
Now I need a shell script which will read array1 and call respective function as well as pass the respective value of Array2 to the function.
Ex: Read val1 from Array1, for val1 call Functionval1 and pass user1 to the function.
Could you please help me in building logic.
Regards,
Siva.
Answer: You could loop over the array indices and call each function and its arguments respectively.
Array1=( val1 val2 val3 val4 val5 )
Array2=( user1 user2 user3 user4 user5 )

for i in ${!Array1[@]}; do
    "Function${Array1[$i]}" "${Array2[$i]}"
done

Consider a test script like this:
#!/bin/ksh
Functionval1 (){
    echo "this is a test $1"
}
Functionval2 (){
    echo "this is another test $1"
}

Array1=( val1 val2 )
Array2=( user1 user2 )
for i in ${!Array1[@]}; do
    "Function${Array1[$i]}" "${Array2[$i]}"
done

Output:
this is a test user1
this is another test user2

You could also rewrite the script to do the same thing, without using ${!...[@]} syntax.
Array1=(val1 val2)
Array2=(user1 user2)
arr_len=${#Array1[@]}
let arr_len--
for i in $(seq 0 $arr_len); do
    "Function${Array1[$i]}" "${Array2[$i]}"
done

Note that you'd have to adjust this for shells like zsh that initiate their first array element to index 1.
Comment: Hi John,  Thanks a lot this script worked. Now I am able to parse the array values to the function and call the required function. Going forward I will make sure that I will post the environment am using.
Comment: Hi John, am using ksh. I tried this logic and it is failing with error "${!Array1[@]}: 0403-011 The specified substitution is not valid for this command.
Comment: This worked for me using Ksh93 and lksh.  See my update.  It's also good to include in the post exactly what shell you're using.
Comment: You're welcome, I'm glad it worked, and welcome to StackOverflow.  If you think this answer is best, you can click the outlined checkmark ✔ next to the answer.
Answer: #!/bin/bash

# functions defined here, e.g Functionval1 etc.

#....

# Array declarations

declare -a Array1=( val1 val2 val3 val4 val5 )
declare -a Array2=( user1 user2 user3 user4 user5 )

# get length of Array1
array1length=${#Array1[@]}

for (( i=0; i<${#Array1[@]}; i++ ));
do
   function_to_run="Function${Array1[$i]}" # E.g. function_to_run becomes Functionval1
   function_parameter=${Array2[$i]} # E.g. function_parameter becomes user1
   $function_to_run $function_parameter # E.g. Functionval1 user1
done

You could do it without declaring function_to_run and function_parameter, but it is a little easier to understand when using them.
Comment: Why offset the array indexes? `for (( i=0; i<${#Array1[@]}; i++ )); do` is cleaner and index arithmetic goes away. All array indexes can be represented with `[$i]` in this case.
Comment: @David - You are totally correct. I have modified it accordingly.
Comment: Hi Warwick, Thanks for the reply.  Sorry for another question. I am a new to shell script and for got to mention that I need ksh script. Could you please help me. Also in above script we are capturing the length of the array1 to array1length.. but we are not using the var in the script. please correct me if I am wrong
Comment: See my alternative answer for using with `ksh`. We only capture the length of the array so that we know how many times to iterate, but the script above will work as expected for `bash`. It will call `Functionval1, Functionval2...`
Answer: The Korn Shell version:
#!/bin/ksh

# functions defined here, e.g Functionval1 etc.

set -A Array1 val1 val2 val3 val4 val5
set -A Array2 user1 user2 user3 user4 user5

# get length of Array1
Array1length=${#Array1[@]}

i=0
while (( $i < $Array1length ))
do
   function_to_run="Function${Array1[$i]}"
   function_parameter=${Array2[$i]}
   $function_to_run $function_parameter
   i=$i+1
done


How to host material icons offline?

Question: My apologies if this is a very simple question, but how do you use google material icons without a
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

?
I would like my app to be able to display the icons even when the user does not have an internet connection
Comment: This article explains for Angular, thought might be helpful for someone, https://thecodeframework.com/host-google-material-icon-fonts-locally-in-angular-in-5-simple-steps/
Answer: Method 2. Self hosting Developer Guide

Release 4 changed things a bit, please investigate recommended
formats and hosting solution.

Download release 3.0.2 from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases
You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.

Replace the source in the url attribute of @font-face, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")

@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
   src: local('Material Icons'),
        local('MaterialIcons-Regular'),
        url(iconfont/MaterialIcons-Regular.woff2) format('woff2'),
        url(iconfont/MaterialIcons-Regular.woff) format('woff'),
        url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

face

NPM / Bower Packages
Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1
Using bower : bower install material-design-icons --save
Using NPM : npm install material-design-icons --save
Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/

Note

It seems google has the project on low maintenance mode. The last
release was, at time of writing, 3 years ago!
There are several issues on GitHub regarding this, but I'd like to
refer to @cyberalien comment on the issue Is this project actively maintained? #951 where it refers several community projects that
forked and continue maintaining material icons.
Comment: Solved my problem … I just wanted to note out that we only need the `iconfont` folder from the whole archive.
Comment: target your local folder in the source url of @font-face : url( "iconfont/MaterialIcons-Regular.woff2" -- updated answer
Comment: How would you do this for a phone GAP app where you would not have a domain?
Comment: Hey, Can you please make an updated answer of this. I have downloaded my mdl icons with npm.
Comment: for this type of "move cdn resource to be served locally" it usually would pay off to have a solid over 3000 requests average response time data BEFORE and AFTER the change - you would be surprised how-often it is not worth it, regardless of your effort to achieve it ...
Comment: `material-design-icons` is not really usable anymore, it is missing a lot of icons and the installing process sometimes freezes.
Comment: In 2020 there was an update to a new version (4.x). I downloaded the older source code on https://github.com/google/material-design-icons/releases/tag/3.0.2 which matches the css given above.
Comment: One issue: the stylesheet references four different font formats (.eot, woff, woff2 and ttf) but the Github repo only has ttf. Opening the CSS from Google Fonts in a browser directly will give you a link to the woff2, but that's all a bit hackish and still no source for eot and woff. (I did check Google's official documentation, and it is not helpful either.) Any ideas?
Comment: Release tagged 3.0.2 still holds the different formats https://github.com/google/material-design-icons/tree/3.0.2/iconfont
Answer: I'm building for Angular 4/5 and often working offline and so the following worked for me.  First install the NPM:
npm install material-design-icons --save

Then add the following to styles.css:
@import '~material-design-icons/iconfont/material-icons.css';

Comment: when call "npm install" wait wait wait lol... but works after long time
Comment: any idea how to add outlined icons?
Comment: It turns out the google repository is not well maintained. The solution I found is to use npm install material-design-icons-iconfont, a fork of the google repository with many fixes and performance improvements.
Comment: @wutzebaer You can use the material-icons package. FMI https://github.com/marella/material-icons#readme
Comment: @SergioCabral Luckily you made the comment about waiting, cause there were about 5 times I thought this install isn't going anywhere...  :)
Comment: Thank You Loved It This Is Best Solution Thank You <3
Comment: Working for me also... :)
Comment: I followed the npm directions above and all works great, except I am missing two icons: toggle_off and toggle_on. I suspect the npm repo might not be up to date?
Comment: When I use npm install it takes a long time, and then adds no new files to my AspNetCore project. Did anyone have a similar problem?
Comment: the `npm install @material-design-icons/font@latest` package is way lighter. import with `@import '@material-design-icons/font';` [docs](https://github.com/marella/material-design-icons/tree/main/font#usage)
Answer: The upper approaches does not work for me.
I download the files from github, but the browser did not load the fonts.
What I did was to open the material icon source link:
https://fonts.googleapis.com/icon?family=Material+Icons
and I saw this markup:
    /* fallback */
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  -moz-font-feature-settings: 'liga';
  -moz-osx-font-smoothing: grayscale;
}

I open the woff font url link https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2
and download the woff2 file.
Then I replace the woff2 file path with the new one in material-icons.css
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
  src: local('Material Icons'),
       local('MaterialIcons-Regular'),
       /* Old file: url(iconfont/MaterialIcons-Regular.woff2) format('woff2'), */
       /* load new file */
       url(2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2) format('woff2'),
       url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

That makes thing works for me.
Comment: @ Kaloyan Stamatov would be nice to share that git repo.. since lot of people have issue with outdated official repo :)
Comment: more up to date in 2019, this solution worked for me as well.
Comment: Thanks! I had the same issue and this fixed it for me.
Comment: I solve my issue with this approach, but later I found another git repo, from where I get the proper release.
Comment: @Grashopper, I do not have it anymore. Sorry
Comment: this is the only way to get the latest icons that I could find...
Comment: in 8/2020 latest v55 link:  https://fonts.gstatic.com/s/materialicons/v55/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2
Comment: i had to install npm package `npm i material-design-icons` then edited: `apps\appName\src\styles.css` and added the content of the file: `\node_modules\material-design-icons\iconfontmaterial-icons.css` but i had to change the fonts path to be of this format: `url('~material-design-icons/iconfont/MaterialIcons-Regular.woff2')` (added the qutes ' and prefix: `~material-design-icons/iconfont/` before each file name )
Comment: @Shaybc check the date on the npm package. It's old! It's best to get the fonts directly from Google fonts as Kaloyan says above. Or you can get them from GitHub.
Answer: As of 2020, my approach is to use the material-icons-font package.
It simplifies the usage of Google's material-design-icons package and the community based material-design-icons-iconfont.

Install the package. npm install material-icons-font --save
Add the path of the package's CSS file to the style property of your project's angular.json file.
...
"styles": [
    "./node_modules/material-icons-font/material-icons-font.css"
],
...
If using SCSS, copy content below to the top of your styles.scss file.
@import '~material-icons-font/sass/variables';
 @import '~material-icons-font/sass/mixins';
 $MaterialIcons_FontPath: "~material-icons-font/fonts";
 @import '~material-icons-font/sass/main';
 @import '~material-icons-font/sass/Regular';

Use the icons in the HTML file of your project.
// Using icon tag
face
face
face

// Using Angular Material's <mat-icon> tag
<mat-icon>face</mat-icon>
<mat-icon>add_circle</mat-icon>
<mat-icon>add_circle_outline</mat-icon>

Icons from @angular/material tend to break when developing offline. Adding material-icons-font package in conjunction with @angular/material allows you to use the  tag while developing offline.
Comment: Simple and clean implementation - works perfectly thank you! As the most current and efficient solution, this should be be the accepted answer...
Comment: Is there a way that I can use face offline ie., without changing to face
Comment: I couldn't agree more with @Mike. This is the best implementation. Thank you for sharing!
Comment: The simpliest way, thank you for sharing :)
Comment: FYI this package hasn't been updated since 2020. Material is currently at 4.0.
Answer: If you use webpack project, after
npm install material-design-icons --save

you just need to
import materialIcons from 'material-design-icons/iconfont/material-icons.css'

Comment: I don't recommend doing this, this repo is far too big, use one desc. below https://www.npmjs.com/package/material-design-icons-iconfont I also noticed that browser will cache https://fonts.googleapis.com/icon?family=Material+Icons and it'll work in the offline mode. Checkout https://keemor.github.io/#/
Comment: Such approach is recommended for building an corporate web application which may work in internal network without access to Internet
Comment: I am  newbie in npm can you elaborate `import materialIcons from 'material-design-icons/iconfont/material-icons.css'` . We adding this line to where?
 app.js or somewhere else. I am using framework7 with Vue and I tried. It didn't work for me.
Comment: @SuatAtanPhD you add this import like any other style imports. If you use webpack you need something like style-loader, css-loader and you can place this import anywhere in your js code, for example in index.js or app.js etc.
Answer: This may be an easy Solution

Get this repository that is a fork of the original repository Google published.
Install it with bower or npm
bower install material-design-icons-iconfont --save

npm install material-design-icons-iconfont --save

Import the css File on your HTML Page

or
<link rel="stylesheet" href="node_modules/material-design-icons-iconfont/dist/material-design-icons.css">

Test: Add an icon inside body tag of your HTML File
face

If you see the face icon, you are OK.
If does not work, try add this .. as prefix to node_modules path:
<link rel="stylesheet" href="../node_modules/material-design-icons-iconfont/dist/material-design-icons.css">

Comment: This is the solution that worked for me, except the stylesheet link in index.html didn't work - I had to add an import into my Styles.scss file:

    `@import"../node_modules/material-design-icons-iconfont/dist/material-design-icons.css";`

Then my locally hosted icons leapt into life
Comment: Employing the _material-design-icons-iconfont_ package works even with the Angular's standard `mat-icon` component. Thus the transition is seamless.
Comment: Also, importing into your scss means that it is a build time dependency and you can NPM install --dev to not make it part of the prod node environment footprint.
Answer: To Avoid
npm i material-design-icons
Google isn't publishing any new version to their npm repository, so please avoid using the npm i material-design-icons since the last publish was 5 years ago.
To use

Download the needed font from their repo. you can ignore the .codepoints extension. Be aware, they do not have .woff2 and .woff type anymore, but .ttf or .otf works just fine.
Add them to your assets folder
Into a css file, do add the following

@font-face {
  font-family: 'Material Icons';
  font-weight: 400;
  font-style: normal;
  src: local('Material Icons'), local('MaterialIcons-Regular'),
    url('/assets/fonts/MaterialIcons-Regular.ttf') format('truetype');
}

.material-icons {
  display: inline-block;
  font-family: 'Material Icons';
  font-size: 24px; /* Preferred icon size */
  font-weight: normal;
  line-height: 1;
  font-style: normal;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

Then add the .material-icons class

face

Angular users do not need to add .material-icons if they already use mat-icon
Outline & Regular at the same time
Both, outline & regular one?
Here is the step.
I'm using the scss @extend method for that purpose because I'm lazy.
@font-face {
  font-family: 'Material Icons Outlined';
  font-weight: 400;
  font-style: normal;
  src: local('Material Icons Outlined'), local('MaterialIconsOutlined-Regular'),
    url('/assets/fonts/MaterialIconsOutlined-Regular.otf') format('truetype');
  font-display: fallback;
}

.material-icon {
  // Same content as the previous example without the `font-family`
}

.material-icons {
  @extend .material-icon;
  font-family: 'Material Icons';
}

.material-icons-outlined {
  @extend .material-icon;
  font-family: 'Material Icons Outlined';
}

<mat-icon class="material-icons-outlined" svgIcon="dark_mode-outline"></mat-icon>

Comment: @LeO Glad I could help. I'm not aware of any better solution yet. But feel free to add a comment here if you find anything useful & I'll be glad to update my answer.

I have to say, my bet is  that google will release something with their new icon set & animation. This is one of the reason why this workaround works for now and why I wouldn't invest to much time into it.

Cheers
Comment: Just a question for this: If I want to use `regular` as well as `outline` ==> how to define it in the `font-face`? Just a new entry with the same `font-familiy`? And then how to use the `outline` vs. the `regular` in a ``? Some kind of `font-set`?
Comment: Hi, thx for the very quick and helpful reply. When I follow your link about the repro I find the Material font and a hint for the variablefont. Right now we're using Angular 14 and many of the outlined icons wont work. Therefore I happy to have your solution. Nevertheless the question arise if we should use the variablefont or not. Is there somewhere a useful link about what's the difference, how to use, etc?
Comment: Just for the sake of completeness: One needs to set (in `.material-icon`) the `width` and `height` to `24px` and the `margin` to `0`. Otherwise it might happen that the Icon shrinks too much in a `flex` and some parts are truncated as consequence. Perhaps you can update as well your answer :-)
Answer: Use material-design-icons-iconfont

Full disclosure, I'm the author of this package
Google's material-design-icons project is on low maintenance
  and out of date for a while. There's a gap between the version in
  https://material.io/icons/ and the version in
  material-design-icons.

I've created material-design-icons-iconfont to address these major issues:

material-design-icons jams npm install - all irrelevant svg/xml/... files has been removed
Font files are always up-to-date straight from Google Fonts CDN
Support for scss

Install via npm
npm install material-design-icons-iconfont --save

It depends on how you pack your web application (webpack/gulp/bower/...), you'll need to import the .css/.scss file (and might change the relative fonts path)

Import Using SCSS
Import in one of your sass files
$material-design-icons-font-path: '~material-design-icons-iconfont/dist/fonts/';
@import '~material-design-icons-iconfont/src/material-design-icons';

Later on, reference your desired icon  + icon-id +
contact_support

read the full instructions on material-design-icons-iconfont for more import methods

Demo page
It comes with a light demo page to assist searching and copy-pasting fonts
Comment: I'm having a problem with PWA. Icons are working while you are in browser but once you add shortcut on home screen and run the app icons are not showing.
Answer: My recipe has three steps:

to install material-design-icons package
npm install material-design-icons

to import material-icons.css file into .less or .scss file/ project
@import "~/node_modules/material-design-icons/iconfont/material-icons.css";

to include recommended code into the reactjs .js file/ project
close

Comment: this package not exist any more
Comment: with angular cli, do npm install material-design-icons and then add css in angular.json -> architect->build->styles
Answer: I have tried to compile everything that needs to be done for self-hosting icons in my answer.
You need to follow these 4 simple steps.

Open the iconfont folder of the materialize repository
link-
https://github.com/google/material-design-icons/tree/master/iconfont

Download these three icons files ->
MaterialIcons-Regular.woff2 - format('woff2')
MaterialIcons-Regular.woff - format('woff')
MaterialIcons-Regular.ttf - format('truetype');
Note- After Download you can rename it to whatever you like.

Now, go to your CSS and add this code

@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url(MaterialIcons-Regular.eot); /* For IE6-8 */
  src: local('Material Icons'),
       local('MaterialIcons-Regular'),
       url(MaterialIcons-Regular.woff2) format('woff2'),
       url(MaterialIcons-Regular.woff) format('woff'),
       url(MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

Note : The address provided in src:url(...) should be with respect to the 'CSS File' and not the index.html file. For example it can be  src : url(../myicons/MaterialIcons-Regular.woff2)

You are ready to use now and here is how it can be done in HTML

face

Click here to see all the icons that can be used.
Comment: 404 on your link
Answer: 2019 Update here:
To self host your material icons, the Regular ones, Rounded, Sharp, all the variants.
Go get them from this repo:
https://github.com/petergng/material-icon-font
For some reason I dont know why these fonts are not easily accessible from Google repositories.
But here you go.
After downloading the package, go to bin folder and you'll see the four variants.
Of course, it is up to you to use whichever.
To use them, create a css file and

Generate a font face for each variant you need:

@font-face {
    font-family: 'Material Icons';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/regular/Material-Icons-Regular.eot); /* For IE6-8 */
    src: local('Material-Icons-Regular'),
    url(./icons/regular/Material-Icons-Regular.woff2) format('woff2'),
    url(./icons/regular/Material-Icons-Regular.woff) format('woff'),
    url(./icons/regular/Material-Icons-Regular.ttf) format('truetype');
}

@font-face {
    font-family: 'Material Icons Round';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/round/Material-Icons-Round.eot); /* For IE6-8 */
    src: local('Material-Icons-Round'),
    url(./icons/round/Material-Icons-Round.woff2) format('woff2'),
    url(./icons/round/Material-Icons-Round.woff) format('woff'),
    url(./icons/round/Material-Icons-Round.svg) format('svg'),
    url(./icons/round/Material-Icons-Round.ttf) format('truetype');
}

@font-face {
    font-family: 'Material Icons Sharp';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/sharp/Material-Icons-Sharp.eot); /* For IE6-8 */
    src: local('Material-Icons-Sharp'),
    url(./icons/sharp/Material-Icons-Sharp.woff2) format('woff2'),
    url(./icons/sharp/Material-Icons-Sharp.woff) format('woff'),
    url(./icons/sharp/Material-Icons-Sharp.svg) format('svg'),
    url(./icons/sharp/Material-Icons-Sharp.ttf) format('truetype');
}

The url will link to where the icons are located in your project.

Now lets register the icon classes:

.material-icons-outlined, .material-icons {
    font-weight: normal;
    font-style: normal;
    font-size: 24px;  /* Preferred icon size */
    display: inline-block;
    line-height: 1;
    text-transform: none;
    letter-spacing: normal;
    word-wrap: normal;
    white-space: nowrap;
    direction: ltr;
}

This will make both
.material-icons-outlined,
and
.material-icons classes use the same defaults.
If you want to to use .material-icons-sharp, just append it to the two class names.

Finally, let us plug-in the font face you pulled in from step 1.

.material-icons {
    font-family: 'Material Icons';
}

.material-icons-outlined {
    font-family: 'Material Icons Outline';
}

Again, to use more variant, like Sharp, just add its block like the two above.
Once done...go to your html and use your newly minted icons.
hourglass_empty

phone

Answer: After you have done npm install material-design-icons, add this in your main CSS file:
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url(~/material-design-icons/iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
  src: local('Material Icons'),
       local('MaterialIcons-Regular'),
       url(~material-design-icons/iconfont/MaterialIcons-Regular.woff2) format('woff2'),
       url(~material-design-icons/iconfont/MaterialIcons-Regular.woff) format('woff'),
       url(~material-design-icons/iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

Answer: With angular cli
npm install angular-material-icons --save

or
npm install material-design-icons-iconfont --save

material-design-icons-iconfont is the latest updated version of the icons. angular-material-icons is not updated for a long time
Wait wait wait install to be done and then add it to angular.json -> projects -> architect -> styles
 "styles": [
          "node_modules/material-design-icons/iconfont/material-icons.css",
          "src/styles.scss"
        ],

or if you installed material-desing-icons-iconfont then
"styles": [
              "node_modules/material-design-icons-iconfont/dist/material-design-icons.css",
              "src/styles.scss"
            ],

Answer: On http://materialize.com/icons.html the style header information you include in the page,you can go to the actual Hyperlink and make localized copies to use icons offline.
Here's how.NB: You will download two Files in all icon.css and somefile.woff.

Go to the following URL as required in the header

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> .
Save page as whatever_filename.css. Default is icon.css

Look for a line like this

src: local('Material Icons'), local('MaterialIcons-Regular'), url(https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2)

Visit the URL that has .woff ending it

https://fonts.gstatic.com/s/materialicons/v22/2fcrYFNaTjcS6g4U3t-Y5ZjZjT5FdEJ140U2DJYC3mY.woff2 . Your browser will automatically download it. Save it in your CSS folder.

You should now have the two files icon.css and 2fcrYFNa....mY.wof22, save them both in your css. Now make edits in your css header location to the icon.css in your directories. Just make sure the .woff2 file is always in the same folder as the icon.css. Feel free to edit the long file names.
Answer: The question title asks how to host material icons offline but the body clarifies that the objective is to use the material icons offline (emphasis mine).
Using your own copy of the material icons files is a valid approach/implementation.  Another, for those that can use a service worker is to let the service worker take care of it.  That way you don't have the hassle of obtaining a copy and keeping it up to date.
For example, generate a service worker using Workbox, using the simplest approach of running workbox-cli and accepting the defaults, then append the following text to the generated service worker:
workboxSW.router.registerRoute('https://fonts.googleapis.com/(.*)',
workboxSW.strategies.cacheFirst({
  cacheName: 'googleapis',
  cacheExpiration: {
    maxEntries: 20
  },
  cacheableResponse: {statuses: [0, 200]}
})
);

You can then check it was cached in Chrome using F12 > Application > Storage > IndexedDB and look for an entry with googleapis in the name.
Comment: I got this to work also with some small changes. I changed "workboxSW" to "workbox". I changed "router" to "routing" and added this code into my sw_config.js file that gets generated when using the workbox cli wizard.
Answer: Kaloyan Stamatov method is the best.
First go to https://fonts.googleapis.com/icon?family=Material+Icons. and copy the css file.
the content look like this
/* fallback */
@font-face {
    font-family: 'Material Icons';
    font-style: normal;
    font-weight: 400;
    src: url(https://fonts.gstatic.com/s/materialicons/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2');
}

.material-icons {
    font-family: 'Material Icons';
    font-weight: normal;
    font-style: normal;
    font-size: 24px;
    line-height: 1;
    letter-spacing: normal;
    text-transform: none;
    display: inline-block;
    white-space: nowrap;
    word-wrap: normal;
    direction: ltr;
    -moz-font-feature-settings: 'liga';
    -moz-osx-font-smoothing: grayscale;
}

Paste the source of the font to the browser to download the woff2 file
https://fonts.gstatic.com/s/materialicons/v37/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2
Then replace the file in the original source. You can rename it if you want
No need to download 60MB file from github. Dead simple
My code looks like this
@font-face {
    font-family: 'Material Icons';
    font-style: normal;
    font-weight: 400;
    src: url(materialIcon.woff2) format('woff2');
}

.material-icons {
    font-family: 'Material Icons';
    font-weight: normal;
    font-style: normal;
    font-size: 24px;
    line-height: 1;
    letter-spacing: normal;
    text-transform: none;
    display: inline-block;
    white-space: nowrap;
    word-wrap: normal;
    direction: ltr;
    -moz-font-feature-settings: 'liga';
    -moz-osx-font-smoothing: grayscale;
}

while materialIcon.woff2 is the downloaded and replaced woff2 file.
Comment: Doesn't work on all browsers, see this SO answer for more information: https://stackoverflow.com/questions/11002820/why-should-we-include-ttf-eot-woff-svg-in-a-font-face
Answer: I solved it using this package (@mdi/font) and importing it on main.js:
import '@mdi/font/css/materialdesignicons.css'

Answer: While I was also facing this same challenge on my angular material project, I came up with a working offline solution. save all the details.
After downloading the resource, just follow these steps on the README.md file
STEP 1
Copy the distribution into your project
STEP 2
import the stylesheets in your angular.json imports array
Example
`angular.json [
        {
            style[
                "css/material.css", "css/icons.css"
            ]
        } `

STEP 3
You should see your icons appear offline after your next auto reload.
Optionally, you can comment or take out this line  https://fonts.gstatic.com https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap https://fonts.googleapis.com/icon?family=Material+Icons from your index.html file.
HAPPYCODING :)
I created an offline repository for ngMatIcons you can download it from this link. :)
Answer: Adding this in case it helps someone... This might not work for your use case, but it might work for someone. I have an offline computer where I use an app that uses materialize. I was also trying to solve this problem, but that github repo is huge, and I was having a difficult time following all the instructions. Additionally, the <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> tag was slowing the opening of my app on the offline computer, as it kept trying to download that file, but couldn't.
Here is what I did (working example at the bottom of this comment)

Download the file at https://fonts.googleapis.com/icon?family=Material+Icons and store it as a local css file in your website directory. This file will require one modification, explained in step 3.
Add a <link> tag to index.html pointing to the file you saved in step 1. (For example, I saved https://fonts.googleapis.com/icon?family=Material+Icons to assets/css/materialize_offline_files/materialize-icons.css in my website directory, then added this to index.html: <link href="assets/css/materialize_offline_files/materialize-icons.css" rel="stylesheet"> rel="stylesheet">.) Note: Make sure to add this link tag before your materialize.css imports.
Modification to file from step 1. If you look at the file at https://fonts.googleapis.com/icon?family=Material+Icons, you'll find this line of css code for the fall back font: src: url(https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2');. Download the file at that src url, https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2, save it to the same directory as materialize_icons.css (the file from step 1), and change that line of code to: src: url("flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2") format('woff2');

Working example (4 files):
index.html
<!DOCTYPE html>

    <link href="assets/css/materialize_offline_files/materialize-icons.css" rel="stylesheet">
    <link href="assets/css/materialize.min.css" rel="stylesheet">

    <button class="btn waves-effect waves-light">Hello!
            send
    </button>

assets/css/materialize_offline_files/materialize-icons.css
/*
 * File downloaded from https://fonts.googleapis.com/icon?family=Material+Icons
 * with slight modification (src url of fallback font)
 */

/* fallback */
@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  /**src: url(https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2) format('woff2');*/
  src: url("flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2") format('woff2');
  /**
   * flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2 is the file
   * downloaded from
   * https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2
   * NOTE:: css src url attributes are relative to the css file,
   * so store flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2
   * IN THE SAME DIR as this css file, for that modification to work.
   */
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;
  line-height: 1;
  letter-spacing: normal;
  text-transform: none;
  display: inline-block;
  white-space: nowrap;
  word-wrap: normal;
  direction: ltr;
  -moz-font-feature-settings: 'liga';
  -moz-osx-font-smoothing: grayscale;
}

Finally (remaining 2 files), make sure you have the files:

assets/css/materialize.min.css (download it from https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css)
assets/css/materialize_offline_files/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2 (download it from https://fonts.gstatic.com/s/materialicons/v139/flUhRq6tzZclQEJ-Vdg-IuiaDsNc.woff2

I thought this would just eliminate the problem the call to fonts.googleapis.com slowing down my app, but actually the few icons I use are actually showing up on the offline computer now. I'm not sure if it will work for all the icons, but it is working for me.
Answer: The answers here are all old. In 2023 you want material-icons npm package NOT material-design-icons. It's much better maintained and automatically updated.
npm install material-icons --save
It's one line of code to get it working:
import 'material-icons/iconfont/material-icons.css';

OR
@import 'material-icons/iconfont/material-icons.css';

There are other alternatives to get it working but see the linked docs for more.
Answer: Install npm package
npm install material-design-icons --save

Put css file path to styles.css file
@import "../node_modules/material-design-icons-iconfont/dist/material-design-icons.css";

Answer: By the way there is video available on YouTube with step by step instructions.
https://youtu.be/7j6eOkhISzk

These are the steps. Download materialize icon package from https://github.com/google/material-design-icons/releases

Copy the icon-font folder and rename it to icons.

Open the materialize.css file and update the following paths:

a. from url(MaterialIcons-Regular.eot) to url(../fonts/MaterialIcons-Regular.eot)
b. from url(MaterialIcons-Regular.woff2) format('woff2') to  url(../fonts/MaterialIcons-Regular.woff2) format('woff2')
c. from url(MaterialIcons-Regular.woff) format('woff') to url(../fonts/MaterialIcons-Regular.woff) format('woff')
d. from url(MaterialIcons-Regular.ttf) format('truetype') to url(../fonts/MaterialIcons-Regular.ttf) format('truetype')

Copy the materialize-icon.css to your css folder and reference it in your html file.
Answer: I chose a lazy solution with apache to evade dissuasions:
<link href="https://MYHOST/gfonts/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://MYHOST/gfonts/icon?family=Material+Icons|Material+Icons+Outlined" rel="stylesheet">

Add small apache plugin
a2enmod substitute

And in my apache config
AddOutputFilterByType INFLATE;SUBSTITUTE;DEFLATE text/html text/plain text/xml text/css
Substitute "s|https://fonts.gstatic.com/|/gsfonts/|i"
SSLProxyEngine on
ProxyPass "/gfonts/"  "https://fonts.googleapis.com/"
ProxyPassReverse "/gfonts/"  "https://fonts.googleapis.com/"
ProxyPass "/gsfonts/"  "https://fonts.gstatic.com/"
ProxyPassReverse "/gsfonts/"  "https://fonts.gstatic.com/"

Answer: Here's how you can automate downloading the latest font and subsetting it from a Node.js script.
1. Downloading
Google API ignores requests which don't have a proper user-agent header. We can use user-agents to bypass the restriction. Please, don't abuse it :)
Go to Material icons, choose one and copy the link HTML that contains the path to the CSS file. It looks like this:
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" />

You can actually edit the parameters here to get the exact font that you want.
This API should be stable enough.
Now, we need to download this CSS file and parse the URL of the actual binary font file. This function can do it for you, just give it the link string and the path where to save the file:
const downloadFont = async (googleFontLink, fullFontPath) => {
  const headers = {
    Accept: '*/*',
    'Content-Type': 'font/woff2',
    'User-Agent': new UserAgent().toString(),
  };
  const cssUrl = googleFontLink.match(/href="(.*?)"/)[1];
  const fontCssRes = await axios.get(cssUrl, { headers });
  const fontUrl = (fontCssRes.data.match(/url\((.*?)\)/) || [])[1];

  const fontFileRes = await axios.get(fontUrl, {
    headers,
    responseType: 'stream',
  });
  await fontFileRes.data.pipe(fs.createWriteStream(fullFontPath));

  const delay = time => new Promise(r => setTimeout(r, time));
  await delay(1000);
};

2. Mapping the ligatures
Fontkit will help here. It can decode the woff2 file. You just need a little script to extract the ligatures. Something like this:
const getLigatures = () => {
  const result = {};
  const font = fontkit.openSync(fullFontPath);

  const lookupList = font.GSUB.lookupList.toArray();
  const lookupListIndexes = font.GSUB.featureList[0].feature.lookupListIndexes;

  lookupListIndexes.forEach(index => {
    const subtables = lookupList[index].subTables;

    subtables.forEach(subTable => {
      const leadingCharacters = [];
      subTable.extension.coverage.rangeRecords.forEach(coverage => {
        for (let i = coverage.start; i <= coverage.end; i++) {
          let character = font.stringsForGlyph(i)[0];
          leadingCharacters.push(character);
        }
      });
      const ligatureSets = subTable.extension.ligatureSets.toArray();

      ligatureSets.forEach((ligatureSet, ligatureSetIndex) => {
        const leadingCharacter = leadingCharacters[ligatureSetIndex];

        ligatureSet.forEach(ligature => {
          const character = font.stringsForGlyph(ligature.glyph)[0];
          if (!character) return;

          const ligatureText =
            leadingCharacter +
            ligature.components.map(x => font.stringsForGlyph(x)[0]).join('');
          const code = character
            .charCodeAt(0)
            .toString(16)
            .toLowerCase();
          const iconName = ligatureText.toLowerCase();

          result[iconName] = code;
        });
      });
    });
  });

  return result;
};

You can filter this dictionary to get the codes of those icons that you actually want. You just need to pass these codes to the script that will create a subset.
3. Subsetting
In my project there's 155 icons. The entire font is 3268. Why would I host the whole thing?
I was not able to find a javascript library that can properly subset and save the result in woff2. But there's a Python script fonttools that does it just fine.
You need to install Python, make sure it works in the terminal and install fonttools with a couple of dependencies:
pip install fonttools zopfli brotli

Then you build the console command like this:
const getCommand = unicodes => {
  return `fonttools subset ${fullFontPath} \
  --unicodes=5f-7a,30-39,${unicodes.join(',')} \
  --no-layout-closure \
  --output-file=${resultFontPath} \
  --flavor=woff2`;
};

...and run it with child_process.exec.
Answer: npm install material-design-icons

and
@import '~material-design-icons/iconfont/material-icons.css';

worked also for me with Angular Material 8
Answer: Added this to the web config and the error went away
<system.webServer>
    <staticContent>
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <remove fileExtension=".woff2" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
    </staticContent>

How to host material icons offline?


Trouble sorting list of lists in Python with Insertion Sort

Question: I am currently making a Python program which takes in the name of a grocery item, the aisle it's on, its location along the aisle, and the price. It holds the data in a list of lists, with each inner list containing 4 elements. The program attempts to create the optimal route through the aisles, with traversal on odd aisles going up (location 1 to loc. N) and traversal on even aisles going down (loc. N to 1).
The code is below:
def sort_aisles(data):
    for item in range(1, len(data)):
        key = data[item]
        j = item - 1

        while j >= 0 and key[1] < data[j][1]:
            print('start first while loop', data)
            print()
            if data[j][1] == data[j + 1][1]:
                if int(data[item][1]) % 2 == 0:
                    # even
                    while j >= 0 and key[2] > data[j][2]:
                        print('start even while loop', data)
                        print()
                        data[j + 1] = data[j]
                        j = j - 1
                        print('end even while loop', data)
                        print()
                else:
                    # odd
                    while j >= 0 and key[2] < data[j][2]:
                        print('start odd while loop', data)
                        print()
                        data[j + 1] = data[j]
                        j = j - 1
                        print('end odd while loop', data)
                        print()
            data[j + 1] = data[j]
            j = j - 1

        data[j + 1] = key
        print('end first while loop', data)
        print()
    return data

def display_route(data):
    total = 0
    for item in range(len(data)):
        total += float(data[item][3])
        print('{:<15} Aisle {:>2} Location {:>2} + {:>6.2f} = {:>6.2f}'.format(data[item][0].title(), data[item][1], data[item][2], float(data[item][3]), total))

def main():
    # Prompt
    data = []
    input_data = input('Name, aisle, location, price? ')
    data.append(input_data.split(','))
    print()
    while input_data.lower() != 'done':
        input_data = input('Name, aisle, location, price? ')
        data.append(input_data.split(','))
        print()
    data.pop()
    # Remove whitespace
    data = [[element.strip() for element in items] for items in data]
    # Testing
    sorted_data = sort_aisles(data)
    display_route(sorted_data)

if __name__ == '__main__':
    main()

Here is a more specific prompt:
Idea:

Go down aisle 1 from location 1 to N, then up

aisle 2 from location N to 1, et cetera.

Store can have any number of aisles and any number of loc. per aisle.
Odd aisles traverse from loc. 1 to N, even from loc. N to 1.

Algorithm:

Prompt for:

item name
aisle number
location number
price

until done is entered (don't include done)
user enters commas between each value
may be additional spaces before/after commas
keep list of lists (items); each item in list will have name, aisle, loc. and price
data[n][1] = nth aisle, data[m][2] = mth loc.
sort list of items

odd aisles sort by ascending location
even sort by descending location

My issue is with sorting. I am using a nested insertion sort currently, but it does not sort as I expect.
The example input I have been using to test is as follows:

Name, aisle, location, price? peanut butter, 3, 5, 1.75

Name, aisle, location, price? fuji apples, 2, 8, 1.50

Name, aisle, location, price? bananas, 2, 1, 2.00

Name, aisle, location, price? potato chips , 3, 3, 2.50

Name, aisle, location, price? cookies,10,5,0.75

Name, aisle, location, price? done

Fuji Apples     Aisle  2 Location  8 +   1.50 =   1.50

Bananas         Aisle  2 Location  1 +   2.00 =   3.50

Potato Chips    Aisle  3 Location  3 +   2.50 =   6.00

Peanut Butter   Aisle  3 Location  5 +   1.75 =   7.75

Cookies         Aisle 10 Location  5 +   0.75 =   8.50

I attempted to use print statements to display what is going on within each loop, but they ended up confusing me more. Here is a pastebin link with the debug information: https://pastebin.com/JWpTPkjJ
For example, the fifth line states it is the end of the first while loop, however the while loop had just output that message previously.
As for what I have tried, initially I had two functions: one which sorted the aisles first using a single insertion sort, which worked wonderfully, and one which sorted locations afterwards using essentially the same code as is in the first if statement in the sort_aisles function. The locations did not sort properly and even caused the cookies on aisle 10 to jump to the top for some reason, so I merged them together, which at least moved the cookies to its rightful spot, but ruined the ordering of the previous items.
I am certain the issue lies in my algorithm for sorting, but I have not been able to figure out what is going wrong. Any help with fixing the sorting algorithm would be much appreciated. Apologies if the post is a bit long, but I felt all of the details were important.
Comment: Is there a reason you're writing your own sort?
Comment: I'm not sure how to use the .sort function to sort the list of lists properly since some locations should be ascending and some descending depending on the aisle.
Comment: For the ascending versus descending issue, can't you do `ascending = ((data[item][1] %2)== 1)`? Or `key = (-1)**((data[item][1] %2 +1)`.
Comment: I'll see if I can put a function together for that.
Answer: So, we want to sort the items in one direction (ascending) on odd aisles and in the other (descending) on even aisles. This means we need to sort by the location number on odd aisles, and the negative of the location number on even aisles. Then we need to take each aisle and sort them by aisle number.
We can do this by writing a key function for the .sort() method. For each item in the list being sorted, the key function returns a value that will sort the items in the correct order. Since we want the items sorted by aisle first, then by the location in that aisle (either ascending or descending), our key function will return two values: the aisle number, and the location number (negated in the case of even aisles).
The aisle is the second number [1] in your record and the location in the aisle is the third item [2]. So:
def shop_sequence(record):
    return record[1], record[2] if record[1] % 2 else -record[2]

Now we just sort using that key function:
data.sort(key=shop_sequence)

Comment: Ah yes, you should probably convert those to integers when they're input.
Comment: Thank you so much! I am getting a TypeError "not all arguments converted during string formatting," how could I fix this? I thought maybe it was because the modulo was on a string, but converting to an int led to a different TypeError "bad operand type for unary -: 'str' "
Comment: I found adding ensuring the else record was an integer too made the program work, but now cookies are being pushed to the top again, but the next 4 entries are sorted properly.


How to redirect a newly registered user to a custom URL after signing up?

Question: By default after a new user signs up, a redirect to the home page happens.
But in such case I want to redirect such user to another page like node/35.
In this node/35 I then want to display some content.
Comment: I think you can easily do this by using LoginToBoggan module which I have mentioned & Rules module which @Pierre.Vriens mention in there answer. It's not a difficult task.
Comment: If you can try any module then you can do this by using LoginToBoggan module which I have suggested in answer. You can also do this by using Rules module also do this by custom code mention in my answer.
Answer: Consider using the Rules module to do this.
Here is how such (fairly basic) rule would look like, based on your extra comment in my answer (= new users that register do NOT need admin approval):

Event: After saving a new user account.
Condition: None
Action: Page redirect (with value = Node/35 in your case).

The above is just a basic rule. You might want to enhance it in various ways. E.g. add a 2nd action to the very same rule to just set a special welcome message (near the top of the main content of your pages).
Comment: there is any approval given from admin just sign up after redirect to custom page like node/35
Answer: You can do this by using LoginToboggan module.

The LoginToboggan module offers several modifications of the Drupal
  login system in an external module by offering the many features
  and usability improvements.

OR
<code><?php
function custom_form_alter(&$form, &$form_state,$form_id) {
  switch ($form_id) {
    case 'user_register_form':
          $form['#submit'][] = 'custom_user_register_submit';
      break;
  }
}

function custom_user_register_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/business';
}
?>
</code>
Comment: thanks to answer to my question but in this code where i can provide can u tell me in briefly
Comment: What can I tell you briefly. I don't think so above code is not understandable. Simply `$form_state['redirect'] = 'node/35';`


How to atomically replace a file?

Question: I'm currently using:
if Path::new(&filename).exists() {
    remove_file(&filename)?;
    debug!("old output file deleted: {filename}");
}

let mut file = OpenOptions::new()
.create_new(true)
.append(true)
.open(&filename)?;
debug!("output file opened: {filename}");

I'm aware that this is a possible race condition.
How can I open and truncate a file in one operation?
Comment: can you just overwrite file if it exists instead of removing it first?
Comment: Can you lock the file so when one action opens it that another action can't access it? avoids the race.
Comment: @AzatIbrakov Yes, I'd be interested in that.
Answer: In the POSIX API, the creat() system call is a shortcut for open() with O_CREAT|O_WRONLY|O_TRUNC.
In the Rust documentation for std::fs::OpenOptions we find an example for truncate().
Note also that std::fs::File::create() is equivalent to the creat() system-call.
Opening a file this way will create it if it does not already exist, or truncate it if it already exists; all the subsequent write calls will take place in a file which is originally empty.

How to atomically replace a file?


How do I load a field of a product in a custom module?

Question: A customer want to have the possibility to use different discounts on products. I'm working with the price resolver and I'll give the possibility to manage different discounts with taxonomy terms. I added an entity reference field (field_discount) to the product.
I'm writing the module that should look which discount is given to the product and then calculate the price based on the discount.
How can I load the value of field_discount in my module?
I made now a lot of research and I tried many different things, but nothing worked.
Answer: Have you tried?
<code>$product->get('field_discount')->entity
</code>
Answer: Try
<code>$product->field_discount->value
</code>


PHP looping limit the number

Question: I have to submit all telephone numbers from my database records to URL, but I need to restrict each time send 300 phone numbers only.
I need a php script able to run following scenario:

Retrieve 2,000 records from database.
Loop all rows and save each into a variable or something else. (important)
Count total has 2,000 records.
Loop 300 records each time to write into URL. (very important)
Submit the URL (this part no need to explain)
loop for next 300 records to write into URL, and repeat it until record 2,000.

I believe in this case, 2,000 / 300 = 7 times of looping, which 300 records for first 6 times and final time is sending 200 records only.
As I mentioned above the looping for 300 records is very important, and next looping able to know starting from record 301 until 600, and so on.
EDITED
Below are my original code, but it's reading all phone numbers and dumb them all to my URL:
<code>    $smsno = trim($_REQUEST['string_of_phone_number_eg_0123456;0124357;0198723']);
    $message = trim($_REQUEST['message']);

    $phoneNo = explode(";", $smsno);

    // ----------
    //
    // Need to count total $phoneNo, eg total is 2,000 phone numbers
    // Loop 300 times for the phone numbers, eg 001-300, 301-600, 401-900, ..., 1501-1800, 1801-2000
    // Every 300 records, eg $phoneStr =  '0123456;0124357;0198723;...' total 300 phone numbers in this string
    // Write into my URL:  $link = "http://smsexample.com/sms.php?destinationnumber=$phoneStr&messagetosms=$message";
    //
    // ----------
</code>
I am seeking solution from here as I have no idea how to loop each 300 records and write into string then throw this string to my URL.
I can make the first 300 records, but how to get next 300 records after first 300 records write into string and throw to my url, and waiting to perform second throw to url.
For example,
first loop for 300 records:
$phoneStr = phoneNumber01;phoneNumber02;phoneNumber03;...;phoneNumber300
$link = "http://smsexample.com/sms.php?destinationnumber=$phoneStr&messagetosms=$message";
second loop for next 300 records
$phoneStr = phoneNumber301;phoneNumber302;phoneNumber303;...;phoneNumber600
$link = "http://smsexample.com/sms.php?destinationnumber=$phoneStr&messagetosms=$message";
and so on.
Comment: What have you got so far? Please update your post.
Comment: sounds like an order.... and we aren't your employee
Comment: @Jleagle , I have updated the code on my post.
Comment: @itachi , I feel you are not a professional user, or even thinking before commenting the post. I am seeking the solution from Q&A, and my questions was asking by me, if you are not understand, please do not simply comment such rudely like a caveman.
Answer: <code>for ($i = 1; $i <= 2000; $i++)
{
    if ($i % 300 == 0 || $i == 2000)
    {
        //Make URL and send
    }
}
</code>
Comment: @DaveRandom or you could just make your requests with `($i+1)` if it was necessary to start with 1.
Comment: @Jack , I have updated my post for the code written by me, please kindly advise me what to enhance from the code. thanks
Answer: <code>// Per-request limit
$limit = 300;

// Get array of numbers
$numbers = explode(';', $_REQUEST['string_of_phone_number_eg_0123456;0124357;0198723']);

// Get message
$message = trim($_REQUEST['message']);

// Loop numbers
while ($numbers) {

  // Get a block of numbers
  $thisBlock = array_splice($numbers, 0, $limit);

  // Build request URL
  $url = "http://smsexample.com/sms.php?destinationnumber=".urlencode(implode(';', $thisBlock))."&messagetosms=".urlencode($message);

  // Send the request
  $response = file_get_contents($url);

}
</code>
Comment: I have updated my post for the code written by me, please kindly advise me what to enhance from the code. thanks

PHP looping limit the number


Solving a scary looking cubic by hand

Question: I came across this question in the Resonance Journal of science education (April edition 2021). Unfortunately it is only available in the hard copy of the magazine. There is a small poem cited from $The \ Ladies' \ Diary \ 1776$ that proposes the following problem,

$x^2+xy+y^2=1087$
$x^4+x^3y^3+y^4=45777295$

I was able to find a cubic equation in xy by substituting the value of $x^4 + y^4$ from first equation into the second equation,
$(xy)^3-(xy)^2-2174(xy)-44595726=0$
Now the questions I have is,

Is this the correct way to approach such a problem? If not please provide an alternative approach.
How do I proceed from here? I prime factorised the last term into $44595726=2×3×7×17×62459$, now do I need to consider all possible combinations of products of these prime factors and plug it in the equation to solve it? (Assuming of course that there were no calculators nor polynomial equation solvers in 1776)
Comment: The equation by @Paul is incorrect. The correct is $(x+y)^2=1087+xy.$
Comment: Not very sure, but assuming $x$ and $y$ being positive integers we can put some bounds on them, and probably solving a great part of the problem in the way.
Comment: @Paul so that gives us $x+y≤32$ since $33^2=1089$ applying AM-GM will give us $xy≤256$ but the root of the cubic is 357.
Comment: I think you mean $(x-y)^2=1087-3xy$ but since we can't apply AM-GM here it doesn't directly help us with the cubic
Comment: One-liner in Python:
```[(x,y) for x in range(100) for y in range(100) if x**2+x*y+y**2==1087 and x**4+x**3*y**3+y**4==45777295]```
Answer: `[(17, 21), (21, 17)]`
Comment: The first equation is $(x+y)^2=1087-xy$, so you are looking for perfect squares less than 1087. This should restrict $x$ and $y$ quite a lot.
Comment: Try the substitution $m=x+y,\ n=x-y$. The first equation becomes $3m^2+n^2=4\times 1087.$ Perhaps the second equation also simplifies?
Comment: @md2perpe unfortunately it doesn't simplify as much as the first one :(
Comment: Or something like $(x-y)^2=1087-xy$ would be better, implying $x-y\leq 32$.
Comment: @ultralegend5385 but that relation is also incorrect
Comment: $(x-y)^2=1087-3xy$ and considering the text will restrict you to 7 possible values of $xy$, which can then be tested in the cubic. One of these is $xy=357=17\times 21$
Answer: The second equation you are given has a subtle hint.
If $x$ and $y$ are large, then the $x^3y^3$ which is degree 6 dominates the other terms.
We can establish this dominance more rigorously by observing that the first given equation forces $x,y\le32$. Then $x^4+y^4$ cannot exceed $2×32^4=2097152$, which is less than $5$% of the right side of the second equation, forcing the $x^3y^3$ term to make up all the rest.
So $xy$ should be close to the cube root of the right side of the second equation, this root being between $300$ and $400$.
The factor that fits this estimate and your product is $3×7×17=357$, so try that value for $xy$.
Assuming that $xy=357$ works (solving the cubic equation), the first equation then gives $x^2+y^2=730$. Then the larger factor must be at least $\sqrt{xy}=\sqrt{357}$ and less than $\sqrt{x^2+y^2}=\sqrt{730}$. The only factor of $357$ that falls within these limits is $21$, so the values of $x$ and $y$ would be (in either order) $21$ and $357/21=17$.
Comment: +1 on this answer. (If $x$ is very small, then the dominating term would be $y^4$,  but in this case $y\approx80$, and this is nonsense since $1087 >y^2 \approx 6700$.)
Answer: From where you pointed out, I could reduce the candidates.
$x$ and $y$ are ages, so they are integers. $xy \mid 2\times3\times7\times17\times62459$; we can neglect the 62459 factor since people cannot live that long.
Product of two people's ages are divided by $2\times 3 \times 7\times 17$. By modular arithmetic, we can assert that $xy \mid 7$, $xy \mid 17$ and $xy \not\equiv 1 \pmod3$. (This is somewhat tedious to do by hand, but I think it is doable.) Now there are three candidates for $xy$; $2\times 7\times 17$, $3\times 7\times 17$ or $2\times 3\times 7\times 17$. Answer is $3\times 7 \times 17$, and their ages would be $17$ and $21$. (Technically $(7,51)$ or $(3,119)$ are also possible.)
(+Edit)
Up to here I was solving the cubic, but more informations were given; with $x^2 + xy + y^2 = 1087$, $(x+y)^2 = 1087 + 357 = 38^2$, so $0<x+y=38$ and $\{x, y\} = \{17, 21\}$ is easy.
Comment: @QuiGonnJinn This answer is solving the scary-looking cubic of $xy$, so there's nothing to do with individual $x$ and $y$.
Comment: The product divides into the expression you cite.
Comment: @QuiGonnJinn $\pmod 7$ for example. $t^3 - t^2 -2174 t -44595726 \equiv t(t^2 - t +3) \pmod 7$. $f(t) = t^2-t+3$ has values $f(0), \dots, f(6) = 3, 3, 5, 9, 15, 23, 33$ so this does not vanishes mod 7. So we have $t \equiv 0\pmod 7$. The calculation is tedious but doable by hand.
Comment: "Now there are three candidates for xy; 2×7×17, 3×7×17 or 2×3×7×17". Not for me. Putting $xy$ even renders the cubic polynomial $\equiv2\bmod4$. We are left with the one correct (odd) value.
Comment: This answer is not right. Even wolfram alpha don't agree with you https://www.wolframalpha.com/input/?i=x%5E2%2Bxy%2By%5E2%3D1087%2C+x%5E4%2Bx%5E3y%5E3%2By%5E4%3D45777295
Comment: Well, yes, I was just solving the cubic which yields $xy =3\cdot 7 \cdot 17$, and by using the given equation we are reduced to exact $x, y = 17, 21$.
Comment: @Jitendra Singh Okay, I edited.
Comment: Your edit is what is OP asking How did you know you had to 730 how did you get to know you have to produce 38^2 also inform the reverse state
Comment: @JitendraSingh OP asked if we have to examine all of the possible combinations, and my answer is about how to reduce the number of combinations into doable set of candidates. Kindly read my post again.
Comment: I am confused  how did you write xy|7 and xy|17 ? Did you mean 7|xy and 17|xy
Comment: In particular I'm not able to follow "By modular arithmetic, we can assert that xy∣7, xy∣17 and xy≢1(mod3)" how did you arrive here? I know basic modular arithmetic but I'm not able to understand your approach
Answer: In year $1776$, they knew how to solve  cubic equations (they were first studied in the $11^{\text{th}}$ century by Omar Khayyam in Persia).
So, they knew that the only real root of
$$(xy)^3-(xy)^2-2174(xy)-44595726=0$$ is $(xy)=357$.
Now, using the first equation, we have that
$$(x+y)^2=(x^2+xy+y^2)+xy=1087+357=1444=38^2$$
$$(x-y)^2=(x^2+xy+y^2)-3xy=1087-3\times 357=16=4^2$$

Solving a scary looking cubic by hand


typescript error: Argument of type 'any' is not assignable to parameter of type 'never' - in accessing specific key in array

Question: I've got this piece of code (TypeScript). Now there's a TS error for item[0]:
Argument of type 'any' is not assignable to parameter of type 'never'.
What should I do? thanks.
  const myFunc = (parentId: string, results = []) => {
    const item = inventoryData.filter(({ id }: Item) => id === parentId);
    results.push(item[0]);
    return results;
  };

Answer: In typescript when you declare a variable and assign it with [] the type is implicitly taken as never.
so you can modify results = [] to results:any[] = []
  const myFunc = (parentId: string, results:any[] = []) => {
    const item = inventoryData.filter(({ id }: Item) => id === parentId);
    results.push(item[0]);
    return results;
  };

hope this help.


Prove that $\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}}$ is rational if and only if $a^2-b$ and $\frac{1}{2}(a+\sqrt{a^2-b})$ are square.

Question: Let $a,b \in \mathbb{R}$ such that $a^2\geq b$. Prove that $\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}}$ is rational if and only if $a^2-b$ and $\frac{1}{2}(a+\sqrt{a^2-b})$ are square.
$\Rightarrow$)
$\begin{align*}
\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}}&= \frac{p}{q}\\
2a+2\sqrt{a^2-b}&=\frac{p^2}{q^2}\\
\frac{1}{2}(a+\sqrt{a^2-b})&=\frac{p^2}{(2q)^2}
\end{align*}$
but I don't know how to relationate $a^2-b$
$(\Leftarrow$
$\begin{align*}
n&=\frac{a+\sqrt{a^2-b}}{2}\\
&=\frac{(a+\sqrt{b})+2\sqrt{a^2+b}+(a-\sqrt{b})}{4}=\left(\frac{\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}}}{2}\right)^2
\end{align*}$
then $\sqrt{n}=\frac{\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}}}{2}$
but again I don't know what to do with $a^2-b$
Comment: @quasi it was a typo, but now it's fixed. Thank you. And for the other question is on $R$ not in $Q$ (Or at least in this exercise)
Comment: Can you give the source of the exercise? I suspect it was specified that $a,b$ are nonnegative rational numbers (in which case, it's easy), not just real numbers.
Comment: @quasi https://tuxdoc.com/download/fernando-zalamea-fundamentos-de-matematicas-coleccion-notas-de-clase-universidad-nacional-de-colombia-2007_pdf (It's in Spanish I hope you don't mind) it exercise 9.5.7//page 103.
Comment: That link doesn't work for me.
Comment: What is the level of the course? What title?
Comment: @quasi it's called 'Fundamentos de matemáticas' by professor Zalamea.
Comment: Ok, I found a copy of the book, and you're right, the author does say $a,b \in \mathbb{R}$. But based on the preceding material in the book, and the other exercises, I'm fairly sure it was just a typo. So as not to stress over an impossible exercise, just assume the intended restriction was $a,b \in \mathbb{Q}$ and $a^2 \ge b \ge 0$.
Answer: Assuming "square" means square of a rational (otherwise any positive real is the square of a real number), it's not true if $a$ and $b$ are not assumed rational.  For example, with $0 < b < 1/4$ and $a = b + 1/4$ we have $\sqrt{a+\sqrt{b}}+\sqrt{a-\sqrt{b}} = 1$.
Comment: Oops, sorry: fixed it.


Validation metrics (R2 and Q2) for Partial Least Squares (PLS) Regression

Question: I'm attempting to validate my  Partial Least Squares (PLS) -regression model. From documentation and other readings regarding PLS regression I've come to understand that there are generally two metrics used to evaluate the performance of the algorithm. $R^2$ is calculated as 1 - residual sum of squares(RSS) and the total sum of squares(TSS):
$$
R^2 = 1 - RSS/TSS
$$
$$
RSS =\sum(y-\hat{\mathbf{y}})^2
$$
$$
\ TSS = \sum(y - \bar{\mathbf{y}})^2
$$
While $Q^2$ is calculated as 1 - Predictive residual Error sum of squares(PRESS)/ TSS:
$$
\ Q^2 = 1 - PRESS/TSS
$$
$$
\ PRESS = \sum(y-\hat{\mathbf{y}})^2
$$
The Calculation for $R^2$ and $Q^2$ are almost identical, with the only difference being that RSS is calculated from the data on which the algorithm is trained and PRESS is calculated from held out data.
My question:
In the view of training/test splits of data, is it appropriate to call $R^2$ a metric of how the algorithm fits the training data and $Q^2$ a metric of algorithm performance on test data?
Side question: Is it good practice to scale Y in the same manner as X in PLS regression?
Comment: @theGD I have changed the question to be more specifically about PLS-R performance measures.
Comment: I think you should reword your question so that it is more about PLS and its performance measures rather than specifically about sklearn functions. I also think the score returning functions are very likely irrelevant of y predictions. Thus, it is probably not the correct way of calculating $Q^2$ and $R^2$. Scaling Y, on the other hand, depends on your data and if you don't know what makes more sense, you can always test different scaling and centering scenarios.
Answer: I was also looking for information on these parameters and found a good explanation in the book Eriksson et al. Multi- and Metavariate Data Analysis Principles and Applications.
In general, I think you have the right idea. According to Eriksson et al, the fit tells us how well we are able to mathematically reproduce the data of the training set. The $R^2$ parameter is known as the "goodness of fit", or explained variation. The $Q^2$ parameter is termed "goodness of prediction", or predicted variation.
The following points are emphasised:

In PLS, the terms $R^2$ and $Q^2$ generally refer to the model performance of the Y-data, the responses, rather than that of the X-data, the predictors.
The two parameters vary differently with increasing model complexity. $R^2$ is inflationary and rapidly approaches unity as model complexity (number of model parameters) increases. Therefore, it is not sufficient only to have a high $R^2$. $Q^2$, on the other hand, is not inflationary and at a certain degree of complexity will not improve any further and then degrade.
There is a trade off between fit and predictive ability, so it is the zone where we have a balance between good fit and predictive power that we wish to identify.

For your side question, I find no specific recommendations and no particular reason to scale the Y variable (I'm assuming there is only one). X-variables are scaled to give them the same variance and thus equal weight in the model. The model should be mathematically equivalent whether the response is scaled or not. If there is more than one Y-variable, a more important issue would be to test whether they correlated and whether to fit one model or separate models for each predictor.


Ruby, how to get numbers after $ symbol

Question: Having an array:
price = ['$6.95', '$7', '$10.50']

I need to get all numbers from it like: 6.95, 7, 10.50
price[0].match('\d+')[0].to_f

returns 6. I expect 6.95
Comment: 6.95 is not an [integer](https://en.wikipedia.org/wiki/Integer)...
Comment: that is not a valid array.
Comment: Can you provide a sample Ruby snippet that's valid code and more accurately represents the data you're dealing with?
Comment: what do you want `$7` to return?
Comment: "." is not a valid number either `\d+` means digit. So your match is effectively `["6","95"]` but the `MatchData` is only going to store the first match in this case so `"6"`
Comment: my bad `price[0].match('\d+')[0].to_f` returns 6.0 anyways
Comment: This is not an exact match for the nominated exemplar, although it is close.
Answer: ['$6.95', '$7', '$10.50'].map { |price| price.match(/\d+\.?\d{0,2}/)[0].to_f }
=> [6.95, 7.0, 10.5]

The regex here supports any number of digits, an optional decimal point, and up to two trailing numbers (cents). If you have commas in your prices (like $1,000) you'll need to be a little bit more clever around the \d+ part.
Comment: `price[1..-1].to_f` returns the same array as this answer.

Ruby, how to get numbers after $ symbol


Ler e serializar infos de um arquivo na saída em formato JSON com Newtonsoft

Question: Galera,
Estou tentando deixar mais bonitinho meu programa Console Aplication serializando o resultado final em formato Json com os atributos da classe mas não estou conseguindo direto usando List em c#. O programa lê as informações, mas o resultado esta vindo assim:
"1,Leandro Azevedo,Sertanejo"
"2,Clecios Camacho,Heavy Metal\t "

mas quero que venha como abaixo usando minha classe que criei:
[{"id":"1",
"NomeCompleto":"Leandro Azevedo",
"EstiloMusical":"Sertanejo"},
{"id":"2",
"NomeCompleto":"Clecios Camacho",
"EstiloMusical":"Heavy Metal"}]

Tentei usar List para criação dos objetos mas alguns exemplos que vi não rolou muito bem, segue o projeto abaixo:
O arquivo txt contém as informações:
1,Leandro Azevedo,Sertanejo
2,Clecios Camacho,Heavy Metal

Classe:
namespace ConsoleApp_LeituraDeArquivoTexto
{
  public class LeituraDeArquivoTexto
  {
     public string Id { get; set; }
     public string NomeCompleto { get; set; }
     public string EstiloMusical { get; set; }
  }
 }

Programa:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace ConsoleApp_LeituraDeArquivoTexto
{
  class Program
  {
     public static string FormatoJson(string json)
     {
         string jsonData = JsonConvert.SerializeObject(json);
         return jsonData;
     }

    static void Main(string[] args)
    {
        String lerArquivo = @"C:\Estudos\C#\ConsoleApp_LeituraDeArquivoTexto\ler_arquivo.txt";

        string[] linhasLidas = File.ReadAllLines(lerArquivo);

        if (linhasLidas.Length == 0)
        {
            Console.WriteLine("ARQUIVO EM BRANCO");
        }
        else
        {
            using (System.IO.StreamWriter escreverLinhaJson = new System.IO.StreamWriter(@"C:\Estudos\C#\ConsoleApp_LeituraDeArquivoTexto\Resultado.txt"))
            {
                foreach (var linha in linhasLidas)
                {
                    if (linha != "")
                    {
                        string serializarDadosJson = FormatoJson(linha);
                        escreverLinhaJson.WriteLine(serializarDadosJson);
                    }
                }
            }

        }

        Console.ReadKey();
    }
}

}
Answer: Pessoal como foi considerado irrelevante minha pergunta, queria fazer era algo do tipo como abaixo, ao invés do artquivo txt usei lista mesmo para serializar a informação em Json, mas valeu o desafio segue abaixo:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace ConsoleApp_LeituraDeListaConversaoJson
{
class Program
{
    public static string FormatoJson(List<string> json)
    {
        string jsonData = JsonConvert.SerializeObject(json);
        return jsonData;
    }

    static void Main(string[] args)
    {
        List<string> listaVideoGames = new List<string>
        {
            "Starcraft",
            "Halo",
            "Legend of Zelda"
        };

        if (listaVideoGames.Count == 0)
        {
            Console.WriteLine("Lista vazia");
        }
        else
        {

            string serializarDadosJson = FormatoJson(listaVideoGames);
            Console.WriteLine(serializarDadosJson);
        }

        Console.ReadKey();
    }
  }
}


How to build openembedded packages

Question: I have my petalinux user package with non-commercial license. And i am trying to add the lines LICENSE_WHITELIST = "non-commercial"at the end of local.conf file but it is not compiling my package library as i understood that i need to specify the following URL: git://github.com/openembedded/openembedded-core.gitto my local.conf file as it is trying to fetch from URL ftp://ftp.netperf.org/netperf/archive/netperf-2.6.0.tar.bz2 which is not the right one. How can I do changes to the following file by adding it to whitlist license and with specifying URL.
MACHINE ??= "qemuzynq"
DISTRO ?= "petalinux"
PACKAGE_CLASSES ?= "package_rpm"
USER_CLASSES ?= "buildstats image-mklibs"
PATCHRESOLVE = "noop"
BB_DISKMON_DIRS = "\
    STOPTASKS,${TMPDIR},1G,100K \
    STOPTASKS,${DL_DIR},1G,100K \
    STOPTASKS,${SSTATE_DIR},1G,100K \
    STOPTASKS,/tmp,100M,100K \
    ABORT,${TMPDIR},100M,1K \
    ABORT,${DL_DIR},100M,1K \
    ABORT,${SSTATE_DIR},100M,1K \
    ABORT,/tmp,10M,1K"
XILINX_VER_MAIN = "2017.1"
SOURCE_MIRROR_URL ?= "https://www.author.xilinx.com/sswreleases/rel-v2017.1/downloads"
INHERIT += "own-mirrors"
INHERIT += "rm_work"

DL_DIR = "${TOPDIR}/downloads"
INHERIT += "uninative"
UNINATIVE_CHECKSUM[x86_64] = "406f783daa6f3923283b3f6ec514cb0470c3a3ea12cb12d5f4bfaec51b2b4dd3"

CONF_VERSION = "1"

INHERIT_remove = "buildhistory icecc"
CONNECTIVITY_CHECK_URIS = ""

SIGGEN_LOCKEDSIGS_SSTATE_EXISTS_CHECK = "none"

SIGGEN_LOCKEDSIGS_TASKSIG_CHECK = "warn"

BB_SETSCENE_ENFORCE_WHITELIST = "%:* *:do_shared_workdir *:do_rm_work *:do_package"

BUILDCFG_HEADER = ""

require conf/locked-sigs.inc
require conf/unlocked-sigs.inc

# Extra settings from environment:
MACHINE = "zynq-generic"

include conf/plnxtool.conf
include conf/petalinuxbsp.conf

Answer: First you most likely want to do 'LICENSE_WHITELIST += "non-commercial"' to avoid overwriting the values already in the whitelist.
Next, I am not certain what you are getting at with the various URLs but as to why netperf is not being built is most likely related to the fact that there is no dependency on netperf (by any other packages, packagegroups or images which you are building). First ensure it will build with 'bitbake netperf'. Then ensure you include netperf in your image. There are a few ways to accomplish this last one but one way is to append to local.conf with 'IMAGE_INSTALL_append += "netperf"'.

How to build openembedded packages


Existence and uniqueness of a solution of a differential equation with continuous function

Question: Let $y_0\in\mathbb{R}$ and $f\in C(\mathbb{R})$ such that $f(y_0)\neq0$. Show then that for any $x_0\in\mathbb{R}$, the point $(x_0,y_0)$ is a point of existence and local uniqueness $y'= f(y)$.
I had in mind to use Peano's existence theorem, but I don`t know how to rigorously pass from a function of one variable to a function of two variables. Also, another idea was to use the following function:
$$
F(y)=\int_{0}^{y}\frac{du}{f(u)},\quad y\in\mathbb{R}.
$$ We would write $y'=f(y)$ as $F(y)+c=x$, $c\in\mathbb{R}$ and its derivative (of $F$) would then be $\frac{1}{f(y)}$ which is either bigger than $0$, either smaller. Then $F$ is strictly monotone and from here I would say that we have a solution on the open interval
$$
I_{c}=\left(\int_{0}^{-\infty}\frac{du}{fu}+c,\int_{0}^{\infty}\frac{du}{f(u)}+c\right).
$$ I have proven that there exists a solution and it is saturated, but I am unsure how to prove the uniqueness part. Any help would be appreciated.
Comment: Your reasoning is right, and uniqueness follows simply from the invertibility of $F$. The solution $y(x)$ must satisfy the equation $F(y(x))=x-x_0+F(y_0)$ and as $F$ is invertible, it is equivalent to $y(x)=F^{-1}(x-x_0+F(y_0))$, which is then the unique solution.
Comment: @M_S Please develope it in a full answer, the ideea is good. In case of a good answer I shall give the bounty.
Answer: As $f(y_0)\neq 0$ we can just solve the equation by separation of variables in the neighbourhood of $(x_0,y_0)$ and obtain
$$F(y)=\int_{y_0}^y \frac{\mathrm{d}u}{f(u)} = x-x_0. $$
Now as you said, the function $F$ is strictly monotone, therefore invertible. Hence we obtain explicit formula for the solution
$$y(x)=F^{-1}(x-x_0),$$
which is unique.
EDIT: Also some remarks about the interval of existence: since the question is about local existence and uniqueness, I suppose you don't have to compute the maximal interval on which $y$ exists and is unique, especially that the latter may get complicated, depending on $f$.
First of all, I think you should write $c$ in terms of $x_0,y_0$. Moreover, the integral limit should be $y_0$ instead of $0$ (simple example: take $f(y)=y^2$ and $y_0>0$ - then $\int_0^\infty \frac{\mathrm{d}u}{f(u)}=\infty$ but $y(x)$ blows up for $x=\int_{y_0}^\infty \frac{\mathrm{d}u}{f(u)}+x_0$, which is finite).
To obtain the interval of unique existence, you also need to consider the integral of $\frac{1}{f(u)}$ in the neighbourhoods of zeros of $f$ (another example: let $f(y)=-\sqrt{|y|}$ and $y_0>0$ - then $y(x)=0$ for $x=x_0+\int_0^{y_0}\frac{\mathrm{d}u}{\sqrt{u}}$ and loses its uniqueness).


Limits and formalizing the solution

Question: I have the following limit and I needed to check whether it exists and, if it does, determine it.
$\lim \limits_{x \to -\infty} \frac{sin(x)}{x}$.
I have come to the following solution - and it'd be great if someone would look over it; I am especially unsure whether my solution is formal enough. It's as if I have the right idea, yet I still have some issues with formalizing these notions, putting, if you will, in the right language. So this, then, would be the solution:
$-1 \ge sin(x) \ge 1 \forall x$
$ \implies (-1 \ge sin(x) \ge 1) \cdot \frac{1}{\left\lvert x \right\rvert} = -\frac{1}{\left\lvert x \right\rvert} \ge sin(x) \ge \frac{1}{\left\lvert x \right\rvert}$
$\lim \limits_{x \to -\infty} -\frac{1}{\left\lvert x \right\rvert}=0$
$\land \lim \limits_{x \to -\infty}\frac{1}{\left\lvert x \right\rvert} \implies$
$\lim \limits_{x \to -\infty} \frac{sin(x)}{x}=0$ Therefore, this limit does not exist.
Thanks for your help!
Comment: "Therefore, this limit does not exist." -- ... did you not just conclude that the limit is zero, and therefore the limit exists?
Answer: You can just write $\frac{1}{x}\leq \frac{sin(x)}{x}\leq-\frac{1}{x}$ (because $x$ is negative). Then you just let the limit do its job. Since the two limits on left and right are 0, by squeeze theorem you get that your desired limit is also equal to 0.
\begin{equation} EDIT \end{equation}
By this principle, you can conclude that
\begin{equation}
(something\ limited)\times(something \ that\ tends\ to\ 0)\rightarrow 0
\end{equation}
Comment: Thanks, I appreciate it!

Limits and formalizing the solution