Showing a subset of vectors is linearly independent

Question: Studying "Linear Algebra Step By Step" p. 217, I am trying to understand why my solution is wrong.

Example 3.15
Let $V$ be the vector space of continuous functions defined on the real line. Let $u=\cos(x)$, $v=\sin(x)$ and $w=2$ be vectors in V.
Show that the vectors u, v and w are linearly independent.

I came to the conclusion that set is not linearly independent because I found non-zero scalars $x=2$, $y=1$ and $z=\frac{-1}{2}$ such that the equation
$$2\cos(0)+1\sin(0)+(\frac{-1}{2})2=0$$
is true.
Could someone give me some insight?
Comment: The same scalars would have to work for all values of $x$, not just $x=0$.
Answer: You proved correctly that the function$$x\mapsto2\times\cos(x)+1\times\sin(x)+\left(-\frac12\right)\times2$$takes the value $0$ at $0$. And then what? At, say, $\frac\pi4$, it doesn't take the value $0$. In other words, it is not the null function.
Answer: Formal Proof:
Suppose $$a \sin x+b \cos x+2c\equiv0 \tag1$$ Which means , the above equation vanishes for all $x$
Differentiation yields $$a \cos x-b \sin x \equiv0 \tag2$$  Put $x=0$ to see $a=0$
Differentiate  $(2)$ again and set $x=0$ to see $b=0$. Now $(1)$ implies $c=0$ too, concluding, the set $\{\sin x, \cos x, 2\}$ is independent
Answer: Let $a\cos x+b \sin x+2c=0$ (for  all $x$). Put $x=0$ to get $a+2c=0$. Put $x=\pi /2$ to get $b+2c=0$. Put $x =\pi /4$ to get $\frac {a+b} {\sqrt 2} +2c=0$. It is easy to show that these equations give $a=b=c=0$ so the functions are linearly independent.
Answer: To show linear dependence we should find $a$,$b$ and $c$ which work for any $x$
$$a\cdot \cos(x)+b\cdot \sin(x)+c\cdot 2=0$$
Answer: Another solution: if
$$a\cos x+b\sin x+2c=0\tag{1}$$
identically, then by replacing $x$ by $-x$,
$$a\cos x-b\sin x+2c=0\tag{2}$$
identically. From $(1)$ and $(2)$ we get both $a\cos x+2c=0$ and $b\sin x=0$
identically. As neither $\cos x$ nor $\sin x$ are constant functions,
those imply $a=c=b=0$.


partial least squares with two dependent variables, one continuous and the other binary

Question: I can do use pls2 to predict multiple dependent variables from a matrix of predictor variables at once as follows:
library(pls)
sensory0 <- cbind(green = oliveoil$sensory[,'green'], syrup = oliveoil$sensory[,'syrup'])
oliveoil0 <- list(chemical = oliveoil$chemical, sensory = sensory0)
oopls0 <- pls::mvr(sensory ~chemical, data = oliveoil0, method = 'simpls', validation = 'LOO')
summary(oopls0)

   Data:  X dimension: 16 5
          Y dimension: 16 2 Fit method: simpls Number of components considered: 5

   VALIDATION: RMSEP Cross-validated using 16 leave-one-out segments.

   Response: green
                (Intercept)  1 comps  2 comps  3 comps  4 comps  5 comps
   CV           24.26    23.87    20.51    21.35    23.96    28.38
   adjCV        24.26    23.79    20.41    21.20    23.70    27.98

   Response: syrup
            (Intercept)  1 comps  2 comps  3 comps  4 comps  5 comps
   CV           3.166    2.134    2.319    2.476    2.937    3.066
   adjCV        3.166    2.128    2.304    2.456    2.899    3.021

   TRAINING: % variance explained

   1 comps  2 comps  3 comps  4 comps  5 comps
   X        99.59    99.87   100.00   100.00   100.00
   green    11.69    43.64    45.39    48.52    48.66
   syrup    57.65    58.80    58.80    58.81    62.39

This ends up suggesting that I use two latent variables, and that we end up predicting about 44% of the variability in green and 59% of the variability in syrup.
What if though, one of the two y variables is a binary variable?
medsplit <- function(x){as.numeric(x > median(x))}
sensory2 <- cbind(green = oliveoil$sensory[,'green'], syrup = medsplit(oliveoil$sensory[,'syrup']))
oliveoil2 <- list(chemical = oliveoil$chemical, sensory = sensory2)

Data:     X dimension: 16 5
          Y dimension: 16 2
Fit method: simpls
Number of components considered: 5

VALIDATION: RMSEP Cross-validated using 16 leave-one-out segments.

Response: green
       (Intercept)  1 comps  2 comps  3 comps  4 comps  5 comps
CV           24.26    23.86    20.51    21.35    23.96    28.38
adjCV        24.26    23.79    20.41    21.20    23.70    27.98

Response: syrup
         (Intercept)  1 comps  2 comps  3 comps  4 comps  5 comps
 CV          0.5333   0.4299   0.4251   0.4315   0.5002   0.5267
 adjCV       0.5333   0.4288   0.4233   0.4293   0.4952   0.5208

TRAINING: % variance explained
         1 comps  2 comps  3 comps  4 comps  5 comps
X        99.59    99.87   100.00   100.00   100.00
green    11.70    43.64    45.39    48.52    48.66
syrup    37.79    45.74    47.38    47.46    47.78

In this case, it looks like I am getting out a similar answer and we predict about the same variance in "green" and slightly less than before with the categorical variable for "syrup". Is this a reasonable approach? Alternatively, do I need to do something to more explicitly handle the binary y variable?
I see the plsRglm package does have an option for logistic PLS, but it seems to only handles one dependent variable rather than several. I suppose I could run two models, one to predict the binary variable and one to predict the continuous one. I prefer this pls-2 approach though for interpretability, since it shows how y variables together get predicted by x varaibles together, although maybe that's not a sufficient reason.
Thoughts? I guess my central question here is: What is the best way to use pls to approach a mix of binary and continuous variables?
Comment: PLS2 is not a very common way to go. It is generally used for classification and when the response variables are correlated. If that is not the case, PLS1 is very likely to perform better since you get to choose different number of components for each response and this approach usually yields a model with higher predictive power.
Comment: Fair point. This points to a shortcoming of my example that I posted here. I have two actual problems with data I shoudn't post:  In problem 1
 the response variablesare not  correlated, but have a similar relationship to the predictor variables. Cross-validation suggests suggest one latent variable and when the model predicts high levels of variable y1 they also predict low levels of variable y2. I like PLS2 in this case because it seems to suggest a way in which my x varaibles seem to have common effect on my y variables.
Comment: In a second case, I have a handful of y variables, some discrete and some continuous, that are indeed correlated. I'd like to take advantage of pls-2's ability to handle correlated y predictors in that case.
Answer: Just throwing some ideas:
Let's say your categorical variable whose name is Cat has 4 levels: A, B, C, D.
And you have 1 continuous variable whose name is Cont
I would create response matrix to be used in PLS2 such that for 3 samples: (first line is headers)
A B C D Cont
- - - - ----
1 0 0 0 4.2
0 1 0 0 3.3
0 0 0 1 1.9

So the first sample has A as categorical response and 4.2 as continous response and so on. You can apply PLS2 to this response matrix.
For prediction, you can assign categorical variable as whichever the maximum of A, B, C, D prediction is.
Edit: I forgot that your discrete variable is binary. Then you have only A and B and same logic applies to your case too.
Comment: Thanks! So in this case, the approach that I used in my question would be appropriate, right? It seems then that I don't have to do anything special besides putting binary variables as ones and zeros in the response matrix.
Comment: I am not sure whether it is the best way. But I would surely give it a shot.


A logarithmic Calculation

Question: I have encountered a logarithmic question that I could not solve. Here is the question:

$$\dfrac {\log 64}{\log4}+\dfrac {\log 8}{\log 2}$$
A)1 B)2 C)3 D)5 E)6

Rules of Logarithm:
$$\log_a\left(\frac xy\right)=\log_ax-\log_ay$$
$$\log_ax^n=n\log_ax$$
Here is my calculation:
$$Q=\dfrac {\log 2^6}{\log 2^2}+\dfrac {\log 2^3}{\log 2}$$
$$Q=6\log 2-2\log 2+3\log 2-\log 2$$
$$Q=6\log 2$$
What is the error in my calculation? Thanks in advance.
Comment: Your second line is already wrong. You have to divide the logarithms, not subtract them. That said, the question is properly asked, so +1
Comment: What is the basis of what you denote $\log$?
Comment: 10. As far as I concerned, base is 10 when it is not denoted.
Comment: I edited your question using mathjax. You may want to learn it simple from here. "MathJax basic tutorial and quick reference - Mathematics Meta Stack Exchange" https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: You've confused $\log x/\log y$ with $\log(x/y)$. Use the second rule twice, with $a=4$ ($a=2$) in the first (second) fraction.
Answer: Your mistake was stated in the alternative answer
$$\log_yx=\frac {\log x}{\log y}≠\log \frac xy =\log x-\log y$$
Just use
$$\frac {\log x}{\log y} =\log _yx$$
We have
$$\frac {\log 64}{\log 4}=\log_4{64}=3$$
$$\frac {\log 8}{\log 2}=\log_28=3$$
Comment: I think you know that, for example $\log_4{64}=\log_4{4^3}=3\log_44=3$
Comment: Yes I know. Even though J.G. is the first answer, your answer is more elaborative.

A logarithmic Calculation


How to include a form in a listing page?

Question: I am displaying a content information page. At the end of the content displaying page i need to display a form.
How shall i do it?
What have I done?

Written a menu callback in hook_menu()
Written a method to collect the information
Registered a theme in hook_theme()
Written hook_preprocess_theme() to register variables
Created a template and assign the variables

By doing all the above, I am displaying the Content Information.
What do I need to do, to display a form at the end of the content?
I have done these thing.

Created a form in a function called content_form() (including logic)
Wrote a submission function (content_form_submit()).

My only todo left is displaying the form at the content information page.
Comment:    Just putting this here to get you started ... probably better ways though
Comment: great jukebox.... U r right... I forget to give drupal_get_form... thanks.. Post this is as answer pleze
Answer: The quick and dirty way to print a form defined by hook_form is to use the drupal_get_form function:
print render(drupal_get_form('content_form'));


Centos 5.6 NetInstaller network issues

