como criar uma função que verifica se duas listas são iguais sem usar o operador (==)?

Question: iguais:: [Int]->[Int]->Bool
iguais [] [] = True
iguais [] _ = False
iguais _ [] = False
iguais (x:xs) (z:zs)

esse é o código, só fiz ate ai. Alguém pode me ajudar?
Comment: Não vale nem `==` pra fazer a comparação de `x == z` ?
Comment: `iguais a b = not (a /= b)`  ok, ok, acho que não era isto que querias...
Comment: não, na verdade eu quero uma chamada recursiva.
Comment: `x == z && iguais xs zs` na tua ultima linha? (ou `not( x /= z) && iguais xs zs` )
Answer: Eu tentei isso:
iguais :: [Int] -> [Int] -> Bool
iguais [] [] = True
iguais [] (_:_) = False
iguais (_:_) [] = False
iguais (x:xs) (x:ys) = iguais xs ys
iguais _ _ = False -- Se chegar aqui eh porque nao deu match na idefinicao de cima

Mas obtive o seguinte erro Conflicting definitions for 'x'.
Descobri que não é possível: https://stackoverflow.com/a/1179394/858412


Javascript sorting numbers and text

Question: how would I sort this using .sort() function in javascript? I know I can add a comparison function here but I'm not sure how I would program this.
Before
1 024c
100 000c
143c
1 020c
10 000c

After
143c
1 020c
1 024c
10 000c
100 000c

Comment: What is format in which you are getting this input? On what basis are you sorting this? What have you tried?
Comment: Can you show your first implementation.
Comment: @void I am trying to order a table column which text similar to this. I have tried the very basic return a-b which works for columns which only has text
Comment: @confusedOne see my answer below.
Answer: If your input is an array then you can use a comparator function
(a,b) => a.replace(/[^\d.]/g, "") - b.replace(/[^\d.]/g, "")
this will remove c and space from the string to form number and compare. See the code below.

var data = ["1 024c",
"100 000c",
"143c",
"1 020c",
"10 000c"]

var sorted = data.sort( (a,b) => a.replace(/[^\d.]/g, "") - b.replace(/[^\d.]/g, ""));

console.log(sorted);
Comment: @ScottSauyet makes sense. Edited :)
Comment: This looks good, but you might want to replace `/ |c/g` with either `/\D/g` or `/[^\d.]/g`.  The first one keeps only digits.  The second keeps only digits and decimals.
Answer: It seems like you want to sort it based on the numbers in them, while excluding spaces.
x.sort(
    (eachObj, prevObj) =>
    parseInt(eachObj.replace(" ","")) - parseInt(prevObj.replace(" ",""))
);

In ES6
Comment: @ScottSauyet missed that. Edited. Thx.
Comment: Note that this gives back `["143c", "1020c", "1024c", "10000c", "100000c"]`, which is not what's wanted.  You need to retain the spaces after sort.

Javascript sorting numbers and text


Operator fault in query

Question: SELECT siteapplications.Application, Count(visits.VisitId) AS CountOfVisitId
FROM visits, siteapplications
WHERE visits.SiteApplicationId=siteapplications.ApplicationID and Month([visits.VisitTime)]=month and Year([visits.VisitTime])=year
GROUP BY siteapplications.Application
ORDER BY CountOfVisitId DESC;

I get a operator fault and when I click ok Group by is highlighted??
Can anyone help, thx all
Comment: Consider a better title. It is vague.
Answer: and Month([visits.VisitTime)]

Your paren closing is off

Operator fault in query


How do you find the matrix M(T)?

Question: $T$ is defined by
$T(x,y,z)= (3x+2y+z,x+5z)$
Find the matrix $M(T,((1,0,0)(1,1,0),(1,1,1)),((1,0),(1,1)))$
So far I have gotten that $M(T)$ is $$ \begin{bmatrix}
        3 &2 &1  \\
        1 &0 & 5 \\
        \end{bmatrix} $$
But I do not know how to incorporate the other values
"$((1,0,0)(1,1,0),(1,1,1)),((1,0),(1,1))$"
Edit:Yes sorry for the lack of clarity, T is the transformation from $R^3$ to $R^2$ and I was asked to find $M(T,((1,0,0)(1,1,0),(1,1,1)),((1,0),(1,1)))$ .
Comment: I think the question is asking you to write the matrix $M$ representing the given linear transformation from $\mathbb{R}^3$ with basis $B_1=\{(1,0,0),(1,1,0),(1,1,1)\}$ to $\mathbb{R}^2$ with basis $B_2=\{(1,0),(1,1)\}$, do you know how to write a change of basis matrix?
Comment: I htink you have to use change of basis.
Comment: What does $M(T,\ldots)$ mean?
Comment: If the ordered pairs are column vectors, then the answer is $\widehat {B_2} \cdot \left[\matrix{3&2&1\cr 1&0&5\cr}\right]\cdot \widehat{B_1}^{-1}$, where $\widehat A$ is the matrix you get by "gluing" the vectors in the basis together (to make a matrix).
Comment: What is a change of basis matrix?  Perhaps that is where I am struggling.
Comment: For example the vector $(2,0)\in\mathbb{R}^2$ in the basis $\{(3,1),(0,7)\}$ would be written as $(6,2)$ in the canonical base $\{(1,0),(0,1)\}$. A change of basis matrix is a matrix representing the identity transformation going from $V$ with a basis to itself with another basis, basically it translates the coordinate of vectors written in a base into another one
Answer: If we interpret $M(T,((1,0,0)(1,1,0),(1,1,1)),((1,0),(1,1)))$ as 'matrix representation of $T$  w.r.t. the bases $\{(1,0,0)^T,(1,1,0)^T,(1,1,1)^T\}$ (in the domain) and $\{(1,0)^T,(1,1)^T\}$ (in the codomain)' then translates to the task to:

Apply $T$ to the basis vector  $\{(1,0,0)^T,(1,1,0)^T,(1,1,1)^T\}$ in the domain, resulting in $v_1 = T((1,0,0)^T), v_2 = T((1,1,0)^T), v_3 = T((1,1,1)^T).$
Write these three vectors $v_1, v_2, v_3$ as linear combinations of $\{(1,0)^T,(1,1)^T\}$
Put the coordinates (i.e. the linear factors in front of $(1,0)^T,(1,1)^T$) of $v_1, v_2, v_3$ column-wise into a matrix.

Does this outlining of these steps help you?
Even though this look different, note that this is essentially the same as calculating $\hat B_2 A \hat B_1^{-1}$ from Carl Heckman's comment.

How do you find the matrix M(T)?


Which statistic test should I use in this situation?

Question: There are 10 questions in which we are comparing peoples' opinion about two conditions, "X"and "Y". Every question was answered by about 90 people who were different than other questions' respondents. The results are something like this:
    X  Y

Q1: 21, 47
Q2: 84, 10
...
Q10: 43, 38
I want to compare these two conditions. One of them is not normally distributed. Which statistic test should I use? Two-Sample t-test or the Paired t-test, Wilcoxon-Mann-Whitney, or something else?
Comment: In the data you present, are those counts of respondents choosing e.g. X? Would every row add up to e.g. your 90 people?
Comment: Both yes. But there is variability in number of respondents.
Answer: I suppose you want to test whether there is significant evidence that either opinion X or Y has stronger support.
Simulated data. One model for your data, in which opinion X is very slightly more popular than opinion Y,  might be that you have $N \sim \mathsf{Pois}(\lambda = 90)$
people answering each of the questions, and then that opinion X gets
$x \sim \mathsf{Binom}(N, p=.55)$ votes and opinion Y gets $y = N-x$ votes.
Simulating this model, we have data:
set.seed(2018); N = rpois(10, 90)
x = rbinom(10, N, .55); y = N-x
cbind(x,y, d=x-y)
       x  y  d
 [1,] 51 34 17
 [2,] 36 45 -9
 [3,] 51 41 10
 [4,] 53 53  0
 [5,] 51 36 15
 [6,] 56 38 18
 [7,] 59 34 25
 [8,] 50 41  9
 [9,] 49 49  0
[10,] 47 44  3

