text:
Q: Can I override links in /usr/bin/ by .zshrc? I have /usr/bin/python mapped to /usr/bin/python3.7, but I prefer to use python3.6 instead. So I recreated links manually, but each time I update my system with pacman -Syu I have them overwritten by system defaults again.
What is the best practice to handle this? Should I add alias python=/usr/bin/python3.6 (which makes non-cli apps use wrong python anyway) or some other option to make my system run python3.6 by default when I run python from anywhere?

A: If programs only require python and do not specify its full path, you can create another directory with the correct symlink and put it in the front of your $PATH.
For example:
$ mkdir ~/bin
$ ln -s /usr/bin/python3.6 ~/bin/python
$ export PATH="$HOME/bin:$PATH"
$ type python
python is /home/xxx/bin/python
$ python --version
Python 3.6.x

If programs specifically require /usr/bin/python, there's nothing you can do about it without root privileges. (And you shouldn't, as programs distributed with Arch often expect the same Python that is distributed with Arch – it's only safe to use an older version with your own programs.)
However, root can change this either temporarily using mount namespaces, or permanently by just moving the file away. To change it permanently (and risk breaking official packages):

*

*In the general [options] section of /etc/pacman.conf, add NoUpgrade = usr/bin/python.

*Use ln -s to change the actual /usr/bin/python symlink in whatever way you want. After a Python upgrade, the new link will be extracted to /usr/bin/python.pacnew and won't reset your changes.


text:
Q: SQL Server: Transaction log still very large after log backup I have a database that is on Full recovery mode.
I previously made a full backup, and then on a daily basis add differential backups.
Now I have backed up the transaction log for the first time, which reflected in the greatly increased file size of the .bak file. However the log file in the \DATA directory is still the same size.
I was under the impression that the transaction log file would automatically be truncated on a log backup, as mentioned here and elsewhere.
Previously I asked a question on Stack Overflow (here) where the answer indicated that the log file info was not up-to-date with the actual log on disk. Is that the case with this observation?
If so, how can I get the Windows file to refresh to display up-to-date data?

A: The transaction log does not automatically shrink because you did a backup.  This is actually a good thing because processes actually stop when the log grows.  Your log has grown to the current size because you had processes that required the log to grow to that size.  These could have been long running units of work that generated a lot of log records (like index maintenance).  The log 'truncation' you're referring to means that, after a log backup, log space is available for 'reuse'.  Again, this process does not automatically reduce the size of the log.  To reduce the log size,, you'd need to 'shrink' the log file.  Repeated shrinking of the log is discouraged because it typically just re-grows, which affects performance.  If you do 'shrink' the log, you should monitor the growth rate.  Here is a helpful article.  I also found this article that provides additional information.

redpajama_set_name: RedPajamaStackExchange


text:
Q: R package devlopment: how to use a variable to save some state? Minimal scenario
Suppose a package which needs to monitor its own usage. For example, the number of times a specific function of the package has been called since the package was loaded.
What is the best way to achieve this?

First idea
I have tried to create a variable inside the .onLoad() function:
## R/zzz.R

.onLoad <- function(libname, pkgname) {
  how_many_times <- 0
}

But this variable is not accessible after the package loading...

Second idea
A variable inside some of the .R file. And the use of the scoping assignement operator <<-:
## R/somefile.R

#' @exports
how_many_times <- 0

#' @exports
count_me <- function() {
  how_many_times <<- how_many_times + 1
  how_many_times
}

But it does not work either! The first defined global how_many_times is not changed when I call the function count_me but it is another variable as a closure inside the function which is modified.


text:
Q: search for element within an array My data[l][m] contains 1,2,3,4,5
I'm trying to search for a particular number, say '2' in it. Is there a better way to do this?
for (var n = 0; n < data[l][m].length; n++) {
    if(data[l][m][n] == num){ // num is equal to '2'
        number = data[l][0];
        document.form.options[l-1] = new Option(number,number,true,true);
    }
}

And how about in: ['id1',['a',[1,2,3,4,5]],['b',[3,4,5,6,7]]]
Many thanks in advance.

A: If you're already including jQuery, use $.inArray(), like this:
if($.inArray(num, data[l][m]) > -1) {
  number = data[l][0];
  document.form.options[l-1] = new Option(number,number,true,true);
}

The shorter vanilla JS version is a direct .indexOf() on the Array, but IE doesn't have this by default.

A: You could use indexOf, although it still has the same O(n) complexity as your for loop:
var pos = data[l][m].indexOf(num);
if (pos !== -1)
{
  // element was found
  number = data[l][0];
  document.form.options[l-1] = new Option(number,number,true,true);
}

Note, however, that older versions of IE do not have the indexOf method for Arrays.

A: I have no major changes to recommend, but do have a couple tweaks to suggest. The first is to create a temporary reference to data[l] to reduce reading complexity by 1 level. This is a cosmetic change for the benefit of the coder. The other is cache the length of the array you are searching, which helps with performance. If you replace your for loop with the while loop as follows, you can also remove the comparison operations.
var layer1 = data[l];
var n = layer1[m].length;
while (n--) {
    if (layer1[m][n] == num) { // num is equal to '2'
        number = layer1[0];
        document.form.options[l - 1] = new Option(number, number, true, true);
    }
}


text:
Q: Does $x_n$ converge, given $\lim(3x_{n+1} - x_{n})=1 $ I want to prove that $x_n$ converges, given that $\lim (3x_{n+1} - x_n ) = 1$
Attempt: Since $\lim (3x_{n+1} - x_n ) = 1$, set $\epsilon > 0, $ such that $\forall n > N, |3x_{n+1} - x_n -1 | < \epsilon. $ Then,
$$|x_{n+1} - x_n|< \min(\frac{\epsilon + 1 - 2x_N}{3},\frac{1 -\epsilon - 2x_N}{3},1)\ .$$
So
$$|x_{n+k} - x_n| \leq |x_{n+k} - x_{n+k-1}| + |x_{n+k-1} - x_{n+k-2}| + ... + |x_{n+1}-x_n|< $$
$$< k \times \min(\frac{\epsilon + 1 - 2x_N}{3},\frac{1 -\epsilon - 2x_N}{3},1)$$
I tried showing that $x_n$ is Cauchy but there seems to be some problems, any advice?

A: The limit, if it exists, is $\frac{1}{2}$, so I think it is easier to work with $u_n:=x_n-\frac{1}{2}$. The hypothesis then is $3 u_{n+1} - u_n \to 0$. We want to prove that $u_n\to 0$.
Let $\epsilon>0$. For big enough $n$ we can get $3 |u_{n+1}|\leqslant |u_n| +\epsilon$, and then
$$
|u_{n+k}|\leqslant \frac{1}{3^k}|u_n| + \frac{\epsilon}{3}.\frac{1}{1-\frac{1}{3}}$$
which will  give the result.

A: Let's prove first that $(x_n)$ must be bounded. Indeed, there is some $N\in \mathbb N$ such that $$n\geq N\implies |3x_{n+1}-x_n-1|\leq 1$$
Since $3|x_{n+1}|-|x_n+1|\leq |3x_{n+1}-x_n-1|$, we get $|x_{n+1}|\leq \frac{2+|x_n|}3$.
Let $M=\max(1,|x_N|)$.
Note that $|x_N|\leq M$ and if $|x_n|\leq M$ then $|x_{n+1}|\leq \frac{2+M}3\leq M$ (the last inequaliy holds since $M\geq 1$). Hence $\forall n\geq N, |x_n|\leq M$ and $(x_n)$ is bounded by $\max(|x_0|,\ldots,|x_{N-1}|,M)$.
Since $(x_n)$ is bounded, it has a convergent subsequence $x_{n_k}\to x$.
But since $3x_n - x_{n-1} \to 1$, we have $3x_{n_k}-x_{n_k-1} \to x$ hence $x_{n_k-1}\to 3x-1$.
Iterating this, $x_n$ has subsequences with arbitrarily large limits, hence $x_n$ is unbounded, a contradiction.
Thus, $x_n$ is bounded and has a unique accumulation point. A classic lemma yields convergence of $x_n$ to this accumulation point.


text:
Q: Memory heavy oval gradient As you may know it is not possible to draw an oval radial gradient using regular Android API.
This is what I want to achieve:

So I implemented this solution: draw a regular radial gradient on a square bitmap and then this bitmap will get stretched by the view itself (idea found here: https://stackoverflow.com/a/3543899/649910)
This works great however this solution takes a lot of memory, because of BitmapDrawable usage (see implementation details below).
Any ideas on how to avoid usage of such a big bitmap are welcome!
This my code:
public class OvalGradientView extends ImageView {

    private Drawable defaultBackgroundDrawable;

    public OvalGradientView(Context context) {
        super(context);
        init();
    }

    public OvalGradientView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public OvalGradientView(Context context, AttributeSet attrs, int defStyleAttr, Paint paint) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setScaleType(ScaleType.FIT_XY);
        defaultBackgroundDrawable = getResources().getDrawable(R.drawable.default_background);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        int width = getWidth();
        int height = getHeight();
        Rect currentBounds = defaultBackgroundDrawable.getBounds();
        // check if we already have bitmap for these bounds
        if (currentBounds.right == width && currentBounds.bottom == height) {
            return;
        }
        // draw the drawable on square bitmap, it will be then stretched if needed to rectangular shape
        // as the view gets more rectangular
        defaultBackgroundDrawable.setBounds(0, 0, width, width);
        Bitmap defaultBackgroundBitmap = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(defaultBackgroundBitmap);
        defaultBackgroundDrawable.draw(canvas);
        setImageBitmap(defaultBackgroundBitmap);
    }
}

And this is the drawable XML - default_background
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#ffffff"
        android:endColor="#ff6600"
        android:gradientRadius="50%p"
        android:type="radial" />
</shape

A: I wouldn't trust my own ability to create bitmaps like that, especially if they are full screen. Why not apply the xml shape as a background to the container view in xml as well? It will stretch to the proportions of the view if the width and height are match_parent
public class OvalGradientView extends ImageView {
    public OvalGradientView(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.my_sexy_gradient, this, true);
    }
}

my_sexy_gradient.xml
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@drawable/default_background"/>

A: I ended up with this implementation:
public class MyBackgroundView extends ImageView {

    public MyBackgroundView(Context context) {
        super(context);
    }

    public MyBackgroundView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyBackgroundView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        setBackgroundResource(R.drawable.my_background);
        setScaleType(ScaleType.FIT_XY);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        if (!changed) {
            return;
        }

        int width = right - left;
        int height = bottom - top;
        float aspectRatio = (float) width / height;
        if (aspectRatio > 1f) {
            setScaleX(aspectRatio);
        } else {
            setScaleY(1 / aspectRatio);
        }
    }
}

where my_background is:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="@color/my_background_start_color"
        android:endColor="@color/my_background_end_color"
        android:gradientRadius="@fraction/my_background_gradient_radius_percent"
        android:type="radial" />
