Why do Hong Kong and China compete separately in Athletics?

Question: At the recent IAAF World Championships in Athletics, Hong Kong and the P.R. of China had separate teams in the 4x100m relay. I understand why the PRC and Chinese Taipei compete separately, as they are de facto separate countries, but why does Hong Kong have its own team?
Comment: Related: [Which countries can participate in the Olympics?](http://sports.stackexchange.com/q/3943/1723)
Comment: Apparently [Taiwan wants to use the name Taiwan in 2020](https://www.insidethegames.biz/articles/1069562/petition-submitted-calling-for-referendum-on-taiwan-dropping-chinese-taipei-name-at-tokyo-2020).
Answer: The main reason is that Hong Kong is a Special Administrative Regions of the People's Republic of China (Similar to  Macau).
Hong Kong was a a British colony until 1997 and then moved back to China according to political agreement under "one country, two systems" principle.
As a result Hong Kong has its own flag, currency, judgement system, immigration and many more attributes of independent country system. Only the military system and the diplomats relationships are managed under the Chinese authorities.
Hong Kong also has Sports Federation and Olympic Committee which is the national Olympic committee (NOC) of Hong Kong. As such it is a separate member of the International Olympic Committee (IOC) and compete separately on the olympics and the IAAF World Championships.
You can read about it here and here
Answer: Because it is one of autonomy traditions of Hong Kong. Before 1997, Hong Kong already has its own flag, currency, sport team, immigration and many more attributes of independent country system.
Hong Kong was a royal colony which were ruled by a governor appointed by the monarch, not under the England nor UK government.
After 1997, the Chinese-British political agreement under "one country, two systems" principle means to not change them, and that Hong Kong should be self-governed.


Why could not we choose the first element as bottom?

Question: I am trying a solve the Exercise 4 of Section 2.4 in the book Category Theory
for Computing Science.
The exercise is "Show that for every set $S$, the poset $(\mathcal{P}(S),\subseteq)$ is a strict $\omega$-CPO."
The definition of $\omega$-CPO is "A poset $(\mathcal{P}(S),\leq)$ is an $\omega$-complete partial order, or $\omega$-CPO, if every chain has a supremum. If the poset also has a minimum element, it is called a strict $\omega$-CPO."
The answer of the book says "Let $\mathcal{L}=(C_0,C_1,C_2...)$ be a chain in $(\mathcal{P}(S),\subseteq)$, the bottom element is $\emptyset$".
However, I think the bottom element is $C_0$. What is wrong with my understanding?
Comment: Thanks for giving the source of the exercise. That helped me write your answer.
Answer: To prove that $(\mathcal P(S), \subseteq)$ is a strict $\omega$-CPO, there are two parts:

Every chain in $(\mathcal P(S), \subseteq)$ has a supremum
$(\mathcal P(S), \subseteq)$ has a bottom element.

The proof first considers a chain $\mathcal L$ to show that it has a supremum. Having done this, it moves on to part 2, the bottom element, and observes that the bottom element of $(\mathcal P(S), \subseteq)$ is $\emptyset$.
It does not say that the bottom element of $\mathcal L$ is $\emptyset$.


Concurrent mode failure even when memory is getting reclamied

Question: Here is VM OPS of my application
-Xms7500m
-Xmx7500m
-Xmn4g
-XX:MaxPermSize=192m
-XX:TargetSurvivorRatio=80
-XX:+AggressiveOpts
-XX:+UseFastAccessorMethods
-XX:+UseParNewGC
-XX:+UseConcMarkSweepGC
-XX:+CMSParallelRemarkEnabled
-XX:+UseCMSInitiatingOccupancyOnly
-XX:ConcGCThreads=6
-XX:+PrintGCApplicationStoppedTime
-XX:+PrintGCCause
-verbose:gc
-XX:+PrintGCTimeStamps
-XX:+PrintGCDetails
-XX:+PrintGCDateStamps
-XX:+PrintTenuringDistribution
-XX:+HeapDumpOnOutOfMemoryError

Concurrent mode exception occurred 3 times in 5 days. App is still running file and memory too is available.
2020-04-16T18:57:47.575-0400: 100509.755: [CMS-concurrent-abortable-preclean-start]
2020-04-16T18:57:51.701-0400: 100513.881: [GC (Allocation Failure)2020-04-16T18:57:51.702-0400: 100513.881: [ParNew (promotion failed)
Desired survivor size 343565920 bytes, new threshold 6 (max 6)
- age   1:   91240280 bytes,   91240280 total
- age   2:   52703592 bytes,  143943872 total
- age   3:   26770336 bytes,  170714208 total
- age   4:   29495504 bytes,  200209712 total
- age   5:    9595480 bytes,  209805192 total
- age   6:   24205808 bytes,  234011000 total
: 3710667K->3614781K(3774912K), 1.1252750 secs]2020-04-16T18:57:52.827-0400: 100515.007: [CMS CMS: abort preclean due to time 2020-04-16T18:57:52.894-0400: 100515.074: [CMS-concurrent-abortable-preclean: 4.174/5.319 secs] [Times: user=14.39 sys=0.29, real=5.32 secs]
(concurrent mode failure): 3227087K->1442206K(3485696K), 8.0583310 secs] 6926256K->1442206K(7260608K), [CMS Perm : 105501K->105321K(176020K)], 9.1844190 secs] [Times: user=9.41 sys=0.01, real=9.18 secs]
--
2020-04-19T18:05:09.581-0400: 356551.761: [CMS-concurrent-abortable-preclean-start]
2020-04-19T18:05:11.759-0400: 356553.939: [GC (Allocation Failure)2020-04-19T18:05:11.760-0400: 356553.939: [ParNew (promotion failed)
Desired survivor size 343565920 bytes, new threshold 6 (max 6)
- age   1:   95822816 bytes,   95822816 total
- age   2:   24589528 bytes,  120412344 total
- age   3:   28175272 bytes,  148587616 total
- age   4:   24536120 bytes,  173123736 total
- age   5:   23041104 bytes,  196164840 total
- age   6:   12194152 bytes,  208358992 total
: 3670487K->3606232K(3774912K), 0.9360540 secs]2020-04-19T18:05:12.696-0400: 356554.875: [CMS2020-04-19T18:05:12.758-0400: 356554.938: [CMS-concurrent-abortable-preclean: 2.224/3.177 secs] [Times: user=10.62 sys=0.17, real=3.18 secs]
(concurrent mode failure): 3233090K->1492098K(3485696K), 7.9204130 secs] 6896158K->1492098K(7260608K), [CMS Perm : 105666K->105467K(176212K)], 8.8569600 secs] [Times: user=9.08 sys=0.01, real=8.86 secs]
--
2020-04-22T19:07:04.975-0400: 619467.155: Total time for which application threads were stopped: 0.0047280 seconds
2020-04-22T19:07:07.174-0400: 619469.354: [GC (Allocation Failure)2020-04-22T19:07:07.174-0400: 619469.354: [ParNew (promotion failed)
Desired survivor size 343565920 bytes, new threshold 6 (max 6)
- age   1:   98089096 bytes,   98089096 total
- age   2:   31239384 bytes,  129328480 total
- age   3:   29372368 bytes,  158700848 total
- age   4:   27791800 bytes,  186492648 total
- age   5:   19365904 bytes,  205858552 total
- age   6:   35928016 bytes,  241786568 total
: 3643909K->3678567K(3774912K), 0.9460110 secs]2020-04-22T19:07:08.121-0400: 619470.300: [CMS2020-04-22T19:07:08.234-0400: 619470.413: [CMS-concurrent-abortable-preclean: 2.612/3.582 secs] [Times: user=12.78 sys=0.18, real=3.58 secs]
(concurrent mode failure): 3230258K->1503933K(3485696K), 8.8236640 secs] 6862317K->1503933K(7260608K), [CMS Perm : 105907K->105647K(176596K)], 9.7702040 secs] [Times: user=10.06 sys=0.00, real=9.77 secs]

App don't have FullGC in last one week
2020-04-15T15:03:29.193-0400: 51.372: [Full GC (Permanent Generation Full)2020-04-15T15:03:29.193-0400: 51.373: [CMS: 771051K->1044286K(3485696K), 4.2744340 secs] 1915012K->1044286K(7260608K), [CMS Perm : 101698K->101581K(102128K)], 4.2749400 secs] [Times: user=4.18 sys=0.11, real=4.28 secs]

Why Concurrent mode failure exceptions are coming when

No frequent Full GC
Memory is getting reclaimed after GC
3227087K->1442206K(3485696K), 8.0583310 secs] 6926256K->1442206K(7260608K)
3233090K->1492098K(3485696K), 7.9204130 secs] 6896158K->1492098K(7260608K)
3230258K->1503933K(3485696K), 8.8236640 secs] 6862317K->1503933K(7260608K)

Node configuration: 8 core CPU, 12 GB RAM RHEL VM, JDK 1.7.0_45
Answer: From chapter 8 Concurrent Mark Sweep (CMS) Collector of the Java Platform, Standard Edition HotSpot Virtual Machine Garbage Collection Tuning Guide:

Concurrent Mode Failure
The CMS collector uses one or more garbage collector threads that run simultaneously with the application threads with the goal of completing the collection of the tenured generation before it becomes full. As described previously, in normal operation, the CMS collector does most of its tracing and sweeping work with the application threads still running, so only brief pauses are seen by the application threads. However, if the CMS collector is unable to finish reclaiming the unreachable objects before the tenured generation fills up, or if an allocation cannot be satisfied with the available free space blocks in the tenured generation, then the application is paused and the collection is completed with all the application threads stopped. The inability to complete a collection concurrently is referred to as concurrent mode failure and indicates the need to adjust the CMS collector parameters. If a concurrent collection is interrupted by an explicit garbage collection (System.gc()) or for a garbage collection needed to provide information for diagnostic tools, then a concurrent mode interruption is reported.

It means that, at the time, your application was generating garbage faster than the collector threads could reclaim them, and/or was using so much CPU the collector threads didn't have time to finish the jobs.
Comment: CPU usage is not high ( < 50%).  If memory is getting reclaimed, why the error is thrown is my query
Comment: @Ravindrababu As I already said, **at the time**, your application was generating garbage faster than it was being reclaimed. Were you monitoring the CPU at 7:07 PM on April 22, 2020? If not, how would you know it was < 50%, *at that time*?
Comment: Monitored sar.
19:00:01        all     22.48      0.00      0.85      0.00      0.00     76.67 19:10:01        all     23.84      0.00      0.92      0.02      0.00     75.22. So increasing young gen will address this issue?


Menu Block - stopping displaying children after a specific level

