Linux/Solaris verification ( after hostname change ) in files according to hostname rule

Question: According to the following Perl command
( this command part of ksh script )
I can replaced  old hostnames with new hostnames in Linux or Solaris
<code> previos_machine_name=linux1a
 new_machine_name=Red_Hat_linux1a

 export previos_machine_name
 export new_machine_name
</code>
.
<code>      perl -i -pe 'next if /^ *#/; s/(\b|[[:^alnum:]])$ENV{previos_machine_name}(\b|[[:^alnum:]])/$1$ENV{new_machine_name}$2/g'  file
</code>
EXPLAIN:  according to perl command - we not replace hostnames on the follwoing case:
RULE: [NUMBERS]||[letter]HOSTNAME[NUMBERS]||[letter]
my question
after I used the Perl command in order to replace all old hostnames with new hostnames
based on the "RULE" in the Perl command
how to verify that the old hostnames not exist in file ?
for example
<code>   previos_machine_name=linux1a

   new_machine_name=Red_Hat_linux1a

   more file

   AAARed_Hat_linux1a          verification should be ignore from this line
   @Red_Hat_linux1a$             verification should be match this line
   P=Red_Hat_linux1a            verification should be match this line
   XXXRed_Hat_linux1aZZZ         verification should be ignore from this line
   .
   .
   .
   .
</code>
Comment: Are we talking a few (less than 10) machines or a lot here?
Comment: why its important ? , any way is could be 1 machine or more then 20 machines depend file configuration , and in my script each time I verify one hostname !
Comment: Well, if it is only a few machine, maybe just do it by hand or commandline "grep".
Comment: but I need to check more 100 files , and I need to match exactly to the RULE: [NUMBERS]||[letter]HOSTNAME[NUMBERS]||[letter]
Comment: Understand. If possible, post the script. Then someone maybe able to modify it for you. Or if it is a stand script come with distribution, post the path so we can look it up in our machine.
Comment: script isn't the issue , the issue is to verify not existing of  the old hostname according to RULE - [NUMBERS]||[letter]HOSTNAME[NUMBERS]||[letter]
Answer: Use fowlling line to print matching string
<code>perl -i -pe 'next if /^ *#/; if ($_ =~ /(\b|[[:^alnum:]])$ENV{previos_machine_name}(\b|[[:^alnum:]])/) { print STDOUT $_; }'  file
</code>
If it print out empty, that means no old hostname exist.


Theorem A3 in Asymptotic properties of MLE for the i.n.i.d. case

