Awk command unexpected newline or end of string

Question: I'm trying to find what sort of value in ${RESULT} as used in this script;
#!/bin/ksh
...
echo ${RESULT}|awk '{if ($0 ~ /RUNNING mode/) {print "STATUS=0"; print "PID="'${PID}'; print "INFO="$0; print '$PID' > "'${INSTALLDIR}/domain'/sample_pid.txt"} else {print "STATUS=1"; print "PID=-1"; print "INFO="$0} }'

Could cause this output:
awk: cmd. line:1: {if ($0 ~ /RUNNING mode/) {print "STATUS=0"; print "PID="27708
awk: cmd. line:1:                                                              ^ unexpected newline or end of string

I've tried throwing many combinations of special characters into ${RESULT} and it never has issues.  I'll probably rewrite the command anyway but I am curious about what ${RESULT} could be both as an educational point and also to help me reproduce the error that was reported to me from a test system, which I haven't otherwise been able to reproduce.
Thanks!
Comment: You can easily debug it. Use the standard way to pass shell variables to awk, not like this. See: https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script `-v pid="$PID"` etc
Answer: Your code has issues with how to call shell variables in awk + redundant use of functions (e.g. print). Keeping awk code like awk '.........' Input_file is what is recommended. You could take the following as a start, but since no samples were given, I have not tested it at all; it's completely based on the attempt by OP.
Also whenever you are writing output to a output file it's better to place output file name in (output file name)
echo "$RESULT" |
awk -v installdir="${INSTALLDIR}/domain" -v pid="$PID" -v outfile="sample_pid.txt" '
{
  if ($0 ~ /RUNNING mode/){
     print "STATUS=0\nPID=" pid "\nINFO="$0 >  (installdir"/"pid"/"outfile)
  }
  else{
     print "STATUS=1\nPID=-1\nINFO="$0
  }
}'


GoogleSheets, gostaria que toda vez que eu preenchesse uma célula ela ficasse maiúscula

Question: Possuo essa function, porém ela só funciona quando eu executo ela, gostaria que ao dar o input na célula ela já funcionasse sem precisar executar a todo momento.
function myFunction() {
var ss=  SpreadsheetApp.getActiveSpreadsheet().getSheetByName("sheets");
for (var i=2;i<=1000;i++){
var range = ss.getRange(i,5);
var value = range.getValue();
range.setValue(value.toUpperCase())
}
}
Answer: Acesse Extensões / Apps Script. Em Arquivos, clique no "+" e depois cole o código abaixo:
<code>function onEdit(e) {
  if (typeof e.value != 'object') {
    e.range.setValue(e.value.toUpperCase());
  }
}
</code>
O qual interpretará todas as edições e converterá para maiúscula. Veja se assim te atende.
Comment: Cara muito obrigado, funcionou só estava com um delay, você é o cara!
Obrigado!!!!!!!!!!!!!!!!!!!!!!
Comment: Não preciso apontar a sheet nem a coluna?
Comment: Ocorreu um erro ao executar o cógio: Erro TypeError: Cannot read property 'value' of undefined
Comment: Não é para executar ali. É só colocar o script onde foi indicado, salvar e fazer o teste na planilha
Comment: Exemplo: https://docs.google.com/spreadsheets/d/1-FTI3r34u7aGPNwUc17b0AngXZGNydpgeJFWaXvmWD4/edit?usp=sharing
Comment: Aí na planilha, só vc digitar e teclar enter ou tab e a mágica acontece


Is really "No Public Class" reachable within its package?

Question: In "Think in Java", the author says:

You just leave the "public" keyword off the class, in which case it has package access. (That class can be used only within that package.)

To prove this, I create one public class and one no-public class:
package com.ciaoshen.thinkinjava.chapter7;
import java.util.*;

//My public class
public class PublicClass {
    //default constructor
    public PublicClass(){
        System.out.println("Hello, I am PublicClass.");
    }
}

//Non public class
//It should be package reachable
class PackageReachableClass {
    //default constructor
    PackageReachableClass(){
        System.out.println("Hi, I am PackageReachableClass.");
    }
}

But when I call them from another class in the same package:
public class InPackageClass {

/**
 *  MAIN
 *  @param args void
 */
public static void main(String[] args){
    //pubic class can be reached from anywhere
    PublicClass newPublicClass=new PublicClass();
    //non-public-class should be accessable in the same package
    PackageReachableClass newPackageReachableClass =new PackageReachableClass();
}
}

The system warning me: The no-public class should not be accessed from outside its own source file.
/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
        PackageReachableClass newPackageReachableClass =new PackageReachableClass();
        ^
/Users/Wei/java/com/ciaoshen/thinkinjava/chapter7/InPackageClass.java:22: warning: auxiliary class PackageReachableClass in ./com/ciaoshen/thinkinjava/chapter7/PublicClass.java should not be accessed from outside its own source file
        PackageReachableClass newPackageReachableClass =new PackageReachableClass();
                                                            ^
2 warnings
Hello, I am PublicClass.
Hi, I am PackageReachableClass.

So here comes my question: Is the no-public class still package reachable? And why Java forbid us to call them from another file in the same package if this is totally legal?
Comment: It's a warning. That means you _can_ do it, but it might indicate you're doing something wrong.
Comment: Is `PackageReachableClass` in it's own file, e.g. `PackageReachableClass.java`?
Comment: Just put this `PackageReachableClass` into PackageReachableClass.java file
Comment: @cricket_007 No, `PackageReachabelClass` and `PublicClass` are in the same file called `PublicClass.java`.  And I am trying to call them from another file `InPackageClass.java` .
Comment: **Is the no-public class still package reachable?** Just try it? **And why Java forbid us to call them from another file in the same package** It doesn't?
Comment: In one file there can only be one public class which is the same as the name of the file. The reason you see the warning is because you have the package private class in the same file as the public class. Do what @Antoniossss suggested, and you'd see the expected behaviour.
Comment: @khelwood  Is that means put several no public class in a single file is not an appropriate  style?
Comment: @Antoniossss yeah, when I put it into a new file, the warning is gone.
Comment: @RahulSharma So put everything in a single file is not a good practice? And we should always create a new `.java` file for each single class right?
Comment: By convention every public, nonstatic class of name "X" must be placed into separate X.java file
Answer: It is only a warning that you have defined an auxiliary class.

auxiliary class PackageReachableClass in PublicClass.java

Which means you have one Java file with 2 classes, which is against Java Code Conventions. (Emphasis mine).

Each Java source file contains a single public class or interface. When private classes and interfaces are associated with a public class, you can put them in the same source file as the public class. The public class should be the first class or interface in the file.

To correctly test your package-private classes, please separate the two classes into separate files based on their class name, i.e. PublicClass.java and PackageReachableClass.java.
Comment: Don't duplicate answers. Add to the existing answer in the duplicate instead if you have something new to add.
Comment: This question was about package-private. That answer was about auxiliary classes. This answer is how to interpret the warning and mitigate it. Therefore, I don't think it's a duplicate.
Comment: The question is misguided because of incorrect (or misleading) example code to start with. Once that example code is "fixed", there is no confusion left. Hence, the question is answered by resolving the confusion. And all of that is still no reason to duplicate the answer.
Comment: Thanks for your answers guys. I just did't find the same question with such a title "What are auxiliary class" :p
Comment: @weiShen really? Because googling "auxiliary class" gives that as exact first result. Google your errors/warnings for future reference.
Comment: @weiShen The exact phrase I searched was from your "warning: auxiliary class in"
Comment: @JeroenVannevel haha, but at that moment, I did't know that calls "auxiliary class" XD
Comment: @weiShen it's literally in the warning message.
Comment: @cricket_007  so I searched for something like "package-private class" or "no-public class".  Actually I am reading "Thinking in Java", and the author did't mention that "auxiliary class" is a bad coding style. Any way, thx for yr answer:)
Comment: @weiShen it is not "bad practice" to have aux classes, only to write your code that way, that they are accessed but the code from outside of main class context

Is really “No Public Class” reachable within its package?


Maping data in React and want toggle specific button

Question: I can't toggle a particular button. I want to toggle that particular button in an array of buttons. Here is demo code link. Please correct it and share solved problem.
Code
import { useState } from 'react';
import { data } from './data';
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    toggle: true,
    index: ''
  })

  const onJoin = () => {
    setState({
      ...state,
      toggle: !state.toggle
    })
  }

  const onRequest = () => {
    setState({
      ...state,
      toggle: !state.toggle
    })
  }
  return (

      {data.map(data => {
        return(

{data.name}

          {state.toggle ?
          <button onClick={() => onJoin()}>Join</button>
          :
          <button onClick={() => onRequest()} >Request</button>
        }

)
      })}

  );
}

Answer: Issue
You are using one state variable for all buttons. You need an array to keep track of which buttons are toggled
Solution
Instead of making toggle a boolean, make it a boolean array.
Working Codesandbox
Code
import { useState } from "react";
import { data } from "./data";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    toggle: [],
    index: ""
  });

  const onJoin = (index) => {
    setState((state) => ({
      ...state,
      toggle: state.toggle.filter((t) => t !== index)
    }));
  };

  const onRequest = (index) => {
    setState((state) => ({
      ...state,
      toggle: [...state.toggle, index]
    }));
  };
  return (

      {data.map((d, index) => (

{d.name}

          {state.toggle.includes(index) ? (
            <button onClick={() => onJoin(index)}>Join</button>
          ) : (
            <button onClick={() => onRequest(index)}>Request</button>
          )}

      ))}

  );
}

Comment: Thanks..
So there is no need of index in state which is already declare?


Como recuperar o click em uma matriz de botões

Question: Estou fazendo um campo minado, logo tenho que adicionar uma matriz de botões em um painel(para serem as casas). Criei a matriz de botões e adicionei cada botão[x][y] em um painel. Porém não sei como faço para recuperar o click em um determinado botão[x][y] dentro da minha matriz. Sei apenas gerar o evento para um botão, não sei como posso "generalizar" para os demais, para que, por exemplo, quando o botão[2][3], dentro da minha matriz for clickado eu receba um "botao[2][3] foi clickado" ou "as posições clickadas foram x = 2, y =3".
Sei que parece uma pergunta óbvia, mas é que iniciei hoje em C#.
Obrigado.
Comment: Tem mais de uma maneira de resolver esse problema. Acho que fica mais fácil responder a sua pergunta se você desse um exemplo do código que você tentou usar (apode fazer algo simplificado que só imprime uma mensagem na tela mesmo)
Answer: Você pode utilizar um único evento gerado para todos os botões e dentro desse evento você verifica quem o disparou, algo desse jeito:
private void botoes_Click(object sender, EventArgs e)
{
    Console.WriteLine(((Button)sender).Name); // imprime no Console o nome do botão clicado
}

Nesse caso o sender irá referenciar o componente que realizou o evento Click, caso você precise de alguma informação específica, você pode colocá-la na propriedade Tag de cada botão e posteriormente acessá-la assim ((Button)sender).Tag


Show that $r$ is a primitive root (mod $p^k$)

Question:
Let $p$ be an odd prime, and let $r$ be a primitive root (mod $p$) such that $r^{p-1} \not\equiv 1$ (mod $p^2$). Show that $r$ is a primitive root (mod $p^k$) for all $k \geq 1$.