Question: So I am using Menu Block 7.23 and it is working awesome, I have it setup to start at 2nd level to show the children of the active menu, and if no children show active menu with max depth of 1 which has been working great.
I have been asked to make this navigation now, stop displaying the children after the 3rd level and I am not sure how to handle that in Menu Block configurations. I see there is a start level, but not a stop level. Here is an example of my heirarchy:
-Solutions
--Enterprise
---Profile Management
----Online/Offline
So essentially when going to Solutions it would show Enterprise, when going to Enterprise it would show Profile Management, but on Profile Management they do not want Online/Offline to appear, they want Profile Management to remain as the side menu. They want the breadcrumb to show the whole path on Online/Offline so I cannot just disable it from navigation, it needs to be part of the menu structure.
They want to just put reference links to Online/Offline in Profile Management page content, and on Online/Offline it would keep the Profile Management side menu.
Any help would be most appreciated.
Answer: You could use 'display:none' in the css as a solution.  I think using Nth-child would help achieve what you need http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/
Comment: I am afraid I do not understand your solution, I still want the side bar menu to appear on Online/Offline, I just want it to be the menu of the Profile Management. As opposed to the levels above needing to show the children. I basically want to stop showing children items after level 3 and just show that level on all pages after level 3. Hope that clarifies a bit more.
Comment: Ah! Ok what your asking has more to it than what I thought.   What I was getting at is using something like.   #nav ul ul ul ul { display:none;} . Would hide the child navigation.  If you want it to then appear on some pages I suppose it would probably be possible to engineer some php code that checks your page hierarchy .  You could do that in Sass . It's not something I've had to do so this is just in theory.
Comment: Hi Deejay, thanks for responding back, so do you know any place that would be able to help me write php to help me achieve this or how I would go about using Sass, I have never used Sass before.
Comment: There's some pretty helpful vids on YouTube on it :). http://m.youtube.com/watch?v=HN0i9cYekKY
Comment: Thank you for the link, I do see how powerful sass can be but I am not knowledgeable enough to apply this alone.


Bloquear para não mostrar outra div enquanto uma já estiver visível para o usuário

Question: E ae pessoal, bllz?
Pessoal, estou com uma dúvida, tenho um sistema de postagem similar ao do facebook, e como sabem, existe no post para o usuário abrir as configurações para excluir e etc, que ao clicar ele exibe a div com as opções, certo, até aí tudo bem, fiz o sistema para poder aplicar a class 'block' nessa div ao clicar no icone das opções... O problema é, quando o usuário clica no icone, ele exibe, mas ele só desaparece se apertar novamente no icone, e queria que ele sumisse ao clicar em qualquer outro lugar, e tipo, eu apertei exibiu uma, se eu deixar aberta e apertar na configuração de outra publicação, fica visível as duas, e eu queria que sumisse quando eu apertasse em qualquer outro lugar e quando apertasse em uma se tivesse já alguma visível, ele escondesse a visível e mostrasse a que o usuário solicitou, tentei fazer isso com Blur(), mas por algum motivo não deu certo, segue abaixo o código .js, lembrando que estou usando JQuery:::
//Código Js, função para exibir a div .configsOp e também esconder...
$('.configsPost .icon').on('click', function(){
   $(this).parent().find('.configsOp').fadeToggle(200).toggleClass('block');
});

//Código que tentei usar para remover a Class Block da div.configsOp
$('.configsOp').blur(function(){
   $(this).fadeToggle(200).removeClass('block');
 });

Quem souber me ajuda por favor.
Answer: Você ira precisar verificar se existe qualquer evento de clique fora de sua div depois de ela ser clicada, para isso você precisa adicionar um listener de eventos no seu código e limitar o evento para somente ser executado em elementos diferente do seu botão (no exemplo abaixo limitei ao botão e aos links)

function ocultar(event) {
  if (!$(event.target).parents('.configsPost.icon').length) {
    $('.configsOp').removeClass("block");
  }
}
document.addEventListener("click", ocultar);
$('.configsPost.icon').on('click', function mostrar() {

  $('.configsOp').addClass("block");

});
.configsOp {
  background-color: #ccc;
  width: 200px;
  height: 0;
  overflow: hidden;
}

a {
  display: block;
}

.block {
  height: auto;
}

  <button>Clique para opções</button>

    opcão 1
    opção 2

Comment: Essa não funcionou pra mim não.
Comment: E não quero chamar função no código HTML não, mas sim chamar a div diretamente no código.
Comment: execute o snippet que enviei no próprio stack overflow (botão executar) e verifique se possuí o comportamento desejado, com relação a não chamar no código html posso modificar meu exemplo sem problemas
Comment: modifiquei o exemplo para o evento ser executado via javascript ( e não inserido diretamente no código html)
Answer: Quando clicar no ícone, basta esconder todos os outros que estiverem sendo exibidos antes de mostrar, caso ele não possua a classe block:
//Código Js, função para exibir a div .configsOp e também esconder...
$('.configsPost .icon').on('click', function() {
  // se o div deste ícone não estiver com classe block, remove essa classe de outros divs que podem estar ativos
  if(!$(this).parent().find('.configsOp').hasClass('block')) {
    $('.configsOp').fadeToggle(200).removeClass('block');
  }
  $(this).parent().find('.configsOp').fadeToggle(200).toggleClass('block');
});

Comment: Muito obrigado cara, Tentei da mesma forma, só que eu não sabia como usar direito o hasClass(), então acabei me atrapalhando, por que eu tinha colocado assim:
if(!$(this).parent().find('.configsOp').hasClass('') == 'block') {
    $('.configsOp').fadeToggle(200).removeClass('block');
  }

Aí Não tinha dado certoo, então eu tentei da forma que tava embaixo
if(!$(this).parent().find('.configsOp').hasClass('block') == 'block') {
    $('.configsOp').fadeToggle(200).removeClass('block');
  }
Por que eu não sabia como fazia essas verificações de classes com JQuery, apenas com JavaScript puro
Comment: E a sua forma ficou muitoo boa, eu apenas removi o fadeToogle(), por que estava dando um pequeno probleminha no efeito de visibilidade, tipo, ele mostrava e dps dava tipo uma piscada sabe pra mostrar com o efeito, então eu resolvi tirar mesmo e ficou bem melhor, obrigado mesmo.
Comment: Beleza. Se estiver com outras dúvidas com as funções do JQuery, a documentação deles é ótima, https://api.jquery.com/ - tem a descrição de cada função e alguns exemplos
Answer: Pessoaal, obrigado pela força novamente, me ajudaram demais mesmo nisso.
E o código final ficou assim pelo do @Dudaskank:
//Código Js, função para exibir a div .configsOp e também esconder...
$('.configsPost .icon').on('click', function() {
  // se o div deste ícone não estiver com classe block, remove essa classe de outros divs que podem estar ativos
  if(!$(this).parent().find('.configsOp').hasClass('block')) {
    $('.configsOp').removeClass('block');
  }
  $(this).parent().find('.configsOp').toggleClass('block');
});

Deixei com os comentários dele aqui no site para vocês, eu retirei apenas os fadeToggle(), pois estavam dando um pequenino problema na hora da exibição, pois ele mostrava instantâneamente a div e depois adicionava o efeito, então dava uma piscada na hora que mostrava. Mas tá aí, sem nenhum erro para quem estiver com caso igual ou semelhante


Como unir arquivos em pastas, baseado em seus prefixos?

Question: Tenho em mão milhares de arquivos que possuem prefixos comuns em seus nomes, algo como:
[Exemplo de prefixo 1]

ABC-1.mp4
ABC-2.mp4
ABC-3.mp4
[...]
ABC-999.mp4

[Exemplo de prefixo 2]

AAA-1.mp4
AAA-2.mp4
AAA-3.mp4
[...]
AAA-999.mp4

Porém, são milhares de arquivos e milhares de prefixos em comum. Gostaria de unir os arquivos que possuem mesmo prefixo numa mesma pasta, sendo que a pasta teria o nome do prefixo, como por exemplo:

ABC (seria o nome da pasta)

ABC-1.mp4
ABC-2.mp4
ABC-3.mp4
[...]
ABC-999.mp4

AAA (seria o nome da pasta)

AAA-1.mp4
AAA-2.mp4
AAA-3.mp4
[...]
AAA-999.mp4
Comment: Isso precisa ser feito em C ou a linguagem não importa? Outra dúvida, Linux ou Windows?
Comment: Qualquer linguagem, o importante é solucionar esse problema.. Windows
Answer: Solução na linguagem Groovy 2.4.4
Download do Groovy: http://www.groovy-lang.org/download.html
É preciso ter o Java instalado para o Groovy funcionar.
def folders = new File("/home/cantoni/Documents/Teste")
def destFolder = "/home/cantoni/Documents/Teste2/"

folders.listFiles().groupBy {it.name.substring(0,3)}.each {group ->
    def folder = new File(destFolder + group.key)
    if (!folder.exists()) new File(destFolder + group.key).mkdir()

    def files = group.value

    files.each {
        it.renameTo(folder.absolutePath + "/" + it.name)
    }
}

Código explicado
O código acima, percorre todos os arquivos que estão dentro da pasta especificada pela variável folders, logo em seguida, agrupa-os pelos 3 primeiros caracteres que compõe o nome.
folders.listFiles().groupBy {it.name.substring(0,3)}

O resultado do agrupamento é um map, onde a chave são os 3 primeiros caracteres e o valor são os arquivos que possuem esses 3 primeiros caracteres no nome. Exemplo:
AAA-123.TXT
AAC-234.TXT
AAA-553.TXT
AAC-001.TXT
CCC-987.TXT

O mapa ficaria assim:
AAA: [AAA-123.TXT,AAA-553.TXT], AAC: [AAC-234.TXT,AAC-001.TXT], CCC: [CCC-987.TXT]

A partir disso, cria-se a pasta (caso a mesma não exista), dentro da pasta especificada pela variável destFolder. O nome de cada pasta é o key do map, ou seja, os três primeiros caracteres.
    def folder = new File(destFolder + group.key)
    if (!folder.exists()) new File(destFolder + group.key).mkdir()

Criada a pasta, é hora de mover os arquivos. O value do map são os arquivos que compartilham da mesma chave. Assim, basta recuperá-los, percorrê-los e, para cada um, realizar o procedimento de movê-los do local atual para a pasta de destino, destFolder.
    def files = group.value

    files.each {
        it.renameTo(folder.absolutePath + "/" + it.name)
    }

Atenção
Esse código foi testado no Linux e funciona. Faça um teste com outros arquivos antes de rodá-lo com seus arquivos de produção. Precaução nunca é demais.
Comment: E se eu quiser que a chave para o agrupamento seja os caracteres antes de um hífen (-), incluindo espaços, ao invés de ser os 3 primeiros caracteres?
Comment: folders.listFiles().groupBy {it.name.substring(0,it.name.indexOf("-"))}. Note, entretanto, que isso só funcionará se existir o caracter "-" no nome do arquivo. Caso não exista, não vai rodar. Se você tiver um cenário bem padronizado, esse código, da maneira que está, ajudará. Caso exista um cenário heterogêneo, é preciso modificá-lo. Certamente, nada complicado, principalmente porque se trata de Groovy.
Comment: Poderia explicar essa linha do código? def folders = new File("/home/cantoni/Documents/Teste")
Comment: Nesta linha, estou instanciando um objeto do tipo File, passando como parametro uma pasta do meu computador, o objeto File (sua referencia na realidade), está sendo atribuída à variável folders. No seu caso (Windows), seria algo como: def folders = new File("C:\Users\thiago\PastaX").
Comment: Qual a diferença para o destFolder?
Comment: folder é a pasta de origem, aonde se encontram os arquivos que você deseja separar. destFolder é a variável que guarda a pasta de destino.


