readDouble(); java programming

Question: I tried to read the double value using read-double function but its reading as some other value, I gave the input as 15.00 it read as 825568816. please help me to get it correct.
    DataInputStream din=new DataInputStream(System.in);
    double d=din.readDouble();
    System.out,println(d);

Comment: I'd suggest the [Scanner](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html) class for this scenario.
Comment: Thanks Marc, but whats wrong with DataInputStream??
Comment: Look at Jon Skeet's answer below. `DataInputStream` is meant to be used with a `DataOutputStream`. His suggestions for other implementations are easier to use and will give you better results.
Answer: Basically, don't use DataInputStream if you're trying to read text. DataInputStream is meant for streams of data written by DataOutputStream or something similar. Read the documentation for readDouble to see exactly what it's doing.
Options for you:

Use Scanner and its nextDouble() method: my experience of questions on Stack Overflow is that Scanner is frankly a pain to use correctly
Create a BufferedReader wrapping an InputStreamReader, and then call readLine() to get a line of text, and Double.parseDouble() to parse that into a double.
A hybrid approach: use Scanner, but only to call nextLine() - just a simpler way to read lines of text from System.in, basically.

Additionally, you might want to consider using BigDecimal - the value "15.00" sounds like it might be a financial value (e.g. a price) - and those should be stored in BigDecimal as that can represent exact decimal values.

readDouble(); java programming


How to disallow users from changing their emails?

Question: I need this because it makes life a bit more difficult for 'professional' spammers who just change their emails after logging in, so that the can use that very email for the next registration, after being blocked.
Appreciate your hints.
Answer: You can either force users to confirm email change or protect the email field from changes.
Both modules have D6/7 versions. Second module can lock password and some other fields as well.
Comment: Great, as usual Drupal community offers more than you expect. That's partly why I love Drupal. Thanks mate.
Comment: I prefered 'email confirm' as a better solution but for some reason it did not install, neither through GUI nor drush. Any ideas?
Answer: There is a new module which is made to handle this situation perfectly.
The module User Account Permissions add the following new permissions for user accounts:

edit own user account
edit own email address
edit other user's email address
change own password
change other user's password
Answer: Or try to use Field Permissions module (D6 or D7). set custom permission to allow create but disallow to edit own field..
Comment: The module `Field Permissions` works fine with Drupal 8 but you could hide only custom fields. `User protect`works fin on D8 to hide user name, email, etc.
Comment: I don't think that works for the e-mail address, it doesn't show up in the field list to be edited like other fields.


Multiple mysql servers with one database?

Question: What are the options for having multiple mysql servers with the same database and data. I know there is replication but I have been reading that it can have issues especially if there are connection issues. Are there any alternatives to the built in replication that are reliable? Someone suggested getting a server on the same network so the mysql server can be accessed by all the servers over lan, but currently that is not an option for me.
Is mysql just not meant for replication? Is there another sql engine that is better for it?
Answer: There are a few options for replicating a MySQL database. Here are a few no-cost options:

MySQL 5.5 has a new semi-synchronous feature that increases the reliability
MySQL Cluster - community edition is no cost
Tungsten Replicator
DRBD and Linux HA

Tungsten and Linux HA both provide failover so that the master database will automatically move to another machine if the primary master fails. However, with DRBD, the second machine is typically passive, meaning that it doesn't serve any traffic at all, while with native MySQL or Tungsten you can use the slaves for reading data.
Comment: If the slave only needs to be able to read from a single table what would you recommend?
Comment: In order to make a choice a lot more detail is needed around your infrastructure and what you are trying to achieve.
Comment: I have a vbulletin forum and want to be able to use the user information from a remote server for a WCF service. I guess I could add an api to vbulletin to request information but the issue is that the forum server goes down a lot and I would like the program that uses the user table to not go down when the forum goes down.
Comment: In that case, default mysql replication would be fine. You can even specify the slave server to only replicate a single server
Answer: The obvious answer would be MySQL Cluster Manager, it costs though.
Comment: Do I need MySQL Cluster Manager for this or can I just manually configure MySQL Cluster?


CSV import by using Python

Question: I was trying to plot graph by using matplotlib. However, after I run my code, there is attributeError: modules object has no attribute 'pyplot' But the csv was available. What is the problem? Here is my code:
{
   import numpy as np
   import urllib
   import matplotlib.dates as mdates

   def bytespdate2num(fmt, encoding='utf-8'):
              strconverter = mdates.strpdate2num(fmt)
              def bytesconverter(b):
                     s = b.decode(encoding)
                     return strconverter(s)
              return bytesconverter

       def graph_data(stock):
              stock_price_url = 'http://ichart.finance.yahoo.com/table.csv?
              s=AAPL&d=9&e=14&f=2008&g=d&a=8&b=7&c=1984&ignore=.csv'
       source_code = urllib.request.urlopen(stock_price_url).read().decode()
       stock_data = []
       split_source = source_code.split('\n')
                 for line in split_source:
                      split_line = line.split(',')
                      if len(split_line) == 6:
             if 'values' not in line and 'labels' not in line:
                      stock_data.append(line)

date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
                                                      delimiter=',',
                                                      unpack=True,
                                                      # %Y = full year. 2015
                                                      # %y = partial year 15
                                                      # %m = number month
                                                      # %d = number day
                                                      # %H = hours
                                                      # %M = minutes
                                                      # %S = seconds
                                                      # 12-06-2014
                                                      # %m-%d-%Y
                                                      converters={0: bytespdate2num('%Y%m%d')})

plt.plot_date(date, closep,'-', label='Price')

plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Interesting Graph\nCheck it out')
plt.legend()
plt.show()

   graph_data('TSLA')
 }

Comment: `import matplotlib.pyplot as plt` ref : http://matplotlib.org/users/pyplot_tutorial.html
Comment: at witch line do you recieve the error? can you add stack trace
Comment: File "C:\Users\User\Downloads\Year 2\Own source\python\ex21.py", line 1, in   import matplotlib.pyplot as plt
  File "C:\Python27\lib\matplotlib\pyplot.py", line 27, in
    import matplotlib.colorbar
  File "C:\Python27\lib\matplotlib\colorbar.py", line 34, in
    import matplotlib.collections as collections
  File "C:\Python27\lib\matplotlib\collections.py", line 27, in
    import matplotlib.backend_bases as backend_bases
  File "C:\Python27\lib\matplotlib\backend_bases.py", line 46, in
    import matplotlib.widgets as widgets
Comment: File "C:\Python27\lib\matplotlib\widgets.py", line 20, in
    from .mlab import dist
  File "C:\Python27\lib\matplotlib\mlab.py", line 187, in
    import csv
  File "C:\Users\User\Downloads\Year 2\Own source\python\csv.py", line 1, in
    import matplotlib.pyplot as plt
AttributeError: 'module' object has no attribute 'pyplot'
Answer: import matplotlib.pyplot as plt
Ref : http://matplotlib.org/users/pyplot_tutorial.html

CSV import by using Python


Requiring the isomorphism between two FOL interpretations to be a bijection when proving they are elementary equivalent

Question: Assume we have a formula $F$ with $k$ free variables of some signature, and we also have two isomorphic interpretations $M_1$ and $M_2$ of that signature with $\alpha$ being the corresponding isomorphism. Let's prove
$$
\forall m_1, \dots, m_k : M_1 \models F(m_1, \dots, m_k) \iff M_2 \models F(\alpha(m_1), \dots, \alpha(m_k)),
$$
which is a slightly more generic claim, but would allow us to prove the original one by induction on the structure.

If $F$ is an atomic formula, then the claim follows from the fact that isomorphisms preserve predicates and functions.
If $F$ is a logical combination of one (using $\lnot$) or two ($\lor, \land, \rightarrow$) formulas, then it follows easily from the inductive hypothesis.
$\forall$ is expressible via $\exists$, so we proceed straight to that.
If $F(\xi_1, \dots, \xi_n)$ is $\exists \xi G(\xi, \xi_1, \dots, \xi_n)$: this is the interesting part. Let's fix $m_1, \dots, m_k$ and consider two subcases:

