Can open sets be an open cover, for itself?

Question: I have Baby Rudin's book with me and it clearly defines a cover to be open. In a followup, it defines a set $K$ to be compact if every open cover of $K$ contains a finite subcover.
And the rest I quote

More explicitly, the requirement is that if $\{ G_{\alpha}\}$ is an open cover of $K$, then there are finitely many indices $\alpha_1, \dots, \alpha_n$ such that $$K \subset G_{\alpha_1} \cup \dots\cup G_{\alpha_n}$$

From the notation, it would seem to suggest that we can't have $K$ to be an improper subset of the covers. Now in another book (which I referenced another user whom referenced the book) by Richardson (I don't know the full name sorry), it's definition of a cover allows a set to cover itself.
So what subtlety could I have possibly overlooked? Sorry if this mysterious reference is vague, but I couldn't get enough information on the book.
Comment: What part of the notation suggests that $K$ can't be an improper subset?
Comment: Note that a set _can_ cover itself, but the requirement that a set be compact is that EVERY open cover has a finite subcover, not just there exists an open cover with a finite subcover.
Comment: Some people use $\subset$ for proper inclusion and $\subseteq$ for possibly improper inclusion. Other people use $\subsetneq$ for proper inclusion and $\subset$ for possibly improper inclusion. Because of this ambiguity in the meaning of $\subset$, I don't use that symbol at all; I use only $\subsetneq$ and $\subseteq$, whose meanings are unambiguous. And of course, I recommend that everybody follow my convention.
Comment: @BDub, isn't $\subset$ mean a proper subset? Mean $K$ can't be equal to the collection of open covers?
Comment: @sizz Usually $\subset$ also means improper set inclusion. If one wants to be specific that a subset is a _proper_ subset, the notation $\subsetneq$ is sometimes used. Here Rudin uses $\subset$ to include the case of improper inclusion.
Comment: @sizz Rudin uses $\subset$ as $\subseteq$
Comment: @Nameless, aren't they different things?
Comment: @sizz Rusin uses them the same way. I treat them differently though
Answer: $K$ can be an improper subset in the definition. Some authors use $\subseteq$ and $\subset$ for subset and proper subset respectively, while others use $\subset$ and $\subsetneq$ respectively. Rudin uses the latter.
An open set obviously forms an open cover of itself, but a set is compact if every open cover has a finite subcover. You need to understand the notation for subset and definition of compact to avoid confusion.
Comment: That's right, so doesn't that mean K can never be equal to the collection of open covers by the notation in Rudin?
Comment: So then he is implying that a set can't cover itself no?
Comment: And therefore it supposedly covers itself? Because the notation says no
Answer: Note that a set can cover itself, but the requirement for a set to be compact states that every possible open cover has a finite subcover. As an example take $I=[0,1]\subseteq\mathbb{R}$ endowed with the subspace topology. Then every open cover $\{G_\alpha\}_{\alpha\in A}$ of $I$ will necessarily properly contain $I$ as $0$ and $1$ must be covered by some open intervals, say $(-\delta,\delta)$ and $(1-\varepsilon,1+\varepsilon)$ for $\delta,\varepsilon>0$. This says that $I\subsetneq \bigcup_{\alpha\in A}G_\alpha$ for every open cover, but since we're in a metric space and $[0,1]$ is closed and bounded, it is compact. Thus, there are a finite number of indices, say $\alpha_1,\ldots,\alpha_n$ such that $$I\subsetneq G_{\alpha_1}\cup\cdots\cup G_{\alpha_n}.$$As an alternative, if we consider $X=[0,1]$ as a topological space in its own right, then it is compact and hence every open cover $\{U_\alpha\}_{\alpha\in A}$ of $X$ will be such that $$X=\bigcup_{\alpha\in A}U_\alpha.$$ This shows that, depending on the space and whether or not it is viewed as a subspace, an open cover may properly contain the space or may equal the space.
Comment: Remember that the Heine-Borel theorem (which you used to say that $I$ is compact) itself requires the compactness $I$. Of course it is always possible to use a fact to prove a theorem, then forget this fact and only remember the theorem, and then restore that fact from the theorem again :-) But I'd say that boundedness and closedness of $I$ is more of an indicator of compactness than the reason for this.
Comment: Oh, and Heine-Borel only works in $\mathbb R^n$, not in every metric space.
Answer: $K$ can be an improper subset in the definition. An open set obviously forms an open cover of itself, and is obviously a finite cover; but a set $K$ is compact if [and only if] every open cover has a finite subcover (as you yourself wrote, as per Definition 2.32 in Baby Rudin).
You'll find soon enough (if you have not already encountered this) that the definition of compactness you discuss above is the "foundational" definition of compactness used in Rudin. You'll see that chapter 2 proceeds to show that there are ways (using Theorems introduced and proven) to establish that a set is compact if it is, for example, (i) a closed subset of a compact space, or (ii) if it is in $\mathbb{R}^n$ and is closed and bounded ... etc.

I think the main confusion here is with the notation Rudin uses to denote "is a subset of."
Usually, authors (like Richardson) use $\subseteq$ to denote subset or set inclusion in general (meaning "is a proper subset of or is equal to") and they use $\subset$ exclusively to denote "is a (strictly) proper subset of".
Other authors, like Rudin, simply use $\subset$ to denote the inclusion relation: "is a subset of or is equal to". Some, but not Rudin in PMA, use the symbol "$\subsetneq$" to denote the exclusion of set equality (i.e., to denote a proper subset).  See the "List of Special Symbols" which immediately precedes the "Index" in Baby Rudin: Rudin makes no mention of, nor any use of, the symbol $\subseteq$ nor of the symbol $\subsetneq$ in his text.
So to specify "$A$ is a proper subset of $B$", Rudin will specify in some sense, that he is referring to a "proper subset" or otherwise omit the prospect of set equality, e.g. "$A\subset B$ AND $A \neq B$"). That is, unless Rudin states otherwise, assume $A\subset B$ means $A\subseteq B$ when reading the text.
Comment: @sizz Is this making sense now? Look through Rudin...
Comment: I think the main problem was me was to get used to seeing this misleading notation on subsets. As for my original question, I feel like I asked "Is an open cover an open cover?". I wonder if that is an equivalent question.
Comment: Sort of equivalent ;-)
Comment: I have an older edition of Rudin, in the appendix, he says his notation is the "inclusion" notation. I am guessing that means he means to *include* equality?
Comment: Yes, sizz, Rudin uses $\subset$ in its "inclusive" sense, meaning what we normally see as $\subseteq$. I took me some getting-used-to when I first encountered Rudin's subset notation. At any rate, is this question (posted) cleared up for you?
Comment: I think I came up with a better argument. If I say and agree that a set is a subset of itself, then by all means i must comply with the fact that an open set is an open cover of itself.
Answer: If $X$ is a metric space and $K$ is a subset, then I believe Rudin (in his Principles book) defines $K$ to be compact if for every collection of open sets $\{U_i:i\in I\}$ of $X$ with the property that $K\subseteq\bigcup_iU_i$, there are finitely many $i_1,\ldots,i_n\in I$ with $K\subseteq U_{i_1}\cup\cdots\cup U_{i_n}$. That is to say, the definition involves coverings by sets open in $X$. Compact subsets in metric spaces are closed, and if the metric space is connected, like $\mathbf{R}^n$, non-empty, proper closed sets are not open, so, because an arbitrary union of open sets is open, if $X$ is connected and $K$ is a non-empty, proper closed subset, you will never have $K=\bigcup_iU_i$ for $U_i$ open in $X$.
The aspect of this definition that I don't really like is that it makes it seem like compactness is a relative property, i.e., that it depends somehow on the ambient space $X$. This is not the case. By restricting the metric on $X$ to $K$, $K$ becomes a metric space in its own right, and one can check that a subset $A$ of $K$ is open in the metric topology of $K$ if and only if $A=K\cap U$ for some open subset $U$ of $X$. With this in mind, you can verify that $K$ is compact in Rudin's sense given above if and only if for every collection $\{V_j:j\in J\}$ of sets open in $K$ with the property that $K=\bigcup_jV_j$ (note the equality), there are finitely many $j_1,\ldots,j_n\in J$ with $K=V_{j_1}\cup\cdots\cup V_{j_n}$.
This carries over to arbitrary topological spaces without change (I just phrased it in terms of metric spaces since I think that is the generality of Rudin's book). The point is that compactness is an intrinsic property of topological spaces, and is in no way relative to some larger ambient space.


$X_1, X_2, \cdots, X_n$ : i.i.d. $\sim \text{Bernoulli}(p)$. Then $\bar{x}$ is an unbiased estimator of $p$.

Question:
Let $X_1, X_2, \cdots, X_n$ be i.i.d. $\sim \text{Bernoulli}(p)$. Then $\bar{x}$ is an unbiased estimator of $p$.

How should I approach for this types of problems.
Some hint will also help me.
Comment: Please see https://math.meta.stackexchange.com/questions/5020/
Comment: Actually independence is redundant here.
Answer: If you define $\bar{x}$ as the sample mean, i.e.
$$\bar{x} = \frac{1}{n}\sum_{i=1}^n X_i$$
Take expectations on both sides
$$E \bar{x} = E \frac{1}{n}\sum_{i=1}^n X_i$$
Since expectation is a linear operator, then
$$E \bar{x} =  \frac{1}{n}\sum_{i=1}^n E X_i$$
But since $E X_i = p$, then
$$E \bar{x} =  \frac{1}{n}\sum_{i=1}^n p$$
Since $p$ is a constant, then we could extract it as
$$E \bar{x} =  \frac{p}{n}\sum_{i=1}^n 1$$
Now since $\sum_{i=1}^n 1 = n$, we get
$$E \bar{x} =  \frac{p}{n}n = p = \mu$$
where $\mu = p$ is the true mean of the Bernoulli distribution, hence we say that $\bar{x}$ is an unbiased estimator of $p$, since in average, it gives us $p$.
Answer: You know that $E(X) = p$ or, for any $i$, $E(X_i) = p$.
So,
$$E(\bar X) = E\Bigl(\frac {\sum_{i=1}^n X_i}{n}\Bigl)$$
$$=\frac{1}{n}\Big(E{\sum_{i=1}^n X_i}\Big)$$
$$=\frac{1}{n}\Big({\sum_{i=1}^n E(X_i)}\Big)$$
$$=\frac{1}{n}(np)$$
$$=p$$
By the definition of Unbiased Estimator, $\bar X$ is an unbiased estimator of $p$.
Answer: Use the fact that $X_i$ are Identical. And the linearity property of Expectation.
$E(\bar{X})=E(X_1)=p$


Hook inside class

Question: I would like know if it's possible to use hook inside a class and inside .module file.
By example :
modulename.module
<?php
use Drupal\xenforo\Xenforo\XenAPI;
use Drupal\Core\Entity\EntityInterface;
Class XenforoBridgeIntegration {
    // use Drupal 8 hook here and can use OrientedObject inside
}

I have try, but hook don't work if it's inside a class ?
Comment: There is an issue for this: https://www.drupal.org/node/1972304 postponed until 8.1.x at this stage.
Answer: No, it's not possible.
Hooks are functions that exist in the global namespace. Class/instance methods cannot be used to implement them.
If you take a look at the very simple ModuleHandler::invoke method, you'll see this in action:
public function invoke($module, $hook, array $args = array()) {
  if (!$this->implementsHook($module, $hook)) {
    return;
  }
  $function = $module . '_' . $hook;
  return call_user_func_array($function, $args);
}

As you can see, you must have a function called MODULENAME_HOOKNAME available in the global namespace, no consideration is given to classes or namespace resolution.
You can (and probably should) hand off whatever processing you're doing inside the hook to a specific class, but the hook itself will need to be implemented in procedural style.
Comment: If you want to keep your code in classes, you could implement a slim function that calls a service or static method. Payment does that for example, but I personally find that goes too far :)

