What characteristic of networking/TCP causes linear relation between TCP activity and latency?

Question: The core of this problem is that our application uses websockets for real-time interfaces. We are testing our app in a new environment but strangely we're noticing an increasing delay in TCP websocket packets associated with an increase in websocket activity.
For example, if one websocket event occurs without any other activity in a 1-minute period, the response from the server is instantaneous. However, if we slowly increase client activity the latency in server response increases with a linear relationship (each packet will take more time to reach the client with more activity).
For those wondering this is NOT app-related since our logs show that our server is running and responding to requests in under 100ms as desired. The delay starts once the server processes the request and creates the TCP packet and sends it to the client (and not the other way around).
Architecture This new environment runs with a Virtual IP address and uses keepalived on a load balancer to balance the traffic between instances. Two boxes sit behind the balancer and all traffic runs through it. Our host provider manages the balancer and we do not have control over that part of the architecture.
Theory Could this somehow be related to something buffering the packets in the new environment?
Thanks for your help.
Answer: Buffering sounds like a reasonable theory. I would take a packet capture from your app servers to make sure that you don't see anything like retransmits or other possibly abnormal behavior in the tcp stream (i.e. tcp window zeroing out?).  Wireshark with a capture filter for the client IP would work for this.
If you verify that the packet capture looks clean, asking your provider to run a packet capture on their load balancer so you can analyize is a reasonable request.
Lastly, have you tested from multiple locations and different machines? Perhaps buffering is somewhere between the client and the provider, or something strange is happening with the client (running a packet capture on the client as well as your servers at the same time can be enlightening as well).
Comment: I have tested with multiple clients/connections but not multiple locations. However, the problem is non-present in the standard IP (old) environment. I am using Wireshark but didn't think about retransmits or window zeroing. I'm going to do a little more research and get back with a response after some testing :) thx!
Comment: Well of the two answers yours is the most accurate. Turns out the firewall in our provider was designed to do a lot of bloated functions that just interfere with the websocket. thanks for the insight.
Answer: It's actually an expected behavior.  As the amount of data increases the size of the transmit window increases which, to a point, will increase the size of the packets sent.  Larger packets mean more efficiency (less overhead and time taken for acknowledgements) but they also mean more latency.  This is the tradeoff for maintaining reliable delivery while also maintaining any kind of throughput in networks of widely varying latencies and bandwidth.
Check out the PSH flag to cause TCP to flush buffers sooner.  It might make a marginal difference under some circumstances.  If you're looking for consistently low latency for lots of small messages, however, you might be better served looking at UDP - which means you'll have to account for assuring delivery on your own but you might realize a bit more consistency.
Comment: PSH might be a reasonable option since I think we can program that into the websocket server itself. My only thought towards UDP is I don't think it is supported by websockets (see http://stackoverflow.com/questions/4657033/javascript-websockets-with-udp). Will respond soon once I can test some of this out!
Comment: Well unfortunately I found out that the PSH flag was already being set by my websocket server. I'll have to look deeper. The UDP was a great idea but unfortunately it isn't part of the websocket spec.


Chi square test in machine learning

Question:

Doubt

How can I set chi-square test on city and brand as the column city and brand doesn't have number but string like city name and brand_name
I'm new to statistics so any hint will be helpful...
Comment: I came to this problem while solving basics of machine learning in python! I have taken screenshot for later learning I went through `chi square` and `t-test` practice problems but in practice problems data format was in numbers
Answer: Chi-Square test works well with categorical data types. The target variable should be categorical, and the feature can be either categorical or numeric. In case of both categorial, you need to form a table with the counts/frequencies of each pair of configuration. This is referred as contingency table as well.
Comment: to my surprise I understood what you said in my dreams but have yet to solve it, thanks!
Comment: Thanks can you please share the format of table I'm still finding difficulty in understanding...
Comment: There is a very good example in the Example section in the wikipedia page. Rows and columns are categories, and the middle entries are the frequencies of these configurations.
Answer: Before you implement a Chi-squared test, you need to format your data as a contingency table.
Comment: Can you please share like how and what should be the format of table...

Chi square test in machine learning


Div para canvas

Question: Olá, estou tendo um problema ao transformar uma div em canvas, pois dentro dessa div tem uma img, e o src contem a url COMPLETA da imagem, com http, quando é uma imagem normal que ja esta no servidor não tenho problemas, ele converte tranquilamente, mas quando o src está com http ele pega a div inteira mas a imagem ele não reconhece, estou usando o html2canvas, segue meu código:
HTML:

texto

JAVASCRIPT:
$(document).ready(function(){

                html2canvas($("#mesa"), {
                    onrendered: function(canvas){

                        var imagem = canvas.toDataURL('image/png');

                        var image = new Image();
                        image.src = imagem;
                        $("body").append(image);

                    }
                });

        });

repetindo, se o src da imagem for uma imagem do servidor (ex: src="imagem.jpg") ele pega normal, mas se for src="http://outrosite.com.br/imagem.jpg" ai ele não pega a imagem, pq acontece isso ? preciso pegar a imagem desse jeito, de outro site... Tem alguma solução ?
obrigado!
Comment: Isso deve ser erro de segurança... já viu o console? Geralmente seu site/domínio não está permitido à atravessar o outro site por causa de configurações, até mesmo no .htaccess.
Comment: Então, no console não da nenhum erro, e no .htaccess não tem nada bloqueando tbm :/
Comment: Então, tem mais algumas pistas?
Comment: Eu vi algo sobre cross-domain, sobre colocar crossDomain = "Anonymous", mas n sei onde colocar isso, ja tentei colocar em alguns lugares, mas mesmo assim n funcionou
Answer: Imagens de dominios diferentes causam o "Taint", basta ler o README, na verdade qualquer LIB que pretenda usar leia o README inteiro, geralmente lá já contem as soluções para os problemas, como já descrito aqui https://github.com/niklasvh/html2canvas#how-does-it-work
Resumindo você pode tentar usar o useCORS assim:
html2canvas(document.getElementById("mesa"), {
    "logging": true, //Habilita os logs
    "useCORS": true
}).then(function(canvas) {
    var img = new Image();

    img.onload = function () {
        img.onload = null;
        document.getElementById("output").appendChild(img);
    };

    img.src = canvas.toDataURL("image/png");
    $("body").append(image);
});

Note que o useCORS só tenta carregar com cross-origim, se não conseguir ele irá tentar o proxy.
Se não funcionar com useCORS você pode combinar com um "proxy" (não confunda com proxy para ISP) ou usar somente o proxy, por exemplo:
html2canvas(document.getElementById("mesa"), {
    "logging": true, //Habilita os logs
    "useCORS": true, //Tenta carregar com crossorigem=anonymous, se não tentará o proxy
    "proxy": "/libs/url-do-proxy.php" //Proxy
}).then(function(canvas) {
    var img = new Image();

    img.onload = function () {
        img.onload = null;
        document.getElementById("output").appendChild(img);
    };

    img.src = canvas.toDataURL("image/png");
    $("body").append(image);
});

Alguns exemplos de proxy que eu escrevi:

Proxy em PHP (compatível com html2canvas 0.4 e 0.5): https://github.com/brcontainer/html2canvas-php-proxy
Proxy em C#: https://github.com/brcontainer/html2canvas-csharp-proxy
Proxy em Python: https://github.com/brcontainer/html2canvas-python-proxy (suporta qualquer framework)
Proxy em VbScript (para asp clássico): https://github.com/brcontainer/html2canvas-asp-vbscript-proxy

Somente o proxy em PHP é compatível com a versão 0.5 do html2canvas, em breve irei reescrever as demais libs/scripts

Div para canvas


Prove that the sequnce converges uniformly to $0$ on $R$

Question: I need some help here.
I should prove that the  sequence:
$$  \frac{1}{x^2+n}$$
converges uniformly to $0$ on $\mathbb{R}$
At first I thought that if this sequence converges I can say that the limit $n \to \infty$ will be $0$  (is that idea right?)
Also I know that $f_n \to f$ uniformly converge if $ \forall \epsilon > 0 \text{,  } \exists N \in \mathbb{N}$ such that $\forall n >N \text{,  } \forall x \in E \text{,  } |f_n(x) - f(x)|< \epsilon$
So I tried to solve this problem using above mentioned
Let $\epsilon > 0 $,  $\forall n>N$
$$|\frac{1}{x^2+n} - 0|< \epsilon $$
$$|\frac{1}{x^2+n}|< \epsilon $$
$$\Downarrow$$
$$\frac{1}{x^2+N} < \epsilon$$
$$\Downarrow$$
$$  N > \frac{1}{\epsilon} - x^2 $$
Is there any way to get rid of $x^2$?
Comment: Note that $0 < \frac{1}{x^2+n} \le \frac 1n$.
Comment: Since $x^2\geq 0$, then $n+x^2\geq n$. Use the squeeze theorem now, since $0\leq\frac{1}{n+x^2}\leq \frac{1}{n}$
Comment: thank you for your comment
Answer: You have
$$\frac{1}{x^2+n} \le \frac{1}{n}\le \varepsilon$$
for all $n>\frac{1}{\varepsilon}$ and $x\in\mathbb{R}$.


hidden-sm-down on Bootstrap4 not working

Question: I'm trying to make my images be above my text on m+ devices, and below the text on sm- devices. I'm using Bootstrap4, and to my knowledge following all the tutorials given from Bootstrap - yet it's not hiding my images.   Thanks for the help in advance.
Here is my code:

Get SMS notifications for new dates

This is where the text would go.

Answer: This is because the classes hidden-sm-down and hidden-sm-up don't exist in Bootstrap 4 Beta 3 anymore.
Instead of hidden-sm-up use d-sm-none etc.
Complete list here:
https://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
Comment: Thank you very much. I swear I was reading the most up to date version, obviously not!
Comment: Why would they remove those classes? They are simpler than combingi things like this ugly `.d-none .d-sm-block .d-md-none`


How big can $\{t \in [0,1] : \lim_{n\to\infty}\exp(2\pi itk_n)=1\}$ be?

Question: Let $(k_n)_{n\geq1}$ be a incresing sequence of positive integers. How big can be
$$C = \{t \in [0,1] : \lim_{n\to\infty}\exp(2\pi itk_n)=1\}?$$
My thoughts so far:

If $k_n = n!$, then $C \supseteq \mathbb{Q}$, so $C$ can be a dense in $[0,1]$.
More generally, if $Q\subseteq [0,1]$ is any countable set, then $C\supseteq Q$ for some choice of $(k_n)_{n\geq1}$ .
By compactness, one can take a subnet $(k_\lambda)_{\lambda\in\Lambda}$ of $(k_n)_{n\geq1}$ such that $\lim_{\lambda\to\infty}\exp(2\pi itk_\lambda)$ exists for all $t \in [0,1]$. I don't know if it is possible to make this limit equal to $1$. In any case, I am not allowing nets in the definition of $C$.
If $k_n = n$, then $C = \{1\}$.

