Qual é a finalidade de um construtor estático?

Question: Sempre utilizei construtores da seguinte forma:
public MinhaClasse()
{
  //Algo
  ...
}

Entretanto descobri que no C# é possível criar um construtor estático da seguinte forma:
public class MinhaClasse
{
    public string Propriedade { get; set; }

    static MinhaClasse()
    {
        //Algo
        ....
    }
}

E a classe com o construtor estático é instanciada da mesma forma que uma classe comum:
MinhaClasse c = new MinhaClasse();
c.Propriedade = "Hello Stackoverflow";
WriteLine(c.Propriedade);

Saída:

Hello Stackoverflow

Dúvidas
Qual é a finalidade de um construtor estático e quais são as diferenças do construtor estático em comparação com o construtor padrão?
Comment: Existe isso de construtor estático? Nossa, pra mim isso é novo. hehe
Comment: @diegofm tentei no Java mas não funcionou ele diz q é invalido, porem no C# funciona hehe
Comment: por isso que eu desconhecia, é um problema sério a gente ficar fechado a uma linguagem apenas viu. :/
Comment: http://stackoverflow.com/questions/4506990/what-is-the-use-of-static-constructors
Comment: Tem no Java tb, tem um *link* na minha resposta que fala disto
Answer: Não vou entrar em muitos detalhes porque várias informações pertinentes ao assunto já foram respondidas em outras perguntas. Estou imaginando que entende a diferença entre membros estáticos e membros de instância.
O construtor estático serve para inicializar os membros estáticos da classe (em oposição a inicializar os membros do objeto instanciado). E ele é chamado exclusivamente pelo CLR em algum momento antes de algum membro estático ser usado, seguindo regras estabelecidas na especificação (se tudo correr bem será chamado apenas uma vez e não há como controlar sua chamada). Só pode existir um construtor sem parâmetro.
Como é comum que os membros já sejam inicializados por conta própria raramente precisamos escrevê-los. Mas pode haver algumas situações que o compilador não consegue avaliar a expressão da inicialização, pode precisar de uma ordem específica de inicialização (um depende do outro), fazer algo extra além da inicialização, então ele pode ser útil.
Sua utilidade é a mesma de um construtor de instância (pode ser vista em perguntas linkadas abaixo), nem mais nem menos, só muda os membros que ele pode manipular.
Na verdade o compilador também gera um construtor estático sempre que há alguma inicialização de membros estáticos. A inicialização não pode ocorrer magicamente, qualquer código a ser executado deve estar sempre dentro de um método, no caso o construtor estático.
public class Exemplo {
    static int x = 1;
}

No fundo será gerado algo assim:
public class Exemplo {
    static int x;
    static Exemplo() { x = 1; }
}

Código IL gerado para o código da pergunta (note a existência de dois ctor, um normal e outro de instância e note o beforefieldinit ):
.class private auto ansi '<Module>'
{
} // end of class <Module>

.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    // Methods
    .method public hidebysig static
        void Main () cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 32 (0x20)
        .maxstack 2
        .locals init (
            [0] class MinhaClasse
        )

        IL_0000: nop
        IL_0001: newobj instance void MinhaClasse::.ctor() //   <========= note a chamada ao método de instância
        IL_0006: stloc.0
        IL_0007: ldloc.0
        IL_0008: ldstr "Hello Stackoverflow"
        IL_000d: callvirt instance void MinhaClasse::set_Propriedade(string)
        IL_0012: nop
        IL_0013: ldloc.0
        IL_0014: callvirt instance string MinhaClasse::get_Propriedade()
        IL_0019: call void [mscorlib]System.Console::WriteLine(string)
        IL_001e: nop
        IL_001f: ret
    } // end of method Program::Main

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed
    {
        // Method begins at RVA 0x207c
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method Program::.ctor

} // end of class Program

.class public auto ansi MinhaClasse
    extends [mscorlib]System.Object
{
    // Fields
    .field private string '<Propriedade>k__BackingField'
    .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
        01 00 00 00
    )
    .custom instance void [mscorlib]System.Diagnostics.DebuggerBrowsableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggerBrowsableState) = (
        01 00 00 00 00 00 00 00
    )

    // Methods
    .method public hidebysig specialname
        instance string get_Propriedade () cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x2085
        // Code size 7 (0x7)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: ldfld string MinhaClasse::'<Propriedade>k__BackingField'
        IL_0006: ret
    } // end of method MinhaClasse::get_Propriedade

    .method public hidebysig specialname
        instance void set_Propriedade (
            string 'value'
        ) cil managed
    {
        .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = (
            01 00 00 00
        )
        // Method begins at RVA 0x208d
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: ldarg.1
        IL_0002: stfld string MinhaClasse::'<Propriedade>k__BackingField'
        IL_0007: ret
    } // end of method MinhaClasse::set_Propriedade

    .method private hidebysig specialname rtspecialname static
        void .cctor () cil managed   //<============== construtor estático aqui
    {
        // Method begins at RVA 0x2096
        // Code size 2 (0x2)
        .maxstack 8

        IL_0000: nop
        IL_0001: ret
    } // end of method MinhaClasse::.cctor

    .method public hidebysig specialname rtspecialname
        instance void .ctor () cil managed   //<============== construtor de instância aqui
    {
        // Method begins at RVA 0x207c
        // Code size 8 (0x8)
        .maxstack 8

        IL_0000: ldarg.0
        IL_0001: call instance void [mscorlib]System.Object::.ctor()
        IL_0006: nop
        IL_0007: ret
    } // end of method MinhaClasse::.ctor

    // Properties
    .property instance string Propriedade()
    {
        .get instance string MinhaClasse::get_Propriedade()
        .set instance void MinhaClasse::set_Propriedade(string)
    }

} // end of class MinhaClasse

Coloquei no GitHub para referência futura.
Evite o uso
É recomendando evitar o uso tanto quanto possível principalmente se deseja performance.
É um perigo fazer algo que gere uma exceção em um construtor estático. Quem chamou tem que capturar, certo? Não foi seu código que chamou ele, foi a máquina virtual. Desastre à vista (a classe fica em estado inválido - não as instâncias).
Em versões modernas do C# é possível controlar o momento da inicialização para evitar surpresas.
Parece o construtor estático, mas não é.
Na verdade no exemplo de uso da pergunta o que está chamando não é o construtor estático, é o construtor de instância sem parâmetros que o compilador gera para você (default constructor) para que a classe possa ser instanciada em qualquer situação. O construtor de instância serve para inicializar os membros de instância.
Diferença entre eles
Basicamente é o que eles manipulam e como são chamados. Mas há pequenas diferenças, como a maneira como pode defini-los, por exemplo.
Mais informações:

Para que serve um construtor?
Diferença entre método e construtor?
Como funciona a inicialização de campos em construtores?
Blocos estáticos, herança e construtores em Java (é Java, funciona um pouco diferente em C#, mas dá uma ideia)
Artigo do Jon Skeet
Documentação.
Comment: Eu ia fazer um comentário extra, mas acho que iria criar confusão: no fundo podemos enxergar o construtor de instância como um método estático que gera uma instância.
Answer: Um construtor estático em C# nunca pode ser chamado diretamente através de código (no caso da sua aplicação foi criado um construtor não estático implícito pelo compilador).
O construtor estático é chamado antes da primeira utilização da classe, seja ela uma chamada estática ou através de objeto a esta classe.
A principal finalidade deste tipo de construtor é inicialização de membros estáticos automaticamente, considerando por exemplo que é necessária a chamada de um método específico para inicializar uma propriedade estática desta classe isto poderia ser feito manualmente (chance do programador esquecer de fazê-la e corromper a classe) ou através da invocação do construtor estática pela aplicação automaticamente quando a chamada estática a esta classe for invocada (especificamente antes da chamada).
Complementando ainda, como as outras respostas colocaram:
O construtor estático não pode conter parâmetros e não pode ser invocado manualmente pelo usuário da classe, portanto também não será impactado por modificadores public, protected e private.


Prove $\big|\int_0^1f(x)dx-\frac{1}{n}\sum_{k=1}^{n} f(\frac{k}{n})\big|=O(\frac{1}{n})$

Question: Let $f(x)$ be bounded ($|f(x)|\le M$) and monotonic function on $[0,1]$. Prove $$\big|\int_0^1f(x)dx-\frac{1}{n}\sum_{k=1}^{n} f(\frac{k}{n})\big|=O(\frac{1}{n})$$ My attempt: Let $\big|\int_0^1f(x)dx-\frac{1}{n}\sum_{k=1}^{n} f(\frac{k}{n})\big|=I$ hence $\exists$ $A > 0$ such that $|I|\le \frac{A}{n}$ hence
$$n\cdot\big|\int_0^1f(x)dx-\frac{1}{n}\sum_{k=1}^{n} f(\frac{k}{n})\big|\le n\cdot\big|\int_0^1f(x)dx\big|+\big|\sum_{k=1}^{n} f(\frac{k}{n}) \big|\le n\cdot\big|\int_0^1f(x)dx\big|+\sum_{k=1}^{n}\big| f(\frac{k}{n}) \big|\le nM+nM=2nM\le A $$ hence $A=2nM$. Is that right?  I didn't use the fact that $f(x)$ is monotonic so I think I made a logical mistake somewhere. Please help because I can't figure that out
Comment: So, you've shown that $|I|\leq \frac{A}{n}=2M$, which is not $O(\frac{1}{n})$.
Comment: Is there a step where I did a wrong conclusion or absolutely everything is wrong?
Comment: It's not wrong, just not nearly tight enough.
Answer: Hint: This is just like the integral test in infinite series.  Let's work on the case where $f$ is monotonically increasing.
For fixed $n$, consider the interval $\left[\frac{a}{n},\frac{a+1}{n}\right]$.  Since $f$ is monotonic, $f\left(\frac{a}{n}\right)\leq f(x)\leq f\left(\frac{a+1}{n}\right)$ for $x\in\left[\frac{a}{n},\frac{a+1}{n}\right]$.
Hence,
$$
\frac{1}{n}\cdot f\left(\frac{a}{n}\right)=\int_{\frac{a}{n}}^{\frac{a+1}{n}}f\left(\frac{a}{n}\right)dx\leq\int_{\frac{a}{n}}^{\frac{a+1}{n}}f(x)dx\leq\int_{\frac{a}{n}}^{\frac{a+1}{n}}f\left(\frac{a+1}{n}\right)dx=\frac{1}{n}\cdot f\left(\frac{a+1}{n}\right).
$$
Therefore,
$$\int_0^1f(x)dx=\sum_{a=0}^{n-1}\int_{\frac{a}{n}}^{\frac{a+1}{n}}f(x)dx\leq\sum_{a=0}^{n-1}\frac{1}{n}\cdot f\left(\frac{a+1}{n}\right)=
\frac{1}{n}\sum_{a=1}^{n}f\left(\frac{a}{n}\right).
$$
On the other hand,
$$\int_0^1f(x)dx=\sum_{a=0}^{n-1}\int_{\frac{a}{n}}^{\frac{a+1}{n}}f(x)dx\geq\sum_{a=0}^{n-1}\frac{1}{n}\cdot f\left(\frac{a}{n}\right)=
\frac{1}{n}\sum_{a=0}^{n-1}f\left(\frac{a}{n}\right).
$$
The first inequality gives us
$$
\frac{1}{n}\sum_{a=1}^{n}f\left(\frac{a}{n}\right)-\int_0^1f(x)dx\geq 0
$$
The second inequality gives us
$$
\int_0^1f(x)dx-\frac{1}{n}\sum_{a=1}^{n}f\left(\frac{a}{n}\right)\geq\frac{1}{n}\sum_{a=0}^{n-1}f\left(\frac{a}{n}\right)-\frac{1}{n}\sum_{a=1}^{n}f\left(\frac{a}{n}\right)=\frac{1}{n}(f(0)-f(1))
$$
or that
$$
\frac{1}{n}\sum_{a=1}^{n}f\left(\frac{a}{n}\right)-\int_0^1f(x)dx\leq\frac{1}{n}(f(1)-f(0))\leq\frac{1}{n}\cdot 2M
$$
Hence, the difference is at most $\frac{2M}{n}=O\left(\frac{1}{n}\right)$.
Comment: This is for monotonic increasing. For decreasing, the inequalities go the other way, but the bounds remain the same.


Subtraction of two column in views

Question: How to subtracts two column in view?
for example:
 say column A and Column B need to subtract i,e [column A - column B]= column C.How can I achieve this is there any module available for it?
Answer: Add another field, select Math Expression from Global group, then in there put something like [field_1_total] 2 [field_2_total]
there is not need any addition module
Comment: i am using view aggregation for one column is field from content type another column is a count getting using aggregation module in simple words one column is not field which is there in content type its a custom field added now i want difference of column1 -column2
Comment: is it [field_1_total] 2 [field_2_total] or [field_1_total] - [field_2_total] ....?
Comment: @though field tokens are listing and i am giving something  [field_total] - [title_1] its showing only first column result....not substracting
Comment: @Vicky8888: i am subtracting tokens but its not considering its retaining the first column result....its not substracting
Comment: go to view ->add Global:math expression from the list of available fields->then go expression textfield of Global:math expression->put there [field_total] - [title_1]
Comment: @Vicky8888: I did this only please check the screen shot
Comment: where is screen shot?
Comment: question i have edited now...i have added there screen shot check
Comment: once check fields u r subtracting are of same type (eg:textfield)
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/31692/discussion-between-neethu-and-vicky8888).
Answer: You can try using Views Calc.
Comment: No, this is not good solution, he can achieve it with `Global:math expression` field
Comment: I think this only does math operations for rows and not columns.
Comment: i think it allows to SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns in Views.

