Números quase primos

Question: Tenho uma duvida em C, eu sei verificar se um numero é primo, porém, quase primo não sei.. como eu faço?
Segue a parte do código funcionando! Porém, só verificando se é primo.. o quase primo não roda
//  quasePrimos.c
//
//
//  Created by Braynner Teixeira on 12/09/17.
//  Copyright © 2017 Braynner Teixeira. All rights reserved.
//

#include <stdio.h>

int main(){

    int num, i, controle=0;

    printf("Informe um numero: ");
    scanf("%d", &num);

    if (num > 1)
    {

         // Dividir o numero informado por todos os numeros que estao entre ele e 1.

        for (i = 1; i <= num; i++)
        {

            if (num % i == 0)
            controle++;

        }

           if (controle == 2) {

            printf("O numero %d e um numero primo!\n", num);

        }
        else if (controle == 2 && controle*controle == num) {

                printf("O numero %d e quase primo!\n", num);

            }else {

            printf("O numero %d nao e um numero primo!\n", num);
        }

    }

    else if (num == 1 ) printf("O numero nao é primo e nem quase primo!");

}

Comment: [Aqui](https://en.wikipedia.org/wiki/Almost_prime) diz que 16 é quase primo (para `k=4`) @JeffersonQuesado
Comment: Isso, nenhum deles são!
Comment: @Jefferson E eu então? Nunca tinha ouvido falar em "quase" primos até agora. Não boto a mão no fogo pelo que está na Wikipedia, nem entendi totalmente.
Comment: Um numero quase primo, ou semi primo, é aquele que é o produto de dois números primos. Por exemplo 4, 6, 9, etc... (2*2, 2*3, 3*3)
Comment: @Cleber Então seria o que diz a Wikipédia limitado a k=2?
Comment: Qual o conceito de número quase primo?
Comment: Todo número inteiro maior do que 1 tem pelo menos dois divisores positivos: ele mesmo e 1. As únicas exceções são 0 e 1
Comment: Jefferson Quesado, eu dou o numero 15, e daí o produto dele: 3*5 é igual a ele mesmo.
Comment: 16 é quase primo? Eu acho que não, pode me confirmar? E 4 também não é quase primo, confere?
Comment: @bfavaretto quadrados perfeitos de números compostos? Ok, então preciso estudar mais
Comment: Essa é minha duvida.. cruel..
Comment: Pelo oque sei, é o produto de dois valores primos
Comment: @bfavaretto, não é limitado. Nesse caso, um "quase primo" é produto de **qualquer numero primo** multiplicado por **qualquer numero primo**.
Comment: Na pergunta dizia o seguinte: um número é quase primo se e somente se ele pode ser descrito como um produto de dois primos distintos.

Ex: 15 (= 5*3) é quase primo, já 2 e 4 não são.
Comment: Bem, o conceito de quase primo na pergunta é o [2-quasi-primo](https://pt.m.wikipedia.org/wiki/N%C3%BAmero_semiprimo). Então, @bfavaretto , é o conceito da Wiki em inglês dado `k=2`. Essa conversa do `k` é uma generalização
Comment: Semi Primo é a mesma coisa de Quase Primo? eu pensava que não!! Semi Primo era o produto de dois primos e Quase era de primos distintos..
Comment: @BraynnerTeixeira segundo as pesquisas de Wikipedia das pessoas dessa thread, não importa os números serem distintos os iguais. E semi primo seria um caso específico de quasi-primo
Answer: Um número k-quasi-primo é dado por ele ser composto por um produto de primos com k fatores. Exemplos:

15 = 3 * 5 é 2-quasi-primo,
9 = 3 * 3 é 2-quasi-primo,
16 = 2 * 2 * 2 * 2 é 4-quasi-primo,
5 = 5 é 1-quasi-primo.

No caso, o conceito quase primo é equivalente a 2-quasi-primo. Ou seja, k = 2.
Para isso, temos de descobrir quais são os fatores primos e quantas vezes eles são usados em cada número. Seu algoritmo está muito próximo da detecção de um número k-quasi-primo. Vou ajustar de tal modo que o valor da variável k indica qual "grau" de quasi-primalidade o número n possui:
int k = 0;
int i = 2;
while (n > 1) {
 while (n % i == 0) {
   k++;
   n /= i;
 }
 i++;
}

No caso, para detectar com quasi-primalidade k=2, basta verificar se k é 2 no final da execução. Também podemos abortar o laço antes da sua conclusão, caso se detecte um novo fator primo e k já valer 2, podemos retornar falso. Desse jeito:
int num = n; // como vou deteriorar o valor de n, vou guardar uma cópia para futura impressão
int quasi_primalidade = 2;
int k = 0;
int i = 2;
while (n > 1) {
 while (n % i == 0) {
   k++;
   n /= i;
   if (k > quasi_primalidade) {
     // pode ser um return se estiver em uma função
     goto FIM_LACOS;
   }
 }
 i++;
}
FIM_LACOS:
if (k == quasi_primalidade) {
  printf("O numero %d e um numero primo!\n", num);
} else {
  printf("O numero %d nao eh um numero primo =(\n", num);
}

Answer: Seu problema é que no primeiro if a condição é (controle == 2).
Logo, ele sempre vai entrar ali e nunca vai entrar no else if (controle == 2 && controle*controle == num) porque se o controle for 2, ele já vai para a primeira condição.
Para resolver este problema, tente inverter as condições:
if (controle == 2 && controle*controle == num) {
    printf("O numero %d e quase primo!\n", num);
}
else if (controle == 2) {
    printf("O numero %d e um numero primo!\n", num);
}
else {
    printf("O numero %d nao e um numero primo!\n", num);
}

Números quase primos


How do I update PHP and all its modules on FreeBSD in one go?

Question: Basically, I usually do something like this:
# portsnap fetch
# portsnap update

# portmaster -L | grep -B1 "New version"
    ===>>> php5-5.2.11
    ===>>> New version available: php5-5.2.12
# portmaster php5-5.2.11

But with PHP I've got about 40 modules and have to them one by one. Is there a better (and safe) way to do this?
Edit: well it turns out that this is what's needed:
# portmaster php5-extensions

It's amazing how hard that was to find out!
Answer: portmaster -db php5*

Comment: Just upgraded php itself, which ended in a segmentation fault. Executing this command saved my day. Thanks for sharing!
Answer: Firstly I should say that I don't use portmaster, I use portupgrade, but then I build ports rather than use packages!
Portupgrade allows you to put:
portupgrade php\*

which will upgrade all the php ports. Portmaster may do the same thing.
Also you can give portsnap multiple commands in one go, so you can put
portsnap fetch update

Comment: Using the new package manager system (The old one was EOL in September 2014), ports and packages can work together without stepping on each other. Portmaster can use either. Portmaster does have one nice feature not in portupgrade, it will ask all of the config questions up front and then do the build, rather than the portupgrade default of doing the config question as each port is built. Having used portupgrade for years and then switching to portmaster recently, I find it nicer.
Comment: I can just install portupgrade and use that then. There's no problem with using them together?
Comment: I don't know, as I've never used portmaster! If you use portupgrade then you can use the -P switch to use packages rather than ports where possible.
Answer: I rebuild/update all packages depending on php5 for safety.
You need to specify the full pkg-name including version.
Find out the exact version with pkg_info:
# pkg_info|grep php
php5-5.3.8          PHP Scripting Language

Then rebuild/update php and all ports depending on it with:
# portmaster -r php5-5.3.8

Answer: A more modern answer using only pkg is:
pkg install `pkg info | grep php | sed 's/72/74/; s/-7.*//'`

The example upgrades PHP 7.2 to 7.4. The first sed command needs to be adjusted for the installed and target versions of PHP.
The version resolution of pkg doesn't know that some PHP extensions needed in older versions of PHP are now part of PHP 7.4. You might have to remove a couple of them with a command like this: pkg delete -fy php72-hash.


Objective C: Load storyboard from a pod/framework

Question: I'm trying to load a view controller that's in a .storyboard in a pod. I'm using the following which normally works:
UIStoryboard *storyboard = [UIStoryboard
storyboardWithName:@"StoryboardName" bundle:nil];
NewViewController *newView = [storyboard instantiateViewControllerWithIdentifier:@"NewViewController"];
[self.navigationController pushViewController:newView animated:YES];

What do I need to change it to so I can load from a pod?
Comment: Does the code in your question work?
Comment: @trungduc it works if the Storyboard is in the project. It doesn't work if it's in an external pod.
Comment: Hey there, did you find a solution for this question ? hope anyone can respond..
Comment: I have created a framework with storyboard and trying to access storyboard from my view controller with below code    NSBundle *bundleName = [NSBundle bundleWithIdentifier:@"bundle id of framwork"];
        UIStoryboard *stainStoryboard = [UIStoryboard storyboardWithName:@"AssignTasks" bundle: bundleName];    but getting error "Exception: Could not find a storyboard named 'AssignTasks' in bundle NSBundle" .
Answer: You should load it with it's bundle identifier
NSBundle* bun = [NSBundle bundleWithIdentifier:"id"]

UIStoryboard *storyboard = [UIStoryboard   storyboardWithName:@"StoryboardName" bundle:bun];

Comment: What would the 'id' be? The pod's name?
Comment: I already marked it as the answer but I'm having some issue. The storyboard is included as a resource_bundles. Any idea on how to load this? Hope it makes sense.
Comment: I get the error: Could not find a storyboard named 'StoryboardName' in bundle NSBundle "
Comment: This is actually a really good answer. Just look for the bundle identifier of your pod which is likely be "org.cocoapods.".


Is there a name for the class of functions which are infinitely integrable in elementary functions?

Question: Is there a name for the class of functions which are infinitely integrable in elementary functions, that is whose consecutive integrals also elementary not depending on how much times we took the integral?
Answer: No, unfortunately there is not name for these functions. In general, the integral of an non-fractional elementary function will result in another elementary function. Polynomials are the name for $ax^2 + bx + c$ sort of things with this being a three term polynomial. In general, I think the term you want is a non-fractional elementary function. Really, this all depends on what you define as elementary. If you include natural logs, and exponents then you would use that as a descriptive term. In general, functions are classes according to their form and basic characteristics, not according to how they react within an integral or derivative.
Comment: There is a well-established notion of an "elementary function", see here https://en.wikipedia.org/wiki/Elementary_function
Comment: There are rational functions (fractional) whose integrals are elementary.


When "drush updatedb" is executed, are scripts cached by OPCache invalidated?

Question: For sites that have PHP OPCache enabled:

Does updating site using Drush require restarting the webserver to invalidate the scripts cached by OPCache?
Does Drupal core or Drush invalidate OPCache before running updates?
Is setting opcache.enable_cli to 0 a better strategy in this scenario?
Comment: I don't know the answer specifically, but I know that when I have opcache enabled, I don't have to do anything special to flush classes after doing updates or clearing the registry. However, I've never actually confirmed that this is because nothing needs to be done, or because I haven't properly configured opcache.
Comment: This probably can easily be found out in a reproducible Docker setup.
Answer: Updated response to address the questions as asked.

Yes, either the web server need to be restarted or the web-server's OPCache needs to be cleared. Drush cannot clear the web-server's opcache as it is a CLI application. Instead of restarting the web server a php script with following content can be added to next to Drupal's update.php
 <?php
 opcache_reset( );
 /*
 Following measures should be taken to safeguard this file from malicious use
 a) Set filename with a long random string as a name (like 100+ characters).
 b) Check the IP address of the requester so the script can only be called from trusted networks.

 To clear cache visit this file at
 siteurl/random_long_string_eiquooR3.php
 or use curl siteurl/random_long_string_eiquooR3.php
 Check the IP address of the requester so it can only be called from trusted networks.
 */

Neither Drupal core nor Drush invalidate OPCache.

Yes, setting opcache.enable_cli to 0 is a fine, it is anyways off by default. Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

Original Answer by @greggles

Restarting the webserver works, but takes quite some time. A more efficient solution is to have a way to call opcache_reset.
Opcache must be reset by calling opcache_reset from within the web process. If you call it inside drush then it will not clear the opcache for the webserver so it won't help the problem.
Unless you are really explicit in your configuration of opcache to enable it on the cli and also use a file based caching mechanism, the opcache exists in memory and is reset on each command line invocation. Therefore you only need to worry about clearing opcache by restarting any long-running PHP command line jobs.

If you want to clear opcache as part of a deploy process, I suggest adding a file that contains opcache_reset and then you have to protect access to that file so malicious users can't easily call it:

Give it a long random string as a name (like 100+ characters).
Check the IP address of the requester it can only be called from trusted networks.
Comment: I updated my answer item 3 to cover opcache cli behavior a bit more. Drush does not perform any opcache flush by default and it's generally not needed due to the way opcache works for cli.
Comment: thanks for sharing the information. Yes, pretty clear that the opcache_reset needs to be performed from the web. However, my question is pertaining to drush?  From experience it appears drush may be performing  a cli-opcache flush when running updatedb command, but I have not looked at the drush code yet.
Comment: @amit In the case it's not clear, greggles' comment is saying that Opcode cache is disabled for CLI. Since Drush is a CLI command, it wouldn't make sense to have a Drush command to clear Opcode cache, since it would be disabled for it.
Comment: I have rephrased @greggles answers, feel free to tweak it before I accept it.
Answer: We just ended up writing a more general solution to purge PHP and Database cache's used by Drupal Core. This module provides three ways to purge Opcache.

Web browser user interface
Curl commands
Drush commands

The Cache Utility module is available on Drupal.org


How to end try- catch in andoid?

Question: I wanna jump out of try block,
How do i do it?
try
{
//some code

if()
{
// I want to break/ jump out from try block here if condition is true
}
else
{
}

//but it continues here
 // More Code
}
catch()
{
}

How Do i jump out of it?
Any help would be appreciated.
Comment: Does this answer your question? [How can I break from a try/catch block without throwing an exception in Java](https://stackoverflow.com/questions/6534072/how-can-i-break-from-a-try-catch-block-without-throwing-an-exception-in-java)
Comment: By "jump out of `try`", do you mean you want to run the code that is _after_ the `try...catch` statement?
Comment: Yes, I want to execute whats after catch block  @Sweeper
Answer: Method 1
Try something like this:
try {
    do {
        ...
        if (condition)
            break;
        ...
    } while(false);
} catch () {
    ...
}

So the try block is just a do-while loop consisting all of the code. If the condition is true, it breaks out of the loop, and hence the try block.
Otherwise, it continues to the end and, because the condition of the do-while is false, comes out of the try block.
Note: If the if-statement is within another loop(other than this do-while loop), label this do-while loop, and later break to this label if condition is true.
Method 2
Make a custom Exception class and throw it only when the condition is met. Later, make the first catch statement to catch that custom exception. Like this:
try {
    ...
    if (condition)
        throw new CustomException();
    ...
} catch (CustomException e) {
    // Condition was true
} catch () {
    ...
}

How to end try- catch in andoid?


Proving why $\Bbb Z_{4} \rightarrow \Bbb Z_{6} \text{ given by } f(\overline x) = [2x+1] $ is not a function.

Question: Question presented: Is following a function from the indicated domain to the indicated
co domain?

$f:\Bbb Z_{4} \rightarrow \Bbb Z_{6} \text{ given by }$
  $ \bbox[white,1px,border:1px solid red]{f(\overline x) = {\left [ 2x+1\right]}
}
$

Q.S: So my main question for this problem is how does the co domain $f(\overline x) = [2x+1] $ affect the equivlanece class $\Bbb Z_{4}$?
QS: So according to my work here would it be correct to assume that $\Bbb Z_{4}$ would change because of the codomain.
Q.S: Lastly how does $x =y(mod)m$ affect the final result of the problem?
In this case we represent an element of the domain as an $\bar x$ and use the notation $[x]$ for equivalence classes in the co-domain.
The set of equivalence classes for the relation $\cong_{m}$ is denoted $\Bbb Z_{m}.$
$f(\overline0) = [1],f(\overline1) = [3],f(\overline2) = [5],f(\overline3) = [7],f(\overline4) = [9],f(\overline5) = [11],f(\overline6) = [13] $
$(4x+0)*2+1 \;\text{ This is what I am doing to get the result for the work bellow for  } \Bbb Z_{4} $ $x$ is an integer that is being multiplied to get the result it
is a visual representation for the function.
$\Bbb Z_{4},\; \overline 0 = \{ ...,-15,-7,1,9,17,... \} \; \Leftarrow \Rightarrow(4x+0)*2+1 $
$\overline 1 = \{ ...,-13,-5,3,11,19.., \} \Leftarrow \Rightarrow \; (4x+1)*2+1$
$\overline 2 = \{ ...,-11,-3,5,13,21,... \}$
$\overline 3 = \{ ...,-9,-1,7,15,23..., \}$
$\Bbb Z_{6}, \; \overline 0 = \{ ...,-12,-6,0,6,12,... \} \Leftarrow \Rightarrow \qquad (6x+0) $
$\overline 1 = \{ ...,-11,-5,1,7,13,... \} \Leftarrow \Rightarrow \qquad (6x+1)$
$ \overline 2 = \{ ...,-10,-4,2,8,14,... \} \Leftarrow \Rightarrow \qquad (6x+2)$
$ \overline 3 = \{ ...,-9,-3,3,9,15,... \} $
$ \overline 4 = \{ ...,-8,-2,4,10,16,... \}$
$ \overline 5 = \{ ...,-7,-1,5,11,17,... \}$
The reason for this not being a function is because $\Bbb Z_{6} \;  \overline 0 \neq \overline4 \; $ or $[1] \neq [9] $
Comment: $1\equiv5\pmod4$, yet $f(1)=3\not\equiv f(5)=11\pmod6$
Comment: Your notation is so confusing. What's $(4x+0)*2+1$? What do you mean by $\Bbb Z_4\ \bar 0 = \{ \dots, -7,1,9,\dots\}$? Didn't you just say that $\bar 0$ is an equivalent class in $\Bbb Z_4$?
Comment: By the way, what do you mean by "the codomain affect the equivalent class $\Bbb Z_4$"? How can the codomain possibly affect the domain?
Comment: @BigbearZzz I believe the OP is  writing  $\Bbb Z_{4}$ in front of $\bar 0$ and $\bar 0$ refers to the equivalence class to the right of the equals sign. I think co-domain is just an error on his part, he just means domain.Also,his general formula for modular arithmetic-(4x+ n)*2 +1 where $n\in \Bbb Z_{4}$-is correct.
Comment: I cannot comprehend your claim like $\overline 2 = \{ ...,-13,-5,3,11,19,... \}$, how did you manage to conclude that?
Comment: @Mathemagician1234 That still doesn't make sense to me since $\overline 1 \ne \{ ...,-14,-6,2,10,18.., \},\ \overline 2 \ne \{ ...,-13,-5,3,11,19,... \}$ and such.
Comment: @BigbearZzz Yes,the formula is right,but he/she clearly made serious errors in his/her computations!
Comment: @BigbearZzz Basically,the reason this isn't a function is that it's not well defined i.e. 2 different ordered pairs in f can have the same first member.
Comment: @Mathemagician1234 Yep, that's quite obvious. The reason I was asking is because the OP had just recently made a similar question (almost identical) with notations as confusing as in this one. I was trying to help him/her clarifying them so more people can understand him in the future.
Comment: I have made grievous mistake. Allow me to correct these indiscretions. For $\Bbb Z_{4}, \overline1 \rightarrow \overline3 $ is not correct.
Comment: Waiting for the third installment of THE SAME question.
Answer: I'm going to answer the question in the title:
The function $f: \mathbb{Z} \to \mathbb{Z}/6$, $x \mapsto [2x+1]$ does not descend to a function on $\mathbb{Z}/4$ because $x_1 \cong  x_2 (mod \,\, 4) \nRightarrow f(x_1) \cong f(x_2) (mod \,\, 6)$.  You can check this explicitly for the choices $x_1=0$, $x_2=4$.
Answer: It is an onto relation from a set of lesser to a set of greater cardinality. Thus it is not a function by definition of cardinality.
Comment: Why is it onto? You should give an exmaple in order to improve the answer.
Answer: $1\equiv5\pmod4$, yet $f(1)=3\not\equiv f(5)=11\pmod6$
That is, $f(x)=2x+1$ is not well defined as a function from $\mathbb{Z}_4$ to $\mathbb{Z}_6$; choosing a different representative for $x\bmod4$ gives a different residue class for $f(x)\bmod6$.


Check whether the following series is uniformly convergent OR not?

Question: Check whether the following series is uniformly convergent  OR not?
$\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}, x\in [0,\infty).$
My attempt
$\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}=x^4\sum_{n=1}^\infty \frac{1}{(1+x^2+x^4)^n}=( \frac{1}{(1+x^2+x^4)}).(\frac{x^4}{1-(\frac{1}{1+x^2+x^4})})=\frac{x^4}{(x^2+x^4)}$
$|\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}-\frac{x^4}{(x^2+x^4)}.1|=|\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}-\frac{x^4}{(x^2+x^4)}.\sum_{n=1}^\infty \frac{1}{2^n}|=|\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}-\sum_{n=1}^\infty \frac{x^4}{(x^2+x^4)}. \frac{1}{2^n}|=|\sum_{n=1}^\infty (\frac{x^4}{(1+x^2+x^4)^n}-\frac{x^4}{(x^2+x^4)}. \frac{1}{2^n})|$
How do I proceed further?
Is there any theorem helps to solve it faster?
I couldn't apply weirstrauss M-Test.
Answer: By generalizing your first line, one can show the tail sum equals
$$\sum_{n=N+1}^\infty \frac{x^4}{(1+x^2+x^4)^n} = \frac{x^4}{(1+x^2+x^4)^{N+1}}\frac{1}{1-\frac{1}{1+x^2+x^4}}
= \frac{x^2}{1+x^2} \cdot \frac{1}{(1+x^2+x^4)^N}.$$
To show uniform convergence, it suffices to check that the following holds.
$$\sup_{x \ge 0} \left(\frac{x^2}{1+x^2} \cdot \frac{1}{(1+x^2+x^4)^N}\right) \overset{N \to \infty}{\longrightarrow} 0.$$
Answer: Hint
$$\sum_{n=1}^\infty \frac{x^4}{(1+x^2+x^4)^n}=\frac {x^2}{1+x^2}$$
Comment: How does this help?series converges to a continuous function. If it would be non continuous function, I could I have say that series is non uniform convergence.