To make the question more concrete: can $C$ be uncountable? If the answer is yes, can it have positive Lebesgue measure?
Answer: It is indeed possible to have $C$ be uncountable.  Since $|e^{2\pi i x} - e^{2\pi i y}| < 2 \pi |x-y|$, $A(k, \epsilon) = \{x: |e^{2\pi i k x} - 1| \le \epsilon\}$ contains an open interval of length $\epsilon/(2\pi^2 k)$
centred at each $j/k$ for integer $j$, $0 < j < k$.  If $k' = m k$ for positive integer $m > 4 \pi^2/\epsilon$, then each of these intervals contains at least two rationals of the form $j/k'$ for integer $k$, and thus (if $\epsilon'$ is small enough, two disjoint
intervals of $A(k', \epsilon')$.  So we can construct an increasing sequence $k_j$ of positive integers, a sequence $\epsilon_j \to 0+$, and a nested sequence $E_j$ of compact sets, such that $E_j$ is the union of $2^j$ intervals in $A(k_j,\epsilon_j)$.
   The intersection of the $E_j$ is then an uncountable Cantor-type set
on which $e^{2\pi i k_j x} \to 1$.
Answer: I have an answer to my second question: $C$ is of Lebesgue measure zero.
By the Dominated Convergence Theorem and the Riemann-Lebsgue Lemma, we have
$$ \mu(C) = \int_\mathbb{R} \chi_C(t)\cdot 1dt = \lim_{n\to\infty}\int_\mathbb{R}\chi_C(t)\cdot e^{2\pi ik_nt}dt = 0,$$
where $\chi_C$ is the indicator function of $C$.


How does one gracefully kill a process in Windows?

Question: I know one can just go into task manager and kill a process; but like not ejecting your thumb drive before pulling it out of the socket, one should notify the process it's being killed first if possible.
So my question is how does one gracefully kill a process in Windows?  Ideally using Powershell.
Answer: https://superuser.com/questions/959364/on-windows-how-can-i-gracefully-ask-a-running-program-to-terminate
taskkill will do it, it sends WM_CLOSE messages to the target process.
Caveat - If a process is hung, it wouldn't be able to respond to your request to gracefully exit anyway.
Comment: This also only applies to processes that have windows... i.e. not console or service processes.  Basically this is the same thing as either clicking the X button on the window or the task manager also tries this first.
Comment: @leeand00 - for an arbitrary app, it has to surface and support some method for doing so. If the app authors didn't handle that case, you can't.
Comment: @psusi How do you gracefully kill a process with no window?  A service for instance?
Comment: @leeand00, there is no general method, but services in particular interface with the service control manager which can pass them a command to shut down.


Trying to make a blank list that is mutable on python

Question: I need to be able to add, delete, edit, and recall transactions in a list.
I opened a while loop, set the constants and defined an empty list. I then proceeded to create the menuing through if statements. Everything seems to work except I am unable to add to the list and then recall all added values.
This is what I have so far:
while True:

    addTransaction = "1"
    deleteTransaction = "2"
    editTransaction = "3"
    displayTransactions = "4"
    exit = "5"
    transactions = []

    menu = input("**********Main Menu***********\n1.  Add Transaction\n2.  Delete Transaction\n3.  Edit Transaction\n4.  Display Transactions\n5.  Exit the Program\n\nChoose a menu option from 1-4 or 5 to exit the program: ")
    if menu != "5":
        if menu == "1":
            newTransaction = (input("Enter new transaction: "))
            transactions.append(newTransaction)
            print("Added")
        elif menu == "2":
            target = input("Edit transaction: ")
            if target in transactions:
                transactions.pop(transactions.index(target))
                print("Removed")
            else:
                print("Transaction not found.")
        elif menu == "3":
            transactions[input("Enter the transaction key to edit: ")] = input("Enter the new transaction key: ")
        elif menu == "4":
            print("******************\n** Transactions **\n" + str(transactions) + "\n******************")
        else:
            print("Invalid input.")
    else:
        break

I am brand new to Python, trying to figure out how to use all of these functions
Answer: You just need to make sure transactions is not in the while loop. Because it was being reset to [] every iteration.
addTransaction = "1"
deleteTransaction = "2"
editTransaction = "3"
displayTransactions = "4"
exit = "5"
transactions = []

while True:

    menu = input("**********Main Menu***********\n1.  Add Transaction\n2.  Delete Transaction\n3.  Edit Transaction\n4.  Display Transactions\n5.  Exit the Program\n\nChoose a menu option from 1-4 or 5 to exit the program: ")
    if menu != "5":
        if menu == "1":
            newTransaction = input("Enter new transaction: ")
            transactions.append(newTransaction)
            print("Added")
        elif menu == "2":
            target = input("Remove transaction: ")
            if target in transactions:
                # Use remove to remeve the first occurance of a value
                transactions.remove(target)
                print("Removed")
            else:
                print("Transaction not found.")
        elif menu == "3":
            transactions[input("Enter the transaction key to edit: ")] = input(
                "Enter the new transaction key: ")
        elif menu == "4":
            # Use join to join elements in a list
            print("******************\n** Transactions **\n" +
                  ", ".join(transactions) + "\n******************")
        else:
            print("Invalid input.")
    else:
        break

You may also want to experiment with match. Which is a Python switch case basically
menu = "1"

match menu:
    case "1":
        # Code here for when menu = 1
    case "2":
        # Code here for when menu = 2
    case _:
        # Code here for when menu != 1 or 2
        print("Error")

Comment: Ah I see. I was under the assumption that the list might need to move further inward but that makes sense that it should be outside of the loop. Thank you much
Comment: No worries Tyler :)


Derivation/Properties of Nonparametric Survival Function Hypothesis Test