Subtraction of two column in views


Let $G=(V,E)$ an undirected graph. Find a cut such that $|E(A)|\geq |E\setminus E(A)|$

Question: Let $G=(V,E)$ an undirected graph and let $A$ be a cut of $G$. Define $E(A)=(A\times (V\setminus A))\cap E$. Find an algorithm that finds a cut $A$ such that $|E(A)|\geq |E \setminus E(A)|$.
So I thought about that algorithm:
i. $A\leftarrow \emptyset$
ii. Find $v\in V$ such that $E(A\cup {v})>E(A)$. If there exists such a $v$ go to iii, otherwise go to iv.
iii. $A\leftarrow A\cup {v}$. return to ii.
iv. return $A$.
I am pretty sure that this is a maximal cut, that is, $E(A)$ is maximal for $G$ but I think there is a better algorithm. If I am not mistaken, finding such a $v$ in step ii will be $O(E)$ and we do it $O(V)$ times so we can say it is $O(VE)$. Maybe we can make it a little lower or is there a better algorithm anyone can think of?
Answer: A more efficient algorithm is to:

Start with $A = B = \varnothing$.
For each vertex $v \in V$, compare the number of neighbors $v$ has in $A$ or $B$, and add it to the one where it has fewer neighbors.
Once every vertex is in either $A$ or $B$, return $A$.

If $v_1, v_2, \dots, v_n$ are the vertices of $V$ in the order that we can consider them in step $2$, we can partition the edge set of $G$ into $n$ parts  $E_1, E_2, \dots, E_n$ where $E_i = \{v_i v_j \in E : i > j\}$ is the set of edges whose second vertex to be considered is $v_i$.
Then in step 2 of the algorithm, when we're deciding where to put $v_i$, $E_i$ is the set of edges under consideration. Since we place $v_i$ so that $|E_i \cap E(A)| \ge \frac12|E_i|$, in the end, we'll get
$$
   |E(A)| = |E_1 \cap E(A)| + \dots + |E_n \cap E(A)| \ge \frac12|E_1| + \dots + \frac12 |E_n| = \frac12 |E|.
$$
In other words, $|E(A)| \ge |E \setminus E(A)|$.
As far as efficiency goes: given an appropriate data structure to use for the graph, step 2 has $O(\deg v)$ time complexity, and so the overall time complexity is $O(|V|+|E|)$.
Comment: Wow I never thought you can do that so efficiently. Thanks a lot!!!
Comment: Just one question, in the case $E=\emptyset$ then the time complexity is $O(|V|)$ because we check each vertex, so won't we say the complexity is $O(|V|+|E|)$?
Comment: @sssss fair enough; I guess I assumed there'd be a reasonable number of edges.
Comment: Generally you are right, but in the course I am taking they make us write it as O(|V|+|E|) xD


Spring Websocket not working with ssl (wss)

Question: I have an application with a websocket connection between a Spring backend and an Angular Frontend behind a Spring Cloud Gateway which works perfectly via http / ws but doesn't work at all.
What I tried and what worked:

starting the angular frontend and spring backend directly
starting the angular frontend and the spring backend locally with docker behind a local spring cloud gateway
exposing a port directly on the backend docker container (emitting the gateway which usses ssl on the server) and starting the angular frontend locally against that backend (with angular proxy)

What does not work:

starting the backend with a docker container and using the websocket with https/wss

I configured the spring cloud gateway as described here https://cloud.spring.io/spring-cloud-gateway/reference/html/:
    - id: websocketinfo
      uri: http://app
      predicates:
        - Host=app.domain.com
        - Path=/api/ws/info/**
    - id: websocket
      uri: ws://app
      predicates:
        - Host=app.domain.com
        - Path=/api/ws/**

The only difference between my local gateway (with which the websocket communication works) and the server gateway is that I have ssl enabled on the server with a p12 key
The error message that I get in the spring cloud gateway is:
io.netty.handler.codec.http.websocketx.WebSocketHandshakeException: Invalid handshake response getStatus: 403

In the Spring Backend Service I get these errors a lot:
2020-04-09 07:03:55.298  WARN 1 --- [p-nio-80-exec-4] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: No converter for [class java.util.LinkedHashMap] with preset Content-Type 'application/javascript;charset=UTF-8']

This confuses me a lot since that seems like the kind of error that should happen no matter which environment you run the application in
Answer: So apparently this was a bug with an older version of spring cloud gateway. After updating to spring version 2.2.1 everything worked with ssl too


Change title of certain paragraphs in a form

Question:

Please see the attached pictures. In one of my projects I have a taxonomy, which users can edit and add data. It has multiple tabs (see picture one) and each tab has multiple fields in which paragraphs can be added (see picture two).
We have different kinds of paragraphs with each different titles. Our problem is that we want to show each paragraph to the end-user (see the second picture, the button "Meting (decimaal) toevoegen") with a title of "meting" while maintaining the more descriptive titles for the admins and developers.
One option is changing the title for the end-user while maintaining the actual title in the DB. The other one would be changing the actual title in the DB and change it for the admins (setting the system name as the title).
and I've tried all kinds of hooks but can't wrap my head around this problem.
Solution:
Due to the structure of the site, I couldn't get any hook solutions to work. So I wrote my own module, which attaches the javascript below to the form.
<code>(function ($) {
  'use strict';

  Drupal.behaviors.test_form_styles = {
    attach: function (context, settings) {
      var regEx = /(?:meting)/i;
      var paragraphTitles = document.getElementsByClassName("paragraph-type-title");
      Object.keys(paragraphTitles).forEach(function (key) {
        if (regEx.test(paragraphTitles[key].innerHTML)){
          paragraphTitles[key].innerHTML = "Meting";
        }
      });

      var submitButtons = document.getElementsByClassName("field-add-more-submit");
      Object.keys(submitButtons).forEach(function (key) {
        if (regEx.test(submitButtons[key].value)) {
          submitButtons[key].value = "Meting toevoegen";
        }
      });
    }
  }
} (jQuery));
</code>
Comment: There are many different directions you can take to "solve" this, it all depends on why you need to make this change. If users understand the shorter version, why would admins need it with more info? Maybe you can add a custom permissions field for admins that label it a certain way? You could use String Overrides https://www.drupal.org/project/stringoverrides/issues/1355174, this answer is relevant: https://drupal.stackexchange.com/questions/233142/how-can-i-override-strings#answer-233144 Your best bet is probably a custom module with hook form alter and user role condition.
Comment: @prkos the admins need the more descriptive version for when they want to make changes in the paragraphs. It's hard selecting the right paragraph if 8 of them are named the same. For the end-users we want to provide them with the most friendly interface.

Unfortunally stringoverrides is only available for 7.x and not 8.x. I've tried hook_form_alter, but I can't find a way to target the right paragraph fields and change their title.
Comment: AFAICT there has been work done on String overrides for D8 so you can check that out. Also try searching for hook form alter questions, or ask a new question targeting that specific scenario.
Answer: If you want to change the title of certain paragraphs in the form:
<code>/**
 * Implements hook_field_widget_WIDGET_TYPE_form_alter().
 */
function mymodule_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'foo') {
    // insert more conditions
    $element['top']['paragraph_type_title']['info']['#markup'] = t('New title for paragraph type Foo');
  }
}
</code>
Comment: thanks! I've tried using the hook, but since I use paragraphs placed in other paragraphs with multiple types of paragraphs, I wasn't able to get it to work. In the end I used a javascript solution (see editted question).
Comment: Perfect, this answer is for the question title others will find when googling and then they have the javascript solution for more advanced cases.