Question: Can someone explain to me why in the theorem below (case in $R^1$)
$$\lim \inf I(A\cap B(u))|X_k(u)| \leq I(A\cap B)|X_k|$$
Full text of proof: http://projecteuclid.org/download/pdf_1/euclid.aoms/1177693066, page 1987
Theorem A3:
Let U be a subset of $\mathcal{R}$. If $\{X_k(u): k=1,2,..., u \in U \} $ is ui (uniformly integrable) and $\lim\limits_{u \rightarrow u_0} X_k(u)=X_k$ as $u \rightarrow u_0$ a.s. [P], then {$X_k: k=1,2,... $} is ui.
Proof (the first part):
Choose $M$ so large that:
$\int_{|X_k(u)>M|}|X_k(u)|dP<\epsilon$
Holding $k$ fixed, let:
\begin{align}
A    &= \{\lim X_k(u) = X_k \ as \ u \rightarrow u_0\}\\
B(u) &= \{|X_k(u)|>M\}\\
B    &= \{|X_k|>M\}
\end{align}
For any $F \in \mathcal{F}$, let $I(F)$ denote the indicator random variable associated with $F$. It is then clear (this is the part I don't understand why it is clear) that as $u \rightarrow u_0$
$$\lim \inf I(A\cap B(u))|X_k(u)| \geq I(A\cap B)|X_k|$$
Comment: Presumably "ui" means *uniformly integrable.*
Answer: We know that

if $\lim_{u\to u_0}g(u)=\ell $ then
  $\liminf_{u\to u_0}f(u)g(u)=\ell\liminf_{u\to u_0}f(u)$.

The wanted inequality is clear if $\omega$ is not in $A$; if $\omega\in A$ then we use the highlighted claim to be reduced to prove that $\liminf_{u\to u_0}\mathbf 1\left(B\left(u\right)\right)(\omega)\geqslant\mathbf 1\left(B \right)(\omega)$. If $\omega$ is not in $B$, the inequality is clear; otherwise we know that $\left\lvert X_k\left(\omega\right)\right\rvert\gt M$ hence there exists a $\delta\gt 0$ such that $\left\lvert X_k\left(u\right)\left(\omega\right)\right\rvert\gt M$ for $u$ such that $\left\lvert u-u_0\right\rvert\lt \delta$. For these $u$, $\omega$ belongs to $B(u)$.


x64 mvc3 project with Oracle Data Access

Question: I'm using the Oracle Data Access(ODP.NET) in a mvc3 project.
the odp.net has both x64 and x86 versions separately and i want to use the x64 version.
I set "Platform target" to x64 and add a reference to x64 version of odp.net, there is no problem to publish on iis server, but i can't run the project for develop and test, however Razor views display errors on c# statements.
How i can develop the project in x64 platform?
Comment: "but i can't run the project for develop and test, however Razor views display errors on c# statements." What errors are you getting?
Comment: for example displays a red line under "@model List", and on mouse over displays "Could not load file or assembly 'project' or one of dependencies. an attempts was to load a program wit an incorrect format.
Answer: I would say the immediate problem is forcing your platform target to x64.  The asp.net development server is 32 bit.  Either leave it as "Any CPU" or run a 64 bit dev server (either the local IIS server or compile cassinidev as 64 bit).  If you do leave it as any cpu so you can continue to use the out of the box dev server, you'll get the same error with the 64 bit version of oracle.dataaccess.dll for the exact same reason.
I install the 32 bit version on my machine (i also install the 64 bit version but I mention that only to note that they run fine side by side).  The reference to Oracle.DataAccess.dll does not include bit-ness, only version.  So as long as you have the same version (or later with publisher policies) of the 64 bit flavor on the server, everything will run fine once you deploy.


Como faço pra criar um espaçamento vertical entre divs no css?

Question: Estou com o seguinte problema, criei um componente de um botão e coloquei ele dentro de uma div, repliquei osso para 3 botões, queria saber se tem alguma propriedade no css para dar um espaçamento na vertical entre esses botões. Tentei com o line-height, mas n deu certo, pois acho q funciona só pra texto.
Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena ler o [Guia de sobrevivência do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8045/70).
Answer: Você pode usar a propriedade do css padding, se quiser espaçamento na vertical usa o padding-bottom ou padding-top, se quiser na horizontal é padding-left ou padding-right.
É possível combinar mais de um deles também.
Para usar seria assim:
No arquivo css:
.exemplo{
  padding-bottom: 10px; //Se quiser que seja relativo usa com % ao invés de px
}

No arquivo html:

....

Answer: no css coloque assim:
div {
   margin-bottom: 10px;
}


What is a protected pick?

Question: In a trade, one NBA team can give to the other a protected pick (I heard of this concept reading about the alleged details of the DeMarcus Cousins trade from Sacramento Kings to New Orleans Pelicans).
I understand the idea of first and second round picks at the NBA lottery, but I fail to see what can be "protected" about a future event dominated by chance.
Answer: A protected pick is one which will be traded only if it is below a certain point in the draft order. For example, in the Cousins trade, the first round pick that the Pelicans are sending to the Kings is "top three protected" - i.e. if the Pelicans end up with any of the first, second or third pick in the draft, then they keep their 2017 pick and the process starts again with their 2018 first round pick.
As always, the CBA FAQ can get you right into the gory details.

What is a protected pick?


OSX Snow Leopard - Multiple httpd/apache instances for PHP 5.2 & 5.3 together

Question: I need to run Apache with both php 5.2 and 5.3, without other webservers such as nginx, lighttpd, etc. Just Apache HTTPD.
The easiest way to have both PHP 5.2 and PHP 5.3 on Apache, on the same machine, is to have them run in different webservers (or at least different webserver instances).
I already do this on windows, it works flawlessly because it is easy to specify the conf file that a specific instance loads.
But how can this be achieved on Mac OSX, without ditching the web server that OSX comes with built in ?
The basic is to create N-ip addresses that each apache instance will bind to, for example:
192.168.0.52 - This is for apache httpd with PHP 5.2
192.168.0.53 - This is for apache httpd with PHP 5.3
(each apache will bind to its own ip address)
On OSX, i don't know how to configure HTTPD to start as multiple service/daemon, with different startup httpd.conf files!
Answer: Install another apache & php using macports or fink into a separate directory and configure it to run on another port. This way you can have Apple supplied apache bound to port 80 and your custom installed on let's say 8080.
httpd.conf is global for the apache instance even if it runs in several threads so the only way is to have two installs.


How to prepare data to analyze two values simultaneously as one

Question: as a newbie in statistics I'm having trouble with preparing my data.
I have data where a measure is performed on left and right side. When comparing group means I need to take simultaneously both measurement from left and right.
So for example I have:
Case     Side_left    SIde_right
When analyzing means should be n=2xCases, so if I have 15 cases, my means is computed from 30 measurements, 15 from left and 15 from right.
Simply creating averaged from left and right won't do the trick, because  SD's are different, Also if I have missing value from one side, for 15 cases I'd have 29 measurements. By creating means first this information is omited. Is there a way to do it SPSS or any other software or manual solution.
Comment: It might help a little if you provide some context by saying what you intend to do with this measure next. I can see a few different ways you could go with this, but they may not all be appropriate to your goal.
Comment: After descriptive statistics and exploring differences I'd analyze for correlations and prediction (regression).
Comment: Okay, and another couple of questions: 1) Are these measures your independent or dependent variables, and 2) Do you expect the right and left measures to be related (and if so, how)?
Comment: These are the independent variables.
Comment: They are related in a such a way that they represent the same measurement, but on alternative side - nerve conduction studies for left and right nerve. Their are expected to be close to each other, as a value, but sometimes that's not the case. SOmetimes a value would be removed, or would be intentionally omited, if for example there is trauma of the right nerve, we just don't take it into account, even if we have measured it.
Answer: I can see three possible approaches for dealing with this.
1. The "just focus on one side" approach
If you believe that the two measures are really closely related, and can produce a reasonably high correlation coefficient to back this up, then you could use data from only one side (whichever side has the least missing data).
I've done work in the past using eye-tracking where we only analyse movements with the right eye (right tends to be the dominant one). For most of the phenomena I've studied, I've had no reason to believe that the left eye will do anything substantively different, so I don't analyse that data (in reality, I don't collect it... Binocular eye-tracking is a hassle!)
2. The "just take an average and live with some missing data" approach
This is relatively similar to the first approach really. If you don't think the two sides are going to be all that different then just average them. Yes, the averaging will add a little noise, but if the effect you're interested in is robust enough then it probably won't make a difference.
3. The "take a sledgehammer to crack a nut" approach
Use PCA/FA to reduce the two sides, which we believe are going to be very closely related, to a single score. This score will probably not be on the same scale as the raw measurements, so you lose some interpretability.
As with 2, you'll lose some cases where there's missing data, but, really, I'm not sure there's an approach out there (short of imputation) where you won't suffer this problem.
Personally, as long as the correlation coefficient was good then I'd probably just do 1.
Comment: Sure, I could it manually.
Comment: Actually the second route is prefered in most papers, and I already done the analyzis that way, but I'm feeling I'm missing data. ALthough not all explain in details how they collected the data (only one side, both sides) and how exactly they computed it. Sometimes there are bigger than expected differences.  Here is one paper that make it the way I want, but I really can't figure out how they prepared the dataset: http://www.ncbi.nlm.nih.gov/pmc/articles/PMC2777171/
Comment: How much data are you losing due to averaging? If averaging is the default approach in your field then you should probably go that way (it's one less potential hurdle for you to face when you try to publish this).
Comment: Have you considered asking others in your field how exactly they do it? If people are reporting their work without sufficient detail for you to repeat it then I don't think it unreasonable for you to ask them to give you relevant information.
Comment: I've asked, they haven't done in the way I need it or stil don't have answer.
Comment: I'm not really sure I know what to suggest. I'm finding it difficult to reconcile the one position that averaging the two measures is the norm, with the other position that you don't know how they're doing it. If you don't know how they're doing it, then how do you know they're averaging? I don't know this field though, so my general advice would be that if there's a convention to do it one way then do that unless it doesn't make sense for you (e.g. because you're having to delete more data than everyone else). If the convention doesn't work, then come up with your own defensible approach.


Causality Analysis and test of Independence

Question: First the problem: I am refering to lecture note, on page 480, 2nd paragraph, it mentions

If
  X is in fact useless for predicting Y given Z, then an adaptive bandwidth selection
  procedure (like cross-validation) should realize that giving any finite bandwidth to X
  just leads to over-fitting.

I am working with this UCI Dataset for room occupancy.
The dataset is simple, as an exercise, I am trying to find the causal Directed Acylic Graph for the following dimensions, Temperature, Humidity, CO2 and Light.
If I follow the quote above, if Temperature cannot predict CO2 given let's say Humidity, then it probably can be assumed that Temperature and CO2 are independent in causal DAG (ofcorse, I shall have to do it for Temperature with Light as well).
Now for prediction, I am considering a simple 3 layer feed forward neural network, where the inputs would be Temperature and Humidity and the output CO2. I shall train the model on the training set and validate it against the test set, which, if Temperature cannot predict CO2 given Humidity, the NN would overfit on the training set and give high Mean Square Error on test set.
However, I am not sure, if this scheme will work, as, may be Temperature does not have ability to predict CO2 but may be Humidity has (as the common confounder is occupancy in the dataset), so the model may predict CO2 with some good accuracy and will not tell me if Temperature and CO2 are cusally independent or not.
In this situation, how to proceed with the problem, given that I only have the observations. Any help n this will be appreciated
Answer: I was unaware of this algorithm for the test of independence. It is an interesting algorithm. I think the reason that this algorithm can determine the independence between $X$ and $Y$ given $Z$ is that if this independence relationship holds in data, adding $X$ beside $Z$ for predicting $Y$ gives no more information and adds unnecessary extra complexity to your model. This can cause overfitting since your model tries to take $X$ into account and because $X$ has nothing to say, the model just tries to model something like noise.
I also agree with you that this scheme may not work and in the lecture note that you referred, it is obviously mentioned: "slightly less rigorous". There are many other factors, such as the amount of the training data, that can affect overfitting which are neglected in this analysis. I suggest you use standard independence test such as chi-squared test. Also, this question seems also beneficial.
Comment: I refered the link to the other question, very interesting, I shall be going through the methods in more details. However, from your answer, if I train an NN with one input let's say Humidity and one output say CO2 and test it on test set and find some MSE. Again train an NN on 2 inputs, Humidity and Temperature and the 2nd NN's MSE on test set becomes higher than the 1st NN, then it would be reasonable to assume that adding Temperature added no more information but noise and Temperature and CO2 are independent to a large degree.
Comment: In my opinion, you should get such a conclusion with more caution. The higher MSE in the second NN can be due to other factors such as the low amount of the training data. In other words, it is possible that CO2 depends on Temperature besides Humidity, but your data is not enough to extract the true dependencies and therefore, it just overfits the data.


Pandas: Repeating list in column does not work

Question: I want to turn a dataframe from this
to this:

It took me a while to figure out the melt and transpose function to get to this

But I did not get to manage to apply the years from 1990 to 2019 in a repeating manner into for every of the 189 countries.
I tried:
 year_list = []
for year in range(1990, 2020,1):
    year_list.append(year)
years = pd.Series(year_list)
years

and then
df['year'] = years.repeat(30)

(I need to repeat it 30 times, because the frame consists of 5670 rows = 189 countries * 29 years)
I got this error message:
ValueError: cannot reindex on an axis with duplicate labels

Googling this error does not help.
Answer: One approach could be as follows:
Sample data
import pandas as pd
import numpy as np

data = {'country': ['Afghanistan','Angola']}

data.update({k: np.random.rand() for k in range(1990,1993)})

df = pd.DataFrame(data)

print(df)

       country      1990      1991      1992
0  Afghanistan  0.103589  0.950523  0.323925
1       Angola  0.103589  0.950523  0.323925

Code
res = (df.set_index('country')
       .unstack()
       .sort_index(level=1)
       .reset_index(drop=False)
       .rename(columns={'country': 'geo',
                        'level_0': 'time',
                        0: 'hdi_human_development_index'})
       )

print(res)

   time          geo  hdi_human_development_index
0  1990  Afghanistan                     0.103589
1  1991  Afghanistan                     0.950523
2  1992  Afghanistan                     0.323925
3  1990       Angola                     0.103589
4  1991       Angola                     0.950523
5  1992       Angola                     0.323925

Explanation

Use df.set_index on column country and apply df.unstack to add the years from the column names to the index.
Now, we use df.sort_index on level=1 to get the countries in alphabetical order.
Finally, we use df.reset_index with drop parameter set to False to get the index back as columns, and we chain df.rename to customize the column names.
Comment: The usage of unstack does a lot for my understanding – because I used stack to solve my problem – where I should have used unstack. Many thanks!!


Dynamically switching between bootstrap.css theme's

Question: I am trying to switch between a dark & light theme I have created on my MVC application.
My _Layout.cshtml page loads the default theme I have created below
<link id="theme" rel="stylesheet" href="~/lib/bootstrap/dist/css/Original.css">

I have created the below buttons to switch between the themes below
<button id="light">Light</button>

<button id="dark">Dark</button>

My two other bootstrap themes are located in lib > bootstrap> dist > css >
I have the below js in my botstrap.js file
$('#dark').click(function () {
    $('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
    $('link[href="~/lib/bootstrap/dist/css/Dark.css"]').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});

Not sure if I am making some obvious error but any help on this is appreciated.
Comment: What is the issue you are having currently?
Comment: Note that buttons, by default, submit any forms they are within.
Comment: Currently there are no changes to the page when the buttons are pressed. I was wondering if there is an issue with the href i have queried or withing the js itself
Comment: Isn't it possible that your dom query for the link-element doesn't return any elements? It looks like you're looking for hrefs literallly starting with `~/`. In your razor page it's being transformed to the path of your content root, but when querying it won't
Comment: Did you try this one? [Replacing css file](https://stackoverflow.com/a/19844696/7894673)
Answer: Here it is in VanillaJS, check also if the href on the link tag resolves to CSS File correctly.
const darkBtn = document.querySelector('#dark');
const lightBtn = document.querySelector('#light');
const linkTag = document.querySelector('#theme');

darkBtn.addEventListener('click', () => {
  linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Dark.css')
});

lightBtn.addEventListener('click', () => {
  linkTag.setAttribute('href', '~/lib/bootstrap/dist/css/Light.css')
});

Comment: You must have attached at all times the bootstrap CSS file, if you want themes, just write the CSS files with the selectors to overwrite the original CSS values. You can also have attached the files with a dark and light theme at all times and just add a class to the body depending on your selectors.
Comment: Hi, Thanks for your answer. Unfortunately this did not work for me. Within my _Layout page i have   and the js i have placed in the bootstrap.js file. Not sure exactly why it is not working. If you can see any other issues it would be appreciated.
Comment: Try to add this code in the footer in a script tag. When you are clicking when you inspect the script changes anything?
Comment: Hi Lucjan, when running this with the snippet you have provided in the footer section. This seems to remove any sort of bootstrap associated with the application, however something  has changed at least now when clicking the button.
Answer: You probably need following code:
$('#dark').click(function () {
    $('#theme').attr('href', '~/lib/bootstrap/dist/css/Dark.css');
});
$('#light').click(function () {
    $('#theme').attr('href', '~/lib/bootstrap/dist/css/Light.css');
});

Your code is looking for a link-element where the href literally starts with ~/. In your razor page the href starts with this string. But ASP.NET replaces this with the path for the content-root, so for the browser, the href does not start with this string.
Comment: Hi, Thnaks for your answer. I tried your snippet and it was the same, nothing happened when i pressed the buttons I am not using razor pages on my MVC application. I am using cshtml pages. For my _Layout page i am not using any server side code so razor is not needed. From my code can you see any issues with the js which i have placed on my bootstrap.js file. Or can you see any other issues which may be causing this?
Comment: I've created a basic example https://github.com/PieterjanDeClippel/DynamicTheme. Just open cmd -> git clone https://github.com/PieterjanDeClippel/DynamicTheme and open the project
Comment: Note that I'm not modifying the original bootstrap.css file. I've created a new css-file where I overload the colors
Comment: Hi, thanks for the response. Have you ran the mvc app you have created? It seems the Application wont change the theme within that. Same issue i have been having
Comment: On my PC it works fine. If you open developer tools (F12) do you get an exception (in pink) in the console?
Comment: Yes i get a few. It wont seem to dynamically switch the css. Is the file in Github the latest version compared to the one you are currently using? I appreciate this help.
Comment: That's right, everything is commited to the repository. I retried the cloning and running the application and I get it working. Can you share an image/text of the errors you're getting in the webbrowser console (modify your question with an EDIT statement). Do you get these errors when loading the page or when clicking the button?
Comment: Can you post a screenshot of the error messages you're getting in de webbrowser console (F12)
Comment: Hi, i have updated your answer with the console error message
Comment: Are you sure that the UseStaticFiles() middleware is still present in the middleware pipeline (Startup.Configure)?
Answer: I downloaded Pieterjan solution and it began to work after I added event.preventDefault() like that:
$(document).ready(function () {
            $('#dark').click(function () {
                event.preventDefault();
                $('#dynamicCss').attr('href', '/css/site-dark.css');
            });
            $('#light').click(function () {
                event.preventDefault();
                $('#dynamicCss').attr('href', '/css/site-light.css');
            });
        });

But website displays light theme again after refreshing the page.


Standardised path coefficient values in a SEM multigroup comparison are very close and yet one is significant for one group while the other is not?

Question: I am testing the hypothesized effect in a model using SEM A -> B between two groups. The results of the standardised path coefficients (SPC) are Group 1: spc = 0.334 p < 0.001;
Group 2: spc = 0.316 p = 0.181. I would have expected the effect of group  2 to also be significant although it is worth noting that there are differences in the group sizes (group 1 = 72 group 2= 189). Is this an issue caused by the difference in the group sizes?
Answer: Yes, the standard error (and hence the p-value) depend on the group size.
It's also possible that other things vary between the groups, such as relationships with other variables.


How to write a permutation with both identical and distinct objects

Question: Let's say we have AEIOUXXXXX, 5 distinct vowels and 5 identical Xs. How can I represent a permutation using the two line notation?
I thought of doing this, but I don't think it works.
$$\binom{AEIOUXXXXX}{XOXIOAXEXX}$$
Comment: You could number the X's maybe? So that you get $\binom{AEIOUX_1X_2X_3X_4X_5}{X_5OX_1IOAX_3EX_4X_2}$.
Comment: I also tried this, but it would make the Xs distinct
Answer: You would keep the top line as usual in two line notation, and the bottom line has the letters. So for your example
$$\left(\begin{array}{llllllllll}1&2&3&4&5&6&7&8&9&10\\X&O&X&I&O&A&X&E&X&X\end{array}\right)$$
The indexing set still consists of $10$ distinguishable indices, it is the $X$'s in the permutation that are indistinguishable. The indices where they occur are still distinguishable.
The elements on the top and bottom in two line notation need not be the same.
There is such a thing as indistinguishable elements on the top in two line notation, but this is no longer a permutation, but rather a generalized permutation. See the Robinson-Schensted-Knuth correspondence.


How to put all related imports in one separate file and use it across the react app

Question: I have included a fontAwesome library into my react app. now i'm trying to create a react definition file like with key value pairs. like below
icon_def.js

import { library } from '@fortawesome/fontawesome-svg-core'
import { fas, faMousePointer } from '@fortawesome/free-solid-svg-icons'
import { far, faHandPaper, faLaugh } from '@fortawesome/free-regular-svg-icons'

library.add(fas, faMousePointer)
library.add(far, faHandPaper, faLaugh)

const icon = {
    faMousePointer : ["fas", "mouse-pointer"]
}

now is it possible to use this across react project. like below
<FontAwesomeIcon icon={icon.faMousePointer} className={'hi-c'} />

Answer: So using this approach, you have to export icon in icon_def.js and export it whenever you wanted to use it:
import { library } from '@fortawesome/fontawesome-svg-core'
import { fas, faMousePointer } from '@fortawesome/free-solid-svg-icons'
import { far, faHandPaper, faLaugh } from '@fortawesome/free-regular-svg-icons'

library.add(fas, faMousePointer)
library.add(far, faHandPaper, faLaugh)

const icon = {
    faMousePointer : ["fas", "mouse-pointer"]
}
export default icon;

So whenever you wanted to us it:
//Sample.js
//assuming icon_def is in the root directory
import icon from "/icon_def"
.
.
.
<FontAwesomeIcon icon={icon.faMousePointer} className={'hi-c'} />

This is the good practice. However, if you want to have access to the icon throughout your application in the browser, you can also use windows object this way:
windows.icon = {
    faMousePointer : ["fas", "mouse-pointer"]
}

And then Whenever you needs it:
<FontAwesomeIcon icon={windows.icon.faMousePointer} className={'hi-c'} />
But as it might cause conflict with other libraries it is not recommended.


Basic question on merging functions from different dimensions ($g(f) = g \circ f, f = \mathbb{R}^2 \to \mathbb{R}, g = \mathbb{R}^4 \to \mathbb{R}^2$)

Question: Is it possible to merge 2 functions in that order: $g(f) = g \circ f$ when:

$f(x_1 ; x_2) = -8x_1 + 3x_2$ [$\mathbb{R}^2 \to \mathbb{R}$]
$g(x_1 ; x_2 ; x_3 ; x_4) = (x_1 + x_2 - x_3 - x_4 \ ; \ -2x_1 + 5x_3 - 7x_4)$ [$\mathbb{R}^4 \to \mathbb{R}^2$]

Will the answer be:
$$g(f) = g \circ f = g(-8x_1 + 3x_2) = (-8x_1 + 3x_2 \ ; \ -2(-8x_1 + 3x_2))$$
I in my assumption, while operating on g, I treat everyting as $x_1$ and make $x_2 = 0 , x_3 =0, x_4 =0$
Is that correct?
Answer: No, this makes no sense. You can do $f\circ g$, but not $g\circ f$. $f(x)\in\Bbb R$ and $g$ needs an input from $\Bbb R^4$, right?
Comment: great, thanks, q closed
Comment: You're not supposed to close questions as soon as they're answered. Just accept the answer and move on.
Comment: Yeah, I mean that I don't need anybody more to help me, I can accept it in 10mins. And that is what I will do. I mean that by "question closed.
Comment: Gotcha. No problem. :)


Estimate for the operator $(1-\Delta)^{-\sigma/2}$

Question: I have the following Banach Space
$Y_T=L^{\infty}(0,T; H^1(\Omega))\cap L^p(0,T; L_\sigma^q(\Omega))$
where $L_\sigma^q(\Omega)=(1-\Delta)^{-\sigma/2}(L^q(\Omega))$ with its norm
$$\|u\|_{Y_T}=\max_{|t|\leq T}\|u(t)\|_{H^1}+\|(1-\Delta)^{\sigma/2} u\|_{L^p(0,T; L^q)}$$ such that
$p>\max(\beta-1,2), 1/p+1/q=1/2, p<\infty$ and $\sigma=1-1/p.$
I don't get to obtain the following estimate estimate
$\|(1-\Delta)^{\sigma/2} u\|_{L^p(0,T; L^q)} \leq C\|u\|_{Y_T} $
Could anyone help me?
Answer: Is the final inequality written correctly? As presented it is trivial:
$$
\|(1-\Delta)^{\sigma/2} u\|_{L^p(0,T; L^q)} \le \|(1-\Delta)^{\sigma/2} u\|_{L^p(0,T; L^q)} + \max_{|t| \le T} \|u(t)\|_{H^1} = \|u\|_{Y_T}.$$
Comment: I'm sorry! Actually,  if I define the operator
$$
\Phi(h)(t):=e^{i\,t\,\Delta}h_0+\int_0^t e^{i(t-\tau)\,\Delta}\,\left[\mathcal{R}_0 h\,(\tau)-i\,|h(\tau)|^2h(\tau)\right]\,d\tau$$ wher $R_0$ is pseudo- differential operator of order $0$.
  I want to prove that $\Phi$ is a contraction on a ball of the Banach space $ Y_T .$ I could not get to obtain
$\|(1-\Delta)^{\sigma/2}\Phi(h)\|_{L^p(0,T; L^q)}\leq$  terms of  $\|h\|_{Y_T}.$


Showing $\lim_{x \to 0}\frac{\sin x}{x}=1$ with epsilon-delta

Question: According to the definition of $\epsilon$-$\delta$ of a limit we have:
$\forall \epsilon \gt 0$, $\exists \delta \gt 0$ such that
$$0 \lt |x-a| \lt \delta \implies |f(x)-L|\lt \epsilon$$
Now I tried to prove $$\lim_{x \to 0}\frac{\sin x}{x}=1$$
We are given $\epsilon$ and we need to figure out $\delta$
So we have:
$$\left|\frac{\sin x}{x}-1\right|\lt \epsilon$$
Assuming $x \gt 0$ we get
$$|\sin x-x|\lt x\epsilon$$
and for $x \gt 0$ we have $x \gt \sin x$
So
$$x-\sin x\lt x\epsilon$$
$$x(1-\epsilon)\lt \sin x \lt 1$$
So we get
$$x \lt \frac{1}{1-\epsilon}$$
Hence $$\delta=\frac{1}{1-\epsilon}$$
Now I took $\epsilon=0.01$ to get $\delta=\frac{100}{99}=1.0101\cdots$
Now $$\left|\frac{\sin 1.0101...}{1.0101...}-1\right|=|0.8384-1|=0.161$$
But $$0.161 \gt \epsilon=0.01$$
Why is this contradictory?
Answer: There is no reason for your $\delta$ to works. Your are after a $\delta>0$ such that$$\lvert x\rvert<\delta\implies\left\lvert\frac{\sin(x)}x-1\right\rvert<\varepsilon.$$You concluded from the inequality$$\left\lvert\frac{\sin(x)}x-1\right\rvert<\varepsilon.\tag1$$that, if $x>0$, then $x<\frac1{1-\varepsilon}$. But you are not supposed to extract conclusions from $(1)$. Instead, you are are supposed to prove that it holds if $\lvert x\rvert<\delta$, for some $\delta>0$.
I must say that I don't think that it is a good idea to prove that $\lim_{x\to0}\frac{\sin(x)}x=1$ using the $\varepsilon-\delta$ definition.
Comment: @Umesh shankar, use the book "Examples and Theorems in Analysis" by Peter Walker or "Analysis I" by Terence Tao.
Comment: ok can you recommend any good book which explains this concept of $\epsilon-\delta$ with lot of examples
Answer: You found that
$$ x(1 - \epsilon) < \sin x ,$$
which implies that
$$ x < \frac {\sin x}{1-\epsilon}.$$
The way you constructed this, it is a tight bound, meaning there is no room for any additional error.
If you choose any number greater than
$ \frac {\sin x}{1-\epsilon},$
you will end up outside the epsilon bounds that you set.
And then you went and chose a number that you knew was greater than
$ \frac {\sin x}{1-\epsilon}. $
So it is not surprising at all that it did not work.
Here is a hint for making problems like this easier. If you overestimate $\delta$ it will give you a wrong result every time.
But there is no penalty (at least none mathematically) for underestimating $\delta.$
If the exact bound is hard to calculate, as it is here, go for something between zero and the exact bound.


sync do sequelize não está funcionando

Question: salve comunidade! estou tentando usar o sequelize, onde no meu server.js coloquei o comando:
const db = require("./app/models");
db.sequelize.sync();

porém ao rodar o node ser.js apresenta a seguinte mensagem:

Alguém me salva?
Comment: A mensagem diz que o `db.sequelize` não foi definido. Dá uma olhada nas configurações do teu db, como ele foi inicializado...
Comment: Dá uma olhada [na documentação](https://sequelize.org/docs/v6/getting-started/) e compara com o teu código, para ver os motivos de não estar definido...
Comment: olhei na documentação e consegui resolver.

vou postar a resposta.
Answer: No exemplo usado, o sequelize estava na versão 5.21 o meu está na versão 6.20.
Com isso na declaração o meu precisava de chaves:
const { Sequelize } = require("sequelize");

Enquanto no exemplo que estava olhando não tinha.
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

sync do sequelize não está funcionando


AspectJ Spring Boot catch method with boolean parameter

Question: I use aspectj and spring boot.
I am trying to log a message when a method(boolean value) is called.
aspects are working in general, but my expression for catching must be wrong
it is working with (but is of cause catching every method):
    @Before("execution(* de.fhb..*(..))")

also working (catching with only one parameter)
    @Before("execution(* de.fhb..*(*))")

now the problem:
    @Before("execution(* de.fhb..*(boolean))")

or
    @Before("execution(* de.fhb..*(java.lang.Boolean))")

does not work. Any help? The mistake must be between execution(* de.fhb..*((my error i think))
here my files (getter && setter are generated with lombok):
pojo:
package de.fhb.showcase;

@Getter @Setter
public class Show {

    private String name;
    private boolean live;

    public void makeShowLive(boolean value) {
        live = value;
    }
}

aspect:
package de.fhb.aop;

import javax.inject.Named;

import lombok.extern.java.Log;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
@Named
@Log
public class CleanCodeAspect {

    @Before("execution(* de.fhb..*(..))")
    public void checkStyleBooleanParameter() {

        log.warning("You used a method with only one boolean parameter. "
                + "Refactor it into 2 methods with True, False at the end.");
    }

}

Comment: Try `java.lang.boolean`. I also doubt that creating to methods like `setLiveTrue()` or `setLiveFalse()` is clean code. It should be more functional like `enable()`/`disable()` or `show()`/`hide()`. But that could be just me.
Comment: java.lang.boolean gives me that error: warning no match for this type name: java.lang.boolean
[Xlint:invalidAbsoluteTypeName]
at org.aspectj.weaver.tools.PointcutParser.parsePointcutExpression and with the clean code i got this idea from http://www.planetgeek.ch/wp-content/uploads/2013/06/Clean-Code-V2.1.pdf (Selector / Flag Arguments) it is only a simple example (not the standard logging, time tracing). but thx for your advice
Answer: Your syntax is correct, see and test for yourself without Lombok. I think the problem is Lombok interfering with AspectJ, maybe similar as described here (follow the links there to learn more details). It might be another issue, but that would be my first bet.
Comment: I removed lombok from my pojo but it does not work with boolean. * work fine. Should i post the link to my github repo?
Comment: Yes, please. I tried with native AspectJ, not with Spring. I am not a Spring user normally.
Comment: got it working with the standard sample here https://github.com/svenhornberg/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-aop . I will look for the difference Named and Component wasnt the reason


Amazon EC2 Plugin for Jenkins: ERROR: Unable to launch the agent for EC2

Question: The Jenkins controller is unable to launch slave nodes on EC2 instances started by Amazon EC2 plugin.
The log shows Java being installed that ends up as follows:
Public IP, no root folder specified:
  ....
  xorg-x11-font-utils.x86_64 1:7.5-21.amzn2
  xorg-x11-fonts-Type1.noarch 0:7.5-9.amzn2

Complete!
Nov 06, 2022 1:54:40 PM hudson.plugins.ec2.EC2Cloud
INFO: Verifying: which scp
/usr/bin/scp
Nov 06, 2022 1:54:40 PM hudson.plugins.ec2.EC2Cloud
INFO: Copying remoting.jar to: /tmp
Nov 06, 2022 1:54:40 PM hudson.plugins.ec2.EC2Cloud
INFO: Launching remoting agent (via SSH client process): ssh -o StrictHostKeyChecking=accept-new -o "UserKnownHostsFile=/tmp/ec2_12318726237497378155_known_hosts" -o "HostKeyAlgorithms=ssh-ed25519" -i /tmp/ec2_11819376404929797195.pem firstname.lastname@example.com -p 22  java  -jar /tmp/remoting.jar -workDir /tmp
[11/06/22 13:54:40] Launching agent
$ ssh -o StrictHostKeyChecking=accept-new -o "UserKnownHostsFile=/tmp/ec2_12318726237497378155_known_hosts" -o "HostKeyAlgorithms=ssh-ed25519" -i /tmp/ec2_11819376404929797195.pem email@example.com -p 22  java  -jar /tmp/remoting.jar -workDir /tmp
ERROR: Unable to launch the agent for EC2 (jenkins-ec2-plugin-slave) - jenkins-ec2-plugin-slave (i-0cddd80399db92097)
java.io.EOFException: unexpected stream termination
    at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:459)
    at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:404)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:437)
    at hudson.slaves.CommandLauncher.launch(CommandLauncher.java:170)
    at hudson.plugins.ec2.ssh.EC2UnixLauncher.launchScript(EC2UnixLauncher.java:270)
    at hudson.plugins.ec2.EC2ComputerLauncher.launch(EC2ComputerLauncher.java:48)
    at hudson.slaves.SlaveComputer.lambda$_connect$0(SlaveComputer.java:298)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:48)
    at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:82)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
command-line line 0: unsupported option "accept-new".
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Launching instance: i-0cddd80399db92097
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: bootstrap()
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Getting keypair...
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Using private key j2 (SHA-1 fingerprint e4:b8:50:f9:87:5c:cb:e6:0d:c1:e2:99:0a:08:eb:db:08:6e:c5:a7)
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Authenticating as ec2-user
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Connecting to 18.104.22.168 on port 22, with timeout 10000.
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Connection allowed after the host key has been verified
Nov 06, 2022 1:58:52 PM hudson.plugins.ec2.EC2Cloud
INFO: Connected via SSH.
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: connect fresh as root
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: Connecting to 18.104.22.168 on port 22, with timeout 10000.
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: Connection allowed after the host key has been verified
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: Connected via SSH.
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: Creating tmp directory (/tmp) if it does not exist
Nov 06, 2022 1:58:53 PM hudson.plugins.ec2.EC2Cloud
INFO: Verifying: null -fullversion

HTTP ERROR 404 Not Found

URI:    /computer/EC2 (jenkins-ec2-plugin-slave) - jenkins-ec2-plugin-slave (i-0cddd80399db92097)/logText/progressiveHtml
STATUS: 404
MESSAGE:    Not Found
SERVLET:    Stapler

Private IP, no root folder specified:
  ....
  xorg-x11-font-utils.x86_64 1:7.5-21.amzn2
  xorg-x11-fonts-Type1.noarch 0:7.5-9.amzn2

Complete!
Nov 06, 2022 1:39:09 PM hudson.plugins.ec2.EC2Cloud
INFO: Verifying: which scp
/usr/bin/scp
Nov 06, 2022 1:39:09 PM hudson.plugins.ec2.EC2Cloud
INFO: Copying remoting.jar to: /tmp
Nov 06, 2022 1:39:10 PM hudson.plugins.ec2.EC2Cloud
INFO: Launching remoting agent (via Trilead SSH2 Connection):  java  -jar /tmp/remoting.jar -workDir /tmp
ERROR: unexpected stream termination
java.io.EOFException: unexpected stream termination
    at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:459)
    at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:404)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:437)
    at hudson.plugins.ec2.ssh.EC2UnixLauncher.launchScript(EC2UnixLauncher.java:283)
    at hudson.plugins.ec2.EC2ComputerLauncher.launch(EC2ComputerLauncher.java:48)
    at hudson.slaves.SlaveComputer.lambda$_connect$0(SlaveComputer.java:298)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:48)
    at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:82)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