Question: I burnt into a CD the netinstaller provided by Centos 5.6.
At boot time the installer comes up and after I choose the HTTP option for installation I choose the "Dynamic IP configuration (DHCP)" option. Now, a popup saying:
<code>Sending request for IP information for eth0...
</code>
is stuck and nothing happens. I have connected a cable from the computer to the router..
Any ideas?
Answer: Assuming that the router works and you were able to use the same PC (or another PC) to obtain an IP address, I suspect that the installer is looking for an IPv6 address. I recall that in a number of cases, the installer will hang if it is unable to obtain an IPv6 address (not sure if it is because the router does not support ipv6 or something else entirely).
I would suggest that during the installation to disable ipv6 before obtaining an network address via DHCP. If that doesn't work, I would suggest that you do either a control+alt+F3 or control+alt-ctl4 to see if you are actually getting a DHCP response.
Comment: Rilindo: I can see that DHCP cpmfiguration failed (timed out). What can I do to fix this?
Comment: Let me ask to make sure: are you sure that you able to to use the same router with another computer with no issues? Is it failing at obtaining an IPv4 address?

Can we get the router address as well as netmask and gateway?
Comment: For that matter, also the model name and number of the router.
Comment: Rilindo: Thanks for the reply. Yes, I was able to connect with other computers to that router ..I disabled IPv6 so it fails on IPv4 ... the router address: 10.0.0.138, Subnetmask : 255.0.0.0. The router is Siemens ADSL-SL2-141. Thanks!
Comment: I might suggest you configure with a static IP during the installation. if you router address is 10.0.0.138, use that as the gateway and select a free address within the 10.0.0.0/8 network.

Centos 5.6 NetInstaller network issues


Windows 2008 Failover Cluster AD settings

Question: I have two servers: serverA and serverB.
They can see the same SAN disks: a 4 and a 400 GByte one.
I created the Failover cluster on them, but the cluster says an error:
<code>Cluster network name resource 'Cluster Name' failed registration of one or more associated DNS name(s) for the following reason:
DNS operation refused.

Ensure that the network adapters associated with dependent IP address resources are configured with at least one accessible DNS server.
</code>
AFAIK this is related that the object for ServerA and ServerB in the AD doesn't have permission for the Cluster object in the AD.
Question: What permission and how can I give in the AD to resolve this error message?
Answer: It's an error 1196? Doublecheck that you have set the DNS server adresses right in every networks you have. I had this issue once, cause one of the networks had a different DNS adress, and pushed these errors every half an hour.
Comment: it is 1196, yes. 2 NIC: 1 for accessing the machine, 1 for heartbeat. I set the nameserver for the heartbeat too, but didn't helped. I think it is an AD related issue. It is in the logs at every 15 minutes.


Probability matching problem

Question: Arriving at party n guests throw their hats into pile. When they leave they each take a hat that is chosen randomly from the pile. We want to compute the probability of the event
$A$ that at least one guest leaves with their own hat.

Describe a sample space that can be used to model this experiment. How many sample points belong to it? For $k= 1;2;:::n,$ let $A_k$ be the event that the $k$th guest goes home with their own hat. Which sample points belong to $Ak$, and how many are of them are there?
Write $A$ in terms of the events $A_k$ and hence compute its probability ( assuming outcomes are equally likely).
What is the probability that exactly r guests leave with their own hat.

For (1) I simply said let $X =\{ 1,2,3....n \} $ where each element is the guest numebered from $1$ to $n$ uniquely and define $f:X\rightarrow X$ where $f(i)=j$ would mean $i$'th person got $j$'s hat for $i,j \in X$.
The sample space will be the set of all bijections from $X$ to $X$ and it will have $n! $ sample points.
$k$th person goes home with his own hat would be sample points s.t. $f(k)=k$ for $k\in X$ . There are n sample points ( best case everyone gets his own hat).
(2) I said $A= \bigcup_{k=1}^{n} A_k $  but I don't know how to calculate the probability.
Any help please with this and third part?
Answer: Hint:  For ii, look up derangements.  For iii, choose $r$ guests to get their own hat, then you need a derangement of the rest.
Comment: It gives the formula $!n$ for derangements, the derivation of which I don't quite understand.
Is it the only way to solve? we have not covered derangements yet. If so $!n$ gives the probability that no one gets his/her hat. What should I do for at least one getting it?
Is it 1-!n ??
Comment: That is correct for at least one.  You have $!n=\frac {n!}e$, rounded to the nearest integer.
Comment: Hmm ok thanks. I have to read derangements carefuly then.
I was hoping there'd be a way using inclusion-exclusion or something.

Probability matching problem


Python "ModuleNotFoundError: No module named 'bindings'" error only when I compile my code

Question: I can run my code on both normal Python IDLE and Visual Studio Code but the executable that was compiled with same Python installation's pyinstaller gives this error:
Traceback (most recent call last):
  File "MyApp.py", line 40, in <module>
  File "PyInstaller\loader\pyimod03_importers.py", line 540, in exec_module
  File "tkinterweb\__init__.py", line 30, in <module>
ModuleNotFoundError: No module named 'bindings'
[4712] Failed to execute script MyApp

I already have installed bindings module by pip.
Also I was imported from tkinterweb import HtmlFrame in line 40. What can I do? Please help me.
Answer: I think this has been answered on Github, but I'll add the answer here for anyone having trouble with this issue and stumbling across this page at some point in the future.

Upgrade to the latest version of both TkinterWeb AND PyInstaller. It will not work if you aren't fairly recent versions.
Then use the --collect-all tkinterweb flag when bundling your app. For example, if you are using pyinstaller --windowed yourscript.py instead run pyinstaller --windowed --collect-all tkinterweb yourscript.py. This tells PyInstaller to include the TkinterWeb files. On many popular packages, this --collect-all command isn't necessary, because PyInstaller has extra files (called hooks) that tell it what to do if it encounters certain packages. PyInstaller does not come with a hook for TkinterWeb, so you simply have to tell it to include the necessary TkinterWeb files manually.

That's all!


consumir api rest com react e renderizar os dados em uma tabela

Question: meu codigo:
import React, { Component } from 'react'
import axios from 'axios'

import PageHeader from '../template/pageHeader'
import cadastroForm from './cadastroForm'
import cadastroList from './cadastroList'

const URL = 'http://localhost:3003/api/cadastros'

export default class Cadastro extends Component {
    constructor(props) {
        super(props);
        this.state = { listaItens: [] }
        this.refresh()

   }

    refresh(Nome = '') {
        const search = Nome ? `&Nome__regex=/${Nome}/` : ''
        axios.get(`${URL}?sort=-createdAt${search}`)
        .then(response => { this.setState({ listaItens: response.data}); })
        .catch(() => { console.log('Erro ao recuperar os dados'); });
    }

     render() {
       return (

     {this.state.listaItens.map(function(item)  {console.log(item)})}

        )
    }

}