Question: Suppose two samples of right-censored failure time data:
$$\boldsymbol{X_1} = \{(X_{i1}, \delta_{i1}) = (\min(T_{i1}, C_{i1}), 1_{T_{i1} < C_{i1}}): i = 1, ..., n_1$$
$$\boldsymbol{X_2} = \{(X_{i2}, \delta_{i2}) = (\min(T_{i2}, C_{i2}), 1_{T_{i2} < C_{i2}}): i = 1, ..., n_2$$
where $T_{ij}$ are the underlying failure times and $C_{ij}$ are the censoring times. Suppose for each sample, the failure times are distributed according to survival functions $S_1$ and $S_2$, respectively. We are interested in testing whether $S_{T_2}(t) = S_{T_1}^\beta(t)$ and so we propose the hypotheses:
$$H_0: \beta = 1, H_1: \beta \neq 1$$
Deriving the log-likelihood function for $\beta$ and differentiating with respect to $\beta$, we obtain the score function under the null hypothesis:
$$S(\beta=1) = \sum_{i=1}^{n_{2}} \left\{ \delta_{i2} + \log(S_{T_2}(X_{i2})) \right\}$$
Questions:

Is the expected value of the score function equal to 0? How can one show this?
How does this likelihood based test reduce to the log-rank test? Is there any connection?
Are there any references to formal likelihood based testing procedures for survival analysis?
Comment: Just to clarify: is $\beta$ simply an exponent, so that you can write $\log  S_{T_2}(t) = \beta \log  S_{T_1}(t)$?
Comment: Yes, that is correct
Answer: What you describe is a proportional hazards model. The hazard function $h(t)$ is:
$$h(t)=-\frac{d\ln S(t)}{dt}.$$
If $\ln S_2(t) = \beta \ln S_1(t)$ for all $t$ as you posit, $h_2(t) = \beta h_1(t)$ and $\beta$ is simply the (constant) hazard ratio $h_2(t)/h_1(t)$. All the standard results under proportional hazards for equivalence of the score and log-rank tests, asymptotic equivalence of score and likelihood-ratio tests (a general result for likelihood-based models), etc., follow.
For a a reference on likelihood-based analysis of survival data that covers non-parametric, semi-parametric, and parametric models, I continue to refer to Klein and Moeschberger's Survival Analysis from 2003. Section 3.5 shows the forms of likelihood construction for all types of truncated and censored data, which I've summarized here. Applications and examples abound therein.


finding equivalence class of a set $U$

Question: Let $R$ be an equivalence relation on a non empty set $X=[0, 1].$ $x R  y$  iff $x=y$ or $x, y \in \{0, 1\}$.
Define $R[A]=\{y \in X: x R y ,\text{for  some $x \in A$}  \}$
Then what is $R(U)?$, where $U=(0, 1/2]$
my ans is $R(U)=U$ but the given ans is $\{0\}\cup U$
Comment: Your answer is correct.
Answer: You are correct.
$\operatorname R{(0;1/2]}~{=\{y\in[0;1]: \exists x\in(0;1/2]~(x\operatorname R y)\}\\=\{y\in[0;1]: \exists x\in(0;1/2]~(x=y\vee(x\in\{0,1\}\wedge y\in\{0,1\}))\}\\=\{y\in[0;1]: \exists x\in(0;1/2]~(x=y)~\vee~\exists x\in(0;1/2]\cap \{0,1\}~(y\in\{0,1\})\}\\=\{y\in[0;1]: \exists x\in(0;1/2]~(x=y)~\vee~\bot\}\\=\{y\in [0;1]\cap (0;1/2]\}\\=(0;1/2]}$

finding equivalence class of a set $U$


Remove a number using regex

Question: I want to remove only  1214" in "ilanlar\u0131 1214", "count"" or remove  2808" in "ilanlar\u0131 2808", "count"". How can I do by using regular expression in python?
I tried this code.
for line in fileinput.input('sektorler.json', inplace=True):

    print(line.replace("^\d+\," , ""))

Comment: just use `\d+"` with `re.sub`. `str.replace` doesn't support regex
Answer: You need to use re.sub which takes regex as first parameter. replace method must take a string as  parameter.
re.sub(r'\d+"', "", strin)

Comment: How can I write re.sub(r'\d+"', "", strin) in my for loop?
Comment: just replace your print function with `print(re.sub(r'\d+"', "", line))`

Remove a number using regex


What is a 0 (zero) step?

Question: I have been watching James Harden and his "creative" ways to take extra steps without being called for a travel.
One concept that he uses is a "0 step." I'm having a hard time figuring out what a 0 step is, not so much with the general concept in which it is a step before a player gathers his dribble, but with how it is enforced.
What is a 0 (zero) step with respect to how is it enforced?
Answer: I can only respond with the FIBA not NBA view. FIBA travel rule was aligned to match NBA in 2017.
The zero step refers to the step taken when gaining control of the ball.
When dribbling, the zero step gathering happens as the ball is gathered in 2 hands or let it rest in 1 hand.
Similarly when moving and catching a ball.
Here is a link to a related Question with NBA reference
NBA traveling - conflicting rules

What is a 0 (zero) step?


Drupal 7 access arguments

Question: Is this right? I want to only give access to the people who have 'Download Original' checked in permissions.
<code>function userDownload_menu() {
  $items['user/download'] = array(
   'title' => 'User Download',
   'page callback' => 'user_download_init',
   'access arguments' => array('Download Original'),
   'type' => MENU_SUGGESTED_ITEM,
 );

return $items;
}
</code>
If this is correct it's not working for me. Otherwise how can I pass a user role to this?
Comment: Have you defined the new permissions in your module ?
Comment: Download Original is already defined in the permissions page, My thought was anyone that has this checked on the permissions page could use this module?
Comment: Have you tried with a custom `access callback` function ?
Comment: I decided not to fight it and add Hook permission, thanks!
Answer: You need to use Hook permission to define the permission within your module

Drupal 7 access arguments


Chart.js responsive option - Chart not filling container

Question: Check out this fiddle. What am I doing wrong? Isn't the responsive option supposed to force the chart to fill it's container?

  <canvas id="myChart"></canvas>

Answer: Sorry about this, but I realized that the version I was using was outdated. For future reference, I found an up to date version of chart.js here.
//cdn.jsdelivr.net/chart.js/1.0.1-beta.4/Chart.min.js

Here is the updated fiddle
Comment: maintainAspectRatio: false, inside your options might help that


The Span of a list of vectors

Question: Is the given Proof Correct?
Theorem. Given a vector space $V$ over a scalar field $\mathbf{F}$ and a list of vectors $v_1,v_2,...,v_{m-1},v_m$ The span of a list of vectors is the smallest subspace to contain all the vectors in the above list.
Proof. For the purpose of this proof we use $\mathcal{S}(U)$ to represent the proposition that $U$ is a subspace of $V$. Consider now the following sets
$$W=\left\{U\subseteq V\middle|\mathcal{S}(U)\ and\ v_1,v_2,...,v_{m-1},v_m\in U\right\}$$
$$span(v_1,v_2,...,v_{m-1},v_m)=\left\{\sum_{i=1}^{m}a_iv_i\middle|\forall i\in\{1,2,...,m-1,m\}(a_i\in\mathbf{F})\right\}$$
Consider now the following Lemmas.
Lemma $(1)$. $span(v_1,v_2,...,v_{m-1},v_m)\in W$.
Proof. Let $\sum_{i=1}^{m}a_iv_i$ and $\sum_{i=1}^{m}b_iv_i$ be arbitrary members of $span(v_1,v_2,...,v_{m-1},v_m)$, evidently $\sum_{i=1}^{m}(a_i+b_i)v_i\in\ span(v_1,v_2,...,v_{m-1},v_m)$ implying that $span(v_1,v_2,...,v_{m-1},v_m)$ is closed under addition.
Consider now an arbitrary $\lambda\in\mathbf{F}$ and $\sum_{i=1}^{m}c_iv_i\in span(v_1,v_2,...,v_{m-1},v_m)$ evidently $\lambda\sum_{i=1}^{m}c_iv_i=\sum_{i=1}^{m}\lambda c_iv_i\in span(v_1,v_2,...,v_{m-1},v_m)$ implying that $span(v_1,v_2,...,v_{m-1},v_m)$ is closed under scalar multiplication.
Consider now the linear combination $\sum_{i=1}^{m}d_iv_i$ where $\forall i\in\{1,2,...,m-1,m\}(d_i=0)$ consequently $\sum_{i=1}^{m}d_iv_i=\sum_{i=1}^{m}0v_i=0$ since $0v_i=0$.
In a similar fashion we can see that $\forall i\in\{1,2,...,m-1,m\}(v_i\in\ span(v_1,v_2,...,v_{m-1},v_{m}))$.
Lemma $(2)$. $\forall U\in W(span(v_1,v_2,...,v_{m-1},v_m)\subseteq U)$.
Proof. Consider now an arbitrary $U\in W$ and assume that
$\sum_{i=1}^{m}a_iv_i\in span(v_1,v_2,...,v_{m-1},v_{m})$ since $v_1,v_2,...,v_{m-1},v_m\in U$ closure under scalar multiplication implies that $a_1v_1,a_2v_2,...,a_{m-1}v_{m-1},a_{m}v_m\in U$ and since $U$ is closed under addition it follows that $\sum_{i=1}^{m}a_iv_i\in U$, consequently $span(v_1,v_2,...,v_{m-1},v_{m})\subseteq U$.
Taking the above two lemmas together we have the required result.
$\blacksquare$
Comment: This is perfect.
Answer: Your proof is indeed correct. I will just make a small amount of suggestions:

There is no need to introduce the concept of $\mathcal{S}(U)$. Simply writing $U\leqslant V$ means that $U$ is a vector subspace of $V$.
There was no need, within the proof of lemma 1, of proving that $0\in\operatorname{span}(v_1,\ldots,v_m)$. When you have a subset $U$ of a vector space which is closed under addition and multiplication by a scalar, the only thing that is still needed in order to prove that $U$ is a subspace is that $U\neq\emptyset$. But you proved right after that $v_1,\ldots,v_n$ belong to your space. Therefore, it cannot be empty.
Comment: @AtifFarooq I know. But if $U\neq\emptyset$, then the existence of $0$ is automatic. indeed, if $v\in U$, then $0=v+(-1)v\in U$.
Comment: Is the reason behind the second point the fact that $0v=0$ is implied by closure under scalar multiplication and is therefore an equivalent condition to that of the existence of the $0$ vector.

The Span of a list of vectors


Move a site hosted on IIS/MS SQL Server across to LAMP stack

Question: I have a Drupal 7 site which is currently hosted in a Windows servers environment (e.g. IIS and MS SQL Server). The site needs to be moved over to Platform.sh, which is using the LAMP stack.
I am wondering if there are likely to be any issues with doing this? For example, is it possible to simply export the existing database from MS SQL Server and then import it into MySQL on the new site using drush?
Answer: There shouldn't be any issues as such if you properly follow the steps of Migrating a Drupal Site. You can find detailed steps on How to Migrate a Site.
This documentation provides a detailed documentation on Backing up and migrating a site.
Regarding taking a database backup of Site, you can checkout Backup and Migrate Module for quick and easy database backup of site. Here's how you can quickly setup Backup and Migrate module and backup your site databse.


Definição das regras do RealTimeDatabase

Question: Como deve ser minhas regras, para que um usuário logado no app tenha acesso, possa ler e escrever apenas nos seus pedidos ???
<code>{
</code>
"pedidos" : {
    "-LMqiTIhAr-VUMKpq8FD" : {
      "name" : "asdasdsa",
      "tel" : "213"
    },
    "-LMr1wgwinGyew0rVpWs" : {
      "name" : "sadasd",
      "tel" : "123"
    }
  },
  "users" : {
    "-LMrEQ9Jb7KbkaqhHyMQ" : {
      "cnpj" : "123456",
      "email" : "email@example.com"
    }
  }
}
Answer: Para aplicar a regra de acesso dos pedidos (e do próprio usuário), será necessário adicionar o UID (ID de usuário do Firebase Authentication) no caminho que será controlado.
UID do usuário exemplo: "rvCXWGhMkbYul6wS9gfxQSAXbmq1"

{
   "pedidos":{
      "rvCXWGhMkbYul6wS9gfxQSAXbmq1":{
         "-LMqiTIhAr-VUMKpq8FD":{
            "name":"asdasdsa",
            "tel":"213"
         },
         "-LMr1wgwinGyew0rVpWs":{
            "name":"sadasd",
            "tel":"123"
         }
      }
   },
   "users":{
      "rvCXWGhMkbYul6wS9gfxQSAXbmq1":{
         "cnpj":"123456",
         "email":"firstname.lastname@example.com"
      }
   }
}

Regra para gravação e leitura:

{
  "rules": {
    "pedidos": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid",
      }
    },
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid",
      }
    }
  }
}

Fonte: https://firebase.google.com/docs/database/security/?hl=pt-br


chromatic descent on minor chord

Question: In popular music I often hear a chromatic descent on some minor chords where the root note of the chord descends downward. So in C major if you take the A minor chord and descend the bass note chromatically from A down to E for example you get a whole different bunch of chords there.
Are those different chords or is this just seen as A minor over a descending bassline? This is by far the most popular example but if anyone else can show me some more examples I would appreciate it. The Beatles (Something) and Queen (Bohemian Rhapsody) did this a lot and the music books rationalize these movements by naming each separate chord, but is this the best way to see this?
Answer: TL;DR depends on the song.  Sometimes one is obviously better than the other, but most of the time it's somewhere in the middle and both interpretations are valid.

