text:
Q: What is returned by .get() on an empty Tkinter Entry Widget I am trying to check if necessary values are entered properly before running a code. To do this, I want to check that the user has actually entered something into both entry widgets:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

entry1_val = None
entry2_val = None
def submit_cmd():
    global entry1_val, entry2_val
    entry1_val = entry1.get()
    entry2_val = entry2.get()

label1 = ttk.Label(root, text='Entry 1:')
label1.grid(row=0, column=0)
label2 = ttk.Label(root, text='Entry 2:')
label2.grid(row=1, column=0)
entry1 = ttk.Entry(root)
entry1.grid(row=0, column=1)
entry2 = ttk.Entry(root)
entry2.grid(row=1, column=1)

submit = ttk.Button(root, text='Submit', command=submit_cmd)
submit.grid(row=2, column=1)

# pseudocode for what I want to check
"""
if(entry1_val == something or entry2_val == something):
    print("Didn't enter both values")

"""
root.mainloop()

I was previously doing this by a simple if statement that checks if both entry1_val and entry2_val have been updated from the None object. Like so:
if(entry1_val != None and entry2_val != None):
    print('Both values good')
elif(entry2_val == None):
    print("Didn't enter 1st value")

However, since submit_cmd updates both entry1_val and entry2_val, even if the user has only entered a value into one of the entry widgets, both values get updated from None.
I am wondering two things:

*

*What is returned when .get() is called on an empty entry widget

*Is there a better way to check that something was correctly entered into the entry widget?

A: if you don't enter anything into your tk.Entry, it will contain a '' by default..
example:
import tkinter as tk
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
print(repr(entry.get()))
root.mainloop()

output:
''
it is because you didn't enter anything to the entry..


text:
Q: Add a class if url is equal to href of a link I'm trying to make a jQuery script in WordPress, that will add the "active" class to the element of my sidebar that has the same URL as the matching link in the navbar.

(function ($) {
    var url = window.location.href;
    $('.navbar-nav li').each(function ($) {
        if ($('.navbar-nav li a').attr('href') == url) {
            $('.navbar-nav li').addClass('active');
        }
    });
    console.log(url);
})(jQuery);
.active {
background-color: black;}
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>

            <a class="nav-link" href="<?php echo get_site_url() ?>/">
                Accueil

          <a class="nav-link" href="<?php echo get_site_url() ?>/la-marque-honey">
            La marque

          <a class="nav-link" href="<?php echo get_site_url().'/la-formule-honey' ?>">
            La formule

          <a class="nav-link" href="<?php echo get_site_url() ?>/conseil">
            Le monde de bébé

It shows an error ( $ is not a function ), while there's another piece of code on the website that works well with the same selectors.
What's the issue here ?
Thanks

A:
It shows an error ( $ is not a function )