retorna:
Answer: Quando você precisa consumir dados de uma API é recomendado você fazer a requisição no método componentDidMount, que é um dos métodos do ciclo de vida de um componente React. Além disso, você não deve chamar o método setState() no construtor (e no método refresh você chama esse método). Assim, a primeira alteração necessária no seu código é invocar o método refresh() dentro componentDidMount().
Depois disso, para renderizar os dados que você carregou na tabela basta fazer um loop no array listaItens e retornar os itens dentro de uma estrutura de tabela.
O seu código vai ficar da seguinte forma depois das alterações:
export default class Cadastro extends Component {
constructor(props) {
    super(props);
    this.state = { listaItens: [] }

    this.refresh = this.refresh.bind(this);
}

refresh(Nome = '') {
    const search = Nome ? `&Nome__regex=/${Nome}/` : ''
    axios.get(`${URL}?sort=-createdAt${search}`)
    .then(response => { this.setState({ listaItens: response.data}); })
    .catch(() => { console.log('Erro ao recuperar os dados'); });
}

componentDidMount() {
    this.refresh()
}

render() {
    return (

                    Nome
                    CPF/CNPJ

               {this.state.listaItens.map(function(item)
                  {
                     return (

                             {item.Nome}
                             {item.CpfCnpj}

                     )
                  }
               }

    )
}


Can a 600Ω XLR dynamic microphone be directly connected to a standard sound card?

Question: With the COVID lockdowns intensifying, the musical education of my daughter has also become increasingly remote. This results in her having to often record her singing and/or piano performances to send to her teachers.
I still don't know much about music, but the techno geek in me is itching to upgrade some equipment to get better results. :D
So I was looking at better (yet still inexpensive) microphones that would provide a noticeable improvement over the simple cheap chat-oriented ones that we have. A local music shop offers a JTS TK-600 for just 30€ and on the paper it looks fine. However it's a 600Ω dynamic microphone with an XLR connector and I'm scratching my head whether or not the sound card that I have (an Asus Xonar U3) will be able to use it properly. I just can't find any information about the microphones it supports. Nor do I know what a typical "skype grade" microphone is like (dynamic, probably, but what impedance, and does it matter?)
So... Should such a microphone work fine with standard consumer sound cards, or do I also need a separate audio interface designed for an XLR microphone?
Answer: In my experience, consumer sound cards are generally quite useless for anything but line-level signals or the electret-condensers that are usually what you find in headsets. Dynamic mics have lower impedance but also lower signal level, and bringing up the recording gain means the low-quality mic preamps in the sound card bring up the noise so much that you could as well have used a 10€ electret mic instead. That's not to say that it isn't worth a try though – perhaps you'll find that it's actually ok with your sound card.
Anyway I'd recommend you'd get at least a very simple audio interface – there are ones available for as little as 15€ now, like Behringer MIC 2 USB which essentially looks like just a cable with XLR on one end, USB on the other, so you can then also save on the cable and adapter you'd otherwise need to buy too.
Another alternative could be a USB microphone. You won't get a really good one for the budget you apparently aim for, however again there are surprising offers available and at any rate you can be sure that mic and preamp are matched well in this case.
Comment: Well, the Asus Xonar line actually has a very good reputation, which is why I picked it up a while back... however it's all about playback, and nobody talks about its recording capabilities. My budget is about 50€. I know that you can easily go up to thousands of € if you want to (and it would be worth it), but that would of course be overkill... Especially since currently nobody has complained yet (except me who thinks the recordings sound awful). Since outright product recommendations are frowned upon here, perhaps you know of some characteristics of a microphone that I should look for?
Answer: No.  Your Xonar expects a different type of mic.
I'm afraid that JTS mic looks absolutely horrible!
The cheapest mic worth buying might be a USB mic for about twice that price.    Some are designed to flatter a vocalist when used hand-held and close, others are more suitable for recording 'the whole room'.
Comment: What's wrong with it? And also - what should I look for when choosing a microphone? USB microphone would be nice too, yes.


How to correctly compute rotation in 3D Procrustes Problem if there is a translation added?

Question: I am developing a routine that should optimally align a sensed 3D point cloud Q  with respect to a reference point cloud P. The transformation involved includes rotation, translation and scaling (a similarity). There exists a great amount of literature about how to compute the transformation using SVD. I have been following this one: R. J. Hanson and M. J. Norris, "Analysis of measurements based on the singular value decomposition," SIAM Journal on Scientific and Statistical Computing, vol. 2, pp. 363–373, 1981.
The algorithm described is as follows: calculate centroids in each point set, compute the centered point sets; compute the covariance matrix between the two centered point sets and perform the SVD on the covariance matrix : C = U * S * V', where C is the covariance matrix, S the diagonal matrix of its singular values, U and V the left and right singular vector matrices, respectively. Then you can compute the rotation component of the transformation as R = U' * V.
This algorithm works for me perfectly if the transformation consists of a rotation and (optionally) a scaling, but if there is a translation present, it fails. I have so far not understood what it is I am doing wrongly. I also failed to find any usable numerical examples that would include translation and lead to a success.
I would also upload my code if someone would like to have a look.
Comment: I have done this before. The theory is correct, so there must be a bug somewhere in the implementation. I would like to see the code.
Comment: http://math.stackexchange.com http://scicomp.stackexchange.com
Comment: @AlexKonnen it is needed to fix the sign of the last eigenvector as described in Kabsch algorithm: https://en.m.wikipedia.org/wiki/Kabsch_algorithm but beyond that, there are degenerate cases like for two vector case if both vectors are colinear then there are infinitely many solutions. However that is infrequent. But since you said the issues are not rare cases, I would tend to think that the SVD algorithm you are using is introducing the instabilities.
Comment: Thanks Mauricio, you may be right, and I am revising the code at the moment. I will eagerly show it to you, then!
Comment: Mauricio, I found the error: it was in the 'scaling' bit: when you compute the translation vector, you need to calculate the scaling first and then use the rotation matrix MULTIPLIED with the pure rotation matrix, otherwise the translation vector so computed will be wrong. However, it took me hours to find it out.
Comment: @MauricioCeleLopezBelon I have gained some new experiences with the algorithm, namely, if the number of the point pairs is less or equal to three, some strange instability randomly occurs: if I am taking nearly identical source and target points, the computed transformation is sometimes correct (unity matrix), but sometimes quite wrong (e.g. -1, 1, -1, 1 on the diagonal). I have also remarked that one of the eigenvalues of the SVD is zero. If I take 4 point pairs or more, this seems not to happen. I always thought 3 point pairs would be enough. Is anything known to this point?
Comment: @MauricioCeleLopezBelon Thanks for your comments, they do help. It is probably a good idea to question the SVD routine. I am using that of MathNet.Numerics which I have also exhaustively and positively unit tested before. However, I have a set of three non-coplanar vector pairs that produce the instability. My "empirical" decision was that to increase the minimum number of points needed to four. According to my observation, no instability happens with 4 points or more, but I cannot prove it.
Answer: As Mauricio Cele Lopez Belon correctly supposed, it was a bug, however, rather a thinking error. Whenever you have a non-unit scaling in the similarity transformation, to compute the translation vector you need to use the rotation matrix multiplied with the scaling:
t = qC - s * R * pC, where pC and qC are the centroids of the reference and the sensed point sets, respectively, R the computed pure rotation matrix, s scaling. You need to use this equation instead of t = qC - R * pC (which you often find in papers), to obtain correct results. If someone is interested in working and unit-tested C# code, I will be pleased to send ( a bit too long for this place).


Node access depending on boolean field in user profile

Question: I would like to control access to specific articles or categories of articles depending on a boolean variable in a user's profile.
For example, this would be on a site where a user gets access to all kinds of data about their product after they purchase it. I would like to manually enable or "tick" a boolean field on their profile which then allows them to see the corresponding information when they browse the website.
I hope you understand what I'm trying to say.
I have already set up a few fields on the user profiles and I'm trying to make it work using the Rules and Content Access modules but I'm not sure if I'm heading in the right direction. I have thought about just setting this up with a "View" but I think the content would still be accessible to everyone by default if they have a link or through Google?
If someone could point me in the right direction, that would be great.
Thanks in advance!
Answer: I got it working, for the sake of anyone ever needing this functionality and stumbling upon this thread:
You'll need the Access Control and ACL modules. The combination of these allows you to set "per user" access for each individual node. For the checkboxes on a profile or page, you'll need to use the Entity Reference module and create a field on the profiles for that type of content. You can then set that field up as checkboxes.
For the final part, you'll need the Rules module and set up two rules: one to "Grant Access per user" and grant view access when a specific value of the checkboxes is true and one to "Revoke Access per user" when values have changed. You'll need to play around with the rule's conditions to make it suit your needs.
Answer: Content Access is a roles-based access control module. So, you must have created a role for your "controlled access" content. And setup the Content Access settings on your content types. From here, you could use standard, Drupal user admin to add remove users to/from this role. Done.
But if you want to assign this role dynamically, Rules is a place you can do it.
Create a rule that triggers on the "Before saving a user account" event. Add a "Data comparison" condition to test your boolean field's value. Select "account" then "" in the Data Selector field. For the Value field, select the value you want to trigger from (most likely the 'on' value for your boolean). Now, add the "Add user role" action, and select your "controlled access" role. Save. And test.
You'll also want create an inverse rule to remove the role.
Good luck!
Comment: Hello, thanks for your response! If I understand correctly, you mean I should make a role that allows access to the content and then automatically give a user that role when the boolean is true using Rules? I understand the approach (I think) but wouldn't that require me to create a role for each product? And if a user would get access to several products, I have to stack user roles? I've looked into the Node Access module which (with a user reference plugin) allows me to select specific users who can view this content but perhaps I can point that to the boolean field in some way? Thanks


Discrete Proposal distribution MCMC

Question: If you want to perform MCMC (Metropolis-Hastings) to infer discrete values, what are some proposal distributions you can use for this. I can't think of a way to extend the notion of a gaussian proposal to this scenario.
Answer: Discrete samplings problems are, in a sense, much more diverse than their continuous counter-parts. In essence, the problem structure becomes much more important in terms of choosing how you want to move around on the space.
Often used proposals are binary switches ([0,0,1] to [0,1,0] or [0,0,0], for eample), switching neighbours in permutations ([1,2,3,4] -> [1,3,2,4] or [1,2,4,3], for example), uniform choice over the entire space if it is (very) small, etc.
Comment: Very good point, the notion of neighbourhood is much harder to specify in a discrete setting than in a continuous one.

Discrete Proposal distribution MCMC


How pass variable in jquery easy confirm

Question: By using javascript confim i have done suspending. Now i want to turn this to jquery easy confirm how can i do this
The function is called in a loop
My PHP Code:
function prepareRow( $flag, $Id )
{
$rowResponse = '

                     ' . $Id . '

';
return  $rowResponse
}

Jquery easy confirm link: http://projectshadowlight.org/jquery-easy-confirm-dialog/
I have tried like this but if  click on 'yes' i want pass '$id' to it. So that i can suspend row.
Please help me out
$("#suspend").easyconfirm({locale: {
    title: 'Are you sure?',
    text: 'Are you sure, you want to suspend?',
    button: ['No',' Yes'],
    closeText: 'Close'
}});

$("#suspend").click(function() {
    $.post("suspend.php", { "Id" : Id },
            function(data){
                $.ajax({
                    type:"POST",
                    url: "prepareTable.php",
                    success: function(data){
                    $("#example").html(data);
                }
                });
            });
});

Comment: "." (Dot) is use for Concatenate in PHP but in JavaScript Concatenate operator is "+"(plus sign). So you just need to change concatenate symbol :)
Comment: i am calling it in a php page. it is working my question is not that
Answer: I suppose you need to look for callback's which will occur when you press Yes or No button. I would use http://tutorialzine.com/2010/12/better-confirm-box-jquery-css3/ You can see:
'action': function(){} Where you specify what to do after pressing yes or no
Answer: I have tried example about jquery easy confirm in local system found bug in it. So i have stopped worry about this question and used jConfirm.


interaction effect in linear mixed models - interpretation

Question: I ran the following model:
test = lmer(Reaction_Time  ~  Code_IS_Condition * Code_IS_Language  + (1 + Code_IS_Condition | Subject) + (1 + Code_IS_Language |Subject) + (1 | Picture_Name) ,
data = data5[data5$PWI_Accuracy=="Hit"  & data5$PWI_Condition=="Cog" & data5$Combined_X=='0',],)

Reaction_Time is a continuous variable; Code_IS_Condition has 3 levels (reference level is level 3); Code_IS_language has 2 levels (reference level is level 2). Below is the effects that was generated
Fixed effects:
                                     Estimate Std. Error       df t value Pr(>|t|)
(Intercept)                           972.522     33.591   20.500  28.952  < 2e-16 ***
Code_IS_Condition1                     82.336     32.042   15.800   2.570  0.02071 *
Code_IS_Condition2                    -54.818     30.594   15.500  -1.792  0.09266 .
Code_IS_Language1                      -9.167     12.672  233.100  -0.723  0.47018
Code_IS_Condition1:Code_IS_Language1 -104.818     35.771  901.100  -2.930  0.00347 **
Code_IS_Condition2:Code_IS_Language1   55.901     35.702  905.300   1.566  0.11775

I interpreted the interaction effect as follows: Reaction times are shorter for Code_IS_Condition 1 than condition 3 when language is 1. However, when I compare this to the raw means, I see that condition 3 takes a shorter time. Can I request you to help?
Thanks
Comment: It might because the interaction "condition1 and lgaguage1" has an even bigger (-104.818) negative coefficient than condition1 (82.366)?
Comment: How did you calculate the "raw means" you refer on?
Answer: For language level 2 it actually is the case that reaction times are longer for condition 1 than condition 3 (+82.336 units). So I assume you calculated your "raw means" given language level 1 (scenario A) or all data (scenario B). In scenario B your findings of a shorter reaction time in condition 3 might be due to a large percentage of condition 3 observations. In scenario A you might be facing the Simpsons's paradox: When conditioning on further variables, your results may change.

Compare how strong fixed effects estimations can change when conditioning on the identifiere variable:
df <- data.frame(ID = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
        x = 1:9,
        y = jitter(c(7:9, 4:6, 1:3)))

plot(y~x, col = ID, data = df)

round(coef(lm(y~x, data = df)), 2)# 9.14 and -0.82
round(fixef(lmer(y~x+(1+x|ID), data =df)), 2) #-0.27 and 1.04


Modify a single option in a select and show changes without clicking into select

Question: I have a form that contains a select with several options. One option can be selected by default based on a value in the DB.
If an option is selected by default, we want to apply some styling to it.
Once the form is rendered, I can simply do something like this...
$('#mySelect option:selected').addClass('customClass');
Lets say customClass just makes background-color:green.
What happens is that once the form is loaded, the option is still default white in the select. It only turns green once you click on the select.
I think this is because only the option is being changed to green.
If I do, just $('#mySelect').addClass('customClass'); then all options are green.
I thought about applying the class to the whole select and then looping through all options and removing the class except for the selected one, but that doesn't seem efficient.
Any ideas of a concise way to do this?
Thanks!
Here's a simple example
almost working example
Comment: Your issue isn't that it's "*only green once you click*", it's that it's only green in the options drop down, the "selected" part (closed drop down) isn't styled.  (at least in my browser...)
Comment: `option` styling is very unreliable and will differ in different browsers. It would be better if you create a custom dropdown(which is made from divs and such) to do this kind of thing
Comment: Makes sense, is there any way to style it inside the select ?
Answer: Working Demo: https://jsfiddle.net/o81hyseg/

$("#mySelect").on("change", function(e){
    if(!e.isTrigger)
           $(this).find("option").removeAttr("selected");

   if($("#mySelect").val() == "green"){
      $('#mySelect').addClass('foo');
      $('#mySelect').attr('title', 'foo');
      $(this.options[this.options.selectedIndex]).attr("selected","");
   }
   else{
      $('#mySelect').removeClass('foo');
      $('#mySelect').removeAttr('title', 'foo');
   }
});

$("#mySelect").trigger("change");
.foo {
  background-color: green;
}

.foo option:not([selected]) {
  background-color: white;
}

<select id="mySelect">
  <option value="">Select...</option>
  <option>white</option>
  <option>white</option>
  <option>white</option>
  <option selected>green</option>
  <option>white</option>
 </select>
Comment: I have updated the answer and demo link as per your concern.
Comment: for that add css class to particular option and apply styling.
Comment: for e.g. add foo class to green option.
Comment: I had something similar, but options other than 'green' still turn green when selected. I need only green to green
Comment: Pls check out https://jsfiddle.net/z8p5ceq0/10/, we are almost there
Comment: Almost! One last edge case (my apologies if my requirements are not concise).
I would like the `green` option to always have its styling (be green and have that title).

Notice that if you select 'white' this removes the styling from the 'green' option.

Is this possible to implement? Thanks!
Comment: Figured out my last edge case by unconditionally setting the specific option's (Where green in this example) styling and title


Google Tag Manager: How to add list of IDs for custom trigger

Question: How do I add a list of ids for a custom trigger? I have ~15 ids that I would like to form a custom trigger but don't want to add each one of them separately.
Is there a way to do something like id contains ('123', '456', '789')
GTM screenshot
I tried to enter a list in the contains function, but the tag did not fire.
Answer: The best way to handle this is with regEx (regular expressions).
Something like (123|456|789) will match all all three of those values. This is the easiest way to apply a filter with multiple matches. If your values are more complex than that, you can also use nested matching groups and or tokens to further enhance your expression.
RegEx is a very deep topic and can get rather complicated. I suggest learning about it and the nuances. I prefer regex101.com but there are a ton of resources available.


Como criar um servidor para colocar um site online?

Question: Fala pessoal, tudo ok?
Bom sei que minha pergunta do titulo ta um pouco estranha, mas aparente deve ter uma resposta bem simples kkkk
Mas antes vou explicar um pouco da minha situação! Eu e meus amigos estamos tentando "Criar" um site nosso para que possamos jogar um rpgzinho de mesa maroto. E não, não somos pessoas que não tem o que fazer kkkkk. Faz muito tempo que não jogamos algo porque não temos tempo ou interesse, a unica coisa que nos une é o famoso RPG de Mesa, jogamos isso durante um tempão na adolescência.
Sim, isso mesmo! É um pouco complicado fazer vários cálculos matemáticos de dano, status e tbm os atributos do set e arma. Estamos querendo automatizar tudo. Eles deixaram a parte dessa automação para mim, mesmo eu não sabendo muito sobre programação, aprendi bastante coisa em curto espaço de tempo, consegui desenvolver algumas coisas no HTM e jav.
Estou terminando a parte de "Status do personagem" que seria uma das principais e agora me dei conta não sei como vou fazer para colocar tudo isso em servidor ou banco de dados para que eu consiga jogar junto de meus amigos.
Então a minha pergunta é, como eu posso fazer isso? Meio que deixar a minha página "Online", como se tivesse um login para acessar no site e que o usuário daquele login tivesse alguns atributos que seria a folha de personagem.

.body{
}
.body #forma img{
    position: fixed;
    width: 100%;
    height: 100%;
    bottom:1px;
    left:1px;
}
#button1{
margin-top:300px;
}
#button1 button{
    width: 200px;
    height: 50px;
    position:relative;
    left: 45%;
    margin-top:10px;
}
.botoes img{
    width: 60%;
    height: 100%;
    position: absolute;
    left: 20%;
    top:2px;
    opacity: 0.7;
}
#sts{
    width: 38%;
    height: 65%;
    border: 1px solid #ffffff;
    background: #ffffff;
    position: absolute;
    top:18%;
    left:32%;
    border-radius: 58px 58px 58px 58px;