So I start of by computing that $\phi(p^k)$ $=p^{k-1} (p-1)$. Now, if $r^x = 1 $ (mod $p^k$) then $r^x = 1$ (mod $p$), and since $r^{p-1} = 1$ (mod $p$), we get that $(p-1) | x$ from basic properties of the order of a integer. The order of $r$ (mod $p^k$) must hence be on the form $p^j (p-1)$, $j < k$.
I need help to prove that $j = k-1$.
Answer: Lemma: $a\in\mathbb Z$ is a primitive root mod $n\ge 2$ if and only if $\gcd(a,n)=1$ and $$q\mid \phi(n)\implies a^{\phi(n)/q}\not\equiv 1\pmod{n}$$
(here $q$ is prime). In your case, you're given that $p$ is an odd prime, $r$ is a primitive root mod $p$ and $r^{p-1}\not\equiv 1\pmod{p^2}$.
I.e. you're given that $p$ is an odd prime, $\gcd(r,p)=1$ and $q\mid p-1\implies r^{(p-1)/q}\not\equiv 1\pmod{p}$ and $r^{p-1}\not\equiv 1\pmod{p^2}$.
You want to prove that if $k\ge 2$, then $\gcd\left(r,p^k\right)=1$ and $r^{p^{k-2}(p-1)}\not\equiv 1\pmod{p^k}$ and $r^{p^{k-1}(p-1)/q}\not\equiv 1\pmod{p^k}$ for all prime divisors $q$ of $p-1$.
$\gcd\left(r,p^k\right)=1$ is clear, because $\gcd(r,p)=1$.
$r^{p^{k-1}(p-1)/q}\not\equiv 1\pmod{p^k}$ is clear, because if $r^{p^{k-1}(p-1)/q}\equiv 1\pmod{p}$, then, since $r$ is a primitive root mod $p$, we get $p-1\mid p^{k-1}(p-1)/q\iff p-1\mid (p-1)/q$ (because $\gcd(p-1,p^{k-1})=1$; see Euclid's Lemma), contradiction.
In order to prove $r^{p^{k-2}(p-1)}\not\equiv 1\pmod{p^k}$, we'll use induction. If $k=2$, then it's true (because it's given that $r^{p-1}\not\equiv 1\pmod{p^2}$). If it's true for some $k\ge 2$, then we'll prove it's true for $k+1$.
I.e., if $r^{p^{k-2}(p-1)}\not\equiv 1\pmod{p^k}$ for some $k\ge 2$, then we'll prove $r^{p^{k-1}(p-1)}\not\equiv 1\pmod{p^{k+1}}$.
We can prove the contrapositive. I.e., if $r^{p^{k-1}(p-1)}\equiv 1\pmod{p^{k+1}}$ for some $k\ge 2$, then $r^{p^{k-2}(p-1)}\equiv 1\pmod{p^k}$.

Let $r^{p^{k-2}(p-1)}=a$. Then you want to prove that if $k\ge 2$, then $$a^p\equiv 1\pmod{p^{k+1}}\implies a\equiv 1\pmod{p^k}$$
There are two ways to prove this:
$1)\ $ Remember $a^p-1=(a-1)\left(a^{p-1}+a^{p-2}+\cdots+1\right)$.
By Fermat's Little theorem $a\equiv 1\pmod{p}$. Let $a=pk+1$. Then it's enough to prove that $$p^2\nmid a^{p-1}+a^{p-2}+\cdots+1$$
$$=(pk+1)^{p-1}+(pk+1)^{p-2}+\cdots+1$$
Use the Binomial theorem:
$$\equiv ((p-1)pk+1)+((p-2)pk+1)+\cdots+((p-p)pk+1)\pmod{p^2}$$
$$\equiv (-pk-2pk-\cdots-ppk)+p\equiv p\left(\frac{-kp(p+1)}{2}+1\right)\equiv p\not\equiv 0\pmod{p^2}$$
$2)\ $ By Fermat's Little theorem $a\equiv 1\not\equiv 0\pmod{p}$, so by Lifting The Exponent Lemma (LTE): $$\upsilon_p\left(a^p-1\right)=\upsilon_p(a-1)+\upsilon_p(p)=\upsilon_p(a-1)+1$$
$$\upsilon_p\left(a^p-1\right)\ge k+1\iff \upsilon_p(a-1)\ge k$$


Why do Chinese auto path URLs become something else?

Question: I have a Drupal 7 site with i18n on it. There are lots of languages. The problem is that if you save a node that is in Chinese, and you select auto path, then the title that was, for example, /空氣清淨機 will be changed to /kong-qi-qing-jing-ji.
What exactly is this process called? Is it an "English alphabet" version of the Chinese text?
Comment: It is pinyin 拼音.. I think it is understandable for Chinese who speak Mandarin.
Comment: This looks to me like the name of the character's. i guess it's understandable, for those who can read the arabic letters .. On my site, the path is stays in the chinese charters', like the title, can you provide more information about your setup ? - What contenttype translation option did you choose ? (i use activated, with translations and fixed language in the extended language options)
- Do you use chinese simplified as language ?
Comment: We use Simplified Chinese for China, and Traditional for Taiwan. This is happening with both. And you should be able to test it by enabling "pathauto" and saving any node with "automatically generate path alias" checked.
Comment: what translation option do you have selected for the affected contenttypes ?
Comment: @coderama : merci (= FRENCH for 'thank you' ...) for the accept! Sorry it took 3 months to discover your question ...
Answer: The process you are describing in your question is called transliteration.
The reason for what you see happening in your site, might be because you're using the Transliteration module. Here is a quote from its project page:

Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

Here is a sample of what this module does for "file names":

However, it can also be used to transforms an URL like mydomain.com/последние-новости-в-Украине-и-мире in something like mydomain/poslednie-novosti-v-Ukraine-i-mire. To do so, you also need to enable the Pathauto module. After that, go to the Pathauto setting page and check "Transliterate prior to creating alias". For more details on that, refer to "D7 Pathauto transliteration". Attention: this does not "fix" already created aliases (those need to be deleted and recreated).
Note: There is also a transliteration tag on drupal.SE (with only 4 questions using it though ...).


Counting number of consecutive occurences of numbers in a series

Question: I've a series (1 dimension array) of numbers, say 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, ...
Is there an elegant (and preferrably fastest) way of counting the number of consecutive occurences of 1 or 0 before it changes? So for this the result would be (0, 2), (1, 3), (0, 1), (1, 4), ...
Comment: Don't think you can do better than O(n)
Comment: @ThomasKowalski, then just the elegant:) Because it's always possible to iterate, counting and keeping the value of the current item, but maybe there's a combination of ready numpy functions which I haven't found, looking in the docs…
Comment: If either of the posted solutions has worked for you, considering accepting the best among them?
Comment: @Divakar, I don't care about it.
Answer: Here's another with NumPy, specifically making use of array-slicing -
def islands_info(a):
    # Compare consecutive elems for changes. Use `True` as sentients to detect edges
    idx = np.flatnonzero(np.r_[True,a[:-1]!=a[1:],True])

    # Index into input array with the sliced array until second last array to
    # get start indices and the differentiation for the lengths
    return np.column_stack((a[idx[:-1]],np.diff(idx)))

Sample run -
In [51]: a = np.array([0, 0, 1, 1, 1, 0, 1, 1, 1, 1])

In [52]: islands_info(a)
Out[52]:
array([[0, 2],
       [1, 3],
       [0, 1],
       [1, 4]])

If you need the output as list of tuples -
In [56]: list(zip(*islands_info(a).T))
Out[56]: [(0, 2), (1, 3), (0, 1), (1, 4)]

Timings -
Comparing against the other NumPy based one by @yatu -
In [43]: np.random.seed(a)

In [44]: a = np.random.choice([0,1], 1000000)

In [45]: %timeit yatu(a)
11.7 ms ± 428 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [46]: %timeit islands_info(a)
8.98 ms ± 40.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [47]: np.random.seed(a)

In [48]: a = np.random.choice([0,1], 10000000)

In [49]: %timeit yatu(a)
232 ms ± 3.71 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [50]: %timeit islands_info(a)
152 ms ± 933 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Comment: In my setup `islands_info` returns a zip object instead of `[(0, 2), (1, 3), (0, 1), (1, 4)]`. Is this due to different Python version?
Comment: @Brenlla Yeah on Pyth3.x, you need to wrap it with `list()`.
Answer: you could use groupby from itertools
from itertools import groupby
x = [1, 0, 0, 1, 0, 1, 1, 0, 0, 0]
occ = [(i, len([*y,])) for i,y in groupby(x)]

Outputs :
In [23]: [(i, len([*y,])) for i,y in groupby(x)]
Out[23]: [(1, 1), (0, 2), (1, 1), (0, 1), (1, 2), (0, 3)]

Comment: Or (with a little help of more_itertools) simply: `[(i, ilen(y)) for i,y in groupby(x)]`
Answer: Here's a NumPy one for a good performance:
a = np.array([0, 0, 1, 1, 1, 0, 1, 1, 1, 1])

# indexes where changes take place
changes = np.flatnonzero(np.diff(a)!=0)
#include initial and end index
ix = np.r_[0,changes+1,a.shape[0]]
# index the array with changes to check the value in question
# stack with the count of values, taking the diff over ix
np.column_stack([np.r_[a[changes], a[a.shape[0]-1]], np.diff(ix)])

array([[0, 2],
       [1, 3],
       [0, 1],
       [1, 4]], dtype=int64)

Timings:
def yatu(a):
    changes = np.flatnonzero(np.diff(a)!=0)
    ix = np.r_[0,changes+1,a.shape[0]]
    return np.column_stack([np.r_[a[changes], a[a.shape[0]-1]], np.diff(ix)])

def groupby(a):
    return [(i, len([*y,])) for i,y in groupby(a)]

a = np.random.choice([0,1], 10_000)

%timeit groupby(list(a))
# 1.83 ms ± 168 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

%timeit yatu(a)
# 150 µs ± 14.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Comment: Aha, thank you. I'll play with it. Myself was considering something along the lines of https://stackoverflow.com/questions/2652368/how-to-detect-a-sign-change-for-elements-in-a-numpy-array if I subtract 0.5 from the sequence.
Comment: You're welcome! This should perform quite nicely. Trying with a k=10_000 length sequence and takes about 100us @aikipooh
Comment: Still a bit arcane though for my peace of mind (and that of the future users of the codebase) =:P
Answer: I used reduce from functools, groupby shown by Ayoub is probably better (and faster), because this one copies the accumulator each time.
from functools import reduce

l = [0, 0, 1, 1, 1, 0, 1, 1, 1, 1]
p = lambda acc, x : acc[:-1] + [(x, acc[-1][1] + 1)] if acc and x == acc[-1][0] else acc + [(x, 1)]
result = reduce(p, l, [])

print(result)

[(0, 2), (1, 3), (0, 1), (1, 4)]
Comment: Oh my! It's too arcane, and yes, I was hoping for something from numpy to be faster as well (the real sequence shall be around 2k in len).
Comment: This one is very Haskell like, for Python you should definitely go with the other option yes


TreeView com Nodes & Childs através de base de dados SQL