This error was because you were redefining $ inside the each as the element being iterated:
 $('.navbar-nav li').each(function ($) {
 // Dont do this -------------------^

There were a few things wrong with your code, but in general what you were doing was using selectors within the whole page instead of selectors with the current element being enumerated using each

$(function() {

  var url = window.location.href;
  $('.navbar-nav li').each(function() {
    if ($('a',this).attr('href') == url) {
      $(this).addClass('active');
    }
  });
  console.log(url);

});
.active {
  background-color: black;
}

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />

                Accueil

            La marque

            La formule

            Le monde de bébé

A: You need to make sure your jquery script is loaded before your function is called. Just make sure the jquery script tag is before the script tag containing your code.
Aside from your initial error - what you have here will add .active to every li that's a child of .navbar-nav.
$('.navbar-nav li').each(function ($) {//So is $ in the function parenthisis
    if ($('.navbar-nav li a').attr('href') == url) {
        $('.navbar-nav li').addClass('active');//this is wrong
    }
});

You should make use of the this keyword. Something like
$('.navbar-nav li').each(function () {
    let anchor = $(this).children('a');
    if ($(anchor).attr('href') == url) {
        $(this).addClass('active');
    }
});

A: Try this:
jQuery( document ).ready(function() {
    var url = window.location.href;
    $('.navbar-nav li').each(function ($) {
        if ($('.navbar-nav li a').attr('href') == url) {
            $('.navbar-nav li').addClass('active');
        }
    });
    console.log(url);
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Applications of Cauchy's convergence theorem Cauchy's Convergence Theorem:
Let {$P_n$} be a sequence of points and let $d(P_m,P_n)$ be the distance between $P_m$ and $P_n$. Then for a sequence to be convergent, $d(P_m,P_n)$ should $\to$ 0, as $n$ and $m$ become infinite.
I understand the theorem, but if I'm given a sequence, how can I apply this theorem to check if the sequence is Cauchy? I have a midterm tomorrow and I'm positive this will be a question.
The only thing I can think to do would be to some how prove that the distance is always less than some $\epsilon$. But I'm not sure how to even do that. Also, my book doesn't have any problems which require the use of this theorem, so I have nothing to really check any kind of work against. There is only the proof of the formula.
Any help is greatly appreciated!

A: Note that the theorem refers to a complete metric space (if you haven't done metric spaces, I presume your points are real numbers with the usual distances).
For calculations, your intuition is correct: if you can prove that $d(x_n,x_m)<\epsilon$ eventually for all $\epsilon$, then you can conclude that the sequence is Cauchy. However, this is not always required, as you can just take limits as well! Choose your favourite convergent sequence and try it out.
As an example, take your sequence of points to be $P_n=\frac{1}{n}$ in $\mathbb{R}$ with the usual metric. Then
$d(P_n,P_m)=\left|\frac{1}{n}-\frac{1}{m}\right|\leq\left|\frac{1}{n}\right|+\left|\frac{1}{m}\right|\to0 $ as $m,n\to\infty$
If you really love your $\epsilon's$, you can also write it like so. Fix $\epsilon>0$. There is a positive integer $k>0$ such that $\frac{1}{k}<\epsilon$. Given $m,n>2k$ (so that $\frac{1}{m}+\frac{1}{n}<\frac{1}{k}<\epsilon$), we have
$d(P_n,P_m)=\left|\frac{1}{n}-\frac{1}{m}\right|\leq\left|\frac{1}{n}\right|+\left|\frac{1}{m}\right|<\frac{1}{2k}+\frac{1}{2k}=\frac{1}{k}<\epsilon$
Your friends in such calculations include the triangle and Cauchy-Schwarz inequalities.

A: Frequently in analysis, you're given a sequence $\{x_n\}$ which we'd like to show converges.  The problem is that the definition of convergence requires we find a point $x$ so that $\lim_{n \to \infty} d(x,x_n) = 0$ for some $x$ in our metric space.  Cauchy's criteria says that in a complete metric space, it's enough to show that for any $\epsilon > 0$, there's an $N$ so that if $n,m \ge N$, then $d(x_n,x_m) < \epsilon$; that is, we can show convergence without knowing exactly what the sequence is converging to in the first place.
So you use Cauchy's theorem when you're trying to show a sequence converges but don't have a good guess what it converges to.


text:
Q: view in base.html django I have notification scrollbar like on fb or twitter. Top menu.html is directly included by base.html Unfortunatelly, I can use only User method there. Is it possible to not write in every view that I need notifications? I want to once paste in one view and have it always in top menu.html which is in base!
from intarface import
menu_nots
nots = menu_nots(request)

A: It is possible. Try writing your own context processor.
def add_notifications(request):
    """ Adds Facebook notifications to the view context. """
    return {'notifications': menu_nots(request)}

Next, add it to your TEMPLATE_CONTEXT_PROCESSORS in settings.py.

A: I think that the best way to solve your problem by using a inclusion tags:
https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags
@register.inclusion_tag('menu.html')
def show_menu():
    #menu logic2

in base.html:

    ...
    {% show_menu %}
    ...

function of inclusion tag will run on every request on every pages

A: Use messages %username% !
view
from django.contrib import messages

messages.add_message(request, messages.INFO, 'Hello world.')
messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')

template
{% if messages %}

    {% for message in messages %}

{{ message }}

    {% endfor %}

{% endif %}

A: add to setting.py part of TEMPLATE append to context_processors list -> app_name.view.base,


text:
Q: how to split and save my problem is next:
char str[25] = "exsample=string=to=split";
char a[2] = "=";
char* token;
token = strtok(str, a);

as you know that code saves first part "exsample" to string token
but how I can take next part of line? meaning string and all after it to split

A: From the documentation for strtok:

str...
  Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

In other words:
nextToken = strtok(NULL, a);

A: Just call token = strtok( NULL, a );
But you should consider using thread safe strtok_r() instead of strtok(). The man page for both functions includes a good example.


text:
Q: after create a new anaconda envs, matplotlib can't show the figure of code this is my first ask question on the here,Please forgive my poor english.
the code just is simple,I can plot it in colab,but in my pycharm it meet the issue.
enter image description here
somrtime, the figure Crash or no response.
Thanks for the kind people who came to save me,I have wasted an afternoon on it.


text:
Q: Probability of sampling linearly independent vectors Let $q$ be a prime so that $\mathbb{Z}_q$  is a field. I would like to sample $n$ vectors independently and uniformly from $\mathbb{Z}^n_q$, to get a set $V = \{ v_i \}_{i=1}^n$.
What is the probability that $V$ is a basis for $\mathbb{Z}^n_q$? I had the following proof idea, by induction. The problem reduces to what is the probability of sampling $n$ linearly independent vectors, and as such, we proceed by induction on the number of sampled vectors $k$. For $k = 1$, we only require that we are not sampling the zero vector, and as such we have that $\Pr[\{v_1\} \text{is LI} ] = 1 - q^{-n}$. Now let us suppose that we have $k$ linearly independent vectors $\{ v_i \}_{i=1}^k$. We sample a new vector $v_{k+1}$. In order for it to be linearly independent, it must be that it is not a linear combination of the others, and as such there are at most $q^k$ possible 'forbidden' values. Namely these correspond to the possible coefficients $\alpha_i$ of the   linear combinations $\sum_{i=1}^k \alpha_i v_i$. So we have that $\Pr[\{v_i\}_{i=1}^{k+1} \text{is LI} \, | \, \{v_i\}_{i=1}^{k} \text{is LI}] \geq 1 - q^{k - n}$. As such we should have that
$$\Pr[\{v_i\}_{i=1}^n \text{is LI}] = \Pr[\{v_i\}_{i=1}^n \text{is LI} | \{v_i\}_{i=1}^{n-1} \text{is LI}] \Pr[\{v_i\}_{i=1}^{n-1} \text{is LI}] \geq \prod_{i=1}^n (1 - q^{i - n})$$
Do you think this analysis is correct? What I am also interested in is the following generalizations, on which I, unfortunately, had less success.

*

*Suppose we set $n=3k$ and that instead of sampling the vectors independently we sample three matrices $M, M_0, M_1 \in \mathbb{Z}^{3k\times k}_q$ such that each matrix is of full rank. What would be an upper bound on the probability of the columns of said matrices spanning $\mathbb{Z}_q^{3k}$? I have found in the literature (Lemma 8) a claim that it should be at least $1 - \frac{2k}{q}$ but have not found any good argument

*Let us relax the very first statement, and admit that $q$ could be composite. Does this change the argument significantly? I am interested in this result both in the vector case and in the three matrices sample case.

Thank you, I hope the formatting is clear enough :)
For context, I am investigating whether the construction in the linked paper would hold in nonprime order groups.

A: Your analysis is correct. There is possibly a typo: $i$ should be $k$. Moreover, I think it is equality. More precisely, $\{v_i\}_{i=1}^{k+1} \text{is LI} \, | \, \{v_i\}_{i=1}^{k} \text{is LI}$ if and only if $v_{k+1}$ is not a linear combination of $v_1,\ldots,v_k$. The only thing that you need to make sure is that two different linear combinations of $\{v_i\}_{i=1}^{k}$ give rise to two different vectors, which would be true since $\{v_i\}_{i=1}^{k}$ is LI. Thus $\Pr[\{v_i\}_{i=1}^{k+1} \text{is LI} \, | \, \{v_i\}_{i=1}^{k} \text{is LI}] = \frac{q^n-q^k}{q^n}$.
If it is not a field (that is $q$ is composite) then the equality may not hold as two different linear combinations can give you the same vector. To see this take $q=6$, then $v_1=(1,0,0,0,0,0)', v_2=(5,2,0,0,0,0)$, note that here $v_1+v_2 = 4v_1+4v_2=(0,2,0,0,0,0)$.
The inequality that you wrote still holds (after the typo correction:)).
Matrix Case: write $M_0|M_1|M_2$ for the augmented $3k\times 3k$ matrix.
Now $M_0|M_1|M_2 \text{ is LD}$ if one of the columns in $M_1$ is linear combination of columns in $M_0$ or one of the column in $M_2$ is linear combination of columns in $M_0$ and $M_1$. Now probability that a fixed column in $M_1$ is linear combination of columns in $M_0$ is at most $\frac{q^k}{q^{3k}}\leq \frac{1}{q}$, and probability that a fixed column in $M_2$ is linear combination of columns in $M_0$ and $M_1$ is at most $\frac{q^{2k}}{q^{3k}}\leq \frac{1}{q}$. Therefore using union bound
$$
\mathbb{P}(M_0|M_1|M_2 \text{ is LD}) \leq  \frac{2k}{q}.
$$
You can see that this bound holds even if $q$ is not a prime.

A: If I am not mistaken, when $q$ is composite without squares, i.e., $q = \prod_{i = 1}^\kappa p_i$ for distinct primes $p_i$, you can use the Chinese Remainder Theorem to establish the probability that $n$ vectors of $\mathbb{Z}_q^n$ are linearly independent over $\mathbb{Z}_q$.
The reasoning is as follows. I denote by $\theta$ the CRT isomorphism from $\mathbb{Z}_q$ to the direct sum $\oplus_{i = 1}^\kappa \mathbb{Z}_{p_i}$ defined by  $\theta: x\mapsto (x \bmod p_1, \ldots, x \bmod p_{\kappa})$ . We can extend it to vectors coordinate-wise. I denote by $\mathbf{v}_1, \ldots, \mathbf{v}_n$ the vectors over $\mathbb{Z}_q^n$ and $\mathbf{v}_1^i, \ldots, \mathbf{v}_n^i$ their CRT residues over $\mathbb{Z}_{p_i}^n$, i.e, $\theta(\mathbf{v}_j) = (\mathbf{v}_j^1, \ldots, \mathbf{v}_j^\kappa)$. Since $\theta$ is an isomorphism we can prove the following result.
$$(\mathbf{v}_1, \ldots, \mathbf{v}_n) \text{ are }\mathbb{Z}_q\text{-linearly independent} \Leftrightarrow \forall i \in \{1, \ldots, \kappa\}, (\mathbf{v}_1^i, \ldots, \mathbf{v}_n^i) \text{ are }\mathbb{Z}_{p_i}\text{-linearly independent} $$

Proof: First assume that $(\mathbf{v}_1, \ldots, \mathbf{v}_n) \text{ are }\mathbb{Z}_q\text{-linearly independent}$. Let $i \in \{1, \ldots, \kappa\}$. Let $\mu_1, \ldots, \mu_n \in \mathbb{Z}_{p_i}^n$ such that $\sum_{j = 1}^n \mu_j \mathbf{v}_j^i = \mathbf{0} \bmod p_i$. For each $j \in \{1, \ldots, n\}$, define $\lambda_j = \theta^{-1}(0, \ldots, 0, \mu_j, 0, \ldots, 0)$ where $\mu_j$ is at position $i$. Then, we have
$$ \theta\left(\sum_{j = 1}^n \lambda_j \mathbf{v}_j\right) = \left(\mathbf{0}, \ldots, \mathbf{0}, \sum_{j = 1}^n \mu_j \mathbf{v}_j^i, \mathbf{0}, \ldots, \mathbf{0}\right) = (\mathbf{0}, \ldots, \mathbf{0})$$
and thus $\sum_{j = 1}^n \lambda_j \mathbf{v}_j = \mathbf{0} \bmod q$ as $\theta$ is injective. By assumption, we have that each $\lambda_j = 0 \bmod q$ and therefore $\mu_j = 0 \bmod p_i$. This proves the first implication. Reciprocally, assume that for each $i \in \{1, \ldots, \kappa\}$, the $(\mathbf{v}_1^i, \ldots, \mathbf{v}_n^i)$ are $\mathbb{Z}_{p_i}$-linearly independent. Let $\lambda_1, \ldots, \lambda_n \in \mathbb{Z}_q^n$ be such that $\sum_{j = 1}^n \lambda_j \mathbf{v}_j = \mathbf{0} \bmod q$. By applying $\theta$, we get that for all $i$,
$$ \sum_{j = 1}^n (\lambda_j \bmod p_i) \mathbf{v}_j^i = \mathbf{0} \bmod p_i$$
By assumption, it yields that for all $j$ and all $i$, $\lambda_j \bmod p_i = 0$.
Then, for all $j \in \{1, \ldots, n\}$,
$$\lambda_j = \theta^{-1}(\lambda_j \bmod p_1, \ldots, \lambda_j \bmod p_\kappa) = \theta^{-1}(0, \ldots, 0) = 0$$

Then, what you need before concluding is the fact that the CRT residues are independent and random over $\mathbb{Z}_{p_i}$. More precisely, you have that
if $x$ is a random variable is uniformly distributed over $\mathbb{Z}_q$, then the random variables $x \bmod p_1, \ldots, x \bmod p_\kappa$ are independent and uniformly distributed over their respective support $\mathbb{Z}_{p_i}$.

Proof: Take the random variable $x$ that is uniformly distributed over $\mathbb{Z}_q$. Denote by $\mathbf{x} = \theta(x)$ the random vector composed of the $x \bmod p_i$. Since $\theta$ is an isomorphism, it holds that $\mathbf{x}$ is uniformly distributed over $\oplus_{i = 1}^\kappa \mathbb{Z}_{p_i}$. Let $\mathbf{y}$ be the random vector over $\oplus_{i = 1}^\kappa \mathbb{Z}_{p_i}$ such that the coordinates are independent and uniform over each $\mathbf{Z}_{p_i}$ respectively. Let $\mathbf{z} \in \oplus_{i = 1}^\kappa$. It holds that
$$ \mathbb{P}_{\mathbf{x}}[\mathbf{x} = \mathbf{z}] = q^{-1} = \prod_{i = 1}^{\kappa} p_i^{-1} = \prod_{i = 1}^{\kappa} \mathbb{P}_{y_i}[y_i = z_i] = \mathbb{P}_{\mathbf{y}}[\mathbf{y} = \mathbf{z}]$$
Then, $\mathbf{x}$ and $\mathbf{y}$ are identical random vectors, which yields that the coordinates of $\mathbf{x}$ are independent and uniform over each $\mathbb{Z}_{p_i}$.

The second result generalizes to vectors coordinate-wise as well. Now, you can conclude:
\begin{align*}
&\mathbb{P}_{(\mathbf{v}_j)_{1\leq j \leq n}}[(\mathbf{v}_j)_{1\leq j \leq n} \text{ are }\mathbb{Z}_q\text{-linearly independent}] &\\
&= \mathbb{P}_{(\mathbf{v}_j)_{1\leq j \leq n}}[\forall i \in \{1, \ldots, \kappa\}, (\mathbf{v}_j^i)_{1\leq j \leq n} \text{ are }\mathbb{Z}_{p_i}\text{-linearly independent}] &\text{ (first result)}\\
&= \prod_{i = 1}^\kappa \mathbb{P}_{(\mathbf{v}_j^i)_{1\leq j \leq n}}[(\mathbf{v}_j^i)_{1\leq j \leq n} \text{ are }\mathbb{Z}_{p_i}\text{-linearly independent}] &\text{ (second result)} \\
&= \prod_{i = 1}^\kappa \prod_{j = 0}^{n-1} \left(1 - \frac{1}{p_i^{n - j}}\right) &\text{ (result for prime }p_i\text{)}
\end{align*}
This proves the result you want but only for $q$ composite without squares. If you have $q = \prod_{i = 1}^\kappa p_i^{\alpha_i}$, both of the results I used still work but with the residues in $\mathbb{Z}_{p_i^{\alpha_i}}$ which are no longer fields. So if you have the result for any prime power, you can use the same reasoning I did to get the result for all composite $q$.


text:
Q: How to make fabric flush the it's output? I'm using fabric to run ssh tasks on remote machines.
The output isn't flushed automatically, is there a method to force auto flushing?
(the documentation doesn't appear to mention this subject)

A: When using Fabric's puts() to output some text, you can use the flush=True parameter to avoid buffering:
puts('Doing stuff', flush=True)

Or if you're concerned about the output from a remote command, you may want to flush the standard output after running the command:
run('some command')
sys.stdout.flush()

Note that some buffering may still occur in Fabric during execution of the command itself (not sure about it though), or within the remote command itself. In that case, you should see the same behavior when running it through Fabric or directly via SSH.

A: I'm slightly biased because I work there but we came up with a logging utility for fabric named gusset at my workplace. It's named gusset and it allows you to have configurable logging with your fabric scripts
from fabric.api import run
from gusset.output import with_output

@with_output(verbosity=1)
def foo():
    run("ls")

In [9]: with settings(host_string="mybox", user="myuser"):
   ...:     foo()
   ...:
[mybox] run: ls


text:
Q: String variable scope issues? Program:
#include <stdio.h>
main ()
{
    char x[6] = "12345\0";
    char y[6] = "67890\0";
    y[7]='A';
    printf("X: %s\n",x);
    printf("Y: %s\n",y);
}

Program output:
X: 1A345
Y: 67890
The following program defines and prints the two variables x and y and gives the above output.
Would someone please be able to explain to me why the character A appears in the output of x?
I believe this is due to the way memory is handled in C and writing outside of the bounds of y.
I am a computer science student and looking to understand why this happens. Thanks in advance!

A: The memory was probably layed out like this:
6  7  8  9  0 \0 1  2  3  4  5 \0
y                x

And then y[7] is the same as x[1]
Do note that this belongs to the realm of undefined behavior. This means that your code is not required to work that way. Enabling compiler optimizations might change it. When I tried your code in gcc, the behavior went away with -O2 and -O3.
Read more about UB here Undefined, unspecified and implementation-defined behavior


text:
Q: Сompare columns in dataframes and update them I have two DataFrames:
a = [{'name': 'AAA'}, {'name': 'BBB'}, {'name': 'BBB'}, {'name': 'CCC'}, {'name': 'DDD'}, {'name': 'EEE'}]
df = pd.DataFrame(a)
b = [{'name': 'AAA='}, {'name': 'BBB='}, {'name': 'DDD='}]
df = pd.DataFrame(a)
df1 = pd.DataFrame(b)
print(df)
print()
print(df1)

I need to compare values in dataframes in columns name and name2. If the values are equal and the difference is only in the = sign, then add it if the value does not contain it.
I need the following result as in the screenshot:

A: If the = is always in the end, a simple method could be:
# which values of df['name'] are also in df1['name']?
m = df['name'].isin(df1['name'].str.rstrip('='))

# select those and add a "="
df.loc[m, 'name'] += '='

Another approach that works with any position of the =:
s = df1['name'].set_axis(df1['name'].str.replace('=', ''))
df['name'] = df['name'].map(lambda x: s.get(s, x))

updated df:
   name
0  AAA=
1  BBB=
2  BBB=
3   CCC
4  DDD=
5   EEE


text:
Q: firefox: refresh content in a div, but the outside textbox also cleared its content, why? I use jQuery ajax to call a function periodly in order to get latest new store in database. I use a div to display the data tracking from database, however, whenever the div got refreshed, a textbox which outside  tag also got refreshed and the content just disappear. I only find this happened in firefox, everything works in IE. Does anyone know why and how to resolve this issue?
setInterval("Get()", 2000);
function Get() {
        var nickName='<%=nickName %>';
        var from = '<%=to %>';
        var time = '<%=insertTime %>';
        $.post('AjaxPages/Chat.aspx', { "type": "get", "from": from,"nickName":nickName, "insertTime": time }, function(data) {
            if (data.length > 0) {
                $('#contentDIV').html(data);
            }
        });
}

User control HTML(I think might use it as a control so won't double my work in future, the user control is embeded in an empty webpage and called by using $.load() in another webpage):

            <input id="Text1" type="text" />

A: You're not closing the div. This is invalid HTML. Use this:

<input id="Text1" type="text" />


text:
Q: Trying to get triangle numbers The question is "Write a program that duplicates the sample run shown at the bottom , which displays the sum of the first n integers for each value of n from 1 to 10. As the output suggests, these numbers can be arranged to form a triangle and are therefore called triangle numbers
1 = 1
1 + 2 = 3
1 + 2 + 3 = 6
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 4 + 5 = 15
1 + 2 + 3 + 4 + 5 + 6 = 21
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55"

I am able to output 1 2 3 4 5... to 10, but I just can't figure out how to get it to look like the triangle above and make it add the next consecutive number.  I'm assuming that I am missing something very obvious.
import java.util.Scanner;
public class prob3
{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        for (int n = 1; n <= 10; n++) {
            for (int i = n; i <= n; i++){

            System.out.println(n);
        }
    }
}
}

A: Your problem is that you print whole lines just with those numbers.
You print:
1
2
3
But you need something like
1=1
1+2=3
Instead, you need to accumulate the content to be printed, like:
StringBuilder builder = new StringBuilder();
for (int i = n; i <= n; i++) {
  builder.append(n);
  builder.append("+");...
  System.out.println(builder.toString() + "=" + sum);
}

The above is just meant to to get you going; as there are still some things missing that you will have to work with:
A) figuring how to use the StringBuilder to "remember" that part of the previous line that you can reuse!
B) computation of overall sum is missing (as it is in your code, too!)

A: Split the handling of each row into a helper method.
public static void main(String[] args) {
    for (int i = 1; i <= 10; i++) {
        printRow(i);
    }
}

/**
 * Print one row.
 * 1 + 2 + 3 + ... + n = sum
 * @param n the max for this row
 */
private static void printRow(int n) {
    int sum = 0;
    StringBuilder sb = new StringBuilder();

    // 1 through n-1
    for (int i = 1; i < n; i++) {
        // TODO - update the sum
        // TODO - update sb with the number and plus
    }

    // final number n
    // TODO - update the sum
    // TODO - update the sb with the final number, equals, and sum

    // display
    System.out.println(sb.toString());
}


text:
Q: SFML window immediately closes I was following a tutorial on how to make buttons in sfml and then when I ran it, the window immediately closed.I have 2 files, one called main.cpp and the other one called button.h. I cannot find any fix on the internet to fix this issue so how do i fix it?
Here is main.cpp:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <windows.h>
#include "button.h"
using namespace std;
using namespace sf;
int main(){
    bool isStartOpen = false;
    RenderWindow window(VideoMode(500, 500), "Operating System", Style::Close | Style::Resize);
    RectangleShape player(Vector2f(500.0f, 30.0f));
    RectangleShape startMenu(Vector2f(300.0f, 400.0f));
    Texture startTexture;
    if(!startTexture.loadFromFile("startButton.png")){
        MessageBox(NULL, "Error loading image file: startButton.png in the system", "Image File Error", MB_OK | MB_ICONERROR);
    }
    startMenu.setFillColor(Color(0, 0, 0, 200));
    startMenu.setPosition(0.0f, 500.0f);
    player.setFillColor(Color::Black);
    player.setPosition(0.0f, 473.0f);
    Font font;
    if(!font.loadFromFile("buttonFont.ttf")){
       MessageBox(NULL, "Error loading font file: buttonFont.ttf in the system", "Font File Error", MB_OK | MB_ICONERROR);
    }
    Button openNotepad("Open Notepad", {200, 50}, 20, Color::Green, Color::Black);
    openNotepad.setPosition({100, 300});
    openNotepad.setFont(font);
    while (window.isOpen())
    {
        Event event;
        while (window.pollEvent(event))
        {
            switch(event.type){
                case Event::Closed:
                    window.close();
                    cout << "Window has been removed" << endl;
                    break;
                case Event::MouseMoved:
                    if(openNotepad.isMouseOver(window)){
                      openNotepad.setBackColor(Color::White);
                    }else{
                        openNotepad.setBackColor(Color::Green);
                    }
                    break;
                case Event::MouseButtonPressed:
                    if(openNotepad.isMouseOver(window)){
                        cout << "You clicked the button" << endl;
                    }
                    break;
            }
        if(Keyboard::isKeyPressed(Keyboard::Key::S) && !isStartOpen){
            startMenu.setPosition(0.0f, 75.0f);
            isStartOpen = true;
        }else{
            startMenu.setPosition(0.0f, 500.0f);
            isStartOpen = false;
        }
        window.draw(startMenu);
        window.draw(player);
        window.display();
        window.clear(Color(1, 159, 255));
    }
    return 0;
}
}

Code for button.h
#pragma once
#include <iostream>
#include <SFML/graphics.hpp>
using namespace sf;
using namespace std;
class Button{
    public:
        Button(){

        }
        Button(string t, Vector2f size, int charSize, Color bgColor, Color textColor){
            text.setString(t);
            text.setColor(textColor);
            text.setCharacterSize(charSize);
            button.setSize(size);
            button.setFillColor(bgColor);
        }
        void setFont(Font &font){
            text.setFont(font);
        }
        void setBackColor(Color color){
            button.setFillColor(color);
        }
        void setTextColor(Color color){
            text.setColor(color);
        }
        void setPosition(Vector2f pos){
            button.setPosition(pos);
            float xPos = (pos.x + button.getLocalBounds().width / 3) - (text.getLocalBounds().width / 2);
            float yPos = (pos.y + button.getLocalBounds().height / 4) - (text.getLocalBounds().height / 2);
            text.setPosition({xPos, yPos});
        }
        void drawTo(RenderWindow &window){
            window.draw(button);
            window.draw(text);
        }
        bool isMouseOver(RenderWindow &window){
            float mouseX = Mouse::getPosition(window).x;
            float mouseY = Mouse::getPosition(window).y;
            float btnPosX = button.getPosition().x;
            float btnPosY = button.getPosition().y;
            float btnxPosWidth = button.getPosition().x + button.getLocalBounds().width;
            float btnyPosWidth = button.getPosition().y + button.getLocalBounds().height;
            if(mouseX < btnxPosWidth && mouseX > btnPosX && mouseY < btnyPosWidth && mouseY > btnPosY){
                return true;
            }

There are no errors in the program so how do i fix the problem?

A: You put return 0; in while(window.isOpen()), so your program closes the window immediately, put return 0; outside the while loop.


text:
Q: Open file from network drive I'm trying to create hyperlinks to open files from network drive G:
This is part of my testing servlet:
@WebServlet(name="fileHandler", urlPatterns={"/fileHandler/*"})
public class FileServlet extends HttpServlet
{
  private static final int DEFAULT_BUFFER_SIZE = 10240; // 10KB.
  ...
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    String requestedFile = request.getPathInfo();
    ...
    File file = new File("G:/test_dir", URLDecoder.decode(requestedFile, "UTF-8")); // cesta se nacita v kazdem doGet
    String contentType = getServletContext().getMimeType(file.getName());

    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setContentType(contentType);
    response.setHeader("Content-Length", String.valueOf(file.length()));
    response.setHeader("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"");
    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try
    {
      input = new BufferedInputStream(new FileInputStream(file), DEFAULT_BUFFER_SIZE);
      output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
      byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int length;
      while ((length = input.read(buffer)) > 0)
      {
        output.write(buffer, 0, length);
      }
    }
    finally
    {
      close(output);
      close(input);
    }
  }
}

My HTML component:
TEST FILE

Network drive is mapped on application server as G:\
Everything is working fine on my localhost application server. I'm able to open file from local drive C: and even from the same network drive G:.
When I start the JSF application on real server, I'm able to open files from local drive only. Not from G: drive.
I've tried to simple JAVA application (to find if java instance has an access to network drive) and it works on both (server and dev.PC):
public class Test
{
  static void main(String[] args)
  {
    String path = "G:/test_dir/test.txt";
    File file = new File(path);
    System.err.println(file.exists() ? "OK" : "NOK");
  }
}

I've tried different URI schemes:

*

*G:/test_dir

*G:\\test_dir
And following doesn't work at all:

*

*file://server/g:/test_dir

*///server/g:/test_dir

*\\\\server\\g\\test_dir ---> in fact, this should work

Where should be a difference between my develop PC and application server?
SOLUTION:
I've found that links to network drive doesn't work in standalone Tomcat, but works in Eclipse + Tomcat, so I have to use complete URI:

*

*Case Eclipse + Tomcat: Path G:/test_dir/test.txt works

*Case Standalone Tomcat: Path \\\\server\\g\\test_dir\\test.txt works

A: If you can debug your server and look at the logs, try this:
String requestedFile = request.getPathInfo();
log.debug('requestedFile='+requestedFile);
String decodedFilename = URLDecoder.decode(requestedFile, "UTF-8");
log.debug('decodedFilename='+decodedFilename);

File dir = new File("G:/test_dir");
log.debug('File g:/test_dir is a dir:'+dir.isDirectory());

File file = new File(dir, decodedFilename);
log.debug('requested file = '+file.getAbsolutePath());
log.debug('file exists = '+file.isFile());

If you do not have a logging framework set up, you can use System.out.println() instead of log.debug(), but that's not recommended for production use.
This won't solve your problem, but you'll be able to see what's going on.

A: I've found that links to network drive doesn't work in standalone Tomcat, but works in Eclipse + Tomcat, so I have to use complete URI:

*

*Case Eclipse + Tomcat: Path G:/test_dir/test.txt works

*Case Standalone Tomcat: Path \\\\server\\g\\test_dir\\test.txt works


text:
Q: SSRS Background Color Expression Error I am trying to make an expression which will make the background color change based on FileType and the DriveLetter associated with the FileType. When I preview the report, this error appears:

Warning   1   [rsRuntimeErrorInExpression] The BackgroundColor expression
  for the text box 'Physical_Name' contains an error: Input string was
  not in a correct format.

Does this mean there is a issue with the datatype for this column or does anyone see something wrong with the expression i used?
Here is the expression:
=Switch(((Fields!DriveLetter.Value = "F") OR (Fields!DriveLetter.Value = "T")) AND (Fields!FileType.Value = "MDF"), "Lime",
        ((Fields!DriveLetter.Value = "F") OR (Fields!DriveLetter.Value = "T")) AND (Fields!FileType.Value = "LDF"), "Red")

Thanks.

A: Try using the below expression:
=IIF(Fields!FileType.Value = "MDF" AND (Fields!DriveLetter = "F" OR Fields!DriveLetter = "T"),"LIME",IIF(Fields!FileType.Value = "LDF" AND (Fields!DriveLetter = "F" OR Fields!DriveLetter = "T"),"RED",""))


text:
Q: Basic Database design question - 1 attribute three Entities Please can someone clarify something which I should really know by now?
If I have Three Entitys Organisation, Director and Company secretary and each have the attribute primary address.
If I were modelling a conceptual ERD should I have the attribute 'primary address' separately in each entity or should I model a fourth entity Address, add primary address and have them all PK > FK to that?
Have since found this link Is this a good way to model address information in a relational database? which pretty much covers everything I need to know.

A: I would do something like this, assuming primary address refers to the Organization location:
Table: Organization
Org_Key {PK},
Org_Name,
Primary Address fields,
Any other fields
Table: Personnel
Person_Key {PK},
Org_Key {FK},
Position {Directory, secretary, etc},
Any other fields
In my opinion, there is really no need to separate those who are "Directors" from those who are "secretaries" because they are both employees of a specific Organization.
Now, if by primary address you mean a personal address (i.e., an individuals home address) then I would add additional fields to the Personnel table.


text:
Q: How To Make Onboarding/Intro Slides only Appear on Initial Login How can I make it so my intro onboarding instructions only appear when a user first logs into the application. Each time after, it will go straight to the regular login. Using Xcode 9, Swift 4 or previous.

A: All you need is a single Bool stored in UserDefaults. Check out this post.


text:
Q: CSS background (svg/base64) gets stretched horizontally upon orientation change I am trying to make a Phonegap application using HTML/CSS3/Jquery and JS.
I have made certain divs which have a background image (a css embedded base-64 encoded svg image). However, this background image gets stretched upon device orientation change. (from portrait to landscape).
i have set the following css properties:
#top-bar #settings {
    background: url(data:image/svg+xml;base64,[image_data]) no-repeat;
    background-size: 50% 50%;
    background-position: center;
    width: 10%;
    height: 100%;
    position: relative;
    float: right;
    right: 0;
}

I have also observed that this behaviour is not visible in my desktop browsers or in certain other Android phones. My phone (where i see the problem is a Galaxy s3 rooted with cyanogen 10.1.3)
Is there any way to stop this from happening? I want the background to look same in any conditions.

A: It seems you are using a single styling for both portrait/landscape orientations, that refer to viewport size in a relative way.
I would use media queries to detect orientation, and define specific styling to perform a fine tuning of the background look according to it.
Something like (check actual syntax):
@media (orientation: portrait){
  #top-bar #settings {
    /* Portrait styling */
  }
}

@media (orientation: landscape){
  #top-bar #settings {
    /* Landscape styling */
  }
}

Hope it helps.

A: The problem are the relative attributes.
background-size: 50% 50%;

width: 10%;
height: 100%;

Those give you different total sizes if the screens width & height is changing without keeping the aspect ratio!
Just keep the background width size at 50%. If no second size is set, it has the initial value "auto", which keeps the aspect ratio of the image.
background-size: 50%;

This should solve your problem.


text:
Q: Clique problem for regular graphs I am looking for NP complete results for cliques in regular graphs. For example is the general problem of determining if a regular graph on n vertices has an n/2 clique NP-complete? (obviously the question is interesting only if the degree is at least n/2). You could also ask the same question for say regular graphs of degree 3n/4.

A: Let $G = (V,E)$ be a graph and $c ≤ |V |$ a positive integer. The independent sets of $G$ are precisely the cliques of the complementary graph $\overline{G}$.
INDEPENDENT SET
INSTANCE: Graph $G=(V,E)$, positive integer $c$.
QUESTION: Does $G$ contain an independent set of size $c$ or more,
The independent set problem remains NP-complete when restricted to
3-regular planar graphs.
Reference:
COMPUTERS AND Intractability, A Guide to the Theory of NP-Completeness
Michael R. Garey / David S. Johnson
page 194-195


text:
Q: What's wrong with my C code(My output is volatile because of malloc)? I SOMETIMES get errors when executing this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int digits(int n){
    int count = 0;
    while(n!=0)
    {
        n/=10;             /* n=n/10 */
        ++count;
    }
    return count;
}