Is there any difference between bool() vs == in python truth testing?

Question: I have two questions.

Can ANYTHING (objects, types, operations, functions..) in python return a boolean value when it is called upon by the bool() method?
Why dont the following two lines of code return the same answer?
print (float == True)  #prints False
print bool(float)      #prints True

Comment: because 0.02 is not equal to `True`, but implements `__nonzero__` interface, which returns `True` (because 0.02 is not zero).
Comment: `float` is ``, and of course that it's different than `True`
Comment: https://docs.python.org/3/reference/expressions.html#boolean-operations.  ```==``` always consider objects of different types to be unequal - from https://docs.python.org/3/reference/expressions.html#not-in
Comment: oh ok.. i understand..
Answer: The two, == and bool(), are different. == is for equality testing, whereas bool() returns the result of truth value testing for the object passed to it as parameter.
According to documentation of bool() -

class bool([x])
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure. If x is false or omitted, this returns False; otherwise it returns True.

The standard truth testing procedure can be found in the documentation -

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered True — so objects of many types are always true.

When you do bool(float), you are checking the truth value for float, which is True.
But when you do float == True, you are doing equality (please note this is not truth value testing, it is equality). In this case float and True are not equal so that results in False.
Comment: thanks.. I have another question.. so i understand that "float" is a type. But what would I classify  "True" as?
Comment: A singleton immutable object? Or a bool: `>>> type(False)` says ``.
Answer:
Yes. The docs for bool() say:

class bool([x])
Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.

The standard truth testing procedure works on any object:

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false: [...] All other values are considered true — so objects of many types are always true.

float is not equal to True. However, when asking "is float a truthy value", i.e. would if float: evaluate the true branch or the false branch, the answer is "yes, it would evaluate the true branch".
Answer:
Yes every object in Python returns a boolean value, when used with bool which calls the __nonzero__-method of this object
because the first print does not call the __nonzero__ method.
Comment: Actually it doesn't always call `__nonzero__`. Consider: `a = object(); a.__nonzero__()` yields an `AttributeError`, yet `bool(a)` is `True`.


How to implement SIS Thresholding in python opencv

Question: In Aforge.net I saw one thresholding named SIS (Simple Image Statistics) Thresholding. How can I implement the same thresholding in opencv python? A link is provided in the comments.
Comment: Please give much more information. We do not know what SIS means and how it relates to thresholding. Please provide a reference link. Also read how to ask a proper question on this forum.
Comment: http://www.aforgenet.com/framework/docs/html/39e861e0-e4bb-7e09-c067-6cbda5d646f3.htm. Please go thru the link .
I want to do same thresholding in opencv . I couldn't find any specific function.
Answer: I do not know OpenCV that well. But this is how I would do it in ImageMagick 7 command line on Bash Unix.
IM 7 (HDRI default) with clamp=off is needed, to avoid the clipping of the convolution for values outside the quantum range (that would happen for non-HDRI).
I note that -scale 1x1! will compute the average, not the sum. But since both numerator and denominator have the same number of pixels, the ratio will not matter whether I sum or average.
Input:

<code>wt=`magick sample11.png \
\( -clone 0 -define convolve:scale=! -define compose:clamp=off -morphology convolve "3x1: -1,0,1" +duplicate -compose multiply -composite -evaluate pow 0.5 \) \
\( -clone 0 -define convolve:scale=! -define compose:clamp=off -morphology convolve "1x3: -1,0,1" +duplicate -compose multiply -composite -evaluate pow 0.5 \) \
-delete 0 -evaluate-sequence max \
-scale 1x1! -format "%[fx:u]" info:`

wtI=`magick sample11.png \
\( -clone 0 -define convolve:scale=! -define compose:clamp=off -morphology convolve "3x1: -1,0,1" +duplicate -compose multiply -composite -evaluate pow 0.5 \) \
\( -clone 0 -define convolve:scale=! -define compose:clamp=off -morphology convolve "1x3: -1,0,1" +duplicate -compose multiply -composite -evaluate pow 0.5 \) \
\( -clone 1,2 -evaluate-sequence max \) \
-delete 1,2 \
-evaluate-sequence multiply \
-scale 1x1! -format "%[fx:u]" info:`

thresh=`convert xc: -format "%[fx:100*$wtI/$wt]" info:`
echo $thresh
50.0114

magick sample11.png -threshold $thresh% result.png
</code>

Here are some useful links for doing the convolution, difference, absolute value, multiply and mean(average) in Python OpenCV:
https://www.pyimagesearch.com/2016/07/25/convolutions-with-opencv-and-python/
https://docs.opencv.org/2.4/modules/core/doc/operations_on_arrays.html
However, I do not think it does a very good job on real images. I tried on a few. Here is one example:

and here is the result:

So I question what the goal of this thresholding is or what types of images does it do well on?


Access to a model attribute in Javascript with Spring MVC

Question:
I have some problem accessing to model attribute in Javascript; in particular I have this controller:
    @RequestMapping(value = "/dashboard")
    public ModelAndView home(HttpServletRequest request, HttpServletResponse
    res, Model model) {
        // Return answer's dictionary from DB to dashboard view
        CompQuest dizRisp = new CompQuest();
        dizRisp.setDizComp(dashDao.getRispEnd());
        model.addAttribute("dizRisp", dizRisp);

        return new ModelAndView("dashboard");
    }

and I have this Javascript file (here: only the part with the code for my chart where I want to refer to model attribute) where I want to access to model attribute "dizRisp" from my controller:
var ctx1 = document.getElementById('myChart1').getContext('2d');
var myRadarChart = new Chart(ctx1, {
    type: 'radar',
    data: {
        labels: ['Valori e identità del SCN', 'La cittadinanza attiva',
              'Il giovane volontario nel sistema del SC', 'Lavorare',
              'Prevenzione e protezione', 'Normativa sicurezza',
              'Rischi sulla salute in tema di ambiente'
        ],
        datasets: [{
            label: "Civiche",
            data: [4, 5, 5, 2, 4, 5, 4],
            fill: true,
            borderJoinStyle: "round"
        }],
    },
    options: {
        maintainAspectRatio: false,
        scale: {
            ticks: {
                stepSize: 1,
                step: 1,
                beginAtZero: true,
                max: 5
            }
        }
    }
});

My classes are (here: no getters and setters):
public class CompQuest {
private HashMap <String, CompRisp> dizComp;}

public class CompRisp {
private ArrayList <Risposte> rispList = new ArrayList <Risposte> ();}

public class Risposte {
int id;
Domande domande;
int valore;
int momento; }

public class Domande {
int id;
String testo;
String descrizione;
Questionario questionario; }

My .jsp file:

<meta charset="UTF-8">

<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/dashboard.css">
<title>Dashboard</title>

In particular I would want to access to my model attribute (Hashmap) in order to put in label and datasets field of my Javascript chart values from my Hashmap that contains data from my Database.
Thanks in advance to everyone that can help me!
Answer: Spring controller
    @RequestMapping(value = "/dashboard")
    public ModelAndView home(HttpServletRequest request,
    HttpServletResponse
    res, Model model) {

        // Return answer's dictionary from DB to dashboard view
        CompQuest dizRisp = new CompQuest();
        dizRisp.setDizComp(dashDao.getRispEnd());

        Gson gson = new Gson() ;
        // Use Gson dependency to convert hashmap to String

        String strmap = gson.toJson(dizRisp)
        model.addAttribute("dizRisp", strmap);

        return new ModelAndView("dashboard");
    }

Javascript

Hope this is what your trying to achieve.
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/185338/discussion-on-answer-by-thivankaw-access-to-a-model-attribute-in-javascript-with).


UIBarButtonItem's customView accessibility

Question: I've created UIBarButtonItem with customView set to BadgeButton (a UIButton that has badge label added).
I am setting accessibilityIdentifier = "properIDHere" and isAccessibilityElement = true  for both: aBadgeButton and aBadgeButton.badgeLabel
When running UITests the badge button is visible and accessible by the ID, but the badgeLabel is not. Do you have ideas why?
final class BadgeButton: MyBaseButton {
   let badgeLabel = UILabel()

   override func addSubviews() {
    addSubview(badgeLabel)
   }

   override func setupConstraints() {
    badgeLabel.snp.makeConstraints { make in
        make.width.height.equalTo(badgeSize)
        make.centerX.equalToSuperview().offset(badgeXOffset)
        make.centerY.equalToSuperview().offset(badgeYOffset)
    }
}

Answer: The runTime lable need a frame or constraint.
final class BadgeButton: UIButton {
        let badgeLabel = UILabel()
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupView()
        }

        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
            setupView()
        }

        func setupView() {
            self.addSubview(badgeLabel)
            badgeLabel.frame = CGRect(x: self.frame.width / 2, y: 0, width: 20, height: 20)
            //or you setup runTime Constraint
        }
    }

Comment: Thanks for the suggestion, adding the badge as subview and layouting it seemed obvious to me. Badge is normally visible, but not through the XCTest accessibility inspector
Answer: On the BadgeButton parent/custom view, try disabling accessibility. Leave it enabled for the UILabel.
After this, back in your XCTestCase, print out the XCUIApplication().debugDescription to see if you're now able to see the UILabel's accessibility information in the app's element hierarchy.
See this post as a possible duplicate:
Xcode UI Tests can't find views that are added programatically


Como fazer lógica de habilitar campo de texto por vez quando preenchido

Question: Como devo proceder com a lógica?
Ha um Formulário de cadastro de dados na página, à saber:

Nome
Sobrenome
Idade
Celular

Preciso deixar estes campos da seguinte forma:
1- Quando a página for carregada o campo Sobrenome, Idade e Celular deveram estar desabilitado
2- Quando clicar e preencher o próximo campo abaixo deverá ficar habilitado
3- E assim por diante, para os demais, sendo sucessivamente
Por fim, quando todos os campos forem preenchidos aparecerá o botão submit.

NOTA - Quando o formulário receber o evento submit voltam agora todos os campos [nome, sobrenome, idade e celular] a ficar inacessíveis.

Pra se ter uma Idéia introdutória

function Inibe() {
  document.formulario.T1.disabled = true;
}

function Exibe() {
  document.formulario.T1.disabled = false;
}
<form name="formulario">

<input type="text" name="T1" size="20" onload="Inibe()">

<input type="radio" name="a" onClick="Exibe()" value="1">Habilita

<input type="radio" name="a" onClick="Inibe()" value="2" checked>Desabilita

</form>
Comment: Uma das forma de se fazer isso seria: 1) definir a quantidade mínima de caracteres para cada campo 2) contar os caracteres no momento em que forem digitados 3) Se a quantidade for igual ou superior habilita o próximo campo, do contrário não. Linguagens: javascript ou jquery
Comment: @WilsonRosaGomes Então Wilson, o meio de validar a quantidade de caracteres dentro de cada campo ja possuo em Javascript! Agora, se por ventura tiver um exemplo prático neste segmento poderia postar como resposta por gentileza.
Answer: Com o JQuery você pode fazer desta forma (acompanhe os comentários):