-moz-border-radius: 58px 58px 58px 58px;
-webkit-border-radius: 58px 58px 58px 58px;
border: 0px solid #000000;
opacity: 0.5;
}
#sts h2{
    margin-left:43%;
}
#input1{
    border: 1px solid #000000;
    border-radius: 5px;
    margin-top:10px;
    margin-left:16%;
    width: 180px;
    height: 20px;
}
#input2{
    border: 1px solid #000000;
    border-radius: 5px;
    margin-top:10px;
    margin-left:16%;
    width: 180px;
    height: 20px;
}
}

STATUS

            <input id="input1" type="text" placeholder="Nickname">
            <input id="input2"type="input" placeholder="Raça">

            <input id="input2"type="input" placeholder="Classe">
            <input id="input2"type="input" placeholder="Sub-Classe">

            <input id="input2"type="input" placeholder="Título">

Answer: Opa beleza?
Então cara, primeiramente pra que você possa "criar" um servidor você teria que ter um investimento muito alto rsrsrsrs. Recomendo fazer o seguinte (a maioria trabalha assim). Ao invés de você montar um servidor, porque você não hospeda seu site em servidores?
Exemplo, temos a Hostgator que para seu caso serve muito bem e não é tão caro o invesimento. Fora isso, vocês vão precisar registrar um domínio via registro.br ou na própria provedora de servidor (Hostgator).
Você tem que pensar no seguinte. Seu site (ou jogo online) são vários arquivos, e você precisa deixar esses arquivos acessíveis, e por esse motivo a necessidade de registrar um domínio, publicá-lo em um serviço de hospedagem e depois disso tudo você poderá acessar seu site.
Hospede aqui: https://www.hostgator.com.br
Registre o domínio aqui: https://registro.br/
Claro que isso você e seus amigos deverão pagar uma mensalidade e anuidade.
Geralmente funciona assim: O Registro de domínio R$ 40,00 (ano) e a mensalidade na hospedagem pra manter seu site no ar (esse preço varia muito com a necessidade, e deve consultar a Hostgator).
Espero ter esclarecido sua dúvida, pois não conheço (e acho que nem existe) outros meios para publicar um site (a não ser que você tenha um servidor próprio).


Esconder formulário ao pressionar tecla

Question: Eu criei um form, eu não quero usar botão minimizar ou maximizar, eu quero usar por exemplo ao pressionar "F1" meu formulário fique oculto e apertar F1 novamente ele volta a aparecer.
Tentei isto, mas sem sucesso:
<code>       private void Form1_KeyDown(object sender, KeyEventArgs e)
   {
       if (e.KeyCode == Keys.F1)
       {

            Form1 fm = new Form1();
            fm .Hide();

       }
   }
</code>
Comment: da uma olhada nesse link, talvez ajude https://social.msdn.microsoft.com/Forums/pt-BR/8d299b9e-bea2-4daf-8705-1394e3e91ca1/maximizando-minimizando-e-arrastando-o-form?forum=vscsharppt
Comment: vlw vitor, me ajudou bastante desisti do esquema das telcas nao funciona no meu form usei um buttom pra minimizar mesmo.
Comment: @CerraossoUC A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Você está criando um nome formulário e escondendo ele, não pode, tem que esconder o atual:
<code>private void Form1_KeyDown(object sender, KeyEventArgs e) => if (e.KeyCode == Keys.F1) this.Hide();
</code>
Coloquei no GitHub para referência futura.

Esconder formulário ao pressionar tecla


Sending an email from contact us form using only Angularjs and Send grid without back end API in place

Question: I have taken a look around the internet and all the solutions emphasize using Express and Node Js API in place to able to send an email. I would love to see any suggestions on how to best go about it because I don't have a backend in place. Thank you.
Answer: You're going to need some sort of backend otherwise the API-Key will be exposed.
From the SendGrid documentation:

When you have a browser-only application that reaches out to APIs, the API key has to be embedded in the application. Anyone with access to a browser-only application can access all of the Javascript source code, including your API keys.
Making your API key publicly accessible could result in anyone authenticating API calls with your API key — this is a significant security concern both for you and SendGrid.

You could use a serverless AWS lambda function or google function which would be a "backend" but without having to support the infrastructure / use a big framework.


Como configurar o editor Summernote para exibir uma pagina web dentro da janela?

Question: Bom dia, queria uma pequena ajuda e dicas para fazer o editor de texto summernote abrir uma pagina web, por exemplo em uma pagina eu estou digitando o HTML normalmente e com clico para ver o codigo, iria aparece a pagina pronta.
exemplo:
Answer: Você pode pegar o html criado no SummerNote dessa forma:
var htmlPagina = $('#idDoEditor').summernote('code');

Crie uma div onde você quer colocar o resultado:

E com jquery jogue o html do summernote nele:
$('#htmlGerado').html(htmlPagina);


Small bugs in my classical guitar