Below we show results of various tests to see which ones detect the slight
difference in preference of opinion X over opinion Y assumed in the simulation
of these data. All alternatives are two-sided.
Sign test. The simplest test is a sign test, which looks at the number of negative
signs in the last column (disregarding the 0's). It does not reject (5% level) the null
hypothesis that the two opinions are equally popular.
The p-value is 0.0703. The sign test has relative low power. It "ignores" that
there are several large positive values in the last column and only one negative value.
2*(pbinom(1, 8, .5))
[1] 0.0703125

Wilcoxon Signed Rank test. A (one-sample) Wilcoxon signed-rank test rejects with approximate p-value 0.035.
The warning messages are because of the 0s and because $\pm 9$ is considered a tie.
wilcox.test(x-y)

        Wilcoxon signed rank test with continuity correction

data:  x - y
V = 33.5, p-value = 0.03547
alternative hypothesis: true location is not equal to 0

Warning messages:
1: In wilcox.test.default(x - y) : cannot compute exact p-value with ties
2: In wilcox.test.default(x - y) :
  cannot compute exact p-value with zeroes

One-sample t test. A one-sample t test rejects the null hypothesis. The p-value is 0.025. The data
may not be normal, but the t test is known to be robust.
t.test(x-y)

        One Sample t-test

data:  x - y
t = 2.695, df = 9, p-value = 0.02459
alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
  1.413365 16.186635
sample estimates:
mean of x
      8.8

Permutation test. A permutation test, using the sum of differences as metric, rejects the
null hypothesis. When signs were randomly permuted, we observed 85 unique
sums of differences. The p value is 0.015; it is the probability that
sums of permuted differences lie outside the two vertical bars (at $\pm 88)$
in the histogram. The p-value is simulated and subject to unimportant
variation with 100,000 iterations. Three subsequent runs gave essentially the same p-value. [The Wilcoxon test is a kind of permutation test, but the
current test needs no adjustments for 0's and ties.]
d.obs = sum(x-y);  d.obs
[1] 88
d.perm = replicate( 10^5, sum((x-y)*sample(c(-1,1), 10, rep=T)) )
mean(abs(d.perm) > abs(d.obs))
[1] 0.01529
length(unique(d.perm))
[1] 85

Summary. In summary, only the notoriously low-powered sign test failed to find
a significant difference in popularity between opinions X and Y. The permutation test gave the smallest p-value. On various grounds, one might wonder whether
the assumptions for the Wilcoxon and t tests are met.
Note: You could also do a chi-squared test of homogeneity using the matrix
of x and y values. It gives a non-significant result, which indicates
there is no significant difference in the distribution of opinions between X and Y across the ten questions. This test is not appropriate for assessing
whether opinions X and Y are equally popular.
chisq.test(cbind(x,y))

        Pearson's Chi-squared test

data:  cbind(x, y)
X-squared = 10.894, df = 9, p-value = 0.2831

Answer: Since you have a table of counts, you will want to use methods appropriate for count data.  These might include chi-square test and logistic regression.
The simplest approach for your data would be to treat each Question separately.  You will be assessing if the proportion of X and Y follow a null 50% / 50% distribution.  For the hypothesis test, you might perform a chi-square goodness-of-fit test or a binomial test.  For the effect size, you might just present the proportions of X and Y, or you could use another statistic like odds ratio.  You might want to construct confidence intervals for the proportions and present these as well.  (Be sure to use a method that is appropriate for proportions).
A different question would be to ask if the distribution of X or Y changes across questions.  Here you could use a chi-square test of association on the whole table (Questions on one axis, and X-Y on the other, as you laid it out in the question).
Another approach to this second question is to use logistic regression where X-or-Y is your dependent variable and Question is your independent variable.  This approach is helpful if you have additional factors you want the model to consider.  For example, if you had also recorded the sex of respondents and wanted to include that as a predictor.
For example, if we look at Question 1, we could conduct a binomial test.
binom.test(21, (21+47))

   # Exact binomial test
   #
   # data:  21 and (21 + 47)
   # number of successes = 21, number of trials = 68, p-value = 0.002186
   # alternative hypothesis: true probability of success is not equal to 0.5
   # 95 percent confidence interval:
   # 0.2023635 0.4325608
   # sample estimates:
   # probability of success
   #          0.3088235

Here, the proportion of X being chosen is 0.31.  This is significantly different than a null proportion of 0.50 (p = 0.002).
We could also report the 95% confidence interval of this proportion (0.20 to 0.43).  This is helpful in presenting results in tabular or graphical form.
Comment: Interesting approach to look at each question separately.(+1)  In a summary of such results one might want to control the family error rate by using Bonferroni or some such method.
Comment: One goal of this answer is to keep the analysis simple.   I suppose what I might do in a case like this is to first run the chi-square test of association.  If that test is not significant, I would probably pool the data across all questions, and run a single binomial test.  If the association test is significant, I would analyze the questions separately.


Cox PH model and time splitting

Question: I have question about the 'setup' for the data for Cox PH survival modelling in case of modelling time to 'breakdown'.
My data are houses and roof repair. For each house I have either the age of the house when it was repaired (Event_01=1) or, if was not repaired, the age at the time of sampling (Event_01=0). So I have the time to event (Event_Year) and the event itself (Event_01).
Furthermore I have some variables for use as explanatory variables like roof type, house price, square meters etc.
In most examples I have seen the age is the age of the 'object' (a person for instance) at the time of the treatment or whatever it is that is examined. However here the 'treatment' is building the house so the (start-)age is always 0 since the time starts when the house is brand new. But the age of the house is an important parameter when it comes the predicting the risk of repair - I would expect the risk to increase as the house age increases. What do you do in this case?
What I did was making time splits for several times like 5, 10, 15 etc. years. Like this:
Original data:
<code>    House ID Event_Year Event_01
           1          3        0
           2          7        1
           3         11        0
           4         13        1
</code>
With splits at 5 and 10 years it becomes:
<code>    House ID Split_Time Event_Year Event_01
           1          0          3        0
           2          0          5        0
           2          5          2        1
           3          0          5        0
           3          5          5        0
           3         10          1        0
           4          0          5        0
           4          5          5        0
           4         10          3        1
</code>
This way my model showed that the higher the split-year, the higher the hazard which matched my expectations.
So my question(s) is: Is this a good way to do it - did I misunderstand something completely? Is there a more simple way to include the house age in this case? Did I violate all assumptions about independence so it is useless?
Answer: I don't see any need to do this.  You can do a survival analysis on the original data, you just don't have a "treatment".  Your only independent variable is "age of house".  Some of your cases are censored (that is, no event occurred) but that's fine - that is the issue that survival analysis was designed for.
Comment: Sorry didn't see your example right way, I will have a look at it tomorrow. Thank you
Comment: That was what I did first but coxph return with a warning and the coefficient looked very strange,

It might be because the house age is actually the same as the event_Year and this is the dependent variable. As I see it the observation of all houses starts at house age = 0 and the event (or censoring) happens at the age of the house (and therefore it is the dependent variable). Hence in the original data all independent house ages are 0. So I have to make my own artificial house age input values by splitting in order to get house ages that are different from 0.
Comment: Categorizing your variable won't help.  The problem is Cox PH.  That requires an independent variable and you haven't got one.  In SAS, you can do what you want with PROC LIFETEST. See, in particular, [Example 3](http://documentation.sas.com/?cdcId=statcdc&cdcVersion=14.2&docsetId=statug&docsetTarget=statug_lifetest_examples03.htm&locale=en)
Comment: I don't see it as categorizing the dependent variable, I see it as creating an input house age variable that has values apart from 0. I don't change the dependent house age (=Event_Year) except concerning the time spit, but it still remains continuous. But I define points in time from where I observe the outcome. This way I will also be able to use the formula in scoring houses that are older than 0 years afterwards.
Comment: I looked at the example and it looks to me like classical treatment data where the objects (persons) have an age when they enter the treatment. In my data the 'survival' time is always measured from when the house was built (age=0 years). So I still don't see any other way than what I wrote in the beginning - creating my own observation points in time. This way I can use the house age 'factor' as input (this is not the same as the Event time house age) and I can use the estimated formula for scoring houses that have an age that is different from 0. I can also make the house age numerical input

Cox PH model and time splitting


jQuery - .children() on a table is not a function

Question: So this is the HTML:

        Doober durr
        Skippi doober
        Doober duck
        Doober McD

        <input type="text" class="form-control" name="v6" placeholder="Mæling 1" />

        <input type="text" class="form-control" name="v9" placeholder="Mæling 1" />

        <input type="text" class="form-control" name="v12" placeholder="Mæling 1" />

        <input type="text" class="form-control" name="v15" placeholder="Mæling 1" />

<button style="float:right;" class="btn btn-primary" id="calc"> REIKNA</button>

Basically what happens is, the statement
$("#calc").click(function () {
        console.log($(this).siblings()[0]);
    });

returns the table, but as soon as I try to call .children() on the table, it says it's not a function.
Answer: That is because $(this).siblings()[0] return dom object of table and not jquery object.You can rather pass table selector to siblings method as argument to get the jquery object of table:
$("#calc").click(function () {
    console.log($(this).siblings('table').children());
});

Comment: @Firkamon: glad it helps :)
Answer: The problem is $(this).siblings()[0] returns a dom element reference so it don't have access to jQuery methods.
So if you want to access the element by index then use .eq(index) which will return a jQuery object reference to the element at the said index.
$(this).siblings().eq(0).children();

Answer: You should use $($(this).siblings()[0]).children() because the way you've written, you get the DOM object of the table, not the jQuery object.
Comment: This is an elegant solutions as well, wrapping the DOM element again in a jQuery wrapper. `$(this).siblings().eq(0).children()` as suggested by @Razvan Dumitru is even better.
Answer: Try with .prev()
$(this).prev().children()

Answer: $(this).siblings()[0] is a DOM element. You can get what you want with $(this).siblings().eq(0).children() or get the jQ object using the DOM element, but it's kinda ugly.
var domEl = $(this).siblings()[0];
var $jQEl = $(domEl);
var $children = $jQEl.children();

Good practice: prefix your jQ objects with $.


Determine if a system described by a differential equation is linear

Question: A system ("A System is any physical set of components that takes a signal, and produces a signal") is described by this equation:
$ \frac{dy(t)}{dt} + 3 \times y(t) = x(t) $
Where $x(t)$ is the input and $y(t)$ the output.
How to determine if this system is a linear one?
Answer: It is linear because the operators on $y(t)$ are linear, namely differentiation and multiplication. An example of a non-linear system would be $$\frac{dy(t)}{dt} + 3 \times y(t)^2 = x(t)$$ because squaring is not a linear operator. It does NOT satisfy $(y_1+y_2)^2=y_1^2+y_2^2$. This is in contrast to $\frac{d}{dt}(y_1(t)+y_2(t))=\frac{d}{dt}y_1(t)+\frac{d}{dt}y_2(t)$ and $3\times(y_1+y_2)=3\times y_1+3\times y_2$.
Comment: Thank you, Teun. I thought I had to use something like S{ a * x_{1}(t) + b* x_{2}(t)} = a* S{x_{1}(t)} + b * S{x_{2}(t)} (In fact this is what you are using, but I wasn't sure which would be the system output)..
Comment: Glad to help! What you're saying is almost correct except for the fact that when we have two solutions $y_1$ and $y_2$ and plug $y_3=ay_1+by_2$ into your differential equation we get: $$\frac{dy_3(t)}{dt} + 3 \times y_3(t) = a\left( \frac{dy_1(t)}{dt} + 3 \times y_1(t)\right) +b\left( \frac{dy_2(t)}{dt} + 3 \times y_2(t)\right)=(a+b)x(t)\neq x(t)$$ unless you pick specific values for $a$ and $b$, so it wouldn't work anymore. This is because the DE is non-homogeneous.
Comment: So the system (and what I mean with system is this: "A System, is any physical set of components that takes a signal, and produces a signal") is not linear?
Comment: No it's linear because of the reasons I posted in my original answer (differentiation and multiplication are linear). I just wanted to show that even though the system is linear, it is important to realize that doesn't mean that every linear combination of solutions will give another solution to your system :)
Answer: It depends on your definition of linear.
In the study of ODEs, the system is linear if it can be expressed in the form $L y = x$, where $L$ is a linear differential operator of the form $(Ly)(t) = \sum_{k=0}^n a_k(t) y^{(k)}(t)$, and the coefficients $a_k$ satisfy some continuity condition. Since we can write the above as $Ly = x$ with  $(Ly)(t) = y^{(1)}(t)+3 y(t)$, it is clear that the system is linear in this sense.
From a control system perspective, the system is linear (I am omitting many details) if the solution $t \mapsto y_{y_0, x}(t)$ is a linear function of $(y_0,x)$, where  $y_0$ is the initial state $y_0$ and $x$ is the input.
The above
equation can be written as $\dot{y} = f(y,x)$, where $f(y,x) = -3 y +x$. $f$ is globally Lipschitz in $y$, hence a globally unique solution exists passing through a given initial condition. Since the solution is unique, it is straightforward to verify (by differentiating and checking that it satisfies the ODE) that the system is linear by just checking that if $y_{y_0, x}, y_{y_0', x'}$ are solutions (with initial conditions and inputs $(y_0, x), (y_0', x')$ respectively), then $\alpha y_{y_0, x} + \alpha' y_{y_0', x'}$ is a solution with initial condition $\alpha y_0 + \alpha'y_0'$ and input $\alpha x + \alpha'x'$. Hence the system is linear.
Comment: What do you mean with "control system"? I've updated my question with a definition of the system I mean. Is your answer in compliance with the new meaning of the system so that I can read it to answer to you?
Comment: The term 'dynamical system' would be have been more appropriate. The dynamical system focus is mainly concerned with modeling the input-output behavior. Your system is linear in both senses.


Where is socket create function implemented in linux

Question: I know the function to create socket:int socket(int domain, int type, int protocol); is located in #include <sys/socket.h> and I can find it on my linux file system.
But where I can find the implementation of this function? I couldn't find a matching one in the kernel source.
Comment: you want `socket()` function definition?
Comment: Why do you ask? With what point of view (kernel hacking, or user-land application code)?
Answer: Look on kernel.org for the authentic kernel source. Understand that socket(2) is one of the many syscalls(2) (you need to understand precisely what system calls are) so it is implemented inside the kernel as sys_socket and/or sys_socketcall and/or do_socket; sockets and network code are an entire subsystem (net/) of the kernel, so see its net/socket.c, etc etc... See also socketcall(2)
Application user-side code are simply issuing a syscall, so socket(2) is a thin wrapper around a system call (in GNU libc or musl-libc or whatever implementation of the C standard library you are using). See also this.
Comment: Yes, a wrapper function
Comment: Also note that you'll be calling a library function in `libc.so` that in turn calls the system call.
Answer: sys/socket.h should be in /usr/include. Typically, it's a part of the "GNU C Library", but depending on your system, that might also be a different C library (ie. on systems you can't call GNU/Linux, like Android, there might be different libc than glibc).
However, that's just the header, not the implementation of the syscalls beneath! You will have to look through glibc's source code (which usually is not installed, only the headers), and then match what you find there to the system calls implementation in linux.
Answer: if you want to check the linux implementation of socket creation, you. can look here


Copy image from Uri in another Folder with another name in Kotlin Android

Question: i am working on an App right now and i want to safe a picture from which i have the uri in another dictonary with a new name.
My App is crashing right now, after i press the button.
The Copy Code function is from Stackoverflow as well, i dont understand it completly, but i am pretty sure, that i used it right. But i'm not sure, if i do the sourcePath and destinationPath right. Also sry for my bad english, i hopy my stuff is understandable.
This is my code rightnow, maybe you can help me:
package com.example.stepbook

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast

import androidx.core.net.toUri

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.URI
import java.nio.channels.FileChannel

import java.util.*

class ChooseWeight : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_choose_weight)

        val uri : Uri? = intent.getStringExtra("Foto")?.toUri()

        val imageView : ImageView = findViewById(R.id.progress_Picture)

        imageView.setImageURI(uri)

        val button : Button = findViewById(R.id.accept_photo_button)

        val kiloText : EditText = findViewById(R.id.weight_input)

        button.setOnClickListener {
            if(kiloText.text.toString().toIntOrNull() == null){
                val toastNull = Toast.makeText(this, "Bitte gib ein Gewicht an!", Toast.LENGTH_SHORT)
                toastNull.show()
            }else{

                val kilo : Int = kiloText.text.toString().toInt()
                val toast = Toast.makeText(this, "Bitte gib ein realistisches Gewicht an! ", Toast.LENGTH_SHORT)
                if(kilo <= 45 || kilo >= 250){
                    toast.show()
                }else{

                    val sourcePath : File = File(URI(uri.toString()))
                    val destinationPath: File = File(URI("content://media/external/images/media/stepbookgallery/" + Calendar.getInstance().toString() + kilo.toString()))
                    copyPicture(sourcePath, destinationPath )

                    val intent = Intent(this, MainActivity::class.java)
                    startActivity(intent)
                }
            }

        }

    }

    fun copyPicture(sourcePath : File, destinationPath : File){
        if(!sourcePath.exists()){
            return
        }

        var source : FileChannel? = null;
        var destination : FileChannel? = null;

        source = FileInputStream(sourcePath).channel
        destination = FileOutputStream(destinationPath).channel

        if(destination != null && source != null){
            destination.transferFrom(source, 0, source.size())
        }
        if(source != null){
            source.close()
        }
        if(destination != null){
            destination.close()
        }

    }

}