What is meaning of high AIC value?

Question: I have a query related AIC value. I am getting very high AIC values while selecting multiple regression model, ranging from 4300-4600. Is it possible to get such high AIC values?
Answer: Since the AIC scales linearly with the number of parameters it is easily possible to get a high AIC score. However, its absolute size is really not all that important.
Instead, the AIC is used mainly to select between different models where the lowest score is the most preferable. The difference in the AIC scores for two different models can be interpreted as 'extra information lost' by using the worse model in comparison to the better model.
See also Wikipedia. If you're interested in a score which has a cleaner interpretation you might also be interested in the BIC.

What is meaning of high AIC value?


bash one-liner loop over directories throws errors

Question: I'm trying to build a bash one-liner to loop over the directories within the current directory and tar the content into unique tars, using the directory name as the tar file name.  I've got the basics working (finding the directory names, and tarring them up with those names) but my loop tosses some error messages and I can't understand where it's getting the commands its trying to run.
Here's the mostly-working one-liner:
for f in `ls -d */`; do `tar -czvvf ${f%/}.tar.gz $f`;done

The "strange" output is:
-bash: drwxrwxr-x: command not found
-bash: drwxr-xr-x: command not found
-bash: drwxr-xr-x: command not found
-bash: drwxrwxr-x: command not found

What portion of the command that I'm running do I not understand and that's generating that output?
Answer: You need to remove the backtics around your tar command.  You also might want to pipe the ls through xargs to  make sure bash picks up all the directories correctly:
for f in `ls -d */ | xargs`; do tar -cvzf ${f%/}.tar.gz $f; done

The backticks are capturing the ouput of tar and attempting to execute that as a command in each iteration of the loop.  The first thing tar prints when you use a -v option is the permissions on each file (e.g. the drwxrwxr-x).  In this case, you want bash to execute the tar command, not capture the output.
Comment: Most excellent - thanks for both the resolution, and more importantly for explaining the what and why.  Highly appreciated!
Answer: bjlaub is correct regarding the backticks around tar, however you don't need to use ls:
for file in */

will do the trick and will properly handle directory names with spaces.
Comment: Indeed you're correct.  Good to know :)
Answer: The other answers here are good, but I wanted to add another option in case you need to get just directories and not symbolic links, etc:
for f in `find -maxdepth 1 -type d` | do -cvzf ${f%/}.tar.gz $f; done

Hope this helps!


fopen returns NULL when opening existing files in Linux

Question: In my laboratory work I need to read data from 2 files and get a resulting file.
I tried using fopen for reading existing files and creating a new one.
FILE* file1 = fopen("1.txt", "r");
FILE* file2 = fopen("2.txt", "r");
FILE* fileRes = fopen("res.txt", "w");

Unfortunately, fopen for file1 and file2 returns NULL, even though fileRes was sucessfully opened. Futhermore, I can't read data from file1 and file2 which results in incorrect output.
Here is my directory:

As you can see files 1.txt and 2.txt are present in directory and file res.txt was sucessfully created.
All files have read/write permissions:
-rw-r--r-- 1.txt
-rw-r--r-- 2.txt
-rw-r--r-- res.txt
Comment: @VeceluXa It means fopen succeed and return not NULL. Something wrong happens later. Hard to say not seeing full code. With debugger, it may be optimized out if you compile with optimization enabled.
Comment: @VeceluXa can you print it in runtime? E.g. `printf("%p\n", (void *)file1)` right after `fopen()`?
Comment: @anastaciu, these files are not any different from one another. I just need to use them in certain order. That's why I used digits instead of other names.
Comment: What is `errno` value after failure? You also can print corresponding error message with `perror()`.
Comment: @dimich, after fopen errno equals 0. When I try to read from this file errno equals 2 and prints "Error occurred while opening file. : Bad file descriptor"
Comment: @anastaciu, if I use "1.txt.txt" fopen also returns NULL.
Comment: @VeceluXa `errno` can't be 0 after `fopen()` return NULL. Please show complete code how do you check it for NULL and print errno value.
Comment: @anastaciu, If I change filename to something other than digits (like text_file.txt) fopen still returns NULL. Also removing .txt extension does not help either
Comment: @anastaciu, If I change filename to something other than digits (like text_file.txt) fopen still returns NULL. Also removing .txt extension does not help either
Comment: @dimich,
`errno = 0;
FILE *file1 = fopen("text_file", "r");
printf("%s", strerror(errno));`
With this code strerror(errno) prints nothing. When I try to read from file before strerror I get "Error occurred while opening file. : Bad file descriptor"
Comment: @VeceluXa But how do you know `file1` is NULL? What code does check it?
Comment: @dimich I check it in gdb debugger using vscode.
Comment: @anastaciu, I managed to write "String" in my result file using fputs.
Comment: @dimich, well, it's strange. In runtime this line printed random address (0x5653c13806d0), but while debugging it prints "(nil)".
Answer: Actually fopen was working just fine. NULL was showing in my debugger (gdb in vscode), while in runtime printf("%p\n", (void *)file1) printed some random address in memory.


How to expand the matrix in Matlab (forming $A$ matrix in least square problem)

Question: If I have 5 data points (actually, this could be vary huge number):
$a = [1;2;3;4;5]$
To each data point, I can form a matrix $[a(i),2a(i)]$. (actually, I have to find the matrix, this matrix needs some calculation.)
For example, $[a(i)\times 2+3, 3\times a(i)cos \theta]$
Therefore, I can form 5 such matrices with different values.
Now, If I want to form a big matrix:
$A = \begin{bmatrix}1 & 2 \\2 & 4 \\3 &6 \\4&8\\5&10 \end{bmatrix}$.
One way to do it is by for-loop. Is there any compact way to do it? (If number of data points is very large).

I want to use this technique to form the $A$ matrix in the least square problem. And I have 200 measurements.
Answer: I don't know if I understood you well, but if you have:

the data array $\mathbf{x}=\begin{bmatrix}x_{1}\\
x_{2}\\
\vdots\\
x_{n}
\end{bmatrix}$
the meassurements array $\mathbf{y}=\begin{bmatrix}y_{1}\\
y_{2}\\
\vdots\\
y_{n}
\end{bmatrix}$

you can create the matrix:
$$\mathbf{A}=\begin{bmatrix}x_{1} & y_{1}\\
x_{2} & y_{2}\\
\vdots & \vdots\\
x_{n} & y_{n}
\end{bmatrix}$$
just with the code:

A = [ x, y ] ;

I hope it was usefull to you
Comment: if the different rows don't follow any nice general formula the best thing you can use is a for-loop, but it's faster if matlab knows from the beggining the size of A, so it's faster if you add, A = zeros( N, 2 ) before the for-loop.
Comment: No, this is not what I ask.  Since I have to find each row (not known before calculating), so I cannot pile up by hand. I edit my problem, hope it is more clear.


Unable to create an ec2 instance using boto3

Question: I am not able to create an EC2 instance using boto3.
I am trying to create an instance using boto3.
ec2 = boto3.resource('ec2')
ec2.create_instances(ImageId='ami-0d8f6eb4f641ef691', MinCount=1, MaxCount=1, InstanceType='t2.micro')

My region is US East(Ohio)
I am not sure how to find the AMI to a specific region. I just selected what was available.
The error message is
botocore.exceptions.ClientError: An error occurred (InvalidAMIID.NotFound) when calling the RunInstances operation: The image id '[ami-0d8f6eb4f641ef691]' does not exist

and I copied the AMI ID from the:
Answer: I think you are missing the region_name parameter.
You can set the region_name is your code as:
ec2 = boto3.resource('ec2', region_name='us-east-2')

Hope it helps.


Objeto como parâmetros para API C#

Question: Tenho uma requisição feita no Angular para o C#. Entretanto não sei como receber os dados na Minha API No C#.
<code> getWithFilters(filter: any) {

    let parametros: any = {
        razaoSocial: filter.razaoSocial,
        cnpj: filter.cnpjcpf,
        telefone: filter.telefone
    }

    return this.http
        .get(this.UrlService + '/Clientes', parametros)
        .map((res: any) => res.data)
        .catch((super.serviceError));
}
</code>
Assim faço a requisição, entretanto no C# Como faço para receber estes parâmetros?
Agradeço desde já.
Lucas.
Comment: Você pode criar uma ViewModel refletindo o seu objeto para que a API faça a serialização/deserialização no C# para receber e responder o objeto para o seu client. Como está a sua API?
Comment: Ahh isso era bem importante,  eu não tinha reparado.
Comment: Seria legal você colocar a sua solução como resposta para que essa pergunta possa ajudar outros usuários no futuro.
Comment: Angelo, consegui o que queria, entretanto deixei de utilizar o GET e passei a enviar via POST. Pois como se sabe no GET não temos como enviar um body. De toda forma, agradeço pela ajuda.
Comment: Sim sim, eu acabei esquecendo na hora também. De toda forma, obrigado.
Comment: Vou fazer isso... obrigado pela ideia.
Answer: Consegui realizar o que eu queria. Entretanto deixei de utilizar o GET e passei a enviar via POST. Pois no GET não temos como enviar um body.

Objeto como parâmetros para API C#


What do these numbers mean? A4, G5, etc

Question: I'm learning how to play a G key Xiao flute.
I found this fingering chart:

But i don't understand the meaning of the numbers in front of each note.
Well, actually i don't understand anything because i don't have any idea of music.
What do the numbers after each note name mean?

The story:
For all my life i loved Chinese music, this sweet melancholic sound from flutes,xun and erhu.
I never had any music instrument in my life and also i cannot read music.
Although i am a little old i decided and i bought a Xiao flute G key 8 holes right hand, well better late than ever.
As i wrote above i don't have no idea what notes are, how to read music and i never had any music instrument.
But i fight a terrible disease and because i love music and flutes i believe this step it will give me energy, it will give me life.
It was always a dream for me to play flute.
So, please help me to learn how to play the Xiao flute.
Please!!
Thank you!
God bless!
Answer: I assume you mean the numbers after the notes? In this case, the numbers are what are called "octave designations." C4 is middle C, C5 is an octave above that, etc. So the D4 on the top left of that image is the lowest D that this flute can play.

Otherwise, I'm not sure how effective a website will be in teaching you to play the Xiao flute. Something as involved as learning an instrument requires consistent feedback from an experienced professional; one answer here can never come anywhere close to that. Is it possible you can find a teacher in your area?
Comment: Thank you. No is not easy to find teacher in my area. Everyday i search, i read, i learn. I use the above fingering chart and i read everything i found about music and xiao playing.