HTTP ERROR 404 Not Found

URI:    /computer/EC2 (jenkins-ec2-plugin-slave) - jenkins-ec2-plugin-slave (i-0137aefa185f5bc64)/logText/progressiveHtml
STATUS: 404
MESSAGE:    Not Found
SERVLET:    Stapler

+ jenkins --version
2.361.3
+ java --version
openjdk 11.0.16 2022-07-19 LTS
OpenJDK Runtime Environment (Red_Hat-220.127.116.11.8-1.amzn2.0.1) (build 11.0.16+8-LTS)
OpenJDK 64-Bit Server VM (Red_Hat-126.96.36.199.8-1.amzn2.0.1) (build 11.0.16+8-LTS, mixed mode, sharing)
Amazon Linux 2 Kernel 5.10 AMI 2.0.20221004.0 x86_64 HVM gp2
Amazon EC2 plugin Version 2.0.3

Tried changing security groups and roles, private and public IP settings with an ec2-user root folder and other settings.
Any help would be much appreciated!
Answer: It looks like the Amazon EC2 plugin installs Java 8:
INFO: Verifying: java -fullversion
bash: java: command not found
Nov 06, 2022 1:38:45 PM hudson.plugins.ec2.EC2Cloud
INFO: Installing: sudo yum install -y java-1.8.0-openjdk.x86_64