Comment: You cannot use the File class for content scheme uries. Further you did not tell the value of the uri that your activity got from intent.
Comment: `URI("content://media/external/images/media/stepbookgallery/" + Calendar.getInstance().toString() + kilo.toString())` You can not build up a MediaStore uri yourself in such a way.
Answer: There are 2 types of uri -> content uri and file uri:
Content uri : "content://media/external/audio/media/710"
Base URI : "file:///sdcard/media/audio/ringtones/nevergonnagiveyouup.mp3"
File class needs file uri. Because content uri does not have a scheme. The function below creates a temporary file using content uri with inputStream. InputStream reads the file from content uri, creates a new file with it. And you can extract file uri, file path from this file. For your problem, you can edit outputDir and fileName variables to save your new file.
fun createFileFromContentUri(fileUri : Uri) : File{

var fileName : String = ""

fileUri.let { returnUri ->
    requireActivity().contentResolver.query(returnUri,null,null,null)
}?.use { cursor ->
    val nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    cursor.moveToFirst()
    fileName = cursor.getString(nameIndex)
}

//  For extract file mimeType
val fileType: String? = fileUri.let { returnUri ->
    requireActivity().contentResolver.getType(returnUri)
}

val iStream : InputStream =
requireActivity().contentResolver.openInputStream(fileUri)!!
val outputDir : File = context?.cacheDir!!
val outputFile : File = File(outputDir,fileName)
copyStreamToFile(iStream, outputFile)
iStream.close()
return  outputFile
}

fun copyStreamToFile(inputStream: InputStream, outputFile: File) {
inputStream.use { input ->
    val outputStream = FileOutputStream(outputFile)
    outputStream.use { output ->
        val buffer = ByteArray(4 * 1024) // buffer size
        while (true) {
            val byteCount = input.read(buffer)
            if (byteCount < 0) break
            output.write(buffer, 0, byteCount)
        }
        output.flush()
    }
}
}

Also, check this link for the answer to "How to Publish Files Via a content Uri?" question.


Use Certificate Revocation List file with X509 in .Net

Question: Need to protect client-server communication. I was found a nice approach in .Net Core to generate X509 Certificates ( Self-Signed).  But it's really lack of any information how to work with Certificate Revocation List in .Net Framework.  Will be appreciate for answers to those questions :

How to create CRL file with .Net ( Without BouncyCastle ) ? Can it be created as any text file and signed after? If yes, what is the format of columns?
Is I'm right understanding that CRL file could be added to Certificate? As far as I know, a change of certificate brokes it.
How to add Certificate to Certificate Revocation List?
Answer:
How to create CRL file with .Net ( Without BouncyCastle ) ?

you can't, .NET natevely don't ship any API to deal with X.509 CRL files. You have to use 3rd party libraries.

Can it be created as any text file and signed after?

No, it is not a text file.

If yes, what is the format of columns?

X.509 CRL uses Abstract Syntax Notation One (ASN.1) for internal representation and ASN.1 module is defined in RFC 5280 Appendix A.1 (page 118). Unfortunately, .NET doesn't provide tools to work with raw ASN.1 data (only for well-known and supported high-level types).
If you can't use 3rd party libraries, you will have to learn about ASN.1 (not easy stuff), write your own binary parser and create X.509 CRL decoder according to ASN.1 module definition. Here is an example of binary ASN.1 parser: Asn1Reader.cs, so you can imagine the complexity in writing your own reliable parser. And an example of X.509 CRL decoder: X509CRL2.cs. I would suggest to get something already working and use it.

How to add Certificate to Certificate Revocation List?

You will have to create X.509 CRL builder/generator by using ASN.1 encoder. CRL entry type is defined as follows:
 revokedCertificates     SEQUENCE OF SEQUENCE  {
      userCertificate         CertificateSerialNumber,
      revocationDate          Time,
      crlEntryExtensions      Extensions OPTIONAL
                               -- if present, version MUST be v2
                           }  OPTIONAL,

This barely makes any sense if you are not familiar with ASN.1, but reveals some useful things. For example, a CRL entry consist of certificate serial number (integer) and revocation date (UTCTime or GeneralizedTime). Optionally, there might be CRL entry extensions, like revocation reason (ENUMERATED).
Answer: The ability to create CRLs was added in .NET 7 in the form of the CertificateRevocationListBuilder class.
Assuming you already have a PKI infrastructure set up, updating a CRL looks like
CertificateRevocationListBuilder crlBuilder = CertificateRevocationListBuilder.Load(
    currentCrl,
    out BigInteger currentCrlNumber);

crlBuilder.AddEntry(certToRevoke);

BigInteger nextCrlNumber = currentCrlNumber + 1;

byte[] newCrl = builder.Build(
    caCertificate,
    nextCrlNumber,
    DateTimeOffset.UtcNow + caCrlUpdateInterval,
    HashAlgorithmName.SHA256,
    RSASignaturePadding.Pkcs1);

Is I'm right understanding that CRL file could be added to Certificate?

The certificate doesn't contain the CRL (otherwise it would basically be immune from revocation...), but if it supports being revoked by CRL it contains a CRL Distribution Point extension that says where the CRL is published.  The CRL Builder class can help with this, but you have to do it at the time you built the original certificate, you can't add it after (because that would require re-signing the certificate, which makes it a new certificate).
X509Extension cdpExtension =
    CertificateRevocationListBuilder.BuildCrlDistributionPointExtension(
        new[]
        {
            "http://example.org/pki/exampleCA2023-shard2.crl",
            "ftp://example.org/pkifiles/crls/exampleCA2023-shard2.crl",
        });

Note that your CDP endpoint should be http, not https, as CRL retrieval systems usually won't follow https, otherwise they could end up in a circular dependency.


Single speaker with 2 8ohm parallel inputs?

Question: I just got a free Fender cabinet that only has one speaker, but looking at the back it has two separate inputs. They're labeled as 8ohm parallel, but I thought you needed at least two speakers to wire a cabinet in parallel.
Does this mean I can just use either one of the inputs and it will be 8ohms?
Comment: You don't want to plug two amps into any speaker!!   it's a strange one, but is probably an orphan, its twin got lost somewhere.
Comment: It's a throughput socket, wired in parallel. Wiring one will give 8 ohms, wiring 2 will give 4 ohms.
Comment: @Tetsujin, so if I only plug my amp into one input it's 8 ohms, but if I were to plug two amps into it, it would be 4 ohms for each?
Comment: no no no... one amp only. Potentially 2 identical speakers... though as you only have one, the point is moot.
Comment: @Tetsujin, I'm still somewhat confused. Why have two inputs for the one speaker if you're never supposed to use both? The cab was clearly built to have only the one speaker.
Comment: Orrr are you saying I can chain multiple cabinets if I had more than one? That would make much more sense
Comment: One amp, two speakers is what it was designed for. As Tim says, **never** two amps, one speaker.
Comment: I assumed that was a bad idea haha that's why two inputs had me confused. Thanks for the help :)
Answer: It's almost certainly a Through connection, wired in parallel with the other socket.  Yes, you can use either socket as input.  If you connect through to a second, similar speaker, the amplifier will be seeing 4 ohms.   This won't worry a modern amplifier, though it might an older valve amp.
Answer: Best solution - open up the cab., see how the jacks are wired - series, parallel, put a multimeter across the speaker to see if it is indeed 8ohms. Then you have the options.


Cannot save a .docm file after assigning a value to a particular document.variable

Question: I have a file with a macro that was originally created as a .doc file. If I try to save it as a .docm or .dotm file, it will not save.  No error message, but the file doesn't get saved.
If I remove the module; or save it as a .docx file, it will save.
If I

open the .docx file
import or copy/paste the previous macro into a regular module
run the macro

again, it cannot be saved as a .docm
If I remove the module, I can save it as a .docm
Or, even with the macro present and having been run, I can save it as a .doc file.
So it seems there might be something in the macro that, after having run, creates a file that cannot be saved as a .docm but could still be saved as a .doc file.
The macro examines some custom properties of the document that are manually entered.  It computes a variety of document variables which are used in fields throughout the document, and then updates those fields.
By using breakpoints, It seems that when the code assigns a value to the Document.Variable "sign", the document can no longer be saved.  That is a date field, but there are other date fields in the document that don't cause this problem.
The code.text for the particular fields:
docvariable "sign" \@ "MMMM, yyyy" \*upper \* MERGEFORMAT
docvariable "sign" \@ "d" \* OrdText \*upper\* MERGEFORMAT

The macro code (in a regular module):
Option Explicit

Sub Update()
    Dim prop As DocumentProperty
    Dim area As Double, rent As Double, start As Date, tend As Date, notice As Date, term As Long, Sign As Date
    Dim annual As Double, annualcents As Double, monthly As Double, monthlycents As Long
    Dim var As Variables

'get Document Properties
For Each prop In ThisDocument.CustomDocumentProperties
    If prop.Name = "area" Then area = prop.Value
    If prop.Name = "rent" Then rent = prop.Value
    If prop.Name = "start" Then start = Int(prop.Value)
    If prop.Name = "term" Then term = prop.Value
    If prop.Name = "sigDate" Then Sign = Int(prop.Value)
Next prop

    annual = area * rent
    annualcents = 100 * (annual - Int(annual))
    monthly = annual / 12
    monthlycents = 100 * (monthly - Int(monthly))
    tend = DateAdd("yyyy", term, start)
    tend = DateAdd("d", -1, tend)
    notice = DateAdd("m", -4, tend)

Set var = ThisDocument.Variables
    var("area").Value = area
    var("rent").Value = rent
    var("start").Value = start
    var("term").Value = term

    'if this line is not run or
    'if this document variable is deleted,
    'the file will save as expected
    var("sign").Value = Sign

    var("annual").Value = annual
    var("annualcents").Value = annualcents
    var("monthly").Value = monthly
    var("monthlycents").Value = monthlycents
    var("tend").Value = tend
    var("notice").Value = notice

ThisDocument.Fields.Update

End Sub