What do these numbers mean? A4, G5, etc


Understanding how to calculate orthogonal projection operator

Question:
Let $\mathcal{H} =\mathbb{C}^2, \mathcal{M}_1 = \mathbb{C}|0\rangle$ with $|\psi\rangle = \alpha |0\rangle + \beta|1\rangle$. Show $Pr(\mathcal{M_1}) = |\alpha|^2.$

We know that $\mathcal{M_1}$ is a subspace of the Hilbert space $\mathcal{H}$, and that $Pr(\mathcal{M_1}) = \langle \psi| Proj_\mathcal{M}|\psi\rangle.$
I'm confused on how to interpret the bra ket notation here and how to actually calculate $Pr(\mathcal{M_1})$ using the formula and information given.
Answer: Let any linear subspace $\mathcal M$ for a (for simplicity's sake: finite-dimensional) Hilbert space $\mathcal H$ with $\{u_1,\ldots,u_k\}$ being any orthonormal basis of $\mathcal M$ be given. Then the orthogonal projection onto $\mathcal M$ is given by $P_{\mathcal M}=\sum_{i=1}^k |u_i\rangle\langle u_i|$ so the probability of finding a pure state $|\psi\rangle$ in there is given by
$$
\langle\psi|P_{\mathcal M}|\psi\rangle=\sum_{i=1}^k |\langle\psi|u_i\rangle|^2\ .
$$
Side note: if the state of the system is not pure $|\psi\rangle\langle\psi|$ but a general mixed state $\rho$ (positive semi-definite, trace 1) then the expectation value generalizes to $\operatorname{tr}(\rho P_{\mathcal M})$---and if $\rho$ is pure then we get back $\langle\psi|P_{\mathcal M}|\psi\rangle$ as expected.


Apache server status does not work with ?auto param

Question: What reason could there be for apache's server-status the ?auto param to result same output as without using ?auto  ?
Answer:
Ensure that your Apache config has something like this and that
you're requesting the URL at /server-status?auto

<Location /server-status>
SetHandler server-status
</Location>

Make sure that no proxy / cache in front of Apache is altering the request. To do this check the access log to make sure the request contains the ?auto such as "GET /server-status?auto HTTP/1.1".


Suggestions for identifying key features

Question: I have a large set of customer data.  For these customers, I have devised a customer loyalty score which is a measure of the loyalty of the customer.  I want to find the features that are strongly associated/correlated with this score.  Features could be number of purchases at various merchant types.
One obvious answer would to be just to calculate the correlation for each feature with the customer loyalty score and see which have the highest correlations.  Is this preferred way of doing this or are there better techniques?
Answer: One way to reformulate your problem is the following: you want to select a small set of features that predict well the loyalty score, using a linear model for example. This problem is called (best) subset selection.
Suppose that you want to pick k features. The first way to do it is to test all the subsets of k features, by doing linear regression on each subset. But for large dataset, this is way too long.
Another way to do it is in a greedy way. You start by picking the feature that is the most correlated with the score and add it to the (empty) subset. You compute the linear model associated to this subset (in this case, just a coefficient) to predict the loyalty score. Then, you pick the feature which is the most correlated with the residual (the difference between the value predicted by your linear model and the true score) and compute the linear model corresponding to your new subset. You do so, until you have k features in your set.
There are other methods, such as the lasso, to do subset selection. For a more complete introduction to subset selection, you should read the section 3.3 of The Elements of Statistical Learning, which is freely download-able on the authors' site.
Answer: I understand that the loyalty score is calculated on the strength of some data. If your features include components that are used in calculating the loyalty score they will prove evidently influential.
Multivariate techniques are probably more useful than pairwise correlations:

they can detect weaker features that may be useful in combination with stronger ones
they can reveal that some features have very similar information content.

The most simple way to start with could be multiple linear regression, although other methods may be better depending on many conditions.
Comment: So from multiple linear regression you end up with weight vector.  I am assuming that a larger weight means a stronger feature.  What I am hoping to find are some key drivers that help maximize the customer loyalty score.
Comment: Re weights: if feature A and B are both predictive, but strongly correlated they may have relative low weights (weight shared between them). Re drivers: from observations you can only get associations, not cause-effect relationships; however your knowledge on the mechanisms may help you decide what are causes, effects or just correlates among the associations.
Answer: Sounds like Business Intelligence work (http://en.wikipedia.org/wiki/Business_intelligence). Could you confirm if it's a customer database or a survey that you ran? Both? Is it from a CRM database? Are customers segmented? Demographically/Physcographically? We need more detail as to what you have.
If it's a customer database, correlations tell a story about how features load upon your score but not the only story (cor != cause). If you have transactional information you can run survival analysis and calculate life time value (always useful).
We need to know a lot more about your variables in order to make recommendations of "what to do with it"
Comment: For the first version of this project, I don't want to consider demographic or physical location.  What I want to look at is the transactional data for each customer.  For each customer, I have purchase history which includes the merchant where they made the purchase and amount.  I have grouped merchants into merchant types and I will be examining features that are counts of purchases at a merchant type over the life of the customer and dollar amount at a merchant type over the life of the customer.
Answer: In addition to the suggestions from the previous answers, I would suggest the catdes function from the FactoMineR package in R. It gives a description of the categories of one factor by qualitative variables and/or by quantitative variables. The output is briefly explained in the manual but I think it would be worth to have a look at the reference mentioned there. The idea is that you get a list of the variables that characterise the most the factor along with a p-value to assess significance.
Note 1 I think that the function is particularly used in a "cluster analysis" context.
Note 2 It requires to discretise your "customer loyalty score"...
By the way, about three years ago I used that function and I had a question about it. I wrote an email to the author (mentioned in the manual) and he kindly answered me!


existence of a PDE problem

Question:
Consider $u''(x)+u'(x)=f(x)$ and $u'(0)=u(0)=\frac{1}{2}[u'(l)+u(l)]$. Does a solution necessarily exist, or is there a condition that f(x) must satisfy for existence?

I proved that the solution is not unique, but I am not sure the strategy in tackling this problem. Any help is appreciated for me to begin.
Comment: Probably best to use the second Fredholm alternative. Also, I'm pretty sure this exact question has been asked on the site before.
Answer: We first solve the IVP
$$u''+u'=f(x),\qquad u(0)=u'(0)=0\ .$$
The auxiliary function $v(x):=e^x u'(x)$ satisfies
$$v'(x)=e^x f(x),\qquad v(0)=0\ .$$
It follows that
$$v(x)=\int_0^x e^\tau f(\tau)\>d\tau$$
and then
$$u(x)=\int_0^x e^{-t} v(t)\>dt=\int_0^x \left( e^{-t} \int_0^t e^\tau f(\tau)\>d\tau\right)\>dt$$
This particular solution $u_0$ can after some manipulation of integrals be rewritten as
$$u_0(x)=\int_0^x\bigl(1-e^{\tau-x}\>f(\tau)\bigr)\>d\tau\ .$$
Therefore we obtain the following general solution of the original ODE:
$$u(x)=c_0+ c_1e^{-x}+u_0(x)\qquad(0\leq x\leq \ell)\ .$$
Now we have to take care of the boundary conditions
$$c_0+c_1=-c_1={1\over2}\bigl(c_0 +C\bigr)\ ,\tag{1}$$
where
$$C=u_0'(\ell)+u_0(\ell)=e^{-\ell}v(\ell)+u_0(\ell)=\int_0^\ell f(\tau)\>d\tau\ .$$
The first condition $(1)$ enforces $c_1=-{c_0\over 2}$, and then the second condition can only be satisfied if $C=0$, whereby $c_0$ may be arbitrary. Therefore we have the following alternative:
If $C:=\int_0^\ell f(\tau)\>d\tau\ne0$ the given boundary value problem has no solution. If $C=0$ the problem has infinitely many solutions given by
$$u(x)=c_0\left(1-{1\over2}e^{-x}\right)+u_0(x),\qquad c_0\in{\mathbb R}\ .$$

existence of a PDE problem


How to combine multiple lists asynchronously

Question: I am not getting how to combine two list producing tasks into a common list.  The below code is incomplete and/or wrong, but I think will get my dilemma across. The OrderFactory requests data from an Internet server. Each OrderFactory completes at some future time and independent of any other OrderFactory. How can the List orders returned from each task be combined into one list? Both tasks are to start together but will return at a different future time.
TIA
        private async Task<List<Orders>> GetReturnToOfficeOrdersAsync(PatientService patient)
        {
            var orders = new List<Orders>();
            var x =  await OrderFactory.CreateOrders(OrderType.RETURNTOOFFICE, patient);
            orders.AddRange(x);
            return orders;
        }

        private async Task<List<Orders>> GetProceduresAsync(PatientService patient)
        {
            var orders = new List<Orders>();
            var x = await OrderFactory.CreateOrders(OrderType.PROCEDURE, patient);
            orders.AddRange(x);
            return orders;
        }

        private async Task GetInCompleteOrderListAsync()
        {
            if (patient == null) return;

            var orders = new List<Orders>();

*** THE LISTS FROM THESE TASKS NEED TO BE COMBINED INTO ONE LIST -- HOW???
            var a = GetReturnToOfficeOrdersAsync(patient);
            var b = GetProceduresAsync(patient);
            await Task.WhenAll(a, b);

            orders = orders.OrderByDescending(o => o.torder).ToList();

            IncompleteOrders = new ObservableCollection<Orders>(orders);
        }

Comment: What's wrong with simply `orders.AddRange(a.Result); orders.AddRange(b.Result);`?
Comment: Since there is nothing asynchronous about combining two or more lists - standard approaches to combine lists apply (hence duplicate). To get the results of multiple asynchronous operations use link provided by @AlanWayne http://stackoverflow.com/questions/17197699/awaiting-multiple-tasks-with-different-results.
Comment: @SamiKuhmonen Ugh. Nothing. Also found answer at http://stackoverflow.com/questions/17197699/awaiting-multiple-tasks-with-different-results. Thanks.
Answer: If you want to add results of tasks a and b to orders, you can use method AddRange:
var orders = new List<Orders>();

var a = GetReturnToOfficeOrdersAsync(patient);
var b = GetProceduresAsync(patient);

orders.AddRange(await a);    // add result of task a to the list
orders.AddRange(await b);    // add result of task b to the list

Comment: why not `await Task.WhenAll(a,b)`, this will make calling `tasks a,b` serial
Comment: The calls are not serial since it is not awaiting them immediately. Variables are a and b are tasks that are kicked off immediately. Then both results are awaited after the tasks have been created.


Preserve array when submitting a form to a JSON file

Question: I have a form that takes in data and writes to a JSON form in PHP.
I needed to submit an array as a numeric input but it keeps giving me a string. Is it possible to enable the form to submit as an array via text input box?
Form example:
<input type="text" name="arraytobepushed[]" placeholder="EG: 1000,2000,3000" />

The output is:
{
"obj": [{
   "arraytobepushed": ["1000,2000,3000"]
       }]
}

Comment: There's no such thing as an array type in HTML inputs. If you want an array from a string input delimited by commas, you have to split the string yourself.
Comment: simply you can not write `array` into `html` input box and think it will going to treat as `array` in `php`. it will be treated as a string. So put comma separated values and then in `php` `explode()` that .it's easy
Answer: You could turn the text into an array by using explode() So you would have something like this:
<?PHP
  $myArray = explode(',', $_POST['arraytobepushed[]']);
?>

The explode() function splits everything separated by the first argument (in this case a comma) you pass and puts it into an array.
So if your inputted was 1000, 2000, 3000 your $myArray would look like:
index 0 = "1000" ($myArray[0])
index 1 = "2000" ($myArray[1])
index 2 = "3000" ($myArray[2])
Keep in mind that the values are still strings, not integers. If you want to make them integers you can do this:
$myArray = array_map('intval', explode(',', $_POST['arraytobepushed[]']));

This makes all your elements into integers like so:
index 0 = 1000 ($myArray[0])
index 1 = 2000 ($myArray[1])
index 2 = 3000 ($myArray[2])
Answer: No. Forms submit text.
PHP special cases fields with [] in the name as fields to be expressed in an array. It has no special case feature to treat a field as a number instead of a string. You need to convert the data explicitly.


How to return non-duplicate values of array of object

Question: var newarray=
[ { value: 'Large', name: 'Size' },
{ value: 'Red', name: 'Color' },
{ value: 'Cotton', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' },
{ value: 'Large', name: 'Size' },
{ value: 'Red', name: 'Color' },
{ value: 'Jute', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' },
{ value: 'Large', name: 'Size' },
{ value: 'Green', name: 'Color' },
{ value: 'Jute', name: 'Material' },
{ value: 'Affinity', name: 'Collection' },
{ value: 'Pine Montage', name: 'Style' } ];

Here is my array i need to find unique array of object with non-repeated values in an array ,Please help
Comment: So perhaps loop through the input array, adding items to another array if they're not already present? Where are you stuck?
Comment: ok let me try this ! thanks for your suggestion
Comment: can you tell me how i will compare object of new temp array and the old array
Answer: I suggest to iterate over the array and filter the items with a look up if the item is stored in a hash map.

var array = [{ value: 'Large', name: 'Size' }, { value: 'Red', name: 'Color' }, { value: 'Cotton', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }, { value: 'Large', name: 'Size' }, { value: 'Red', name: 'Color' }, { value: 'Jute', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }, { value: 'Large', name: 'Size' }, { value: 'Green', name: 'Color' }, { value: 'Jute', name: 'Material' }, { value: 'Affinity', name: 'Collection' }, { value: 'Pine Montage', name: 'Style' }],
    unique = function (a) {
        var o = {};
        return a.filter(function (b) {
            var k = b.name + '|' + b.value;
            if (!(k in o)) {
                o[k] = true;
                return true;
            }
        });
    }(array);

document.write('
' + JSON.stringify(unique, 0, 4) + '
');
Answer: You can use Set for getting unique values
var uniq = Array.from(new Set(newarray.map(function(a) {
    return JSON.stringify(a);
}))).map(function(a) {
    return JSON.parse(a)
});

console.log(uniq); // will print your unique values


Java - get index of key in HashMap?

Question: In java if I am looping over the keySet() of a HashMap, how do I (inside the loop), get the numerical index of that key?
Basically, as I loop through the map, I want to be able to get 0,1,2...I figure this would be cleaner than declaring an int and incrementing with each iteration.
Thanks.
Comment: What's even better is that two HashMaps that are equal can still have different orderings. They can do it *even if they have the same history of adds/removes* (different capacities would do it).
Comment: What do you need it for? As mentioned in the answers, order in a map is not necessarily constant, it can change when keys get added or removed.
Comment: http://stackoverflow.com/questions/18188739/arraylist-of-hashmap-or-linkedhashmap-to-get-item-by-index/18959271#18959271
Answer: Use LinkedHashMap instead of HashMap
It will always return keys in same order (as insertion) when calling keySet()
For more detail, see Class LinkedHashMap
Comment: Order may not be important - we may only need to test for first or last read pair for instance.
Answer: Not sure if this is any "cleaner", but:
List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

Comment: Or similarly: `int index = 0; for (Object key : map.keySet()) { `Object value = map.get(key); ++index; } // dang formatting
Answer: The HashMap has no defined ordering of keys.
Comment: But LinkedHashMap does
Answer: If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:
for (Object key : map.keySet()) {
    Object value = map.get(key);
    //TODO: this
}

Or, you can iterate over the entries of a map, if that is what you are interested in:
for (Map.Entry<Object, Object> entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
    //TODO: other cool stuff
}

As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.
Answer: You can't - a set is unordered, so there's no index provided. You'll have to declare an int, as you say. Just remember that the next time you call keySet() you won't necessarily get the results in the same order.
Comment: If the OP does really *want* this, it is not hard to write a collection backed by a TreeSet and a Map.  That way you can get the results always in the same order.  Now as to how to behave when the Map is modified during iteration is up to the OP but a data structure that is a map where the keys are in an ordered set is definitely doable.  (btw I'm more commenting on your answer than on the OP's question).
Comment: This answer is wrong.
Whilst it is true that a set per se is unsorted a LinkedHashMap does indeed keeps the insertion order so on iteration it is possible to get it index based
Answer: Simply put, hash-based collections aren't indexed so you have to do it manually.
Comment: What is the recommended data structure in this case?
Answer: Posting this as an equally viable alternative to @Binil Thomas's answer - tried to add it as a comment, but was not convinced of the readability of it all.
int index = 0;

for (Object key : map.keySet()) {
   Object value = map.get(key);
   ++index;
}

Probably doesn't help the original question poster since this is the literal situation they were trying to avoid, but may aid others searching for an easy answer.
Answer: I was recently learning the concepts behind Hashmap and it was clear that there was no definite ordering of the keys.
To iterate you can use:
Hashmap<String,Integer> hs=new Hashmap();
for(Map.Entry<String, Integer> entry : hs.entrySet()){
      String key=entry.getKey();
      int val=entry.getValue();
      //your code block
  }

Answer: I don't know is this what you're looking for
List keys = new ArrayList(map.keySet());
int index = keys.indexOf(element);

Answer: You can directly get the keys in Set<K> keySet().
val teamMember = hashMapOf(
            "Coach" to "manager",
            "Player Coach" to "editor",
            "Player" to "member",
            "Supporter" to "readonly"
        )

teamMember.keys.forEachIndexed { index, key ->
   // Here is your key in string
}

Java - get index of key in HashMap?


Can't log in to back end

Question: I have been trying to upgrade to 8.8.3 from 8.4.4 for some time. My 8.4.4 site was holding but after repairing a database malfulnction in which the watchdog file went mad with assert errors, now I can't login to the back end. After failing to login using the login module on the front page, the WSOD appears with this meesage.
'''The website encountered an unexpected error. Please try again later.Drupal\Core\Extension\InfoParserException: Missing required keys (core) in core/modules/path_alias/path_alias.info.yml in Drupal\Core\Extension\InfoParserDynamic->parse() (line 29 of core/lib/Drupal/Core/Extension/InfoParserDynamic.php).'''
I don't know where to start with this.
Comment: Do you have try to clear browser cache and cookies?
Comment: I test in three browsers, Chrome and Firefox on Windows and Safari on the Mac. And I try to empty the caches.
Comment: Have you run the database update script?
Answer: This is due to the new core_version_requirement key taking the place of the core key in module.info files. Here's the change record: https://www.drupal.org/node/3070687.
A dirty hack to get around this would be to add the following to path_alias's .info file:

core: 8.x

I would do this only for the purpose of getting your site back in order, and remove the key afterwards. You are likely to run into this error, or similar, for other modules as well. I think that disabling the path_alias module, and any other troublesome modules, prior to upgrade might help.
This change record about path_alias becoming its own core module might be relevant, as well: https://www.drupal.org/node/3092086.
It's also worth mentioning that, if you have drush installed, you can get a one-time login link by running drush uli 1. You'll get a link that looks something like this: http://default/user/reset/1/1584508997/mFfBCIO2zmwKOm3Bh7l5bBwGxwMO6MVqJ6-S-cvZ-pU/login. Take the part of the URL starting with "/user" and append it to your domain name.
Ex: http://my.site.dev/user/reset/1/1584508997/mFfBCIO2zmwKOm3Bh7l5bBwGxwMO6MVqJ6-S-cvZ-pU/login

Can't log in to back end


Como corrigir um JSON errado?

Question: Seguinte, eu estou desenvolvendo um programa em Python que colete os dados de um JSON e o transfira para um arquivo CSV.
Contudo, a rotina do servidor me trás um JSON com a estrutura errada em alguns pontos dela, como nesse caso:
...
"Campo": valor,
"Campo": "valor"
},
[
{}
][
{
  "Campo": valor,
  "Campo": {},
...

Quando rodo o programa (o qual funciona perfeitamente com arquivos JSON formatado corretamente) com este JSON, ele me retorna o erro:
  File "C:\Users\mpolillo\Documents\json-extraction\script\fix_json.py", line 17, in fix_test
    content = json.loads(content)
  File "C:\Users\mpolillo\AppData\Local\Continuum\anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "C:\Users\mpolillo\AppData\Local\Continuum\anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\mpolillo\AppData\Local\Continuum\anaconda3\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 123944 column 2 (char 3653439)

Ou seja, está me avisando a linha onde este erro está. Queria saber se há alguma forma de reescrever esse JSON sem precisar fazê-lo manualmente ou sem precisar fazer com que o Python reescreva tudo na mão e, depois, gravá-lo em um novo arquivo ou em cima dele mesmo.
Comment: Quem gera esses JSON? O que seria `valor` da segunda linha do JSON que postou na pergunta?
Comment: É uma rotina escrita em TypeScript. O `valor` e `campo` são só nomes ilustrativos, porque tem informações do banco os quais não posso colocar. O ponto é que, não posso fazer alterações na rotina, tenho que dar um jeito de arrumar este JSON no próprio programa.
Answer: Fica bem difícil responder uma vez que você não falou nada de como quer reescrever o JSON (você só quer reescrevê-lo para que se torne um JSON válido, você quer inserir alguns dados que possam estar faltando ou outra coisa...?) nem se os pontos com estrutura errada seguem sempre o mesmo padrão do seu exemplo.
Com isto dito, eu acho que a melhor solução (com as informações que você disponibilizou) é incluir um bloco try-except para tratar esse erro como uma exceção. Escreva algo assim:
try:
    ...
    content = json.loads(content)
    ...
except JSONDecodeError:
    content = 'JSON mal estruturado...'
except Exception as erro:
    content = f'JSON com erro: {erro}'

Se você carregar vários JSONs no seu programa isso vai fazer com que seu script continue a escrever no arquivo CSV mesmo que um dos JSONs apresente algum erro. Espero que te ajude, mas considere fornecer mais informações para que possamos respondê-lo com mais exatidão.
Comment: Desculpe, achei que eu tinha conseguido ser específico. O que eu queria era reescrever este JSON, porém ignorar o erro que eu coloquei acima, ou seja, alguma forma de reescrever esse JSON e remover os `[{}][{` que aparecem a torto e a direito.
Comment: Antes de passar por `json.loads`,  `type(content) == str`, certo? Se sim, já tentou usar `replace()`?

`if '[{}][{' in content:
   content = content.replace('[{}][{', '')`

Como corrigir um JSON errado?


Create Unique ID from 0 to Upward Google Sheets

Question: I have a sheet where data is being added to the last empty row and inserting the new row between the rows which has already data.
I want to create a Unique Numeric number that will be 0 to upward in sequence. Like we use =IF(B3<>"",B2+1,"").
But when new row is added the formula is missed I want to Add unique number for each row.
Because when you insert the row all values are bonded but when you type anything in newly added row in Col B all the number goes disturb. It should work like timestamp once a number is allotted to specific row data it should not change even new row is inserted within data.
For example If script has assigned number 1 to 7 and new row inserted then it should assign new row a number 8 even new row is inserted with data in col B
Your help will be appreciated
Comment: Would you mind sharing a sample sheet with similar data to your actual sheet for replication? Or will you be willing to share at a least a screenshot of your desired goal (specially how it will look like when you said `create a Unique Numeric number that will be 0 to upward in sequence`? See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example)
Comment: About sharing spreadsheets, do note that [it exposes your email address](https://meta.stackoverflow.com/questions/394304/). So, use a dummy Google account if you consider your email address to be private.
Answer: In the top row,
=ARRAYFORMULA({"ID";SEQUENCE(COUNTA(B:B)+0)})

Change 0 to 1 or 2, if you want some blank row offset.
Comment: Receiving this error `Function ARRAY_ROW parameter 2 has mismatched row size. Expected`
Comment: @ShRa Check edited answer
Comment: Sorry for being late @TheMaster the problem with your answer is whenever i sort the data A to Z Array keeps the Sequence does not change according to the rows.
Answer: ALTERNATIVE SUGGESTION
If I have understood your goal correctly, you may try this custom script below that you can copy and paste as a bound script to your Spreadsheet file:
UPDATED Script
function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var data = ss.getRange("B2:B").getValues().filter(String); //Add the range where data you want to have IDs, on my end, it's B2 and below (B2:B)
  var ids = [];
  var lastRow;

 for(row=0; row<=data.length-1; row++){
   ids.push([row]);
 }

 lastRow = ids.length + 1;
 ss.getRange("A2:A"+lastRow).setValues(ids);

}

SAMPLE DEMONSTRATION

The custom function will add IDs starting on the cell A2 and below once you run it for the first time from the Apps Script editor:

When new added data on cell B10 has been entered:
Comment: Thanks i was exactly looking for this solution but was unable to elaborate. There is one problem it should not use any formula in sheet. Because when you insert the row all values are bonded but when you type anything in newly added row in Col B all the number goes disturb. Ti should work like `timestamp` once a number is allotted to specific row data it should not change even new row is inserted with data. @Irvin Jay G. For example If script has assigned number 1 to 7 and new row inserted then it should assign new row a number 8 even wherever the row is inserted with data in col B
Comment: Wouldn't then a unique id from your yagi link be more appropriate? Why do you need serialization from 0,1,2..?
Comment: I see, please update your post just to make sure it reflects your actual goal. I have updated my answer, which uses an `onEdit` trigger, so it auto adds new row number every time you enter a new data on column `B` using your keyboard.
Comment: I have updated the post, I just added the link to show script or formula should work like this but it has to increment the number.
Comment: I have been facing an problem whenever i reference the two different sheets in the script where the ranges are different it gives me an error `The number of rows in the data does not match the number of rows in the range. The data has 65 but the range has 62.` but when i use the same range it works fine. @Irvin Jay G.


Qual o erro de sintaxe desse join?

Question: Quando uso esse join, aparece que tem um erro de sintaxe "operador faltando", alguém consegue me dizer onde está e por que dá esse erro?
SELECT tbEquipamento_Movimentacao.NUMERO_ATIVO_FK,
    tbEquipamento.TIPO_EQUIPAMENTO,
    tbMovimentacao.DATA,
    tbTipo_Movimentacao.TIPO_MOVIMENTACAO,
    tbTecnico.NOME_TECNICO,
    tbUsuario.NOME_USUARIO
FROM tbEquipamento_Movimentacao
INNER JOIN tbEquipamento
    ON tbEquipamento.NUMERO_ATIVO = tbEquipamento_Movimentacao.NUMERO_ATIVO_FK
INNER JOIN tbMovimentacao INNER JOIN tbTipo_Movimentacao INNER JOIN tbTecnico INNER JOIN tbUsuario
    ON tbUsuario.MATRICULA_USUARIO = tbMovimentacao.MATICULA_USUARIO_FK
    ON tbTecnico.MATRICULA_TECNICO = tbMovimentacao.MATRICULA_TECNICO_FK
    ON tbTipo_Movimentacao.COD_TIPO_MOVIMENTACAO = tbMovimentacao.COD_TIPO_MOVIMENTACAO_FK
    ON tbMovimentacao.COD_MOVIMENTACAO =  tbEquipamento_Movimentacao.COD_MOVIMENTACAO_FK

Comment: Tem INNER Join sem a comparação
Comment: Não entendi... Qual ?
Answer: Você deve sempre usar o inner join da seguinte maneira:
INNER JOIN tbEquipamento ON tbEquipamento.NUMERO_ATIVO = tbEquipamento_Movimentacao.NUMERO_ATIVO_FK

Ou seja, faça o inner/left/right join na tabela e faça a comparação na outra tabela.
Comment: Nunca usei o Left/Right. Como ficaria nesse caso ?
Comment: A devMedia tem um conteúdo bem legal. De uma olhada https://www.devmedia.com.br/clausulas-inner-join-left-join-e-right-join-no-sql-server/18930
Answer: O erro é que você agrupou os join e depois os on.
A estrutura JOIN tabela ON campo_1 = campo_2 devem sempre ser mantida; ou seja, ao "juntar" uma tabela, você deverá indicar o campo de ligação antes de juntar a próxima, ficando a consulta assim:
SELECT tbEquipamento_Movimentacao.NUMERO_ATIVO_FK,
    tbEquipamento.TIPO_EQUIPAMENTO,
    tbMovimentacao.DATA,
    tbTipo_Movimentacao.TIPO_MOVIMENTACAO,
    tbTecnico.NOME_TECNICO,
    tbUsuario.NOME_USUARIO
FROM tbEquipamento_Movimentacao
INNER JOIN tbEquipamento ON tbEquipamento.NUMERO_ATIVO = tbEquipamento_Movimentacao.NUMERO_ATIVO_FK
INNER JOIN tbMovimentacao ON tbMovimentacao.COD_MOVIMENTACAO =  tbEquipamento_Movimentacao.COD_MOVIMENTACAO_FK
INNER JOIN tbTipo_Movimentacao ON tbTipo_Movimentacao.COD_TIPO_MOVIMENTACAO = tbMovimentacao.COD_TIPO_MOVIMENTACAO_FK
INNER JOIN tbTecnico ON tbTecnico.MATRICULA_TECNICO = tbMovimentacao.MATRICULA_TECNICO_FK
INNER JOIN tbUsuario ON tbUsuario.MATRICULA_USUARIO = tbMovimentacao.MATICULA_USUARIO_FK

obs: perceba que a ordem dos on precisou ser alterada, já que a condição é específica da tabela que está sendo adicionada à consulta. Em outras palavras, ao fazer join com a tabela tbTipo_Movimentacao você precisa indicar um campo de uma tabela que "já está na consulta" como ligação, no caso, tbMovimentacao.
Comment: Boa tarde rLinhares, tudo bem ?
Cara, gostei da sua explicação, você acrescentou algumas coisas que ainda não tinha conhecimento. Porém o código deu um "Erro de sintaxe (operador faltando) na expressão de consulta 'tbEquipamento.NUMERO_ATIVO =  tbEquipamento_Movimentacao [...]"
Comment: não sei se vai ser o caso do _ms-access_, mas tenta jogar o `on` na mesma linha do `join` (sem dar enter). De qualquer forma, vou alterar a resposta..
Comment: Realmente não era isso, continuou o mesmo erro
Answer: Encontrei um problema igual ao seu no stackoverflow em inglês.
De acordo com a resposta, quando há múltiplos JOINs, o Access exige o uso de parênteses.
Documentação do suporte da Microsoft.
Como não tenho MS Access, não tenho como simular a sua query para poder validar a sintaxe.
Answer: Resolvido da seguinte maneira:
SELECT tbEquipamento.NUMERO_ATIVO,
    tbEquipamento.TIPO_EQUIPAMENTO,
    tbMovimentacao.DATA,
    tbTipo_Movimentacao.TIPO_MOVIMENTACAO,
    tbTecnico.NOME_TECNICO, tbUsuario.NOME_USUARIO
FROM tbTipo_Movimentacao
   INNER JOIN (tbUsuario
   INNER JOIN (tbTecnico
   INNER JOIN (tbMovimentacao
   INNER JOIN (tbEquipamento
   INNER JOIN tbEquipamento_Movimentacao
      ON tbEquipamento.NUMERO_ATIVO = tbEquipamento_Movimentacao.NUMERO_ATIVO_FK)
      ON tbMovimentacao.COD_MOVIMENTACAO = tbEquipamento_Movimentacao.COD_MOVIMENTACAO_FK)
      ON tbTecnico.MATRICULA_TECNICO = tbMovimentacao.MATRICULA_TECNICO_FK)
      ON tbUsuario.MATRICULA_USUARIO = tbMovimentacao.MATICULA_USUARIO_FK)
      ON tbTipo_Movimentacao.COD_TIPO_MOVIMENTACAO = tbMovimentacao.COD_TIPO_MOVIMENTACAO_FK;

Qual o erro de sintaxe desse join?


Aegir Drupal 7 Website migration

Question: I need desperately help.
I clarify that I am not a developer but I have just basic knowledge of Drupal and Aegir.
Few years ago a developer guy installed Aegir on VPS (Hostwind) and Drupal.
Now Hostwind decided to interrupt this service and I have to migrate.
My question is: what is best option to migrate?
Should I migrate Drupal and Aegir or just Drupal (without Aegir)? Is it possible to migrate only Drupal?
As test can install Aegir locally on Mac using MAMP to test if I am doing correctly?
Thank you
Comment: There are a lot of questions in this forum already about Aegir, for example, https://drupal.stackexchange.com/questions/283619/transfer-aegir-site-to-lamp
Comment: Yes I saw it. From that answer I understood that if want to migrate a Drupal website installed under Aegir to another host I need Aegir also in the new host. Is that correct?
Comment: The question is almost identical.
Answer: You can always run a Drupal site somewhere without Aegir.  However, as an application life-cycle manager (ALM) platform as a service (PaaS), Aegir adds extra value (e.g. monitoring, backups, rollback on upgrades, etc.)
The value of Aegir increases with the number of sites hosted.  The selling point for me is that you can upgrade 200 sites at once with a single button click.  But if you only have one site, it may not be worth it.  You have to weigh the benefits that Aegir provides (see the docs) vs. the added maintenance of maintaining Aegir itself.
That is, if you really want to run your own platform as a service (PaaS).  Other options are hosted Aegir (if you really like it) or finding a Drupal hosting company which offers their own proprietary PaaS for running Drupal.  (I'll leave this search as an exercise to the reader. Ask good questions like: Does your Drupal hosting company lack native Composer support?)
Obviously, you can forget about the PaaS, and just run the Drupal site yourself if you want to self host.
If you'd like to try Aegir locally, have a look at the Aegir Development VM.
Comment: I totally agree that Aegir can be worthy. The only issue is that I am not sure if I have the skills to use it. I may try a local version and see how it goes.
Comment: regarding that particular website that now is under Aegir I tried to extract and run without Aegir and it didn't work. The organisation of the folder with Aegir and without Aegir are different.
Comment: Thanks a lot for your answer
Comment: @Gilles9999 If you have a budget for some consulting help and it's not urgent, we may be able to help.  We're a bit busy, but might be able to find some time soon.  If you're interested, please use [our contact form](https://consensus.enterprises/#contact).

Aegir Drupal 7 Website migration


Getting a failed to post notification on channel "channel_id_here" error

Question: I have been struggling for days now to get local notifications to display on an Android device. Notifications simply do not show up and I'm getting a developer warning:
package Failed to post notification on channel "channel_id_here" error.

I went through many tutorials and StackOverflow posts to see if there's anything I missed, but I simply can't find it. Can someone please take a look if I did something wrong here or if there's something I'm missing. I would appreciate some assistance in sorting this out.
My app is targeting API 29 and I used code from this git
Here is the relevant code from my app:
AppCompatPreferenceActivity.java
public abstract class AppCompatPreferenceActivity extends PreferenceActivity {

    private AppCompatDelegate mDelegate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getDelegate().installViewFactory();
        getDelegate().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getDelegate().onPostCreate(savedInstanceState);
    }

    public ActionBar getSupportActionBar() {
        return getDelegate().getSupportActionBar();
    }

    public void setSupportActionBar(@Nullable Toolbar toolbar) {
        getDelegate().setSupportActionBar(toolbar);
    }

    @Override
    public MenuInflater getMenuInflater() {
        return getDelegate().getMenuInflater();
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().addContentView(view, params);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        getDelegate().onPostResume();
    }

    @Override
    protected void onTitleChanged(CharSequence title, int color) {
        super.onTitleChanged(title, color);
        getDelegate().setTitle(title);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        getDelegate().onConfigurationChanged(newConfig);
    }

    @Override
    protected void onStop() {
        super.onStop();
        getDelegate().onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getDelegate().onDestroy();
    }

    public void invalidateOptionsMenu() {
        getDelegate().invalidateOptionsMenu();
    }

    private AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, null);
        }
        return mDelegate;
    }
}

NotificationPublisher.java
public class NotificationPublisher extends BroadcastReceiver {
    public static String NOTIFICATION = "notification";

    @Override
    public void onReceive(Context ctx, Intent intent) {
        NotificationManager notificationManager = (NotificationManager)
                ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        // The notification may come from the received intent (see SettingsActivity for how to build
        // it and add it to the intent). If not then we'll build a notification here.
        Notification notification;
        if (intent.hasExtra(NOTIFICATION)) {
            notification = intent.getParcelableExtra(NOTIFICATION);
        } else {
            notification = buildNotification(ctx);
        }

        // notificationId is a unique int for each notification.
        // TODO Is the current time good enough?
        int notificationId = (int) System.currentTimeMillis();

        notificationManager.notify(notificationId, notification);
    }

    private Notification buildNotification(Context ctx) {
        Intent intent = new Intent(ctx, com.app.myapp.activity.MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_stat_notification)
                .setContentTitle("Hello I'm a notification!")
                .setContentText("Well look at that, it's content")
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        return builder.build();
    }
}

NotificationSchedulerApplication.java
public class NotificationSchedulerApplication extends Application {

    public static final String CHANNEL_ID = "1998882";

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
    }

    private void createNotificationChannel() {
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = getString(R.string.channel_name);
            String description = getString(R.string.channel_description);
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            channel.setDescription(description);
            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}

SettingsActivity.java
public class SettingsActivity extends AppCompatPreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {

    private static final String ENABLE_NOTIFICATIONS_PREF_KEY = "notifications_enable";
    private static final String NOTIFICATION_TIME_PREF_KEY = "notifications_time";

    // This request code is used for all PendingIntents so that PendingIntents previously submitted
    // to the AlarmManager can be looked up for cancellation or modification.
    private static final int REQUEST_CODE = 0;

    /**
     * A preference value change listener that updates the preference's summary
     * to reflect its new value.
     */
    private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            if (preference instanceof ListPreference) {
                // For list preferences, look up the correct display value in
                // the preference's 'entries' list.
                ListPreference listPreference = (ListPreference) preference;
                int index = listPreference.findIndexOfValue(value.toString());

                preference.setSummary(
                        index >= 0
                                ? listPreference.getEntries()[index]
                                : null);
            } else if (preference instanceof TimePreference) {
                TimePreference timePreference = (TimePreference) preference;
                preference.setSummary(timePreference.valueToSummary((int) value));
            } else {
                // For all other preferences, set the summary to the value's
                // simple string representation.
                preference.setSummary(value.toString());
            }
            return true;
        }
    };

    /**
     * Helper method to determine if the device has an extra-large screen. For
     * example, 10" tablets are extra-large.
     */
    private static boolean isXLargeTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
    }

    /**
     * Binds a preference's summary to its value. More specifically, when the
     * preference's value is changed, its summary (line of text below the
     * preference title) is updated to reflect the value. The summary is also
     * immediately updated upon calling this method. The exact display format is
     * dependent on the type of preference.
     *
     * @see #sBindPreferenceSummaryToValueListener
     */
    private static void bindPreferenceSummaryToValue(Preference preference) {
        preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

        // Trigger the listener immediately with the preference's current value.
        SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(
                preference.getContext());
        Object value;
        if (preference instanceof TimePreference) {
            value = sharedPrefs.getInt(preference.getKey(), 0);
        } else {
            value = sharedPrefs.getString(preference.getKey(), "");
        }
        sBindPreferenceSummaryToValueListener.onPreferenceChange(preference, value);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();

        // Listen for changes to any preferences.
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
        // We only want to take action if these particular preferences change.
        if (!s.equals(ENABLE_NOTIFICATIONS_PREF_KEY) && !s.equals(NOTIFICATION_TIME_PREF_KEY)) {
            return;
        }

        // If the preference was changed to false then we should cancel any pending notifications.
        if (s.equals(ENABLE_NOTIFICATIONS_PREF_KEY) && !sharedPreferences.getBoolean(s, false)) {
            cancelIntents();
            return;
        }

        // Get the time at which to schedule notifications.
        Calendar startTime = TimePreference.valueToCalendar(
                sharedPreferences.getInt(NOTIFICATION_TIME_PREF_KEY, 0));

        // If the time has already passed today, start notifications tomorrow.
        Calendar now = Calendar.getInstance();
        if (now.after(startTime)) {
            startTime.add(Calendar.DATE, 1);
        }

        // Build a notification, add it to the intent we'll schedule, and schedule it.
//        Notification notification = buildNotification();
//        scheduleNotification(notification, startTime);

        // Schedule an intent, and build and publish the notification in the future whenever
        // the intent is received.
        scheduleNotification(startTime);
    }

    private PendingIntent getNotificationPublisherIntent(Notification notification) {
        Intent intent = new Intent(this, NotificationPublisher.class);
        if (notification != null) {
            intent.putExtra(NotificationPublisher.NOTIFICATION, notification);
        }

        return PendingIntent.getBroadcast(
                this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private Notification buildNotification() {
        Intent intent = new Intent(this, com.app.myapp.activity.MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_stat_notification)
                .setContentTitle("Hello I'm a notification!")
                .setContentText("Well look at that, it's content 111")
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);

        return builder.build();
    }

    private void scheduleNotification(Notification notification, Calendar startTime) {
        scheduleIntent(getNotificationPublisherIntent(notification), startTime);
    }

    private void scheduleNotification(Calendar startTime) {
        scheduleIntent(getNotificationPublisherIntent(null), startTime);
    }

    private void scheduleIntent(PendingIntent intent, Calendar startTime) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY, intent);
    }

    private void cancelIntents() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(getNotificationPublisherIntent(null));
    }

    /**
     * Set up the {@link android.app.ActionBar}, if the API is available.
     */
    private void setupActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // Show the Up button in the action bar.
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean onIsMultiPane() {
        return isXLargeTablet(this);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void onBuildHeaders(List target) {
        loadHeadersFromResource(R.xml.pref_headers, target);
    }

    /**
     * This method stops fragment injection in malicious applications.
     * Make sure to deny any unknown fragments here.
     */
    protected boolean isValidFragment(String fragmentName) {
        return PreferenceFragment.class.getName().equals(fragmentName)
                || NotificationPreferenceFragment.class.getName().equals(fragmentName);
    }

    /**
     * This fragment shows notification preferences only. It is used when the
     * activity is showing a two-pane settings UI.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static class NotificationPreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.pref_notification);
            setHasOptionsMenu(true);

            // Bind the summary of the TimePreference to its value. When the value changes, the
            // summary is updated to reflect the new value, per the Android Design guidelines.
            bindPreferenceSummaryToValue(findPreference("notifications_time"));
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
            if (id == android.R.id.home) {
                startActivity(new Intent(getActivity(), SettingsActivity.class));
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    }
}

TimePreference.java
public class TimePreference extends DialogPreference {

    // This is the same as the default value set in the XML. Keep them in sync.
    private static final int DEFAULT_TIME = 7 * 60;  // 0700

    // The currently chosen time stored as the number of minutes after midnight.
    private int time;

    private TimePicker picker;

    public TimePreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    public TimePreference(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public TimePreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TimePreference(Context context) {
        super(context);
    }

    /**
     * valueToSummary takes the raw value of the preference and converts it into a human-readable
     * string fit for use in e.g. the preference's summary.
     *
     * @param value The raw value of the preference.
     * @return The time formatted according to the current settings (locale, 12/24 hour clock)
     */
    public String valueToSummary(int value) {
        return DateFormat.getTimeFormat(getContext()).format(valueToCalendar(value).getTime());
    }

    public static Calendar valueToCalendar(int value) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, getHours(value));
        calendar.set(Calendar.MINUTE, getMinutes(value));
        calendar.set(Calendar.SECOND, 0);

        return calendar;
    }

    private void setTime(int minAfterMidnight) {
        time = minAfterMidnight;
        persistInt(time);
        notifyChanged();
    }

    private static int getHours(int minAfterMidnight) {
        return minAfterMidnight / 60;
    }

    private static int getMinutes(int minAfterMidnight) {
        return minAfterMidnight % 60;
    }

    @Override
    protected View onCreateDialogView() {
        picker = new TimePicker(getContext());
        return picker;
    }

    @Override
    protected void onBindDialogView(View view) {
        super.onBindDialogView(view);

        picker.setIs24HourView(DateFormat.is24HourFormat(getContext()));
        if (Build.VERSION.SDK_INT >= 23) {
            picker.setHour(getHours(time));
            picker.setMinute(getMinutes(time));
        } else {
            picker.setCurrentHour(getHours(time));
            picker.setCurrentMinute(getMinutes(time));
        }
    }

    @Override
    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult) {
            int hours, minutes;
            if (Build.VERSION.SDK_INT >= 23) {
                hours = picker.getHour();
                minutes = picker.getMinute();
            } else {
                hours = picker.getCurrentHour();
                minutes = picker.getCurrentMinute();
            }

            int newTime = hours * 60 + minutes;
            if (callChangeListener(newTime)) {
                setTime(newTime);
            }
        }
    }

    @Override
    protected Object onGetDefaultValue(TypedArray a, int index) {
        return a.getInt(index, DEFAULT_TIME);
    }

    @Override
    protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
        super.onSetInitialValue(restorePersistedValue, defaultValue);
        setTime(restorePersistedValue ? getPersistedInt(time) : (int) defaultValue);
    }
}