The new Jenkins version 2.361.3 requires Java 11. In the section Init script add the following commands to install Java 11 (Amazon Linux/RHEL):
sudo yum update -y
sudo yum upgrade -y
sudo amazon-linux-extras install java-openjdk11 -y

For Ubuntu use apt instead.
For Amazon Linux 2023:
sudo yum install java -y

NOTE: If you are installing Maven on Amazon Linux 2/2023 using the command:
sudo yum install maven -y

it may try to install the java-17-amazon-corretto package as a dependency. To avoid conflicts with other Java packages, you can exclude the installation of Java.


Was Isaac Albéniz a Romantic?

Question: I'm a big fan of Isaac Albéniz and I love classical guitar.
As a big classical guitar fan, I obviously love Baroque music and I love Flamenco as well. I am not the biggest fan of Romantic music and my humble opinion is that the piano is the main instrument of this era and hence not many Romantic pieces were transcribed to the classical guitar (please correct me if I'm wrong).
With that said, considering Isaac Albéniz lived from 1860 to 1909 (therefore during the Romantic period), is he considered a Romantic composer? He has a lot of Flamenco sounding pieces as well, so could he be considered a popular composer instead of a classical composer? If so, considering the amount of Baroque ornamentation in Flamenco music, can we say that it's kind of a gray area?
(there's probably not a "black or white" way to answer this, but I'm looking forward to reading some of your answers...)
Answer: When Isaac Albéniz found his musical voice, I suppose it could best be described as 'Spanish Nationalist'. The nationalist movement ln music is generally categorised as 'Romantic' I think.
This Wiki article postulates a 'Golden Age' of guitar works in the Romantic period.
https://en.wikipedia.org/wiki/Classical_guitar_repertoire#Romantic_era
Comment: Albéniz went beyond simply copying folk tunes.  Maybe not so much in the works commonly transcribed for guitar though.  But are the Bach suites 'classical'?   Chopin waltzes?  And what does it matter how you label them anyway?
Comment: Baroque:  Musical development through counterpoint.  Classical: Musical development through structural key contrasts.  Romantic: Tunes and colours.    If you accept those basic descriptions, I guess Albéniz is Romantic.  But it all overlaps.
Comment: That's a very good point. I hadn't thought about the nationalistic component of the Romantic era, and he definitely was a Spanish nationalist in his compositions. However, I'm finding it hard to link the Spanish "folk music" that Albéniz played and "classical music". I mean, if it's nationalist folk it can't be classical, right? How can one differentiate Isaac Albéniz, as a Romantic composer, from other Spanish folk/popular composers of the 19th century whose pieces are not considered classical music?
Comment: Well the idea isn't to exactly _label_ anybody, but more to understand if generally Albéniz is considered a romantic or not. Saying that he belongs in a gray area is also fine if that's the case. I understand we can't reduce any single composer to one era or label.

Was Isaac Albéniz a Romantic?


Does every non-trivial element of $\mathbb{Z}_p$ generate the group?

Question: This just popped up in my head and I just wanted to make sure if I'm right.
Every element (except the identity element $0$) of the group $\mathbb{Z}_p$ (under addition and $p$ is prime) is a generator for the group. For example, $\mathbb{Z}_5 = \langle 1 \rangle = \langle 2 \rangle = \langle 3 \rangle = \langle 4 \rangle$.
Thanks!
Answer: Yes. In general, the generators of $\mathbb{Z}_n$ are those integers $m$ such that $\gcd(m,n) = 1$.
Comment: @IncnisMrsi I did commit the sin of denoting a congruence class by one of its representatives, but this is harmless here as the property of being relatively prime to $n$ makes sense on the quotient.
Comment: The question wasn't about *integers* suitable for generation of the group. It was about an *element of the group* as the generator.
Answer: Yes!
$$nm\equiv 0\iff  m\equiv 0 \text{ or } n\equiv 0$$
Thus shows that $m,2m,\ldots, pm$ are distinct which is what you needed.
Comment: Another way to see it: By Lagrange's theorem, every element must have order that divides $p$. Only $0$ may have order $1$, so the other elements must have order $p$ (since it is prime). An element whose order is the order of the group generates the group, so we're done.
Answer: You can show that $\mathbb{Z}_p$ is a field, so if $H= \langle h \rangle$ with $h \neq 0$, $1 \in H$ since $h$ is invertible; you deduce that $H= \mathbb{Z}_p$, ie. $h$ is a generator.


Intelligently handling puppet master unavailable (almost caching)

Question: Is there a good way to set up caching for Puppet, specifically templates? I have a number of modules that would be really, really useful to have available in a DR situation.
Proposed Solution
I know there isn't an inbuilt way to set up caching directly, based on the template documentation. Natively templates are rendered server side and there isn't a direct way to change this.
I was thinking about using a custom mount point  to pull down specific modules I flag for offline use.
This would be pointed back to the same directory puppet master reads from, to avoid things getting out of sync. I actually already have the basics for this working.
Once I have a local copy some kind of logic could perform a puppet run using the local mirror.
This would be a pseudo masterless puppet, something like
puppet apply --modulepath ./modules manifests/site.pp

How can I have effectively have puppet say puppet master isn't available, so execute these commands?
Comment: I presume there are reasons you don't want a masterless puppet setup?
Comment: Do you need the templates to be re-rendered based on dynamic fact values? I ask because the agent **does** cache templated files out of the box.
Comment: @FelixFrank that is exactly it.
Answer: As long as the master is operating normally, the agent will update the timestamp on $vardir/state/state.yaml on every run. A failing master (including compiler errors etc.) will lead to an outdated state.yaml file. You can use its freshness to determine whether your master is up and well.


React: How to select all text in each div

Question: When I pressed Ctrl + A (Command + A), it's select all text in the page. how can I select only the letters inside the selected div when I pressed Ctrl + A (Command + A)?
Below is my full code.
import React, { useState } from 'react';

const Test = () => {
  const [chatList, setChatList] = useState([]);
  const onSubmit = (e) => {
    e.preventDefault();
    const value = e.target[0].value;
    setChatList([...chatList, { value }]);
  };
  return (

      <form onSubmit={onSubmit}>
        <textarea placeholder="Enter text"></textarea>
        <button type="submit">submit</button>
      </form>
      {chatList.map((chat, index) => (

          {chat.value}

      ))}

  );
};

export default Test;

Comment: You're trying to force the user's browser to not work how it was designed to work. Even if you could figure it out, that's not a good idea. Why would you want to program a key to do something that the user wouldn't expect? Have a UI button to do it if necessary, although the whole notion seems weird to me.
Comment: @xpusostomos Well, if it's not the direction the browser is aiming for, there's nothing I can do about it. Thank you for answer!
Answer: Browsers are not able to selectively highlight using Ctrl+A. Selecting all truly selects all text on the page. There may be browser plugins you can use to select different lines at once but you won't be able to reliably provide others with that experience.
While I don't know the exact use case, I'm going to assume it's to copy/paste the content.
I'd recommend grabbing the values of the different content areas you want and putting those into a textarea (you'll almost certainly want the textarea hidden with style="display:none").
Then, once the content is all in the textarea, you can copy it to the clipboard programatically.
Then instead of having users hit Ctrl+A, you can provide an easy "Copy" button which is more instructive to people not familiar with the select all shortcut.
Here's a basic example showing the copy function in vanilla JS.
<textarea></textarea>