How to programmatically add custom markup to every displayed user name

Question: Drupal 8.x
I am currently using hook_preprocess_user().
I would like to alter the username to add some custom markup to every username.
MYMODULE.module:
function MYMODULE_preprocess_user(&$variables) {
  $variables['elements']['#user']->name->value = t('Name @newMarkup', ['@newMarkup' => ' Hello']);
}

This returns Name Hello Hello. Concatenation adds 'Hello' twice so this approach is not working.
I've also worked with user_format_name_alter(&$name, $account), however, this does not seem to fit my use case.
How can I alter the username text? Not looking for a "currentUser" solution, but every user so names are changed everywhere. Reference, Views, etc.
Comment: In a views preview at `/admin/structure/views/view/view_name` and a views page, it appears to render ok. I have been testing via a referenced views block.
Answer: Seems hook_user_format_name_alter() is your best bet. But same as in the other answer markup doesn't seem to be allowed everywhere. Normally the user name is only allowed to be a string.
The following won't work for Views for example. It will print just a string.
use Drupal\Core\StringTranslation\TranslatableMarkup;

/**
 * Implements hook_user_format_name_alter().
 */
function MYMODULE_user_format_name_alter(&$name, $account) {

  $name = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $name = $variables['title']['#markup']->__toString();
    $variables['title'] = new TranslatableMarkup('@name Foo Bar', ['@name' => $name]);
  }
}