If $M_1 \models \exists \xi F(\xi, m_1, \dots, m_k)$, then, well, there exists some $m$ such that $M_1 \models F(m, m_1, \dots, m_k)$, and by the inductive hypothesis $M_2 \models F(\alpha(m), \alpha(m_1), \dots, \alpha(m_k))$, so $M_2 \models \exists \xi F(\xi, \alpha(m_1), \dots, \alpha(m_k))$.
If $M_1 \not\models \exists \xi F(\xi, m_1, \dots, m_k)$, assume still $M_2 \models \exists \xi F(\xi, \alpha(m_1), \dots, \alpha(m_k))$, and $m'$ is the value of $\xi$ that makes it true. Since $\alpha$ is an isomorphism, then there exists $\alpha^{-1}(m')$, and by the inductive hypothesis $M_1 \models F(\alpha^{-1}(m'), m_1, \dots, m_k)$, contradicting the claim.

One might note that we haven't really used that $\alpha$ is an isomorphism. Instead, we have only used its surjectivity, which brings two questions:

Is this proof correct?
If it is, can the surjectivity requirement also be dropped as the injectivity is? The claim looks symmetrical, so it would be surprising if it couldn't.
Answer: Let's identify the issue first, and then try to figure out where the omission occurs.
We want to argue that $\alpha$ preserves all formulas. In particular, this means that somewhere along the line we'll need to show (something which implies) that $\alpha$ preserves the formula "$\neg x=y$." But clearly this is equivalent to the injectivity of $\alpha$. So we can see that there must in fact be a gap somewhere in your argument, since in order to show that $\alpha$ preserves all formulas we must use injectivity somewhere.

OK, so where's the gap?
As written, I would say you need to be more explicit at (2). Specifically, the negation case is important: think about e.g. "$\neg x=y$" (and the relation between preserving this and being injective). So technically you've given the correct "shape," but the injectivity assumption on $\alpha$ is buried in behind the word "easily."
Another option would be to be more explicit at (1). Maybe by "preserves atomic formulas" you mean "preserves and reflects atomic formulas," or equivalently "preserves atomic and negated atomic formulas." In this case you will need to actually give an argument: while preservation of atomic formulas is built into the hypotheses (other than injectivity) on $\alpha$, the reflection of atomic formulas isn't.
Either way, something needs to happen to cover the negated atomic case; this isn't present in your proof as written, and accounts for the apparent unnecessity of injectivity.
Comment: Probably a dumb question, but why? In the negation case $F(\xi_1, \dots, \xi_n) = \lnot G(\xi_1, \dots, \xi_n)$, and $M_1 \models \lnot G(m_1, \dots, m_n) \iff M_1 \not\models G(m_1, \dots, m_n) \iff M_2 \not\models G(\alpha(m_1), \dots, \alpha(m_n)) \iff M_2 \models \lnot G(\alpha(m_1), \dots, \alpha(m_n))$, where the first and last equivalences are by definition of truthfulness in an interpretation, and the middle one is by the induction hypothesis.
Comment: @0xd34df00d It depends on exactly how you phrase the base case. What you've written is just that $\alpha$ *preserves* atomic formulas, but you also want it to *reflect* atomic formulas. (Or, maybe by "preserves" you mean "preserves in both directions.") The point is that when it comes time to argue that $\alpha$ preserves "$x\not=y$" (or if you prefer, reflects $x=y$) then you need the injectivity of $\alpha$.
Comment: It might be easier to start at the beginning: do you see why, in order to argue that $\alpha$ preserves $x\not=y$, we will need to know that $\alpha$ is injective?
Comment: @0xd34df00d I've edited my answer to be clearer; let me know if this doesn't improve things and I'll further edit or revert as preferred.
Comment: Ah, I see what you're saying now, thank you for the clarification! Yes, I meant "preserves and reflects", so that the implication in both directions holds (sorry, the book I'm using is written in another language, so I might be translating incorrectly). Further, your argument indeed shows that this essentially requires $\alpha$ to be injective, but here you seem to assume the interpretations are normal — or, in other words, that $=$ is interpreted as a match between two elements. That wouldn't be necessarily the case for non-normal interpretations, would it?
Comment: @0xd34df00d I'm not sure what you mean by "non-normal interpretation." "$=$" is always considered a binary relation symbol; moreover, in all modern presentations of first-order logic it's also considered a *logical* symbol (= present regardless of the language) and required to be interpreted as genuine equality. In the absence of equality, you in fact do not require injectivity a priori. For example, consider the empty language in FOL without equality; then *any* surjective function from one structure in this language to another satisfies your principles (cont'd)
Comment: since the only formulas are $\top$, $\perp$, and trivial variations of those (e.g. "$\forall x\exists y\top$").
Comment: Less trivially, suppose we have an arbitrary relation language $\Sigma$ and a $\Sigma$-structure $\mathcal{A}$. We can produce a "thick" version of $\mathcal{A}$ - call it $\mathcal{A}^+$ - by duplicating elements: the domain $A^+$ of $\mathcal{A}^+$ is $A\times\mathbb{N}$, and the interpretation is given by $R^{\mathcal{A}^+}((a_1, k_1), ..., (a_n, k_n))\iff R^\mathcal{A}(a_1,..., a_n)$ for each $n$-ary $R\in\Sigma$ (note that this would be much more complicated with function symbols). Now any "block-preserving" self-surjection from $\mathcal{A}^+$ is "FOL$\setminus\{=\}$"-elementary.
Comment: That explains it! The book I'm using considers `=` as a binary predicate, but it always points out explicitly whenever `=` is interpreted as equality.
Comment: @0xd34df00d Ah. What book are you using, out of curiosity?
Comment: Not sure if the reference would be useful since it's in Russian, but it's https://www.mccme.ru/free-books/shen/shen-logic-part2-2.pdf , based on lectures of Moscow State University's math department.


Preparing a product list but UI is not correct

Question: I have created a product list menu with a hover dropdown i.e when a user hovers on a particular menu the list will automatically be shown.
But there are 2 problems first is I want to divide the vegetable dropdown menu into 3 columns.
Secondly, when I hover correctly in between vegetable and spices dropdown menu the dropdown menu of both vegetables and spices starts shaking.
I am not getting the actual problem why is this happening.
please help.
I am Uploading the stackblitz link because the code is huge.
This is the link for the actual code on StackBlitz
This is the link to see the output of my code
Answer: 1) For your .column css, your width is set to 50% which signifies a maximum value of up to 2 columns per row. If you alter that value to 33%, you will be able to fit up to 3 columns per row. This is at line 57 inside your app.component.css file.
2) The shaking is occurring because the window width is changing when you hover over vegetable because of the scroll bar being activated. When that happens your current cursor position thinks that its in between of both vegetables and spices at the same time, creating the shaking effect and alternating between the drop down menus.
Comment: @Orbit Your welcome make sure you upvote the answer! Happy to help.


How to deselect a HTML button tag with a simple chrome extension

Question: I have created a chrome extension with a simple popup.html file that contains a button tag as first element inside the body. When I test it on Chrome 26 under OS X, each time I click on my  extension icon that triggers the popup, my button seems selected/focused given that I see it with a blue halo. I cannot figure out how to disable auto focus. It seems autofocus is applied on the first tag from the popup.html file. I tried to apply blur() on the button instance retrieved with document.getElementById but it does not work.
Is there any solution? workaround? alternative?
Answer: The only solution I found consists of adding tabindex="1" on the html tag. I tried to put focus on other elements or to use autofocus="autofocus" but this does not work.
Answer: You can set focus to element either by js el.focus() or by the new html5 autofocus="autofocus" attribute
You cannot remove focus from an element unless you set focus on some other element - so you can set focus on some bogus anchor element or something to remove the focus from your button


Expectation maxmisation algorithm increases true likelihood at each iteration

Question: I've heard that the EM algorithm ensures that the true likelihood is non-decreasing at each iteration of the algorithm, but I'm not sure why this is the case. I've provided a basic plot which I believe to illustrate the difficulty I have in understanding this.
To frame the question, let's first consider the EM algorithm decomposition, where $x$ is the observed data, $z$ is the missing data, $\theta$ represents the parameter set.
$$ L(\theta) \equiv \text{ln}P(x|\theta) = \text{ln}\left[\sum_{z}P(x|z,\theta)P(z|\theta)\right] $$
Multiplying by $\text{ln}\left[\frac{P(z|x,\theta\prime)}{P(z|x,\theta\prime)}\right]$ and adding and subtracting $L(\theta\prime) \equiv \text{ln}P(x|\theta\prime)$ yields
$$
\text{ln}\left[\sum_{z}P(x|z,\theta\prime)\frac{P(x|z,\theta)P(z|\theta)}{P(x|z,\theta\prime)}\right] - \text{ln}P(z|\theta\prime) + L(\theta\prime) \\
\geq \sum_{z}P(x|z,\theta\prime)\text{ln}\left[\frac{P(x|z,\theta)P(z|\theta)}{P(x|z,\theta\prime)P(z|\theta\prime)}\right] + L(\theta\prime)\ldots (\text{by Jensen's inequality}) \\
= \sum_{z}P(x|z,\theta\prime)\text{ln}\left[\frac{P(x,z|\theta)}{P(z,x|\theta\prime)}\right] + L(\theta\prime) \equiv B(\theta,\theta\prime)
$$
This represents the expression we want to maximize in the EM process; from this, we can see that $L(\theta\prime)$ is a lower bound for $L(\theta)$ (this bound is realized when $\theta$ is equal to $\theta\prime$).
Now assume two possible entry points (theta$\prime$1 and theta$\prime$2) to the EM process exhibited in the plot below. In this plot, the true likelihood is given by the L(theta) (blue) line whilst the function to be maximised is given by the B(theta,theta$\prime$) (orange) line.
The local maximum corresponding theta$\prime$1 (which corresponds to the lower bound scenario mentioned above, L(theta) = L(theta$\prime)$) does indeed increase L(theta); however, the local maximum corresponding to theta$\prime$2 doesn't increase L(theta). What's to prevent the theta$\prime$2 scenario from happening?

Also, I've also heard that the role of the expectation step is to equate $P(x,z|\theta)$ and $P(z,x|\theta\prime)$ which would achieve the lower bound scenario above, but I'm not sure how this works. I suspect that this property is linked to the answer to the above question. Perhaps somebody could elaborate on this.
Answer: I think your picture is misleading you.  Rather than envisioning a single orange lower-bound approximation to the true blue likelihood, instead you should be thinking of a series of orange lower-bounds that are approximations about particular points $\theta_t$.  In particular, the approximation is necessarily tightest about the approximation point. So at $\theta_2$ your orange approximation  must be closer to the blue curve than it is at $\theta_{2}^{\mbox{max}}$.  See figure (from wikipedia).

This follows from the EM derivation.  First observe that the incomplete data likelihood can be written as a ratio of a joint and a conditional: $p(X|\theta)=\frac{P(X,Z|\theta)}{P(Z|X,\theta)}$, and that the expectation over $Z$ leaves the LHS unchanged.  Restating this fact and taking logs,
$$
\begin{align*}
\log p(\mathbf{X}|\theta) &= E_z \left[ \log p(\mathbf{X},\mathbf{Z}|\theta) - \log p(\mathbf{Z}|\mathbf{X},\theta) \right] \\
\log p(\mathbf{X}|\theta) &
= \sum_{\mathbf{Z}} p(\mathbf{Z}|\mathbf{X},\theta_t) \log p(\mathbf{X},\mathbf{Z}|\theta)
- \sum_{\mathbf{Z}} p(\mathbf{Z}|\mathbf{X},\theta_t) \log p(\mathbf{Z}|\mathbf{X},\theta) \\
& = Q(\theta|\theta_t) + H(\theta|\theta_t).
\end{align*}
$$
So we hope to use $Q(\theta|\theta_t)$ as a surrogate of $\log p(\mathbf{X}|\theta)$, and the error from using this approximation is $-H(\theta|\theta_t)=Q(\theta|\theta_t)-p(\mathbf{X}|\theta)$.
Now, I contend that when $\theta = \theta_t$, then $-H(\theta_t|\theta_t)$ is minimized, thus the approximation is tightest.  In fact, this follows directly from $H$ being an expectation of a log-likelihood, which is maximized (thus $-H$ minimized) at its generative value,in this case $\theta_t$. (This is just restating that the expectation of a score function is zero).
Comment: thank you for this answer... my prof. Clayton Scott didn't explain the Q as a surrogate... which makes hundreds of students no clue for months....
Answer: The EM algorithm directly maximizes the expected complete data likelihood, but can guarantee the increase of observed data likelihood. The correct version of the proof is in the following reference. Statistical Inference by Casella and Berger also addresses this problem.
Wu, C. F. Jeff (1983). "On the Convergence Properties of the EM Algorithm". Annals of Statistics 11 (1): 95–103.


Week Start from Monday for a given date

Question: In the below image I am trying to start the week of "ManufactureDate" to every Monday but unable to get it the desired result.
Query used:
select distinct     dateadd(week, DATEDIFF(week, 0, [ManufactureDate]),0 )sp, [ManufactureDate]
FROM ab

Current result Set:
SP                           Manufacturing Date
2019-10-14 00:00:00.000  2019-10-13 00:00:00.000
2019-10-14 00:00:00.000  2019-10-14 00:00:00.000
2019-10-14 00:00:00.000  2019-10-15 00:00:00.000
2019-10-14 00:00:00.000  2019-10-16 00:00:00.000
2019-10-14 00:00:00.000  2019-10-17 00:00:00.000
2019-10-14 00:00:00.000  2019-10-18 00:00:00.000
2019-10-21 00:00:00.000  2019-10-20 00:00:00.000

Desired result:
Sp        Manufacturing Date
10/14/2019  10/14/2019
10/14/2019  10/15/2019
10/14/2019  10/16/2019
10/14/2019  10/17/2019
10/14/2019  10/18/2019
10/14/2019  10/20/2019
10/21/2019  10/21/2019

Image:
Comment: Did you actually need the image? Looks the same as the text data (which is better).
Comment: @DaleK, no  I didn't, I think I don't have that privilege to remove answers.
Comment: Possible duplicate of [Get the week start date and week end date from week number in SQL Server](https://stackoverflow.com/questions/1267126/get-the-week-start-date-and-week-end-date-from-week-number-in-sql-server)
Answer: SELECT
DATEADD(DAY, ((DATEPART(WEEKDAY,[ManufactureDate]) + 5) % 7) * -1, [ManufactureDate]) Sp, [ManufactureDate]
FROM ab

Here's a fiddle.
Sp                  ManufactureDate
2019-10-07          2019-10-13
2019-10-14          2019-10-14
2019-10-14          2019-10-15
2019-10-14          2019-10-16
2019-10-14          2019-10-17
2019-10-14          2019-10-18
2019-10-14          2019-10-19
2019-10-14          2019-10-20
2019-10-21          2019-10-21

Week Start from Monday for a given date


Backgrounds aleatórios em cada carregamento de pagina em paginas estáticas

Question: Estou criando um site/blog com o jekyll, e eu crieri um banner.html e inclui ele no layout default, porem eu queria que ao carregar a pagina toda hora fosse um background diferente nesse banner e estou tentando fazer isso por javascript mas ainda não tive sucesso, o código que crie foi esse:
function aplicarBGAleatorio() {
var numeroBG = Math.floor(Math.random() * 5);

if ($("#bannerMain").length) {
    alert(backgroundAleatorio(numeroBG));
    $("#bannerMain").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });
}

if ($("#bannerSecondary").length) {
    alert(backgroundAleatorio(numeroBG));
    $("#bannerSecondary").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });
}
}

