EnsureUser not returning valid User

Question: I am trying to get a user back in SharePoint Client OM using EnsureUser. My code is:
ClientContext clientContext = new ClientContext(siteUrl);
User spUser = clientContext.Web.EnsureUser(user);

Where siteUrl and user are both strings set as appropriate.
The result is spUser is the shell of a User object but all its properties (for example Email, Title, etc.) are not initialized. In VS they are showing {"The property or field has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested."}
What would be causing this? I thought EnsureUser would create the user if it is not already there. I know in Server OM sometimes you need to use "AllowUnsafeUpdates", is there something like that for Client OM?
Comment: Did you intend to use `clientContext.Web.EnsureUser(user)` ?
Comment: Yeah that was just a copying error, I meant to use clientContext.Web.EnsureUser
Answer: It is almost a year late, but just in case someone else is searching for the same answer.
After getting a reference to the user object you need to do the following before accessing the properties of the user.
clientContext.Load(spUser);
clientContext.ExecuteQuery();

or if you want to get the email and title only to reduce the pay load.
clientContext.Load(spUser, u => u.Email, u => u.Title);
clientContext.ExecuteQuery();

Basically, it establishs a request to the SharePoint Web and ask for the properties of the spUser. The request will be send when ExecuteQuery() is called.

EnsureUser not returning valid User


Find same data in two DataFrames of different shapes

Question: I have two Pandas DataFrames that I would like to compare. For example
    a    b    c
A   na   na  na
B   na   1    1
C   na   1    na

and
    a    b    c
A   1    na   1
B   na   na   na
C   na   1    na
D   na   1    na

I want to find the index-column coordinates for any values that are shared, in this case
    b
C   1

Is this possible?
Answer: If you pass the keys parameter to concat, the columns of the resulting dataframe will be comprised of a multi-index which keeps track of the original dataframes:
In [1]: c=pd.concat([df,df2],axis=1,keys=['df1','df2'])
        c

Out[1]:
   df1           df2
     a    b    c   a   b   c
A   na   na   na   1  na   1
B   na    1    1  na  na  na
C   na    1   na  na   1  na
D  NaN  NaN  NaN  na   1  na

Since the underlying arrays now have the same shape, you can now use == to broadcast your comparison and use this as a mask to return all matching values:
In [171]: m=c.df1[c.df1==c.df2];m
Out[171]:
    a   b   c
A NaN NaN NaN
B NaN NaN NaN
C NaN   1 NaN
D NaN NaN NaN