Answer: The Document.Variable "sign" is used by Word to indicate that a valid digital signature has been applied to the code project.
Choose a different name for your variable such as "sigDate"
Comment: Thank you for the solution.  I searched for things like "ms-word reserved words", and found nothing.  I looked up `Sign` and found it listed as a method of the `Signature` object.  I changed the name in the `CustomDocumentProperties`, but I never changed it in the `Variables` list.  This has been driving me crazy for years!


derivate of a Trace operator

Question: What is the derivative of this operation
$A=Trace [(1U-W)\circ(1U-W)]$ with respect to $U$, when $\circ$ represents an element wise (hadamard) product. $1$ is a matrix with same size as $U$ where all elements are $1$.
Comment: What have you done so far?
Comment: I have tried to convert hadamard product to normal matrix product.
Comment: And $U$ and $W$ are quadratic of the same size, right?
Comment: Yes, they are same size
Answer: We have for $U, H \in \def\Mat{\mathop{\rm Mat}\nolimits}\Mat_n(\def\R{\mathbb R}\R)$ that$\def\tr{\mathop{\rm Trace}}$
\begin{align*}
  A(U+H) &= \tr\bigl([1(U+H) - W]\circ [1(U+H)-W]\bigr)\\
         &= \tr\bigl((1U - W + 1H)\circ (1U - W + 1H)\bigr)\\
         &= \tr\bigl((1U - W)\circ(1U- W) + 2\cdot 1H\circ(1U-W) + 1H  \circ 1H\bigr)\\
         &= A(U) + 2 \tr \bigl(1H \circ (1U-W)\bigr) + \tr(1H \circ 1H)
\end{align*}
Now $\def\abs#1{\left|#1\right|}\def\norm#1{\left\|#1\right\|}$
$\tr(1H \circ 1H)$ is a finite sum of two-factor-products of entries of $H$, hence $\abs{\tr(1H \circ 1H)} \le C\norm{H}^2$ for some ($n$-dependent) constant $C$. So $\tr(1H \circ 1H) = o(\norm H)$ and as $H \mapsto 2\tr(1H \circ (1U-W))$ is linear in $H$, this is the derivative, giving
$$ A'(U)H = 2\tr\bigl(1H \circ (1U-  W)\bigr) $$
Comment: What is H? I dont have any H in my  question. I would like to computze $\frac{\delta A}{\delta U}$
Comment: The definition of derivative I used is the following: $A$ is differentiable in $U$ iff there is a linear $A'(U) \colon \Mat_n(\R) \to \R$ such that $$ A(U+H) = A(U) + A'(U)H + o(\norm H), \quad H \to 0 $$
Then $A'(U)$ is called the derivative of $A$ in $U$. What definition do you know?

derivate of a Trace operator


Sort nodes based on the amount of tags that match a specific node tags

Question: Is there anyway to sort the nodes on a views display using the amount of matching tags of a specif node? I would like to have a views display that shows me all the nodes that most match with a given node.
For example: I have one node with three terms associated with it and I'll pass this node to a views as an argument. The views should display first the nodes that have this same three terms, after that it should display the nodes which match with two of the three terms, after that the nodes that match one of the three terms and after that the nodes that doesn't match any of the three terms.
I couldn't find something that could solve this problem for me. If there isn't any implemented solution I'd like to know if it's feasible to implement this on Drupal 7.
Comment: http://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3
Answer: Check out Similar by Terms module. This Drupal module attempts to provide context for content items by displaying a block with links to other similar content. Similarity is based on the taxonomy terms assigned to content. Blocks are available based on similarity within each of the defined vocabularies for a site as well as a block for similarity within all vocabularies. There are two methods of sorting. 1) Based on the most number of matching terms. 2) Based on lest used terms.
Or you could use the Relevant Content module. This module provides two ways of referencing relevant content. Both of these methods provide configuration to filter for specific content types and vocabularies, limit the maximum size of the result and provide some header text. The result on both cases are a list of nodes which the module considers most relevant based on the categorization of the current page. This is achieved by finding other nodes which are of one of the allowed types and have the most number of terms in common.
Comment: this two modules are a little bit buggy for drupal 7 and they don't really solve my problem. I would like some module that integrates with views and both of your solution don't.
Comment: Do you have any idea on how hard would be to implement this sort on views 3.0 and drupal 7?
Comment: Similar by terms is entirely built in views.
Comment: are you sure that the version for drupal 7 uses views?
Comment: I have just downloaded and enabled the 7 version and it appears to be quite unstable (As per the description on the project's homepage). That being said, the 6 version was moved to a views plugin so it could be more flexible, so I would assume that the seven version, when solid, would be the same. You just may have to wait.
Comment: yeah... pretty unstable... And I don't have enough time to wait and the last update on this module was on february so I'm giving up it. Do you know any other alternative using views to develop this?
Comment: Not sure. Similar by Terms was created specifically to fill this gap in Drupal and Views. I am not sure if there is another method that came along after. Maybe someone else can chime in if they know.
Answer: I don't know if have a specific module to use, but I have two options, you can use query_alter to change the arguments, but I guess that you will need to execute the views other times to get the other results. Another option is execute a specific query to get a list of nids ordered by the sum of matching terms.


Como usar preg_match() para pegar um link dentro de um código Javascript

Question: Olá, estou fazendo um file_get_contents() no PHP e obtendo um JS, nesse javascript tem um código onde contem:
$("#download-botao").attr("href", "link.com");

Estou querendo pegar esse link.com no meu PHP, estou tentando através de preg_match(), com o seguinte código:
preg_match('/$("#download-botao").attr("href", "(.*?)");/', $url, $final);

porem não está funcionando, está retornando empty, quem puder ajudar, ficaria agradecido!
Answer: Pode verificar em: https://www.phpliveregex.com/p/oLJ
\$\("#download-botao"\)\.attr\("href", "(.*)"\);

array(2
0   =>  $("#download-botao").attr("href", "link.com");
1   =>  link.com
)

Answer: Em vez de colocar toda a string na Regex, você pode colocar apenas a parte que interessa pegando o grupo 1, que é o que está entre o último par de aspas:
<?php
$url = '$("#download-botao").attr("href","link.com");';
preg_match('/,\s?"(.+?)"\);/', $url, $final);
echo $final[1]; // link.com
?>

Teste no IDEONE
Explicação da Regex:
,          tem uma vírgula antes
\s?        tem um espaço ou não após a vírgula e antes das aspas
"(.+?)"    qualquer coisa entre as aspas
\);        tem parênteses e um ponto e vírgula após a segunda aspas,
           onde o parênteses deve ser escapado com a barra invertida \


Como instalar as dependências de um projeto Durandal usando Mimosa?

Question: Deixa eu explicar a pergunta. Eu saberia a resposta se a pergunta fosse:
"Como instalar as dependências de um projeto Laravel usando Composer?"

No mundo do PHP, usando o Composer, a gente pode criar um projeto a partir de um esqueleto pronto, usando o comando composer create-project. No caso do framework Laravel, podemos criar um projeto com o comando:
composer create-project laravel/laravel

Da mesma forma, no mundo do front-end, usando Mimosa, a gente pode criar um projeto a partir de um esqueleto pronto, usando o comando mimosa skel:new. No caso do framework Durandal, podemos criar um projeto com o comando:
mimosa skel:new durandal

Em ambos os casos, o "esqueleto" é obtido de um repositório (no GitHub ou outro local) devidamente registrado (no Packagist ou outro local), e em seguida as dependências são automaticamente processadas e instaladas.
Mas ao copiar o projeto para outro lugar, não copiamos a parafernália toda das dependências junto (a pasta vendors ou equivalente). Copiamos apenas os arquivos do projeto. (Há um .gitignore que deixa essa parafernália fora dos commits.)
Pois bem: com o projeto copiado para outro local, no caso do Composer, o comando para torná-lo utilizável é:
composer install

Este é o comando que create-project executa automaticamente após obter o esqueleto.
A minha pergunta é: qual o comando para instalar as dependências de um projeto no caso do Mimosa? Qual é o comando que é executado automaticamente após a obtenção do esqueleto? O que eu preciso rodar na minha cópia para deixar igual ao original, após skel:new?
Comment: Utilize o `MooTools` para emitir um Mugido e atrair a `Mimosa`, espere ela chegar até você. Logo após disto, peça para que ela instale as dependências do `Durandal`.
Answer: Originalmente esta resposta foi escrita em inglês e o autor com as melhores intenções de ajudar desculpou-se por não conseguir responde-la em português.