Question: Gostaria de saber como posso popular uma TreeView com Nodes e Childs através de uma conexão de SQL. A conexão já está feita este é o código que tenho para já, mas não funciona pois adiciona apenas uma node que é a primeira da lista.
n01 - ParentNode
n02 - ChildNode
foreach (DataRow dr in tb.Rows)
{
    if (treeView_menus.Nodes.Count > 0)
    {
        if (treeView_menus.TopNode.Tag == dr.ItemArray[1])
        {
            TreeNode node = new TreeNode();
            node.Tag = dr["Id02"];
            node.Text = dr["n02"].ToString();

            treeView_menus.Nodes[dr["n01"].ToString()].Nodes.Add(node);
        }

    }
    else
    {
        TreeNode node = new TreeNode();
        node.Tag = dr["Id01"];
        node.Text = dr["n01"].ToString();
        treeView_menus.Nodes.Add(node);
    }

}

Answer: Eu fiz esse método que uso há alguns anos, e até por isso ainda utilizava um DataTable como entrada dos dados, se fosse fazer novamente, utilizaria uma List de um objeto. Seria mais fácil.

Você pode aproveitar a lógica de preencher a treeview, mas recomendo não utilizar DataTable e adequar para uma lista tipada.

public static void PreencherMenu(DataTable dtMenu, TreeView tree)
{
    if (tree != null)
    {
        tree.Nodes.Clear();

        dtMenu.DefaultView.Sort = "nivel, ordem";
        dtMenu = dtMenu.DefaultView.ToTable();

        foreach (DataRow r in dtMenu.Rows)
        {
            string nome = r["nome"].ToString();
            string pai = r["pai"].ToString();

            TreeNode t = new TreeNode(r["texto"].ToString());
            t.ImageKey = r["img"].ToString();
            t.SelectedImageKey = r["simg"].ToString();
            t.Name = r["nome"].ToString();
            t.Text = r["texto"].ToString();
            t.Tag = String.IsNullOrEmpty(r["tag"].ToString()) ? null : r["tag"].ToString();

            if (String.IsNullOrEmpty(pai))
            {
                tree.Nodes.Add(t);
            }
            else
            {
                TreeNode[] parent = tree.Nodes.Find(pai, true);
                if (parent.Length != 0)
                {
                    parent[0].Nodes.Add(t);
                }
            }

        }
    }
}

A tabela de entrada, deve ter o seguinte formato:
DataTable dt = new DataTable();

dt.Columns.Add("texto"); //Texto de Exibição do item
dt.Columns.Add("nome");  //Nome do item (chave) deve ser único
dt.Columns.Add("pai");   //Nome do item pai do item atual, se não houver um pai, informar null
dt.Columns.Add("img");   //Index de uma imagem a ser usada em um imagelist associado ao controle
dt.Columns.Add("simg");  //Index de uma imagem a ser usada em um imagelist associado ao controle (quando o item for selecionado)
dt.Columns.Add("tag");   //Tag associada ao item
dt.Columns.Add("nivel", typeof(Int32));//Nivel do item (0 = Raiz)
dt.Columns.Add("ordem", typeof(Int32));//Ordem que o item deve aparecer

dt.PrimaryKey = new DataColumn[] { dt.Columns["nome"] };

Exemplo de um menu Cadastro:
dt.Rows.Add(new object[] { "Cadastros", "cadastros", null, "Folder-Close.png", "Folder-Open.png", null, 0, 1 });

dt.Rows.Add(new object[] { "Pessoas / Convênios", "pessoas", "cadastros", "Clients-icon.png", "Clients-icon.png", null, 1, 1 });

Comment: Obrigado pela resposta, vou ver o que consigo fazer. :)


(Newbie question) Something goes wrong here with db_add_field