So, what I'd recommend now is, you maybe take the *_preprocess_page_title hook – as this is working just fine on user pages – and for all other places (references, Views etc.) you maybe create a new custom formatter or pseudo field to do the job.
Comment: +1 ^. I've noticed a lot of different implementations of the "username". For example a view of users displaying fields, and the field username. If you link that field to the user it will use `username.html.twig` template, if you do not link the field it uses `views--field.html.twig` template. So far it seems whether with preprocess or template overrides, you need multiple implementations to get all username instances... The other side of the problem is that `hook_preprocess_user()` gets rendered multiple times in some instances.
Answer: <?php
use Drupal\user\Entity\User;

// Updating a user is a three step process:
// 1) load the user object to change
// 2) set property/field to new value
// 3) Save the user object.

// This example updates the user name.

// $uid is the user id of the user user update
$user = \Drupal\user\Entity\User::load($uid);

// Don't forget to save the user, we'll do that at the very end of code.

// Modify username
$username = $user->getUsername();
$username .= " Hello";
$user->setUsername($username); // string $username: The new user name.

// The crucial part! Save the $user object, else changes won't persist.
$user->save();

// Congratulations, you have updated a user!

I based this on the examples in this Github gist:
https://gist.github.com/dreambubbler/671afd7f962ae46687e41340b396d266
Comment: Seems you are actually recommending to fetch all users and re-save them with an updated user name. In a batch maybe, on `hook_update_N`? And this doesn't append markup. Only strings seem to be allowed.
Comment: Good point -- this is wrong. The question is just how to alter the markup, not the actual user object. So this doesn't answer the question at all. Hopefully someone else can do a better job! (I'll just leave this here rather than deleting it, because it does something interesting and somewhat related.)


Customise Drupal 7 Taxonomy View / Template (without module)

Question: How would I go about changing a custom taxonomy view / template without using a module?
i.e. I have a taxonomy named 'tutorials' which has three posts.
How would I modify the HTML output for 'tutorials?
From what I've heard, you can create a file named 'taxonomy--name.tpl.php' to override the default taxonomy template?
Thanks!
Answer: As described in Drupal 7 Theme Hook Suggestions, the template files that Drupal looks for a taxonomy term page are the following:

taxonomy-term--[tid].tpl.php
taxonomy-term--[vocabulary-machine-name].tpl.php
taxonomy-term.tpl.php

Replace [tid] with the taxonomy term ID, and [vocabulary-machine-name] with the machine name set for the vocabulary. Supposing that the machine name is programming_languages, then the template filename that Drupal looks is taxonomy-term--programming-languages.tpl.php. (The underscores are replaced with hyphens.)
The first file that is found is the one that Drupal uses.
Answer: Basically, if you don't want to use any module, but are fine to carve in your PHP templates, then this taxonomy.module API is what you need. We could probably come up with more detailed help  if you described your goal more precisely.
Answer: You can rewrite output in Views, and change Style (the HTML containers and classes) for each.
Did you mean without create a custom module? If so, there are several contrib taxonomy modules out there:
Taxonomy Formatter -- lets you add HTML wrappers around element and container
Taxonomy Page Display -- create custom taxonomy page for each term (or certain terms)
Display Suite - let you customize dang near any node or form


Passing incorrect values into MultiValueConverter by MultiBinding

Question: I've been trying to implement a dynamic ToolTip (WPF) for RadioButton (the ToolTip switches, when IsEnabled of the RadioButton changes). I wanted to achieve this with a MultiValueConverter, which would be sort of a general Converter, that accepts 3 values - the IsEnabled value, enabled ToolTip and disabled ToolTip in this exact order.
But sadly I have encountered an issue, that I haven't been able to solve yet. Basically when the code reaches the Convert Method, the Array of values is filled with DependencyProperty.UnsetValue items.
What I managed to find while googling was, that the problem is propably caused by having a wrong DataContext as mentioned here WPF MultiBinding in Convertor fails ==> DependencyProperty.UnsetValue , but I feel like I have tried every combination of RelativeSources and DataContexts, that I could come up with and nothing helped.
Here is the sample code of the View:
<code> <window.Resources>
            <local:BooleanToStringConverter x:Key="BooleanToStringConverter"/>
        </window.Resources>
        <Grid>
            <RadioButton x:Name="RadioButton" ToolTipService.ShowOnDisabled="True"
                IsEnabled="{Binding IsRadioButtonEnabled}" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Radio">
                <RadioButton.ToolTip>
                    <ToolTip>
                        <TextBlock>
                            <TextBlock.Text>
                                <MultiBinding Converter="{StaticResource BooleanToStringConverter}">
                                    <Binding ElementName="RadioButton"  Path="IsEnabled"/>
                                    <Binding RelativeSource="{RelativeSource AncestorType={x:Type local:MainWindow}}"  Path="ViewModel.EnabledToolTip"/>
                                    <Binding RelativeSource="{RelativeSource AncestorType={x:Type local:MainWindow}}"  Path="ViewModel.DisabledToolTip"/>
                                </MultiBinding>
                            </TextBlock.Text>
                        </TextBlock>
                    </ToolTip>
                </RadioButton.ToolTip>
            </RadioButton>
</code>
So the result, that I expect from this, is that the correct values will be passed into the Converter (in this case value of IsEnabled and string values of Enabled/Disabled ToolTips).
If anybody has any ideas, I would very much appreciate to hear them :).
Thanks in advance.
Answer: I managed to fix this by explicitly setting DataContext on the RadioButton and removing the RelativeSources within the MultiBinding. Though I don't understand why it did not work with the RelativeSources, it works. Here is the code, in case of anyone reading this in the future:
<code><RadioButton x:Name="RadioButton" ToolTipService.ShowOnDisabled="True"
                     DataContext="{Binding ViewModel, RelativeSource={RelativeSource AncestorType={x:Type local:MainWindow}}}"
            IsEnabled="{Binding IsRadioButtonEnabled}" VerticalAlignment="Center" HorizontalAlignment="Center" Content="Radio">
            <RadioButton.ToolTip>
                <ToolTip>
                    <TextBlock>
                        <TextBlock.Text>
                            <MultiBinding Converter="{StaticResource BooleanToStringConverter}">
                                <Binding Path="IsRadioButtonEnabled"/>
                                <Binding Path="EnabledToolTip"/>
                                <Binding Path="DisabledToolTip"/>
                            </MultiBinding>
                        </TextBlock.Text>
                    </TextBlock>
                </ToolTip>
            </RadioButton.ToolTip>
        </RadioButton>
</code>


Trying to understand the git branching approach used in the git project

Question: I've been reading the gitworkflows page of the git-scm docs and am confused about some parts of the workflow. My current understanding is this:

maint is the oldest integration branch and is intended for hotfixes for the previous release.
master contains commits going out for the current release
next contains experimental patches being regression tested.
seen contains patches that have been viewed in the mailing list by the maintainer. (if I'm incorrect, please elaborate).

All patches graduate from unstable to more stable, with master or maint being the most stable branches. As a general rule, integration happens upwards. This use of upwards here is confusing, but assuming that we don't want to regress, upwards means something like maint -> master -> next -> seen, where maint is merged into master, master is then merged into next, etc. This is further supported by the following quote:

If you notice that you have applied a fix to e.g. master that is also required in maint, you will need to cherry-pick it (using git-cherry-pick) downwards.

If cherry-picking from master to maint is considered merging downwards, then I think my understanding of upwards merging is correct.
Topic branches, the rule to not merge downstream unless necessary, and throw away integration branches make sense to me. It's all about keeping branches focused and clean while also providing means to test many changes together outside of the next branch.
One area I'm still unsure about is the documentation on Maintenance branch management after a feature release. It claims that master is a superset of maint, meaning that master contains all commits in maint. It then fast-forwards on the maint branch to master after each release. But how is this possible? If maint is for hotfixes for the previous release, wouldn't adding any hotfixes on top of it force a merge commit instead of a fast-forward when updating the maint branch when master is updated with the next release? Wouldn't the below merge command fail in that case?
git checkout maint
git merge --ff-only master

I know this merge can still be done with a merge commit, but it seems like the overall flow has been focused on clarity and ensuring history linearity. Having merge commits seems to muddy that clarity a bit (despite being more accurate in terms of how changes are introduced). Is my understanding of git.git's worflow correct?
Comment: Note that the `seen` branch is regularly rewound and rebuilt: "seen" commits can be ejected if they prove buggy, and then corrected commits are added back again later. The other branches do not get this treatment: bugs that need fixes are either fixed or, in some cases, have a commit reverted until the fix can be done. (`seen` used to be called `pu`, Proposed Updates or PickUp depending on who you asked.)
Answer: Some time after a release, we have this situation:
    o--o--o    <- master
   /
--o            <- maint

Then comes a hot-fix for maint. First, the fix is applied to (or merged into) maint, then maint is immediately merged into master, hence, we have, this situation:
    o--o--o--M    <- master
   /        /
--o--------F      <- maint

This is so that the master branch can also take advantage of the hot-fix. Later, when a new release is cut, maint can be fast-forwarded to master:
    o--o--o--M--o--o    <- master, maint
   /        /
--o--------F

No new merge commit is needed for git checkout maint; git merge master.

but it seems like the overall flow has been focused on clarity and ensuring history linearity

Not at all. Linear history is by no means a goal with this workflow; see the situation after the hot-fix. On the contrary, it takes advantage of Git's abilitiy to cope with merges. In fact, in the examples above, you can consider every o as well as F to be a merge commit that merges a topic branch.


Block all incomming requests on any port, unless from list of source IPs

Question: I have a number of CentOS 7 VPS running Docker and are orchastrated by Cattle (Rancher).
These VPS should only be accessible from a couple of IP addresses on the internet and all other sources should be dropped/ignored. I have configured firewalld appropriately and the restriction is working for the standard system services, such as SSH, but when I deploy a container to them the exposed port is being allowed from anywhere.
It seems that Docker is mapping the host IP/port to the container IP/port (which is correct) but then this rule is being inserted into netfilter BEFORE my explicit source allow list...
Is there anyway to get around this? Any help would be much appreciated.
Answer: Yeah, you just have to make your blocking firewall entries evaluate before the entries added by docker.
In my environment, docker adds allow rules to a chain called DOCKER and deny rules to a chain called DOCKER-ISOLATION.  These get evaluated at the beginning of the FORWARD chain.  So if your env is like mine, just stick your own rules at the top of the FORWARD chain.  This is in the 'filter' table.  I recently confused myself with the 'filter' and 'nat' tables.
Hope that helps
-Dylan
Comment: This is exactly what I was thinking of doing, but I figured iptables chains were frowned upon in CentOS 7 land. I think this might be my only option unless there is some magic I haven't found in FirewallD...
Comment: Looks like we need this patch to go live to get a proper solution... https://github.com/docker/libnetwork/pull/1675
Answer: I struggled with this one for a few hours, but here is a solution using iptables instead of firewalld.
The key is to get your blocks in before Docker. However Docker has a nasty habit of putting it's rules right to the top of the FORWARD chain on the filter table; on every service restart. So... I had to get creative and leverage the mangle table and the POSTROUTING chain, like so:
*mangle
:IS-ALLOWED -
-A IS-ALLOWED ! -o docker0 -j RETURN
-A IS-ALLOWED -o docker0 -s 22.214.171.124 -j RETURN
-A IS-ALLOWED -j DROP
-I POSTROUTING -j IS-ALLOWED
COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:IS-ALLOWED -
-A IS-ALLOWED -s 22.214.171.124 -j RETURN
-A IS-ALLOWED -i lo -j RETURN
-A IS-ALLOWED -j DROP
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -j IS-ALLOWED
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

This restricts access to just 188.8.131.52 for the machine's services (SSH, ICMP etc) and the Docker forwarded services on the docker0 interface.


Different values for the same array element?

Question: So I'm not sure what is going on here.
I have a function which is supposed to solve this problem, except that while typing out the elements of an array in main() I get different results:

0 if I cout it in the same line with the function
the correct result if i write it out below

Here's the code:
#include <bits/stdc++.h>

using namespace std;

int a[100100],mx=0,bg;

int collatz(int n){
    a[1] = 1;
    for(int i=2; i<=n; i++){
        int p = 0;
        int j=i;
        while(j!=1 && j>=i){
            if(j%2==0) j/=2, p++;
            else if(j%2==1) j=3*j+1,
        }
        a[i] = p + a[j];
        if(mx<a[i]) mx = a[i], bg = i;
    }
    return mx;
}

int main()
{
    for(int i=1; i<=10000; i++) a[i] = 0;
    cout << collatz(1000) << " " << a[1] << " " << a[2] << " " << a[3]<< "\n";
    cout << a[1] << " " << a[2] << " " << a[3] << " ";
    return 0;
}

And here's what I get:

The compiler I use is CodeBlocks, though I've tested it on others and it's the same issue!
Thanks
Comment: There are a few things [good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) will taught you that an online judge or competition site will not. Among them that array indexes start at zero, and that order of evaluation when outputting using `<<` is not defined (which is your problem).
Comment: I also suggest you take some time to read [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) And learning that [`using namespace std` is bad](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice).
Comment: CodeBlocks is an IDE, not a compiler.  You can use any compiler with it; it seems you are using an old compiler
Comment: btw the word ["inline"](https://en.cppreference.com/w/cpp/language/inline) has a particular meaning (which is not relevant here). I edited your question, because it took me a while to get what you really mean ;)
Comment: Yep I'm aware of how array indexing works. This particular problem would have been a mess if I had started with 0 though. Thanks for the answer!
Answer: On the line:
 cout << collatz(1000) << " " << a[1] << " " << a[2] << " " << a[3]<< "\n";

Before the C++17 standard,  the compiler was allowed to evaluate the operands in any order, so it could look up a[1] etc. and save the result, then call collatz(1000), and then display the saved results in the right order.
To fix this, either compile in C++17 mode (use -std=c++17 compiler switch) or change the code to be:
cout << collatz(1000);
cout << " " << a[1] << " " << a[2] << " " << a[3]<< "\n";

Comment: Thanks for the actual answer instead of a passive aggressive comment!

Is there a reason why the C++17 compiler isn't set as default for new projects?
Comment: You would have to inquire with Code::Blocks developers about that one.


How to solve "The process has been signaled with signal 11" - Snappy Library?

Question: I am using a Snappy PDF library in Laravel 5.7. Locally it works everything fine, but in my dev environment I get this error: The process has been signaled with signal "11". Till now I was not able to find a solution that would help me. This is my code in controller:
   public function pdfReport(Request $request){
    $pdf = \Snappy::loadView('index', compact(
                  'name', 'lname', 'date', 'address'
                  ))
                  ->setOrientation('portrait')
                  ->setOption('margin-bottom', 0)
                  ->setOption('margin-top', 0)
                  ->setOption('margin-left', 0)
                  ->setOption('margin-right', 0);
     return $pdf->download(str_replace(' ', '', $request->description) . Carbon::now()->format('dYm_His') . '.pdf');
  }

Any help is appreciated!!!
Comment: In my case, The problem was the Xdebug extension.
Answer: This is probably not related to the OP's question, but in case anyone else is getting this, it might be helpful:
In my case, the The process has been signaled with signal "11" exception was linked to an infinite loop. I encountered this exception when running a test case that was stuck in a self-calling recursion.
More generally speaking, a signal 11 is a segmentation fault, and the exception is raised by the Symfony Process class. A segmentation fault is usually an illegal memory access and can be caused by a buffer or stack overflow.
So, in my case, it was a stack overflow due to the infinite recursion.
Answer: I had this issue while running laravel v9, laravel-snappy v1, phpunit v9 with Alpine Linux in gitlab CI. I was able to fix it by install some dependencies by changing the following in gitlab-ci.yml, from:
- apk add --no-cache wkhtmltopdf
to:
- apk add --no-cache wkhtmltopdf xvfb ttf-dejavu ttf-droid ttf-freefont ttf-liberation
I derived this solution from https://sasablagojevic.com/setting-up-wkhtmltopdf-on-docker-alpine-linux
Answer: I solved it through composer.
In my case its seemed to be coming from Symfony\process\process.php:441,
    do {
        $this->checkTimeout();
        $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
        $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
    } while ($running);

    while ($this->isRunning()) {
        $this->checkTimeout();
        usleep(1000);
    }

I followed every step but nothing worked. But after running
"composer require h4cc/wkhtmltopdf-amd64" and "composer require barryvdh/laravel-snappy" I replaced the vendor directory on the server.
Answer: I have solved it installing wkhtmltopdf directly in the linux machine
and having the below codes in snappy.php.
P.S. I was running wkhtmltopdf in Cpanel, and having the path from the vendor give me the above-mentioned error.
'pdf' => array(
        'enabled' => true,
        'binary' => '/usr/local/bin/wkhtmltopdf',
        'timeout' => false,
        'options' => array(),
        'env' => array(),
    ),


Proper way to run nameko service(s) inside a Django application?

Question: If I have a vanilla Django REST (DRF) application and I would like to integrate a nameko service (specifically an event_handler event listening service), what's the best way to achieve this?
I cannot simply nameko run a service if it's part of a Django application.
I'm considering running the nameko service via a custom Django management command, but would I lose some of nameko's features, say, scalability? Eg. nameko maintains a pool of 10 workers per nameko run (if I remember correctly).
Comment: I don't know much of nameko, but as far as I have seen from docs, I don't think you should make it a management command. As far as I understand(and I could be wrong), you should make it an standalone web service and communicate it from django via REST api
Answer: This is how:
https://github.com/sivabudh/djanko/blob/master/services.py
See: django-nameko-standalone
Update: If you want to do microservices with Django, just use Celery. Works like a charm.


How to show that $f(S) \subset Y $ is dense, when $f$ is continuous and surjective, and $S \subset X$ is dense in $X$?

Question: Let $(X,d_x)$ and $(Y,d_y)$ be metric spaces. Furthermore, let $f:X \to Y$ be surjective and continuous. Furthermore: $S \subset X$ is dense in X.
Question: How to prove that $f(S) \subset Y$ is dense in Y?
I wrote down the definitions of continuity:
$\forall x \in X, \forall a \in \mathbb{R} :  \exists \delta > 0 $ such that $\forall \epsilon > 0 : |x-a| < \delta \implies |(f(x) - f(a) | < \epsilon , $
and of $S \subset X$ being dense in X:
$ \bar{S} = \{ x \in X | \forall \epsilon > 0 : \exists y \in S $ such that $d(x,y) < \epsilon \} = X $,
and of $f$ being surjective:
$\forall p \in Y : \exists x \in X : f(x) = p $.
Using these definitions, I tried to prove:
$\overline{f(S)} = \{ p \in Y | \forall \epsilon ' > 0 : \exists z \in f(S) $ such that $d(p,z) < \epsilon ' \} = Y.$
I couldn't figure it out, though. I tried proving this by contradiction, but to no avail. Could you please help me out?
Comment: It becomes very easy once you have proven that a function is continuous if and only if $f(\overline A)\subseteq\overline{f(A)}$ for every subset $A$ of $X$. By the way, the result is true for arbitrary topological spaces and continuous surjective maps.
Comment: You need the additional assumption that X is compact.
Comment: I'm sorry, I made a mistake in translating "dicht" from Dutch to English. It should be "dense"!
Answer: Note that in a metric space the closure of a set is the set of limits of all sequences. In particular a set $A$ is dense in a space $X$ iff for any $x \in X$ there is a sequence $a_n \in A$ such that $a_n \rightarrow x$.
Hint: Let $y \in Y$. Then $y = f(x)$ for some $x \in X$. Now think about how to use the fact that $S$ is dense in $X$.
Edit: Since $S$ is dense in $X$ there exists a sequence $s_n \in S$ such that $s_n \rightarrow x$. Can you now find a sequence in $f(S)$ that tends to $y = f(x)$? (Remember, $f$ is continuous!)
Edit 2: To prove this using epsilon delta methods, take any $y \in Y$ and let $\epsilon > 0$. $f$ is surjective so $\exists x \in X$ such that $f(x) = y$. Since $f$ is continuous, $\exists\delta > 0$ such that $d_X(x,z) < \delta \implies d_Y(f(x),f(z)) < \epsilon$. Since $S$ is dense in $X$ there exists some $x_0 \in S$ such that $d_X(x,x_{0}) < \delta$. Hence $d_Y(f(x),f(x_{0})) < \epsilon$ and $f(x_0) \in f(S)$. As such $f(S)$ must be dense in $Y$.
Comment: I'm sorry, I guess this probably shouldn't be very difficult but I just can't see it. Could you please elaborate?
Comment: @MaxMuller No problem, I just extended the answer!
Comment: "In particular a set $A$ is closed..." Shouldn't you be changing "closed" to "dense" there?
Comment: @MaxMuller I've actually used a different (but equivalent) characterisation of dense sets to what you used in the question. This means that we can avoid having to get into the details of using epsilons and deltas. If you like, I can add another part to the answer proving it with epsilons and deltas.
Comment: @PeterTamaroff It certainly should be, thank you very much!
Comment: @MaxMuller I've added in an epsilon delta proof to my answer. There's a lot more to it than there is to the original proof, but it doesn't rely on knowing the alternative definition of dense sets. Thinking about it, this should probably be what I wrote in the first place, since showing that the other condition for a set to be dense is the same as the on you gave is not a trivial result. (Although it's not THAT hard, and I encourage you to try and prove it when you're a little happier with the material!) I hope this helps, let me know if something needs clarifying!
Answer: Another characterisation of $S$ being dense in a metric space $X$ is the following:

for all $x \in X$ and all $\epsilon > 0$ there is a $y \in S$ with $d(x,y) < \epsilon$.

Given $v \in Y$ and $\epsilon > 0$, by surjectivity there is an $x \in X$ with $f(x) = v$, and by continuity there is a $\delta > 0$ such that $d_Y ( f(x) , f(y) ) < \epsilon$ for all $y \in X$ with $d_X (x,y) < \delta$. As $S$ is dense in $X$ there must be a $y \in S$ such that $d_X (x,y) < \delta$. But now $f(y) \in f [ S ]$ and by choice of $\delta$, $d_Y ( v , f(y) ) < \epsilon$.
Answer: Let $x=f(y)$ and $\epsilon>0$. We want to find $z\in f(S): d(y,z)<\epsilon$.
Since $f$ is continues exists $\delta>0: d(x,w)<\delta \Longrightarrow d(f(x),f(w))<\epsilon.$
Now use the fact that $S$ is dense in $X$ to find $w\in S:d(x,w)<\delta.$
Answer: Continuous functions preserve limits. Take a point in $x\in X$, and a sequence in $(x_n)\in S$ converging to $x$. Then $(y_n=f(x_n))\in f(S)$ will converge to $f(x)\in Y$ (by surjectivity).
ADD Recall that in metric spaces, we can characterize density in the following manner:

A subset $D$ is dense on $X$ if for every $x\in X$ there exists a sequence of points $d_n\in D$ such that $d_n\to x$.
Comment: @TaylorRendon The result is false otherwise. Consider a constant function.
Comment: Why do we require that $f$ be onto for the image of a dense subset to be dense?
Answer: To show that $f(S)$ is dense in $Y$, we show that $f(S)\cap V\neq\emptyset$ for all non-empty open subsets $V$ of $Y$. By way of contradiction, suppose there is a non-empty open set $V\subseteq Y$ such that $f(S)\cap V=\emptyset.$ The preimage of $\emptyset$ under any function is $\emptyset$, so $$\begin{align}\emptyset &= f^{-1}\bigl(f(S)\cap V\bigr)\\ &= \bigl\{x\in X:f(x)\in f(S)\cap V\bigr\}\\ &= \bigl\{x\in X:f(x)\in f(S)\bigr\}\cap\bigl\{x\in X:f(x)\in V\bigr\}\\ &= f^{-1}\bigl(f(S)\bigr)\cap f^{-1}(V).\end{align}$$ We necessarily have $S\subseteq f^{-1}\bigl(f(S)\bigr)$, so it follows that $$S\cap f^{-1}(V)=\emptyset.$$ Now, $S$ is dense in $X$, and $f^{-1}(V)$ is open, as the preimage of the open set $V$ under the continuous map $f$, so we must have $f^{-1}(V)=\emptyset.$ But $V$ is a non-empty subset of $Y$ and $f$ maps surjectively to $Y$, so we have our contradiction.
Answer: Direct proof: let $U \subset Y$ be open and non-empty. Since $f$ is surjective, $f^{-1}(U) \subset X$ is non-empty, and open since $f$ is continuous so it preserves open-ness.
Now $S$ is dense in $X$ so $S \cap f^{-1}(U)$ is non-empty. So $\exists x \in f^{-1}(U) \cap S$ s.t. $f(x) \in U$, i.e. $\exists x \in S$ s.t. $f(x) \in U \implies f(S) \cap U$ is non-empty.
$\therefore f(S)$ is dense in $Y$.


How to remove the gray margin in the cardviews in a gridlayout

Question: I'm using a gridlayout and when I add the cardviews there's a gray margin covering the sides. Is there any way I can remove/hide it? I'm still exploring android studio.
Comment: Please show code of Layout contains CardView and the one that contains RecyclerView
Comment: `android:clipToPadding="false"`
Answer: Already answered on these links
CardView inside RecyclerView has extra margins
Unnecessary padding in CardView?
<code>useCompatPadding=true
</code>


Arranging $6$ orange marbles and $6$ red marbles in a circle.

Question: I would like to count the number of ways to arrange $6$ orange marbles and $6$ red marbles in a circle, if rotations of a given arrangement are considered the same (and marbles of the same color are identical).
I realize this can be done by considering the $12$ rotations of the circle and trying to count the number of arrangements each rotation leaves fixed, or by breaking this up into cases according to how the orange marbles are spaced, but is there a more elementary way to work this?
Answer: There are $\frac{12!}{6!6!}$ arrangements if we do not identify per rotation.
For all divisors $d$ of $6$, you need to count how many arrangements are invariant under rotating by $2d$ steps (the number is $n_d=\frac{(2d)!}{d!d!}$) and employ the inclusion-exclusion principle.
From this we get that the count of arrangements having no rotational symmetry is
$$ n_{6}-2n_3-n_2+n_1$$
the count of those having a threefold but not sixfold symmetry is
$$ n_{3}-n_1$$
the count of those having a twofold but not sixfold symmetry is
$$ n_{2}-n_1.$$
Thus after identification modulo rotation, we obtain
$$ \frac{n_{6}-2n_3-n_2+n_1}{12}+\frac{n_2-n_1}{6}+\frac{n_3-n_1}{4}+\frac{n_1}2$$
Comment: @HagenvonEitzen- the question says "rotations of a given arrangement are considered the same".
Comment: Thanks -- I hadn't seen this method of solution before.


Can't send ngfor index from HTML to child component

Question: I tried to let my child component to read parents HTML's ngfor value to display the child page. But the child component seems didn't get the index number from the parent page.
This is my Parents: app.component.html:
<code>     <ul *ngFor="let item of formDoc.components | keyvalue: valueAscOrder; let i = index ">
            <li *ngIf="item.value['type'] == 'columns'">
                <mat-card [style.backgroundColor]="'white'" [style.border]="lightgrey" [style.width]="'50%'">
                    {{item.value["label"]}}

                    <app-columns [indexnumber]="i"></app-columns>

                </mat-card>

            </li>
      </ul>
</code>
And this is the child: Columns.component.ts
<code>import { FormBuilderComponent } from 'angular-formio';
import { Injectable } from '@angular/core';
import { Component, Input } from '@angular/core';
//import { ColumnComponent } from 'src/column/Column.component';
import { AppComponent } from '../app.component'

@Injectable()

@Component({
  selector: 'app-columns',
  templateUrl: './Columns.component.html',
  styleUrls: ['./Columns.component.scss'],
})

export class ColumnsComponent {
    @Input() columnsData: object[];
    public saveData: object[];
    @Input() public indexnumber: string;

    constructor(public appComponent: AppComponent){
        if (this.indexnumber) {
            this.columnsData = appComponent.Temp2[this.indexnumber]["component"];
        }
    }
}
</code>
The value of indexnumber is always undefined. I'm wondering how to make index number in Columns.component.ts get the ngfor 'i' value?
Answer: Fist of all, the index of an array is a number, not a string. So
<code>@Input() public indexnumber: string;
</code>
should be
<code>@Input() public indexnumber: number;
</code>
Second: in order for angular to be able to set the indexnumber of your component, your component needs to exist. So it must have been constructed before. So, at the time the constructor is invoked, the input can't possibly have been set yet. So trying to access the value of an input in the constructor can't possibly give you the value passed by the parent.
Use ngOnInit or ngOnChanges. That's the methods that are called when the inputs are set for the first time/changed.
Comment: ngOnInit(){
        this.columnsData = this.appComponent.Temp2[this.indexnumber]["component"];
    }


Bayesian and Markovian Networks: How do we obtain the probabilities at each node in a Bayesian or Markovian network

Question: I just have a very basic 2 part question about Bayesian and Markovian networks. I suppose my confusion stems by trying to learn about these things through blog posts and videos, and not being able to ask someone direct clarifying questions, but hopefully someone here can ally my confusion.
The 2 questions are explained below. But here are the questions for easy reference.

How are the probabilities computed at each node in a Bayesian or Markovian network.
Can we, or how can we use continuous distributions at different nodes?

Say I have a Bayesian network like the one pictured below. I would like to understand how the probability distribution is setup at each node in the network. That is, usually the probability distribution at each node is setup as a simple table with a discrete probability distribution. Now, if I have a dataset and I want to create the distribution for each node, do I just subset the table and then compute the simple frequencies? For example in the table to compute the distribution over "Congestion" would I just subset my dataset and manually compute the number of times someone has congestion given that the have the flu, over the total number of people with congestion. And then compute the total number of times that someone has congestion given hayfever, divided by the total number of people with congestion. I am not sure if I might need to renormalize the probabilities, but would it just be that simple to obtain the discrete distribution for each node? I might just be overthinking it because I am used to applying multivariate control on things like this--but the graphical structure of the model seems to be handling the multivariate control that I would use in some regression. I mean, some of the people who have Hayfever might have the Flu at the same time, so how do we deal with this?

The second question is what to do with continuous distributions. Is it possible to use a continuous distribution for the node? Technically I could discretize the continuous distribution but I was just wondering if something like that is possible, and how we would again estimate the distribution from data. Again, it is just creating a distribution from the table, or is there anything more than that.
Thanks for any assistance with clarifying how Bayesian and Markov networks work.
Comment: I've completed my answer, so let me know if anything isn't clear.
Comment: @mhdadk thanks so much for the answer. The only thing I was still not clear on what how the probabiltiies are assigned at each node. Is it just as simple as getting the frequencies from the table of data? Is multivariate control applied through the structure of the network?
Comment: "the table of data" could you be more specific?
Comment: @mhdadk Ahh, sorry. I come from Statistics so usually think in terms of estimating parameters. In my naive mind, I should be estimating the conditional probabilities using some likelihood function. But in the Koller book and other places, they just show a table of the discrete values of `P(Congestion | Hayfever, Flu)`. So is it just as simple as calculating the conditional probability at each node from a table, or is there an algorithm to calculate those conditional probabilities. That is why I was a bit confused about multivariate control, since say season can affect both hayfever and flu.
Comment: Just use Bayes' rule to compute `P(Congestion | Hayfever, Flu)`. To do this, you would need to compute `P(Congestion,Hayfever, Flu)` in the numerator `P(Hayfever, Flu)` in the denominator. Both of these can be computed using belief propagation.
Answer: The purpose of both Bayesian networks and Markov networks is to represent conditional independencies, although each of them have slightly different ways of doing so. In a Bayesian network, conditional independencies can be understood using the Markov condition. It states that for each node in a Bayesian network, the random variable in this node is conditionally independent of its non-descendants given its parents.
To better understand this, consider the Flu random variable in the Bayesian network in your question. Its descendants are Muscle-Pain and Congestion. This means that Season and Hayfever form its set of non-descendants. However, Season is also Flu's parent, and so we don't include it in Flu's set of non-descendants. Therefore,
$$
\text{Flu} \perp \text{Hayfever} \ \mid \ \text{Season}
$$
which reads as "Flu is independent of Hayfever given Season". Now suppose that we are interested in computing $p(\text{Flu})$. Using the law of total probability,
$$
p(\text{Flu}) = \sum_{\text{Season},\text{Hayfever},\\ \text{Congestion},\\ \text{Muscle-Pain}} p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain})
$$
Using Bayes' rule
$$
p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain}) = \\
p(\text{Muscle-Pain} \mid \text{Season},\text{Hayfever},\text{Congestion},\text{Flu}) \times \\
p(\text{Congestion} \mid \text{Hayfever},\text{Season},\text{Flu}) \times \\
p(\text{Flu} \mid \text{Season},\text{Hayfever}) \times \\
p(\text{Hayfever} \mid \text{Season}) \times \\
p(\text{Season})
$$
However, we know that Flu is independent of Hayfever given Season, and so the term
$$
p(\text{Flu} \mid \text{Season},\text{Hayfever})
$$
becomes
$$
p(\text{Flu} \mid \text{Season})
$$
We can then use the Markov condition to deduce other conditional independencies from the Bayesian network. These are
$$
\text{Season} \perp \emptyset \ \mid \ \emptyset \\
\text{Hayfever} \perp \text{Flu},\text{Muscle-Pain} \ \mid \ \text{Season} \\
\text{Muscle-Pain} \perp \text{Hayfever},\text{Congestion},\text{Season} \ \mid \ \text{Flu} \\
\text{Congestion} \perp \text{Season},\text{Muscle-Pain} \ \mid \ \text{Flu},\text{Hayfever} \\
$$
where $\emptyset$ indicates no parents or no non-descendants. We can use these to simplify the expression for
$$
p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain})
$$
even further, such that
$$
p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain}) = \\
p(\text{Muscle-Pain} \mid \text{Flu}) \times \\
p(\text{Congestion} \mid \text{Hayfever},\text{Flu}) \times \\
p(\text{Flu} \mid \text{Season}) \times \\
p(\text{Hayfever} \mid \text{Season}) \times \\
p(\text{Season})
$$
What did we gain from this simplification? More generally, what did we gain from representing these conditional independencies using a Bayesian network? Notice that if we want to compute
$$
p(\text{Flu}) = \sum_{\text{Season},\text{Hayfever},\\ \text{Congestion},\\ \text{Muscle-Pain}} p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain})
$$
which actually consists of 4 summations:
$$
p(\text{Flu}) = \sum_{\text{Season}} \sum_{\text{Hayfever}} \sum_{\text{Congestion}} \sum_{\text{Muscle-Pain}} p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain})
$$
Let us substitute
$$
p(\text{Flu},\text{Season},\text{Hayfever},\text{Congestion},\text{Muscle-Pain}) = \\
p(\text{Muscle-Pain} \mid \text{Flu}) \times \\
p(\text{Congestion} \mid \text{Hayfever},\text{Flu}) \times \\
p(\text{Flu} \mid \text{Season}) \times \\
p(\text{Hayfever} \mid \text{Season}) \times \\
p(\text{Season})
$$
into this summation, such that
$$
p(\text{Flu}) = \sum_{\text{Season}} \sum_{\text{Hayfever}} \sum_{\text{Congestion}} \sum_{\text{Muscle-Pain}} \\
p(\text{Muscle-Pain} \mid \text{Flu}) \times \\
p(\text{Congestion} \mid \text{Hayfever},\text{Flu}) \times \\
p(\text{Flu} \mid \text{Season}) \times \\
p(\text{Hayfever} \mid \text{Season}) \times \\
p(\text{Season})
$$
Notice that we can re-arrange and distribute the summations such that
$$
p(\text{Flu}) = \\
\left[\sum_{\text{Muscle-Pain}}
p(\text{Muscle-Pain} \mid \text{Flu}) \\
\left[\sum_{\text{Congestion}} \sum_{\text{Hayfever}} p(\text{Hayfever} \mid \text{Season}) \cdot p(\text{Congestion} \mid \text{Hayfever},\text{Flu}) \\
\left[\sum_{\text{Season}} p(\text{Season}) \cdot p(\text{Flu} \mid \text{Season})\right]\right]\right]
$$
This a bit messy, so let us clean it up by letting:
\begin{align}
\phi_1(\text{Flu}) &= \sum_{\text{Season}} p(\text{Season}) \cdot p(\text{Flu} \mid \text{Season}) \\
\phi_2(\text{Season},\text{Flu}) &= \phi_1(\text{Flu}) \cdot \sum_{\text{Congestion}} \sum_{\text{Hayfever}} p(\text{Hayfever} \mid \text{Season}) \cdot p(\text{Congestion} \mid \text{Hayfever},\text{Flu}) \\
\phi_3(\text{Season},\text{Flu}) &= \phi_2(\text{Season},\text{Flu}) \cdot \sum_{\text{Muscle-Pain}} p(\text{Muscle-Pain} \mid \text{Flu}) \\
p(\text{Flu}) &= \phi_3(\text{Season},\text{Flu})
\end{align}
So, computing $p(\text{Flu})$ now involves a sequence of recursive calculations. Additionally, we have drastically reduced the number of additions and multiplications that we need to perform by