Hook inside class


Privileges for spark sql with sentry

Question: I'm trying to make the privileges to access Spark-SQL with sentry, and spark sql connects with thrift port withe hiveserver2( --hiveconf hive.server2.thrift.port). However, while I can limit users' privileges on hive successfully, I cannot limit the access with spark SQL through sentry.
Anyone who met with the same problem?
Comment: According to [this posting](https://community.cloudera.com/t5/Advanced-Analytics-Apache-Spark/Spark-and-Sentry/td-p/41273) by a Cloudera employee, Spark SQL does not currently go via HiveServer2
Answer:
Follow the doc,config hive in Spark.
Add Sentry jars to the classpath, Spark will load them automatically.

It works for me.

Privileges for spark sql with sentry


Usar conteudo selecionado pelo usuário no ComboBox como key (map) em classe enum

Question: Beleza, galera?
To com uma dificuldade. É exatamente o que o título diz.
Código que contem o cbox:
JFileChooser fc = new JFileChooser(new File(pastaPadrao));
String[] siglaStrings = { "Selecione", "CIC", "CISEI", "GERMEM" };
public  JComboBox<String> siglaList = new JComboBox<String>(siglaStrings);
int teste;

public TelaInicial() {
    super("Selecionar um Caso de Uso para validação");
    this.setLocation(new Point(600, 400));
    Container container = getContentPane();
    GridBagLayout layout = new GridBagLayout();
    container.setLayout(layout);
    container.add(siglaList);

    JButton btnSelecionarCasoUso = new JButton("Selecionar Caso de Uso");

    btnSelecionarCasoUso.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            fc.setPreferredSize(new Dimension(1000, 600));

            int res = fc.showOpenDialog(null);

            teste = siglaList.getSelectedIndex();
            if (res == JFileChooser.APPROVE_OPTION && teste != 0) {
                File arquivo = fc.getSelectedFile();
                ResultadoQa resultadoQa = new ResultadoQa(arquivo.getName());
                resultadoQa.setVisible(true);
                resultadoQa.setSize(1200, 800);
                resultadoQa.setLocation(new Point(100, 50));
                resultadoQa.setResultado(getResultadoQa(arquivo));
            } else {
                JOptionPane.showMessageDialog(null, "Você não selecionou nenhum arquivo\n ou não selecionou a sigla do CSU.");
            }
        }
    });

    container.add(btnSelecionarCasoUso);

    setSize(400, 200);
    setVisible(true);
}

Classe enum com as chaves:
public enum TipoItem {

/*Itens Genéricos*/
REGRA_NEGOCIO_GENERICA     ("Regra de Negócio Genérica", "(RNEG).(\\d+)"),
REGRA_VALIDACAO_GENERICA   ("Regra de Validação Genérica", "(RVAG).(\\d+)"),
FLUXO_ALTERNATIVO_GENERICA ("Fluxo Alternativo Genérico", "(FAG)(\\d+)"),
FLUXO_EXCECAO_GENERICA     ("Fluxo de Exceção Genérico", "(FEG)(\\d+)"),
MENSAGEM_GENERICA          ("Mensagem Genérica", "(MSGG).(\\d+)"),

SIGLA                      ("Sigla do CSU", "(siglaLista)"), //*** --> tem que ser recebido na tela inicial junto com a escolha do doc
REGRA_NEGOCIO              ("Regra de Negócio", "(RNE).(\\d+).(\\d+)"),
REGRA_VALIDACAO            ("Regra de Validação", "(RVA).(\\d+).(\\d+)"),
REQUISITO_FUNCIONAL        ("Requisito Funcional", "(RF).(\\d+)"),
REQUISITO_NAO_FUNCIONAL    ("Requisito Não Funcional", "(RNF).(\\d+)"),
MENSAGEM                   ("Mensagem", "(MSG).(\\d+).(\\d+)"),
FLUXO_PRINCIPAL            ("Título do Fluxo Principal", "(Fluxo Principal)"),
FLUXO_ALTERNATIVO          ("Fluxo Alternativo", "(FA)(\\d+)"),
FLUXO_EXCECAO              ("Fluxo de Exceção", "(FE)(\\d+)"),
PONTO_INCLUSAO             ("Ponto de Inclusão", "(PI).(\\d+)"),
PONTO_EXTENSAO             ("Ponto de Extensão", "(PE).(\\d+)"),
ATOR                       ("Ator", "((A)|(a))(tor)(\\s)"),
COMPLEXIDADE               ("Complexidade", "((Baixa)|(Média)|(Alta))"),
PRIORIDADE                 ("Prioridade", "((Opcional)|(Desejavel)|(Essencial))"),

MSG_FE                     ("MSG dento do Fluxo de Exceção na respectiva oredem", "(O sistema exibe a MSG)"),

SAAA                       ("SAAA", "(SAAA)"),
INTERFACE                  ("Interface", "((I)|(i))(nterface)(\\s)"),
TERMOINGLES                ("Termos em Inglês", ""),
CAMPO                      ("Campos", "");

private final String descricao;
private final String expressaoRegular;

TipoItem(String descricao, String expressaoRegular){
    this.descricao = descricao;
    this.expressaoRegular = expressaoRegular;
}

public String getDescricao() {
    return descricao;
}

public String getExpressaoRegular() {
    return expressaoRegular;
}

}
Estou usando o HashMap para definir algumas keys, sendo assim,  o que eu quero é transformar a string do índice selecionado pelo usuário em uma key, assim o meu programa vai me retornar a quantidade de ocorrência dessa String no doc (word). Ou seja, eu só quero adicionar mais uma chave, só que é como se fosse um Scan, e não uma constante já definida na classe enum (onde estão as chaves). Agradeço muitão a quem tentar ajudar.
Answer: Tenta o seguinte: primeiro, cria o renderer:
class TipoItemRenderer extends BasicComboBoxRenderer {
    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (value != null) {
            TipoItem tipoItem = (TipoItem) value;

            if (index == -1) {
                setText("" + tipoItem.ordinal());
            } else {
                setText(tipoItem.getDescricao());
            }
        }

        return this;
    }
}

Então, instancia o comboBox:
comboBox = new JComboBox(TipoItem.values());
comboBox.addActionListener(this); // Vai chamar o método actionPerformed(ActionEvent)
comboBox.setRenderer(new TipoItemRenderer());

Por último, cria o método do evento:
public void actionPerformed(ActionEvent e) {
    JComboBox comboBox = (JComboBox) e.getSource();
    TipoItem tipoItem = (TipoItem) comboBox.getSelectedItem();

    System.out.println(tipoItem.ordinal() + " - " + tipoItem.getDescricao());
}

Comment: Precisa de um comboboxmodel para isso funcionar. renderer sozinho presume-se de que um model esteja tratando o tipo de objeto TipoItem, sem ele, o renderer não receberá nunca um objeto tipoitem.
Comment: Não tive como testar, mas com essa resposta você deve chegar onde precisa.
Comment: Não fui eu o autor dá pergunta. Foi só uma dica pra completar a resposta, pq somente com renderer não vai funcionar, precisa de Combomodel também.


How do I add a new blank directory to a Git repository

Question: How can I add a blank directory (that contains no files) to a Git repository?
Answer: Git does not allow adding/tracking empty directories (as for, for example, CVS).
There is a common convention to add an empty file to the directory you need to track named <code>.gitkeep</code>.
You will remove this file if a meaningful file will be added to it.


upgrading to specific php version on centos 7

Question: I am currently running centOS 7 with an apache based webserver with php 5.5.38 and I was recommend to upgrade to PHP 5.6.XX for best stability on behalf of my custom made web-app.
Is there a way to upgrade to this specific PHP version without getting the latest built? Please do not answer with advice on how the latest built is the best and most recommended, I am looking for a solution to upgrade to an exact version.
Some expert help would be greatly appreciated, thank you
Comment: I think a supported  PHP 5.6 is available in the software collections repo, but I don't have a CentOS 7 system available at the moment https://wiki.centos.org/AdditionalResources/Repositories/SCL
Answer: Multiple versions of PHP are available in the SCL Repos but if you're looking for a very specific version of PHP, you might want to check the repos here to see if your build is available.
If it's not, you may have to package up the version of PHP you want into an RPM, or install it manually. There's an example spec file in the PHP github repo


D7. Facebook Stream: show user's feed

Question: I try to display authorised user's news feed:
I installed Facebook Stream module in Drupal 7. After facebook login module displays an error:

FacebookApiException: User must specify a valid extended permission or
  data permission in BaseFacebook->throwAPIException() (line 1325 of
  Z:\home\devfb.kz\www\sites\all\modules\facebook_stream\facebook-php-sdk\src\base_facebook.php).

I can't understand why permissions which I specified in the module are invalid?
Permissions:
<code>return '<fb:login-button '. drupal_attributes($attr) .' onclick="FB_Connect.login_onclick()" scope="read_stream,publish_stream,offline_access">'. $text .'</fb:login-button>';
</code>
Maybe I can do this with another module?
Answer: If I understand what you want correctly, you don't need a specific module at all to do this. You can just have embed code generated and add that to the source code for the block/page you want to add it to. You can have embed code generated here. Be sure to select "Show Posts" if that's what you want.
Edit: I just re-read your question and see that you mean to do this for the authorized user... in this case my answer may not be helpful.
Answer: I understud: I'm use "read_stream" scope without additional submit in my FB App settings. To access user's news feed I must submit my App to review and only after approval I'll have ability to get access to this API feature.

D7. Facebook Stream: show user's feed


Does CAS support OAuth Resource Owner Password Credentials Grant?

Question: After some rudimentary testing I've gotten CAS to work with the Authorization Code Grant. This seems to be the only grant mentioned in the documentation. Does CAS support other grants outlined in the OAuth2.0 draft 2-31 section 4.3? What are the service endpoints?
Answer: I'm the creator of the OAuth server support for CAS and so far, it only supports the authorization code grant which matches pretty well with the CAS webflow...
Comment: Does CAS support any other grant type other than Authorization Grant?


Erro ao instalar mongo-hack no Ubuntu 14.04

Question: Ao instalar o o mongo-hack no Ubuntu está sendo gerado o seguinte erro:

npm install -g mongo-hacker
  |
  email@example.com install
  /usr/lib/node_modules/mongo-hacker make install
cat config.js base.js hacks/aggregation.js hacks/api.js
hacks/auto_complete.js hacks/cmd_search.js hacks/color.js
  hacks/common.js  hacks/count.js hacks/dbref.js
  hacks/find_and_modify.js hacks/helpers.js  hacks/index_paranoia.js
  hacks/old_aggregation.js hacks/prompt.js  hacks/show.js
  hacks/sh_status.js hacks/uuid.js hacks/verbose.js >  mongo_hacker.js
INSTALLATION
Linking MongoHacker to .mongorc.js in your home directory: ln -sf
  "/usr/lib/node_modules/mongo-hacker/mongo_hacker.js" ~/.mongorc.js ln:
  failed to access '/root/.mongorc.js': Permission denied make: ***
  [install] Error 1
npm ERR! email@example.com install: make install
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the firstname.lastname@example.com install script.
npm ERR! This is most likely a problem with the mongo-hacker package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     make install
npm ERR! You can get their info via:
npm ERR!     npm owner ls mongo-hacker
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 3.19.0-47-generic
npm ERR! command "/usr/bin/node" "/usr/bin/npm" "install" "-g"
  "mongo-hacker"
npm ERR! cwd /mongo-hacker/mongo-hacker/hacks
npm ERR! node -v v0.10.37
npm ERR! npm -v 1.4.28
npm ERR! code ELIFECYCLE
firstname.lastname@example.com postuninstall /usr/lib/node_modules/mongo-hacker
  make uninstall
rm -f ~/.mongorc.js rm: cannot remove '/root/.mongorc.js': Permission
  denied