Question: I'm trying to adapt that D6 module to D7.
I'm on the "add afield" part of .install
Here's my code :
function node_statistics_install() {
    db_add_field('accesslog', 'nid', array(
    'description' => 'Field added by node_statistics',
    'type' => 'int',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'length' => 11,
    'default' => 0,
  ));

but nothing happens in the database on install, no errors in drupal logs...
Am I missing something?
Comment: have you reviewed http://api.drupal.org/api/drupal/includes!database!database.inc/function/db_add_field/7
Comment: check if accesslog table exists in your database.
Answer: First, make sure that Statistics module installed/enabled.
Second, replace your code with the following code:
function node_statistics_schema_alter(&$schema) {
  // Add field to existing schema.
  $schema['accesslog']['fields']['nid'] = array(
    'type' => 'int',
    'length' => '11',
    'default' => '0',
    'not null' => TRUE,
    'unsigned' => TRUE,
    'description' => 'Field added by node_statistics',
  );
}

function node_statistics_install() {
  $table = 'accesslog';

  $schema = drupal_get_schema($table);

  db_add_field($table, 'nid', $schema['fields']['nid']);
}

Note: make sure to uninstall and install your module after you apply the new code.


Visual Studio C++ static lib function exposing problem

Question: I have created example of using static libraries. The goal is this functionality:

DllTestFunctDll.dll links static_lib.lib (contains fnStaticLibrary())
example.exe links DllTestFunctDll.dll (contains dllTestFunct())
main() calls directly fnStaticLibrary() and dllTestFunct().
dllTestFunct() calls directly fnStaticLibrary().

I don't understand one thing, this works only if fnStaticLibrary() is inside same project as main() and dllTestFunct().
If I create another solution that

DllTestFunctDll.dll links also static_lib.lib (contains fnStaticLibTest())
main() newly also calls directly fnStaticLibTest().
dllTestFunct() newly also calls directly fnStaticLibTest().

dllTestFunct() is able to call fnStaticLibTest() and main() is unable to call fnStaticLibTest() due to linker. But I am able to call fnStaticLibTest() inside dllTestFunct().
I used dumpbin to see what functions are exported:
dumpbin /EXPORTS "C:\\path\\DllTestFunctDll.dll"

Output:
ordinal hint RVA      name
      1    0 00001000 ?dllTestFunct@@YAXXZ = ?dllTestFunct@@YAXXZ (void __cdecl DllTestFunct(void))
      2    1 00001070 ?fnStaticLibrary@@YAXXZ = ?fnStaticLibrary@@YAXXZ (void __cdecl fnStaticLibrary(void))

You can see that fnStaticLibTest() is missing inside the output.
In both static lib projects I export function by "__declspec(dllexport) ".
I assume that the problem is inside the Visual Studio. Do you know how to solve it?
Thank you in advance for your answers.
CODE (VS17 solution) LINK: https://github.com/Ales5475/StaticLibProblemExample
Comment: When it doesn't work, what is the problem you have? What errors or runtime problems do you get? And do your main application link with `static_lib`? If not, why? A DLL is a totally separate entity, it's essentially a specially linked executable. The libraries a DLL links with are separate from the libraries that your application links with.
Comment: This is a side-effect of the way the linker uses static libraries. It only includes function definitions to resolve undefined symbols in the DLL project. The declspec in the declaration is not enough. Since the DLL code does not itself call the function, it has no reason to include the definition and create the export. A simple workaround is to write a dummy call to the function in the DLL source code. Or use the linker's /EXPORT option. Or use #pragma comment(linker, "/export:?fnStaticLibTest@@YAXXZ") in the DLL source.
Comment: As I wrote, my main ampplication link static_lib, but not static_lib2. I unfortunatelly don't know why it is not linking. Maybe here we missunderstood, I will edit question.
Comment: Sorry for the confusion the point is that if .dll links .lib inside solution, .lib function is callable inside .exe. If .dll links .lib from another solution .lib function is callable inside .dll but not inside .exe.
Comment: And how is `static_lib2` involved? And Visual Studio is quite smart, if the library is in your solution, and you reference a function from it, VS probably links with the library for you. If you look at the references, linker settings, and the actual build output (which should show the commands and all arguments) what does it tell you?
Comment: Yeah this is probably the problem, that Visual Studio is doing something what I don't want. I set path to both static libraries in "General"->"Additional Library Directories" and also targets to "Input"->"Additional Dependencies". In "Command line" : /OUT:"C:\path\MainProgram\Release\DllTestFunctDll.dll" /MANIFEST /LTCG:incremental /NXCOMPAT /PDB:"C:\path\MainProgram\Release\DllTestFunctDll.pdb" /DYNAMICBASE "static_lib.lib" "static_lib2.lib" ...
Comment: Should be some specific switch inside build command? I don't know the VS build syntax much.
Comment: can't immediately find a stack overflow duplicate but see https://devblogs.microsoft.com/oldnewthing/20140321-00/?p=1433
Comment: `main() is unable to call fnStaticLibTest() `  Please provide specific error message. Static libraries do not need __declspec(dllexport). And it will be better to upload your minimal reproducible example without personal privacy via Github.
Comment: LNK2001 unresolved external symbol "void __cdecl fnStaticLibTest(void)" (?fnStaticLibTest@@YAXXZ) MainProgram C:\path\MainProgram\MainProgram\MainProgram.obj 1
Comment: I have added code link to the problem. It is comprimed VS17 solution.
Comment: @Alan Birtles It seems that this should be the problem. But how to force VS to link the static library into the .obj or .lib?
Comment: @Hans Passant You are probably right. But I call both libraries function in Dll. Also this "pragma comment" didn't work for both functions. LNK1120 1 unresolved externals
 adn also LNK2001, do you know why? The name is exactly what you wrote me.
Comment: LNK1120 tells you that the #pragma worked.  But you didn't post the function declaration so I had to guess at the mangled name of the function.  Use dumpbin.exe /exports on the .lib file to see it.  Or declare the function `extern "C"` so the name doesn't get mangled beyond recognition.
Comment: @Hans Passant I cannot use the command, because build of .dll failed. Mangled names I solved by adding `extern "C"`.
Comment: May I know if your problem has been solved? I also noticed that mksteve updated his answer.
Comment: @Minxin Yu - MSFT I am still finding right answer. Only one which hardly workds is described by Hans Passant, adding the linker /EXPORT option.  There are also officital several ways https://learn.microsoft.com/en-us/cpp/build/reference/opt-optimizations?view=msvc-170 But a lot of people are complaining that it doesn't work...
Comment: What you're trying to do is the disadvantage of static library. It would be more convenient to design them all as dynamic libraries.
Comment: @Minxin Yu - MSFT I know that this should be possible. But is it possible to implement extern .dll functions inside main code (in .lib it is possible)? I agree that it is probably possible to avoid this problem using another approach (.dll). I selected this approach to avoid a lot of .dll files attached with my program...
Comment: The talk in reply  is beyond the scope of this question. You can use dumpbin to view the functions exported by the dynamic library. But the static library cannot view the export, just use it directly.
Answer: An object module is added from a .lib, if it is required.  If the dll does not call (or reference) any item in a compilation unit (c/cpp file), it won't be added to the dll
This behavior is important for libraries, as it ensures that when linking against the C/C++ runtimes, then you don't import the whole of the libraries.  Just those which are required.
In your case you have a DLL which doesn't require the test function, and a .EXE which expects the DLL to have it.  There is no visible requirement for the test function when the DLL is being built.
Comment: Are you sure, that is true? If I add static library, it should be similar to copy code (.h and .cpp) to the .dll. And if there is `__declspec(dllexport)` before function inside static .lib header, I would expect that this function should be visible. However, why is one static function (inside solution) added and second (outside solution) is not?
Comment: I would like to react to your edit. The both static library functions are also called in function in DLL. Please see the code which I posted in a link.
Answer: A DLL has explicit exports.  Either
__declspec(dllexport)

or a .DEF file with exports.  In this case, it appears that the static lib doesn't know if it is in a DLL or the EXE, so isn't decorated with declspec(dllexport) the best solution is for the .def file for the DLL to explicitly export the function.
The code in StaticLibTest.h
__declspec(dllexport) void fnStaticLibTest();

is inconsistent with the code in StaticLibTest.cpp
void fnStaticLibTest(){

This will not cause the function to be exported.  In general include a file which declares a function / structure to ensure it is consistent.
The correct form is
void __declspec(dllexport) fnStaticLibTest(){

and
void __declspec(dllexport) fnStaticLibTest();

Otherwise you are adding the attribute to the void.
Comment: All static libraries functions have `declspec(dllexport)` before function declaration, as I wrote at problem description bellow. So, from static library definition I would assume that the static library code is just added to .dll and due to this reason it should be accessible from .exe.
Answer: Here is the snippet  I did use  #pragma comment successfully.
DLL:
__declspec(dllexport)   void DllTestFunct();

...
  #pragma comment(linker, "/export:fnStaticLibTest")
  void DllTestFunct() {
    fnStaticLibrary();
    fnStaticLibTest();
    printf("Hello world (Dynamic library)!\n");
    }

DLL's dependency:
Header Folder:
XXX\StaticLibTest\StaticLibTest;
XXX\MainProgram\StaticLibrary;

DLL Folder:
XXX\StaticLibTest\x64\Debug;
XXX\MainProgram\x64\Debug;

DLL  input:
StaticLibTest.lib;
StaticLibrary.lib

Static Lib:
  extern "C" void fnStaticLibTest();
...
extern "C" void fnStaticLibTest() {
    printf("Hello World! (Static library from another project)\n");
}

Comment: Can you share code with me, please. `#pragma comment(linker, "/export:fnStaticLibTest")` always throw linker errors for me (LNK1120 and LNK2001).
Comment: I'm not allowed to upload project. This is all code you need to modify in DLL and StaticLibTest. I am using VS2022(but should have little effect). Try to copy and paste carefully. Also don't forget to input StaticLibTest.lib and
StaticLibrary.lib in DLL properties.
Comment: If these lines are everything what you changed. It doesn't work for me. I have ".h" in C++ dependencies. "*.lib" in Linker Input and path to .lib in linker paths. Also I have question, why is `extern "C"` put after  `__declspec(dllexport)`? And also, why is `__declspec(dllexport)` missing in Static Lib? I think that this should'nt have to work.
Comment: Static libraries do not need __declspec(dllexport), which is used in dynamic libraries.
Comment: Still same problem, I don't know why, but everytimes I add this `#pragma comment(linker, "/export:fnStaticLibTest")`, linker throws error. How did you test that it was working?
Comment: I did not encounter Lnk2001. Only lnk2019, which is caused by incorrect input .
Check which function the error message is about. It will be better to rebuild using the link you provided.
Comment: Different linker errors may be caused by different versions of Visual Studio. But how did you tested that symbol from library in different solution is visible in .exe? Did you call it directly in .exe?


Custom Jekyll Plugin (Liquid Filter?) rendering script tags as text, not as JavaScript

Question: I'm experimenting with building a site using Jekyll for a friend.
I'm trying to transform front matter from files like /_events/2020-02-25-an-event.md and /_events/2020-02-26-another-event.md into something that can be easily embedded into the body of various building blocks of content and result in those pages, as viewed by a visitor, including  tags conforming to schema.org event standards.
A file like /_events/2020-02-25-an-event.md looks like this:
---
layout: event
title: An event
published: true
startdatetime: 2020-02-28
venue: Best Club Ever
---

Members of the events collection are meant to render as individual viewable URLs and should have a snippet of JavaScript hiding in their rendered output like this:

I got that working by writing /_plugins/event_schema.rb as follows:
require 'liquid'

module EventSchemaFilters

  def do_not_use_me_directly_single_json_curly(input_object)
    %Q(
        {
            "@context" : "http://schema.org",
            "@type" : "Event",
            "name" : "#{input_object['title']}",
            "startDate" : "#{input_object['startdatetime']}",
            "location" : "#{input_object['venue']}"
        }
    )
  end

  def event_single_schema_script(input_object)
    %Q(

    )
  end

  def event_multiple_schema_script(input_object_array)
    %Q(

    )
  end

  def event_multiple_schema_script(input_object_array)
    %Q(

    )
  end

  end

Liquid::Template.register_filter(EventSchemaFilters)

And then by writing /_layouts/event.html (which looks up to "page" layout, which looks up to "default" layout) as:
---
layout: page
---

{{ page | event_single_schema_script }}

Unfortunately, if I write /index.md like this, while I get a nice little array of upcoming events, it renders surrounded by ... tags and shows up in the body of the home page:
---
title: Home Page
layout: default
---

# {{ page.title }}

{{ site.events | event_multiple_schema_script }}

The desire is to have this script be part of the DOM's JavaScript ... not part of the text on the page:

Moving {{ site.events | event_multiple_schema_script }} to be the contents of /_includes/event_all_schema_script.html and trying {% include event_all_schema_script.html %} didn't help at all -- same problem.
Removing the call to {% include event_all_schema_script.html %} from /index.md and putting it into /_layouts/default.html instead does render the way I want it to.  But now it's on every page, including pages like https://example.com/events/2020-02-25-an-event/, which is not what I want.  But it does demonstrate that my problem is that I wrote something I can't just "inject" into the markdown of a ... thing ... that's going to become a web page.
Things that also work in /index.md but aren't what I want to do:

Hand-writing  code straight into it
Putting {% include event_all_schema_script_hardcode.html %} into it, where /_includes/event_all_schema_script_hardcode.html is literally just  text copy-pasted from the output I showed all of you.

If only "generators for dummies" material weren't so hard to find (Jekyll documentation isn't very extensive; Google is useless because the phrase "static site generator" is to prevalent), maybe I could write code that would make building such a file at build-time possible?  This seems like a pretty high bar to get over, though., with my current Jekyll/Ruby knowledge.

I'm open to re-architecting this, by the way.  Not attached to the idea of "filtering" things like site.events, etc.  This is just as far as I got in my "hello world."
The only principles I'm really attached to in a final design:

All data entry into the calendar of "events" should be done through the front matter of items in the events collection (so I can get a CMS like Forestry.io or Netlify CMS to play nice with it).
The computation of the contents of the  block should happen in an "independent, insertable component."

I don't want to do a big Liquid loop inside /_layouts/homepage.html that I have to remind a web designer to copy/paste into /_layouts/better_homepage.html.
Instead, I just want to be able to tell a web designer, "Hey, if you want to make a page's metadata include a feed of events, just drop {% include event_all_schema_script.html %} somewhere into it or its layout."
I want {% include event_all_schema_script.html %}, or whatever equivalent people here help me come up with, to work both in the body of pages/posts/collection-markdown and in layouts.

I'm going to take what I learn from this to also write "plain-old DIVs for web designers to style as they see fit" like /_includes/event_all_div.html and /_includes/event_single_div.html, and to let them be used anywhere that the web designer sees fit -- in markdown or in a layout.

Again, I'm not a web designer.  I'm just the data-structure transformation person.  My only goal is to generate nice, "boring" snippets of HTML that are ready for a proper web designer to reuse and style as they see fit.

Any thoughts on how I can improve this attempt at rendering HTML so it will be both layout- and markdown-friendly?
Thanks so much.
Comment: Workaround w/ `/_includes/evnt.json` as `{"@context" : "http://schema.org", "@type" : "Event", "name" : "{{ include.event_name }}"}`, `/_includes/all_evts_script.html` as ``, & `/_includes/single_evt_page_script.html` as `{% if page.collection == 'events' %}{% endif %}`, but still ?? why a function call renders badly in Markdown.
Answer: I can't reproduce your problem but it certainly comes from the fact that Kramdown understands any line with four spaces indentation or more like a standard code block.
If you don't want to process some parts of your markdown files, you can use nomarkdown extension like this :
{::nomarkdown}
     Any indented line or block
{:/nomarkdown}

Another workaround can be to switch to html files for your events.
Comment: If you don't need to add structured content (bellow front matter) to you collection items, just go `.html` extension, this will avoid the indentation glitch with markdown. Otherwise, if you have to include markdown content from netlify cms, you can go with the `nomarkdown` around your plugin code, it will work well.
Comment: Oh, wow, that _(the indentation thing)_ makes so much sense!  Can .HTML files have front matter just like .MD files?  The idea is to use the front matter of the "event" files like values for records in a database _(planning to use Netlify CMS or Forestry.io to let a non-technical person add events to the calendar)_.
Comment: Also, I got so frustrated with this effort yesterday that I ended up using a simple parameterized-include structure and deleted all the code that I wrote.  So I have to find some time to rebuild it all to test whether your suggestion works.  Sorry I can't mark answer as "accepted" right away -- hope to get to that over the weekend!


Comment ID in Comment field

Question: I've added a custom static field to comments. This static field is custom php code but I need to access the specific comment ID using php code in it. So how can I get the comment ID for every comment in the static php field?
Thanks
Answer: In Drupal 7 you can use the below code to get all the comments of a node using node ID
<code> $nid = 2;
 // you can get nid
 // $node = menu_get_object();
  //  $nid = $node->nid;
    $comments = db_select('comment')
              ->fields('comment', array('cid'))
              ->condition('nid', $nid, '=')
              ->execute()
              ->fetchAssoc();
    foreach($comments as $comment) {
        print your comments here
    }
</code>
Also you can check below links
https://api.drupal.org/api/drupal/includes%21common.inc/function/entity_load/7
https://api.drupal.org/api/drupal/modules%21comment%21comment.module/function/comment_get_thread/7
In Drupal 6 you can use the comment_render() ;
Comment: Thanks for your answer. But i need to get a specific ID. Ok let's say that the static php field will display a submission(check) button on every comments. This submission button should send via POST the relative comment ID. How can I do that? Thanks again.
Comment: do you have any specific data by which you want to get cid ?   you can use comment_get_thread() function to get all the comment of a node and then you can get comment id by filtering using comment value(title)
Comment: No. I mean I've added this php "button" as a field on every comment and I need to get the cid of the comment the button is on(something like a Token to access). I don't know if I've been clear, my english is not the best in the world. But thanks again for your help.
Comment: Sorry I left your comment unreaded. With the title, the problem is the same: how can I get the single comment title in php(the static field php) programmatically to filter the cid?
Comment: $subject ='comment title';                           $comments = db_select('comment')
              ->fields('comment', array('cid'))
              ->condition('subject', $subject, '=')
              ->execute()
              ->fetchAssoc();
    foreach($comments as $comment) {
        print your comments here
    }
Comment: here you will get the comment id by using comment title
Comment: Ok probably my english is not so good. $subject should be dynamic, should change on every comment. There isn't any specific 'title', I should access the title of the comment on which the static field is (repeated on every comments). Let's say I click on the button which is on comment with cid 56 and title 'Test'. The php code in the button should get cid 56 using title 'Test'. Or just get cid 56. Thanks. Tell me if i need to be more precise.

Comment ID in Comment field


Find the value of $m$ given that $\displaystyle\int_0^m \dfrac{dx}{3x+1}=1$

Question: I have to find the value of $m$ such that:
$\displaystyle\int_0^m \dfrac{dx}{3x+1}=1.$
I'm not sure how to integrate when dx is in the numerator. What do I do?
edit: I believe there was a typo in the question. Solved now, thank you!
Comment: You can bet a typo in the book !
Answer: That was probably a typo (meaning the double $\mathrm{d}x$) and your integral is the same as the following:
$$ I = \int^m_0  \frac{1}{3x+1} \, \mathrm{d}x  = \int^m_0  \frac{\mathrm{d}x}{3x+1} = \int^m_0  \mathrm{d}x  \, \frac{1}{3x+1} $$
You can place $\mathrm{d}x$ in the numerator, or even before the fraction while there's no confusion (the latter is less common). It's just a matter of notation and convention.
Can you take it from here?
Comment: Oh ok - I'll just assume 1 is the numerator then - I've never seen 2 dxs in an integral before so I was a bit confused.
Comment: You will see them when you deal with double integrals! But this is not the case. Cheers!
Answer: Since:
$$\int_{0}^{m}\frac{dx}{3x+1}=\frac{1}{3}\log(3m+1)$$
we have:
$$ m = \frac{e^3-1}{3}.$$
Answer: It's like integrating $\int f(x)dx$ with $f(x) = \frac{1}{3x+1}$


EOFError: EOF when reading a line

Question: Eu estou fazendo um programa que é uma resolução dessa questão da Olimpíada de Informática.
A, B, C = input("A").split(), input("B").split(), input("C").split()
A, B, C = int(A[0]), int(B[0]), int(C[0])
if A >= 1 and A <= 300 and B >= 1 and B<= 300 and C >= 1 and C <= 300 :
    pass
else :
    raise ValueError("Deu Erro")

H, L= int (input("Qual a altura")), int (input("Qual a Largura"))#dimensões da porta
if H >= 1 and H <= 250 and L >= 1 and L <= 250 :
    pass
else:
    raise ValueError("Deu Erro")

if (A and B) > (H and L) or (A and C) > (H and L) or (B and C) > (H and L):
    print ("N")
else :
    print("S")

Ele ainda tem muitas falhas, mas ao rodar ele não estou tendo o erro:

EOFError: EOF when reading a line

Quando coloco pra corrigir ele, estou. Eu queria saber o porquê disso.
Answer: O código está um pouco confuso, e pelo que deu para ler no enunciado não deve pedir 3 entradas e quebrar em partes, deve ler uma entrada e quebrar (odeio isso, costuma dar problemas, mas vamos fazer o que o exercício pede). Depois deve pedir um dado para ser quebrado em duas partes. Curiosamente uma parte do código fez de um jeito e o outro de outro jeito, mas ambos errados de acordo com o demonstrado na página.
Deixei a exceção exposta assim embora isso não é um código bem feito, mas serve como exercício principalmente porque ele não pede para tratar adequadamente, mas tenha isso em mente.
entrada = input("A B C").split()
A, B, C = int(entrada[0]), int(entrada[1]), int(entrada[2])
if A >= 1 and A <= 300 and B >= 1 and B <= 300 and C >= 1 and C <= 300:
    pass
else:
    raise ValueError("Deu Erro")
entrada = input("Qual a altura e largura").split()
H, L = int(entrada[0]), int(entrada[1])
if H >= 1 and H <= 250 and L >= 1 and L <= 250:
    pass
else:
    raise ValueError("Deu Erro")
if (A and B) > (H and L) or (A and C) > (H and L) or (B and C) > (H and L):
    print ("N")
else:
    print("S")

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: @Smaug eu acebei me perdendo na hora de escrever, editei.
Answer: Esta questão que tem como título Colchão, foi inicialmente disponibilizada pela OBI de 2012 e posteriormente, disponibilizada por Uri Online Judge, com o mesmo título, Colchão, e com a numeração 2409 da categoria AD-HOC.
Como é de se perceber, a questão nos pede para verificar se dada as dimensões de um colchão, dizer se o mesmo consegue ou não passar pela porta, com uma de suas faces, paralela ao chão.
Observe que a questão diz, que o colchão deve passar pela porta com uma de suas faces paralela ao chão. Além disso, nos diz que as dimensões do colchão são (1 <= A, B, C <= 300) e também, as dimensões da porta são (1 <= H, L <= 250).
Para resolver esta questão corretamente devemos perceber que como a dimensão máxima do colchão é 300 e a dimensão máxima da porta é 250 e que também, o colchão sempre passará pela porta com uma de suas faces paralela ao chão, devemos implementar o seguinte algoritmo...
colchao = sorted(list(map(int, input().split())))
porta = sorted(list(map(int, input().split())))

if (colchao[0] <= porta[0]) and (colchao[1] <= porta[1]):
    print('S')
else:
    print('N')

Veja o funcionamento do algoritmo no repl.it.
Observe que, quando este algoritmo é executado, a tela fica limpa aguardando os valores das dimensões do colchão. Neste momento devemos, digitar todas as três dimensões do colchão, na mesma linha, separadas por apenas um espaço e pressionar Enter.
Depois que digitamos todas as dimensões do colchão, os valores são ordenados e armazenados dentro da lista colchao.
Em seguida inserimos as dimensões da porta tal como inserimos as do colchão.
Após pressionarmos a tecla enter o programa irá verificar se a menor dimensão do colchão é menor ou igual à menor dimensão da porta e, também, verificará se a dimensão intermediária do colchão (largura do colchão) é menor ou igual à maior dimensão da porta. Caso o resultado seja positivo, exibirá a mensagem S. Caso contrário, exibirá a mensagem N.
Esta questão já foi testada, submetida e devidamente aprovada no site URI sob a linguagem de programação Python 3.
Só para constar, esta questão levou apenas 0.036 s para ser executada no site do URI.

EOFError: EOF when reading a line


Are universities teaching math too fast?

Question: I love math and I feel happy to learn it. But in universities, I think there's too much to learn. For example, in my university, there are mathematical analysis(I,II,III), linear algebra(I,II), ODE, topology, differential geometry,..., 24 courses altogether. In addition, we don't attend courses in the 4th year, so I have to finish 24$\div$3$\div$2=4 math courses per semester. That's
too much. In such a hurry, it's almost impossible for me to digest the big bulk of
knowledge, and to gain deep understanding of the concepts. It's painful.
So my problem is: Are universities teaching too fast? Or it's unnecessary to try to fully understand what I've learnt in a rush, because it cannot be achieved until I gain more experience at job?
Comment: I would view the learning as a process rather than something you do once. It is useful to get exposure to many different ideas and see how they weave together.
Comment: Pfft. When _I_ was an undergraduate, our terms were only 8 weeks long, and we had more than 4 courses per term (on average).
Comment: Like @copper.hat said, learning never ends. In fact most of my learning I did after my graduation, outside of school/university. But you do need to learn how to learn and teach yourself. The rewards are then endless.
Comment: Agree with what has been said. I feel that I am _learning_ maths more now than during my degree (I learnt a lot, but didn't have the time to enjoy some deep arguments there).
Comment: @copper.hat But what if I have to get exposure to these ideas in a not-long-enough time and I can't understand them all?
Comment: I upvoted this question because I think the answer is yes, universities are teaching too much and that problem needs to be fixed. People are struggling because university courses are trying to teach so much. I think the whole school system could be fixed up. In early grades, they could teach less and get students to teach themselves how to solve certain problems. They should also give them very little homework because that way, they can explore their own interests in discovery. Then they'll become really smart and then later learn stuff so much more efficiently.
Comment: https://www.huffpost.com/entry/teaching-discovery-learning_b_856463 seems to support my claim.
Answer: In my opinion, mathematics is a very poor fit for the standard university model of lectures, presented linearly, over the course of a quarter/semester.
If you fall a little behind in a math course, it is painful, if not impossible, to catch up.  This is because it is not enough to learn the material—you have to practice it, and in doing so you might discover very deep issues in your understanding of the background ideas.  Yet the course speeds along, giving you no time at all to polish what needs polishing.
We, the teachers, handle such situations very badly.  We tell ourselves that these students weren't ready for the course, that they should have taken something else first, or, worst of all, we think that they aren't "true mathematicians".  But this is all wrong.  Becoming great at mathematics involves all sorts of false starts and reworking of basic techniques.  The people who are "ready" for the course are often the people who get the least out of it; they could as well have read the book!
Math should be taught in a way that allows students to explore their weaknesses more deeply.  This is impossible to do if every student must be learning the same material at the same time.
I was lucky enough to have access to an at-my-own-pace style of math education throughout high school.  In college, I felt like I was a great student, always on top of my math classes.  Looking back, the classes were far too slow for where I was, and I was just a terrible student with the right background.  I wasn't being challenged, and so I learned a lot of bad habits, which made grad school very, very painful for me until I remembered how to push myself and focus on my weaknesses again.
So I don't think that math goes too fast exactly.  I don't think that math should have any pace at all, but be driven by the needs and abilities of the student.  This is not an easy ideal to achieve, of course, but I think that everyone in mathematics too easily accepts the myths surrounding the system that now exists.  Those at the top become arrogant, and everyone else becomes anxious and fearful.  You are right.  We can do much, much better.
Comment: But there are still things that I think are overstated. I don't think that 'great' is really relevant, but becoming very good at mathematics does not necessarily involve all sorts of false starts and reworking of basic techniques. People who are 'ready' for a course are often people who get the *most* out of it, even though many of them could have learned much of it on their own from the book. And some students really *aren't* ready some courses. Note that I am not saying that one size fits all: it doesn't. Nor am I saying that the traditional structure works well for all students: it doesn't.
Comment: @BrianM.Scott I was only bringing up my own experience to contrast with the poster's assertion that math is too fast.  My justification for my opinions rests far more heavily on my experience with my students than on my own time as a student, which I readily admit to be highly atypical.
Comment: @BrianM.Scott You're right; it's almost as though this is the perspective of a single person, and should have started with "In my opinion".
Comment: While there is certainly some truth in this, I think that you're over-generalizing from your own experience.
Comment: @user33433 By saying "too fast", I don't mean "math goes too fast", but mean "university goes too fast", that is, are they unnecessarily setting too many courses that I have no time to digest?
Comment: @AaronSan You're right, I'm kind of conflating the two things.  But they're related: if you have time to digest, the next one won't feel so rushed, and if you can take a course slowly, you might not worry about taking another one soon after.  My general point is just that there's a particular university model that gets applied to all courses, whether history, biology, music, or math, and I'm arguing that some of the difficulty you're describing has to do with this model not being a very good fit for mathematics in particular.
Comment: @user33433 So should I keep my own pace even though it'll be a little slower than the courses?
(In fact, for some reason, I've studied analysis & linear algebra shallowly last year, so being a little slower than the courses seems not to be a big problem. I just need to go deeper now.)
Comment: @user33433 BTW, what do you exactly mean by saying "model"? "Eat as much as you can, digest it later"? I think it doesn't fit for most domain of knowledge besides math.
Comment: @AaronSan What to do depends a lot on your priorities.  I always worried about whether I was enjoying courses, not whether I was keeping up or getting good grades or digesting or whatever.  This worked well for me in my math courses, but I also had the benefit of good preparation beforehand.  It's hard to say what would work for you, as I don't know you, or your university.  It might be necessary to push yourself hard—or maybe pushing yourself hard would be destructive.  But if you are thinking about "going deeper", I think you are on the right track.
Comment: @user33433 Thanks for your advice! I'll try to go at my own pace. I really prefer enjoying the process of learning rather than worrying about grades.
Comment: @AaronSan Glad you found some of it helpful.  Lots of people know how to work hard at math, but knowing how to enjoy it is a very rare skill.  I'm TA'ing for an introductory graduate math course right now, and it is a little sad how much people worry about grades (and how little good it does them!).  I wish you and your pace all the best.
Answer: I am a graduate student from Applied Mathematical &Physical Sciences.I had 59 courses,about 10 for Physics and 49 for Maths.I remember and use about 10-12 of them.
But i don't regret studying there. It was hard but i did not feel that we were going ''too fast''. It is better to learn as much as you can when you are young,and then keep only what is interesting and necessary for yourself.
P.S. I don't use anymore measyre theory but learning that some sets have measure $0$ was really exciting. I believe that for someone who loves mathematics we can find many more examples like this.


facing gradle error while running my code?

Question: I am facing an error while running my code. Its showing multiple lines error which you can see in the below screenshot. Kindly help me to resolve this issue
Comment: Can you include your code-snippet? Also connect to the internet and then build.
Answer: Delete the test folder and try to rerun the project. Hopefully, the issue will be resolved.


Parsing time from C++ DLL to Matlab

Question: I'm writing a C++ DLL which will be accessed using MATLAB's loadlibrary. I need a specific function to return the current time in milliseconds precision, and parse it correctly in matlab. Specifically i'll need to extract the year, month, day, hours, minutes, seconds and milliseconds.
I currently have something like
long long time_since_epoch()
{
    return std::chrono::system_clock::now().time_since_epoch().count();
}

which MATLAB calls using t = calllib('myDLL', 'time_since_epoch');.
Then I tried parsing it using dt = datetime(t, 'convertfrom', 'epochtime');, which didn't work.
But, I compared it with the time given from posixtime(datetime) and found out I'm getting a correct answer by using dt = datetime(t / 10000000, 'convertfrom', 'epochtime');, which is very odd.
I don't fully understand what's going on here, and I somehow lost the milliseconds  in the process.
Answer: Your system_clock is not counting milliseconds, it is counting something finer than a millisecond.  Exactly what isn't important because you can specifically ask for the count in milliseconds:
long long time_since_epoch()
{
    using namespace std::chrono;
    return time_point_cast<milliseconds>(system_clock::now()).time_since_epoch().count();
}

Parsing time from C++ DLL to Matlab


Reliable email service for personal use using own domain name

Question: I have my own domain name but do not want to manage the email. I'm looking for a web-based email client (similar to Gmail) but able to use my own domain. The main requirement is reliability.  I've tried Google Apps (Premium, $50/year) but the reliability based on my personal usage is way too low (up time around 90%). I'm willing to pay up to $100/year.
Any suggestions?
Follow-up:
The errors I see with Google Apps Mail are:
Oops... the system encountered a problem (#717) - Retrying now...
Oops... the system encountered a problem (#767) - Retrying now...
Oops... the system encountered a problem (#6502) - Retrying now...

as well as:
Temporary Error (500) ... Numeric Code 21
Temporary Error (500) ... Numeric Code 67

and also:
502 Server Error, Server Error The server encountered a temporary error that could not complete your request. Please try again in 30 seconds

When I get these errors, they last for about 15 minutes. This happens at least 10 times per day. So 15 minutes times 10 = 150 minutes. 150 minutes downtime per day (1440 minutes) = 10.4% downtime.
I have also have a free Gmail account which works great. It's just that my Google Apps Mail has a constant server related issue. This might be an isolated incident, but it's very real to me. It's been going on for a week know.
Okay, I just did a search and it's not so isolated. Seems others have the same problem. link, link and link
I've created a trouble ticket with Google Apps support, but they have yet to fix the issue. Maybe they'll fix it someday, but reading the various Google Help Form posts doesn't give me a lot of confidence.
As for Google's Service Level Agreement, it's not very valuable. They define a service outage as 10 minutes or more. The compensation is not to exceed 15 days of service for the service term, which for Google Apps is one year. So you get 15 frees day added to one year, which isn't very much. See this article for an analysis of Google's SLA.
I don't want this to turn into a Google bashing thread. I would love for Google Apps Mail to work for me. Since it isn't working for me (currently), I'm investigating other options.
Follow-up 2: The intent of this question is to inquire about reliable email service. I really don't want hear about how reliable Google Apps Email is for everyone else so somehow my experiences aren't valid. I'm looking for suggestions on reliable email services, this could include Google Apps Email but I'd like hear what else exists.
Comment: Not an answer, so much as an attempt to urge you to try Google again. Maybe something was misconfigured or you got a really bad luck of the draw at Google. Signing up for Premium does give you a 99.9% SLA that they make amply clear, so if you definitely had 90%, challenge them on that and they should be able to give you a very good answer.
Comment: Of those links you included, almost all of them are well older than a month old.  You said that this is something that's come up within the last week, and if it were a widespread issue I'd expect to see way more of your references listing the last week.  We have a client that heavily uses gmail and when there are widespread issues we hear about it from them.  It's happened twice in the last year or two I think, but I haven't heard they have been having problems this week.
Comment: @Sean Reifschneider, I just setup my Google Apps Mail a week ago. So yes, it "came up" in the last week. My point was that many others, at one point or another have encountered the errors that I'm seeing, which BTW, are still ongoing and unresolved (that is, there's still 10 or so 10-minute outages per day).
Comment: @Steven Xu, I haven't given up on Google yet. I still use Google Apps Mail everyday, but it's still consistently down for 5-10% of the day, every day since I've signed-up a week ago. I'd love to keep using Google App Mail, but I don't know how long my patience will last.
Answer: Sorry, but your 90% reliability of GApps is way off. If their reliability was that bad, there's no way they would have the market share they currently do. If you insist that their uptime is that bad, I'd start looking into your own infrastructure to see if something is wrong.
I've been using GApps Standard (the free version) for several personal and corporate domains since they started offerring the service, and have had incredibly good luck on all accounts.

Update:
It certainly sounds like you are running into some issues. Whether those issues lie in your specific setup, your ISP (packet loss), or in Google's infrastructure, we'll never know. As others have said, in the experience of the vast majority of GApps customers, they provide the most reliable email service out there. It's quite unfortunate that you have not found that to be the case.
Comment: How could an HTTP 500 or 502 possibly be the user's fault? Some users see more downtime with google apps than others. Some accounts have far more downtime. I think it's most likely that Google has one bad machine in a 100-machine cluster, or something similar, so a specific one percent of their users see crappy service while everyone else has no problem.
Comment: My own infrastructure in this case is a computer with a browser. The problem is clearly with Google's servers.
Comment: Well let's see. I've cleared my cache+cookies, restarted the browser, used different browsers (Chrome, Firefox, Safari), different OSs (OS X, Windows), different ISPs (work and home). On top of that, Google tech support confirmed that it's on their end. Just because the majority of the people don't have problems with Gmail, doesn't diminish the issues I'm personally seeing.
Comment: @Sparr - the OP posted those errors after I made that comment. He provided zero data for us to work on initially. I'll remove my comment if you recind your down-vote. :)
Comment: I know it's not fair, but once he edited his question then your answer because [more obviously] wrong. The only way to fix that is to -1 your answer out of the top spot, or for you to edit your answer.
There are some discussions on the various meta sites about fixing this phenomenon.
Comment: There we go - edited.
Answer: You might consider Rackspace's email service: https://www.rackspace.com/applications/rackspace-email (updated link after Rackspace orphaned it)
Or you could leave your email on Google Apps, and use a personal web-mail client like RoundCube to access it...
Edit: 12 years on, Rackspace might not be the best choice. Migadu is a solid, reliable email provider at an excellent price.
Comment: +1.  Rackspace is in the hosting business and doesn't parse your email either, so says their privacy policy.
Answer: I'm not sure where this 90% uptime came about, but Google Apps (even the personal edition) is very reliable.  More so than other commercial equivalents.  The <10 times that GMail has had issues were widely publicized due to the rarity of this happening.  Even with this downtime, it still beats out other alternatives like Hotmail (Windows Live) and Yahoo.
You can also use the free version, which you can sign up for here--which doesn't cost a dime.
Comment: See followup in my post for how I get at 90% uptime.
Comment: Thanks for explaining it, but for future reference, please try to do that first--claiming low uptime in extremely isolated instances (remember, a few hundred cases is nothing in Google's case) is bound to cause issue, especially if its not a backed up by industry stats.
Comment: Fair enough, I should have been more explicit that 90% uptime was based on my own personal experience, and not those of others.
Answer: Yahoo has a "business" class service that lets you use your own domain.  I had a client that used this and was happy with it, but they switched away when they got acquired.
Fast-email.com has some business services that let you use your own domain.  I have a friend that uses them and likes them, but he has their personal plan.
I'm sure other e-mail providers have similar services.
Answer: I've had good luck with Fastmail.fm.


Two select field cck field

Question: I need to implement two select field in a content type.Currently cck modules allows only one select field. So how can I implement two select fields using cck.
Eg:- select field value for months and year.
Tks in adv
Vil
Comment: do you want to create select field for month and year only ?
Answer: Try Date module. This provides the cck widget to select the date.
The Select List date widget presents users with a drop-down list or textfield for each part of the date (year, month, day, hour, etc.). The whole selector is collapsed onto a single line using css (except for the timezone selector, if date-specific timezones are collected). The selector is highly configurable and you can set it up to use 5, 10, or 15 minute increments for minutes and seconds, or make some parts of the selector use textfields instead of drop-downs, useful to allow any year without creating a huge drop-down selector.
For more Documentation See here
Comment: yea but i have to keep options like Select option 1:-0 1 2 3 4 5 6 7 8 9 10 11 12 | Select option 2:- 0 1 2 3 4 5 6 7 8 so on..
Comment: and are they dependent ? I mean value of 2nd select is dependent to first one ?
Comment: No they just work individually...anyways came up with a solution. Tks for your replies :)

Two select field cck field


XQuery - count + value of node

Question: i have a small problem with getting count of something and value of parent node for it.
Actually xml schema looks like that:
<car>
     <carID> 1 </car>
    <fixes>
     <fix>
      <fixID> 1 </fixID>
     </fix>
     <fix>
      <fixID> 2 </fixID>
     </fix>
    </fixes>
 </car>
well more or less... what im trying to achieve is: by using XQuery (and thats important part) i need to return how many fixes each car has (i know that in example there is just one car). So i need in result something like  1  2 or something like that.
Any help would be greatly appreciated
Edit:
   <car>
     <carID> 1 </car>
     <departmentID> 1 </departmentID>
    <fixes>
     <fix>
      <fixID> 1 </fixID>
     </fix>
     <fix>
      <fixID> 2 </fixID>
     </fix>
    </fixes>
 </car>
Now id like something a bit more troublesome ;/ I have XMLcolumn in sql server which hold sqldocument for car in a separate rows, so one row one . What im trying to do further on is to get carID for each department wich most amount of fixes. Any clue?;/
Comment: Wouldnt each `fix` have a `fixid`? (so two `fix`'s in your example?)
Comment: You are indeed correct, that is my mistake
Answer: After fixing the closing </carID> tag,  you can apply the xpath count aggregate to return the count of fixes:
DECLARE @xml XML =
'<car>
     <carID> 1 </carID>
    <fixes>
     <fix>
      <fixID> 1 </fixID>
      <fixID> 2 </fixID>
     </fix>
    </fixes>
 </car>';

SELECT
  Nodes.node.value('(carID)[1]', 'int') AS Car,
  Nodes.node.value('count(fixes/fix/fixID)', 'int') AS Fixes
FROM
  @xml.nodes('//car') AS Nodes(node);

SqlFiddle example here
Edit
Update for OP's new Question.
You need to use CROSS APPLY to apply the xml scraping to a column for all rows in a table. Once you know how to project data out of an Xml Column, the rest becomes a simple matter of using successive Sql projections to move to the end result:
WITH cteCarFixes AS
(
    SELECT
      Nodes.node.value('(carID)[1]', 'int') AS CarId,
      Nodes.node.value('(departmentID)[1]', 'int') AS DepartmentId,
      Nodes.node.value('count(fixes/fix/fixID)', 'int') AS Fixes
    FROM
        CarFixes cf
        CROSS APPLY cf.SomeXml.nodes('//car') as Nodes(node)
),
cteRankedCarFixes AS
(
    SELECT CarId, DepartmentId, Fixes,
        ROW_NUMBER() OVER(PARTITION BY DepartmentId ORDER BY Fixes DESC) AS Ranking
    FROM
        cteCarFixes cf
)
SELECT DepartmentId, CarId, Fixes
    FROM
        cteRankedCarFixes
    WHERE
        Ranking = 1

Updated SqlFiddle here
Comment: That indeed works thanks a lot. But now i have a bit different problem. I have XML instances in SQL Server. Please check Edit in main post if possible. Thanks anyway!
Comment: I've updated, above. Next time, please ask a new question (you will reach a wider audience and likely be a faster resolution).
Comment: This looks like SQL with some embedded Xpath expressions. Why tag it xquery?
Comment: @charlesross [This](https://msdn.microsoft.com/en-us/library/ms189075.aspx) may help you
Comment: Yikes - MS 'XQuery' is a thing that is to the XQuery standard as the old Jscript was to Javascript. It presents a tagging problem here.

XQuery - count + value of node


How to force image URLs as HTTPS?

Question: There are a few places where I am calling ImageStyle::load('style')->buildUrl($uri) to get a physical file path of an image.
After enabling HTTPS and forcing all traffic to use HTTPS, I noticed that this will only return http:// at the start of the url, and not https:// causing mixed mode flag in the browser.
Is there a way to do this and get the correct protocol? Can I not just obtain the relative path to the file instead? I notice that this method has hardcoded 'absolute' => TRUE when building the url to return.
Edit: fields using the normal rendering method i.e. {{ content.field_image }} have the correct protocol and do not cause an issue.
Here is the code I am using to generate the variable:
/**
 * Implements hook_preprocess_node().
 * @param $variables
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle =='homepage' && $variables['elements']['#view_mode'] == 'hero') {
    $hero_image = $node->get('field_hero_image')->getValue();

    if (!empty($hero_image)) {
      $entity = Media::load($hero_image[0]['target_id']);
      $variables['hero_image'] = ImageStyle::load('homepage_hero')->buildUrl($entity->field_image->entity->getFileUri());
    }
  }
}

In the node view mode twig template:
  {% if node.field_hero_image is not empty %}

  {% endif %}

Answer: You can use file_url_transform_relative():
/**
 * Transforms an absolute URL of a local file to a relative URL.
 *
 * May be useful to prevent problems on multisite set-ups and prevent mixed
 * content errors when using HTTPS + HTTP.
 *
 * @param string $file_url
 *   A file URL of a local file as generated by file_create_url().
 *
 * @return string
 *   If the file URL indeed pointed to a local file and was indeed absolute,
 *   then the transformed, relative URL to the local file. Otherwise: the
 *   original value of $file_url.
 *
 * @see file_create_url()
 */
function file_url_transform_relative($file_url) {

Comment: This is what core is doing everywhere to solve problems when using mixed mode. But it should actually default to https if you have only https. Which is recommended anyway
Answer: You could try altering your base_url by un-commenting the following line in settings.php and changing the http to https.
/**
 * Public file base URL:
 *
 * An alternative base URL to be used for serving public files. This must
 * include any leading directory path.
 *
 * A different value from the domain used by Drupal to be used for accessing
 * public files. This can be used for a simple CDN integration, or to improve
 * security by serving user-uploaded files from a different domain or subdomain
 * pointing to the same server. Do not include a trailing slash.
 */
# $settings['file_public_base_url'] = 'http://downloads.example.com/files';

How to force image URLs as HTTPS?


Quantile regression for Sales forecast in R

Question: Issue: Cannot forecast sales accurately using quantile regression in R. I am using rq function from "quantreg" package which is giving me warning "Result might have Non unique solutions"
Aim: I am trying to forecast hourly sales of a store using quantile regression.
Below are the columns in my source table for forecasting.

transaction_date : sales date (input)
hr1 to hr24 : column with hourly sales info. (24 columns) (input)
totala : total of 24 column hr1 to hr24 (not using currently)
location, department, sales_type: forecasting will be done for each location, sales_type and department. (used to select data)
f1 to f24 : columns I want to forecast for each hour (24 columns) (output)

Packages Used: forecast, quantreg, Metrics
Code:
I have extracted date features from transaction_date eg. weekend, week of month and also holidays (1 if it is holiday 0 for regular days).
attach(train_data)
Y <- cbind(hr)
X <- cbind(transation_date, Years, Months, Days, WeekDay, WeekofYear, Weekend, WeekofMonth, holidays)

quantreg.all <- rq(Y ~ X, tau = seq(0.05, 0.95, by = 0.05))
prediction_train <- data.frame(predict(quantreg.all))

I have 19 models in prediction_train for each tau from 0.05 to 0.95, I select best model based on rmse value and than forecast using that tau.
rmse(actual, predicted)

transaction_date is Date type, quantreg.all is rqs class and rest are numeric.
Note: Stores are not open 24 hours, hence many hour columns will be 0 (time when store was close). Currently for most of such hours rq is predicting 0 or some negative values.
Weather  does not have major impact on sales.
Comment: What is the actual problem? That you're predictions aren't very accurate? Or that you're getting the warning from `rq`?
Comment: @scribbles Prediction are not accurate, and I think it might be because of the warning message which says solution may be non unique.
Answer: Can you define "accurate"? What do you expect to obtain?
It is still a regression and it will not guarantee you 100% precision.
Furthermore quantile regressions will give you the value corresponding to the chosen quantile of the distribution. So, for example, regression with tau=0.25 and some specified value of X will give you y_fit that is greater than 25% of all the observations in the sample for the same X value (25% of observations will lie below y_fit). So in general you shouldn't expect the high accuracy with quantile regressions.
As for the warning, it may be not relevant to your accuracy issue at all. But changing method parameter in qr may help you get rid of the warning. For example, using method="fn" should help in the cases with a high number of observations.
Comment: Thank you for your reply. By "accurate" I mean error rate ((actual-predicted)/actual*100) should be minimum 5%. Can I expect this much accuracy from quantile regression? Thanks for answer on warning message. You are correct it was not relevant to accuracy issue. Warning messages were because of same values in data (In my case 0 was repeated for sales on less busy hours)
Comment: The accuracy measure, that you mention, is called in forecasting "Percentage Error" (PE). I assume that you take mean absolute values of PE, which leads to MAPE. The thing with MAPE is that it is scale dependent. So you can obtain 5% when the actuals are high (something like thousands of units) or when the error is very low. In general it is hard to have 5% for some data using any model, so I wouldn't aim for that. And actually you shouldn't aim for some percent. All the different error measures are made for the comparison of models' forecasting accuracy, not the comparison with some value.
Comment: Thank you @Ivan Svetunkov , I understood using MAPE is not helpful, hence like you suggested I am going for RMSE ( using Metrics R package). Any other suggestions are welcome.


The Maximimum Monochromatic k-Cliques for Complete Graph

Question: Show:
For a complete graph $K_{n}$, there is a coloring of the edges with $2$ colors, such that the number of monochromatic $k$-Cliques is a maximum of $\binom{n}{k}2^{1-\binom{k}{2}}$.
I do not know where to begin on this exercise. As a hint, our professor gave us the following pre-exercise, which I have been able to solve:

Let $n \in \mathbb N$, and $\mathcal{K}$ be the set of permutations
  possible for a set $\{1,...,n\}$. Let $\sigma \in \mathcal{K}, $ such
  that $\sigma: [n] \to [n]$ is a randomly selected permutation. Find
  the probability space, define random variable $X$ as the number of
  fixed points and find $\mathbb E[X]$.

How do the two questions fit together? I am lost.
Comment: I do not know about those random graph and just google about that. And I found https://people.cs.pitt.edu/~kirk/cs3150spring06/HW6_B.pdf Problem 6.2A has a similar question - which the number there is the expected number of monochromatic clique. But I do not quite follow how is that related to "at most".
Answer: This problem is a classical problem in probabilistic graph theory due to Erdos and can be found in pretty much any introductory course on probabilistic graph theory.
Denote by $I_{x_1,...,x_k}$ the indicator function of the k-clique of vertices ${x_1,...,x_k}$(for a random coloring of $K_n$). Thus $I_{x_1,...,x_k}$ is 1 if ${x_1,...,x_k}$ is monochromatic or 0 else. Then the total number of monochromatic k-Cliques is equal to $\sum_{x_1,...,x_k}I_{x_1,...,x_k}$ where the sum is taken over all ${n\choose k}$ groups of k-vertices in the graph. The expected number of monochromatic k-Cliques is then equal to ${n\choose k}P({x_1,...,x_k}$ is monochromatic $) = {n\choose k}2^{1-{k\choose 2}}$, by linearity of expectation and also by $E(I_A)=P(A)$, for any event set A, so you can find at least one graph with ${n\choose k}2^{1-{k\choose 2}}$ monochromatic k-Cliques.
For completion, note that $P({x_1,...,x_k}$ is monochromatic $) = 2^{1-{k\choose 2}}$ because ${x_1,...,x_k}$ is monochromatic if it is either red or blue(whence the factor of 1 in its exponent and the probability that each of its $k \choose 2$ edges is red is exactly $\frac{1}{2}$)


Selecting the right dependent variable for regression

Question: I am new to statistics and starting a project to develop a set of probabilities for a horse race. I am using Stata with a database containing about 20 variables. One of the variables is finish position with values 1 for win and 0 for others. Would I use this as the dependent variable ? and does each race need a unique ID ?
Thanks
Ian
Answer: As far as my knowledge goes, your dependent variable should be the thing you're trying to predict. Setting a clear objective to your model will help you determine this. Since your project is about horse races, I'm assuming the objective of your model is to determine the winning horse for each race. In that case, your assumption is correct, the finish position variable would be your dependent. And considering your dependent variable is organized in a binary form (0 or 1's), you should also use the logistic regression for the best results.


Does open set in $R_d \times R $ containing $R\times 0$ contain any subset $I \times (-\varepsilon, \varepsilon)$, with infinite $I$?

Question: Let $R_d$ be the set of reals with discrete topology, $R$ be the set of reals with natural topology and let $X=R_d \times R$ with product topology. Assume that $R_d \times \{0\} \subset V \subset X$  and $V$ is open. Do there exist an infinite set $I \subset R$ and a number $\varepsilon >0$ such that $I \times (-\varepsilon, \varepsilon) \subset V$ ?
Thanks
Answer: Directly from the definition of product topology we know that for each $x\in\mathbb  R$ there is a rational $\varepsilon_x>0$ such that $\{x\}\times(-\varepsilon_x,\varepsilon_x)\subseteq V$.
Now, for each $q\in\mathbb Q$ denote $A_q=\{x\in\mathbb R; \{x\}\times(-q,q)\subseteq V\}$. We have $\mathbb R=\bigcup_{q\in\mathbb Q} A_q$.
If every set $A_q$ would be finite, this would imply that $\mathbb R$ is countable, a contradiction.
(You could do basically the same thing working with the numbers of the form $\frac1n$, $n\in\mathbb N$, instead of rationals.)
You can also note that we would obtain the same contradiction by assuming that all $A_q$'s are countable, hence this shows that there is an $\varepsilon>0$ and an uncountable set $I$ with the property you're asking about.


Are there typical stages for leaning how to sight read music?

Question: I am spending the next year( or as long as it takes) to learn to sight read any pieces of music.
I am using Bela Bartok Mikrokosmos as a main theme with other music.
I know all my notes well, thanks to a great app.
I have learned to put these notes into keys and continue practicing daily. My practise is short but highly concentrated(15-30mn/day)
I know how to analyse a piece well before actually reading notes, identifying its characters and difficult passages.
I still find it challenging to read both treble and bass at the same time. Does anyone have any ideas to improve that?
Because the exercise is sight reading, I concentrate on that, reading or following the notes in the page.
However,
Because I have an excellent memory and a strong scales practitioner, I find that I stop reading or following individual notes. Instead, I start following the trends of the music, concentrating more on the rhythm and dynamics of the piece, sometimes using the wrong note!
Is this a normal progression? What will happen next?
I know I'll get there eventuality but insight knowledge from more experienced musicians has been excellent!
Basically, I want to be able to pick up a piece of music, analyse it, then play it.... in my opinion, that's the path to studying and researching an artist in the future. I think?
Answer: Sight reading is only as good as three factors:
1) Technical ability.  If you have technical flaws and can't execute what is on the page, your sight reading will suffer.
2) Knowledge of music theory.  When you read text or words, you are not seeing every letter in a word, but your brain fills in the letters you don't actually see.  Music theory is the same.  Once you know the alphabet of scales and chords, reading will become easier.
3) You hands need to know where they are going without thought.
Sight reading isn't necessarily a skill on its own.  It is an amalgamation of other skills.
Answer: Don't concentrate TOO hard on sight-reading, you have to be able to PLAY it as well as read it!  If you're working through Mikrokosmos you should find that both your sight-reading and your playing gradually improve.  But do play other stuff as well!  Even if religion irritates you as much as it does me, work through a hymn book with the mindset "Today's hymn HAS to be played, make the best job you can".


Why do we say function "parameterized by" vs just function of (x,y,z,...)?

Question: I'm studying statistics, and in a lot of textbooks, the regression formulas always refers to the functions themselves as f(x) parameterized by a,b,c or something. And they are often written $f(x; a,b,c)$, why can't we just write $f(x, a, b, c)$?
I would like to know perhaps the history of how this came about, and why there is this seemingly dual method of expressing the same idea. Is there some esoteric mathematical notation that a noob like me hasn't encountered yet, or did mathematicians of old just like doing things in different ways?
An example: A function that maps age of tree to height:
$$f(age; growth\_rate) = age * growth\_rate$$ vs $$f(age, growth\_rate) = age * growth\_rate$$
Comment: Consider also sequences and time series -- it's strange to express a sequence as $a(n)$, even though it's perfectly valid -- a sequence is a function from $\mathbb{N}$ to whatever the domain of $a$ happens to be. Similarly for time series -- common to see functions like $V_t (x)$ which are actually just $V(x, t)$, or even $V(x; t)$, to come full circle.
Answer: Strictly speaking you're right. It's sometimes difficult to explain clearly what is a parameter and what is a variable. When you write $f(x;a,b,c)$, there is no mathematical difference between $x$ and $a$ for example, they're both variables for the function $f$. I think the real difference is in how we interpret things. When we have an expression such as $f(x;\theta)$ or $f_\theta(x)$, $x$ and $\theta$ don't exactly play the same role, that's why we use different notations for them. In fact it's for the sake of clarity. When you have lots of different variables in an expression, using different notations is an easy way to know what role they play.
In the framework of statistics, the notion of parameter is even more important. As you may know, there's a whole branch of statistics called parametric statistics, where we introduce families of probability distributions, indexed by a set of parameters:
$$\mathcal{P}=\{P_\theta,\theta\in\Theta\}$$
where $\Theta$ is some subset of $\mathbb{R}^d$.
Note that you could actually see this as a function from $\Theta$ to the set of probability distributions on a certain space. In many cases, $P_\theta$ has a density w.r.t. the Lebesgue measure, and we denote it by $f(x;\theta)$ or $f_\theta(x)$. You see in this example that $x$ and $\theta$ have very different meanings. $\theta$ is the parameter that comes from our statistical model, whereas $x$ is a variable of integration.
In other cases, we use the "opposite" notation. For example when you consider the likelihood function $l(\theta;x_1,\dots,x_n)$, we consider it primarily as a function of $\theta$ (that we want to maximize most of the time), and $x_1,\dots,x_n$ as fixed parameters (they are the observation, we can't change them). Once again, it's a question of context and meaning of the variables.
Comment: If this means anything, I'd say that parameters are somewhat "more fixed" than variables. They are not the first thing that we want to make vary.
Comment: Exactly; TL;DR: because we have _very specific interpretations_ for how to think about parameters as opposed to variables. We tend to think of parameters as "fixed" (even though they're not, which is why we leave them as symbols).
Comment: If you have any background in programming, a good comparison would be template/generic arguments vs function arguments. The template arguments are still technically arguments you pass to the function, but they effectively change the template of the function you're calling in the first place.
Answer: While the answers already given are correct, I suspect that they may be bringing in terminology and notations you are unfamiliar with. If so, let me try to recast the answer more simply.
You are correct that $f(x; a, b, c)$ is the exact same thing as $f(x, a, b, c)$. But the difference is in how we are using $x$ vs how we are using $a, b, c$. With $f(x, a, b, c)$, all four values are equally important, equally of interest. With the former, we are considering $f$ as a function of $x$ only. $a, b, c$ are simply values that we use in defining that function. By making these values variables too, the mathematics we do applies to all the different functions of $x$ that are defined by the various possible values of $a, b, c$, instead of having to work each particular example we need separately.
For example, when talking of linear functions, we will write things such as $$y = mx + b$$ You could consider this as defining $y$ as a function of three variables, $x, m, b$, but what is important is the dependence of $y$ on $x$. The slope $m$ and intercept $b$ are just values expressing which line is represented by the relationship between $y$ and $x$. So if want to find the root for $y = 0$, that is $x = \frac{-b}{m}$, not $b = -mx$ or $m = \frac{-b}x$.
That is what the notation $f(x; a, b, c)$ means. It is just telling you that $x$ is the one whose variance is important to us. The others we are going to consider fixed (although not currently known) values.
Comment: I like this better than the accepted answer. If we define $f(x;a,b,c)$, we are defining a family (parameterized by $a$, $b$, and $c$), of functions of a single variable (which we represent as $x$). $f(x;1,2,3)$ is then a specific function of one variable. While this is technically the same as saying $f(x;a,b,c)$ is a function of four variables, it is not as useful a conceptualization. Given $m$ and $b$, $f(x)=mx+b$ is a linear function of one variable. If we're studying lines, we want to say that, not that $f(x,m,b)$ as a function of three variables that describes a line if we fix $m$ and $b$.
Answer: Think to something like this: $f(x;\sigma) = e^{-x^2/\sigma^2}$.
If you read for example "the derivative of $f$" probably you immediately undestand that we are speaking of $\partial f/\partial x$ because you recognize $f$ as a function of $x$, whose definition contains some $\sigma$ which is not a "variable".
Otherwise if you read:
$f(x, \sigma) = e^{-x^2/\sigma^2}$
a sentence like "the derivative of $f$" would be ambiguous: it's $\partial f/\partial x$? $\partial f/\partial \sigma$? $\nabla f = (\partial f/\partial x, \partial f/\partial \sigma)$?
So without this distinction every time one has to write explicitly "the derivative of $f$ with respect to the variable $x$".
Answer: In fact there is a formal distinction between parameter and argument, which captures our subjective view.
Let $P$ be the parameter space (set of growth rates), $X$ the domain (set of ages) and $Y$ the codomain (set of heights). A family of functions from $X$ to $Y$ parameterised by $P$ is formally a function $f: P \rightarrow Y^X$, where $Y^X$ is the set of functions from $X$ to $Y$.
In other words, it is a function taking growth rates and returning maps from ages to heights.
Of course, you are correct that this naturally and uniquely corresponds to a function $F: P \times X \rightarrow Y$, that is, a function taking a growth rate and an age and returning a height. This natural isomorphism is succintly denoted by
$$ \left( Y^X \right)^P \approx Y^{P \times X}$$
Comment: See [Currying](https://en.wikipedia.org/wiki/Currying). It still leads us to ask why mathematicians don't use notation like $f(a,b,c)(x)$, which I think is best explained in section 2 of [this essay](http://arxiv.org/pdf/1505.07238.pdf). In short, functions were originally meant to be of type $\mathbb R \to \mathbb R$ or $\mathbb C \to \mathbb C$. Mathematicians were wary to generalize this because it was difficult to explain the modern notion of function in terms of existing concepts.
Comment: But they do, except they always prefer the clearer alternative $f_{a,b,c}(x)$. Also, thanks for the nice read!
Answer: The area where I am used to seeing parameterizations is when considering curves and similar geometric objects. Consider a curve drawn in $\mathbb{R}^3$, this is just a set of points and initially is not a function of any kind. But we can in fact make it into the image of a function by defining a mapping $f:[0,1] \rightarrow \mathbb{R}^3$ which 'traces' the curve as the input variable goes from 0 to 1. So in this context a parameterization means taking an object that is just a subset of a given space and defining a mapping whose image is the object we are interested in. The inportant thing here is that the choice of this mapping is arbirtrary, in that there are an infinite number of different functions we could define whose image would be our object of study. Hence calling it a parameterization really is indicating that we have chosen a suitable functional description, but indicates that it is not unique.
This seems the same as for the function example you give, as there are any number of ways of taking the heights of trees and defining functions which map to these correctly for each tree. So your semicolon notation appears to simply be saying that this function has been chosen to use growth rate along with the fixed age input in order to define height, but is indicating that there were other choices you could have made instead.