Is there a way to provide theme name suggestion for form elements?

Question: I'm trying to look for a way to modify the markup for a form element without touching the default theme/template. Upon checking the source code, Drupal does not seem to recommend any theme suggestions for editing form elements. I have multiple views using the same field on the exposed filter. If I try to edit the form-element-label.html.twig it will affect all of the elements with the same field.

Themes

Comment: see https://drupal.stackexchange.com/questions/211271/how-can-i-theme-a-form-element-with-hook-preprocess-form-element and https://drupal.stackexchange.com/questions/226491/change-a-normal-submit-input-type-to-button-type-with-button-tag
Answer: Seems you have to implement two hooks. One to add the suggestion, and one to define a template. hook_theme_suggestions_HOOK_alter and template_preprocess_form_element (aka hook_preprocess_HOOK).
/**
 * Implementation of hook_theme_suggestions_form_element_alter().
 */
function MYTHEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables) {
  if (\Drupal::service('path.current')->getPath() == '/user/login') {
    $suggestions[] = $variables['theme_hook_original'] . '--user-login';
  }
}

/**
 * Implementation of hook_preprocess_form_element().
 */
function MYTHEME_preprocess_form_element(&$variables, $hook, &$info) {
  $info['template'] = 'form-element--user-login';
}

Source: Form element template suggestion has no effect.
Comment: Hello, apologies for my ignorance. Lets say I have a view with an exposed filter. Is it possible to only target the form elements of a specific view? I'm trying to understand the answer you have suggested. Still new with drupal hooks. Let's say I want to create a theme suggestion for a `form-element` that has a `label` and `select` element
Comment: @clestcruz – You have to wrap the code inside the hooks with some `if` conditions to fire only according your logic. Check what's inside `$variables`, maybe there's something you can identify your view with. As last resort you can also check the current URL.


Contour Integrals and Residues

Question: I'm trying to figure out what it is all about, but my mind is blowing up. First of all, I have turned back and looked at the general definitions of integrals. Then I have looked to line integrals. Basically, the integral is helping us to find the area between two points along the curve. For example when force $F$ is constant but height of the object varies point to point, we can use the integral to find the total work done by $F$.
The line integral is helping us to find the total work done by any vector or scalar fields along any path. Arch length formula gives us the length of curve. So if all these definitions are Ok, please help me to understand about Contour and Residues? Why do we need to use them? Is there any physical meaning or are we just expanding our number set to use The Euler formula and obtain the result easily?
Comment: "area between two points along a curve"? This doesn't seem to make much geometric sense, does it?
Comment: Hi Erbil, maybe you can leave the things you understand about integration out of the question and just focus on the complex analysis issues you'd like to understand? This would make your question a bit more concise.
Comment: https://upload.wikimedia.org/wikipedia/commons/2/2a/Riemann_sum_convergence.png,I'm not a native English speaker so it would be wrong.That picture is explain what I'm trying to say.
Comment: @Dilaton You're right.But as you know Contour integral is just a Line integral on complex plane.
Comment: Cross-posted from http://physics.stackexchange.com/q/65733/2451
Answer: In complex analysis, you might want to think of contour integrals as anti-derivatives. This helps to explain why the path can be moved (as long as it does not pass over a singularity) without altering the integral; it is just the difference of the anti-derivative at the endpoints.
Another way to express this is using Green's Theorem applied to a complex differentiable function:
$$
\oint_{\partial\Omega} f(z)\,\mathrm{d}z
=\iint_\Omega(if_x-f_y)\,\mathrm{d}x\,\mathrm{d}y\tag{1}
$$
The Cauchy-Riemann Equations are simply
$$
if_x=f_y\tag{2}
$$
Applying $(2)$ to $(1)$ yields Cauchy's Integral Theorem:
$$
\oint_{\partial\Omega} f(z)\,\mathrm{d}z=0\tag{3}
$$
when $f$ is holomorphic (i.e. satisfies the Cauchy-Riemann Equations) in $\Omega$.
$\hspace{2.5cm}$
Thus, the difference of the integral along the green path and the integral along the red path is the integral along the blue path. According to $(3)$, that is $0$.
There are points at which otherwise holomorphic functions go bad. These are singularities. The residue is $\frac1{2\pi i}$ times the integral counter-clockwise around such a point.
$\hspace{2.5cm}$
Note that the difference between the integrals along the green and red paths is the integral along the blue path, taking the integral in along the bottom of the blue line and out along the top (the integrals along the lines cancel, being in opposite directions). The blue contour is the boundary of the "C"-shaped area which avoids the singularity, so the integral along the blue contour is $0$. Therefore, the integral along the green path equals the integral along the red path. Thus, it does not matter which contour around the singularity we take, the residue will be the same.
Answer: An analytic function $f:\ \Omega\to{\mathbb C}$ can be viewed as a kind of "complex force field" in $\Omega$, so that it makes sense to integrate $f$ along curves $\gamma\subset\Omega$.
A physical force field $F$ is conservative (meaning: it conserves energy) when the integral of $F$ along any closed curve $\gamma\subset\Omega$ is zero. Now it is a basic property of  analytic functions $f$ that they are locally conservative, meaning that integrals along "short" closed curves are zero. The reason for this is the following: The "complex curl" $${\partial f\over\partial\bar z}$$ of such a function is identically zero  – this is the content of the CR equations.
But "in the large" such a complex force field $f$ need not be conservative, as is exemplified by the function $$f(z):={e^z\over z^3}$$ in the punctured complex plane. When $\partial D$ is the counterclockwise oriented unit circle then $$\int_{\partial D} f(z)\ dz=\pi i\ne0\ .$$ In this example the non-conservativeness of $f$ can be precisely localized: It is the pole, an isolated singularity, of $f$ at $0$. But that's not all: The value of the integral need not be computed the hard way; it can be extracted from  the Laurent expansion of $f$ at $0$, which is given by
$$f(z)={1\over z^3}+{1\over z^2}+{1\over 2z}+{1\over 6}+{z\over 24}+\ldots\quad.$$
The residue of $f$ at $0$ is on the one hand the coefficient ${1\over2}$ of the ${1\over z}$-term in this expansion, and on the other hand it is  the value of the above integral, divided by $2\pi i$. That these two numbers coincide is the content of the residue theorem (which, of course, covers much more complicated cases).

Contour Integrals and Residues


Varnish 3.0 and Drupal 7, get registered user to always have non-cached content

Question: I have issue with Varnish on Drupal 7 detailed here: http://drupal.org/node/1886218
Basically, what happens is:

User visits the certain page as anonymous, gets content served by Varnish Cache (OK)
Logs in
Clicks the link of the page that he visitied as anonymous previosly, but he gets cached page, instead of user-specific (that should not happen)
If he reloads page (f5), he gets backend served page, but if he clicks that link on the menu, he gets cached page.

It turns out that cached page was delivered by browser, not by Varnish; anyway, that should not happen, because user thinks he is logged out (I have user specific block in header).
How i can deliver such cache-control in header, so Registered users always get updated (not cached) content, even if they browsed site as anonymous before they have logged in ?
Thanks for help!
HTTP response:
The url we checked: www.mydomain.com
    HTTP/1.1 200 OK
