Basis of topological space and topological subspace

Question: This topics is a continuation of this Basis of topological space. I rewrite the most important theorem:

Theorem. Let $(X, \mathcal{G})$ a topological space.
$(i)$ Let $\mathcal{B}\subseteq\mathcal{G}$ a basis of $(X,\mathcal{G})$. Then,
$(a)$ $\mathcal{B}$ is a coverage of $X$;
$(b)$ for each $B_1,B_2\in\mathcal{B}$, $B_1\cap B_2\ne\emptyset$ and for each $x\in B_1\cap B_2$ exists $B\in\mathcal{B}$ such that $x\in B\subseteq B_1\cap B_2$.
$(ii)$ Let $\mathcal{B}\subseteq \mathcal{P}(X)$ a family of nonempty set for which they are valid $(a)$ and $(b)$, then exists a unique topology $\mathcal{G}$ on $X$ of which $\mathcal{B}$ is basis.

$$$$

Proposition 1.
  Let the family set
  $$
\tilde{I}:=\{(a,b)\;|\;-\infty<a<b<+\infty\}\subseteq\mathcal{P}(\mathbb{R}).
$$
  The family $\tilde{I}$ is a basis of a single topology on $\mathbb{R}$.
proof. This proof was addressed in the previous topics. Verifying the properties $(a)$ and $(b)$ of the theorem.

The topology on $\mathbb{R}$ of which $\tilde{I}$ is basis we denote it with $\tau(\mathbb{R})$.
$$$$

Proposition 2. Let the family set $$\overline{I}:=\{(a,b)\;|\;-\infty<a<b<+\infty\}\cup\{[-\infty,b)\;|\;-\infty<b<+\infty\}\cup\{(a,+\infty]\;|\;-\infty<a<+\infty\}\subseteq\mathcal{P}(\mathbb{\overline{R}}).$$
  The family $\overline{I}$ is a basis of a single topology on $\mathbb{\overline{R}=\mathbb{R}\cup{\{\pm\infty\}}}$.
proof. If $x\ne\pm\infty$, we proceed as in the Proposition 1. Otherwise if $x=+\infty$, we consider $(x-\epsilon,+\infty]$, where $\epsilon>0$. In the same way if $x=-\infty$. Therefore the property $(a)$ of the theorem is verified.
  How can I proceed to check point $(b)$?

The topology on $\mathbb{\overline{R}}$ of which $\overline{I}$ is basis we denote it with $\tau(\mathbb{\overline{R}})$.
$$$$

Proposition 3. Let the family $$V=\{B(x_0,r)\;|\;x_0\in X,r>0\}\subseteq\mathcal{P}(\mathbb{R}^n),$$
  where $B(x_0,r)=\{x\in\mathbb{R}^n\;|\;d(x_0,x)<r\}$, and $d$ is the Euclidean distance.
proof If $x\in\mathbb{R}^n$, we consider $B(x,r)$. Then $x\in B(x,r)$, therefore the property $(a)$ is verified. How can I proceed to check point $(b)$?

