Help deriving a probability

Question: Let's say I have 6 balls and 3 containers which are initially empty (A, B, and C).
If the 6 balls are distributed randomly across the 3 containers, what is the probability that a specific container (let's say A, though it doesn't matter which one) will end up with 2 or more balls?
More generally, what's the solution with n1 balls, n2 containers and a threshold of n3?
I took a probability course at university, but that was a while ago--can you help me derive the solution?
Comment: Do you suppose, that every single ball has the same probability to go into every container?
Comment: Yes - thank you
Comment: Are all the balls identical?
Answer: The probability, that no ball goes into the container $A$ is $(\frac{2}{3})^6$.
Now, name the balls giving them numbers as name. The probability that the #1 ball is the only, which goes into the container $A$ is $\frac{1}{3}(\frac{2}{3})^5$. It means that probability that the #1 or #2 or ... #6 ball is the only, which goes into the container $A$ is $6\cdot\frac{1}{3}(\frac{2}{3})^5$.
That is, the probability that at least two balls go into $A$ is
$$1-\left(\left(\frac{2}{3}\right)^6+6\cdot\frac{1}{3}\left(\frac{2}{3}\right)^5\right).$$
Well, I think, this is a hint for the general problem too.
Comment: So if I wanted to calculate the probability of 3 or more balls in A, the third term in parenthesis would be: (6 choose 2)*(1/3)^2*(2/3)^4, is that right?
Comment: Yes, it is. Perfectly.
Answer: It is usually best to answer a question like "$2$ or more" by finding the probability of $0$ or $1$ and then taking the complement. The probability of having 0 balls in $A$ is $\frac{2}{3}^6$ because for each ball there is a $\frac{2}{3}$ chance that it is not going into $A$ and since each ball is independent we can multiply these probabilities together $6$ times to get $P(\mbox{0 in A})=(\frac{2}{3})^6$. Maybe you can figure out how to find out $P(\mbox{1 in A})=$?
Comment: P(1 in A) would be (1/3)*(2/3)^5, so P(2 or more) would be 1 - [P(0)+P(1)-P(0)P(1)], correct?
Comment: It should just be $1-P(0)-P(1)$ since $P(1)$ and $P(0)$ are mutually exclusive.

Help deriving a probability


O que significa "@" em JSF?