</shape>

Width and height of this view are both match_parent.


text:
Q: How to create AngularJS app with all views defined in one file? I want to create an app using AngularJS that is contained in one file. Something similar to jQuery Mobile's multi-page template. It would be nice to define several divs with ng-controller, each of which would represent a controller with a template. Instead, angular-ui-router seems to require a templateUrl or a template string. Is there an elegant way to do that?

A: Sure , you can put your templates into script tag directives like this:

And then customize the routeProvider in this way:
$routeProvider.when('/page1', {

  templateUrl : "page1.html"

}).when('/page2', {

  templateUrl : "page2.html"

}).otherwise({

  redirectTo: 'page1'

});

Example: http://plnkr.co/edit/akd7gX?p=preview


text: Q: Which is the best way to use OKTA SSO, for my asp.net MVC web application(C#) Which is the best way to use OKTA SSO, for my asp.net MVC web application(C#) and I need to integrate outlook to my web application where I need to access user address book(Outlook).


text:
Q: MongoDB: Update field number with inverse value? My sitiuation is: I have a document in collection Users, example:
Users : {
  _id : "id_str",
  active : 1
}

I want to update active status of this user with only one query, like:
Users.update({
    _id : "id_str"
}, {
   $set : {
      active : 0 if active now is 1, 1 if active now is 0
   }
})

I'm not looking for any solution that find user document to get active status and then update it. I only want to use 1 query for resolve this problem
In the MySQL, I often resolve this problem within only one SQL:
UPDATE users SET active = ABS(active - 1) WHERE...
But I dont know how do it in MongoDB. Please help me.
Thanks in advance

A: You can do this with $bit and the xor operator, but you need to ensure that your values are integers and not doubles as they default to in the shell.
So if you create your docs as:
db.users.insert([{
  _id : "id_str1",
  active : NumberInt(0)
},{
  _id : "id_str2",
  active : NumberInt(1)
}])

You can toggle their active values using:
db.users.update({}, {$bit: {active: {xor: NumberInt(1)}}}, {multi: true})


text:
Q: Subprocess Python Error when I run this subprocess command from python, it seems like python stalls and never outputs anything :
msg = subprocess.call(['/Users/admirmonteiro/bin/Praat', '/Users/admirmonteiro/tmp/tmp.praat'])

but when I run the command itself from the terminal, it runs and closes as it should :
Praat /tmp/tmp.praat

Is anyone able to tell me why python is not finishing up the code and is stalling and not outputting anything?
thanks !

A: You could try making sure the stdin and stdout (or other file descriptors) are not causing the problem:
p = subprocess.POpen(
    ['/Users/admirmonteiro/bin/Praat', '/Users/admirmonteiro/tmp/tmp.praat'],
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    close_fds=True,
)
print p.communicate()
print p.wait()

A: it seems you have exchanged the arguments.
msg = subprocess.call(['/Users/admirmonteiro/bin/Praat', '/Users/admirmonteiro/tmp/tmp.praat'])

should be
msg = subprocess.call([ '/Users/admirmonteiro/tmp/tmp.praat','/Users/admirmonteiro/bin/Praat'])


text:
Q: Why is Mathematica giving this answer for the derivative of 2^x? I'm trying to use Mathematica to take the derivative of 2^x with respect to x. It's giving me the attached answer, which is not correct. Am I doing something wrong? Why is it giving this answer?

Edit: The answer I'd expect it to give is ln(2) 2^x, as indicated by this explanation, which makes sense to me. Is the explanation incorrect?

A: Because
 Exp[x Log[2]] == 2^x

True


text:
Q: Laplace distribution and, generally, interpreting an undefined moment I'm studying the distributional properties of a laplace distribution, and I'm trying to get some intuition beyond plotting the distribution of what it means to have an undefined moment.
In wikipedia you can see that the mgf is only defined for $|t| < 1/b$ so as the variance of the laplace distribution increases to 1, you lose all moments including the mean. Does this matter? What is the intuition? For example the fourth moment can blow up, but the distribution will still look generally okay. What is the benefit of having a defined moment if you have the distribution?
If I have some data that fits the laplace distribution fits well with a very high b, should I be concerned? If for two data sets where b is close to 1 in one data set, but smaller in another, am I more confident in the fit to the data set with a b that generates more moments?
Any thoughts would be greatly appreciated. And if I'm thinking about this the wrong way let me know.

A: I was incorrectly using the moment generating function which led to my misunderstanding of the Laplace distribution.
The moment generating function is  $M_X(\theta) = \text{E}(e^{\theta X})$.
When you use that to find the $n^{\text{th}}$ moment, you take the $n^{\text{th}}$ derivative at $\theta=0$:
$$\frac{d^{n}(M_X(\theta))}{d(\theta)^{n}} |_{\theta=0}\quad\text{.}$$
If you see my note above there is a proof using Taylor series expansion of $E(e^{\theta X})$. When you take the n-th derivative the leading term will not have a $\theta$ in it, but higher order terms will have $\theta$. This allows you to set $\theta=0$ and use the moment generating function to produce moments.
So for the Laplace we have  $E(e^{\theta X}) = e^{\mu\theta}/(1-b^{2}\theta^{2})$ (from Wikipedia)
$E(X) = d^{1}(M_X(\theta))/d(\theta)^{1} = (e^{\theta\mu} (\mu + b^2 \theta (2 - \theta \mu)))/(-1 + b^2 \theta^2)^2$
if you evaluate this for $\theta=0$, then you get $E(X) = \mu$ as expected.
Now the second part of my question is trying to understand undefined moments. The implication of an undefined moment means that trying to estimate the parameters of the distribution by matching moments will generally require more advanced techniques (such as maximizing log-likelihood).
There is a good discussion about this for the Cauchy distribution which does not have defined moments see http://en.wikipedia.org/wiki/Cauchy_distribution
As an added thought, in Python there is a symbolic algebra package called sympy that makes evaluating moments very simple using symbolic algebra. There are simple formulas to convert non-central moments to central moments, allowing you to calculate skewness and kurtosis fairly easily for many distributions.


text: Q: Application function call tracing I have compiled the source code of a project. I have all the pdb files needed for debugging. Now a profiler will tell me the percentage of time an application spends in some function. Is there some utility tool which can track all the application calls that an application makes during its execution. I want an output like strace but for application functions. Something like function A was called at time T with return value x...


text:
Q: Misma font-family en toda la página Tengo definido entre otras propiedades
body {
  font-family: "Open Sans", Helvetica, sans-serif;
}

No hay ninguna referencia más en toda la página a cambios de fuente ni nada similar, y aparentemente se establece bien la propiedad para toda la página, pero en los input y en los botones cambia la fuente automáticamente y pone la Arial, tachando la que yo le "impongo" desde el body

Forzando cada elemento lo podría conseguir, pero la pregunta es, ¿por qué no hereda correctamente?

A: El problema está en que los elementos tipo input tienen su propia especificación de fuente de acuerdo a la hoja de estilos global que aplica el navegador.
Por lo tanto si deseas que tus elementos tipo input tengan la misma familia de fuente que el elemento body, podrias hacerlo de la siguiente manera:
styles.css
body, input {
    font-family: "Open Sans", Helvetica, sans-serif;
}

Así, todos los elementos tipo input de tu documento usarán la familia de fuentes establecida en tu hoja de estilos.
También podrías usar algo como:
body {
    font-family: "Open Sans", Helvetica, sans-serif;
}
input {
    font-family: inherit;
}

Así podrías entonces aplicar diferentes fuentes envolviendo tu elemento input en algún contenedor que tenga una fuente diferente a la establecida para body.
Espero que sea la respuesta que buscabas.


text:
Q: Is there a Python function to remove characters in text? I have a text that there is an open and close parenthesis and in this text there is a parenthesis that is open and not close and open but not close so I need to remove that is open and not close and open but not close and replace it with "!error". How can I do ???
Text_To_Correct = """Lorem ipsum dolor sit amet, (consectetur) adipiscing elit. Nunc) fringilla metus eget) elit tristique (dignissim.
                     Mauris id nisi (et tortor fringilla tincidunt) sed sit amet elit. Aliquam feugiat velit sollicitudin, tempor velit et,
                     maximus sem. Etiam (varius tincidunt est. Proin (mattis convallis) tincidunt phasellus euismod tortor eget
                     vestibulum sollicitudin, mi lorem eleifend libero, non consequat sem velit in elit. Ut nisi felis, lacinia nec elit
                     non, lacinia rutrum urna. Quisque (vitae sagittis) diam, ut lobortis nisi. Maecenas id massa velit phasellus et
                     massa laoreet, maximus diam aliquam, ) accumsan elit."""

Remove_Close_Parenthesis= Text_To_Correct.replace(")", " !error ")

Remove_Open_Parenthesis= Remove_Close_Parenthesis.replace("(","!error")

print(Remove_Open_Parenthesis)

I figured out that all parenthesis are removed.

A: Replacing correct () pairs with [] (any delimiter) and remaining with !error and undo the first step
r=Text_To_Correct
r= re.sub(r'\(([^()]*?)\)',r'[\1]',r)
r= re.sub(r'\(|\)',r'!error',r)
r= re.sub(r'\[([^\[\]]*?)\]',r'(\1)',r)

For nested ()
r=Text_To_Correct
pattern=r'\(([^()]*?)\)'
while re.search(pattern,r):
    r= re.sub(pattern,r'[\1]',r)
r= re.sub(r'\(|\)',r'!error',r)
pattern2=r'\[([^\[\]]*?)\]'
while re.search(pattern2,r):
    r= re.sub(pattern2,r'(\1)',r)


text:
Q: Chi Square Contingency Table - Formula Derivation A chi-square distribution is constructed from normal random variables $X_i i=1,...n$ , each with normal distribution and mean $\mu$ and variance $\sigma^2$.  Transforming to standard normal and squaring, i.e.:
$$\frac{(X_i - \bar{X})^2}{\operatorname{Var}(X_i)}\sim N(0,1)^2$$
Then add these over all your $n$ random variables, then you get $\chi^2_{n-1}$ - a chi-square with $n-1$ degrees of freedom.
For contingency tables, suppose there are $k$ categories of observations $O_i, i = 1, \ldots , k,$ each with probability $p_i$. The statistic
we're proposing, assuming $O_i \sim \operatorname{Normal}$, is:
$$\frac{(O_i-np_i)^2}{\operatorname{Var}(O_i)} \sim N(0,1)^2$$
The variance of each observation is $np_i(1-p_i)$
For contingency tables, a test to see if the underlying mean is the same across categories, the standard equation taught for calculating the Chi-Square statistic is:
$$\sum_{i=1}^k\frac{(O_i-np_i)^2}{np_i} \sim \chi^2_{n-1}$$
So, where in the equation for assessing contingency tables does the term $(1-p_i)$ disappear to?

A: One experiment. Illustration in terms of rolling a fair die. Suppose I use R statistical software to roll a fair
die $n=600$ times, observing counts $X = (104, 96, 96, 104, 101, 100)$ of the respective faces $1, 2, \dots, 6.$ The expected number for each face is $E=100.$
[The code with rle is a quick way to get the vector $X$ in a form usable
by other functions.]
set.seed(420);  x = sample(1:6, 600, rep=T)
table(x)
x
  1   2   3   4   5   6
104  96  95 104 101 100

set.seed(420); X = rle(sort(sample(1:6,600,rep=T)))$lengths
[1] 104  96  95 104 101 100

Then the chi-squared statistic is $Q = \sum_{i=1}^6 \frac{(X_i-E)^2}{E} = 0.747 < 11.07,$ so in this particular (unusually well behaved) experiment, there is no evidence
that the die is unfair. Under the null hypothesis that all faces are
equally likely, $Q \stackrel{\text{aprx}}{\sim} \mathsf{Chisq}(df=5),$
so the critical value is $q^* = 11.07.$
X = c(104, 96, 95, 104, 101, 100);  E = 100
Q = sum((X-E)^2/X);  Q
## 0.7474179
qchisq(.95, 5)
## 11.0705

Many experiments. Now we seek to illustrate that $Q$ has very nearly the
claimed chi-squared distribution, which has $E(Q) = 5$ and $Var(Q) = 10.$ We do many 600-roll experiments
in order to get an idea of the distribution of $Q.$
set.seed(4321)
m = 10^5;  Q = numeric(m);  n = 600;  E = 100
for(i in 1:m) {
  X = rle(sort(sample(1:6,n,rep=T)))$lengths
  Q[i] = sum((X-E)^2/E) }
mean(Q);  var(Q);  quantile(Q, .95)
## 5.004733  # aprx E(Q) = 5
## 9.973967  # aprx Var(Q) = 10
##    95%
##  11.02    # aprx c with P(Q < c)=.95;  c = 11.07
hist(q, prob=T, br=50, col="skyblue2", main="Simulated Dist'n of Q with CHISQ(5) Density")
curve(dchisq(x, 5), add=T, lwd=2, col="red")

The histogram below shows 100,000 values of $Q$ and the red curve is
the density of $\mathsf{Chisq}(df = 5).$

The theory that supports the approximate chi-squared distribution of $Q$
is asymptotic. Simulation studies have shown that the approximation is
useful for doing goodness-of-fit tests, provided there are enough 'rolls of the die' so that $E > 5,$ which
is certainly true here.


text:
Q: Create testdata with List, Autofixture Trying to get this simple test to work:
public class MyClass
{
    public string Text { get; set; }
    public List<string> Comments { get; set; }

}
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var fixture = new Fixture();
        fixture.Customize<string>(c => c.FromSeed(s => s)); //Just return propertyname, no GUID appended
        var test = fixture.Create<MyClass>();

    }
}