Another question: why $\tau(\mathbb{\overline{R}})\cap \mathbb{R}=\tau(\mathbb{R})$? From here how can I conclude that the topological space $(\mathbb{R},\tau(\mathbb{R}))$ is a topological subspace of $(\overline{\mathbb{R}},\tau(\mathbb{\overline{R}})$?
Thanks in advance!
Answer: For Proposition two you will have to break the proof into cases. Given the candidate basis $\bar{I}$ you have described you need to consider $U,V\in\bar{I}$ and $x\in U\cap V$. You need to show that there is some $W\in\bar{I}$ such that $x\in W\subseteq U\cap V$. However, you have several different possibilities for the nature of $U$ and $V$.
Case 1: $U,V\in\tilde{I}$. In this case $U$ and $V$ are both bounded open intervals and you say that you've shown that there if $x\in U\cap V$ then there is another open interval $W\in\tilde{I}$ such that $x\in W\subseteq U\cap V$. Because $\tilde{I}\subseteq\bar{I}$ there is then nothing to be done.
Case 2: $U\in\tilde{I}$ and $V\in\bar{I}\setminus\tilde{I}$. Say without loss of generality that $U=(a,b)$ and $V=(c,\infty]$ (the case where $V=[-\infty,c)$ is similar and we won't consider it here). If $x\in U\cap V$ then $a<x<b<\infty$. Then letting $d=\max\{a,c\}$ we have that $x\in(d,b)$. Setting $W=(d,b)$ we see that $x\in W\subseteq U\cap V$ and $W\in\bar{I}$.
Case 3: $U,V\in\bar{I}\setminus\tilde{I}$. Technically this case splits into two further cases but we will only consider the case where $U=[-\infty,b)$ and $V=(a,\infty]$ for the simple reason that I don't want to write out the other case. Now if $x\in U\cap V$ then $a<x<b$. Thus, setting $W=(a,b)$ we have that $W\in\bar{I}$ and $x\in W\subseteq U\cap V$.
I'm assuming that you can fill in the cases that I ignored.
Regarding Prop 3 you will have to wield the triangle inequality.
Let $y,z\in\mathbb{R}^{n}$ and $\epsilon,\delta>0$. Define $U=B(y,\epsilon)$ and $V=B(z,\delta)$. Assume that $x\in U\cap V$. Then, by definition $d(x,y)<\epsilon$ and $d(x,z)<\delta$. Say $\eta_{1}=\epsilon-d(x,y)$ and $\eta_{2}=\delta-d(x,z)$. Define $\xi=\frac{1}{2}\min\{\eta_{1},\eta_{2}\}$. We claim that $W:=B(x,\xi)$ is such that $x\in W\subseteq U\cap V$. It is clear that $x\in W$. Assume that $x^{\prime}\in W$. Then $d(x,x^{\prime})<\xi$. By the triangle inequality we then have that
$$d(x^{\prime},y)\leq\eta_{1}+\xi<\epsilon$$
$$d(x^{\prime},z)\leq\eta_{2}+\xi<\delta$$
Thus $x^{\prime}\in U\cap V$.
I'm not going to expound on your last question. I will simply give you the hint that you know that $\mathcal{T}(\mathbb{R})\subseteq\{U\cap\mathbb{R}\mid U\in\mathcal{T}(\bar{\mathbb{R}})\}$. You then need only show that if $U\in\mathcal{T}(\bar{\mathbb{R}})$ then you need to show that you can write $U\cap\mathbb{R}$ as a union of bounded open intervals.
Let's now show that $\mathcal{T}(\mathbb{R})=\mathcal{T}(\bar{\mathbb{R}})\cap\mathbb{R}$. We will do this directly.
Let $U\in\mathcal{T}(\mathbb{R})$. Then $U=\bigcup_{\alpha\in A}(a_{\alpha},b_{\alpha})$ where $a_{\alpha}<b_{\alpha}$ for each $\alpha\in A$. That is $U$ is a union of elements of $\tilde{I}$. Because $\tilde{I}\subseteq\bar{I}\subseteq\mathcal{T}(\bar{\mathbb{R}})$ we have that $U\in\mathcal{T}(\bar{\mathbb{R}})$. Now we can determine:
$$U\cap\mathbb{R}=\left(\bigcup_{\alpha\in A}(a_{\alpha},b_{\alpha})\right)\cap\mathbb{R}=\bigcup_{\alpha\in A}[(a_{\alpha},b_{\alpha})\cap\mathbb{R}]=\bigcup_{\alpha\in A}(a_{\alpha},b_{\alpha})=U$$
Therefore $U\in\mathcal{T}(\bar{\mathbb{R}})\cap\mathbb{R}$ and hence $\mathcal{T}(\mathbb{R})\subseteq\mathcal{T}(\bar{\mathbb{R}})\cap\mathbb{R}$.
Now we will show that $\mathcal{T}(\bar{\mathbb{R}})\cap\mathbb{R}\subseteq\mathcal{T}(\mathbb{R})$. To do this we, as you did in the comments, take $V\in\mathcal{T}(\bar{\mathbb{R}})$. Noting that $V=\bigcup_{\beta\in B}W_{\beta}$ where $W_{\beta}\in\bar{I}$ for each $\beta$. Now, note that we have the following:
$$V\cap\mathbb{R}=\left(\bigcup_{\beta\in B}W_{\beta}\right)\cap\mathbb{R}=\bigcup_{\beta\in B}(W_{\beta}\cap\mathbb{R})$$
Because $\mathcal{T}(\mathbb{R})$ is closed under arbitrary unions it will then suffice to show that $W\cap\mathbb{R}\in\mathcal{T}(\mathbb{R})$ for each $W\in\bar{I}$ (Exercise: Why is that?). We then consider our various cases. If $W=(a,b)$ where $a,b\in\mathbb{R}$ and $a<b$ then $W\cap\mathbb{R}=W$ which is an element of $\tilde{I}$ which is itself a subset of $\mathcal{T}(\mathbb{R})$ yielding $W\in\mathcal{T}(\mathbb{R})$. We then consider the case where $W=(a,\infty]$ for some $a\in\mathbb{R}$. In this case we have
$$W\cap\mathbb{R}=(a,\infty)=\bigcup_{n\in\mathbb{N}}(a,a+n)$$
Each open interval $(a,a+n)$ is in $\tilde{I}\subseteq\mathcal{T}(\mathbb{R})$, so $W\cap\mathbb{R}=\bigcup_{n\in\mathbb{N}}(a,a+n)$ is an element of $\mathcal{T}(\mathbb{R})$. The final case is where $W=[-\infty,a)$ where $a\in\mathbb{R}$, however this case is very similar to the previous one.
We then have that $W\cap\mathbb{R}\in\mathcal{T}(\mathbb{R})$ for each $W\in\bar{I}$. Therefore if $V=\bigcup_{\beta\in B}W_{\beta}$ is an element of $\mathcal{T}(\bar{\mathbb{R}})$ where $W_{\beta}\in\bar{I}$ for each $\beta$ then as shown above $V\cap\mathbb{R}=\bigcup_{\beta\in B}(W_{\beta}\cap\mathbb{R})$. We just showed that each $W_{\beta}\cap\mathbb{R}$ is an element of $\mathcal{T}(\mathbb{R})$ and $\mathcal{T}(\mathbb{R})$ is closed under arbitrary unions so $V\cap\mathbb{R}$ is an element of $\mathcal{T}(\mathbb{R})$. Therefore, $\mathcal{T}(\bar{\mathbb{R}})\cap\mathbb{R}\subseteq\mathcal{T}(\mathbb{R})$, establishing equality.
Apologies for being verbose, but I wanted to be thorough.
Comment: I will edit my answer with some help.
Comment: Let me know if you have questions with my edited answer.
Comment: That is correct.
Comment: @RobertThingumThanks for your answer. If $U\in\tau({\overline{\mathbb{R}}})$, then $U=\cup_{i\in I}B_i$, where $\{B_i\}\subseteq\overline{I}$. Therefore $U\cap\mathbb{R}=\cup_{i\in I}(B_i\cap\mathbb{R})$. Then $\tau(\mathbb{R})\supseteq\{U\cap\mathbb{R}\;|\;U\in\tau(\overline{\mathbb{R}})\}$. Therefore $\tau(\mathbb{R})=\{U\cap\mathbb{R}\;|\;U\in\tau(\overline{\mathbb{R}})\}:=\tau(\overline{\mathbb{R}})\cap\mathbb{R}$. Correct?
Comment: I appreciate your patience
Comment: if we show that $W\cap\mathbb{R}\in\mathcal{T}(\mathbb{R})$ for each $W\in\overline{I}$, then chosen any set $C$ of indices $\cup_{\gamma\in C}(W_{\gamma}\cap\mathbb{R})\in\mathcal{T}(\mathbb{R})$.


Flickrapi e fotos de um usuário específico com Python

Question: Olá, pessoal, tudo bem?
Preciso pegar algumas fotos de um usuário específico do FLICKR e com uma descrição específica para um trabalho de faculdade.
Ainda estou aprendendo a programar, então não sei muito bem como fazer, tentei ler as orientações de API, mas não entendi bem. O máximo que consegui baixar foram algumas fotos com uma "keyword" específica, mas o conteúdo não bate exatamente com o que preciso. Tentei colocar várias keywords ou tentar adicionar o nome da fotógrafa, mas não consegui baixar nenhuma foto.
Acredito que resolveria o problema se eu puxasse apenas as fotos de um usuário específico com a descrição que preciso, é possível fazer isso com o flickrapi ou outra api?
#id da marcozeroconteudo: 152991702@N05
Aqui envio um exemplo de foto que preciso baixar. E as descrições do texto são essas:

Marco Zero Conteúdo Suape,16 de agosto de 2018. Estaleiro Atlantico
Sul. Crédito: Keila Castro/MZ Conteúdo
As tags dela são: Suape, Estaleiro, Atlantico Sul

import flickrapi
import urllib
import urllib.request
from PIL import Image
from tqdm import tqdm
from keras.preprocessing.image import ImageDataGenerator

# image.load_img()
#id da marcozeroconteudo: 152991702@N05

# Flickr api access key
flickr=flickrapi.FlickrAPI('MINHA_API_KEY', 'MINHA_API_SECRET', cache=True)

N_MAX = 500
keyword = 'Estaleiro Altantico Sul'

PHOTOs = flickr.walk(text=keyword,
                     tag_mode='all',
                     tags=keyword,
                     extras='url_c',
                     per_page=108,           # may be you can try different numbers..
                     sort='relevance')

urls = []
for N, PHOTO in tqdm(enumerate(PHOTOs)):

    url = PHOTO.get('url_c')
    urls.append(url)

    # get 50 urls
    if N > N_MAX:
      break
print (urls)

# Download image from the url and save it to '00001.jpg'
#urllib.request.urlretrieve(urls[0], '00001.jpg')
RESIZE_OPTION = Image.ANTIALIAS #Image.NEAREST, Image.BICUBIC

for i in range(N_MAX):
  fname = f'img_{keyword}{i}.jpg'
  urllib.request.urlretrieve(urls[i], f'img{keyword}_{i}.jpg')
# Resize the image and overwrite it

image = image.open(fname)
image = image.resize((256, 256), RESIZE_OPTION)
image.save(fname)

Agradeço desde já pela ajuda,
Answer: Reaproveitando seu código
Importando as bibliotecas necessárias:
import flickrapi
import urllib.request
from PIL import Image

Autenticação:
api_key = u'API_KEY' # passando em formato unicode
api_secret = u'API_SECRET' # passando em formato unicode
flickr = flickrapi.FlickrAPI(api_key, api_secret, cache = True)

Tags que serão buscadas:
tags = ['Suape', 'Estaleiro', 'Atlântico Sul']
photos = flickr.walk(tag_mode='all',
                     tags = tags,
                     extras='url_c',
                     per_page=100)

Pegando as urls, neste caso só insiro as com 65535, que é um padrão da url do usuário que você deseja pegar as imagens:
urls = []
for i, photo in enumerate(photos):
    user = '65535'
    try:
        url = photo.get('url_c')
        if user in url:
            urls.append(url)
    except:
        pass

Baixando as imagens e salvando no diretório em que o script está sendo executado:
for i, url in enumerate(urls):
    try:
        name = str(i) + '.jpg'
        urllib.request.urlretrieve(url, name)
        image = Image.open(name)
        image = image.resize((256, 256), Image.ANTIALIAS)
        image.save(name)
    except:
        pass

Removi a api_key e secret ja que a pergunta foi atualizada para não prejudicar o autor da pergunta.


Flux returns unsorted data for StepVerifier

Question: I expect to receive two elements after writing three to the database. The query returns a Flux, which returns the elements unsorted.
@Test
fun `SUCESSFULLY query pending purchases`() {
    // arrange
    val arrived = TestDataFactory.buchungssatzEntity(
        sequentialId = 1,
        arrived = true
    )

    val pending = TestDataFactory.buchungssatzEntity(
        sequentialId = 2,
        arrived = false
    )

    val next_pending = TestDataFactory.buchungssatzEntity(
        sequentialId = 3,
        arrived = false
    )

    // act
    buchhaltungWriter.save(arrived)
    buchhaltungWriter.save(pending)
    buchhaltungWriter.save(next_pending)

    val purchases = inventoryFinder.findAllPendingPurchases()

    // assert
    StepVerifier.create(purchases)
        .expectNext(pending)
        .expectNext(next_pending)
        .verifyComplete()
}

This always throws

expected value: BuchungssatzEntity(... sequentialId=2 ...); actual value: BuchungssatzEntity(... sequentialId=3 ...)

I do not want to add sorting to the database query, it's a waste of time. How can I test Flux with 'all of these elements but in any order' or should I just go for a Mono in this case, return a list and do the rest myself? Then again, that's not why I'm using reactive.
PS: Goal of this test is to verify that my Spring query language statement filters correctly.
-------- UPDATE
I solved it by using
StepVerifier.create(inventoryFinder.findAllPendingPurchases())
    .recordWith { listOf<PurchasesModel>() }
    .thenConsumeWhile { i: Any? -> purchases.contains(i) }
    .consumeRecordedWith{ }
    .verifyComplete()

Comment: any query to any database is never guaranteed any order unless you provide a `ORDERED BY` so never assume that the data is going to be retrieved as you inserted it.
Comment: I know, what's why I'm asking how I can properly test that in a reactive env
Answer: One way to do that is to use the thenConsumeWhile operator along with expectNextCount. If there is any element in the sequence that doesn't match, the StepVerifier will error.
In Java:
List<Item> pendingItems = List.of(pending, next_pending);

Flux<Item> items = inventoryFinder.findAllPendingPurchases();

StepVerifier.create(items)
        .expectNextCount(2) //expecting 2 elements
        .verifyComplete();

StepVerifier.create(items)
        .thenConsumeWhile((i) -> pendingItems.contains(i)) // check if element was expected
        .verifyComplete();

Comment: That does not work : / Fails with the same error message, I guess it's expecting it to arrive in the same order. So your solution seems to be exactly mine but you're passing a list instead of two explicit `next` calls
Comment: @nykon You are right, I have updated my answer.
Comment: It's still not working but I get the idea. Now I get a `expected: onComplete(); actual: onNext(BuchungssatzEntity(id=c637` but I think the direction is the right one
Comment: @nykon Could you post your code? You are expecting three elements, so you should have `.expectNextCount(3)`
Comment: Sorry for the delay - current code can be found here: https://github.com/rainerknabenbauer/ecommerce-bay/blob/main/backend/src/test/kotlin/de/einsupershop/ecommerce/inventory/dao/InventoryFinderTest.kt
Comment: Change ` StepVerifier.create(purchases)
            .expectNextCount(2)
            .verifyComplete()` to ` StepVerifier.create(purchases)
            .expectNextCount(3)
            .verifyComplete()`
Comment: You are expecting 3 elements.
Comment: I'm expecting 2 elements - behind 'findAllPendingPurchases()' is a Spring Query Language statement `return buchhaltungRepository.findByArrivedFalse()` which will return only arrived = false => 2 elements. That's what all this is about, verifying that it returns two elements.
Comment: Btw this query does work. The orders are being displayed in the UI accordingly. I just cannot possibly write a test for that, that drives me nuts.
Comment: Try to  .log() the chain to find out what the additional element is.
Comment: What did work was

StepVerifier.create(contentBuilderService.getActiveClinics())
            .recordWith { listOf() }
            .thenConsumeWhile { i: Any? -> clinics.contains(i) }
            .consumeRecordedWith{ }
            .verifyComplete()


ReTagging Questions

Question: I have a few questions regarding changing tags from "magento-1.7" to "ce-188.8.131.52"

Should we always do it for new questions? - I guess the answer here is yes,
Should we do it for old questions or at least add the new ce style tag? - If so when do we stop?
Should we always ask for clarification of magento version when someone asks a questions?
Is there a way to migrate tags?
Answer: yes, yes, it's always up to author and it is highly recommended to precisely specify the version however nobody should be forced to.
Comment: I agree with not forcing people to add a version.
Answer: David, first: thanks for heading to meta to ask this questions! I'd like to think I sort of helped prompt it since I rejected some of your tag edits. Sorry! :/
I think that we really need to settle on tags used to indicate versions, and then migrate the deemed old tags as appropriate. I'm not sure if there is a way for anyone (maybe mod only) to retag all questions from one to another, but there is a way to mark a tag as an alias of another.
As they are relevant, here are two links to meta questions where version tags came up fairly early on:

Does magento-1 tag make any sense?
How should we manage magento versions?

Something pointed out by Tim in a comment on the 2nd post…

If you specify a ce-1.3 tag people will ask you for a clarification. because different versions of 1.3.x.x (and 1.4.x.x also) have significant changes.

In comments on an answer further down the same page…

People obsess with all the dots because the bruhaha around 1.4.2 or 1.4.3 or whatever it was when the magento-verse passed too close to a dwarf star and altered course forever. 1.7 is 1.7 and that's about all that's needed since 1.5. A better tag would be to highlight BIG and dangerous changes between versions; major or minor

I will point out a few things:

There are major differences between EE 18.104.22.168 and EE 126.96.36.199 in the Mage_PayPal module. We (re)discovered this when we recently launched our PayPal providing saved credit card functionality atop the original integration. It made a big difference because the config system for the base totally changed (and to top things off you can't specify minor release in EE compatibility on Connect) — The same (I believe) goes for CE 18.104.22.168 as compared to CE 18.104.22.168
We all know that CE 1.8 was just released, and with the release some stuff included in the alpha was removed due to issues which have been being ironed out in the EE 1.13 core as it's been deployed into production environments. This is all fine and dandy, until these changes pulled from the initial 1.8 release are henceforth included in the CE 184.108.40.206 release as I expect them to be.

Both of the above are examples of continued usefulness of having the full version number be used in tags. Once 1.8.1 is released (and assuming the plans don't change) I would expect questions will start being asked about URL key related changes…and if you specify only 1.8 it will not be clear to readers which version the OP is using or asking about, but will make a difference as far as the solution goes.
I am personally fine with longer tags like "magento-1.x" but also see the merit of using shorter tags which include the full version. Or more correctly stated, I see including the full version number as necessary. Maybe we should try and encourage including both a generic major release number tag as well as a minor release version tag.
For now though, the "magento-1.x" tags have had their descriptions changed (for quite a while now) to read something like this:

This tag is redundant and shall not be used. Please use ce-1.7.x.x tag instead.

If we decide to "reopen" the magento-1.x" tags for use, then I'm totally fine with it. However, if a user tags a question with a specific version number, I would much prefer to see the generic tag added as opposed to replace the original and more specific tag.
To answer the question about whether or not there are methods to migrate tags: I believe there are ways as I see evidence of such on the tag synonyms page, but I'm not sure all users can do so. But, all users can suggest synonyms for tags here: https://magento.stackexchange.com/tags/synonyms
Comment: No need to be sorry without someone forcing me to stop and think about the tags I would have +2ed my way to 1k ;)
Answer: I've noticed a lot of users making these 'edits'. I agree with Tim that it's better to be precise in specifying the version but as for the moment the magento-1.7 tag is user 3 times more than the ce-18.104.22.168 tag.
Instead of phasing out either one of the tags perhaps the best thing would be to 'improve' the edit by adding them both when a users requests to replace one for the other?
Answer: So since I raised the question I will add my opinion/answer to the list :)
We deal with a wide variety of users which means we have a wide range of knowledge on this site. I would always suggest to make it as easy as possible for the lowest level of knowledge to get something out of this site. (Not that I am saying that a wrongly tag version would stop an answer).
So If I was a non developer and just a shop owner that had a problem maybe I would not know what version I have or if it was community or enterprise, it could happen. So where would I find this version number, well I would put forward that they would look in the admin area. In the admin section footer of community it looks like the following:
Magento ver. 126.96.36.199

So maybe the magento tag would be best suited for all. Just an opinion happy for everyone else's ideas :)

ReTagging Questions


How can I hide revision information on node forms?

Question: Trying to figure out how to hide revision information from node form. When users create a node, they see revision info at the bottom which confuses them.
I can't seem to disable revision info from the content type edit settings since there are nodes already. So the only solution is to hide it.
The way that I am going is by trying to add this:
<code>$form['revision_information']['#access'] = false;
</code>
My question is how can I add that to my theme-name.theme file?
The content type is QUESTIONS
Comment: If the theme you are talking about is the admin theme, you can add it in that file with hook_form_alter.
Comment: No it is not the admin theme.
Comment: If the node creating/editing is under the admin theme, then adding it in any other theme file won't have an effect. If the theme you are editing is the one used by this, then you can add it to the .theme file with hook_form_alter.
Comment: It is a custom bootstrap theme. Adding that line directly to the mytheme.theme file made no difference. Can form altered via mytheme.theme file or does it have to be with a custom module?
Answer: Please try below code in your theme-name.theme file.
<code>/**
 * Implements hook_form_alter().
 */
function THEMENAME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['revision_information']['#access'] = FALSE;
}
</code>
Answer: There also is the Hide Revision Field module which makes the revision info another field you can disable in the form mode of an entity. It also gives you some more options, like permission based display etc.

Hide Revision Field provides a configurable field formatter for the
revision log field for revisionable entities. This allows you to
create revisions but reduces noise for your content editors/site
owners. All revisionable entity types are supported including module
added.
Answer: When you create a new content type you have the option to not create new revisions. Whilst you can set that for future content any existing nodes will still have revisions on. If there are not too many to change you could manually uncheck this or write a script in the database to uncheck them.
Answer: Try hiding it using css:
<code>.field--name-revision-log-message {
  display: none;
}
</code>
I used this for media.


Three random points in a cube

Question: Select three points $A$, $B$, and $C$ randomly from a uniform distribution in a cube.  What is the probability that $C$ is inside the sphere whose diameter is $AB$?
This problem might be pretty messy to solve, possibly even more so than the average length of a line segment in a cube problem, but it is still a good problem.  It is related to finding the bounding sphere of four random points in $\mathbb{R}^3$.  I was somewhat surprised how rarely the circumsphere of the four random points (as a tetrahedron) is the bounding sphere of the points.  Usually, the bounding sphere is determined by only three of the points.  And sometimes it is determined by only two of them.
Comment: This is the same as the probability that $\angle ACB>90^\circ$, or that $\vec c.\vec c+\vec a.\vec b<\vec a.\vec c+\vec b.\vec c$
Comment: @Michael I believe you mean $\geq 90^{\circ}$ to include points on the surface of the sphere.
Comment: @DylanSp the surface of the sphere has zero volume and does not contribute to the result.
Answer: Hint: (1) What is that probability for uniform $C$ and fixed $A$ and $B$? (2) Integrate that result over all $A$ and $B.$

Three random points in a cube


How to hide a specific user profile?

Question: I would like to be able to hide a specific user profile.
I want to completely hide it from Drupal and search engines. How can I achieve this?
Answer: To avoid users can access a user profile, I would implement hook_ENTITY_TYPE_access().
For the search engines, it would be sufficient to check the logged-in user isn't anonymous. For any Drupal user and the search engines, it's sufficient to check the permission the logged-in user has. (I would not hide the user profile to users who have the permission to administer users.)
In the first case, I would use code similar to the following one.
function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && $account->isAnonymous()) {
    return AccessResult::forbidden()->cachePerUser();
  }
}