If your 'na' value are actually zeros, you could use a sparse matrix to reduce this to the coordinates of the matching values (you'll lose your index and column names though):
import scipy.sparse as sp
print(sp.coo_matrix(m.where(m.notnull(),0)))
  (2, 1)    1.0

Comment: Very nice answer, but I think you need `any` instead of `all` there. Also, the OP will still need to find the column that matches.
Comment: Great answer
Comment: @lev you're right, I misunderstood the his question, I've edited my answer
Answer: If you just want the indices that are different, you can do: different_indices = [(i,j) for i in range(len((df1 != df2).columns)) for j in range(len(df1 != df2)) if (df1 != df2)[i][j]]
Or, slightly more readable:
m = (df1 != df2)
different_indices = [(i,j) for i in range(len(m.columns)) for j in range(len(m)) if m[i][j]]


Asynchonous subtasks in Celery Python

Question: i need async call subtasks in celery to another worker (on another machine) like this:
<code>#db.py
@task()
def query(x,y):
   ...something
   return z

#worker2.py
@task()
def main(x,y):
   result=db.query.async((x,y), queue='db')
   try:
       a=result.get(timeout=5)
   except celery.exceptions.TimeoutError:
       ....
</code>
But i get warning when starting worker:
RuntimeWarning: Never call result.get() within a task!
How can i call async tasks from another task? I wont'n use chain, chord etc.
Comment: The correct approach is to use chain. Why can't you use it?
Comment: I tried chain now:
    res = chain(db.query.s(x, y))()
    print(res.get())
and i get ** Never call result.get() within a task!** again :(
Comment: Same question here. Celery plays nice with fixed scenarios where you know from the start what will be executed, but when the scenario is dynamic I've got this issue & it blocks a worker
Answer: You never want to block one task to wait for another, so the correct approach is to use chain:
<code>db.py
@task()
def query(x, y):
   ...something
   return z

#worker2.py
@task()
def main(resultFromQuery, x, y):
   a = resultFromQuery.get(timeout=5)
   ...

res = chain(query.s(x,y), main.s(x,y));
res.get()
</code>
Comment: but i need call subtask from another task. Not from Main program.
This is system where i don't kwow exact workflow of at the begin :(
Comment: then don't call `result.get()` - do you need the result of the second task ?

Asynchonous subtasks in Celery Python


Excel vba: Salvando dados de uma planilha no formato .txt

Question: Boa tarde. Tenho a macro abaixo e ela já faz quase o que eu quero (cria um arquivo txt com os dados da planilha Historico, sempre reescrevendo o arquivo, ou seja, não cria varias copias), porém essa planilha Historico, contem nomes de times de futebol e ao encontrar nomes estranhos tipo: "Śląsk Wrocław , Górnik Łęczna , Wisła Płock" a macro trava e aparece a mensagem: Erro em tempo de execução '5': Argumento ou chamada de procedimento inválida
Option Explicit
Sub CrearTXT()
'tem que ativar a referência => Microsoft Scripting Runtime

Dim NombreArchivo, RutaArchivo As String
Dim obj As FileSystemObject
Dim tx As Scripting.TextStream
Dim Ht As Worksheet
Dim i, j, nFilas, nColumnas As Integer

NombreArchivo = "Batch"
RutaArchivo = ActiveWorkbook.Path & "\" & NombreArchivo & ".txt"

Set Ht = Worksheets("Historico")
Set obj = New FileSystemObject
Set tx = obj.CreateTextFile(RutaArchivo)

nColumnas = Ht.Range("A1", Ht.Range("A1").End(xlToRight)).Cells.Count
nFilas = Ht.Range("A2", Ht.Range("A2").End(xlDown)).Cells.Count

For i = 1 To nFilas

    If Ht.Cells(i + 1, 4).Value <> "" Then

    For j = 1 To nColumnas
        tx.write Ht.Cells(i + 1, j).Value  'É nesta parte onde a macro trava
        If j < nColumnas Then tx.write "|"
    Next j

    tx.writeLine

    End If

Next i

End Sub
Comment: Veja [este site](https://ozh.github.io/ascii-tables/)
Comment: E [esta resposta](https://pt.stackoverflow.com/a/286876/75104) tem uma parte de salvar em arquivo txt com codificação UTF-8, com esta codificação estes erros irão desaparecer.
Answer: Se você não se importar que esses nomes não entrem em seu txt você pode simplesmente adicionar no inicio do código:
On Error Resume Next

Se o caso não for esse, tente rever o método que esta usando para escrever no txt, eu uso geralmente
Print #1, "Texto qualquer"

Podemos conversar mais, qualquer coisa.
Comment: Bom dia Leandro. Esse nomes tem que entra, pois são os nomes dos times. como eu "encaixaria" o código: Print #1, "Texto qualquer" no código que já tenho? esse código acima esta no ponto que quero, apenas com essa falha em relação a letras de outro alfabetos


Optimize MySQL query using range and group by on large table

Question: My table structure:
CREATE TABLE `jobs_view_stats` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `job_id` int(11) NOT NULL,
  `created_at` datetime NOT NULL,
  `account_id` int(11) DEFAULT NULL,
  `country` varchar(2) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_D05BC6799FDS15210` (`job_id`),
  KEY `FK_YTGBC67994591257` (`account_id`),
  KEY `jobs_view_stats_created_at_id_index` (`created_at`,`id`),
  CONSTRAINT `FK_YTGBC67994591257` FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE SET NULL,
  CONSTRAINT `job_views_jobs_id_fk` FOREIGN KEY (`job_id`) REFERENCES `jobs` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=79976587 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='New jobs views system'

This is the query:
SELECT COUNT(id) as view, job_id
from jobs_view_stats
WHERE jobs_view_stats.created_at between '2022-11-01 00:00:00' AND '2022-11-30 23:59:59'
GROUP BY jobs_view_stats.job_id

Execution plan:

id
select_type
table
partitions
type
possible_keys
key
key_len
ref
rows
filtered
Extra

1
SIMPLE
jobs_view_stats
null
range
IDX_D05BC6799FDS15210,jobs_view_stats_created_at_id_index
jobs_view_stats_created_at_id_index
5
null
1584610
100
Using index condition; Using MRR; Using temporary; Using filesort

This query takes 4m to complete I want to reduce it to take minimum time.
Comment: you can create [partitions](https://dev.mysql.com/doc/refman/8.0/en/partitioning-types.html) by `YEAR_MONTH`.
Comment: Try a compound index on `(created_at, job_id)` or `(job_id, created_at)`. An index on `(created_at, id)` is probably unnecessary, there aren't many instances where you want to search by both a time range *and* an ID; index only `created_at`.
Comment: @Schwern Still searching from `1603308` rows. taking more than 4 min.
Comment: Have you tried running the query on the table without the jobs_view_stats_created_at_id_index index? It could just scan the whole table (how many rows are on it?), but this index is making it do it a funny way. It might be faster without that index though you need to know if anything else on your system requires it. You could maybe try dropping the index, running your query, then adding it again. I don't know how long it would take to rebuild the index on a table of this size (probably minutes?). At least then you would know why it is so slow.
Comment: @SimonGoater After removing the index rows are  25774075 and the total rows are 28384645. It takes 5m 54s
Comment: I see, so that didn't help. It might have been faster if there were fewer rows not selected by the query. You could try giving mysql more memory to play with in the config file or put your tables on fast(er) SSDs. Other than that, you could change your application to maintain the count somewhere so you can just select it rather than having to scan such a lot of data.
Comment: @SimonGoater The issue is due to this `job_views_jobs_id_fk` index. When I tried after removing this index `job_views_jobs_id_fk` and creating an index on `created_at, job_id`. Query working fine
Answer: In your execution plan, you are returning 1584610 rows that are then grouped by, which in turn uses a temp table to sort through and group (slow).
jobs_view_stats_created_at_id_index contains also 'id' which will make the key cardinality excessively large, could try instead adding job_id to the key as that is what you are grouping by.
I think the main issue is your where clause returns over 1.5 million rows that have to all load into a temp table to then be re-read in full to be grouped by.
You need to bite off smaller chunks i think.
I'm going to assume you are using a programming lang to envoke the DB calls (like PHP), if so you could try
SELECT DISTINCT job_id
from jobs_view_stats
WHERE jobs_view_stats.created_at between '2022-11-01 00:00:00' AND '2022-11-30 23:59:59'

then when you have the job_id list
do smaller queries looping over the results from the first
SELECT count(*) FROM jobs_view_stats where job_id = *theid*

or if there are many different job_id's batch them
SELECT count(*) FROM jobs_view_stats where job_id IN('id1', id2, id3....)

for a pure MySQL resolution, I would create a temp memory table of all the job_ids as a memory table using
CREATE TEMPORARY TABLE `temptable`
(
 job_id INT PRIMARY KEY
) ENGINE=MEMORY

INSERT INTO 'temptable' SELECT DISTINCT job_id
 from jobs_view_stats
 WHERE jobs_view_stats.created_at between '2022-11-01 00:00:00' AND '2022-11-30 23:59:59'

Then
SELECT count(*) as view, job_id FROM jobs_view_stats where job_id = (SELECT job_id FROM `temptable`)

this is all totally untested so might be typos.
Answer: Change COUNT(id) to COUNT(*) since it does not need to check id for being NOT NULL
Add
INDEX(job_id, created_at)
INDEX(created_at, job_id)

Either of those will be "covering".  (I don't know which is better; the Optimizer will know.)
Drop the index (job_id), as being redundant.
Unless you specifically need (created_id, id), drop it.
For even more performance, build and maintain a Summary Table .  Then perform the query against it.  Such a summary table might have PRIMARY KEY(job_id, created_date) and daily counts for each day for each job.


The import org.springframework.web.bind.annotation.CrossOrigin cannot be resolved

Question: Não estou conseguindo importar a annotation @CrossOrigin. A ide não encontra o pacote necessário apesar de todas as outras annotations estarem funcionando normalmente. O erro que ocorre é esse:

The import org.springframework.web.bind.annotation.CrossOrigin cannot be resolved

Está faltando alguma dependência no meu maven?
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>${springframework.version}</version>
    </dependency>
    <dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId>cors-filter</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>com.thetransactioncompany</groupId>
        <artifactId>java-property-utils</artifactId>
        <version>1.10</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.5.1.RELEASE</version>
    </dependency>
<springframework.version>4.0.6.RELEASE</springframework.version>

Comment: Bem-vindo ao StackOverflow **em português**. Tal como o nome sugere, o idioma oficial usado aqui é o português. Assim sendo, você poderia por favor traduzir sua pergunta? Caso prefira, você também pode fazer essa mesma pergunta no [site em inglês do StackOverflow](http://stackoverflow.com/questions/ask).
Answer: A anotação @CrossOrigin foi adicionada ao Spring na versão 4.2 e você está usando a versão 4.0.6.RELEASE. Mude sua versão para a mais recente do Spring 4.3.6.RELEASE e Isso resolverá o problema.
Além disso, como você está usando o Spring Boot, as seguintes dependências não precisam ser declaradas no seu pom.xml já que elas são dependências do próprio Spring Boot:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${springframework.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${springframework.version}</version>
</dependency>


How do I make the default content View filterable by multiple content types?

Question: Below is a clip from the content list admin page in Drupal 9, showing the Content type field drop-list, allowing admin users to filter the content list by content type.
Is there any way to alter this form to allow the list to be filtered by more than one content type at once? ie turn the content type drop-list into a multi-select field or checkboxes?
Answer: Yes. This admin page is a Drupal View. Go to /admin/structure/views/view/content. Under Filter Criteria, click Content: Content type (exposed) and check the box that says Allow multiple selections. Save the setting then save the View.
Comment: Thank you for the answer. Accepted.


hashing issue. How to use hazelcast map/multimap with byte arrays keys and values?

Question: I'm trying to use hazelcast multimaps and maps with already-serialized data, i.e. with both keys and values being byte arrays. As demonstrated below, it does not work as expected.
In the javadoc it is noted in the "gotchas" section that the hashing is handled by hazelcast on the serialized form and does not rely on implementations of hashCode and equals (which are not overriden in case of byte arrays). So, I don't understand why apparently, Object.hashcode is used.
Could please somebody tell me how to use hazelcast maps with byte arrays?
Am I obliged to store byte array wrappers with adequately overridden hashcode/equal methods?
thanks for any help.
Problem:
 scala> val mm:MultiMap[Array[Byte], Array[Byte]] = hi.getMultiMap("test-baMuMa")
 mm: com.hazelcast.core.MultiMap[Array[Byte],Array[Byte]] = MultiMap [test-baMuMa]

 scala> mm.put("a".getBytes,"b".getBytes)
 res29: Boolean = true

 scala> mm.put("a".getBytes,"b".getBytes)
 res30: Boolean = true
 // => should return false..

 scala> mm.remove("a".getBytes,"b".getBytes)
 res31: Boolean = false
 // =>  should return true

 scala> mm.containsEntry("a".getBytes,"b".getBytes)
 res32: Boolean = false
 // =>  should return true (confirmed that removal did not occur)

Answer: I answer my own question here, because I think in the hazelcast documentation is not as clearly stated as it could be:

key objets don't need to override equals/hashcode
value objets need to override equals/hashcode

This can be seen by this simple test:
object TestHazel{

  class Klaus(a:Int) extends Serializable
  // class does not override equals/hashcode

  def main (args:Array[Byte]){
    import com.hazelcast.core._
    val hi = Hazelcast.newHazelcastInstance
    val map = hi.getMap[Klaus, Klaus]("asdf")
    val klaus1 = new Klaus(1)
    map.put(klaus1, klaus1)
    val containsKey = map.containsKey(new Klaus(1))
    println("\n\ncheck if key overrides equals/hashcode: " + containsKey)
    // true

    val containsValue = map.containsValue(new Klaus(1))
    println("\n\ncheck if value overrides equals/hashcode: " + containsValue + "\n\n")
    // false

    hi.shutdown
 }
}

So, in my case, for byte array values, a wrapper is required that overrides equals and hashcode. Unfortunately, value classes scala >= 2.10 cannot be used with classes overriding equals/hashcode, so we cannot avoid the boxing :-(
Furthermore, if you want to index with order, the wrapper has to be a comparable.
Here is a sensible implementation of such a wrapper:
class BAWrapper2(ba:Array[Byte], comparator:Comparator[Array[Byte]])
    extends Serializable with Comparable[BAWrapper2]
{
  def data: Array[Byte] = if (ba == null) Array.empty[Byte] else ba
  def equals(other:BAWrapper2):Boolean = util.Arrays.equals(data, other.data)
  override def equals(obj:Any):Boolean =
    if (obj.isInstanceOf[BAWrapper2]) equals(obj.asInstanceOf[BAWrapper2])
    else false
  override def compareTo(that:BAWrapper2):Int =
    if (comparator != null) comparator.compare(this.data, that.data)
    else BAComparator.compare(this.data, that.data)
  override def hashCode:Int = util.Arrays.hashCode(data)
}


Erro: Column count doesn't match value count at row 1

Question:
include "config_db.php";

$sql = "INSERT INTO tb_produto (NOME_PROD,DESC_PROD,VALOR_PROD,VL_COMP_PROD,STATUS_PROD,COD_CAT,TAM_PROD,COR_PROD,COD_BARRA_PROD,ID_FORN,MAT_FUNC, QTD_PROD,FT_PRODUTO)VALUES('$nome',$desc,$val,$vld,'$status',$cat,'$tam','$cor',$cbr,$forn,$func,$qtd,'$ft')";
$sel = mysqli_query($con,$sql) or die (mysqli_error($con));
$caminho_imagem = "prod/ft/".$ft;
if(move_uploaded_file($ftmp, $caminho_imagem)){
    echo"

    Produto Cadastrado

    Voltar";
}

Esse código apresenta o erro citado no titulo, como resolver?
Comment: Alguma das variáveis está vindo com aspas simples?
Comment: $sql = "INSERT INTO tb_produto (NOME_PROD,DESC_PROD,VALOR_PROD,VL_COMP_PROD,STATUS_PROD,COD_CAT,TAM_PROD,COR_PROD,COD_BARRA_PROD,ID_FORN,MAT_FUNC, QTD_PROD,FT_PRODUTO)VALUES($nome,$desc,$val,$vld,$status,$cat,$tam,$cor,$cbr,$forn,$func,$qtd,$ft)";
Comment: sem as aspas simples.. teste ai..
Comment: Já havia tentado mas sem sucesso esse metodo, mas já resolvi o problema, Obrigado
Answer: Algumas das variáveis na query estão vindo com aspas simples ', fazendo com que mais de um VALUE se torne apenas 1, e com isso o número de VALUES se torna menor em relação ao número de colunas da query. Por exemplo:
Se eu tenho esta query:
"insert into tabela (coluna1,coluna2)values($abc,$def)"

E os valores das variáveis são:
$abc = "'foo";
$def = "bla'"

A query ficaria assim:
"insert into tabela (coluna1,coluna2)values('foo,bla')"

Veja que o VALUES possui agora apenas 1 parâmetro, delimitado entre as aspas simples, resultando no erro citado na pergunta (Column count doesn't match value count at row 1):

Solução e Sugestão:
Antes de inserir no banco, fazer um replace em todas as variáveis tirando as aspas simples. Uma sugestão seria substituir as aspas simples pelo código HTML que representa um apóstrofo:
$abc = str_replace("'","’",$abc);

Answer: Neste caso do seu INSERT o ideal serial alterar esta linha
$sql = "INSERT INTO tb_produto (NOME_PROD,DESC_PROD,VALOR_PROD,VL_COMP_PROD,STATUS_PROD,COD_CAT,TAM_PROD,COR_PROD,COD_BARRA_PROD,ID_FORN,MAT_FUNC, QTD_PROD,FT_PRODUTO)VALUES('$nome',$desc,$val,$vld,'$status',$cat,'$tam','$cor',$cbr,$forn,$func,$qtd,'$ft')";

Para esta abaixo linha abaixo, com todas variáveis dentro de aspas simples identificando que cada campo receberá somente um valor evitando conflitos e também que o número de values seja maior ou menor que o número de campos informados na query
$sql = "INSERT INTO tb_produto (NOME_PROD, DESC_PROD, VALOR_PROD, VL_COMP_PROD, STATUS_PROD, COD_CAT, TAM_PROD, COR_PROD, COD_BARRA_PROD, ID_FORN, MAT_FUNC, QTD_PROD, FT_PRODUTO) VALUES ('$nome', '$desc', '$val', '$vld', '$status', '$cat', '$tam', '$cor', '$cbr', '$forn', '$func', '$qtd', '$ft')";

Comment: Usei seu método e também o str_replace para substituir o "," por "." na inserção de valores em dinheiro(decimal) no banco de dados, muito obrigado
Comment: Se esta resposta te atendeu, marque como melhor esposta para os outros usuários entenderem isso e não utilizarem o tempo para resolver uma questão que ja foi atendida


Mozart's violin bowing

Question: In L. Mozart's book about violin playing, he goes to great lengths to explain how to determine which way to bow per note. I'm seeing a lot of arbitrary rules in the sense that that he doesn't really explain the ultimate logic behind them. It may look nice if everyone bows the same, but it doesn't mean it is the best.
Usually there are several side cases for the standard "alternate bowings, downbow on down beat" type of rule, of which I haven't figured out why he is mentioning them and he doesn't really explain why, but just how.
What is the ultimate "law" of bowing strokes?  Is there a way to take a non-marked piece of music an determine the bowings that give the most correct way to play it (and what is correct then?)?
I'm not one to just blindly follow a set of rules, no matter who the authority. Obviously down bows and up bows are different and produce a subtle accent difference, and we usually want the accents to align with the meter, but is that the basis for all the rules?
I'd like a somewhat comprehensive answer, if one exists. A lot of technique is based on strong experiences, but I have yet to see how the bowing theories apply, except in multiple bowing instruments having a unity through their bowing direction... which looks nice but also provides an enhancement of the differences between them. While this is true, it doesn't explain why the specific rules were chosen, except as possibly a standard that everyone can agree on (e.g., like 440hz tuning standard).  I'd like to know if there is something more to it, which should explain the rules he gives (the why part that he left out).
Comment: Just remember that since Leopold Mozart couldn't predict the future, his "rules" are fairly irrelevant for any music written after 1800, especially considering the adoption of the Tourte bow and abandoning gut strings!
Answer: alephzero has a point – with a Tourte bow, you could play something like 80% of all notes in the "wrong" direction and still get virtually the same sound. Indeed some solo players are known to play passages with completely unorthodox bowing and get perfectly fine results, not to speak of Irish Folk fiddle players who often seem to follow no system at all but random back-and-forth.
Nevertheless, I don't think those guidelines by e.g. Mozart are obsolete. A crucial part is indeed just to have any kind of (reasonably simple) rules, even if they're arbitrary: this allows the players to worry about other things and in particular relieves the voice leaders from having to explicitly communicate lots of extra information to keep the section in sync. Most of the time in an orchestra, the string players will just know intuitively what the bowing will be.
The rules are not in fact arbitrary though, because the original simplistic classification (nobilis: downbow, vilis: upbow) still holds in mainly the sense that it's easier to play confident, crisp accents with a downbow. Yes, it's possible to play such accents with an upbow, but it gets really exhausting for passages containing many notes which require powerful response. This is especially true for the low strings of the bass section, but probably at least somewhat significant for violins too.
Perhaps even more importantly, the standard bowing keeps a sensible feel for  the music's pulse. A downbow has a "grounding" feel, as an extreme analogy like stomping feet in a march. An upbow has no such feel, it rather has something of a "taking breath" thing to it, so inverting the bowing can give a bit of a feeling of hyperventilation. At least is loses much of the common-pulse effect that a string section can have if playing well together.
Answer: This will not be comprehensive, but I'll get you started.
In a piece written in 4-4 meter (common time), the first beat of the measure has a natural stress: ONE - two - three - four, ONE- two - three - four, etc.  Well, as @leftaroundabout pointed out, the down bow naturally comes out with a bit more emphasis than the up bow, all other things being equal.  So, generally speaking, it makes perfect sense to match up the down bow with the naturally stressed note of the measure.  I like the way you described this: "we usually want the accents to align with the meter."
When you are learning to juggle, starting with the dominant hand is easier, but to get better, you must practice starting with the non-dominant hand also, and strive to make this as smooth and reliable as when you're doing it the easy way.
Similarly, percussionists have to practice rhythmic sequences in both dominant-favoring patterns and in the opposite as well.  Just like dancers need to practice right-hand pirouettes AND left-hand pirouettes.
Well, once you get past the beginning stages of learning a string instrument, it can be surprisingly helpful to vary your practice of a piece that you've been working on for awhile, by sometimes starting with the opposite bowing from what you're used to.  (It gets you out of your rut!)  Do you see the connection with what I explained about dancers, percussionists and jugglers?
So, it can be helpful in one's training and practicing to bow everything "backwards," and counteract the natural tendencies of the bow, to achieve similar results even though you're doing things temporarily the hard way.
However, when performing, there are so many things to think about, one is generally better off sticking to the easy way whenever possible.
Part of what makes one way the "easy" way is that you can conserve energy by using gravity as your friend.  This is especially important playing in orchestra.  If your performance lasts 90 - 120 minutes, it would not be good to waste energy where it's not actually needed, because you will want to have maximum energy available for your performance.  You want to be just about to run out of energy just when you are getting to the end of the last piece on the program.  That is an optimal performance.
Your shoulder is somewhat stressed when you spend a lot of time at the tip, especially in the lower strings (D and especially G).  So orchestral bowings generally try to minimize how long you have to park yourself at or near the tip -- except for very soft parts, where you really will need to stay at or near the tip for long periods, to get that special tip timbre.
Learning bowing conventions is one of the easy aspects of learning a string instrument.  It will happen naturally as you progress, especially if you are playing in an orchestra during your training.
Good intonation, developing a repertoire of various types of expressive tone, these are things that take more work.
Answer: If it's a law you want, let's try a law of physics: how a lever works.  Compared to playing at the tip, at the frog you don't have to push nearly as hard to exert the same downforce on the string, because the lever arm is shorter.
This isn't "gravity."  It works if you're hanging upside down, or in a helicopter flying a complicated trajectory, or in even odder situations.  If Chris Hadfield had a violin instead of a guitar, he could have demonstrated this in orbit.
So, all else being equal, if you want a note to start with a strong accent, prefer to start it at the frog.  Balance this rule against the many others that apply in a particular situation of phrasing and rhythm and accents.

Mozart's violin bowing


A sequence raised to a sequence

Question: I was wondering if the following is true...
If $(a_{n})$ is a sequence of positive terms converging to $a$ and $(b_{n})$ is a real sequence converging to $b$, then the sequence $(a_{n}^{b_{n}})$ converges to $a^{b}$.
This is what I did
$$ a_{n}^{b_{n}} = e^{b_{n}\ln{a_{n}}}$$
Now as the logarithm function is continuous, we have, for a fixed $m$
$$ \lim\limits_{n\to \infty}a_{n}^{b_{m}} = e^{b_{m}\ln{a}} $$
Now as exponential is continuous, we have our result.
Is every step here correct? I am skeptical because this is an important result and the proof is easy (if it is correct) and yet it is not found in real analysis books.
EDIT: We have $(1 + 1/n) \to 1$ and $n\to \infty$ and $(1 + 1/n)^{n} \to e$. Does this qualify as a counterexample? Is the result only true for finite $a$ and $b$?
Answer: The proof is not quite correct. You can't decide which variable to keep fixed and which one to compute a limit on (as your edit shows, one can obtain lots of nonsense by doing so). Instead, simply argue by continuity of $\ln$ that $\ln (a_n)$ converges to $\ln (a)$ (assuming here $a\ne 0$), and then it follows that $b_n\cdot \ln(a_n)$ converges to $b\ln(a)$. Then the computation is complete.
The proof is easy but it uses the continuity of the exponential function and of $\ln$, as well as the fact that $a^b=e^{b\ln a}$. None of these is particularly trivial. Notice that you can define exponentials from first principles, only using the algebraic definitions up to when the exponent is a rational number (all positive). Then you can define arbitrary exponents by continuity. This will produce an elementary a rigorous definition of exponents, including of the exponential function itself. If this is done, then $a^b$ is defined to be the limit $a_n^{b_n}$ where $a_n$ is a sequence of rationals converging to $a$, and $b_n$ is a sequence of rationals converging to $b$. It is then elementary and not too hard to show that $a^b$ is independent of the choice of sequences.
Answer: I would skip the step of disconnecting the indices of the two sequences.
Rather:  by continuity of the logarithm, $\ln a_n\rightarrow a$ as $n\rightarrow\infty$. Hence $b_n\ln a_n\rightarrow b\ln a$ as $n\rightarrow\infty$; so, by continuity of the exponential, $a_n^{b_n}\rightarrow a^b$.
Note that you should also explicitly add the assumption that $a>0$.

A sequence raised to a sequence


_setCampNameKey usage in Google Analytics

Question: I'm looking at the js for google analytics on a page. It contains the following (changed the domain name, name etc). This is on the home page. I understand that these are used to set campaign variables but... why would someone do this on the home page? Perhaps because they have multiple sites and are tracking hits to each one as a campaign? Is this a good configuration?
 _gaq.push(['_setDomainName', 'somesite.co.uk']);
  _gaq.push(['_setAllowLinker', true]);
  _gaq.push(['_setCampNameKey', 'John Doe']);
  _gaq.push(['_setCampSourceKey', 'any']);
  _gaq.push(['_setCampMediumKey', 'any']);
  _gaq.push(['_setCampTermKey', 'plumbs']);
  _gaq.push(['_setCampContentKey', 'all']);
  _gaq.push(['_trackPageview']);

Answer: You're thinking a step further.  All the _setCamp*Key functions tell GA there to look in the Key -- not the value.  Take a closer look at the examples in the GA Campaign Tracking Docs
Comment: Ah, thanks! So from the docs if the incoming link has a param description = 'xxx' then setCampContentKey is saying map whatever is in the description field to the standard utm_content field... but does that make sense for the example above? Wouldn't the line  _gaq.push(['_setCampContentKey', 'all']); indicate there is a param all='something' which should be mapped to utm_content?


Switching multiple DB and mysql_close

Question: Do we need to call mysql_close(); before switching the database using                db_set_active('sharedb');?
Comment: Why the downvote?  This is a concise, yet interesting question.
Answer: No, you should not call any mysql functions at all. You don't mention the drupal version, but in 6, it's likely that you're actually using the mysqli extension and in 7, you're using PDO.
I don't think that a handful open database connections is going to be a problem, they will be automatically closed by the end of the request. So unless you have a long-running process or more than a handful connections you need to make, I wouldn't worry.
If you have either of those, then you might need to care about this, if you're on 7.x, there's an API for this: Database::closeConnection().
On 6.x, you're not so lucky, while you could check global $db_type (see db_set_active()), and call the right function, you also need to pass global $active_db to the function to close the right connection and you can't update $db_conns in db_set_active(), so that will not know that you closed the connection and you can't re-open the connection again.
Comment: The version is drupal 6. When I am trying below code to close the connection but it throwing a warning..supplied argument is not a valid MySQL-Link resource.                                              global $active_db;
mysql_close($active_db);
Comment: As I said, Drupal 6 uses mysqli if available

Switching multiple DB and mysql_close


how to disable access to file WEB-INF/web.xml in tomcat

Question: On a tomcat 7 server used by a third party program, the WEB-INF/web.xml file is accessible from user's browser. Is there a way to prevent this from happening?
Answer: Had a similar issue today. WEB-INF/web.xml was accessible with http://example.com/WEB-INF./web.xml (mind the . in front of /web.xml).
This only happen on Windows servers with tomcat.
To resolve that behavior, edit $TOMCAT_HOME/conf/context.xml and remove allowLinking=true (or set to false) in th <Context ... /> tag. Then restart tomcat.
See also Tomcat Documentation - The Context Container

allowLinking
If the value of this flag is true, symlinks will be allowed inside the
  web application, pointing to resources inside or outside the web
  application base path. If not specified, the default value of the flag
  is false.
NOTE: This flag MUST NOT be set to true on the Windows platform (or
  any other OS which does not have a case sensitive filesystem), as it
  will disable case sensitivity checks, allowing JSP source code
  disclosure, among other security problems.


Error when try to upload an .ipa file to saucelabs

Question: Hellow! I am using curl to upload an ios file to SauceLabs.com but get this error in terminal.
Any idea?
curl: (7) Failed to connect to  port 80: Connection refused

Comment: Better to contact Sauce Labs support for this instead of using SO
Comment: Yep, thanks man! I did it, just that looks takes long time to get an answer
Answer: Without verbose logs to look at, there's two reasons this might be happening:

You're trying to connect to the REST API on port 80 instead of port 443, either explicitly or because you're using http instead of https.

Your network is blocking the connection.

Generally, if you run curl with the -v argument, it'll give you more details about what's going wrong.
Comment: Thank you very much! This is solved and was because some of this reasons. Thanks


How can I use Pages in drupal 7?

Question: I am using Drupal 7.
I want to make different looking pages, but I can't do this because it is always using the main theme block regions, and I can't change my specific page elements. For example, I want to make a page that has a cartoon images and another page that has a movie images on the background, and the block regions can be reordered.
I tried Pages in Structure menu, but I don't understand it. I created one page, and assigned it a URL, but I can't access the page with my URL, as it says "page not found."
Comment: I think you need to do it in preprocess_page to create a tpl for every page or you can do that via $variables['classes_array'][] or $vars['template_file'] using arg()...its up to you if what approach do you want to use...
Answer: The Context module would help here. It allows make 'sections' within your site based on selection rules like the path, views or menus chosen etc. Using Context you can apply a CSS class to the body based on the current section and then make the background image change based on that.
Context also allows you to use alternative layouts and you to re-order blocks as needed, and there are many add-on modules for it to extend its abilities further.
Answer: You should create different templates for every section you need. Check this out. The comments also :)
Answer: I think you could reuse the solution I suggested here and use ThemeKey contrib module.

How can I use Pages in drupal 7?


Dynamic pricing of products/line items with a "pricing entity"

Question: I'm trying to achieve a pricing functionality in which product/line item's price is configured in an external entity. So that I can have one product which can be priced by multiple entities depending on which is being viewed.
This external entity is a "host" entity or a product display which has two fields: product reference and a price field (float).
Now, when customer visits this host entity page and adds a line item to cart it should change the price according to host entity price field.
At first I tried this with Rules but it was just so inconsistent that I decided to look other options. So here's a piece code that I think could solve this:
<code>    // Alter the price in list and single product page.
function commerce_dynamic_pricing_commerce_product_calculate_sell_price_line_item_alter($line_item){

    if ($node_wrapper = entity_metadata_wrapper('node',_commerce_dynamic_pricing_menu_get_any_object()) ) {

        if ($node_wrapper->type->value() == "price_list") {

            $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);

            dsm($line_item_wrapper->commerce_unit_price->amount->value(). 'Old price');

            foreach ($node_wrapper->field_collection_licenses as $key => $license) {
                if ($line_item_wrapper->commerce_product->product_id->value() === $license->field_license->product_id->value()) {
                                            $line_item_wrapper->commerce_unit_price->amount->set($license->field_license_price->value());
                }

                $line_item_wrapper->save();
            }

            dsm($line_item_wrapper->commerce_unit_price->amount->value(),'New price');
            }
        }
}
</code>
The problem with this code is that the price isn't changed/updated. I'm not sure that how the price should be modified.
Answer: So this first alter hook handles price on product display.
But price needs to be handled again with another hook: commerce_dynamic_pricing_commerce_cart_line_item_refresh.
This handles prices regarding current line items in cart.
I also needed to avoid combining same type of line items into "quantity groups".This works well in:
<code>    $line_item->data['context']['add_to_cart_combine'] = FALSE;
</code>


Timeout error when loading 300 MB file into BigQuery

Question: I followed the Node.js example provided on the loading data post request page (near the bottom here: https://cloud.google.com/bigquery/loading-data-post-request), but I'm running into a problem with larger files. The example code works for a .csv of 13 MB, but when I try bigger files, whether 25 MB or 300 MB, it doesn't work. I see the following error:

events.js:154
            throw er; // Unhandled 'error' event
            ^
<code>Error: ETIMEDOUT
    at null._onTimeout (/Users/Hertig/Development/BitDeliver/BigQuery/node_modules/request/request.js:772:15)
    at Timer.listOnTimeout (timers.js:92:15)
</code>

I thought that this method of loading data would support bigger files. Has anyone else experienced this? Any advice on loading much bigger files (around 400 MB or larger) would be appreciated.
Answer: When loading big files to BigQuery, the best method is uploading them to Google Cloud Storage first - then tell BigQuery to read them from your gs://bucket/path/file*.


Fast algorithm for solving system of linear equations

Question: I have a system of $N$ linear equations, $Ax=b$, in $N$ unknowns (where $N$ is large).
If I am interested in the solution for only one of the unknowns, what are the best approaches?
For example, assume $N=50,000$. We want the solution for $x_1$ through $x_{100}$ only. Is there any trick that does not require $O(n^{3})$ (or $O$(matrix inversion))?
Comment: Is $A$ full or sparse? Are you doing this once or many times with the same $A$?
Comment: You may apply iterative methods (CG, if you matrix is spd, GMRES something similar otherwise). You may also want to ask at http://scicomp.stackexchange.com/.
Comment: A is not sparse and has many nonzero elements, however, the coefficients themselves are derived from a smaller set of variables.
Comment: About your second question, yes I'm doing this many times. I am familiar with the LU decomposition trick to speed up when the coeffs matrix is unchanged. Is there any other tricks to do that even more efficiently?
Answer: The fastest matrix multiplication algorithm is an important open mathematical question
The Wikipedia page https://en.wikipedia.org/wiki/Matrix_multiplication_algorithm#Sub-cubic_algorithms shows how the fast known asymptotic algorithm has evolved through time:

This begs the question: how close can we get to O(n^2), which is of course a lower bound since we have to read 2 * n^2 inputs at least once?
Proving the upper lower bound, even non constructively, would make you instantly famous. Wikipedia lists it as an "Unsolved problem in computer science".
The constant factor for the better algorithms is so large though that it makes them impractical for most matrix sizes found in practice today, and I doubt this will change if new algorithms are found.
Therefore any practical real world answer will come down to optimizing against a given machine model, which is an important software / hardware engineering optimization question, but not of much mathematical interest.
Personal guess about solving for single variables: I don't think you can reduce complexity like that in general, since the entire system is coupled. How would you know that your solution for some variables also satisfies the entire global solution?
Comment: Here is the wiki to the family of algorithms you are referring to: https://en.wikipedia.org/wiki/Coppersmith%E2%80%93Winograd_algorithm

Also worth looking at https://en.wikipedia.org/wiki/Strassen_algorithm
Answer: Unless your matrix is sparse or structured (e.g. Vandermonde, Hankel, or those other named matrix families that admit a fast solution method), there is not much hope of doing things better than $O(n^3)$ effort. Even if one were to restrict himself to solving for just one of the 50,000 variables, Cramer will demand computing two determinants for your answer, and the effort for computing a determinant is at least as much as decomposing/inverting a matrix to begin with.
Answer: There is a way to reduce the complexity and make the system solvable in parallel.
It is called Diakoptics (a method invented by Gabriel Kron). The methods primary use is for large electrical networks that have few interconnections like power grids. But you should be able to adapt it.
The complexity (for the case below) is reduced from $O(n^3)$ to $O(2(\frac{n}{2})^3)$ or $O(\frac{1}{4}n^3)$, the impact can be much greater if the system is divided it into more subsystems. For that case the complexity is ($s$-subsysems, $c$-interconnection points) $O(c^3)+O((\frac{n^3}{s²}))$, if the systems is divided into equaly sized subsystems. I'm not sure about the notation for multiple variables, but you should get the point.
In short:
Lets assume you have a $N \times N$ system, lets say you can divide the system into two systems with 1 connection point(plus reference when you look at electrical systems). The connection points are $m$ and $n$. Lets assume these systems are of the size $N_1=N/2$ and $N_2=N/2$ (for simplicitys sake). You should now solve them separately.
$\mathbf A_1^{-1}=\mathbf  B_1$
$\mathbf A_2^{-1}=\mathbf  B_2$
The next step is to put them back together, that is done with the help of the so called "Thevenin Matrix"(in our case it is 1$\times$1). You can look up the exact principle for higher orders(more connection points), but for this example it looks like:
\begin{align}
\mathbf{B_{TH}}=B_{1mm}+B_{2nn}-2B_{mn}
\end{align}
For our case we have $B_{mn}=0$. Now we need the solutions $x_1$ and $x_2$ to form the coefficients $b_{th}$.
$\mathbf x_{th}=x_{1m}-x_{2n}$
$\mathbf b_{p}=\mathbf{B_{TH}}^{-1} \mathbf x_{th}$
\begin{align}
\mathbf b_{th}=\begin{bmatrix}0&\cdots&b_{p}&\cdots&-b_{p}&\cdots&0
\end{bmatrix}^T
\end{align}
The $\mathbf b_{th}$ matrix only has nonzero elements at $m$ an $N/2 +n$. Now we can finally find the solution $x_n$ for the whole system:
\begin{align}
\mathbf x_n=\begin{bmatrix}x_1\\x_2
\end{bmatrix}-\begin{bmatrix}B_1&0\\0&B_2
\end{bmatrix}\begin{bmatrix}b_{th}
\end{bmatrix}
\end{align}
I'm more used to the engineering notation with $Z, I, U$ and so on, so excuse for non-standard symbol usage.
Answer: Im suggesting you take a look into what quantum computing can do for you.
If you are able to make api calls form your product - then this might be the most performant approach by a lot.
This youtube video for example is a lecture which discusses problems that appear with large nr of equations : Quantum algorithm for solving linear equations
For quantum computer api you can use a service like: http://rigetti.com/forest
I personally did not tested this services, but this answer is just for pointing out the posibility. Just to show is something that can be used today, not science fiction.


Hyperplanes optimally classify data when inputs are conditionally independent - Why?

Question: In the paper called Deep Learning and the Information Bottleneck Principle the authors state in section II A) the following:

Single neurons classify only linearly separable inputs, as they can
  implement only hyperplanes in their input space $u = wh+b$.
  Hyperplanes can optimally classify data when the inputs are
  conditioanlly indepenent.

To show this, they derive the following. Using Bayes theorem, they get:
$p(y|x) = \frac{1}{1 + exp(-log\frac{p(x|y)}{p(x|y')} -log\frac{p(y)}{p(y')})} $ (1)
Where $x$ is the input, $y$ is the class and $y'$ is the predicted class (I assume, $y'$ not defined). Continuing on, they state that:
$\frac{p(x|y)}{p(x|y')} = \prod^N_{j=1}[\frac{p(x_j|y)}{p(x_j|y')}]^{np(x_j)} $ (2)
Where $N$ is the input dimension and $n$ I'm not sure (again, both are undefined). Considering a sigmoidal neuron, with the sigmoid activation function $\sigma(u) = \frac{1}{1+exp(-u)}$ and preactivation $u$, after inserting (2) into (1) we get the optimal weight values $w_j = log\frac{p(x_j|y)}{p(x_j|y')}$ and $b=log\frac{p(y)}{p(y')}$, when the input values $h_j=np(x_j)$.
Now on to my questions. I understand how inserting (2) into (1) leads to the optimal weight and input values $w,b,h$. What I do not understand however, is the following:

How is (1) derived using Bayes theorem?
How is (2) derived? What is $n$? What is the meaning of it? I assume it has something to do with conditional independence
Even if the dimensions of x are conditionally independent, how can one state that it is equal to to its scaled probability? (i.e how can you state $h_j=np(x_j)$?)

EDIT: The variable $y$ is a binary class variable. From this I assume that $y'$ is the "other" class. This would solve question 1. Do you agree?
Comment: I am struggling to understand where eq 2 comes from, despite the pointers in the answer by the author of the paper (Prof. Tishby). I do understand the part that comes from the conditional independence assumption. However, I am not sure about the exponent $n p(x_j)$ - why is it there?
Answer: Sorry about the missing details in our short paper, but these relations and connections between Likelihood Ratio test and sigmoidal neurons are certainly not new, and can be found in textbooks (e.g. Bishop 2006). In our paper, 'N' is the input dimension and 'n' is the test sample size (which actually translated to the input SNR under the assumption that the SNR grows like sqrt(n)). The connection to the sigmoidal function is done through Bayes rule, as the posterior of the class. Nothing in the rest of the paper and our newer and more important paper from 2017 actually depends on this.
Naftali Tishby
Comment: Thank you for clarifying this here. It is standard practice in this community to write full citations so that interested readers may seek out the sources. Could you please do this for Bishop (2006)?
Answer: This is a model setup where the authors are using a special form of Bayes theorem that applies when you have a binary variable of interest.  They first derive this special form of Bayes theorem as Equation (1), and then they show that the condition in Equation (2) leads them to the linear form specified for their network.  It is important to note that the latter equation is not derived from previous conditions --- rather, it is a condition for the linear form they are using for their network.

Deriving the first equation: Equation (1) in the paper is just a form of Bayes theorem that frames the conditional probability of interest in terms of the standard logistic (sigmoid) function operating on functions of the likelihood and prior.  Taking $y$ and $y'$ to be the two binary outcomes of the random variable $Y$, and applying Bayes theorem, gives:
$$\begin{equation} \begin{aligned}
p(y|\mathbf{x})
= \frac{p(y,\mathbf{x})}{p(\mathbf{x})}
&= \frac{p(\mathbf{x}|y) p(y)}{p(\mathbf{x}|y) p(y)+p(\mathbf{x}|y') p(y')} \\[6pt]
&= \frac{1}{1+ p(\mathbf{x}|y') p(y')/p(\mathbf{x}|y) p(y)} \\[6pt]
&= \frac{1}{1+ \exp \Big( \log \Big( \tfrac{p(\mathbf{x}|y') p(y')}{p(\mathbf{x}|y) p(y)} \Big) \Big)} \\[6pt]
&= \frac{1}{1+ \exp \Big( - \log \tfrac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} - \log \tfrac{p(y)}{p(y')} \Big)} \\[6pt]
&= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg). \\[6pt]
\end{aligned} \end{equation}$$
Using Equation (2) as a condition for the lienar form of the network: As stated above, this equation is not something that is derived from previous results.  Rather, it is a sufficient condition that leads to the linear form that the authors use in their model ---i.e., the authors are saying that if this equation holds, then certain subsequent results follow.  Letting the input vector $\mathbf{x} = (x_1,...,x_N)$ have length $N$, if Equation (2) holds, then taking logarithms of both sides gives:
$$\begin{equation} \begin{aligned}
\log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')}
&= \log  \prod_{i=1}^N \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big]^{n p (x_i)} \\[6pt]
&= \sum_{i=1}^N n p (x_i) \log \Big[ \frac{p(x_i|y)}{p(x_i|y')} \Big] \\[6pt]
&= \sum_{i=1}^N h_i w_i. \\[6pt]
\end{aligned} \end{equation}$$
Under this condition, we therefore obtain the posterior form:
$$\begin{equation} \begin{aligned}
p(y|\mathbf{x})
&= \text{logistic} \Bigg( \log \frac{p(\mathbf{x}|y)}{p(\mathbf{x}|y')} + \log \frac{p(y)}{p(y')} \Bigg) \\[6pt]
&= \text{logistic} \Bigg( \sum_{i=1}^N h_i w_i + b \Bigg), \\[6pt]
\end{aligned} \end{equation}$$
which is the form that the authors are using in their network.  This is the model form postulated by the authors in the background section, prior to specifying Equations (1)-(2).  The paper does not define $n$ is in this model setup, but as you point out, the answer by Prof Tishby says that this is the test sample size.  In regard to your third question, it appears that the requirement of Equation (2) means that the values in $\mathbf{x}$ are not conditionally independent given $y$.
Comment: Prof. Tishby (author) says, in his own answer, that $n$ is the test sample size. This is why I felt that eq (2) had a much richer interpretation than just an arbitrary condition to the linear form of the network.
Comment: Thanks - I have edited my answer to reflect this additional information.
Answer: For 1
$P(y \mid x) = \frac{P(y, x)}{P(x)}$
$= \frac{P(y,x)}{\sum_{i}P(y_{i},x)}$
Now as $y_{i}$ is binary, this becomes:
$= \frac{P(y,x)}{P(y,x)+P(y',x)}$
$= \frac{1}{1+\frac{P(y',x)}{P(y,x)}}$
$= \frac{1}{1+exp[-log \ \frac{P(y,x)}{P(y',x)}]}$
and from there its just the property of the logarithm to get to the final form (should be sufficiently clear by this point, let me know if not).


Is it possible to create an interceptor for any redirection in ASP.NET Core?

Question: I'm creating a tool to detect redirections and show them in an admin panel.
I want to somehow know about all redirections without the developer getting involved.
Is it possible in ASP.NET Core?
If yes, how can I do it?
Comment: What do you mean by "interceptor"?
Comment: @Dai, the interceptor pattern. Something that exists in Axios or EF Core. To augment functionality without writing it everywhere. I know about middleware in ASP.NET Core. But I'm not sure if they can be used for that purpose.
Comment: your means is visitor come from where? or visitors going where after your site? (both can be implement)
Comment: @foadabdollahi, I want to add a DLL to a project, configure it in one line preferably, and then log any redirect call. `Response.Redirect` for example.
Answer: This problem must require developer intervention, which can be stored in logs. Convenient to display records in your admin panel.
public class RedirectHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RedirectHandlerMiddlerware> _logger;

    public RedirectHandlerMiddleware(RequestDelegate next, ILogger<RedirectHandlerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        await HandleRedirect(context, ex);
        await _next(context);
    }

    private Task HandleRedirect(HttpContext context)
    {
        if (context.Response.StatusCode == 302)
        {
            ...
            //context.Response.Redirect("...");
        }
        return Task.CompletedTask;
    }
}

You need to register in Startup.cs. It should be placed after app.UseAuthentication();.
app.UseMiddleware<RedirectHandlingMiddleware>();


Django 2 Template inexistente

Question: No meu projeto tenho um projeto com 2 apps.
A primeira app é learning_logs que possui um template, base.html
A segunda app é users, estou tentando utilizar o template do learning_logs no users da seguinte forma:
<code>{% extends "learning_logs/base.html" %}
</code>
Acontece que a app que está tentando usar o template, está procurando dentro da sua própria app, e como não encontra está aparecendo msg de template inexistente.
Answer: Tirei o nome da app onde está o template e funcionou.
<code>{% extends "base.html" %}
</code>

Django 2 Template inexistente


Universal introduction - how exactly does it work?

Question: How does universal introduction work?
I have tried something like this :
1) $\exists x: p(x) \Rightarrow p(x) $
I'm using this rule and I'm getting something like this:
2) $\exists x: p(x) \Rightarrow \forall x: p(x) $
Next someone on this forum once said that this is wrong, could you explain why?
Next I have tried doing something like this:
Now I 'm using Existential instantiation which gets me:
3) $ p(a) \Rightarrow \forall x: p(x) $
Here Universal instantiation which leads me to :
4) $p(a) \Rightarrow p(a) $
What don't I understand in those rules?
Comment: You have to be more precise on the set of *rules* you are allowed to use ... But, in any way, **no** "sound" set of rules whatever may licences the derivation of $\exists x p(x) \to \forall x p(x)$ because it is *invalid*. Consider $\mathbb N$ and the predicate $x=0$; clearly $\exists x (x=0)$ is *true* in $\mathbb N$ while $\forall x (x=0)$ is *false*. Thus, in this interpretation, the conditional $\exists x (x=0) \to \forall x (x=0)$ is *false*.
Answer: (A) The basics. Informally, the idea is this. If you have established $\phi(a)$ for some arbitrarily chosen object $a$ in the domain and relying on no special "inside knowledge" about $a$ in particular, then you are entitled to infer $\forall x\phi(x)$.
So we get a UI rule like this: given you have established $\phi(a)$, where the parameter ("temporary name") $a$ doesn't appear in the premisses you've ultimately used [that ensures that you are indeed using no special knowledge about $a$!], then you can infer $\forall x\phi(x)$. NB the introduced quantifier has to go right at the front! You are saying $\phi$ applies to this, but this is an arbitrary example, so everything is $\phi$.
Now, some presentations of first-order logic recruit variables $x$ to serve double duty as parameters. Don't let that confuse you. Use different letters for free and bound variables if that helps. In this sort of presentation, the rule will be that if you have established $\phi(x)$ where the unbound-variable-$x$-used-as-a-parameter doesn't appear in any premiss that you rely on [and that will be guaranteed if you insist that premisses can't have free variables!], then you can infer $\forall x\phi(x)$. NB, to repeat, the introduced quantifier has to go right at the front!

(B)Turning to the first example. What is the wff here? In unambiguous notation is it

$\exists x(Px \to Px)$
$(\exists xPx \to Px)$

If (1), then the sentence $\exists x (Px \to Px)$ hasn't got any parameters/free variables in it: both occurrences of $x$ inside the bracket are already bound by the initial quantiser. So, on one standard story [the best sort!] you can't apply universal quantifier introduction at all. If on the other hand your system allows vacuous quantification, then you are always allowed to infer $\forall y\exists x (Px \to Px)$ or even $\forall x\exists x (Px \to Px)$ with the useless dangling quantifier that does no work. But NB, the added vacuous universal quantifier, if allowed, has to go right at the front, as it is the whole wff that is quantified in a move of UI.
If (2) then the second $x$ is free. But that still does NOT by itself mean that you can apply UI. It will depend on what premisses you have used to in getting as far as (2) in your proof! Does the parameter occur free in a premiss? If it does, you are in trouble! IN particular, you can't apply UI to (2) if (2) is your only premiss!!!
But if you've got (2) from premisses which don't contain $x$ free, then you can infer $\forall y(\exists xPx \to Py)$ or, if you insist, $\forall x(\exists xPx \to Px)$ by UI. NB the quantifier is at the front! And then by further steps  we can infer $(\exists xPx \to \forall x Px)$: but note that takes more work and further rules.
Is that last result weird? No! You'll only be able to infer (2) $(\exists xPx \to Px)$ with its free variable from some generalization about all $x$! So not such a surprise that you can go on to recover a generalization about all $x$!
Comment: May I suggest $(\exists x\,Px)\to Px$ as a _more_ unambiguous notation for (2)?
Comment: It helped a little but: if have something like this

1) $(\exists x: p(x)) \Rightarrow p(x) $
and then p(x) is unbound i can't use universal introduction?  What should look like  this example if using introduction will be correct?
Comment: Ah I see I may have misread, so I have edited.


Como utilizar caracteres especiais para selecionar um elemento utilizando jQuery?

Question: Preciso verificar se um input type=radio foi checado com jQuery para passar para próxima etapa do formulário. Minha função para isso já estava funcionando, porém precisei transformar o name do checkbox em array para ela armazenar dados de todas as opções escolhidas.
Segue o código:
 $("#button-food").click(function() {
    var food = "";
    $('input:checkbox[name=food[]]').each(function() {
        if ($(this).is(':checked')) {
            food = $(this).val();
            console.log(food);

        }
    })
    console.log(food);

    if (food != "") {
        $("#food-page").hide();
        $("#drink-page").show();
    } else {
        alert("Você precisa escolher uma alternativa! Caso não coma nada, selecione a última opção.")
        $("#button-food").blur();
    }

})

O erro só apareceu depois que eu alterei o name dos inputs para name="food[]", mudança que foi necessária para o back-end do site.
E a mensagem de erro do console foi a seguinte:

Uncaught Error: Syntax error, unrecognized expression: input:checkbox[name=food[]]
    at Function.se.error (jquery-3.5.1.slim.min.js:2)
    at se.tokenize (jquery-3.5.1.slim.min.js:2)
    at se.select (jquery-3.5.1.slim.min.js:2)
    at Function.se [as find] (jquery-3.5.1.slim.min.js:2)
    at E.fn.init.find (jquery-3.5.1.slim.min.js:2)
    at new E.fn.init (jquery-3.5.1.slim.min.js:2)
    at E (jquery-3.5.1.slim.min.js:2)
    at HTMLInputElement. (quiz.js:43)
    at HTMLInputElement.dispatch (jquery-3.5.1.slim.min.js:2)
    at HTMLInputElement.v.handle (jquery-3.5.1.slim.min.js:2)
se.error @ jquery-3.5.1.slim.min.js:2
se.tokenize @ jquery-3.5.1.slim.min.js:2
se.select @ jquery-3.5.1.slim.min.js:2
se @ jquery-3.5.1.slim.min.js:2
find @ jquery-3.5.1.slim.min.js:2
E.fn.init @ jquery-3.5.1.slim.min.js:2
E @ jquery-3.5.1.slim.min.js:2
(anonymous) @ quiz.js:43
dispatch @ jquery-3.5.1.slim.min.js:2
v.handle @ jquery-3.5.1.slim.min.js:2
Answer: Isso acontece porque você não pode colocar qualquer caractere como seletor. A documentação do jQuery destaca estes caracteres como "reservados" para seletores:
! "#$%&'()*+,./:;<=>?@[\]^`{|}~

Desse modo, quando você tenta utilizar o seletor:

//                      ↓↓
input:checkbox[name=food[]]

Ele vai dar um erro — comparável a um erro de sintaxe em uma linguagem de programação. Afinal, o funcionamento é o mesmo. Precisa-se fazer uma análise sintática do seletor para que a biblioteca possa compreendê-lo, de modo que, ao encontrar um caractere "errado" (como, neste caso, um caractere reservado em posição inválida) o analisador não é capaz de prosseguir, já que há, evidentemente, um erro.
Para corrigir, você precisa informar que o trecho [] faz, de fato, parte do atributo name. Para isso, você pode escapá-los, utilizando o caractere de barra invertida (\) ou envolvê-los entre aspas:
// Opção 1: Utilizar aspas para denotar corretamente o conteúdo do atributo `name`:
//                     ↓      ↓
$('input:checkbox[name="food[]"]');

// Opção 2: Escapar, com barra invertida, o caractere reservado:
//                         ↓↓ ↓↓
$('input:checkbox[name=food\\[\\]]');


Identifiability of a state space model (Dynamic Linear Model)

Question: Take a general linear Gaussian state space model (SSM)(aka Dynamic Linear Model DLM):
\begin{align}
X_{t+1} &= FX_t + V_t  \\
Y &= HX_t+W_t  \\[10pt]
V_t &\sim N(0,Q)  \\
W_t &\sim N(0,R)  \\
\end{align}
I am interested in the unidentifiability issues related to these models:
Hamilton (1994) states that "in the absence of restrictions on F, H, Q
and R, the parameters of the state-space representation are unidentified -
more than one set of values for the parameters can give rise to the identical
value of the likelihood function, and the data give us no guide for choosing
among these"
Now I realise that this representation is not unique as multiplication by any orthonormal matrix $M$ produces a new representation:
\begin{align}
MX_{t+1} &= MFM^{-1}M X_t + MV_t  \\
Y        &= HM^{-1}MX_t+W_t
\end{align}
This type of unidentifiability where the observed values can be produced by various orthonormal transformations of the state variables is inherent to state space models.
However, I also came across another type of unidentifiability that seems to be related to the estimation method. In this case "Kalman Filtering." See the simple example starting on page 8 of this pdf.
In this case there is a linear transformation of the observation equation and an offsetting one made to the variance of the state equation

Do both the transformations above give rise to the same kind of identifiability issues described by Hamilton (I believe they do but want to check)?
Are there other ways in which identifiability issues can manifest themselves in Linear Gaussian SSMs?
Is the fix always the same find constraints or analogously (Bayesian priors) that will ensure that the final parameters are correct?

Lastly this link in Matlab suggests that it is possible to build an "identifiable SSM". Unfortunately the link doesn't explain the theory. Thus:

It is possible to translate any Linear Gaussian SSM into an "identifiable form"? Can someone please supply a link reference explaining how this works. It would seem at first blush that no matter what representation is used initially it would still be subject to the problems shown above?
Comment: There is no related example starting on page 8 - is this about the example on page 40? The state there is scalar, so it's just a special case of the "$M$ transformation" mentioned in OP (since for scalars $M\,F,M^{-1} = F$, only the variance changes in the state evolution).  (Unclear if this is the answer to Q1 as it is unclear whether this is the one referred to).
Answer: In my understanding you have to put restrictions on parameters, for example setting them to a constant, to ensure identification. There is no way to rewrite an unidentified model, while preserving all parameters, to a identified model.
There is however an algorithm to check whether a SS-model is identified.  Try looking up the article:
J. Casals, A. Garcia-Hiernaux and M. Jerez, From general State-Space to VARMAX models, Mathematics and Computers in Simulation
In this article they give a cookbook to check for identification, but one step is left unexplained, it is the so-called "stair case algorithm" from the book,
H. H. Rosenbrock, State Space and Multivariable Theory, John Wiley,
New York, 1970,
which I never had any luck locating.
Comment: Hi there, there is a related algorithm to the Rosebrock algorithm here: http://la.epfl.ch/files/content/sites/la/files/users/105941/public/VanDooren.pdf
Comment: The suggestion to place constraints on parameters in order to guarantee identifiability is a fairly obvious one. Is anyone perhaps aware of a concrete example of a set of constraints that would guarantee this for the linear dynamical system described in the original post?
Answer: It is not true that Gaussian state space models (GSSM) are unindentifiable. First, inference on GSSM is inherently Bayesian. It can be shown that Kalman filter recurrences are identical to the equations used to update prior mean and covariances under a Bayesian perspective. Second, a sufficient condition for a GSSM to be identified is that its observability matrix is full rank. Take a look at chapter 5, page 143 of the book by West and Harrison.
Comment: Did you realize the question is about (non)identifiability of the parameters, $F,~H,~Q,~R$? Can you clarify in what sense the GSSM is identified if observability matrix is full rank? (I don't have the book and answers should anyway be self-sustainable)
Comment: Ok, checked pages 143-144 from Springer's preview, don't see any connection with parameter identifiability
Comment: In fact, I meant identifiability of states, which is the case one is interested in general. Matrices F and H are not in general fully estimated, in most cases it is possible to define them as functions of a smaller set of parameters which are identifiable. The same with covariances Q and R. Anyway, under a Bayesian perspective identifiability is not a concern, the question is if posterior distributions are proper or not. Remember that maximum likelihood is just Bayesian inference with uniformative priors.


Log-in page php redirect and cookie deletion

Question: I've fixed my login page to create a user entry with an insert statement and the logout button on the next page delete the user but the issue is when I click log-in the user becomes registers but my page does not redirect to the next page automatically, I have to refresh the page then it leads to the next page because a user is seen as logged in. This is my code:

<?php
if(isset($_POST["Logout"])){
    $saveuser = $_COOKIE["user"];
    $savepass = $_COOKIE["password"];
    $hostname='localhost';
    $username='root';
    $password='';

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=cs266db_db1",$username,$password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
        $sql3 = "DELETE FROM userid
   WHERE user='".$saveuser."' AND password='".$savepass."'";
        if ($dbh->query($sql3)) {
            echo "";
        }
        else{
            echo "";
        }

        $dbh = null;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }

    unset($_COOKIE["user"]);
        unset($_COOKIE["password"]);
}
?>

<?php
if(isset($_POST["submit"])){
    $cookie_user = $_POST["user"];
    $cookie_pass = $_POST["password"];
    setcookie("user", $cookie_user, time() + (86400), "/");
    setcookie("password", $cookie_pass, time() + (86400), "/");

    $hostname='localhost';
    $username='root';
    $password='';
    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=cs266db_db1",$username,$password);

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
        $sql2 = "INSERT INTO userid
   VALUES ('".$cookie_user."','".$cookie_pass."')";
        if ($dbh->query($sql2)) {
            echo "";
        }
        else{
            echo "";
        }
        $dbh = null;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}
?>

<?php
if(!isset($_COOKIE["user"])) {
    echo"<form action="."''"."method="."post".">";
    echo"<input type='"."text'"." name='"."user'"." placeholder='"."Enter Username'"." required/>

";
    echo"<input type='"."password'"." name='"."password'"."  placeholder='"."Enter Password'"." required/>

";
    echo"<input type='"."submit'"." name='"."submit'"." value='"."  Register'"."/>";
    echo"</form>";
}
else {
    header("Location: index_1.php"); /* Redirect browser */
    exit();
}
?>

Also when I log out the user is deleted correctly but then when I load the page from netbeans it takes me to index_1 because it seems the cookie was not deleted? Any help would be great! Again my question is how to redirect it correctly to index_1 and how to properly delete the cookie when I log out.
Comment: Also you should not be injecting variables right into the sql statement like that. Since you are using PDO, you should be using bind.
Comment: if you want to remove cookie use `setcookie` http://php.net/manual/en/function.setcookie.php, `$_COOKIES` assignments and unsets won't work at all
Comment: When I use **setcookie** the logout button does not work though
Comment: Why are you saving the password to a cookie? That is not a good idea from a security standpoint. Especially if it's not even encrypted. You should not need the password at any point after login.
Comment: Also, there is no real need to create two connections separately as you have it. You just need one connection that you can use in both cases. If you create a function (or class if you are savvy that way), you can wrap your connection and keep it on a separate included page at the top.
Comment: Lastly, if you are not really concerned about being stateless, you might have better luck using `$_SESSION` instead of cookies. Cookies can be refused by the client browser.
Comment: My professor wants us to use cookies for the project, also do you understand why my log-in button doesnt redirect?
Comment: Probably/maybe because you can not put `header()` after you have output to the browser. That could be one reason for sure. Very rarely a redirect will still work after output, but more often than not, it will not redirect.
Comment: At the very top of the page, you should add error reporting, that would help  you troubleshoot. ``
Comment: Your script should be: DB Connection, `if/else` logic, (header if required with `exit;`), output to browser. Further, you don't need to do all that crazy `echo` on the form stuff. Do `HEREDOC` or close/open php tags/html: `?>html<?php` or create an html file and `include($htmlfile);` You will save yourself a concatenation headache!
Comment: Ok, I got past the login page, thank you very much @Rasclatt
Comment: **WARNING**: When using PDO you should be using prepared statements and supply any user data as separate arguments. Using string concatenation or interpolation can cause severe [SQL injection bugs](http://bobby-tables.com/). [Using PDO properly is not hard to learn](http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/) and a guide like [PHP The Right Way](http://www.phptherightway.com/) can help with this and other problems. You have **severe** injection bugs in this code that need to be fixed.
Comment: **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/5.2/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and never store passwords as plain-text.
Answer: In all occurrences of closing and opening PHP tag, remove the blank line.
Also, remove the  tag, and all the blank lines and spaces on the top of your code (thanks, @Rasclatt)
Long story short, you should have a continuous PHP code. The cause of problem is described here. You do not see the problem because you turned off error reporting.
Instead of:
.
.
.
?>

<?php
.
.
.

should be:
.
.
.

.
.
.

Alternative solution: use JavaScript redirect instead of HTTP redirect.
Comment: Don't forget the `` tag at the top.


Objective-c multicasting delegates

Question: I create new tabbed view project in xcode, in appdelegate I created a protocol
.h file
@protocol myProtocol <NSObject>
-(void)myProtocolMethodOne;
@end
.
.
.
@property (weak) id<myProtocol> mypDelegate;

.m file
@synthesize mypDelegate;
.
.
.
//Inside didFinishLaunchingWithOptions
[mypDelegate myProtocolMethodOne];

In firstViewController & secondViewController (both are displayed as two different tab) I did this in both
AppDelegate *ad = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    [ad setMypDelegate:self];
.
.
.
-(void)myProtocolMethodOne
{
    NSLog(@"1st VC");
    [[self tabBarItem]setBadgeValue:@"ok"];
}

The code is working perfectly but only secondViewController is responding.
I am looking for a broadcasting and listener kind of mechanism using delegates not notifications.
I searched a lot but did find any solutions except this but code is advance for me to understand, so I am taking a step by step approach to understand this by starting form a simple project. Please help me regarding this. How both viewcontrollers can respond to delegate at same time, what should I do?
Comment: Only one object (at a time) can be the delegate, that's why it's not working. A broadcasting and listening mechanism IS what notifications are. Why don't you want to use that?
Comment: @rdelmar notification do not return values, and for full detail please visit the link I provided. First I was also thinking why not notification but after working on xmppframework I got the answer.
Comment: Why not create an array of delegate objects?
Comment: @overboming please provide a code, how can I use delegate array in my current code that I shared in my question. Thank a lot for replying.
Answer: Instead of delegates you might consider something that looks like the Visitor pattern.
@interface MyVisitor : NSObject < myProtocol >

-(void)addAcceptor:(id < myProtocol >)acceptor

@end

@implementation

-(void)myProtocolMethodOne {
    [_acceptors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *break){
        [obj performSelector:_sel];
    }];
}

// etc etc ... obviously you have to handle return values if you're getting these

@end

Comment: _acceptors is still an array should that be declared as weak? secondly performselector doesn't work really well with multiple arguments
Answer: Since delegate is a simple variable, assigning to it overwrites the value rather than adding to it. You could convert it to an array, but because NSArray keeps strong references to the objects within it you need to deal with potential circular references. (A circular reference in this case is that two objects own each other. Since they're both owned by someone, neither will be freed. Even though they only own each other. Wikipedia has more. But the typical pattern in Objective-C is to make all delegates weak for this reason.)
Instead of delegates, you may wish to consider using NSNotificationCenter notifications.
Instead of 1:1, they're 1:any (including 0 without special considerations). The idea is that one object posts a notification, and the objects that are interested in it observe it. Each object can pick which events they're interested in.
There's a few steps you'll need to perform:

Remove all the delegate code you've written.
Agree on a notification name.
Register the objects that will respond to the notification. (This is where you set the delegate.)
Handle the notification.
Post the notification (where you previously called the delegate).
Unregister the objects when they're destroyed.

What you would do is agree on a key, probably in a constant.
Keys.h:
extern NSString *MethodOneNotification;

Keys.m:
NSString *MethodOneNotification = @"MethodOneNotification";

Then register in firstViewController and secondViewController like this somewhere like viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self
      selector:@selector(methodOneNotification:) object:nil];

Provide a handler in both firstViewController and secondViewController for the selector:
- (void)methodOneNotification:(NSNotification *)notification {
    NSLog(@"%@ got the notification!", [self class]);
}

Call the notification where you previously called the delegate:
[[NSNotificationCenter defaultCenter] postNotificationName:MethodOneNotification
     object:nil];

And in both firstViewController and secondViewController, you'll want to remove the notification registration (certainly in dealloc):
- (void)dealloc {
    [[NSNotification defaultCenter] removeObserver:self name:MethodOneNotification
     object:nil];
    // [super dealloc] if you're not using ARC, but you should be
}

Within the notification handler, you can access the notification's sender as notification.object. If you need to pass information along with the notification, you can use a different variant of postNotification: that accepts a NSDictionary, then you can access the dictionary as notification.userInfo.
If you need to return values to the object that posted the messages, you'll have to send them back by sending messages to the poster (which you have access to as notification.object). For instance:
- (void)methodOneNotification:(NSNotification *)notification {
    AppDelegate *appDelegate = notification.object;
    [appDelegate returningValue:1];
}

Here, obviously, AppDelegate would need to define and handle -(void)returningValue:(int)value.
You'll need to keep the return value on the class instance. Of course, if you have multiple returns possible, you'll need to collect those in returningValue: with an array. But at least you've skipped circular references.
The other way to solve this is with blocks. That would double the size of this answer, though. :) Bottom line, though: The delegate pattern is the wrong pattern for this problem. Luckily, the others are easy to pick up.
Comment: Thanks for replying, please tell me what to do if I also have to return values.
Comment: Updated answer with one way to do so.
Comment: you are welcome :) ... please explain in detail regarding this "but then you need to deal with potential circular references."
Comment: I provided a bit of context, but I don't want to drag the answer too far off the main thrust of it. Is that sufficient?
Comment: yes it is, I also thank you for helping me, please read this you will like it https://github.com/robbiehanson/XMPPFramework/wiki/MulticastDelegate , you are more experienced you will get it quickly, but I am having difficulty understanding this and thats what I am pursuing :)
Answer: In your case is enough to hold an array with all delegates, by holding an array of delegates, possibly as a private property, and allowing to add/remove delegates:
@interface AppDelegate() // .h file

@property (nonatomic,strong,readwrite) NSMutableArray* delegates;

@end

// .m file

- (void) addDelegate: (id<MyProtocol>) delegate // By convention the first letter should be capital.
{
    // Optional code you may need to execute before adding it.
    [delegates addObject: delegate];
}

I leave to you the removeDelegate method, it's very simple to implement.
How to call the delegates methods
It's enough to call the selector on every object:
[delegates makeObjectsPerformSelector: myProtocolMethodOne];

If you need to take return values it's better to do it this way:
NSMutableArray* returnValues= [NSMutableArray new];
for(id<MyProtocol> delegate in delegates)
{
    id result= [delegate myProtocolMethodTwo]; // Method returning a value
    [returnValues addObject: result];
}

How to add the delegates
In every controller (up to N times) you should be able to add it:
AppDelegate *ad = (AppDelegate*)[[UIApplication sharedApplication]delegate];
[ad addDelegate:self];

Additional problem: You may want to have weak delegates, but a NSArray holds strong references. Here you can find a nice solution for this:
NSArray of weak references (__unsafe_unretained) to objects under ARC
It basically says to use NSValue to store weak reference using the valueWithNonretainedObject method.
Comment: my confusion point is how it will work, in appDelegates its like [mypDelegate myProtocolMethodOne]; means who ever implements the protocol should respond so only one is responding. Please help me out in this.
Comment: I added this part under "How to call the delegates methods".
Comment: if I iterate its like [objectAtIndex0InArray myProtocolMethodOne] ?
Comment: You can't ignore the circular reference problem by breaking the circle in `dealloc`: if there's a circular reference the `dealloc` method will never be called. That's why it's a problem at all. :)
Comment: Following Ramy's answer, it's a good idea to store references to the delegates in a data structure, and you would solve the strong reference issues by using an `NSHashTable`.

See the implementation here:
http://arielelkin.github.io/articles/objective-c-multicast-delegate/

Objective-c multicasting delegates


Remover classes recursivamente

Question: Cenário teste
Tenho um menu, com sub-itens, em que cada sub-item é um link:

        Tab 1

            Opção 1 Tab 1
            Opção 2 Tab 1

        Tab 2

            Opção 1 Tab 2
            Opção 2 Tab 2

        Tab 3

            Opção 1 Tab 3
            Opção 2 Tab 3

Funcionamento
Cada sub-item, é um link com uma ação JQuery, e essa ação ao ser disparada deve adicionar a classe active na aba raiz (até aqui sem problema).
O problema, é saber de qual a "aba anterior" para remover a classe active.

Dúvidas

Gostaria de saber, é se existe uma forma no JQuery que remova de forma recursiva, qualquer elemento que tenha a classe active, nesse caso.

Algo do tipo $('#MenuTabs').removeClass('active'), mas que pegue todos elementos dentro do elemento id="MenuTabs".
Comment: Não seria apenas `$('#MenuTabs .active').removeClass('active')`?
Comment: @AndersonCarlosWoss Exatamente isso professor! Muito obrigado!
Answer: Basta você fazer:
$('.active').removeClass('active');

Isso removerá a classe active de qualquer elemento que possuí-la.
Caso queira limitar a árvore de busca para evitar conflitos com o restante da página, você pode utilizar do seletor CSS que define o elemento root: root .active, assim buscará apenas elementos com a classe .active dentro de root. Considerando o elemento pai como #MenuTabs, bastaria fazer:
$('#MenuTabs .active').removeClass('active')

Remover classes recursivamente


Why does the author play C and E on this sheet music?

Question: Looking at this sheet music, I would have played E and G but he plays C and E. Is there something I don't understand?

Thanks
Reference :
Comment: It's probably just a mistake in the sheet music.
Comment: I'm voting to close this question because "why did [anyone] choose to do [anything]" is too speculative to answer.
Comment: Because no one is actually obligated to play exactly what's written; they can change notes if they want and no one will arrest them. That's especially true if you're the composer. A separate (more useful?) question is "Which version is 'right,'" or "which version should I use." In this case, the played version seems more likely, since it provides the entire C chord instead of doubling the fifth.
Comment: Well technically it's his own sheet music so it's most probably a mistake since there would be no reason why somebody would record themselves on youtube and proposing to buy the sheet music if the sheet music isn't the same as one the youtube video. Anyway! Thanks for confirming guys.
Comment: @Guest That clarifies things. This is extremely common — the YouTube performer records a piece, then later writes it down, near always with mistakes. There is plenty of Q&A on this site where others have encountered the same propblem.
Comment: You're correct, the sheet music doesn't correspond to the first notes of the recording.
Answer: In this case, the video confirms that it's a misprint.  It's C and E.
E and G would be musically possible, but unlikely, if only because the right hand is already playing the G.
Answer: It is most likely simply a stylistic choice. The general chord this section is built around appears to be C major, so playing C and G is a perfectly reasonable (if not BETTER) choice to make. In the future, however, realize that sheet music is not an end all be all. The answer to your question is quite honestly "why not".
Answer: To elaborate a bit on Laurence's answer, there are several questions on this site concerning keyboard music that appears to call for the same note to be played simultaneously by both hands (or by one hand while the other is holding it down having already played it), so this isn't per se a red flag.  In those cases, however, it's because of a desire to show that the same note belongs to two different musical ideas that happen to overlap at that point.  In this case, the left hand part especially is not particularly melodic.  Furthermore, the instruction "with ped" means that the G will not sound any different whether it is held as a quarter note or a half note.
In this case, as it is an arrangement, I would tend to view the original as "correct."  If you listen to the soundtrack (for example in the trailer, below), you'll find that there's definitely a C in the first chord.
Comment: I think usually when I see this happen in sheet music, one of the parts will have the note-head in parentheses, just to indicate "Yeah, the other hand's got this."  An exception might be when it's music scored for an organ, harpsichord, or other instrument with multiple manuals, in which case you can hit the note with both hands at once.


Os navegadores armazenam o arquivo .htaccess em cache?

Question: Escrevi uma expressão regular para fazer com que o site seja sempre redirecionado para o protocolo HTTPS. Porém, não é possível usar HTTPS no localhost. Para conseguir acessar, eu transformei as linhas responsáveis pelo redirecionamento em comentários e, antes de finalmente colocar as edições no ar, desfazer essas alterações no .htaccess para que o redirecionamento seja feito.
Minha dúvida é: o navegador salva o arquivo .htaccess em cache? Pois quando transformei as linhas em comentários e atualizei a página, continuava redirecionando para HTTPS, e quando desabilitei o cache através do DevTools do Chrome, o redirecionamento não foi mais feito.
Comment: já parou pra pensar que o cache é feito no seu navegador ?
Answer: Não o navegador nem tem acesso a esse arquivo, ele é uma forma de configurar o Apache no seu servidor, o que acontece é que o navegador faz uma requisição para seu servidor, por exemplo:
GET http://dominio.com

E armazena a resposta em cache, quando é feita uma segunda requisição igual o navegador nem chega a completar a requisição, em vez disso ele já retorna com aquilo que está em cache, ou seja, as mudanças no arquivo .htaccess no servidor nem foram "usadas" (não foi feito uma nova requisição, foi usado o cache), o navegador sequer sabe que houve uma mudança, e usa a versão antiga
Quando você limpa o cache, o navegador apaga aquela resposta do GET http://..., então a próxima requisição não é interrompida e realmente chega ao servidor que responde com um novo conteúdo, no seu caso o redirecionamento


No write permission for Wordpress under Nginx in CentOS 7

Question: I have a CentOS 7 machine with Nginx running and the user is "nginx" (tghe default one in CentOS). I've installed Wordpress, which is working perfectly, and I've give wrtite permissions for nginx user in the wordpress folder and subfolders (775), but a still get a permission error:

Unable to create directory wp-content/uploads/2015/05

I double checked which user is running nginx worker processes and it is nginx.
It must be something trivial that I missed. Can someone help me?
EDIT:
I noticed this in /var/log/nginx/error.log:

2015/05/03 20:42:41 [error] 23652#0: *1 FastCGI sent in stderr: "Unable to open primary script: /usr/share/nginx/html/index.php (No such file or directory)" while reading response header from upstream, client: XXX.XXX.XXX.A, server: XXX.XXX.XXX.B, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm/php-fpm.sock:", host: "XXX.XXX.XXX.B"
2015/05/03 20:44:18 [error] 23652#0: *3 FastCGI sent in stderr: "Unable to open primary script: /usr/share/nginx/html/wp-admin/admin-ajax.php (No such file or directory)" while reading response header from upstream, client: XXX.XXX.XXX.A, server: XXX.XXX.XXX.B, request: "POST /wp-admin/admin-ajax.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php-fpm/php-fpm.sock:", host: "XXX.XXX.XXX.B", referrer: "http://XXX.XXX.XXX.B/wp-admin/"
2015/05/03 21:02:54 [emerg] 23803#0: getpwnam("http") failed in /etc/nginx/nginx.conf:6

EDIT 2
$ ps -elf|grep nginx
1 S root      2045     1  0  80   0 - 27393 sigsus 15:46 ?        00:00:00 nginx: master process /usr/sbin/nginx
5 S nginx     2049  2045  0  80   0 - 27503 ep_pol 15:46 ?        00:00:00 nginx: worker process
5 S nginx     2050  2045  0  80   0 - 27503 ep_pol 15:46 ?        00:00:00 nginx: worker process
5 S nginx     2051  2045  0  80   0 - 27503 ep_pol 15:46 ?        00:00:00 nginx: worker process
5 S nginx     2052  2045  0  80   0 - 27503 ep_pol 15:46 ?        00:00:00 nginx: worker process

The server configuration file is:
server {
    listen       80;
    server_name  XXX.XXX.XXX.B;

    location / {
        root   /var/www/wordpress;
        index index.php index.html index.htm;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    error_page 404 /404.html;
    location = /404.html {
        root /usr/share/nginx/html;
    }
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        root /var/www/wordpress;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

As for the nginx configuration file:
user  nginx;
worker_processes  4;

error_log  /var/log/nginx/error.log;

pid        /run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;

    keepalive_timeout  65;

    index   index.html index.htm;

    include /etc/nginx/conf.d/*.conf;

    server {
    listen       80 default_server;
    server_name  localhost;
    root         /usr/share/nginx/html;

    include /etc/nginx/default.d/*.conf;

    location / {
    }

    error_page  404              /404.html;
    location = /40x.html {
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
    }
    }
}

Comment: Did you check SELinux?
Comment: Well, I checked the logs, nothing that I could tell.
Comment: Please post the nginx configuration...
Comment: You say that you are using the 'nginx' user, but your logs suggest that it is the user named 'http' that it is trying to run as.
Answer: It isn't the user nginx is running as that is important, but it is the user php-fpm is running as. After all, it is PHP-FPM that executes the PHP scripts, and WordPress is running under privileges that the PHP-FPM running user has.
So, check that your upload directory can be written by the user running PHP-FPM.
Comment: I checked the configuration file of PHP-FPM and it was set to apache. I corrected it setting the user and group to nginx and still got the same error message.
Comment: The owner of the configuration file does not matter. You have to check which is the user that is used to run the PHP-FPM process, and make sure that the particular user can write to the directory.
Comment: This was the solution, but because of previous changes I did, I do not noticed untill I undid them. Thank you.


C - reading from file (pretty simple)

Question: I have this code where I want to read from a text file each line and then print it to the standard output. For no reason it only saves the last line of the file in that array of chars.
Any tips why(some explanations are)?
  9 int main(){
 10     FILE * f;
 11     char buffer[255];
 12     char * arr[255];
 13     int i=0,n;
 14
 15     f = fopen("input.txt", "r");
 16     while(1){
 17         if(fgets(buffer,255,f) != NULL ){
 18             arr[i++] = buffer;
 19         }else break;
 20     }
 21     n=i;
 22     for(i=0;i<n;i++){
 23         printf("%s",arr[i]);
 24     }
 25
 26     fclose(f);
 27     return 0;
 28 }

Answer: Your program only has one one buffer that gets overwritten with each line of the file
EDIT:
char* buf;
while(1){
   buf = malloc(255);
   if(fgets(buf,255,f) != NULL ){
        arr[i++] = buf;
    }
    else break;
}

Comment: arr[i] only gets a pointer to buffer.  so in the end, every entry in arr just contains the address of buffer, and buffer contains the last line of the file
Comment: you could allocate a new buffer for each call to fgets, then store that pointer in arr[i]
Comment: @nickNatra, not sure what you mean.  set what to null?
Comment: @nickNatra, you don't need to copy anything.  Your issue is that you haven't allocated memory for your strings.  arr[] just holds space for pointers to strings, not the strings themselves
Comment: You need to strcpy the contents I think to the arr[] and before that allocate memory.
Comment: then I have to save each time for each buffer read char by char?
Comment: or can i set it to null on each step? (yes/no)
Comment: the buffer,
something like
`arr[i++]=buffer;
buffer= null;
`
Comment: ok, i'm dumb; i guess the sollution will be to copy each char from the buffer to the array then?
Answer: char * arr[255] is a pointer to an array of 255 characters. When you assign arr[i] = buffer you are making the pointer point to buffer for each element of your (unallocated) array. Therefore every element will point to the same char buffer[255], which will have only the last line in it by the time you get to printing.
Answer: Here:
#include <cstdlib>
#include <string.h>

int main(){
  FILE * f;
  char buffer[255];
  char * arr[255];
  int i=0,n;

  f = fopen("c:\\temp\\input.txt", "r");
  while(1){
     if(fgets(buffer,255,f) != NULL ){
         arr[i] = (char *) malloc(255 * sizeof(char));
         strcpy(arr[i++], buffer);
     }else break;
 }
 n=i;
 for(i=0;i<n;i++){
     printf("%s",arr[i]);
 }

 fclose(f);
 for (int j=0; j<i; j++)
     free(arr[j]);
 return 0;
}

Answer: You never increment i.  In your reading loop you save to 0 then i++.  But it doesn't save the new i value into i.  So your i is 0 for your next iteration.  You need to add "i = i + 1" after "arr[i++] = buffer;"
Comment: And the i++ is not needed in the "arr[i++] = buffer;"  it should be "arr[i] = buffer;"

C - reading from file (pretty simple)