Vi o tráfego a partir desta questão afluindo para o site do Mimosa e gostaria de tentar ajudá-lo.
mimosa skel:new apenas faz um git clone.  https://github.com/dbashford/skelmimosa/blob/master/src/command/new.coffee#L51
Se você executar mimosa skel:new durandal durandal você vai ter um projeto Durandal dentro de uma pasta durandal.
Dentro dessa pasta, para iniciar, você precisa executar npm install. Isso vai instalar todas dependências contidas no package.json.  Então, quando você executar mimosa watch ou mimosa build a primeira vez, Mimosa vai instalar qualquer módulo de Mimosa necessário.
Espero que tenha ajudado!
Comment: O próprio autor do Mimosa veio aqui responder. Que legal! (Mimosa's own author came here to answer. Cool!) :-)
Comment: First, I apologize for answering in the wrong language again, but its my only option!!!  I meant "mimosa watch" and "mimosa build".  If you do attempt to switch from grunt, I'd love to hear about any trouble you have.  I don't want to break any more language rules than I already have, so if you have specific questions you can reach me via a Mimosa GitHub issue, Twitter (@mimosajs) or the Google Group.  Thanks!!!
Comment: You said "when you run mimosa watch or mimosa watch the first time", is that really what you meant? BTW, I didn't know Mimosa, it looks like a really great tool. I'm considering switching from grunt.
Comment: Taí... o cenário é mais complexo do que no composer/PHP, pois temos o `npm` para instalar as dependências declaradas no `package.json` do esqueleto, e depois Mimosa por sua vez instala tanto as suas próprias dependências (parafernália que precisa para rodar), quanto as demais declaradas no projeto do esqueleto, seja na configuração específica `mimosa-config.coffee`, seja nas demais, como por exemplo `bower.json` (Mimosa irá executar Bower, que irá instalar tais dependências). É um "ecossistema" sofisticado!


What is the best practice for deploying Prometheus monitoring Kubernetes?

Question: There seem to be a few different ways for deploying prometheus to monitor your K8s cluster, mainly through Prometheus Operator or through creating the manifests and managing all details of the deployment yourself.
What is the preferred industry best practice when deploying Prometheus and Grafana to monitor a K8s cluster?
The use case is to monitor resource usage on a cluster level, node level, and pod level.
Answer: It depends on what all you want to deploy to monitor the cluster. If you just wantt to collect metrics and want to setup various dashboards then you don't need prometheus operator. Just deploy prometheus, Grafana, nodeexporter to collect node metrics, kube state metrics to collect cluster metrics and that is all.
But if you want to define thresholds on the metrics that you are going to collect and need to take an action when the metrics exceed the threshold limits then you are going to need kind of alerting solution for your cluster. This is where the prometheus operator fits. It bundles monitoring and alerting solution and can be plugged into your cluster on-demand with little bit of configuration
Comment: The main goal is to track metrics for resources utilization, like CPU and Memory for the cluster.
Comment: then you dont need prometheus operator. the tools that i mentioned above will do. you might also need to deploy metrics-server to review the cpu and memory at pod/namespace level


spreadsheetgear checking HPageBreaks

Question: I use spreadsheetgear.

I want to check how many HPageBreaks in my worksheet.
I want to check the row content PageBreak.

How could I do that. I have tried the following code but something went wrong
<code>SpreadsheetGear.IWorkbook wb = wbvMain.ActiveWorkbook;
IWorksheet wsPo4Printing = wb.Worksheets["Testing"];
pageCount = wsPo4Printing.HPageBreaks.Count;
</code>
The pageCount always return 0 even I have many data on this worksheet.
Thanks,
LVD
Answer: I assume you are looking for a pageCount based on natural or Automatic page breaks.  The IWorksheet.HPageBreaks/VPageBreaks collections only take into account Manual page breaks--not Automatic--and so would return 0 if no Manual page breaks were present in the worksheet.
SpreadsheetGear 2012 does not support determining where Automatic page breaks will occur.  Automatic breaks are not determined until you begin printing, then they are discarded after the print job completes, so there's really no way for SpreadsheetGear to give you this information, unfortunately.

spreadsheetgear checking HPageBreaks


How to generate new, 2048-bit Diffie-Hellman parameters with Java keytool?

Question: We are non-experts trying - unsuccessfully so far - to update our web server (JBoss-5.1.0.GA) settings to meet Diffie-Hellman standards.  After running a test on https://weakdh.org/sysadmin.html, we are told that we need to "generate new, 2048-bit Diffie-Hellman parameters".  In the past, we have generated keys with Java keytool, but we have been unable to find any information on generating a new, 2048-bit Diffie-Hellman parameter with Java keytool.  Does anyone know how to do this or could point us in the right direction?  Thank you!
Answer: You can't do that with keytool. First, keytool doesn't support DH at all. Second, keytool doesn't generate parameters by themselves for any algorithm, only a privatekey/keypair. Third, when keytool generates a keypair it also generates a self-signed cert (which sometimes is subsequently replaced by a "real" CA-issued cert) and it's impossible to generate a self-signed cert for DH because DH doesn't sign. You could write a very simple (about 10 lines) Java program to generate DH parameters. But it probably wouldn't do you any good because:
Java doesn't accept DHE parameters here anyway. JbossWS (the Jboss webserver, later Wildfly) is a fork of Tomcat, and normally uses the Java implementation of SSL/TLS, JSSE. Up through Java 7, JSSE uses its own DHE parameters which are 768-bit which is unacceptably weak. (Except for the EXPORT suites where JSSE obeys the RFC requirement for DH-512, which is totally broken, but then the EXPORT suites are by design totally broken anyway, and disabled by default in Java 7 up.) Java 8 JSSE allows you to control the size of the DHE parameters, but not the actual value.
Your (some overlapping) options are:
Use Java 8. JSSE in Java 8, but not earlier, defaults DHE to 1024 bits, which most authorities consider strong enough even though weakdh.org does not, and allows you to specify more, see https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#customizing_dh_keys and for background https://stackoverflow.com/questions/30352105/how-to-set-custom-dh-group-in-java-sslengine-to-prevent-logjam-attack . Note that if you have any Java clients before Java 8, they will fail if the server uses DHE over 1024 bits. I don't know any other clients that have this problem, but test yours before committing to this change.
Enable ECDHE. JSSE in Java 7 and later implements ECDHE, which is not subject to precomputation like DHE, (normally) using P-256, which is more than strong enough. (Although some people don't trust any of the NIST ECC curves because NIST in general is influenced by NSA, although no open source I know of has shown a problem in the ECC curves specifically.) Java 6 actually has the JSSE part for ECDHE but it is only enabled if the JVM has a crypto "provider" for ECC primitives, which Java 6 doesn't. bcprov-*-jdk15on from http://www.bouncycastle.org/ is a JCE provider for a range of Java crypto primitives including ECC, so if you add the jar to your JRE/lib/ext and add org.bouncycastle.jce.provider.BouncyCastleProvider to the list in JRE/lib/security/java.security (or do a suitable Security.add/insertProvider() somewhere early in your code) Java 6 can do ECDHE. Of course whether you should have any Java 6 still in use is a question on its own.
A few years ago, support for ECDHE in browsers and other clients was iffy, but today AFAIK all up-to-date browsers support it and prefer it to DHE -- that is, the browser hello lists the ECDHE suites before the DHE suites so that if the server implements both it should choose ECDHE. Non-browser clients maybe not; test to be certain.
Disable DHE. You can configure the list of ciphers in the Connector attribute to exclude DHE ciphers; while you're at it also exclude staticDH and staticECDH which are useless, and (single) DES and (all) "EXPORT" if present (Java 6). This means browsers and clients that don't do ECHDE will be stuck with plain-RSA and no Forward Secrecy, but at least they have "current" secrecy. I don't recall for sure, but I think 5.1 Connector config was still someplace like $server/deploy/jbossweb/server.xml .
Try native. Tomcat, which as I said JbossWS started from, has an option to implement HTTPS (SSL/TLS) using "native" aka "APR" which is actually OpenSSL inside rather than JSSE. I have had mixed success in getting this option to work on JbossWS, and don't recall about 5.1. If your JbossWS has a workable TC-native option, and if it can handle configuring DH parameters, then use openssl to generate the DH parameters and the JbossWS-native instructions to configure them.
Comment: Thank you for this great information.  The [answer](http://serverfault.com/questions/721489/how-to-make-jboss-5-1-0-ga-meet-diffie-hellman-standards) for us ultimately did not involve keytool, just changes to our server.xml file, but I am going to check this answer.
Answer: Actually you can specify custom DHE Parameters with recent Java 8 versions. That is independend of the application (as Long as it using JSSE TLS implementation).
You first need to specify the size of the DHE key to use (-Djdk.tls.ephemeralDHKeySize=1024 or -Djdk.tls.ephemeralDHKeySize=2048). On the Server this will use a pre-defined generator/prime combination for DHE. With Java 8 only 1024 or 2048 can be used, JDK 9 will support larger sizes.
If you want to provide a different combination you can specify them in jre/lib/security/Java.security with the jdk.tls.server.defaultDHEParameters security property (since 8u51). It takes a list of Parameters (one for each used keysize) and it must contain the prime and the Generator (typically 2 or 5) as hex.
If you used openssl dhparam -out dhparam2048.pem 2048 to generate a new pair you can use openssl dhparam -noout -text -check -in dhparam2048.pem to read and print that file in text mode. You will have to copy and paste the text into the Java security properties (using tr -d ':' to remove the : between the openssl hex representation)
Here is a sample (1024 bis only):
>openssl dhparam -in p -check -text -noout | tr -d ':'
PKCS#3 DH Parameters: (1024 bit)
    prime:
       00f7a63b59edcc43a43df12077f0e9
        14129c20a73cef95f919896e608ebc
        8722776c948765bbbf61542e118329
        6c6ea74ecbded3a93aff77a062aba4
        fcf04fc01030e65077f5a802605058
        65b836368dd5ea389d77691fac0f2c
        f7a161c51c8e97ddecb3cf7f872b0c
        cfaf54373d5203edcabc575e871bb1
        107ec2f30c78ebf403
    generator: 2 (0x2)
DH parameters appear to be ok.

And this results in
jdk.tls.server.defaultDHEParameters= \
    { \
        00f7a63b59edcc43a43df12077f0e9 \
        14129c20a73cef95f919896e608ebc \
        8722776c948765bbbf61542e118329 \
        6c6ea74ecbded3a93aff77a062aba4 \
        fcf04fc01030e65077f5a802605058 \
        65b836368dd5ea389d77691fac0f2c \
        f7a161c51c8e97ddecb3cf7f872b0c \
        cfaf54373d5203edcabc575e871bb1 \
        107ec2f30c78ebf403, 2 }

You should restart the Server and verify that it actually uses this prime (and not the default ones) as the process is not straight Forward, so a lot can go wrong. The Default is defined in source, for 2048 bit the prime is from TLS FFDHE draft.
For example when running openssl s_client, I can see the 1024bit prime (ffffff ffffffffffc90f...5381ffffffffffffffff) when connecting to an Java 8 JSSE Server:
>openssl s_client -msg -cipher DHE-RSA-AES128-SHA256 -connect localhost:1234
...
<<< TLS 1.2 Handshake [length 018f], ServerKeyExchange
0c 00 01 8b 00 80 ff ff ff ff ff ff ff ff c9 0f
da a2 21 68 c2 34 c4 c6 62 8b 80 dc 1c d1 29 02
4e 08 8a 67 cc 74 02 0b be a6 3b 13 9b 22 51 4a
08 79 8e 34 04 dd ef 95 19 b3 cd 3a 43 1b 30 2b
0a 6d f2 5f 14 37 4f e1 35 6d 6d 51 c2 45 e4 85
b5 76 62 5e 7e c6 f4 4c 42 e9 a6 37 ed 6b 0b ff
5c b6 f4 06 b7 ed ee 38 6b fb 5a 89 9f a5 ae 9f
24 11 7c 4b 1f e6 49 28 66 51 ec e6 53 81 ff ff
ff ff ff ff ff ff 00 01 02 ...

Instead of this, you must see your custom Parameters when installed.
The Default Parameters for Java 7 (768bit) would be "e9e642...7a3daf" wit a long generator "30470ad..529252" as defined in the ParameterCache.
Answer: I've been going through this same problem, but from Glassfish.
Firstly, I'd recommend (if you can) to put some sort of reverse proxy in front of your JBoss server as it will remove the link between the cipher/certificate security and the version of Java you are running.
To get a larger Ephemeral DH key length than 768 bits you need to be running on Java 8. 1024 is the new default, and you can go up to 2048 using the jdk.tls.ephemeralDHKeySize (details:  customising DH keys). From what I could find, there is no concept of regenerating the key parameters separately in Java.
Comment: Thanks for this suggestion of an alternative.  We may look into this in the future.
Comment: There is now, see http://serverfault.com/a/798036/4591
Comment: for glassfish/payara/payara-micro to disable the DHE ciphers add `` to the `` SSL connector


Ubuntu 18.04.5 Server DNS issue

Question: I am suddenly having a problem running updates on an Ubuntu 18.04.5 server after years of running weekly updates without any problems. It seems to be DNS related.
I am able to ping outside IP addresses but not FQDNs. I am able to connect to this machine from outside the network with SSH, so I know the connection is working.
systemd-resolve --status shows:
<code>> Global
>          DNS Servers: 188.8.131.52
>                       188.8.131.52
>                       184.108.40.206
>           DNSSEC NTA: 10.in-addr.arpa
>                       16.172.in-addr.arpa
>                       168.192.in-addr.arpa
>                       17.172.in-addr.arpa
>                       18.172.in-addr.arpa
>                       19.172.in-addr.arpa
>                       20.172.in-addr.arpa
>                       21.172.in-addr.arpa
>                       22.172.in-addr.arpa
>                       23.172.in-addr.arpa
>                       24.172.in-addr.arpa
>                       25.172.in-addr.arpa
>                       26.172.in-addr.arpa
>                       27.172.in-addr.arpa
>                       28.172.in-addr.arpa
>                       29.172.in-addr.arpa
>                       30.172.in-addr.arpa
>                       31.172.in-addr.arpa
>                       corp
>                       d.f.ip6.arpa
>                       home
>                       internal
>                       intranet
>                       lan
>                       local
>                       private
>                       test
>
> Link 2 (eth0)
>       Current Scopes: none
>        LLMNR setting: yes MulticastDNS setting: no
>       DNSSEC setting: no
>     DNSSEC supported: no
</code>
I am stumped and would appreciate any assistance.
Comment: What is the content of the `/etc/resolv.conf` file?
Comment: nameserver 188.8.131.52
nameserver 188.8.131.52
nameserver 22.214.171.124
Comment: Seems reasonable. So what happens if you try to ping a FQDN?
Comment: a good long delay of about 20 seconds and then ping: yahoo.com: Temporary failure in name resolution
Comment: Check your network connectivity and firewalls.
Comment: Network connectivity is fine as I am using SSH to connect to the server remotely. Turning off ufw does not help this issue. I am going to see if the network team made any changes on the network firewall.
Comment: Server settings ended up being fine. The network team made changes to Cisco Umbrella without informing me. Changed nameservers to the Umbrella DNS servers and it is working now.
Answer: Server settings ended up being fine. The network team made changes to Cisco Umbrella without informing me. Changed nameservers to the Umbrella DNS servers and it is working now.

Ubuntu 18.04.5 Server DNS issue


How to replace \n by space using sed command?

Question: I have  to collect a select query data to a CSV file. I want to use a sed command to replace \n from the data by a space.
I'm using this:
query | sed "s/\n/ /g" > file.csv .......

But it is not working. Only \ is getting removed, while it should also remove n  and add a space. Please suggest something.
Comment: Ah, yes, `echo my\nname\nis` on its own will already remove the backslashes because they're unquoted. Look at the output without sed.
Comment: Does your query contain literally the string `\n`? Can you show example input and the expected output? If it really is `\n`, you have to escape the backslash: `sed 's/\\n/ /g'` or (double quotes require one more level of escaping) `sed "s/\\\n/ /g"`.
Comment: If the input is ...my\nname\nis\nrohinee.....then the output comes as ....mynnamenisnrohinee....and I want output as my name is rohinee....I have tried 's/\\n/  /g' and  s/\\\n/  /g'  also...still didn't got the output as expected
Comment: Can you [edit] the question with the example input and the output you get?
Comment: Just now showed that only
Comment: You should put that into the question, with proper code formatting. It's hard to tell what's going on in comments.
Comment: I suspect you store the input in a variable and then print it without quoting, thus having the shell remove the backslashes. Please show exactly how you're sending your input to sed.
Comment: Select comments from tablename | sed 's/\n/ /g' > file.csv
Comment: Yes ...I wasn't using the quotes to input ....that was the problem .... thanks allllloottt ....your answer helped ..
Comment: So you were NOT using `Select comments from tablename | sed 's/\n/ /g' > file.csv`, but storing your input in a variable? Please update the question ([edit]) to reflect that, or the answer to your problem is something that cannot be inferred from what's in the question right now.
Comment: How would `Select comments from tablename | sed 's/\n/ /g' > file.csv` even work? Where are you issuing that command?
Comment: What sed version are you using on what OS? No modern sed would remove a backslash given `sed "s/\n/ /g"` so I'm wondering if you're using a very old one on Solaris or something.
Comment: The query I was using was....mysql -uuserid -p -hhostname dbname -e "" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > file.csv.      ........on a Linux server.... But this wasn't working to replace \n ......so  just to check another method of sed to replace \n .....I was using echo my\nname\nis | sed 's/\n/ /g' for testing purpose
Comment: @EdMorton I'm fairly sure the string containing `\n` was unescaped at some point and sed was a no-op, the backslashes removed by the shell.
Answer: You want to replace newline with space, not necessarily using sed.
Use tr:
tr '\n' ' '

Answer: \n is special to sed: it stands for the newline character. To replace a literal \n, you have to escape the backslash:
sed 's/\\n/ /g'

Notice that I've used single quotes. If you use double quotes, the backslash has a special meaning if followed by any of $, `, ", \, or newline, i.e., "\n" is still \n, but "\\n" would become \n.
Since we want sed to see \\n, we'd have to use one of these:

sed "s/\\\n/ /g" – the first \\ becomes \, and \n doesn't change, resulting in \\n
sed "s/\\\\n/ /g" – both pairs of \\ are reduced to \ and sed gets \\n as well

but single quotes are much simpler:
$ sed 's/\\n/ /g' <<< 'my\nname\nis\nrohinee'
my name is rohinee

From comments on the question, it became apparent that sed had nothing to do with removing the backslashes; the OP tried
echo my\nname\nis | sed 's/\n/ /g'

but the backslashes are removed by the shell:
$ echo my\nname\nis
mynnamenis

so even if the correct \\n were used, sed wouldn't find any matches. The correct way is
$ echo 'my\nname\nis' | sed 's/\\n/ /g'
my name is


Abnormally high standard error in binary logistic regression

Question: I did a binary logistic regression test on SPSS with a sample size of 24. The study is about the correlation of teenage pregnancy and depressive symptoms. Of the 24, 11 are pregnant teenagers. Of the 24 only 1 is positive for the presence of depressive symptoms. Both variables are recoded to nominal, so that 1 means yes and 0 means no.
What could the abnormally high standard error mean? And is there any way to solve it?
Hoping for kind responses. Thank you.
Comment: See https://stats.stackexchange.com/questions/tagged/separation?sort=votes&pageSize=50. And note that methods for 2x2 contingency tables are applicable in this case.
Comment: $n=24$ is extremely low for logistic regression.
Answer: You have almost-separation, as Scortchi notes.
Your data - 11 pregnant teenagers, none of which are depressed, and 13 non-pregnant ones, one of which is depressed - is consistent with a model that essentially says that if you are pregnant, you have a zero chance of depression, whereas if you are not pregnant, you do have a small chance. Logistic regression does not play well with chances of zero or one, and one symptom of separation is large standard errors.
And of course, it's not as if there really were a zero chance of depression during pregnancy. You will simply need to collect more data.
With a point prevalence of about 3% for MDD, 24 participants are way too few, in any case, unless you screened explicitly for depression. This should have been taken into account during sample size calculation.
Comment: Thank you so much for that response. I was actually considering that it was a matter of too little sample size. Your comment reaffirmed that. Thank you.


CSS: Set divs horizontally in 2 rows

Question: Lets say I have

1

2

3

4

5

6

7

What I want to have is to plase the .single divs in 2 rows like bricks horizontaly from left to right this simple way: 1st div will be in left top corner, 2nd will be placed below 1st, 3rd will be placed next to 1st, 4th will be placed below 3rd and so on like:
1 3 5 7 9
2 4 6 8

All the divs has the same size.
I've tried with masonry.js and its working like a charm, but its way to complex solution for so simple task (simply solution is important).
fiddle playground
Answer: There is a CSS property that does exactly that
http://tinker.io/8ff59
.cont {
    -webkit-columns: 5em;
    -moz-columns: 5em;
    columns: 5em; /* desired width of column */
}

http://caniuse.com/#feat=multicolumn
Comment: it works in IE 10.. set a width to the container div like 400 px etc.
Answer: I had the very same problem and solved using the grid.
Here's the CSS you should add to your container:
.cont {
    height: 220px;
    background: red;
    display: grid;
    grid-template-rows: repeat(2, 100px);
    gap: 10px;
    grid-auto-flow: column;
    grid-auto-columns: 100px;
}

Answer: I don't think you can do that with css with structure as you have.
This structure should help you to get your required layout:

1

2

3

4

Comment: It will propably work, but it changes structure of DOM and it may get tricky when goes about sorting etc. I was thinking about some nth css elements, but I'm not sure if its possible
Comment: do you need only two rows or more?
Comment: lets say 2, I'm not sure 100%, but we can assume that.
Answer: For the sake of argument, let's say you can't change your document structure - you need to do this through layout definitions alone.
If you know how many items you will have, the easiest way to manage this would be CSS3 columns with inline-block elements. Your .singles are the inline-blocks, and .cont uses the 'columns' property to set 5 columns each wide enough to hold your singlets, whilst using max-height to force the inline-blocks onto new columns every two items. The singlets have a min-size large enough to stop multiple inline-blocks displaying on the same line.
You can see this effect as a jsfiddle here: http://jsfiddle.net/mwjJG/25/ :
.container {
    height: 240px;

    columns: 100px 5;
    -webkit-columns: 100px 5;
    -moz-columns: 100px 5;
    }

.single {
    display: inline-block;
    height: 100px;
    width: 100px;
    }

Do be aware this won't work on IE<10 unless you can use some kind of JS-based shiv to add support for the columns property (CSS Pie may be able to do this).
Answer: I accomplished this with CSS here using this code: It's kind of hackish though.
I set three of the divs (the last three) to the class 'double'
.cont .single {
    background: blue;
    color: white;
    width: 100px;
    height: 100px;
    margin: 10px;
    float:left;
    display: inline-block;
}
.cont .double {
    background: blue;
    color: white;
    width: 100px;
    height: 100px;
    margin: 10px;
    display:inline-block;
    float:left;
}

div:nth-child(5) {
    clear:left;
}

.cont {
    height: 220px;
    background: red;
}

CSS: Set divs horizontally in 2 rows


Error in calling json data

Question: I am trying to call the data present in (data/app.json) file.
Below is component(customer.component.ts)file
import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';

@Component({
   selector: 'ylb-customer',
   templateUrl: './customer.component.html',
   styleUrls: ['./customer.component.css']
})
export class CustomerComponent  {

   spaceScreens: Array<any>;

   constructor(private http:Http){
         this.http.get('./data.json')
        .map(response => response.json().screenshots)
        .subscribe(res => this.spaceScreens = res);
      }

 }

This error I got

error TS2339: Property 'map' does not exist on type
  'Observable'.

For the error i tried this solution too
 import 'rxjs/add/operator/map'

and
import 'rxjs/Rx';

Which were marked as correct in this post(Property 'map' does not exist on type 'Observable<Response>')
Still no result.
this is (customer.component.html)file

          <mat-card class="example-card">
            <mat-card-header>

              <mat-card-title>
{{ spaceScreen.description }}
</mat-card-title>
            </mat-card-header>
          </mat-card>

This is (app.json) present in inside folder called data
     {
       "screenshots":[
         {
            "img":"assets/img/json_1.jpg",
            "description":"USA"
        },

        {
            "img":"assets/img/json_2.jpg",
            "description":"UK"
        },

        {
            "img":"assets/img/json_3.jpg",
            "description":"INDIA"
        }

    ]
  }

Now getting this error
    ERROR TypeError: Cannot read property 'description' of undefined

Answer: Starting from RxJS 5.5 you need to use pipeable operators and pass map operator into the pipe function.
Import map operator from the
import { map } from 'rxjs/operators'

and use like
this.http.get('./data.json').pipe(
        map(response => response.json().screenshots)
    ).subscribe(res => this.spaceScreens = res);

Comment: Hi @Shankarguru if this or any answer has solved your question please consider [accepting it](https://meta.stackexchange.com/q/5234/179419) by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this.
Comment: Ya i know,But i have to wait 5 min to give correct tick mark.Surely i will give after 5 min.
Comment: Maybe you have used `.description` in another place also except view?
Comment: I haven't used anywhere the image is coming ,But no the text
Answer: Property 'map' does not exist on type Observable. The problem was related to the fact that you need to add pipe around all operators.
Change this,
this.http.get('./data.json').map(data => {})

to this
this.http.get('./data.json').pipe(map(data => {}))

And
Import map like this,
import { map } from 'rxjs/operators';

It will solve your issues.
Comment: use safe navigation operator   {{ spaceScreen?.description }}
Comment: What about image,I mean this .
Comment: you have to do the same
Comment: Response {_body: "↵↵↵Cannot GET /data/app.json↵↵↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …}
Comment: you need to put the jso n in you assets folder
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/177326/discussion-between-shankar-guru-and-sajeetharan).
Comment: But text is not loading ,This tag {{ spaceScreen?.description }} and images are placing one above the other

Error in calling json data


How to interpret the regression co-efficient of a particular variable in a negative binomial regression?

Question: I have the following regression equation with a count variable as the dependent variable and diversity as the predictor.
glm.nb(numberOfJobApplicationsReceived ~ controlVar1 + FunctionalDiversityOfTheFirm)

The FunctionalDiversityOfTheFirm variable is computed as a Blau's index

The variable value ranges from 0 to 0.833. The maximum value is 0.833 as I have six different functional categories. So maximum is 1 -(6*(1/6)^2).
The regression output indicates that the FunctionalDiversityOfTheFirm variable has a significant coefficient of 3.0788 (p < .05).
Since this is a negative binomial regression, I understand that this means that for 1 unit change in the FunctionalDiversityOfTheFirm variable, the numberOfJobApplicationsReceived increases by log(3.0788). But I am not sure what one unit change in the FunctionalDiversityOfTheFirm means. How do I meaningfully translate this to draw practical conclusions about increasing diversity?
Answer: You got it backwards. The R function (from MASS) glm.nb uses a log link function as default. That means that $\DeclareMathOperator{\E}{\mathbb{E}} \E Y= e^{\beta_0 + \beta_1 x_1 + \dotsm}= e^{\beta_0} (e^{\beta_1})^{x_1} \dotsm$ so when diversity increases with 1 the expectation is multiplied with $e^{3.0788}$. But the range of diversity is less than one, so it is better to express this for some meaningful (that is, smaller) change. You are probably better off using visualization, for example try an R package like effects (on CRAN).


How to Integrate $\int (\tan x)^{1/3}\,dx$

Question: How to integrate
$$\int (\tan x)^{1/3}\,dx?$$
Is it substitution or by parts?
Comment: wolfram tells us http://www.wolframalpha.com/input/?i=integral+%28tanx%29%5E%281%2F3%29+dx
Comment: A [related problem](http://math.stackexchange.com/questions/504548/calculating-int-sqrt3-tanxdx-and-int-sqrt4-tanxdx/504556#504556).
Answer: $$\tan x=u^3\implies x=\arctan(u^3)\implies dx=\frac{3u^2du}{1+u^6}$$
$$\implies\int\sqrt[3]{\tan x}dx=3\int\frac{u^3du}{1+u^6}=\frac32\int \frac{vdv}{1+v^3}(\text{ setting } u^2=v )$$
Now using Partial Fraction Decomposition,  $$\frac{v}{1+v^3}=\frac A{1+v}+\frac {Bv+C}{1-v+v^2} $$
Multiply with $1+v^3$ and equate the constants & the coefficients of $v,v^2$
Now, $\displaystyle 1-v+v^2=\frac{4v^2-4v+4}4=\frac{(2v-1)^2+3}4$
Using Trigonometric substitution, set $2v-1=\sqrt3\tan\theta$
Comment: Nice solution lab bhattacharjee...
Comment: @juantheron, thanks for your feedback


Conditions for two eigenvectors of $AA$ to be eigenvectors of $A$

Question: Let $V$ be a $d$-dimensional real vector space with inner product $\langle\cdot{,}\cdot\rangle$, and suppose $A$ is a symmetric linear map $V\to V$. Then, by the spectral theorem, $A$ has an orthonormal basis of eigenvectors.
Clearly, if $A$ is symmetric, so is $AA$. Suppose further that the eigenvalues $\lambda_{1} \dotsc,\lambda_{d}$ of $AA$ are all distinct, so that every eigenspace is one-dimensional. In other words, $AA$ has an orthonormal basis $(e_{1},\dotsc,e_{d})$ of eigenvectors, and such basis is unique (up to permutation and reflection).
Now, since every eigenvector of $A$ is an eigenvector of $AA$, we may conclude, by the uniqueness of $(e_{1},\dotsc,e_{d})$, that $e_{i}$ is an eigenvector of $A$ for every $i \in \{1,\dotsc,n\}$.
Question: Relaxing the hypothesis that the eigenvalues of $AA$ are all distinct, and assuming only that $\lambda_{j} \neq \lambda_{k}$, can we conclude that $e_{j}$ and $e_{k}$ are eigenvectors of $A$?
Comment: Orthonormal bases for symmetric linear maps with distinct eigenvalues are unique up to permutation *and reflection*. If $e_1, e_2, \ldots, e_d$ is an orthonormal basis, then so is $\pm e_1, \pm e_2, \ldots, \pm e_d$.
Comment: Related question: https://math.stackexchange.com/questions/3357243
Comment: @TheoBendit Thanks for the comment. I've corrected it.
Answer: Suppose that $B$ is an $n\times n$ matrix with distinct eigenvalues.
If $A$ is an $n\times n$ matrix which commutes with $B$ then $A$
preserves each eigenspace of $B$, so $A$ and $B$ can be simultaneously
diagonalised. Indeed $A$ can be expressed as a polynomial in $B$, by say
Lagrange interpolation.
In this example, take $B=A^2$. Then $AB=BA$ and so each eigenvector
of $B$ is an eigenvector of $A$.
For your last question: consider
$$A=\pmatrix{0&1&0\\1&0&0\\0&0&2}.$$
Then we can take $e_1,\ldots,e_3$ to be the standard basis, but
$e_1$ is not an eigenvector of $A$.
Comment: Yes, since the eigenvectors of $B$ are eigenvectors of $A$. Think of the case where $B$ is diagonalisable.
Comment: Does the assumption that $B$ has distinct eigenvalues and commutes with a (non-necessarily symmetric) $A$ really imply that $A$ is diagonalizable?


AngularJS equivalent of .html() to replace html chars

Question: In jQuery, if you have a string with HTML in it you can process the HTML in it and replace special characters like '&' with '&'
var myString = 'Jack & Jill';
var filtered = $('
').html(myString).text();
console.log(filtered); // outputs 'Jack & Jill'

I am writing a filter which would process HTML, but I'm depending on jQuery here, is there an AngularJS way to do it?
Here is my Filter code:
myApp.filter('filterHtmlChars', function() {
    return function(html) {
        return $('
').html(html).text(); // how could I use AngularJS here?
    };
});

PS: I already know about ng-bind-html, what I'm trying to do is filter.
Comment: jqLite would do the trick if your main goal is to avoid loading jQuery: http://plnkr.co/edit/ce7g2p64JO4CahakupYt?p=preview However, I think you might be asking for a way that doesn't involve using a stand-in element altogether?
Answer: Use built-in jqLite instead:
.filter('filterHtmlChars', function(){
   return function(html) {
       var filtered = angular.element('
').html(html).text();
       return filtered;
   }
});

Then, in your view, {{ foo | filterHtmlChars}} outputs "Jack & Jill where $scope.foo = 'Jack & Jill'
Plunker Demo


Bootstrap Navbar Image size is too big

Question: I am new to bootstrap 4 and I have a question about the navbar. So I want to have my Company name and its logo next to it, but for some reason the image is way too big. What can I do to change the size of the image to fit inside of the navbar. Thank you!

         OddJob

Comment: See [here](http://www.echoecho.com/htmlimages03.htm) about sizing images in HTML and [here](https://www.reduceimages.com/) for resizing an image.
Answer: You have to define height of logo image to reduce its image size. Also need to float image to left in order to have company name next to this. Also define width of navbar-brand if necessary. You can use following css:
.navbar-brand {
  width:150px;
  font-size: 24px;
}
.navbar-brand img {
  height: 50px;
  /* put value of image height as your need */
  float: left;
  margin-right: 7px;
}

Bootstrap Navbar Image size is too big


Error: "Request aborted" axios laravel vuejs

Question: i want to add a function using laravel and vuejs and axios but it gives me error Error: "Request aborted".if I delete form validation system and checkForm function it all works well,really i don't know what error sign what,what kind of error.
fonction.blade.php

      <form @submit="checkForm">

@{{ error }}

        <input type="text" class="form-control" id="fonction" name="fonction" v-model="fonction.fonction" placeholder="fonction">

        <button class="btn btn-theme" @click="addFonction">AJOUTER FONCTION</button>
      </form>

vuejs

SalarieController.php
public function addFonction(request $request){
      $fonction = new Fonction;
      $fonction->fonction = $request->fonction;
      $fonction->save();
      Response()->json(['etat' => true]);
    }

Answer: Same question, maybe it connect with <form> tag.
I am solve for myself by replace <form> this tag with
 tag. Also I replace all submit events with click ones on button.


Stylus Lookup for hash name

Question: Is there a way to use Stylus lookup function for applying hashes inside for-in loop?
$badge-photo-S   = {
  size: 36px
  font-size: 16px
}
$badge-photo-XS  = {
  size: 32px
  font-size: 13px
}
.s-badge
  &-photo
    for each in S XS
      &--{each}
        {lookup('$badge-photo-'+each)}

It should yields to:
.s-badge-photo--S {
  width: 36px
  height: 36px;
  font-size: 16px;
}

.s-badge-photo--XS {
  width: 32px
  height: 32px;
  font-size: 13px;
}

But it provides an empty output.
Answer: You need to save the result of lookup to a variable and then use it inside {}:
$badge-photo-S   = {
  size: 36px
  font-size: 16px
}
$badge-photo-XS  = {
  size: 32px
  font-size: 13px
}
.s-badge
  &-photo
    for each in S XS
      &--{each}
        hash = lookup('$badge-photo-'+each)
        {hash}

Stylus Lookup for hash name


PHP stripslashes problem

Question: I have a development machine that is local and a server out on the net. Weird thing is that when I use stripslashes on my development machine, all slashes are removed and when I upload the same code to the net server, I see the escape character even though I am using stripslashes. Anyone have any ideas?
Answer: This could be Magic Quotes. Try to disable them or remove them before processing the data.
Comment: I just checked the ini file on the server and magic_quotes is set to ON. Shouldn't this be disabled for security reasons? What is the norm?
Comment: @Jim: They should be disabled if possible. But applications need to be aware that they might be enabled/disabled and should be able to remove them.  Or at least they shouldn't rely on that they are always enabled/disabled.
Answer: Perhaps what the note says on the manual page might be the problem.

PHP stripslashes problem


"Last Out" Raffle Probabilities/Stats

Question: I'm part of an online community that raffles away prizes, typically with 30 or 40 spots in a raffle. The numbered chips/balls are placed into some type of hopper, and pulled out one at a time (random/controlled/etc). The rules are pretty simple: you can buy as many spots as you'd like, and the last out wins the prize (so numbers are drawn until there is one chip/ball remaining, and that is the winning spot). Not a math or stats guy, so looking for some help as it's caused some debate...
Let's say it's a 10 spot raffle, and I buy one single spot.
Do I have a 1 in 10 shot of winning? Or do I have a 1 in 10 chance of losing (since you actually want to avoid having your number drawn until the end)? Do my odds reset with every number drawn, or do they carry through the entire raffle?
Do you get where I am going with this?
Thanks for any help/insight!
Answer: If you have M chips out of N chips in total, you have a M/N chance of winning. It doesn't matter if the last chip drawn wins, or the first one, or N/2th one - there is exactly one chip that will win, and each of the N chips is equally likely to be it. Every chip has a 1/N chance of being the winning chip, so M chips have an M/N chance of winning overall.
Having the last number drawn be the winner is absolutely no different from having the first number drawn be the winner, it just takes longer.
You odds do "reset" after each number drawn to reflect the remaining N. If there are only two chips left and you hold one of them, your chance of winning at that point is 1/2. But your overall chance of winning at the start before any numbers are drawn is still 1/N (or M/N if you have multiple chips).

"Last Out" Raffle Probabilities/Stats


If $\{F_n\}$ is a decreasing sequence of compact subsets of $X$ Hausdorff and $f$ is continuous, then $f(\cap F_n) = \cap f(F_n)$

Question: I have to prove the following statement:

Let $X$ and $Y$ be Hausdorff Spaces and $f:X\to Y$ a continuous function. If $\{F_n\}$ is a decreasing sequence of compact subsets of $X$, then $f(\cap F_n) = \cap f(F_n)$.

I already proved it, however, my proof doesn't use the hypothesis that $Y$ is Hausdorff, and that makes me think it might be wrong, but I don't find any mistakes. I would be really thankful if someone could verify it.
Proof. First we see that $f(\cap F_n) \subseteq \cap f(F_n)$. If $x\in f(\cap F_n)$, there must exists $a\in \cap F_n$ such that $f(a)=x$. It is clear that $a\in F_n$, for all $n\in\mathbb{N}$ and in consequence $x\in f(F_n)$, for all $n\in\mathbb{N}$, which implies $x\in\cap f(F_n)$.
Now we are going to prove that $\cap f( F_n) \subseteq f(\cap F_n)$. Let $x\in\cap f( F_n)$, this implies that $x\in f( F_n)$ for all $n\in\mathbb{N}$. From here we get for each $n\in\mathbb{N}$ there exists $y_n\in F_n$ such that $f(y_n)=x$. Since $\{F_n\}$ is a decreasing sequence, we have that $F_n \subseteq F_1$ for all $n\in\mathbb{N}$ and this implies that $y_n\in F_1$ for all $n\in\mathbb{N}$. This way, $\{y_n\}$ is a sequence in $F_1$. Because $F_1$ is compact, $\{y_n\}$ must have a convergent subsequence. Lets say this subsequence is $\{y_{n_k}\}$, and that it converges to $y$. Futhermore, since $X$ is Hausdorff, this limit is unique.
We see that $y\in\cap F_n$. Let $i\in\mathbb{N}$. There exists a $j\in\mathbb{N}$ such that $i<n_j$. Now lets consider the sequence $\{a_k^j\}$ given by $a_k^j=y_{n_{k+j}}$. It is clear that $a_k^j=y_{n_{k+j}}\in F_{n_{k+j}}\subseteq F_{n_{j}}\subseteq F_i$, which implies that the sequence $\{a_k^j\}$ is a sequence in $F_i$. Also, this sequence is just a shift of $\{y_{n_{k}}\}$, and because of this it must also converge to $y$. Because $F_i$ is compact, and $X$ is Hausdorff, $F_i$ is closed, and since $\{a_k^j\}$ is in $F_i$, we have that $y\in F_i$. As $i\in\mathbb{N}$ is arbitrary, we get that $y\in\cap F_n$.
Finally, using the continuity of $f$ and the uniqueness of the limit of $\{y_{n_k}\}$ we get that $f(y)=f(\text{lim}_{k\to\infty}y_{n_k})=\text{lim}_{k\to\infty}f(y_{n_k})=\text{lim}_{k\to\infty}x=x$, from where we get that $x=f(y)\in f(\cap F_n)$.
In conclusion, $f(\cap F_n) = \cap f(F_n)$
Answer: For the non-trivial backward direction I'd do a sequence-free proof because not all compact Hausdorff spaces are sequentially compact.
So let $y \in \bigcap_n f[F_n]$. And define $C_n = f^{-1}[\{y\}] \cap F_n$ which is a non-empty closed subset of $X$ (for every $n$, some $x \in F_n$ maps onto $y$ as $y \in f[F_n]$, closed as singletons are closed in $Y$ and $f$ is continuous.)
As the $F_n$ are decreasing so are the $C_n$ ($x \in C_{n+1}$ then $f(x)=y$ and $x \in F_{n+1}$, so $x \in F_n$ and still $f(x)=y$ so $x \in C_n$).
So the $C_n$ form a family of closed subsets with the FIP inside the compact set $F_1$, so there is a point $x \in \bigcap_n C_n$.
Clearly $x \in \bigcap_n F_n$ too and for any $n$, $x \in C_n$ so that $f(x)=y$ and so $x$ witnesses that $y \in f[\bigcap_n F_n]$ as required.
So it seems we can get ayway with $Y$ being merely $T_1$ instead of Hausdorff.
Comment: Very interesting proof. Seems more elegant than mine. I really like this argument around the FIP. Thanks!
Comment: @Kerd You're welcome!
Answer: It is wrong to say $$f(\lim_{k\to\infty}y_{n_k})=\lim_{k\to\infty}f(y_{n_k})$$ if $Y$ is not Hausdorff.  Indeed, it is not even meaningful to write $\lim_{k\to\infty}f(y_{n_k})$, since the limit may not be unique.  All you can say is that $f(\lim_{k\to\infty}y_{n_k})$ is equal to some limit of the sequence $f(y_{n_k})$, but it might be a different limit from $x$.
(Separately, it is wrong to say that $(y_n)$ has a convergent subsequence.  It is not true in a compact space that a sequence always has a convergent subsequence.  This error is easily corrected by taking a convergent subnet instead, though.)
Comment: @Kerd As a more general critique: it's **not** true that a sequence in a compact Hausdorff space has a convergent subsequence, this uses sequential compactness and not all compact Hausdorff spaces are sequentially compact! e.g $\beta \Bbb N$ and $[0,1]^I$ for large $I$ are counterexamples. So the proof fails on that. You'd have to use an $\omega$-accumulation point or convergent subnet instead.
Comment: That's correct.
Comment: Oh I see now why $Y$ being Hausdorff is necessary. Thanks a lot! So the argument would be like: $f(y)$ and $x$ are both limits of $f(y_{n_k})$, but since $Y$ is Hausdorff, the limit is unique, which implies $f(y)=x$, right? About the subsequence stuff, I thought the subnets of a sequence were subsequences, but I guess I was wrong.
Answer: Here is a concrete example showing how the result can fail when $Y$ is not $T_1$; I think that it's probably about as simple as you can get.
Let $X=\{p\}\cup\Bbb N$, where $p$ is some point not in $\Bbb N$; the topology on $X$ is
$$\wp(\Bbb N)\cup\{X\setminus F:F\subseteq\Bbb N\text{ is finite}\}\,.$$
In other words, points of $\Bbb N$ are isolated, and open nbhds of $p$ contain all but finitely many points of $\Bbb N$; clearly $X$ is a compact Hausdorff space. For $n\in\Bbb N$ let
$$F_n=X\setminus\{k\in\Bbb N:k<n\}\,;$$
then
$$X=F_0\supsetneqq F_1\supsetneqq F_2\supsetneqq\ldots\,,$$
each $F_n$ is compact, and $\bigcap\limits_{n\in\Bbb N}F_n=\{p\}$.
Let $Y=\Bbb N$. For each $n\in\Bbb N$ let $U_n=\{k\in\Bbb N:k\ge n\}$; the topology on $Y$ is $\{\varnothing\}\cup\{U_n:n\in\Bbb N\}$, so $Y$ is $T_0$ but not $T_1$.
Let
$$f:X\to Y:x\mapsto\begin{cases}
0,&\text{if }x=p\\
1,&\text{if }x=n\text{ and }n\text{ is odd}\\
\frac{n+4}2,&\text{if }x=n\text{ and }n\text{ is even;}
\end{cases}$$
$f^{-1}[U_0]=f^{-1}[Y]=X$, and $f^{-1}[U_n]\subseteq\Bbb N$ if $n\ge 1$, so $f$ is continuous, and it's not hard to verify that
$$f[F_n]=\{0,1\}\cup U_{\left\lceil\frac{n+4}2\right\rceil}$$
for each $n\in\Bbb N$. Thus,
$$f\left[\bigcap_{n\in\Bbb N}F_n\right]=f[\{p\}]=\{0\}\,,$$
but
$$\bigcap_{n\in\Bbb N}f[F_n]=\bigcap_{n\in\Bbb N}\left(\{0,1\}\cup U_{\left\lceil\frac{n+4}2\right\rceil}\right)=\{0,1\}\,.$$


como carregar um select com dados vindos de uma API com AngularJS

Question: Boa noite, não estou conseguindo carregar um select no angularJS! Ele nao carrega, fica em branco. Vou postar o codigo, se alguem puder me ajudar agradeço!!
Controller:

index.html:
 <select class="form-control" ng-model="paciente.pacienteEspe" ng-options="pacienteEsp.Procedimento_tuss for pacienteEsp in pacienteEspe">
             <option value="">Selecione uma opcão</option>
           </select>

ele nao carrega, ele fica como se os dados estivessem lá, porem nao tem nada! ja tentei de tudo.. Se alguem puder ajudar..
Valeu!

Retorno no console:
Comment: Poderia mostrar um exemplo de JSON retornado pela API?
Comment: [
  {
    "Id_amb92": 79,
    "Cod_amb92": "19010117",
    "Procedimento_amb92": "TESTES CUTANEOS DE LEITURA IMEDIATA",
    "Cod_tuss": "41401425",
    "Procedimento_tuss": "TESTES DE CONTATO - ATÉ 30 SUBSTÂNCIAS",
    "Ch": "60"
  }
]

Obs: quando exibo somete o array {{pacienteEspe }} ele me exibe exatamente isso! E algumas informações como resposta da API, no caso 200.
Comment: @leonardobarussi Tem como postar na sua pergunta como está o JSON recebido do server-side? Digo, ele sendo mostrado no console na aba network do navegador, ou até mesmo diretamente no navegador, chamando a URL.
Comment: `$scope.pacienteEspe = data.data;`
Comment: @jbueno deu certo! rapaaaaaaaaaz, foi quase 2 dias batendo cabeça com esse problema! Muito obrigado velho!
Comment: Beleza!! @jbueno voce poderia me explicar porque eu tive que repetir o data?
Comment: Sim, veja o `console.log`. Aquele é o retorno da função `get`, os dados retornados do server-side ficam na propriedade `data` deste retorno. Seria melhor você dar um nome mais descritivo, como `response` ou qqr outro equivalente. Entende? Este objeto representa a resposta inteira e não apenas os dados, os dados são parte da resposta.
Answer: Em uma análise inicial me parece que seu código não possui nenhum problema. O que pode estar acontecendo é que sua aplicação não está sendo inicializada corretamente.
Segue abaixo o seu código em estado funcional, com dados pré-carregados e uma view para iteração com o controller:

angular.module("cadastroMedico", [])
    .controller("cadastroMedicoController", function($scope) {
        $scope.app = "Cadastro de pacientes";
        $scope.pacienteEspe = [
            {
                "Id_amb92": 79,
                "Cod_amb92": "19010117",
                "Procedimento_amb92": "TESTES CUTANEOS DE LEITURA IMEDIATA",
                "Cod_tuss": "41401425",
                "Procedimento_tuss": "TESTES DE CONTATO - ATÉ 30 SUBSTÂNCIAS",
                "Ch": "60"
            }
        ];
    });

    <select class="form-control" ng-model="paciente.pacienteEspe" ng-options="pacienteEsp.Procedimento_tuss for pacienteEsp in pacienteEspe">
     <option value="">Selecione uma opcão</option>
    </select>

{{paciente | json}}

Comment: então, ai é que está. Quando eu carrego o array manualmente como voce fez, sem a API jogando o JSON nela, o select carrega normalmente. O problema é quando eu carrego o select com os JSONS da API. Ele está me trazendo o valor corretamente, tanto que se eu exibir o que tem dentro do array quando carrego ele com a API {{ pacienteEspe }} ele me exibe exatamente o JSON que eu preciso, mas na hora de carregar no select ele me mostra a imagem que eu apresentei acima =/
Comment: Cara, com esse codigo que voce mandou formatado, aconteceu algumas mudanças. {{paciente | json}} com esse codigo, ele mostra quando eu clico, o JSON inteiro da API. Porem ainda não exibe no SELECT. Ele aparece em branco!
Comment: @leonardobarussi então seu select está provavelmente lendo do escopo errado. Para fins de teste, mude seu ng-options para "`pacienteEsp.Procedimento_tuss for pacienteEsp in $parent.pacienteEspe`". Isso pode acontecer se o conteúdo estiver dentro de um `ng-if`.
Comment: "pacienteEsp.Id_amb92 for pacienteEsp in $parent.pacienteEspe" com esse codigo ele nao funcionou. Agora ele nao exibe nada! Vou criar um novo projeto, colocar apenas um select e tentar. Dou noticias aqui caso de certo! Só um momento
Comment: Com esse ultimo codigo que voce informou ele nao pegou. Porem agora o SELECT aparece "undefined", seria alguma coisa que eu nao devini?
Comment: @leonardobarussi Ainda me parece uma questão de escopo. Você poderia postar mais do seu código aqui?
Comment: claro! fiz inline para testar. Vou postar aqui e voce da uma olhada!!
Comment: `
Comment: `

Selecione uma opcão

{{paciente | json}}
`
Comment: Não sei velho, o array está identico ao json vindo da API. E não funciona, não mudo NADA no select! Com o array ele me exibe, com a API não. Mostra um valor undefined!
Comment: Valeu a força!! Deu certo.
Comment: @leonardobarussi Fico feliz que tenha funcionado! Foi realmente um problema de escopo?