In the second case, I would use code similar to the following one.
function mymodule_user_access(EntityInterface $entity, $operation, AccountInterface $account) {
  if ($operation == 'view' && $entity->id() == USER_ID && !$account->hasPermission('administer users')) {
    return AccessResult::forbidden()->cachePerPermissions();
  }
}

(In both the cases, replace USER_ID with the actual user ID of the user profile you need to hide.)
The code checks the value of the operation, and forbids it only when it's view. In this way, the code is simpler, as it doesn't need to check users are trying to edit their own accounts, for example (which I assume it's not an operation you want to forbid).
hook_ENTITY_TYPE_access() is not invoked for pages listing more than one entity, for example a view page. In the case of user accounts, hook_ENTITY_TYPE_access() should be sufficient, but if you want to avoid that user account is listed also in a view output, the alternative is hook_query_TAG_alter() which is more complicated to implement, but it works in every case.
Answer: To hide the page from Google and search engines, you can add the robots metatag.
Add this code to a custom module to add the metatag to the specefic profile page.
function MY_MODULE_preprocess_html(&$variables) {
  $user_id = 'ID of the user to hide profile page for';

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {
    $user = \Drupal::routeMatch()->getParameter('user');
    if ($user instanceof \Drupal\user\UserInterface && $user->id() == $user_id) {
      $robots_none = [
        '#tag' => 'meta',
        '#attributes' => [
          'name' => 'robots',
          'content' => 'none',
        ],
      ];

      $variables['page']['#attached']['html_head'][] = [$robots_none, 'robots-none'];
    }
  }
}

If you want to hide the page in Drupal too, you can create a redirect from the specific user profile page to the /system/403 page.
Comment: Thanks, but I want to completely hide the page itself. How would I do that?
Comment: I have updated my answer, `If you want to hide the page in Drupal too, you can create a redirect from that page to the 403 page using the redirect module.`
Comment: You're welcome, I'm glad it helped.
Comment: I have set the robots.txt with the metatag module

How to hide a specific user profile?


Skip custom action on uninstall (WiX)

Question: I'm authoring a MSI for an existing product. In the previous version there was a custom action that wasn't restricted to only run on install, and now fails on uninstall w/ MajorUpgrade.
Is there any way in the new installer, to tell WiX to skip over that particular custom action on uninstall?
Comment: Unfortunately the _old_ Uninstaller is executed but AFAIK you may first _patch_ the previous one before the major upgrade.
Answer: Yes, you can do this automatically from the new installer.
The solution:
1) You need to fix the problem in the project that builds your current version of the installer and build the good MSI again, from that project. In this case you only need the MSI database, which normally is a few KB, not the entire setup package (i.e CAB files containing all the installation files, etc...)
2) In the new installer, you need a custom action that runs before RemoveExistingProducts standard action which will recache the MSI for the previous version on the machine. Your custom action must execute this command:

msiexec.exe /fv "< path_to_MSI >"

The MSI you're trying to recache the is the new one you'be built in step #1. You need to include this MSI as a resource in the new version installer (and future versions, in case some users skip this version), and pass to you custom action the full path, where this MSI file is extracted, as a parameter.
Basically what you are doing to is automate the steps of recaching the old installation with a correct MSI (where you have set the correct conditions on your custom action). Now, when the RemoveExistingProducts standard action will execute, Windows Installer will trigger the uninstall of the old version using the newly cached MSI, which has the correct conditions set on your custom action, and uninstall successfully.
Comment: This works great, but you have to ensure that the ProductCode is the same (and likely the version).  If you have ProductID="*", look up the ProductCode in the registry (e.g., HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall) and find it, then temporarily change * to it.
Answer: The accepted answer from Bodgan Mitrache does not seem to be completely valid since it's not possible to run msiexec command from another msi package.
The first part is still correct. You have to fix the problem in the wix project and generate a new package with the same ProductCode/Version and with the MSI database only. We will use this package to recache the previous one so that it will be possible to uninstall it successfully.
In the new installer, you need 2 steps:

recaching the previous msi
launch new msi (product update)

The only way I found is to create a Wix bundle to chain sequentially the 2 steps.
1- Recaching operation can be made by a standalone executable consisting in a simple call to msiexec /fv valid_recache.msi. Here is a C++ example:
#include <Windows.h>

int main()
{
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);

    SHELLEXECUTEINFO shExecInfo;
    shExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
    shExecInfo.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_UNICODE;
    shExecInfo.hwnd = NULL;
    shExecInfo.lpVerb = L"open";
    shExecInfo.lpFile = L"cmd";
    shExecInfo.lpParameters = L"/c msiexec /fv path_to\\recache.msi";
    shExecInfo.lpDirectory = NULL;
    shExecInfo.nShow = SW_SHOW;
    shExecInfo.hInstApp = NULL;
    ShellExecuteEx(&shExecInfo);
    WaitForSingleObject(shExecInfo.hProcess, INFINITE);
}

2- Create your new msi from your project as usual (with new ProductCode and upper version number)
Combine the 2 steps in a Wix bundle project which can looks like this (useful link here):
<?xml version="1.0" encoding="UTF-8"?>
<Wix
  xmlns="http://schemas.microsoft.com/wix/2006/wi"
  xmlns:bal="http://schemas.microsoft.com/wix/BalExtension"
  xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">

  <Bundle
    Name="your_name"
    Version="1.0.0"
    Manufacturer="your_organization"
    UpgradeCode="your_uuid"
    Copyright="your_copyright"
    AboutUrl="your_url">

    <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.HyperlinkLargeLicense">
      <bal:WixStandardBootstrapperApplication
        LicenseUrl=""
        LogoFile="your_logo"
        ShowVersion="yes"
        SuppressOptionsUI="yes"/>
    </BootstrapperApplicationRef>

    <util:RegistrySearch
      Root="HKLM"
      Key="SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{ProductCode}"
      Value="Version"
      Variable="CurrentMsiPackageVersion"
      Result="value"
      Win64="yes" />

    <Chain>

      <ExePackage
          Id="Patch"
          SourceFile="MsiRecache.exe"
          Vital="yes"
          InstallCondition="(CurrentMsiPackageVersion="invalid_msi_version")">

          <Payload Name="recache.msi" SourceFile="relative_path_to\recache.msi"/>
      </ExePackage>

      <MsiPackage
        Id="your_id"
        SourceFile="your_setup.msi"
        DisplayInternalUI="yes"
        Vital="yes"/>
    </Chain>
  </Bundle>
</Wix>

Last, generate the bundle by calling:
candle.exe -ext WixBalExtension -ext WixUtilExtension bundle.wxs
light.exe -ext WixBalExtension -ext WixUtilExtension bundle.wixobj
Note that the bundle will have .exe extension instead of msi.

Skip custom action on uninstall (WiX)


Porque meu Ajax retorna um codigo HTML ao invés de só retornar o valor? Codeigniter

Question: Bom dia Galera, tudo beleza?
Estou a dias tentando retornar um valor da minha view para meu controller usando codeigniter. Porém não quero que aconteça refresh na página.
Então decidir usar o ajax, porém na minha consulta ou ele vem com o codigo html da minha pagina ou ele da esse erro:
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Meu HTML:

<form real="form" id="form" nome="form" method="post" action='<?= base_url("index.php/welcome");?>'>
                  <select class="form-control" name="selectUser" id="seletor">
                     <option  value='<?= $_SESSION["nome"]?>' >Only me</option>
                     <option  value="Trello">Team</option>
                  </select>
                </form>