This is a very basic example of copying data. For more details, view this answer: How do I copy to the clipboard in JavaScript?
Comment: Well, if it's not the direction the browser is aiming for, there's nothing I can do about it. Thank you for answer and example!


R - paste() invokes as.numeric() when passing data frame to it?

Question: I have a particular problem with Rs paste-function in combination with the row- and coloumn-selection of a data frame. It seems that paste always surrounds it's input-arguments with as.numeric() or something which does a similar job.
Here is a code snippet of what I am doing:
paste(df[1, c("entry1", "entry2")], collapse="; ")

This passes the first row of a data frame df with column entries for column "entry1" and "entry2". I assumed an output like this:
"Auffuellung; Holozaen"

Instead I am receiving the concatenated number equivalents (not indices) of the passed data frame entries:
"1; 5"

Calling str(df[1, c("entry1", "entry2")]) on my real data base results in the following output (German, do not wonder ;) ):
'data.frame':   1 obs. of  2 variables:
 $ Hauptbestandteile: Factor w/ 38 levels "Auffuellung",..: 1
 $ Chronografie     : Factor w/ 18 levels "Devon","Famennium",..: 5

What am I doing wrong in this case? Until now, I never faced such a problem with the paste-function and I would have never expected something like this to happen. So, how do I solve the problem and get the correct output of concatenated strings instead of concatenated number equivalents?
Thank you in advance!
Comment: Sorry, that I didn't described it ealier. It is the first row of a data frame, containing 2 column entries.
Comment: @SimonO101 I added the `str`-output the the question-post.
Comment: @SimonO101 , my expected output is "Auffuellung; Holozaen" after the `paste`. Maybe the solution is to somehow extract the string values which are hidden behind the dataframe-internal, somehow sorted enumeration.
Answer: Your problem is related to the fact that your data are factor variables. paste is pasting the underlying "integer" code. This is confusing and not immediately obvious as to how to get around it. You need to turn it into a vector using unlist() and it will work as exepcted...
Example
df <- data.frame( Month = factor(month.name) , Short = factor(month.abb) )
df[ 1 , ]
#    Month Short
#1 January   Jan

paste( df[ 1 , ] , collapse = "; " )
#[1] "5; 5"

paste( unlist( df[ 1 , ] ) , collapse = "; " )
#[1] "January; Jan"

Of course when reading your data in you can avoid strings being automatically converted to factors using the stringsAsFactors = FALSE argument to read.*.
See the R room chat log here for a discussion on this.
Comment: I just found out that there is a `stringsAsFactors`-argument in the `read.csv`-function. It is set to `stringsAsFactors=default.stringsAsFactors()` as default. In my case it hase to be `stringsAsFactors=FALSE`. This absolutely solves any issues. Please add this to your answer and I will accept it as the right one.


Unobtrusive Javascript gallery navigation

Question: I have a slideshow on my site - it all works as it should - But I want to change the navigation for it to be unobtrusive.
How do I do it? The navigation is:
<prev
start
view
stop
next>