Question: For the last seven years, when winter comes (and the cold weather) I notice small bugs (about half a millimeter) strolling my classical guitar.
They are whitish and I don't see any apparent damage to the guitar but am concerned that they might damage it somehow and also it bothers me they are there.
Does anyone know what these might be? (and if they damage the instrument somehow, and why only in the winter?)
(The reason I'm asking after so many years is that this site didn't exist then).
I'm not sure this question is appropriate in this site.
Answer: We have a very old Gibson mandolin, and we had a problem with some bugs. The bugs would eat some kind of glue that they used to make the mandolin, and it eventually collapsed in. When our mandolin was repaired a few years back, we left mothballs in the case for a while to keep anything out. The mandolin / case smell like mothballs now, but I haven't noticed any bugs.
Comment: uhhh... hope that's not my case. Did the bugs only appear with cold weather?
Comment: I looked around the web a bit, and I found these ( http://archivesalberta.org/vol16_3/cory.htm ) which come out during cold weather and eat glue ( they say normally books, but it could be instruments Iassume )
Comment: Those glue eating bugs might not be the problem though, it could be something else. There are also two good suggestions here, about taking the bugs somewhere to look at ( disregard the stupid posts and termite ones / spraying pesticides until you know for sure what they are, they could damage your instrument. ( http://acapella.harmony-central.com/showthread.php?936243-I-think-bugs-are-eating-my-guitar! )
Comment: After some search on the internet and by thoroughly examining my guitar, I'm glad to say that *apparently* these bugs aren't doing any glue or wood eating. Fortunately I photographed my guitar 10 years ago in detail and used those photos to compare with today's state. I'm inclined to say that the cold weather is just a coincidence, the humidity percent. is higher and I think it would be a factor for these bugs' appearance. I'm going to collect some and take to a science dep., then probably use some leafs/smells to cast them out, and finally *groom* my guitar more often. Thanks for your reply!
Answer: From what I can tell, these bugs are mites. They could be the white spider mite. I can't be sure, and I'm still looking for more information...its a problem I've encountered a number of times on bagpipes. For the first time though, I found then on my own set and freaked out a little bit. There apparently is no information about how to treat these bugs on an instrument. But I clean the surfaces with isopropyl alcohol and oil the porous wood surfaces after using this harsh alchohol.
If anyone has any more info, please share.
Comment: It looks like the asker was able to confirm what their actual bugs were, so your answer is likely to be wrong in this particular case. If you want to point out other things future readers could look for, that might be more appropriate as a comment on the question.

Small bugs in my classical guitar


Why does a request to an undefined route result in 401 unauthenticated in Laravel

Question: A Laravel 8 application with Sanctum.
When I send a request to a defined route using Postman with an access token the response is correct. I'm happy with this.
When I send a request to a defined route using Postman without an access token the response is 401 Access denied. I'm happy with this.
When I send a request to an undefined route using Postman with an access token the response is 401 Unauthenticated. I'm NOT happy with this. I want a more appropriate response, such as 404.
I don't know how to choose what code from my application to include this question. Please ask me for whatever might be useful and I'll add it.
Update:
Thanks to the answer by @MartinZeitler I worked out that the problem is caused by me making Nova accessible at / instead of /nova.
I did this in /config/nova.php by changing
'path' => '/nova',
to
'path' => '/',.
If I revert this to '/nova' then everything works as I expect it to.
But I need Nova at /, so what can I do?
Comment: Is it possible that you accidentally restricted access to your 404 page? Maybe a dumb question, but I only ask because I know a guy who actually did this, who may or may not be me
Comment: checked at Laravel 8 with sanctum - undefined route with token - 404, not 401. maybe you define auth middleware in Kernel for all routes?
Comment: @cja Please share your route `api.php`
Comment: @Don'tPanic I don't know how to restrict access to my 404 page. Which doesn't mean I haven't done it!
Comment: This was not something I did in Laravel (okay, it was me). It was in a symfony app that restricted routes based on regular expressions, and I unintentionally restricted every route in the app. After looking at the sanctum docs, it looks like you have to explicitly protect each route, so it doesn't look like that could have happened in this case. Just a thought.
Comment: Can you review this https://stackoverflow.com/a/31621512/13875884
Comment: You had to make some modification in the middleware priority or Service Providers to get this behavior, because the default behavior of a Laravel + Sanctum installation should return a 404 error instead of 401. I have tested it myself a few moments ago and this is how it works by default.

Maybe placing the content of `app\Http\Kernel.php` could help us.
Comment: @cja does my answer helped you. if not you can share your `App\Http\Kernel.php` in order to find out the problem
Comment: I don't have the source code of Nova but maybe the undefined route you request beings captured by Nova because you run Nova at root `/` path, you can try disable auth and send a request to that undefined route to make sure it's not captured by Nova
Comment: what are all the composer package you are using
Answer: It's difficult to answer a routing question without, eg. the output of php artisan route:list.
The 401 likely comes from Sanctum or from missing a catch-all route Route::any('', [ ... ]).
Since Laravel 8.26.0, there is a new missing() method available.
Beside that, my best bet would be Illuminate\Foundation\Http\Kernel ...
/**
 * The priority-sorted list of middleware.
 *
 * This forces non-global middleware to always be in the given order.
 *
 * @var array
 */
protected $middlewarePriority = [];

Answer: 401 & 404 are exceptions that exit the application flow from normal behavior.
in your situation it seems The 401 exception get executed sooner, and doesn't let the 404 to get executed.
if these exception controls has been placed in the middlewares, you could
change the execution order of middlewares from The App\Http\Kernel
for route middleware from $middlewarePriority
for global middleware from $middleware
but The url not match error (The 404) occurs here :
Symfony\Component\Routing\Matcher The method: match(), and it is out of middlewares scope.
but how to prevent the 401 from running first?
this exception is thrown from the authentication middleware,
The Middlewares can get called in 3 places in the laravel:

as Global Middleware
as Route Parameter Middleware
only get called in the Controller's Constructor

I have tested, that if The middleware is Global it gets executed, before the Url not match 404.
In the laravel docs, it is mentioned that:

The withoutMiddleware method can only remove route middleware and does not apply to global middleware.

I would translated it to:

The Global Middleware has executed before we get to the routes files

TL;DR
so I guess, You have added the authentication middleware in the $middleware.
and I think you have to move it ('auth' => \App\Http\Middleware\Authenticate::class) to the $routeMiddleware array.
then use the middleware(auth:sanctum) in The routes files or the RouteServiceProvider
Comment: Thank you for your suggestion but this is not what I've done.
Comment: @cja : from your question, is there two types of 401 error? ( Access denied & Unauthenticated )
Comment: no (here's an extra few characters to allow comment to submit)
Answer: Maybe need to check a FormRequest class which handle your method in the controller, and then check method authorize he is should return when true for example
public function authorize()
{
   return auth('sanctum')->check(); // or for test just return true
}

Answer: try to add this to the Handler.php file in the register function in Exceptions directory.
  $this->renderable(function (NotFoundHttpException $e, $request) {
      //json response
      return $this->error('Not found', 404);

      // return 404 as html view
      // abort(404);
   });

Answer: You can create custom exception handling to handle all exceptions.
public function register()
{
    $this->renderable(function (\Exception $e, $request) {
        if($request->is('api/*'))
            return $this->handleException($request, $e);
    });
}

public function handleException($request, \Exception $exception)
{
    if ($exception instanceof ValidationException) {
       return $this->sendValidationError($exception->errors());
    }

    if ($exception instanceof NotFoundHttpException) {
        return $this->sendError([], 404, __('message.page_not_found'));
    }

    if ($exception instanceof AuthenticationException) {
        return $this->sendError([], 401, __('auth.unauthorized'));
    }

    if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
        return $this->sendError([], 404, __('message.not_found'));
    }

    if($request->is('api/*')) {
       return $this->sendError([], 501, __('message.error_message'));
    }
}


Long-term relation between time series with deterministic trends

Question: say I have two time series that move together but both seem to be characterised by a deterministic trend.
I have two questions:

How can I test whether the trend is deterministic or stochastic?
How would I determine the long-run relationship between the two series in the event they both have deterministic trend? I know that in case of two stochastic trend you might want to use VECM (in case they are co-integrated), but I am not sure if VECM also applies to deterministic trends?

Many thanks, and please ask if you need further information.
Comment: VECM would not be applicable if the variables do not have unit roots.
Comment: Hi Richard, thanks for the clarification. What would be the alternative then. I so far could not detect that they have a unit root.
Answer:
try them both and compare the results.
For more see Statistics for time series trend in R
Comment: The language in your quotation is bizarre, because it attempts to define a *model* in terms of an *estimator* ("least squares coefficients") of a model!
Comment: e.g. deterministic trend model      Y(t)=B0 + B1*T where T is the counting numbers (1,2,...T) ;  e.g. stochastic trend(adaptive)   Yt)=Y(t-1) +B2
Comment: Hi, I did some checking and I cannot conclude that they have a stochastic trend. Suppose I believe really hard that the two deterministic trends are related, how would I quantify their relation? I assume that is the equivalent to a VECM, but w/o stochastic trends...
Comment: I would construct a transfer function between the two series. https://onlinecourses.science.psu.edu/stat510/node/75 and http://www.math.cts.nthu.edu.tw/download.php?filename=569_fe0ff1a2.pdf&dir=publish&title=Ruey+S.+Tsay-Lec1 (ignoring corner method) . If you wish you can post your data in a csv file and I will look at it.
Answer:
How would I determine the long-run relationship between the two series in the event they both have deterministic trend?

Assuming the trends are both linear, here are some options:

Simple regression $y_t=\beta_0+\beta_1 x_t+\varepsilon_t$. Due to superconsistency the estimator for $\beta_1$ will be converging at a rate $t^{(3/2)}$ rather than $t^{(1/2)}$ and any autocorrelated errors or the like will be have a negligible effect on the estimator given a sufficiently large sample.
Regression with ARMA errors $y_t=\beta_0+\beta_1 x_t+u_t$ where $u_t$ is an ARMA process -- if one of the variables is exogenous. This is similar to 1. but could be more efficient in presence of autocorrelated errors, especially if the sample is not that large.
VAR model with exogenous time trends -- if both variables are endogenous.
Comment: Hi Richard, I suppse this is all non-detrended variables right? This is because I "believe" that there is no issue of spurious relation here. For option 3, when you write that both are endogenous: do you mean that the causal effect can run both ways, or coud this also be a confounding factor that makes t hem endogenous?
Comment: @clog14, yes, I mean the original variables, not transformations thereof. Regarding "endogenous" I would not exclude the possibility of a confounding factor.
Comment: @clog14 and regarding the first question, an idea would be to investigate the variance of the series. The variance grows faster in case of a linear trend than a stochastic trend. I guess there exist some tests based on that. Related threads: https://stats.stackexchange.com/questions/103193/stochastic-vs-deterministic-trend-seasonality-in-time-series-forecasting, https://stats.stackexchange.com/questions/286440/decompose-a-time-series-data-into-deterministic-trend-and-stochastic-trend


Attach different CSS classes to first and second link

Question: I have a Paragraph type 'Call to action' with one link field field_link.
I have another Paragraph type where I call the 'Call to action' paragraph as an Entity reference revisions field. With Allowed number of values set to 2.
So the editor is able to insert two Call to action links.
I want to attach 2 specific CSS classes to both links:
On the first link:
Button one

On the second link:
Button two

How do I loop through, so I am able to attach different classes?
Update:
In paragraph--call-to-action.html.twig I added:
{% block paragraph %}
{% for item in content.field_link %}
    {% if loop.index == 1 %}
      Button one
    {% elseif loop.index == 2 %}
      Button two
    {% endif %}
  {% endfor %}
{% endblock paragraph %}
But now it's rendering always the 2 buttons? What's wrong here?
Answer: I figured how to loop through an entity reference field. Because I am looping from inside a paragraph twig through another paragraph (entity reference) I have to loop the children:
{% for item in content.field_name|children %}

So the children did the trick! Then you can do something like:
{% set link_class = loop.index == 1 ? 'primary' : 'secondary' %}

Answer: You can create a custom twig template to the call to action paragraph type.
Some code like this might work:
{% for item in content.field_link %}
  {% if loop.index == 1 %}
    {% set class == 'button-one' %}
  {% elseif loop.index == 2 %}
    {% set class == 'button-two' %}
  {% endif %}
  {{ item.title }}
{% endfor %}

When creating a for loop in twig you always have the loop.index available.
Loop.index is 1 indexed thats why you have to check if index is 1 or 2.
Comment: If you only want the custom buttons some places you can maybe add a checkbox to the field, that you can check if you want custom fields, and then check for the field in twig.
Comment: No this is not the case. It should be possible with an index or loop or something isn't it? I have a Paragraph type (Slide) where you can insert a Title, image and one, or two buttons! The buttons are the `Entity reference revisions field` from the Paragraph type Call to action (with one field `field_link`). The first link should get `class="button-one"` and the second button should get `class="button-two"`
Comment: I have updated my code, try that.
Comment: Have you cleared cache?
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/95735/discussion-between-jdrupal-and-meez).
Answer: You are limiting the number of links via the Drupal UI, plus you don't have to style instance99 if you had more than two links.
I would keep it simple.
Twig:
{% for item in content.field_link %}

    Button one

{% endfor %}

Styles:
a.button {
  background: #f3f3f3;
  color: #333;

  &.instance1 {
    color: #444;
  }

  &.instance2 {
    color: #555;
  }
}

Adding an additional class will provide better scalability as well.


How long is Staccato?

Question: Question for skimmers: how do we know when to play portamento/portato or a dry staccato? Is it based on a date or composer? Or is a half-staccato still common practice?

Sometime in college I played a timpani part and had a conversation like this:

Instructor: You're playing that too dry.
Me: It's staccato.
Instructor: Yes, but staccato means play the note for 1/2 its value. Staccato half notes should sound like quarter note.

After which I said something like "Yessir", thought "how have I missed this?", and accepted it. Unfortunately I don't remember the piece, but my guess is that it was early romantic era. (That semester my big timpani challenges were the jarring juxtaposition of a Beethoven Symphony and Candide, but it could have been another piece).
Most contemporary definitions just say "detached" or something similar:

Wikipedia: Staccato (Italian for "detached") is a form of musical articulation. In modern notation it signifies a note of shortened duration, separated from the note that may follow by silence.

This is representative of most easily accessible internet definitions.
But some older definitions assume the "half-staccato" as common knowledge, and even newer dictionaries retain vestiges of the definition propounded by my teacher. All works below accessible in the US via Google Books.

Facts on File Dictionary of Music (2004): Staccato performance in practice reduces the time value of a note by one-half or more;...

The Pronouncing and Defining Dictionary of Music (1896): Staccato Marks. Small dashes or dots placed under the notes, thus: [example] No difference is now made in playing the dotted staccato signs and the pointed ones. Formerly it was taught that the dots represented a half staccato. [Emphasis mine].

Haydn: an Introduction to his Keyboard Works (2005): It may be that Haydn intended the stroke for a short staccato and the dot for a somewhat longer portamento, but the marks cannot always be differentiated in his manuscripts or those of his copyists. In general, a staccato note should be about one-half the length of its usual value. [Bold emphasis mine]

The Etude: the Musical Journal (vol 40, 1922): Remembering that the dash (staccatoissimo) reduces the sound to approximately one quarter of its value, and the dot to about one-half, the slurred staccato reduces it to about three-fourths of its normal length. [in the context of a piece by Beethoven, bold emphasis mine].

I've also heard Bach staccatos played as half-duration values.
So, in the absence of a marking like secco or portato, how do we know when to play portamento/portato or a dry staccato? Is it based on a date or composer? Or is a half-staccato still common practice?
Comment: `Is it based on a date or composer?`  Yes, and composer's intent. Plus people get to throw whatever interpretation they like on top!
Comment: I've never understood that way of writing. Wouldn't a crotchet and 3 beats rest come out sounding the same?
Comment: @Tim That's my question - is it equivalent to a crochet and 3 beats of rest of something even shorter? And yeah, it seems kind of pointless, but it occurs pretty regularly.
Answer: It is pretty much context-dependent, although different people have different (often-strong) opinions on this.  Apparently your director falls into the latter group.  The style of the music will indicate more traditionally how it might be expected to be played, but ultimately it is still up to the performer's interpretation (in this case - your conductor).  "By half or more" sounds sloppy to begin with, but I will often not fully halve a note even if it is staccato depending on tempo and other factors.  This is as a wind player, not a percussionist, although I suppose the dynamic considerations aren't much different from a roll.
Actually I want to elaborate a little bit - I think the way I try to do it in many cases is to literally think of the note halved, and then play almost imperceptibly longer than that.  My thinking was always that "if they wanted it halved, they'd have written half."
Comment: It was actually question of when to damp the ringing, so pretty similar to ending the breath. I've never been asked to roll a staccato (knock on wood). But, presumably in the same piece all the parts should handle the staccato the same way. You think that it's a division among interpreters more than era then?
Comment: Unfortunately I can't even begin to comment on what the academic musical community views as traditional for each era. Especially on an instrument I don't know the first thing about playing ;p
Answer: I seem to remember a musician telling me staccato is used for readability too, for instance this:

is (arguably) more easily read than this:

It puts visual emphasis on the counter rhythmicness of the notes.
Anyway, I'm definitely no expert.
Answer: If the note that has the dot is a long note, then I would interpret the dot as meaning that there would be a clear separation from the next note, if there were one.  I.e. the opposite of legato.
(How short you need to go to get a nice separation or articulation depends on the acoustics of the space and other conditions inherent to the instrument and the player.)
If the note that has the dot is a short note, then I would interpret the dot as meaning, play the note as short as possible, so that it just sounds like a little blip, but still a nice-sounding little blip.  So maybe the timpani teacher felt that your little blip was so short it had lost its beauty.
On a string instrument, it is possible to stop the bow dead in its tracks, in such a way as to stop all ringing, all resonance.  This can be useful as part of a particular practice technique, I suppose -- at least that's what Suzuki teachers seem to think -- but I have yet to hear any music that that style is suited to.
I might not be answering exactly the questions you asked; but I hope my way of thinking about the matter is helpful.
Comment: aparente001, the Suzuki method starts off with good basic violin techniques, both bow technique and left hand technique. Regarding the type of staccato where the bow is kept on the string: On violin there are several staccato techniques where the bow does not get off the string. They are an important part of violin playing. If you heard someone doing it without a nice sound it just indicates that they need more practice on the matter. You can also play with a bouncing bow on and off the string which is a different technique. Sooner or later the Suzuki students will also learn that.
Comment: @LarsPeterSchultz - Well, students are pretty far along when they start doing spiccato.  Long before that, they get beyond the the dry total staccato I was describing, which is done in the very beginning stage. // I'm sorry if I sounded like a Suzuki detractor -- I'm not.  It's just that super dry staccato in the early stage that I'm not a big fan of.  However, I haven't done any controlled experiments to find out whether that particular feature is one of the keys of the Suzuki method's success.  (I wonder if anyone has?)
Answer: First, don't confuse portamento and portato.  Two different things.  In fact, two very different things.  Portamento is a slide, portato is a type of detatched.
Second, as a percussionist, don't get sidetracked by the special meanings string players have for various dot/slur notations.
A classic definition of staccato is 2/3 of the written length.  Some would say 50%.  But it's very much a matter of context and style.
(But I can't think of a style or period where 'staccato' mean't 'as short as possible'.)

How long is Staccato?


Stacking footer DIVs with CSS

Question: Looking for a specific stacking order inside a flex container.  Pretty basic footer split into 3 sections, so you have left and right Divs 100% height and 20% width. The middle would flex to fill the difference BUT middle needs to be split in half.  So top and bottom Divs inside at 50% height each.  I can't seem to figure out the positions with absolute, fixed, ect. Or floating whatever works best.
Thanks
Ok sorry, here is the CSS inside flex container
.footer_left_box {
    position: absolute;
    display: inline-block;
    float:left;
    left:0;
    width: 10%;
    height: 100%;
    background-color:#C9D329;
}
.footer_middle_top_box {
    position: relative;
    display: inline-block;
    width: 80%;
    height: 50%;
    background-color:#2BB851;
}
.footer_middle_bottom_box {
    position: relative;
    display: inline-block;
    width: 80%;
    height: 50%;
    background-color:#3954D4;
}
.footer_right_box {
    position: absolute;
    right:0;
    width: 10%;
    height: 100%;
    background-color:#E33538;
}

This is an example of what I need
Comment: Stackoverflow is not a code writing service. You must show what you have done by posting a complete example of your code **in the question itself**.
Comment: As Hunter said: To help you with your CSS we first need to see your ["Minimal, Complete, and Verifiable example"](http://stackoverflow.com/help/mcve) HTML and attempted CSS, so we can try to solve your problem and explain why your own attempt failed - that way you can learn something useful for your future development, as well as getting an answer to this single problem.
Comment: @LeeAlexander share us the layout you want and your html code for reference
Comment: It won't let me attach an image, which I have because Im not ranked 10.
Comment: Plus it wont let me add any more to my question. I am trying to add HTML code in comment section but doesn't come out correctly
Answer: Flexbox can do that but you may need to adapt the structure.

footer {
  height: 150px;
  display: flex;
}
.left,
.right {
  flex: 0 0 20%;
}
.left {
  background: rebeccapurple;
}
.right {
  background: #bada55;
}
.middle {
  flex: 1;
  border: 2px solid red;
  display: flex;
  flex-direction: column;
}
.top {
  flex: 0 0 50%;
  background: #c0c0ae;
}
.bottom {
  flex: 0 0 50%;
  background: #c0ffee;
}

Comment: thank you Paulie_D I appreciate the answer and your time!

Stacking footer DIVs with CSS


Is it feasible for a mobile app like a peer to peer torrent app to discover peers via Internet, not just direct Wifi?

Question: If I create an app that will be installed on different devices (Windows, Android, Apple).
Different devices will be connected to Internet via different ISPs. Mostly devices will have changing dynamic IP address.
In this situation will it be possible for one client to find and communicate with all unknown devices connected to Internet and app installed. Like is it possible for one client to broadcast data to all other clients.
Is this potentially possible WITHOUT USING ANY CENTRAL SERVER for client to find ALL other clients?
Answer: Of course it's possible, this is the way all peer-to-peer networks operate. And yes, this includes (any)Torrent and Bitcoin.
How to actually implement it, however, is way besides the scope of this site (or any site).
You can start from here.


Conditional Probability Example

Question: I don't understand the following example,

Consider two urns, the first containing two white and seven black balls, and
  the second containing five white and six black balls. We
  flip a fair coin and then draw a
  ball from the first urn or the second urn depending upon whether the outcome was heads or
  tails. What is the conditional probability that the outcome of the toss was heads given that
  a white ball was selected?

What is the relationship between coin and selecting a ball ?
Answer: This can be found using Bayes' theorem.
Say that $A$ is the even that the outcome of the toss was heads, and $B$ is the even that the white ball was selected.
$P(B | A) = \frac{2}{9}$, because that means the first urn was used.
$P(A) = 0.5$, because the coin is fair.
$P(B) = 0.5 \frac{2}{9} + 0.5 \frac{5}{11}$, by the Law Of Total Probability.
Using Bayes' law, you can get $P(A|B)$ from this.
Answer: Suppose you drew a white ball. Both first Urn (A), and the second Urn (B), have a white balls in them (2 and 5 resp.). The choice whether we will draw a ball from Urn A or Urn B depends on whether the coin showed heads or tails.
The question asks you to tell the probability of coin showing a head if a white ball had been drawn. Alternatively, it asks you to tell the probability of the ball being from Urn A (since we chose A if we get head), if it is a white ball.
Let us define W to be the event of ball being white. A of ball being from urn A, and B of ball being from Urn B.
P(A|W) (Our answer) = P(A.W)/P(W)
Now, *P(A.W) = 2/9, P(B.W) = 5/11, P(W) = 1/2*P(A.W) + 1/2*P(A.B)*
Plug the value. Get the answer. As to your question, the relationship between tossing a coin and selecting a ball is that outcome of the coin decides which urn we are going to draw from, and thus changes the probability distribution of drawing the ball, or chances of getting a white(or a black ball).

Conditional Probability Example


Conditional Probability Question (Prizes)

Question: Forty 17- and 18-year old students are the only people present at a party.
Male 17 yr olds: 9
Male 18 yr olds: 13
Female 17 yr olds: 7
Female 18 yr olds: 11
In the Grand Draw, each of the forty students has an equal chance of winning one of two prizes. The first prize is a gift token. The second prize is a box of chocolates. No student may win more than one prize. Find the probability that the box of chocolates will be won by a 17 year old, given that the gift token is won by a 17 year old male student.
I tried using the formula P(A and B) / P(B):
Here's one attempt: [ (9/40) * (15/39) ]/ 16/40
I did a few other tries, trying different logic, but the answer should be 0.467. I'm very confused.
Comment: I think it should be 15/39, (your were almost right, but should have used P(B)=9/40). The book answer is equal to 7/15 which seems to be the answer to a different question alltogether.
Comment: What Jaap Scherphuis commented.  More specifically, normally, the chance would be (16/40).  However, one of the 17 year olds (a boy) is eliminated from consideration because he won the other prize, and no one is allowed to win both prizes.  Therefore, of the 39 candidates left, only 15 are 17 year olds.  Your instinct, which was probably influenced by the book's typo re the wrong answer, led you astray.  It led you to think that the solution was more complicated than it actually is.
Comment: The book's anwer is correct for the question "Find the probability that the box of chocolates will be won by a 17 year old **female**, given that the gift token is won by a 17 year old male student"
Comment: To the OP: what Henno Brandsma's comment is suggesting is that his explanation was intended by the person who composed the problem.  Possibly, but that means that the problem was **very poorly worded.**
Comment: whew! that makes sense! I've spent almost an hour on this. Thank you, all!
Answer: You can just skip to the second draw after the first has been won by a 17-year old male (so only 8 are left, and 15 17-year olds in total).
The chance of a 17 year old winning in this situation is just $\frac{15}{39}$ and not the answer in your text. That one also mystifies me.
In your attempt the right numbers are $P(B)=\frac{9}{40}$ and $P(A \text{ and} B) =  \frac{9}{40}\frac{15}{39}$ and would have given the same.


How do I dynamically add some piece of php code to an exact position in page before it is returned to the browser?

Question: I need to add this piece of code right before my wp_head(); call using PHP because the code has to execute server side. Hooking the code into my wp_head(); does not work. I need to add it right before. Here is the PHP code to be added.
gravity_form_enqueue_scripts(1,true);

Here is where the code needs to be inserted:
<?php

/* We add some JavaScript to pages with the comment form
 * to support sites with threaded comments (when in use).
 */
if ( is_singular() && get_option( 'thread_comments' ) )
    wp_enqueue_script( 'comment-reply' );

/* Always have wp_head() just before the closing
 * tag of your theme, or you will break many plugins, which
 * generally use this hook to add elements to  such
 * as styles, scripts, and meta tags.
 */

gravity_form_enqueue_scripts(1,true);

wp_head(); ?>

The code should not show on return to browser. How do I add this PHP snippet to this exact location dynamically?
Comment: Is it possible to do this with a combination of jQuery and PHP ?
Comment: Maybe I should hook it into another action in wordpress ?
Answer: I actually needed to :
add_action('wp', 'gforms_add_before_wp_head');

not
add_action('wp_head', 'gforms_add_before_wp_head');

I turns out I just needed to find the right hook to add_action to.


Virtual server EC2 recebe requisições mas não consegue acessar outro host

Question: Tenho uma máquina virtual no Amazon AWS com Ubuntu onde eu mesmo instalei o Apache2, o PHP5 e o MySql.
Estava tudo rodando bem, bem configurado, meu site funcionando muito bem nele.
Até que de repente a máquina virtual parou de acessar outros hosts. Isso acontece para qualquer requisição.
Descobri isso quando um script PHP passou a dar erro de connection timed out ao usar a função file_get_contents().
<?php echo file_get_contents('http://example.com'); ?>

Fui para a linha de comando do servidor, via SSH, e tentei dar um ping num host externo ping google.com e nada.
Tentei usar o apt-get para atualizar o sistema apt-get update e também não conecta.
Ou seja, o meu server EC2 não está conectando a nada externo.
O engraçado é que se eu tento acessar o site, o server recebe normalmente a requisição e devolve o site pro navegador. Ou seja, a conexão com a internet está existindo.
Outo detalhe é que, esse acesso ao file_get_contents() do PHP que estou tentando fazer é também no mesmo site, não num site externo, e ainda assim da timed out.
Aqui o resultado do comando netstat -lnp:
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      957/sshd
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      1098/mysqld
tcp6       0      0 :::22                   :::*                    LISTEN      957/sshd
tcp6       0      0 :::443                  :::*                    LISTEN      1145/apache2
tcp6       0      0 :::80                   :::*                    LISTEN      1145/apache2
udp        0      0 0.0.0.0:68              0.0.0.0:*                           560/dhclient
udp        0      0 0.0.0.0:18032           0.0.0.0:*                           560/dhclient
udp6       0      0 :::60689                :::*                                560/dhclient
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   PID/Program name    Path
unix  2      [ ACC ]     STREAM     LISTENING     8236     785/dbus-daemon     /var/run/dbus/system_bus_socket
unix  2      [ ACC ]     STREAM     LISTENING     6500     1/init              @/com/ubuntu/upstart
unix  2      [ ACC ]     STREAM     LISTENING     8549     965/acpid           /var/run/acpid.socket
unix  2      [ ACC ]     SEQPACKET  LISTENING     6797     324/systemd-udevd   /run/udev/control
unix  2      [ ACC ]     STREAM     LISTENING     8919     1098/mysqld         /var/run/mysqld/mysqld.sock

Aqui o resultado do comendo iptables -L:
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

O que pode estar acontecendo?
Answer: Pra quem teve o mesmo problema como eu, fui a fundo até descobrir que o nameserver estava setado para o ip da amazon.
Então editei o /etc/resolv.conf
e coloquei os nameservers do google
nameserver 188.8.131.52
nameserver 18.104.22.168

e funcionou.
Espero que isso ajude alguém.


Access Token expires when using AWS Load Balancer with OIDC and Keycloak

Question: We run the following setup:

AWS Load Balancer (ALB) with Listener configured to authenticate requests via OIDC. Our OIDC Server is Keycloak
When authentication completed, the request is forwarded to our nginx, acting as Reverse Proxy.
Frontends are stored in AWS S3 and proxied through the nginx.

This work as expected (fine).
Our problem occurs when calling our backend services from the Webbrowser.
For example:
<code>setInterval(() => {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://our-backend-api-via.reverse.proxy.com');
    xhr.send();
}, 1000);
</code>
This works fine until the AccessToken is expired (60s). Then our backend will see that the token is expired and returns HTTP 401 for multiple times.. after a while (20 seconds) a new AccessToken is received and the backends responses fine.
The process of getting new accessToken via AWS ALB seems to be a blackbox for us, we cannot explain why expired accessTokens are send to our backends, shouldn't the AWS ALB renew the token in time?
Comment: can you try to increase the time duration of the access token? say from 60s to 1hour?
Comment: already done, than the token expires after 1 hour.. but same effect as with 1 minute. Now talking to AWS support.
Comment: hi, any update from the AWS support team?
Comment: @AlexJiang Yepp, See my answer. We have used the wrong oidc- header to verify the token (-: Blame on me.
Answer: It was an implementation error. We have used the original JWT provided from Keycloak to verify the expiration time.
The correct way is to use the token provided by alb via x-oidc-amazon-data header.
Answer: You have wrong infra for your use case. ALB OIDC auth is intended for webapps. Your case looks like a SPA = frontend in the browser will be responsible to manage auth state = it will be watching token validity and it will trigger token refresh before token expiration,...


How to Get Image Path From SurfaceView android

Question: How to get the Image path from SurfaceView till now i tried this code
public class CameraSwitch extends Activity implements SurfaceHolder.Callback, OnClickListener {

    private static final String TAG = "MainActivity";

    private Cursor mImageCursor;
    private ImageThumbnailAdapter mAdapter;
    private TwoWayGridView mImageGrid;
    Camera camera;
    SurfaceView surfaceView;
    SurfaceHolder surfaceHolder;
    boolean previewing = false;
    LayoutInflater controlInflater = null;

    int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
    int numberOfCamera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.cameraswitch);

        surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.custom, null);

        Button switchCam = (Button)findViewById(R.id.flip);
    //    Button toggleFlash = (Button)findViewById(R.id.toggleflash);

        LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

        this.addContentView(viewControl, layoutParamsControl);

        switchCam.setOnClickListener(this);

    initGrid();

        Button picbtn = (Button) findViewById(R.id.button1);
        picbtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                camera.takePicture(null,null, new PhotoHandler(getApplicationContext()));
            }
        });
     }

    private void initGrid() {
        // TODO Auto-generated method stub
        Log.e("Bottom Grid View", "Grid view Bottom");

    }

    @SuppressLint("NewApi")
    public void openFrontFacingCamera() {
        numberOfCamera = Camera.getNumberOfCameras();
          if(camId == Camera.CameraInfo.CAMERA_FACING_BACK){
          camId = Camera.CameraInfo.CAMERA_FACING_FRONT;
            Toast.makeText(getApplicationContext(), "BACK TO FRONT" ,1000).show();
                try {
                        Toast.makeText(getApplicationContext(), "try block BACK TO FRONT" ,1000).show();
                         camera.release();
                    camera = Camera.open(camId);
                    camera.setDisplayOrientation(90);
                    //camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

                    /* Comment this set previewDisplay*/
                   // camera.setPreviewDisplay(surfaceHolder);
                    camera.startPreview();
                    previewing = true;
                    }
                catch (RuntimeException e)
                {
                    e.printStackTrace();
                }
                catch (Exception e) {}
        }
        else if(camId == Camera.CameraInfo.CAMERA_FACING_FRONT){
            camId = Camera.CameraInfo.CAMERA_FACING_BACK;

            Toast.makeText(getApplicationContext(), "FRONT TO BACK" ,1000).show();
                    try {
                        camera.release();
                        camera = Camera.open(camId);
                        camera.setDisplayOrientation(90);
                        camera.setPreviewDisplay(surfaceHolder);
                        camera.startPreview();

                    } catch (RuntimeException e) {
                        e.printStackTrace();
            } catch (IOException e) {}
        }
    }

    @Override
    public void onClick(View click) {
        if(click.getId() == R.id.flip){
            openFrontFacingCamera();

        }else if(click.getId() == R.id.flip){
            openFrontFacingCamera();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        if(previewing)
        {
            camera.stopPreview();
            previewing = false;
        }
        if (camera != null){

            try {
                camera.setPreviewDisplay(surfaceHolder);
                camera.startPreview();
                previewing = true;
            } catch (IOException e)
                {
                    e.printStackTrace();
                }
        }
    }

    @SuppressLint("NewApi")
    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        camera = Camera.open(camId);

        camera.setDisplayOrientation(90);
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        camera.stopPreview();
        camera.release();
        camera = null;
        previewing = false;
    }
}