Making use of the conditional independencies induced by the Bayesian network
Re-arranging and distributing the summations.

This two-step process is encapsulated by the Belief Propagation algorithm. To summarize: Why are probabilistic graphical models useful? Because they allow us to model conditional independencies, which in turn allow us to compute probabilities very efficiently.
As for your second question

Can we, or how can we use continuous distributions at different nodes?

Yes. This is done by replacing summations with integrations in the process above. However, the process of re-arranging integrations is a bit more nuanced. See Fubini's theorem for details.


tf.data.Dataset with stepping batches

Question: I have a temporal dataset of 8760 samples. I wonder if there is a way to batch it with a step of 1, that is: the first batch contains the No.1 to 4, the second batch contains the No.2 to 5, the third batch contains the No.3 to 6 etc.
Answer: Since you have only 8760 samples, you probably can afford (in terms of RAM costs) the simplest possible solution - just transform your data using ordinary Python code:
dataset = [sample1, sample2, ... sample8760]
transformed_dataset = []
for i in range(len(dataset) - 3):
    transformed_dataset.append(dataset[i:i + 4])

If you can't afford to store your dataset in memory, try using generator function (since TF 2.1 you may pass generators directly to model.fit():
def dataset_generator():
     for i in range(len(dataset) - 3):
         yield dataset[i:i + 4]