Comment: Using [closures/scopes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures) and [self executing anonymous functions](http://stackoverflow.com/q/592396/1960455), and [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener) and make sure it is useable without javascript.
Answer: You can attach events after they are loaded into the dom. There are differances in how IE and wc3 attach events are handled, this is where libraries like jquery shine because they normalize the event model.
adding event listener cross browser
http://www.quirksmode.org/js/events_advanced.html
jquery
$('#slideshow_prev').click(slideshow.previous);

without jquery w3c standard
document.getElementById("slideshow_prev").addEventListener("click", slideshow.previous);

for legacy ie
document.getElementById("slideshow_prev").attachEvent('onclick',slideshow.previous)

Answer: Here's a basic example.
First, remove any inline javascript:
<prev
start
view
stop
next>

Get element references:
var prev = document.getElementById('slideshow_prev');
var start = document.getElementById('slideshow_start');
//etc

Attach event listeners to each element:
prev.addEventListener('click', slideshow.previous);
start.addEventListener('click', slideshow.slideshow.play);
//etc

Optimize/Automate
Rather than manually getting each reference and attaching the listeners, I created an object to associate an id with a function, then iterated over the object's properties to automate the process: Live demo (click).
var x = {
  slideshow_prev: slideshow.previous,
  slideshow_start: slideshow.slideshow.play,
  slideshow_view: slideshow.hotlink,
  slideshow_stop: slideshow.pause,
  slideshow_next: slideshow.next
};

for (var prop in x) {
  var elem = document.getElementById(prop);
  var clickFunc = x[prop];
  elem.addEventListener('click', clickFunc);
}


Choosing prior for exponential data

Question: I'd like to calculate Bayes Factor for two exponential datasets, testing $H_0: \lambda_1 = \lambda_2$ against $H_1: \lambda_1\not=\lambda_2$, and here comes the prior probability $\pi$ for all $\lambda$'s.
Question. How I choose a prior $\pi$ for $\lambda$'s if I want it to be non-informative?
My exponential data models depressive symptoms total score so I guess that prior for $\lambda$'s should have some kind of connection to this, right? I was thinking about flat prior $\pi$  ~ $U[0,1]$.
I am aware of the existence of Jeffreys prior, but as I have learnt from here they're not to be applicable here, 'cause this prior is improper (or 'too improper' for computing Bayes Factors).
Comment: When I think of a non-informative prior, I often think of a uniform prior, so I think that should work
Comment: To my understanding, the [Bayes factor](https://en.wikipedia.org/wiki/Bayes_factor) doesn't require priors (it just comes from the ratio of two likelihoods). Are you after a ratio of posteriors (which would be a BF times a ratio of priors)?
Answer: You can use a Gamma Prior that is almost flat (very little informative) with some specific hyper-parameters if you want a conjugate prior.
Another possbility is to use, for example, an $U[0,k]$ with very large $k$. In both cases how large or small the parameters must be to become very little informative depends on the scale of your data.

Choosing prior for exponential data


Java object access overwriting previous entries

Question: first question attempt here. Trying some interview preparation challenges on parenthesis logging - ie: log the open and close bracket positions of a string. I have tried to use a bracket object, to then use a single array with an open and close position at each entry. The conditions all seem to catch but then the array just duplicates the last results to all entries in the array. Any idea what I'm doing wrong? Have left the printing to screen for my attempts to debug this already and know I'm only considering the basic case so far with my algorithm. Thanks in advance.
class ParanthesisMatch {

static final char leftBracket = '(';
static final char rightBracket = ')';

public static void main(String[] args) {

    String str = "(I (am (the) basic) case)";
    char[] input = str.toCharArray();

    int opens = 0;
    int closes = 0;
    int brackets = 0;

    Bracket[] bracketArray = new Bracket[10];

    System.out.println(input.length);

    for (int i = 0; i < input.length; i++) {
        System.out.println(input[i]);
        if (input[i] == leftBracket) {
            bracketArray[opens] = new Bracket();
            System.out.println("Open trigger: " + i);
            bracketArray[brackets].openBracket = i;
            System.out.println("Open bracket is: " + bracketArray[opens].openBracket);
            brackets++;
            opens++;
        }
        if (input[i] == rightBracket) {
            System.out.println("Close trigger: " + i);
            bracketArray[brackets - closes].closeBracket = i;
            System.out.println("Pos: " + (brackets - closes)
                    + "Close bracket is: " + bracketArray[brackets - closes].closeBracket);
            closes++;
        }
    }

    for (int i = 0; i < brackets; i++) {
        System.out.println("Bracket: " + i + " Open is " + bracketArray[i].openBracket + ", Close is " + bracketArray[i].closeBracket);
    }
}
}

class Bracket {

public static int openBracket;
public static int closeBracket;

Bracket() {
    openBracket = 0;
    closeBracket = 0;
}

public void setOpen(int open) {
    this.openBracket = open;
}

public void setClose(int close) {
    this.closeBracket = close;
}
}

Update - Thank you both very much. I discovered the null pointer exception error after and was able to fix myself with the same change. The static tip was very useful for a lot of issues I've had with my objects! Working code for basic case ( ( ( ) ) ) , not nested ( ( ) ( ) ) yet is:
class ParanthesisMatch {

static final char leftBracket = '(';
static final char rightBracket = ')';

public static void main(String[] args) {

    String str = "(I (am (the) basic) case)";
    char[] input = str.toCharArray();
    System.out.println(input.length);

    int opens = 0;
    int closes = 0;
    int brackets = 0;

    Bracket[] bracketArray = new Bracket[10];

    for (int i = 0; i < input.length; i++) {
        if (input[i] == leftBracket) {
            bracketArray[opens] = new Bracket();
            bracketArray[brackets].setOpen(i);
            brackets++;
            opens++;
        }
        if (input[i] == rightBracket) {
            bracketArray[brackets - 1 - closes].setClose(i);
            closes++;
        }
    }
    System.out.println(input);
    for (int i = 0; i < brackets; i++) {
        System.out.println("Bracket: " + i + " Open is " + bracketArray[i].openBracket + ", Close is " + bracketArray[i].closeBracket);
    }
}
}
class Bracket {
public int openBracket;
public int closeBracket;
Bracket() {
    openBracket = 0;
    closeBracket = 0;
}
public void setOpen(int open) {
    this.openBracket = open;
}
public void setClose(int close) {
    this.closeBracket = close;
}
}

Answer: There are two things wrong with your code.
The first problem is in your Bracket class:
class Bracket {

    public static int openBracket;
    public static int closeBracket;

You have declared the fields openBracket and closeBracket as static, which means that they belong to the Bracket class itself rather than each Bracket object you create.  As a result there is only one copy of each field, shared between the Bracket class and all instances of it.  This explains why the same values are shown for each Bracket at the end.
However, this is not the only problem.  Take the static modifiers away and you get a NullPointerException on this line:
        bracketArray[brackets - closes].closeBracket = i;

The reason for this is that you are accessing the wrong entry in the array. At the point it fails, brackets is 3 and closes is 0, but bracketArray[3] is still null.   You want to be accessing the entry at index 2 instead, so replace brackets - closes with brackets - closes - 1 in all three places you're using it.
After replacing brackets - closes with brackets - closes - 1, I was able to run your code successfully.
What I found surprising about this was that the NullPointerException appeared after removing the static modifier from those two fields.  I made no other modifications, and if I reintroduced the static modifier, the NullPointerException went away.  It turns out that even if you have a null reference, you can still call static methods and access static fields.  For example, if you re-introduce the static modifier to your fields, then the following line will not throw a NullPointerException:
    System.out.println(((Bracket) null).openBracket);


How do you determine if you're ready to join a band?

Question: I've been pondering joining a band for some time now, but I usually get stalled at deciding whether or not I should spend more time learning to play first. I don't want to go through potential embarrassment of being told that I completely suck.
Is there a particular set of skills that you'd say is required before one considers joining a band? I.e. playing common chords, scales, knowledge of notes of the neck, etc. Is being able to compose new melodies important, or is it possible for a new player to get by for a while with someone else working out the arrangements?
I feel like as a fairly new player I'm not yet up for playing covers (I can usually get the rhythm down, but solos? Forget it.) and yet also not that good at creating my own stuff. Does that mean I'm doomed to play by myself for the foreseeable future?
Answer:
Is there a particular set of skills that you'd say is required before one considers joining a band?

Not really. Look for other players at about your own skill level. If you are taking classes, perhaps your teacher can advise you of others looking to play together. If you are reasonably comfortable playing in front of others, you should do reasonably well. I don't consider myself a beginner, but due to an abusive ex, I don't play in front of others. Older students tend to be far more critical of their own abilities, so the "tell me I suck" concern is something a teenager won't have. I am quite comfortable standing in front of a group of strangers and giving a presentation/speech (I've even run for elected office), but put an instrument in my hands in front of even close friends and I choke.

Is being able to compose new melodies important, or is it possible for a new player to get by for a while with someone else working out the arrangements?

This totally depends on the group. I've seen some bands that played in bars who had players of widely different skill levels together in the same band. One could tell the guitarists who were classically trained, as their skills were a lot higher than others. In some of the groups, most of the music was written by one of the players. For an example, look at the early Indigo Girls albums, compare and contrast the songs written by Emily (complex and deep meaning) vs Amy (simple).
Finally, if you are looking to play in bands, you may want to pursue bass (guitar) as those players are a lot less common. Bassists are far more rare and hard to come by.
Comment: Methinks it's all about passion. One must one want to play, not just play in a band. If one doesn't love the bass, I wouldn't recommend picking it up simply for the sake of playing in a band. In music, passion is everything. You won't stake out much for something you don't love. Except, well, playing on a band is more important that what one plays...
Comment: @JimiOke and then there's Paul McCartney who picked up the bass because the band needed a bass player.  They did OK as I recall.  The passion needs to be for music, not an instrument.
Comment: If anyone feels like their technical abilities are inhibiting their creativity, just remember that we live in a world where Bob Dylan is one of the most influential singers of all time.  Artistic merit can be more about the quality of the ideas than the execution.
Answer: Just going to paste Dave Grohl's take on this:

When I think about kids watching a TV show like American Idol or The
  Voice, then they think, 'Oh, OK, that's how you become a musician, you
  stand in line for eight f___ng hours with 800 people at a convention
  center and… then you sing your heart out for someone and then they
  tell you it's not f___in' good enough.' Can you imagine?" he implores.
  "It's destroying the next generation of musicians! Musicians should go
  to a yard sale and buy and old f___ing drum set and get in their
  garage and just suck. And get their friends to come in and they'll
  suck, too. And then they'll f___ing start playing and they'll have the
  best time they've ever had in their lives and then all of a sudden
  they'll become Nirvana. Because that's exactly what happened with
  Nirvana. Just a bunch of guys that had some s__tty old instruments and
  they got together and started playing some noisy-ass s__t, and they
  became the biggest band in the world. That can happen again! You don't
  need a f___ing computer or the internet or The Voice or American Idol.
-- Dave Grohl

Rock 'n' Roll Jedi
Comment: Can you give the source for this quote? Also, it might be fair to make this community wiki.
Answer: I agree with Tangurena's answer.
I would add that if you aren't sure about your skills at the moment, find one or two people you can jam with that are better than you.
I've found that playing with people better than me forces me to get better faster than just playing on my own.
Answer: Joining a band should not be a question of your abilities. Sure, those are important, but the most important factor is your passion for playing with other people. If this is something that drives you or makes you go insane at the very thought of it, then look for a band without delay. Or form yours. You only really get better when you have to perform.
Answer: All a band requires is a couple of people that enjoy playing their instruments and playing them with each other.
Answer: Do both. There isn't a minimum required skill set to play in a band. When I started playing in a band, I could barely follow a song. But I kept practicing on my own. A couple years later we recorded a fairly good album, nothing out of the ordinary for most people, but something I personally I'm very proud of.
It is very important to practice on you own, so you polish you skills and learn new things that the rest of the band don't need or don't want to learn. But it is equally important to play with someone because you will also improve a different set of skills that you just can't practice on your own.
If someone tell you that you suck, so what? Maybe that person doesn't even play nothing more than a plastic rock band guitar or maybe he does play, but at some point he had to suck as much as we all did :-)
Practice is the key, I used to come home from school, finished all my homework and duties and practiced until I fell asleep. Every day, I practiced like 6-8 hours until I got fairly good.
Finally, it is great to get with people of your same skills, so you learn together, but try also to play with someone better, so you will learn from them.
Answer: Joining a little band is very often a transformative experience that others might not understand. They might be thinking it's just music, but very often it's like joining a new family or club where you aren't just learning a new repertoire or act to earn some extra cash, but also how to work together, how to compromise for the good of the whole band, how to cover for each other, and how to learn from each other. I look at it like a child who is just learning to talk, it happens much faster if the child has someone to talk with, some one to practice communicating with. I think it's the same with playing music. Play with people who are better, people who are not as good as, and people who are on the same level as you are. If you are open to learning, they will all teach you something, and you will come away knowing things you didn't know before, probably resulting in advancement musically and socially.
Answer: As others have said, there is no particular thing. However I'd suggest that being able to play reasonably in time is going to help a lot. Because you can play the wrong note at the right time, you may well get off with it, but if you play the right note at the wrong time - well that just doesn't work at all with other people.
(And that's also why everyone needs to work with a metronome sooner or later.)
But the real answer is - just as soon as you find people who you have fun playing with.


ApplicationInsight does not exist in the namespace Microsoft

Question: I've been working my way through video training series on Microsoft's Virtual Academy. The series I'm watching is titled "Windows 10 Development for Absolute Beginners" I'm at the penultimate video when I ran into a problem. Bob Tabor put the following into the constructor of the App class (in App.xaml.cs):
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
    Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
    Microsoft.ApplicationInsights.WindowsCollectors.Session);

However, this line doesn't work at all for me. I'm getting red squiggly lines under Microsoft.ApplicationInsights. And when I compile I get the following error message:

The type or namespace name 'ApplicationInsights' does not exist in the
  namespace 'Microsoft' (are you missing an assembly reference?)

I have tried to add a reference to that, but it didn't work. In fact VS 2017 told me outright that it was impossible to add the reference I'd found.
I'm thinking that the problem is because I'm using VS 2017, whereas when Bob Tabor did the videos he was using VS 2015. Something has changed in the configuration, but I don't understand what. I'm sure the issue is that I need to include some sort of NuGet package. I'd be delighted to do so, only I've no idea what NuGet package to install.
I'm developing for Windows 10, using Visual Studio 2017 Community Edition.
Comment: If you right click your project in solution explorer, it looks like there should be an option to add application Insights sdk into your project. https://learn.microsoft.com/en-us/azure/application-insights/app-insights-asp-net
Answer: For the "Windows 10 Development for Absolute Beginners" series videos,there is a correspondent sample here. If you opened one project you are referenced and build, you will find there are three ApplicationInsights relative Nuget packages referenced, and one ApplicationInsights.config file in the project. This should caused by when OS build is 10240, you create a new Windows 10 universal application in Visual Studio that a reference to Microsoft.ApplicationInsights is added to the references folder automatically. And after that, new builds coming without adding this package automatically.
So that if you just need the error gone you may add the same three Nuget packages:Microsoft.ApplicationInsights 1.0.0,Microsoft.ApplicationInsights.WindowsApps 1.0.0,Microsoft.ApplicationInsights.PersistenceChannel 1.0.0 manually.
But actually, Microsoft.ApplicationInsights is not supported UWP app starting 2.0.0. Currently you should not use ApplicationInsights for UWP app which may be deprecated, but use HockeyApp SDK instead.
Comment: Thank you very much, Sunteen. I wasn't aware of that GitHub repo!


Comparison on the basis of min function

Question: How exactly does the min function work for lists in python ?
For example,
 num = [1,2,3,4,[1,2,3]]
 num2 = [1,2,3,4,5]

 min(num,num2)

gives num2 as the result. Is the comparison value based or length based ?
Answer: First thing - when comparing two lists with min, elements are compared in order.  So it is comparing 1 with 1, 2 with 2... and 5 with [1,2,3].
Second, in python 2, unequal types are allowed to be compared, and give an "arbitrary, but consistent" ordering.  Quoth the docs:

The operators <, >, ==, >=, <=, and != compare the values of two
  objects. The objects need not have the same type. If both are numbers,
  they are converted to a common type. Otherwise, objects of different
  types always compare unequal, and are ordered consistently but
  arbitrarily.
...
(This unusual definition of comparison was used to simplify the
  definition of operations like sorting and the in and not in operators.
  In the future, the comparison rules for objects of different types are
  likely to change.)

In cPython, at least, this comparison is equivalent to comparing the strings that represent their respective types.  Therefore:
5 < [1,2,3]
Out[8]: True

because 'int' < 'list'.  I believe this is an implementation detail, the arbitrariness of this ordering should be stressed.
Thankfully in python 3 this silliness is replaced with TypeError.
Comment: That doc quote seems slightly misleading - I think it was right at some point in the past, but even in Python 2's case, it isn't the whole story anymore. What happens in all versions since 2.1 is that each object is given a chance to answer the comparison: `a < b` calls `a.__lt__(b)` (which can return True, False, or "NotImplemented", the clayton's answer). If it is NotImplemented (or the method doesn't exist), it tries `b.__ge__(a)`. Python 2 will then try `__cmp__`. After all that, if there's still no answer, *then* the default - comparison by type or TypeError is used.
Comment: @lvc yes, I cherry-picked sentences from the docs that were relevant to comparing two built-in types.  All of that information is essentially noise that isn't pertinent to understanding why `5 < [1,2,3]`.
Answer: When you compare incompatible data types in python it compares the "first letter" of the data types. for Ex:
>>> {}<[]
True
'dict'<'list'

here 'd'<'l',hence returns True. The same logic is implemented in all the places wherever you have comparison like <,>,=, min(), max()...
I hope the above example is clear now.

Comparison on the basis of min function


Derivation of advection-diffusion equation

Question: I'd like to request for a reference in which I can look up for derivation of
advection-diffusion equation that is applicable in a variable cross-sectional area.
$$\frac{\partial AC}{\partial t} = \frac{\partial}{\partial x}D\frac{\partial C}{\partial x} - \frac{\partial (vAC)}{\partial x}$$
C is the concentration, A is area, v is velocity and D is diffusion
Answer: The advection-diffusion equation in $n$ dimensions is
$$
\frac{\partial C}{\partial t} + \nabla \cdot (\mathbf{v} C) = \nabla \cdot (D \nabla C).
$$
You can find the derivation of this equation pretty much anywhere, but it comes from the balance of the fluxes in an infinitesimal volume.
If we integrate this equation in the volume between two sections of the duct (I hope you can visualize that), we have
$$
\int_V \frac{\partial C}{\partial t} \mathrm{d}V + \int_V \nabla \cdot (\mathbf{v} C) \, \mathrm{d}V = \int_V \nabla \cdot (D \nabla C)\, \mathrm{d}V.
$$
Let's look at the advective term. Using the divergence theorem, we write
$$
\int_V \nabla \cdot (\mathbf{v} C) \, \mathrm{d}V = \int_{\partial V} \mathbf{v} C \cdot \mathbf{n} \, \mathrm{d}A = \int_{S_1} \mathbf{v} C \cdot \mathbf{n} \, \mathrm{d}A + \int_{S_2} \mathbf{v} C \cdot \mathbf{n} \, \mathrm{d}A + \int_{S_3} \mathbf{v} C \cdot \mathbf{n} \, \mathrm{d}A,
$$
in which $S_1$ is one section, $S_2$ is the other section and $S_3$ is the wall of the duct. Look at what happened: we got rid of the divergence operator and expanded the surface integral into three sections.
If the walls of the duct are impermeable, there is no flow in the direction normal to the wall, and therefore the third term is $0$. Now we assume that $C$ and $\mathbf{v}$ are uniform along each section, and the integrals simplify to
$$
\int_V \nabla \cdot (\mathbf{v} C) \, \mathrm{d}V = \left[ v C A \right]_2 - \left[ v C A \right]_1.
$$
Now, if the sections that define the volume are close, we can write this difference as a derivative,
$$
\int_V \nabla \cdot (\mathbf{v} C) \, \mathrm{d}V = \frac{\partial}{\partial x} (v C A) \Delta x,
$$
in which $\Delta x$ is the distance between the sections. See that this derivative is similar to the divergence operator in the original equation. We transformed the equation to the integral form, but now we are back to the differential form.
If we do the same thing to the diffusion term, assuming that there is no flux of $C$ to the wall (e.g., if $C$ is temperature then the wall is adiabatic), we have
$$
\int_V \nabla \cdot (D \nabla C)\, \mathrm{d}V = \frac{\partial}{\partial x} \left(D \frac{\partial C}{\partial x}  A \right) \Delta x.
$$
This hypothesis (of no flux of $C$ to the wall) is not always valid. If you want to relax this assumption you will need to include a term associated to the flux through $S_3$.
Finally, the transient term is
$$
\int_V \frac{\partial C}{\partial t} \mathrm{d}V = \frac{\partial}{\partial t} \int_V C\, \mathrm{d}V.
$$
If this volume is very thin, $C$ is pratically constant inside it, and the volume integral is $C A\Delta x$. Therefore,
$$
\int_V \frac{\partial C}{\partial t} \mathrm{d}V = \frac{\partial}{\partial t} (AC) \Delta x.
$$
Therefore, the equation is
$$
\frac{\partial}{\partial t} (AC) + \frac{\partial}{\partial x} (v C A) = \frac{\partial}{\partial x} \left(A D \frac{\partial C}{\partial x}  \right).
$$
I find it unlikely that the duct shape will be varying with time. In that case, you can take $A$ outside the time derivative:
$$
A \frac{\partial C}{\partial t} + \frac{\partial}{\partial x} (v C A) = \frac{\partial}{\partial x} \left(A D \frac{\partial C}{\partial x}  \right).
$$
As a final comment, notice that the equation in the question lacks an $A$ in the diffusive term. The equation derived here corrects this.


Create form via a controller

Question: I have a template in which I've manually built a form. It renders some variables that come from a controller.
I've looked over the Form API and I think I should build the form using that. But I'm not quite sure how to go about it.
I'm relatively new to Drupal 8 and to be perfectly honest the Documentation is good, if one knows what to look for. It's not the case here.
Basically what I'm asking, is it possible(or rather advised) to somehow grab the form in the controller, and instead of passing the variables to the template, simply pass the created form to the template?
I'm assuming it would be better to do that, although I'm note quite sure that's the case.
Answer: This is definitely possible (and preferable). There are a few ways to do this, but I think the preferred approach is to first specify your form in your routing entry (mymodule.routing.yml)
mymodule.some.route:
  path: '/foo/bar'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'My form title'

The routing system will automatically build your form for you. The class \Drupal\mymodule\Form\MyForm should implement FormInterface. An easy starting point is to extend \Drupal\Core\Form\FormBase.
There are several examples of this in core. For instance, the entity.user.admin and user.admin_permissions routes in users.routing.yml.
Answer: Too late but incase someone stumbles across this:-
Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8
And if you want to embed a form in controller check this out:- How do I embed a form in a controller response?
To theme your form. You need to implement hook_theme() in your .module file to define a new theme implementation. Something like this:-
public function buildForm(array $form, FormStateInterface $form_state) {

       //Your code
       $form['#theme'] = 'a_b_c';

       return $form;
}

And then in your .module file attach
function example_theme() {
  return [
    'a_b_c' => [
      'render element' => 'form', // here 'form' is a variable name and can be anything you want.
    ],
  ];
}

And then you can print your variables in templates/a_b_c.html.twig something like:
{{ form.name }} //if name is your form element.

Create form via a controller


What does the property ColSpan in the Material UI TablePagination mean?

Question: What is ColSpan here for?
Example from : https://material-ui.com/components/tables/#table
look for the arrow
        <TableFooter>
          <TableRow>
            <TablePagination
              rowsPerPageOptions={[5, 10, 25, { label: 'All', value: -1 }]}
------------> colSpan={3}
              count={rows.length}
              rowsPerPage={rowsPerPage}
              page={page}
              SelectProps={{
                inputProps: { 'aria-label': 'rows per page' },
                native: true,
              }}
              onChangePage={handleChangePage}
              onChangeRowsPerPage={handleChangeRowsPerPage}
              ActionsComponent={TablePaginationActions}
            />
          </TableRow>
        </TableFooter>

Answer: The component <TablePagination> provides props not listed to <TableCell>, which provides props not listed to the native element. I assume that would be
The attribute colSpan determines how many columns a cell spans.


C++ No appropriate default constructor available C2152 , but I don't specify any constructors?

Question: I am having a problem with that "No appropriate default constructor available" error, and it is probably just ONE TINY thing that I am missing. I'm pretty new to C++, but I'm slowly getting it.
As I understand, C++ will create a default constructor if you don't specify any constructors. However, I get the error even though I have not specified any constructors. I've tried googling solutions to this, but everyone else is either extending a class wrong or HAVE specified constructors, hence they get this error. I HAVE NOT specified any constructors, yet I get this error anyway. The DirectXGame class is below.
DirectXGame.h
#include "StdAfx.h"
#include "DirectInputHelper.h"

class DirectXGame
{
public:
    //DirectXGame();

    bool Initialize(HINSTANCE hInstance, HWND windowHandle);
    void ShutDown();

    bool LoadContent();
    void UnloadContent();

    void Update(float timeDelta);
    void Render();

private:
    HINSTANCE progInstance;
    HWND winHandle;

    D3D_DRIVER_TYPE driverType;
    D3D_FEATURE_LEVEL featureLevel;

    ID3D11Device* pDev;
    ID3D11DeviceContext* pDevContext;
    ID3D11RenderTargetView* pBackBufferTarget;
    IDXGISwapChain* pSwapChain;

    DirectXInput::DirectInputHelper inputHelper;
    DirectXInput::KeyboardState* keyboardDevice;
    DirectXInput::MouseState* mouseDevice;

    bool isShutDown;
};

Notice I have not specified any constructor, as they've been commented out. The actual error is thrown on the line in the main method where I create a new instance of the class.
DirectXApp.cpp
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{

    UNREFERENCED_PARAMETER( hPrevInstance );
    UNREFERENCED_PARAMETER( lpCmdLine );

    if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
        return 0;

    //std::auto_ptr<DirectXGame> DirectXGame( new DirectXGame() );
    DirectXGame* game = new DirectXGame(); //The compile error is on this line.

    bool result = game->Initialize(g_hInst, g_hWnd);

    if(!result)
    {
        game->ShutDown();

return -1;
}

// Main message loop
MSG msg = {0};
while(TRUE)
{
    if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);

        if(msg.message == WM_QUIT)
            break;
    }
    else
    {
        game->Update(0.0f);
        game->Render();
    }
}

game->ShutDown();

//Don't forget to delete the game object, as it is a pointer.
delete game;

return static_cast<int>(msg.wParam);

}
I'm probably just missing one of the many small details you have to pay attention to in C++.
Comment: Should DirectXInput::DirectInputHelper inputHelper be a pointer?
Comment: There are other cases where you will not get a compiler generated default constructor.  Such as when any of the objects in your class do not have a default constructor.  The only candidate I see for that is `DirectXInput::DirectInputHelper inputHelper;` -- Does it have a default constructor?
Comment: You're new to C++, but trying to make a DirectX game? Is there a problem with using an object on the stack though?
Comment: Bet you didnt read the whole error message.
Comment: Does your class have any `const` data members?
Comment: And about making a game, I've programmed in C# and Java for a while, so C++ is kind of a slap to the face, but  all I'm really trying to do is get a feel for DirectX, and learn more detailed C++ along the way. I learn better by doing and playing with it. I'm not programming for anyone.
Answer: You are missing your blank/default constructor, and the compiler cannot guess at how to implement one for you automatically.
C++ will create a blank constructor for you if it is a trivial (non-complex) class. If your class is descended from another class, then its ancestory must implement default constructors or be trivial in themselves.
If your class includes other classes, the included classes must either have default constructors defined for them, or they must be trivial in themselves so that the compiler can implement trivial constructors for them as well.
In your case, the culprit is likely DirectXInput::DirectInputHelper inputHelper; as your class does not have any ancestors, and all your data members are pointers, basic data types, or defined data types other than that one class data variable.
Comment: I changed the inputHelper to a pointer, and that solved the problem. So now I have another questions. A default constructor will NOT be generated if my class contains things other than primitives, pointers, and structs, am I correct about that?
Comment: @NkosiDean: No, not correct.  The easiest way to think about it is this: The compiler-generated default constructor of an object will recursively call the default constructor of each of its sub-objects(or in the case of POD objects, it will just allocate them, essentially).  So if any of your sub-objects do not have default constructors, and are not POD objects, then no default constructor will not (and can not) be generated for you.  Also, if your class has const objects or references, no default constructor will be generated, since those both need to be initialized with some value.