Picture Handler Class
 import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

public class PhotoHandler implements PictureCallback {

  private final Context context;

  public PhotoHandler(Context context) {
    this.context = context;
  }

  @Override
  public void onPictureTaken(byte[] data, Camera camera) {

    File pictureFileDir = getDir();

    if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {

   //   Log.d(MakePhotoActivity.DEBUG_TAG, "Can't create directory to save image.");
      Toast.makeText(context, "Can't create directory to save image.",
          Toast.LENGTH_LONG).show();

      return;

    }

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
    String date = dateFormat.format(new Date());
    String photoFile = "Picture_" + date + ".jpg";

    String filename = pictureFileDir.getPath() + File.separator + photoFile;

    Log.e("path", filename.toString());

    File pictureFile = new File(filename);

    try {
      FileOutputStream fos = new FileOutputStream(pictureFile);
      fos.write(data);
      fos.close();
      Toast.makeText(context, "New Image saved:" + photoFile,Toast.LENGTH_LONG).show();
    } catch (Exception error) {
    //  Log.d(MakePhotoActivity.DEBUG_TAG, "File" + filename + "not saved: "
      //    + error.getMessage());
      Toast.makeText(context, "Image could not be saved.",
          Toast.LENGTH_LONG).show();
    }
  }

  private File getDir() {
    File sdDir = Environment
      .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    return new File(sdDir, "Demo App");
  }
}