Meu controller:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Welcome extends CI_Controller {

 public function index()
 {

  $nome = $this->input->post('valor');
  var_dump($nome);

  $this->load->model('testemodel');

  $verifica= $this->testemodel->verifica($nome);

  $data['nomecliente'] = $verifica['nome_cliente'];
  $data['horatotal'] = $verifica['hora_total'];
  $data['atividade'] = $verifica['nome_atividade'];

  $this->load->view('test', $data);

 }

Meu JavaScript:

$("#seletor").change(function(){

 var value = $("#seletor").val();

 $.ajax({
  url: 'welcome/index',
  type: 'POST',
  dataType: "json",
  data: {"valor" : value},
  success: function(data){
   console.log(data);

  },
  error: function(data){
   console.log(data);
  }
 });
});

Espero que possam me ajudar. Ficarei muito grato!
Answer: Simplesmente porque no controller você esta carregando a view:
$this->load->view('test', $data);

Seria mais facil fazer o retorno json direto:
echo json_encode($data);

Comment: Está dando esse erro aqui no console.log();

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
Comment: Da uma olhada no console do browser na aba network se o teu request esta retornando corretamente
Comment: Salvou mano! obrigado mesmo!


Where is Pathauto's "Strings to Remove" stored in MySQL?

Question: I've tried looking in the "variable" table with SELECT name FROM variable but I think it's not there.
Where does the module save that setting?
Answer: It's stored in the variable named pathauto_ignore_words, you can get it directly like this:
SELECT value FROM variable WHERE name = 'pathauto_ignore_words'

or using the Drupal API like this:
$ignore_words = variable_get('pathauto_ignore_words', '');

Answer: As @Clive mentioned, it is stored in the variable table, but only after you save the settings for the first time.
Before you save the settings, it is not found in the DB. By default it is stored in a constant within the module. See the default ignore list for Pathauto 7.x-1.2


product of $f(x)f(y)f(z)\geq1$ for $f(x)=ax^2+bx+c$ with $xyz=1$ and $a+b+c=1$.

Question: Let $a,b,c,x,y,z$ be positive reals with $xyz=1$ and $a+b+c=1$.
Let $f(x)=ax^2+bx+c$. Prove $f(x)f(y)f(z)\geq 1$.
Im stuck, I tried a bunch of things but the best ive managed to obtain is:
$f(x)f(y)f(z)\geq 27\sqrt[9]{abc}$ which is useless.
Answer: By Holder:
$$(ax^2+bx+c)(ay^2+by+c)(az^2+bz+c)\geq\left(a\sqrt[3]{x^2y^2z^2}+b\sqrt[3]{xyz}+c\right)^3=1.$$
Comment: can you explain a bit more?
Comment: It's Holder for three sequences. See here: https://math.stackexchange.com/tags/holder-inequality/info
Comment: oh, that helped, thank you!
Comment: You are welcome!


Set content-encoding to specific files via aws command

Question: I deploy static application by aws command.
I copy all files from my folder to s3 bucket by this command :
aws s3 sync C:\app s3://myBucket

I want to set content-encoding to gzip just to js,jpg,and html files.
I succeed to do it for all folder by this command : --content-encoding gzip
How can I do it just for the specific files type ?
Answer: This is old, but I needed to find a way to do this: I'm not using Cloudfront, and the proxy we are using doesn't handle gzip... so:

Exclude all files
Include individual file types as needed
Set the appropriate encoding/options

Below I'm also adding access control and cache-control, and deleting any files in s3 not present in the local directory
I've separated the JS/CSS from all of the images, html but that is probably not necessary.
I did however have a lot of trouble by not explicitly setting the content-encoding/cache for each individual --include, so I've set it like below to make it clearer.
The AWS docs that I could find don't mention any of this stuff
aws s3 sync ./dist/ s3://{bucket} \
--exclude "*" \
--include "static/*.ico" --acl "public-read" --cache-control no-cache \
--include "static/*.png" --acl "public-read" --cache-control no-cache \
--include "*.html" --acl "public-read" --cache-control no-cache \
--include "static/img/*.svg" --acl "public-read" --cache-control no-cache \
--delete \

aws s3 sync ./dist/ s3://{bucket} \
--exclude "*" \
--include "static/js/*.js" --acl "public-read" --cache-control  no-cache --content-encoding gzip \
--include "static/css/*.css" --acl "public-read" --cache-control no-cache --content-encoding gzip \
--delete \

Pretty neat little speed improvement for serving only from s3.
Comment: There is no need to set `--acl` and `--cache-control` for each file type as the last one is used for all of them.


Limit the creation of tags

Question: I wish to create a taxonomy where the administrator users limit which terms can be tagged.
Suppose I have a vocabulary containing the following terms:

Football
Golf
Snooker

I want the tag autocomplete to show the tags that can be used. If I typed "Foo", the autocomplete should show "Football"; if I typed "Basketball," the autocomplete would not show anything, the node would submit, but no term is created.
Is this possible?
Answer: It looks like the Content Taxonomy modules provides the ability to do this.
Without this, you'd have to implement hook_nodeapi('presave') and remove terms that don't exist yet.
Not even Drupal 7 seems to allow this without a contrib module, even though it does have specific edit terms permission for each vocabulary. Strange.

Limit the creation of tags


How to generate Normal variables parts of which are correlated (in R)?

Question: My second attempt to explain the question.
Start with a vector of numbers V1 of length M. The elements of V1 form a Normal distribution. Take (any) N elements from this vector. Generate a replica of this subset with some random error. Call this V2. Add to V2 elements so it becomes of length M and so that all M elements in V2 form a Normal distribution. As a result, V1 and V2 must be two normal random variables with one part that is correlated and one part which is not correlated across the two variables. And the resulting variables must have (the same) predefined mean and standard deviation.
My approach has been the following (in R):
rho<-0.9 #set the correlation level
x<-rnorm(1000,0,2)
y<-x*rho+sqrt(1-rho^2)*rnorm(1000,0,2) #this generates the correlated parts of X and Y
x[1001:1500]<-rnorm(500,0,2) #this is the uncorrelated part of X
y[1001:1500]<-rnorm(500,0,2) # this is the uncorrelated part of Y

The remaining problem is that for now the correlated elements of x and y are normally distributed which is admissible but should not be necessary. In other words, how to attach elements to any collection of numbers so that the resulting set has a normal distribution?
If that would clarify things, in reality the data I am trying to simulate comes in the following form: people assign a fixed number of statements (based on agreement with the statement) into bins which follow a quasi-normal distribution. It is suspected that people score (assign) a subset (but not all) of these statements in a very similar way. I want to simulate such data in order to explore the power of different statistical tools to detect such data structure.
Comment: Can you be explicit about what 'combined' means? Not just in words if possible.
Answer: Just thought to throw it out there. If you are by chance interested in specifying a correlation between 2 independent variables (of any kind), it is possible to use the correlate package to do so (it uses rejection sampling to provide a practical, natural, multivariate distribution).
E.g.
somevar <- 1:1000
x <- rnorm(1000)
data <- cbind(somevar, x)
cor(data)
[1] 0.03

require(correlate)
newdata <- correlate(data, 0.5)
cor(newdata)
[1] 0.50001

# values within variable do not change
all(sort(newdata) == sort(data))
[1] TRUE

It sounds like this might help with your simulation design.
Comment: still works like charm, though unfortunately the `correlate` package has been removed from CRAN: it can however be installed using the archived source code https://cran.r-project.org/src/contrib/Archive/correlate/
Answer: You (presumably) don't mean 'sum' there, but in any case need to more explicitly detail what 'combine' means. Please be explicit, either via algebra or a concrete example.
I take it what you actually need is that the marginal distributions of the correlated and uncorrelated parts are the same.
This is easily achieved.
If you simulate standard normal random variables $X$, and $Z$ then $Y=\rho X +\sqrt{1-\rho^2}Z$ is also standard normal but correlated with $X$ (with correlation $\rho$).
If you then generate the uncorrelated variables also to be standardized, you can then scale to any desired mean and variance without affecting the correlation structure.
In R, you can take advantage of a call to mvrnorm in the package MASS (there are other functions in other packages that will also do it).
Using the above methodology (directly, rather than via mvrnorm) we have the following (1000 points with correlation 0.8 in black, and 800 points with correlation 0 in red):

And here are kernel density estimates for correlated and uncorrelated parts of the x-variable (same colour scheme)

(the equivalent plot for $y$ looks similar)


Can I run Drush in a situation where the database is on one server and the remainder of the Drupal installation is on another?

Question: I have a setup (out of necessity not choice) where my drupal installation is on server a, and the database on which it relies is on server b.  The site is working fine, however when I run most Drush commands I get the good old:
Drush was not able to start (bootstrap) the Drupal database.
On the server where everything except the database is stored, there is no mysql.  If drush isn't an option for me that's perfectly fine but I've been tearing my hair out on this one.
Many thanks in advance for any ideas.
Answer: I've never run a Drupal site like this, but Drush should take your database settings from your settings.php file; if the database is remote for Drupal, then it should be remote for Drush as well.  Note that most Drush commands (with the notable exception of the sql-* commands, which you will not be able to use without a local mysql installation) just call through to the corresponding Drupal code, after first bootstrapping.  If your bootstrapping is failing, check to see if there is anything in your settings.php that depends on the site's URI to select the database.  If so, make sure that you use the --uri= flag, or set the 'uri' element in your Drush site alias when using Drush.  If that doesn't get you going, post the output of a failing Drush command with the --debug flag specified.
Comment: drush core-status --debug is a gem


Como adicionar indicadores de ordenação em uma tabela?

Question: Criei um algoritmo de ordenação [ascendente - descendente] de [letras - números].
Estou tentando adicionar algum indicador de ordenação no titulo das colunas, mas não esta funcionando como deveria.
Exemplo:

function sortTable(table, col, reverse) {
  var tb = table.tBodies[0],
    tr = Array.prototype.slice.call(tb.rows, 0),
    i;
  reverse = -((+reverse) || -1);
  var str1;
  var str2;
  tr = tr.sort(function(a, b) {
    if (a.cells[col].children[0] === undefined) {
      str1 = a.cells[col].textContent.trim();
      str2 = b.cells[col].textContent.trim();
    } else {
      str1 = a.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
      str2 = b.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
    }

    if (!isNaN(str1)) {
      if (str1.length === 1) {
        str1 = '0' + str1;
      }
      if (str2.length === 1) {
        str2 = '0' + str2;
      }
    }
    return reverse * (str1.localeCompare(str2));
  });
  for (i = 0; i
= 0)
    (function(i) {
      var dir = 1;
      th[i].addEventListener('click', function() {
        sortTable(table, i, (dir = 1 - dir));
      });
    }(i));
}

function makeAllSortable(parent) {
  parent = parent || document.body;
  var t = parent.getElementsByTagName('table'),
    i = t.length;
  while (--i >= 0) {
    if (t[i].attributes['data-sortable'] !== undefined) {
      makeSortable(t[i]);
    }
  }
}
makeAllSortable();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

      Código
      Nome

      1
      A - POSTO ASXL

      2
      B - POSTO BSP

      3
      AA - POSTO XYZ

Detalhe estou utilizando os icons da Font Awesome caso seja possível
  reaproveitar
Answer: Bem na função makeSortable() identifque o indice "th" e faca ele receber as classes do font-awesome fa-caret-up e fa-caret-down conforme tipo de ordenação (ascendente - descendente) que é identificado pela condição if((1 - dir) === 1) // ascendente else descendente.
Exemplo:

function sortTable(table, col, reverse) {
  var tb = table.tBodies[0],
    tr = Array.prototype.slice.call(tb.rows, 0),
    i;
  reverse = -((+reverse) || -1);
  var str1;
  var str2;
  tr = tr.sort(function(a, b) {
    if (a.cells[col].children[0] === undefined) {
      str1 = a.cells[col].textContent.trim();
      str2 = b.cells[col].textContent.trim();
    } else {
      str1 = a.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
      str2 = b.cells[col].getElementsByTagName(a.cells[col].children[0].tagName)[0].value;
    }

    if (!isNaN(str1)) {
      if (str1.length === 1) {
        str1 = '0' + str1;
      }
      if (str2.length === 1) {
        str2 = '0' + str2;
      }
    }
    return reverse * (str1.localeCompare(str2));
  });
  for (i = 0; i
= 0)
    (function(i) {
      var dir = 1;
      $(th[i]).append('  ');
      $(th[i]).append('  ');
      th[i].addEventListener('click', function() {
        sortTable(table, i, (dir = 1 - dir));
        if ((1 - dir) === 1) {
          $(th).find('i[data-order=down],i[data-order=up]').addClass('hidden');
          $(th[i]).find('i[data-order=up]').removeClass('hidden');
        } else {
          $(th).find('i[data-order=down],i[data-order=up]').addClass('hidden');
          $(th[i]).find('i[data-order=down]').removeClass('hidden');
        }
      });
    }(i));
}

function makeAllSortable(parent) {
  parent = parent || document.body;
  var t = parent.getElementsByTagName('table'),
    i = t.length;
  while (--i >= 0) {
    if (t[i].attributes['data-sortable'] !== undefined) {
      makeSortable(t[i]);
    }
  }
}
makeAllSortable();
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

      Código
      Nome

      1
      A - POSTO ASXL

      2
      B - POSTO BSP

      3
      AA - POSTO XYZ

Answer: Você pode usar o DataTables. É uma biblioteca de js muito útil para todo tipo de ordenação que você precisar em suas tables.
Segue um exemplo:

            Name
            Position
            Office
            Age
            Start date
            Salary

            Name
            Position
            Office
            Age
            Start date
            Salary

            Tiger Nixon
            System Architect
            Edinburgh
            61
            2011/04/25
            $320,800

            Garrett Winters
            Accountant
            Tokyo
            63
            2011/07/25
            $170,750

Aqui o javascript pra acionar a ordenação:
$(document).ready(function() {
$('#example').DataTable();
} );

E aqui como fica:

Lá no site deles tem a documentação completa, recomendo fortemente.


Commenting on each paragraph of node body

Question: I want to provide this option in Drupal that users be able to put comment on each paragraph of an article beside putting comment on the whole article.
I use explode command to make an array which contains paragraphs:
$paragraphs = explode("
",render($content));

In order to put comment for the whole article I write:
print render($content['comments']);

I am trying to find the file where $content is defined, so I can add another array like $content[]['paragraphcomments'] for comments for each paragraph of an article. Does anyone know in which file $content is defined. Also does anyone have any suggestion?
Comment: FYI Never hack core https://drupal.org/best-practices/do-not-hack-core
Comment: Thank you. So as I understood the only files I can change are the files inside Sites folder, Am I right?
Comment: Generally speaking, you should only change files you have created yourself. Changing files from contrib modules can create more or less the same problems as hacking core. Anyway, in most cases it's just not necessary because of the modular architecture of drupal. It's a good practice to create separate subfolders for contrib modules and for your own custom code inside sites/all/modules (or sites/YOURSITE/modules).
Answer: $contentis defined in node.module in the function template_preprocess_node().
You can add elements to the nodes content using hook_node_view()(D7) or hook_nodeapi() (D6).
See the accepted answer of this question for more details.
Comment: Thank you so much. So do you think I should write a module with hook_node_view function and add element to the node content or I can do that by changing node.module?
Comment: Don't hack core! Especially if it's not necessary. Create a module and use `hook_node_view()`.
Comment: I checked template_preprocess_node() function in node.module file. but I did not find what I am looking for. I want to know how $content['comments'] is defined, so with hook_node_view I can create a new field like $node->content['comment for each paragraph'] and define it the same way that $node->content['comments] is defined.but make it a 2 dimensional array, so users can put comment on each paragraph of a node body. I would really appreciate it if you can give me some info. Thank you
Comment: @mery This deserves a new question. I'm not quite sure about your approach. Anyway, this question already has an accepted answer, so you will probably get more attention when you create a new question.
Answer: You should create a module and can use jquery to shown & insert comments within paragraphs. If you use jquery then you'd need to use Ajax. You should show comment paragraphs in accordion style and allow visitor to comment after expanding it.
You can see simple Drupal developer examples in the example module.


PySpark: How to join dataframes with column names stored in other variables

Question: I am trying to learn PySpark. I must left join two dataframes, let's say A and B, on the basis of the respective columns colname_a and colname_b. Normally, I would do it like this:
# create a new dataframe AB:
AB = A.join(B, A.colname_a == B.colname_b, how = 'left')

However, the names of the columns are not directly available for me. They have been stored in a specific module, and I must call them like this:
module.COLNAME_A   # contains string with colname of A
module.COLNAME_B   # contains string with colname of B

How can I put these string values into the command above, in order to join the dataframes?
Comment: Possible duplicate of [How to join in pyspark dataframe with dynamic keys](https://stackoverflow.com/questions/57064511/how-to-join-in-pyspark-dataframe-with-dynamic-keys)
Answer: Use square bracket instead of dot notation to access the column names:
AB = A.join(B, A[module.COLNAME_A] == B[module.COLNAME_B], how = 'left')

Comment: It's more of a python syntax that works for both `pandas` and PySpark.
Comment: I see, so the `pandas` syntax works for PySpark as well?
Comment: what if I have multiple column? do i need to create key? or is there any other option?


"Resource is not in the state changeSetCreateComplete" when deploying to AWS with CloudFormation from Azure DevOps

Question: I'm deploying an application to AWS using the CloudFormation plugin for Azure DevOps.
It works really well, and will automatically update things that need changing, leaving other things alone.  I've been working on it for a few days, and it works fine.
However I just saw the following error when committing a small change:
Test for existence of change set Dev-TV-API-ChangeSet-Release-42 returned error: 'Stack [Dev-TV-API-NoAuth] does not exist'.
That looked a bit strange, so I thought maybe it's having trouble working out what needs to change.  So I decided to delete the stack manually, and re-run the pipeline.  Now I get exactly the same error.  The stack shows up in AWS with status REVIEW_IN_PROGRESS - and a single event.
Any ideas what could be going on here?
Full log:
2020-07-30T14:17:27.5715771Z Test for existence of change set Dev-TV-API-ChangeSet-Release-42 returned error: 'Stack [Dev-TV-API-NoAuth] does not exist'.
2020-07-30T14:17:27.5718700Z Loading template file from 'D:\a\r1\a\_TV CI\drop\package.yml'
2020-07-30T14:17:27.5724733Z Loading template parameters file 'D:\a\r1\a\_TV CI\drop\api.parameters.dev.json'
2020-07-30T14:17:27.5731008Z Successfully loaded template parameters
2020-07-30T14:17:27.5733302Z Setting capability CAPABILITY_IAM for stack
2020-07-30T14:17:27.5733902Z Setting capability CAPABILITY_NAMED_IAM for stack
2020-07-30T14:17:27.5734434Z Setting capability CAPABILITY_AUTO_EXPAND for stack
2020-07-30T14:17:27.5735777Z Creating CREATE type change set Dev-TV-API-ChangeSet-Release-42
2020-07-30T14:17:27.8132789Z Waiting for change set Dev-TV-API-ChangeSet-Release-42 to be validated for stack Dev-TV-API-NoAuth
2020-07-30T14:17:58.3348363Z Change set creation request failed with error: 'Stack Dev-TV-API-NoAuth failed to create successfully from the change set Dev-TV-API-ChangeSet-Release-42. Error: 'Resource is not in the state changeSetCreateComplete'' Error: Stack Dev-TV-API-NoAuth failed to create successfully from the change set Dev-TV-API-ChangeSet-Release-42. Error: 'Resource is not in the state changeSetCreateComplete'
2020-07-30T14:17:58.3355531Z     at .<anonymous> (D:\a\_tasks\CloudFormationCreateOrUpdateStack_7ef7cdfa-aa45-42c5-93c8-d7603643dd99\1.7.0\CloudFormationCreateOrUpdateStack.js:2:4039841)
2020-07-30T14:17:58.3356313Z     at next (native)
2020-07-30T14:17:58.3357470Z     at o (D:\a\_tasks\CloudFormationCreateOrUpdateStack_7ef7cdfa-aa45-42c5-93c8-d7603643dd99\1.7.0\CloudFormationCreateOrUpdateStack.js:2:4028532)
2020-07-30T14:17:58.3359409Z     at process._tickDomainCallback (internal/process/next_tick.js:135:7)
2020-07-30T14:17:58.3489430Z ##[error]Error: Stack Dev-TV-API-NoAuth failed to create successfully from the change set Dev-TV-API-ChangeSet-Release-42. Error: 'Resource is not in the state changeSetCreateComplete'
2020-07-30T14:17:58.3772097Z ##[section]Finishing: Create/Update Stack: Dev-TV-API-NoAuth

Answer: It turns out that some of the validation which happens before a template is deployed is logged in a different place.   So while I was seeing this error in the task log, and nothing much in the AWS Stack Info page, there is a "Change sets" tab at stack level, listing the failed changeset.  If you click on that, you will see a status reason describing the error, which should help with debugging.


MySQL Database store image url and php page display it?

Question: I was wondering if there's any way I could store an image URL in a database with a unique numeric id, and a php page display the image by getting data (the image URL) from the database and displaying it to the user on the image.php page?
An example of this would be:
- Having the image URL http://www.example.com/images/image10.jpg (where this URL would be stored in the database, alongside an id of 10)
- Having an image.php page which retrieves the image URL from the database and displays the image on the same page (the image.php page) (and doesn't redirect to the image URL) - an example result being image.php?id=10 where the image.php file would source the image URL from the database with an image id of 10  (using my example: www.example.com/images/image10.jpg) and display it (so it would be like viewing the image as if you were viewing www.example.com/images/image10.jpg but instead the URL would be http://www.example.com/image.php?id=10)
Is there any way to do this?
I'm new to php and MySQL so not really good with code - trying to experiment :)
Thanks in advance!
Edit:
I think people are getting confused by my bad description (sorry abot that).
I've noticed in your answers that you have included the actual image URL in your code - I dont understand why though.
EXAMPLE of how I'd like this to work:
My table would have these feilds:
img_id
img_url
The image.php file would GET the img_url FROM the table using the id on the end of the image.php url. FOR EXAMPLE:
- image.php?id=10 - the image.php file would use the id (which is 10), and display the image by retreiving the img_url (which would be: www.example.com/images/image10.jpg) from the table and displaying it - the image id would be img_id in the table.
- image.php?id=12 - the image.php file would use the id (which is 12) and display the image by retreiving the img_url (which would be: www.example.com/images/image12.jpg) from the table and displaying it - the image id would be img_id in the table.
Comment: Can you give us some code that you have tried?
Answer: You can try this:
//File: image.php?id=10
//you query
$img = 'http://example.com/sample.jpg'; // Image path from database
$getInfo = getimagesize($img);
header('Content-type: ' . $getInfo['mime']);
readfile($img);

Comment: This looks good but I'm confused by your answer - I want the php code to Source the image URL from the database, then display an image based on its ID - for example Image10.jpg would have a unique numeric id in the database - this being 10. So I want the image.php to Display AN image by first getting the id (like: image.php?id=10) and using the image url to display the image - where the image url would be on the same row (or would be part of the same record) as the record with an id '10'.
Comment: Your comment is not clear to me. please explain in simpler way, so may be I can help you.
Answer: I think what you need is this :
$image_path="http://example.com/image10.jpg";'
'mysql_query("INSERT INTO table VALUES ('',$image_path)");
in the php have this :
$id=$_GET['id'];if (isset($_GET['id'])){'
'$result = mysql_query("SELECT path FROM table WHERE id=$id");'
'$row = mysql_fetch_row($result);'
'$path=$row[0];echo "Image number ".$id." is ';}
Comment: Thanks for your answer. I am confused by this though - why would the image url be in this php code if the php file has to GET the image URL from the database?
Comment: You said you want the link look like this : http://www.example.com/image.php?id=10 . This means that you want to send the id through the link. The php takes the id from the link with $_GET['id']. Then searches within the database for the image with this id. When it founds it it takes the path. If all images look like this : image 10 image 11 etc you can use $path='http://www.example.com/image.php?id='; $path.=$_GET['id']; $path.='.jpg'; This code will results http://www.example.com/image.php?id=10 . With ".=" you concatenate strings.
Comment: Mysql injections would work here very easy, also use mysqli_* functions the mysql_* are marked as deprecated
Answer: It all depends on your code organisation, let me explain my self, right now in my mind i can think of two ways of organisation:
First, using a folder containing all images, with the same name + number for each image; e.g: images/img1.jpg - images/img2.jpg - images/img3.jpg etc
Using this method you'll not have to use even database, just within your page you go for this code, exemple for page http://exemple.com/images.php?id=10
$id = (isset($_GET["id"]))? $_GET["id"] : NULL; //Get the ID

Then use the method given by user3410107
$img = "http://example.com/img$id.jpg"; // Image path
$getInfo = getimagesize($img);
header('Content-type: ' . $getInfo['mime']);
readfile($img);

Second method is indeed using database, in this case there should be at least 2 columns within db, a unique ID + Images path, in this case you'll go for:
$query = mysql_query("SELECT id, imagePath FROM table WHERE id = $id");
while($data = mysql_fetch_assoc($query)){
$img = $data["imagePath"];
}

Once you get the image path, the same process as before:
$getInfo = getimagesize($img);
header('Content-type: ' . $getInfo['mime']);
readfile($img);

For security reasons add this line after $id variable
$id = (isset($_GET["id"]))? $_GET["id"] : NULL; //Get the ID
$id = mysql_real_escape_string($id);

Comment: Please use the mysqli_* functions, mysql_* is marked as deprecated
Comment: Thanks! The second method is the method I wanted!


Guitar D9 without 3rd and 7th?

Question: I've seen D9 on a guitar expressed as D A D2 E2 A2.
So I see no 3rd and no 7th. I've seen some topics talking abouth 12th and voicing, but still have no idea what that is all about and how it works.
Could someone enlighten me, please?
The chord tab as played:
e|-5- (A)12th
b|-5- (E)9th
G|-7- (D)8th
D|-7- (A)5th
A|-5- (D)1st
E|-x-

Comment: I haven't seen the talk about 12ths and voicing, but that's a Dsus2. It would fit in fine if someone else in the band is playing a *complete* D9, but as you say, it has no 3rd or 7th. And there may be no band!
Comment: Where did you see this?
Answer: The notes you list wouldn't be WRONG to play over a D9 harmony.  But they are insufficient, in themselves, to establish D9.
This happens all the time in music.  A chord symbol can't tell the whole story.
Answer: That's no D9. The notes which make up D9 are D, F♯, A, C and E. With only D A and E, at best it could be called Dsus2. It won't even be D add9, as there would need to be F♯. D sus9 is a faint possibility, with the E so high in the mix.
To be a 9th chord needs the 7th (of some sort) to also be present. It's not. And without a third, and more description, it can't be D9, Dmaj9 or Dm9.

Guitar D9 without 3rd and 7th?


Why isn't microtonal music more often used in soundtracks?

Question: Film and video game music has a clear goal, to provoke emotional responses coherent with the message of the corresponding scene. Because there are so many films, most receiving their own scores, there is an 'inventory' of tricks, elements that film composers have at their disposal, established so in the cultural consciousness. Some are even on TvTropes (a site not normally about music), like Dramatic Timpani and Deathly Dies Irae. These shortcuts can establish a mood or a setting in just a few seconds.
Having been introduced to microtonal music recently, and the truly alien chord progressions you can produce by going outside the typical 12-tone temperament, I wondered: why isn't this used for every alien theme, all the time? The listeners are not used to it, but the same goes for compound meter, and 5/4 is used liberally for villain themes.
Microtonality has the issue that you cannot use standard brass, woodwinds, and regular tuned percussion; but strings, the human voice and electronic instruments are still fair game. Particularly the latter is going to be very appropriate for any aliens.
Yet, in this extensive list of pieces in 24-tone temperament (which is a microtonal scale quite easier to grasp than any of the other multipliers), there's only two movie scores; one from the 1960's, and one by Danny Elfman. Compared to the list of pieces in quintuple meter specifically, and the popular music section does not even try to be comprehensive.
So why is microtonality so rare in popular music, particularly soundtracks for films and video games, that deal with aliens or generally other-worldly beings, that would be so well served by exotic scales?
Comment: I suspect there's no real answer to this question, being as it is a matter of musical taste.  My personal opinion is that microtonality is just too weird for most people.  But be that as it may- it's not quite correct to say that woodwinds cannot play microtonally.  Here's Phillip Gerschlauer playing a 128 tone per octave scale on sax: https://www.youtube.com/watch?v=lGa66qHzKME
Comment: Aliens like equal temperament https://www.youtube.com/watch?v=AphKxQ2NsQo
Comment: Maybe they prefer aleatory? Beatles to Batman ;)
Comment: You can absolutely play most brass and woodwind instruments microtonally. It's just super hard. It's keyboard instruments and pitched percussion that really slow you down.
Answer: First, I want to shout out to Stanley Kubrick who did choose music that transcended traditional tonality for both his science fiction and horror movies.
Also we might be hearing some amount of microtonality in the soundtracks by Trent Reznor and Atticus Ross, as working with analog synthesizers makes it easier to actually work with microtonal scales without hiring musicians who are very experienced with microtonality.
Which leads to what I believe is almost certainly the ultimate reason why soundtracks generally sound the way they do: money.
An original score for anything is a significant investment (usually) that most investors are going to want to expect some return on. By that I mean, the desire in hiring composers and musicians to create a soundtrack is that the additional revenue that a property will earn because it has a quality soundtrack will be greater than the cost of producing the soundtrack.
Currently, it is more difficult and therefore more expensive to hire musicians who can quickly (and therefore cheaply) render a microtonal composition. And that's assuming you've found a composer who is able to create effective microtonal music. And that's assuming you have a director who feels that microtonality will add to the story they are telling. And that's assuming you have producers who trust the director and the composer to create a finished product that will sell well enough to recoup the investment. And that's assuming you have a segment of the public as your market that will appreciate, consciously or subconsciously, the distinction between the more expensive microtonal soundtrack versus the more affordable and predictable investment in a 12ET soundtrack.
In other words, I think there is another, often more primary goal of video game, film, TV, and all commercial music: to make money.
Answer:
Film and video game music has a clear goal, to provoke emotional responses coherent with the message of the corresponding scene.

While this is true, there's often also the requirement for music to take a background role - to enhance the emotional effect of of the images and story without grabbing too much attention itself. When the alien is coming, we want the listener to feel (for the sake of argument) scared, rather than snap out of the suspension of disbelief and think 'wait a minute - this music is out of tune'. I guess this is a rephrasing of Scott Wallace's comment that microtonality may be too weird - it's often going to be weird enough to be a distraction rather than an enhancement.
That doesn't mean that playing with tuning and intonation isn't used... have a listen to Cliff Martinez' First sleep, from the Solaris OST:

This is an example of where subtle shifts in tuning, along with the inharmonicity of some of the instrument sounds chosen, create an otherworldly effect without the jarring effect that in-your-face microtonality might have on some listeners.
Answer: Microtonal music cannot be writen on music sheet. This is a problem to consider.
Comment: Uhh, [you can](https://commons.m.wikimedia.org/wiki/File:Helmholtz-Ellis_JI_pitch_notation_microtonal_accidents_legend.gif)
Comment: Say whaaaaat lol


Problema com condicional no React

Question: Estou tentando fazer uma condicional em que o componente ativo depende de uma variável do estado.
this.state = {
  display: 0,
}

O estado 0 é o estado inicial, que é mudado quando o usuario clica em um botão.
Dependendo do botão a variável display mudará para um valor de 1 a 4.
{if (this.state.display == '0') {
      return ()
      } else if (this.state.display == '1') {
        return()
      } else if (this.state.display == '2') {
        return()
      } else if (this.state.display == '3') {
        return()
      } else if (this.state.display == '4') {
        return(
          <Catalogo></Catalogo>
        )}
    }}

O código na íntegra se encontra em github/cmoutella
O erro diz 'Parsing error: Unexpected token' e aponta para o if.
Como eu posso fazer isto?
Answer: Você não pode colocoar IF's dentro do escopo do retorno.
Caso queira fazer a lógica dentro do return tem que utilizar a condição ternária.
ex:
render() {
  const {display} = this.state;
  return

      {display == 0 && <Component1/>}
      {display == 1 && <Component2/>}
      {display == 2 && <Component3/>}
      {display == 3 && <Component4/>}

;
}

Ou então você faz a lógica antes do return e atribui o retorno para uma variável que você irá retornar
ex:
render() {
  const {display} = this.state;
  let retorno;
  if (display == 0) {
    retorno = <Component1/>;
  } else if (display == 1) {
    retorno = <Component2/>;
  } else if (display == 2) {
    retorno = <Component3/>;
  } else {
    retorno = <Component4/>;
  }

  return

   {retorno}

;
}

Answer: O problema que você deve retornar o seu elemento diretamente.
Seu método render deveria ser algo como:
  render(){
    if (this.state.display == '0') {
      return ()
    } else if (this.state.display == '1') {
      return()
    } else if (this.state.display == '2') {
      return()
    } else if (this.state.display == '3') {
      return()
    } else if (this.state.display == '4') {
      return(
        <Catalogo></Catalogo>
      )}
    }
  }

Você somente escopa o código quando já estiver retornando algum elemento, mas mesmo assim, sua condicional deveria retornar um valor. Por isso o if não funciona.
Comment: para efeitos de teste eu coloquei para retornar  nos que nao tinham ainda o componente a ser retornado, mas o erro persiste. Pesquisando no google encontrei que o React não suporta if else.
Comment: o código atualizado: https://github.com/cmoutella/cmoutella.github.io/blob/issues/03/temporario/hinode/src/App.js

Problema com condicional no React


Avoid memory leaks sending jquery selectors as constructors parameters

Question: I builded some views without using MVC framework. Only jQuery and JavaScript.
I have more or less, the next construction:
function LeWildConstructor ($selector) {
   $selector.find('anElement').bind(function () {
     ...
   });
}

$(function () {
  window.wildConstructor = new LeWildConstructor($('.container'));
});

An soft architect told me this construction is potentially leaking if the page continue open for a while.
He suggest do something like:
function LeWildConstructor () {
   var $selector = $('.container')
   $selector.find('anElement').bind(function () {
     ...
   });
}

$(function () {
  window.wildConstructor = new LeWildConstructor();
});

I think both approches are the same.
I understand after the ready document the constructor call once, and the parameter sended one time, and jQuery is lazy, once I send the node element, doesn't call anymore each time I reference $selector inside of the constructor.
But I'm not sure if I'm missing other practices than can generate a possible leak.
Comment: That architect is too soft. Get a harder architect. This sounds like rubbish, does he have any evidence to back his claims?
Comment: Sounds liked some miscommunication going on. Ask for a better explanation of the issue
Answer: If you don't assign it to a variable I don't see why there would be any leaking, but consider this code:
$(function () {
  var something = $('.container');
  window.wildConstructor = new LeWildConstructor();
});

This closure would not be collected until you delete the global variable, so it's true that the other approach avoids 1 reference to be "leaked". Now, there is probably no difference between having 1 extra jQuery selector in memory on any page, specially if it's called just a few times.
I'm not sure how jQuery works, but this seems to be an array of objects (references) and that should be ultra lightweight to have floating in memory.
TL;DR Although relevant, I think his consideration is pointless and false in this specific case.
Edited after a bit more of thinking
Edited again to clarlify after t.niese comment
Comment: I don't see a `var something = $('.container'); window.wildConstructor = new LeWildConstructor();` in the code of the OP, just a `window.wildConstructor = new LeWildConstructor( $('.container') );`.
Comment: "This closure would not be collected until you delete the global variable, so it's true that the other approach avoids 1 reference to be "leaked"." --- this is simply wrong. An object that `something` holds a reference to will be marked as a garbage as soon as the interpreter goes out of this anonymous function scope.


index.js:1 Warning: validateDOMNesting(...):  cannot appear as a descendant of

Question: index.js:1 Warning: validateDOMNesting(...):
 cannot appear as a descendant of
.
index.js:1 Warning: validateDOMNesting(...):
 cannot appear as a descendant of
.
index.js:1 Warning: validateDOMNesting(...): <form> cannot appear as a descendant of
.

What is the cause of these errors?
Answer:
 is used to denote a paragraph of text, and it makes no logical sense to include a heading, list or form inside of a paragraph. As such,
,
 and <form> are not valid children of the
 tag. The only permitted content for
 tags is phrasing content.
The only phrasing content (and the only valid children of the
 tag) are , <audio>, , <bdo>,
, <button>, <canvas>, , , <command> (obsolete), <data>, <datalist>, <dfn>, , <embed>, , , , <input>, , <keygen> (obsolete), , , <math>, <meter>, , <object>, <output>, <picture>, <progress>, <q>, <ruby>, <samp>, , <select>, , , , , , <svg>, <textarea>, <time>, <var>, <video>, <wbr> and plain text (not only consisting of white spaces characters).
Answer: Find elemnt by run this code in console
document.querySelectorAll(" p * ul ")

<CustomElement tag={"p"} />
// OR
<Text as="p" />

change with
<CustomElement tag={"div"} />
// OR
<Text as="div" />

Answer: you may have called mui Typography control without variant somewhere which is converted as a P tag on DOM render. either give variant or remove Typography control, it applicable for all.


Subdividing square problems due to floating point precision errors

Question: I have a problem (in JAVA) which I unable to solve due to floating point precision errors.
I have an axis-aligned square class which is defined by specifying 2 points. In the constructor it is determined what the largest distance is (either in x- or y-direction) and this is used to create the square, with the points equal distance form the center. This means the points are on the boundary.
As an example, if I define a square with points (0, 2) and (3, 3) the largest distance is the x-distance (3) and the square will be defines as follows:

lower left point  = (0, 1)
upper right point = (3, 4)

As can be seen the points are on the edge and the midpoint of the points is exactly the center of the square (1.5, 2.5).
I created a method to check if a square contains a certain point, which looks like something like this:
see added code sample below

Which means that if a point is on the boundary it is 'contained'.
Now I want to subdivide the square into 4 'equally' sized sections (NorthEast, NorthWest, SouthWest and SouthEast) and logically the initial points that defined the original square must be contained in at least 1 of the sections. But when unit testing this which random points it fails and it looks like it is because of double precision floating point errors.
I tried different methods of solving it and my last iteration was as follows:

use the initial points to define the midpoint (p0) of the square
use the initial points + midpoint to define the 4 corner points (p1, p2, p3 p4 in clockwise direction, starting bottom-left) of the square

This guarantees that the original points are contained and I can easily create the subdivisions and I thought it guarantees that the original points are contained it at least 1 of the sections if I ensure no math is performed on the characteristics of the points defining the square (since they are on the boundary). My subdivision routine is as follows:
see added code sample below

But when running a unit test of a large amount of iterations with random points almost 1 in 16 still fails and I have no idea why the edge points are changed. In all those tests the initial containment check (whether or not the parent square contains the points although they are on the edge) passes 100%.
EDIT
Some actual code showing my implementation:
public class Point implements IPoint {
    double x, y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public double x() {
        return x;
    }

    @Override
    public double y() {
        return y;
    }

    @Override
    public IPoint midPoint(IPoint other) {
        return new Point((x() + other.x()) / 2, (y() + other.y()) / 2);
    }
}

public class Rectangle implements IRectangle {
    IPoint p0, p1, p2, p3, p4;

    public Rectangle(IPoint v1, IPoint v2) {
        double dx, dy, dl;
        IPoint v0;

        // calculate dominant length
        dx = Math.abs(v1.x() - v2.x());
        dy = Math.abs(v1.y() - v2.y());
        dl = dx >= dy ? dx : dy;

        if (dx >= dy) {
            // make sure v0 = left-most
            if (v1.x() <= v2.x()) {
                v0 = v1;
                v1 = v2;
            } else {
               v0 = v2;
            }
        } else {
            // make sure v0 = bottom-most
            if (v1.y() <= v2.y()) {
                v0 = v1;
                v1 = v2;
            } else {
                v0 = v2;
            }
        }

        this.p0 = v0.midPoint(v1);
        if (dx >= dy) {
            // this way v0 and v1 are always on the vertical boundaries
            this.p1 = new Point(v0.x(), this.p0.y() - dl / 2);
            this.p2 = new Point(v0.x(), this.p0.y() + dl / 2);
            this.p3 = new Point(v1.x(), this.p0.y() + dl / 2);
            this.p4 = new Point(v1.x(), this.p0.y() - dl / 2);
        } else {
            // this way v0 and v1 are always on the horizontal boundaries
            this.p1 = new Point(this.p0.x() - dl / 2, v0.y());
            this.p2 = new Point(this.p0.x() - dl / 2, v1.y());
            this.p3 = new Point(this.p0.x() + dl / 2, v1.y());
            this.p4 = new Point(this.p0.x() + dl / 2, v0.y());
        }
    }

    @Override
    public boolean contains(IPoint p) {
        if (p.x() < p1.x() || p.x() > p4.x()) return false;
        if (p.y() < p1.y() || p.y() > p2.y()) return false;
        return true;
    }

    @Override
    public IRectangle[] subdivide() {
        return new Rectangle[] {
            new Rectangle(p0, p2),
            new Rectangle(p0, p3),
            new Rectangle(p0, p4),
            new Rectangle(p0, p1)
        };
    }
}

And here is the test case:
@Test
public void testMassedSubdivide() throws Exception {
    Random r = new Random();
    IPoint p1, p2;
    IRectangle[] rects;
    boolean check1, check2;
    for (int i = 0; i < 100000; i++) {
        p1 = new Point(r.nextDouble(), r.nextDouble());
        p2 = new Point(r.nextDouble(), r.nextDouble());
        q = new Rectangle(p1, p2);
        assertTrue(q.contains(p1));
        assertTrue(q.contains(p2));

        rects = q.subdivide();
        check1 = rects[0].contains(p1) || rects[1].contains(p1) || rects[2].contains(p1) || rects[3].contains(p1);
        check2 = rects[0].contains(p2) || rects[1].contains(p2) || rects[2].contains(p2) || rects[3].contains(p2);
        assertTrue(check1);
        assertTrue(check2);
    }
}

One of the failure cases resulting from my randomized test:
p1 = (0.31587198758298796,  0.12796964677511913)
p2 = (0.04837609765424089,  0.6711236142940149)

This one fails, because p1 should be in the SouthEast sector, but that one is defined as:
p0=(0.31791253449833834,    0.2637581386548431),
p1=(0.18212404261861442,    0.12796964677511916), <- wrong, last 6 should be 3
p2=(0.18212404261861442,    0.39954663053456707),
p3=(0.4537010263780623,     0.39954663053456707),
p4=(0.4537010263780623,     0.12796964677511916)  <- wrong, last 6 should be 3

Comment: Thank you for a wonderfully thorough description. This sounds to me like the result of a minor coding error rather than a fundamental flaw in your approach. You're right in thinking you shouldn't be running into precision-loss problems as long as you're doing it right. As such, I suspect we won't be able to find the problem without a bit more code. Could you provide a more complete implementation of the code in question, and perhaps some of the failure cases?
Comment: I added some implementation code + test case + failure data.
Comment: The key to getting the result you want is to accept that floating point arithmetic is not real number arithmetic. You seem to be depending on identities that are not guaranteed. Any time you think the result of a calculation should be an already known value, use that value instead of doing the calculation.
Comment: So one minor code suggestion, I think you might be able to simplify this code significantly by replacing the middle `id (dx >= dy)` block with `IPoint bl = new Point(min(v0.x, v1.x), min(v0.y, v1.y)); IPoint tr = new Point(max(v0.x, v1.x), max(v0.y, v1.y));`, that way you can always work with bottom-left and top-right coordinates, which makes things a bit easier to read. I disagree with Patricia, though--since you can use the same number as you're given without any operations, there's no reason floating-point precision should be a factor.
Comment: suggestion: when using random numbers for testing, use a seed. This will allow failures to be reproduced. So, `Random r = new Random(42)` instead of `new Random()`.
Comment: I like to look for broken symmetry - in your case, it is surprising to see `p.x() < p1.x()` and `p.y() < p1.y()`  - there are no uses of p3 in your `contains` method, while p1, p2 and p4 are used, and p1 twice...
Answer: After looking at your code, it doesn't make any sense that it would fail, given that as far as I can tell, you are not applying any operations to the Y values in that failure case--you're just passing it through without any manipulation so floating-point precision loss is irrelevant. It was a bit hard for me to follow though, when p1-p4 could represent any corner, so I rewrote the Rectangle class as follows in the hopes of being a bit clearer:
public class Rectangle implements IRectangle {
    IPoint centroid, bottomLeft, topLeft, bottomRight, topRight;

    public Rectangle(IPoint v0, IPoint v1) {
        IPoint bottomLeft = new Point(Math.min(v0.x, v1.x), Math.min(v0.y, v1.y));
        IPoint topRight   = new Point(Math.max(v0.x, v1.x), Math.max(v0.y, v1.y));

        // calculate dominant length
        double dx = topRight.x - bottomLeft.x;
        double dy = topRight.y - bottomLeft.y;  // Assumes (0, 0) is in the bottom-left.
        double dl = dx >= dy ? dx : dy;

        this.centroid = bottomLeft.midPoint(topRight);
        if (dx >= dy) {
            // this way bottomLeft and topRight are always on the vertical boundaries
            this.bottomLeft  = new Point(bottomLeft.x(), this.centroid.y() - dl / 2);
            this.topLeft     = new Point(bottomLeft.x(), this.centroid.y() + dl / 2);
            this.bottomRight = new Point(topRight.x(), this.centroid.y() - dl / 2);
            this.topRight    = new Point(topRight.x(), this.centroid.y() + dl / 2);
        } else {
            // this way bottomLeft and topRight are always on the horizontal boundaries
            this.bottomLeft  = new Point(this.centroid.x() - dl / 2, bottomLeft.y());
            this.topLeft     = new Point(this.centroid.x() - dl / 2, topLeft.y());
            this.bottomRight = new Point(this.centroid.x() + dl / 2, bottomLeft.y());
            this.topRight    = new Point(this.centroid.x() + dl / 2, topLeft.y());
        }
    }

    @Override
    public boolean contains(IPoint p) {
        if (p.x() < bottomLeft.x() || p.x() > topRight.x()) return false;
        if (p.y() < bottomLeft.y() || p.y() > topRight.y()) return false;
        return true;
    }

    @Override
    public IRectangle[] subdivide() {
        return new Rectangle[] {
            new Rectangle(centroid, bottomLeft),
            new Rectangle(centroid, topLeft),
            new Rectangle(centroid, bottomRight),
            new Rectangle(centroid, topRight)
        };
    }
}

If that doesn't fix the issue, perhaps some logging will suss out at point the 0.12796964677511913 changes to 0.12796964677511916
Comment: Upvoted because it is much more readable. However, there appear to be minor typos - v1 v2 in constructor parameters, v0 v1 used in code.
Answer: I fixed it! Thanks for all the help 0x24a537r9 because it made it a lot clearer. I added your code (and fixed a typo) but we still missed one special case, namely the case that it is a perfect square and thus, dx == dy.
If dx == dy we know all the  points of the square and they can be added without using dl. In my failure case it was a perfect square, and therefore it would end up in the first if clause and thus use dl to calculate 2 new corner-points (which would result in floating point errors).
Logically it would end up in a square situation, because I force it to be square....
My final constructor code is like follows:
IPoint centroid, bottomLeft, topLeft, topRight, bottomRight;

public Rectangle(IPoint v0, IPoint v1) {
    IPoint bottomLeft = new Point(Math.min(v0.x(), v1.x()), Math.min(v0.y(), v1.y()));
    IPoint topRight   = new Point(Math.max(v0.x(), v1.x()), Math.max(v0.y(), v1.y()));

    // calculate dominant length
    double dx = topRight.x() - bottomLeft.x();
    double dy = topRight.y() - bottomLeft.y();  // Assumes (0, 0) is in the bottom-left.
    double dl = dx >= dy ? dx : dy;

    this.centroid = bottomLeft.midPoint(topRight);
    if (dx == dy)  // special case where it is square <- important, because this one fixes the errors
    {
        this.bottomLeft = bottomLeft;
        this.topLeft = new Point(bottomLeft.x(), topRight.y());
        this.topRight = topRight;
        this.bottomRight = new Point(topRight.x(), bottomLeft.y());
    }
    else if (dx >= dy) {
        // this way bottomLeft and topRight are always on the vertical boundaries
        this.bottomLeft  = new Point(bottomLeft.x(), this.centroid.y() - dl / 2);
        this.topLeft     = new Point(bottomLeft.x(), this.centroid.y() + dl / 2);
        this.bottomRight = new Point(topRight.x(), this.centroid.y() - dl / 2);
        this.topRight    = new Point(topRight.x(), this.centroid.y() + dl / 2);
    } else {
        // this way bottomLeft and topRight are always on the horizontal boundaries
        this.bottomLeft  = new Point(this.centroid.x() - dl / 2, bottomLeft.y());
        this.topLeft     = new Point(this.centroid.x() - dl / 2, topRight.y());
        this.bottomRight = new Point(this.centroid.x() + dl / 2, bottomLeft.y());
        this.topRight    = new Point(this.centroid.x() + dl / 2, topRight.y());
    }
}

Comment: Ha! I had actually thought of the square case and typed it into one of my earlier comments on your question. But it pushed the comment over the char-limit, so I removed it thinking "Yeah, I mean it *could* happen, but would be so unlikely, probably not even worth mentioning..." Oh well. Sorry I didn't just make a second comment!


SVG Filter animation feColorMatrix

Question: I'm trying to make a hover effect on an image using SVF filters. My problem is that I don't know how to make the effect to last. I can give 1 second of duration but I can't keep the values of the feColorMatrix as I want.
<filter id="blurred" color-interpolation-filters="sRGB" x="0%" y="0%" height="10%" width="10%">
  <feColorMatrix result="wispy" type="matrix" values="8 0 0 0 -1 4 0 4 3 -1 4 0 0 0 -1 1 0 0 0 0">
    <animate
    attributeType="XML"
    id="blurredAnimation"
    attributeName="values"
    from="8 0 0 0 -1 4 0 4 3 -1 4 0 0 0 -1 1 0 0 0 0"
    to="3 0 0 0 -1 4 0 4 3 -1 4 0 0 0 -1 1 0 0 0 0"
    dur="1s"
    values = "8 0 0 0 -1 4 0 4 3 -1 4 0 0 0 -1 1 0 0 0 0;3 0 0 0 -1 4 0 4 3 -1 4 0 0 0 -1 1 0 0 0 0;"
    keyTimes = "0;1"
    begin="indefinite" />
  </feColorMatrix>
</filter>

I want the green effect to stay there as long as the hover is there.
Thank you
Here is the jsFiddle
Answer: If you add fill="freeze" the animation will stay like it is once it's finished. You may want to add something to reset the animation on mouseout too.
function toggleBlurOff(background) {
    document.getElementById("svg").setCurrentTime(0);
};

Comment: Thank you. Using freeze help me. Here is the final thing: http://jsfiddle.net/yvoef3ab/2/

SVG Filter animation feColorMatrix


Post a link in VIADEO using it API

Question: I have tried to post a link in viadeo net work using it API, i have used the following CURL code. but its not working, I have tried with php as my server side code. Can Any one please help me to sort out this.
API reference
<code>$url = 'https://partners.viadeo.com/api/member/activity/share';
  $headers[] = 'Authorization: Bearer ' . $userArray['accessToken'];
  $headers[] = "Accept: language/json";
  $headers[] = 'Content-Type: application/JSON';

  $headers[] = 'X-CSRF-Token: ' . $token;

    $fields = array(
        'status' => "My Messafge",
        'url'   =>  "www.google.com"
    );

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data

    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_POST, count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($fields));
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_HEADER, $headers);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
</code>
But I got response as below
<code>    HTTP/1.1 406 Not Acceptable
Cache-control: no-cache="set-cookie"
Content-Type: application/json; charset=utf-8
Date: Wed, 10 Aug 2016 09:20:16 GMT
ETag: W/"79-LjiXR3TEaswtDc0NbPbnlA"
Server: nginx/1.8.1
Set-Cookie: AWSELB=EB652D71104D5A540BBD90F6B05BD98BEE3F41DAFDC50D85BE8FBFFCF095D7D78EB45C92813C3646048981782B8C4C76C884420B93A5B55954F394AA61798FEFC028CD93F8;PATH=/
X-Powered-By: Express
Content-Length: 121
Connection: keep-alive

{"error":"The provided Accept header is not acceptable. Try one of the following : application/json,multipart/form-data"}
</code>
Comment: Change `$headers[] = "Accept: language/json";` to `$headers[] = "Accept: application/json";`
Comment: @Jigar I tried like that too, i got same response.
Answer: Try Like this, it will work for sure
<code> $headers[] = "Accept: application/json";
 $headers[] = 'Content-Type: application/json';
</code>

Post a link in VIADEO using it API


Boolean Algebra Manipulation/Simplification

Question: I have come across a couple questions while doing my digital logic work.
1) Is it possible to simplify these, while keeping each a product of sums? (I'm leaning towards no--the only way I could see to simplify them would be to distribute.)  They're separate problems.
$$(a+b+c)(a'+b'+c')$$
$$(x+y)(x'+y+z')$$
2) Find the minimum sum of products expression (I honestly didn't even know how to begin this one, if you could just get me started...):
$$x_1'x_3'x_5'+x_1'x_3'x_4'+x_1'x_4x_5+x_1x_2'x_3'x_5$$
- The hint was to use the consensus theorem: $xy+yz+x'z=xy+x'z$
3) Find the minimum product of sums expression (again, if you could just help me get started)
$$x_1x_3'+x_1x_2+x_1'x_2'+x_2'x_3$$
Any help is greatly appreciated!  Thanks!
Answer: 1b)
$$(x+y)(x'+y+z')$$
can be simplified to
$$(x+y)(x'+z')$$
Convince yourself using a thruth table.
2)
$$x_1'x_3'x_5'+x_1'x_3'x_4'+x_1'x_4x_5+x_1x_2'x_3'x_5$$
can be simplified to
$$x_1'x_3' + x_1'x_4x_5 +  x_2'x_3'x_5$$
Such simplifications can be done using a Karnaugh-Veitch map.
3)
$$x_1x_3'+x_1x_2+x_1'x_2'+x_2'x_3$$
is a sum of products.
It can be minimized to
$$x_1 + x_2'x_3$$
Written in Conjunctive Normal Form (CNF):
$$(x_1 + x_2')(x_1 + x_3)$$
Answer: 1b)
$$(x+y)(x'+y+z')=\text{ (Distribution)}$$
$$y+x(x'+z')= \text{ (Reduction)}$$
$$y +xz'$$
This is actually an instance of a General Reduction Theorem that says that:
General Consensus Theorem
$PQ+PQ'R=PQ+PR$
$(P +Q)(P+Q'+R)=(P+Q)(P+R)$
We can also use this for 2):
$$x_1'x_3'x_5'+x_1'x_3'x_4'+x_1'x_4x_5+x_1x_2'x_3'x_5=\text{ (Distribution)}$$
$$x_1'(x_3'x_5'+x_3'x_4'+x_4x_5)+x_1x_2'x_3'x_5=\text{ (Consensus)}$$
$$x_1'(x_3'x_5'+x_3'x_4'+x_4x_5+x_3'x_5)+x_1x_2'x_3'x_5=\text{ (Adjacency)}$$
$$x_1'(x_3'+x_3'x_4'+x_4x_5)+x_1x_2'x_3'x_5=\text{ (Absorption)}$$
$$x_1'(x_3'+x_4x_5)+x_1x_2'x_3'x_5=\text{ (Distribution)}$$
$$x_1'x_3'+x_1'x_4x_5+x_1x_2'x_3'x_5=\text{ (General Reduction)}$$
$$x_1'x_3'+x_1'x_4x_5+x_2'x_3'x_5$$
Finally, the Consensus Theorem also works great for 3):
$$x_1x_3'+x_1x_2+x_1'x_2'+x_2'x_3=\text{ (Consensus)}$$
$$x_1x_3'+x_1x_2+x_1'x_2'+x_2'x_3+x_1x_2'=\text{ (Adjacency)}$$
$$x_1x_3'+x_1+x_2'+x_2'x_3=\text{ (Absorption)}$$
$$x_1+x_2'$$