Question: O que significa este @ nas páginas JSF? Ex:
<code>process="@this"
update="@form"
</code>
Answer: O @ em JSF é usado nas chamadas anotações, que servem para anotar classes, métodos e campos para que possam ser tratadas pelo compilador, ferramentas de desenvolvimento e bibliotecas. Existe explicação mais técnica pra isso, mas em simples palavras seria como se quando você rodasse o programa
ele verificasse essas anotações em tempo de compilação ou utilizasse-as por ferramentas, tais como analisadores de código, frameworks de persistência ou de testes unitários, entre outras.
Existem anotações marcadoras, anotações de valor único Ex. @Anotacao("valor"), Anotações completas, padrões como @Override da java.lang. Ex. a anotação @Deprecated é uma anotação marcadora que indica que um método está obsoleto e é colocada na assinatura do método. @SuppressWarnings desliga os alertas de uma parte do codigo da aplicação, e outras.
Comment: Eu me refiro aos "@" nas páginas xhtml, não nas classes java.
Comment: Entendi, desculpe o mal entendido. Não sei se estou 100% certo mas por ex. quando numa tag  no atributo update eu atribuir @form (update="@form''), ele atualiza a página inteira ao clicar no botão, evitando erros pois as vezes uma parte do código não é compilada e tal.. não sei se ajudou.

O que significa "@" em JSF?


How to translate entity in the views footer

Question: I am creating a multilingual site. I have views and when it was created, I added to the footer entity (node/22). Next, I created a translation of this content and now changed id (node/45). How to specify the settings views to display different node corresponding to the user's language?
Answer: With views php module you could add php in footer instead of entity. Sample untested code:
global $language;
if ( $language-> language='en'){
$n=node_load(22);
echo $n->title; //or any other field
} else ...
A more elegant way is to use a view attachment and put another view in the footer


django,python keyerror from a kwarg key that isn't there - how do i avoid this?

Question: if i have some code:
variableA = self.kwarg['maybe']

now, 'maybe' is sometimes there and sometimes not. I really don't care if it isn't there - i check if variableA is None down the line - so how do i avoid the oh-so-annoying "keyerror" that pops up when it isn't there?
I just want django to let me set a variable to None!
UPDATE: thanks all!
Answer: I never used django, but if self.kwarg is a dict, you can use the get() function, which returns None (or an optional default value) for elements not in the dictionary:
d = dict()
d.get("abc")              #-> None
d.get("abc", "default")   #-> "default"

Answer: http://docs.python.org/library/stdtypes.html#dict.setdefault

setdefault(key[, default])
  If key is in the dictionary, return its value. If not, insert key with
  a value of default and return default. default defaults to None.

Applied to your code:
variableA = self.kwarg.setdefault('maybe')
# -> variableA is now None


Content field value as background color

Question: I have a content type with 4 fields

1.featured_pic
2.company_logo
3.background_color

I'm using views for the teaser rewriting the result.

           {{ featured_pic }}

      {{ company_logo }}

However the background color is not being picked up. How can I use it as an inline style value.
or is it possible to pass the value {{ background_color }} to jquery

Comment: Can you add the HTML being printed
Comment: its prints like in order as shown above... but the style is missing or not picked up
Comment: Don't use jquery - please see my answer.
Answer: Looks like the Views text area filters style="anything" out to prevent XSS attacks. If you create a template file for your view, I believe it will work.
As pointed out by @4K4

If you put a twig variable inside of a style attribute standard
  sanitizing won't prevent . To protect against this you need to
  filter even brackets. See XSS attacks and style attributes

Therefore, you need to make sure your field is not a text field, where the user has the power to write/put whatever they want. You should use a Select list field or better yet use a color field.
Comment: If you put a twig variable inside of a style attribute standard sanitizing won't prevent ``. To protect against this you need to filter even brackets. See http://stackoverflow.com/questions/4546591/xss-attacks-and-style-attributes
Comment: ... and there are many other attacks possible, see the accepted answer in the SO link. User input inside of a style attribute is not safe at all and the answer to this question should be to choose another approach.
Comment: i tried that --- it didnt work
Comment: @TheNagaTanker looks like the views text area filters `style="anything"` out to prevent XSS attacks. If you create a template file for your view, I believe it will work. You don't have to worry about XSS attacks with Twig, since Twig auto escapes everything by default. (e.g. anything between `{{ }}`) gets automatically sanitized if no filters are used.
Comment: @4k4 I guess you could keep the same approach as long as you use a select list, which has different colours for selections, or an HTML color picker field and NOT use a text field where the user has the power to write/put whatever he/she wants.
Comment: Yes, that's more safe, but you have to trust the person who can change or translate this. The best advice is probably to use classes and CSS.
Comment: is there a way to pass the `{{ background_color }}` to jquery something like this  `$(this).css("background", "{{ background_color }}");`
Comment: @TheNagaTanker I doubt it that you can from Twig. I know you can from a module, so you could create a custom module that passes the node's background color to jQuery.
Answer: Since you have the markup written I would advise telling Views to use the "Content" rendering, and select the teaser view mode.
Your teaser view mode twig template becomes:

      {{ content.featured_pic }}

        {{ content.company_logo }}

Note that {{ content.foo }} is a renderable array for each field - which will call their respective field twig templates and render them according to the field formatter setting.
It is here where you can control the exact markup and not worry about Views escaping anything.
As for the background color, depending on the value or type of input, you may have to do one of two things.
field--field-background-color.html.twig
You might use this template suggestion to strip out all markup and just print the field value.
{% for item in items %}
  {{ item.content }}
{% endfor %}

Although you may have minor issues getting it to print what you're looking for.. I don't know if it is a raw color value or hex color. As noted, don't use a text field for this.
template_preprocess_node
Another thing you can do is preprocess a node and add a new variable to it:
/**
 * Implements hook_preprocess_paragraph().
 * @param $variables
 */
function mytheme_preprocess_paragraph(&$variables) {
  $node = $variables['elements']['#node'];
  $bundle = $node->bundle();

  if ($bundle == 'your_bundle') {
    $variables['background_color'] = $node->field_background_color->value;
  }
}

This would add background_color as a variable, and you can print it in your teaser twig template with {{ background_color }}.
Comment: now my head is spinning.... actually I have already stripped the items loop on the views template like this

`{% set size = rows | length %}`
`{% if size == 1 %}

      {{rows[0] . content }}

`

for styling purpose so I can control individual loop items and to which divs it goes to.
Comment: You left that out of the original question.
Comment: sorry .. forgot to add that

Content field value as background color


Regular Expression to extract a HTML-Tag without certain parameter (to fix a WordPress-Plugin)

Question: I need the help of some RegEx-Experts to fix a bug in a WordPress-Plugin, which is no longer maintained by the author.
Inside the plugin there is the following php-sytax to find included scripts:
'/(\\s*)(#i'

It uses a (?!..) negative assertion to look at each string part after a space. This will not exactly match HTML attributes, but is sufficient to detect the single case. You might need to add alternatives though (media=print or media='print') because preg_match is looking for raw strings, not interpreting HTML-equivalent expressions. (Using DOM however would certainly be overkill for this task.)
Comment: It should be ok with script tags, but there may be attributes with values including space characters.
Comment: @jswolf19: There might be, but it wouldn't matter for this regex since it only needs to blacklist and doesn't need to care about syntactic correctness. For example `
Comment: @mario, that's true. Of course, it brings up the question that @GeroB didn't specify: what about a script with multiple medias? e.g. media="print, screen"
Comment: And then again, what if the attribute is surrounded by no quotes like `media=print`or the odd (but i already seen) `media='print'` ?!
Comment: @jswolf19: Sounded more like it was a specific single instance he wanted to filter. (The real question is, why isn't WP configurable to omit any unneeded script areas except that admin thingy bar.)
Comment: @Tsadiq: Already mentioned that with " You might need to add alternatives though (media=print or media='print') ..."
Comment: This line does not work. I think it changes the original "surrounding" of the line with a (\\s*)( before the


Como fazer uma meta descripition dinâmica em angularjs?

Question: Como fazer para a descrição, que está em um Array no controller, seja renderizada para a <meta name="description" content="{{metadescription}}"> , que está na index.html, e possa aparecer dinamicamente nas views?
Eu uso $routeParams; quando eu coloco: title: ':pageName' o title é substituido pela rota atual, ao acessar a página. Gostaria de fazer algo parecido com a metadescription , fazendo a descrição que está dentro do Array items no controller NatureCtrl aparecer nas views.
Controller
angular.module('tareasApp')
  .controller('NatureCtrl', function ($scope, $routeParams, $sce, $location, $anchorScroll) {

    $scope.pageName = $routeParams.pageName;

$scope.items =[
 {
      href:'/relaxing-sounds-waves',
      img:'waves.jpg',
      descricao:'Those Relaxing Sounds of Waves'
 },
 {
      href:'/relaxing-ocean-sounds',
      img:'ocean.jpg',
      descricao:'Nature Sounds Relaxing Ocean Sounds'
 }
];
 });

app.js
    var myApp = angular.module('tareasApp')
      myApp.config(function ($routeProvider, $locationProvider) {
        $locationProvider.html5Mode(true);
        $routeProvider
          .when('/:pageName', {
                    templateUrl: 'views/wizard.html',
                    title: ':pageName',
                    metadescription: 'Aqui precisa ir algo que faça a ligação entre a descricao, que está no controller NatureCtrl, a metadescription que está na index.html e seja dinamicamente inserido nas views',
                    controller: 'NatureCtrl'
                })
                .otherwise({
                  redirectTo: '/'
                });
            });

// Dessa forma consigo obter os títulos das páginas baseado na route e routeParams. Como configurar a $rootScope.metadescription para obter a descrição referente a cada páginas?
myApp.run(['$location', '$rootScope', '$routeParams', function($location, $rootScope, $routeParams) {
   $rootScope.$on('$routeChangeSuccess', function (event, current) {
   var title = current.$$route.title;
if (title && $routeParams){
    for(var PageName in $routeParams) {
        title = title.replace(new RegExp(':' + PageName, 'g'), $routeParams[PageName]);
    }
}
$rootScope.title = title;
$rootScope.metadescription = current.$$route.metadescription;
     });
 }]);

Página index.html
<!DOCTYPE html>

<meta charset="utf-8">
<title ng-bind="title"></title>
<meta name="description" content="{{metadescription}}">
<base href="/">
<meta name="fragment" content="!">

   Conteúdo vai aqui.....

Comment: Acredito que você teria que mudar a declaração do seu controller junto à tag `html` para fazer o bind do `metadescription`. Chegou a tentar isso?
Comment: Tentei com $scope.$parent.items só que uso outros ng-repeat na index e está dando conflito.
Comment: Qual sua intenção com isso? Motores de busca não executam Javascript, logo não verão essa description dinâmica que quer fazer.
Comment: Após indexar as páginas e enviar o sitemap no [google para desenvolvedores](https://www.google.com/webmasters/tools) o `title` e `description` das páginas únicas estão aparecendo nas pesquisas do Google (Páginas únicas são as principais do menu; nessas eu não uso `$routeParams`) essa pergunta que fiz se refere a fazer uma configuração para adaptar as páginas dos artigos, que usam `$routeParams`, a dinamicamente mostrar as `descriptions` de cada página, ao acessá-la. Os titles das páginas dos artigos, que uso `$routeParams`, já aparecem, gostaria de adaptar o `myApp.run` para as `descriptions`.
Comment: @DiogoDoreto na verdade, o GoogleBot executa conteúdo javascript antes do parse: http://www.rimmkaufman.com/blog/googlebot-crawling-javascript-site-ready/03062014/
Answer: Você pode utilizar o módulo Angular-Update-Meta.
Com ele, é só você chamar em cada página a tag <update-meta name="description" content="A descrição da nova página aqui"></update-meta>.
Além de que com este módulo, você também consegue atualizar dinamicamente o título, entre outras meta-tags.
Answer:
<title ng-bind="metaservice.metaTitle()">Test</title>
<meta name="description" content="{{ metaservice.metaDescription() }}" />
<meta name="keywords" content="{{ metaservice.metaKeywords() }}" />


AngularJS: Header tag breaks ngSwitch

Question: When I use
 tags inside the ngSwitch in my html, the entire thing breaks.
Error: [$compile:ctreq] Controller 'ngSwitch', required by directive 'ngSwitchWhen', can't be found!
If i replace the
 tag with a  tag for example then it works.
You can try out the example here: http://jsfiddle.net/Lb8aatyz/1/
Html #1

Account type:

    {{ type }}

Html #2

    Account type:

    {{ type }}

Comment: It seems like all the block level tags beside headers break ngSwitch(p and div for example).
Answer: It is because the h3, or div inside a p is invalid in any HTML standard. In this case, if you use inspect elements in the browser, you will find the h3 closes p automatically, which makes ngSwitch breaks.
More details here: https://stackoverflow.com/a/4291608/1867608
Answer: The solution is here:

Account Type:

        {{ type }}

var myApp = angular.module('myApp', []);

myApp.config(function($controllerProvider) {
    $controllerProvider.allowGlobals();
});

myApp.controller('MyCtrl', function($scope) {
    $scope.type = "email";
});

You can not use block element inside inline tag and there is no need to use :: before type in the ng-if and you can also use ng- instead of data-ng-
Answer: It seems like replacing the p tag with div resolves the problem but unfortunately I cannot explain this..
Answer: You can not use a block element (h3 tag) inside an inline tag (span).
See this: h1 and the span
Comment: Hey, you are right about the tags, but unfortunately this doesn't seem to be the cause of the problem in this case. Even if I take out the (span) tag or switch them around (put span inside h3) it still has the same issue.

AngularJS: Header tag breaks ngSwitch


Chance of me beating my friend in trivia

Question: This is probably a fairly easy question, but I wasn't able to come up with a concrete answer.  Let's pretend my friend and I are playing a trivia game.  The rules of the game are  each player is asked trivia questions until they answer one incorrectly at which point the other player gets the same opportunity.  At any point when 1 player has answered 20 questions (20 questions total they do not have to be 20 in a row), that player is declared the winner.  Now I answer trivia questions correctly about 70% of the time, but my friend is much smarter and answers them correctly about 85% of the time.  How often will I win this trivia game?
The only avenue I've approached so far is thinking well the chance of me getting all 20 questions in a row is (.7)^20 which is .080%~ and his chance is (.85)^20 which is 3.876%~ which means he is 48x more likely to answer them all, which games him like a 98% chance of being the winner if the game had ended in 1 round.  But I'm not sure if this stat would extend to say that is his chance of winning in the more likely situations where we miss a few questions.  Can anyone help if I'm on the right track, or how to correctly approach this (it's not homework, I'm actually curious what my odds of beating my friend are =P).
Comment: Who goes first (it matters!)? Must you answer 20 in a row each attempt, or do you only have to get to 20 (e.g. if you answer 17 correct before a wrong answer then your opponent answers 12 correct and then one wrong, play passes back to you -- do you now need 20 or 3)? Can you clarify what you mean by "*situations where we miss a few questions*"?
Comment: Ah. It doesn't work the same when the play can extend over multiple rounds; that should improve the chances of the better player still further.
Comment: We'll say I go first, to give me a better chance.  However I guess ideally I would like the stats of him winning when he goes first avg'ed with the stats of me going first, assuming it's half and half
Comment: I wrote *"situations where we miss a few questions"* meaning I *think* I correctly calculated the odds of each player winning on their first round, but I've ignored all the cases of the game where neither player gets all 20 on the first round, I wasn't sure if that statistic correctly models the game by ignoring those cases
Comment: I assumed that, but wasn't sure how to approach the problem
Answer: This question generalizes the famous Problem of Points whose consideration by Blaise Pascal and Pierre Fermat in the summer of 1654 is generally credited as the beginning of probability theory.  The Problem of Points itself has been traced back to problems of insurance raised under 13th century (CE) Islamic contract law.  It concerns the situation where each play has equal chances of $0.5$ to win.
Recursion is the answer--but it requires a nice trick to work.  With you to start, your chances are about $12.4\%$, but if you go second they drop to $7.6\%$.  An analysis and working code follow.  The analysis is similar to that proposed by Fermat.

Fix $p=0.7$ and $q=0.85$.  Let $f(m,n)$ be the chance you will win the game when you need $m$ questions to win, your opponent needs $n$, and it's your turn.  Similarly, let $g(n,m)$ (notice the reversal of arguments!) be the chance your opponent will win when she needs $n$ questions to win, you need $m$, and it is her turn.
Obviously $f(0,n) = g(0,m) = 1$ whenever $n\gt 0$ and $m\gt 0$.
On your turn to play, either

With probability $p$ you give a correct answer.  It is still your turn and your chances of winning have become $f(m-1,n)$.
With probability $1-p$ your answer is wrong.  It is now your opponent's turn.  Her chances of winning are $g(n,m)$, so your chances of winning are $1-g(n,m)$.

Therefore
$$f(m,n) = p f(m-1,n) + (1-p)(1 - g(n,m)).$$
There is a comparable relation for $g$,
$$g(n,m) = q g(n-1,m) + (1-q)(1 - f(m,n)).$$
Unfortunately, these relations do not suffice for a recursive solution.  The problem is that the $g(n,m)$ at the end will be expressed in terms of $g(n-1,m)$ and $f(m,n)$--but that brings us right back where we were before.
The solution is to replace $g(n,m)$ in the preceding equation with its equivalent:
$$\eqalign{
f(m,n) &= p f(m-1,n) + (1-p)(1 - \color{blue}{g(n,m)}) \\
&= p f(m-1,n) + (1-p)(1 - (\color{blue}{q g(n-1,m) + (1-q)(1 - f(m,n))})) .
}$$
Isolating $f(m,n)$ yields
$$(1 - (1-p)(1-q))f(m,n) = p f(m-1,n) + q(1-p)\left(1 - g(n-1,m)\right).$$
Similarly
$$(1 - (1-p)(1-q))g(n,m) = q g(n-1,m) + p(1-q)\left(1 - f(m-1,n)\right).$$
Each lets us solve for $f$ or $g$ in terms of values of the other where $m+n$ has decreased by $1$.  This will assuredly terminate with one of $m$ or $n$ equal to $0$ within $m+n-1$ moves.  The algorithm, implemented as a dynamic program, requires $O(mn)$ time and space, making it practicable for $mn \lt 10^6$, more or less (where it will start taking around a minute in R or Mathematica, for instance).
With $m=n=20$, $p=0.7$, and $q=0.85$, we easily find
$$f(20,20) \approx 0.1238327668,\ g(20,20) \approx 0.9238111399.$$

The following is working R code.
f <- function(a, b, p, q, F, G) {
  if (missing(F)) F <- matrix(NA, a+1, b+1)
  if (missing(G)) G <- matrix(NA, b+1, a+1)
  F[1, ] <- G[1, ] <- 1

  d <- 1 - (1-p)*(1-q)
  pp <- p / d; pq <- (1-p)*q / d
  qq <- q / d; qp <- (1-q)*p / d

  f <- function(m, n) {
    x <- F[m+1, n+1]
    if (is.na(x)) F[m+1, n+1] <<- x <- pp * f(m-1, n) + pq * (1 - g(n-1, m))
    return (x)
  }
  g <- function(m, n) {
    x <- G[m+1, n+1]
    if (is.na(x)) G[m+1, n+1] <<- x <- qq * g(m-1, n) + qp * (1 - f(n-1, m))
    return (x)
  }
  return (list(Value=f(a, b), F=F, G=G, a=a, b=b))
}

m <- n <- 20
p <- 0.70; q <- 0.85
x <- f(m, n, p, q)
y <- f(n, m, q, p, x$G, x$F) # Don't recalculate the stored arrays

cat("Your chances of winning (if you start) are", 100*x$Value, "%\n")
    cat("If you do not start they are", 100*(1 - y$Value), "%\n")

Comment: This is why I love stackexchange, thank you very much for the very detailed / informative answer!


Simple random walk on infinite tree (recurrence / transience)

Question: Short Version:
I'm reading Probability on Trees and Networks and I am currently struggling with Exercise 3.4 (page number 80 / page 97 in the PDF) which asks "For simple random walk on $T$ to be transient, is it necessary that $\operatorname{br} T > 1$?". The hint says to consider spherically symmetric trees. Of course, an infinite spherically symmetric tree $T$ with branching number $\operatorname{br} T = 1$ would be the tree where every node has exactly one child ($=$ a root with an infinite line of nodes attached). The simple random walk on this graph is recurrent, so $\operatorname{br} T \geq 1 \nRightarrow \textrm{transient}$. Hence, we need $\operatorname{br} T > 1$ to infer transience.
My question is about the other direction: does transience imply $\operatorname{br} T > 1$? Or is there an infinite tree with $\operatorname{br} T = 1$ which has a transient simple random walk?
Another way to phrase this question is: does it hold that $$\operatorname{br} T = 1 \iff \textrm{simple random walk on } T \textrm{ is recurrent}$$
(if this holds, then transience would imply $\operatorname{br} T > 1$; the direction $\impliedby$ is clear since $\operatorname{br} T > 1 \implies \textrm{transient}$)
In summary, I'm looking for either of these two:

either an example of an infinite tree $T$ with $\operatorname{br} T = 1$ and a transient simple random walk
or a proof that $\operatorname{br} T = 1$ implies recurrence

Long Version:
Let $T$ be a locally finite infinite rooted tree (infinitely many nodes, but every node has only finitely many neighbors). The branching number $\operatorname{br} T$ is not completely straightforward to define, but it measures something like the average number of children of a node. In the book mentioned above, there is a good definition in Section 1.2 (page number 2 / page 19 in the PDF). Consider a simple random walk (taking every edge with equal probability) starting at the root.
The random walk is transient if the probability of never returning to the root is positive, and recurrent otherwise. The branching number $\operatorname{br} T$ is closely connected to recurrence and transience, see Section 1.4, Theorem 1.7 in the book (page number 7, page 24 in the PDF). This theorem also implies that $\operatorname{br} T > 1 \implies \textrm{transient}$ for simple random walks. The case $\operatorname{br} T = 1$ for simple random walks is not covered by the theorem, however. My question above is exactly about that case.
In this question, 1. bullet point, almost the same question was asked. The answer, however, is not correct in my opinion. A simple random walk on the modified binary tree given in the answer is recurrent, and not transient, as claimed in the answer (I'm quite confident that this is correct, but feel free to leave a comment if you think it is transient). There was only this one reply to that question, so I'm still looking for a correct answer.
Comment: I think you misunderstood the example given in the other answer. They are adding a bunch of leaves (or one ended rays if you don't want leaves) to bring the average down, but random walks can't be recurrent if the original graph wasn't recurrent.
Comment: Could you explain why you don't think the example works in your question?
Comment: Also do you agree that the example has branching number 1? (I have not looked at the formal definitions but if your "intuition definition" is accurate that should be the case)
Comment: Yes, the branching number of the example is $1$. However, the simple random walk on it is recurrent. To see that, consider the correct example I posted as answer below. Instead of adding $n$ nodes in a row, more than $2^n$ nodes would be added (if I understand correctly). The very last formula will then not give a finite sum anymore (because $n$ has to be replaced with $2^n$). However, the correct example is of course almost the same.
Comment: Possibly, I'm not quite sure. The infinite trees which are considered in the book do not have leaves ("For the purposes of this chapter, we do not allow the possibility of leaves, that is, vertices without children", page 2, Section 1.2). I therefore assumed that he meant adding paths with nodes which have only one child. However, now that you've pointed out the other interpretation, I guess it's much more likely that this was the intended meaning... I just didn't see it. (even though the phrase "adding generations" sounds wrong to me in this context)
Comment: To be honest I am not sure if I was interpretting the answer right, and on second thought I don't think that gives branching number 1 so you probably interpreted their answer as intended.
Answer: Counterexample to $\operatorname{br} T = 1 \iff T \textrm{ recurrent}$:
This counterexample uses the following notation: $T$ is a locally finite infinite tree with root $o$, i.e.
the number of vertices is infinite but the degree of every node is finite. All considered random
walks are simple random walks starting at the root, i.e. random walks which take each edge with
equal probability. The random walk is recurrent if it returns to the root with probability
$1$ (and hence returns to the root infinitely often almost surely), and transient if it
only returns to the root with probability $< 1$, i.e. the probability of never returning is positive.
The branching number $\operatorname{br} T$ of a tree $T$ is defined as in 1, page 80 / Equation 3.4.
A spherically symmetric tree is a tree such that every node at distance $n$ from the root
has the same number of children. By 1, page 4 / Exercise 1.2, it holds that
$\operatorname{br} T = \operatorname{gr} T$ (if the latter exists) for every spherically symmetric tree where $\operatorname{gr} T$ is the
growth rate given by $\operatorname{gr} T := \lim_{n\to\infty} \left|T_n\right|^{\frac{1}{n}}$ with $T_n$ being the set
of vertices at distance $n$ from the root.
In the following, random walk will be used for simple random walk. As it depends entirely on the
tree $T$ whether the simple random walk is recurrent or transient, the formulation $T$ is recurrent or
transient will be used, meaning that the simple random walk on $T$ starting at the root is
recurrent or transient.
It holds that $\operatorname{br} T = 1 \impliedby T \textrm{ recurrent}$. See 1, Theorem 3.5.
However, $\operatorname{br} T = 1 \implies T \textrm{ recurrent}$ is wrong, as the following example shows:
Consider the infinte binary tree. Let $T_n$ as above. Then, replace every edge exiting $T_n$ with
a chain of $n$ nodes. See Figure 1: at every level $T_n$ of the original binary tree, linearly
many (exactly $n$) generations with only one child per node are added, indicated in blue.

From now on, call this tree $T$ ($T$ is on the right in Figure 1). Claim: $\operatorname{br} T = 1$
and the random walk on $T$ is transient.
Proof:
First, $\operatorname{br} T = 1$ is shown, followed by the proof of transience.

$T$ is spherically symmetric, so $\operatorname{br} T = \operatorname{gr} T = \lim_{n\to\infty} \left|T_n\right|^{\frac{1}{n}}$.
It holds that
\begin{align*}
    \left|T_n\right| = 2^k \textrm{ for } \frac{k\left(k-1\right)}{2} < n \leq \frac{k\left(k+1\right)}{2}
  \end{align*}
This can be seen easily: $2^k$ is the number of nodes on level $k$ in the original binary tree.
Adding first $1$, then $2$, then $3$, and so on nodes in between the levels, $2^k$ is now the number
of nodes for all levels between $1 + 2 + \ldots + k - 1 = \frac{k\left(k-1\right)}{2}$ (exclusive) and
$1 + 2 + \ldots + k = \frac{k\left(k+1\right)}{2}$ (inclusive), also see Figure 1.
This implies, selecting the appropriate $k$:
\begin{align*}
    \sqrt[k+1]{4} = \left(2^k\right)^{\frac{2}{k\left(k+1\right)}} \leq \left|T_n\right|^{\frac{1}{n}} < \left(2^k\right)^{\frac{2}{k\left(k-1\right)}} = \sqrt[k-1]{4}
  \end{align*}
Both sides converge to $1$ for $k \to \infty$, and as $k \to \infty$ for $n \to \infty$,
we conclude $\operatorname{gr} T = \lim_{n\to\infty} \left|T_n\right|^{\frac{1}{n}} = 1$.
To show that $T$ is transient, we use the following Theorem 11 from 2 /
Theorem 2.11 from 1 (these two theorems are the same):
the random walk on $T$ is transient if, and only if, the tree admits a finite energy source flow.
A flow is a map $f: E \to \left[0, \infty\right)$ with the set of edges $E$ (outward-oriented)
of $T$, such that the incoming flow at every node (except from the root) from its parent is the same as the sum of the outgoing flows
to its children. The energy of the flow is defined as $\sum_{e \in E} f\left(e\right)^2$.
Hence, it suffices to show the existence of such an $f$ for the considered $T$ with finite energy.
Define $f$ as follows: for the edges exiting the root, set $f\left(e\right) = \frac{1}{2}$. Then,
whenever a node has two children, split the flow equally among them. See Figure 2:
the flow $f$ is indicated in blue for selected edges.

It remains to calculate the energy of the flow. This is simple: there are exactly $2^n \cdot n$
edges with a flow of $\frac{1}{2^n}$, also see Figure 2 again. It then follows
that $\sum_{e \in E} f\left(e\right)^2 = \sum_{n = 1}^\infty 2^n \cdot n \cdot \left(\frac{1}{2^n}\right)^2$
which is convergent by the root test. In fact, $\sum_{n = 1}^\infty 2^n \cdot n \cdot \left(\frac{1}{2^n}\right)^2 = 2$.
Hence, the energy of $f$ is finite and we can conclude that $T$ is transient.


Como coverto esta conexão e código com o DB para PDO com charset utf-8?

Question:
Minha pergunta não estava clara, editei o título, parecia apenas sobre UTF-8, mas não é, é uma conversão de conexão e query para PDO
  com UTF-8

<code><?php
      //export.php
 if(isset($_POST["export"]))
 {
      $connect = mysqli_connect("localhost", "root", "", "simrede");

      header('Content-Type: text/csv; charset=utf-8');
      header('Content-Disposition: attachment; filename=Cadastro_Alunos-Simrede.csv');
      $output = fopen("php://output", "w");
      fputcsv($output, array('lastname', 'firstname', 'department', 'institution', 'username',  'email', 'city', 'course1', 'password'));
      $query = "SELECT * from cs_alunos ORDER BY institution";
      $result = mysqli_query($connect, $query);
      while($row = mysqli_fetch_assoc($result))
      {
           fputcsv($output, $row);
      }
      fclose($output);
 }
 ?>
</code>
Answer: A conexão PDO é simples, para deixar ela como utf8 é só usar o código abaixo.
<code>   <?php
      //export.php
 if(isset($_POST["export"]))
 {
    try {

        $host  = "localhost";
        $user  = "root";
        $pass  = "root";
        $dbname = "db";

        $con = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $user, $pass);

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename=Cadastro_Alunos-Simrede.csv');

        $output = fopen("php://output", "w");

        fputcsv($output, array('lastname', 'firstname', 'department', 'institution', 'username',  'email', 'city', 'course1', 'password'));

        $query = "SELECT * from cs_alunos ORDER BY institution";

        $result = $con->query($query);
        $alunos = $result->fetch(PDO::FETCH_ASSOC);

        foreach($alunos as $aluno)
        {
            fputcsv($output, $aluno["seu_campo_que_retorna_da_query"]);
        }

        fclose($output);

    }catch(PDOException $e){

        echo $e->getMessage();
    }
 }
 ?>
</code>
Comment: Além da conexão, coloque o resto do código. `prepare()` `execute()` `fetchall()` . Acho que é isso que ele quer também.
Comment: @William a conexão PDO eu sei como é, o que quero saber é como fica o código restante, pois não basta mudar só a conexão.
Comment: @MiguelSilva então não sei muito bem o que você está pretendendo fazer com esse código, mas ai está o restante dele editado na resposta. ( PS: Se você estiver querendo converter esses registro em uma planilha excel sugiro usar alguma lib  como o ***PhpSpreadsheet***.)
Comment: @William esse código exporta uma tabela do DB em formato CSV, não entendi o que colocar em `"seu_campo_que_retorna_da_query"`
Comment: O Código está funcionando bem, gostaria apenas de atualizar para uma versão atualizada da conexão e consequentemente do restante do código


trying to solve $2^x \equiv 9 \pmod{13}$

Question: I'm trying to solve
$$ 2^x \equiv 9 \pmod{13} $$
so I tried to define all numbers for $x$ which match this requirement and I came up with this equation:
$$ \sqrt{\sin(((x)-13/2-9)*\pi/13)^2} $$
now i just want numbers 2^x and i changed it to
$$ \sqrt{\sin(((2^x)-13/2-9)*\pi/13)^2} = 1 $$
this part seems to work, i come to
$${pi = pi, x = ln(-1/2*(-31*pi+13*Pi)/pi)/ln(2)}, {pi = pi, x = ln(1/2*(31*pi+13*Pi)/pi)/ln(2)}$$
and
$$ 2^(1.442695041*ln(-.5000000000*(-31.*pi+40.84070450)/pi)) = 9.00000000099 $$
the second requirement is that $x$ is an integer, I defined it by this equation
$$ \sqrt{\sin((x+1/2)*\pi)^2}=1 $$
but when I try to solve this system of equations with maple, I don't get an answer, why?
Comment: How did you come up with these equations?
Comment: i plotted them and thought it looks good
Comment: Are you familiar with modular arithmetic?
Comment: Find the minimal case that $2^d=0$ and test cases below that above zero. The solutions are the the solutions you found plus integer multiples of $d$.
Comment: Note that $2^d\equiv0\pmod{13}$ has no (integer) solutions. Do you mean $2^d\equiv1\pmod{13}$?
Comment: @Pax: There are infinitely many solutions, they are the integers of the form $8+12k$ with $k\in\mathbb{Z}$.
Comment: why not $9+13k$ ?
Comment: did nobody try to follow my thoughts?
Comment: It's not that no one tried to follow them, it's that, while they work, there are much, much simpler ways to do this. Not everything has to be a function on the real numbers.
Comment: yes but the other ways are mostly trial and error
Answer: The powers of $2$ mod $13$ are:
$$
\begin{array}{c|c}
n&0&1&2&3&4&5&6&7&8&9&10&11&12\\
\hline
2^n\text{ mod }13&1&2&4&8&3&6&12&11&9&5&10&7&1
\end{array}
$$
Note that this repeats for $n$ mod $12$. Therefore,
$$
n\equiv8\pmod{12}\implies2^n\equiv9\pmod{13}
$$

Here are plots of the functions you are using:
$\hspace{8mm}$
Both curves do seem to meet at $x=8$; however, tangents to solutions are often less stable for automated solvers. A small amount of error can keep a solution from being found. This is most likely why Maple is having trouble finding solutions. The frequecy of the green function get higher as $x$ gets larger, while the frequency of the red function stays constant. This also adds to the numerical instability.

A more stable attempt would be to use
$$
\sin((2^x-9)\pi/13)=0
$$
and
$$
\sin(x\pi/13)=0
$$

However, the frequency of the green function becomes so great at the next solution ($x=20$), that numerical solution become sensitive to small errors because of that.
Comment: The question is: What's right about them? How do you justify them?
Comment: i know the brute force way... the question was what's wrong with my equations?
Comment: you can plot them... the maximum points of the first equation are the solutions for x mod 13=9
Comment: Is there a more general theorem at use here to show that $n \equiv a \space \left( \text{mod } b \right)$ implies $2^n \equiv c \space \left( \text{mod } d \right)$?
Comment: @Ryan: Yes. If $n\equiv a\pmod{\phi(13)}$, then $2^n\equiv2^a\pmod{13}$
Comment: hm and why isn't there a solution for this system of equations? $sin((2^x-9)*Pi/13)=sin(x*Pi)$ is no problem, but the combination with $sin(x*Pi)=0$ ...
Comment: @wutzebaer: My guess is that it is because you are trying to find the intersection of three curves in $\mathbb{R}^2$. That is fraught with trouble if there is *any* error.
Answer: I used another method, using less intelligence than Mark Bennet's answer but still a little quicker than checking all the powers until the answer appears.  Checking powers of 2 modulo 13, I got 2, 4, 8, 3, 6, 12.  Since $2^6\equiv 12\equiv-1$ and $2^2=4$, it follows that $2^{6+2}\equiv4\cdot(-1)\equiv 9$ so one solution is 6+2, i.e., 8.
To get all the solutions, use the fact that powers of 2 (or of anything) repeat after 12 steps, by Fermat's little theorem.  The powers of 2 don't repeat after any proper divisor of 2 many steps (because none of the 2, 4, 8, 3, 6, 12 computed above are 1), so all the solutions are $8+12k$ for arbitrary natural numbers $k$.
Answer: Note that $2^4=16 \equiv 3 \mod 13$ so that $2^8=(2^4)^2\equiv (3)^2=9 \mod 13$
Comment: @wutzebaer I didn't know what the answer was, and I have written down how I worked it out. If I didn't spot a short cut, I could compute all the powers of $2$ modulo $13$: $2^0=1, 2, 4, 8, 3, 6, 12, 11, 9$ until I got to $9$. It is not guaranteed that there will be a solution, but since we know from Fermat that $2^{12} \equiv 1$ we know that we have a finite task - and in fact when $2^4$ and $2^6$ turn out not to be $1$ we know that $2$ is a primitive root mod 13, and there will be a solution.
Comment: this only works if i already know that the result is 8
Comment: means i just need to find an $2^x$ whichs result is an divider of the wanted result?


Migrating to the webserver - what do I have to take care for?

Question: What do I have to keep in mind? What do I have to take care for - especially if I have troubles with

file ownership
permissions

If I set up a drupal-commons version 6.25 locally on my machine at home - which is a openSuse 12.1 - everything runs nice. All goes smoothly.
especially if I want to upload files - no problem here.
But if I want to do the same - uploading pictures - on the version that I either installed directly on the webserver or ported over to the webserver I have terrible issues.
It is not possible to upload any file - I have troubles and get error messages....
regarding the temp-directory (which is complained to be missing)
regarding the permissions on site/default/files
Well some words regarding the server and the circumstances and conditions it runs with: my serveradmin works with the setgit bit
I run a linux sever that is administered by a friend of me. He prepares the chown and permissions - with the setgit-bit to on. See the issues with the server described more detailed here
on a sitenote:
Well the trouble is that i get lost the setgitbit every time when I touch the permissions with FileZilla.
That is the terrible issue! Note - at the moment I do not have a access to the server wit WinSCP - WinSCP can set the Setgit. FileZilla cannot do this at all!
The question is: what do I have to take care for if porting over Drupal. Both versions:
.a a Drupal commons version 6.25 and
.b a Drupal version 7.12
Do I have to set up a tmp directory again? Note: if I create the whole installation here on my local server then my assumption is, that all things have been done properly.
What experience do you have - what do I have to take care for?
I love to see a fruitful discussion.
Answer: I strongly recommend you look into using drush to synchronise sites.  Although it admittedly will not solve your permission woes, it will greatly ease the pain of doing this for every update you need to push.
As for permissions, there are many ways of configuring depending on your set-up and how safe you want to be. I usually just have all files belong to webserver and add my user to webservers group, but like I said many things can go wrong with permissions.
Coming back to drush rsync, I would most probably attack this by setting up 2 aliases, one for @dev and the other one for @live (or @stage). So, with those aliases you can rsync  via the simple command  drush rsync @dev @live your whole site will be transferred. Just set proper permissions the first time you do this on /files and other folders needing write access, and you should be set to go.
PS: Do look into drush sql-copy and other goodies hidden in drush.  I cannot imagine doing this manually anymore, I have used aliases for a few years now and would NOT go back the old way!
Hope that helps, good-luck!
Comment: HELLO dear steffgosselin - manymany thanks! i will take all your advices into consideration - especially the drushed ones;-)


Google Apps Script - TypeError: data.forEach is not a function

Question: I've copied another developer's code from Youtube. It extracts data from a Google Sheet and creates multiple PDFs. I understand Python better than Javascript, hence my question.
The code is as follows:
function createBulkPDFs() {
  const docFile = DriveApp.getFileById("###");
  const tempFolder = DriveApp.getFolderById("###");
  const pdfFolder = DriveApp.getFolderById("###");
  const currentSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DoE");
  const data = currentSheet.getRange(2, 1, (currentSheet.getLastRow() - 1, 4), 9);
  data.forEach(row => {
    createPDF(row[1], row[2], row[3], row[0], row[4], row[5], row[6], row[7], row[8], docFile, tempFolder, pdfFolder, row[1] + " " + row[2]);
  });
}

I've read on the other threads that row => should not be used, but this video was created in April 2020, so I thought it was up-to-date programming. I realise it doesn't show in the auto-text dropdown when I click data.
I want to iterate through each of the rows in a Google Sheet.
Comment: I think that the reason of your issue of `TypeError: data.forEach is not a function` is due to that you are trying to use the Range object as an array. `getRange` returns the Range object. In your case, please modify `const data = currentSheet.getRange(2,1,(currentSheet.getLastRow()-1,4),9);` to `const data = currentSheet.getRange(2,1,(currentSheet.getLastRow()-1,4),9).getValues();` or `).getDisplayValues();`. By the way, I'm not sure about `createPDF`. So I'm not sure whether your script works without errors after you modified above. I apologize for this.
Comment: Thanks for being creative. Neither solution worked.
Comment: I just retyped all the code. It must have been a syntax error. Thanks for anyone else who may have looked!
Comment: Thank you for replying. I apologize for the inconvenience. About `Neither solution worked.`, I have to apologize for my poor English skill. Unfortunately, I cannot understand about it. When you modified `const data = currentSheet.getRange(2,1,(currentSheet.getLastRow()-1,4),9);` to `const data = currentSheet.getRange(2,1,(currentSheet.getLastRow()-1,4),9).getValues();`, the same error of `TypeError: data.forEach is not a function` occurs. Is my understanding correct?
Answer: I believe your issue comes from the declaration of the constant data. When you say

const data = currentSheet.getRange(2,1,(currentSheet.getLastRow()-1,4),9)

As the above function only takes 4 parameters. See Sheet.getRange(row, column, numRows, numColumns)
When simplifying your data it becomes:
currentSheet.getRange(2,1,x,4,9) where "x" is currentSheet.getLastRow()-1.
To fix this you should only pass the 4 parameters that getRange expects.


Writing down chord names and understanding their function in an example

Question: I've been trying to learn more about music theory by transcribing songs. I am not bad at writing down the notes, but have a lot of trouble understanding the chords/harmony.
Below is a sketch of one such transcription. I have written down my guess at the chord names (which may have errors) but I have no idea how to understand their function in relation to one another.
Any feedback/help would be appreciated, but here are a few specific questions I would like help with.

As a classical musician, I am not familiar with chord notation. Are there any errors in my chord naming?
I used slash chord for some chords I found more complicated to analyze. Is it appropriate here and/or how would one name these chords without slash notation?
I really need help understanding the function of the chords, especially the half diminished chords. I could not find any cadence to latch onto, so I am not even sure what key this song is in.
Comment: @Max has provided you with a very good answer which I agree with (except maybe the last bar is B7sus4b9 on beat one then B7b9 on beat 3?). I see a few other chord spellings which are incorrect as well, for example, bar 8 beat 1 is F#m7 (there is no A#) and beat 3 is more like a Bsus, that bar being an unresolved ii V to I. There are others but I would suggest posting a link to the recording or at least the song title and artist and the time where this excerpt occurs.
Comment: If that's alto *sax*, the written key won't be the same as that of the piano.
Answer: While providing a full analysis would be off-topic for this site, I'll give you a few points.
Errors
In bars 2 and 6, the bass note is A, so this chord should be analyzed as Am6.
In bar 8, on beat 3 you have written C♯m7, but the bass has a B. I would analyze this as B7sus4.
Slash chords vs. altered chords
In general, I think you are writing too many slash chords and too few chord alterations. Jazz pianists often use a RH upper structure that looks like another chord, so it can seem intuitive to analyze such voicings as slash chords, but writing it as an altered chord instead can make the function more transparent. Examples:

In bar 4, I would call the chord on beat 1 a C♯7♭9♭13 (spelled enharmonically).
Bar 10: usually chords like B/C♯ and D/E can be analyzed as 7sus4, although the slash notation isn't uncommon either.
Likewise, in bar 15 E/A is just Amaj9. Notice C♯ in the melody.
Final bar: F♯dim7/B is B7♭9.

In my opinion, recognizing upper structure voicings is a valuable learning tool and may be useful when transcribing, but if I am writing charts for other musicians to read, I will favor the altered chord notation. Bassists in particular are notorious for hating slash chords, because it forces them to read the chord "backwards" as they search for their note. (A good bassist won't be tripped up by this, but it's still good to know their preferences.)
On the other hand, some musicians feel the opposite way, preferring slash chords because they can specify a certain upper structure voicing. So, it's a good idea to maintain a mental dictionary of chord "synonyms." For example, C9sus4 = Gm7/C = B♭/C.
Key of analysis
I agree with the choice of E major for this example. Bar 14 looks like a resolution point, and the song just happens to start on the IV chord, which is no problem. Notice also the occurrences of an Amaj7 Am6 sequence: IV iv iii and IV iv I are fairly common progressions.
There are several unusual things going on harmonically here, including a lot of descending-fourth bass motion (whereas descending fifths are more common). If you want to practice roman-numeral analysis, you might get more bang for your buck by working on a more linear tune like "I Thought About You."
Comment: I can't thank you enough for taking the time to write this out. I appreciate you giving so much feedback specific to this example, as well as speaking about things at a more general level. Also, your use of certain terms (chord alteration, upper structure voicing) will help me with Googling things on my own; it's hard to do self-research when I don't know the terminology for certain concepts.


Mapeamento de classes com FluentAPI e Entityframework C#

Question: Tabela Pais, Estado, Cidade;
Um país pode ter vários estados e um estado pode ter apenas 1 pais;

Estado->Pais : 1:N

Uma cidade pode ter apenas um estado e um estado pode ter várias cidades.

Cidade|Estado 1:N
Gostaria de saber como deveria montar esse relacionamento na minha classe do C#. Como as coleção de dados e a parte de relacionamento de FK, estou meio confuso como é realizado isso.

public class Pais : EntityBase
{
    public Pais()
    {
        Estados = new List<Estado>();
    }

    public override long Handle { get; set; }
    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public virtual ICollection<Estado> Estados { get; set; }
}

public class PaisMap : EntityTypeConfiguration<Pais>
{
    public PaisMap()
    {
        ToTable("Pais");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(3).IsRequired();
        HasMany(x => x.Estados);
    }
}

public class Estado : EntityBase
{
    public Estado()
    {
        Pais = new Pais();
        Cidades = new List<Cidade>();
    }

    public override long Handle { get; set; }
    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public long PaisHandle { get; set; }
    public virtual Pais Pais { get; set; }
    public virtual ICollection<Cidade> Cidades { get; set; }
}

public class EstadoMap : EntityTypeConfiguration<Estado>
{
    public EstadoMap()
    {
        ToTable("Estado");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(2).IsRequired();

        HasRequired(x => x.Pais)
            .WithMany(x => x.Estados)
            .HasForeignKey(x => x.PaisHandle);

        HasMany(x => x.Cidades);
    }
}

public class Cidade : EntityBase
{
    public Cidade()
    {
        Pais = new Pais();
        Estado = new Estado();
    }

    public override long Handle { get; set; }
    public string Descricao { get; set; }
    public string Sigla { get; set; }
    public long PaisHandle { get; set; }
    public virtual Pais Pais { get; set; }
    public long EstadoHandle { get; set; }
    public virtual Estado Estado { get; set; }
}

public class CidadeMap : EntityTypeConfiguration<Cidade>
{
    public CidadeMap()
    {
        ToTable("Cidade");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(2).IsRequired();

        HasRequired(x => x.Estado)
            .WithMany(x => x.Cidades)
            .HasForeignKey(x => x.EstadoHandle);
    }
}

Comment: Não entendi a necessidade de cidade está vinculada diretamente com o País. Pois através de um determinado estado já está vinculado ao país de toda forma.
Comment: @Cleidson_eng, tirando esse relacionamento que não ficou tão correto, gostaria de saber como faço para realizar o mapeamento, pois estou fazendo da forma que está no código e não da certo, gostaria qual a forma correta de fazer mapeamento usando o CodeFirst e FluentAPI
Comment: Veja Esse link Tem exemplo que pode lhe ajudar:
[ Parte 1](http://netcoders.com.br/mapeamento-com-entity-framework-code-first-fluent-api-parte-1/) [Parte 2](http://netcoders.com.br/mapeamento-com-entity-framework-code-first-fluent-api-parte-2/)
Answer: Olha, evite utilizar a FluentAPI para os casos mais basicos, neste caso é melhor usar DataAnnotations.:
Segue abaixo uma implementação, note que na EntityBase estou à utilizar o EntityFramework.Triggers para automatizar a atualização de alguns campos.
// Não esqueça do abstract
public abstract class EntityBase
{
    // Acredite, colocar o ID na classe base não é uma boa.
    // Como você faria com uma entidade com chave multipla
    // public Guid EntityID { get; set; }

    public Guid UsuarioCriacaoID { get; set; }
    public Guid UsuarioAtualizacaoID { get; set; }
    public DateTime DataCriacao { get; set; }
    public DateTime DataAtualizacao { get; set; }
    public bool IsDeleted { get; set; }

    [ForeignKey("UsuarioCriacaoID")]
    public virtual Pais UsuarioCriacao { get; set; }
    [ForeignKey("UsuarioAtualizacaoID")]
    public virtual Pais UsuarioAtualizacao { get; set; }

    static EntityBase()
    {
        Triggers<EntityBase>.Inserting += entry =>
        {
            var contexto = entry.Context as MyContext;
            entry.Entity.DataCriacao = DateTime.Now;
            entry.Entity.DataAtualizacao = DateTime.Now;
            entry.Entity.UsuarioCriacaoID = contexto.UsuarioID;
            entry.Entity.UsuarioAtualizacaoID = contexto.UsuarioID;
            entry.Entity.IsDeleted = false;
        };
        Triggers<EntityBase>.Updating += entry =>
        {
            var contexto = entry.Context as MyContext;
            entry.Entity.DataCriacao = DateTime.Now;
            entry.Entity.DataAtualizacao = DateTime.Now;
            entry.Entity.UsuarioCriacaoID = contexto.UsuarioID;
            entry.Entity.UsuarioAtualizacaoID = contexto.UsuarioID;
            entry.Entity.IsDeleted = false;
        };
        Triggers<EntityBase>.Deleting += entry =>
        {
            var contexto = entry.Context as Contexto;
            entry.Entity.IsDeleted = true;
            entry.Cancel = true;
        };
    }
}

[Table("Usuarios")]
public class Usuario
{
    [Key]
    public Guid UsuarioID { get; set; }

    [Required]
    [Index(IsUnique=true)]
    [MaxLength(50)]
    public string Logon { get; set; }

    [Required]
    [MaxLength(64)]
    public byte[] Senha { get; set; }

    [Required]
    [MaxLength(16)]
    public byte[] Salt { get; set; }
}

[Table("Paises")]
public class Pais : EntityBase
{
    [Key]
    public Guid PaisID { get; set; }

    [Required]
    [MaxLength(150)]
    public string Descricao { get; set; }

    [Required]
    [MaxLength(3)]
    public string Sigla { get; set; }

    public virtual ICollection<Estado> Estados { get; set; } = new List<Estado>();
}

[Table("Estados")]
public class Estado : EntityBase
{
    [Key]
    public Guid EstadoID { get; set; }
    public Guid PaisID { get; set; }

    [Required]
    [MaxLength(150)]
    public string Descricao { get; set; }
    public string Sigla { get; set; }

    [Required]
    [MaxLength(2)]
    public long PaisHandle { get; set; }

    // Utilize o Atributo ForeignKey apenas se a propriedade usada configurar o relacionamento tenha um nome diferente da Key da Entidade Referenciada.
    // [ForeignKey("PaisID")]
    public virtual Pais Pais { get; set; }

    public virtual ICollection<Cidade> Cidades { get; set; } new List<Cidade>();
}

[Table("Cidades")]
public class Cidade : EntityBase
{
    public Cidade()
    {
        Pais = new Pais();
        Estado = new Estado();
    }

    [Key]
    public Guid CidadeID { get; set; }
    public Guid EstadoID { get; set; }

    [Required]
    [MaxLength(150)]
    public string Descricao { get; set; }

    [Required]
    [MaxLength(2)]
    public string Sigla { get; set; }

    // Utilize o Atributo ForeignKey apenas se a propriedade usada configurar o relacionamento tenha um nome diferente da Key da Entidade Referenciada.
    // [ForeignKey("EstadoID")]
    public virtual Estado Estado { get; set; }
}

public class MyContext : DbContext
{
    public Guid UsuarioID { get; private set; }
    public MyContext(Guid usuarioID)
    {
        this.UsuarioID = usuarioID;
    }

    public DbSet<Usuario> Usuarios { get; set; }
    public DbSet<Pais> Paises { get; set; }
    public DbSet<Estado> Estados { get; set; }
    public DbSet<Cidade> Cidades { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Filter("IsDeleted", (EntityBase d) => d.IsDeleted, false);
        // Faça aqui os mapeamentos que não conseguir fazer por DataAnnotations, como por exemplo algo especifico para o SGBD.
    }
}

Por fim, se decidir usar Soft Delete como no exemplo acima, será interessante usar algum esquema de filtro global, como por exemplo o EntityFramework.DynamicFilters
EDIT - Sobre o Fluent API
Vamos olhar apenas o seguinte trecho de codigo.:
public class EstadoMap : EntityTypeConfiguration<Estado>
{
    public EstadoMap()
    {
        ...
        HasMany(x => x.Cidades);
    }
}

public class CidadeMap : EntityTypeConfiguration<Cidade>
{
    public CidadeMap()
    {
        ...
        HasRequired(x => x.Estado)
            .WithMany(x => x.Cidades)
            .HasForeignKey(x => x.EstadoHandle);
    }
}

ao fazer HasRequired(x => x.Estado).WithMany(x => x.Cidades).HasForeignKey(x => x.EstadoHandle) no CidadeMap você já está mapeamento os dois lados do relacionamento, então chamar HasMany(x => x.Cidades) no EstadoMap é desnecessário, apenas remova este tipo de mapeamento.
public class PaisMap : EntityTypeConfiguration<Pais>
{
    public PaisMap()
    {
        ToTable("Pais");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(3).IsRequired();
    }
}

public class EstadoMap : EntityTypeConfiguration<Estado>
{
    public EstadoMap()
    {
        ToTable("Estado");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(2).IsRequired();
        HasRequired(x => x.Pais).WithMany(x => x.Estados).HasForeignKey(x => x.PaisHandle);
    }
}

public class CidadeMap : EntityTypeConfiguration<Cidade>
{
    public CidadeMap()
    {
        ToTable("Cidade");
        HasKey(x => x.Handle);
        Property(x => x.Descricao).HasMaxLength(150).IsRequired();
        Property(x => x.Sigla).HasMaxLength(2).IsRequired();
        HasRequired(x => x.Estado).WithMany(x => x.Cidades).HasForeignKey(x => x.EstadoHandle);
    }
}

Comment: compreendi totalmente sua dica, só que essas classes peguei apenas de exemplo para mostrar aqui, tem muitas tabelas, e pelo que estudei e ouvi falar bastante, é que é importante e uma ótima pratica, deixar a Entity totalmente sem regra de negócio, ou seja, usar a fluent API para realizar isso, Estou tentando fazer aqui mais está dando erro na Migrations. Vou abrir outro tópico para ver se alguém pode me ajudar no problema. Obrigado pela Solução onde realmente era os relacionamentos das tabelas
Comment: @NicolaBogar não vi regras de negocio no modelo acima, apenas regras inerentes à Modelagem, então não estamos a ferir este principio..
Comment: Correto, mas nesse caso ai de cima que você mesmo passou, você poderia me dar um exemplo usando FluentAPI?
Comment: @NicolaBogar pronto.


Usuário com cookies do navegador desativados

Question: Tenho um sistema e utilizo cookies para guardar temporariamente uma informação, porém notei um problema com certo usuário e ao tentar resolver o problema, notei que o mesmo tinha os cookies desabilitados (não me pergunte o porquê).
Eu seto os cookies de maneira convencional pelo php
setcookie(...);

Então, essas são minhas perguntas:

Tem como eu saber se um usuário está com os cookies do navegador desabilitados?
Se sim, como devo proceder?
Comment: Não seria o caso de gravar e tentar recuperar um cookie justamente para fazer o diagnóstico e então avisar o usuário de que o site requer a habilitação dos cookies ou até bloquear o acesso ao sistema?
Comment: De certa forma sim, @LeandroAngelo
Answer: Creio que com o PHP não será possível, mas você pode tentar em javascript, algo do tipo:

Referência
Comment: De nada!.Lembre-se, o PHP é server-side. Dificilmente vai ter algo nele pra coisas que são tratadas em client-side.
Comment: É uma boa solução. Nem tinha se passado pela minha cabeça. Obrigado!
Comment: Bem lembrado hahaha


Fourier series of $f(x) = 1$ on the interval $\pi/2 < |x| < \pi$

Question: I am trying to calculate the Fourier series of $f(x) = 1$ on the interval $\pi/2 < |x| < \pi$ and $f(x) = 0$ otherwise.
$f(x) = 1$ is an even function. Therefore, $b_n = 0$.
I am troubling how to proceed with the interval due to the absolute value in this case. Any help would be grateful.
Comment: Is $f(x)=0$ outside this interval (these two intervals)?
Comment: Yess, outside the interval it's zero
Comment: If you could do this for $\pi/2 < x < \pi$ then it would be easy enough to do it for $-\pi < x < -\pi/2$ and then add the two results together.  Or if you prefer even functions then you could do it for $-\pi < x < \pi$ and for $-\pi /2 \le x \le \pi/2$ and subtract
Answer: When in doubt, plot it out. Your function looks like this:

It's $0$ in the interval $(-\pi/2,\pi/2)$ and $1$ in the intervals $(-\pi, -\pi/2)$ and $(\pi/2,\pi)$. From this we can determine
$$
\int_{-\pi}^\pi f(x)\cos(k x)dx = \int_{-\pi}^{-\pi/2}\cos(kx)dx + \int_{\pi/2}^\pi \cos(k x)dx.
$$
You can use standard integration techniques to evaluate this integral and find the Fourier coefficients. If you do it all right, you should get $a_0 = 1/2$, $a_{2n} = 0$, and $a_{2n-1} = (-1)^n 2/[(2n-1)\pi]$.
Comment: Thank you! I now see what I did wrong.
Answer: We have
$f(x)=0$ for $x \in [-\pi/2, \pi/2]$
and
$f(x)=1$  for $x \in ( -\pi,\pi) \setminus [-\pi/2, \pi/2]$
Can you proceed ?
Comment: This is what I understand. I am struggling how to visualize and put it into integral form to calculate $a_0$ and $a_n$.


Como somar propriedade de objetos em Array em um *ngFor

Question: Tenho um array passado para um *ngFor, como faço para somar os valores de uma propriedade, vlr, por exemplo.

order=[
  {"qtd": Number(1),"vlr":Number(3.50)},
  {"qtd": Number(6),"vlr":Number(4.00)},
  {"qtd": Number(2),"vlr":Number(1.20)}
];

    <ion-grid>
      <ion-row>
        <ion-col width-33 text-center>
              {{e.qtd}}
        </ion-col>
        <ion-col width-33 text-center>
          {{e.vlr}}
        </ion-col>
      </ion-row>
    </ion-grid>

Answer: Sugiro que você processe o total no controller, poderia ser assim:

var order=[
  {"qtd": Number(1),"vlr":Number(3.50)},
  {"qtd": Number(6),"vlr":Number(4.00)},
  {"qtd": Number(2),"vlr":Number(1.20)}
];
var total = order.reduce( function(a, b){
        return a + b['vlr'];
    }, 0);

console.log(total);

Usei Array#Reduce para efetuar a soma. O total você pode salvar em uma variável de escopo e exibir onde precisar.
Answer: Como você quer a soma de todos elementos, não se deve colocar dentro do ngFor que é onde você apresenta algo para cada elemento.
Se você não quiser seguir a recomendação do Lucas Costa, você pode utilizar:
{{order.reduce((acumulado,linha) => acumulado + linha.vlr, 0)}}

Por exemplo:

    <ion-grid>
      <ion-row>
        <ion-col width-33 text-center>
              {{e.qtd}}
        </ion-col>
        <ion-col width-33 text-center>
          {{e.vlr}}
        </ion-col>
      </ion-row>
    </ion-grid>

Total: {{order.reduce((acumulado,linha) => acumulado + linha.vlr, 0)}}

Porém acredito que você talvez queira o valor multiplicado pela quantidade, que fica:
{{order.reduce((acumulado,linha) => acumulado + linha.qtd * linha.vlr, 0)}}


Migrate fields to another site?

Question: I have a Drupal 8 site with a contact form that has a lot of fields. I need to duplicate these fields onto another Drupal 8 site but can't find where they are stored in the DB.
In the config table there is a row per field, but when I try to copy these across, I get this message:

Drupal\Core\Field\FieldException: Attempt to create a field my_field_name that does not exist on entity type contact_message. in Drupal\field\Entity\FieldConfig->getFieldStorageDefinition() (line 286 of core/modules/field/src/Entity/FieldConfig.php).

Does anyone know if it's possible to copy the contact form fields to another site via the Database?
Answer: Yes. One way could be:

You export your configuration. (drush cex -y, or on the interface configuration management)
You filter the configuration you need.
You import those configuration files into the other site (drush cim, or manually).

Migrate fields to another site?


If else statement not outputting correctly?

Question: I'm a beginner to Python and am struggling with a project I am working on. The program takes monthly income, fixed monthly expenses, asks for any additional expenses, and then outputs with an if else statement. My issue is in this function:
def spending(income, totals):

  finalTotal = income - totals

  if income > finalTotal:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif finalTotal > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")

It is printing:
You saved $ -805.00 this month!

When I'd like it to print:
You overspent by $ 805.00 this month!

Any feedback would be greatly appreciated!!
Here is my code:
https://replit.com/@ashleyshubin/BudgetProgram#main.py
Comment: It's unrelated to your main question (about the `if`/`elif` conditions), but your formatting is a bit weird in the `print` calls. There's no reason to split the `%.2f` into its own string just for the formatting. You could use `"You saved $%.2f this month!" % finalTotal`, or better, do something similar with `str.format` (or an f-string).
Answer: If totals is your monthly expenses, then subtracting totals from income gives you how much money you made this month. The first if statement should be
if finalTotal > 0:

The second if statement would be
if finalTotal < 0:

And you would want to use abs(finalTotal) when printing finalTotal so it does not display a negative number
Answer: Your checks are wrong. You can do the following:
def spending(income, totals):
  finalTotal = income - totals
  if income > totals:
    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:
    print("You overspent by $", "%.2f"%-finalTotal, "this month!")
  else:
    print("You broke even this month!")

Answer: This section is where it is going wrong:
finalTotal = income - totals
  if income > finalTotal:
    print("You saved $", "%.2f"%finalTotal, "this month!")

It looks like you're comparing the wrong variables in your "if" statement. your "finalTotal" variable already includes your income. Think of it like alegbra, and replace "finalTotal" with "income - totals", and your if statement now looks like:
    if income > (income - totals):

this statement will always evaluate to true, no matter what values you are using. You probably want to rewrite your if statements to compare "income > totals", rather than finalTotal.
Answer: your comparison shoud be based on finaltotal , as fianaltotal is finalTotal = income - totals, also else  never runs based on the other conditions in your code:
def spending(income, totals):
    finalTotal = income - totals
    if finalTotal > 0:
        print("You saved $", "%.2f" % finalTotal, "this month!")
    else:
        print("You overspent by $", "%.2f" % abs(finalTotal), "this month!")

Answer: you should be comparing Income with total spends.
def spending(income, totals):

  finalTotal = abs(income - totals)

  if totals < income:

    print("You saved $", "%.2f"%finalTotal, "this month!")
  elif totals > income:

    print("You overspent by $", "%.2f"%finalTotal, "this month!")

  else:

    print("You broke even this month!")


Python 3 Tkinter: Como pegar um value/string de um RadioButton dentro de uma função?

Question: Eu gostaria de pegar valor do sexo selecionado e imprimir na janela DadosSalvos, mas não funciona, nem mesmo os outros dados digitados como nome ou idade.
Eu possuo aqui uma janela principal onde irá exibir dois botões: CADASTRAR e SAIR. O botão sair ainda não possui o comando, mas o cadastrar sim, que é abrir a janela SALVADADOS (localizada no primeiro def/função do código. Nessa janela que irá abrir, há um botão CADASTRAR para que seja exibida uma outra janela, a DADOSSALVOS como já citada antes. É nessa janela que preciso que os meus dados digitados nos campos (Entry) e o sexo selecionado no RadioButton sejam salvos com o get() e exibidos como texto (Label) nessa janela DADOSSALVOS.
from tkinter import *

def entrar():
  #Janela Principal
  janela = Tk()
  janela.title("Salvadados")
  janela.geometry('400x600')
  #Textos e entrada
  Lab1 = Label(janela, text='Nome completo:')
  Lab1.pack()
  textao = Entry(janela, textvariable = var,borderwidth= 5,relief ='ridge')
  textao.pack()
  Lab2 = Label(janela, text = 'Idade:')
  Lab2.pack()
  textao2 = Entry(janela, textvariable = d,borderwidth= 5,relief ='ridge')
  textao2.pack()
  Lab3 = Label(janela, text = "Sexo:")
  Lab3.pack()
  RBTN1 = Radiobutton(janela, text = 'Feminino',variable = kw,value = 'Feminino').pack()
  RBTN2 = Radiobutton(janela, text = 'Masculino', variable = kw, value = 'Maculino').pack()
  Lab4 = Label(janela, text = "Estado:")
  Lab4.pack()
  #Comando para o botão
  def janelanova():
     k = Tk()
     k.title("DadosSalvos")
     k.geometry('100x120')
     L2 = Label(k,text='Dados salvos:',bg='Red',fg='White')
     L2.pack()
     L = Label(k,text='')
     L.pack()
     L3 = Label(k,text='')
     L3.pack()
     L4 = Label(k,text='')
     L4.pack()
     b = var.get()
     t = d.get()
     g = kw.get()
     #para imprimir também(sem usar label)
     print(b)
     print(t)
     print(g)
     L.config(text=b)
     L3.config(text= t)
     L4.config(text=g)
#JanPrincipal
janelaprincipal = Tk()
janelaprincipal.title('Menu Principal')
janelaprincipal.geometry('1010x200')
janelaprincipal['bg'] = '#C1FFC1'
mensagem1 = Label(janelaprincipal,text='Seja bem-vindo à Programação de Eventos do IFSP - Câmpus ----, cadastre-se para visualizar os eventos e suas programações completas.',font = ' -size 12',bg= 'green',fg='white')
mensagem1.place(x = 1,y= 14)
botaocadastro = Button(janelaprincipal,text= 'Cadastrar',font='-weight bold -size 16',fg='white', width = 20,activebackground='#B4EEB4',command=entrar)
botaocadastro['bg']='green'
botaocadastro.place(x = 355,y=60)
botaosair = Button(janelaprincipal,text = 'Sair',font='-weight bold -size 16',fg='white', width = 20,activebackground='#B4EEB4')
botaosair['bg']='green'
botaosair.place(x = 355,y=120)
#Variáveis
var = StringVar()
d = StringVar()
var2 = StringVar()
kw = StringVar()
mainloop()

Comment: A pergunta não ficou muito clara @Mikalayla. E a endentação não está correta. Você poderia tentar ser mais clara e corrigir isso?
Comment: Pergunta corrigida juntamente com o código.
Answer: Ola @Mikalayla, o problema é que você ao criar as novas telas utilizou Tk().
Por conceito Tk() define a sua janela principal, para outras telas é interessante utilizar Toplevel().
Não fiz grandes alterações no seu código:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""""""
from tkinter import *
from tkinter import messagebox

def entrar():
    # Toplevel() porque já existe uma janela principal (janelaprincipal = Tk())
    janela = Toplevel()
    janela.title("Salvadados")
    janela.geometry('400x600')

    Lab1 = Label(janela, text='Nome completo:')
    Lab1.pack()
    textao = Entry(janela, textvariable=var, borderwidth=5, relief='ridge')
    textao.pack()

    Lab2 = Label(janela, text='Idade:')
    Lab2.pack()
    textao2 = Entry(janela, textvariable=d, borderwidth=5, relief='ridge')
    textao2.pack()

    Lab3 = Label(janela, text="Sexo:")
    Lab3.pack()

    # kw = StringVar()
    RBTN1 = Radiobutton(janela, text='Feminino', variable=kw, value='Feminino')
    RBTN1.pack()
    RBTN2 = Radiobutton(janela, text='Masculino', variable=kw, value='Masculino')
    RBTN2.pack()

    Lab4 = Label(janela, text="Estado:")
    Lab4.pack()

    # Botão que irá chamar a nova tela ou tkinter messagebox.
    btn_salvar = Button(janela, text='Salvar dados', command=lambda: janelanova(var, d, kw))
    btn_salvar.pack()

    btn_salvar = Button(janela, text='Salvar dados (messagebox)', command=lambda: janela_confirmacao(var, d, kw))
    btn_salvar.pack(pady=10)

def janelanova(var, d, kw):
    k = Toplevel()
    k.title("Salvadados")
    k.geometry('100x120')
    L2 = Label(k, text='Dados salvos:', bg='Red', fg='White')
    L2.pack()
    L = Label(k, text=var.get())
    L.pack()
    L3 = Label(k, text=d.get())
    L3.pack()
    L4 = Label(k, text=kw.get())
    L4.pack()

def janela_confirmacao(var, d, kw):
    msg = f'Dados que serão inseridos:\nNome: {var.get()}.\nIdade: {d.get()}\nSexo: {kw.get()}'
    resposta = messagebox.askokcancel(title='Confirmar?', message=msg)
    print(resposta)
    if resposta is True:
        print('Você clicou em OK')
    else:
        print('Você clicou em CANCELAR ou fechou a janela')

def sair():
    janelaprincipal.quit()

# JanPrincipal
janelaprincipal = Tk()
janelaprincipal.title('Menu Principal')
janelaprincipal.geometry('1010x200')
janelaprincipal['bg'] = '#C1FFC1'

mensagem1 = Label(janelaprincipal,
                  text='Seja bem-vindo à Programação de Eventos do IFSP -Câmpus Jacareí,'
                       'cadastre-se para visualizar os eventos e suas programações completas.',
                  font=' -size 12', bg='green', fg='white')
mensagem1.place(x=1, y=14)

botaocadastro = Button(janelaprincipal, text='Cadastrar', font='-weight bold -size 16',
                       bg='green', fg='white', width=20, activebackground='#B4EEB4', command=entrar)
botaocadastro.place(x=355, y=60)

botaosair = Button(janelaprincipal, text='Sair', font='-weight bold -size 16',
                   bg='green', fg='white', width=20, activebackground='#B4EEB4', command=sair)
botaosair.place(x=355, y=120)

# Variáveis
var = StringVar()
d = StringVar()
var2 = StringVar()
kw = StringVar()

mainloop()

Deixei a janela que você criou para exibir os dados e adicionei um caixa de mensagem (messagebox) que realiza a mesma função com a vantagem de poder verificar qual botão foi pressionado.
Observações:

Sempre que possível tente utilizar nomes mais claros que deixem subentendido o que cada elemento realiza. Mesmo que o código fique um pouco mais verboso.
Futuramente tente dar uma olhada na documentação do Python referente ao Tkinter, pois lá tem alguns exemplos de como criar o código utilizando classes, dependendo do tamanho do seu aplicativo utilizar classes pode ternar o código mais legível e fácil de dar manutenção.

Exemplo com classes utilizando o seu código como base:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exemplo"""

import tkinter as tk
from tkinter import messagebox

class TelaCadastro(tk.Toplevel):
    """Classe TelaCadastro 2 herda de tk.Toplevel()."""

    def __init__(self, **kw):
        """Construtor."""
        super().__init__(**kw)
        # Definindo a cor de fundo da janela (tk.Toplevel).
        self['background'] = '#E57373'
        # Título da janela.
        self.title(string='Tela de cadastro')
        # Denifindo um ícone diferente para nova janela.
        # icon_png = tk.PhotoImage(file='../icons/icon.png')
        # self.iconphoto(False, icon_png)

        # Tamanho da janela.
        width = round(self.winfo_screenwidth() / 2)
        height = round(self.winfo_screenheight() / 2)
        self.geometry(newGeometry=f'{width}x{height}')
        self.minsize(width=width, height=height)

        # Inserindo um frame sobre a janela para posicionar os widgets.
        # Não é obrigatório, contudo mantém organizado o layout.
        self.container = tk.Frame(master=self)
        self.container.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)

        self.criar_widgets()

    def criar_widgets(self):
        label_nome = tk.Label(master=self.container, text='Nome completo:', anchor=tk.W)
        label_nome.pack(fill=tk.X, padx=10)
        self.entry_nome = tk.Entry(master=self.container)
        self.entry_nome.pack(fill=tk.X, padx=10, pady=(0, 10))

        label_idade = tk.Label(master=self.container, text='Idade:', anchor=tk.W)
        label_idade.pack(fill=tk.X, padx=10)
        self.entry_idade = tk.Entry(master=self.container)
        self.entry_idade.pack(fill=tk.X, padx=10, pady=(0, 10))

        label_sexo = tk.Label(master=self.container, text='Sexo:', anchor=tk.W)
        label_sexo.pack(fill=tk.X, padx=10)

        self.kw = tk.StringVar()
        RADIOBUTTON = [('Feminino', 'Feminino'), ('Masculino', 'Masculino')]
        for texto, valor in RADIOBUTTON:
            radio_button = tk.Radiobutton(master=self.container, text=texto, variable=self.kw, value=valor, anchor=tk.W)
            radio_button.pack(fill=tk.X, padx=10)
        self.kw.set('Feminino')

        label_estado = tk.Label(master=self.container, text='Estado:', anchor=tk.W)
        label_estado.pack(fill=tk.X, padx=10, pady=(10, 0))

        button_salvar = tk.Button(self.container, text='Salvar registro', command=self.salva_registro)
        button_salvar.pack(pady=10)

    def salva_registro(self):
        msg = f'Dados que serão inseridos:\nNome: {self.entry_nome.get()}.\n' \
            f'Idade: {self.entry_idade.get()}\nSexo: {self.kw.get()}'
        resposta = messagebox.askokcancel(title='Confimar dados?', message=msg)
        print(resposta)
        if resposta is True:
            print('Você clicou em OK')
            self.destroy()
        else:
            print('Você clicou em CANCELAR ou fechou a janela')

class MeuApp(tk.Frame):
    """Classe herda de tk.Frame()"""

    def __init__(self, master=None):
        """Construtor"""
        super().__init__(master=master)
        self.pack(expand=True, fill=tk.BOTH, padx=10, pady=10)
        self.criar_widgets()

    def criar_widgets(self):
        mensagem1 = tk.Label(master=self,
                             text='Seja bem-vindo à Programação de Eventos do IFSP - Câmpus Jacareí.\n'
                                  'cadastre-se para visualizar os eventos e suas programações completas.')
        mensagem1.pack(expand=True, fill=tk.BOTH)

        botaocadastro = tk.Button(master=self, text='Cadastrar', command=self.abrir_tela_cadastro)
        botaocadastro.pack(fill=tk.X)

        botaosair = tk.Button(master=self, text='Sair', command=self.sair)
        botaosair.pack(fill=tk.X, pady=10)

    @staticmethod
    def abrir_tela_cadastro():
        TelaCadastro()

    def sair(self):
        self.master.quit()

root = tk.Tk()
root.title(string='Título do aplicativo')
# icon_png = tk.PhotoImage(file='../icons/icon.png')
# root.iconphoto(False, icon_png)
width = round(number=root.winfo_screenwidth() / 2)
height = round(number=root.winfo_screenheight() / 2)
root.geometry(newGeometry=f'{width}x{height}')
root.minsize(width=width, height=height)
app = MeuApp(master=root)
app.mainloop()

Vale notar que não existe um código que esteja certo ou errado, são apenas formas/paradigmas diferentes para se resolver o mesmo problema.
Comment: O código deu erro, disse que TopLevel não foi definido
Comment: Fiz um teste com ambos os código, inclusive copiando e colando o código da resposta e a execução foi normal. Verifique se você não está com algum erro na edentação do código.


SpringBoot 3 using semicolon in JPA query

Question: I have a JPA query in Spring Boot 3 that search for a text with semicolon. The query is like this:
Query(value=".... LIKE CONCAT(?, '%;') ...")

It ends up generating the following query
LIKE CONCAT(?, '% limit ?;')

I tried different approaches to use ESCAPE the key word or adding \\ but all didn't success. The same code was working earlier in Spring Boot 2.7
I don't know what problem there are after the upgrade!
Any ideas?
Update
This normal query works fine with the List
@Query(value = "SELECT u.* FROM  user u WHERE u.userId LIKE CONCAT(?1, '%;') OR u.userId IN ?2)", nativeQuery = true)
List<UserEntity> search(String search, List<String> userIds);

If we replace the List with pagination, then it fails
@Query(value = "SELECT u.* FROM  user u WHERE u.userId LIKE CONCAT(?1, '%;') OR u.userId IN ?2)", nativeQuery = true)
Page<UserEntity> search(String search, List<String> userIds, Pageable pageable);

Comment: Could you post all your query? Have you insert nativeQuery = true?
Comment: @fforfabio I have added the simplified query without joins
Comment: I have tried a query with concat and semicolon, with Spring Boot 3.1.4, and it works fine as I expected. I have escape the ; with this instruction `LIKE CONCAT(?1, '%' , ';')`.    So, I have two questions: 1) Can you explain exactly your problem? Is the query retrieving the wrong data or something else?  2) Which version of Spring Boot have you have installed?
Comment: Thanks @fforfabio for your trail, yes it works for normal quires, I got to know the real issue now, it's related to the pagination, as per my understanding for some reasons the pagable object tries to look for the semicolon to add the limit before it directly, that's why I see the limit before the semicolon LIKE CONCAT(?1, ' limit ?;') and breaks the code. I think it's a bug inside Spring data. the point I'm still confused why it worked earlier in older versions
Answer: To resolve the semicolon issue with pagination, I did the below work-around by replacing pagination using Page with List and create my own custom pagination logic with additional counter query
@Query(value = "SELECT u.* FROM  user u WHERE u.userId LIKE CONCAT(?1, ';%') OR u.userId IN ?2) limit ?3, ?4", nativeQuery = true)
List<UserEntity> search(String search, List<String> userIds, int page, int size);

@Query(value = "SELECT count(u.userId) FROM  user u WHERE u.userId LIKE CONCAT(?1, ';%') OR u.userId IN ?2)", nativeQuery = true)
Integer searchCount(String search, List<String> userIds);

Integer total = userDao.searchCount(search , userIds);
List list = userDao.search(search, userIds , page * size, size);
Page<UserEntity> = new PageImpl(list, PageRequest.of(page, size), total);


Normalize response variable?

Question: I understand one should normalize the features in supervised learning.
Does it ever make sense to normalize the response variable?
Answer: The purpose of normalization is to prevent a subset of features from dominating the behavior of the model.  So normalizing the output variable is not critical.
Perhaps if you're implementing the model using low-precision or fixed point math. For example, in an MCU for an embedded system.  On a server, desktop or laptop using floats or doubles it's not critical to normalize the output.

Normalize response variable?


Problema em form em modal bootstrap

Question: Existe alguma restrição para formulário em modal do bootstrap? Quando coloco o formulário dentro do modal, não recebo o alert do Ajax, porém, se tiro o formulário de dentro da modal, os dados passam e recebo o alert.
Quando coloco o formulário dentro do modal também recebo no console: Undefined index...
Segue o código.
Modal

        <button type="button" class="close" data-dismiss="modal">×</button>
        <form method="post" id="cadastrarReserva" autocomplete="off">
            Código:
            <input type="text" id="idCliente" name="idCliente" >
            Cliente:*
            <input type="text" name="cliente" id="clienteReserva" autofocus required >
            Data:*
            <input type="text" name="data" value="<?php echo $dataFiltro; ?>" class="dataFiltro" required/>
            Hora:*
            <select name="hora" required>
                <option value="">Selecione...</option>
                <option value="11:30:00">11:30h</option>
                <option value="12:00:00">12:00h</option>
                <option value="14:00:00">14:00h</option>
                <option value="15:00:00">15:00h</option>
                <option value="15:30:00">15:30h</option>
                <option value="16:00:00">16:00h</option>
                <option value="16:30:00">16:30h</option>
                <option value="17:00:00">17:00h</option>
                <option value="17:30:00">17:30h</option>
                <option value="18:00:00">18:00h</option>
            </select>
            Número de Pessoas:*
            <input type="text" name="nmPessoas" required/>
            Tipo Café:
            <select name="tipoCafe">
                <option value="">Selecione...</option>
                <option value="Simples">Simples</option>
                <option value="Completo">Completo</option>
                <option value="Almoço">Almoço</option>
            </select>
            Tipo Reserva:*
            <input type="radio" name="tipo" value="Normal" required/> Normal
            <input type="radio" name="tipo" value="Grupo" required/> Grupo
            Ouve Pagamento Adiantado?*
            <input type="radio" name="pagamentoAdiantado" value="Não" required/> Não
            <input type="radio" name="pagamentoAdiantado" value="Sim" required/> Sim
            Observação:
            <textarea maxlength="96" name="observacao"></textarea>

            <input type="hidden" name="status" value="Reserva" />
            <input type="submit" name="cadastrarReserva" value="Cadastrar" />
            <input type="reset" value="Limpar"/>
        </form>

ajax.js
jQuery(document).ready(function(){
jQuery('#cadastrarReserva').submit(function(){
    var dados = jQuery( this ).serialize();

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: "crud/insere.php",
        data: dados,
        success: function(data) {

            alert('alerta');
        }
    });
    return false;
});
});

insere.php
<?php
date_default_timezone_set('America/Sao_Paulo');
include('../../resources/conexao/conexao.php');

$cliente = $_POST ['idCliente'];
$data = $_POST['data'];
$data = implode("-",array_reverse(explode("/", $data)));
$hora = $_POST['hora'];
$nmPessoas = $_POST['nmPessoas'];
$checkboxTipoCafe = $_POST['tipoCafe'];
$checkboxTipoReserva = $_POST['tipo'];
$pagamentoAdiantado = $_POST['pagamentoAdiantado'];
$observacao = $_POST['observacao'];
$status = $_POST['status'];
$dataCadastro = date('Y-m-d  H:i:s');

if(empty($hora)){
    $insert = "INSERT INTO Reserva(idCliente, data, numeroPessoas, tipoCafe, tipo, pagamentoAdiantado, observacao, status, dataCadastro, cancelado)
               VALUES ('$cliente', '$data', '$nmPessoas','$checkboxTipoCafe','$checkboxTipoReserva', '$pagamentoAdiantado', '$observacao', '$status', '$dataCadastro', 'N')";
} else {
    $insert = "INSERT INTO Reserva(idCliente, data, hora, numeroPessoas, tipoCafe, tipo, pagamentoAdiantado, observacao, status, dataCadastro, cancelado)
               VALUES ('$cliente', '$data', '$hora', '$nmPessoas','$checkboxTipoCafe','$checkboxTipoReserva', '$pagamentoAdiantado', '$observacao', '$status', '$dataCadastro', 'N')";
}
$conexao = conexao();
$PDO = $conexao -> prepare($insert);
$PDO -> execute();

$retorno = array('id' => "teste");
    echo json_encode($retorno);*/

Comment: Você quer que quando abra  o modal execute o ajax? ou dentro da modal com o form execute o ajax ?
Comment: Dentro do modal, vou preencher os campos e dar um submit para inserir no banco.
Comment: Ola, Pode dizer por completo o erro do console? Qual é a linha? O que tem a linha?
Comment: {main}() D:\Ferramentas\wamp\www\agenda-reserva-3\agenda\crud\insere.php:0

Notice:  Undefined index: idCliente in D:\Ferramentas\wamp\www\agenda-reserva-3\agenda\crud\insere.php on line 5

Observação: Apenas com o formulário está dentro do modal.
Comment: O erro consiste na pagina insere.php porque o idCliente não tem valor na linha 5. pode indicar o codigo pelo menos do inicio da pagina, para ser possivel analisar melhor.
Comment: Código do insere.php ou o principal que contém o modal?
Comment: insere.php para saber a causa do erro
Comment: Desculpe não vi que já esta na pergunta
Comment: O que aparece se no insere.php logo ao inicio colocar print_r($_POST)
Answer: Você esta utilizando dois id's iguais, id é único! em modal e em form esta cadastrarReserva, depois você tenta dar submit  com eles, se utilizar o submit com o "form"  ou colocar outro id vai funcionar.
Veja um exemplo no jsfiddle
Comment: Cara, boa observação, não tinha percebido este erro, desta maneira não iria funcionar mesmo.
Obrigado pela ajuda! Abraço!

Problema em form em modal bootstrap


What is the proper process to customize htaccess files?

Question: We have custom redirect links that use the RedirectMatch rules that redirect based on a root path. We'd rather handle these at the web server level rather than using the Redirect module (if it can even do match based rules), so we put these rules in the .htaccess file, e.g.:
RedirectMatch 301 ^/computing/hpc[/]?(.*) https://hpc.our.domain/$1

Since the .htaccess file is updated with a composer install because of the scaffolding, what is the best process for adding our rules to the file? I'm not looking to prevent the scaffolding from updating the .htaccess file, but I may need to modify our patch from time to time so that it is applied to the newest version.
How do you go about editing and updating the patch when something needs to get added or removed?
Comment: Does this answer your question? [Composer keeps overwriting .htaccess (and other files) every time I do anything](https://drupal.stackexchange.com/questions/290989/composer-keeps-overwriting-htaccess-and-other-files-every-time-i-do-anything)
Comment: Not really. I have edited my question so that it hopefully more clear.
Answer: Depending on level of customization, there are two strategies you could employ.

Patch drupal/core with a modified htaccess file including your customization.
Override the htaccess file via scaffolding.

If you choose the first option here is a really easy way to do it.

Checkout the version of Drupal you are using to a folder.
Adjust the htaccess file in assets/scaffold.
Run git diff > htaccess.patch.
Go back to your project and create a patches folder, place the new file inside.
Add the following to composer.json extra section (make sure you have installed cweagans/composer-patches):

"patches": {
  "drupal/core": {
    "Add redirects": "patches/htaccess.patch"
  }
}

If you choose option two:

Create an assets/scaffold folder(s) in your project.
Copy the htaccess file inside of it.
Make your adjustments to the file.
Add the following to composer.json extra section:

"drupal-scaffold": {
  "locations": {
    "web-root": "web/"
  },
  "file-mapping": {
    "[web-root]/.htaccess": "assets/scaffold/.htaccess"
  }
}

Answer: Ryan Hartman's answer was great. We ended up taking a slightly different route. As with Drupal, there are often many ways of doing things.
We added this section to our composer.json file:
"scripts": {
        "post-drupal-scaffold-cmd": [
            "cd docroot && patch -p1 <../patches/htaccess.patch"
        ]
    }

Our .htaccess file is still part of our git repo. Each time we need to edit the rules, we make all the necessary changes to the .htaccess file and then we run a bash script (actually a Docksal custom fin command) that generates the patch file. The script looks like this:
mkdir temphtaccess
cd temphtaccess
git init
cp "${DOCROOT_PATH}/core/assets/scaffold/files/htaccess" "${PROJECT_ROOT}/temphtaccess/.htaccess"
git add .
git commit -m 'Scaffold htaccess commit'
cp "${DOCROOT_PATH}/.htaccess" "${PROJECT_ROOT}/temphtaccess/.htaccess"
git diff > ../patches/htaccess.patch
cd ${PROJECT_ROOT} && rm -rf temphtaccess


How can i sync images from local windows forms application to web forms application

Question: I have a windows forms application..How can i am syncing the databases from local database to online database but how can i sync the images
Comment: Welcome to Stack Overflow. Please read [FAQ], [ask] and [help] as a start..
Answer: Please post the correct scenario so that anybody can help
https://msdn.microsoft.com/en-us/library/ee819079%28v=sql.100%29.aspx
Here is some syncing code using wcf ..Hope this helps..


Properly export/import parts of a JS project

Question: I'm building an npm package (ES6 + Babel) for the first time and I'm having trouble connecting it all together so it can be imported by the end user.
My build (output) folder structure is the same as src:
build
    - index.js
    - BaseClass.js
    sublclasses
        - SubClassA.js
        - SubClassB.js

SubClassA and SubClassB import and extend BaseClass and are both exported using the module.exports. The entry point, index.js, has only two lines:
import SubClassA from './subclasses/SubClassA'
import SubClassB from './subclasses/SubClassB'

package.json has the main field set to ./build/index.js.
When installing the project (or npm linking) into a test project, I write:
import SubClassA, SubClassB from 'my-package'

Import works, but imported classes are undefined. I've tried a couple more ways to do it, but it didn't work.
How should I do it properly?
EDIT: after changing index.js to:
import SubClassA from './subclasses/SubClassA'
import SubClassB from './subclasses/SubClassB'

module.exports = SubClassA
module.exports = SubClassB

it kind of works. 'Kind of' means that if I import both classes in the test project like so:
import SubClassA, SubClassB from 'my-package'

and then do:
let sca = new SubClassA()

it turns out to be SubClassB. If I ommit SubClassB from import, it works normally.
EDIT 2 - SOLUTION:
Per instructions in the comments below, I've changed the index.js file like so:
export { default as SubClassA } from './subclasses/SubClassA'
export { default as SubClassB } from './subclasses/SubClassB'

and I imported it in the test project like so:
import { SubClassA, SubClassB } from 'my-project' and it worked.

Comment: are you exporting SubClassA and B from main file?
Comment: you should then use it with `import {SubClassA, SubClassB} from 'my-package'`
Comment: @maioman you're right, it's not enough to just import them in the main file, like I did. exported them, rebuilt and it worked, but with a new twist this time. I will update my anwer in a minute.
Comment: yup, works! thanks
Answer: The problem is you're not exporting anything from your main file,
using es6 import/export syntax you can directly export it with:
export {default as SubclassA} from './subclasses/SubClassA'
export {default as SubclassB} from './subclasses/SubClassB'

then to you can use the named imports :
{SubClassA, SubClassB} from 'my-package'

Comment: I'm also writing a Readme (usage instructions). When exported like this, can it still be imported with the require('...') syntax?
Comment: require/module.exports are originally used for modules so that wouldn't be possible inside a node environment


How to rewrite part of URL in .htaccess?

Question: I have this URL:
example.com/news/article/254

How to make a PHP script to process this URL (example.com/blog/article/254) as example.com/news/article/254,
and example.com/blog as example.com/news, etc.
Comment: So, I don't see any current code or even the actual php URL to rewrite? You didn't provide really enough clear information to help.
Comment: I need code for .htaccess file
Answer: The following code should work if you add it to your .htaccess file.
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteRule ^blog/article/(.+?)\/?$ /news/article/$1 [R=301, L]
</IfModule>

If you don't want to tell robots etc. that you have permanently redirected then take out the "R=301, " above.
Comment: i've tested the code and works, however, placement in your .htaccess file could be an issue or perhaps you don't need the IfModule test.  Can you post or send me your .htaccess file?