but I keep getting the error

The decorated ISpecimenBuilder could not create a specimen based on the request: System.String. This can happen if the request represents an interface or abstract class; if this is the case, register an ISpecimenBuilder that can create specimens based on the request. If this happens in a strongly typed Build<T> expression, try supplying a factory using one of the IFactoryComposer<T> methods.`

If I remove the Customize line, is seems to work...
Not quite sure what I need to do to make it work

A: You can create string instances without appending a GUID by customizing the Fixture instance as shown below:
public void GuidsAreNotAppendedOnStringValues()
{
    var fixture = new Fixture();
    var expected = string.Empty;
    fixture.Customizations.Add(
        new StringGenerator(() => expected));

    var actual = fixture.Create<MyClass>();

    Assert.Equal(expected, actual.Comments.Aggregate((x, y) => x + y));
}

That way also the Text property is Text, instead of Texte85e2f6f-c1a3-47c7-baf2-4756c498f523.

A: Ended up, adding my own ISpecimenBuilder
public class TextBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
        var pi = request as PropertyInfo;
        if (pi == null)
            return new NoSpecimen(request);
        if (pi.PropertyType == typeof(string))
            return pi.Name;
        if (pi.PropertyType == typeof(IList<string>) || pi.PropertyType == typeof(List<string>))
        {
            var tmps = (List<string>)context.Resolve(typeof(List<string>));
            for (var n = 0; n != tmps.Count; ++n)
                tmps[n] = pi.Name + n.ToString(CultureInfo.InvariantCulture);
            return tmps;
        }
        return new NoSpecimen(request);
    }
}


text:
Q: Apache Geode debug Unknown pdx type=2140705 If I start a GFSH client and connect to Geode. There is a lot of data in myRegion and to check through it then I run:
query --query="select * from /myRegion"

I am getting the response:
Result     : false
startCount : 0
endCount   : 20
Message    : Unknown pdx type=2140705

How does one troubleshoot / debug this problem?
UPDATE: The error in the Geode server log is:
[info 2018/07/04 10:53:07.275 BST IsGeode <Function Execution Processor1> tid=0x48] Exception occurred:
java.lang.IllegalStateException: Unknown pdx type=1318971
  at org.apache.geode.internal.InternalDataSerializer.readPdxSerializable(InternalDataSerializer.java:3042)
  at org.apache.geode.internal.InternalDataSerializer.basicReadObject(InternalDataSerializer.java:2859)
  at org.apache.geode.DataSerializer.readObject(DataSerializer.java:2961)
  at org.apache.geode.internal.util.BlobHelper.deserializeBlob(BlobHelper.java:90)
  at org.apache.geode.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1911)
  at org.apache.geode.internal.cache.EntryEventImpl.deserialize(EntryEventImpl.java:1904)
  at org.apache.geode.internal.cache.PreferBytesCachedDeserializable.getDeserializedValue(PreferBytesCachedDeserializable.java:73)
  at org.apache.geode.internal.cache.LocalRegion.getDeserialized(LocalRegion.java:1269)
  at org.apache.geode.internal.cache.LocalRegion$NonTXEntry.getValue(LocalRegion.java:8771)
  at org.apache.geode.internal.cache.EntriesSet$EntriesIterator.moveNext(EntriesSet.java:179)
  at org.apache.geode.internal.cache.EntriesSet$EntriesIterator.next(EntriesSet.java:134)
  at org.apache.geode.cache.query.internal.CompiledSelect.doNestedIterations(CompiledSelect.java:837)
  at org.apache.geode.cache.query.internal.CompiledSelect.doIterationEvaluate(CompiledSelect.java:699)
  at org.apache.geode.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:423)
  at org.apache.geode.cache.query.internal.CompiledSelect.evaluate(CompiledSelect.java:53)
  at org.apache.geode.cache.query.internal.DefaultQuery.executeUsingContext(DefaultQuery.java:558)
  at org.apache.geode.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:385)
  at org.apache.geode.cache.query.internal.DefaultQuery.execute(DefaultQuery.java:319)
  at org.apache.geode.management.internal.cli.functions.DataCommandFunction.select(DataCommandFunction.java:247)
  at org.apache.geode.management.internal.cli.functions.DataCommandFunction.select(DataCommandFunction.java:202)
  at org.apache.geode.management.internal.cli.functions.DataCommandFunction.execute(DataCommandFunction.java:147)
  at org.apache.geode.internal.cache.MemberFunctionStreamingMessage.process(MemberFunctionStreamingMessage.java:185)
  at org.apache.geode.distributed.internal.DistributionMessage.scheduleAction(DistributionMessage.java:374)
  at org.apache.geode.distributed.internal.DistributionMessage$1.run(DistributionMessage.java:440)
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  at org.apache.geode.distributed.internal.DistributionManager.runUntilShutdown(DistributionManager.java:662)
  at org.apache.geode.distributed.internal.DistributionManager$9$1.run(DistributionManager.java:1108)
  at java.lang.Thread.run(Thread.java:748)

A: You can tell the immediate cause from the stack trace.
A PDX serialized stream contains a type id which is a reference into a repository of type metadata maintained by a GemFire cluster.  In this case, the serialized data of the object contained a typeId that is not in the cluster's metadata repository.
So the question becomes, "what serialized that object and why did it use an invalid type id ?"
The only way I've seen this happen before is when a cluster is fully restarted and the pdx metadata goes away, either because it was not persistent or because it was deleted (by clearing out the locator working directory for example).
GemFire clients cache the mapping between a type and it's type ID.  This allows them to quickly serialize objects without continually looking up the type id from the server.  Client connections can persist across cluster restarts.  When a client reconnects it does not flush the cached information and continues to write objects using its cached type ID.
So the combination of a pdx-metadata losing cluster restart and a client that is not restarted (e.g. an app. server) is the only way I have seen this happen before. Does this match your scenario ?
If so, one of the best ways to avoid this is to persist your pdx metadata and never delete it.


text:
Q: How can I display array items using a loop? I'm trying to add an item into an empty array using .push inside loop then display it again but nothing is happening. Below is my current code:

$('.button').on('click', function(){
   const canvasArray = [];
   $('.box').each(function(){
       var boxName = $(this).text();
       canvasArray.push(boxName);
   });
   console.log(canvasArray);
});

Red

Blue

Green

Yellow

In my console log, it returns something like this:
Array(4) [ "Red", "Blue", "Green", "Yellow" ]
0: "Red"
1: "Blue"
2: "Green"
3: "Yellow"
length: 4

I want to display the value of my canvasArray and append it to a DIV and I'm trying to do something like this:
$.each(canvasArray, function(index, value){
    $("#result").append(index + ": " + value + '
');
});

but nothing is happening and no error in my console log. Any idea?

A: Your code works. Here it is. Perhaps you were unsure how to structure it all?
In this demo, the results div is populated upon a second button press - but you could alternately just move the $.each() code up into the first button's click handler (below the console.log, for example).

const canvasArray = [];
$('.button').on('click', function(){
   $('.box').each(function(){
       var boxName = $(this).text();
       canvasArray.push(boxName);
   });
   console.log(canvasArray);
});

$('.button2').on('click', function(){
  $.each(canvasArray, function(index, value){
    $("#result").append(index + ": " + value + '
');
  });
});
#result{
  position:fixed;
  top: 0px;
  left: 350px;
  width: 200px;
  height: 130px;
  margin-top:20px;
  background:wheat;
}

Red

Blue

Green

Yellow

<button class="button">Populate Canvas Array</button>
<button class="button2">Write Into Results Div</button>


text:
Q: How to configure Eclipse to format all java code except Strings declaration? How to configure Eclipse to format all java code except Strings declaration?
Example:
Before Ctrl+I:
    String sql =
        "Select column " +
        "from   table  " +
        " where column1 > 0 AND column2 < 0";

After Ctrl+I:
    String sql = "Select column " + "from   table  "
            + " where column1 > 0 AND column2 < 0";

Thank you!
edit:
Has any way to configure using Formatter preferences (Window > Preferences > Java > Code Style > Formatter)?

A: You could use // to prevent the formatting like this:
String sql = //
        "Select column " + //
        "from   table  " + //
        " where column1 > 0 AND column2 < 0";

That's not very nice but works in every case (i.e. when your coworkers don't use exactly the same settings in Eclipse).

A: You can enable the @formatter:on and @formatter:off tags in the formatter preferences:
// @formatter:off
String s = "..." +
           "..." ...
// @formatter:on


text:
Q: requestPermissions() for gps inside a service . Error:"location provider requires ACCESS_FINE_LOCATION permission." The Problem I am facing is giving gps permissions to the application through service I am writing.
I tried finding an example to achieve this and examples shows writing a gpslocation finder in Activity, but in this case, i would like to implement this in service.
The Service code is as follows:
public class TravelService extends Service{

    private LocationManager locManager;
    private LocationListener locListener;

    @Override
    public void onCreate() {
        super.onCreate();
        locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                locManager.requestLocationUpdates("gps", 5000, 100, locListener);

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            locManager.requestLocationUpdates("gps", 5000, 100, locListener);

            Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        locManager.requestLocationUpdates("gps", 5000, 100, locListener);

        Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service destroyed",Toast.LENGTH_LONG).show();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}

Here is my code in the Manifest.xml:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.param.dateandtime">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!--  Entry for LoginActivity.class -->
        <activity android:name=".LoginActivity"
            android:label="@string/app_name"></activity>
        <activity android:name=".Finish"
            android:label="@string/app_name"></activity>
        <service android:name=".TravelService"
            android:exported="false"/>
    </application>

</manifest>

Here I have attached the error log, showing the error I'm facing. I can see the error as "location provider requires ACCESS_FINE_LOCATION permission."
Error log:

A: You cannot request permissions from service since a service is not tied to a UI.
So do it from the activity when you startService().
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number can be used

And implement onRequestPermissionsResult() callback
 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1001: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                        || ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
                    //Start your service here
                }
            }
        }
    }


text:
Q: sqlite: Can I mock the current time `now()` for testing? I build a test suite for a program that runs a lot of SQL statements with now() against a sqlite data base.  I would like to mock the sqlite clock --- to test behaviour that is designed to take several days within one second.  I do not want to touch the system clock.
Is this possible with sqlite?

A: Example in Python:
import sqlite3
def mock(*_):
    return '1984-01-02 11:22:33'
connection = sqlite3.connect(':memory:')
print(connection.execute('SELECT DATETIME()').fetchone()[0])
connection.create_function('DATETIME', -1, mock)
print(connection.execute('SELECT DATETIME()').fetchone()[0])

Output
2022-03-01 11:23:05
1984-01-02 11:22:33

A: SQLite's built-in functions can be redefined with sqlite3_create_function.
[Edit by Yaakov Belch --- additional information:]

*

*In perl, you can access this API through the $dbh->sqlite_create_function method of a DBD::SQLite data base handle.

*For python or PHP see this stackoverflow answer.


text:
Q: How I can generate a matrix from a set of terms? I want to build a matrix, from the following set $S = \{a b , a c\}$
  S = {a b , a c}

where the terms of S represent the raw of the matrix m , and the element in S represent the column of the matrix m , then we get
Column of m such that c1={a,a},c2={b,0} and c3={0,c}
raw of m such that r1={a,b,0} and r2={a,0,c}
building m from columns m={c1,c2,c3}
or building m from raw  m={r1,r2},
then we get
m={{a, b, 0}, {a, 0, c}}

$m=\left( \begin{array}{ccc}  a & b & 0 \\  a & 0 & c \\ \end{array}
 \right)$

Is this possible in practice?
In general, is this possible regardless of the terms of set?
Thanks for the help.

A: One idea:
S = {a b, a c};

PowerExpand @ Log[S /. {a -> Exp[{a, 0, 0}], b -> Exp[{0, b, 0}], c -> Exp[{0, 0, c}]}]

{{a, b, 0}, {a, 0, c}}

A: New method
Leveraging CoefficientRules.
S = {a b, a c};

var = Variables[S];

var # & /@ CoefficientRules[S][[All, 1, 1]]

{{a, b, 0}, {a, 0, c}}

Old Method
S = {a b, a c};

rls = MapIndexed[# -> #2.{1} -> # &, Variables[S]];

m = PadRight[SparseArray /@ (List @@@ S /. rls)]

{{a, b, 0}, {a, 0, c}}

Automation of Carl Woll's method:
PowerExpand @ Log[S /. Thread[# -> Exp@DiagonalMatrix@#]] & @ Variables[S]

{{a, b, 0}, {a, 0, c}}

A: rule = Thread[Variables[S] -> DiagonalMatrix[Variables[S]]];
Block[{Times = Plus}, S /. rule]

{{a,b,0},{a,0,c}}


text:
Q: How do i render and show another page when user hovers over the link? I have one link. I want that when user hovers over the link, one page should get rendered which contains all  tag and should show it in one box (tooltip type). How can i do this?
Thanks in advance:)

A: Have a look at jquery tooltip. Very easy and powerfull way of doing what you want.

A: Can you show us what you tried? Or, can you paint some more details as to what your imagination captured? Basically, you are looking to perform an ajax call on mouseover, for example:
$(document).ready(function() {

    // when I mouseover an element with class="foo"
    $(".foo").mouseover(function() {

        // get me a reference to the next (hidden) div relative (or more precisely, sibling) to this element
        var $theDiv = $(this).next("div"); // or wherever it's at

        // using jQuery's $.data utility, I have stored the 'href' of the
        // page/view or whatever this mouseovered element points to.
        // the url parameter to load can optionally have a valid selector attached to it
        // to filter matching elements from the response
        $theDiv.load('linkToLoad.html' + '?dynamicImagePageThingieLink=' + $(this).data('link') + ' img', function() {

            // this will execute once the loading has finished
            alert('The next div has been filled up with image tags from linkToLoad.html');
            $theDiv.slideDown();
        });
    });
});

A: Qtip will do what you want very easily, something like this;

    Image One
    Image Two
    Image Three

There are tons of options; check out the example and view the code.


text:
Q: number of sheets of covering map Suppose $a,b,c,d$ are integers with $ad-bc\ne 0$ and write the torus $T$ as $\{(x,y)\in \mathbb C^2: 1=|x|=|y|\}.$ Consider the map $p: T\to T$ defined by $(x,y)\to (x^ay^b,x^cy^d)$.
I am able to prove that $p$ is a covering space.

I want to now find the cardinality $|p^{-1}(x_0)|$ for each $x_0\in
T$.

Could someone please explain how this works?

A: Let's use $(u, v)$ for the complex coordinates, so that we can write
$$
u = e^{ix},\quad
v = e^{iy}.
$$
Since $a$, $b$, $c$, and $d$ are integers, the map $p$ sends $(u, v) = (e^{ix}, e^{iy})$ to
$$
(u^{a} v^{b}, u^{c} v^{d}) = (e^{(ax + by)i}, e^{(cx + dy)i}).
$$
It should be apparent that the lift $\hat{f}$ of $p$ is as in the hint.
To count the number of sheets in the covering $p$, consider the image of some fundamental domain, such as the unit square $[0, 1] \times [0, 1]$ under $\hat{f}$, and ask "how many unit squares" the image covers (i.e., what is its area?).
The number of sheets is:

 $|\det \hat{f}| = |ad - bc|$.


text:
Q: C# Windows forms - Data Conduit to connect to a windows form app Hi guys I need some help with this dataconduit. Its written by my tutor and we used it on a web development project. I am trying to use it for a windows forms application to connect to the database but i get the following error:
An attempt to attach an auto-named database for file C:\Users.... failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The data conduit works indeed if i use it on a asp.net website but not on a windows forms
i did try to researched but no luck.
I am just testing it with two text box and a save button
thank you
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

///This class uses the ado.net sql classes to provide a connection to an sql server database.
///it is free for use by anybody so long as you give credit to the original author i.e me
///Matthew Dean mjdean@dmu.ac.uk De Montfort University 2011

//you will need to modify the name of the namespace to suit your own program.
namespace MyClassLibrary
{
    public class clsDataConduit
    {
        //connection object used to connect to the database
        SqlConnection connectionToDB = new SqlConnection();
        //data adapter used to transfer data to and from the database
        SqlDataAdapter dataChannel = new SqlDataAdapter();
        //ado.net class for building the sql commands
        SqlCommandBuilder commandBuilder = new SqlCommandBuilder();
        //stores a list of all of the sql parameters
        List<SqlParameter> SQLParams = new List<SqlParameter>();
        //data table used to store the results of the stored procedure
        DataTable queryResults = new DataTable();
        //data row used to store the data for a new record
        DataRow newRecord;
        //string variable used to store the connection string
        private string connectionString;

        public clsDataConduit()
        {
            //this is the constructor for the class
            //you will need to modify this to suit your own database name and folder structure
            //
            //variable to store the patth to the database
            string DbPath;
            //variable to store the partial path and file name of your database
            //modify this line to suit your own needs
            string DatabaseName = "\\MyDatabase\\NamesData.mdf";
            //set the DbPath concatenating the name of your database
            DbPath = GetParentPath() + DatabaseName;
            //build up the connection string for the sql server database
            connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + DbPath + ";Integrated Security=True;User Instance=True";
        }

        private string GetParentPath()
        ///this function returns the path to the parent folder of the solution
        {
            //get the folder for the project
            string DbPath = System.AppDomain.CurrentDomain.BaseDirectory;
            //variable to store the position of the \\ characters
            int Posn;
            //loop through the path twice
            for (int Counter = 0; Counter != 2; Counter++)
            {
                //find the right most instance of \\
                Posn = DbPath.LastIndexOf("\\");
                //split the path at that point
                DbPath = DbPath.Substring(0, Posn);
                //do it one more time
            }
            //return the new path
            return DbPath;
        }

        public void AddParameter(string ParamName, string ParamValue)
        ///public method allowing the addition of an sql parameter to the list of parameters
        ///it accepts two parameters the name of the parameter and its value
        {
            //create a new instance of the sql parameter object
            SqlParameter AParam = new SqlParameter(ParamName, ParamValue);
            //add the parameter to the list
            SQLParams.Add(AParam);
        }

        public void Execute(string SProcName)
        {
            ///public method used to execute the named stored procedure
            ///accepts one parameter which is the name of the stored procedure to use
            //open the stored procedure
            //initialise the connection to the database
            connectionToDB = new SqlConnection(connectionString);
            //open the database
            connectionToDB.Open();
            //initialise the command builder for this connection
            SqlCommand dataCommand = new SqlCommand(SProcName, connectionToDB);
            //add the parameters to the command builder
            //loop through each parameter
            for (int Counter = 0; Counter < SQLParams.Count; Counter += 1)
            {
                //add it to the command builder
                dataCommand.Parameters.Add(SQLParams[Counter]);
            }
            //set the command type as stored procedure
            dataCommand.CommandType = CommandType.StoredProcedure;
            //initialise the data adapter
            dataChannel = new SqlDataAdapter(SProcName, connectionToDB);
            //set the select command property for the data adapter
            dataChannel.SelectCommand = dataCommand;
            //use the copmmand builder to generate the sql insert delete etc
            commandBuilder = new SqlCommandBuilder(dataChannel);
            //fill the data adapter
            dataChannel.Fill(queryResults);
            //get the structure of a single record
            newRecord = queryResults.NewRow();
            //close the connection
            connectionToDB.Close();
        }

        public void WriteToDatabase()
        //void method that updates changes to the data adapter thus changing the database
        {
            //update any changes
            dataChannel.Update(queryResults);
        }

        public DataRow NewRecord
        ///this method provides access to the new record as a single data row
        {
            get
            {
                //return the blank data row
                return newRecord;
            }
        }

        public void RemoveRecord(int Index)
        //void method that removes a record at a specified index in the query results
        {
            //remove the record
            queryResults.Rows[Index].Delete();
        }

        public void AddToDataTable()
        //void method that adds the new record to the table data
        {
            //add the new record to the table
            queryResults.Rows.Add(newRecord);
            //re initialise the new record
            newRecord = queryResults.NewRow();
        }

        public int Count
        //property that returns the count of records in the query results
        {
            get
            {
                //return the count of the query results
                return queryResults.Rows.Count;
            }
        }

        public DataTable QueryResults
        //public property that provides access to the query results
        {
            get
            {
                //return the query results
                return queryResults;
            }
            set
            {
                //set the query results
                queryResults = value;
            }
        }
    }
}

this is the code for my name class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyClassLibrary
{
   public class clsName
    {
       private string firstName;
       private string lastName;

       public string FirstName
       {
           get
           {
               return firstName;
           }

           set
           {
               firstName = value;
           }
       }

       public string LastName
       {
           get
           {
               return lastName;
           }

           set
           {
               lastName = value;
           }
       }

       public void Save()
       {
           clsDataConduit Names = new clsDataConduit();
           Names.Execute("sproc_tblNames_GetAll");
           Names.NewRecord["FirstName"] = firstName;
           Names.NewRecord["LastName"] = lastName;
           Names.AddToDataTable();
           Names.WriteToDatabase();
       }

    }
}

A: thank you guys but i finally managed to make it work. i am not sure if it is the right way to do it but what u have done is i have commented out the public clsDataConduit() {} method and before this method i have modified the connection string adding the full path of my database as follow: private string connectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users...\NamesData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");


text:
Q: Only get data with 56 as the 8th and 9th digits in SQL Working on an SQL query where data is only shown from phone numbers where the 8th digit is "5" and the 9th digit is "6."  For example, a phone number ending in "567."

A: select * from mytable where phone like '_______56%'

_ stands for a single character
'%' stands for any number of character, including 0.


text:
Q: How to make a long time Full GC in Java manually How to write some code to allocate the objects into Old Gen that will cause the full GC time longer than three or five seconds?

A: "Allocate the objects into Old Gen" and "long GC pauses" are hard to combine, as the worst thing you could do to the garbage collector, is to create lots of small, linked, live objects forming a graph that the garbage collector must traverse.
But small objects are not allocated into the Old Gen. Only large objects, e.g. arrays, are allocated directly into the Old Gen, but these do not stress the GC that much. Especially primitive type arrays, which you stated to have been used in your first attempt, are no challenge, as they can not contain object references in general.
So, to stress the GC, you have to create lots of small linked objects, enough to get them eventually promoted to the Old Gen, followed by modifying the old objects to enforce Full GC, resp. updates of the remembered sets of the affected cards.
If that's sounds like familiar pattern, you're right. We're talking about LinkedList here.
LinkedList<Object> list = new LinkedList<>();
for(ListIterator<Object> it = list.listIterator();;) {
    for(;;) {
        it.add(new Object());
        if(!it.hasNext()) break;
        it.next();
    }
    while(it.hasPrevious()) {
        it.previous();
        it.add(new Object());
        it.previous();
    }
}

This iterates over the list back and forth, inserting new objects between the old ones, which implies modifying the next pointer of the preceding and the prev pointer of the succeeding list node. We have to do this via ListIterator, as trying to use add(int index, E element) would become too slow for a growing linked list, not creating enough objects to stress the GC.
Running on Java 9.0.4 with -Xmx7G -Xlog:gc gave me
[0.023s][info][gc] Using G1
[0.230s][info][gc] GC(0) Pause Young (G1 Evacuation Pause) 24M->22M(256M) 60.748ms
[0.263s][info][gc] GC(1) Pause Young (G1 Evacuation Pause) 34M->36M(256M) 21.686ms
[0.299s][info][gc] GC(2) Pause Young (G1 Evacuation Pause) 46M->47M(256M) 18.848ms
[0.336s][info][gc] GC(3) Pause Young (G1 Evacuation Pause) 57M->58M(256M) 20.904ms
[0.391s][info][gc] GC(4) Pause Young (G1 Evacuation Pause) 68M->68M(768M) 31.420ms
[0.521s][info][gc] GC(5) Pause Young (G1 Evacuation Pause) 104M->105M(768M) 56.681ms
[0.620s][info][gc] GC(6) Pause Young (G1 Evacuation Pause) 138M->140M(768M) 46.616ms
[0.737s][info][gc] GC(7) Pause Young (G1 Evacuation Pause) 173M->174M(768M) 58.947ms
[0.906s][info][gc] GC(8) Pause Young (G1 Evacuation Pause) 207M->209M(2304M) 100.361ms
[1.272s][info][gc] GC(9) Pause Young (G1 Evacuation Pause) 319M->321M(2304M) 142.440ms
[1.656s][info][gc] GC(10) Pause Young (G1 Evacuation Pause) 421M->423M(2304M) 162.770ms
[1.992s][info][gc] GC(11) Pause Young (G1 Evacuation Pause) 523M->525M(2304M) 145.804ms
[2.404s][info][gc] GC(12) Pause Young (G1 Evacuation Pause) 625M->627M(4250M) 221.090ms
[3.088s][info][gc] GC(13) Pause Young (G1 Evacuation Pause) 824M->826M(4250M) 302.307ms
[3.721s][info][gc] GC(14) Pause Young (G1 Evacuation Pause) 1011M->1013M(4250M) 250.395ms
[4.421s][info][gc] GC(15) Pause Young (G1 Evacuation Pause) 1198M->1199M(4250M) 304.642ms
[5.179s][info][gc] GC(16) Pause Young (G1 Evacuation Pause) 1384M->1386M(5418M) 334.825ms
[6.134s][info][gc] GC(17) Pause Young (G1 Evacuation Pause) 1629M->1631M(5418M) 381.155ms
[6.897s][info][gc] GC(18) Pause Young (G1 Evacuation Pause) 1867M->1868M(5418M) 309.688ms
[7.670s][info][gc] GC(19) Pause Young (G1 Evacuation Pause) 2104M->2106M(5418M) 399.689ms
[8.498s][info][gc] GC(20) Pause Young (G1 Evacuation Pause) 2342M->2344M(6118M) 388.430ms
[9.515s][info][gc] GC(21) Pause Young (G1 Evacuation Pause) 2615M->2617M(6118M) 439.557ms
[10.477s][info][gc] GC(22) Pause Young (G1 Evacuation Pause) 2883M->2884M(6118M) 451.488ms
[11.489s][info][gc] GC(23) Pause Initial Mark (G1 Evacuation Pause) 3150M->3152M(6118M) 443.329ms
[11.489s][info][gc] GC(24) Concurrent Cycle
[12.660s][info][gc] GC(25) Pause Young (G1 Evacuation Pause) 3418M->3419M(6538M) 467.964ms
[14.124s][info][gc] GC(26) Pause Young (G1 Evacuation Pause) 3706M->3708M(6538M) 454.921ms
[15.538s][info][gc] GC(27) Pause Young (G1 Evacuation Pause) 3993M->3995M(6538M) 465.929ms
[16.945s][info][gc] GC(28) Pause Young (G1 Evacuation Pause) 4280M->4281M(6538M) 460.913ms
[18.490s][info][gc] GC(29) Pause Young (G1 Evacuation Pause) 4566M->4568M(6790M) 493.803ms
[20.083s][info][gc] GC(30) Pause Young (G1 Evacuation Pause) 4866M->4868M(6790M) 491.910ms
[21.516s][info][gc] GC(31) Pause Young (G1 Evacuation Pause) 5164M->5166M(6790M) 486.847ms
[22.895s][info][gc] GC(32) Pause Young (G1 Evacuation Pause) 5462M->5464M(6790M) 443.031ms
[24.342s][info][gc] GC(33) Pause Young (G1 Evacuation Pause) 5760M->5762M(6942M) 475.235ms
[25.258s][info][gc] GC(24) Pause Remark 5988M->5988M(6942M) 0.794ms

[25.827s][info][gc] GC(34) Pause Young (G1 Evacuation Pause) 6066M->6067M(6942M) 458.463ms
[27.021s][info][gc] GC(35) Pause Young (G1 Evacuation Pause) 6370M->6372M(6942M) 448.794ms
[27.485s][info][gc] GC(24) Pause Cleanup 6484M->6484M(6942M) 28.631ms
[27.490s][info][gc] GC(24) Concurrent Cycle 16000.856ms
[28.250s][info][gc] GC(36) Pause Young (G1 Evacuation Pause) 6675M->6676M(7024M) 481.748ms
[29.651s][info][gc] GC(37) To-space exhausted
[29.651s][info][gc] GC(37) Pause Initial Mark (G1 Evacuation Pause) 6983M->7127M(7168M) 751.288ms
[29.651s][info][gc] GC(38) Concurrent Cycle
[30.135s][info][gc] GC(39) To-space exhausted
[30.135s][info][gc] GC(39) Pause Young (G1 Evacuation Pause) 7168M->7168M(7168M) 203.578ms
[30.205s][info][gc] GC(40) Pause Young (G1 Evacuation Pause) 7168M->7168M(7168M) 69.831ms
[53.924s][info][gc] GC(41) Pause Full (Allocation Failure) 7168M->6955M(7168M) 23719.072ms
[53.924s][info][gc] GC(38) Concurrent Cycle 24273.544ms
[54.654s][info][gc] GC(42) To-space exhausted
[54.654s][info][gc] GC(42) Pause Young (G1 Evacuation Pause) 7167M->7167M(7168M) 484.771ms
[54.811s][info][gc] GC(43) Pause Initial Mark (G1 Evacuation Pause) 7167M->7167M(7168M) 156.984ms
[54.811s][info][gc] GC(44) Concurrent Cycle
[75.187s][info][gc] GC(45) Pause Full (Allocation Failure) 7167M->7166M(7168M) 20375.807ms
[75.187s][info][gc] GC(44) Concurrent Cycle 20375.993ms
[75.197s][info][gc] GC(46) To-space exhausted
[75.197s][info][gc] GC(46) Pause Young (G1 Evacuation Pause) 7167M->7167M(7168M) 8.585ms
[75.199s][info][gc] GC(47) Pause Initial Mark (G1 Evacuation Pause) 7167M->7167M(7168M) 1.773ms
[75.199s][info][gc] GC(48) Concurrent Cycle
[95.382s][info][gc] GC(49) Pause Full (Allocation Failure) 7167M->7167M(7168M) 20183.050ms
[115.575s][info][gc] GC(50) Pause Full (Allocation Failure) 7167M->7167M(7168M) 20192.989ms
[115.575s][info][gc] GC(48) Concurrent Cycle 40376.227ms
[115.581s][info][gc] GC(51) Pause Young (G1 Evacuation Pause) 7167M->7167M(7168M) 2.649ms
[115.613s][info][gc] GC(52) Pause Initial Mark (G1 Evacuation Pause) 7167M->7167M(7168M) 0.629ms
[115.613s][info][gc] GC(53) Concurrent Cycle
[119.694s][info][gc] GC(54) Pause Full (Allocation Failure) 7167M->0M(8M) 4080.414ms
[119.694s][info][gc] GC(53) Concurrent Cycle 4080.622ms
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.base/java.util.LinkedList.linkBefore(LinkedList.java:162)
    at java.base/java.util.LinkedList$ListItr.add(LinkedList.java:952)
    at test.Tmp.main(Tmp.java:32)

Note the reported pauses at [53.924s], [75.187s], [95.382s], and [115.575s] of over 20 seconds each…

A: I wrote a jshell script which creates what G1GC calls humongous objects which automatically bypass Eden and Survivor space.  Humongous allocations are allocations that are larger than 50% of the region size (HeapRegionSize) in G1.
You can find the code it here
GCAllocationTest.jsh


text:
Q: Searching filename in a textfile I need to search through a text file and find filenames and folders. If a filename is found, display a text and if a folder is found, display another text.
can anyone suggest how to do it?
cat filenames.txt | while read line
do
echo $line
done


text:
Q: Displaying Query and its Explain Plan as a HashMap I have to generate execution plans for each query extracted from a log file. I have to generate a Hashmap that contains the query as the key and value as the execution plan. This HashMap is to be displayed as a table in Angular.
So far I have tried the following. I am getting the table with query and execution plans as two columns. But the explain plain is displayed in a single line, instead of the table form I get when I print it out on the console (See the picture). Is there a way to get the same format while displaying it in the Angular table.

The Console Prints it in this form, which is what I want in the table also.

CODE:
ExecutionPlanService: Connects to the Oracle DB and generates Explain Plan.
@Service
public class ExecutionPlanService {
List<String> l = new ArrayList<>();
String execute;

public List<String> getExecPlan(String line) throws IOException, SQLException, ClassNotFoundException{
    ResultSet rs=null;

        Class.forName("oracle.jdbc.driver.OracleDriver");

        Connection con=DriverManager.getConnection("jdbc:oracle:thin:@10.49.7.212:1521:AVMPRD","CtmDitRW","CtmDit1743");

        Statement stmt = con.createStatement();
        stmt.execute(line);
        rs = stmt.executeQuery("select plan_table_output from table(dbms_xplan.display())");

        while (rs.next())
        {
            l.add(rs.getString(1));

        }

        return l;

   }
   public String prepend(String line, String prepend){
      String output = null;
       for (int index = 0; index < line.length(); index++) {
          output = prepend + line;
       }
       return output;

     }
     }

ExecPlanService: Checks if the given line is SQL statement, generates explain plan and puts these both as key and value in a HashMap.
private SQLCheckerService checker = new SQLCheckerService();
private ExecutionPlanService service = new ExecutionPlanService();
List<String>l =  new ArrayList<String>();
Map<String, List<String>> map = new HashMap<>();
String trimmedLine;
public Map<String, List<String>> processLine(String line) throws FileNotFoundException, UnsupportedEncodingException, ClassNotFoundException, IOException, SQLException {

     if(this.checker.isSelectStatement(line))

    {
       System.out.println("working!!");

      //Trim the line to start with a SQL keyword
           trimmedLine= this.checker.trimString(line);
           String prepend = this.service.prepend(trimmedLine, "Explain plan for ");
          l =this.service.getExecPlan(prepend);
          l.forEach(System.out::println);

          map.put(trimmedLine,l );
          System.out.println(map);

   }

    return map;
  }

ReadFileExecPlanService: Reads a log file line by line and processes it to generate explain plan.
public Map<String, List<String>> readFile(String filename) throws IOException, ClassNotFoundException, SQLException{

private ExecPlanService eservice= new ExecPlanService();
Map<String, List<String>> hashMap =  new HashMap<>();

     try (BufferedReader br = new BufferedReader(new FileReader(filename))){

         for(String line; (line = br.readLine()) != null; ){

          hashMap = this.eservice.processLine(line);

         }

       }
     System.out.println(hashMap);
        return hashMap;
}

ExecPlanController
@RestController
public class ExecPlanController {
@Autowired
ReadFileExecPlan exservice;

Map<String, List<String>> map = new HashMap<>();

@GetMapping("/getPlan")
@ResponseBody
public Map<String, List<String>>  getPlan() throws IOException, ClassNotFoundException, SQLException{
     String rootLocation = "C:\\Users\\Apoorva_Sharma\\Desktop\\upload-dir";

     File directory = new File(rootLocation);
        //get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList){
            if (file.isFile()){
                map = (exservice.readFile(file.getAbsolutePath()));
            }
        }
        System.out.println("WORKING!!");
        System.out.println(map);
        return map;

      }
      }


text:
Q: What is the right way to self-host a Web API? I'm not asking for a best practice advice since there are numerous blog posts and tutorials about the topic all over the internet.
I'm asking out of confusion since Microsoft made a lot of change to the whole self hosting procedure and every tutorial I find take a different, deprecated or unfamiliar approach.
My goal is to set up a self hosted Web API in a legacy Windows Service to control various long running tasks from a non-Windows client, such as an Android application where integrating a WCF / SOAP client can really be a PITA.
I'm aware about the fact that WCF is capable of offering a RESTful service, but since Web API is really suited for such a task, I thought I gave it a shot.
This is how I currently start my API hosted using OWIN (Katana):
public class ApiBootstrap {

    var httpConfiguration = new HttpConfiguration();
    // ... configure routes etc.

    appBuilder.UseWebApi(httpConfiguration);     // appBuilder = IAppBuilder
    var disposable = WebApp.Start<ApiBootstrapper>(_myBaseUri);

}

But most tutorials go on a different approach:
var config = new HttpSelfHostConfiguration("http://localhost:999");
// ... configure routes etc..

var server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();

Now, I understand the HttpSelfHostServer class is from System.Web.Http.SelfHost and not using OWIN, and both work fine.
But I'm struggling for days to achieve very simple tasks such as securing the connection using SSL, creating authorization etc., just because every tutorial I find on those topics referr to the self hosted method not using OWIN. But AFAIK, OWIN (Katana) is Microsofts prefered approach to achieve self hosting.
As a beginner, I am completely confused and helpless!
Edit: 4 upvotes, 1 fav and 30 views in only 6 minutes but still no answer. Can't really say if I'm doing genious coffee stuff here or if it's just an incredible dumb question.

A: The HttpSelfHostServer is now marked as legacy on Nuget.  However, the Owin HTTPListener has only been RTM for a fairly short period of time now.
Also, part of the intent of Owin to ensure that how you setup middleware is identical regardless of how you host.  So you will not likely see many articles targeting Owin HttpListener hosting directly because it should be irrelevant which host you are using.
The OwinHttpListener currently uses the standard .net HttpListener under the covers, which in reality is the same thing that the HttpSelfHostServer used.  Therefore stuff like SSL should be configured in pretty much the same way.
As far as authentication is concerned, have you looked at Microsoft.Owin.Security, most likely everything you need is in there.


text:
Q: What is the time limit on requests that have them? Some requests have a time limit attached to them. But unlike regular persona games there is no date to be based on and I can't find a definite amount of time attached to any of them. So, what is the time limit on these?

A: Time limits do not appear to be specific. Those requests just must be finished before the completion of the current labyrinth.


text:
Q: Ionic start page depending on a condition I am developing an App where I want to route the user to a input screen when he logs in for the first time and then to the standard login screen when he launches the app for the second time.
Ideas anyone?
Thanks!

A: I have a sample posted here.
https://github.com/aaronksaunders/simpleKinveyAngular/blob/master/index.html
The basic premise is to use the resolve capabilities on the ui-router to determine if the user has logged in to the app or not. Based on the results, you take a different path in the route


text:
Q: Build up a matrix similar to a given one Construct a matrix $B \in M(3,\mathbb R)$ such that:

*

*$B$ is similar to $A = \begin{bmatrix}
    0 & -1 & -1  \\
    1 & 2 & 1  \\
    -1 & -1 & 0 \\
  \end{bmatrix} \in M(3,\mathbb R)$

*$(1, 0, 1) \in \ker B$

*$\operatorname{Im} B =\{(x,y,z) \in\mathbb R^3 : x-y-2z=0 \}$

How to proceed?
What I did:
Let be $A = \begin{bmatrix}
    a & d & g  \\
    b & e & h  \\
    c & f & i \\
  \end{bmatrix}$
For the 2nd condition: $\begin{equation}
   \begin{cases}
   a+g=0\\b+h=0 \\ c+i=0
   \end{cases}
\end{equation}
$
And for the 3rd one: $\begin{equation}
   \begin{cases}
   a-b-2c=0\\ d-e-2f=0
   \end{cases}
\end{equation}$
Is it correct? How i can use the first condition?


text:
Q: Triples $(p,q,r)$ of primes satisfying the quadratic residue relation $\left(\frac{p}{q}\right)\cdot\left(\frac{q}{r}\right)=\left(\frac{p}{r}\right)$ I stumbled upon this problem while thinking about quadratic residues:

Find all triples $(p,q,r)$ of primes such that
  $$\genfrac(){}{0}{p}{q}\cdot\genfrac(){}{0}{q}{r} = \genfrac(){}{0}{p}{r}$$

I didn't make much progress beyond some trivial observations.

A: One can demonstrate infinitely many solutions as follows:-
Let $p$ and $q$ be distinct primes congruent to $3$ modulo $4$. Then $\genfrac(){}{0}{p}{q}$ and $\genfrac(){}{0}{q}{p}$ have opposite signs.
Therefore, for any other odd prime $r$, precisely one of $(p,q,r)$ and $(q,p,r)$ satisfies your rule.


text:
Q: What's Clang's problem with my code? GCC and MSVC think it's fine I'm working on an Advent of Code challenge (2021 day 18). Just as a test I tried compiling it on different compilers. While GCC (11.2) and MSVC (19.30) think it's fine, Clang (13.0.0) throws a list of errors. link to compiler explorer
/opt/compiler-explorer/gcc-11.2.0/lib/gcc/x86_64-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/alloc_traits.h:514:4: error: no matching function for call to 'construct_at'
          std::construct_at(__p, std::forward<_Args>(__args)...);
          ^~~~~~~~~~~~~~~~~
/opt/compiler-explorer/gcc-11.2.0/lib/gcc/x86_64-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/vector.tcc:115:21: note: in instantiation of function template specialization 'std::allocator_traits<std::allocator<RegularNumber>>::construct<RegularNumber, int, Named<int, index_for_vector_of_RegularNumber> &, Named<int, index_for_vector_of_RegularNumber>>' requested here
            _Alloc_traits::construct(this->_M_impl, this->_M_impl._M_finish,
                           ^
<source>:115:19: note: in instantiation of function template specialization 'std::vector<RegularNumber>::emplace_back<int, Named<int, index_for_vector_of_RegularNumber> &, Named<int, index_for_vector_of_RegularNumber>>' requested here
        regNumVec.emplace_back(*it - '0', leftRegNumIdx,
                  ^
/opt/compiler-explorer/gcc-11.2.0/lib/gcc/x86_64-linux-gnu/11.2.0/../../../../include/c++/11.2.0/bits/stl_construct.h:94:5: note: candidate template ignored: substitution failure [with _Tp = RegularNumber, _Args = <int, Named<int, index_for_vector_of_RegularNumber> &, Named<int, index_for_vector_of_RegularNumber>>]: no matching constructor for initialization of 'RegularNumber'
    construct_at(_Tp* __location, _Args&&... __args)
    ^

What doesn't Clang understand what seems fine according to the other two? Is this a bug, or my mistake?
Here's the "minimalized" code:
#include <algorithm>
#include <concepts>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>

template <typename Type, typename Description>
class Named {
   public:
    using UnderlyingType = Type;

    // clang-format off
  constexpr Named()
    noexcept(std::is_nothrow_default_constructible_v<Type>)
    requires std::default_initializable<Type>
  = default;
  explicit constexpr Named(Type const &val)
    noexcept(std::is_nothrow_copy_constructible_v<Type>)
    requires std::copyable<Type>
    : val_{val}
  {}
  explicit constexpr Named(Type&& val)
    noexcept(std::is_nothrow_move_constructible_v<Type>)
    requires std::movable<Type>
    : val_{std::move(val)}
  {}

  constexpr operator Type() const&
    noexcept(std::is_nothrow_copy_constructible_v<Type>)
    requires std::copyable<Type>
  {
    return val_;
  }
  constexpr operator Type() const&&
    noexcept(std::is_nothrow_move_constructible_v<Type>) // move assignable?
    requires std::movable<Type>
  {
    return std::move(val_);
  }

 private:
  Type val_;
};
// clang-format on

template <typename T>
auto readinputdata(std::istream &&is) {
    auto data{std::vector<T>{}};
    copy(std::istream_iterator<T>{is}, std::istream_iterator<T>{},
         back_inserter(data));
    return data;
}

static constexpr auto testData{
    "[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]]\n"
    "[[[5,[2,8]],4],[5,[[9,9],0]]]\n"
    "[6,[[[6,2],[5,6]],[[7,6],[4,7]]]]\n"
    "[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]]\n"
    "[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]]\n"
    "[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]]\n"
    "[[[[5,4],[7,7]],8],[[8,3],8]]\n"
    "[[9,3],[[9,9],[6,[4,9]]]]\n"
    "[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]]\n"
    "[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]]\n"};

struct index_for_vector_of_Pair;
using PairIndex = Named<int, index_for_vector_of_Pair>;

struct index_for_vector_of_RegularNumber;
using RegNumIndex = Named<int, index_for_vector_of_RegularNumber>;

struct RegularNumber {
    using IndexType = RegNumIndex;

    int value{};
    RegNumIndex leftIdx{}, rightIdx{};
};

using IndexVariant = std::variant<PairIndex, RegNumIndex>;

struct Pair {
    using IndexType = PairIndex;

    PairIndex parent{};
    IndexVariant leftIdx{}, rightIdx{};
};

static auto pairVec{std::vector<Pair>{}};
static auto regNumVec{std::vector<RegularNumber>{}};

// used for converting the input strings to pairs
static auto leftRegNumIdx{RegNumIndex{-1}};

static constexpr auto invalid_index{-1};

template <typename Type>
auto get_last_index(std::vector<Type> const &vec) {
    using Index = typename Type::IndexType;
    return Index{static_cast<typename Index::UnderlyingType>(size(vec))};
}

auto generate_pair(std::string::const_iterator &it, PairIndex parent)
    -> PairIndex;

auto generate_side(std::string::const_iterator &it, PairIndex pairIdx)
    -> IndexVariant {
    if (*it == '[') {
        return generate_pair(it, pairIdx);
    } else {
        regNumVec.emplace_back(*it - '0', leftRegNumIdx, // error on this line
                               RegNumIndex{invalid_index});
        auto const litIdx{get_last_index(regNumVec)};
        if (leftRegNumIdx != invalid_index) {
            regNumVec[leftRegNumIdx].rightIdx = litIdx;
        }
        leftRegNumIdx = litIdx;
        return litIdx;
    };
}

auto generate_pair(std::string::const_iterator &it,
                   PairIndex parent = PairIndex{invalid_index}) -> PairIndex {
    pairVec.emplace_back();
    auto const pairIdx{get_last_index(pairVec)};
    auto &pair{pairVec.back()};
    pair.parent = parent;

    ++it;  // skip [
    pair.leftIdx = generate_side(it, pairIdx);
    ++it;  // skip comma
    pair.rightIdx = generate_side(it, pairIdx);
    ++it;  // skip ]

    return pairIdx;
}

int main() {
    auto const snailFishNumbers{readinputdata<std::string>(  //
        std::stringstream{testData}                          //
        )};

    auto const outerPairIdxs{[&] {
        auto outerPairIdxs{std::vector<PairIndex>{}};
        outerPairIdxs.reserve(size(snailFishNumbers));
        transform(cbegin(snailFishNumbers), cend(snailFishNumbers),
                  back_inserter(outerPairIdxs), [](auto const &str) {
                      auto it{cbegin(str)};  // need lvalue
                      return generate_pair(it);
                  });
        return outerPairIdxs;
    }()};

    return 0;
}

A: Your type is an aggregate
struct RegularNumber {
    using IndexType = RegNumIndex;

    int value{};
    RegNumIndex leftIdx{}, rightIdx{};
};

which construct_at tries to initialize with round parenthesis
::new(std::declval<void*>()) T(std::declval<Args>()...).
However, an aggregate needs a {} initializer, until the compiler implements P0960 Allow initializing aggregates from a parenthesized list of values
And Clang just isn't there yet. Compiler support for C++20


text:
Q: Magento custom module config only shows up in main website config scope I have created a custom Magento module which all works fine when the config scope is set to Main Website.
However, If I switch the config scope to default config the config panel for my custom module disappears, I have no idea where this is specified in my config, which file is the scope of the module config set?
Main website:

Default config:

As you can see my custom config is missing on the deafult config scope.
Edit: Added system.xml
<?xml version="1.0"?>
<config>
    <tabs>
        <intilery translate="label" module="analytics">
            Intilery Analytics
            <sort_order>100</sort_order>
        </intilery>
    </tabs>

    <sections>
        <intilery translate="label" module="analytics">
            Tracking Code
            <tab>intilery</tab>
            <frontend_type>text</frontend_type>
            <sort_order>100</sort_order>

            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>

            <groups>
                <tracking translate="label" module="analytics">
                    Tracking Code
                    <frontend_type>text</frontend_type>
                    <expanded>1</expanded>
                    <sort_order>1000</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>

                            Account Code:
                            <comment>Please enter your account code, you can find this under your settings.</comment>
                            <frontend_type>text</frontend_type>
                            <sort_order>20</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>

                        <active translate="label comment">
                            Enabled:
                            <comment>Select whether or not Intilery tracking is enabled.</comment>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </active>
                       </fields>
                </tracking>
                <logging translate="label">
                    Logging
                    <frontend_type>text</frontend_type>
                    <sort_order>1</sort_order>
                    <show_in_default>1</show_in_default>
                    <show_in_website>1</show_in_website>
                    <show_in_store>1</show_in_store>
                    <fields>
                        <enabled translate="label">
                            Logging
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>10</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                        </enabled>
                    </fields>
                </logging>
            </groups>
        </intilery>
    </sections>
</config>

A: You are missing <show_in_default>1</show_in_default> for your sections in your code.
Try following it should work for you.
<?xml version="1.0"?>
<config>
    <tabs>
        <intilery translate="label" module="analytics">
            Intilery Analytics
            <sort_order>100</sort_order>
        </intilery>
    </tabs>

    <sections>
        <intilery translate="label" module="analytics">
            Tracking Code
            <tab>intilery</tab>
            <frontend_type>text</frontend_type>
            <sort_order>100</sort_order>
            <show_in_default>1</show_in_default>
            <show_in_website>1</show_in_website>
            <show_in_store>1</show_in_store>


text:
Q: Dynamic load css with CakePHP on a Page I am using CakePHP 2.0 and I want to load a concrete CSS style in a Page. (with no controller but using the Layout).
I know it can be done with scripts using:
$this->Html->script('photos', array('inline' => false));

And then on the Layout:
<?php echo $scripts_for_layout; ?>

But i have no idea if it exists or not something similar to $scripts_for_layout; for CSS style.
Do you know how can i do it?

A: If you can upgrade to 2.1 then you can use this:
// in your view
$this->Html->script('carousel', array('block' => 'scriptBottom'));

// in your layout
 echo $this->fetch('scriptBottom');

http://book.cakephp.org/2.0/en/views.html#using-blocks-for-script-and-css-files
update:
In earlier versions you could do it like you do with scripts:
$this->Html->css('some.css', null, array('inline' => false));

And it will be placed to $scripts_for_layout.


text:
Q: Sending custom status codes from AWS Lambda I have a Lambda@Edge function set up in AWS that checks incoming requests for a given cookie and rejects the request if it's not present, or if it is present it modifies the request for another operation. So far the code works correctly in that the request is 'rejected' if the cookie isn't present, and passes if it is present, but the response I am getting from the Lambda is a 502 which isn't really appropriate for what I'm trying to achieve. Abbreviated code below:
exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const requestHeaders = request.headers;

  const response = event.Records[0].cf.response;

  // Perform cookie check
  const downloadCookie = 'download-cookie=true';
  let downloadCookieFound = false;

  if (requestHeaders.cookie) {
    for (let i = 0; i < requestHeaders.cookie.length; i++) {
      if (requestHeaders.cookie[i].value.indexOf(downloadCookie) >= 0) {
        downloadCookieFound = true;
        break;
      }
    }
  }

  // Reject if cookie not present
  if (!downloadCookieFound) callback(null, request);

  // I have tried this as well but it doesn't seem to work
  // if (!downloadCookieFound) callback(null, { statusCode: 403, body: 'Cookie missing' };

  // Perform other operations
  // ...

  //Return modified response
  callback(null, response);
};

How do I get the Lambda to return a 403 response instead of this 502:
502 ERROR
The request could not be satisfied.
The Lambda function returned invalid JSON: The JSON output must be an object type. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

A: Solved it with luk2302's aid - change the line:
if (!downloadCookieFound) callback(null, request);
To:
if (!downloadCookieFound) callback(null, { status: '403' });
Other information can be added to the returned object if desired.


text:
Q: Two racket modules colliding I am requiring two modules to my file:
(require sicp) ; contains set-car! and set-cdr!
(require (planet dyoo/sicp-concurrency:1:2/sicp-concurrency)) ; contains procedures parallel-execute and test-and-set!

Problem: both libraries use different flavors of scheme. The sicp-concurrency uses mzscheme. Requiring this module prevented me from using else in a cond clause.
Is there a way to prevent the features of mzscheme in sicp-concurrency while still making use of the procedures I needed?

A: I have updated Danny Yoo's code to Racket 7.
Get the new file "sicp-concurrency.rkt" here:
https://gist.github.com/soegaard/d32e12d89705c774b71ee78ef930a4bf
Save the file in the same folder as your program file.
Here is an example of use:
#lang sicp
(#%require "sicp-concurrency.rkt")

(define (test-1)
  (define x 10)
  (parallel-execute (lambda () (set! x (* x x)))
                    (lambda () (set! x (+ x 1))))
  x)

(define (test-2)
  (define x 10)
  (define s (make-serializer))
  (parallel-execute (s (lambda () (set! x (* x x))))
                    (s (lambda () (set! x (+ x 1)))))
  x)

(test-1)
(test-1)
(test-1)
(test-1)
(test-1)


text:
Q: PhoneGap Cordova > 3.1.0 inAppBrowser not working I'm using cordova 3.3 with InAppBrowser plugin. When i call
ref = window.open('http://www.google.de', '_blank', 'location=yes');

in my onDeviceReady ready function all is fine.
But i have a second function, i called it after onDeviceReady is finished.
function LinkDropBox() {
  ref = window.open('http://www.google.de', '_blank', 'location=yes');
}

error console told me:
uncaught typeerror property 'open' of [object global] object is not a function
Any ideas to fix it?
i already tried
typeof window.open

in LinkDropBox and onDeviceReady function

*

*In onDeviceReady it returns "function"

*in LinkDropBox  it returns "string"

A: I'm going to guess that you are overwriting window.open by forgetting the var keyword in front of a local variable, e.g.
function doSomething() {
  open = "hello world";
}

instead of
function doSomething() {
  var open = "hello world";
}

Can you check your code for this issue?


text:
Q: Schedule a job through a web app using user input I am using the quartz scheduler. And I can schedule jobs in the usual way without any problem.
Code
public class QuartzTest implements Job {

    public void execute(JobExecutionContext context)
            throws JobExecutionException {
                System.out.println("Hello Quartz on " + new Date());
            }

    public static Scheduler scheduler;

    public void scheduleLoad(String time, int jobNo) {
        try {
            // Transform user input into a date
            SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy:HH:mm:ss");
            Date scheduleDate = dateFormat.parse(time);

            // Grab the Scheduler instance from the Factory
            //Scheduler
            scheduler = StdSchedulerFactory.getDefaultScheduler();

            // Listener
            //scheduler.getListenerManager().addJobListener(new SimpleJobListener());

            // and start it if it is shut down
            if(!scheduler.isStarted())
                scheduler.start();

            // Define a job and tie it to a class
            JobDetail job = newJob(QuartzTest.class)
                    .withIdentity("job"+jobNo)
                    .build();

            // Define trigger
            SimpleTrigger trigger = (SimpleTrigger) newTrigger()
                    .startAt(scheduleDate)
                    .forJob("job"+jobNo)
                    .build();

            // Schedule job using trigger
            scheduler.scheduleJob(job, trigger);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SchedulerException {
        String runTime = "04/15/2013:17:37:10";
        QuartzTest quartz = new QuartzTest();
        quartz.scheduleLoad(runTime,1);
        String runTime2 = "04/15/2013:17:37:15";
        quartz.scheduleLoad(runTime2,2);
        String runTime3 = "04/15/2013:17:37:20";
        quartz.scheduleLoad(runTime3,3);
    }
}

But I have to create a web app, in which I have to schedule a job using the "user's input". This is where I am getting stuck. How do I do this ? I will be using JSP.
e.g.- User 1's command - /home/user/load.sh -a -b -c (schedule on Monday)
User 2's command - /home/user/load.sh -a -b -g (schedule on Tuesday)
I can take the user's command, schedule date, etc from the web page as a string and then parse this string later inside Quartz scheduler. But how do I pass this string to Quartz in the first place to schedule the user's job ?
Just to make myself clear-
I want the user to be able to define his own job and schedule.
Thanks

A: You'll need a class that extends HttpServlet that is registered in your application's web.xml file. Again, take a look at the wiki, for how to do this
@WebServlet("/jobs") // only with Servlet 3.0
public class SchedulerServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // get input parameter
        String time = request.getParameter("time");
        // validate that it is not null/empty and is valid time (custom method)
        if (time != null && !time.isEmpty() && isValidTime(time)) {
            int jobNo = ... // generate job no
            YourJobScheduler scheduler = ... // get scheduler
            JobDetails jobDetails = scheduler.scheduleLoad(time, jobNo); // maybe this return details of the scheduled job

            request.setAttribute("jobDetails", jobDetails);
            // do something with response
            request.getRequestDispatcher("/WEB-INF/ShowJobDetails.jsp").forward(request, response);
        }

        // missing input parameter, so send error
    }
}

This class will take the input parameter time, validate it, and then pass it to your scheduler, which is basically the method you have in your question, except maybe it returns an object containing the details of the job you just scheduled. If you add that object to your request attributes, you can then show it in your View (as a jsp).


text:
Q: Select each and every unique row when an auto filter is applied? For example I wanted to select the unique names that i get under the filter and then send an email

A: Using the below VBA code you can do this.
Selection.AutoFilter
Range("A:A").AdvancedFilter Action:=xlFilterInPlace, Unique:=True


text:
Q: how to compare date and time using MomentJs and React I am using MomentJs in a ReactJs project. I am trying to compare the date and time
How can I compare the time. use the remindTime object
Im am currently doing the follow however does not work because it is looking at the remindTime object and not the date and time
moment() >= moment(remindTime) ? true : false

const remindTime =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2021-09-26', time: '7:43:21 pm' },
            isComplete: false,
        }

Basically I want to know if the current time is great or equal to the date and time in the remindTime object

A: I think you can use  [moment query functions]:https://momentjs.com/docs/#/query/
Take into account that moment works with specific param formats, so you cannot give it standalone objects.
Considered that, you'll need the diff function and parse apropiately  remindTime.date and remindTime.time:
To get the difference in milliseconds, use moment#diff like you would use moment#from.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b) // 86400000

And to get the difference in another unit of measurement, pass that measurement as the second argument.
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

An example for this could be:
//given
const remindTime1 =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2021-09-26', time: '7:43:21 pm' },
            isComplete: false,
        }
// and also given another object for comparing times and dates

const remindTime2 =
        {
            _id: new ObjectId("614fa5ed18b365aa83099183"),
            title: 'Third Message',
            description: 'Item 3',
            remindTime: { date: '2020-09-28', time: '9:50:21 pm' },
            isComplete: false,
        }

const parseDate1= remindTime.remindTime.date.split('-');
//this returns [2021,09,28]
const parseDate2= remindTime2.remindTime.date.split('-');
//this returns [2021,09,26]

var a = moment(parseDate1);
var b = moment(parseDate2);

//then you can compare dates in different ways sush us:

a.diff(b, 'days')   // 1
a.diff(b) // 86400000 => this is miliseconds
a.diff(b, 'years');   // 1

Also it could be easier to think that diff is a kind of minus operator:
a.diff(b) // a - b < 0
b.diff(a) // b - a > 0

Hope it works, for further info please check this out: https://momentjs.com/docs/#/query/


text:
Q: XML string to be stored as string in variable without parsing by PHP (xml inside JSON) ts simple but I can't understand where I am wrong. The code is:
<?php
$v='<?xml version="1.0" ?>{point.key}
';
print $v;
?>

I want the browser to output as
'<?xml version="1.0" ?>{point.key}
'

but the browser prints
{point.key}

If I view the page source I get
<?xml version="1.0" ?>{point.key}

I am confused. if $v variable has the unparsed xml string or not. Actually I got this problem transfering XML string with JSON as
"tooltip": {
                headerFormat: '{point.key}
',
                pointFormat: '
{series.name}:	{point.y:.1f} mm
',
                footerFormat: '
',
                shared: true,
                useHTML: true
    },

where  I get
headerFormat: '{point.key}'`