The receiver in my AndroidManifest.xml:
<receiver android:name=".activity.NotificationPublisher" />

I can set the time in my app and notifications are enabled for the app on the device. They simply don't display.
Note: I am developing with Android API 29.
Comment: Hi Mike. I compiled and installed the Github project. It posted 2 "Hello I'm a notification!" notices on my Android One device running Android 10. Does the original project work for you? Regards.
Comment: Also, can you put a break point on createNotificationChannel() and tell me if that is called? Are there any errors in logcat after it is called? Thanks.
Comment: I am still getting the toast while debugging, but the breakpoint doesn't seem to be hit. Nothing appearing in Logcat
Comment: I have moved the discussion below to the answer for more room. Cheers.
Answer: In the sample app, in NotificationSchedulerApplication:
@Override
public void onCreate() {
    super.onCreate();
    createNotificationChannel();
}

private void createNotificationChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

The bit in the AndroidManifest.xml that causes onCreate to be called in the Application followed by createNotificationChannel is this:
<application
    android:name=".NotificationSchedulerApplication"
    .../>
</application>

onCreate in the Application should be called every time you do:
Run -> Debug
Just click on the left of createNotificationChannel() to set a breakpoint.
Comment: This was my issue. I overlooked that entirely. I moved the createNotificationChannel class to my app's main.java file and now it's working. Thanks :)
Answer: I faced this problem when didn't create channel id
import PushNotification, {Importance} from 'react-native-push-notification';
...
PushNotification.createChannel(
{
  channelId: "channel-id", // (required)
  channelName: "My channel", // (required)
  channelDescription: "A channel to categorise your notifications", // (optional) default: undefined.
  playSound: false, // (optional) default: true
  soundName: "default", // (optional) See `soundName` parameter of `localNotification` function
  importance: Importance.HIGH, // (optional) default: Importance.HIGH. Int value of the Android notification importance
  vibrate: true, // (optional) default: true. Creates the default vibration pattern if true.
},
(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created, false means it already existed.
);


Detect touch on EditText, but not interrupt it?

Question: I need to know when the user touches/taps/clicks the edittext in my activity.
How can I do this without interrupting the events, so the keypad still displays properly?
(And I need to know about it before the OS displays the keypad...if possible)
Answer: txtEdit.setOnTouchListener(new View.OnTouchListener(){
    public boolean onTouch(View view, MotionEvent motionEvent) {
         // your code here....
         getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
         return false;
    }
});

Comment: Thanks, although I didn't need the line above 'return false;' as the keypad appeared automatically.
Answer: View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if(event.getAction() == MotionEvent.ACTION_UP){

...

}

Comment: Thank you for posting an answer to this question! Code-only answers are discouraged on Stack Overflow, because it can be difficult for the original poster (or future readers) to understand the logic behind them. Please, edit your question and include an explanation of your code so that others can benefit from your answer. Thanks!
Answer: You should be able to do this by attaching an OnClickListener to your EditText. If you're concerned about blocking the UI thread in your OnClickListener, you can spawn a new Thread and do your work in there - though, if you do that, there's no guarantee the work will be done before the keypad shows up.
Comment: OK. Try looking at this... http://stackoverflow.com/questions/2403632/android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext
Comment: If I attached a new onFocusChangeListener, it interrupts the keypad, and it has to be pressed twice to show it.  When I override, is there a way to call super or something?  Maybe I'm reaching...
Comment: Actually, that was the example I was following.  I also tried getting the activity window and setSoftInputMode, but it always takes 2 taps to reveal the keypad.
Answer: Less verbosity
The same Mathias Conradt's approach, but using kotlin:
txtEdit.setOnTouchListener({ view, motionEvent ->
    // your code here....
    false
})

This line getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); is unnecessary since the keyboard shown when you tap the editText view.
Answer: OnTouchListener was getting called twice for me (on Pixel 2 running Pie). So I used
OnFocusChangeListener instead:
txtEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Log.d(TAG,"Focused Now!");
                }
            }
        });