Comment: it's my first time start a question. Could your see if i did it right?

tf.data.Dataset with stepping batches


On a piano scale what is considered "middle C"?

Question: I'm learning to play the piano and I'm slightly confused after reading this:
http://pianoscale.org/scales/root/c/major/
Is the 1st note in the treble clef the same as the 8th notes in the bass clef? And if so, is that considered to be "middle C" on a piano?
Also, wouldn't there typically be more notes in between the bass clef and treble clef? Why are they missing in this case? If they normally show up, then where is "middle C" on such a scale?
Answer: Here are two pictures that should explain everything.

To your question, "Also, wouldn't there typically be more notes in between the bass clef and treble clef? Why are they missing in this case?" I should explain that in typesetting sheet music, the amount of space between the treble and bass clef of the piano is variable, but the number of notes between them are not. More or less space can be put between the staves to allow for slurs or ties or other musical symbols or text, and to allow for the peculiarities of cross-staff notes and cross-staff beaming. Regardless of the visual appearance, technically there is only one ledger line between the staves, and on that line goes only the pitch C (or C# or Cb).
It should also be noted that the two staves are traditionally set up to separate the part played by the left hand from the part played by the right hand; the lower staff is for the left hand, the upper for the right. When the music requires both hands to be in the bass register, or both hands to be in the treble register, the two staves can use different clef signs (for instance two staves with treble clefs or two staves with bass clefs) or the notation "8va" or "8vb" can be put over certain notes to indicate that they are to be played an octave higher or lower than they appear on the staff.
When you see notes like the example below on the left, this is to indicate that the note below the treble staff is to be played with the right hand. The example on the right notates exactly the same thing, with exactly the same pitches, but using cross-staff beaming.

Here is an example from a Bach harpsichord concerto.

The two musical lines can cross from one staff to the other, but because of the cross-staff beaming and stem direction, and the lack of rests in the second measure in the bass staff, it's obvious that there are two lines played by two hands.
Comment: It is actually quite common to see more than one ledger line in the middle of a grand staff. As you mention, the staves are set up to separate the two hands, so when one hand needs to go into the other's territory briefly, it is done with multiple ledger lines. Extended passages would necessitate a change of clef.
Comment: The two examples represent the same notes but are not really equivalent.  The example on the right would, by more common conventions, indicate that the right hand was to play the D and the left hand was to play the A.  The alternative to cross-staff beaming would be for the treble cleff to contain an eighth-note D followed by a rest, and the bass cleff to contain an eight-note rest followed by an A.
Comment: Hmm. That's not how I interpret cross-staff beaming. I have always understood that because the two notes are beamed together, they are intended to be played by the same hand. See my extra example above.
Comment: The cross-staff beaming I take to indicate that the notes belong to a single *voice*, not necessarily to be played by a single hand. The fingering for contrapuntal pieces is driven by practical considerations (e.g., fluidity, articulation, voicing) more than theoretical ones and can be surprisingly and confoundingly tricky in some situations. (I realize this is an old thread, but I think the point is worth making.)
Answer: Yes, the first note on the upper staff is the middle C, as is the 8th note on the lower staff. The hands play one octave apart.
I'm not sure what you mean by "more notes in between the bass clef and treble clef", but what's written on the web page is standard. The middle C is always one line below the lowest line in treble clef, and one line above the highest line in bass clef. This can only be modified by using special notation such as an "8" above or below the clef symbol or on "8va" or "8vb" line above or below (respectively) the modified passage.
Answer: I explain it thus : originally music was written on 11 lines, with spaces (obviously) between. This roughly approximated the range of monks etc. voices.Trouble is, it wasn't easy to read notes written near the middle , so the lines were split into 2 lots of 5. This left the notes which lived in the middle line (C) without a line of their own.It didn't matter too much - middle C was not used any more than other notes, so when it did need to be written, it was given a little line of its own - a ledger line. Then, if playing keyboard type instruments in particular, any notes in the treble clef lower than middle C would have to have extra ledger lines, which actually doubled up the lines on the stave, but denoted them to be played with the right hand.And vice versa for left hand played notes that were higher than middle C.Hope this puts it all into place, Ein Doofus.
Comment: It's a nice way to put everything into place but AFAIK, when people started using "lines" (at least in Europe) at around 1000AD, only one was used instead of 11.
Comment: And would that line have been middle C ?
Comment: According to [this](http://voices.yahoo.com/origin-music-staff-4245925.html) it was F below middle C. There are some sources listed at the bottom.


Newton-Raphson Method used in a real engineering/physical/mathematical situation

Question: I've been using the Newton-Raphson Method in my Numerical Methods course for a while now, blindly solving non-linear equations and systems of equations . This makes me somehow lose motivation, as I can't manage to find a real problem in which this tool is applied .
Can anyone suggest such a problem in an engineering/physical or mathematical environment ? I'm interested in seeing a meaningful equation related to a possible problem and the motivation behind finding its roots.
Comment: The method solves the vast majority of all variable equations. The problem is *not* that they don't exist, you just are looking right past them. (equations make up 99% of physics and 1% of engineering (just kidding!))
Comment: I wasn't implying that such problems don't exist, it's pretty obvious this is not the case since they're teaching this method centuries later. I'm just saying that I haven't encountered such a situation on my own and I would like to see one . Feel free to make a suggestion :)
Comment: One powerful way to get nonlinear algebraic equations is from taking Fourier transforms of nonlinear differential equations. For instance, in my undergrad work I dealt with an equation like $(u_{xx} + a F(u) + b u)_{xx}=0$. In my setting $F$ was a nonlinear function. In Fourier space this is an algebraic equation $K^4 \hat{u} + K^2 a \hat{F}(\hat{u}) + K^2 b \hat{u}=0$. Here $K$, at least when dealing with a finite Fourier expansion (for a numerical approximation) is a diagonal matrix.
Comment: You can use them with Kirchhoff's Laws for electronics and for Triangulation for determining location.
Answer: Almost all engineering calculations involve solutions of nonlinear equations and, in a single steady state simulation, these are typically solved billions of times (in a dynamic simulation, zillions of time). Most of the time, these equations are solved using Newton-Raphson method (or higher order equivalents).
Just to give you a simple one, consider Colebrook equation $$\frac 1{\sqrt f}=-2\log_{10}\Big(\frac{\epsilon}{3.71D_h}+\frac{2.51}{Re \sqrt f}\Big)$$ in which $f$ is the friction factor, $\epsilon$ the roughness height, $D_h$ the hydraulic diameter and $Re$ the Reynolds number. This friction factor determines the pressure drop in a pipeline and I suppose that you perceive the impact of that when we speak about gas or oil pipelines.
Even if we know an explicit solution of this equation in terms of Lambert function, most of the time, this equation is solved using Newton method. But, in order to save iterations and ensure stability, we use to find proper transforms and "good" starting values. For example, changing variables $f=\frac 1{x^2}$ leads to $$\Phi(x)=x+2\log_{10}\Big(\frac{\epsilon}{3.71D_h}+\frac{2.51}{Re} x\Big)=0$$ Dozens of papers have been published proposing unexpensive ways for the generation of the initial estimate; these make the convergence of Newton method very fast to high accuracy.
More difficult is the case of Underwood equations $$\Phi(x)=\sum_{i=1}^n \frac {a_i}{b_i-x}-c=0$$ for which all the roots must be found ($n$ can be several hundreds). This equation is also solved zillions of time in chemical process simulations. Hundreds of papers addressed how to estimate the starting points, how to transform the equation to ensure proper convexity but by the end, Newton--Raphson does the job.
Simpler could look the next example : the key part of any process simulation is the thermodynamic model. In oil and gas industry, the most commonly used models are based on so-called cubic equations of state. Any single step in the calculation requires computing the real roots of a cubic polynomial. Because of limited precision, Cardano method is never used and again Newton.


Uninstall Vista update without being able to run Windows

Question: The PC of a friend will no longer boot into Windows (not even safe mode). I have recovered the crash dump file and run it through WinDbg. This indicates that the problem comes from WinInit.exe and the error is VISTA DRIVER FAULT
Also in my investigations I have found that 8 Windows upgrades were downloaded and installed the last time the PC booted OK, 5 of which were security updates. As the next step, I want to uninstall these updates but as I cannot boot into Windows I can't do it in the normal way.
I have tried using the restore points on the system, but there are non stored.
Is there any way I can revert or delete these updates only the drive in a seperate PC ?
Thanks
Paul
Answer: At this point it may well be quicker to do a repair install. Note you need a Vista DVD at the same or later service pack level to do this.
Answer: You need to use tools in DaRT (Diagnostic and Recovery Toolset), a part of Microsoft Desktop Optimization Pack.
Comment: The Hotfix Uninstall shows only 1 of the 8 hotfixes that were in the WindowsUpdate.log file. When I try to uninstall that one I get 'Failed. Error: Indicates two revision levels are incompatible'


Please explain rowspan and colspan, col and colgroup

Question: Can anyone explain rowspan and colspan, col and colgroup? And are these W3C valid and semantically correct? Under which circumstances are these useful?
Answer: colspan

    people are...

    monkeys
    donkeys

rowspan

    monkeys are...
    ... real monkeys

    ... 'unreal' monkeys (people...)

w3c
as you see, this is for connecting table-cells - and because this is sometimes neccessary, it's valid (RegDwights links will give more information...).
col/colgroup
colgroup and col are used to set attributes to every line in the table (so you don't have to write width="80" for the first td in every line(tr)):

  <colgroup>
    <col width="80">
    <col width="100">
    <col width="320">
  </colgroup>

    first line, first column
    first line, second column
    first line, third column

you can also group the cols, lets say the first and second column should get a with of 80, the third should get 320:

  <colgroup width="80" span="2"></colgroup>
  <colgroup width="320" span="1"></colgroup>

    first line, first column
    first line, second column
    first line, third column

Comment: added col/colgroup, hope this helps.
Comment: can we use width="80" ? isn't it deprecated
Comment: if i remember right, width is only deprecated for td, th, pre and... something else - but if you don't wand to use it, you can have the same effect by using stylesheets.
Answer: Yes, they are all recommended by W3C. Here are direct links to the documentation:

col
colgroup
colspan
rowspan
Answer: rowspan and colspan are attributes that allow the designer to 'merge' cells - much like the same command in Excel (for example).
col and colgroup allow the designer to apply css to a vertical column, rather than having to apply css to individual cells in a column. Without these, this task would be much more difficult as html tables are row-based.
All four of these are valid.
For future reference, try http://reference.sitepoint.com/html


Localizar aspas com espaços em branco com RegEx

Question: Preciso localizar erros em que dentro de aspas possuem espaços em branco no início ou no fim delas.
Exemplos de erros:

A notícia foi dada pelo " Jornal do Brasil".
Paris é considerada a "Cidade Luz ".

Reparem que, no primeiro caso, dentro das aspas, inicia com um espaço em branco, e no segundo caso, termina com um espaço em branco.
Quero retirar esses espaços em branco desnecessários, utilizando expressões regulares para apontar o erro.
Utilizei duas RegEx para isso:
" .*?"
".*? "

No primeiro, consigo apontar as aspas que começam com o espaço em branco, no segundo, quando termina.
Acontece que, existe um problema nessas expressões.
Exemplo:

Gosto das cores "azul" e "preto".

Observe que não existe nenhum erro na frase. As duas palavras "azul" e "preto" não começam e nem terminam com espaços em branco, mas, utilizando a expressão regular acima, ele acha um falso positivo no " e ".
Tentei de várias formas, mas meu conhecimento em expressões regulares ainda é muito pobre e não consegui corrigir esse erro.
Qual a ExpReg que devo utilizar nesse caso?
Muito obrigado!
Comment: @Kyllopardiun No meu entender, o exemplo da pergunta está correto. Mesmo porque nenhum falso positivo ocorreria se o `e` estivesse dentro das aspas.
Comment: @Kyllopardiun Não. A frase é assim mesmo. Com o **e** fora das aspas.
Comment: @mgibsonbr Exato.
Answer: O melhor que posso te sugerir é um regex que case a string como um todo. Pois o problema aqui é que uma análise local pode produzir resultados diferentes de uma análise global.
Minha tentativa de solução seria:
^[^"]*(?:"(?:[^"\s]|[^"\s][^"]*[^"\s])?"[^"]*)*$

Exemplo no Rubular. Explicação:

^ - início da string
[^"]* - seguida de zero ou mais caracteres que não são aspas (texto fora das aspas)
(?:...)* - seguido de zero ou mais de:

" - abre aspas
(?:...|...)? - com ou sem:

[^"\s] - um único caractere que não é aspas nem espaços; ou:
[^"\s] - um caractere que não é aspas nem espaços, seguido de
[^"]* - zero ou mais caracteres que não são aspas, seguido de
[^"\s] - um caractere que não é aspas nem espaços, seguido de

" - fecha aspas
[^"]* - zero ou mais caracteres que não são aspas (texto fora das aspas)

$ - fim da string

Explicando em linguagem natural, ela pega um trecho fora das aspas, depois um trecho dentro, um trecho fora, um trecho dentro, e assim por diante. Os trechos dentro de aspas podem ser de três tipos: a) vazias - ""; b) com um único caractere - "a"; c) com um caractere que antes e depois, e qualquer coisa no meio - "a...b".
Cabe notar que tudo o que essa regex fala é se a string é válida ou inválida: ela não consegue te mostrar em que caractere está o erro.
Atualização: se o que você quer é uma regex que case strings com erro - e te diga onde está o erro - isso foi o melhor que consegui fazer:
^[^"]*(?:"(?:[^"\s]|[^"\s][^"]*[^"\s])?"[^"]*)*("(?:\s[^"]*|[^"]*\s)")[^"]*(?:"(?:[^"\s]|[^"\s][^"]*[^"\s])?"[^"]*)*$

Exemplo no jsFiddle. Essa "monstruosidade" se resume a:
^ regex_original ("(?:\s[^"]*|[^"]*\s)") regex_original $

Ou seja: "case algo que está correto, seguido de algo que está incorreto, seguido de algo que está correto". Ela vai detectar um e somente um erro desse tipo - se a string tiver dois ou mais erros, ou se tiver uma aspa que abre mas não fecha, etc, a regex não vai conseguir pegar.
Creio que com um pouco mais de esforço se dê pra melhorar isso um pouco, mas estamos chegando no ponto em que regex já não é mais a ferramenta mais indicada para o trabalho...
Comment: @Dinho Atualizei a resposta. Não está perfeito, aliás é 99% de certeza que se você procurar você vai achar algum falso positivo ou negativo. Entretanto, estamos chegando no limite do que dá pra fazer "com sanidade" usando regex, de modo que *eu até posso* tentar melhorar mais, mas seria no sentido de "desafio de programação" e não "algo que eu usaria em produção"...
Comment: @Dinho No seu exemplo faltou o `$` no final, por isso os casamentos parciais. Quanto a apontar a parte com erro, não sei sequer se é possível, mas vou pensar um pouco, se conseguir algo posto aqui. (a razão pelo qual eu penso que *talvez* seja impossível é porque esse problema é muito parecido com o do "balanceamento de parênteses" - algo teoricamente impossível de se fazer somente com regex)
Comment: @Dinho Comigo também falhou nesse site. É estranho, pois quando ativo a flag "multiline" acontece isso que você falou (normal, pois ele está considerando o texto inteiro, não só linha por linha), mas quando desativo tudo para de funcionar!!! Não entendo por que...
Comment: Testei aqui e a princípio funciona, mas com esse código ele destaca o que está correto. Quero que ele faça justamente o inverso, aponte o que está errado.  Exemplo: http://www.regexr.com/39d0n Nesse link, tente corrigir o que está errado que você vai entender o que quero dizer...
Comment: Uau! hehehe! Testei pelo seu link no jsFiddle e funcionou tudo certo. Só não entendi por que não funcionou no RegExr e outros editores de expressões regulares que testei... Veja esse outro exemplo: http://www.regexr.com/39d16 Ele está indicando que a segunda frase (que não tem erro nenhum) está casando com a primeira que contém o erro. Experimente corrigir o erro da primeira frase, o destaque some. Por que será? Muito obrigado, amigo! Já ajudou demais! :D
Answer: Aqui fica uma sugestão, que funciona no texto que experimentei:
var texto = '" Jornal do Brasil". Paris é considerada a "Cidade Luz " Gosto das cores "azul" e "preto".';

var textoLimpo = texto.replace(/"([^"]*)"/g, function (match, r) {
    return '"' + r.replace(/^\s+|\s+$/g, '') + '"';
});
console.log(textoLimpo); // "Jornal do Brasil". Paris é considerada a "Cidade Luz" Gosto das cores "azul" e "preto".