function backgroundAleatorio(x) {
switch (x) {
    case 0:
        return "background0.jpg";
        break;
    case 1:
        return "background1.jpg";
        break;
    case 2:
        return "background2.jpg";
        break;
    case 3:
        return "background3.jpg";
        break;
    case 4:
        return "background4.jpg";
        break;
}
}

$(document).ready(function () {

aplicarBGAleatorio();

com esse código do jeito que está, os dois alerts dentro dos ifs funcionam, mas os backgrounds não aparecem, e não da erro no console.

{% if page.title %}{{ page.title | escape }}{% else %}{{ site.title | escape }}{% endif %}

{% if page.desc %}{{ page.desc | escape }}{% else %}{{ site.slogan | escape }}{% endif %}

    <button>{ Ver mais }</button>

section#bannerMain {
width: 100%;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-repeat: no-repeat;
background-position: 50% 0;
background-attachment: fixed;
background-size: cover;
padding-top: 75px;

}
Comment: Já olhou no inspetor do navegador qual é o valor da propriedade que foi carregada? Aliás, "não aparecem" é o fundo ficar branco, sem imagem alguma?
Comment: O navegador aprensenta algum erro? se sim qual?
Comment: Disponibilize o html,css para que possamos analisar todo o contexto..
Comment: Disponibilize o html e o css
Comment: @AndersonCarlosWoss no inspetor do chrome não da indícios de que foi aplicado algum background-image, o background fica branco, sem imagem sem erro no console e sem nada de diferente no inspetor
Comment: O path da `URL` das imagens está incorreto.
Comment: @FabianoLothor mas eu fiz alguns testes deixando o javascript de lado e colocando essa mesma url `url("../../assets/Imagens/background0.jpg");` no css ele aparece o background
Answer: Modifique as linhas abaixo:
Ao invés de fazer:
$("#bannerMain").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });

$("#bannerSecondary").css({ 'background-image': 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '");' });

Faça:
$('#bannerMain').css('background-image', 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '")');

$('#bannerSecondary').css('background-image', 'url("../../assets/Imagens/' + backgroundAleatorio(numeroBG) + '")');

Comment: Funcionou perfeitamente, obrigado @FabianoLothor


Consider a simple connected graph with $n$ vertices $(n ≥ 2)$ such that no two vertices of the same degree are connected by a simple path of length 2

Question: Consider a connected simple graph with $n$ vertices $(n ≥ 2)$ such that no two vertices of the same degree are connected by a simple path of length $2$. Prove that there exists a vertex of degree $1$.
It's not easy even to imagine a graph like this. For example, it could be a path graph with $4$ vertices, but this tells me nothing.
Answer: Let $G$ be a nonempty finite graph with maximum degree $\Delta(G)=k\ge1$. Choose a vertex $v$ of degree $\deg(v)=k$. The $k$ neighbors of $v$ have $k$ different degrees, which are all in the set $\{1,\dots,k\}$, so every element of that set must be the degree of some neighbor of $v$.


Which finger is correct for number 5 on guitar tab?

Question:
I'm very new to guitar and I'm practicing beginner stuff, I press the appropriate fret with the numbered finger, 1 for index and 3 for ring.
Also I play in fret hand position 1 with index on first fret, the 5 in the second measure confuses me. Do I shift finger 3 my ring finger down 2 frets on the A string and then shift back up to fret hand position 1? Or can we use any finger for the shift?
Comment: Do you mean that in the first bar you use your ring finger for both the F and the E on the fourth and fifth string?
Comment: I think it is more comfortable to use open string 4
Comment: @WillemvanRumpt It is, therefore, a comment, not an answer
Comment: @WillemvanRumpt That could be a good answer if you can elaborate it a bit more
Comment: I don't think the sheet music suggests an "arpeggiated chord," if one were to finger a barre F-minor (at fret one) and then a Gm-7 (at fret 3), the fingering would take care of itself. The answers are spot on though: it depends on the context whether this way of doing it makes sense. For guitar tabs it sometimes helps to demystify the choices by thinking of a chord form.
Comment: ^should read "**but** if one were to"...
Answer: The numbers in TAB are not finger numbers they are fret numbers.  If you are not shifting positions and you have one finger over each of 4 consecutive frets in the lowest position then it makes sense to say first fret is the index finger but that won't work in general.  In standard music notation they indicate left hand fingering by placing the finger number (1, 2, 3, 4) = (index, middle, ring, pinky) right next to the note.  A string number is indicated by a number in a circle.  Given just the TAB numbers and nothing else you can use any finger you want, as long as it makes sense and is easy to play.
Based on the pattern I'd shift up so that the first finger is on the 3rd fret and use ring for the 5 while baring the 3rd fret with the index finger.  However you could stretch and play the 5 with your pinky.  It would be inconsistent with the TAB to play the 5 as an open string.  Even if that makes sense.  TAB is usually trying to replicate not only notes in a song but the playing style of a guitarist.  So if this is a song and you want to imitate the style of playing you would want to figure out how to play it as written.  If it's a basic technical exercise then again you may want to figure out what the intent of the exercise is and stick to it.  Did this TAB come from a book, or Guitar for the Practicing Musician or some other source with instructions?  That may help clarify it.
Answer: Given that the next note is a G on the bottom string, and you played the first G with 3, then yes, pinky wins!
However - tab often tries to be helpful, and tell the reader where to play each note, but you must always remember that there are several different places to play each note, unlike a piano, where every note has its own personal key, and that's it.
Bearing that in mind, that D note could be played as an open 4th string. And also, a heck of a lot of tabs are posted by folk still wet behind the ears, and all they do is write where they play it - often not an optimum place at all, and sometimes inaccurate! It may even be that the tab writer believes that what he's (and /or she's!) written is spot on, in blissful ignorance.
That second bar, in a different view than the one ggcg takes, could be played pulling off to the open D, and hammering back on to the F. I would defy a lot of listeners to tell the difference! Just another 'interpretation'...
Answer: For measure 1 play 1st finger for F on sixth string, 3rd finger for C on fifth string, 4th finger for F on fourth string.  This is fingering for a power chord.  Then move whole hand barring the third fret with the 1st finger and using 3rd finger for the D not on fifth string.


What does this congruent proof actually say?

Question: I have a statement that says:

For every $n >= 2$.
If n is an odd number then $7^{n}-1$ is not divisible by 4

Prove whether the statement is true or false.
The proof:

$7\cong  -1 (mod 4)$ so $7^n-1\cong (-1)^n-1\cong -1(mod 4)$ and thus 4 does not divide $7^n-1$