Print query result on form page

Question: I'm writing a custom module to obtain an online quote.
The form has an additional button and once it is clicked, a database query runs and print a value.
//My code for custom button
function garden_form_alter( &$form, &$form_state,$form_id ){
if ($form_id == 'webform_client_form_4208') {
$form['actions']['garden_quote']  = array(
    '#type' => 'submit',
    '#value' => t('Get online estimate'),
    '#submit' => array('mymodule_custom_submit'),
);
$form['#validate'][] = 'mymodule_custom_validate';
}
}

//Custom submit handler
function mymodule_custom_submit($form, &$form_state) {
$query = db_select('gardenvalue', 'f');
$query->fields('f', array('total_cost'))
    ->condition('meters', '2', '=');
$result = $query->execute();
dpm($result);
}

Once the form has been submitted dpm shows the 'meters' value as'db_condition_placeholder_0' and not number 2. What can be the reason?
Also I would like to show the $result value on a new text field once the form reloads. If we assume this new text field key is 'total_garden' how can I change its' value to $result on form reload?
Thanks in advance!
Answer: //My code for custom button
function garden_form_alter(&$form, &$form_state, $form_id ){
    if ($form_id == 'webform_client_form_4208') {
        $form['actions']['garden_quote']  = array(
            '#type' => 'submit',
            '#value' => t('Get online estimate'),
            '#submit' => array('garden_custom_submit'),
        );
        $form['#validate'][] = 'garden_custom_validate';
    }
}