Demo: http://jsfiddle.net/zg7otqv9/1/
No fundo divido o processo em duas partes. Primeiro isolando pedaços começando e acabando em " (aspas) e depois limpando um a um com r.replace(/^ | $/g, '').
A primeira parte /"([^"]*)"/g apanha tudo o que esteja entre duas aspas, ou seja, usando o [^"]* procuro tudo o que não tenha aspas, pois fecho a regex com ".
A segunda parte usa o sinalizador de inicio e fim de string (resp: ^ e $) e usando o alternador | no meio.
Comment: +1 só uma sugestão: use `\s+` em vez de um simples espaço, não só porque pega outros tipos de espaço em branco (como tabulações por exemplo) como também previne o caso em que há mais de um espaço nos limites das aspas. Ex: `Paris é considerada a "Cidade Luz      "`
Comment: @mgibsonbr boa dica. Corrigido. Dava-lhe outro `+1` se pudesse votar duas vezes :)
Comment: @Dinho, nesse caso sugiro que use/aceite a resposta do mgibsonbr.
Comment: @Sergio Gostei da alternativa, mas, não posso utilizar desse jeito. No programa que estou utilizando não existe nenhuma forma de utilizar programação, aceitando apenas RegEx. A ideia é, utilizar o RegEx apenas para apontar os erros sem fazer a correção.
Answer: Essa expressão pegará qualquer coisa dentro de aspas (inclusive as aspas).
Ex: "Isso não se faz"
"(.*?)(\w+)\b"