Vuejs2 window get the height scrolled

Question: I'm trying to add a class of sticky to navbar whenever a user scrolls down and remove the class whenever the user scrolls to the top.
So basically I'm trying to find the height scrolled. I have:
mounted(){
    this.setUpRoutes();
    window.addEventListener('scroll', this.handleScroll);
},

destroyed () {
    window.removeEventListener('scroll', this.handleScroll);
},

methods:{
    handleScroll(event){
        console.log("handling event scroll here", event.height());
    }
}

But am getting an error: event.height() is not a function
How do I determine the height scrolled?
Answer: You need to find the scrollTop, not the offsetHeight only.
for example:
Get scroll position and direction with vanilla JS
mounted(){
    this.setUpRoutes();
    window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
    window.removeEventListener('scroll', this.handleScroll);
},

methods:{
 handleScroll(event){
    // I think   document.body.scrollTop is not FF compatible, but for example.
    console.log("handling event scroll here", {top: document.body.scrollTop, height: window.innerHeight });
  }

}

Comment: can you add the green V ?

Vuejs2 window get the height scrolled


Traffic through GKE load balancer to node refused

Question: I've followed the GKE ruby bookshelf example and referenced the kubernetes examples.  While I have resources deployed, I cannot ping my rails frontend node.  I implemented a simple ping route to test the most basic connectivity.
I have decreased replicas to 1 to simplify things, and grabbed the logs from the node to confirm that it is up and running without any errors present.
> wget http://18.104.22.168/ping
--2017-09-15 14:14:54--  http://22.214.171.124/ping
Connecting to 22.214.171.124:80... failed: Connection refused.