//Custom submit handler
function garden_custom_submit($form, &$form_state) {
    $query = db_select('gardenvalue', 'f');
    $query->fields('f', array('total_cost'))
        ->condition('f.meters', 2, '=');
    $result = $query->execute();
    dpm($result);
}

You have spacing errors and identation errors, the condition is not pointing to a field in the table, and you have to dig into the results array to extract the value, as far as I know you only can print results in a form with
drupal_set_message(t('your message', 'success'); instead of dpm hope this help you a little bit...

Print query result on form page


Prove that $j < n$, $k < n - j$ and $(n - j) - k = n - (j + k)$ if we know that $j + k < n$ in $\mathbb{N}$

Question: Suppose $j + k < n$ in $\mathbb{N}$.

Show that $j < n$
Show that $k < n - j$
Show that $(n - j) - k = n - (j + k)$

Thoughts for the Problems
I'm not really good with proof, so I start to have some thoughts about it.  I learned addition, subtraction, distributive law and well-ordering in my number system class.
For the first two parts, I believe that well-ordering, trichotomy and induction are needed to show certain statements.  I think that for the last part, I need to apply the first two parts for this problem and then, use the elementary additions and subtraction laws.
Any comments or advices?
Answer: Because $j,k,n \in \mathbb{N}$ it obvious that:
$$j < j+k$$
From the condition we have:
$$j+k<n \implies j<n$$
The second inequality is just a rearrangment of the initial condition.
$$j+k<n \implies j<n-k$$
And for the equality just get rid of the parenthesis. So we end up with:
$$(n-j) - k = n - (j+k) \implies n-j-k = n-j-k$$, which is obviously true.
Comment: No, I mean: show this by setting a theorem on inequality/variable.  For instance, I prove the statement by induction on the variable.