Python, Selenium - Scroll Google Maps

Question: Bom dia.
Estou desenvolvendo um Script python onde ele acessa o Google Maps e pesquisa determinada loja e coleta os dados dela através do XPATH //[@id="pane"].
Porém o Google Maps carrega a lista de lojas dinamicamente (eu acho), então ele pega no máximo até o 7 //[@id="pane"], após isto ele não consegue visualizar os demais.
Através de pesquisa localizei algumas soluções como por ex.:
browser = webdriver.Chrome('chromedriver.exe', options=self.browserProfile)
brownser.get('your url here')
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")

ou
driver.get("https://www.google.com/maps/place/Bengaluru,+firstname.lastname@example.com,77.4908522,11z/data=!4m5!3m4!1s0x3bae1670c9b44e6d:0xf8dfc3e8517e4fe0!8m2!3d12.9715987!4d77.5945627")
option = driver.find_element_by_xpath("//div[@class='hNLpDc-HiaYvf-DWDkFd-HiaYvf-haAclf']")
driver.execute_script("arguments[0].scrollIntoView(true);",option)

Porém mesmo alterando ele não funciona, ele pula para a condição final e nem mesmo apresenta erro.
Saberiam me informar se existe algum modo de selecionar a lista do google maps e fazer scroll dela até o final ?
Obrigado.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Segue uma função para rolar página até o final:
def scroll_page(self):
    SCROLL_PAUSE_TIME = 0.5
    last_height = self.webdriver.execute_script("return document.body.scrollHeight")
    while True:
        # Scroll down to bottom
        self.webdriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)
        # Calculate new scroll height and compare with last scroll height
        new_height = self.webdriver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

Python, Selenium - Scroll Google Maps


Assigning a a sequence number to dictionaries in a list

Question: I have written a django query like this.
stud_record = Student.objects.filter()

Thus stud_record is a queryset.
Now what I want to do is, i want to calculate the total num of stud_record, and then divide it by 5.
For ex: I have 20 records in stud_record. After dividing by 5 I got 4 each. So now i want to rank the first four students as ran 1, then from 5-8 students as rank 2....16-20 students as rank 5. This rank will be inserted to the same stud_record and will be send to the template page.
How can we do it.
Currently I am getting the structure like this
[{'name': u'mark', 'roll': 71},
 {'name': u'robin', 'roll': 42},
 {'name': u'julien', 'roll': 39}]

After division and inserting the rank it should look like
[[{'name': u'mark', 'roll': 71, 'rank': 1},
  {'name': u'robin', 'roll': 42, 'rank': 1},]
 [{'name': u'julien', 'roll': 39, 'rank': 2}]]

Right now I am getting 185 results in my stud_record. After dividing 185/5 i am getting 37 as result. Now i want to give rank 1 to 1-37 students, then rank 2 to 38-75 students... like this
Comment: what should the result be if there are 21 student records?
Comment: 1-5 rank1, 6-10 rank 2....15-21 rank 5
Comment: 1-5:1, 6-10:2...15-21:5, and how do you split up the 11-14 between 3 and 4?
Answer: Try using Len(stud_record). This will get you the number of student for that queryset. Then play around with division and modulo to get your desired range of student. Sorry I can't give you a definite solution for the laptop I'm currently using is not installed with a Python program. Hope this helps :)
Comment: Yeah i am getting the total count for stud_record. But not getting the logic how to assign the ranks depending upon the division results...;(
Answer: You contradict yourself  in the question on what you want. Your example code of what you want has one list of students, each with a rank. But you say you want to assign the same rank to all students in a sublist. That's two different things.
For giving an order number for each record in a list do this:
for rank, student in enumerate(student_list):
    student['rank'] = rank

For giving the same rank to all records in a sublist you can do this:
for rank, student_list in enumerate(all_students):
    for student in student_list:
        student['rank'] = rank

But this last thing is surely easier, even completely trivial, to do when you are splitting the main list into sub_lists, not afterwards.
Do that for each of the sublists you have created.
Also don't insert it into stud_record, instead add the results to the context. In a class-based view you can do it like this:
def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(KlassDetailView, self).get_context_data(**kwargs)
    # Add data to the context:
    stud_record = Student.objects.filter()
    context['stud_ranks'] = calculate_ranks(stud_record)
    return context

Now you have the 'stud_ranks' variable available in the template.
Comment: Yeah this is right, but how can i assign first 1-4 students as rank 1, then the next set of students as rank 2 etc..
Comment: I guess this is a method u r invoking here. What should be its definition.
Comment: @sandeep: Also note that your title is completely misleading, if your main question is how to assign ranks. I will change it.
Comment: You have modified the title, that is absolutely fine, no issues. Now i just want to know what should be the definition of calculate_ranks()
Comment: Sorry, but i am bit confused. Right now i am getting 185 results in my stud_record. After dividing 185/5 i am getting 37 as result. Now i want to give rank 1 to 1-37 students, then rank 2 to 38-75 students... like this
Comment: @sandeep: You are very unclear of what you want in the question. I'll update.
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/23197/discussion-between-sandeep-and-lennart-regebro)
Answer: I would go like this
iter=0
for item in sorted(stud_record, key=lambda x:x['roll']):
    item['rank'] = math.floor(iter / 5) + 1)
    iter+=1

You sort your items by 'roll', and assign a 'rank' field that is observing repartition in five bins.
Comment: In the `__future__`, this division will result in a float. So it is better to `math.floor(iter / 5) + 1)`.
Answer: Add ranks to your dicts first and then group them using itertools.groupby:
from itertools import groupby

lst = [{} for _ in range(21)]  # simple testlist

def rank_it(lst,n):
    for index,d in enumerate(lst):
        rank = index/(len(lst)/n)+1
        d['rank'] = rank if rank < n else n

rank_it(lst,5)  #  add ranks
[list(g) for _,g in groupby(lst, lambda x: x['rank'])]  #group by rank

out:
[[{'rank': 1}, {'rank': 1}, {'rank': 1}, {'rank': 1}],
 [{'rank': 2}, {'rank': 2}, {'rank': 2}, {'rank': 2}],
 [{'rank': 3}, {'rank': 3}, {'rank': 3}, {'rank': 3}],
 [{'rank': 4}, {'rank': 4}, {'rank': 4}, {'rank': 4}],
 [{'rank': 5}, {'rank': 5}, {'rank': 5}, {'rank': 5}, {'rank': 5}]]

NB! This solution needs the list to be sorted, if its not, add:
lst.sort(key=lambda x: x['roll'],reverse=True)


Get File Path of a System.Drawing.Bitmap

Question: Is there a way to get the File Path of a System.Drawing.Bitmap Type?
Something like:
My.Resources.myImg.GetFilePath Or
GetFilePath(My.Resources.myImg)
Obviously my above example does not exist. I am just showing my intention.
Comment: In general, a bitmap is an object in memory. It may not have been read from a file, so it doesn't necessarily have a file path.
Answer: I'm not so sure the resources has a path, I think they're embedded in the application and then read into the memory (I could be wrong however).
If you want them to have a path you'd have to save them to a file. This saves the image in the Local Application Data folder:
Dim MyImgPath As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "myImg.bmp")
My.Resources.myImg.Save(MyImgPath, Imaging.ImageFormat.Bmp)

If you want to save the image in the same folder as your application:
Dim MyImgPath As String = IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory(), "myImg.bmp")

Comment: @Chris : The `My Project\Resources` folder won't exist _after_ you've compiled the application. As far as I'm aware you need to write the resources to a file.
Comment: I actually do have the file in my `Resources` folder and could hard code it. That's kind of what I am trying to avoid. The problem is I'm working with someone else's function that expects a string.
Comment: Try taking out only the .exe and run it on another computer. You will still have the images although you have not copied any images with it. Your `Resources` folder won't matter after you've compiled the application, so in order to get a file path from an image: save it every time you need it.
Comment: I have the resource set to copy to output directory. I know this isn't the best way to do it but the existing code base I am working with has functions I am not aloud to touch that take strings as parameters for image paths. Right now they have it dependent on a network resource. I am just trying to create a local fallback that is just a tiny bit more dependable than a file on a network
Comment: @Chris : If you set the resource to `Copy to output directory` then why do you have it as a resource? Use either or, or else you'd have one embedded image and one image saved on disk. In order to simply move your app around, I'd recommend to use the image as a normal resource (`My.Resources`) and then writing it to the disk when needed (as shown above).
Answer: You might want to create your own object:
Public Class MyBitmap
Inherits Bitmap

Private _FilePath As String
'------------------------'

Public Property FilePath as String
Get
Return _FilePath
End Get

' etc...

The you could set the path and get it later on from the property
Comment: That won't do for resources though. Besides, you don't need `Private _FilePath As String`, you only need this line: `Public Property FilePath as String`.
Comment: You might be right on this one, but I think it's better to have the variable in the class itself, too.
Comment: It doesn't actually make much of a difference unless you use ReadOnly properties or custom actions when setting/getting, otherwise they're both the same. The compiler creates the variable for you if there is none, anyway. :)
Comment: Yeah but I learned it that way in Java at school and got a habit out of it.
Comment: Y'know old habits die hard
Comment: It's okay to do that, I didn't say that :). It's just... unnecessary... for VB.NET. (:
Answer: Pretty sure this isn't possible as there's quite a few ways to init a System.Drawing.Bitmap (e.g: Stream, Uri, another image object) and this Bitmap is a very generic object.
Depending on the technology you're using, there may be a more specialized image type that's better to use. For example, if you're using WPF, check out BitmapImage which does store the file path as the property UriSource.
If you really need to work with System.Drawing.Bitmaps, I'd recommend creating a model that houses both the bitmap and the file path. Like this:
{
    public Bitmap MyImage {get; set; }
    public string FilePath {get; set; }
}


Views - Wrapper Fields in DIV after ROW class

Question: Have this:

And need this:

Answer: If you start editing your view, on the right side under the advanced options you will find Theme: information. You will see the currently used template files and the candidate files.
My solution would be to overwrite the default template files with your own. That way you could simply add a wrapper around $rows.