make: *** [uninstall] Error 1
npm WARN continuing anyway firstname.lastname@example.com postuninstall: make
  uninstall
npm WARN continuing anyway Exit status 2
npm ERR! not ok code 0

Já tentei como root e mesmo assim o erro continua.
Answer: Passei pelo mesmo problema hoje.
Depois de tentar várias soluções, encontrei essa com a qual eu consegui resolver esse problema.
<code>sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
</code>
Se quiser consultar o link original :  https://docs.npmjs.com/getting-started/fixing-npm-permissions


How to determine if a script is started by cron?

Question: I have a script that run in some cases when some event occur. It also run when cron run (cron.php) or the "Run cron button" from admin panel is clicked.
How can I determine that from script that is started by drupal cron.php?
Comment: Inspect `debug_backtrace()`, the first entry will have the name of the originating file in it (index.php or cron.php)
Comment: Pretty sure this is a dup if someone wants to dig.
Answer: You may check your $_SERVER globals in the script.
A better way, I think, would be to pass a parameter with your call to the script that separates the caller (I.e when you call it from the HOOK_cron(), add a myFunc(..., $caller="cron") to your call. And declare myFunc(..., $caller=null) as default parameter.
If this is not possible, you may set a session variable in HOOK_cron and check that in your script.
Answer: If you want to run a script during cron, you should do so by invoking hook_cron in a module like this:
function my_module_cron() {
  invoke_custom_script();
}

When you do this, you could tell the script, that it is being called from cron by adding a parameter etc. This could be done like this.
function my_module_cron() {
  invoke_custom_script(array('context' => 'cron'));
}


erro classe abstrata (invalid new-expression of abstract) C++

Question: Bom estou com um erro nas minhas 3 classes filhas(dvd,jogos,carro) de uma classe mãe chama locadora.
Estou tentando utilizar o factory method e gera o erro no new com seguinte mensagem: invalid new-expression of abstract class type no dvd no jogo e no carro.
<code>Produto* CriarNovoProduto(){
char letra;
do{
  printf("QUAL PRODUTO?:\n");
  printf("(J)OGO  (C)ARRO  (D)VD\n");
  letra=getchar();
  letra=tolower(letra);
  }while(letra!='j' && letra!='c' && letra!= 'd');
   switch(letra){
            case 'j':
             return new Jogo();
            case 'c':
              return new Carro();
            case 'd':
              return new Dvd();
            default:
               return NULL;
          }
         }
</code>
(não sei se posso postar link com o  código completo mas de qualquer forma: https://ideone.com/XLGAoI )
Answer: a função "getpreco" não foi refeita nos filhos


Aplicando mascara Jquery em valor e não input

Question: Olá, tenho os seguintes valores de telefone e celular respectivamente:
Telefone: 1111111111
Celular: 11111111111
Já possuo o valor no banco de dados, gostaria apensar de apresentar esses valores formatados com as seguintes máscaras:
Telefone = (11) 1111-1111
Celular = (11) 11111-1111
Alguém poderia me ajudar ? Gostaria de apenas aplicar as mascaras via JavaScript não quero por no input, pois guardo o valor somente numérico no BD, gostaria apenas de apresenta-lo formatado.
Se alguém puder ajudar agradeço!
Comment: Você pode usar subtring
Comment: Editei minha resposta, por falta de atenção respondi sobre formatação em um input, mas já arrumei para o seu caso, da uma olhada ai! Se puder marcar como resposta correta agradeço ;)
Comment: Um exemplo de como formatar qualquer tipo de padrão de forma flexível com uma única função: https://pt.stackoverflow.com/a/55235/4793
Comment: Bruno, obrigado, mas utilizei a solução do nosso amigo abaixo. Mesmo assim obrigado!
Answer: Use Regex e replace():
<code>function mascaraTelefone(value){
    value = value.replace(/\D/g,"");                  //Remove tudo o que não é dígito
    value = value.replace(/^(\d{2})(\d)/g,"($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    value = value.replace(/(\d)(\d{4})$/,"$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    value = value.substr(0, 15);
    return value;
}
</code>
Chame a função passando o valor (telefone) o retorno dela sera o telefone formatado:
<code>//Esse seria o telefone que vem do banco de dados
var tel = "1125346283"

//Essa variavel você pode apresentar
var telFormatado = mascaraTelefone(tel);
</code>
Comment: Obrigado Lucas! Funcionou corretamente!


Probability of pulling black balls from the bag

Question: Bag has 3 balls. 2 white and 1 black. There are 3 pulls. If white is drawn it is removed from the bag. If black is drawn it stays in the bag.
Final outcome can lead to pulling 1, 2 or 3 black balls in total.
Calculating the probability of pulling $3$ black balls in total is easy. $1/3 \cdot 1/3 \cdot 1/3$.
What about the rest? Number of balls can be reduced after a pull if white is drawn.
Comment: There are $2^3=8$ potential patterns of pulls, though white-white-white has a probability of $0$.  You can find the probability of each one (for example white-black-white has a probability of $\frac23 \times \frac12 \times \frac12$) and then add up the cases to answer the question
Comment: Thank you I got 1 black 61%, 2 black 35% and 3 black 4%. is there a general equation for this?
Comment: @Innuendo Your results are correct, as shown in my answer below. I am not aware of a general equation for this particular problem.
Answer: Let $X$ represent the amount of black balls that are drawn. Like you said, the probability of drawing three black balls equals:
$$P(X = 3) = \frac{1}{3} \cdot \frac{1}{3} \cdot \frac{1}{3} = \frac{1}{27}$$
Since the white balls are removed when drawn, we know that the probability of drawing zero black balls equals:
$$P(X = 0) = 0$$
Further, one black ball can be drawn in three ways: $WWB$, $WBW$ or $BWW$. We find:
$$P(WWB) = \frac{2}{3} \cdot \frac{1}{2} \cdot \frac{1}{1} = \frac{1}{3}$$
$$P(WBW) = \frac{2}{3} \cdot \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{6}$$
$$P(BWW) = \frac{1}{3} \cdot \frac{2}{3} \cdot \frac{1}{2} = \frac{1}{9}$$
Thus, the probability of drawing one black ball equals:
$$P(X = 1) = \frac{1}{3} + \frac{1}{6} + \frac{1}{9} = \frac{11}{18}$$
Then, the probability of drawing two black balls must equal:
$$P(X = 2) = 1 - P(X = 0) - P(X = 1) - P(X = 3) = 1 - 0 - \frac{11}{18} - \frac{1}{27} = \frac{19}{54}$$
Indeed, we find:
$$P(WBB) = \frac{2}{3} \cdot \frac{1}{2} \cdot \frac{1}{2} = \frac{1}{6}$$
$$P(BWB) = \frac{1}{3} \cdot \frac{2}{3} \cdot \frac{1}{2} = \frac{1}{9}$$
$$P(BBW) = \frac{1}{3} \cdot \frac{1}{3} \cdot \frac{2}{3} = \frac{2}{27}$$
And thus:
$$P(X = 2) = \frac{1}{6} + \frac{1}{9} + \frac{2}{27} = \frac{19}{54}$$


A question about an asymptotic formula

Question: I've been told that the asymptotic formula $\pi(x+y)-\pi(x)\sim y/\ln x$ holds for $y\ge x^{1/2+\varepsilon}$ if Riemann's hypothesis is true, but I was unable to find a journal reference for this. Does anybody know of any journal reference or any other source where I can find this conditional result?
Comment: I added the reference-request tag, since this is what your question is.  I had to remove the asymptotics tag, though.
Comment: no problem, thank you!
Answer: I don't know the original source, but you can find the result in

Helmut Maier, Primes in short intervals, Michigan Math. J. 32:2 (1985), pp. 131–255.

There are more details in

D. R. Heath-Brown, The number of primes in a short interval, Journal für die reine und angewandte Mathematik (Crelles Journal), 389 (1988), pp. 22–63.

which proves a weaker result without RH.
Selberg had earlier proved that this, and more, is true (unconditionally) for a set of density 1:

A. Selberg, An elementary proof of the Prime Number Theorem, Ann. of Math. 50 (1949), pp. 305–313.
Comment: thank you!! the first reference you've provided is enough for me
Comment: @user135328: Glad to help, sorry I couldn't find the original source.

A question about an asymptotic formula


Find a matrix by Householder transformation

Question: Let A =
 \begin{bmatrix} 1  & -2 \\0  & 0.84 \\0 & 2.88 \\0 & 0 \\\end{bmatrix}
find matrix B
that
B * A =
\begin{bmatrix} *  & * \\0  & * \\0 & 0 \\0 & 0 \\\end{bmatrix}
Could you help me out with that? I would really appreaciate it.
It is supposed to be a simple task but I fail every time I try to do it.
Comment: Don't you think that that the order is B*A ?
Comment: Of course  :) Sorry for the mistake.
Comment: hint: B should leave the first row unchanged. You are really looking for a 3x3 Householder matrix
Answer: Here is a solution :
$$B=\begin{pmatrix}
    1    &     0    &     0     &    0\\
         0 &   0.28  &  \ \ \ 0.96   &      0\\
         0  &  0.96  & -0.28   &      0\\
         0  &       0   &      0  &  1 \end{pmatrix} \ \text{giving} \ \ B*A=\begin{pmatrix}
         1  &  -2\\
         0  &  \ \ 3\\
         0  &  \ \ 0\\
         0  &  \ \ 0   \end{pmatrix}. $$
I assume a certain knowledge about Householder transforms, in particular that such transforms are isometries, thus are norm-preserving ; therefore we must care to send vectors onto vectors with the same norm.
In order for you to understand how $B$ has been found but also to leave you some work :)), here is the Matlab program that has helped me to do the computations:

<code>#1:  U=[1;0;0;0];V=[-2;0.84;2.88;0];% first and second col. of matrix A
#2:  A=[U,V];
#3:  a=sqrt(V(2)^2+V(3)^2+V(4)^2);% observe that V(1)^2 is "missing"
#4:  V1=[-2;a;0;0]; % norm(V1)=norm(V) (Householder = isometric transf.)
#5:  V2=V-V1;
#6:  V2=V2/norm(V2);% now with unit norm
#7:  I4=eye(4); % order 4 identity matrix
#8:  B=I4-2*V2*V2';% Householder matrix mapping V onto V1 and U onto itself.
</code>