till now i tried this
Thanks
Comment: you have one method getDir right. make it public.
Comment: after that log the getDir using instance of PhotoHandler.
Answer: In the takePicture() method one parameter is picture callback. You have to implement that callback and its method on picture taken. It will give you the image data in bytes. You can save the image from there and after that you can do whatever you want to do with that data. This link might help you
http://developer.android.com/reference/android/hardware/Camera.PictureCallback.html
Comment: hi Bhavin Parmar i have already did this by PhotoHandler class and now i want to get capture Image path from that folder to CameraSwitch Class.
Comment: You can make File pictureFileDir a global member or  store the path of the image while capturing in the database.


Linq, fazendo Join comparando com Like

Question: Tenho uma dúvida referente ao Linq. Como tenho observado alguns códigos, geralmente eles utilizam como por exemplo:
 var _s = (from p in exemplo1
           join q in exemplo2 on p.blabla equals q.blablabla

Eu gostaria de saber se uma estrutura como por exemplo que vou mostrar abaixo é válida e como posso criar ela:
var _s = (from p in exemplo1
          join q in exemplo2 on SqlMethods.Like(p.blabla, "%" + q.blablabla + "%")

Comment: Tentei, porém ele "obriga" começar com on e em seguida equals na estrutura, mas eu acho que matei a charada...Vou postar a resposta...
Comment: Isso vai gera erro ... `LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String)' method, and this method cannot be translated into a store expression. `
Comment: @MarconcilioSouza Depois de um tempo pensando eu testei uma solução e funcionou de uma forma semelhante da minha dúvida. Postei na resposta.
Answer: Depois de alguns minutos de chute, eu utilizei está solução e funcionou.
var _s = (from p in exemplo1
          from q in exemplo2
          where
          SqlMethods.Like(p.blabla, "%" + q.blablabla + "%")

Answer: Você pode usar o método Contains para fazer isso.
using (var DBCtx = new RohrdbContext())
{

    var s = (from p in DBCtx.exemplo1
            from q in DBCtx.exemplo2
            where q.blablablabla.Contains(p.blabla)
            select p);

    // eu particulamente prefiro dessa forma.

    var s2 = DBCtx.exemplo1
        .Select(p => new
        {
            P = p,
            C = DBCtx.exemplo2.FirstOrDefault(C => C.Id = p.Id),

        })
        .Where(p => p.P.blablablabla.Contains(p.C.blabla));
        //.Where(p => p.P.blablablabla.StartsWith(p.C.blabla)); // Inicio da string
        //.Where(p => p.P.blablablabla.EndsWith(p.C.blabla)); // fim da string
}

Answer: Like Extensão Linq / SQL
Classe LikeExtension
Testado em .NET 5
 public static class LikeExtension {

    private static string ColumnDataBase<TEntity, TKey>(IModel model, Expression<Func<TEntity, TKey>> predicate) where TEntity : class {

        ITable table = model
            .GetRelationalModel()
            .Tables
            .First(f => f
                .EntityTypeMappings
                .First()
                .EntityType == model
                .FindEntityType(predicate
                    .Parameters
                    .First()
                .Type
            ));

        string column = (predicate.Body as MemberExpression).Member.Name;
        string columnDataBase = table.Columns.First(f => f.PropertyMappings.Count(f2 => f2.Property.Name == column) > 0).Name;

        return columnDataBase;

    }

    public static IQueryable<TEntity> Like<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {

        string columnDataBase = ColumnDataBase(context.Model, predicate);
        return context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);

    }

    public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this DbContext context, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {

        string columnDataBase = ColumnDataBase(context.Model, predicate);
        return await context.Set<TEntity>().FromSqlRaw(context.Set<TEntity>().ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);

    }

    public static async Task<IEnumerable<TEntity>> LikeAsync<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) where TEntity : class {

        DbSet<TEntity> entities = query as DbSet<TEntity>;
        string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
        return await entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text).ToListAsync(cancellationToken);

    }

    public static IQueryable<TEntity> Like<TEntity, TKey>(this IQueryable<TEntity> query, Expression<Func<TEntity, TKey>> predicate, string text) where TEntity : class {

        DbSet<TEntity> entities = query as DbSet<TEntity>;
        string columnDataBase = ColumnDataBase(entities.EntityType.Model, predicate);
        return entities.FromSqlRaw(query.ToQueryString() + " WHERE [" + columnDataBase + "] LIKE {0}", text);

    }

}