This is often called a "line cliché", and depending on how it's executed it can sound either like harmonic movement or just like a moving baseline with "pedal notes" in the top.  It can be completely chromatic, or it can include whole steps too.  It occurs in major and minor keys (C, CΔ7/B, C7/B♭, F/A, Fm(6)/A♭ is pretty common in wishy washy love ballads too haha)
Often how to notate it (or think of it) isn't really a case of "this or that" but of perspective, both things are true, but different songs lean in different directions.
Are you trying to create an effect of constant harmony with a shifting bass, or are you trying to give a sense of harmonic movement. Or from a listener's perspective, which one does it sound more like?  Generally, if it sounds like everything in the song is harmonically static, with just a wandering bass, then that's probably the best way to transcribe it.  If it sounds more like a "chord progression", then it's best to write it like that.
A lot of it comes down to voicing, often in more "harmonic movement" sounding implementations of the line cliché, the voicings of the rest of the band change to accomodate the harmonic movement.  (so in a band, the guitar for example won't just keep playing the same chord, but play different chords in addition to the bass playing different notes.  Or on a piano, both the left and the right hand will change, not just the left hand.)
So let's say we have a common minor line cliché (just one example, there are many more)
1 Am, Am/G, Am/F# Am/F
vs
2 Am, Am7/G, Am6/F♯ Am/F
vs
3 Am, Am7/G, F♯ø, FΔ7
These are all ways of writing the essentially same chords.  Generally a guide for me is whether it's literally only the bass that's changing, or whether there are harmonic changes throughout the range (in the "left hand" and "right" hand in piano terms, but in a whole arrangement, what are all the other instruments doing?")
Generally for me "1" implies a very rigid arrangement with only a moving bassline, whereas the 3rd one implies proper solid harmonic movement (that may include other extensions and more interesting voicings).  If something is in the a "there's a bit of harmonic movement but it's only really the bass" then I'd lean towards the 2nd option; hedging my bets.
The other thing is how much does the arrangement tolerate the clashes caused by a line cliché.  In the example I gave above, there were none; but when it's a pure chromatic line cliché, there's often a clash caused by that second chord.  So Am, Am/G♯... for example.  In fast more animated pop music (and often in pop music), you often just basically ignore it, keep playing A minor in the top and treat the ensuing weird chord as just a passing chord to the next note.  On the other hand, in slower music (or in musical styles or bands with more of a focus on harmony), you'll find there will often be changes in the harmony to accompany that major 7th. E7/G♯, G♯dim, G♯+. The first two of these are very different from Am/G#, and so really need to be written.
But even in this case, there's still a middle ground there too, sometimes you don't really change the harmony (like with a G♯dim chord), you just try and avoid playing any As so there's no clash, and so you get an aug chord almost by accident. (i.e. ACE goes to G#CE).  In that case I'd write it as G♯+ or G♯Aug, but honestly maybe in a pop context I'd instead write "Am/G♯"(no root) just to not scare people who don't really feel comfortable with Aug chords.
This answer could do with some refining, I'll pop back and clean it up later and maybe add some examples.  Hopefully I've basically answered your question though.
Comment: just to give an example off the top of my head where I certainly *would* write explicit chords, have a listen to this. http://youtu.be/NkCjGjt4e_4 .  For me that'd be C-, B°, E♭6/B♭, Aø, A♭7, G+7     (or in more ASCII notation, `Cm, Bdim, E♭6/B♭, Am7(♭5), A♭7, Gaug7`)    If you wrote that as just Cm over a bunch of roots, you'd lose way too much harmonic information there. (in case the link dies, it's tempo de amor from "Os Afro Sambas" https://youtu.be/jXOJnnWaDnc)
Answer: I have seen the term CESH used in multiple sources: Chromatic Embellishment of Static Harmony.
There are common forms in major and minor.

Because by the Dave Clark Five displays the ascending chromatic line in major: G G+ G6 G7
My Funny Valentine the Rogers & Hart standard displays the descending chromatic line in minor: Dm DmΔ7 Dm7 Dm6

In my experience these lines are used to embellish a tonic chord.
Both major and minor forms lead easily to the subdominant.

...Are those different chords or is this just seen as A minor over a descending bassline?

With jazz symbols this would be described as Am AmΔ7 Am7 Am6
In classical Roman numerals I would simply label it with i and the chromatic line would be considered decorative/passing motion.
In both systems it is viewed as one chord. That is why it is regarded as static in the term CESH the single chord is not changing.
Answer: I was thinking also of this line cliché and as you say the Beatles ... I remember when I heard the first time the White double album: there are more than only one of this:
While my guitar gently weeps
and other LP's: Fixing a hole,
etc. all little varied.
other examples: I heard the voice of Jesus say (Edwin Hawkings)
Thanks to Some_Guy for the term Line Cliches:
http://www.thejazzpianosite.com/jazz-piano-lessons/jazz-chord-progressions/line-cliches/

As you can see there are  several different chord progressions built together with this line downstep.
There is also a piano concerto by Bach:
It's the Larghetto of BWV 1055

chromatic descent on minor chord


container with volatile POD type

Question: I have some (say, dynamically generated) code and STL container with POD data (say, std::vector< T > of static_assert(std::is_floating_point< T >::value, "!");) which accessed from that code.
Apparently I need to declare the data with the volatile qualifier. But in such case gcc emits an errors:
c:\mingw\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++\ext\new_allocator.h:110: ошибка: invalid conversion from 'volatile void*' to 'void*' [-fpermissive]
       { ::operator delete(__p); }

c:\mingw\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++\bits\stl_construct.h:75: ошибка: invalid static_cast from type 'volatile double*' to type 'void*'
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

c:\mingw\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++\bits\stl_algobase.h:372: error: invalid conversion from 'volatile void*' to 'void*' [-fpermissive]
      __builtin_memmove(__result, __first, sizeof(_Tp) * _Num);
                                                         ^
c:\mingw\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++\bits\stl_algobase.h:372: error: invalid conversion from 'const volatile void*' to 'const void*' [-fpermissive]

Is this the only solution, that I should provide my own allocator with proper correction of pointer conversions?
Comment: _'Apparently I need to declare the data with the volatile qualifier.'_ Just for curiosity: Can you point out a reasonable use case for such construct?
Comment: @g-makulik `std::vector< volatile double >.data()` passed to dynamically generated code as value of base register to access `std::vector`'s elements. OK?
Comment: @g-makulik Or even all the elements of `std::vector< volatile T >` R/W accessed from plenty of threads.
Answer: If you have to cast from volatile T * to T* you need to use const_cast (surprise, surprise!). Further cast to void * will require static_cast or reinterpret_cast.
Comment: I.e. `static_cast< void * >(const_cast< typename rebind< std::remove_volatile< value_type > >::pointer >(_p))` ?
Comment: @KDukales: Well, don't know rebind... But something along the lines.
Comment: `template< typename U > struct rebind { using other = xallocator< U >; };` is mandatory for STL containers part of some allocator `xallocator` implementation, as I know.
Answer: A vector of volatile objects cannot work with the standard allocator. There is a GCC bug open on this, and it looks like a defect in the standard, not in GCC.
You have to provide your own allocator.

container with volatile POD type


netbios domain rename

Question: we have windows server 2008 r2 domain controllers. the forest and domain functional level is windows server 2003 (it's possible to raise the levels). we have an exchange 2010 server.
i would like to rename the netbios domain name (pre-windows 2000 domain name). i don't touch the dns domain name.
so if i just rename the netbios domain name is there any impact to the exchange organisation?
a best practice for renaming the netbios domain name would be nice.
Answer: I have seen this request numerous times in numerous forums.  Rather than reinvent the wheel, I want to point you to a blog article written by Ace Fekay that does an excellent job explaining how to perform this task.
http://msmvps.com/blogs/acefekay/archive/2009/08/19/domain-rename-with-or-without-exchange.aspx
Comment: The linked blog no longer contains portions of the process.  Effectively the same steps are in TechNet (the blog likely plagiarized them): http://technet.microsoft.com/en-us/library/cc794869(v=ws.10).aspx
Answer: You will need to do a full domain rename (which you can't do since you are running Exchange) or a domain migration to a different domain (which will require a new FQDN domain name)

netbios domain rename


Java: Why is this loop throwing me a java.lang.IndexOutOfBoundsException?

Question: In the following sample code, I'm moving through two large arrays, 40,000+ indices, of x and y coordinates. However, I'm being thrown the java.lang.IndexOutOfBoundsException upon reaching the final index - as I've deduced with much testing. I'm aware that this exception is thrown when referring to an index that's out of bounds, however, I don't think I'm referring to any out of bounds indices. Furthermore, it seems as if this exception is only being thrown on certain computers. Any kind of help is much appreciated.
BufferedImage img = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = img.createGraphics();

for(int i = 0; i < arrayList.size()-1;){
    for(int j = 0; j < arrayList2.size()-1;){
        g2d.setColor(col);
        g2d.setStroke(new BasicStroke(1));
        g2d.setRenderingHint(
              RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawLine(arrayList.get(i),
                  arrayList2.get(j),
                  arrayList.get(i+1),
                  arrayList2.get(j+1));
        i++;
        j++;
    }
}

Comment: Can you post the exception you are getting?
Comment: You can include your increment expressions in the for loop parenthesis, if that helps alleviate confusion.
Comment: This is why you should use for loops properly, with your index incrementation at the top of the loop where it belongs. Voting to close as a typo.
Comment: @HovercraftFullOfEels I apologize for not explaining previously in my context, however, due to the actual project I'm coding, it's necessary to iterate through the lists at the same time, not through all of the first one and then the second one, if that makes any more sense. Sorry!
Comment: No, that makes no sense at all, and again is the reason for your bug.
Answer: The problem here is that you are incrementing i in the inner loop, instead of after the inner loop completes.
The following code should behave better:
for(int i = 0; i < arrayList.size()-1; ++i){
    for(int j = 0; j < arrayList2.size()-1; ++j){

        g2d.setColor(col);
        g2d.setStroke(new BasicStroke(1));
        g2d.setRenderingHint(
              RenderingHints.KEY_ANTIALIASING,
              RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawLine(arrayList.get(i), arrayList2.get(j), arrayList.get(i+1), arrayList2.get(j+1));
    }
}

If arrayList has 10 elements, and arrayList2 has 20 elements, then your code will iterate the inner loop 19 times.  On each run of the inner loop, you will increment both i and j.  After the tenth iteration of the inner loop, then i and j both equal 10, and the code arrayList.get(i+1) will fail.
Comment: Yes! That's awesome - Thank you so much!


How can I make a PDF output file form Excel in Vba access

Question: I used to print Excel file in Vba Access by this code :
Excel_App.ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True
How can I make a PDF from Excel file in Vba Access?
Comment: please indent the line of code by 4 spaces so that it shows up as code
Answer: You should try like this method..
Example-
Private Sub Prepare_PDF_Click()
Dim MyFullName As String
Dim xlAppFTP As Object, xlWb As Object, xlWs As Object
Set xlAppFTP = CreateObject("Excel.Application")
Set xlWb = xlAppFTP.Workbooks.Open("X:\ANALYSIS\GHH.xlsm")
MyFullName = "X:\ANALYSIS\GHH" & format(Now(),"YYYYMMDD") & ".pdf"
xlWb.ExportAsFixedFormat Type:=0, FileName:=MyFullName, _
Quality:=1, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

For More Information. Go to this Site
Comment: Thanks a lot, it works fine. I need to have this pdf format in landscape orientation. I will ask in another question, please give me the answer.


jQuery - Separate text into strings

Question: Lets say my HTML looks like this:

12345, 23, 64229, 359

This paragraph can have hundreds of values separated by comma.
It can also be empty.
I wanna make these values into links.
The first value should link to "http://www.example.com/?id=12345"
The second value to "http://www.example.com/?id=23"
..and so on.
What would be the best way to do this?
Answer: You can use a regex .replace(), something like this:
$("p").html(function(i, h) {
  return h.replace(/\d+/g, function(m) { return "http://www.example.com/?id=" + m; });
});

You can test it out here, or to make them clickable links:
$("p").html(function(i, h) {
  return h.replace(/\d+/g, function(m) {
     return ""+m+"";
  });
});

You can give it a try here.
Answer: Try it out: http://jsfiddle.net/uJRb6/
var nums = $('p').text().split(/\s*,\s*/);
var tags = '';

    $.each(nums,function(i,val) {
        tags += '' + val + '
'
    });
$('body').append(tags);

If you're concerned about the security of the content, you could do this:
var nums = $('p').text().split(/\s*,\s*/);
var tags = [];

    $.each(nums,function(i,val) {
        tags.push($('',{text:val + ' ', href:'http://www.example.com/?id=' + val}));
    });
$(tags).appendTo('body');

Answer: you don't need jQuery for this, you can mostly do this with pure javascript:
vals = $('p').html().split(',');
for(var i in vals) {
  tags += 'link
'
}
$('body').append(tags)

Comment: Not to be difficult, but aside from the string appending, this *is* mostly jQuery :)
Comment: `for/in` over an Array is not a good idea. You should use a `for` loop.

jQuery - Separate text into strings


git cloning. What am I doing wrong

Question: It has been a little time since I did my last cloning from a repository. My situation is the following:
There is a repository in github that I want to clone into my local system.
I go to the github page and there are two options for cloning: download as a zip file or open with github desktop. Let's put the github desktop aside for a while.
Now, there is another option for cloning. I go to my terminal and do git clone <address of the repository>
In both cases I do get a copy of the repository on my local system successfully but it is not a git repository (Of course I can do git init to make it one but I am not sure it is the correct procedure-therefore this question)
Of course there is no origin that link this local copy to the github repository.
My goal is to have a local copy that I can pull frequently so that I can always have an actualized version of.
So my question is what is the correct procedure to clone a github repository to my local system so that I can be linked to it and can frequently pull to?
Answer: The "Download ZIP" option does not download a clone, instead it only downloads the latest commit without any history (i.e. there is no .git directory inside of it).

what is the correct procedure to clone a github repository to my local system so that I can be linked to it and can frequently pull to?

Use your terminal and run git clone <address> - it will be a git repository and it will have GitHub set up as a remote (as origin). Don't forget to cd into the clone directory after it's created in order for the git command-line to work on that repo.
It's likely you can't see the .git directory because you have "Show hidden (dot-prefixed) files" disabled - you'll see it if you run ls -al to show all files.
You will see the remotes by running git remote -v - but only if you cd into the newly created repo directory.
Comment: Thank you! I was just forgetting to cd into the clone directory!

git cloning. What am I doing wrong


Views: Show All Distinct Dates

Question: I have a custom content type with a date field that includes year, month, day, hour and minute. If I create a view of all the node start dates I get something like this
2014-10-23 13:00:00
2014-10-24 18:30:00
2014-10-24 21:00:00
2014-10-25 09:30:00
2014-10-25 10:00:00
2014-10-25 13:00:00
2014-10-25 18:30:00
2014-10-25 21:00:00

I want to create a view that lists only the unique days in ascending order. If possible I'd also like to rewrite these as links. Ideally I'm looking to generate something like
Thursday, October 23 2014
Friday, October 24 2014
Saturday, October 25 2014

or even better
Thursday, October 23 2014
Friday, October 24 2014
Saturday, October 25 2014

I've tried aggregating but I have to install extra modules to get the day granularity and even then I can't sort by date ASC. I've tried grouping but that just add extra headers I can't rewrite as links plus it means I still output a line for each node like this
Thursday, October 23 2014

Thursday, October 23 2014
Thursday, October 23 2014
Thursday, October 23 2014

Friday, October 24 2014

Friday, October 24 2014
Friday, October 24 2014

Saturday, October 25 2014

Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014
Saturday, October 25 2014

because the view is only using one field and if I hide it the view doesn't work. I've also used 'Distinct' and 'Pure Distinct' but they don't seem to do anything.
Is there something I'm misunderstanding? I don't get why this is so much trouble to do.
Answer: This video https://www.youtube.com/watch?v=Cp2SPiwA2Qg shows exactly wat you want. I ussualy follow these steps:

Add a second date field to the view.
In the configuration of that field

Configure the field to only display the year
Exclude the field from display

In the format settings of the view, group by this field.
Comment: That's not quite what I'm looking for. That view gives you

`date
--title
--title
date
--title`
I only want to show the dates, no other fields. Basically I only want to show the field I am grouping by.
Comment: Then you just have to change the title field with the date field...

Views: Show All Distinct Dates


jQuery ajax: Request a page that contains JS

Question: I need to apply AJAX loader that loads some different contents form the page, to a existing CMS.
The problem is that some of those contents, contain included JS Files or inHTML JS.
$.ajax({
type: "GET",
url: refURL,
success: function(resultData){
//returns the content in $content
   showContents($(resultData), title);
},
error: function(){
  showContents("something went wrong", "ERROR 404");
}
});

showContents() uses .HTML() to place the content into $(resultData) after some fancy animation. This works fine as long as there is no JS in the requested pages..
Is there any way i could make this work?
Answer: Perhaps you should use directly the innerHTML property of the element you are using.
$('selector_for_element_to_hold_results')[0].innerHTML = resultData;

and pass it to the showContents method in raw format showContents(resultData, title);
(if the resultData is what you want to insert in the DOM)
Comment: resultData is what i insert into the DOM. this worked perfectly. Thank you!


Switch through Textboxes Automatically After reaching Max Length

Question: I am wondering if there is anyway to simulate exactly what happens when you type a PaysSafeCard pin. The PaySafeCard pin has 4 Textboxes and they are each 4 numbers long. Each one of them when filled, automatically tabs to the next one. All i want to do is do that in vb.net so I don't have to manually press Tab every time. I gave it some thought but i cannot find the command that checks if the Textbox has reached its maxLength so it Tabs to the next one.
Hopefully i made myself understandable :| , thanks for your time.
Answer: Kind of broad, but I'm kind of bored.
Yes, you can check the length of the TextBox.Text property each time it is changed. Use the TextChanged event. If the length is >= 4, you want to move to the next TextBox.
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
    If TextBox1.Text.Length >= 4 Then TextBox2.Focus()
End Sub

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    If TextBox2.Text.Length >= 4 Then TextBox3.Focus()
End Sub

Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
    If TextBox3.Text.Length >= 4 Then TextBox4.Focus()
End Sub

In my example there are 4 TextBoxes, numbered 1 to 4. It is a bit hard-coded but it works for just 4 TextBoxes.
This also adds a nice feel, so if you enter a TextBox which already has text, it will be selected.
Private Sub TextBox_Enter(sender As Object, e As EventArgs) Handles TextBox1.Enter, TextBox2.Enter, TextBox3.Enter, TextBox4.Enter
    DirectCast(sender, TextBox).SelectAll()
End Sub

Hope this helps
Comment: `In my example there are 4 TextBoxes, numbered 1 to 4.`, I see only three... ;)
Comment: OP can handle TextBox4 appropriately. `automatically tabs to the next one` is undefined for number 4


JSF - Selecionar Item de um Conjunto

Question: Quero fazer um xhtml que retorne uma lista de usuários e do lado apareça um botão para selecionar determinado usuário. Algo assim:
+----------------------------+
| ID | Usuário | (Botão) |
+----------------------------+
Minha duvida é: Como faço um laço de repetição no xhtml para construir a pagina com todos os objs q estão dentro do conjunto e qual é a melhor maneira para fazer o botão referencia o respectivo objeto de sua linha.
Se alguém puder me ajuda. Agradeço desde já.
Answer: Datatable é o que a maioria usa
http://www.primefaces.org/showcase/ui/data/datatable/edit.xhtml
Answer: Tente
<code><p:panelGrid columns="3"> .... </p:panelGrid>
</code>
O p: é do primefaces mas funciona tambem com JFS puro.
Comment: Me ative ao desenho.
Relendo a pergunta acredito o mais adequado a necessidade ser mesmo um dataTable como mencionado por outros colegas.
Answer: Jhow,
Como o Tiago falou acima, você pode utilizar o dataTable do PrimeFaces ou pode usar também o dataTable do JSF.
Segue um exemplo abaixo.
Vamos ter na sua classe "@ManagedBean("usuario")" uma lista do objeto que você quer inserir na tabela.
<code>    private List<Usuario> usuario = new ArrayList<Usuario>();

   <h:dataTable value="#{usuario.usuario}" var="u">

                <h:column>
                    <f:facet name="header">Order No</f:facet>
                    #{u.id}
                </h:column>

                <h:column>
                    <f:facet name="header">Product Name</f:facet>
                    #{u.nome}
                </h:column>

                <h:column>
                    <f:facet name="header">Price</f:facet>
                    #{u.sexo}
                </h:column>

                <h:column>
                    <f:facet name="header">Quantity</f:facet>
                    <h:commandButton value="submit" type="submit" action="#{usuario.fazAlgumaCoisa(u)}" />
                </h:column>

    </h:dataTable>
</code>
Segue um link de referência.
http://www.mkyong.com/jsf2/jsf-2-datatable-example/

JSF - Selecionar Item de um Conjunto


Adding content to a page through a module

Question: I just want to echo some words when a certain node comes up.
Currently however it doesn't echo within the content section, but above the header.
How do I get my module to echo the words at the top of the content section?
Comment: How are you "echoing words" currently? Are you wanting to echo the same words? or different words for each node?  Need more description... more details.
Answer: If the content is always static then you can look into adding it to a theme template file (by creating a subtheme).
Or you could add some php as part of preprocess_node in template.php to append/prepend the text to the content/body array.


Monte Carlo Simulation of AR(1) in R but Demeaned

Question: Suppose that I want to run $i=100$ simulations of the following AR(1) model over 10 time periods:
$ X_{t,i} = 0.5(X_{t-1,i}-\bar{X}_{t-1})+e_{t,i} $
Here $ \bar{X}_t$ refers to the mean across the $i=100$, hence it is given by:
$ \bar{X}_{t-1}=\frac{1}{100}\sum_{i=1}^{100}X_{t-1,i}$
How would I go about this? Any help would be appreciated!
Comment: Generate one epoch $t$ at a time. Where is the difficulty?
Answer: You can compute a simulated sample by using the recurrence relation. But, you need an initial sample that has the right variance and covariance between the different samples $i$.
You need to figure out the covariance of different pairs of variables

Same time different series $\Sigma_1 = X_{t,i},X_{t,j}$
Different time same series $\Sigma_2 = X_{t,i},X_{t+1,i}$
Different time different series $\Sigma_3 = X_{t,i},X_{t+1,j}$
Same time same series $\Sigma_4 = X_{t,i},X_{t+1,j}$

You can do this with your relationship
$$X_{t,i} = 0.495 \, X_{t-1,i}- 0.005 \, \sum_{j \neq i} {X}_{t-1,a}+e_{t,i}$$
Based on that you can make relationships between the covariances using the rules for covariances of linear combinations.
I can get to
$$\Sigma_4 = Var(X_{t,i}) = 1 + (0.495^2 + 99 \cdot 0.005^2) \Sigma_4 + (2 \cdot 0.495\cdot - 0.005 \cdot 99 \cdot + 0.005 \cdot 0.005 \cdot 99 \cdot 98) \Sigma_1 = 1 + 0.2475 \Sigma_4 - 0.2475 \Sigma_1$$
And for the covariance $X_{t,i}, X_{t,j}$
$$\Sigma_1 = (2\cdot0.495\cdot -0.005\cdot + 98\cdot 0.005\cdot 0.005 ) \Sigma_4 + ( 2 \cdot 0.495^2 + 4 \cdot 98 \cdot 0.495 \cdot -0.005 + 97\cdot 98 \cdot 0.005 \cdot 0.005 ) \Sigma_1 = -0.0025 \Sigma_4 -0.2425 \Sigma_1 $$
From which it follows that
$$\Sigma_1 = -\frac{0.0025}{1.2425} \Sigma_4$$
$$\Sigma_4 = \left( 1-0.2475(1+  \frac{0.0025}{1.2425}
)  \right)^{-1} \approx 1.328025 $$
and $\Sigma_1 \approx  -0.002672$

<code>set.seed(1)

### computation of the covariance matrix of the samples within the same time
s4 = 1/(1-0.2475*(1-0.0025/1.2425))
s1 = s4*-0.0025/1.2425
Sigma = diag(rep(s4-s1,100))+s1

### compute the initial time
x = matrix(MASS::mvrnorm(1,rep(0,100),Sigma),100)

### compute new times using the recurrence
for (i in 1:10^2) {
   x = cbind(x,0.5 * (x[,i] - mean(x[,i])) + rnorm(100))
}

plot(x[1,],type="l", col = rgb(0,0,0,0.1), xlab = "time", ylab = "value")
for (i in 1:100) {
    lines(x[i,],col=rgb(0,0,0,0.1))
}
lines(x[1,], col = 2)
</code>

Alternatively a simpler derivation might be made by adding all equations together to get
$$\bar{X}_{t-1} = \frac{1}{n} \sum_{i=1}^n X_{t,i} =  \frac{1}{n} \sum_{i=1}^n \left( 0.5(X_{t-1,i}-\bar{X}_{t-1})+e_{t,i} \right) =  \frac{1}{n} \sum_{i=1}^n  e_{t,i}$$
from which it follows that $\bar{X}_{t-1}$ is Gaussian noise.
We can now also compute the following
$$(X_{t,i}-\bar{X}_{t}) = 0.5(X_{t-1,i}-\bar{X}_{t-1})+e_{t,i} - \frac{1}{n} \sum_{i=1}^n  e_{t,i}$$
which means that $(X_{t,i}-\bar{X}_{t})$ can be described by an AR(1) process. Although I am not sure how to continue. We can compute the variance of $(X_{t,i}-\bar{X}_{t})$, but we also need to know the correlation between $(X_{t,i}-\bar{X}_{t})$ and $\bar{X}_{t}$ in order to compute the variance of $X_{t,i}$.


overlay submit feedback

Question: This might be a very simple question, but I can't figure out the answer.
I love the overlay module in drupal 7, but I am annoyed by the lack of visual feedback when a form is submitted in an overlay. eg. admin/structure/block, hitting submit doesn't give any indication that something is happening in the background.
I would love to know what I have to do to attach some behavior to the submit button of a form in an overlay that provides visual feedback that the form has been submitted (like greying out the overlay or something).
Comment: This is one of the reasons I turn off Overlay as soon as I can. :-)
Comment: Is this a question about how to add JavsScript or how to write JavaScript that does the above?
Comment: The question is what is the JavaScript that does the above. I know how to write and add it (different ways) but haven't been able to figure out WHAT to write
Answer: I just added a block with following code to the content region of my administration theme

Comment: Yeah, that would do it.
Answer: You could use jquery-loadmask. It looks like it grays out the div and puts a throbber over it.
Comment: Thanks for answering, I don't think I even need another library. Guess I figured it out

overlay submit feedback


How do I store a custom field type settings for checkboxes?

Question: I have already created my field_type,field_widget, field_formatter  using Drupal console and also a set of checkboxes options to appear in field settings, I get this all working but when I select few options and save the settings it isn't storing those values , so when I go back again to field_settings I see the previously checked options are empty.
 public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$elements = [];

$elements['cars'] = array(
  '#type' => 'checkboxes',
  '#title' => t('Types of cars?'),
  '#options' => array('ferari' => t('Ferari'), 'prius' => t('Prius'), 'jaguar' => t('Jaguar'), 'lamborghini' => t('Lamborghini')),
  '#default_value' => $this->getSetting('cars'),
);
return $elements;}

This is a sample piece of code of mine, I need a way of storing the values that I check on the options.
Comment: `[]` is perfectly valid in the PHP version required to run Drupal 8; that is not surely the problem, nor does it make any difference.
Comment: change $elements = []; to $elements = array(); and try apart all is well.
Answer: You need to implement defaultFieldSettings() method in your class:
public static function defaultFieldSettings() {
    return [
        'cars' => [],
      ] + parent::defaultFieldSettings();
  }


pthread mutex lock/unlock in while(1)

Question: I'm trying to write very simple multi threading program just to get the catch of it but I fail to understand what exactly is wrong in one of the cases. So:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>

char string[100];
pthread_t thr_id_rd;
pthread_t thr_id_wr;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond, cond1;
int read = 0;

void *thread_rd()
{
    pthread_mutex_lock(&lock);
    while (1) {
        pthread_cond_wait(&cond, &lock);
        printf("rd: entered: %s\n", string);
        pthread_cond_signal(&cond1);
    }
    pthread_mutex_unlock(&lock);
}

void *thread_wr()
{
    pthread_mutex_lock(&lock);
    while (1) {
        printf("wr: enter something: ");
        scanf("%s", string);
        pthread_cond_signal(&cond);
        pthread_cond_wait(&cond1, &lock);
    }
    pthread_mutex_unlock(&lock);
}

int main(int argc, char *argv[])
{
    pthread_create(&thr_id_rd, NULL, thread_rd, NULL);
    pthread_create(&thr_id_wr, NULL, thread_wr, NULL);

    pthread_join(thr_id_rd, NULL);
    pthread_join(thr_id_wr, NULL);

    return 0;
}

The above seems to work correctly. But when I edit the two threads like this:
void *thread_rd()
{
    while (1) {
        pthread_mutex_lock(&lock);
        pthread_cond_wait(&cond, &lock);
        printf("rd: entered: %s\n", string);
        pthread_cond_signal(&cond1);
        pthread_mutex_unlock(&lock);
    }
}

void *thread_wr()
{
    while (1) {
        pthread_mutex_lock(&lock);
        printf("wr: enter something: ");
        scanf("%s", string);
        pthread_cond_signal(&cond);
        pthread_cond_wait(&cond1, &lock);
        pthread_mutex_unlock(&lock);
    }
}

I'm getting undefined behavior - sometimes it's OK sometimes the program is stuck. According the man pages pthread_cond_wait must be called with mutex locked but there is no such restriction for _cond_signal (Question: What is the best practice?). So I decided to call it with mutex locked...
Obviously I'm complete newbie so please excuse my stupid question :(
I'll be very grateful if someone can explain this to me...
Comment: In fact this was really a stupid question but I was frustrated I needed some time away from it to see how stupid I am (and actually read some man pages...) :D As I said I have absolutely no experience with threads... :(
So the mutex can be held by only 1 thread at a time so at pthread_thread_create both threads are racing for the mutex and who is locking it first can't be defined.
My solution is additional flag to determine which thread to lock the mutex first.
Is this correct? Again I'll really appreciate if someone can share some "good practices"...
Answer: pthread conditional variable signals are not persistent. If you signal when nothing is waiting for the signal, the signal will be lost. So you could see something like this:
WR: Lock
WR: Read input
WR: Signal cond
WR: Wait for cond1 (implicitly unlocks)
RD: Lock
RD: Wait for cond (implicitly unlocks)

At this point you have a deadlock - both threads are waiting for signals which will never come.
The usual pattern with condvars is to have a flag (or some other persistent condition) paired with the conditional variable. You can then do a loop like:
while (!flag) pthread_cond_wait(&cond, &lock);

To signal, you set the flag, and then signal the condvar to wake up any waiters.
In your case you can actually use string as your flag - have string == NULL be the wake-up condition paired with cond1 and string != NULL paired with cond. Now if your reader thread enters the lock late it'll see that string != NULL and not wait on the condvar.

pthread mutex lock/unlock in while(1)


what is event log permission in security permissions of event logs

Question: I have a group called event log in security permissions list of event log which I did not configure I want to know whether it is a default user group or not
http://tinypic.com/r/2dv6545/8
check with the link
Answer: Is this on Windows 7 or Server 2008 (or newer)? If so, then this article will answer your question. In short:

Eventlog and EventSystem are Virtual Accounts. Virtual Accounts were introduced in Windows Server 2008 and Windows 7.
(1)Virtual Accounts aren't created but are used to run services. You access them by typing NT SERVICE[service name] into the 'This account' field on the service's Log On tab in the service management console and leaving the password fields blank. Virtual Accounts have the same permissions as Network Service: They have standard user rights on the local machine but communicate with the network as the local computer account.
Comment: Thank you kate and I have another doubt..(i.e) can you give me detailed explanation or link about windows user account like                 1.what is shared user account 2.what is network service account etc..


Comparing column values with a TOPN measure

Question: I am new to Power BI. I have a measure that returns TOPN values based on another measure like the following:
MaxMovingAverageSecond = TOPN(1,
    VALUES('Main Table'[Seconds]),
    [DifferenceBetweenAverages10Seconds],
    DESC)

And now I am trying to find the next highest value based on a condition. The condition is that the seconds should be 30 points higher than the value in the measure MaxMovingAverageSecond.
The following measure is my attempt to find the second highest value:
NextMaxMovingAverageSecond =
CALCULATE(
    VALUES('Main Table'[Seconds]),
    TOPN(
        1,
        FILTER(
            ALL('Main Table'[Seconds]),
            'Main Table'[Seconds] > [MaxMovingAverageSecond] +30
        ),
        [DifferenceBetweenAverages10Seconds],
        DESC
    )
)

It returns a blank value but it works when I replace the MaxMovingAverageSecond with any integer. So, it works with:
            'Main Table'[Seconds] > 200

I will appreciate any help.
Answer: Is this related to question: TOPN with condition based on a measure ?
NextMaxMovingAverageSecond =
  var firstMaxSecond = [MaxMovingAverageSecond]
  return CALCUALTE(
    [MaxMovingAverageSecond],
    'Table'[Seconds ] > firstMaxSecond + 30
  )

Comment: Yes, but this was a specific one about the comparison. Thanks for the help Sam.


OpenSSL issue on Debian server

Question: I've been battling this annoying issue for quite some time now, and it's bugging me a lot that I can't find any fix for it.
When I use "tail -f" to my error_log file to check for errors on my webserver, one specific error keeps popping up all the time, every visitor and page-refresh generates this issue.
I've been googling and searching here on Stack Overflow for a looong time, but nothing is directly related to the problem.
So the error that is thrown looks like this:

[Fri Aug 17 00:16:23 2012] [error] [client xx.xx.xx.xx]
  PHP Warning:  PHP Startup: Unable to load dynamic library '/usr/lib/php5/20090626/openssl.dll' - /usr/lib/php5/20090626/openssl.dll: cannot open shared object file: No such file or directory in Unknown on line 0, referer: http://mysite.dk/

What could I do?
I have tried to remove OpenSSL, and re-installed it again with no luck. I've tried to upgrade every PHP-related package and still didn't work.
grep -ir ssl /etc/php*

gives:
/etc/php5/cli/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/apache2/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/apache2/php.ini.saved_by_psa.08.03;20:24:;extension=openssl.dll       ; moved to conf.d/zend_extensions_psa.ini by Plesk
/etc/php5/apache2/php.ini:;extension=openssl.dll        ; moved to conf.d/zend_extensions_psa.ini by Plesk
/etc/php5/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/cgi/conf.d/zend_extensions_psa.ini:extension=openssl.dll

Comment: Let's see `grep -ir ssl /etc/php*`
Comment: /etc/php5/cli/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/apache2/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/apache2/php.ini.saved_by_psa.08.03;20:24:;extension=openssl.dll       ; moved to conf.d/zend_extensions_psa.ini by Plesk
/etc/php5/apache2/php.ini:;extension=openssl.dll        ; moved to conf.d/zend_extensions_psa.ini by Plesk
/etc/php5/conf.d/zend_extensions_psa.ini:extension=openssl.dll
/etc/php5/cgi/conf.d/zend_extensions_psa.ini:extension=openssl.dll
Answer: So you've got four copies of zend_extensions_psa.ini and all of them are trying to load this nonexistent file. Edit them all, delete or comment out the lines mentioning openssl.dll, and all should be well.
The Debian package management system treats your modifications to configuration files with great respect. It doesn't undo them when you upgrade or reinstall a package unless you remove the the package with dpkg --purge or install the new one with --force-confnew.
Answer: It could be that you have something like this in your PHP configuration (php.ini maybe):
extension_dir=/usr/lib/php5/20090626/

and then
extension=openssl.dll

And it could cause a problem because there is no file like that in a given path. This could be caused by manually copying extensions and/or different extensions installers.

OpenSSL issue on Debian server


Retrieve all values Mongo Query

Question: I am new to MongoDB. I am trying to retrieve all values for 'des' from termL list. It contains string value.
Sample data
{'_id': ObjectId('5d19fbc0e4b0490ed4c5a02d'), 'uID': '2004', 'documentTitle': 'Training the trainers','termL': [{'code': '30', 'des': 'SVM'}, {'code': '50', 'des': 'NN'}]}

Mongo query
record = mycollection.find({}, {
    "uID":1,
    "documentTitle": 1,
    "indexTermList": {'$elemMatch':{'des':1}}
}).limit(1)

Comment: Something like {'des':['SVM','NN']}. The des field should contain all values.
Comment: What's the expected output ?
Answer: You can use $project operator and the dot notation to reshape your data:
db.collection.aggregate([
    {
        $project: {
            _id: 1,
            uID: 1,
            documentTitle: 1,
            des: "$termL.des"
        }
    }
])

Mongo Playground
Comment: Thanks. How can I limit the number of results
Comment: @joel use $limit as the next statement (https://docs.mongodb.com/manual/reference/operator/aggregation/limit/)

Retrieve all values Mongo Query


Can we generate a valid $9\times 9$ sudoku using this algorithm?

Question: Begin with a board of $9*9$ cells, each of the cells has no value but is possible to contain a number from $1$ to $9$ (I will call the numbers can be assigned to a cell is guesses; the amount of numbers in a guesses is number of guesses; and a board of $9\times 9$ guesses is guess map). Repeat these following steps:

Determine the collection of cells that have the least number of guesses in the guess map.

Two situations can happen:
2.1. If the number of guesses is not $1$: randomly choose a cell in the collection, randomly choose a number from the guesses, and mark that number as the value of that cell.
2.2. If the number of guesses is $1$: we use a queue to handle this. If the number of cells in the collection are more than one, which cell turned to be $1$ (number of guesses is $1$) first will be added to the queue first and so on; in case several cells turned to be $1$ at the same time, randomly choose the order of these cells and add them to the queue. Get the cell at the front of the queue and mark the last guess of that cell as the value of it.

Remove the value of that cell from the guesses of its row, column and its neighbor. For instance, the cell at coordinates $(3,2)$ ($0$-based, the origin is at the top left of the board) and contains number $5$, $5$ will get removed from the guesses of row $3$ and column $2$. The neighbor of $(3,2)$ cell are $3*3$ cells where rows are from $3$ to $5$ and columns are from $0$ to $2$.

Does this strategy work?

Example of the procedure:
Suppose we have a board which has no value and contains the guess map like below:

Step 1: since all the cells have number of guesses of $9$, the collection is all 81 cells.
Step 2: the number of guesses is $9$, not $1$, we will go with step 2.1. The cell that is chosen is $(3,2)$ and the value is $5$, so we write $5$ to that cell.
Step 3: remove $5$ from row $3$, column $2$ and its neighbor. The result is the image below.
Answer: The answer is no, because it is possible to set up situations where the exact value of certain cells is not known, but they still restrict the possible values in other cells.
A simple example is something known as a "naked pair". This is a pair of cells in the same row, column or box that share the same two candidate values. For example, suppose that the cells in r1c1 and r2c1 have both been reduced to containing only the values 3 and 5, but it is not known which order.
Whichever value r1c1 takes, r2c1 must take the other - if one is a 3, the other must be a 5 and vice versa. As a result, both 3 and 5 can be eliminated as candidates from every other cell in column 1 (and in the top-left box, in fact). However, your algorithm does not do this, and so it is feasible that it might pick, for example, r8c1 and try to set it as a 5 which will break the sudoku.
Comment: I got the idea. Thanks for pointing it out!
Comment: Are you sure it fully answers the question? Remember there is no clue initially in the grid, and that the algorithm provided has a heuristic that might avoid this type of situation. For example, this algorithm seems to always work on 4x4 sudoku. After all the complexity of filing a sudoku with no clue given is far lower than when we have clues.
Comment: Even though the heuristic does try to pick from cells with the fewest available candidates, it's still possible to set up situations where this kind of problem will occur - if not a naked pair, then a naked triple or quadruple is entirely possible (and there are more sophisticated patterns that are built into actual puzzles all the time that take it to another level entirely).
Comment: Do you have an example where you can set up such a situation? It is actually rather different to set up a naked pair in a composed puzzle than in a puzzle that is generated from the start using this heuristic. I tried to do it (not too hard though), but couldn't do it.


Why does this assembly code show 2 different colours?

Question: I've compiled this with nasm, and i'm running it through bochs. In my mind the 2 colour variable should make it print the 2 lines in blue. It actually prints one brown and one white. I cannot figure it out though. Any help immensely appreciated
    [BITS 16]
    [ORG 0x7C00]
    main:

    ;set video mode
    mov ah,0x00     ;function ref
    mov al,0x10     ;param - video mode
    int 0x10

    mov si, TestString
    mov bl,Color        ; Normal text attribute
    call PutStr

    mov si, TestString
    mov bl,Color2       ; Normal text attribute
    call PutStr

    jmp $

    ;-------------------------------- End of running code

    PutStr:
    ; Set up the registers for the interrupt call
    mov ah,0x0E         ; The function to display a chacter (teletype)
    mov bh,0x00         ; Page number

    .nextchar:
    lodsb               ; load string byte from SI into AL and increments SI
    or al,al            ; check for end of string
    jz .endofstring     ; jump to end if null

    int 0x10            ; Run the BIOS video interrupt
    jmp .nextchar       ; Loop back round to the top

    .endofstring:
    ret

    Color db 0001b
    Color2 db 0001b
    TestString db 'Hello world',13,10,0,0

    times 510-($-$$) db 0       ; Fill the rest of the sector with zero's
    dw 0xAA55           ; Add the boot loader signature to the end

Answer: The problem is actually with the usage of the Color and Color2 identifier. You need to "dereference" them to get the actual value of what they "point" to:
mov bl, [Color]

Check out Effective Addresses in the NASM manual for more information.
Comment: yeah, i changed it to: Color db 1b Color2 db 1b, I had to keep the db or it throws an error but it makes no difference. I know if I put the value into the mov as you suggest "mov bl, 1b" it work fine but I'm trying to understand how variables work so it's not really a solution for me. Thanks anyway though
Comment: What i mean is neither "Color db 1" or "Color db 00000001b" change the colour to blue. They are bright pink and red regardless of what i seem to put as the value.
Comment: no further ideas? it's driving me nuts!! thanks again for trying though.
Comment: Yeah, I got it now. I'll change the answer
Answer: db allocates a byte of memory and sets the symbol to be the address of that memory (hence the need to dereference it).
If you just want a symbolic name for a constant value, use equ:
Color equ 0001b
...
mov bl, Color
...


docx Template Docx4j replacing text in Java

Question: Im new to Docx4j and my task is to replace some Text of a docx Template.
I read the getting Started Guide of docx4j but I don't think I fully understood the whole concept.
Well Anyway... I already tried [the unmashalling Template of Docx4j][1],
which worked fine with the given docx, but then I got the same Problem when I tried it on my own template
The Exceptions say, that the HashMap doesnt contain valid keys or values, and therefore it doesnt replace the placeholders.
I replaced the
<w:proofErr w:type="spellEnd"/>

by disabling the spellchecking, but it still didn't work... And it also takes quite some time to run the app.
In didn't understand the databound example in the Getting_Started.pdf, so I'm running out of options...
How can I simply replace some String-Texts from a docx?
EDIT:
I found out that if I add some Text to the unmarshallFromTemplate.docx and save it, that it wont replace the new lines of text.
the  - Tags are somehow splitted into multiple Tags:
<w:p w:rsidR="002512F8" w:rsidRDefault="002512F8" w:rsidP="002512F8"><w:r><w:t>My</w:t></w:r><w:r w:rsidR="001A5174"><w:t xml:space="preserve"> favourite ice cream is ${DEGREE</w:t></w:r><w:r><w:t>}.</w:t></w:r><w:bookmarkStart w:id="0" w:name="_GoBack"/><w:bookmarkEnd w:id="0"/></w:p>

editing the Text in the document.xml, and adding the missing Information didnt help much.
well anyway here is the document.xml of the Template.docx that im using:
http://uploaded.net/file/vz4qr23o
EDIT 2:
Well guys. I found a quite suitable workaround for myself and dont know why it took so long to figure it out.
As I was saying: The runs where splited up, and the reason for this was the ${} in my opinion. Therefore I simply used a # before my Placeholders and rewrote every placeholder, so that it would all be in one run.
Had to switch couple of times to the document.xml and rewrite the passages but then it worked. Then I simply used a replace(placeholder, xml) and replaced the text of the marshalled document.xml, then I unmarshalled it again.
Worked. End of Story, fuck the nightly build or the mappings. THX
Comment: Please fill this question with all required data; posting a link to other forums on which you asked it is not a good practice.
Answer: docx4j source code has been on GitHub for a while now; that svn repository is obsolete.
The equivalent sample is now called VariableReplace.  That code is a bit more efficient, but you need to build it yourself, or use a current nightly build.
You'll probably find running VariablePrepare addresses your issue.
Comment: Hi! Thx for the advice. I tried to get it to work like in this thread: http://stackoverflow.com/questions/15664726/optimize-docx4j-performance But it still doesnt work. Now I cant even see my textarea, where my placeholders where kept in. Isnt there an easier approche? Maybe simply plain text replacement?
Comment: You'll need to unzip your docx, and post the contents of word/document.xml so we can see what you are talking about.  Edit the question and add it there.
Comment: I found [>this link<](http://openxmldeveloper.org/discussions/formats/f/13/p/2389/8183.aspx#8183) to be helpful also after finding that the VariableReplace link above is dead
Comment: See now https://github.com/plutext/docx4j/blob/master/src/samples/docx4j/org/docx4j/samples/VariableReplace.java
Comment: Works for me, pretty amazing. Just had to add filterSettings.setRemoveBookmarks(true);
Answer: The placeholder search and replace code built in to docx4j works just fine, but if you're having issues with placeholders getting broken up by rsid entities, you need to ensure that you have grammar and spell-checking disabled when saving your "template" (i.e. source) document. This will help prevent your text runs becoming fragmented (note that you might want to disable proof-reading too, as that inserts bookmark tags here there and everywhere).
Once you've done the search and replace and have a new / updated document, you can re-enable spell-checking easily enough. This thread has more on RSIDs: turnoff rsid's spell check & grammar check in generated xml


Using LIKE in bindParam for a MySQL PDO Query

Question: I've read multiple examples on how these queries should be written but I'm struggling to get this specific like to run when using bindParam
Would this be the correct way to match usernames that begin with a?
$term = "a";
$term = "'$term%'";

$sql = "SELECT username
        FROM `user`
        WHERE username LIKE :term
        LIMIT 10";

$core = Connect::getInstance();

$stmt = $core->dbh->prepare($sql);
$stmt->bindParam(':term', $term, PDO::PARAM_STR);
$stmt->execute();
$data = $stmt->fetchAll();

Answer: No, you don't need the inner single quotes so just $term = "$term%";
The statement you're running now would try to match 'a%' instead of a%
bindParam will make sure that all string data is automatically properly quoted when given to the SQL statement.
Comment: Here is a sample code: https://gist.github.com/arsho/a203e7bc156ea566587361a76038f020
Answer: You can use bindValue , suppose you are having a $query = "search string"
$stmt->bindValue(':term', $query.'%'); // this will do like search for "search term XXXXX"

similarly
$stmt->bindValue(':term', '%'.$query.'%');

or
$stmt->bindValue(':term', '%'.$query);


Get field value directly from inside views-view-list.tpl.php

Question: Inside views-view-list.tpl.php there is a loop like this:
<?php foreach ($rows as $id => $row): ?>
  <li class="<?php print $classes_array[$id]; ?>"><?php print $row; ?>

<?php endforeach; ?>

I want to be able to access the actual values of the fields inside each item, rather than passing off the rendering of the html to views-view-fields.tpl.php.
In pseudocode, I would like to do this (THIS CODE DOES NOT WORK):
<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_field_name']; ?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
  <?php print $row->$fields['field_my_second_field_name']; ?>
<?php endforeach; ?>

Would I actually use the $row object, or would I use something else?
Answer: took me a while to work this out so sharing the solution i used.
<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_field_name', $id);?>
<?php endforeach; ?>

<?php foreach ($rows as $id => $row): ?>
    <?php print $view->render_field('field_my_second_field_name', $id);?>
<?php endforeach; ?>

Comment: Why is this not working! I am wondering how it got three votes
Answer:
views-view-list.tpl.php file it's a view template to display a list of
  rows, not fields.

Theming only fields:
<?php foreach ($fields as $id => $field): ?>

<?php print $field->content; ?>

<?php endforeach; ?>

* file: views-view-fields--[view name]--[display].tpl.php
Theming the whole output:
<div class="<?php print $classes; ?>">
    <?php foreach ($view->style_plugin->rendered_fields as $delta => $item): ?>

<?php print $item['field_my_field_name']; ?>

    <?php endforeach; ?>

* file: views-view--[view name]--[display].tpl.php
Answer: There is a $view variable inside most Views templates that contains the entire View Object.  Inside of it, you can access the raw results via $view->result which is basically an array of the rows.  Throwing in a drupal_set_message('
' . print_r($view->result, TRUE) . '
') or equivalent will give you an idea of what you have to work with.
Answer: The simplest way is : $fields["field_name"]->content; Where field_name -> cck field name.
Hope that will help !!
Cheers ! Raj


Using pointers to verify whether the string consists of only a finite set of substrings

Question: I had earlier written a program in java which takes in as input a string as an input and checks if it is valid or not. The rules for deciding are:
1) The string is recognizable if and only if it contains the words "pi", "ka","chu" as its fragments, in any order repeated any number of times .

2) If it contains any other fragments( or subsequence), Then it is unrecognizable

I was able to do so in java a bit easily as java has better support for string functions. My code is (this works fine)

import java.util.Scanner;
public class RecognisingWords {
public static void main(String[] args) throws Exception
{
    Scanner inp= new Scanner(System.in);
    String str;
    System.out.println("Enter the string to be tested:");
    str=inp.nextLine();

    while(str.length()>0)
    {

    if(str.startsWith("pi"))
    {
        str= str.substring(2);
    }

    else if(str.startsWith("ka"))
    {
        str= str.substring(2);
    }

    else if(str.startsWith("chu"))
    {
        str= str.substring(3);
    }

    else
    {
        System.out.println("Unrecognisable Sequence");
        break;
    }

    }

    if(str.length()==0)
    {
        System.out.println("Recognisable Sequence");
    }
}
}

However when i am writing the corresponding program in c (using pointers), my code runs into infinite loop. Please check my code and point wher the error is. Also is it possible to implement this program without using pointer ??

#include <stdio.h>
#include <stdlib.h>
#include<string.h>

int main(void)
{
char str[10];
int len=0,flag=1;
char *ptr;

printf("Enter the string : ");
gets(str);
len=strlen(str);
ptr=str;

while(*ptr!='\0')
{
    if(!strcmp("pi",ptr))
    {
        ptr=ptr+2;
    }

    else if(!strcmp("ka",ptr))
    {
        ptr=ptr+2;
    }

    else if(!strcmp("chu",ptr))
    {
        ptr=ptr+3;
    }

    else
    {
        printf("String not recognised");
        flag=0;
        break;
    }
}

if(flag==1)
    printf("String is recognised");

return 0;
}

I have corrected some of my very silly mistakes. Hope You people don't mind
Comment: Oh yes!! My mistake but even after correcting that it runs into infinite loop
Answer: You probably want to advance your pointer by ptr += 2 or ptr += 3 rather than changing the  character pointed by the pointer: *ptr = ....
The logic in the loop is also not correct. You should loop until the current position of the pointer points to 0 (NUL character - which is the string terminator in C), by while (*ptr != '\0'). You seem to have missed out the break in the last else block.
There is also the problem with gets(str), which may cause buffer overflow problem in C. Security stuffs aside, your program will behave unexpectedly if you enter a string longer than 9 characters.
There are potentially other problems with your C code that I cannot list out by just eyeballing your code.
EDIT
Another problem is that you used strcmp, which will compare everything pointed to by the pointer with the fragment. i.e. If the input is "pikachu", it will compare "pi" with "pikachu" and finds that "pi" is lexically smaller than "pikachu" and it will show that the string is not recognized. You probably want strncmp, in which you can specify the number of characters to compare.
Comment: Okay !! Another of my silly pointer mistakes.. BUt even after that the program runs to infinite loop


Update existing 'paragraph' entity while changing the ID is not supported

Question: I'm trying to update a paragraph with this code:
<code>$entityManager = \Drupal::entityTypeManager();
      $paragraph = $entityManager->getStorage('paragraph')->load('1');
      $paragraph->set('field_test','testValue');
      $paragraph->save();
</code>
But I received this error:
<code>Drupal\Core\Entity\EntityStorageException: Update existing 'paragraph' entity while changing the ID is not supported. in Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 846 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).
</code>
Do you know why?
P.s. If I try to update with the last ID it works. It doesn't work only for old Paragraphs.
Comment: Maybe you have a hook that changes the ID to latest, thus; would explain why no error on last and error on the rest.
Comment: Paragraphs are not stand-alone entities. The error could be caused by an older paragraph now orphaned or you load an outdated revision. I'm not sure if it makes sense to load and save a paragraph out of context. What you are trying to achieve?
Comment: It might also be related to revisions and possibly a failed update process.  There are a lot of issues around updating to 8.7? and not having a default revision field properly set by the update process.
Answer: You could load the paragraphs through their parent entity to get the active revisions:
<code>$nids = \Drupal::entityQuery('node')
  // load only nodes where this paragraph reference field exists and has content
  ->exists('field_paragraph')
  ->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $node) {
  $paragraphs = $node->field_paragraph->referencedEntities();
  foreach ($paragraphs as $paragraph) {
    if ($paragraph->hasField('field_foo')) {
      $paragraph->field_foo->value = 'bar';
      $paragraph->save();
    }
  }
}
</code>
Comment: got the same error


Select a p tag depending on its content

Question: I have a HTML script

 some content

 some text content

Now, what I want to do is change the width of that paragraph which content image inside it, But rest of the paragraphs having text content will remain the same.
Say in our case:
Paragraph containing text : width=80%
Paragraph containing image : width = 100%
Can I achieve this through jQuery?
I tried some selectors :has and some others, but nothing seems to work.
Comment: Like this http://jsfiddle.net/j08691/onomcctx/?
Answer: You can use :has selector:
 $('p:has("img")').css('width','100%');

Comment: Ya, I achieved it with `:has` `jQuery('.post-content p:has(img)').addClass( "full-width-p" )`
Comment: but can we do this using inline css??
Comment: CSS do not have has selector. this can not be achieved with pure CSS.
Comment: @MilindAnantwar "this can not be achieved with pure CSS" ...yet. http://dev.w3.org/csswg/selectors-4/#relational
Answer: You can traverse the DOM using a parents function in jQuery.
$( 'p' ).css( 'width', '80%' );
$( 'img' ).parents( 'p' ).css( 'width', '100%' );

Answer: This can be implemented rather easily in plain JavaScript: just process all p elements, checking whether the element contains any img elements, and if not, setting its width. So unless you have special reasons (like uniformity of coding) to use jQuery, you can do it as follows:

window.onload = function() {
  var p = document.getElementsByTagName('p');
  for(var i = 0; i < p.length; i++) {
    if(p[i].getElementsByTagName('img').length == 0) {
      p[i].style.width = '80%';
    }
  }
}
p { outline: solid red } /* Just to show the widths */

 some content

 some text content

Answer: You can use JQuery to select the image node inside the paragraph, and once you get that object, just ask for its parent node

Select a p tag depending on its content


What is the origin of fans chanting players' names with an extended "u" sound?

Question: At many American sporting events, if a player with a "u" sound in his name is on the home team, and he enters the game or makes a play in the game, then there is a good chance the fans will chant his name with an extended "u" sound.
Here are a few examples:

Whenever fullback John Kuhn of the Green Bay Packers touches the ball at a home game, then the fans will chant "Kuuuuuuuuuhn".
In the 1990s, Daryl Johnston was a fullback with the Dallas Cowboys.  His nickname was "Moose".  Whenever he touched the ball at a home game, the fans would chant "Moooooooose".
Luke Walton was a basketball player for the L.A. Lakers, and whenever he entered a game at home, the fans would chant "Luuuuuuuuke".
In the 1980s, Joe Dumars was a basketball player for the Detroit Pistons, and whenever he scored a basket at a home game, the P.A. announcer would yell "Joe Duuuuuuuuumars!"

When did this tradition originate?
Comment: It dates at least back to the 60s, as [Ron Luciano](https://en.wikipedia.org/wiki/Ron_Luciano) mentions it in his books.
Comment: I don't have an answer for where it first started, but those long vowel sounds lend themselves to that type of call, and coupled with the fact that there's some irony in it sounding like booing when it's not, I wouldn't be surprised if it "originated" in a few different places.
Comment: Another example is Roberto Luongo of the National Hockey League. When he used to play for the Vancouver Canucks they would chant `Luuuuuuuuuuuu` after any significant save, although I am not sure if the Florida Panthers fans have kept up the tradition.
Comment: Another example is Ruud van Nistelrooy of United, where the fans would scream "Ruuuuuud" after he scores, which confused some people since it sounds like they are booing him :)

https://www.youtube.com/watch?v=-sHcp3-ka3M
Comment: It's a vowel sound. You can stretch vowel sounds more easily than consonants. I think it's the idea of stretching out names in general. You just happened to pick a bunch of examples with an 'ooooo' sound. I recall other names being stretched out without 'ooo' sounds such as "Darrrrrrrrr-illllllll [Darryl Strawberry]"
Comment: This same treatment is given to Panthers Linebacker Luke Kuechly.
Answer: Boog Powell played first base for the Baltimore Orioles from 1961 until 1974. I recall watching baseball on color TV (which was fairly new technology) and seeing Powell play for Baltimore against other American League teams. The Baltimore fans would chant, "Boooooog," when he did anything.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


A real differentiable function is convex if and only if its derivative is monotonically increasing

Question: I'm working on a problem in baby Rudin, Chapter 5 Exercise 14 reads:

Let $f$ be a differentiable real function defined in $(a,b)$. Prove that $f$ is convex if and only if $f'$ is monotonically increasing.

I am trying to prove that $f'$ is monotonically increasing under that assumption that $f$ is convex. I have written a proof, but a friend and I do not agree on the validity of my argument. Here is my argument.

First, assume that $f$ is convex. Since $f$ is differentiable and real on $(a,b)$, $f$ is continuous on $(a,b)$. So, for $a<s<u<v<t<b$, by the mean value theorem there exist points $y_1\in[s,u]$ and $y_2\in[v,t]$ such that
  $$
f'(y_1)=\frac{f(u)-f(s)}{u-s}\quad\text{and}\quad f'(y_2)=\frac{f(t)-f(v)}{t-v}.
$$
Then, by exercise 23 of chapter 4 (proven previously):
  $$
\frac{f(u)-f(s)}{u-s}\leq\frac{f(t)-f(v)}{t-v}
$$
  or,
  $$
f'(y_1)\leq f'(y_2).
$$
  Hence, $f'$ is monotonically increasing. $\hspace{3.5in}\square$

My friend claims that this merely proves that for any two arbitrary intervals $[s,u]$ and $[v,t]$ there are points that satisfy $f'(y_1) \leq f'(y_2)$. He says that what I need to prove is that for any two arbitrary points $y_1\leq y_2$ we have $f'(y_1)\leq f'(y_2)$. (I should mention that he doesn't know how one would do this.)
Is he right? Is my proof insufficient? If so, how can I fix it?
Comment: Your friend is correct.  If you want to show that a function is monotonically increasing you have to **choose** $y_1 < y_2$ and then show $f'(y_1) \leq f'(y_2)$.  You don't choose $y_1$ and $y_2$; they come as a consequence of your choice of $s,u,v,t$.  There's no guarantee that every $y_1$ and $y_2$ in $(a,b)$ can be gotten by choosing $s,u,v,t$ as you've done.
Comment: +1 for showing us your work and asking a clear question.
Answer: Your friend is right.
From the previously solved exercise, you can show that for arbitrary $s<t$ in $(a,b)$, $\lim\limits_{u\to s+}\frac{f(u)-f(s)}{u-s}\leq\lim\limits_{v\to t-}\frac{f(t)-f(v)}{t-v}$, so $f'(s)\leq f'(t)$.