Important remark : (in connection with the remark made by @Dunham) Let us recall that the $k$th step of the Householder method consists in working on an $k-1$ dimensional space (here, $k=4$: we are in a first step) This is why (program line #3) we haven't modified the first coordinate of the second vector V (said otherwise: the first coordinate of $V_2:=V-V_1$ is $0$, thus $U$ is sent onto itself because $(I_-V_2V_2^T)U=IU-0=U$).
Remark: Results are exact (no accuracy loss) because in fact all computations can be done with rational numbers with common denominator $25$ such as:
$$ 0.84=\tfrac{21}{25}, \ \ 2.88=\tfrac{72}{25}, \ \ 0.24=\tfrac{7}{25} \ \ \text{and} \ \ 0.96=\tfrac{24}{25}$$
Comment: You haven't been on Math SE site after you have asked your question 4 days ago. Does it mean you are no longer interested by its solution ?


CONSULTAR DADOS A PARTIR DE UMA TABELA DE CHAVE ESTRANGEIRA

Question: Eu tenho 3 tabelas em um banco de dados, uma abriga os dados dos clientes, outras dos produtos e uma das vendas, contendo a chave estrangeira do id da tabela produtos e clientes.

Eu necessito fazer uma consulta que exiba as compras realizadas pelo cliente de ID = 2, mostrando seu nome e o nome do produto que ele comprou. A parte que me confundiu foi na hora de mostrar o nome do produto comprado, consegui realizar apenas a seguinte consulta:

Desde já, agradeço.
Answer: Acredito que essa consulta deve resolver:
select c.nome as 'cliente', p.nome as 'produto' from clientes c
join vendas v on v.idcliente = c.idcliente
join produtos p on p.idproduto = v.idproduto
where c.idcliente = 2

Comment: Obrigado! funcionou...
Answer: Deve ser mais ou menos isso que você procura.
SELECT
    Cliente.NOME,
    Produto.NOME
FROM
    Vendas
        LEFT JOIN Cliente on (Vendas.IDCliente = Cliente.IDCliente)
        LEFT JOIN Cliente on (Vendas.IDProduto = Produto.IDProduto)
WHERE
    Cliente.IDCliente = 2


fiber product of local artinian rings

Question: Let $A,B,C$ be local artinian rings and $p : A \to C, q : B \to C$ local homomorphisms. Why is the fiber product $A \times_C B$ again a local artinian ring?
It is easy to see that $P:=A \times_C B$ is a local ring with maximal ideal $\mathfrak{m}_P=pr_A^{-1}(\mathfrak{m}_A) = pr_B^{-1}(\mathfrak{m}_B)$. Since some power of $\mathfrak{m}_A$ vanishes, the same is true for $\mathfrak{m}_P$. Thus it suffices to prove that $\mathfrak{m}_P$ is finitely generated. But I don't know how to find generators. Is this true at all?
Remark: This is used (without proof) in Schlessinger's article "Functors on Artin rings".
Answer: In the article the author considers $\Lambda$-algebras (where $\Lambda$ is a complete local noetherian ring) which are local, Artin and have the same residue field as $\Lambda$ (which means that the composition $\Lambda \rightarrow A \rightarrow A/\mathfrak{m}_A$ is surjective).
In that case $A$ is a $\Lambda$-module of finite length (because simple $A$-modules are $k$-lines hence simple $\Lambda$-modules, and $A$ is an $A$-module of finite length), and similarly for $B$, so $A \times_C B \subset A \times B$ is also a $\Lambda$-module of finite length, and so it is an artinian $\Lambda$-algebra.
Edit: for those who do not have access to the article, $k$ denotes the residue field of $\Lambda$.
Comment: Some kind of residue field assumption is necessary.  For example, $A = \mathbf C(x)[\epsilon] / (\epsilon^2)$, $B = \mathbf C(y)[\delta] / (\delta^2)$, $C = \mathbf C(x,y)$.  The fiber product is $\mathbf C + \mathbf C(x) \epsilon + \mathbf C(y) \delta$, which is not artinian.
Comment: Ah, thank you! So perhaps it's false in the general case? Anyway I accept this answer because this is the only case which is needed in the article.

fiber product of local artinian rings


Without the return statement for a method written in a class I was able to print the value of that function from outside the class

Question: I am a beginner in python .
There is a class employee which has three function. One is the __init__ function,fullname function  and other apply_raise function .The apply raise function does not take any arguments except for the instance variable(self) itself. Without using the return statement for this function  I was able to print the value of the function from outside the class. How is that possible?
def apply_raise(self):
        pay=int(self.pay*1.04)
        return pay ( its not re

class Employee:
    def __init__(self,first,second, pay):
        self.first = first
        self.second= second
        self.pay = pay
        self.email = first+"."+second + "@gmail.com"
    def fullname(self):
        return "{} {}".format(self.first,self.second)
     def apply_raise(self):
        self.pay=int(self.pay*1.04)
Emp1 = Employee("Mercury","John",5000)
Emp2=  Employee("Abe","Jo",6000)
print(Emp1.pay)
Emp1.apply_raise()
print(Emp1.pay)

def apply_raise(self):
   pay=int(self.pay*1.04)
   return pay                         //with return statement
Emp1.apply_raise()
print(Emp1.pay)    ->The output is 5000

def apply_raise(self):
        self.pay=int(self.pay*1.04)       //without return statement

mp1.apply_raise()
print(Emp1.pay)    ->The output is 5200

Both output are different
Answer: Let's use your example to explain step by step. You have a class employee and you create an instance of this class, that is an object, like this:
emp1 = Employee("Mercury","John",5000)

This will call the constructor, which is the __init__ function defined inside the class. The constructor is going to call it with the given parameters, that is
first = "Mercury"
second = "John"
pay = 5000

The constructor sets up the values of the object attributes: first, second, pay and email. So your current emp1 has the following:
first = "Mercury"
second = "John"
pay = 5000
email = "email@example.com"

The attributes and the methods (object functions) can be accessed using dot after your object, so if you want to see the value of pay you do it like this:
print(emp1.pay) # This shows 5000

You can also set the values of the attributes the same way:
emp1.first = "Luke"

Now if you want to show the first attribute:
print(emp1.first)  # This shows Luke

The value of first has been updated to "Luke".
When you call emp1.apply_raise() in your code, you are actually calling the same function each time, which is the one defined in your class. To call the function defined outside the class, you need to call it like apply_raise(emp1).
In apply_raise you are modifying the value of the attribute pay, by multiplying it by 1.04.
print(emp1.pay)     # shows 5000
emp1.apply_raise()  # modifies pay=5000*1.04
print(emp1.pay)     # shows 5200

The return statement is the value to which the function is going to evaluate to. If you specify no return, it evaluates to None, as it is the case for apply_raise.
print(emp1.apply_raise())  # shows None

But you can still access pay value, because it is not a local variable, it is an attribute since it is prefixed with self. It would be a different story if you would have defined the class method as following:
def apply_raise(self):
    pay = self.pay*1.04

Here we are creating a local variable called pay. This variable exists only in the context of the function. No modification is being done to the object's attribute pay. So if we try it out:
print(emp1.pay)     # shows 5000
emp1.apply_raise()  # defines pay=5000*1.04
print(emp1.pay)     # shows 5000
print(pay)          # error! not defined

But if you return the local variable pay, you could use this outside the context of the method:
def apply_raise(self):
    pay = self.pay*1.04
    return pay

You need to assign it to a variable:
print(emp1.pay)               # shows 5000
new_pay = emp1.apply_raise()  # returns pay=5000*1.04 and assigns it to new_pay
print(emp1.pay)               # shows 5000
print(new_pay)                    # 5002

You notice the attribute of emp1 did not change, but we were able to use the pay local variable outside apply_raise by assigning it to new_pay, thanks to the return statement.
Hope it is clear enough. If you have more questions, do not hesitate!


Lost with Sympy solving

Question: I'm approaching this problem with little math experience and moderate python experience, any help appreciated.
I have these values and equations and need to find x and y:
x+y == a
a = 32.8
b = 19.3
c = 82
d = 12
e = 8
f = 69
f == ((((b+e)+x)*c)+(d*y))/(b+x+y)

Using sympy, I wrote the following code:
from sympy import symbols, Eq, solve, init_printing

a,b,c,d,e,f,x,y = symbols('a b c d e f x y')
init_printing(use_unicode=True)

expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)

#I think this is x in terms of y
xiny = solve(expr.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]),x)

# and I think this is y in terms of x
print(solve(eq.subs(a,32.8),y))

#But how to sub them in and continue?
Eq(f,expr)
eq = Eq(x+y,a)
solution = solve((eq.subs(a,32.8),expr.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]) ),(x,y))
print(solution)

Using sympy I think I've managed to find x in terms of y, and y in terms of x but can't tie it all together. I'm getting negative numbers which don't make sense to me(especially for volumes which is the use case). What's the best way to approach this, especially as the a-f variables will be input by the user. Any help appreciated.
Comment: Welcome to SO @brraap. To enable the other users to help you, it is best to append a minimal working example of your code here.
Answer: I've giving up the sympy syntaxe to focus on the math problem, so your system of equation you wanna solve is :
x+y = 32.8
((19.3+8+x)*82+12y)/(19.3+x+y) = 69
And I got the solution x = 9627/700 and y = 13333/700
If this solution is not correct than I guess there is a problem with the equation, or of course I can have solve it wrong
And in your sympy code, shouldn't it be more something like this :
expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)
eq1 = Eq(f,expr)
eq2 = Eq(x+y,a)
solution = solve((eq2.subs(a,32.8),eq1.subs([(b,19.3), (c,82),(d,12),(e,8),(f,71)]) ),(x,y))
print(solution)

Answer: Interesting... Let's see. As I got you need to solve this system with a as parameter:.(It's made with https://codecogs.com/latex/eqneditor.php. May be it will help you to explain your tasks in future)
And code:
from sympy import *

a,b,c,d,e,f,x,y = symbols('a b c d e f x y')
init_printing(use_unicode=True)

a = 32.8 # you can put here a input() command
b = 19.3
c = 82
d = 12
e = 8
f = 69

# Note that "==" operator always returns bool, so this row does nothing
f == (((b+e+x)*c)+(d*y))/(b+x+y)

expr = ((((b+e)+x)*c)+(d*y))/(b+x+y)

eq1 = Eq(f,expr)

eq2 = Eq(x+y,a)

solve([eq1, eq2], (x,y))

{:13.7528571428571, :19.0471428571429}

I found that you have defined your variables twice: in the begining ang in the subs method.
When you write solve(), it solves system of equations.

Lost with Sympy solving


Redirecionamento entre páginas com datatable(primefaces) sem perder os filtros

Question: Eu tenho 3 páginas e elas são responsáveis por buscar objetos em meus bancos de dados baseados no filtro de seleção da primeira página.
Meu site é sobre anúncios de carros e tem a seguinte estrutura:

1ª página: É responsável pelo filtro de seleção do usuário.
2ª página: É a página da datatable com os resultados do filtro da primeira página.
3ª página: É relacionado com os detalhes do carro

Eu usei @SessionScoped no meu projeto para ser capaz de fazer o que eu quero e "consegui" dessa forma, mas o problema é que quando eu estou na terceira, quarta, quinta página do datatable, ao clicar em uma linha de detalhes do anúncio e retornar para a página do datatable, em vez de ele retorna para a página que eu estava, ele retorna para a primeira não importa onde ela está. Ela sempre retorna para a primeira página...
Por causa disso, eu tentei mudar meu bean para usar @ViewScoped. Eu pensei que iria resolver o meu problema, mas quando eu volto a partir da terceira página do site para a segunda, a datatable perde os dados do filtro(por ser @ViewScoped).
Eu tenho usado o contexto Lazyload, mas acho que não importa para o caso.
Minha necessidade é que o usuário possa clicar em um anúncio e se ele quer voltar exatamente para a página que ele estava, ele consiga.
Answer: Já tive um problema similar mas não foi especificamente com o PrimeFaces.
Você pode criar um entidade para a view que contenha os filtros de tua pagina e/ou "sub-entidades", no Spring é conhecida como View Object. Como você cria o VO no teu controller, é só armazenar em tua sessão a tua entidade de filtros e recuperar quando necessitar.
Fica algo do estilo:
FiltrosVO filtros = new FiltrosVO();
/* ARMAZENA FILTROS */
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
session.setAttribute("FILTROS", this.filtros);
/* RECUPERA FILTROS */
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = (HttpSession) request.getSession();
filtros  = session.getAttribute("FILTROS");


VNC - full screen (Laptop viewer)

Question: I have a winXP laptop with vnc viewer installed.
I am connecting from the laptop to my other fedora machine.
In the viewer when I set to full screen it is not streched, meaning i need to scroll up and down to see the desktop boundries.
Changing the server resolution did not help, how can i make the viewer to be streched all over the lap top screen?
Thanks
Comment: Your question does not include enough specific details to give you very a very precise answer. Please include information such as what software you are using for the vnc viewer and server compnents. There are lots of different programs and they all have settings in different places.
Answer: Some VNC servers and viewers have a "scale" function that can change the output size. I know UltraVNC supports this for example. Also the Xvnc compnent you are probably using to export your fedora box supports scaling, but it is more difficult to setup on that end.

VNC - full screen (Laptop viewer)


Changing YYYYDDMM_rest_of_filename.xls to YYYYMMDD_rest_of_filename.xls in Ruby on Rails