int fib(int n){
    int r;
    if(n == 1 || n == 0)
        return 0;
    else if(n == 2)
        return 1;
    r = fib(n-1) + fib(n-2);
    return r;
}

void function(void){
    char* test;     //number you want to scan
    int* table;
    int length, length2, test2 = 0, number, l, random = 0, j = 1, buffer;
    test = malloc(sizeof(test));
    table = malloc(sizeof(table));
    scanf("%s", test);
    number = atoi(test);
    length = strlen(test);      //length of input test number
    while(test2 < length + 1){
        printf("fib(%d) = %d\n", j, fib(j));
        buffer = table[j - 1] = fib(j);
        test2 = digits(buffer);
        j++;
    }
    //input size of "table" into "length2"
    length2 = j - 1;
    for(l = 0; l < length2; l++){
        if(table[l] == number){
            printf("YES\n");
            random = 1;
            break;
        }
    }
    if(random == 0)
        printf("NO\n");
    free(table);
    free(test);
}

int main(void){
    int num, i;
    scanf("%d", &num);

    for(i=0; i < num; i++){
        function();
    }
    return 0;
}

And this is the output:
3
2
fib(1) = 0
fib(2) = 1
fib(3) = 1
fib(4) = 2
fib(5) = 3
fib(6) = 5
fib(7) = 8
fib(8) = 13
YES
*** Error in `./Am_I_a_Fibonacci_Number': free(): invalid next size (fast): 0x08384018 ***
Aborted (core dumped)

First number is to count how much input the user wants, (in this case 3) and the 2nd(in this case, 2nd, 3rd and 4th) number is the number you want to test whether its a Fibonacci number or not.
Sorry if this is very hard-to-read code, I have a lot to learn.

A: You are not allocating enough memory, thus you corrupt the heap. sizeof() applied on a pointer (as in your program) usually results in 4 or 8, depending on the architecture. Obviously, this might just be enough for test, but is definitely too little for table.
You need to figure out how much memory you really need, and use this as argument in malloc.

A: test = malloc(sizeof(test));
table = malloc(sizeof(table));

"test" is a variable of type char*. Such a variable has typically a size of 4 or 8 bytes. So you allocate memory for 4 or 8 bytes, which is enough for 4 or 8 chars.
"table" is a variable of type int*. Again, typically 4 or 8 bytes. Allocating 4 or 8 bytes is usually enough for 1 or two int's. If you try to store more, things will go badly wrong.
Figure out how many chars and ints you want to allocate, then call for example table = malloc (required_elements * sizeof (int)).


text:
Q: Pulling Data from JSON file coded in PHP I've pieced the below together from various articles and tutorials but I'm very very new to PHP, JSON, and Javascript.
I have a div with id "playerName" that I need to update every 10 seconds.
Questions:
1) I'm doing it "right" or is there an easier way?
2) If I want to update 2 different divs with different values from the JSON file do I just duplicate the full "ajax_get_json" function?
My json file (aka: data.php):
<?php
header("Content-Type: application/json"); // set the content type to json
$jsonData = '{
    "u1":{ "name":"Bob", "age":"25", "country":"United States" }
}';
echo $jsonData;
?>

My html file:
<!DOCTYPE html>

I'm almost over my head and buried in google searches. Any help is appreciated!
Most of the code has come from Adam Khoury's tutorial series: https://youtu.be/wbB3lVyUvAM

A: Avoid building json by hand, it error prone just encode your native data type into json
$data = [
    "u1"=>[ "name"=>"Bob", "age"=>"25", "country"=>"United States" ]
];
echo json_encode($data);

Don't set the content type header for GET requests, you can't actually a content body in a GET request(via XMLHttpRequest). You may be mixing up the response content type with the request?
There is a value you can set for what you expect the response to be, its responseType.
If you want to update more divs just put the data to do it in the response.
<?php
header("Content-Type: application/json"); // set the content type to json
$data = [
    "u1"=>[ "name"=>"Bob",    "age"=>"25", "country"=>"United States" ],
    "u2"=>[ "name"=>"Marley", "age"=>"11", "country"=>"of Jamaica" ]
];
echo json_encode($data);

function ajax_get_json(){
    // Create our XMLHttpRequest object
    var results1 = document.getElementById("player1Name");
    var results2 = document.getElementById("player2Name");
    var hr = new XMLHttpRequest();
    // Create some variables we need to send to our PHP file
    hr.open("GET", "data.php", true);
    // Set response type so the browser knows what to expect and parses it for you
    hr.responseType = 'json';
    // Access the onreadystatechange event for the XMLHttpRequest object
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = this.response;
            results1.innerHTML = data['u1'].name;
            results2.innerHTML = data['u1'].name;
            setTimeout(ajax_get_jsonStatus, 10000);
        }
    }
    // Send the data to PHP now... and wait for response to update the status div
    hr.send(null); // Actually execute the request
}


text:
Q: Freeze arrays and hashes by default? Just wondering if something like:
# frozen_string_literal: true
exists but for Array and Hash?
The goal is not having to .freeze every single of those within the same globals file.

A: I didn't find any library that monkey patches default ruby classes like Array or Hash. But I found an interesting gem immutable-ruby that may fit your needs
Simple example
require "immutable/hash"

person = Immutable::Hash[name: "Simon", gender: :male]
# => Immutable::Hash[:name => "Simon", :gender => :male]

and you cannot just modify values of it, cause it is immutable. You can perform some actions on that hash, but new copy will be returned to you
friend = person.put(:name, "James") # => Immutable::Hash[:name => "James", :gender => :male]
person                              # => Immutable::Hash[:name => "Simon", :gender => :male]
friend[:name]                       # => "James"
person[:name]                       # => "Simon"

A: Found a way to handle it without using another gem using only vscode and rubocop :

*

*Install the rubocop extension on vscode

*Open your .vscode/settings.json

*Append those rules :

{
  "editor.formatOnSave": true,
  "editor.formatOnSaveTimeout": 5000,
  "ruby.format": "rubocop"
}

*save

*enjoy

Thanks to Tom Lord for the hint.


text:
Q: Partition by Range ERROR 1491 (HY000): The PARTITION function returns the wrong type I am trying to partition a table by range. The column is type float. I know partitions do not work with float so I thought using a FLOOR() function would allow it to work see code below

 ALTER TABLE tester_full
    -> PARTITION BY RANGE (FLOOR(Alt))
    -> (
    -> PARTITION p200 VALUES LESS THAN (FLOOR(300.0)),
    -> PARTITION p300 VALUES LESS THAN (FLOOR(400.0))
    -> );

However when I run this I get the following error ERROR 1491 (HY000): The PARTITION function returns the wrong type
Can someone show me how to partition a column that has type float or what this error means?

A:  ALTER TABLE tester_full
    -> PARTITION BY RANGE (CAST(Alt AS UNSIGNED INTEGER))
    -> (
    -> .....
    -> PARTITION p200 VALUES LESS THAN (300),
    -> PARTITION p300 VALUES LESS THAN (400),
    -> .....
    -> PARTITION pMAX VALUES LESS THAN MAXVALUE
    -> );


text:
Q: HTML in the input field value How can I get HTML to work in the value of the input field ?   If you include HTML in the value, it appears as pure text.  Is there a way to do something like this?
<input type='text' value='tekst'></input>

So the the output is:
tekst
instead of
tekst
I think that was bad example... I want every appropriate HTML tag to work.  If i want to include an image, the image appears in the input, if i want to add a  tag ... the text should appear as a link linked.

A: You have to encode all the HTML you want in the value and paste it in the  input value.
If you encode this:
"http://sansoftmax.blogspot.com/"

It will look like this:
"http://sansoftmax.blogspot.com/"

In input:
value=""http://sansoftmax.blogspot.com/""

Online Html Encoder/Decoder

A: You can try to decode you entities from your postvalue.
In PHP you can do this with html_entity_decode();

A: I'm not sure from your question whether you are trying to make the value contain HTML, or whether you want to apply HTML to something inside the input.
If you want to be able to set the value to some HTML, like <input value="Some HTML"> where the value will actually show the HTML, you need to encode the HTML brackets like <input value="<b>Some text<b/>">. There are functions available to do this for you automatically in most scripting languages (e.g. htmlentities() in PHP).
If you want to apply HTML to the input value, short answer is... you can't. If you want formatting on there, you could use the contentEditable attribute in HTML5 which lets you just edit-in-place (think Flickr headers).
If you just want a standard input field to be styled, you can just use CSS like the other answers suggested.

A: I don't think you can put HTML inside a text field and have it interpreted as HTML instead of as text in the field.
To accomplish what you want you'll have to use CSS.  An in-line example to bold the text as you cited in your example:
<input type="text" style="font-weight: bold;" value="tekst" />

A: Try CSS:
input[type=text] {
    font-weight: bold;
}


text:
Q: Mapbox gl js bearing auto reset to zero Mapbox gl js default rotate behavior is following: when user stop rotating map with bearing value close to zero (+-5deg) then map will auto correct bearing value to zero. My question is: how to disable this behavior?

A: According to the documentation, the default is 7 degrees. You should be able to set it to zero (ie, no automatic snap) by doing this:
var map = new mapboxgl.Map({
   ...
   bearingSnap: 0
});


text:
Q: Mailing a tar.gz file How would I use the mail command, without the mutt utility, to send a tar.gz file.
The Mail utility works on the command line, however it asks me who to cc and the text on the terminal page. It also requires me to ctr D to send a mail. How would I avoid this in a script?

A: This question has sort of been answered already...
https://stackoverflow.com/questions/17359/how-do-i-send-a-file-as-an-email-attachment-using-linux-command-line
Based on the answers I've seen above though it doesn't deal with the CC part though. Basically, you just need to add a "-c ccaddress@emailaddress.com" option.
cat message.txt | mail -s "Backup" -a file.tar.gz backup@email.com -c ccaddress@emailaddress.com

Stick it in a script file and it that will be the basis for further automation.

A: You cat some sort of message file to the mail utility.
cat mailbody.txt | mail -A yourfile.tgz -s "your mail subj line" email@to.send.to

Note that contrary to previous answer at least in Ubuntu mail utility you specify attachments by -A. -a is used to add extra headers.


text:
Q: Which is economical for getting Date in String format? creating date objects every time or using date instance thru calendar object I have a requirement to get current time often and covert that to string and stamp it into a file or as a file name based on business. I have learnt that creating many objects deters the performance.
Now I have two methods to do it, first by creating a Date object every time to get current time.
//Using Date object
SimpleDateFormat sdf = new SimpleDateFormat("MMDDHHmm");
String timeNow = sdf.format(new Date());
System.out.println(timeNow);

Second is to create a Calendar object and get date instance by using getTime() method.
//Using Calendar object to get date instance
SimpleDateFormat sdf = new SimpleDateFormat("MMDDHHmm");
Calendar cal = new GregorianCalendar();
String timeNow = sdf.format(cal.getTime());
System.out.println(timeNow);

which method yields better performance in terms of time and memory used? If there is any other method that'll be more efficient than these two please do share

A: Creating a Calendar object is a relatively slow and complex action, it has to compensate for all the oddities that are inherent to dates and times such as timezones, daylight savings etc.
Your best bet is to use the Date object as your first example, see here for a comparison on performance metrics of Date, Calendar and SimpleDateFormat.
Another approach could be to use JodaTime, see here for performance comparison between JodaTime and Calendar. Whilst the difference between Java Date and JodaTime is probably negligible in performance terms, JodaTime is generally agreed to be a better way of handling dates and times. For your purpose, importing JodaTime just for a timestamp may well be overkill though.

A: The first one is faster, but it's so little that you should use whatever code looks more appealing to you. The Calendar will create a new Date as well, and base it on the current time, just like your first code except in many more methods calls.

A: If you need improved speed maybe in synchronization or database handling, the best way is to use JodaTime Library, it is 5 times faster than SimpleDateFormat.


text:
Q: Получить русские слова Python. Необходимо получить массив русских слов (не обязательно актуальных и всех). Видел вот это:
https://github.com/danakt/russian-words
Но моих знаний программирования недостаточно, чтобы как-то с этим связать.

A: Для этого нам нужно будет установить библиотеку requests через pip. Команда:
pip install requests

Если у вас нету pip, скачайте его следуя инструкции на официальном сайте PyPI.
А теперь дело за кодом. Так как у нас ссылка ведет на Raw версию файла на GitHub, то с помощью запроса мы попробуем получить его содержимое:
# Импортируем библиотеку с помощью которой будем выполнять запрос
import requests

# Выполняем запрос с помощью которого мы получим слова и фамилии
first_reply = requests.get('https://raw.githubusercontent.com/danakt/russian-words/master/russian.txt')
second_reply = requests.get('https://raw.githubusercontent.com/danakt/russian-words/master/russian_surnames.txt')

Итак, содержимое есть, но тут присутствует одна ма-а-аленькая проблема. Все содержимое закодировано в формат Windows-1251. Значит, будем декодировать в привычный для нас формат:
# Декодируем их, так как используется кодировка "windows-1251"
russian_words = first_reply.content.decode('cp1251')
russian_surnames = second_reply.content.decode('cp1251')

Декодировали, осталось их в массив запихнуть. У переменных формата str есть функция splitlines. Она переводит все строки в один список по порядку. А ниже её применение:
# Преобразовываем все строки в один лист
list_words = russian_words.splitlines()
list_surnames = russian_surnames.splitlines()

Готово! Вот так легко мы получили список русских слов и фамилий. Если будут еще вопросы задавайте их в комментарии.


text:
Q: Compilation error in shaders Hi I am writing a program using shaders and getting some error while compiling shaders. Following are my shader string
const GLchar* vertexShaderCode =                               \
    "#verison 140                                      \n" \
    "in vec4 a_Position;                               \n" \
    "uniform   mat4 u_MVPMatrix;                       \n" \
    "void main()                                       \n" \
    "{                                                 \n" \
    "    gl_Position = u_MVPMatrix * a_Position;       \n" \
    "}                                                   ";\

const GLchar* fragmentShaderCode =                             \
    "#verison 140                                      \n" \
    "uniform vec4 u_Color;                             \n" \
    "out vec4 fragmentColor;                           \n" \
    "void main()                                       \n" \
    " {                                                \n" \
    "  fragmentColor = u_Color;                        \n" \
    " }

Following is my code to load initialize shader objects
GLuint MtShader::LoadShader(int type, const GLchar* shaderCode)
{
    GLuint shader = glCreateShader(type);

    // Add the source code to the shader and compile it
    glShaderSource(shader, 1, &shaderCode, NULL);
    glCompileShader(shader);

    GLint  compiled;
    glGetShaderiv( shader, GL_COMPILE_STATUS, &compiled );
    if ( !compiled ) {
        std::cerr << " failed to compile:" << std::endl;
        GLint  logSize;
        glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &logSize );
        char* logMsg = new char[logSize];
        glGetShaderInfoLog( shader, logSize, NULL, logMsg );
        std::cerr << logMsg << std::endl;
        delete [] logMsg;

        exit( EXIT_FAILURE );
    }

    return shader;
}

void MtShader::CompileShader(const GLchar* vertexShaderCode, const GLchar* fragmentShaderCode)
{
    // Load the shaders.
    int vertexShader      = LoadShader(GL_VERTEX_SHADER,   vertexShaderCode);
    int fragmentShader    = LoadShader(GL_FRAGMENT_SHADER, fragmentShaderCode);

    // Create the program.
    m_Program = glCreateProgram();             // Create empty shader Program.
    glAttachShader(m_Program, vertexShader);   // Add the vertex shader to program.
    glAttachShader(m_Program, fragmentShader); // Add the fragment shader to program.
    glLinkProgram (m_Program);                 // links the shader program.

    GLint  linked;
    glGetProgramiv( m_Program, GL_LINK_STATUS, &linked );
    if ( !linked ) {
        std::cerr << "Shader program failed to link" << std::endl;
        GLint  logSize;
        glGetProgramiv( m_Program, GL_INFO_LOG_LENGTH, &logSize);
        char* logMsg = new char[logSize];
        glGetProgramInfoLog( m_Program, logSize, NULL, logMsg );
        std::cerr << logMsg << std::endl;
        delete [] logMsg;

        exit( EXIT_FAILURE );
    }

    glUseProgram(m_Program);
}

When I compile this shader, it does compile successfully. I checked the shader log using glGetShaderInfoLog. It gives following error
ERROR: 0:1: '' :   Invalid Directive verison
ERROR: 0:1: '' : syntax error: unexpected tokens following preprocessor directive - expected a newline
ERROR: 0:6: 'u_MVPMatrix' : undeclared identifier
ERROR: 0:6: 'a_Position' : undeclared identifier
ERROR: 0:6: 'assign' :  cannot convert from 'float' to 'Position 4-component vector of float'

PS.   I am creating opengl 3.1 context. Any help ??


text:
Q: How to set graph (and not figure !) size in matplotlib I am trying to get a graph in which the square dots touch each other without overlapping. For that, I need a defined graph size so I can adapt my squares' size.
The problem is that I found a lot of ways to control the figure( graph + axes, labels and title) size, but not the graph size itself.
Just so you know, my graph represents dots in some defined position that colors depends on the corresponding value in the matrix (I wish I could send an example, but I do not have enough reputation it seems...)
Thank you,

A: You can control the axes size within the figure using add_axes:
import matplotlib.pyplot as plt

fig = plt.figure()
fig.add_axes([0.1,0.1,0.5,0.5])
plt.show()

Where the argument to add_axes is rect = l,b,w,h and the units are the fraction of the figure size.
However, if you're trying to get squares that touch but don't overlap, you may want to use imshow:
z = [[5,2,7],[8,1,5],[3,4,10]]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(z,extent=[3,6,6,9],interpolation='none')

plt.show()


text:
Q: Deleting an Item from one list using indexWhere() when presisng a button on an item from a different list Flutter So far I have declared a FavoriteItems class like so:
enum Type {
  a,
  b,
  c,
}

class FavoriteItem {
  final String id;
  final String itemType;
  final String title;
  final String icon;
  final String item;
  final Type type;

  FavoriteItem({
    required this.id,
    required this.itemType,
    required this.title,
    required this.icon,
    required this.item,
    required this.type,
  });

  FavoriteItem copyWith({
    String? id,
    String? itemType,
    String? title,
    String? icon,
    String? item,
    Type? type,
  }) {
    assert(tags != null);
    return FavoriteItem(
      id: id ?? this.id,
      itemType: itemType ?? this.itemType,
      title: title ?? this.title,
      icon: icon ?? this.icon,
      item: item ?? this.item,
      type: type ?? this.type,
    );
  }
}

And have succesfully implemented a manager to add items from other lists to this list, and from the favorites screen to be able to safely delete it... buuut, On the screen where the items to be favorited are I run into the problem of not being able to write the propper getter to be able to remove this element from the favorites list when clicking again on the heart icon.
IconButton(
              onPressed: () {
                if (_isFavorite == false) {
                  setState(() {
                    _isFavorite = true;
                  });
                  final manager =
                      Provider.of<FavoritesManager>(context, listen: false);
                  manager.addItem(
                    FavoriteItem(
                        id: widget.mitem.id,
                        itemType: widget.mitem.itemType,
                        title: widget.mitem.title,
                        icon: widget.mitem.icon,
                        item: widget.mitem.item,
                        type: Type.a),
                  );
                }
                if (_isFavorite == true) {
                  setState(() {
                    _isFavorite = !_isFavorite;
                  });
                  final manager =
                      Provider.of<FavoritesManager>(context, listen: false);

                  manager.deleteItem(favoriteItem
                      .indexWhere(widget.mitem.id = favoriteItems.id));
                }
              },
              icon: Icon(_isFavorite ? Icons.favorite : Icons.favorite_border),
            )

I have tried things like
final FavoriteItem favoriteitem

And
final _favoriteItems = <FavoriteItem>[];

  List<FavoriteItem> get favoriteItems => List.unmodifiable(_favoriteItems);

But they all either show errors at the very "getter" line or later mention that the favoriteitem does not have an id declared.
My question is, how do I properly call for the favorite items list so as to be able to use the indexwhere method to successfully remove the item from the favorites list?
I am of course a complete begginner

A: for removing an item from your favelist you can write manager.removeWhere((element) => element.id == widget.mitem.id);

A: I would suggest rethinking the data structures you are using rather than trying to delete an item from a List using indexWhere. If you use a Set instead of a List to track which of the items have been favorited, you can delete an item in O(1) by simply calling the remove method. Whereas indexWhere on a List will be O(n).
Try this demo:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider<FavoritesManager>.value(
          value: FavoritesManager(),
        ),
      ],
      child: const MaterialApp(
        home: FavoritesPage(),
      ),
    ),
  );
}

class FavoritesPage extends StatelessWidget {
  const FavoritesPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer<FavoritesManager>(
      builder: (context, manager, child) => Scaffold(
        appBar: AppBar(
          title: const Text('Favorites Page'),
        ),
        body: Column(
          children: [
            for (final item in manager.items)
              ListTile(
                title: Text(item.title),
                leading: Text(item.icon),
                trailing: IconButton(
                  onPressed: () => manager.isFavorite(item)
                      ? manager.removeFavorite(item)
                      : manager.addFavorite(item),
                  icon: Icon(
                    manager.isFavorite(item)
                        ? Icons.favorite
                        : Icons.favorite_border,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }
}

class FavoritesManager extends ChangeNotifier {
  // favorites contains only those items that have been marked
  // as a favorite.
  final Set<Item> _favorites = {};

  // _items contains all of the items whether they have been
  // marked as favorite or not.
  // The list has been populated with some example data.
  final List<Item> _items = const [
    Item(
      id: '0',
      itemType: 'A Type',
      title: 'A Title',
      icon: 'A Icon',
      item: 'A Item',
      type: Type.a,
    ),
    Item(
      id: '1',
      itemType: 'B Type',
      title: 'B Title',
      icon: 'B Icon',
      item: 'B Item',
      type: Type.b,
    ),
    Item(
      id: '2',
      itemType: 'C Type',
      title: 'C Title',
      icon: 'C Icon',
      item: 'C Item',
      type: Type.c,
    ),
  ];

  List<Item> get items => List<Item>.unmodifiable(_items);

  bool isFavorite(Item item) {
    return _favorites.contains(item);
  }

  void addFavorite(Item item) {
    _favorites.add(item);
    notifyListeners();
  }

  void removeFavorite(Item item) {
    _favorites.remove(item);
    notifyListeners();
  }
}

enum Type {
  a,
  b,
  c,
}

// renamed FavoriteItem to Item to be less confusing,
// since not every item will be favorited.
class Item {
  final String id;
  final String itemType;
  final String title;
  final String icon;
  final String item;
  final Type type;

  const Item({
    required this.id,
    required this.itemType,
    required this.title,
    required this.icon,
    required this.item,
    required this.type,
  });

  Item copyWith({
    String? id,
    String? itemType,
    String? title,
    String? icon,
    String? item,
    Type? type,
  }) {
    return Item(
      id: id ?? this.id,
      itemType: itemType ?? this.itemType,
      title: title ?? this.title,
      icon: icon ?? this.icon,
      item: item ?? this.item,
      type: type ?? this.type,
    );
  }

  // Add == and hashCode so that this class can be used
  // in data structures that use hashing such as Set.
  @override
  bool operator ==(Object other) {
    return other is Item && id == other.id;
  }

  @override
  int get hashCode => id.hashCode;
}


text:
Q: I've made a slight mistake in my .htaccess and now i cannot access my page anymore To be more specific, i changed my php_value memory_limit accidently to 20GB while i was changing the maximum upload and post sizes. I changed it back to what it was 512MB but my page is still giving me a HTTP ERROR 500.
Anyone got any ideas what i'm missing?
This is my .htaccess
<IfModule mod_headers.c>
  <IfModule mod_setenvif.c>
    <IfModule mod_fcgid.c>
       SetEnvIfNoCase ^Authorization$ "(.+)" XAUTHORIZATION=$1
       RequestHeader set XAuthorization %{XAUTHORIZATION}e env=XAUTHORIZATION
    </IfModule>
    <IfModule mod_proxy_fcgi.c>
       SetEnvIfNoCase Authorization "(.+)" HTTP_AUTHORIZATION=$1
    </IfModule>
  </IfModule>

  <IfModule mod_env.c>
    # Add security and privacy related headers
    Header set X-Content-Type-Options "nosniff"
    Header set X-XSS-Protection "1; mode=block"
    Header set X-Robots-Tag "none"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-Download-Options "noopen"
    Header set X-Permitted-Cross-Domain-Policies "none"
    SetEnv modHeadersAvailable true
  </IfModule>

  # Add cache control for CSS and JS files
  <FilesMatch "\.(css|js)$">
    Header set Cache-Control "max-age=7200, public"
  </FilesMatch>
</IfModule>
<IfModule mod_php5.c>
  php_value upload_max_filesize 5G
  php_value post_max_size 5G
  php_value memory_limit 512MB
  php_value mbstring.func_overload 0
  php_value always_populate_raw_post_data -1
  php_value default_charset 'UTF-8'
  php_value output_buffering 0
  <IfModule mod_env.c>
    SetEnv htaccessWorking true
  </IfModule>
</IfModule>
<IfModule mod_php7.c>
  php_value upload_max_filesize 5G
  php_value post_max_size 5G
  php_value memory_limit 512MB
  php_value mbstring.func_overload 0
  php_value default_charset 'UTF-8'
  php_value output_buffering 0
  <IfModule mod_env.c>
    SetEnv htaccessWorking true
  </IfModule>
</IfModule>
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
  RewriteRule ^\.well-known/host-meta /public.php?service=host-meta [QSA,L]
  RewriteRule ^\.well-known/host-meta\.json /public.php?service=host-meta-json [QSA,L]
  RewriteRule ^\.well-known/carddav /remote.php/dav/ [R=301,L]
  RewriteRule ^\.well-known/caldav /remote.php/dav/ [R=301,L]
  RewriteRule ^remote/(.*) remote.php [QSA,L]
  RewriteRule ^(?:build|tests|config|lib|3rdparty|templates)/.* - [R=404,L]
  RewriteCond %{REQUEST_URI} !^/.well-known/acme-challenge/.*

This is my error log
[Sun Sep 10 16:37:08.095999 2017] [proxy_fcgi:error] [pid 634:tid 1974465584] [client 212.238.239.196:56997] AH01071: Got error 'PHP message: PHP Fatal error:  Allowed memory size of 2097152 bytes exhausted (tried to allocate 65536 bytes) in /var/www/nextcloud/lib/composer/composer/ClassLoader.php on line 412\n'
[Sun Sep 10 16:38:14.788907 2017] [mpm_event:notice] [pid 632:tid 1995735040] AH00491: caught SIGTERM, shutting down
[Sun Sep 10 16:38:15.055829 2017] [ssl:warn] [pid 1218:tid 1995862016] AH01909: 127.0.1.1:443:0 server certificate does NOT include an ID which matches the server name
[Sun Sep 10 16:38:15.153908 2017] [ssl:warn] [pid 1219:tid 1995862016] AH01909: 127.0.1.1:443:0 server certificate does NOT include an ID which matches the server name
[Sun Sep 10 16:38:15.159375 2017] [mpm_event:notice] [pid 1219:tid 1995862016] AH00489: Apache/2.4.25 (Raspbian) OpenSSL/1.0.2l configured -- resuming normal operations
[Sun Sep 10 16:38:15.159570 2017] [core:notice] [pid 1219:tid 1995862016] AH00094: Command line: '/usr/sbin/apache2'
[Sun Sep 10 16:38:16.044752 2017] [proxy_fcgi:error] [pid 1223:tid 1974465584] [client 212.238.239.196:57043] AH01071: Got error 'PHP message: PHP Fatal error:  **Allowed memory size of 2097152 bytes exhausted (tried to allocate 65536 bytes)** in /var/www/nextcloud/lib/composer/composer/ClassLoader.php on line 412\n'

Any help would be appreciated to the max

A: Your htaccess file is invalid. You are starting the directive <IfModule mod_rewrite.c> but never closing it using </IfModule>.
I would advice to download the default htaccess file shipped by nextcloud and try again. Just download the zip file from here: https://nextcloud.com/install/#instructions-server and replace the htacess file.

A: The htaccess settings are only used for PHP executed within that folder or sub folders - What is the difference between php.ini and .htaccess?
Looking at the error message (Allowed memory size of 2097152 bytes exhausted) suggests that composer has a much lower memory limit than what you set so my guess would be that it is not affected by your htaccess.
Try setting the limit in your php.ini file instead.


text:
Q: Samsung pay integration I want to know, is Samsung pay API available for android ?? how can we integrate it into android? I have tried many times but did not get anything,
i got links like below : http://apps.cybersource.com/library/documentation/dev_guides/Samsung_Pay_SCMP_API/html/wwhelp/wwhimpl/js/html/wwhelp.htm#href=ch_Registration.5.1.html
can you guide more for it?

A: To quote Samsung Support on this:

Samsung Pay is focusing on in-store purchases, and at this time, there is no support for implementing in-app purchasing using Samsung Pay. The Samsung Pay SDK and corresponding API documentation will be made available at developer.samsung.com at a later time. For more information on utilizing Samsung's extensive B2B resources, visit the Samsung Partner Portal.

If you already have an account on Samsung Developer/Partner Portal, I would suggest you sign in and get in contact with a representative from Samsung to help you out.

A: Yes, it's possible! But it depends on the country and payment gateway you want to work with:
Access https://pay.samsung.com/partners/ and contact a Samsung Pay Relationship Manager
Here is the portal for developers: https://pay.samsung.com/developers


text:
Q: How to measure using word vectors I'm attempting to understand how bias can be measured using word embeddings. Reading the article https://towardsdatascience.com/gender-bias-word-embeddings-76d9806a0e17

What is the bias being identified in the above statement ? Is the bias here that a woman cannot be seen as a doctor when a man is involved ?
Is a neutral bias for a either a man or woman being identified is where there is a small difference between woman,doctor man,doctor , represented a vector : $woman + doctor \approx man + doctor$ ?

A: You would expect that
woman + doctor = man + doctor

Or rewritten:
woman + doctor - man = doctor

But since it is 'nurse' in that word embedding space, that is an indicator for bias towards women in healthcare to be percieved as nurses.
Doctors are associated more with men in the corpus from which the embeddings were trained, so it can be concluded that the corpus (and the learned word embedding) has a gender bias.


text:
Q: PHP array sort by number of items I need to sort my array-based on the number of elements in the inner array.
It's my current array.
Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [0] => 2-3
        )

    [2] => Array
        (
            [0] => 5-9
        )

    [3] => Array
        (
            [0] => 5-9
            [1] => 2-3
        )

)

I need to sort the array by this format.
Array
(
[3] => Array
        (
            [0] => 5-9
            [1] => 2-3
        )

    [2] => Array
        (
            [0] => 5-9
        )

    [1] => Array
        (
            [0] => 2-3
        )

[0] => Array
        (
        )

)

A: This seems to do it:
<?php

$a = [
   [], ['2-3'], ['5-9'], ['5-9', '2-3']
];

$f = fn ($b, $c) => count($c) <=> count($b);
usort($a, $f);
print_r($a);

https://php.net/function.usort

A: i hope this answer help you
$result  = array();
$sorter  = array();
foreach($values as $key => $vals){
  $sorter[$key]= count($vals);
}
arsort($sorter);
foreach ($sorter as $ii => $va) {
  $result[$ii]=$values[$ii];
}

output


text:
Q: Setup .fxml file programmatically I am used to writing code in JavaFx like the one given below because that's how I learn a few years ago.
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.*;

public class test extends Application {
    int c=0;
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("Demo");
        Button b = new Button("Click me");
        Label l = new Label("Count=" + c);
        VBox v = new VBox(20);
        v.getChildren().addAll(b, l);
        b.setOnAction(event -> {
            c++;
            l.setText("Count=" +c);
        });
        primaryStage.setScene(new Scene(v, 300, 300));
        primaryStage.show();
    }
}

I have recently installed JetBrains IntelliJ IDEA Ultimate Edition 2018.1.6 and I am seeing that to open up the primaryStage window, I need to have an fxml file.

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.GridPane?>
<GridPane alignment="center" hgap="10" vgap="10" xmlns="http://javafx.com/javafx/8.0.121" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Main">
</GridPane>

And I have to do,
primaryStage.setScene(new Scene(FXMLLoader.load(getClass().getResource("sample.fxml")), 300, 300));

If I run the first code snippet, nothing shows up. But if I replace VBox v with FXMLLoader.load(getClass().getResources("sample.fxml")), Just a window shows up without the Button and Label. Is there a way in which I can either ignore the usage of the fxml file? Or can I, using the standard way of coding(first code snippet) and let the compiler change that into fxml format for me?
That's because I want to have 100x100 labels in a grid layout, when each Label is one pixel. Hence, in code, it's easy to run nested for loops to initiatialize and address each Label using 2-d Array. But initializing 1000 labels inside the fxml is too lengthy, exhausting and illogical.
I never had to do such things in JetBrains IntelliJ IDEA Community Edition 2017.0.2. When I upgraded to Ultimate Edition 2018.1.6, I'm getting these errors.

A: You can definitely use IntelliJ with JavaFX without FXML.
Q: Is there a way in which I can either ignore the usage of the fxml file?
A: Considering your code snippet you refer on default setup you get from IntelliJ when you create new JavaFX project, yes their default setup uses .fxml but it isn't required to use it. You can delete that sample.fxml file and rewrite start as you want.
Side note: Nothing prevents you to use both fxml and code approach in same project, in some cases using fxml is better approach while in some other situations it is better to use code.
Q: Or can I, using the standard way of coding(first code snippet) and let the compiler change that into fxml format for me?
A: There is no way to convert Java code to fxml, but as I already said it is up to you to decide which one to use, and you can even uses both of them in same project.


text:
Q: How to write LaTeX on a static blog smoothly? I want to write some of my notes in blog format.
I want to use my own domain with an github.io-provided static website. I don't know whether I can setup Wordpress there, so Trevisan's latex2wp is maybe not the right choice. Also, Wordpress LaTeX is quirky sometimes. I would want to use Hugo, Jekyll or Nikola for the blog layout.
The look of the blogpost I'm targeting is similar to this blog or this one. But anything goes if it's easy to setup and use.
My ideal work process would be as follows: write the LaTeX in emacs, copy the file to some git repo, git push, and the blog appears on my website.
Has anyone set something similar up, or has an idea how to do this?

A: For both Hugo or Jekyll you can follow
this guide
http://flennerhag.com/2017-01-14-latex/#mjx-eqn-label
.
It tells you how to use mathJax to render LaTeX in markdown files.

*

*If you are using hugo, the file where you have to add the snippet is the footer.html or site-footer.html under layouts/partials of your theme.

*If you are using Jekyll then it is under _layout as specified by the guide.

For commutative diagrams, it is going to be tricky, as mathJax does not support commdiag or Tikz natively (as far as I am aware, and of today). The only solution I could find is to create an image out of the commutative diagram, and then post the image directly in the blog.


text:
Q: One-line PHP random string generator? I am looking for the shortest way to generate random/unique strings and for that I was using the following two:
$cClass = sha1(time());

or
$cClass = md5(time());

However, I need the string to begin with a letter, I was looking at base64 encoding but that adds == at the end and then I would need to get rid of that.
What would be the best way to achieve this with one line of code?

Update:
PRNDL came up with a good suggestions which I ended up using it but a bit modified
echo substr(str_shuffle(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ),0, 1) . substr(str_shuffle(aBcEeFgHiJkLmNoPqRstUvWxYz0123456789),0, 31)

Would yield 32 characters mimicking the md5 hash but it would always product the first char an alphabet letter, like so;

However, Uours really improved upon and his answer;
substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1).substr(md5(time()),1);

is shorter and sweeter
The other suggestion by Anonymous2011 was very awesome but the first character for some reason would always either M, N, Y, Z so didn't fit my purposes but would have been the chosen answer, by the way does anyone know why it would always yield those particular letters?
Here is the preview of my modified version
echo  rtrim(base64_encode(md5(microtime())),"=");

A: If you need it to start with a letter, you could do this. It's messy... but it's one line.
$randomString = substr(str_shuffle("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 1) . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 10);

echo $randomString;

A: I decided this question needs a better answer. Like code golf! This also uses a better random byte generator.
preg_replace("/[\/=+]/", "", base64_encode(openssl_random_pseudo_bytes(8)));

Increase the number of bytes for a longer password, obviously.

A: Creates a 200 char long hexdec string:
$string = bin2hex(openssl_random_pseudo_bytes(100));

maaarghk's answer is better though.

A: Rather than shuffling the alphabet string , it is quicker to get a single random char .
Get a single random char from the string and then append the md5( time( ) ) to it . Before appending md5( time( ) ) remove one char from it so as to keep the resulting string length to 32 chars :
substr("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", mt_rand(0, 51), 1).substr(md5(time()), 1);

Lowercase version :
substr("abcdefghijklmnopqrstuvwxyz", mt_rand(0, 25), 1).substr(md5(time()), 1);

Or even shorter and a tiny bit faster lowercase version :
chr(mt_rand(97, 122)).substr(md5(time()), 1);

/* or */

chr(mt_rand(ord('a'), ord('z'))).substr(md5(time()), 1);

A note to anyone trying to generate many random strings within a second: Since time( ) returns time in seconds , md5( time( ) ) will be same throughout a given second-of-time due to which if many random strings were generated within a second-of-time, those probably could end up having some duplicates .
I have tested using below code . This tests lower case version :
    $num_of_tests = 100000;

    $correct = $incorrect = 0;

    for( $i = 0; $i < $num_of_tests; $i++ )
    {
        $rand_str = substr( "abcdefghijklmnopqrstuvwxyz" ,mt_rand( 0 ,25 ) ,1 ) .substr( md5( time( ) ) ,1 );

        $first_char_of_rand_str = substr( $rand_str ,0 ,1 );

        if( ord( $first_char_of_rand_str ) < ord( 'a' ) or ord( $first_char_of_rand_str ) > ord( 'z' ) )
        {
            $incorrect++;
            echo $rand_str ,'<br>';
        }
        else
        {
            $correct++;
        }
    }

    echo 'Correct: ' ,$correct ,' . Incorrect: ' ,$incorrect ,' . Total: ' ,( $correct + $incorrect );

A: base_convert(microtime(true), 10, 36);

A: You can try this:
 function KeyGenerator($uid) {
    $tmp = '';
    for($z=0;$z<5;$z++) {
      $tmp .= chr(rand(97,122)) . rand(0,100);
    }
    $tmp .= $uid;
    return $tmp;
  }

A: I had found something like this:
$length = 10;
$randomString = substr(str_shuffle(md5(time())),0,$length);
echo $randomString;

A: I have generated this code for you. Simple, short and (resonably) elegant.
This uses the base64 as you mentioned, if length is not important to you - However it removes the "==" using str_replace.
<?php
        echo  str_ireplace("==", "", base64_encode(time()));
?>

A: I use this function
usage:
 echo randomString(20, TRUE, TRUE, FALSE);

  /**
   * Generate Random String
   * @param Int Length of string(50)
   * @param Bool Upper Case(True,False)
   * @param Bool Numbers(True,False)
   * @param Bool Special Chars(True,False)
   * @return String  Random String
   */
  function randomString($length, $uc, $n, $sc) {
      $rstr='';
      $source = 'abcdefghijklmnopqrstuvwxyz';
      if ($uc)
          $source .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
      if ($n)
          $source .= '1234567890';
      if ($sc)
          $source .= '|@#~$%()=^*+[]{}-_';
      if ($length > 0) {
          $rstr = "";
          $length1= $length-1;
          $input=array('a','b','c','d','e','f','g','h','i','j,''k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z')
          $rand = array_rand($input, 1)
          $source = str_split($source, 1);
          for ($i = 1; $i <= $length1; $i++) {
              $num = mt_rand(1, count($source));
              $rstr1 .= $source[$num - 1];
              $rstr = "{$rand}{$rstr1}";
          }
      }
      return $rstr;
  }

A: I'm using this one to generate dozens of unique strings in a single go, without repeating them, based on other good examples above:
$string = chr(mt_rand(97, 122))
          . substr(md5(str_shuffle(time() . rand(0, 999999))), 1);

This way, I was able to generate 1.000.000 unique strings in ~5 seconds. It's not THAT fast, I know, but as I just need a handful of them, I'm ok with it. By the way, generating 10 strings took less than 0.0001 ms.

A: JavaScript Solution:
function randomString(pIntLenght) {
  var strChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var strRandomstring = ";

  for (var intCounterForLoop=0; intCounterForLoop < pIntLenght; intCounterForLoop++) {
      var rnum = Math.floor(Math.random() * strChars.length);
      strRandomstring += strChars.substring(rnum,rnum+1);
  }
   return strRandomstring;
}

alert(randomString(20));

Reference URL : Generate random string using JavaScript
PHP Solution:
function getRandomString($pIntLength = 30) {
      $strAlphaNumericString     = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

      $strReturnString         = ";

      for ($intCounter = 0; $intCounter < $pIntLength; $intCounter++) {
           $strReturnString .= $strAlphaNumericString[rand(0, strlen($strAlphaNumericString) - 1)];
      }
      return $strReturnString;
}

echo getRandomString(20);

Reference URL : Generate random String using PHP

A: This function returns random lowercase string:
function randomstring($len=10){
 $randstr='';
 for($iii=1; $iii<=$len; $iii++){$randstr.=chr(rand(97,122));};
 return($randstr);
};

A: I find that base64 encoding is useful for creating random strings, and use this line:
base64_encode(openssl_random_pseudo_bytes(9));

It gives me a random string of 12 positions, with the additional benefit that the randomness is "cryptographically strong".

A: to generate strings consists of random characters, you can use this function
public function generate_random_name_for_file($length=50){
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));
    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }
    return $key;
}

A: It really depends on your requirements.
I needed strings to be unique between test runs, but not many other restrictions.
I also needed my string to start with a character, and this was good enough for my purpose.
$mystring =  "/a" . microtime(true);
Example output:
a1511953584.0997

A: How to match the OPs original request in an awful way (expanded for readability):
// [0-9] ASCII DEC 48-57
// [A-Z] ASCII DEC 65-90
// [a-z] ASCII DEC 97-122
// Generate: [A-Za-z][0-9A-Za-z]
$r = implode("", array_merge(array_map(function($a)
                             {
                                 $a = [rand(65, 90), rand(97, 122)];
                                 return chr($a[array_rand($a)]);
                             }, array_fill(0, 1, '.')),
                             array_map(function($a)
                             {
                                 $a = [rand(48, 57), rand(65, 90), rand(97, 122)];
                                 return chr($a[array_rand($a)]);
                             }, array_fill(0, 7, '.'))));

One the last array_fill() would would change the '7' to your length - 1.
For one that does all alpha-nurmeric (And still slow):
// [0-9A-Za-z]
$x = implode("", array_map(function($a)
                           {
                               $a = [rand(48, 57), rand(65, 90), rand(97, 122)];
                               return chr($a[array_rand($a)]);
                           }, array_fill(0, 8, '.')));

A: The following one-liner meets the requirements in your question: notably, it begins with a letter.
substr("abcdefghijklmnop",random_int(0, 16),1) . bin2hex(random_bytes(15))

If you didn't care whether the string begins with a letter, you could just use:
bin2hex(random_bytes(16))

Note that here we use random_bytes and random_int, which were introduced in PHP 7 and use cryptographic random generators, something that is important if you want unique strings to be hard to guess. Many other solutions, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), array_rand(), and shuffle(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.
I also list other things to keep in mind when generating unique identifiers, especially random ones.

A: True one liner random string options:
implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21));

md5(microtime() . implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21)));

sha1(microtime() . implode('', array_rand(array_flip(str_split(str_shuffle('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'))), 21)));


text:
Q: Android - Calendar возвращает неверные данные Облазил весь гугл, только ещё больше запутался. Дело в том, что Calendar возвращает неверные данные.
Вот мой код:
    mCalendar = Calendar.getInstance();
    mDate = new Date();
int month = mCalendar.MONTH;
int dayofweek = mCalendar.DAY_OF_WEEK;
int day = mCalendar.DAY_OF_MONTH;
int hour = mDate.getHours();
int min = mDate.getMinutes();
int sec = mDate.getSeconds();

mMonth.setProgress(month);
mDayOfWeek.setProgress(dayofweek);
mDay.setProgress(day);
mHour.setProgress(hour);
mMinute.setProgress(min);
mSecond.setProgress(sec);
Log.e("DBG", "" + month + "|" + dayofweek + "|" + day + "|" + hour + "|" + min + "|" + sec);

Что я получаю в логе:
DBG 2|7|1|22|52|34

Хотя должно быть вот так
DBG 1|5|31|22|52|34

Где я допустил ошибку и почему дата возвращается неверно?

A: Все очень просто - mCalendar.MONTH - это не текущий месяц. Это константа для номера поля внутри объекта.  Вам нужен метод get, которому параметром эту константу нужно и передать.
int month = mCalendar.get(Calendar.MONTH);

Почему так странно сделано? да все просто. Иначе пришлось бы делать кучу методов. set/get/add для дней/месяцев.


text:
Q: Cutting Edge to the Left Bottom I have find that code but all in vain to put the cutting edge to the left bottom please help.
how can we put that corner to left bottom. i have been trying but all in vain
Fiddle

CSS
.doc{
   position:relative;
   height:46px;
   width:28px;
}

.doc,
.doc:before{
  background-color: #c40d12;
}

.doc:after{
  position:absolute;
  top:0px;
  right:-9px;
  content:"";
  display:block;
  width:0px;
  height:0px;
  overflow:hidden;
  border-bottom: 9px solid #c40d12;
  border-right: 9px solid transparent;
  background:transparent;
}
.doc:before{
  position:absolute;
  top:9px;
  right:-9px;
  content:"";
  overflow:hidden;
  display:block;
  width:9px;
  height:37px;
}

.doc:hover,
.doc:hover:before{
  background-color: #970101;
}
.doc:hover:after{
  border-bottom: 9px solid #970101;
}

A: Try using the following CSS rules overwriting existing one.
JSFiddle link : http://jsfiddle.net/W5Hx9/
.doc{
   position:relative;
   height:46px;
   width:28px;
}

.doc,
.doc:before{
  background-color: #c40d12;
}

.doc:after {
    position: absolute;
    bottom: 0px;
    left: -9px;
    content: "";
    display: block;
    width: 0px;
    height: 0px;
    overflow: hidden;
    border-top: 9px solid #c40d12;
    border-left: 9px solid transparent;
    background: transparent;
}

.doc:before {
    position: absolute;
    bottom: 9px;
    left: -9px;
    content: "";
    overflow: hidden;
    display: block;
    width: 9px;
    height: 37px;
}

.doc:hover,
.doc:hover:before{
  background-color: #970101;
}
.doc:hover:after{
  border-bottom: 9px solid #970101;
}

A: Here's a bit simpler solution: http://jsfiddle.net/W5Hx9/1/.
.doc{
   position:relative;
   height:46px;
   width:37px;
   background-color: #c40d12;
   cursor: pointer;
}

.doc:after{
  position:absolute;
  left:0px;
  bottom: 0px;
  content:"";
  border-bottom: 9px solid #fff;
  border-right: 9px solid transparent;
}

.doc:hover {
  background-color: #970101;
}

A: Had modified the before and after css like this
Working Code:JSFIDDLE


text:
Q: How can I use multiple ControlTemplates in a XAML-file? I'm having this annoying problem with WPF that I can't get my head around.
What I'm trying to create, is a very basic implementation of a drawing program (it's a school assignment) with movable tool windows, like in Photoshop.
I've managed to figure out that I can use this element "Thumb" to implement simple Drag functionality. Since the Thumb element itself is not visible, and the object that I'm using as a container (a DockPanel) does not have a DragDelta property, I simply created a ControlTemplate and attached it to the Thumb, so now I have a draggable color picker that works okay. So far so good.
But, problems arise when I want to create additional ControlTemplates, to use for other Thumb-elements that I plan to use (I get the error: The property 'VisualTree' is set more than once.).
This is what I want help with. I have pasted my whole Window.Resources-tag here so you can see what's going on.
<Window.Resources>
        <Style x:Key="toolBoxBtn" TargetType="Button">
            <Setter Property="Width" Value="60" />
            <Setter Property="Height" Value="60" />
            <Setter Property="Margin" Value="5" />
            <Setter Property="DockPanel.Dock" Value="Top" />
        </Style>

        <Style x:Key="style1" TargetType="{x:Type Thumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">

                        <DockPanel Background="#e6e6e6" HorizontalAlignment="Left" Margin="0" Height="auto" Width="auto" Canvas.Left="640" Canvas.Top="8">
                            <Label VerticalAlignment="Top" DockPanel.Dock="Top" Background="#282828" Foreground="white" Content="Colors" HorizontalAlignment="Stretch" Width="auto" Height="auto" />

                            <StackPanel>
                                <StackPanel Orientation="Horizontal" Margin="7" VerticalAlignment="Center">
                                    <Rectangle DockPanel.Dock="top" Name="red" Fill="Red" Height="20" Width="20" Stroke="Black" MouseDown="getColor" />
                                    <Rectangle DockPanel.Dock="top" Name="blue" Fill="Blue" Height="20" Width="20" Stroke="Black" MouseDown="getColor"/>
                                    <Rectangle DockPanel.Dock="top" Name="green" Fill="GreenYellow" Height="20" Width="20" Stroke="Black" MouseDown="getColor"/>

                                    <Rectangle DockPanel.Dock="top" Name="customColorSlot1" Fill="White" Height="20" Width="20" Stroke="Black" MouseDown="getColor" />
                                    <Rectangle DockPanel.Dock="top" Name="customColorSlot2" Fill="White" Height="20" Width="20" Stroke="Black" MouseDown="getColor"/>
                                    <Rectangle DockPanel.Dock="top" Name="customColorSlot3" Fill="White" Height="20" Width="20" Stroke="Black" MouseDown="getColor"/>
                                </StackPanel>
                                <GroupBox Header="Selected Color">
                                    <Rectangle Name="currentColor" Fill="White" Height="40" Width="40" Stroke="Black" MouseDown="test"/>
                                </GroupBox>
                            </StackPanel>
                        </DockPanel>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="fillTool" TargetType="{x:Type Thumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Ellipse HorizontalAlignment="Left" Height="19" Margin="310,330,0,0" VerticalAlignment="Top" Width="19" Fill="Blue"/>
                        <Ellipse HorizontalAlignment="Left" Height="12" Margin="317,316,0,0" VerticalAlignment="Top" Width="12" Fill="Blue"/>
                        <Ellipse HorizontalAlignment="Left" Height="8" Margin="307,320,0,0" VerticalAlignment="Top" Width="7" Fill="Blue"/>
                        <Ellipse HorizontalAlignment="Left" Height="3" Margin="317,302,0,0" VerticalAlignment="Top" Width="3" Fill="Blue"/>
                        <Ellipse HorizontalAlignment="Left" Height="5" Margin="311,310,0,0" VerticalAlignment="Top" Width="5" Fill="Blue"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

    </Window.Resources>

What could be the problem here?

A: ControlTemplate can only contain one child. Try and change it to a Canvas instead
        <Style x:Key="fillTool" TargetType="{x:Type Thumb}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Thumb}">
                        <Canvas>
                           <Ellipse HorizontalAlignment="Left" Height="19" Margin="310,330,0,0" VerticalAlignment="Top" Width="19" Fill="Blue"/>
                           <Ellipse HorizontalAlignment="Left" Height="12" Margin="317,316,0,0" VerticalAlignment="Top" Width="12" Fill="Blue"/>
                           <Ellipse HorizontalAlignment="Left" Height="8" Margin="307,320,0,0" VerticalAlignment="Top" Width="7" Fill="Blue"/>
                           <Ellipse HorizontalAlignment="Left" Height="3" Margin="317,302,0,0" VerticalAlignment="Top" Width="3" Fill="Blue"/>
                           <Ellipse HorizontalAlignment="Left" Height="5" Margin="311,310,0,0" VerticalAlignment="Top" Width="5" Fill="Blue"/>
                        </Canvas>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>


text:
Q: How to find total DOM processing and page rendering time in chrome How to find total DOM processing and page rendering time in chrome for a particular page (running locally) .. i want to see the total time for the entire page and not individual resources in the page.

A: Use the Timeline function in the developer tools in Chrome. Alternativly you can also use the Profiler if you want to watch memory usage or the Network tab to view downloading and rendering of the page.