I can't find any good explanations on the net.
The most I know from congruency is that a $\cong b(mod (n)))$ if n divides $a - b$.
Answer: You are on the right track.
$$7\equiv -1 \pmod4$$
$$7^n\equiv (-1)^n \pmod4$$
And for odd $n$, we have
$$7^n\equiv -1 \pmod4$$
$$7^n -1\equiv -1-1\pmod4$$
$$7^n -1\equiv -2\not \equiv 0\pmod4$$
So the given statement is true.
Comment: Could you explain what : $7^n−1≡−2$ means? Or what $x ≡ y$ means for that matter.
Comment: @pillikasnazsaxc it is the congruence symbol, the standard symbol. The notation that you have used is not standard.
Answer: You might find the following proof easier to follow
$\qquad \begin{align}{\rm mod}\ 4\!:\,\ 7^{\,\large 1+2K} &=\, \color{#0a0}7\cdot \color{#c00}{49}^{\large K}\\
&\equiv\, \color{#0a0}3\cdot \color{#c00}1^{\large K}\\
&\equiv\, 3\end{align}\!\!$
by $\ \begin{align} \color{#0a0}{7\equiv 3}\\ \color{#c00}{49\equiv 1}
\end{align}$
The quoted proof is the same except it deduces $\,\color{#c00}{7^{\large 2}\equiv 1}\,$ by squaring $\,7\equiv -1$.
Above we used standard Congruence Rules (the Product and Power Rules)
Answer: You know $a \equiv b \mod n$ means $n$ divides $a-b$. (Notation: I will write $n|k$ to mean "$n$ divide $k$).
There are a few basic facts to know about this that in a very short time you will take for granted that most people won't even bother to state them and just assume they are obvious.
1) $a \equiv b \mod n \iff n|a-b \iff a = b + kn$ for some integer $m$ $\iff $ $a$ and $b$ have the same remainder when divide by $n$.  All four of those statements mean the exact same thing. (It's easy to prove this and it makes a good excercise.)
2) $a \equiv 0 \mod n \iff n|a$
3) if $a\equiv r \mod n$ and $0 \le r < n$ then $r$ is the remainder when you divide $a$ by $n$.
Those are so basic that I imagine must mathematicians will just assume they are obvious and go without saying.
Not so obvious but still basic.
4) If $a \equiv b \mod n$ and $c \equiv d \mod n$ then $a+c \equiv b + d \mod n$ and $ac \equiv bd \mod n$ and $a^k \equiv b^k \mod n$
Pf: $a \equiv b \mod n \implies a = b + kn$ for some  integer $k$. Likewise $c \equiv d \implies $c = d + jn$ for some $j$.  So $a + c = b + d + n(k+j)$.  $k+j$ is an integer so $a+c \equiv b+d \mod n$.
$ac = (b+kn)(d+jn) = bd + kdn + jbn + jkn^2 = bd + n(kd + jb + jkn)$.  $kd + jb + jkn$ is and integer so $ac \equiv bd \mod n$.
$a \equiv b \mod n$ so $a^2 = a*a \equiv b*a \equiv b*b = b^2 \mod n$.  Repeat inductively.  $a^k \equiv b^k \mod n$.
Okay, with all that in mind.
$4$ divides $7^n - 1 \iff$
$7^n -1 \equiv 0 \mod 4 \iff$
$7^n \equiv 1 \mod 4$.
As $7 = -1 + 2*4$ we know $7 \equiv -1 \mod 4$.
So $7^n \equiv (-1)^n \mod 4$.  If $n $ is odd then $(-1)^n = -1$.
So $7^n \equiv (-1)^n = -1\mod 4$.
And as $1 - (-1) = 2$ and $4$ does not divide $2$, $-1 \not \equiv 1 \mod 4$
So $4$ does not divide $7^n - 1$.
If that seems a little to abstract or obtuse....
Note this hinged on $7 = (2*4) - 1$.
Then $7^n - 1 = (8 - 1)^n - 1$
Note: $(8 - 1)^n = \sum_{i = 0}^n {n \choose i}8^i(-1)^{n-i}$.
Note each of the ${n\choose i}8^i(-1)^{n-i}$ where $i \ge 1$ are divisible by 8 and therefore divisible by $4$.
So the remainder of dividing $(8-1)^n$ by $4$ will be the one term where $i=0$.  So the remainder will by ${n \choose 0}8^0(-1)^{n-0} = (-1)^n$ and as $n$ is odd, the remainder is $-1$.  Oh... actually it is $3$, I guess,  (see what I said about assuming things are so obvious they go without saying?)
So the remainder of dividing $(8-1)^n - 1$ will be $3 -1 = 2$.  So $4$ does not divide $7^n -1$ for $n$ odd.
(Note: if $n$ is even and $n > 0$ the $4$ will always divide $7^n - 1$.


Does using a custom ServiceHost disable simplified configuration?

Question: I have some one-time initialization tasks to do on service startup, and in order to do this I have defined a custom ServiceHostFactory and ServiceHost to override InitializeRuntime.
Service1.svc markup:
<%@ ServiceHost Language="C#" Debug="true" Factory="service.Our_Service_Host_Factory" Service="service.Service1" CodeBehind="Service1.svc.cs" %>

Service Host definitions:
public class Our_Service_Host_Factory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        return new Our_Service_Host(serviceType, baseAddresses);
    }
}

class Our_Service_Host : ServiceHost
{
    public Our_Service_Host(Type serviceType, Uri[] baseAddresses)
        : base(serviceType, baseAddresses) { }

    protected override void InitializeRuntime()
    {
         // one time setup code
    }
}

Snippet from web.config:
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
  </protocolMapping>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>

If I remove the Factory attribute on the ServiceHost markup, the WCF Test Client can successfully connect to my service.  If I put it back in, it can't find the metadata endpoint with the following error:
Error: Cannot obtain Metadata from http://localhost:50154/Service1.svc If this is a Windows (R)
Communication Foundation service to which you have access, please check that you have enabled
metadata publishing at the specified address.  For help enabling metadata publishing, please
refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.WS-Metadata
Exchange Error    URI: http://localhost:50154/Service1.svc    Metadata contains a reference that
cannot be resolved: 'http://localhost:50154/Service1.svc'.    There was no endpoint listening at
http://localhost:50154/Service1.svc that could accept the message. This is often caused by an
incorrect address or SOAP action. See InnerException, if present, for more details.    The
remote server returned an error: (404) Not Found.HTTP GET Error    URI:
http://localhost:50154/Service1.svc    There was an error
downloading 'http://localhost:50154/Service1.svc'.    The request failed with HTTP status 404:
Not Found.

It looks like having a custom ServiceHost/ServiceHostFactory might break simplified configuration.  Is this the case, or is there something I'm overlooking which would make this continue to work?
Comment: I noticed that you have `service.Our_Service_Host_Factory` for the factory - could it be something as simple as it should be `Service.Our_Service_Host_Factory` (uppercase vs lowercase)?
Comment: Also, have you tried adding `<%@Assembly name="MyAssembly" %>` to your svc file?  Replace MyAssembly with your assembly's name, of course. :)
Comment: Nope, the namespace it's in is definitely service.
Answer: If you override InitializeRuntime(), make sure you call base.InitializeRuntime() or you may see this behavior.  After calling base.InitializeRuntime() before calling my additional startup logic, my service is now being correctly routed to.
Comment: Thanks for sharing the answer - we use a custom service host in our application and are currently upgrading from 3.5 to 4.5, so I'll need to ensure this is captured :)


xcode 4.2 + xcode project from makefile

Question: I am trying to build c++ xcode application from makefile.
I am using xcode 4.2, and in this version i dont see command line utility->standard tool.. All the help says "If you are just trying to build a command-line utility, selectone of the tools—for example, Standard Tool."
I have installed command line tools from preferences->downloads->components
Can some one help me on this?
Answer: You should have "Command Line Tool" available when starting a new project in "OS X"->"Application". If you don't, try updating your softwares, including XCode.
Comment: I found command line tool under application. Now how would i add existing make file and the source files for xcode project?
Comment: Once the project is created, click on "File"->"New"->"Target" and under "OS X" -> "Other" you will find External Build System. Name the target however you like ("Build with Make" for instance), and the Build settings for this new target should appear. Switch to the "Info" tab and pick as the Directory the directory where your makefile is. Don't forget to use that target you just created for your project.
Comment: thanks a lot. i am not able to use the new created target for the project. please how would i do this?

xcode 4.2 + xcode project from makefile


Why is the flux of a uniform field necessarily zero for any closed surface?

Question: From taking and working in physics, I know that, given some uniform vector field $\vec{V}$, the flux of $\vec{v}$ through any closed surface is necessarily zero. I do not, however, understand, why this is, either intuitively or in a mathematically rigorous way.
For simple surfaces, it can be seen easily. Take, for example, a cube "parallel" to some vector field $\vec{V}$. By quick geometric examination, or argument by symmetry, we can see that  only two sides "contribute" to the total flux, and their area are opposite in direction, thus the total flux is $0$. Similar approaches can be taken for spheres, etc.

For more complex surfaces, however, this is both bizzare and amazing. Why, intuitively and rigorously, is this true?
Comment: How about dividing your region (or almost your region, at least) into many tiny little cubes parallel to the field?
Comment: That's because of https://en.wikipedia.org/wiki/Divergence_theorem : the divergence of your uniform vector field is $0$.
Answer: Because the flux is proportional to the projected area, not the area itself (there is a cosine factor), and the surface can in a way be seen as flat. As a closed surface has as many entering as exiting faces, the whole contribution is zero.


I get a Dead code warning when trying to write an if condition

Question: I got a Dead code warning for this code:
Topic topic = findTopicByID(point.getIDTopic());

if (topic != null)
{
   ...
}
else if (topic == null)
{
    // I get Dead code warning for every thing I write here!
}

Sometimes when I get a warning but everything look OK, I restart IDE and I don't get that warning anymore! but this time...
EDIT:
public Topic findTopicByID(int IDTopic) {
    for (Topic topic : topics)
        if (topic.getID() == IDTopic)
            return topic;
    return null;
}

Edit:
Full code here:
Topic topic = Res.getSchedule().getTopicBox().findTopicByID(point.getIDTopic());
            Section section =     topic.findSectionByID(point.getIDSection());

            if (topic != null)
            {
                View rowView = inflater.inflate(R.layout.daily_day_day_row, lLDoneWorks, false);

                TextView tVLabel = (TextView) rowView.findViewById(R.id.daily_day_day_row_label);
                TextView tVNum = (TextView) rowView.findViewById(R.id.daily_day_day_row_num);
                TextView tVTopic = (TextView) rowView.findViewById(R.id.daily_day_day_row_topic);
                TextView tVSection = (TextView) rowView.findViewById(R.id.daily_day_day_row_section);

                int color = topic.getColor();
                tVLabel.setBackgroundColor(color);
                tVNum.setTextColor(color);
                tVTopic.setTextColor(color);
                tVSection.setTextColor(color);

                tVLabel.setText(topic.getName().substring(0,1).toUpperCase(Locale.US));
                tVNum.setText(Integer.toString(point.getCount()));
                tVTopic.setText(topic.getName());
                if (point.getIDSection() != Point.DEFAULT_SECTION)
                    tVSection.setText(section.getName());

                lLDoneWorks.addView(rowView);
            }
            else if (topic == null)
            {
                TopicArchived archivedTopic = Res.getSchedule().getTopicBox()
                            .findArchivedTopicByID(point.getIDTopic());
                    if (archivedTopic == null)
                        removedTopicsPoint += point.getCount();
                    else
                        archivedTopicsPoint += point.getCount();
            }

Comment: Most likely the code isn't exactly as you presented it.  There is some detail you are missing, do you call `topic.method()` before the `if` statement?
Comment: The dead code warning should be on the `else if (topic == null)` line instead of everything below it. It is a wrong indication of the IDE.
Comment: Can `findTopicByID` return null? Or does it thrown an exception if the topic isn't found? If it doesn't return null, maybe the IDE is smart enough to realise that `topic` can never be null, and therefore that code can't be reached.
Comment: I do not get this warning for second if condition, I get it for EVERYTHING I write in the second statement block.
Comment: Even if I delete `if (topic == null)` I still get this warning
Comment: You know the `if (topic == null)` is redundant.
Comment: Peter is right, I used `topic.method()` before if condition
Answer: You could code
if (topic != null)
{
   ...
}
else
{
   ...
}

instead.
Answer: It's likely the compiler misinterpreting the goal of the condition. Rewrite it as:
if (topic != null) {
   ...
}
else {
    // Code
}

In the else condition topic is logically guaranteed to be null. If it wasn't null the if block was taken and the else would not be.
Comment: Why should it complain about the code _in_ the the then-branch, then?
Comment: @JanDvorak I'm guessing it's likely OP's misunderstanding/misinterpretation from the question.
Answer: Take a look on your code.
if(topic != null) {
} else { // here topic definitely not null, so the your if is redundant.
}

Comment: It definitely *is* null if it gets to the `else`.
Answer: What you have is overkill, I think.  Why not just:
if (topic != null)
{
    ...
}
else
{
    // It must be null if it gets here
}

Answer: It's because of this line:
Section section =     topic.findSectionByID(point.getIDSection());

if topic is null, you have a NullPointerException there, and the rest of the code is not reached. Therefore every check on the nullness of topic that would come afterwards is irrelevant: the compiler knows that topic is not null after that line.
You should put that line inside the first branch of your if statement.


Access Denied when installing Server 2003 server on Windows 7

Question: Having an issue connecting to a Server 2003 print server with Windows 7 computers.  I get an "Access Denied" error when trying to connect.
A Microsoft article shows the exact problem and solution by modifying the group policy.  Trouble is I can only find the policy item in Server 2008, not 2003.  Any thoughts.
Here is the MS article that revers to:
  Computer Configuration\Policies\Administrative Templates\Printers\Point and Print Restrictions = Disabled
http://technet.microsoft.com/en-us/library/cc753269.aspx
UPDATE: If we modify the above mentioned policy setting on the local Win 7 system all works fine.  Found this at a few other sites.  Problem is, I don't want to manually update 200 machines at the local policy level.  Any thoughts?
Comment: Are you sure that's the problem? Have you run RSOP or GPRESULTS to confirm?
Answer: UPDATE:
Have you downloaded RSAT and tried to manage the point and print option through group policy from a Windows 7 machine? You should be able to create a "point and print" GPO and apply it to your clients and have it work.
ORIGINAL MESSAGE:
Is your domain\forest operating at a Windows 2003 functional level? You should be able to install RSAT on Windows 7 and manage the policy from there assuming the functional level is 2003 or greater.
Comment: Also, as joeqwerty mentions in the comment above, make sure you run `gpresult /r` to confirm that the policy is being applied.


Does a drone create harmony?

Question: I noticed there's no typical harmony (chords, etc) in Scotland the Brave but rather there's three elements: a drone on B-flat, the melody, and the drums.

So is a single continuous note (drone) considered harmony?
Comment: Towards the end there is specific harmony, as in I (Bb) IV (Eb) and V (F).
Answer: If by harmony we intend the mere superpositions of sounds, the single drone note alone does not costitute harmony - but the drone + melody does.
If by harmony we intend the backbone on top of which be build the melody, the drone (and its overtones) helps to establish the tonal center (of the mixolydian mode, in this case), so it fulfills the harmonic role.
Answer: A drone is a pedal tone, right? So you have a pedal tone and a melody, at least two notes sounding all the time. And the melody plays different notes which at times seem to outline chords. There is definitely harmony in your example.
Answer: To the extent that the melody against the drone will produce consonances and dissonances and consonance and dissonance are harmonic concepts, then "yes" harmony is produced by a drone.
If you try to shoe-horn that into common practice/Roman numeral analysis, I suppose you would label all the music as a tonic chord with passing motion. (Sort of like how a dominant pedal point passage can be labelled with a simple V.) That won't be very musically illuminating about the melody played over the drone, but that is what you will get for harmonic analysis.
Answer: Twinkle twinkle little star can be played with a drone.
It should really be played with at leadt two bass notes (1 and 5).  The chords are I, IV/V and V(7).
I play with only two notes in the bass even if play it as four-part harmony.

Does a drone create harmony?


LMER Factor vs numeric Interaction

Question: I am attempting to use lmer to model my data.
My data has 2 independent variables and a dependent variable.
The first is "Morph" and has values "Identical", "Near", "Far".
The second is "Response" which can be "Old" or "New".
The dependent variable is "Fix_Count".
So here is a sample dataframe and what I currently have for running the linear model.
<code> Subject <- c(rep(1, times = 6), rep(2, times = 6))
 q <- c("Identical", "Near", "Far")
 Morph <- c(rep(q, times = 4))
 t <- c(rep("old", times = 3),rep("new", times=3))
 Response <- c(rep(t, times = 2))
 Fix_Count <- sample(1:9, 12, replace = T)
 df.main <- data.frame(Subject,Morph, Response, Fix_Count, stringsAsFactors = T)

 res = lmer(Fix_Count ~ (Morph * Response) + (1|Subject), data=df.main)
 summary(res)
</code>
And the output looks like this:

The issue is I do not want it to do combination but an overall interaction of Morph:Response.
I can get it to do this by converting Morph to numeric instead of factor. However I'm not sure conceptually that makes sense as the values don't properly represent 1,2,3 but low-mid-high (ordered but qualitative).
So:
1. Is it possible to run lmer to get interaction effects between 2 factor variables?
2. Or do you think numeric is a fine way to class "Identica", "Near", "Far"?
3. I have tried setting contrasts to see if that can help, but sometimes I get an error and other times it seems like nothing is changed. If contrasts would help, could you explain how I would implement this?
Thank you so much for any help you can offer. Please let me know if this Q is better off on stackoverflow if it turns out the answer is a coding issue not a stats issue.
Best,
Kirk
Answer: 1) it is possible and you have done it. You are simply looking at a table that doesn't show "overall" interaction. The effects in the table you posted are coefficients of the two interactions in the linear model. The overall interaction effect is in an ANOVA table, which is printed with anova()
<code>> anova(res) # assumes lmerTest is loaded
Analysis of Variance Table of type III  with  Satterthwaite
approximation for degrees of freedom
               Sum Sq Mean Sq NumDF DenDF F.value Pr(>F)