$($("input").on("change input paste", function(){ //Event handle para quando o usuario escrever algo
    if ($(this).val()){ //Checa se tem valor (truthy)
        let atual = $(this).data("order") //Pega a ordem do input
        $('input[data-order="' + (atual + 1) + '"]').removeAttr("disabled") //Remove o atributo disabled do prox input
    }
    else{
     $("input[type=submit]").attr("disabled", true) //Adiciona disable ao botão
    }
}))

<form onsubmit="return false">
<input data-order="1" placeholder="nome">
<input data-order="2" placeholder="sobrenome" disabled>
<input data-order="3" placeholder="idade" disabled>
<input data-order="4" placeholder="celular" disabled>
<input data-order="5" type="submit" disabled>
</form>

Veja funcionando no JSFiddle.
Agora com o Javascript puro, usando ES6, você pode fazer desta forma:

changed = (input) => {
    if (input.value){ //Checa se tem valor (truthy)
        let atual = parseInt(input.getAttribute("data-order")) //Pega a ordem do input
        document.querySelector('input[data-order="' + (atual + 1) + '"]').removeAttribute("disabled") //Remove o atributo disabled do prox input
    }
    else{    document.querySelector("input[type=submit]").setAttribute("disabled", true) //Adiciona disable ao botão
    }
}
<form onsubmit="return false">
<input data-order="1" onchange="changed(this)" oninput="changed(this)" placeholder="nome">
<input data-order="2" onchange="changed(this)" oninput="changed(this)" placeholder="sobrenome" disabled>
<input data-order="3" onchange="changed(this)" oninput="changed(this)" placeholder="idade" disabled>
<input data-order="4" onchange="changed(this)" oninput="changed(this)" placeholder="celular" disabled>
<input data-order="5" type="submit" disabled>
</form>

Ficaria assim: https://jsfiddle.net/a4tmj2d4/4/
Comment: Não precisa colocar `document.querySelector('input[data-order="' + (atual + 1) + '"]')`, basta colocar `input.nextElementSibling`
Answer: Habilita campo de texto por vez quando preenchido, e desabilita os subsequentes quando limpa um campo.

$(document).ready(function() {
  $('.step').on("change input paste", function() {
    next_step = $(this).next('.step');
    all_next_steps = $(this).nextAll('.step');
    // Se o elemento tiver um valor
    if ($(this).val()) {
        // deve também realizar a validação aqui
        next_step.attr('disabled', false);
    }
    // Se o elemento não tiver um valor ou for apagado
    else {
        // limpa o valor de todas as próximas etapas e adiciona disable
        all_next_steps.val('');
        all_next_steps.attr('disabled', true);
    }
  });

  $("#habilita").click(function (){
       // habilita o primeiro campo
        $("#step1").prop("disabled", false);

    });

    $("#desabilita").click(function (){
       // desabilita e limpa  tudo
        $('input[id^="step"]').val('');
        $('input[id^="step"]').prop("disabled", true);

        /******BONUS******/
        $('#step6').attr('disabled','disabled');
        $('#step6').val('');
        /****************/

    });
});

<form class="formulario">

    <input type="text" class="step" id="step1" name="T1" disabled/>
    <input type="text" class="step" id="step2" disabled />
    <input type="text" class="step" id="step3" disabled />
    <input type="text" class="step" id="step4" disabled />
    <input type="text" class="step" id="step5" disabled />

    <select id="step6" class="step" data-id="cazzo" disabled>
        <option value="">Escolha um</option>
        <option value="Leo">Leo</option>
        <option value="Francisco">Francisco</option>
    </select>

<input type="radio" name="a" value="1" id="habilita">Habilita
<input type="radio" name="a" id="desabilita" checked>Desabilita

</form>