instead of
headerFormat:'{point.key}
'

A: Once $v is printed, the browser just interprets the tags. If you don't want things like  to be treated as actual HTML, you have to escape the string. The easiest way in PHP is with htmlspecialchars():
<?php
$v='<?xml version="1.0" ?>{point.key}
';
print htmlspecialchars($v);
?>

This will escape all the greater-thans and lesser-thans, etc. and output:
<?xml version="1.0" ?><span style="font-size:10px">{point.key}</span><table>

which should give you what you want in the browser.


text:
Q: How can I show that $ \lim_{R\to+\infty}{\int_0^\pi\log(1-e^{2i(iR+x)})dx}=0 $? How can I show that
$$
\lim_{R\to+\infty}{\int_0^\pi\log(1-e^{2i(iR+x)})dx}=0\quad ?
$$
What I've done so far is rewriting the integrand as
$$
\log(1-e^{2i(iR+x)})=\log|1-e^{2i(iR+x)}|+i\theta(x)
$$
It's not hard to get an estimate of $\log|1-e^{2i(iR+x)}|$.

How can I estimate $|\log(1-e^{2i(iR+x)})|$?

A: With Taylor series, it is easy to see that
$$
|\log(1-z)|\leq|\log(1-|z|)|
$$
for $|z|<1$.
So your integral is bounded by
$$
\int_0^{2\pi}|\log(1-e^{-2R})|dx=2\pi |\log(1-e^{-2R})|.
$$
Now let $R$ tend to $+\infty$.

A: $$e^{2i(iR+x)}=e^{-2R+2xi}=e^{-2R}(\cos 2x+i\sin 2x)\Longrightarrow$$
$$\left|1-e^{2i(iR+x)}\right|=\left|(1-e^{-2R}\cos 2x)+ie^{-2R}\sin 2x\right|=\sqrt{1+e^{-4R}-2e^{-2R}\cos 2x}\Longrightarrow$$
$$\log\left|1-e^{2i(iR+x)}\right|=\frac{1}{2}\log \left(1+e^{-4R}-2e^{-2R}\cos 2x\right)\xrightarrow[R\to\infty]{}\frac{1}{2}\log 1=0$$