Repositório
    public async Task<IEnumerable<TEntity>> LikeAsync<TKey>(Expression<Func<TEntity, TKey>> predicate, string text, CancellationToken cancellationToken) {

        return await context.LikeAsync(predicate, text, cancellationToken);

    }

    public IQueryable<TEntity> Like<TKey>(Expression<Func<TEntity, TKey>> predicate, string text) {

        return context.Like(predicate, text);

    }

Uso
 IQueryable<CountryEntity> result = countryRepository
     .Like(k => k.Name, "%Bra[sz]il%") /*Use Sync*/
     .Where(w => w.DateRegister < DateTime.Now) /*Example*/
     .Take(10); /*Example*/

Ou
 IEnumerable<CountryEntity> result = await countryRepository
     .LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/

Ou
 IQueryable<CountryEntity> result = context.Countries
     .Like(k => k.Name, "%Bra[sz]il%")
     .Where(w => w.Name != null); /*Example*/

Ou
 List<CountryEntity> result2 = await context.Countries
     .Like(k => k.Name, "%Bra[sz]il%")
     .Where(w => w.Name != null) /*Example*/
     .ToListAsync(); /*Use Async*/

Ou
 IEnumerable<CountryEntity> result3 = await context.Countries
     .Where(w => w.Name != null)
     .LikeAsync(k => k.Name, "%Bra[sz]il%", cancellationToken); /*Use Async*/

Linq, fazendo Join comparando com Like