Morph          13.167  6.5833     2     5 1.18976 0.3779
Response        3.000  3.0000     1     5 0.54217 0.4946
Morph:Response  4.500  2.2500     2     5 0.40663 0.6861
</code>
2) and 3) the short answer is, neither recoding the variable to numeric or using contrasts will get what you want. The long answer is, this will all become more more clear as you progress in statistics and better understand what a linear model is, what contrasts are and what an anova table (or decomposition) is. It's not easy.

LMER Factor vs numeric Interaction


solving vector equations involving the L2 (or any other) vector norm

Question: My question is very simple. How can we solve a vector equation involving the L2 norm, for example.
$$a + 2\frac{x}{\Vert x \Vert _2}=0$$
Even if a write it this way:
$$a + 2\frac{x}{\sqrt{\sum_i x_i^2}}=0$$
where $a$ is a real value vector with same dimension as $x$
I am not able to continue.
Thanks.
Comment: The first part of the sum is a number, $3$, and the second one will be a vector. To be able to add them up, the vector needs to be a $1$-vector.
Comment: Can you explain what $+$ is here? Since you're summing a unit vector and a scalar. Note that this has no solutions even if I assume that $3 = 3(1,....,1)$, since then every component of the unit vector needs to be $-3/2$.
Comment: sorry, my mistake, let's assume that 3 is a vector a with any possible value and same dimension as x. I will edit it
Answer: $a$ has to be vector of length $2$, and hence we need $-\frac{a}2$ to be a unit vector.
We have $$\frac{x}{\|x\|_2}=-\frac{a}2$$
Any positive multiple of $-a$ is then a possible solution.
Comment: but, is there any way we can express everything in terms of x, such as:

$x=.....$

The thing is that in my real problem $a$ is a gradient operator and 2 is a lagrange multiplier, and $x$ is the variable w.r.t I want to get the optimum.
Comment: $x=-ka$ where $k>0$.
Comment: I think you could say $\|\mathbf{x}\| = -(1/2)\int \mathbf{a} \cdot d \mathbf{x}$, though I may be wrong
Comment: I do not agree because the normalization value K depends entirely on the value of x, and thus it cannot be part of the solution of x @SiongThyeGoh
Comment: $k$ is an arbitrary positive  constant. Remark: I m traveling with limited Internet access, slow response expected.
Comment: So, there is not a procedure to solve these problems? My problem is quite more complicate than this and I cannot let things depend on an arbitrary value. I thought there would be a procedure or  something like that
Comment: What else do u know about the problem? Currently the problem has multiple solutions. There is a restriction on $a$ for it to have a solution and any negative multiple of $a$ is a solution currently.
Comment: my problem involves optimization with restrictions, I put a post one year ago but no one answer it, that is why I tried to get this simple answer in order to continue https://math.stackexchange.com/questions/2612396/simple-optimization-with-inequality-restrictions


UICollectionView not showing cells properly

Question: I'm new to the UICollection View. Some cells are not showing up as can be seen in the image below. This is my code for setting it up, would be happy if someone could explain why some cells are missing. Also, when I scroll up and down the images in the cell will change for some reason (although in this screen shot I'm using the same images for all cells). The entire second and forth row are missing, and the middle column is missing. The intent is to have rows of three images per row adjacent to one another. Thanks!
<code>   UICollectionViewFlowLayout *layout=[UICollectionViewFlowLayout new];
   self.collectionView=[[UICollectionView alloc] initWithFrame:Frame(0,225,1080, Denormalize(screenHeight) - 225) collectionViewLayout:layout];
   [self.collectionView setDataSource:self];
   [self.collectionView setDelegate:self];

   [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
   [self.collectionView setBackgroundColor:[UIColor redColor]];
   layout.minimumLineSpacing = 0;
   layout.minimumInteritemSpacing = 0;
   layout.sectionInset = UIEdgeInsetsMake(0,0,0,0);

   [self.view addSubview:_collectionView];

#pragma mark - CollectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
  return self.allVideos.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
//  cell.backgroundColor=[UIColor greenColor];

  NSDictionary *video = self.allVideos[indexPath.row];

  UIImageView *thumbnail = [UIImageView new];
  thumbnail.contentMode = UIViewContentModeScaleAspectFill;
  thumbnail.frame = cell.frame;
  thumbnail.clipsToBounds = YES;
  thumbnail.image = [UIImage imageNamed:@"DefaultAvatar.png"];
//  thumbnail.image = video[@"image"];
  [cell addSubview:thumbnail];

  return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
  return CGSizeMake(self.view.frame.size.width/3, self.view.frame.size.width/3);
}
</code>
Answer: One major issue here is that you are adding a UIImageView as a subview in cellForItemAtIndexPath. This method runs every time a cell is dequeued, not every time a cell is initialized. This means that every time one of those cells is rendered like when the collection scrolls, a new subview is being added on top of the existing image view on the cell. This will very quickly cause major problems graphically and use way more memory then you intend to. The first thing I would do is subclass UICollectionViewCell and add your UIImageView to the subclass. You can then set the cell's image in that method but adding a subview in that particular spot is a really bad idea.
Here's my approach.
First, make a cell subclass and expose a method to set your image.
// MyCollectionViewCell.h
<code>#import <UIKit/UIKit.h>