Server: Apache (removed from security)
X-Powered-By:   PHP(removed from security)
X-Drupal-Cache: MISS
Expires:    Sun, 19 Nov 1978 05:00:00 GMT
Last-Modified:  Tue, 15 Jan 2013 08:38:54 +0000
Cache-Control:  public, max-age=10800
ETag:   "1358239134-1"
Content-Language:   hr
X-Generator:    Drupal 7 (http://drupal.org)
Link:   <http://www.mydomain.com/>; rel="canonical",<http://www.mydomain.com/>; rel="shortlink"
Vary:   Accept-Encoding
Content-Encoding:   gzip
Content-Type:   text/html; charset=utf-8
Content-Length: 33254
Accept-Ranges:  bytes
Date:   Tue, 15 Jan 2013 08:49:22 GMT
X-Varnish:  1420616326 1420614128
Age:    622
Via:    1.1 varnish
Connection: keep-alive
X-Varnish-Cache:    HIT

Comment: Are you using [Varnish HTTP Accelerator Integration](https://drupal.org/project/varnish) module? If no, maybe you should at least give it a try. After all, it is designed do solve problems like this.
Comment: Can you post the HTTP request and response headers?
Comment: Question updated with http response, how could i print http request ?
Comment: In a typical Drupal/Varnish config you bypass caching if the session cookie is set. Anon users don't get a session cookie from D7 by default. Check your Varnish config to see if that code is present. It's generally a good idea to have this because it also defeats caching of form results.
Answer: You seem to be missing Vary: Cookie in addition to Vary: Accept-Encoding. You may add it in vcl_deliver using something like this:
if (resp.http.Vary !~ "Cookie") {
    set resp.http.Vary = resp.http.Vary + ", Cookie";
    set resp.http.Vary = regsub(resp.http.Vary, "^,\s*", "");
}

Answer: Try changing the response Cache-Control headers:
Cache-Control:no-cache, max-age=0, must-revalidate

Comment: nice suggestion, i tried to add this to all pages via custom module hook, no luck for now.


HOWTO: Common fields (weak entity)

Question: Long story short:
I have various entity types in my system and some of their subsets (bundles) has the very same fields. So far I have 3 "common fields" sets, which are from EntityRelation perspective the weak entities. A set has from 3 to 9 fields in it.
The following constraints I need:

When changing something in field bundle settings (eg: make it
required) I don't want to sync all of the other occurrence
of this    field.
Field content should be translatable (based on the
    parent)
Field content should be revisionable (based on the
        parent)

So far the following solutions came to my mind:

Field Collection (bad experiences in D7, still in dev)
Separate bundle / entity (ECK maybe) + Inline Entity Form (months ago
there was a problem with revisions)
Paragraphs (translation + revisioning good, but I couldn't make it to
appear in forms just like Inline Entity Form (it always had the "+
Add new paragraph" and if it was a new content, the form of the
paragraph didn't appear, only after clicking the add button)
Custom entity, which includes these fields as base fields. (a lot of hassle to generate the forms, listers, revision support.. etc.)

Do you have any advice for me to solve this issue?
Answer: Not a defintive answer, just some input.
We (the paragraphs maintainers) are working on reaching feature and user experience parity (or be better, of course) with the Field Collection module, specifically for non-typical paragraph scenarios (single paragraph type, single cardinality, default paragrapht type, ..). There are discussions on officially deprecating field collections in favor of Paragraphs, this might or might not happen. So I'd recommend to not use FC, but I'm obviously biased there.
The latest Paragraphs dev version has support for setting a default paragraph type now, which means that it will by default show the form fields for that already, and you don't need to add a type. The add button should only be shown if you allow more than one field, which is the default for paragraph fields but can easily be changed.
Revisions should work fine in IEF as well, if you use an Entity Reference Revisions Field. If not, then you'll have to report a but, but I assume the maintainers are actively working on that as it is a critical element of Commerce 2.x.
One important difference between the two is Paragraphs are by definition a composite of the parent node, that means they have a parent reference and not re-usable, in case that is a requirement. IEF doesn't have that and allows to search and reference existing entities.
The advantage of custom entitiy types (with base classes or traits to re-use base field definitions) is that they're way more efficient, Paragraphs/IEF both result in separate entities that need to be saved, and all the configurable fields need to be stored in separate tables. With custom entity types, you can add all the fields you need as base fields. We're constantly working on requiring less code for custom entities, listings can be done with views with none or very little custom code, widgets work for base fields too, so anything you can do with configurable fields can be done with base fields as well. One major pain point right now is a revision UI, but we're making improvings there as well and entity.module provides some basic user interfaces there as well, diff.module is also working on supporting all entity types.
Yet another option would be to define base fields/configurable fields in code. That is possible as well, but I personally wouldn't really recommend it, there are still some unfinished areas there, especially uninstalling/removing those fields is really hard, as the delete/purge process only works for configurable fields. You could technically also maintain configurable fields with code and sync them between multiple bundles.
Comment: Thanks very much! That's much more I was expecting in the first place!
Based on these facts I will able to make the right way to choose!

HOWTO: Common fields (weak entity)


Can every sufficiently nice volume integral be transformed to surface integral?

Question: Let us assume that $f: \mathbb{R}^3 \to \mathbb{R}$ is sufficiently nice and that the following integral is convergent.
$$ \int \limits_{V \subseteq \mathbb{R}^3} f(x) dx $$
Can this integral be always computed as a surface integral over $\partial V$? My reasoning is that following the answer to this question we have that if
$f$ is sufficiently nice then there is a solution to a Poisson equation:
$$ \nabla^2 \varphi = f $$
In that case, if we define $g = \nabla \varphi$ then we have that by Stokes theorem:
$$ \int \limits_{V \subseteq \mathbb{R}^3} f(x) dx = \int \limits_{V \subseteq \mathbb{R}^3} \nabla \cdot g(x)dx = \int \limits_{\partial V \subseteq \mathbb{R}^3} g(x) dx .$$
Comment: I believe you're asking if every nice function $f$ on $V$ is the divergence of some nice vector field. Take any antiderivative $F$ of $f$ with respect, say, to $x$. Then take $\mathbf g = (F,0,0)$.
Answer: Sure. I mean, you could even just trivially define
$$g = \frac{\int_{V} f(x)\,dV}{\int_{\partial V} 1\,dA}$$
and $f$ doesn't even need to be "nice," beyond integrable.
Your construction works as well, though you need to be careful with boundary conditions (in particular Dirichlet boundary conditions will work, but Neumann will not!)
Of course, usually the problem isn't existence of $g$; it's existence of a computationally convenient $g$ so that the surface integral is simpler to calculate than the original volume integral. Solving the Poisson equation is often no easier than just integrating the original function.


Javascript and a Blank Web Page

Question: I'm struggling to initialize a function in JavaScript. I'm fairly new to it, and can't seem to see the problem in my code. Every time I test it, I just see a blank web page. Here's a snippet of the code where I think the problem is:
function initialize(){
    cities();
};

//function to create a table with cities and their populations
function cities(){
    //define two arrays for cities and population
        var cityPop = [
            { ...

I've looked through lessons on codecademy, and been browsing around for answers but can't seem to figure it out. Any advice?
Comment: Well I mean.... what do you expect to SEE other then a blank page, your script doesn't really do any rendering/DOM manipulation for you to notice
Comment: Megan, you may need to post more than that. What you posted has nothing to do with a blank page. Look at the browser's developer tools console, are there any error messages? Start there as it may tell you exactly where a syntax error is.
Answer: You have to call the initialize function also which will call the cities function
function initialize(){
    cities();
};

//function to create a table with cities and their populations
function cities(){
    //define two arrays for cities and population
        var cityPop = [
            { ...}]
}
initialize();

Comment: Thank you! I realized that later on in my code where I was calling the initialize function, there was a bracket that got misplaced. It works now!

Javascript and a Blank Web Page


Quais os motivos para escolher entre camelCase e PascalCase em nomes de métodos?

Question: Primeiro, não estou querendo saber o que você gosta mais ou o que usa na sua linguagem, quero saber a motivação para escolher um ou outro padrão em uma linguagem hipotética.
Segundo, isto é um pouco estilo de codificação, que na verdade você deve seguir o padrão que a linguagem adotou, mas principalmente sobre porque uma linguagem adotaria assim. Não é sobre uma linguagem existente, vou as citar para exemplificar o que quero.
Um exemplo bem típico é o Java ter adotado camelCase e o C# adotou o PascalCase. Eu tenho um bias hoje para o PascalCase, não sei bem porque mas assim que vi o PascalCase fez muito sentido pra mim, mesmo tendo adotado camelCase antes em outras linguagens. Mas meio que só C# o adotou. Eu olho aquilo e sinto que está melhor padronizado, parece algo da estrutura do código e diferencia da variável que faz parte do algoritmo.
Meio que todo mundo adotou o PascalCase para nomes de tipos e até de namespaces. Em C# não diferencia nada para o método, mas são contextos diferentes, o IDE coloca cor adequada. Java, JS, e outras preferiram deixar claro que é um método de uma forma diferente, ao mesmo tempo que confunde com nomes de variáveis, exceto pelos parenteses que quase sempre é usado, mas não em todos casos. No começo Java nunca tinha essa confusão, hoje tem, JS tinha como confundir, mas não foi uma linguagem bem pensada (PHP tem um pouco das duas coisas, não confundia no começo e não foi bem pensada, ela nem respeita sempre isso). C# nasceu sabendo que isto poderia ser confuso.
Eu gosto da ideia do camelCase, mas parece feio (é bem subjetivo mesmo). Considero isto um aspecto da UX do programador e por isso considerando o design de linguagem, porque escolher o estilo padrão não deixa de fazer parte desta disciplina, então queria entender a motivação de uso de cada um.
Comment: Conheço uma linguagem que ficaria triste porque não considerou a *snake_case* na pergunta.
Comment: @VirgilioNovic Perceba que a pergunta não é "qual estilo devo usar", mas sim "quais são os parâmetros considerados que levam uma linguagem a adotar um determinado estilo". A resposta não depende da opinião de quem está perguntando ou respondendo.
Comment: Vou ressaltar também a abordagem do Go, que torna público os membros que começam com caractere capitalizado. Não é específico ao `PascalCase`, mas acaba sendo a convenção adotada. Os em `camelCase`, por consequência, ficam privados. Apesar disso, acho curioso a pergunta não ter incluído o `snake_case`, que acaba sendo adotado por linguagens como Rust. Eu pessoalmente acho o `snake_case` o mais fácil de ler, embora peque com maior quantidade de caracteres consumidos, dificultando o enquadramento em monitores menores. Acho que no fim é uma mera questão de opinião do designer mesmo.
Comment: Mas pode falar dele :) Esse eu odeio com todas as forças e já sei porque :P
Comment: é uma pergunta que remete muitas opiniões, porque se a linguagem como exemplo `C#` te fornece um estilo (ela indica pela IDE mas, nada que não possa ser desabilitado) e você não quer seguir esse estilo, não tem obrigação e pode ser escolhido a sua maneira, o importante é se começou de um jeito que faça sempre do mesmo jeito.
Comment: @VirgilioNovic a pergunta não é sobre isso, é sobre a justificativa plausível e fundamentada de decisão de escolher um ou outro estilo, por isso não tem opinião, é o porquê de fazer um ou outro. https://pt.meta.stackoverflow.com/q/486/101
Comment: @Maniero `é sobre a justificativa plausível e fundamentada de decisão de escolher um ou outro estilo` o estilo é geral (para todas as programação que fizer) ou o estilo é mediante linguagens (parece amplo e a indagação porque citou na pergunta linguagens)?
Comment: Para dar exemplos de diferenças existentes hoje e mostrar que há basicamente duas escolhas principais. A pergunta é sobre qualquer linguagem, não sobre uma ou algumas específicas, na verdade é sobre uma possível futura linguagem hipotética, pegando o comentário do Anderson, é sobre os parâmetros as se considerar para escolher um estilo ou outro se você for criar uma linguagem e for estabelecer na API básica dela e guia de estilo. A pergunta é sobre *design* de linguagem e não sobre as existentes. É sobre a motivação para dar melhor experiência do programador quando vai codificar.
Comment: É uma pergunta intrigante. Eu conheço uma pessoa que detesta com todas as forças tanto um quanto outro e sempre tende a usar _snake_case_ ou _kebab-case_ (vi esse nome no SO agora pouco) — como é usado em Lisp e derivados — sob a premissa de que é a leitura fica muito mais simples e "natural".
Comment: @LINQ A resposta não precisa fica presa só nesses dois, quem sabe até falando de outra forma possa indicar um caminho (desde que não seja só a pessoa falando porque gosta)
Comment: relacionado https://github.com/ktaranov/naming-convention/blob/master/C%23%20Coding%20Standards%20and%20Naming%20Conventions.md e https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-1.1/xzf533w0(v=vs.71) explicam o porque de algumas questões
Comment: @VirgilioNovic não achei nada que explicasse a decisão. Dizer que é pra ser consistente com o .NET não ajuda nada, porque a pergunta é justamente porque é adotado assim, e não que convenção alguém adotou. De qualquer forma a pergunta não é sobre o que o C# adotou e sim porque uma linguagem deveria adotar uma forma ou outra. Pode ser que coincidentemente o C# ou outra linguagem tenha tomado uma decisão com base em algum critério e ele sirva como boa explicação, mas não é o foco da pergunta entender nada se uma linguagem específica, isto é colateral. Obrigado pelos *links*.
Comment: Então a sua pergunta não vai ter uma resposta digna, já visto que quem criou isso fica complicado a gente falar com ele para perguntar **porque foi feito assim**.Esses links são referencia do site oficial e independente de qualquer coisa não tem divulgação do porque mas, tem alguns pontos por isso "relacionado" e não como razão principal, mas, eu já tenho a conclusão que essa pergunta infelizmente não trará as respostas, não adianta fazer uma pergunta tão ampla dessa, deveria sim ser divididas em linguagens (que já seria muita coisa) cada uma segue um filosofia e até vi cultura em muitos links
Comment: Se a pessoa entender sobre *design* de linguagem terá. Novamente, a pergunta não é sobre a decisão que alguém tomou, e sim sobre porque tomar essa decisão, independe de alguém ter tomado a decisão de uma determinada forma. Mesmo que ninguém tenha tomado pode tomar agora, desde que tenha uma explicação plausível, desde que a pessoa exponha as vantagens e desvantagens de cada um, que tenha uma informação que mostre um motivo, como o hugo fez, ainda que não de forma completa. Você está com a ideia fixa que eu quero saber de cada linguagem, não é isso que eu pedi.
Comment: Eu entendi depois do penúltimo comentário que você quer as razões, os porquês. Pra mim a sua pergunta é boa, mas, é ampla tem que se levar em conta muitos aspectos.
Answer: Primeiro um pouco de história
Essa resposta é baseada nesse excelente artigo do Celso Kitamura https://celsokitamura.com.br/pascal-case-e-camel-case/
Em 1813 Jacob Berzelius, químico, sugeriu uma convenção para formaliza a forma de escrever as fórmulas químicas. Ele propôs indicar cada elemento químico por um símbolo de uma ou duas letras, sendo a primeira em maiúscula. Veja o Exemplo abaixo:

No exemplo da fórmula NaCl teríamos SódioCloro = Cloreto de sódio, mesmo naquela época não havia um conceito único para escrever fórmulas químicas, e essa proposta foi adotada para normalizar a escrita, e posteriormente acabou virou regra. Foi algo que facilitou a vida do usuário, pois gera menos erros e é de fácil compreensão e utilização na hora de escrever fórmulas e elementos.
Essa é a convenção adotada na tabela periódica, e que posteriormente foi aplicada em outros meios como na programação.

Os pontos cardeais por sua vez utilizam de outra convenção por exemplo.

Ainda entre as décadas de 70 e 80 não existia bem um padrão, por N motivos, vou tentar aborda-los em outro momento. Mas o que se viu foi o Camel Case ou Pascal Case serem adotados culturalmente, e apesar de não ser regra são incentivados.

No caso do .NET, a Microsoft recomenda:

Usar Pascal Case para todos os nomes de membros, tipos e namespace públicos que consistem em várias palavras.
PropertyDescriptor
HtmlTag
Usar Camel Case para nomes de parâmetros.
propertyDescriptor
htmlTag

Aqui tem uma lista com o Naming_Convention de vária linguagens, para refletir no que elas têm em comum, prós e contras, etc. (C e C++, Java, JavaScript, .NET, PHP, Python, Ruby, etc.): https://en.wikipedia.org/wiki/Naming_convention_(programming)

Fornecer informações adicionais (ou seja, metadados) sobre o uso para o qual um identificador é colocado;
Ajudar a formalizar expectativas e promover consistência dentro de uma equipe de desenvolvimento;
Permitir o uso de ferramentas automatizadas de refatoração ou pesquisa e substituição com potencial mínimo de erro;
Aumentar a clareza em casos de potencial ambiguidade;
Para melhorar a aparência estética e profissional do produto de trabalho (por exemplo, desaprovando nomes excessivamente longos, nomes - Cômicos ou "fofinhos" ou abreviações);
Para ajudar a evitar "colisões de nomenclatura" que podem ocorrer quando o produto de trabalho de diferentes organizações é combinado (consulte também: namespaces);
Fornecer dados significativos para serem usados em transferências de projetos que requeiram o envio do código-fonte do programa e toda a documentação relevante;
Para fornecer melhor entendimento em caso de reutilização de código após um longo intervalo de tempo.

Uma palavra é uma chave

Repare como a variação de altura da linha ascendente entre maiúscula é minúscula cria um pattern visual, que pode ser usado para reconhecer facilmente as palavras. Esse variação na frequência das letras ajuda o olho a reconhecer padrões e palavras de forma mais rápida. Já quando esta tudo em CAIXA ALTA, a linha não varia, fica reta, e para reconhecermos a palavra precisamos realmente ler com mais atenção.
var UmaChaveUtil //(3 variações de Case)
var umaChaveUtil //(2 variações de Case)

Uma "chave" com mais variações de "segredo" pode ser mais útil e melhor para o reconhecimento de maneira geral... (falarei mais disso abaixo)

Além das convenções - Aspectos tipográficos e de UX
Independente da linguagem outros pontos devem ser levados em consideração. Por exemplo, qual a dificuldade de se escrever PalavrasLongasEmCamelCase? Qual a leiturabilidade disso? Em um mundo de palavras é mais fácil reconhecer UmaPalavra ou umaPalavra. A escaneabilidade é muito importante na hora de identificar palavras específicas no meio de outras. E nesse artigo do NNGroup existem boas pistas das práticas que você pode adotar e que vão apresentar uma melhor UX https://www.nngroup.com/articles/glanceable-fonts/.
Independente de ser adotado Camel ou Pascal o sistema é case sensitive? Usar essas regras vão resultar em mais erros ou menos erros, é mais fácil de escrever ou de ler? Para um sistema que ainda não existe, considere fazer um Teste A/B. As palavras reservadas pode seguir uma convenção, já as classes que são nome próprio podem ter outra... Então até mesmo uma Pesquisa Qualitativa pode ser interessante nessa faze, algo que é muito comum de se fazer em UX e Design Thinking.

4° Lei da heurística: Os usuários não devem se perguntar se palavras, situações ou ações diferentes significam a mesma coisa.

Quando se fala em heurística o principal fator talvez seja a consistência, então ter regras claras evita erros e deixa o usuário mais confortável. Então ao definir uma regra, evite deixar que coisas como essa sejam válidas, pois além de não ter coerência, pode ser ambíguo e confundir o usuário.
Fonte: https://www.nngroup.com/articles/ten-usability-heuristics/

Repare novamente na imagem acima. Será que o usuário poderia entende "Calendário" de forma diferente que "calendário"? Não posso afirmar, mas pode ser que as pessoas entendam isso de forma diferente, um calendário pode ser um calendário qualquer, já o Calendário, pode ser o App de Calendário.
Proeminência Visual

Repare na imagem acima, veja como um título com Cases variados parece se destacar mais do que o outro só com a letra inicial maiúscula.
Fonte: https://medium.com/@jsaito/making-a-case-for-letter-case-19d09f653c98
Um pouco de opinião

Quando você pensa em sistemas, as palavras reservadas ou palavras padrão da linguagem, ou que se repetem a todo o momento e são iguais para todos, poderiam ser "mais discretas", já as variáveis ou classes (como no CSS), que são palavras que o usuário "inventa" (e que cada um pode escrever de um jeito), você poderia definir regras claras. Pois como são palavras concebidas  pelo próprio usuário regras poderiam ser melhor que boas práticas. Essa seria uma maneira de normalizar a escrita independente de quem escreve. No CSS .classe é diferente de .Classe, mas os dois funcionam... Isso é bom ou ruim? Logicamente depende, mas se só fosse permitido uma das formas poderia ser melhor para o usuário. O usuário gosta de seguir padrões, e o olho aprende a achar padrões... E o Pascal Case pode ser um padrão mais fácil para o usuário identificar palavras não originais da linguagem (palavras que são definidas por outros usuários). Mas como falei, mais pesquisas e testes devem ser feitos.
Exemplo de tabela com regras claras:

Gestalt
Quando se fala em "reconhecimento de padrão" lembre-se que nem tudo que vemos estamos na verdade lendo. Um dos princípios da Gestalt é o reconhecimento de formas. O olho humano e o cérebro sempre tendem e reconhecer formas e padrões. E isso pode ser fundamental para a escaneabilidade do código. É como um artifício que pode auxiliar a reconhecer rapidamente palavras no meio do texto.

Como nosso cérebro utiliza parâmetros de leitura visual, ao enxergarmos um composto de elementos (sejam eles objetos, pessoas, paisagens, animais ou textos), a tendência é agrupar características que sejam semelhantes, de forma que sua interpretação seja a mais rápida possível.

Fonte: https://whitecom.com.br/8-principios-da-gestalt/
Wiki da Gestalt: https://pt.wikipedia.org/wiki/Gestalt

Embora seja sabido há algum tempo que o texto de tamanho maior é mais legível, este estudo mostrou que o peso e o processo também são importantes. As letras minúsculas exigiam 26% mais tempo para leitura precisa do que letras maiúsculas, e o texto condensado exigia 11,2% mais tempo do que o normal. Também houve efeitos significativos de interação entre o caso e o tamanho, sugerindo que os efeitos negativos das letras minúsculas são exacerbados com pequenos tamanhos de fonte.

Antigamente as IDEs, Terminais e Prompts não eram tão customizáveis, eles tinham um font-size padrão assim como um font-family padrão, e cor. Tudo foi pensado para o usuário ter uma melhor experiencia. Então as escolhes tipográfica também estão ligadas a forma como você vai escrever. Já é comprovado que textos longos não devem ser escritos todo em maiúsculo, assim como fontes mais "condensadas" são mais difíceis de serem lidas.

Repare no formato dos "shapes" veja como o UpperCase é mais difícil de identificar o caractere, principalmente pela "falta" de contraste por não ter descendentes (p) e ascendentes (d) na base-line e caps-line.

Veja como uma fonte com a "Altura de X" pequena é mais difícil de perceber a diferença entre Upper e Lower case (a primeira fonte tem o X Height menor).

Auto regulamentação
Mas quando a linguagem é livre o que se vê é o surgimento de convenções, seja de escrita ou de organização, como é o caso do CSS e suas metodologias de nomenclatura como OOCSS, SMACSS, BEM, DRY. Site com alguns exemplos e definições https://tableless.com.br/oocss-smacss-bem-dry-css-afinal-como-escrever-css/ vale dizer que para cada uma delas existem prós e contras, mas escolhendo um padrão regras devem ser seguidas, mesmo em uma "linguagem" que não tem regras :)

E no Mobile?
Já pensou como pode ser cansativo escrever variando entre maiúsculas em minúsculas em um dispositivo Mobile? Ainda mais com o corretor ortográfico tentando transforma o camelCase toda hora? Esse é um ambiente que certamente teria que ser estudado para avaliar o que seria mais fácil e produtivo para o usuário trabalhar. Não achei dada que se refira ao assunto, mas talvez o kebab-case (palavras com hifenização) sejam mais fácil de digitar no celular.

Então todas essas escolhas podem influenciar na UX e na escolha do que adotar...
Livro recomendado Design-Time Web Usability Evaluation with Guideliner: https://site-109191.mozfiles.com/files/109191/2228-7961-1-SM.pdf
OBS 1: O artigo do NNGroup citado acima feito com palavras "avulsas" e não em textos corridos. Ele não aborda especificadamente Camel Case ou Pascal Case, e inclusive sugere que se façam mais estudos.
OBS 2: Não abordei no assunto, mas pense também qual dos dois estilos seria mais interessantes para os Dislexos. Pensando em acessibilidade e inclusão seria legal ter mais informações e levar em conta como uma pessoa com dislexia ou TDAH interagem com esses tipos.
Comment: Pior que eu acho que eles não têm :D Caso contr´rio seria fácil achar algo sobre isso, eu acho que eles escolhem porque gostavam assim. O pessoal do C# deve ter um motivo bom, mas só suponho. Porque o C# e .NET nasceram de uma implementação real do Java, pra eles mudarem tudo devem ter um motivo. Não quero nem saber o motivo deles, mas sim o motivo geral, que por coincidência pode ser o deles. A resposta é boa, instrutiva, ainda não tenho certeza se ela responde ao que quero. Sobre a consistência eu sei, até já escrevi várias vezes sobre isso. E não é questão de qual escolher, mas porque.
Comment: A introdução é muito boa porque não sabia disto, depois sobre a documentação do .NET não achei que adicionou nada relevante porque não é o foco da pergunta, a parte mais importante onde fala do que interessa é promissora, ainda estou digerindo. Tudo faz sentido, mas note que houve uma escolha diferente para variáveis, métodos, e tipos, só pra dizer os itens que considero mais importantes e sua explicação não considera essas diferentes, note que a pergunta tem a ver com método (eu entendo um pouco melhor a escolha pra variável e tipo).
Comment: A questão do *case sensitive* aí não importa para a questão, mas vamos dizer que é. A ideia do teste A/B é padrão pra UX e de fato deveria ser feita para a escolha, a dúvida é justamente se fizeram antes que eu possa aproveitar ou concluíram algo mesmo que empiricamente. Inclusive imagino que tudo foi pensado para usar sem IDE de forma legível. pena que a análise final não é sobre os dois estilos. Ainda estou avaliando mais.
Comment: @Maniero sem querer dar desculpinhas rss, mas é que eu tenho um conhecimento muito superficial das abstrações da programação, assim como o que seriam métodos, classes etc... Tentei contribuir com o conhecimento que tenho sobre Tipografia e UX. Acho que quando surge uma linguagem (algo raro), assim como o FW JS por exemplo, os autores hj tem muito mais acesso a pesquisas e testes para avaliar o que seria mais adequado. Imagine em um ambiente Mobile, como seria chato ficar alternando entre o Upper e Lowers, e para piorar imagine o corretor ortográfico mudando o que vc escreve...
Comment: @Maniero Uma das eurística mais importantes é a consistência. Então o importante é que não seja algo "cada um faz como gostar", seria mais indicado manter um padrão. Agora qual padrão escolher vc pode decidir estudando sua persona, o ambiente dela e tendo empatia.
Comment: @Maniero esse é um assunto mais profundo do que parece, espero que apareçam outros dispostos a contribuir e que tragam algo que possa ser mais "definitivo" ou mais concreto pelo menos []´s


Is it possible to force "font priority" in style sheets?

Question: In various browsers, when a specific font is used (e.g. - Helvetica Neue), if that font is not found, the first font in the immediate family is used. So if I were to specify that Arial Narrow was the base font style for an element and my reader did not have this font, it would travel to the first available Arial font the system could find.
As an exercise, many sites like the Helvetica fonts (particularly the 'Neue' and 'Condensed' versions). They typically specify font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; believing that the browser will travel along this particular path and each font should be yummy with the first listed being the yummiest. However, Firefox/IE/Chrome (so I assume webkit browsers) all will fail to the find the specific Helvetica font required and move directly to the first font they encounter in the Helvetica family. One would think this would be Helvetica, but on my system it was defaulting to Helvetica 95 Black. I even tried renaming the font file to see if that was the cause, and no matter the filename, the result was that the page would default to Helvetica Black. I've found this to be the case with Arial as well.
So other than attempting to account for every single flavor of Helvetica, Arial, Verdana, Tahoma, ad infinitum, is there a way to force the browser to stop "guessing" at the family and accept only the exact font in question?
Comment: If you are on windows, did you just rename the original font file or go through the process of re-installing the font via the control panel?
Comment: You didn't by chance have font-weight set to 800 did you? (or something greather than 400 or bold)
Comment: Two useful links: http://www.rachaelmoore.name/web-design/fonts-typography/declare-a-safe-font-stack-with-css-font-family/ , http://www.rachaelmoore.name/web-design/fonts-typography/finding-font-name-css-font-family-font-stack/
Comment: @methodin - these weren't my pages. the new stackexchange site Nothing to Install did this upon launch. Deleting Helvetica 95 Black corrected the problem, but I'd like some method of being able to force standard Helvetica to prevail instead.
Answer: For starters, here's a description of the font matching algorithm as outlined in the CSS 2.1 specification (or CSS 3, if you prefer). This is a tricky issue though, as is evidenced by the disclaimer before the algorithm's details are outlined:

Because there is no accepted, universal taxonomy of font properties, matching of properties to font faces must be done carefully. The properties are matched in a well-defined order to insure that the results of this matching process are as consistent as possible across UAs (assuming that the same library of font faces is presented to each of them).

Also, note that you must enclose any font name containing whitespace with either single or double quotes, as per section 15.3.
Comment: Yah, the quotes thing is usually in there, that was just lazy typing on my part. My concern though is that the "black" fonts are being chosen first which bloats and distorts pages.
Comment: Close enough for government work. Might as well be marked as the answer.


Translation of list (text) values

Question: I am new do Drupal. I am testing out Drupal 8's multilingual capabilities.
I created a new content type with a field of type List (text) and a field of type Text. I have provided a translation for the text field, and switching language works fine when displaying it in a view. I have also entered a translation for the list field values, but those do not change when changing language. How do I get them to display in the selected language? I did set the Rendering Language to "Interface text language selected for the page". I don't see an option to make field values render in the selected language, but it's working fine for text fields. I cannot figure out why it does not work for list values.
Answer: You can refer the following tutorial for the same, it's well explained.
https://www.ostraining.com/blog/drupal/d8-multi-lingual/
https://www.drupal.org/docs/8/multilingual/choosing-and-installing-multilingual-modules
Comment: Thanks, that is a useful walk-through (although it did not answer my particular question).
Answer: Oh! After adding a translation for a list value, you have to edit (and save) one of the content entries containing the list, and after that the translations show up.
Comment: For me it took a whole lot of cache clearing. Also, I have found no way to translate the key since I'm using this on my Manage Display > format to output some HTML. Someone else might be trying to do this as well and thought I'd mention it.
Comment: Translating the key would not be a good idea. The key is like a "machine name" and it is used in queries, like Views. If you are filtering based on the values in the list, you want your query to always use the same keys, and have Drupal translate the values based on context.

Translation of list (text) values


Element "tucked" under another element...and it shouldn't

Question: This should be a CSS style question, but it has some C#/Blazor components...that's why I tagged both.
Here my main layout:

This is the header

    @Body

This is the footer

My problem is that whatever component that I have that takes place in @Body will appear "under" the header bar (even it's just a simple div or span).  My workaround right now is use css' top to avoid the header.  What do I have to do, so that the elements in the div won't start from underneath the header element?
Thanks!
Comment: I am sorry, Is not it how it is supposed to work, header>body>footer ?
Am i missing something
Comment: @ZiaAhmad...the header/footer/body are just semantics...I can call them whatever I want...the problem here is that the middle element seems to span the whole viewport, thus causing its element to show up underneath the header.  Hope this helps.
Comment: please include a screenshot, but from what i understand, you should add margin-top = header height on elements after header.
Answer: If you remove the fixed-top from your navbar element the body will no longer "tuck" under the header.

This is the header

    @Body

This is the footer

If you want to retain the fixed-like header and footer you should be able to use something like the below adapted from this answer
body {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.content {
  overflow: auto;
}

This is the header

  @Body

This is the footer

Comment: I believe the body would also "tuck" under the footer content if it was long enough due to ```fixed-bottom```. I have added an edit with an adaptation from another answer mimicking the fixed header and footer behavior with flex.
Comment: I took your first recommendation and apply h-100 to the middle div (body), the bottom remained as fixed-bottom and everything looks great!  Thank you for the lead!
Comment: I accept this answer thought it introduces a side-effect...when I scroll, I lose the header.  The good thing is that I am building a single-page app, so no scroll should be allowed any way....
Answer: To keep elements in normal flow don't give them position: fixed, or position: absolute. Use float: right and float: left. IF you have a header that is fixed or absolute, then the normal flow that follows that element will need a margin-top equal to or slightly greater than the height of the header div element. The margin will 'fill' the space behind the fixed/absolute element.
Comment: @Nikhil...thx for the prompt reply...as you can see the "header" does not call out the height explicitly...in this case what's my option for defining the margin-top?  thanks again!
Comment: @Nikhil...thanks for following up...I took the lead given by Douglas Riddle and everything  is working out now.


Nodejs Puppeteer Object undefined after function

Question: I am trying to do a webScraping application, but when initializing browser and page objects, they are undefined after returned from init() function. Here's a snippet:
Browser and Page are initialized at the top of my file: with browser = null  and page = null
so i want to use these globals in my init() function.
async function init() {
try {
    browser = await puppeteer.launch({
      headless: true,
      args: ["--disable-setuid-sandbox"],
      ignoreHTTPSErrors: true,
    });
    page = await browser.newPage();
  } catch (err) {
    console.log(err.message);
  }
  return {
    first: page,
    second: browser,
  };
}
var retvals = init();
browser = retvals.browser;
page = retvals.page;
console.log(typeof browser);
console.log(typeof page);

scrapeSite(urls[0]);

How can i solve this?
Thanks in advance
Comment: what if you put console log  after this line: "page = await browser.newPage();" before catch, what did you get ?
Comment: @sohaieb both of type object there.
Answer: You return this object from init():
{
  first: page,
  second: browser,
}

but you use it like this:
var retvals = init();
browser = retvals.browser;
page = retvals.page;

you should use it like this:
var retvals = await init();
browser = retvals.second;
page = retvals.first;

But I do recommend renaming those object keys since it's confusing (even to you now).
Also note that you made init() an async function. Every async function returns a promise, so:
console.log(typeof browser);
console.log(typeof page);

is executed before the promise is resolved, that's why these are undefined. So you need to use some way of dealing with asynchronous code, e.g. awaiting init().
Comment: it remains undefined.. I remember trying this aswell, but still not working.
Comment: One thing I missed: `init()` is an async function, so it returns a promise. You need to await it or use `.then()`. I updated my answer.


Adding bcd store entry to add in legacy win 2003 dual boot option

Question: What settings to you use to add a legacy win 2003 config to the bcd store on win2008 server to enable the dual boot option. I tried to use easybcd, but I think it is a crock and it added a legacy boot.ini option which I don't think was their in the first place. I think it was {bootmgr}. Any help would be appreciated, as I am completely in the dark.
regards
Bob.
Answer: Have a look at this KB article; it was written for repairing non-working dual boot configurations, but it contains instructions to create additional boot entries for previous operating systems:
http://support.microsoft.com/kb/919529/en-us


Is there any reason why I would want to upgrade Windows 2003 Server to Windows 2008 Server Enterprise?

Question: I found similar questions but in reality I have to justify why I really need 2008.  I have 2003 and other than it's nine-years-old, I found it wouldn't do ASP.MVC and I am sure many other things.  I'm sure I'm not specific enough.  I was hoping for something...

things I can come up with AD is better, but I don't know why.
Security better, but I don't know why
faster?  I have no idea.
better IIS.  Is this really true?

Not sure really why one is better than the other.
thanks.
Comment: Why the down vote with no comment?  bad form.
Comment: Sounds like you need to do some research on your own and come back when you have a real question.
Comment: Aside: Server 2003 will do ASP.NET MVC, you just need to install it. I had Server 2003 with ASP.NET MVC 3 in a VM only last week. I did have to install .NET 4 and the MVC files, but that was about it.
Comment: Johnny, there's not really much of a question here, and there's sort of 5 half-questions. If you have a very specific question that can actually have a objective answer, please update your question, otherwise I don't think you'll find what you're looking for.
Comment: @mark I disagree but okay.
Comment: @johnny Please read the [faq] - This is a place for specific questions to get answered, not for discussions. The question that you are asking can only be answered by a discussion.
Answer: I'd say age is the biggest factor here. The fact you're even thinking about not buying the current version of the operating system (seemingly without good reason) is crazy to me, but that's my opinion I guess. Also, when you say Windows Server 2008, I hope you actually mean Windows Server 2008 R2.
More importantly however, the final set of security updates for Windows Server 2003 will be released on July 14th 2015. That's only 4 years away and will come round so much quicker than you think. Unless you can be absolutely certain the server will be replaced before the operating system reaches end of life, you'll be running production (and I'm guessing business critical) applications on an unsupported and vulnerable operating system before you know it.
Not only is Microsoft going to shun you when something breaks, so will your application vendors. If you have any kind of problem, you are pretty much up the proverbial creek without a paddle.
Then you've got your security problems. There WILL be vulnerabilities, and Microsoft WILL NOT patch them. Try explaining to your boss that your server is down because it's been hacked. Then try to explain that when you re-install Windows, the attackers can do it all over again because there is not and will never be a patch to fix the underlying security problem.
Comment: Not to mention that the cost of bringing an out-of-date system up to current becomes increasingly expensive over time. Consider the cost of upgrading from Exchange 2007 to Exchange 2010 versus upgrading from Exchange 2000 to Exchange 2010. Supported upgrade paths also become fewer as time drags on.
Comment: Good stuff, I agree with it personally 100%. I wish I saw more vendors agreeing with the Vendors shunning the OS. I know some that aren't even close to supporting 2008 yet, and at least 1 that still uses 2000. I wish they would die.
Answer: With Windows 2008 Enterprise (and enough RAM), you could run up to 4 Enterprise Windows VMs with Hyper-V.  You could also Physical-to-Virtual (P2V) your existing Windows 2003 server for running any applications that won't run on Windows 2008.
Comment: Why not?  Beats buying 4 physical servers.
Comment: But why would I want to run 4 enterpise windows server iterations like that?
Comment: because then my single point of failure is the same machine.  If that goes down I lose everything.


Count JSON objects where value is x

Question: I want to use jQuery to count all alarms where almSeverity = "1". I get the following JSON response from a web service:
{
"notification": "Alarm search is complete",
"alarmList": [
  {
     "almId": 1,",
     "almSeverity": "1"
  },
  {
     "almId": 2,
     "almSeverity": "2"
  },
  {
     "almId": 3,
     "almSeverity": "1"
  }
]
}

I count all alarms like so:
data.alarmList.length;

...but what would be the best way to count the alarms where almSeverity is 1?
Comment: create a custom json parser function and counting the no. of almSeverity are equal to 1.
Answer: Looks like you have a javascript array, not JSON, and if so you can just filter it
data.alarmList.filter(function(x) {
    return x.almSeverity == '1';
}).length

FIDDLE

Count JSON objects where value is x


How to enable or disable a ClusteredScheduledTask in Powershell 4.0

Question: Reference to this page: http://technet.microsoft.com/en-us/library/jj649815.aspx
I'm finding ClusteredScheduledTasks a bit daunting to handle without a GUI interface.
For example, they have a Disable-ScheduledTask cmdlet.  Could I run that against a ClusteredScheduleTask?  If not, what would be the procedure to enable or disable a clustered schedule task?
Are many people actually using the Windows feature of ScheduledClusteredTasks, or do they get some third party utility?
Answer: The proper procedure is to use Unregister-ClusteredScheduledTaskcmdlet.
The Unregister-ClusteredScheduledTask cmdlet removes a clustered scheduled task from all nodes of a failover cluster
Comment: You can try piping it to disable-scheduledtask `get-ClusteredScheduledTask | disable-scheduledtask`.
Comment: I don't want to remove it, just disable it for maybe an hour, then re-enable it.  Is that not possible?


$f(f(f(x))) = x$. Prove or disprove that f is the identity function

Question: Let $f$ be a continuous function on $\mathbb R$ satisfying the relation
$$f(f(f(x))) = x\ \text{for all}\ x \in \mathbb R$$
Prove or disprove that $f$ is the identity function.
I tried taking the derivative. From the derivative, I'm not sure about it, but I concluded it had to be of degree 1 if it is a polynomial since if it'd have been of degree 2 or higher.. there needed to be terms of $x$ in the derivative.. which are not there.
Comment: Hint : $x,f(x),f (f(x))$ must be different. Now use the  intermediate value theorem  for $f$ in a clever fashion. Interestingly enough, something similar can be done for functions continuous on the unit circle.
Comment: Hello, Would you mind showing us what you have tried, or what your think is the answer. It would help immensely in showing you how and why it is what it is.
Comment: There are ways to disprove. Try some functions with undetermined coefficients.
Comment: @GeorgeLaw thanks for pointing that out.. I forgot that if I took the derivative.. I was assuming that f is differentiable.. but couldn't we at least assume in general that f has to be differentiable over some of the domain?
Comment: Related: [Suppose a function $f : \mathbb{R}\rightarrow \mathbb{R}$ satisfies $f(f(f(x)))=x$ for all $x$ belonging to $\mathbb{R}$.](https://math.stackexchange.com/questions/758951/suppose-a-function-f-mathbbr-rightarrow-mathbbr-satisfies-fffx)
Comment: @dxiv: No that function is not _defined_ on domain $\mathbb{R}$. In particular, $-\frac{1}{\sqrt{3}} \notin \mathrm{dom}(f)$ for the given function. It _would_ work if we were in the projectively extended real number line though, then it is both defined everywhere and continuous everywhere. But not $\mathbb{R}$ and the question is about $\mathbb{R}$.
Comment: @Winther Each of those has a discontinuity, indeed. Point taken, close-as-duplicate vote retracted.
Answer: You can prove that $f(x) \equiv x$ in four fairly simple steps:

Show that $f$ is one-to-one. Assume $f(x) = f(y)$ and show that this implies $x=y$ by applying $f$ two times to each side of the equation.
Show that a continuous function that is one-to-one has to be strictly increasing or decreasing. This follows for example by the mean-value theorem.
Show that $f$ cannot be strictly decreasing. If it is then $f(x) < f(y)$ for $x > y$. Now apply $f$ two times show that this gives us a contradiction ($x<y$).
Show that if $f$ is strictly increasing then $f(x) = x$. Assume 1) $f(x) > x$ and 2) $f(x) < x$ and try to derive a contradiction in both these cases (again by applying $f$ to the inequality using that $f$ is increasing).

All these points apart from the first two are covered in the answer to this question.
Answer: The only solution is $f(x)=x$.  First, we note that if we have two functions $f:X\to Y$ and $g:Y\to X$ such that $f\circ g$ and $g\circ f$ are identity maps, then $f$ and $g$ must be bijective functions.  Now take $g=f\circ f$.
Further, because $f$ is continuous and bijective, it must be monotonic.  Now, you have two cases, $f$ is increasing, or $f$ is decreasing.  If $f$ is increasing and $f(x)>x$, then $x=f(f(f(x)))>f(f(x)>f(x)>x$, which is a contradiction.  The inequalities are reversed if $f(x)<x$.  If $f$ is decreasing, we have that if $x<f(x)$, then $f(x)>f(f(x))$, so $f(f(x))<f(f(f(x))=x$, and hence $x>f(x)$, which is a contradiction, and similarly if $f(x)<x$.

However, a harder and more interesting problem is asking if you can have a point with period 3.  This is impossible for polynomials with integer coefficients, but is possible for continuous functions, but when it happens, things are messy.  As shown in the paper "Period three implies chaos", if you have a point of period 3, you will have a point of every other possible order.
Comment: @SJA I do not know of any references. I have never read any books on dynamical systems, just a random paper I found on Sharkovskii's theorem.
Comment: The Last result @Aaron had mentioned is the very interesting theorem named SARKOVSKII's theorem
Comment: Actually, Sharkovsii's theorem is a refinement of this which says exactly which periodicities imply which other periodicities. There's is a well ordering of the integers for this, 3 being the first element. https://en.wikipedia.org/wiki/Sharkovskii's_theorem
Comment: @ Aaron can you please refer a good book of discrete dynamical system. In particularly where structural stability is discussed in a nice way.. Because to prove a map structurally stable , I find it quite difficult. Actually I follow Robert Devaney's book . Please suggest me a good reference.


Calculate the value in a column based on JOIN results?

Question: I have a table, Account, which I am querying to identify old accounts based on sales records. An account may have multiple rows in a Property table. A property may be closed. If all properties on an account are closed, the account should be returned as it is old.
How do I identify an account where all properties are closed?
Additionally, an account is considered old if they have not purchased a Service in 24 months.
As an example, given the following tables:
-- ACCOUNT --
+-------+-----------------------------------+
| ac_id | ac_email                          |
+-------+-----------------------------------+
|  1416 | email@example.com                       |
|  1419 | firstname.lastname@example.com                       |
+-------+-----------------------------------+

-- PROPERTY --

+------+---------------+-------+
| p_id | p_closed      | ac_id |
+------+---------------+-------+
|    3 |  FALSE        |  1416 |
|    6 |  TRUE         |  1419 |
|    7 |  TRUE         |  1419 |
+------+---------------+-------+

--SERVICE--

+------+------------+
| p_id | s_saledate |
+------+------------+
|    3 | 2010-03-17 |
|    3 | 2011-02-16 |
|    6 | 2022-11-14 |
|    7 | 2022-01-24 |
+------+------------+

I would expect the following returned table
+------------+-----------------------+-----------------------+--------------+------------+--------------+------------------+
| account_id | email                 | all_properties_closed | property_ids | latest_sale_date |
+------------+-----------------------+-----------------------+--------------+------------+--------------+------------------+
|       1416 | email@example.com           |       FALSE           |     9            | 2011-02-16       |
|       1419 | firstname.lastname@example.com           |       TRUE            |    6,7           | 2022-11-14       |
+------------+-----------------------+----------------+---------------------------+--------------+------------------+

Bob's account is returned because he's not had a Service in over 2 years & Joe's account is returned because he has had a service in 2 years, but all of his properties are closed.
This is my current query
 SELECT
 ac_id as account_id,
 GROUP_CONCAT(DISTINCT p_id) as property_ids,
 MAX(sale_date) as latest_sale_date
 FROM Account
 JOIN Property USING (ac_id)
 JOIN Service USING (p_id)
 GROUP BY ac.ac_id
 HAVING latest_sale_date < 2021-03-31

I imagine I need to use the ALL operator and WHERE to get the all_properties_closed column, but I'm unsure how. Do I need a subquery?
Comment: What is the data type of `p_closed`?
Comment: @forpas it's bit(1) with a default b'0'. I just put it as TRUE or FALSE in my example because the actual value does not render in my CLI
Answer: You can compute all_properties_closed with conditional aggregation. Assuming that p_closed is of a string-like datatype, that would look like:
SELECT
    ac_id as account_id,
    MIN(p_closed = 'FALSE') all_properties_closed
    GROUP_CONCAT(DISTINCT p_id) as property_ids,
    MAX(sale_date) as latest_sale_date
FROM Account
JOIN Property USING (ac_id)
JOIN Service USING (p_id)
GROUP BY ac.ac_id
HAVING latest_sale_date < 2021-03-31 OR all_properties_closed

Expression MIN(p_closed = 'FALSE') yields 0 if any p_closed in the group has a non-'FALSE' value, else it returns 1; we can use this information to filter in the HAVING clause.
In normal usage you would have a 0/1 flag in column p_closed, and we could just do:
MIN(p_closed) all_properties_closed

Answer: Yes, you can use a subquery to check if all properties for an account are closed. Here's a modified version of your query that adds the all_properties_closed column:
SELECT
 ac.ac_id as account_id,
 ac.ac_email as email,
 GROUP_CONCAT(DISTINCT p.p_id) as property_ids,
 MAX(s.s_saledate) as latest_sale_date,
 NOT EXISTS (
   SELECT 1 FROM Property p2 WHERE p2.ac_id = ac.ac_id AND p2.p_closed = FALSE
 ) as all_properties_closed
FROM Account ac
LEFT JOIN Property p ON p.ac_id = ac.ac_id
LEFT JOIN Service s ON s.p_id = p.p_id
GROUP BY ac.ac_id
HAVING latest_sale_date < 2021-03-31 OR all_properties_closed

In the subquery, we're checking if there exists a property for the same account that is not closed (p2.p_closed = FALSE). If there is no such property, then NOT EXISTS returns TRUE, indicating that all properties are closed.
Note that I've also added ac.ac_email to the select list and used LEFT JOIN instead of JOIN to ensure that we get all accounts, even if they don't have any properties or services.
The HAVING clause at the end includes both criteria for identifying old accounts: those with no services after the given date, or those with all properties closed.


resultado em 2 colunas da tabela

Question: Boa tarde amigos, estou com dificuldade em montar uma tabela com resultado em 2 colunas com informações do banco de dados.

Equipamento locado

Patrimônio

if($cliente->equipamento){

    $array_equipamento = explode( "," , $cliente->equipamento ) ;

    foreach ($array_equipamento as $value) {

    $equipamento = $objeto_equipamento->busca_equipamento($value);

        $equipamento->nome
        $equipamento->patrimonio

    }

}

coluna 1 	  Coluna 2

 1 	  2

 3 	  4

 5 	  6

 7 	  8

Os números do exemplo representam a sequencia de resultados para melhor entendimento.
Comment: Não estou entendendo... qual código você está usando?
Comment: desculpa, editei o html para melhor vizualização !!!
Comment: Thiago, meu caro Odson, se você não passar como está as colunas dessa tabela, fica complicado sabermos como gerar a mesma!
Comment: Precisamos saber da onde você pega essas informações?
Comment: do banco de dados mysql ... vem da consulta query !!!
Comment: `$equipamento` faz assim da um `var_dump($equipamento)` e cola o resultado aqui!
Comment: è o seguinte, eu ja recebo e listo tudo na tabela amigo, o problema que tenho é montar o resultado em duas colunas, só isso .... um algoritimo para dividir na tabela
Comment: como informei, o importante nao são meus dados e sim como apresentar o resultado dividido em 2 colunas, se vc conseguir o algoritimo eu aplico em meu codigo !!
Comment: é complicado dar um `var_dump`?
Comment: @ThiagoLopez
Somente com os dados fornecidos é impossível propor uma solução.
Comment: editei o codigo, se fica ais simples pra voces assim !

Como podem ver esta listando em duas colunas com duas informações, porem eu quero que tenha mais duas colunas a direita e que liste 2 registros por linha para aproveitar o tamanho da folha.
Answer: Boas,
Mostra a estrutura da tabela sff.
Simulei a esturra das tabelas com classes utilitário (código a seguir) e resultado foi o apresentado a seguir. Não alterei mais nada.
    <?php

/*
*
* Classes utilitária para simular a estrutura da tabela
*/
class Equipamento{

    public $id;
    public $nome;
    public $patrimonio;

    public function busca_equipamento($value){

        $testeEquipamentos = self::obterListaDeEquipamenetoTeste();

        foreach($testeEquipamentos as $k => $equipamento){
            if($equipamento->id == $value){
                return $equipamento;
            }
        }

        // um pequeno teste, caso não for encontado o respetivo id/value
        return new  Equipamento();
    }

    public function obterListaDeEquipamenetoTeste(){

        $eq1 = new Equipamento();
        $eq1->id = 1;
        $eq1->nome = "Equipamento 1";
        $eq1->patrimonio = "200€";

        $eq2 = new Equipamento();
        $eq2->id = 2;
        $eq2->nome = "Equipamento 2";
        $eq2->patrimonio = "300€";

        $eq3 = new Equipamento();
        $eq3->id = 3;
        $eq3->nome = "Equipamento 2";
        $eq3->patrimonio = "400€";

        return [$eq1,$eq2,$eq3];

    }
}

class Cliente{
    public $id;
    public $nome;
    public $equipamento;
}

$cliente = new Cliente();
$cliente->id = '1111';
$cliente->nome = 'Clinet Teste';
$cliente->equipamento = '1,2,3';

?>

    <?php
    /*
    *
    * codigo original => nada alterado
    */

Equipamento locado

Patrimônio

    <?php

    $objeto_equipamento = new Equipamento();

    if($cliente->equipamento){

        $array_equipamento = explode( "," , $cliente->equipamento ) ;

        foreach ($array_equipamento as $value) {

        $equipamento = $objeto_equipamento->busca_equipamento($value);

        echo "

            $equipamento->nome
            $equipamento->patrimonio

";

        }

    }

    ?>

Comment: muito bom amigo, agora o que falta é fazer o que realmente preciso que é listar o resultado da maneira que descrevi na pergunta !! sendo 2 registros por linha na tabela.
Comment: Podes postar uma imagem do diagrama da base de dados. Suponho que tens duas tabelas "Cliente" e "Equipamento". Onde cada cliente pode ter 0 ou mais equipamento.
Answer: Boa tarde a todos, obrigado pela ajuda de todos mas já resolvi meu problema ... segui o codigo fonte onde separo os resultados da query em duas colunas independente da qtd de registros, grato.
if($cliente->equipamento){

    // quantidade de virgulas faz distinção de numero de registros - 1
    // $reg é uma string separada por ',' na coluna $cliente->equipamento na minha BD, para entendimento de todos
    $reg = substr_count( $cliente->equipamento , ',' ) ;

    $array_equipamento = explode( "," , $cliente->equipamento ) ;

    $colunas = 2;

    $html .= '
';

    $i = 0;

    foreach ($array_equipamento as $value)
    {

        $equipamento = $objeto_equipamento->busca_equipamento($value);

        if( $i == $colunas)
        {
            $html .= '

';
            $i=0;
        }

        $html .= ''.$equipamento->nome.'	';
        $i++;
    }

    $html .= '
';
}

Comment: alguem pode aceitar minha resposta para finalizar o top, por favor !!!

resultado em 2 colunas da tabela


Prove that acl(acl(A))=acl(A), in model theory

Question: Can someone give me an elementary proof of this fact?
Edit: This is an exercise in Marker's text, right after he defines
$$\text{acl}(A)=\{x:x \text{ is algebraic over }A\}.$$
The question and the full definition is here.
Comment: Can you do this in particular cases? Say, do you see how to prove that the span of the span of a set of vectors is just the span of the set of vectors, or that the result holds if the algebraic closure is in the usual field theoretic sense?
Comment: What properties of $\operatorname{acl}$ do you have at your disposal?  E.g., if you are working through a book could you please provide that as a reference?
Comment: Thanks for the comment. I've added to the question, so that hopefully it's more accessible.
Answer: First, note that if Grandma Helen has only finitely many children, and each of those children have only finitely many children, then Grandma Helen has only finitely many grandchildren.
For the problem, however, there is the subtlety that perhaps some but not all of the children of Helen have only finitely many children. But you can still use the same idea: If Grandma Helen has only finitely many children, and one of those children has at most 10 children (perhaps some others have infinitely many), then the collection of grandchildren of Helen whose parents have at most 10 children is finite.
Those grandchildren (whose parents have at most 10 children) satisfy a first-order expressible property, with Helen as a parameter, that is satisfied by only finitely many other people.
Comment: This is a very nice way to explain what's happening without the formulas getting in the way. Thanks!


Spring 2.1.0.M4 rabbitmq declare queues and bind them to listeners in runtime

Question: Let's say I have a declared listener:
Listener.java
@RabbitListener(id = "test listener 1")
    public String test2(String req) {
        return req + " result";
}

I'm trying to expose it via queue during runtime:
ListenerTest.java
Queue declaredQueue = new Queue("new.queue", false);

admin.declareQueue(declaredQueue);

SimpleMessageListenerContainer listener = (SimpleMessageListenerContainer)
            registry.getListenerContainer("test listener 1");
listener.addQueues(declaredQueue);

And then I try message the newly declared queue :
String result = template.convertSendAndReceiveAsType("new.queue", "req", ParameterizedTypeReference.forType(String.class));

But it just times out and returns null.
When I inspect the listener in debugger I can't see any consumers bound to the new queue
You can find by rabbit config here and the rest of the source to test this here.
It's worth to note that this exact setup works in spring boot version 2.0.5.RELEASE so it might be a bug. I need to find a way to reinitialize the consumers.
Answer: Adding queues at runtime will cause the container to recycle its consumers (the equivalent of stopping and restarting the container). See https://github.com/spring-projects/spring-amqp/blob/master/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java#L687 This is due to the way the consumer is designed; each consumer thread consumes from multiple queues.
Changing the consumer count does not restart all consumers; see https://github.com/spring-projects/spring-amqp/blob/master/spring-rabbit/src/main/java/org/springframework/amqp/rabbit/listener/SimpleMessageListenerContainer.java#L168
The new DirectMessageListenerContainer does not need to restart its consumers when queues are added (there is at least one consumer per queue).
However, it does not support dynamic concurrency scaling.
Comment: Oh, I see; yes; looks like a bug; however, `addQueueNames()` should work.
Comment: DirectMessageListenerContainer was not used here at all, listeners are the implementation of SimpleMessageListenerContainer, does that mean that it's supposed to restart it's consumers?
Comment: I was just suggesting that, if restarting the consumers concerns you, you can use a DMLC instead. Adding queues to the SMLC should automatically restart the consumers; turn on DEBUG logging to verify.
Comment: that's the whole point of this question, after the spring update `SimpleMessageListenerContainer#addQueues` no longer refreshes the consumers, please see the updated answer I posted
Comment: I've been looking for a way to report it, thanks for raising a ticket
Comment: spring-rabbit 2.1.0.RELEASE is in maven central with the fix; it will be incorporated into Boot 2.1.0.RC1 (due tomorrow)
Answer: After the 2.1.0 release SimpleMessageListenerContainer no longer overrides AbstractMessageListenerContainer#addQueues which causes SimpleMessageListenerContainer#queuesChanged to not be invoked (likely a bug). However SimpleMessageListenerContainer#addQueueNames is overrided and working. So this  either has to be changed to
SimpleMessageListenerContainer listener = (SimpleMessageListenerContainer)
            registry.getListenerContainer("test listener 1");
listener.addQueueNames(declaredQueue.getName());

Or queuesChanged has to be called manually
SimpleMessageListenerContainer listener = (SimpleMessageListenerContainer)
            registry.getListenerContainer("test listener 1");
listener.addQueues(declaredQueue);
Method method = SimpleMessageListenerContainer.class.getDeclaredMethod("queuesChanged");
method.setAccessible(true);
method.invoke(listener);


i made c++ code where its need to pass structure pointer in a function

Question: i got confused about the structure when i need to to pass the value in a function
<code>#include <iostream>
using namespace std;

struct student
{
    int studentID;
    char studentName[30];
    char nickname[10];
};

void read_student(struct student *);
void display_student(struct student *);

int main()
{

    student *s;
    //struct student *ps;
    read_student(s);

    display_student(s);

}

void read_student(struct student *ps)
{
    int i;
    for (i = 0; i <= 2; i++)
    {
        cout << "Enter the studentID : ";
        cin >> ps->studentID;
        cout << "Enter the full name :";
        cin.ignore();
        cin >> ps->studentName;
        cout << "Enter the nickname : ";
        cin.ignore();
        cin >> ps->nickname;
        cout << endl;

    }
}

void display_student(struct student *ps)
{
    int i;
    cout << "student details :" << endl;

    for (i = 0; i <= 2; i++)
    {
        cout << "student name : " << *ps ->studentName << " (" << &ps ->studentID << ")" << endl;

        ps++;
    }
}
</code>
its only problem at the variable at line 19 and when i try to edit it will became more problem

<code> student *s;
 //struct student *ps;

  //struct student *ps;
  read_student(s);
  display_student(s);
</code>

also can someone explain how to transfer pointer value of structure to the function and return it back to the main function
Comment: You don't need to repeat `struct` everywhere in c++.
Comment: *"how to transfer pointer value of structure to the function and return it back to the main function..."* Read about **pass by reference** in your favorite [c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)
Comment: What are the inputs? What is the expected output? What is the current output? How does the expected output differs from the current output.
Comment: Others gave you good links already. Let me add that if the resource you are learning from (book, course etc) teaches the use of `char` arrays for strings and the repeated `struct` use, it is probably not a good resource. In any case, as a new user here, please take the [tour] and read [ask].
Answer: You are suffering from some leftovers from your C-Language time. And, you have still not understood, how pointer work.
A pointer (as its name says) points to something. In your main, you define a student pointer. But it is not initialized. It points to somewhere. If you read data from somewhere, then it is undefined behavior. For writing, it is the same, plus that the system will most likely crash.
So, define a student. And if you want to give it to a sub-function, take its address with th &-operator (this address will point to the student) and then it will work.
You need also to learn abaout dereferencing. Your output statement is wrong.
Last but not least, if you want to store 3 students, then you need an array or some other storage where to put them . . .
In your read function you always overwrite the previously read student and in your display function you show undetermined data.
Please have a look at your minimal corrected code:
<code>#include <iostream>
using namespace std;

struct student
{
    int studentID;
    char studentName[30];
    char nickname[10];
};

void read_student( student*);
void display_student( student*);

int main()
{
    student s;
    //struct student *ps;
    read_student(&s);

    display_student(&s);

}

void read_student( student* ps)
{
        cout << "Enter the studentID : ";
        cin >> ps->studentID;
        cout << "Enter the full name :";
        cin.ignore();
        cin >> ps->studentName;
        cout << "Enter the nickname : ";
        cin.ignore();
        cin >> ps->nickname;
        cout << endl;
}

void display_student( student* ps)
{
    cout << "student details :" << endl;
    cout << "student name : " << ps->studentName << " (" << ps->studentID << ")" << endl;
    ps++;
}
</code>
And, the commenters are right. You must read a book.


Blank lines in text files: Ubuntu vs Windows

Question: I have a text file which contains some data, with a number of blank lines which intersperse the data.
When opened in Ubuntu, I can see the blank lines, however on a windows machine all the data is displayed on the same line with no new lines at all.
What is the reason for this?
Comment: Possible duplicate of [Difference between CR LF, LF and CR line break types?](http://stackoverflow.com/questions/1552749/difference-between-cr-lf-lf-and-cr-line-break-types)
Comment: CRLF vs LF - different newlines on different platforms.
Answer: In a text file there are characters that you can't see in the text editor that indicate a new line. On Windows it is \n\r and on Linux it is \n.
Here is a good link that will explain this in a little more detail.


How to recover partition/filesystem from failed dd command

Question: I have a server with two SSDs of 250GB each.sda contained all my stuff while sdb was empty. I was trying to copy drive sda to drive sdb using the following command:
dd if=/dev/sda of=/dev/sdb conv=noerror,sync
I ran the command over ssh. However before the process finished, my pc was closed, the ssh connection closed as well and so was the dd command. I thought it's not a big deal since I was copying FROM sda to sdb. But now I can't boot into my server, sda appears to have been damaged, the boot partition is missing, I can t mount the partition left on sda, sda1. On sdb there s nothing as well. Also sda1 appears to have overwritten the original boot & sda1 partition that held my filesystem.
Looking with TestDisk on the sda1 partition I could only see a lost+found empty directory on the partition.
Using photorec I could recover files, mostly photos so I know for sure that the my files are still there.I just don't have a partition/working filesystem.
How could I recover the old partitions and filsystem from sda?
Comment: Please edit your question to add the errors logged you get when attempting to fsck or TestDisk then mount these volumes. And which file system type.  And where  /boot and /  were supposed to be and what  sda1 is.
Answer: Regarding getting back up and running, figure out when this server needs to be repaired. Note it will take significantly longer to do analysis and recovery of block and file system corruption, versus a clean rebuild.
Restore from any backups that may exist. As your OS distro is busted, this will require a recovery environment. And possibly a clean install. Recovery of the broken storage can also happen, but you may need to run these in parallel to get up and running in a reasonable amount of time.
Should backups not exist and the data be valuable, do not do anything to the problem disks until consulting with a data recovery specialist. Obviously you do not have to use such services, but the fewer writes after the problem the better.
If what you say is true that sdb was the target device, and was blank, sda corruption would be mysterious.
Beware, however, that  sda and sdb are not stable names, and may change depending on how hardware is enumerated and added. Going forward, on Linux it is safer to use one of the stable names under /dev/disk/by*.    The last few digits of a LUN WWN are just as easy to confirm, and will not change.
Comment: Already did a backup image of the damaged disk with dd rescue. Then recovered some files mostly photos using photorec.

Then I tried recovering the partition with testdisk. I ran a deep search and found the partition and even managed to mount it and the size appears to match the original partition. Problem is the partition contains only a `lost+found` directory with all my files. How would I be able to rebuild a filesystem from this partition?


undefined local variable or method

Question: class ProdutItem
  attr_reader :item, :price_unit, :qtde

  def initialize(item, price_unit, qtde)
    @item = item
    @price_unit = price_unit
    @qtde = qtde
  end

  def calc_qtde
     (price_unit * qtde)
  end

end

 prod = ProdutItem.new("A", 0.50, 3)
 puts prod.calc_qtde

class CalcDiscount
  attr_reader :discount

  def initialize(discount)
    @discount = discount
  end

  def calc_desc
    (price_unit * qtde) - discount
  end
end

desc = CalcDiscount.new(0.20)
puts desc.calc_desc

Quando eu executo esse meu codigo acima retorna a seguinte msg de erro:

teste_04.rb:29:in calc_desc': undefined local variable or method
  price_unit' for #
  (NameError)
              from teste_04.rb:34:in `'

Eu nao consigo identificar o erro. Alguem poderia me ajudar?

Comment: Acredito que você não esteja criando a variavel : "calc_desc"
Comment: `price_unit` não existe dentro da classe `CalcDiscount` apenas na `ProdutItem` e se existir tem de ser acedida com `@`
Comment: Isac, mesmo add o price_unit, continua com erro: teste_04.rb:24:in `initialize': wrong number of arguments (given 1, expected 2) (ArgumentError)
Answer: Fiz dessa maneira e funcionou:
class ProdutItem
  attr_reader :item, :price_unit, :qtde

  def initialize(item, price_unit, qtde)
    @item = item
    @price_unit = price_unit
    @qtde = qtde
  end

  def calc_qtde
    (price_unit * qtde)
  end

end

class CalcDiscount
  attr_reader :discount

  def initialize(discount)
    @discount = discount
  end

  def calc_desc(product)
    (product.price_unit * product.qtde) - discount
  end
end

prod = ProdutItem.new("A", 0.50, 3)
puts prod.calc_qtde

desc = CalcDiscount.new(0.20)
puts desc.calc_desc(prod)

Para calcular o desconto, o método precisa do preço unitario e a quantidade do produto. Devido a isso, adicionei o parametro product no método que calcula o desconto para que possamos ter acesso a informação que queremos.

undefined local variable or method


Shopify API: How do I send customer an email about product being shipped?

Question: I'm trying to send a customer an email with order tracking information by updating the order fulfillment but the email is not being sent out. I can retrieve the fulfillment and add a tracking code and it saves properly but the status doesn't update.
 fulfillment_id = 3252574519475
 shopify_order_id = 3683332686003

 fulfillment = shopify.Fulfillment.find(fulfillment_id,order_id=shopify_order_id)
 fulfillment.tracking_numbers = [tracking_number]
 fulfillment.tracking_company = tracking_company
 fulfillment.notify_customer = "true"
 fulfillment.status = "success"
 fulfillment.shipment_status = "delivered"
 result = fulfillment.save()

When I visit https://dev-store.myshopify.com/admin/orders/3683332686003/fulfillments.json  I see the tracking_numbers update along with the tracking_company and tracking_urls but the status is still open:
 {
    "fulfillments": [{
        "id": 3252573110451,
        "order_id": 3683332686003,
        "status": "success",
        "created_at": "2021-03-22T14:36:55-04:00",
        "service": "gift_card",
        "updated_at": "2021-03-22T14:36:56-04:00",
        "tracking_company": null,
        "shipment_status": null,
        "location_id": 61514940595,
        "line_items": [{
            "id": 9689309610163,
            "variant_id": 39396209983667,
            "title": "$100 ta E-Gift Card",
            "quantity": 1,
            "sku": null,
            "variant_title": "$100.00 USD",
            "vendor": "A",
            "fulfillment_service": "gift_card",
            "product_id": 6571217256627,
            "requires_shipping": false,
            "taxable": false,
            "gift_card": true,
            "name": "$100 ta E-Gift Card - $100.00 USD",
            "variant_inventory_management": null,
            "properties": [],
            "product_exists": true,
            "fulfillable_quantity": 0,
            "grams": 0,
            "price": "95.00",
            "total_discount": "0.00",
            "fulfillment_status": "fulfilled",
            "price_set": {
                "shop_money": {
                    "amount": "95.00",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "95.00",
                    "currency_code": "USD"
                }
            },
            "total_discount_set": {
                "shop_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                }
            },
            "discount_allocations": [],
            "tax_lines": []
        }],
        "tracking_number": null,
        "tracking_numbers": [],
        "tracking_url": null,
        "tracking_urls": [],
        "receipt": {
            "gift_cards": [{
                "id": 483988799667,
                "line_item_id": 9689309610163,
                "masked_code": "•••• •••• •••• 74e2"
            }]
        },
        "name": "#1013.1"
    }, {
        "id": 3252574519475,
        "order_id": 3683332686003,
        "status": "open",
        "created_at": "2021-03-22T14:37:23-04:00",
        "service": "manual",
        "updated_at": "2021-03-22T14:49:45-04:00",
        "tracking_company": "UPS",
        "shipment_status": null,
        "location_id": 61514940595,
        "line_items": [{
            "id": 9689309642931,
            "variant_id": 39396224663731,
            "title": "The Pack",
            "quantity": 1,
            "sku": "FM-001",
            "variant_title": null,
            "vendor": "A",
            "fulfillment_service": "manual",
            "product_id": 6571220402355,
            "requires_shipping": true,
            "taxable": true,
            "gift_card": false,
            "name": "The Pack",
            "variant_inventory_management": null,
            "properties": [],
            "product_exists": true,
            "fulfillable_quantity": 0,
            "grams": 3629,
            "price": "111.99",
            "total_discount": "0.00",
            "fulfillment_status": null,
            "price_set": {
                "shop_money": {
                    "amount": "111.99",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "111.99",
                    "currency_code": "USD"
                }
            },
            "total_discount_set": {
                "shop_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                },
                "presentment_money": {
                    "amount": "0.00",
                    "currency_code": "USD"
                }
            },
            "discount_allocations": [],
            "tax_lines": []
        }],
        "tracking_number": "1Z6R96W802851935",
        "tracking_numbers": ["1Z6R96W802851935"],
        "tracking_url": "https:\/\/www.ups.com\/WebTracking?loc=en_US\u0026requester=ST\u0026trackNums=1Z6R96W80302851935",
        "tracking_urls": ["https:\/\/www.ups.com\/WebTracking?loc=en_US\u0026requester=ST\u0026trackNums=1Z6R96W80302851935"],
        "receipt": {},
        "name": "#1013.2"
    }]
 }

How do I get shopify to send the customer an email with the tracking number and update the status of the fulfillment from open to success so that the whole order is set to fulfilled? I've been manually creating orders on the store im not sure if that has anything to do with it.
I'm using this Python package https://github.com/Shopify/shopify_python_api
Answer: If you have set "notify_customer" to true at the fulfillment, that's the first thing. You should then create a so-called fullfillment event with "status" set to "in_transit". As a result of that, Shopify will:

Send an email to the customer
Set the fulfillment status to "in_transit"
Display the new status on the order status page

Creation of a fulfillment event is described quite well In Shopify's API documentation at:
https://shopify.dev/docs/admin-api/rest/reference/shipping-and-fulfillment/fulfillmentevent
With the help of fulfillment events you can also set further status values like "out_for_delivery" and "delivered".
Answer: As far as i see shopify doesn't have any relation with smpt so another lib is required, on python is quite easy to send emails; jinja is for convenience, you can send a full on html page.
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import jinja2
import ssl
import os

class Shipment_Email:

    mail_addr = 'smtp.mail.yahoo.com'
    mail_port = 465

    __email = str('email@example.com')
    __passw = str('your_api_password')

    def send_to(self, to, sub, data):
        content = self.template.render(data=data)
        msg = MIMEText(content, 'html', 'utf-8')
        msg['Subject'] = Header(sub, 'utf-8')
        msg['From'] = self.__email
        if not isinstance(to, str):
            msg['To'] = ', '.join(to)
        else:
            msg['To'] = to
        self.server.sendmail(self.__email, to, msg.as_string())

    @staticmethod
    def load_template(src):
        if os.path.isfile(src):
            with open(src, 'r') as file:
                return jinja2.Template(file.read())

    def __init__(self, debug=False):
        ssl_context = ssl.create_default_context()
        self.server = smtplib.SMTP_SSL(self.mail_addr, self.mail_port,
                                       context=ssl_context)
        self.server.login(self.__email, self.__passw)
        self.server.set_debuglevel(debug)
        self.template = self.load_template('./index.html')

    def exit(self):
        self.server.quit()

if __name__ == '__main__':
    mail_hanlde = Shipment_Email(debug=True)
    mail_hanlde.send_to('email@example.com',
        'Shopping list', {
            'Name': 'Alex',
            'Product': {
                'Coffe': 8.50,
                'Keyboard': 150
            }
        })
    mail_hanlde.exit()

index.html :
<!DOCTYPE html>

    <meta charset="utf-8">

{{ data['Name']}}'s shoping list:

    {% for item in data['Product'] %}

{{ item }} : {{data['Product'][item]}} eu

    {% endfor %}

For this to work on yahoo mail you need to get a custom device password, so tick the marked option and use that password instead of the account, they are not the same.


Persisting complex data between postbacks in ASP.NET MVC

Question: I'm developing an ASP.NET MVC 2 application that connects to some services to do data retrieval and update. The services require that I provide the original entity along with the updated entity when updating data. This is so it can do change tracking and optimistic concurrency. The services cannot be changed.
My problem is that I need to somehow store the original entity between postbacks. In WebForms, I would have used ViewState, but from what I have read, that is out for MVC. The original values do not have to be tamper proof as the services treat them as untrusted. The entities would be (max) 1k and it is an intranet app.
The options I have come up are:

Session - Ruled out - Store the entity in the Session, but I don't like this idea as there are no plans to share session between
URL - Ruled out - Data is too big
HiddenField - Store the serialized entity in a hidden field, perhaps with encryption/encoding
HiddenVersion - The entities have a (SQL) version field on them, which I could put into a hidden field. Then on a save I get "original" entity from the services and compare the versions, doing my own optimistic concurrency.
Cookies - Like 3 or 4, but using a cookie instead of a hidden field

I'm leaning towards option 4, although 3 would be simpler. Are these valid options or am I going down the wrong track? Is there a better way of doing this?
Comment: Don't forget TempData http://stackoverflow.com/search?q=tempdata
Comment: @R0manarmy Isn't TempData valid only for the current request?
Comment: Apparently it changed a lot in ASP.NET MVC2 http://blog.donnfelker.com/2010/02/26/aspnet-mvc2-tempdata-now-persists/  Choice quite

"We've changed the implementation in MVC 2 slightly as a result: the value will be removed from TempData after the request in which it is read, so it will continue to exist in your TempData dictionary until you display it in some page. This allows a multi-redirect scenario (such as Windows Live ID login) to use TempData and have it still be hanging around until you're ready for it."
Comment: Sounds like a HeisenData idea.. It changes when it is observed.
Comment: @R0MANARMY: Tempdata relies on Session Data TTBOMK
Answer: I am not quite sure why Session is a bad idea, if the client dose not need that backup copy, keeping the whole thing in server memory sounds the best; since the rest of the candidates are all sending from server to place (temporary) in clients' browser, and then get it back whenever client does any action. Situation is, whenever client ping back, server will unpack the encoded data (either in hidden field, cookie, url etc) and would possibly place in server again! It also waste bandwidth IMO.
OK, if client need (to inspect) the backup, I would consider hidden field(set) or simply serialize the data in XML and put it somewhere in the HTML.
EDIT
I still vote for Session. If you plan to take care the server farm, consider implement a cross server session provider:
http://msdn.microsoft.com/en-us/library/ms178587%28VS.80%29.aspx
and simply store the state in database.
Comment: The reason against session was we were not going to share session among web servers and we don't know how long to keep the data in cache. Also we would still need a way to add an identifier to the page to associate the particular edit with it's entity.
Answer: If you do Store it in a session then you need to ensure that if you implement a web farm that the session is loaded correctly.
We have (exactly) the same question here at the moment and what we've decided to do is to implement the Repository Pattern and link it to a cookie.
Then, if this becomes an issue, we can simply slot in either a session manager, db manager or whatever and our code need not even know because of the repository pattern.
We tinkered with the idea of hidden fields but it felt too much like ViewState and we all hated it in WebForms so the idea was scrapped.  But not just because we hated view state.  There were issues when you pressed Ctrl F5.  The contents would be cleared and then what do you do?
So at this point its a repository pattern with a cookie which may change but the implementation lends itself kindly to change.
EDIT
We also decided against hidden fields because it would be too easy to make changes to them and so you need to do some token stuff from the server to ensure it wans't tampered with.
The hidden fields just kept on adding complexity to what essentially should have been a very simple problem.
At least that was our thoughts on the matter.
Comment: How are you linking a particular series of page requests to the item in the repository? Eg if a user has two of the same page open, changes one then the other? Also do you clear the items after a set time to save memory?
Comment: The ctrl-F5 would not be an issue as the data is only used on a "PostBack", ie when the save button is clicked.
Comment: Never mind ctrl+F5, regular F5 can resubmit previous form.  In some cases clicking the Back button in the browser can also resubmit the form.  Are either of those cases an issue or would the given entity just be updated twice to the same value (second operation basically being a no-op)?
Comment: I was thinking F5 is Visual Studio... No, refresh in the browser would not be a problem as it would treat it as an update. These are simple CRUD screens.


Cryptography in java bytes to bits

Question: I wrote server and client and I would like to send some file which will be encrypted. So I have to operate on bits, not bytes, because my cryptography metod is like that: I send my file in parts of about 8 bits and I add to them some specific MAC. (its: winnowing and Chaffing metod)
In my program I read file into byte array. But I need byte to bits to add MAC adress to each part of file and send them in parts.
My question is:
Is there any posibility to operate on bits in Java, or if not how would you solve this problem?
Comment: 8 bits is a single byte. You're really going to send your file *one byte at a time*? Are you inventing your own encryption scheme here? That's almost *always* a bad idea.
Comment: The same basic bit shifting options as are available in C and C++ are available in Java. What bit twiddling operations are you looking for?
Comment: The [`Chaffing and Winnowing`](http://people.csail.mit.edu/rivest/chaffing-980701.txt) method looks interesting. But I'd say it was invented just to prove that encryption is not required for confidentiality, not as a serious mechanism to securely transmit data. http://www.wired.com/techbiz/media/news/1998/03/11127
Answer: Why dont you just use SSL or TLS? Or any other built in security protocol. It seems weird to re-invent the wheel here.
Often, proprietary encryption systems are less secure than well known ones, because they have not been subject to public scrutiny.
The fact that nobody knows about it does not make it more secure. "Security by Obscurity" is never the best practice.
Comment: Yep of course I would like, but this is my project for university:P
Answer: I really don't think your problem will be solved by converting bytes to bits, but here's how you can do it.
<code>static boolean[] byteToBits(byte b) {
  boolean[] bits = new boolean[8];
  for (int idx = 0; idx < 8; ++idx)
    bits[idx] = ((b >> idx) & 1) == 1;
  return bits;
}
</code>

Cryptography in java bytes to bits