Question: I have an enormous amount of excel files formatted as: YYYYDDMM_rest_of_filename.xls
How could I change them all using ruby in the less number of commands possible to YYYYMMDD_rest_of_filename.xls?
Answer: Just switch them:
str = "20103109_rest_of_filename.xls"

str[4,2], str[6,2] = str[6,2], str[4,2]
p str #=> "20100931_rest_of_filename.xls"

Answer: Go file by file and run a regexp on the filename capturing
the YYYY, DD, MM, _rest_of_filename groups.
Once you have the groups it's easily to concatenate strings
and rename the file with the rename function in the File class.
Answer: Using regular expressions:
file_name = '20113009_report.xls'
file_name.sub!(/(\d{4})(\d{2})(\d{2})(.+)/, '\1\3\2\4' )
p file_name  # "20110930_report.xls"


Weird 'Parameter not provided' error

Question: Ok, I have this simple stored procedure:
 CREATE PROCEDURE dbo.spLoadRFPIDs
    -- Add the parameters for the stored procedure here
    @ClientID VARCHAR(10),
    @BidYear VARCHAR(20)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    SELECT
        -- these are the property and Bid specifics.. the RFPID the Propcode etc..
        ID_RFP AS 'RFP ID',
        PropCode AS 'Property Code',
        Chain_Parent AS 'Parent Chain',
        PropName AS 'Property Name',
        PropAdd1 AS 'Property Address',
        --ALl the GDS Codes
        SabreCC AS 'Sabre CC',
        SabrePC AS 'Sabre PC',
        ApolloPC AS 'Apollo',
        AmadeusPC AS 'Amadeus',
        WorldspanPC AS 'Worldspan'

        --This is our preferred, company View
        FROM port_prfh_co prch

    WHERE
        prch.AcctCode = @ClientID -- We always use a clientid to identify which client we are using
        and prch.BidYear = @BidYear -- Each client has a BidYear all their Bids are associated with. some of our clients are still on the 2013 year and have not started 2014 yet.
        and prch.Accept_Status = 'Accept'
END

And in my code behind I'm calling it like so (simple like I said)
Public Function Load(ByVal client_id As String, ByVal year As String) As DataTable
    Using conn As New SqlConnection(SqlConn.GetConnectionString("ProLodgic"))
        Using cmd As New SqlCommand()
            With cmd
                .CommandType = CommandType.StoredProcedure
                .CommandText = "spLoadRFPIDs"
                .Parameters.AddWithValue("@ClientID", client_id)
                .Parameters.AddWithValue("@BidYear", year)
                .Connection = conn
            End With

            SqlConn.HandleConnection(conn, False)

            Using ad As New SqlDataAdapter(cmd)
                ad.SelectCommand = New SqlCommand(cmd.CommandText, conn)
                Dim table As New DataTable()
                Try

                    ad.Fill(table)
                    Return table
                Catch ex As Exception
                    ErrorMessage.Text = ex.Message
                    Return Nothing
                End Try
            End Using
        End Using
    End Using
End Function

Protected Sub RadGrid1_NeedDataSource(sender As Object, e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
    TryCast(sender, RadGrid).DataSource = Load("bloomberg", "2014")
End Sub

But when I load the page I get an error telling me that @ClientID wasn't supplied, but as you can clearly see I am supplying it, so what am I missing here?
Answer: You are assigning a new SqlCommand to the property SelectCommand of the SqlDataAdapter.
Of course this new SqlCommand has no parameters and no type StoredProcedure.
But the SqlCommand used in the constructor of the SqlDataAdapter is automatically assigned as the SelectCommand for the SqlDataAdapter
  Using ad As New SqlDataAdapter(cmd)
      ' just comment the following line '
      ' ad.SelectCommand = New SqlCommand(cmd.CommandText, conn) '

Comment: Thanks Steve, I knew I was done something stupid but couldn't see past my own eyes. Appreciate the fast reply :)

Weird 'Parameter not provided' error


Azure YAML Pipelines - Jobs/Tasks package issues

Question: So I've been doing some learning into Azure DevOps Yaml Pipelines and I've come across an issue I can't seem to figure out what would be the cause.
I was building my first pipeline for a small class library solution, the idea being to restore, build, test, pack & publish it when changes are committed into master.
I split the different parts of the deployment into stages/jobs (which may not be the correct way to use these), but when I do so, the "Nuget pack" step can never find any of the built files.
This YAML does not work, and errors out on the "NuGet (Pack)" Step because it cannot find the "projects.assets.json" file, which I have confirmed that the build step does produce.
trigger:
- master

pool:
  vmImage: 'windows-latest'

name: 'Set dynamically'

variables:
  buildConfiguration: 'Release'
  version.Major: 1
  version.Minor: $[counter(variables['version.Major'], 0)]
  version.Patch: 0
  version.Revision: $[counter(variables['version.Minor'], 0)]
  version.Number: '$(version.Major).$(version.Minor).$(version.Patch).$(version.Revision)'

stages:
- stage: Prepare
  jobs:
    - job: Prepare_Sources
      steps:
      - checkout: self
        clean: true

    - job: Prepare_BuildAndVersionNumbers
      steps:
      - task: PowerShell@2
        displayName: Set the name of the build
        inputs:
          targetType: 'inline'
          script: |
            [string] $dateTime = (Get-Date -Format 'yyyyMMdd')
            [string] $buildName = "$(Build.DefinitionName)_$(Build.SourceBranchName)_$($dateTime)_$(version.Number)"
            Write-Host "Setting the name of the build to '$buildName'."
            Write-Host "##vso[build.updatebuildnumber]$buildName"

- stage: Build
  jobs:
    - job: BuildRestore
      steps:
      - task: NuGetCommand@2
        displayName: 'Restore (NuGet)'
        inputs:
          command: restore
          restoreSolution: '**\*.sln'fs
          feedsToUse: select
          includeNuGetOrg: true
          vstsFeed: 'internalfeed1'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

      - task: DotNetCoreCLI@2
        displayName: 'Restore (.NET Core)'
        inputs:
          command: restore
          includeNuGetOrg: true
          nobuild: true
          vstsFeed: 'internalfeed1'
          nuGetFeedType: internal
          projects: '**/*.csproj'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

      - task: DotNetCoreCLI@2
        displayName: 'Build all projects in solution'
        inputs:
          command: build
          projects: '**/*.csproj'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

- stage: Test
  jobs:
    - job: Test_UnitTests
      steps:
      - task: DotNetCoreCLI@2
        displayName: 'Run & Analyse UnitTests'
        inputs:
          command: test
          projects: '**/*Tests/*UnitTests.csproj'
          arguments: '--configuration $(buildConfiguration) --collect "Code coverage"'

- stage: Package
  jobs:
    - job: Package_Nuget
      steps:
      - task: NuGetAuthenticate@0
        displayName: "Nuget (Authenticate)"

      - task: DotNetCoreCLI@2
        displayName: 'NuGet (Package)'
        inputs:
          nobuild: true
          command: pack
          packagesToPack: '**/*.csproj'
          versioningScheme: byBuildNumber
          arguments: '--configuration $(buildConfiguration)'

      - task: DotNetCoreCLI@2
        displayName: 'NuGet (Publish)'
        inputs:
          command: push
          searchPatternPush: '$(Build.ArtifactStagingDirectory)/*.nupkg;'
          feedPublish: 'internalfeed1'

If I simplify it all down into one single job without the stages/jobs the deployment all works ok (as below)
trigger:
- master

pool:
  vmImage: 'windows-latest'

name: 'Set dynamically'

variables:
  buildConfiguration: 'Release'
  version.Major: 1
  version.Minor: $[counter(variables['version.Major'], 0)]
  version.Patch: 0
  version.Revision: $[counter(variables['version.Minor'], 0)]
  version.Number: '$(version.Major).$(version.Minor).$(version.Patch).$(version.Revision)'

steps:
      - checkout: self
        clean: true

    - task: PowerShell@2
        displayName: Set the name of the build
        inputs:
          targetType: 'inline'
          script: |
            [string] $dateTime = (Get-Date -Format 'yyyyMMdd')
            [string] $buildName = "$(Build.DefinitionName)_$(Build.SourceBranchName)_$($dateTime)_$(version.Number)"
            Write-Host "Setting the name of the build to '$buildName'."
            Write-Host "##vso[build.updatebuildnumber]$buildName"

    - task: NuGetCommand@2
        displayName: 'Restore (NuGet)'
        inputs:
          command: restore
          restoreSolution: '**\*.sln'fs
          feedsToUse: select
          includeNuGetOrg: true
          vstsFeed: 'internalfeed1'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

    - task: DotNetCoreCLI@2
        displayName: 'Restore (.NET Core)'
        inputs:
          command: restore
          includeNuGetOrg: true
          nobuild: true
          vstsFeed: 'internalfeed1'
          nuGetFeedType: internal
          projects: '**/*.csproj'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

    - task: DotNetCoreCLI@2
        displayName: 'Build all projects in solution'
        inputs:
          command: build
          projects: '**/*.csproj'
          arguments: '--configuration $(buildConfiguration) /p:Version=$(version.Number)'

      - task: DotNetCoreCLI@2
        displayName: 'Run & Analyse UnitTests'
        inputs:
          command: test
          projects: '**/*Tests/*UnitTests.csproj'
          arguments: '--configuration $(buildConfiguration) --collect "Code coverage"'

      - task: DotNetCoreCLI@2
        displayName: 'NuGet (Package)'
        inputs:
          nobuild: true
          command: pack
          packagesToPack: '**/*.csproj'
          versioningScheme: byBuildNumber
          arguments: '--configuration $(buildConfiguration)'

      - task: DotNetCoreCLI@2
        displayName: 'NuGet (Publish)'
        inputs:
          command: push
          searchPatternPush: '$(Build.ArtifactStagingDirectory)/*.nupkg;'
          feedPublish: 'internalfeed1'

Can't find an answer on the documentation for these pieces of the puzzle that would explain why it wouldn't work when split up into stages/jobs, does anyone know what the reasoning is? Are Stages/Jobs not supposed to interact with each other in this way?
Thanks
Answer: This is becuase each job runs on different agent

A stage contains one or more jobs. Each job runs on an agent. A job represents an execution boundary of a set of steps. All of the steps run together on the same agent. For example, you might build two configurations - x86 and x64. In this case, you have one build stage and two jobs.

And this since jon is a boundary for set of steps source code is not shared amongs them. SO if you need keep this as seprate jobs and stages you should repeat in each job checkout step
      - checkout: self
        clean: true

Please read this basics about pipeline, they will give you high level picture how it works.
And if you want to share some artifact between jobs please take a look here.
And if you need share some variables between stages I wrote an article about this.
Comment: That would certainly explain thank-you for the information. I assumed it was some sort of scoping issue but couldn't find anything that explicitly defined it.

Ok so that's good to know, I assumed they were sort of the YAML way of doing task groups, but mis-read that part it looks like. Great info and links!

Happy to get rid of them, just trying to learn by doing! :)
Comment: Task group are for classic release pipelines. For YAML we have templates.


MySQL where's the my.cnf path?

Question: I've managed to locate my install directory for MySQL: /usr/local/mysql/
Where can I find the path to my.cnf to know where I should configure the server?  I've tried creating a /etc/my.cnf(as shown below) and it had no affect
[mysqld]

#charset
collation_server=utf8_general_ci
character_set_server=utf8
default_character_set=utf8