@interface MyCollectionViewCell : UICollectionViewCell

- (void)setImage:(UIImage *)image;

@end
</code>
// MyCollectionViewCell.m
<code>#import "MyCollectionViewCell.h"

@interface MyCollectionViewCell ()

@property (strong, nonatomic) UIImageView *imageView;

@end

@implementation MyCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupImageView];
    }
    return self;
}

- (void)setupImageView
{
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.backgroundColor = [UIColor greenColor];
    [self addSubview:imageView];
    self.imageView = imageView;

    [imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
    NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];
    NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0];
    NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
    NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];

    [self addConstraints:@[leading, trailing, top, bottom]];

}

- (void)setImage:(UIImage *)image
{
    [self.imageView setImage:image];
}

@end
</code>
The layout constraints here are key. UICollectionViewCells, in my experience often have a frame of 0 when they are initialized which is why you are seeing a ton of empty boxes (the UIImageView on a new cell is being initialized with CGRectZero). The constraints will make sure that when they do eventually lay out correctly, the imageView will also resize itself to fit.
After this, register your custom cell class and then you can implement this in your CollectionViewController
<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    [cell setImage:[UIImage imageNamed:@"emoji.jpg"]];
    // Configure the cell

    return cell;
}
</code>
Here's the before and after shots of setting the UIImageViewFrame explicitly

vs. using NSLayoutConstraints.

For the hell of it, here's how to do the same thing in cellForItemAtIndexPath.
<code>- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

    NSInteger viewTag = 1000;
    UIImageView *imageView = (UIImageView *)[cell viewWithTag:viewTag];

    if (!imageView) {
        imageView = [[UIImageView alloc]init];
        imageView.tag = viewTag;
        [cell addSubview:imageView];

        [imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
        NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0];
        NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0];
        NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeTop multiplier:1.0 constant:0];
        NSLayoutConstraint *bottom = [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:cell attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0];
        [cell addConstraints:@[leading, trailing, top, bottom]];
    }

    imageView.image = [UIImage imageNamed:@"emoji.jpg"];

    return cell;
}
</code>
Comment: Good point, though it doesn't address the question. I hate subclassing - makes the code too granular. Is there a way to check if the cell already has shit on it?
Comment: I updated my comment also including my fix to your missing image views using layout constraints. You could hypothetically tag the subview you add in cellForItemAtIndexPath and then check the cell's subviews for a view with your specific tag, but that would require iterating over the cell's subviews whenever it is dequeued which is extra work for no real reason. I think standard and preferred practice in object oriented languages like Obj-C would definitely be to subclass in this case.
Comment: Yup, that would be the accepted way - well, I'm an embedded C guy - object oriented was never my thing, I like code that is short, readable, sweet, and concise. If you have any idea why UICollectionView is skipping out on some cells do let me know, perhaps there is a way to check if the cell was already initialized for that row before calling dequeueReusableCellWithReuseIdentifier
Comment: Yeah, so the problem is where you are setting the imageView frame. I edited my answer above so you can check it out. I fixed it with constraints, you can probably also find a way to reset the imageView frame when the cell lays out its subviews if you do decide to go the subclassing route. If you really have your heart set on it you could add those constraints in cellForItemAtIndexPath.
Comment: Cool, that seems right - will give UICollectionView another go at some point.
Comment: For the sake of my own curiosity, I just added the code to do everything in cellForItemAtIndexPath too if you're interested. Much shorter/more concise but less style conscious.


Definir constante em Python

Question: Como posso declarar uma constante em Python da mesma forma que faço em C com
#Define PI 3.1415

ou em java
public final double PI = 3.1415

Comment: No caso se criar uma tupla?
pi = (3.141592)
Comment: Este é o campo exclusivo para respostas. Se tem uma pergunta que foi não foi respondida, pode utilizar o botão "Faça uma pergunta". Aliás, o trecho que colocou não define uma tupla, pois, neste caso, os parenteses serão utilizados apenas para gerenciamento de precedência de operadores na expressão. Para criar uma tupla precisaria fazer `pi = (3.141592,)`, com a vírgula, mas isso não seria semântico.
Answer: Em Python (em versões menores que a 3.8) isso não é possível. Apenas crie uma variável e não mude o seu valor.
PI = 3.1415

Essa segunda opção não teria o mesmo efeito de uma constante, uma vez que é possível reescrever uma função em outras partes do código.
 Um workaround simples, se realmente for muito necessário ter total garantia de que este valor nunca vai ser reescrito em outra parte do código é criar uma função que retorne o valor desejado.
def const_pi():
    return 3.1415

Comment: Exceto se alguém reescrever a função `const_pi` em outra parte do código haha
Comment: LINQ, já que editou, não seria interessante remover a sugestão de definir uma função visto que ela não garante que seja constante como diz na resposta?
Comment: @AndersonCarlosWoss Verdade. Eu acho que tava na cabeça que não era possível redefinir funções.
Answer: Não tem. Não se esqueça que Python é uma linguagem de script, por isso ela não precisa suprir todos mecanismos que outras linguagens possuem.
O jeito é fazer:
alguma_coia = 10 #não mexa neste valor, ele deve ser constante

Coloquei no GitHub para referência futura.
Answer: Na versão 3.8 do Python foi adicionado no módulo typing o tipo Final justamente para representar que um nome não poderá sofrer reatribuição, mas assim como toda a anotação de tipos do Python, isso não garante em tempo de execução, apenas informa ferramentas externas de validação de tipos.
from typing import Final

PI: Final = 3.14159
PI = 4

print(PI)

Ao executar o código acima você terá como saída o valor 4, pois mesmo indicado que o nome PI é um valor final não alterará o comportamento em tempo de execução. Porém, ao executar o mypy nesse mesmo arquivo você obteria um erro indicando que há uma reatribuição em um valor final.
(.env) ➜  mypy main.py
main.py:4: error: Cannot assign to final name "PI"
Found 1 error in 1 file (checked 1 source file)

Você pode inclusive utilizá-lo em conjunto com outro tipo para especificar o tipo real da variável:
PI: Final[float] = 3.14

Answer: Como colocado nas outras respostas, Python, sendo uma linguagem dinâmica,
não tem o recurso de "constantes" de uma forma simples: tudo em Python é um objeto.
Quando você define um número literal em código Python, na verdade, esse número é uma constante - o compilador que gera o bytecode coloca o valor literal dele no .pyc  -só que, pela natureza da linguagem, qualquer variável é apenas um nome vinculado a um objeto -e  a qualquer momento,
você pode simplesmente vincular o nome a um outro objeto.
No uso normal, assume-se que "Python é uma linguagem feita para ser usada por adultos que consentem com o que estão fazendo" - então um valor declarado no corpo de um módulo, apontado por um nome com letras maiúsculas, é, por convenção, tratado como uma constante, e não se deve mudar o valor daquela variável. Simples assim.
Entenda  se você tem essas duas linhas em seu código, o valor 3.141592 continua existindo na memória. Só que a variável Pi agora vai fazer referência a um objeto float em outra posição da memória:
Pi = 3.141592
Pi = Pi + 1

Agora, Python permite uma personalização quase sem limites da forma como dados são acessados se eles são atributos de uma classe (se são variáveis de um módulo, a história é outra, mas hacks são possíveis).
Descrever esses mecanismos e sugerir varias formas de criar coisas parecidas com constantes seria possível, mas avançado demais, e teria o tamanho de um capítulo de livro.
Em vez disso, vamos nos ater a um exemplo: a classe da biblitoeca padrão "Enum" pode ser usada para criar classes com "constantes" dentro - que além de um valor que não pode ser alterado de forma direta, ainda tem outras propriedades como "nome legível", dentre outras:
import enum

class Numeros(enum.Enum):
    pi = 3.141592

print (Numeros.pi, Numeros.pi.value)

exibe:
(<Numeros.pi: 3.141592>, 3.141592)

E tentar fazer:
Numeros.pi = 4

resulta em:
AttributeError: Cannot reassign members.

Esse mecanismo de Enum usa o dinamismo de Python para fazer uma coisa que não é possível fazer nas linguagens que tem as constantes "normais" que você menciona: em tempo de execução é possível usar o nome da constante. Isso é: em C é impossível você imprimir "PI" se usar um #define PI 3.141592 - uma vez que o define é um search and replace. Algumas bibliotecas tem suporte a usar o Enum  de C de forma  a poder olhar o nome  em tempo de execução (acredito) - mas em Python, basta fazer:
print(Numeros.pi.name)

Para ver o texto "pi" impresso.E se desejar usar o valor de forma numérica, deve-se usar o atributo "value": print(Numeros.pi.value)

Definir constante em Python


List of TCP & UDP ports known to be used by malware, etc

Question: Where can I find a regularly updated, downloadable list of TCP & UDP ports that are known to be commonly used by malware, trojans, etc.?
This is for import into an IT asset management system to help identify devices that might be in need of attention, security-wise.
Comment: `ports that are known to be used by malware, trojans, etc.?` - ALL of them.
Comment: Anything that isn't serious, enterprise-grade scanning such as Retina, Nessus, etc., is just a waste of time.
Comment: Identifying what ports are listening on all your devices and which ones might be suspicious is only the first step, from which you can launch Nessus scans, etc. against specific devices and ports of interest.  There is a lot more data that I have not shared here; my question is simply about a downloadable list of TCP & UDP ports that are known to be used by malware, etc.
Answer: Such a list is not useful, as malware uses any and all IP ports for what they do. There are some specific bits of malware that use custom ports, which is a big part of why good security posture includes setting a default-deny firewall rules for outbound connections. In response to this particular security posture, malware authors are putting things over HTTP which is generally allowed outside of firewalled networks.
Such a list will only be useful for identifying a small subset of potentially infected computers.
Comment: I am aware that malware can use any and all ports, both outbound and inbound (and egress filters are of course a must).  And of course it is difficult to detect malware using outbound port 80, etc., but there are a ton of more easily detected malware, worms, etc. out there that are using more unique ports.  I am not saying that this list takes the place of other security measures - it is just another layer of security.
Answer: It would be much easier to match listening ports against known services.  Anything else would be suspect.  With few exceptions, services run on well-known ports.  Others, can usually be assigned fixed ports.  In any given organization, the number of active services (ports) is usually much fewer than that which would be found in the services file.  It should be possible to generate a list of services that are used in the organization.
There are many ports that are used by both malware and legitmate software.  A fair number of the lesser known ports I use show up as malware ports when I research them.
Scanning servers for listening ports (both externally and internally) and matching against expected services could be more effective.
Comment: Yes, that sounds like a better approach!  Especially since I know the type of device for each IP, I should be able to identify unusual ports based on device/server type.