Caso queira validar também a quantidade de caracteres nos inputs
troque essa linha
if ($(this).val()) {
por essa
if (($(this).val())&&($(this).val()).length>3) {

length>3 significa quantidade de caracteres acima de 3

$(document).ready(function() {
  $('.step').on("change input paste", function() {
    next_step = $(this).next('.step');
    all_next_steps = $(this).nextAll('.step');

    if (($(this).val())&&($(this).val()).length>3) {
        next_step.attr('disabled', false);
    }
    // Se o elemento não tiver um valor ou for apagado
    else {
        all_next_steps.val('');
        all_next_steps.attr('disabled', true);
    }
  });

  $("#habilita").click(function (){
        $("#step1").prop("disabled", false);
    });

    $("#desabilita").click(function (){
        $('input[id^="step"]').val('');
        $('input[id^="step"]').prop("disabled", true);

        /******BONUS******/
        $('#step6').attr('disabled','disabled');
        $('#step6').val('');
        /****************/

    });
});

<form class="formulario">

    <input type="text" class="step" id="step1" name="T1" disabled/>
    <input type="text" class="step" id="step2" disabled />
    <input type="text" class="step" id="step3" disabled />
    <input type="text" class="step" id="step4" disabled />
    <input type="text" class="step" id="step5" disabled />

    <select id="step6" class="step" data-id="cazzo" disabled>
        <option value="">Escolha um</option>
        <option value="Leo">Leo</option>
        <option value="Francisco">Francisco</option>
    </select>

<input type="radio" name="a" value="1" id="habilita">Habilita
<input type="radio" name="a" id="desabilita" checked>Desabilita

</form>


Solving $a^2+b^2\equiv 0$ mod $c$ for distinct integers $a,b,c$ constrained between two consecutive squares

Question: Show that for any natural number $n$, between $n^2$ and $(n+1)^2$ one can find three distinct natural numbers $a,b,c$ such that $a^2+b^2$ is divisible by $c$.
A friend and I found a general case that always work with a computer problem, I would like to see a different solution, or a solution that tells the motivation of how to find that general case without a computer.
Comment: By between, do you mean inclusive/exclusive on the lower and upper bounds?
Comment: It must be strict intervals, $n^2 < a,b,c < (n+1)^2$
If it helps, I already found out that $a = n^2+2$ and $b=n^2+n+1$ give $c = n^2+1$. But I haven't found out a way to do it without a computer, I would like to see a motivated proof.
Comment: Hmmm... I have the desire that is exactly opposite to yours: can you tell how you used a computer here?
Comment: Note that for n=1, then you're looking between 1 and 4 which only has 2 and 3 unless the ends can be included as something to note here.
Answer: This is sort of cheating, since I already saw the answer in your comments, so my ability to reinvent the solution is questionable. That said, here's a hypothetical way to solve it.
We want $a, b, c$ such that
$$a^2 + b^2 \equiv 0 \pmod c$$
This suggests that we pick $c$ to be a sum of squares $d^2+e^2$ and then pick $a$ and $b$ so that
$$a \equiv d \pmod c$$
$$b \equiv e \pmod c$$
Then we have $a^2+b^2 \equiv d^2+e^2 \equiv 0 \pmod c$.
We try some values. With the constraint that $n^2<c<(n+1)^2$, our choices are sort of limited, so it doesn't take too long to hit upon $d=n$, $e=1$. That produces
$$c=n^2+1$$
$$a=n^2+n+1$$
$$b=n^2+2$$
and we're done.
Comment: But how can I found those?
Could  you add the motivation?
Comment: @user116489: Try things? I just tried squaring a few things until I found some numbers that worked. Once I tried squaring $(n+1)^2-1$, it was a pretty easy jump to looking at other multiples of $n$.
Comment: Ooooops I just re-read the problem and it is not inclusive, $c$ must be greater than $n^2$
Comment: @user116489: Then you can't do it. For $n=1$, no choice of numbers works.
Comment: Yeah, it mentions that $n \ge 2$ as well.
Comment: @user116489: Solution edited.
Answer:
I would like to see a motivated proof

It looks like it is easier to be divisible by a smaller number, so let $c$ be the least one. The only thing that matters for divisibility of the sum of squares by $c$ is what remainders $a,b$ have modulo $c$, so let $x,y$ be those remainders. Then, since we are squeezed in a narrow window, we have $a=c+x$, $b=c+y$, $c|x^2+y^2$. Now, $c>n^2$ and, certainly, $x,y<2n$, so if $x^2+y^2=kc$, we have $1\le k\le 7$ and it looks like the less $k$ is, the more room we have. Thus, we want $0<x<y$ so that $x^2+y^2>n^2$ and $x^2+y^2+y<(n+1)^2$. Now it is pretty clear where the formulae you mentioned came from: to have more room, we want to have $c$ as much to the left as possible, so let us try $c=n^2+1$. Then the trivial representation $c=x^2+y^2$ with $x=1,y=n$ jumps at you and this choice works. The other extreme would be trying to make the step $y$ as small as possible, i.e., to choose the least $x>\frac n{\sqrt 2}$ and put $y=x+1$. However, the trivial estimate for the "offset" $c-n^2$ will then be of order $3\sqrt 2n$, which is greater than $2n$, so, to make this plan work, we'll need to exercise more care. It is still possible and even gives smaller "range" for really large $n$: you can squeeze $a,b,c$ between $n^2$ and $n^2+qn$ for any $q>\frac 1{\sqrt 2}$ and $n>n_0(q)$, which is pretty much the best one can hope for. Still, this small improvement is hardly worth the cost as far as the original problem is concerned.
Comment: Where did the $1 \le k \le 7$ came from?
Comment: $\frac{x^2+y^2}{c}<\frac{2\cdot(2n)^2}{n^2}=8$


Maximum Value for Unsigned Int is it -1

Question: I was trying to figure out the minimum and maximum value for an unsigned data type. I know that the minimum unsigned value is 0 and the maximum value is (2^n)-1. However, when I tried to run my program (I cannot post my code, but you can refer to this), I keep getting -1 as the maximum value. Can someone explain to me why? Also, UINT_MAX is giving me 4294967295 while ULLONG_MAX is 4294967295. However, the maximum value of unsigned int is supposed to be 65535 while unsigned long long int is supposed to be +18,446,744,073,709,551,615.Why is it the output is different?
Comment: Maybe you are printing it with wrong format specifier?
Comment: UINT_MAX is the same bit-wise as -1 in two's complement notation.  You're probably printing it out as a signed integer.
Answer: Whats the format specifier are you using to print those values ?
These kind of error mostly occur due to wrong format specifier.
<code>#include <stdio.h>
#include <limits.h>

int main()
{
    printf("%u", UINT_MAX); // This will print 4294967295 (system dependent)
    printf("%d", UINT_MAX); // This will print -1
    return 0;
}
</code>
Comment: `printf("%d", UINT_MAX); // This will print -1` This is also system dependent as not every system is two's complement.
Comment: @ChristianGibbons: While in theory non-twos-complement machines can exist, you won't find one outside a museum.
Comment: I agree with both of your comment
Comment: the `%d` ver is undefined behaviour so could print anything , or format your hard drive
Comment: My classmates are also getting -1

Maximum Value for Unsigned Int is it -1


Traffic shaping for upload/download speed simulation

Question: I'm building a network emulator to help realize different speeds. Basically, this system would shape a given user's network metrics (such as upload speed/download speeds/packet loss/jitter etc) based on the user's request. For instance, if a user selected 3G, the system would transform his/her connection to behave like a 3G connection. I imagine doing this by using the user's IP address.
I have been searching for some help on this but couldn't find a lot. I wonder if this is feasible at all.
Answer: You can simulate the drop packages using something like this:
iptables -A OUTPUT -p tcp -d [your station ip] --sport 80 -m statistic --mode random --probability 0.2 -j DROP
Translate to: the server will drop with a probability of 20 percent packets going to your station.
For more advanced options take a look at this.
Comment: Can we do this differently for each user? I would like to set a different package drop for each user.


Time/Resource/Machine problem

Question: I am unable to solve this question.

If $3$ people can work on $120$ machines over $10$ days to finish, then in how many days much does $5$ people working on $90$ machines finish the same task ?

Regards,
Answer: This Wikipedia page might help.

It takes $(3 \text{ people}) (10 \text{ days}) = 30 \text{ person-days}$ to finish working on $120 \text{ machines}$.
Multiplying by $\dfrac{90 \text{ machines}}{120 \text{ machines}} = \dfrac{3}{4}$, we know that it takes $30 \cdot \dfrac{3}{4} = \dfrac{45}{2}\text{ person-days}$ to finish working on $120 \cdot \dfrac{3}{4} = 90 \text{ machines}$.
Since there are $5 \text{ people}$, it will take $\dfrac{45/2 \text{ person-days}}{5 \text{ people}} = \dfrac{9}{2}=4.5 \text{ days}$ to finish working on $90 \text{ machines}$.

Time/Resource/Machine problem


Set div background color to inherit when checkbox is unchecked

Question: I currently have checkboxes in groups; I want to be able to set color of unchecked checkboxes when a checkbox is checked.

var name = $("input:checkbox[name='fooby[2][]']:checked").prop('id')
var unique_id = $(this).parent().find('label[for="' + name + '"]').find('div.eachText').attr('id')
var2 = $("input:checkbox[name='fooby[2][]']:checked")
if ($(var2).is(":checked")) {
  $("input:checkbox[name='fooby[2][]']:checked").map(function() {
    document.getElementById(unique_id).style.backgroundColor = 'grey';
  })

} else {
  document.getElementById(unique_id).style.backgroundColor = 'inherit'
}

<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />

        dTLA

            555 West 5th street, 34th floor
 811 W 7th St

<input type="checkbox " class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />

  Long Beach

    100 W Broadway

My goal is to be able to set checkbox to grey when checked and to inherit when unchecked.
Comment: `type="checkbox" class="radio"` um that does not make it a radio button....
Answer: No need for JavaScript to set the color with that markup. Just use CSS checked and sibling selector

input[type="checkbox"]:checked + label > div {
   background-color: red;
}
<input type="checkbox" class="radio" value="dTLA" id="group4" name="fooby[2][]" />

        dTLA

            555 West 5th street, 34th floor
 811 W 7th St

<input type="checkbox" class="radio " value="Long Beach " id="group5 " name="fooby[2][] " />

  Long Beach

    100 W Broadway


Google Calendar Watch and Events working together

Question: I am creating a Node/Express Webapp that would mirror a user's calendar. It would get a notification for every change in the users calendar, and would update the DB with the latest of that user's calendar.
Lets assume that we want to monitor email@example.com. Kindly tell me if this is the best (and only) way to do it:

Set up for Push notification - While doing so, we provide (amongst other fields):

token - A plain-text that would be echoed back. This is where I can put something like 'email@example.com'
id - A UUID channel id

Upon every change, my webhook will get a push notification that would contain:

token : email@example.com
id : the channelId - I dont understand if this field alone can be used to trace this notification message back to email@example.com

Now that I know firstname.lastname@example.com has changed, I would do a list with a synchToken. This will return me the change in john's calendar since last synch

What baffles me here is that the seemingly important fields channelId and resourceId (which appears as x-goog-resource-id in the push notification header) are useless, and the only field that ties the push message to list is an optional plain-text field token .
Kindly tell me if this is the only way to track a user's calendar.
UPDATE
Thanks @KENdi for the answer.
My struggle was with the point that simply looking at a push notification message, there is no way to trace it back to email@example.com . I now understand why such is the case, that a push notification does not contain the calendarId, but the resourceId instead (which, in plain terms is the event object). It is so because an event can be associated with multiple calendars, and hence multiple calendarIds. Hence, it is the subscriber's responsibility to maintain association of the channel to the calendarId that he had used to create the channel at the first place.
Answer: Yes, you are correct, you need the calendar push notification, to notify you about all the changes happened in the Google Calendar.
The purpose of X-Goog-Resource-ID is an opaque value that identifies the watched resource. And this ID is stable across API versions.
Check this SO question to know more about the purpose of X-Goog-Resource-Id.


Reducing the execution time of the code using CLANG/LLVM compiler

Question: Well... When i was searching for a good compiler I came across clang/LLVM. This compiler gives me same result as other compilers like icc, pgi. But the problem is there are very few tutorials on this compiler... Kindly let me know where can I find the tutorials on the clang compiler.
Note by:
I have compiled my c code using the following flags  clang -O3 -mfpmath=sse file.c
Comment: this is second question from you about ways of optimizing (making faster) code. May be you can post the actual code on StackOverflow? Only that part of code which takes a lot of execution time.
Answer: Clang (the command line compiler) takes gcc-compatible options, but accepts and ignores a lot of flags that GCC takes (like -mfpmath=sse).  We aim to generate good code out of the box.  There are some flags that allow clang to violate the language standards that can be useful in some scenarios, like -ffast-math though.
If you're looking for good performance, I highly recommend experimenting with link-time-optimization, which allows clang to optimize across source files in your application.  Depending on what platform you're on, this is enabled by passing -O4 to the compiler.  If you're on linux, you need to use the "gold" linker (see http://llvm.org/docs/GoldPlugin.html).  If you're on the mac, it should "just work" with any recent version of Xcode.
Comment: I can't find a page that list the gcc options that clang actually takes into account (like -ffast-math). Is there a such page?
Comment: @AlexandreHamez The man page lists -ffast-math. I would guess that the man page is authoritative.
Answer: The clang is not a compiler, it is just frontend of LLVM compiler. So, when you calls clang, it parses c/c++ file but the optimization and code generation is handled in LLVM itself.
Here you can found a documentation of LLVM optimization and analysis options: http://llvm.org/docs/Passes.html
The full documentation is here http://llvm.org/docs/
Also useful options are listed here http://linux.die.net/man/1/llvmc (I suggest clang will accept most of them too)
Comment: I think that Clang simply pass those to the LLVM compiler :)
Comment: @Matthieu M., yes it can pass some. But also (at least theoretically) it can disallow some options and give a error (abort) on them. E.g. clang can abort on `-x` option with not c/c++ lang, but llvmc itself can accept this lang if it have a frontend for it.


php post input validation

Question: how can I validate on test.php to echo all of the entered text for fname value to be echo as text and only text whether its html,js or php

<form action="test.php" method="POST">
Enter Your name : <input type="text" name="fname">
<input type="submit">
</form>

Comment: [What have you tried?](http://www.whathaveyoutried.com/) See [ask advice](http://stackoverflow.com/questions/ask-advice), please.
Answer: this is the key
htmlspecialchars()
Answer: htmlspecialchars() or htmlentities() will achieve what you need.
An example:
if (isset($_POST['txtExample'])) {
    echo(htmlentities($_POST['txtExample']), ENT_QUOTES));
}

Good luck.

php post input validation


Copy data from a selected view in a fieldcollection field

Question: I have content_type TYPE1 content with two fields:

fiedl_1 is a viewfield type that allows me to display a view inside a node.
fiedl_2 is fieldcollection type.

Is it possible to copy the rows resulting from the view into my fielcollection?
Thanks a lot
Comment: What do you mean by copy? Are you wanting to move the view field into your field collection, or are you wanting to copy the data in the view into different fields into the field collection?
Comment: Thank you so much for your help @Shawn Conn.
Yes, I want to copy the data returned by the view in my field collection.
Answer: Yes, it's possible but you're going to have to do some hoop jumping to make it happen:

Determine when this copy action will happen (e.g. hook_entity_update trigger).
Programmatically retrieve the View's data (e.g. via Views::getView() /  views_get_view() depending on your Drupal version)
Parse the view data an update the update relevant node fields with the view data. (which will also depend on your Drupal version).
Comment: Thanks a lot @Shawn Conn. I use Drupal 7. So, this copy action will happen after save the node, because the view is displayed only after saving the node.


Calculate mean and autocovariance for random walk to check stationarity

Question:
I am confused by the second line and the third line of the autocovariance calculation. Like how the var() and the 0 come, and why there is t*sigma^2 at the end.
Comment: $var(Y)=E[(Y -E[Y])^2]=E[Y^2]-(E[Y])^2$ may help
Comment: How the 0 term come?
Comment: It comes from $E[X_t]=0$ so $(E[X_t])^2=0$ and $E[X_t]E[X_s]=0$
Answer: The second term is $\mathbb E\left[\sum_{1\leq j\leq k}Z_j\sum_{1\leq j'\leq k}Z_{t+j'}\right].$ Now $\langle Z_j\rangle$ is a white noise process. That means $\mathbb E[Z_tZ_\tau] =0$ when $t\ne \tau.$ So, the concerned term yields zero.


DFS Replication slow to a single server

Question: This is a proper head-scratcher...
A customer has a domain with eight DCs. Two (including the PDC) are Hyper-V VMs in our datacentre, four are vSphere VMs at national site offices (not RODCs) and the other two are also vSphere VMs in a 3rd-party datacentre.
SYSVOL replication is all but instantaneous between the PDC (DC1001) and the site DCs, yet between DC1001 and the other Hyper-V DC (DC1002), replication is taking a couple of hours.
I've checked AD Sites and Services to ensure that all the links are in place and I can see direct connections between the two Hyper-V boxes.
We've put the two Hyper-V boxes on the same host to see if there was a Hyper-V networking problem, but slow replication is persisting.
I've run a DFS Replication heath check report and the results are a bit confusing to say the least...
Of all eight DCs, none of them have any backlogged receiving transactions yet all of them except DC1002 have over 300 backlogged sending transactions. DC1002 has no backlog at all and this is the "slow" node in the web. How can this be?
DFSR Diag commands (with the backlog exception) report everything to be hunky-dory yet there must be an explanation as to why replication is taking hours to show on DC1002.
I'm no Hyper-V expert, so there may well be something I've missed there.
There appears to be no file replication taking place, just SYSVOL.
There are also associated entries in Event Viewer > Applications and Services Logs > DFS Replication

Log Name:      DFS Replication
Source:        DFSR
Date:          20/01/2022 11:42:06
Event ID:      5014
Task Category: None
Level:         Warning
Keywords:      Classic
User:          N/A
Computer:      DC1002.domain.local
Description:
The DFS Replication service is stopping communication with partner Site1-001 for replication group Domain System Volume due to an error. The service will retry the connection periodically.

Additional Information:
Error: 1726 (The remote procedure call failed.)
I've looked up this error in relation to DFS replication, but there's a myriad of solutions for all kinds of problems so this seems like an unassailable minefield.
The RPC service is running on all hosts (Auto startup), there are not firewall rules blocking this and general network connectivity is fine throughout.
Any advice or experience with this problem would be greatly appreciated!!!
EDIT:
As a note, the two Hyper-V DCs reside in the same site so inter-site replication does not take place for these two I would guess. Also, all inter-site intervals are set to 15 minutes.
Comment: The default replication interval for Intersite replication is 180 minutes, so I'd suggest making sure that Active Directory Sites and Services is configured appropriately for your sites and the Domain Controllers at each site.
Comment: You should be able to start a capture, and initiate a sync. Ports of interest would include tcp/135,5722, and the high ports (49152+). Also Hyper-V network adapters have a history of causing network issues, that may be worth checking.
Comment: Fair comment @joeqwerty, thanks, I'll check this. What do you think would be causing changes to replicate to all other DCs almost instantaneously?
Comment: `I've looked up this error in relation to DFS replication, but there's a myriad of solutions for all kinds of problems so this seems like an unassailable minefield.` How is that? I'm inclined to think a packet capture between the two DC's would provide at least some information.
Comment: @GregAskew - Thanks for your response. I've asked our network team for the capture and am awaiting a reply. There's a number of search results relating to DISM errors which I'm not sure this is, and there's a number of proposed solutions for this:
Stopped RPC Service; Name Resolution Issues; Traffic Blocked at Firewall; Network Connectivity Issues. I know that it's none of these as replication is completing, albeit slowly. I'm also finding a lot of results for replication not working at all or replication being slow overall, nothing for a single node.
Answer: Turns out performing a non-authoritative synchronization of DFSR-replicated sysvol replication was the way forward.

In the ADSIEDIT.MSC tool, modify the following distinguished name (DN) value and attribute on each of the domain controllers (DCs) that you want to make non-authoritative:

CN=SYSVOL Subscription,CN=Domain System Volume,CN=DFSR-LocalSettings,CN=<the server name>,OU=Domain Controllers,DC=<domain> msDFSR-Enabled=FALSE

Force Active Directory replication throughout the domain.
Run the following command from an elevated command prompt on the same servers that you set as non-authoritative:

DFSRDIAG POLLAD

You'll see Event ID 4114 in the DFSR event log indicating sysvol replication is no longer being replicated.
On the same DN from Step 1, set msDFSR-Enabled=TRUE.
Force Active Directory replication throughout the domain.
Run the following command from an elevated command prompt on the same servers that you set as non-authoritative:

DFSRDIAG POLLAD

You'll see Event ID 4614 and 4604 in the DFSR event log indicating sysvol replication has been initialized. That domain controller has now done a D2 of sysvol replication.

https://docs.microsoft.com/en-US/troubleshoot/windows-server/group-policy/force-authoritative-non-authoritative-synchronization

DFS Replication slow to a single server


What does the pre shape, and EQ In/Out buttons do on my guitar?

Question: I just bought a second hand ovation celebrity and I was wondering what some of its buttons do. Do they change the sound (distortion/loudness)? If not what do they do?
Comment: A picture is worth a thousand words.
Answer: Eq is equaliser. A sophisticated tone control split into several frequency bands. The pre shape is a preset shaping of tone that Ovation hope players will like and use. The eq in/out actually switches the equaliser on/off. So, with the eq set to what you want for a particular sound, instantly there are options.


Delete a record from a specific table when a submission is deleted

Question: Is it possible to delete a record from a specific table when a webform submission is deleted?
I know it's possible in Drupal 7, with hook_webform_submission_delete().
The code I would use in Drupal 7 is similar to the following one.
function app_webform_submission_delete($node, $submission) {
  $id = $submission->data[7][0];
  // Delete a record from x table when a submission is deleted.
  db_delete('x_table')
    ->condition('type', "submission_type")
    ->condition('nid', $id)
    ->condition('sid', $submission->sid)
    ->execute();
}

What would the code for Drupal 8 be?
My question, in fact, is: How to respond to a specific webform submission deletion in drupal 8? In my code when a webform is submitted i insert sid with information in a custom table. When a specific submission is deleted i want to delete as well the record inserted in the custom table that have the deleted submission sid.
Comment: Can somebody help me please? I do not know how to do it in drupal 8. Maybe it is a stupid question but i do not know how to do this. Thank you
Comment: How were you able to add it to `x_table`?
Comment: No Sssweat, in witch environment do you ask (D8 or D7)?
Answer: Please be very careful when executing direct delete queries on a table. I am not sure if your x_table is a "Drupal" table or a custom table that you had created. Preferably you should use the Drupal API to ensure records for entities or such are deleted gracefully.
If the record that you are trying to delete is an entity ie. a node, then you would do something like:
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$node->delete();

Alternatively use the database service for non-entities:
\Drupal::database()->delete('x_table')
  ->condition('foo', 'bar')
  ->execute();

You can put this code in your implementation of hook hook_webform_submission_delete().
Comment: Look in webform.api.php @Yan187, the info is all in there
Comment: x_table is a custom table. hook_webform_submission_delete() it is still available for D8?
Comment: @Clive i did not fount anything related with hook_webform_submission_delete() in webform.api.php
Comment: I solved. Thanx to @Clive and baikho


How to get activity in full screen (immersive) also over the front camera hole area?

Question: My app is immersive and full screen, but in new devices running android 9 + with front camera hole  on screen - there is a black line instead of the status bar. (the status bar used to be where the camera hole is). I want to get all of the screen full, include the camera hole area.
I know the user can go to :
setting, display, full screen apps - and in this option find my app and  change it from "auto" to "full screen"  (in android 9) or from OFF  to ON (in android 11) and than it will be stretched also over the camera hole.  but I must do it programmatically from inside the app.
I can see many games and apps on the phone that are in a total full screen also over the camera hole, even if in setting: display: full screen apps -> the "full screen" option is switched OFF (android 11) or "Auto" (android 9) for these apps. So it must be possible to do it programmatically.
Now I am using this in order to go full screen (same as in android studio simple fullScreenActivity new project):
<code>   private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
        // Delayed removal of status and navigation bar

        // Note that some of these constants are new as of API 16 (Jelly Bean)
        // and API 19 (KitKat). It is safe to use them, as they are inlined
        // at compile-time and do nothing on earlier devices.
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
    }
};
</code>
Thanks for answering
In the pictures:

Full screen activity when device`s full screen display settings for this app is : "Auto" so there is a black line instead of the status bar (on the front camera area). how can I make the full screen stretch also on this place?

Full screen activity where android display settings for this app is "Full screen".

The settings change options(I want to change from "Auto" to "Full screen" programmatically).

enter image description here
Comment: Share the image of output
Answer: My friend Dima Kroytor found the answer! here it is..
Galaxy S10, S10+ Full Screen Mode
posted by Mohamad Bdour :  in values: style: add this to your AppTheme style
<code>  <item name="android:windowLayoutInDisplayCutoutMode">shortEdges</item>
</code>
if min level of your app is < 27 then put it under folder values-27
Comment: thanks for simple answer:)


Why am I not able to resolve names on subnet behind a lab network?

Question: I have gotten the task of setting up a network where there is an existing gateway for my "public ip" 10.200.3.2/28 already. I am to setup a gw/dhcp which uses the existing gateway the given ip address on one vlan interface (eth0.2) and uses NAT to get traffic out from 172.16.0.0/25 to the internet and back masquaraded.
I first tried setting up a simple NAT like this:
*nat
:POSTROUTING ACCEPT [0:0]

#Forward traffic through eth0.2
-A POSTROUTING -s 172.16.0.0/25 -o eth0.2 -j MASQUERADE
-A POSTROUTING -s 172.16.1.0/25 -o eth0.2 -j MASQUERADE

and then set up BIND9 on a second machine with only the internal ips (forward and backward), using no views or acl. This worked and I was able to resolve. I then proceeded to end up at the point I am now. I am not able to resolve with ping or nslookup, and when I try with for example "www.example.com" I get this:
user@ns:~$ nslookup www.example.com
;; communications error to 172.16.0.2#53: timed out
;; Got SERVFAIL reply from 172.16.0.2, trying next server
;; communications error to 10.250.0.5#53: timed out
;; communications error to 10.250.0.5#53: timed out
;; no servers could be reached

status shows this:
Nov 24 22:23:46 ns.bedrift3.d3-101.usn named[2232]: network unreachable resolving 'ntp.ubuntu.com/AAAA/IN': 10.250.0.5#53
Nov 24 22:28:55 ns.example.com named[2232]: listening on IPv4 interface eno1, 172.16.0.2#53
Nov 24 22:57:08 ns.example.com named[2232]: managed-keys-zone/public: Unable to fetch DNSKEY set '.': timed out
Nov 24 22:57:08 ns.example.com named[2232]: managed-keys-zone/private: Unable to fetch DNSKEY set '.': timed out
Nov 24 23:14:05 ns.example.com named[2232]: managed-keys-zone/private: Unable to fetch DNSKEY set '.': timed out
Nov 24 23:14:05 ns.example.com named[2232]: managed-keys-zone/public: Unable to fetch DNSKEY set '.': timed out

I am quite new in this field and feel as if I have tried to the best of my ability, so any feedback would be greatly appriciated.
Both machines are on ubuntu 22.04 LTS Server
Everything GW DHCP (172.16.0.1)
Is able to resolve from gw (really slow for some reason)
user@gw:~$ ping google.com
PING google.com (22.214.171.124) 56(84) bytes of data.
64 bytes from fra07s64-in-f174.1e100.net (220.127.116.11): icmp_seq=1 ttl=52 time=10.5 ms
64 bytes from fra07s64-in-f174.1e100.net (184.108.40.206): icmp_seq=2 ttl=52 time=10.3 ms
64 bytes from arn11s03-in-f14.1e100.net (18.104.22.168): icmp_seq=3 ttl=52 time=10.3 ms
64 bytes from fra07s64-in-f174.1e100.net (184.108.40.206): icmp_seq=4 ttl=52 time=10.6 ms

user@gw:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether dc:a6:32:44:a2:19 brd ff:ff:ff:ff:ff:ff
    inet 169.254.245.151/16 brd 169.254.255.255 scope link noprefixroute eth0
       valid_lft forever preferred_lft forever
3: wlan0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN group default qlen 1000
    link/ether dc:a6:32:44:a2:1a brd ff:ff:ff:ff:ff:ff
4: eth0.2@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether dc:a6:32:44:a2:19 brd ff:ff:ff:ff:ff:ff
    inet 10.200.3.2/28 brd 10.200.3.15 scope global noprefixroute eth0.2
       valid_lft forever preferred_lft forever
5: eth0.30@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
    link/ether dc:a6:32:44:a2:19 brd ff:ff:ff:ff:ff:ff
    inet 172.16.0.1/25 brd 172.16.0.127 scope global noprefixroute eth0.30
       valid_lft forever preferred_lft forever

user@gw:~$ ip r
default via 10.200.3.1 dev eth0.2 proto static metric 401
10.200.3.0/28 dev eth0.2 proto kernel scope link src 10.200.3.2 metric 401
169.254.0.0/16 dev eth0 proto kernel scope link src 169.254.245.151 metric 100
172.16.0.0/25 dev eth0.30 proto kernel scope link src 172.16.0.1 metric 400
22.214.171.124/4 dev eth0 proto static scope link metric 100

/etc/ufw/before.rules
# nat Table rules
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]

#Forward traffic through eth0.2
-A POSTROUTING -s 172.16.0.0/25 -o eth0.2 -j MASQUERADE
-A POSTROUTING -s 172.16.1.0/25 -o eth0.2 -j MASQUERADE

#Port forwarding
-A PREROUTING -i eth0.30 -p tcp --dport 25 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 25 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p tcp --dport 53 -j DNAT --to-destination 172.16.0.2
-A PREROUTING -i eth0.30 -p udp --dport 53 -j DNAT --to-destination 172.16.0.2
-A PREROUTING -i eth0.30 -p tcp --dport 80 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 80 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p tcp --dport 110 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 110 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p tcp --dport 143 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 143 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p tcp --dport 443 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 443 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p tcp --dport 1433 -j DNAT --to-destination 172.16.0.3
-A PREROUTING -i eth0.30 -p udp --dport 1433 -j DNAT --to-destination 172.16.0.3

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT

dhcpd.conf
option domain-name "example.com";
default-lease-time 600;
max-lease-time 7200;
ddns-update-style none;
authoritative;

subnet 172.16.0.0 netmask 255.255.255.128 {
        option domain-name-servers 172.16.0.2, 10.250.0.5, 126.96.36.199;
        option routers 172.16.0.1;
        option broadcast-address 172.16.0.127;
}

host DNS {
        hardware ethernet 18:03:73:28:00:35;
        fixed-address 172.16.0.2;
}

host webserver {
        hardware ethernet 00:25:64:E6:FD:CF;
        fixed-address 172.16.0.3;
}

host safe-dhcp {
        hardware ethernet DC:A6:32:44:A2:58;
        fixed-address 172.16.0.4;
}

Everything ns (172.16.0.2)
user@ns:~$ ping google.com
ping: google.com: Temporary failure in name resolution

user@ns:~$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 18:03:73:28:00:35 brd ff:ff:ff:ff:ff:ff
    altname enp0s25
    inet 172.16.0.2/25 brd 172.16.0.127 scope global dynamic noprefixroute eno1
       valid_lft 509sec preferred_lft 509sec
    inet6 fe80::1a03:73ff:fe28:35/64 scope link
       valid_lft forever preferred_lft forever
user@ns:~$ ip r
default via 172.16.0.1 dev eno1 proto dhcp metric 100
172.16.0.0/25 dev eno1 proto kernel scope link src 172.16.0.2 metric 100

DNS files
/etc/bind/named.conf.options
10.150.0.5 is a dns server which is tested to work on the lab.
options {
        listen-on port 53 { localhost; 172.16.0.2; };
        directory "/var/cache/bind";
        allow-query { any; };
        allow-transfer { any; };
        forwarders { 10.250.0.5; };
        forward only;
};

acl private { localhost; 172.16.0.0/25; 172.16.1.0/25; };

acl public { 10.100.7.0/24; 10.250.0.0/16; };

/etc/bind/named.conf.local
view private {
        match-clients { private; };

        zone "." {
                type hint;
                file "/usr/share/dns/root.hints";
        };

        zone "example.com" IN {
                type master;
                file "/etc/bind/db.example.com";
                allow-update { none; };
        };

        zone "3.200.10.in-addr.arpa" IN {
                type master;
                file "/etc/bind/db.10.200.3";
                allow-update { none; };
        };
};

view public {
        match-clients { public; };

        zone "example.com" IN {
                type master;
                file "/etc/bind/db.public.example.com";
                allow-update { none; };
        };

        zone "0.16.172.in-addr.arpa" IN {
                type master;
                file "/etc/bind/db.172.16.0";
                allow-update { none; };
        };
};

/etc/bind/db.example.com
$TTL 1h
@ IN SOA dns-example.com. firstname.lastname@example.com. (1234 1H 1800 60 30)

@       IN      NS      dns-example.com.

gw      IN      A       172.16.0.1
ns      IN      A       172.16.0.2
www     IN      A       172.16.0.3
mail    IN      A       172.16.0.3
safe    IN      A       172.16.0.4
@       IN      MX      10      mail

/etc/bind/db.public.example.com
$TTL 1h
@ IN SOA dns-example.com. firstname.lastname@example.com. (1234 1H 1800 60 30)

@       IN      NS      dns-example.com.

gw      IN      A       10.200.3.1
ns      IN      A       10.200.3.2
www     IN      A       10.200.3.2
mail    IN      A       10.200.3.2
safe    IN      A       10.200.3.2
@       IN      MX      10      mail

/etc/bind/db.10.200.3
$TTL 1h
@ IN SOA dns-example.com. firstname.lastname@example.com. (1234 1H 1800 60 30)

@       IN      NS      dns-example.com.

1       IN      PTR     gw.example.com.
2       IN      PTR     ns.example.com.
3       IN      PTR     www.example.com.
3       IN      PTR     mail.example.com.
4       IN      PTR     safe.example.com.

/etc/bind/db.172.16.0
$TTL 1h
@ IN SOA dns-example.com. firstname.lastname@example.com. (1234 1H 1800 60 30)

@       IN      NS      dns-example.com.

1       IN      PTR     gw.example.com.
2       IN      PTR     ns.example.com.
3       IN      PTR     www.example.com.
3       IN      PTR     mail.example.com.
4       IN      PTR     safe.example.com.

Comment: Small update, I changed the etc/resolv.conf to say:
`nameserver 10.250.0.5`

not:
`nameserver 172.16.0.2
nameserver 10.250.0.5`
and it is now resolving to google.com a lot faster. It does not seem to have solved anything else, but a little progress atleast.
Answer: It seems like your dns server is not reachable on 10.150.0.5, because you forward everything to 172.16.0.2.
You could try to change your iptables rules for dns forward to something like this
iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to-destination 10.150.0.5
I'm not sure if that will work because with all the config files your setup confuses me a bit.
Comment: I'll try to elaborate a bit more. the lab I am setup in has a gateway setup spesifically for my subnet at 10.200.3.1. This same lab has a DNS which is used for getting access to the internet on 10.250.0.5.

My subnet has its own gw with my dhcp for subnet 172.16.0.0/25. This subnet has its own DNS on 172.16.0.2 which I want things to be resolved on internally if there is a listing for it. If not I want it to be forwarded by the same DNS to the DNS on the lab network.

Does that clear things up or is there something else that seems confusing @Turdie ?
Comment: As I said you are not forwarding anything to your dns in your current iptables/ufw rules, try to figure that out


Making A slideshow appear on more than first page

Question: I am using the premium responsive theme in Drupal 7 to create a site. In the theme the front page has a slideshow on it. Is it possible to make the slideshow appear on the top of every page?
EDIT
So I was messing around with this a little more and I tried bringing the code into page.tpl.php so that it would appear on all pages, but nothing happened. I then tried doing it on the maintenance.tpl.php page, and still nothing happened. Any ideas out there?
Comment: The css says the display is block, but there is no physical block to move to a region no the interface.
Comment: Then check the page--front.tpl.php file.  If it's hard coded, then it will need to added to page.tpl.php to show on other pages.
Answer: It seems like we're working on a similar problem, but since you helped answer my question I thought I'd help you out. In the templates folder you have to create a new page--front.tpl.php (which I'm sure you have), and put it the code from this website:
Go Here
This will make your front-page unique, and you can copy the similar code to your page.tpl to make changes to the remaining nodes.


How to solve for a distribution function over which another function is integrated?

Question: How to solve for a distribution function $F$ in:
$$T(x) = \int_a^x p(y) dF(y)$$
Let me provide you with the following example.  A company may advertise a price in range between $[a,x]$ for its product. $F(y)$ stands for a probability that the company advertises a price smaller than or equal to $y$ ($y \in [a,x]$), and greater than $a$. $p(y)$ is the proportion of consumers (which can be assumed as a unity mass) to which the advertisement of price $y$ reaches; obviously, $0 \leq p(y) \leq 1.$  Finally, $T(x)$ is the probability that a particular consumer observes an ad offering a price $x$ or lower (and greater than $a$).
Given the above equation, how to solve for $F$ in terms of $T()$ and $p()$ for $y \in [a,x]$?
Comment: Welcome to Maht.SE ! your question is in its presents form, impossible to understand. You shoudl provide more details about what you mean by solving, what are $b(x)$ and $T(x)$ and what you have attempted to find the solution. You won't get any answer unless you do this.
Comment: @Tom-tom, thanks a lot for the comment.  I edited the question to make it easier to understand.  Also the question probably relates to statistics, but I assumed that I can ask it here
Comment: You mean $T(x)=\int_a^x p(y)dF(y)$. The nice case for this is when $F$ is absolutely continuous (i.e. the price random variable has a density) and $p$ is continuous and never vanishes. Then $T'=pf$, so $f=T'/p$, so $F=\int_a^xT'(y)/p(y)dy$.
Comment: When $F$ is pure discrete and $p$ is continuous and doesn't vanish where $F$ has jumps, everything is also OK: the jumps in $F$ are equal to the jumps in $T$ divided by the corresponding values of $p$. By linearity everything is *still* OK when $F$ just has no singular part: just handle the continuous and discrete parts separately. I don't know what to do if there is a singular part, though.
Comment: @Ian, thank you very much for the detailed explanation!!
Comment: Thank you for editing the question. There is still a point that I don't get : why does $T$ depend on $x$, since $x$ is the integration variable on the right-hand side. Shouldn't it be written as $T[F]=\int_a^bp(x)\mathrm dF(x)$ ?
Comment: @Tom-Tom, you are right. My apologies for the confusion. As Ian pointed out, it should be $T(x) = \int_a^x p(y) dF(y)$
Answer: This is a problem of functional optimization. $T$ depends on $F$ and $p$ is given (or at least could be known using polls).
Let us first follow @Ian's comment by assuming that $F$ is absolutely continuous. This means that $\mathrm d F(y)=f(y)\mathrm dy$, where $f$ is the probability density of the price. As $T$ depends not on a single variable, but on all the values of $f$, one uses the notation $T[f]=\int_a^xp(y)f(y)\mathrm dy$. Let us consider $\delta f$ an arbitrary function satisfying $$\int_a^x\delta f(y)\mathrm dy=0\tag 1$$ (to ensure the normalization of $f+\delta f$).
If $f$ is the optimal price probability, the quantity $T[f+\delta f]-T[f]$ must be negative for any function $\delta f$. Now we should notice that $T[f+\delta f]-T[f]=T[\delta f]$. This does not depend on $f$ ! In this case, there is a solution only if $p(y)=\frac1{x-a}$ is the uniform distribution. In any other case, one can find a function $\delta f$ satisfying (1) and $T[\delta f]>0$. (take any function satisfying (1) such that $\operatorname{sign}\left(\delta f(y)\right)=\operatorname{sign}\left(p(y)-\frac1{x-a}\right)$.)
So we have a first solution:
If $p$ is a uniform distribution, any choice of $F$ is optimal.
In a second case, if $p$ is not uniform, we have shown that $F$ cannot be continuous. Let us concentrate on the discontinuities and chose $F$ as steps
$$F(y)=\sum_{i=1}^n a_i\Theta(y-y_i)\tag 2 $$
where $y_i\in[a,x]$, $a_i>0$ and $\sum_{i=1}^Na_i=1$. Therefore
$$T=\sum_{i=1}^Na_ip(y_i).$$
If $p$ reaches its absolute maximum on $[a,x]$ at point $y_{\mathrm m}$, then the maximum of $T$ is reached for $N=1$, $y_1=y_{\mathrm m}$ (and $a_1=1$). If the absolute maximum of $p$ is reached at several values
of $y$, any solution of the form (2) with $y_i$ equal to these values is optimal. This is the optimal solution because if $F$ grows between to discontinuities, this will result in diminishing the coeffients $a_i$.
If $p$ is not uniform, the optimal solution are $F$ of the form
(2) where the discontinuities are located where $p$ reaches its absolute maximum.
In a way, a uniform distribution reaches its absolute maximum everywhere, so the two cases merge.
Note Few words concerning the income function $P=\int yp(y)\mathrm dF(y)$ : the reasoning is the same except that the function $p$ is replaced by $q(y)=yp(y)$. The "reference" function is therefore not the uniform distribution but $p(y)=1/y$. For this function, any choice of $F$ is optimal. Otherwise, apply the same reasoning with the discontinuities and locate the absolute maximum of $q$ on $[a,x]$. Example: if $p(y)=A\exp(-y/y_0)$, the optimal price is $\max\left\{\min\{x,y_0\},a\right\}$.


What is the exact accuracy score for k-fold cross validation?

Question: In my sentiment analysis work ı have used k fold cross validation,  and ı got below results
precision    recall  f1-score   support
<code>       0      0.906     0.916     0.911       878
       1      0.865     0.845     0.855      1142
       2      0.849     0.864     0.857       950

accuracy                          0.872      2970
</code>
macro avg      0.873     0.875     0.874      2970
weighted avg      0.872     0.872     0.872      2970
val-accuracy for each fold [0.7805452709525412, 0.8114478114478114, 0.8454545454545455, 0.8494949494949495, 0.8720538720538721]
average val-accuracy 0.8317992898807439
I wonder that what is my model accuracy,  ı got 87 for last fold but ı got only about 70s  when ı tested my model with unseen data. I think when we test with unseen  ı am getting results like first fold. For kfold cross validation after first fold the model knows every data, because of that reason at second or third... fold we got more accuracy,am ı true? ıf ı am true kfold doesnt increse accuracy
Answer: Kfold is not used for increasing accuracy, it is used to shuffle your data and then test your estimator, your predefined parameters in the model. It gives you an insight how your model behaves. If you have vastly changes in accuracy/scores in a kfold, you may have a look at outliers in your data as this or these outliers may sometimes jump from one fold into the other.
In summary:
Kfold takes different subsamples of your data to use as test_data, thus there is no exact acuracy score.
Comment: Thank you for your answers, patrick. I want to ask another thing,  When ı investigate some questions about kfold some contributors says that each fold is used to train a new model from scratch, predict the accuracy, and then the model is discarded. But when ı used k fold cv, ı see that accuracy increasing each fold, smallest one is initial fold. is it just a coincidicence?
Comment: I do not know your data, but it sounds you didn't shuffled your data, which could be an indicator to your phenomenon as the relationship grows towards the end of the data, thus the latest split, try to insert a shuffle https://www.statology.org/k-fold-cross-validation-in-python/
Comment: Acctually  ı shuffled data at kfold definition, also ı shuffled data when loading my  csv data, ı still have above problem . ı  saw some recommendations that advise using built in cross_val_score. In that case ı dont know how to use my model attributes like epoch , batch szie, call backs, because cross_val_score doesnt have them.


Abrir nova tela com as opções do usuário clicado

Question: Tenho uma listView e nela coloquei todos os usuários do banco, uso um adapterView para pegar a posição e o id, porém não sei como irei abrir uma nova tela para as opções avançadas para cada usuário.
segue o código
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
      .permitAll().build();
    StrictMode.setThreadPolicy(policy);
      setContentView(R.layout.list);
      listView = (ListView) findViewById(R.id.listView1);
      accessWebService();

      listView.setOnItemClickListener(new OnItemClickListener() {
             public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
               // When clicked, show a toast with the TextView text
               Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
                   Toast.LENGTH_SHORT).show();
             }
           });

     }

Teria que vincular algum atributo identificador no item para pega-lo, ou posso fazer tudo com Json?
Comment: ele está em um banco local? Ou vem de um webservice?
Comment: vem de um webservice no apache
Comment: Então, acho que vc terá que passar o ID deste usuário para e lá (através de outra requisição) pegar os dados do servidor através do ID.
Answer: listDebitosPendentes.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                  Intent intent = new Intent(getApplicationContext(), DetalhesDebitosActivity.class);

                  //Passa para a activity o id no banco de dados
                  intent.putExtra("ID", id);

                  startActivity(intent);
        }

    });

Na outra activity você pega da seguinte forma.
 Long idSelected = getIntent().getLongExtra("ID", 0);

No meu caso eu faço uma query pegando por esse ID.
int id = Integer.valueOf(idSelected.toString());

debitosPendentes = debitoPendentesDao.queryForId(id);


Chrome not showing up in vscode. Manjaro Linux

Question: i'm on Manjaro. i've install google-chrome from AUR and it shows up in flutter doctor , flutter devices when executed from terminal. the problem is when i run flutter doctor from vscode it says

[✗] Chrome - develop for the web (Cannot find chrome executable at google-chrome)
      ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
Answer: First you need to switch master channel
flutter channel master

Then run
flutter upgrade

Enable Web support by running
flutter config --enable-web

Find installation path of chrome by running
which chrome

set an Environment variable to chrome's installation path.
If your installed using AUR it will in /opt/google/chrome/chrome
export CHROME_EXECUTABLE=/opt/google/chrome/chrome

Finally run
flutter devices

You can see chrome as a connected device.
Answer: To use chrome or chromium on Linux(Manjaro), first you have to find their location.
Run the following command:
which chromium

My chromium is located at:
/usr/bin/chromium

If you wish to add this browser to Flutter, then you should add it to the CHROME_EXECUTABLE environment variable.
the following command needs to be placed in the .bashrc:

/usr/bin/chromium is my chromium location; add yours.

You can use nano:
nano .bashrc

Add the following command and press Ctrl+x and then Y to make sure it has been saved.
export CHROME_EXECUTABLE=/usr/bin/chromium

And finally run:
source .bashrc

Now restart the previous open IDE and it should work.
If you run:
flutter doctor

You should find it in the connected device.
Comment: While this answer is rather for linux users, for macOS PATH look like this on macOS: `export CHROME_EXECUTABLE=/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome`
Answer: check $PATH
try to chrome- and tab
ln -s /usr/bin/google-chrome-stable /usr/local/bin/google-chrome

Answer: run flutter pub global activate webdev
Answer: If you are using brave browser on Manjaro, open the terminal and start here:
which brave-browser

My brave is located at:
/usr/bin/brave-browser

Then you can run the executable:
export CHROME_EXECUTABLE=/usr/bin/brave-browser

Then you can run flutter devices:
flutter devices

The output of flutter devices should be:
1 connected device:

Chrome (web) • chrome • web-javascript • Brave Browser 184.108.40.206 unknown

Run flutter doctor in verbose:
flutter doctor -v

Here's the output all green:
[✓] Flutter (Channel master, 2.6.0-12.0.pre.999, on Manjaro Linux
    5.9.16-1-MANJARO, locale en_US.utf8)
    • Flutter version 2.6.0-12.0.pre.999 at /home/mbuso/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 895beb04bb (33 hours ago), 2021-12-10 18:54:10 -0800
    • Engine revision 79f750d4a5
    • Dart version 2.16.0 (build 2.16.0-85.0.dev)
    • DevTools version 2.9.1

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /home/mbuso/Android/Sdk
    • Platform android-30, build-tools 30.0.3
    • ANDROID_HOME = /opt/android-sdk
    • Java binary at: /opt/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • CHROME_EXECUTABLE = /usr/bin/brave

[✓] Android Studio (version 2020.3)
    • Android Studio at /opt/android-studio
    • Flutter plugin version 62.0.1
    • Dart plugin version 203.8452
    • Java version OpenJDK Runtime Environment (build 11.0.10+0-b96-7249189)

[✓] IntelliJ IDEA Community Edition (version 2021.2)
    • IntelliJ at /usr/share/idea
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart

[✓] Connected device (1 available)
    • Chrome (web) • chrome • web-javascript • Brave Browser 22.214.171.124 unknown

• No issues found!

To make sure that the export executes on every start you can include this line in your ~/.bashrc or ~/.zshrc depending on which shell you use:
export CHROME_EXECUTABLE=/usr/bin/brave-browser

Comment: For me, I it didn't worked. I had to add the line export CHROME_EXECUTABLE="/usr/bin/chromium" into home>~./bashrc file. Then it started showing
Comment: Yeah man...I forgot to include the export CHROME_EXECUTABLE=/usr/bin/brave in the ~/.bashrc or ~/.zshrc. Thank you


CSS div wrapper works with everything except these div tags. Why?

Question: I have used a wrapper to center div tags and it works for everything except the css in the link
Please check out:
http://jsfiddle.net/T5rBU/3/
As you can see the pink box with text is in the center but the black box isn't.
I have put
float: left;

but that is only because if I don't the black box doesn't show!?
Answer: try this:
.center div {
     display:inline-block;
     text-align:center;
}

it seams to work:
http://jsfiddle.net/u3ggV/
Comment: You're welcome. (If you think it is the right answer accept it so others can benefit from your question too)
Comment: Just a quick one, when I put my code into this site: http://jsfiddle.net/GJMtC/ the mouseovers work but when I write it in textedit and view it on my browser it doesnt? It worked like an hour ago but doesnt now?
Comment: Sorry, I didn't saw that question in time, I'm always cleanings browser cache so I'm always losing my session. When you want to ask a new question do it in the http://stackoverflow.com/questions/ask so everyone can see it and answer it, it's best for you and for the community. I don't have time right now so I hope you already figure out what was failing.
Answer: add a with to .center
.center {width:400px;}
or another width you cant center div with text-align
Answer: I don't quite follow what you mean but I think it could be down to not having a wrapping element to hold both divs - http://jsfiddle.net/djsbaker/T5rBU/4/
Did you want the black box beside or above/below the navigation?