Comment: Specifics about the distro you are using would be helpful.
Comment: Pretty sure debian/*buntu/rhel/cent wouldn't be using /usr/local from a package install. That sounds more like slack or freebsd.
Answer: As per this article:
Running this command from the command line / terminal will show where MySQL will look for the my.cnf file on Linux/BSD/OS X systems:
mysql --help | grep "Default options" -A 1

This will output something like this:
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf

You can now check for files using the above output at /etc/my.cnf, then /etc/mysql/my.cnf and so on. If there isn't one at one of those locations, you can create one and know MySQL will use it.
Answer: On a Linux system 'locate my.cnf" will be the fastest solution.
If there are several my.cnf files, all looking likely (e.g. in /etc, /etc/mysql, /opt/mysql/etc, etc.), then you can run strace to see where MySQL binary tries to find its configuration file, but I do think that's an overkill.
Comment: I get `-bash: locate: command not found`... I've tried `find / my.cnf` but it finds nothing.
Comment: This assumes that your locatedb has been updated since the my.cnf file was create. Usually this is done daily via cron. If you need to update it manually run "updatedb" as root
Comment: `locate: command not found` is not an updatedb problem, he doesn't have the package.
Comment: install "slocate" package.
Answer: It seems like the file your cnf created is being superseded by another one. Check out hte default order below.
From

mysqld --verbose --help

Default options are read from the following files in the given order:
/etc/my.cnf ~/.my.cnf /etc/my.cnf
Answer: OK a wild shot in the dark:
If the database is installed in /usr/local/mysql, then try looking in /etc/local for my.cnf
Here is how you can tell if you have a my.cnf
Run this query (<= 5.6.7)
SELECT * FROM INFORMATION_SCHEMA.GLOBAL_VARIABLES
WHERE VARIABLE_NAME IN ('wait_timeout',
'innodb_buffer_pool_size','innodb_log_file_size');

OR (>= 5.6.8) it moved to the performance schema.
SELECT * FROM PERFORMANCE_SCHEMA.GLOBAL_VARIABLES
WHERE VARIABLE_NAME IN ('wait_timeout',
'innodb_buffer_pool_size','innodb_log_file_size');

SHOW GLOBAL VARIABLES LIKE 'wait_timeout';
SHOW GLOBAL VARIABLES LIKE 'innodb_buffer_pool_size';
SHOW GLOBAL VARIABLES LIKE 'innodb_log_file_size';

If you should get:

wait_timeout 28800
innodb_log_file_size

Default Value (>= 5.6.8) 50331648
Default Value (<= 5.6.7) 5242880

innodb_buffer_pool_size 134217728

You are running with defaults and there is a possibility that there may not be a my.cnf present.
NOTE:

As of MySQL 5.7.6, information available from the tables described here is also available from the Performance Schema. The INFORMATION_SCHEMA tables are deprecated in preference to the Performance Schema tables and will be removed in a future MySQL release. For advice on migrating away from the INFORMATION_SCHEMA tables to the Performance Schema tables, see Section 25.20, "Migrating to Performance Schema System and Status Variable Tables".
Comment: `-bash: updatedb: command not found`
Comment: Updated my answer. Please try again !!!
Comment: `/usr/bin/which: no updatedb in (/sbin:/usr/sbin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/X11R6/bin:/bin:/usr/games:/opt/gnome/bin:/opt/kde3/bin:/usr/lib/java/bin:/usr/local/apache2/bin:/usr/local/firefox:/usr/local/mysql/bin:/usr/games:/usr/local/fetter/bin)`
Answer: How did you install MySQL and on what platform?
Brute force method on an unixoid OS:
find / -name my.cnf -print

Comment: I didn't install it, it's on a machine that's a few years old.  It's on `Linux mars 2.6.5-7.147-bigsmp #1 SMP Thu Jan 27 09:19:29 UTC 2005 i686 i686 i386 GNU/Linux`
Answer: strace -fe open /etc/init.d/mysql start 2>&1|grep my.cnf should show you the system call used to open the file.
Answer: How are you sure that your cnf file is not being read?
Have you restarted mysqld since the change?
Have you tried to create a new db and looked at its values?
Answer: To install locate and updatedb to be able to run it..
Using fedora, centos run as root:
yum install mlocate

if you are running Ubuntu run:
sudo apt-get install mlocate

After you finish the install run updatedb
Fedora (as root):
$updatedb

Ubuntu:
sudo updatedb

then you can run the locate command as listed above. Again the my.cnf is typically located in /etc. Are you sure mysql is installed? if not do the commands above to install it and replace mlocate with mysqld best of luck!

MySQL where's the my.cnf path?


Upper bound for integral of two variables

Question: Is it true that if $f(x,y)$ and $g(x,y)$ are two positive real bounded functions in $\mathbb{R}^2$, then
$$
\int \int  dx \, dy \,  f(x,y) \, g(x,y) \leq \sup_{ \tilde y \in \mathbb{R}} \, \,  \int \int dx\,  dy \,  f(x,y) \,  g(x,\tilde y) \, \,
$$
assuming that the integral in the left hand side is finite? I am confused.
Comment: The right hand side doesn't make sense to me. Does it mean $\sup_{y' \in \Bbb R} \int_x \int_y f(x, y) g(x, y') ~dy ~dx$, so that the $y$ in $f(x, y)$ is a variable of integration, but the $y'$ in $g(x, y')$ is fixed? If so, the answer seems likely to be "no". {Also: double-checking: is $y'$ supposed to be in $\Bbb R$ or in $\Bbb R^2$, as you wrote? If it's the latter, I'm baffled.}
Comment: I edited the text, now it should make more sense. Thanks.
Comment: Did you look at my answer? I'd like to think that my time wasn't entirely wasted.
Answer: Big idea: these integrals, at least over a small domain, and for simple $f$ and $g$, are analogous to double-sums, which are easier to think about. If we look at
$$
\sum_{i=1}^n \sum_{j=1}^n f_{ij} g_{ij} \le \sup_k \sum_{i=1}^n \sum_{j=1}^n f_{ij} g_{ik},
$$
where $f$ and $g$ are now matrices, we can divide both sides by $n$ to get
$$
\frac{1}{n}\sum_{i=1}^n \sum_{j=1}^n f_{ij} g_{ij} \le \sup_k \frac{1}{n}\sum_{i=1}^n \sum_{j=1}^n f_{ij} g_{ik},
$$
We can now think about each matrix as made up of $n$ column vectors, $f_k$ and $g_k$. The left hand side (which I'll call $L$) then is the average of the pairwise dot-products:
$$
L = \frac{1}{n} \sum_j f_j \cdot g_j
$$
The right hand side (denoted $R$), on the other hand, can be reshuffled a little to become
\begin{align}
R
&= \sup_k \frac{1}{n}\sum_{i=1}^n \sum_{j=1}^n f_{ij} g_{ik}\\
&= \sup_k \frac{1}{n}\sum_{i=1}^n \bigl( \sum_{j=1}^n f_{ij} \bigr) g_{ik} \\
&= \sup_k \sum_{i=1}^n  \bigl( \frac{1}{n}\sum_{j=1}^n f_{ij} \bigr) g_{ik}\\
&= \sup_k \bar{f} \cdot g_k,
\end{align}
which is the biggest dot product between the average of the $f$ vectors, $\bar{f}$ and any column of $g$.
So the question becomes: is the average of $f_j \cdot g_j$ always less than the max (over $k$) of $\text{avg}(f_j) \cdot g_k$? And the answer to that is "no". We can see this in the $2 \times 2$ case. Let
$$
F = G = \pmatrix{0 & 2 \\ 2 & 0}
$$
(more generally, we can let $F$ be an $n \times n$ matrix of all $n$s, with $0$s on the diagonal, but I'll stick with $2 \times 2$ here). The average column of $F$ is then $\bar{f} = \pmatrix{1\\1}$. $L$ is $\frac{4 + 4}{2} = 4$. $R$ is ... well, $\bar{f} \cdot g_k$ is independent of $k$: it's just $2$. So $R = 2$. And we end up with $L > R$.
Now we have to turn this intuition into a function.
Restrict the domain to $D = [0, 2] \times [0, 2]$ by defining $f$ and $g$ to be zero outside $D$. Now we can write everything with finite integrals. I know; this makes $f$ and $g$ nonnegative rather than positive. I'll come back to that at the end.
Next, I'm going to make $f$ and $g$ piecewise constant on little squares (indeed, 1 x 1 squares). So now we can describe $f$ and $g$ via $2 \times 2$ matrices indicating the value in each little square. The value in the lower-left square $ 0 \le x, y \le 1$, for instance, will be the lower left entry of the matrix $F$ above, i.e., $2$; the value in the upper left square $0 \le x \le 1, 1 \le y \le 2$, will be the upper left entry of $F$, namely $0$, and so on.
Yes, this function is non-negative rather than positive. You may replace the $0$ in this case with $.000001$, and then work out the remaining details. It's not going to turn $2$ into something greater than $4$.
Now the integrals you need to compute are just $4$ times the sums I computed above, hence we end up with the left integral being larger than the right integral, and we're done.
To more properly extend $f$ and $g$ outside the square, define them via
$$
f(x, y) = \begin{cases}
\text{as above}   & 0 \le x, y \le 2 \\
\frac{C}{(x-1)^{100} (y-1)^{100}} & \text{otherwise}
\end{cases}
$$
By picking $C$ small, you can arrange for the integral of $f^2$ over the exterior of $D$ to be no larger than, say, $0.0001$, and the whole argument still holds.


Question on continuity of functions from $X\times X\rightarrow Y$

Question: I am stuck on the following problem, which I do not believe to be so difficult.
Let $X$ and $Y$ be Banach spaces. Let $f:X\times X\rightarrow Y$ be a function such that for any fixed $x_0$, $f(x,x_0)$ and $f(x_0,x)$ are continuous in $x$. Then is $f(x,x)$ continuous in $x$?
I tried taking an arbitrary convergent subsequence $\{x_n\}$ which converges to some $x$ and trying to argue that $f(x_n,x_n)$ converges to $f(x,x)$ using continuity in both terms, but I cannot seem to make this work for some reason.
Any help is greatly appreciated.
Answer: Let $X=Y:=\Bbb R$ and
$$f(x,y):=\begin{cases}\frac{xy}{x^2+y^2},&\mbox{if }(x,y)\neq (0,0);\\
0&\mbox{ if }(x,y)=(0,0).
\end{cases}$$
This function is continuous once a variable is fixed, but is not globally continuous.
Comment: In particular, $f(x,x)=0$ if $x$ is $0$, $f(x,x)=1/2$ otherwise.
Answer: Consider the function $f:\mathbb R\times \mathbb R\to \mathbb R$ given by $f(x,0)=f(0,x)=0$ for all $x\in \mathbb R$, and $f(x,y)=1$ if either $x$ or $y$ is irrational, and $f(x,y)=1/2$ otherwise.
Clearly, $f(x,0)$ and $f(0,x)$, being constantly $0$, are continuous. However, $f(x,x)$ is a Dirichlet function which is discontinuous. Note that the discontinuity is not removable.
Intuitively what is going on here is that there are infinitely many directions to consider in $\mathbb R \times \mathbb R$ and knowledge of the behaviour of the function along just two directions (along the axis) is not sufficient to determine it's behaviour with respect to the other infinity of directions.


HP drive array "ready for rebuild" (RAID5)

Question: We have a ProLiant server with Smart Array P440ar controller.
Since about three weeks the "don't remove" lights on some of the SAS drives are on. Perhaps after a power loss.
If we reboot it, it shows in the post screen:

Embedded RAID : Smart Array P440ar Controller - Configuration Required

1786-Slot 0 Drive Array Recovery Needed The following SAS/SATA drive(s)

need Automatic Data Recovery (Rebuild): Port 1I, box:6, bay: 4 (SAS)

The Smart Storage Administrator software shows the status "Ready for Rebuild" on our RAID5 Array. We have two arrays: A RAID1 with two disks (obviously) and a RAID5 with three disks. The error status is given for the RAID5.
It does not show errors on any specific drive, just on the array.
It's been like this for weeks. We tried to shut down the virtual servers for a week-end in order to give the server "rest" because I read somewhere that the rebuild might not start if there is too much load on the drives. However it also didn't start with the virtual servers shut down.
Here's the link to the ADU Report: http://strategyplayer.net/downloads/offtopic/ADUReport1.zip
My knowledge isn't good enough to read something useful form it.
Any help appreciated!
Answer: "Ready for rebuild" means that the rebuild process is blocked. If it's on the RAID5 array, you probably have run into a URE situation where you have a failed disk and a failing disk. The failing disk likely has read errors and can't be read from reliably to complete the reconstruction of the failed disk.
You should run a proper backup NOW, then try turning the hardware off (drives spin down) and powering up again. Watch the controller prompts and see if that jumpstarts the rebuild process.
Edit:
After reading the ADU report, two of the three 300GB disks have hard read errors. URE is the likely situation. Power loss alone wouldn't necessarily cause this. Is this system connected to a backup battery?
Comment: Thanks for your reply. So you say that two of the disks are failing now (apparently started failing at the same time)? So what can we do about it? As far as I understand we could just replace the failing disk if ONE disk in a RAID5 is failing. But what do we do if TWO are failing?
Comment: Take a backup while the systems are up. Do what I said... turn the system off. See if the drives begin to rebuild. If they don't you'll have to rebuild the array. There's no recovery option at that point.
Comment: We're taking a separate bare metal recovery backup right now. (We have a scheduled backup every night.) After this we will try powering down and powering up the device again. We already did it some days ago and got a prompt form the controller (I mentioned the prompt in the original question.)
May I ask for clarification about your definition of "rebuild" and "recovery" of the array? I've read quite a view conflicting definitions online (meaning: not anyone seems to mean the same thing with "rebuild") so I want to make sure that I understand your message correctly.


Ubuntu 14.04 apache won't load https on 443, iptables blocking 443?

Question: On an Ubuntu 14.04 server I'm trying to get https running to get SSL for a website (server will be replaced in couple of weeks). Website works fine on http, but can't get it running on https. Webbrowser gives an "Unable to connect" so I'm thinking iptables is blocking the connection. I'm somewhat familiar with ufw  but not with iptables.
When I do a iptables -L --line, I have the following output:
Chain INPUT (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
38300 2312K fail2ban-ssh  tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
  122  7916 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
    0     0 ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
37010 2251K ACCEPT     tcp  --  *      *       x.x.x.x              0.0.0.0/0            tcp dpt:22
 162K 6486K DROP       all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate INVALID
  11M 4302M ACCEPT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            ctstate RELATED,ESTABLISHED
50298 3001K ACCEPT     all  --  lo     *       0.0.0.0/0            0.0.0.0/0
 6998  431K ACCEPT     icmp --  *      *       0.0.0.0/0            0.0.0.0/0            icmptype 8
 106K   26M UDP        udp  --  *      *       0.0.0.0/0            0.0.0.0/0
1057K   53M TCP        tcp  --  *      *       0.0.0.0/0            0.0.0.0/0
 106K   26M REJECT     udp  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable
 194K 8099K REJECT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with tcp-reset
 5553  178K REJECT     all  --  *      *       0.0.0.0/0            0.0.0.0/0            reject-with icmp-proto-unreachable
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443 ctstate NEW,ESTABLISHED
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 80,443 ctstate NEW,ESTABLISHED
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443
    0     0 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:443

Chain FORWARD (policy DROP 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 18270 packets, 6985K bytes)
 pkts bytes target     prot opt in     out     source               destination
    2   120 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp spt:443 ctstate ESTABLISHED
  714 80354 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            multiport dports 80,443 ctstate ESTABLISHED

Chain TCP (1 references)
 pkts bytes target     prot opt in     out     source               destination
59249 3411K ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:80
 1200 64152 ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:3306
 498K   26M ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpts:49152:49200
 305K   15M ACCEPT     tcp  --  *      *       0.0.0.0/0            0.0.0.0/0            tcp dpt:21

Chain UDP (1 references)
 pkts bytes target     prot opt in     out     source               destination

Chain fail2ban-ssh (1 references)
 pkts bytes target     prot opt in     out     source               destination
38300 2312K RETURN     all  --  *      *       0.0.0.0/0            0.0.0.0/0

Some public IP addresses have been replaced with x.x.x.x.
Under Chain INPUT (policy DROP) rule #21-25 show https, but it's an ACCEPT in the policy DROP list. Does it mean the connection is dropped or allowed to pass through? There is no rule for http in this list.
Under Chain OUTPUT (policy ACCEPT) rule #1 shows https and #2 shows http and https. Looks like this is the accepting rule. However, if the previous one is the rule to drop the connection I'm assuming rule #1 doesn't get reached.
Under Chain TCP (1 references) rule #1 shows http, but no rule for https.
Do I need to delete the rules onder policy DROP? I've tried to add the rule with iptables -A INPUT -p tcp --dport 443 -j ACCEPT but I still can't connect.
Also in /etc/iptables/rules.v4 there is a rule for port 80 (-A TCP -p tcp -m tcp --dport 80 -j ACCEPT) but none for 443. Do I need to add it manually?
Update
Added requested information, replaced some domain names with example.com
Chain INPUT (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination
1    38723 2341K fail2ban-ssh  tcp  --  any    any     anywhere             anywhere             multiport dports ssh
2        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
3        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
4        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
5      122  7916 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
6        0     0 ACCEPT     tcp  --  any    any     x.x.x.x/26           anywhere             tcp dpt:ssh
7        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
8        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
9        0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
10       0     0 ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
11   37418 2278K ACCEPT     tcp  --  any    any     example.com          anywhere             tcp dpt:ssh
12    168K 6750K DROP       all  --  any    any     anywhere             anywhere             ctstate INVALID
13     12M 4492M ACCEPT     all  --  any    any     anywhere             anywhere             ctstate RELATED,ESTABLISHED
14   51339 3063K ACCEPT     all  --  lo     any     anywhere             anywhere
15    7249  445K ACCEPT     icmp --  any    any     anywhere             anywhere             icmp echo-request
16    108K   27M UDP        udp  --  any    any     anywhere             anywhere
17   1084K   54M TCP        tcp  --  any    any     anywhere             anywhere
18    108K   27M REJECT     udp  --  any    any     anywhere             anywhere             reject-with icmp-port-unreachable
19    201K 8383K REJECT     tcp  --  any    any     anywhere             anywhere             reject-with tcp-reset
20    5669  181K REJECT     all  --  any    any     anywhere             anywhere             reject-with icmp-proto-unreachable
21       0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:https
22       0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:https ctstate NEW,ESTABLISHED
23       0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             multiport dports http,https ctstate NEW,ESTABLISHED
24       0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:https
25       0     0 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:https

Chain FORWARD (policy DROP 0 packets, 0 bytes)
num   pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 381K packets, 210M bytes)
num   pkts bytes target     prot opt in     out     source               destination
1        2   120 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp spt:https ctstate ESTABLISHED
2      718 80790 ACCEPT     tcp  --  any    any     anywhere             anywhere             multiport dports http,https ctstate ESTABLISHED

Chain TCP (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1    60377 3478K ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:http
2     1202 64232 ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:mysql
3     510K   26M ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpts:49152:49200
4     311K   16M ACCEPT     tcp  --  any    any     anywhere             anywhere             tcp dpt:ftp

Chain UDP (1 references)
num   pkts bytes target     prot opt in     out     source               destination

Chain fail2ban-ssh (1 references)
num   pkts bytes target     prot opt in     out     source               destination
1    38723 2341K RETURN     all  --  any    any     anywhere             anywhere

ports.conf from apache:
Listen 80
Listen 443 http

I have to add http to the 443 port otherwise Apache won't start (based on this answer). This error then happens:
 AH02240: Server should be SSL-aware but has no certificate configured [Hint: SSLCertificateFile] ((null):0)

Host configuration:
<VirtualHost *:443>
        ServerName www.example.com

        #ServerAdmin firstname.lastname@example.com
        DocumentRoot /var/www/test

        ErrorLog /var/log/apache2/www.example.com-ssl-error.log
        CustomLog /var/log/apache2/www.example.com-ssl-access.log combined

        <Directory /var/www/test >
               Options Indexes FollowSymLinks
               AllowOverride All
               Order allow,deny
               allow from all
         </Directory>

         SSLEngine On
         SSLCertificateFile /etc/ssl/cert/www_example_com.crt
         SSLCertificateKeyFile /etc/ssl/cert/www_example_com_com.key
         SSLCertificateChainFile /etc/ssl/cert/www_example_com_com.ca-bundle
</VirtualHost>

There are no log entries for www.example.com-ssl*.log
Comment: perhaps "iptables -L -v --line-numbers" would provide something worthwile investigating.
Comment: Is your webserver even listening on Port 443? `Unable to connect` does not sound like a firewall issue.
Comment: It looks like you've "added" rules for https, but you should have inserted them before the reject lines.  That's where the line-numbers come in handy.  You can't move lines, you'll need to delete them or the rejects, and respectively insert or add them.
Comment: BTW, it's better to drop than to reject, to spite the bots.
Comment: That makes sense, the REJECT rules are the last ones that will be matched? And http is being accepted, because it's in the TCP group? Would it be better to add 443 also to the TCP group?
Comment: You could indeed add just one accept https rule to the TCP chain, and delete everything from the INPUT chain from line 18 onwards - since the default policy is DROP.  You'd better set the default policy for the TCP chain to DROP too.
Answer: All your iptables rules for the https port are below 3 REJECT rules for UDP, TCP and ALL, so they match your https traffic and reject the connection.
Move the https rules above those (inserting them at least at the 18th position) or move the REJECT rules below the https ones.
NOTE: if  Gerard H. Pille creates a similar answer as me, please, give him the credit.
EDIT:
To clean all that up:
this would add the https port to the already defined http port on the TCP group:
iptables -R TCP 1 -p tcp -m multiport --dports 80,443 -j ACCEPT

this would delete all the unnecesary rules you appended into the INPUT chain (order of commands is important):
iptables -D INPUT 25
iptables -D INPUT 24
iptables -D INPUT 23
iptables -D INPUT 22
iptables -D INPUT 21

OUTPUT chain does not need any of those rules since it has a default policy of ACCEPT (ssh works and you do not have any OUTPUT rule for ssh, do you?), so you could delete both of them safely:
iptables -D OUTPUT 2
iptables -D OUTPUT 1

Comment: I won't do that, first come, first served.  Besides, you're more in need of credits than I am ;-)
Answer: ports.conf should be
Listen 0.0.0.0:80
Listen 0.0.0.0:443 https

but it is not necessary to define those ports at all in the ports.conf because:

You only need to set the protocol if you are running on non-standard ports. For example, running an https site on port 8443

https://httpd.apache.org/docs/2.4/bind.html#protocol


Re-expressing matrices in another form.

Question: How do I go about writing
$(a x_0+by_0)\begin{bmatrix}q\\r\end{bmatrix} e$λ1t + $(cx_0+dy_0)\begin{bmatrix}s\\t\end{bmatrix}$eλ2t
in the form
$\begin{bmatrix} w&x\\ y&z \end{bmatrix}\begin{bmatrix}x_0\\y_0\end{bmatrix}$
Where a,b,c,d,q,r,s,t,λ1,λ2 ∈ $\mathbb{Z}$.
Answer: $w = aqe^{{\lambda_1}t} + cse^{{\lambda_2}t}$
$x = bqe^{{\lambda_1}t} + dse^{{\lambda_2}t}$
$y = are^{{\lambda_1}t} + cte^{{\lambda_2}t}$
$z = bre^{{\lambda_1}t} + dte^{{\lambda_2}t}$
EDIT:
To see why:
$(a x_0+by_0)\begin{bmatrix}q\\r\end{bmatrix} e^{\lambda_1t} + (cx_0+dy_0)\begin{bmatrix}s\\t\end{bmatrix}e^{\lambda_2t}$
$= [a\ b]\begin{bmatrix}x_0\\y_0\end{bmatrix}\begin{bmatrix}q\\r\end{bmatrix} e^{\lambda_1t}
+ [c\ d]\begin{bmatrix}x_0\\y_0\end{bmatrix}\begin{bmatrix}s\\t\end{bmatrix} e^{\lambda_1t}$
$= e^{\lambda_1t}\begin{bmatrix}q\\r\end{bmatrix}
[a\ b]\begin{bmatrix}x_0\\y_0\end{bmatrix}
+ e^{\lambda_2t}\begin{bmatrix}s\\t\end{bmatrix}
[c\ d]\begin{bmatrix}x_0\\y_0\end{bmatrix}$
 (this step works because $[a\ b]\begin{bmatrix}x_0\\y_0\end{bmatrix}$ for example is just a simple number)
$= (e^{\lambda_1t}\begin{bmatrix}q\\r\end{bmatrix}[a\ b] + e^{\lambda_2t}\begin{bmatrix}s\\t\end{bmatrix}[c\ d])\begin{bmatrix}x_0\\y_0\end{bmatrix}$
So the matrix $\begin{bmatrix} w&x\\ y&z \end{bmatrix}$ you want is basically just $(e^{\lambda_1t}\begin{bmatrix}q\\r\end{bmatrix}[a\ b] + e^{\lambda_2t}\begin{bmatrix}s\\t\end{bmatrix}[c\ d])$.
Answer: Let $c_1=e^{\lambda_1 t}$ and $c_2=e^\lambda_2 t$.
Write
$$\eqalign{
(a x_0+by_0)\begin{bmatrix}q\\r\end{bmatrix} c_1 +  (cx_0+dy_0)\begin{bmatrix}s\\t\end{bmatrix} c_2
&=
\begin{bmatrix}q(a x_0+by_0)c_1\\r(a x_0+by_0)c_1\end{bmatrix}
+ \begin{bmatrix}s(cx_0+dy_0)c_2\\t(cx_0+dy_0)c_2\end{bmatrix} \cr
&=\left[\matrix{ q(a x_0+by_0)c_1 +  s(cx_0+dy_0)c_2\cr
  r(a x_0+by_0)c_1+ t(cx_0+dy_0)c_2 } \right]\cr
&=   \left[\matrix{ (qa c_1 +scc_2)x_0    + (qbc_1+sdc_2)y_0  \cr
  (rac_1 +tcc_2)x_0+ (rbc_1+tdc_2)y_0 } \right]\cr  \cr
&=    \left[\matrix{ qa c_1 +scc_2   &    qbc_1+sdc_2  \cr
   rac_1 +tcc_2&  rbc_1+tdc_2  } \right]
\left[\matrix{x_0\cr y_0}\right].
\cr
 }
$$

Re-expressing matrices in another form.


What is urgency when referring to music

Question: I've heard commentators call certain songs and artists  "urgent" or say the phrase "he plays with such urgency" I have no idea what this describes.
Answer: "To play with urgency" is related to tempo, or time.
It describes music being a little prime on each beat, producing a feeling of urgency, of a fast driving movement. It could be a tempo indication by the composer, or a band being a bit stressed out, or an artist always producing fast-paced songs.

What is urgency when referring to music


Dynamic Scraping in R: Webpages that require user to scroll to load more information

Question: I am trying to write a a single RScript that will scrape college ranking information from https://www.usnews.com/best-colleges/rankings/regional-universities-north. This site requires scrolling down to load more college information.
My hope is to do this without the use of docker or an outside program that requires command line prompts. From my attempts, it seems that RSelenium is defunct as well.
Comment: Please, could you provide your code?
Answer: Here is a partial answer,
<code>library(RSelenium)
driver <- rsDriver(browser=c("firefox"))
remDr <- driver$client

remDr$navigate("https://www.usnews.com/best-colleges/rankings/regional-universities-north")
# Name of the college
remDr$findElement(using = "xpath",'//*[@id="school-0"]/div/div[1]/div[1]/div[1]/h3') -> collegename
collegename$getElementText()
#Rank of the college
remDr$findElement(using = "xpath",'//*[@id="school-0"]/div/div[1]/div[1]/div[2]/ul/li/a/div') -> rankcollege
rankcollege$getElementText()
</code>
This gives you college name and rank.
But to get rank for all colleges you have to loop. To scroll down the page refer, Scrolling page in RSelenium


How to apply patches on Pantheon?

Question: This is specifically a question about Pantheon best-practice workflow, which I'm new to.
I run from a Win7 machine and do not have a full dev environment set up locally: it's just too much hassle to get Windows to play usefully and smoothly as a dev space behind my hosted *nix worlds. So, I am in the habit of developing online.
With Pantheon there is no shell access, but there is git and drush.
I don't use git because the workflow there asssumes that I want to move something off of my local repository up to Pantheon (eg, if I have a local working environment I would apply the patch, then push the patched code to my Pantheon dev), but this is not my usecase.
Using drush seems like an option, but I can't figure out how/if applying a patch is supported.
So...
How to patch a contrib module on Pantheon given no local dev environment?
Answer: I'm not sure what you mean by moving something off of your local, but I really think your best bet is to use git and push the patch up, even if you don't have a local environment set up. You don't need a local server or database running, you're just altering code in the repo.

clone Pantheon dev environment locally
patch -p1 < name_of.patch
commit and push

You could edit the files manually using the SFTP mode, but I wouldn't recommend that.
Using Git with Pantheon
Comment: @boabjohn Yes, git will only send the diff back up again, you're not pushing the whole repo around every time you push
Comment: Alright, I made a new screencast with audio updated in the answer, let me know if it helps.
Comment: Hey there Kyle, Thanks for the clue but I'm not sure what you mean. I have git on my local machine, so there is a repository, yes. I could clone the Pantheon dev which would suck everything down locally. But then how do I run the command line at your step 2? Without a local environment running, what tool is letting me navigate to a module and apply a patch? And lastly, isn't this method requiring me to bring the entire dev site local simply to patch one module? And then push it all back? Is there some clever diff business going on to ensure we're only moving the changed code?
Comment: I went ahead and made a screencast on how to use git/patch with Pantheon. I used the GitHub client because it's universal for Mac and Windows so you can try it out. Just like @Clive said, it's just pushing pieces.

Uhh... just realized I didn't record audio. Whoops. :)
Comment: Hey guys this sounds (or will sound?) great: I've just freshened up my local git set up and am cloning the site now. So I'll be ready for your tutorial soon!
Comment: Thanks fabulously @KyleTaylored: very helpful and clear explanation. Kind regards from the land of Oz!

How to apply patches on Pantheon?


Figuring out the difference between major and relative minor scales

Question: We know that the  notes as well as the chords in a major scale and its relative minor scale are the same.So, how does soloing in a major scale differ from soloing in its relative minor scale?
Answer: The only difference in a major scale and its relative minor, is the tonic center.
When you solo on C major scale, you play with the C as your tonic. If you change that, to A (with the A natural minor scale), you will focus on another note and the whole outcome will sound different.
Another way to see what difference the change in the tonic makes are modes. Take the C major scale (ionian mode) and play it. Then play all the other modes (dorian, phrygian etc) which consist of the same exact notes, but each one starts off at a different note, and the outcome is different. It gives a different feel every time.
Comment: There is no real harmonic gravity with the natural minor scale. You will need the leading-tone from the harmonic minor to establish the tonic-dominant relationship.
Answer: Regarding: "Figuring out the difference between major and relative minor scales" (and more).
If you know the C Major scale, and the relative minor, A minor, then you know the scales of two of the modes, C Ionian, and A Aeolian.  You should know you can play scales with all of the other modes, too and they all sound different, but all are from a Major scale.  Here's the rest of the story.
A, Aeolian, the relative minor of C Major is the sixth degree of the C Major scale.  When you name it, it is called A Aeolian.  If you compare it to the A Major scale which has F#, C# and G#, this scale has a flat 3, flat 6 and flat 7.  Thus the sharps in A Major are flattened when the scale is played in C Major. It also sounds totally different from when you start the scale with C.
Each of the modes has it's own signature.  As mentioned, in C Major the scales are  I, C Ionian, ii, D Dorian, iii, E Phrygian, IV, F Lydian, V7, G Mixolydian, vi, A Aeolian, and vii b 5, B Locrian.
In C Major the Ionian beginning on C, has no sharps or flats.  ii, Dorian has a flat three and flat 7, iii, Phrygian has flat 2, flat 3, flat 6 and flat 7,  IV, Lydian has a sharp 4, V7, Myxolydian has a flat 7, vi, Aeolian has flat 3, flat 6, flat 7 and vii, Locrian has flat 2, flat 3, flat 5, flat 6, flat 7.
This goes beyond what you asked for, but, I included it for perspective as I think you have to take into account all the modes when your refer to the relative minor.  So, that's the broader picture of how the relative minor fits in to the scheme.  You can't leave the other modes out and appreciate how the relative minor fits in.  These concepts apply to all the Major scales. Modes are not some dusty old concept.  Musicians apply these scalesa when playing.


Passar resultado do SQL para JSON

Question: Olá, Quero passar o resultado de um select para json, mas não consigo verificar o porque não consigo visualizar o mesmo.
Portanto alguém saberia me dizer porque este código não imprime nada?

include_once 'conexao.php';

$query = "SELECT client_id, name, email FROM client";
$result = $dbcon->query($query);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
}

echo json_encode($rows);

Resultado do var_dump($rows):
array(8) {
    [0]=> array(3) {
        ["client_id"]=> string(1) "1"
        ["name"]=> string(26) "Fernanda Neri Duarte Silva"
        ["email"]=> string(18) "firstname.lastname@example.com"
    }
    [1]=> array(3) {
        ["client_id"]=> string(1) "2"
        ["name"]=> string(36) "Elaine Cristina Gon�alves Durvalino "
        ["email"]=> string(16) "firstname.lastname@example.com"
    }

Comment: Isso é uma resposta de requisição ajax?
Answer: Tente alterar o conteúdo do seu while para o seguinte:
while($row = mysqli_fetch_assoc($result)) {
  $vclientid = $row['client_id'];
  $vname = $row['name'];
  $vemail = $row['email'];

  $rows['client'][] = array('client_id' => $vclientid, 'name' => $vname, 'email' => $vemail);
}

Answer: Tente fazer assim:
$array[0] =  array('jujuba', 'bola', 'cachorro');
$array[1] =  array('carro', 'da like', 'em mim o/');

echo "
";
var_dump($array);

var_dump(json_encode($array, JSON_FORCE_OBJECT));

Adicione o parâmetro JSON_FORCE_OBJECT
Comparando resultados:
// Sem JSON_FORCE_OBJECT
string(63) "[["jujuba","bola","cachorro"],["carro","da like","em mim o\/"]]"

// com JSON_FORCE_OBJECT
string(95) "{"0":{"0":"jujuba","1":"bola","2":"cachorro"},"1":{"0":"carro","1":"da like","2":"em mim o\/"}}"

Fiz uma classe (ainda to aprimorando) que faz debug se, quiser da uma olhada
www.bulfaitelo.com.br/2016/11/debugar-variaveis-e-classes-com-o.html
Answer: Encontrei a resposta. O problema eram os acentos. Tive que codificar para UTF-8 para conseguir resolver.
A resolução foi até um pouco simples. Veja:
**

$query = "SELECT client_id, name, email FROM `client`";
$result = $dbcon->query($query);
$myArray = array();
while($fetch = $result->fetch_assoc()) {
    $myArray[] = array("client_id" => utf8_encode($fetch['client_id']), "name" => utf8_encode($fetch['name']), "email" => utf8_encode($fetch['email']));
}

$json = json_encode($myArray);
echo $json;**

Comment: Marque como resposta certa quando der.
Comment: Pode deixar! =)

Passar resultado do SQL para JSON