Config
apiVersion: v1
kind: Service
metadata:
  name: foo-frontend
  labels:
    app: foo
    tier: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: foo
    tier: frontend
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: foo-frontend
  labels:
    app: foo
    tier: frontend
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: foo
        tier: frontend
    spec:
      containers:
      - name: foo-app
        image: us.gcr.io/foo/api:latest
        imagePullPolicy: Always
        env:
        - name: FORMATION
          value: web=1
        - name: RAILS_ENV
          value: production
        - name: RACK_ENV
          value: production
        - name: RAILS_LOG_TO_STDOUT
          value: enabled
        - name: RAILS_SERVE_STATIC_FILES
          value: "true"
        - name: SECRET_KEY_BASE
          valueFrom:
            secretKeyRef:
              name: production-secrets
              key: SECRET_KEY_BASE
        - name: DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: production-secrets
              key: DB_PASSWORD
        ports:
        - containerPort: 8080

Dockerfile
snippet
EXPOSE 8080/tcp

CMD bundle exec foreman start --formation "$FORMATION"

Procfile
web: bundle exec rackup --port 8080
worker: bundle exec rake run_worker

Status
> kubectl get pods; kubectl get services

NAME                                READY     STATUS    RESTARTS   AGE
foo-frontend-284775361-4pzk3   1/1       Running   0          9m
NAME                CLUSTER-IP      EXTERNAL-IP       PORT(S)        AGE
foo-frontend   10.15.246.177   188.8.131.52   80:30917/TCP   9m
kubernetes          10.15.240.1     <none>            443/TCP        22h

And
> kubectl describe service
Name:           foo-frontend
Namespace:      default
Labels:         app=foo
            tier=frontend
Annotations:        <none>
Selector:       app=foo,tier=frontend
Type:           LoadBalancer
IP:         10.15.246.177
LoadBalancer Ingress:   220.127.116.11
Port:           <unset> 80/TCP
NodePort:       <unset> 30917/TCP
Endpoints:      10.12.2.13:80
Session Affinity:   None
Events:
  FirstSeen LastSeen    Count   From            SubObjectPath   Type        Reason          Message
  --------- --------    -----   ----            -------------   --------    ------          -------
  10m       9m      2   service-controller          Normal      CreatingLoadBalancer    Creating load balancer
  9m        9m      2   service-controller          Normal      CreatedLoadBalancer Created load balancer

Name:           kubernetes
Namespace:      default
Labels:         component=apiserver
            provider=kubernetes
Annotations:        <none>
Selector:       <none>
Type:           ClusterIP
IP:         10.15.240.1
Port:           https   443/TCP
Endpoints:      184.108.40.206:443
Session Affinity:   ClientIP
Events:         <none>

TL;DR

Can you spot any errors in my config?
What is the best next step in debugging? (or any other advice)
Answer: I believe the key problem was I did not specify a targetPort in the service.  I setup a compute static ip as well with gcloud compute addresses create foo-frontend-ip --region=us-central1, so either way, it was one of the two.
apiVersion: v1
kind: Service
metadata:
  name: foo-frontend
  labels:
    app: foo
    tier: frontend
spec:
  type: LoadBalancer
  # use your external IP here
  loadBalancerIP: x.x.x.x
  ports:
  - port: 80
    targetPort: 8080
    protocol: TCP
  selector:
    app: foo
    tier: frontend

Comment: For my case, I created a new frontend with a reserved IP and it worked! Thanks


views slideshow jquery interfering with nice menus

Question: Building a site for my friend who is a lawyer. Every time views slideshow changes slides, it resets the hover state for views slideshow. I tried calling the nice menu javascript at the bottom of the page but that did not help.
http://www.tripodi.devserver2012.com/
Answer: I think it's z-index and it's a CSS issue, not a Javascript issue.
Put the following in your CSS sheet (any one of them that's included in your homepage):
#views_slideshow_singleframe_teaser_section_slideshow-block_1 {
  z-index: 1;
}

ul.nice-menu li {
  z-index: 10;
}