Replacing images with same names in folders

Question: A.) When i use code to delete lets say Image123.jpg in folder Pics and i upload another image and rename that image also Image123.jpg and place it into folder Pics for some reason the new image get's displayed but its using the dimensions of the Image i delete. Using a Repeater over here to display the image.................
B.) When i just copy and past say Image99.jpg into my Pics folder that all ready contain a Image99.jpg then of course it changes the original one. So for some reason it must get cached because when i run my page it is still shows the first Image. Using a normal Image control over here................
Why is it doing A and B........and how can i go around this.....Problem A it more important to me because i need to change the Images names when the User clicks on "Change Logo" button.
Comment: Some code would help. I'd like to have a look at your repeater control and your code which handles the file-manipulation
Answer: The browser caches the images, so if you replace an image you have to change the url that requests the image to see the new image.
You can do this either by:

Changing the name of the image itself.
Add a querystring to the url, which you change.

If you add a version number to the url, e.g. images/Image123.jpg?version=42 and increase the version number when you replace the image, the browser will request the new image from the server as the browser caches the files based on the complete url, not just the file name.
Comment: How would i do that in code - adding version numbers that is.
Comment: That depends on what your code looks like... how do you set the url of the image in the first place?
Answer: If it is indeed a caching issue you could do the following.
Programmatically:
Response.Cache.SetCacheability(HttpCacheability.NoCache);

Declaratively:
<%@ OutputCache Location="None" VaryByParam="None" %>

By caching Web pages, you avoid re-creating information on subsequent requests so keep in mind that this may adversely affect page load times as caching will be disabled.
Comment: MMM, thanks, that could work i guess but i dont want to do that since the site is meant for South Africa and the internet is VERY slow over here!