Laravel 5.8 show data of the another table like join

Question: I need how to show data in another table like MySQL join or something like that
MySQL example

My Code
Model usuarios
class Usuario extends Model {
    protected $table = 'usuarios';
    protected $primaryKey = 'idusuarios';
    protected $filliable = [
        'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
        'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
    ];

    public function Usuario() {
        return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
    }

    const CREATED_AT = NULL;
    const UPDATED_AT = NULL;
}

Model Roles
class Roles extends Model {
    protected $table ='roles';
    protected $primarykey  = 'idrole';
    protected $filliable = ['desc_rol'];

    public function Roles() {
        return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
    }
}

Controller usuarios
public function index(Request $request) {
    if (!$request->ajax()) return redirect('/');
    $usuarios = Usuario::all();
    return $usuarios;
}

View usuarios

that's what I need
Answer: Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
            return [
                'field1' => $role->field1,
                'field2' => $role->field2,
                'field3' => $role->field3,
                'field4' => $role->field4,
                'field5' => $role->field5,
                'rol' => $role->Usuario->desc_role
            ];
        });


(Java) How can I make a loop that will assign random names I've generated from an array to multiple strings?

Question: Relatively new to Java, looking for a solution to a crucial part of a game I'm making for a class. The idea is to make a very simple stock market simulation game, but the problem is related to creating made-up company names. I have three arrays for the first, middle, and last names of companies. I'm trying to make some of these companies have one word names, others two, etc. So far I've used a random number generator and if/elif/else statement to simulate one, but I would like five of them and I would prefer a more efficient method of doing so. Here's the code:
import java.util.Random;
import java.io.*;
import java.util.*;

class Main {

    public static void main(String[] args) {
        // The code all goes in here

        String[] companyFirstNames = {"Alpine", "Bear", "Bull", "Cuckoo", "Delta", "Dragon", "Echo", "Fighter", "Giant", "H20", "Indo", "Jared", "Jason", "Kicker", "Lodge", "Little", "Manzo", "Mint", "Neighbour", "Nelson", "Ossuary", "Open", "Private", "Poor", "Quick", "Quiant", "Reach", "Rebel", "Space", "Spear", "Titus", "Trebble", "Underdog", "Upper", "Vital", "Vert", "White", "Whistle", "X's", "Yuri's", "Yogurt", "Zebra"};

        String[] companySecondNames = {" Science", " Technology", " Arts", " Research", " Laboratory", " Lodging", " Woodworking", " Fashion", " Oil", " Trading", "  Investing"};

        String[] companyLastNames = {" Limited", " Co.", " Corp.", " Corporation", " Ltd", " Institute", " Association", " Federation", " Firm"};
        //Three arrays of random company name "pieces"

        Random randomNamer = new Random();
        //Used for getting random names & ints

        int randomOne = randomNamer.nextInt(companyFirstNames.length);
        int randomTwo = randomNamer.nextInt(companySecondNames.length);
        int randomThree = randomNamer.nextInt(companyLastNames.length);
        //Three ints that are given random values associated to the arrays

        int numberOne = randomNamer.nextInt(100);
        //Getting a random 0-100 number

        String bigNameCompany = companyFirstNames[randomOne] + companySecondNames[randomTwo] + companyLastNames[randomThree];
        String midNameCompany = companyFirstNames[randomOne] + companyLastNames[randomThree];
        String smallNameCompany = companyFirstNames[randomOne];
        //The three types of company names possible to produce

        String companyOne;
        String companyTwo;
        String companyThree;
        String companyFour;
        String companyFive;
        //The five companies I want to name

        if (numberOne <= 45) {
            companyOne = bigNameCompany;
            //The first company name is random and big
        } else if (numberOne <= 85) {
            companyOne = midNameCompany;
            //Two word name
        } else {
            companyOne = smallNameCompany;
            //One word name
        }

        System.out.println(companyOne);
        //printing the name of the first company

        //Can i get a loop to do this more efficiently for 5 companies?

    }

}

Answer: I'd encourage you to play around with it. That's the fun of programming is solving little puzzles like this, and there are a bunch of ways to do something like this. Here is one to give you some ideas:
    Random randomNamer = new Random();
    String[] companyFirstNames = { "Alpine", "Bear", "Bull", "Cuckoo", "Delta", "Dragon", "Echo", "Fighter", "Giant", "H20", "Indo", "Jared", "Jason", "Kicker", "Lodge", "Little", "Manzo", "Mint", "Neighbour", "Nelson", "Ossuary", "Open", "Private", "Poor", "Quick", "Quiant", "Reach", "Rebel", "Space", "Spear", "Titus", "Trebble", "Underdog", "Upper", "Vital", "Vert", "White", "Whistle", "X's", "Yuri's", "Yogurt", "Zebra" };
    String[] companySecondNames = { " Science", " Technology", " Arts", " Research", " Laboratory", " Lodging", " Woodworking", " Fashion", " Oil", " Trading", "  Investing" };
    String[] companyLastNames = { " Limited", " Co.", " Corp.", " Corporation", " Ltd", " Institute", " Association", " Federation", " Firm" };

    for (int i = 0; i < 5; i++) {
        int chance = randomNamer.nextInt(100);
        int firstIdx = randomNamer.nextInt(companyFirstNames.length);
        int secondIdx = randomNamer.nextInt(companySecondNames.length);
        int lastIdx = randomNamer.nextInt(companyLastNames.length);

        String name = null;
        if (chance <= 45) {
            name = companyFirstNames[firstIdx] + companySecondNames[secondIdx] + companyLastNames[lastIdx];
        } else if (chance <= 85) {
            name = companyFirstNames[firstIdx] + companyLastNames[lastIdx];
        } else {
            name = companyFirstNames[firstIdx];
        }
        System.out.println(name);
    }

Comment: Thank you for this! I gave the thing a couple tries but was pretty limited by my current java knowledge. I'm going to peek at this while I rework my code and figure out how to get five individual strings (for the 5 companies) from this that I can use in later code.
Answer: You can create a simple method for that (and you don't need white spaces in your name Strings):
private final String[] companyFirstNames = {"Alpine", "Bear", "Bull", "Cuckoo", "Delta", "Dragon", "Echo", "Fighter", "Giant", "H20", "Indo", "Jared", "Jason", "Kicker", "Lodge", "Little", "Manzo", "Mint", "Neighbour", "Nelson", "Ossuary", "Open", "Private", "Poor", "Quick", "Quiant", "Reach", "Rebel", "Space", "Spear", "Titus", "Trebble", "Underdog", "Upper", "Vital", "Vert", "White", "Whistle", "X's", "Yuri's", "Yogurt", "Zebra"};

private final String[] companySecondNames = {"Science", "Technology", "Arts", "Research", "Laboratory", "Lodging", "Woodworking", "Fashion", "Oil", "Trading", "Investing"};

private final String[] companyLastNames = {"Limited", "Co.", "Corp.", "Corporation", "Ltd", "Institute", "Association", "Federation", "Firm"};

private final Random randomNamer = new Random();

private String generateRandomName() {

    StringBuilder sb = new StringBuilder();

    int size = random.nextInt(100);
    int first = random.nextInt(companyFirstNames.length);

    sb.append(companyFirstNames[first]);

    if (size <= 85) {
        int second = random.nextInt(companySecondNames.length);
        sb.append(' ').append(companySecondNames[second]);
    }
    if (size <= 45) {
        int last = random.nextInt(companyLastNames.length);
        sb.append(' ').append(companyLastNames[last]);
    }
    return sb.toString();
}

Then you can do:
private List<String> generateNames(int numberOfNames) {
    return IntStream.range(0, numberOfNames).mapToObj(i ->
            generateRandomName()).collect(Collectors.toList());
}

Calling the last method will allow you to create as many names as you want:
List<String> names = generateNames(5)

System.out.println(names);

Output:
[White Trading Firm, Open Research, Indo Oil, Fighter Technology, Cuckoo Oil Corporation]

Comment: I never thought about making my own method, that's another for me to check out. Also, what does .append() do? I've never seen that before.
Comment: This is a better option that what I posted below..
Comment: A StringBuilder/StringBuffer is a more efficient way to concatenate Strings (sometimes) than using the + operator. In practice, in most cases the compiler ends up optimizing the + concatenation to be the same as using a StringBuilder, but there are some cases where it cannot.
Comment: @Jared take a look at [`StringBuilder`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/StringBuilder.html).
Comment: @crig I think is very similar, the main difference is `StringBuilder`
Answer: Your solution would probably work, but you could reuse your Random to decide whether a company name should have one, two or three words to make it more compact. This example would always generate a company with at least one name, while there's an equal probability for second and third:
final Random rnd = new Random();
final String[] companies = new String[5];

for(int i = 0; i < companies.length; i++) {
  final int idx = rnd.nextInt(100);
  companies[i] = companyFirstNames[idx%companyFirstNames.length]
  + (rnd.nextBoolean() ? companySecondNames[idx%companySecondNames.length] : "")
  + (rnd.nextBoolean() ? companyLastNames[idx%companyLastNames.length] : "");
}

You can use something like rnd.nextInt(2) == 0 or rnd.nextInt(3) == 0 to play with the odds of a longer company name instead of nextBoolean().
Edit
Something that may be worth thinking about is uniqueness - is it a problem if you happen to generate the same company name more than once? Depending on your strategy you could keep track of either the number or name you generate (probably in a Set), and regenerate if it already exists.
Comment: Ok I think I get the jist of it, but I'm not entirely sure how the math within the companies[i] part works; specifically the companyFirstNames[idx...]. Why is there a modulus being used with idx and the companyFirstnames.length? Also thanks for reminding me about possible company names being the same, I didn't catch that.
Comment: It's a common technique used with array indexes to ensure a number is always within the array bounds. If you imagine a few scenarios you'll see how it works: if idx is 20 and array length 10, then 20%10 is 0. If idx is 21, 21%10 is 1. If idx is 5, 5%10 is 5. And so on. It just means you can reuse the same index for all the arrays.


My PostgreSQL database (and users) disappeared, how do I find out what happened to it?

Question: Where I work, servers are managed by an external company, so when you want a new server you get the root password for a while to set it up, and then they change it and you are supposed to make do with a non-root user.
So a while ago I set up my server, it runs Red Hat Enterprise Linux server 5.4, Apache 2.2.3, Apache Tomcat 5.5.23, and PostgreSQL 8.1.22.  I created a user, a database, populated it with data, no problem. They changed the root password and everything seemed to work okay.
A couple of months ago, the server was shutdown for electrical maintenance in the building. I don't know if they shut it down cleanly or not.
As the server is not much used, I only found out last week that the PostgreSQL server didn't start again at reboot. I had to ask them to start it up and when they did, surprise, everything is gone: the user I created, the database.... The Tomcat application itself is still there and working but without a database connection, it doesn't do much.
I managed to get a root password for the time being, so I can look around.
Is there a way to find out what deleted everything? How can I prevent it from happening again?
Everything in /var/lib/pgsql/ is dated the day they restarted the server, in fact everything looks like that day was the first time it was ever started.
Is it possible there are multiple PostgreSQL servers or locations on the machine and the old database is still there somewhere? Or did something wipe out PostgreSQL?
I have a backup so the data itself is not lost, but I would very much like to learn what happened.
Comment: Without knowing what this other company did, it's hard to say what happened or what to do about it.  One guess is that the database wasn't shut down cleanly, and that postgres was refusing to start until it was repaired, and they forced it to start when you told them to start it.  Since you have root now, it would be best to see if you can find the logs from when the system powered back on after reboot, and when they turned postgresql on, to see if there are any meaningful messages
Comment: I think your support company restore server from its own backup, witch was made when they changed root password. Check last system logs before system was damaged.
Answer: Anything special about the disk/lvm configuration on this server?
Was the /var/lib/pgsql/data directory a separate filesystem, maybe on a SAN or just a separate set of disks? If someone had manually mounted data/ without also putting it in fstab you would have a big surprise after your first reboot.
Answer: I think on older version of RH, the init scripts would always look in /var/lib/pgsql/data and init a new cluster if one wasn't found, so a situation like @iPaulo mentions, or any non-default might end up like you have described.
I'd be inclined to do a server wide search for postgres specific files like postgresql.conf or pg_hba.conf and see if I could find another copy of the database, and also check for any logs in /var/log or similar places that might show evidence of the old cluster; there might be a PGDATA lying around some place.
side note, if all is lost, you could use this opportunity to upgrade; 8.1 was EOL'd years ago. Get 9.1 instead :-)


Box topology and connectedness property

Question: I've been trying to properly comprehend how the box topology is constructed, which I noticed I don't understand corretly when my professor asked me to show if it's false or true that the box-topology of connected spaces is connected. I know that it isn't and I've found an example in this thread here: Infinite product of connected spaces may not be connected?. The definition I'm using for the box topology is the same as from Munkres, which is:
Let $\{X_\alpha\}_{\alpha \in J}$ an indexed family of topological spaces. We will take a basis for the space $\prod_{\alpha\in J} X_\alpha$ as the set of the following products $\prod_{\alpha \in J} U_\alpha$, where $U_\alpha$ is an open set of $X_\alpha$ for every $\alpha \in J$.

Firstly, I thought that it was connected and I came with a proof:
Let $A,B$ be open sets for $X = \prod_{\alpha\in J} X_\alpha$ in the box topology, where $ A = \prod_{\alpha\in J} A_\alpha$ and $B = \prod_{\alpha\in J} B_\alpha$, where $A_\alpha, B_\alpha$ are open sets for $X_\alpha$ for every $\alpha$ and $A\cup B = X$ with this union being disjoint.
Since, the union is disjoint we must have at least one $\alpha' \in J$ such that $A_{\alpha'}\cap B_{\alpha'} = \emptyset$. Since $A\cup B = X$, then $A_{\alpha'} \cup B_{\alpha'} = X_{\alpha'}$ and given the fact that $X_{\alpha'}$ is connected we gain that $X_{\alpha'} = A_{\alpha'}$ and $B_{\alpha'} = \emptyset$ without loss of generality.
So, what I did next is to say that we must have $B = \emptyset$, because it has one of its coordinates being the "empty coordinate". Otherwise, if $B$ is not the empty set, something that doesn't make sense to me, how could I pick an element that is equal to something not empty in the coordinates $B_\alpha$ for $\alpha \neq \alpha'$ while being something "empty" in the coordinate $B_{\alpha'}$?
In general, I'm really doubtful if some set similar to $B$, in the case where $B\neq \emptyset$, can be an element for the basis of the box topology. According to the definition it seems possible however from my point of view I don't see how it is viable to pick an element from such a set.
In the end, considering I wasn't so sure of what I did, I searched a little and I found the page I cite in first paragraph. My proof is obviously wrong, but I didn't managed to understand my mistake until now and I have a feeling that this is strictly related on how the box topology works somehow.
If someome can help me I'd be much obliged :)
Comment: You only covered the case that $X$ is covered by two **basic** open sets, not two **general** open sets. That makes a big difference.
Answer: The problem with your proof is that $A$ and $B$ do not have to have the form $A = \prod_{\alpha\in J} A_\alpha$ and $B = \prod_{\alpha\in J} B_\alpha$.  Remember, sets of this form are not the entire box topology, but only a basis for the box topology.  So instead, $A$ and $B$ just must be unions of sets of this form.
Comment: Correct, that does not hold.  I would suggest testing that out with an example where $I$ and $J$ each have just two elements and you can draw the sets as rectangles in the plane.
Comment: Sure, it's just the empty set.
Comment: Yes, a product is empty if any of its coordinates are empty.
Comment: Sure, that works.
Comment: So what you are also saying is that the following equality $\cup_{\beta \in I}\prod_{\alpha \in J} A_\alpha^\beta =\prod_{\alpha \in J} \cup_{\beta \in I}A_\alpha^\beta$ doesn't hold, right?
Comment: Ok, thanks, I'll do that! However I still have a doubt: what about that type of basic open set $\prod_{\alpha \in J} B_\alpha$ where $B_\alpha' = \emptyset$ for some $\alpha'$? Does it make sense in the box topology?
Comment: Even if all the others coordinates are not the empty set?
Comment: I can prove it by contradiction, right? I can suppose that it has an element in such a product, which then lead me to say that there is an element in this coordinate given by the $\emptyset$, giving us the contradiction.
Comment: Thanks, you helped me a lot!

Box topology and connectedness property


Pointer behaviour gives value as 1

Question: To be clear, I am aware of pointer to pointer concept in C and of dereferencing double, triple pointers. The only doubt I have is in the following program which I wrote:
<code>#include<stdio.h>
int main(){
    int a;
    int* p;
    a=5;
    p=&a;
    int **q;
    printf("*p=%d\n",*p);
    printf("*q=%d\n",*q);
}
</code>
Now I know, the program is quite stupid and makes no sense, but that's  not the problem. The question is WHY?
Why is the Output like this:
<code>*p=5
*q=1
</code>
Why is *q=1 on every run?
Also it is to keep in mind, if I now declare a ***r;
And add the following line:
<code>printf("*r=%d\n",*r);
</code>
Now the output is :
<code>*p=5
*q=-40821602 //garbage
*r=1
</code>
Now, *r=1. WHY?
Same goes for ****s. In that case, *q,*r is a garbage and *s=1. Why?
Comment: You have undefined behaviour, that's why.
Comment: Undefined Behavior (UB for short) usually means that any discussion about behavior is moot. However what happens here is that you're using uninitialized variables, whose values are *indeterminate* and seemingly random. It's this "seemingly random" values you see.
Comment: It isn't that strange for undefined behaviors to be consistent over time.  I've had some that were consistent for days, then something happened and the behavior changed.  Maybe I took an antivirus update, or a hotfix, who knows.  The fundamental answer to 'why' is 'because that pointer occupies a portion of memory that happens to have a '1' in it fairly consistently'.  Recompile with different flags and see if it changes (e.g., change debug settings or optimization settings.
Comment: If you open a debugger in assembly you can step through the machine instructions one by one which should provide clarity. Nothing you've seen surprises me at all and I'm not sure why you find it odd.
Comment: Two things: You need to print `void *` pointers (casting is needed) using the `"%p"` format specifier; And you never initialize `q` meaning it dereferencing it will lead to [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior).
Comment: I am familiar with genric pointer. The question is what's with 1? Is displaying 1 an undefined behaviour?
Comment: I would advise you to open it up in a debugger. It will likely print something different and/or seg fault but you might learn a bit about uninitialized pointers. Normally, they aren't written intentionally.
Comment: I am not seeing 1 as random, I have clearly mentioned 1 gets displayed on every run.
Comment: @doug I have tried using a debugger. No good
Comment: @doug I am using Immunity by default.
Comment: "Seemingly random" doesn't mean "really random". Also note what happens once you make a very small change, how suddenly you get something completely different? And talking about random: https://xkcd.com/221/ and https://imgur.com/gallery/uR4WuQ0
Comment: @Someprogrammerdude I appreciate the comment. Failure to learn from mistakes makes it worse. Thanks for correcting me.
Comment: Printing `*p` prints the value of `a`, which is `5` as you are seeing.   Printing `*q` gives undefined behaviour in multiple ways: `q` is uninitialised so evaluating its value gives undefined behaviour, as does evaluating `*q` (it is necessary to evaluate `q` to evaluate `*q`), and then printing it introduces another round of undefined behaviour (`%d` format and the type of `*q` don't match).   When behaviour is undefined, any result is permitted.   Consistency of that result is permitted, but not guaranteed.
Answer: Evaluation of an uninitialized pointer is undefined behavior, and that is what you did. cppreference states the following on undefined behavior:

Undefined Behavior:

undefined behavior - there are no restrictions on the behavior of the program. Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, modification of the same scalar more than once in an expression without sequence points, access to an object through a pointer of a different type, etc. Compilers are not required to diagnose undefined behavior (although many simple situations are diagnosed), and the compiled program is not required to do anything meaningful.

Hence, you cannot expect anything meaningful coming out of your program. It may print 1, but it could also do anything else. In my case, for example, it simply crashed.
So the question "why?"  is simply not a valid question.

Pointer behaviour gives value as 1