x11 window delay on OSX

Question: I have a newer generation macbook pro. I have El Capitan installed with the latest X11 release from xquartz. Whenever I try to open up a X11 window, such as just running xclock, it takes about 15 seconds to get the window. If I do the same thing on my work laptop, which has an identical version of OS X and X11, it takes a fraction of a second. I can't figure out what is going on. Does anyone have some suggestions of what the problem could be, or how to diagnose such a problem?
Answer: I ended up figuring out that macports had its own X11, and didn't rely on XQuartz. I uninstalled XQuartz, and just used the macports xorg.server for my X11. Still don't know why having both works fine on my work laptop but not on my personal laptop. Oh well...problem fixed.

x11 window delay on OSX


Problems with this max likelihood estimation

Question: I have the following density function:
$f(x;\omega) = \omega*x^{(\omega-1)}*I_{(0,1)}(x)$ for $\omega > 0$
First I want to have the Likelihoodfuntion, which is
$\prod_{i=1}^n f(x_i;\omega)$
I used the log and got:
$ln L(\omega) = ln \sum_{i=1}^n\omega*x^{(\omega -1)} $
Im wondering if this is correct or not, since when I wanna get the ML estimator (derive the function and set it to zero) I cant get a correct result.
thanks for any help in advance
Answer: I assume $I_{(0,1)}$ is a characteristic function, and $*$ is multiplication. If you ignore $I$ when finding the maximum likelihood, make sure to take it into consideration later.
Your $\ln$ should be inside the $\sum$. This comes from the property:
$$\ln(xy) = \ln x + \ln y$$
for $x, y > 0$. If you wanted to convince yourself that it's true for any number of factors, you can use induction, but you probably believe it. Perhaps the summation notation confused you.
$$\ln(x_1x_2x_3 \ldots x_n) = \ln\left({\prod_{i = 1}^n x_i}\right)$$
$$= \ln x_1 + \ln x_2 + \ln x_3 + \ldots + \ln x_n = \sum_{i = 1}^ n \ln x_i$$
Answer: It's just better to write out everything step by step.
$$\begin{align*} \mathcal L(\omega \mid \boldsymbol x) &= \prod_{i=1}^n \omega x_i^{\omega - 1} \mathbb 1(0 < x_i < 1) \\ &= \omega^n \biggl( \prod_{i=1}^n x_i \biggr)^{\omega - 1} \mathbb 1 (0 < x_{(1)})  \; \mathbb 1 (x_{(n)} < 1) , \end{align*}$$ where $x_{(1)} = \min_i x_i$ is the first order statistic and $x_{(n)} = \max_i x_i$ is the last order statistic.  Then the log-likelihood is $$\ell(\omega \mid \boldsymbol x) = n \log \omega + (\omega - 1) \sum_{i=1}^n \log x_i = n \log \omega + (\omega - 1) \overline{\log x},$$ if $0 < x_{(1)} \le x_{(n)} < 1$.  Taking the derivative with respect to $\omega$ gives $$\frac{\partial \ell}{\partial \omega} = \frac{n}{\omega} + \overline{\log x}$$ and solving for the critical point gives the maximum likelihood $\hat \omega$.


Bootstrap 3: Trouble with panels in responsive columns

Question: I have a page where my primary content is a series of Bootstrap panels. On xs screens, I want to have one panel in a row, so effectively one wide column. On md screens, I want to have two panels in each row, so effectively two columns. I am placing each panel in a column like so:

This works almost perfectly, but on medium screens, depending on the height of the panels, there is extraneous blank vertical space. see the image below for what I mean:

It is important that the ordering be the same on both the xs and md screen sizes. I.e, if on a xs screen the panels went:
A
--
B
--
C

Then on the medium screen size, it must go:
A  | B
-------
C  |

jsBin is here (or jsFiddle if you prefer). Note that to reproduce, you'll need to widen output/preview pane so that it uses the medium screen size styling.
Comment: I see a lot of a questions about this issue, but it's not something that `bootstrap` handles on it's own. Look into `masonry`: https://github.com/desandro/masonry
Comment: Don't forget, the CSS associated with `.row` requires its direct parent to be a `.container`!
Comment: @TimLewis Thanks, I was able to use Masonry and get this fixed!
Answer: Thanks to Tim Lewis' suggestion, I can accomplish this using Masonry. It seems it is quite simple, and the following javascript snippet works so far:
$('.row').masonry(
    {itemSelector: '.col-md-6'}
);

This gets rid of the extraneous space and it works with the responsive design. My only issue so far is that collapsing/expanding the panels isn't quite right, but that wasn't part of the initial question here and I think I can fix it by just calling masonry again after the panel has been collapsed/expanded.


Habilitar e desabilitar botão para elementos dinâmicos no carrinho

Question:
Criei essas funções para caso a quantidade do produto seja alterada, independente de ser pelos botoes setas ou diretamente no campo, apareça o botão "Atualizar", apenas para o produto que sofreu a alteração. Porém, se altero 1 produto o botão aparece para todos os outros.E quando clico novamente no mesmo produto, o botão dele remove, porém, adiciona outro botão em outro produto.

<form action="http://.../checkout/cart/updatePost/" method="post" id="form-validate" class="form form-cart">
      <input name="form_key" type="hidden" value="rW5XuwwQiEurJLOt">

Itens do Carrinho de Compras

              Item
              Preço
              Qtd
              Subtotal

                      Estojo para lentes de contato Bausch & Lomb azul

                     R$4,90

                            Qtd

                    <input id="cart-2217-qty" name="cart[2217][qty]" data-cart-item-id="1530" value="4" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">

                          R$19,60

                    Editar

                Remover item
                  <button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button><button id="updateCar"
                    type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button><button id="updateCar" type="submit" name="update_cart_action"
                    data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button><button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update=""
                    value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button>

                                                    Renu Fresh 120ml

                                R$24,90

                            Qtd

                    <input id="cart-2218-qty" name="cart[2218][qty]" data-cart-item-id="1350" value="1" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">

                                R$24,90

                    Editar

                Remover item

          Continuar Comprando

        <button type="submit" name="update_cart_action" data-cart-empty="" value="empty_cart" title="Limpar Carrinho de Compras" class="action clear" id="empty_cart_button">
                    Limpar Carrinho de Compras
                </button>
        <input type="hidden" value="" id="update_cart_action_container" data-cart-item-update="">

    </form>

function habilitaButton() {

  var divTableCart = document.getElementById('shopping-cart-table');
 var itemProduct = divTableCart.getElementsByClassName('action-delete');

for(var j =0; j < itemProduct.length; j++){
  itemProduct[j].insertAdjacentHTML("afterend", '<button id="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update">Atualizar</button>');
 }
}
function removeButton(){
 var divTableCart = document.getElementById('shopping-cart-table');
 var itemProduct = divTableCart.getElementsByClassName('action-delete');

 for(var l =0; l < itemProduct.length; l++){
  document.getElementById("updateCar").style.display="none";
 }
}

var QtdyProduct = document.getElementsByClassName("control qty");

for(var i =0; i < QtdyProduct.length; i++){
 var qtdAlterada = QtdyProduct[i].getElementsByTagName('input')[0];
 qtdAlterada.addEventListener("blur", habilitaButton);

 qtdAlterada.addEventListener("focusin", removeButton);
}
Comment: Tem como postar o HTML? Aí daria pra testar o código.
Comment: oi @VítorFerragini tem sim.
Answer: Isto está acontecendo porque na function habilitaButton() você está percorrendo todas as DIVs "action-delete" e inserindo nelas o Botão de Atualizar, o correto é verificar se o índice atual é igual ao que está no for.
Para simplificar todo o script eu alterei o HTML do Botão de Atualizar, trocando o id  "updateCar" por classe no lugar dele para poder procurar por todos os Botões no JavaScript e adicionei ele em todos os itens do carrinho e também adicione a classe "input-qty" em todos os inputs de Quantidade.
O HTML ficou da seguinte forma:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Testes</title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
 <link rel="stylesheet" href="style.css">

 <form action="http://.../checkout/cart/updatePost/" method="post" id="form-validate" class="form form-cart">
      <input name="form_key" type="hidden" value="rW5XuwwQiEurJLOt">

Itens do Carrinho de Compras

              Item
              Preço
              Qtd
              Subtotal

                      Estojo para lentes de contato Bausch & Lomb azul

                     R$4,90

                            Qtd

                    <input id="cart-2217-qty" class="input-qty" name="cart[2217][qty]" data-cart-item-id="1530" value="4" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">

                          R$19,60

                    Editar

                Remover item

      <button class="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button>

                                                    Renu Fresh 120ml

                                R$24,90

                            Qtd

                    <input id="cart-2218-qty" class="input-qty" name="cart[2218][qty]" data-cart-item-id="1350" value="1" type="number" size="4" title="Qtd" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty">

       R$24,90

                    Editar

                Remover item
    <button class="updateCar" type="submit" name="update_cart_action" data-cart-item-update="" value="update_qty" title="Atualizar Carrinho de Compras" class="action update" style="display: none;">Atualizar</button>

          Continuar Comprando

        <button type="submit" name="update_cart_action" data-cart-empty="" value="empty_cart" title="Limpar Carrinho de Compras" class="action clear" id="empty_cart_button">
                    Limpar Carrinho de Compras
                </button>
        <input type="hidden" value="" id="update_cart_action_container" data-cart-item-update="">

    </form>

Depois fiz o script da seguinte forma:

function togleButton(event, qtdPadrao){
 let qtdAlterada = event.target.value;
 let index = Array.from(QtdyProducts).indexOf(event.target);
 let buttonUp = document.querySelectorAll('.updateCar');
 if (qtdPadrao == qtdAlterada)
  buttonUp[index].style.display="none"
 else
  buttonUp[index].style.display="";
}

let QtdyProducts = document.querySelectorAll('.input-qty');

QtdyProducts.forEach(function(product){
 let qtdPadrao = product.value;
 product.addEventListener('blur', function(){
  togleButton(event, qtdPadrao);
 }, false);
})

Agora algumas explicações.
A primeira coisa que eu fiz foi armazenar em uma variável todos os inputs de quantidade:
let QtdyProducts = document.querySelectorAll('.input-qty');

Depois usando o forEach() eu percorro essa variável e para cada item eu salvo o valor padrão do input de quantidade em uma variável, para poder passar para a função togleButton() além do evento em si.
É importante ressaltar que se eu não tivesse colocado o
function(){
   togleButton(event, qtdPadrao);
}, false

no addEventListener() ele iria chamar a função togleButton() assim que a página carregasse e iria dar erro.
Já na função togleButton() eu armazeno a quantidade alterada pelo usuário em uma variável:
let qtdAlterada = event.target.value;

Para poder comparar com a quantidade padrão que estava setada para o input de quantidade.
Depois armazeno em uma variável o índice do input atual que usuário está alterando o valor:
Array.from(QtdyProducts).indexOf(event.target);

E armazeno também todos os botões existentes em uma variável novamente:
let buttonUp = document.querySelectorAll('.updateCar');

Por último comparo se a quantidade alterada é igual a quantidade padrão:
if (qtdPadrao == qtdAlterada)
    buttonUp[index].style.display="none"
else
    buttonUp[index].style.display="";

Se for igual eu altero o display para "none", se for diferente eu removo o display "none".
Comment: oi @RenatoGonçales , primeiramente agradeço pela sua dedicação na resposta. Gostaria de compartilhar também como foi solucionado este problema, com a ajuda de um colega de trabalho. Veja a solução tomada.
Answer:

function habilitaButton(numero) {
  var qtd = document.getElementsByClassName("input-text qty");
  var btn = document.getElementsByClassName("qty-changer");
  var num = 0;
  for(var x = 0; x < qtd.length; x++){
   if(qtd[x] == numero){
    num = x;
   }
  }
  for(var y = 0; y < btn.length; y++){
   if(btn[y] == numero){
    num = y;
   }
  }

  document.getElementsByClassName("action update")[num].style.display = "block";
   }
 var QtdyProduct = document.getElementsByClassName("control qty");
 var divTableCart = document.getElementById('shopping-cart-table');
 var itemProduct = divTableCart.getElementsByClassName('action-delete');
 document.getElementsByName("update_cart_action")[1].style.display = "none";
 for(var j =0; j < itemProduct.length; j++){
  itemProduct[j].insertAdjacentHTML("afterend", '<button type="submit" name="update_cart_action" style="display:none;" data-cart-item-update="" value="update_qty" title="Atualizar" class="action update">Atualizar</button>');
 }
 for(var i =0; i < QtdyProduct.length; i++){
  var qtdAlterada = QtdyProduct[i].getElementsByTagName('input')[0];
  document.getElementsByClassName("qty-changer")[i].onclick = function(){
   habilitaButton(this);
  }
  qtdAlterada.onchange = function(){
   habilitaButton(this);
  }
 }


Scraping websites with rake task

Question: This is in my lib/tasks folder in my rails app, for some reason I keep getting an error every time I try to run the task.
desc 'Fetch product prices'
task :fetch_prices => :environment do

  require "nokogiri"
  require "open-uri"

  Product.each do |product|
    url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html"
    doc = Nokogiri::HTML(open(url))
    price = doc.at_css(".fntlb").text[/[0-9\.]+/]
    product.update_attribute(:price, price)
    puts "Product #{Product.id} has been updated with price #{price}"
  end
end

The following is the error I get when I try to run this task:
rake aborted!
undefined method each' for nil:NilClass
/vagrant/depot/lib/tasks/product_prices.rake:7:inblock in '
Answer: You want Product.all.each not Product.each.  Although it's a little weird the error says it's on nil.
Comment: I changed it to Product.all.each and now get this error: rake aborted!
404 Not Found
/vagrant/depot/lib/tasks/product_prices.rake:9:in `block (2 levels) in '
/vagrant/depot/lib/tasks/product_prices.rake:7:in `block in '
Comment: Odds are the URL isn't valid.  Can't really help you there.
Answer: You need to define your Product variable
Change this:
desc 'Fetch product prices'
task :fetch_prices => :environment do

require "nokogiri"
require "open-uri"

 Product.each do |product|
  url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html"
  doc = Nokogiri::HTML(open(url))
  price = doc.at_css(".fntlb").text[/[0-9\.]+/]
  product.update_attribute(:price, price)
  puts "Product #{Product.id} has been updated with price #{price}"
 end
end

to this:
desc 'Fetch product prices'
task :fetch_prices => :environment do

require "nokogiri"
require "open-uri"

url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html"
doc = Nokogiri::HTML(open(url))
product = doc.css('CSS SELECTER FOR YOUR CONTENT')

 Product.each do |product|
  price = doc.at_css(".fntlb").text[/[0-9\.]+/]
  product.update_attribute(:price, price)
  puts "Product #{Product.id} has been updated with price #{price}"
 end
end

Scraping websites with rake task


Is there a way to apply a function to each parameter of another function/method in Python?

Question: Let us suppose a following code where a method of an object accepts multiple integer parameters :
def my_function(target):
    return target + 2

my_object.DoSomething(param1=my_function(1), param2=my_function(4), param3=my_function(7))

Is there a way to map a single function to all parameters of a method like that?
If not, how would you approach it from efficiency standpoint if there were undefined number of parameters?
Please note I am aware of how Python's map() and Pandas' apply() work. Also the numbers above are just examples to illustrate my point.
Comment: You _could_ use a dictionary comprehension and just double-star it in the function call. Alternatively, if the parameters need not be named, you can always just unpack a single map object in the call.
Answer: You can store your parameters in a dictionary and unpack them when calling your function:
params = {'param1': 1, 'param2': 4, 'param3': 7}
my_object.DoSomething(**{k: my_function(v) for k, v in params.items()})

Comment: Much better than manual typing. Thank you for your input.  Any other ideas are most welcome.


Running between the wickets rule

Question: If suppose a batsman running between the wickets. On the time of ball hitting the stumps by the fielder. The bat reached inside the crease but the bat was free from the batsman hand. What will be the decision there by umpire??
Answer: This depends on when the hand and the bat became separated. If the bat became separated before the batsman made their ground, then the batsman is out as they never made their ground. If the batsman made their ground with their bat but then dropped the bat, they are considered to still be in their ground; quoting Law 30.2:

However, a batsman shall not be considered to be out of his/her ground if, in running or diving towards his/her ground and beyond, and having grounded some part of his/her person or bat beyond the popping crease, there is subsequent loss of contact
[...]
between the bat and person, provided that the batsman has continued movement in the same direction.

Running between the wickets rule


how could "virsh snapshot-list" with description

Question:
virsh snapshot-create-as win7 snap01 --description "something here"

How could I list snapshots list with the description ?
Answer: I managed to do a simple bash script to list all VMs and the snapshots description:
#!/bin/bash

vmdomains=`sudo virsh list --all | sed 1,2d | awk '{ print $2 }'`

echo -ne "Domain\t\t\tSnapshot Name\t\t\tDescription\n"
echo "-----------------------------------------------------------------------------------------"
for vmdomain in $vmdomains; do
  echo -ne "$vmdomain\t\t"
  snapshots=`sudo virsh snapshot-list $vmdomain | sed 1,2d | awk '{ print $1 }'`
  snapshotflag=0
  for snapshot in $snapshots; do
    snapshotflag=1
    echo -ne "$snapshot\t\t"
    sudo virsh snapshot-dumpxml --domain $vmdomain --snapshotname $snapshot | grep "<description>" | sed 's/  <description>//' | sed 's/<\/description>//'
  done
  if [ $snapshotflag -eq 0 ]; then
    echo
  fi
done

Edit: Output example
~$ sh listsnap.sh
Domain               Snapshot Name                  Description
-------------------------------------------------------------------------------------
Win10                Win10_Disabled_Updates         Used gpedit to disable updates
Win10                Win10_games_installed          Gaming Rig with passtrhough gpu
CentOS               CentOS_origin                  Installed Nginx and web dependencies
CentOS               CentOS_Wednesday               Installed Anaconda and Julia
CentOS               CentOS_weekend                 Updated PIP dependencies
Fedora
Ubuntu               Testing_nfs_Ubuntu             Configured nfs server

Edit: This was a quick script and may not handle all cases in the best way, see other scripts posted here for more detailed workaround. Also RHEL web console already shows snapshot descriptions Yay!
Comment: Works for me if I use `echo -ne` instead of `echo -n`. Otherwise the escape sequences do not get interpreted.
Answer: I tried Holger Jakobs' solution but it required packages not on my Linux system.
Then I tried Faustino Aguilar's solution and it almost works.  However, it is legal to embed spaces in the snapshot name and his script doesn't handle that case. I also had serious formatting problems for snapshots that didn't include a description.
So, I made significant modifications and believe I have a working script with the caveat that a domain name or a snapshot name over 20 characters won't work as desired without modifying the script.
#!/bin/bash
#
# Prints snapshots with descriptions for virsh.
#
# Caveats
# This script has undefined behavior if snapshot name > 20 characters.
# (If that is a problem, consider changing "formatPre" and "cut -c2-21" below.)

vmdomains=`virsh list --all | sed 1,2d | awk '{ print $2 }'`
formatPre="%-21s%-21s"
format="$formatPre %s\n"

printf "$format" "Domain" "Snapshot Name" "Description"
printf "$format" "--------------------" "---------------------" "--------------------------------------"

SAVE_IFS="$IFS"
IFS=$(echo -en "\n\b")
for vmdomain in $vmdomains; do
  snapshots=`virsh snapshot-list $vmdomain | sed 1,2d | cut -c2-21 | sed 's/ *$//'`
  for snapshot in $snapshots; do
    printf "$formatPre " "$vmdomain" "${snapshot}"
    description=`virsh snapshot-dumpxml --domain "$vmdomain" --snapshotname "${snapshot}" | grep "<description>" | sed 's/  <description>//' | sed 's/<\/description>//'`
    echo "$description"
  done
done

IFS="$SAVE_IFS"

Sample output.  (Not all my snapshots have descriptions.)
Domain               Snapshot Name         Description
-------------------- --------------------- --------------------------------------
ps111                0-init
ps111                1-setup
ps111                2-named
ps111                3-python
ps111                4-tmp
skit20               00initial             initial
skit20               01setup               apt update/upgrade + vim + ssh
skit20-clone         00initial             initial
train20              01 Initial
train20              02 LinuxBase
watchdog20           00initial             initial

Answer: You can get the description from the snapshot xml dump:
virsh snapshot-dumpxml --domain {domain name} --snapshotname {snapshot name}

Answer: You can produce a list of all machines with information about their snapshots including the description with this little script.
  #!/bin/sh
  #\
  exec sudo tclsh "$0" "$@"

  # List KVM snapshots of all machines (domains) including their description
  # firstname.lastname@example.com 2020-08-21

  package require tdom

  ### Acquire list of machines (domains) from "virsh list --all"
  set machines ""
  foreach machineInfo [lrange [split [exec virsh list --all] \n] 2 end-1] {
    set name [string trim [string range $machineInfo 7 37]]
    set state [string trim [string range $machineInfo 38 end]]
    dict set machines $name state $state
  } ;# foreach

  ### Acquire list of snapshots for all machines (name, time and description)
  foreach m [dict keys $machines] {
    foreach snapshot [lrange [split [exec virsh snapshot-list --domain $m] \n] 2 end-1] {
      set name [string trim [string range $snapshot 1 21]]
      set xmlRoot [[dom parse [exec virsh snapshot-dumpxml --domain $m --snapshotname $name]] documentElement]
      set descr [[$xmlRoot selectNodes /domainsnapshot/description/text()] data]
      set creaTime [clock format [[$xmlRoot selectNodes /domainsnapshot/creationTime/text()] data] -format {%Y-%m-%d %H:%M}]
      dict set machines $m snapshots $name time $creaTime
      dict set machines $m snapshots $name descr $descr
    } ;# foreach snapshot
  } ;# foreach machine

  ### Output a list of all machines with their snapshots including time and description
  foreach m [dict keys $machines] {
    puts [format "\nMACHINE '%s' (%s)" $m [dict get $machines $m state]]
    catch {unset snapshots}
    dict with machines $m {
      if [info exists snapshots] {
        foreach sn [dict keys $snapshots] {
          puts "  SNAPSHOT '$sn', created: [dict get $snapshots $sn time]"
          foreach line [split [dict get $snapshots $sn descr] \n] {
            puts "    $line"
          }
        } ;# foreach snapshot
      } ;# if snapshot exists
    } ;# dict with
  } ;# foreach machine

  puts ""

Answer: This worked to a quick view
virsh snapshot-dumpxml --domain {domain name} --snapshotname {snapshot name} | grep 'description'


Entrada, na mesma linha, de uma string sem espaços e outra com espaços

Question: Meu programa pede que, na entrada, numa mesma linha, haja uma string sem espaços
nome, o nome do depositante, e uma string que pode conter espaços desc, a descrição do objeto depositado. De modo que, depois, eu crie um dicionário para relacionar o nome e o objeto.
Ex entrada:
Ana Bolsa azul
Contudo, da forma que eu fiz, só é possível entrar com uma palavra no local da descrição do objeto. Como proceder para entrar com mais de uma palavra em desc??
Como fiz:
dic={}

nome,desc=input().split()

dic.update({nome:desc})

Comment: Possível duplicata de [Como armazenar um int e um string completo de dentro de um input?](https://pt.stackoverflow.com/questions/209062/como-armazenar-um-int-e-um-string-completo-de-dentro-de-um-input)
Answer: Você pode alterar o split para quebrar apenas na primeira ocorrência
Como vai ficar o seu código:
dic={}

nome,desc=input().split(" ", 1)

dic.update({nome:desc})

Comment: Muito obrigada! (:


Testing background color espresso Android

Question: Is it possible to check if the background color matches a given color with espresso?
Update:
I made a custom matcher, similar to what @Irfan suggested, thanks!
public static Matcher<Object> backgroundShouldHaveColor(int expectedColor) {
    return buttondShouldHaveBackgroundColor(equalTo(expectedColor));
}
private static Matcher<Object> buttonShouldHaveBackgroundColor(final Matcher<Integer> expectedObject) {
    final int[] color = new int[1];
    return new BoundedMatcher<Object, Button>( Button.class) {
        @Override
        public boolean matchesSafely(final Button actualObject) {

            color[0] =((ColorDrawable) actualObject.getBackground()).getColor();

            if( expectedObject.matches(color[0])) {
                return true;
            } else {
                return false;
            }
        }
        @Override
        public void describeTo(final Description description) {
            // Should be improved!
            description.appendText("Color did not match "+color[0]);
        }
    };
}

Comment: To check the back ground colour of textview.
onView(withId(R.id.myTexView)).check(matches(hasBackground(R.drawable.background_colour)))
Answer: In my tests I have the following matcher for testing EditText color:
public static Matcher<View> withTextColor(final int color) {
    Checks.checkNotNull(color);
    return new BoundedMatcher<View, EditText>(EditText.class) {
        @Override
        public boolean matchesSafely(EditText warning) {
            return color == warning.getCurrentTextColor();
        }
        @Override
        public void describeTo(Description description) {
            description.appendText("with text color: ");
        }
    };
}

And usage is :
onView(withId(R.id.password_edittext)).check(matches(withTextColor(Color.RED)));

Comment: You should replace EditText for TextView, since the first inherits from the latter and getCurrentTextColor() is implemented in TextView. I haven't tested it, but it should work for both EditText and TextView.
Comment: or: withTextColor(ContextCompat.getColor(mActivityTestRule.getActivity(), R.color.your_color)) :)
Comment: I think it should be:
return getTargetContext().getColor(color) == warning.getCurrentTextColor();
Comment: has anyone seen this approach and in general `hasBackground` method failing from Android 28?
Comment: Kotlin cant knows 'withTextColor'
Answer: I am not sure about that but we can retrieve the color of some of elements like button and text views `
Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();

and you can try like this
ColorDrawable b_color = (ColorDrawable) button.getBackground();

and then
int color = b_color.getColor();
if (color == R.color.green) {
    log("color is green");
}

Hope this will get you started.
Answer: I am late but this might be helpful to someone else
    public static Matcher<View> matchesBackgroundColor(final int expectedResourceId) {
    return new BoundedMatcher<View, View>(View.class) {
        int actualColor;
        int expectedColor;
        String message;

        @Override
        protected boolean matchesSafely(View item) {
            if (item.getBackground() == null) {
                message = item.getId() + " does not have a background";
                return false;
            }
            Resources resources = item.getContext().getResources();
            expectedColor = ResourcesCompat.getColor(resources, expectedResourceId, null);

            try {
                actualColor = ((ColorDrawable) item.getBackground()).getColor();
            }
            catch (Exception e) {
                actualColor = ((GradientDrawable) item.getBackground()).getColor().getDefaultColor();
            }
            finally {
                if (actualColor == expectedColor) {
                    Timber.i("Success...: Expected Color " + String.format("#%06X", (0xFFFFFF & expectedColor))
                            + " Actual Color " + String.format("#%06X", (0xFFFFFF & actualColor)));
                }
            }
            return actualColor == expectedColor;
        }
        @Override
        public void describeTo(final Description description) {
            if (actualColor != 0) { message = "Background color did not match: Expected "
                    +  String.format("#%06X", (0xFFFFFF & expectedColor))
                    + " was " + String.format("#%06X", (0xFFFFFF & actualColor));
            }
            description.appendText(message);
        }
    };
}

I also logged the expected and actual color In hex format which might be helpful.
Usage: onView(withId(R.id.viewId)).check(matches(matchesBackgroundColor(R.color.colorId)));
Comment: Thanks a lot for this. This has been helpful for checking the background color of toolbar.
Answer: Another approach to check TextView text's color could be via hasTextColor(int color) as it comes directly from Espresso.
import static android.support.test.espresso.matcher.ViewMatchers.hasTextColor;

onView(withId(R.id.anyTextView)).check(matches(hasTextColor(R.color.red)));

Be aware that this method is currently in Beta for Espresso 3.0.1
Answer: It is possible to to test on color. I created a method to test on TextView background color as below. Also notice that am passing color resource.
 private fun withBackgroundColor(@ColorInt color: Int): Matcher<View> {
        Checks.checkNotNull(color)
        return object : BoundedMatcher<View, TextView>(TextView::class.java) {
            override fun describeTo(description: Description?) {
                description?.appendText("TextView background color to be $color")
            }

            override fun matchesSafely(item: TextView?): Boolean {
                val backgroundColor = item?.background as ColorDrawable
                val colorDrawable = ColorDrawable(ContextCompat.getColor(item.context, color))
                return colorDrawable.color == backgroundColor.color
            }

        }
    }

I create ColorDrawable object from color resource and get color from the object.
Comparing color from resource without the ColorDrawable does not pass. Hope this helps you.
Answer: private fun hasBackgroundColor(colorRes: Int): Matcher<View> {
    Checks.checkNotNull(colorRes)

    return object : TypeSafeMatcher<View>() {
        override fun describeTo(description: Description?) {
            description?.appendText("background color: $colorRes")
        }

        override fun matchesSafely(item: View?): Boolean {

            val context = item?.context
            val textViewColor = (item?.background as ColorDrawable).color
            val expectedColor: Int?

            if (Build.VERSION.SDK_INT <= 22) {
                expectedColor = context?.resources?.getColor(colorRes)
            } else {
                expectedColor = context?.getColor(colorRes)
            }

            return textViewColor == expectedColor
        }
    }
}

Answer: Here is what i use in my tests
public static Matcher<View> withTextColor(final int color) {
    Checks.checkNotNull(color);
        return new BoundedMatcher<View, TextView>(TextView.class) {
            @Override
            public boolean matchesSafely(TextView textView) {
                return ContextCompat.getColor(getTargetContext(),color)==textView.getCurrentTextColor();
            }
            @Override
            public void describeTo(Description description) {
                description.appendText("with text color: ");
            }
        };
}

and call it as
onView(withId(R.id.price_value)).check(matches(withTextColor(R.color.black)));
Answer: More concise and elegant way of doing in Kotlin with SAM conversion
onView(withId(R.id.tv_login_result)).check{
            view, _ ->
        val actualColor = ((view as MaterialTextView).background as
                           ColorDrawable).color
        assertEquals(Color.RED, actualColor)
    }


List 'areas' used in TFS project

Question: I've been playing about with the WorkItem objects from the Microsoft.TeamFoundation schemas in C#, but was wondering if anyone knows how I would refer to an object of type 'Area' or, for that matter, 'Iteration'.
It seems that these are treated as objects in TFS, but I haven't come across any information on how to refer to these in C#.
You can filter WorkItems by [Area] or [Iteration] using WIQL, but what if I wanted to populate a ComboBox with all Areas or Iterations?
Also, how can I view the database structure of my workplace's TFS project?
Thanks guys,
Andy
Answer: Have a look at this Blog Post. There's sample code and a demo.
Here's a quick LINQPad Query that should do the job (download VS2010 / VS2012):
<code>void Main()
{
    const String CollectionAddress = "http://tfsserver:8080/tfs/MyCollection";
    const String ProjectName = "MyProject";

    using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(
        new Uri(CollectionAddress)))
    {
        tfs.EnsureAuthenticated();
        var server = tfs.GetService<ICommonStructureService>();

        var projectInfo = server.GetProjectFromName(ProjectName);
        var nodes = server.ListStructures(projectInfo.Uri).Dump();

        // You should be able to re-factor this with "Iteration"
        // for getting those too.
        var nodesXml = server.GetNodesXml(
            nodes
                .Where(node => node.Name == "Area")
                .Select(node => node.Uri).ToArray(),
            true);

        var areaPathAndId =
            XElement.Parse(nodesXml.OuterXml)
            .Descendants("Node")
            .Select(xe => new
            {
                Path = xe.Attribute("Path").Value,
                ID = xe.Attribute("NodeID").Value,
            })
            .Dump();
    }
}
</code>
Comment: Thanks Dave. Since I don't have any experience with LINQ, I've started with the link you posted. Managed to get it working but only for the top layer of the hierarchy. I'm pulling my hair out trying to get to the child nodes, e.g. for iteration: Releases/1/1.0/1.01. I may come back here for more help.

List 'areas' used in TFS project


Query Selector questions

Question: Can you take something like...
var skullclick = document.querySelector('input[value="Small Haunted Skull"]').click();

and then make it so that it will find more like..
var skullclick = document.querySelector('input[value="* Small Haunted Skull"]').click();

the * referring to anything before this is accepted , the way its shown on the page is # Small Haunted Skulls so i can't just do Small Haunted Skulls, Or am I wrong?
a.k.a the problem I'm having is I'm just unsure if you are actually able to take just a part of the text rather then the requirement of the entire text given and it still come out the same way as if you were to add the numbers before hand.
Comment: Hmm, what is the aim of your code? What do you want it to do?
Comment: This is the pages code for the button
http://puu.sh/ln4JD/cbe65f9956.png
i'm simply trying to make TamperMonkey click that specific thing, the problem is i can't go by the id since the slot is always changing where that item is. so i want it to find the "Small Haunted Skulls" part of the innerhtml and click that button rather then something else.
Comment: Stefan's should work for you then
Comment: It doesn't look at my comment on his.
Comment: Sorry, I cannot figure out what you are asking. You want something automatically clicked? If you are just trying to find an element that contains particular text, use jquery and check out `selector:contains`
Comment: It should be with the way it's written is to click Automatically the "Small Haunted Skulls" find, and then the Use buttons.
Answer: Have a look at CSS attribute selectors
input[attribute$="Small Haunted Skull"] might just be what you are looking for.
Comment: http://puu.sh/ln6C5/e6a2279f41.png
Doesn't seem to be working it's as if nothing is actually going on really, the stamina is coming back 0 (should be) so by that if statement it should click the small haunted skulls button then click the use after that.

without clicking it
http://puu.sh/ln6GN/9a5fb2907b.png

After clicking (how it should look)
http://puu.sh/ln6Jy/5cc19c5471.png
Comment: Check your console. It looks to me like you are having a typo in in your setIntervall call (";" too much).

Query Selector questions


Flat s-t 4d Killing vectors via solving Killing equation

Question: So I know what these are
4 translation : $\frac{\partial}{\partial_ x^{u}} = \partial_{x^u}$
3 boost: $z\partial_y - y \partial_z$ and similar for $x,z$ and $ y,x$
3 rotation: $t\partial_x + x\partial_t $ and similar for $y , z$
however I want to do it by solving Killing equation:
$\nabla_u V^v + \nabla_v V^u =0 $
So in flat space, these $\nabla_u$ reduce to partial derivatives $\partial_u$
So Killing equation reduces to : $\partial_u V^v + \partial_v V^u=0$
Without writing things out explicitly, e.g the time translation $\partial x^0 = (1,0,0,0) $ I am confused how to work in index notation. To begin, the translations $\partial_{x^u}$ are covector and not vector, the Killing equation works in vector, so rather do I need $\frac{\partial}{\partial x_u}$ instead of $\frac{\partial}{\partial x^u}$, I don't know what this is explictly?
Further I am confused with the indices in the boosts and the rotations, so the translations are given as covectors, which we can raise an index to get a vector but isn't something like:
$z\partial_y - y\partial_z$  a covector multiplied by a vector and so not a vector but a scalar, since $x^u=x,y,z,t$ is a vector but $\partial_x^u $ is a covector.
Anyway once I've cleared these up the HINT is to differentiate Killing equation and then solve the ODE.
Should I do $\partial_u$ or should I choose a different index not already in Killing equation. Does it matter? I dont see how we can convert this PDE itno an ODE since it already has $\partial_u$ and $\partial_v$, if I hit it with $\partial_u$ I get a $\partial^2_u$ but then also the mixed term $\partial^2_uv$
Many thanks
Answer: Ok, I will provide you with a sketch, but you have to fill in the details. So the Killing equation is: $\partial_\mu V_\nu + \partial_\nu V_\mu = 0$. Let $A_{\mu\nu} = \partial_{\mu}V_\nu$. By the Killing equation, we have that $A_{\nu\mu} = -A_{\mu\nu}$. In other words, $A$ is skew-symmetric in its two indices.
Now define $B_{\rho\mu\nu} = \partial_\rho A_{\mu\nu}$. Then $B$ is symmetric in its first two indices, by Euler's theorem, and skew-symmetric in its last two indices, by the Killing equation. Exercise, by playing with indices, show that this implies that $B$ must be identically $0$.
Deduce then that $(A_{\mu\nu})$ must be a constant skew-symmetric matrix, which we denote by $(c_{\mu\nu})$. Then solve the equation $\partial_\mu V_\nu = c_{\mu\nu}$.


Training a Support Vector Machine classifier on a satellite image using python

Question: I am new to the concept of supervised classification technique. I am trying to use an SVM classifier for classifying Sea Ice types in the Arctic using satellite image. All the tutorials I have read for performing a supervised SVM classification use data that comes with labels. For instance, if we have a table which is populated with different crops (trying to predict the crop type), each row of the table corresponds to a label (crop type). Then. the procedure for classifying these data is straightforward.
In my case, I have acquired a satellite image over my area of interest. A satellite image has x,y coordinates and two bands (channels). To train my model (using scikit-learn), I have to provide the SVM classifier with training and target data (which is the label data). In my case, I have no label data.
According to my understanding, I have to create label data somehow out of my whole dataset? Is that right? I am trying to get my head around that problem.
Is there any automatic method in python where it trains the model without providing label data? I have not managed to find a solution so far
Comment: Unlabelled/[unsupervised learning](https://en.wikipedia.org/wiki/Unsupervised_learning) encompasses different techniques (and problems) than supervised learning. If you want "correct" classification (such as trying to predict crop types) then you'll generally need examples of that (otherwise, how do you know if you're doing better at being correct?). If you just want to identify differences (what's unlike what and how) that's the unsupervised type of problem -- it will find you "kinds" of things without anyone knowing what the "kinds" are; these might not correspond to the way humans see it.
Comment: .... the point being you should clarify what you want your model to actually be giving you. If you want to spot known types - let's call them I, II and III - that's supervised (tell it what those look like). If you want it to say "well I found these nine kinds that look alike within their kinds and look different between them"  (i.e. they "cluster"), that's unsupervised and you don't need labels (though you might be able to invent names for those clusters *post hoc*)
Answer: This is the basic supervised / unsupervised dichotomy in machine learning:

Supervised learning, unsupervised learning and reinforcement learning: Workflow basics
Unsupervised, supervised and semi-supervised learning
Semi-supervised learning, active learning and deep learning for classification

To answer your question, to train a classifier, yes, you're going to need some labels. Unsupervised techniques like clustering ($k$-means, for example) might also be useful for studying your data.


telerik radscheduler Appointments don't update with ruler change

Question: In my application I want to give the user the ability to see that start and end date of the radscheduler control.
I found I can do this using the following code
RulerPrimitive ruler = (this.scheduler.SchedulerElement.ViewElement as SchedulerDayViewElement).DataAreaElement.Ruler;
ruler.StartScale = 5
ruler.EndScale = 9

After I add the code, the ruler will adjust but the appointments start and end times will no longer align with the appropriate time on the ruler. The telerik docs don't mention anything else that need to get called, so I am wondering what I am missing?
Comment: What do you mean by "the appointments start and end times will no longer align with the appropriate time on the ruler". Are you expecting the appointment start/end times to be changed according to the new ruler scale?
Comment: @checho no, but I would expect the appointment block to re-align with the ruler scale markings as the scale is adjusted. This is not happening. Example by default the ruler scale is hourly. if i change it to half hour, the ruler scale changes but the appointment stays in the exact same position on the screen, thus making the appointment appear like it occurs before it actually does.
Answer: It seems like you need the exact time rendering functionality of the Telerik UI for WinForms RadScheduler. Here is how to turn it on:
radScheduler1.EnableExactTimeRendering = true;


Adding Object in Entity Framework

Question: In an Application it has Data Access layer.In which it has DataEntityModel.edmx  (entityframework model)  and repository class.

Below code is my repository class.
namespace DataModel.Repository
{
 public class ProductRepository
 {
    internal WebApiDbEntities Context;
    internal DbSet<Product> DbSet;

     public ProductRepository(WebApiDbEntities context)
    {
        this.Context = context;
        this.DbSet = context.Set<Product>();
    }

    public virtual void Insert(Product entity)
    {
        DbSet.Add(entity);
    }

}

}

Question is I have used DbSet.Add(entity) method to insert . But Entity Framework will generate it's own Add method Context.Products.Add(entity)
So, What is the difference between those two methods. Why Most of the
  time DbSet.Add(entity) is used ??
Answer: A repository replaces the use of the DbContext.
So to add an entity, instead of:
var dbContext = new WebApiDataModel();
dbContext.Products.Add(entity)

You use a repository:
var dbContext = new WebApiDataModel();
var productRepository = new ProductRepository(dbContext);
productRepository.Insert(entity);

In the end, both call DbSet<Product>.Add(), but there are reasons why you may want to introduce the repository pattern with Entity Framework.
Comment: my question is with in the productRepository.Insert() method we can call dbContext.Products.Add(entity) method. But why we use  DbSet.Add(entity) rather than  dbContext.Products.Add(entity) ?
Comment: Yes, you can use either. Someone (not you, apparently) decided to introduce the repository pattern. You use that to abstract away the use of DbContext. So yes, you can use both, but you should choose either.

Adding Object in Entity Framework


How to display a number of different lines in a label using c#?

Question: I know how to display one line of text in a label using
thislabels.Text = "Hello";
But I want to be able to display a line of text each time an event happens, while also maintaining whats currently on display.
For example, I'm making a scoreboard and I want to print every time someone scores something like this..
Joe Smith scored 3 points
Joe Smith scored 5 points
...
Smith Joe scored 3 points

How do I do this? I'm not concerned with any of the formatting of how to display the text, I just want to know I can keep a running of events
Comment: In this case a ListBox is also good because of the scrollbars
Comment: try ``thislabels.Text+="\n"+event`` (remember to set to empty string initially)
Comment: I would recommend you not using a label if the text is going to change based on an event. i'd rather use a readonly textbox
Answer: You could append a newline every time, some examples:
label.Text += $"{Environment.NewLine}YourTextHere";//String-interpolation
label.Text += String.Format("{0}YourTextHere", Environment.NewLine);
label.Text += Environment.NewLine + "YourText";

This could however get quite big, I suggest putting your label in a panel with the property AutoScroll to true, this way the panel is the max size of the label and instead of going off the Form it will make a scrollbar:
panel.AutoScroll = true;

Answer: thislabel.Text += "Hello"

Hello

thislabel.Text += "\r\nWorld"

Hello
World


mime type ('text/html') is not supported stylesheet MIME type, and strict MIME checking is enabled

Question: Im just trying to add Fontawesome to my new custom theme in libraries.yml but im getting: mime type ('text/html') is not supported stylesheet MIME type, and strict MIME checking is enabled.
global-fontawesome:
  version: 6.2.0
  css:
    theme:
      fontawesome/css/fontawesome.min.css: {}

Comment: This seems like a web server misconfiguration but there isn't enough information here to make any conclusion.
Answer: SOLVED:
Just adding attributes:
global-fontawesome:
  version: 6.2.0
  css:
    theme:
      fontawesome/css/fontawesome.min.css: {attributes:{type: "text/html"}}


Unable to import module from another package

Question: I have a directory structure like this
conf
    __init__.py
    settings.py
    abc.conf
    def.conf
src
    main.py
    xyz.py

src I chose not to make a package but a regular folder.
I am trying to import the settings.py file in the main.py and executing the whole thing with the command python3 main.py
My import statement in main.py : import conf.settings
The error I'm getting is No module named conf.settings and I can't get my head around it.
Is python failing to recognize conf as a package? Can packages contain files other than .py files (.conf files in my case)
Comment: It says
    ```from . import conf.settings
SyntaxError: invalid syntax```

With the marker on ```config.settings```.Does it make a difference if I added the __init__.py file later? config was originally meant to be a folder, I later decided it was better suited as a package.
Comment: This new import statement says ```No module named conf``` and my __init__ file is empty. I'm running the ```python main.py``` command from inside the src folder.
Comment: Do you expect for Python to go into every single folder _upstream_ of your current working directory (which is `src` given that you're executing your program with `python3 main.py`), check them all for `__init__.py` and add them to its import module resolution path? That would take a lot of time on each run, not to mention all the possible conflict/path clashes it may cause. Therefore, your options are to either add your _parent_ folder to the Python path (`PYTHONPATH` env. variable), alter `sys.path` at runtime or, the simplest and most recommended approach - just move `conf` to `src`.
Answer: When importing python search current directory and the sys.path. Since your main.py is in src folder it cannot see the conf package folder. Luckily you could update sys.path at runtime.
root
     conf
        __init__.py
        settings.py
     src
        main.py

So you could append sys.path from main.py before importing conf module. Try following:
# main.py
import os, sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

from conf import settings
...

The other way is to update PYTHONPATH directly and add path to your script root directory.
Comment: Is this the recommended way of importing modules outside the current directory or is it just a hack of doing so?
Comment: It is legitimate way.
Comment: You could move your `conf` inside of `src` and avoid updating `sys.path` at all, if that is acceptable...


Probability of events where outcomes do not have equal probability

Question: so I'm taking an intro to probability course and this question was given as part of the first assignment. I've read over notes and course material but nothing seems to be relevant to question such as this (i.e. all outcomes a1, a2, etc. not having equal probability). I've guessed that I need to incorporate partitions in some way, but honestly I'm at a loss.
I was wondering if somebody could point me in the right direction. Given this is for an assignment, I'm not looking for a solution, just a little bit of advice. The question is as follows:
Let the sample space Ω = {a1, a2, a3, a4, a5, a6} be given. Assume that: Let A = {a1, a2, a3}, B = {a2, a4}, C =
{a4, a5, a6}, D = {a2} and E = {a4}. If P(A) = P(B) = P(C) and P(D) = 2P(E). Find:
(a) P(A ∩ D')
(b) P(A ∪ E)
(c) P(A|B')
Thanks in advance!
Comment: notice that the sets $A$ and $C$ are mutually exclusive and exhaustive in $\Omega$  so $P(A) + P(C)=1$
Comment: Nevermind I figured it out. As P(A) + P(C) = 1, then P(A) = P(B) = P(C) = 1/2. And then I could deduce from there. Thanks for the tip!!
Comment: Thanks! Though to clarify, I'm still lost as to how I should be expressing the probability. Do I have to figure out the likelyhood of each outcome, or express it in terms of other events? Or am I completely off-base?
Answer:
Let the sample space $Ω = \{a_1, a_2, a_3, a_4, a_5, a_6\}$ be given. Assume that: Let $A = \{a_1, a_2, a3\}, B =\{a_2, a_4\}, C = \{a_4, a_5, a_6\}, D = \{a_2\}$ and $E = \{a_4\}$. If $P(A) = P(B) = P(C)$ and $P(D) = 2P(E)$.

$$\begin{array}{|l|l:6l|}\hline & a_1 & a_2 & a_3 & a_4 & a_5 & a_6 \\ \hline A & \checkmark & 2x & \checkmark  \\ \hdashline B && 2x  && x \\ \hdashline C &&&& x & \checkmark & \checkmark \\ \hdashline D && 2x \\ \hdashline E &&&& x \\ \hline \end{array}$$
$P(E)=x, P(D) = 2x, P(A) = P(B) = P(C) =3x$
Also $P(A)+P(C)=1$ so...
Answer: Work it out where the probability of a1, a2... a6 is equal. For a, that's the probability for a1 or a3 but not a2, which is P(a1, a3), which is 1/3. For b, which is for A or E, which is P(a1, a2, a3, a4), which is 2/3. I expect you can work out the third one. (If you can't, ask me.)
Comment: But how can they be equal if P(a2) = 2P(a4)? Am I overthinking it?
Comment: Let $P(a_4)=x, P(a_2)=2x$ then $P(a_2\cup a_4)=3x~=P(B)$ and...


Can an analytic function on the open unit disk blow up near the boundary?

Question: Can we have a map $f$, holomorphic on the open unit disk, such that $|f(z)|\rightarrow \infty$ as $|z|\rightarrow 1$? I think not, (at least I can't think of any such map), but I'd like to be able to prove this.
Comment: Do you mean as $|z|\rightarrow 1$?  1/(z-1) blows up at one point, do you need it to blow up at all boundary points?
Comment: To blow up at all boundary points consider the answer to [this post](http://mathoverflow.net/questions/10831/example-of-continuous-function-that-is-analytic-on-the-interior-but-cannot-be-an)
Answer: Such a function cannot exist. Suppose such a function exists. Let $z_1,\ldots,z_k$ be the zeros of $f$ in the unit disc with corresponding multiplicites $m_1,\ldots,m_k$. Then
$$g(z) = \frac{(z - z_1)^{m_1}\cdots(z - z_n)^{m_k}}{f(z)}$$
is an analytic function in the unit disc such that $\lim_{\vert z \vert \to 1}g(z) = 0$. This contradicts the maximum modulus principle.
Comment: Note that we don't have $\lim\limits_{\lvert z\rvert \to 1} \lvert f(z)\rvert = +\infty$. That is not possible for holomorphic functions on the unit disk. Also, the denseness of dyadic rationals doesn't prove that the radial limit is $\infty$ at other points.
Comment: @Curious See the edited answer. Such a function could have only finitely many zeros, and dividing those out would leave a zero-free holomorphic function that still blows up at all boundary points (since the domain is bounded). Then its reciprocal would violate the maximum modulus principle.
Comment: @Daniel Fischer Why is it not possible to have holomorphic function that blows up at all boundary points?
Comment: @DanielFischer Excellent, thanks!


Matriz intercalada

Question: Olá, estou fazendo este exercício, mas estou tendo uma dificuldade. Segue o enunciado:

22) Escreva um programa para gerar uma matriz (N x M) (<=20) e outra (N x
  P) (<=20). Gerar uma terceira matriz (N x (M+P)) (<=20 x <=40), sendo que
  para cada linha intercalar suas respectivas colunas e apresentar as três matrizes.

Eis o código que já tenho:
import java.util.Scanner;

public class Ex22 {
    public static void main(String args[]) {
        Scanner leia = new Scanner(System.in);

        int n, a = 0, b = 0;

        do {
            System.out.printf("Entre com o tamanho da matriz: ");
            n = leia.nextInt();
        } while (n > 20);

        int [][] m = new int [n][n];

        System.out.printf("\nMatriz M:\n");
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                m[i][j] = (int)(Math.random() * 9+1);
                System.out.printf("%d ", m[i][j]);
            }
            System.out.printf("\n");
        }

        do {
            System.out.printf("\nEntre com o tamanho da matriz: ");
            n = leia.nextInt();
        } while (n > 20);

        int [][] p = new int [n][n];

        System.out.printf("\nMatriz P:\n");
        for(int i=0; i<n; i++){
            for(int j=0; j<n; j++){
                p[i][j] = (int)(Math.random() * 9+1);
                System.out.printf("%d ", p[i][j]);
            }
            System.out.printf("\n");
        }

        int [][] q = new int [n][n+n];

        System.out.printf("\nMatriz Q:\n");
        for(int i=0; i<n; i++){
            for(int j=0; j<(n+n); ){
                q[i][j] = m[i][a];
                a++;
                j++;

                q[i][j] = p[i][b];
                b++;
                j++;
            }
        }

        for(int i=0; i<n; i++){
            for(int j=0; j<(n+n); j++){
                System.out.printf("%d ", q[i][j]);
            }
            System.out.printf("\n");
        }

    }
}

Alguém sabe porque está dando estouro?
Comment: Alguém sabe porque está dando estouro?
Esse é o erro que retorna:

 Matriz Q:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
 at Ex22.main(Ex22.java:53)

Mas em C ele compila sem erros.
Comment: Você não reinicia `a` e `b` no for da matriz q, não analisei o resto do código, mas você tá considerando que n = m = p e não é isso que a questão pede também...
Comment: Michael Martins, compilar ele compila normalmente, mas entre compilar e executar há uma diferença enorme.
Answer: Primeiramente, você está lendo n duas vezes, mas você deveria ler n, m e p de forma independente.
Depois o trecho mais problemático é este:
    for(int i=0; i<n; i++){
        for(int j=0; j<(n+n); ){
            q[i][j] = m[i][a];
            a++;
            j++;

            q[i][j] = p[i][b];
            b++;
            j++;
        }
    }

Observe o a++; e o b++;, vão fazer cada um ir de 0 até 2n² e não acho que é isso que você quer, uma vez que ao acessar m[i][a] ou p[i][b] você terá um indíce de coluna fora do intervalo válido, e portanto a exceção:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
        at Ex22.main(Ex22.java:46)

Provavelmente está faltando um a = 0; e um b = 0; em algum lugar.
Comment: Exatamante. a=b=0

Obrigado a todos ^^

Matriz intercalada


Why is the absence of zero divisors not sufficient for a field of fractions to exist?

Question: I've recently begun to read Skew Fields: The General Theory of Division Rings by Paul Cohn.
On page 9 he writes,

Let us now pass to the non-commutative case. The absence of zero-divisors is still necessary for a field of fractions to exist, but not sufficient. The first counter-example was found by Malcev [37], who writes down a semigroup whose semigroup ring over $\mathbb{Z}$ is an integral domain but cannot be embedded in a field. Malcev expressed his example as a cancellation semigroup not embeddable in a group, and it promped him to ask for a ring $R$ whose set $R^\times$ of nonzero elements can be embedded in a group, but which cannot itself be embedded in a field.

The cited paper [37] is On the immersion of an algebraic ring in a skew field, Math. Ann 113 (1937), 686-91. (EDIT by M.S: doi: 10.1007/BF01571659,
GDZ.)
I've had no luck finding this freely available online, nor at the library. Does anyone have reference to this paper, or at least the part where Malcev demonstrates these two parts of his counter-example? I would greatly appreciate seeing it. Thanks.
Comment: Mathematische Annalen are freely available at GDZ (I've edited link to your post.) You would have found that link if you have checked [Wikipedia
article](http://en.wikipedia.org/wiki/Mathematische_Annalen). This is my general advice - if a journal is available freely online and there is a Wikipedia article about this journal, you will most probably find a link there. (Anyway, getting the paper directly from Springer would be better, since you would have an OCRed version.)
Comment: BTW I was not sure whether I should post the link to the paper as a comment or as an answer - the reason is that title of your post is somewhat different from the body. The title suggest that you would like to see an explanation, but from the body it seems that you just want to find the paper, if it is available online.
Comment: Thanks Martin, the link was quite helpful. I've used your advice on finding papers a handful of times already since you've posted these comments!
Comment: See also here: [Is there any way to read articles without subscription?](http://math.stackexchange.com/questions/30297/is-there-any-way-to-read-articles-without-subscription/).
Answer: You can find in most good noncommutative algebra books a discussion of how the normal "field of fractions" construction fails in some noncommutative domains. Your keywords to look for are "Ore condition" and "right Ore domain". If you haven't had luck downloading Cohn's example, there will be many under these keywords.
In short, the right Ore condition is necessary and sufficient for the normal field of fractions definition to work. Without it, it may be impossible to add or multiply fractions, because there will problems finding common denominators.
Here's what I mean: If you carry out the normal equivalence relation in an effort to create a right division ring of fractions, you use $(x,y)\sim(w,z)$ if there exists nonzero $s$ and $t$ such that $ys=zt\neq0$ and $xs=wt$. This allows you to bring things to common denominators, but notice you are only allowed to introduce things on the right.
Suppose you want to add $(a,b)+(c,d)$ where $b,d$ are nonzero. You would like to define this as $(stuff,bd)$. You can form $(ad,bd)\sim (a,b)$ but you are unable to form $(bc,bd)$ because you cannot introduce $b$ on the left.

If you have access through googlebooks or otherwise, Lam's Lectures on Modules and Rings recounts Mal'cev's example of a domain which is not embeddable into a division ring on page 290.
Comment: I think equivalence relation is rather : $(x,y) \sim (w,z)$ iff $\exists t,s \neq 0$ st $yt=zs$ and $xt=ws$.
Comment: @user10676 Yes thanks... fixed. I don't know how I screwed that up here... I'm working on that very definition in another post simultaneously! Must be the 100+ degree weather...
Comment: Thanks for the reference, it's quite illuminating for me.


How to pull the next available previous date?

Question: What I have:
I have table with a unique date column.

id
date

1
2021-09-01

2
2021-08-01

3
2021-07-01

4
2020-04-01

5
2020-03-01

6
2020-12-01

I pull data based on a month and year from a GET parameter.
DB::table('budgets')->whereMonth('created_at', $request->get('month'))->whereYear('created_at', $request->get('year'))->get()->first();

I do a check to see if a previous month is available in table
$pm = DB::table('budgets')->whereMonth('created_at', $prev_month)->whereYear('created_at', $prev_year)->count();
if ($pm > 0) {
  $prev_month = date('m', strtotime($_GET['month']. ' - 1 month'));
  $prev_year = date('m', strtotime($_GET['month']. ' - 1 month'));
  Previous Month
}

This works great... if there is a previous month i.e. 1 month behind.
My question is:
How can I check what the nearest/next date is?
Example:
If I was already on '2021-07-01', how would I know the next 'previous' date is '2020-12-01' and visa versa?
Comment: You should not do this by trying to _calculate_ the previous year and month. Select the records with a date _lower_ than the one you are trying to find previous ones for, _order_ the result properly, and pick the first one of those.
Comment: @CBroe Much better logic, thanks.
Answer: You can check the nearest/next date this way
$next_date = DB::table('budgets')
              ->where('created_at', '<', $date)
              ->orderByDesc('created_at')
              ->first()
              ->value('created_at');

Answer: The solution as per @CBroe advice:
<?php
$this_date = date('Y-m-d', strtotime($_GET['month'].'-'.$_GET['year'].'-01'));
$pm = DB::table('budgets')->where('created_at', '<', $this_date)->orderby('created_at', 'desc')->get()->first(); // Find dates less than the one searching for and order it descending order and get only the first row.

if ($pm) {
  $prev_month = date('m', strtotime($pm->created_at));
  $prev_year = date('Y', strtotime($pm->created_at)); ?>

  Previous Month

<?php } ?>


Windows 10 Hibernate Boot let's suspend (Powershell) Script execution at Startup

Question: I am intensively working with Powershell Scripts which are executed at startup (local machine, not logon). I had some problems to troubleshoot like "Wait for network" or replication failures between our domain controllers that prevented sometimes the execution of my Powershell Script during startup.
As I now have fixed all of these problems and the event log looks good, I discovered, that the Powershell script is often not executed. I looked what my colleagues made and it seems like the Powershell script at startup ist only executed when the perform a restart. As I know Windows 10 (and 8?) performs a hibernate shutdown and startup when you normally use "shutdown". This isn't the case if you choose restart.
Am I right with this assumption? I found nothing documented in the world wide web. I disabled the Fast Boot / Hibernate Boot in our domain and will have a look every day the script is at least executed one time.
Looking forward to hear your experience.
Answer: I could verify this behavior in our domain at 20 computers at all. I am pretty sure that hibernate / fast startup prevents the script execution at startup often. I worte a blogpost about this and how to disable this via GPO (regkey modification). If you know the exact reason why Window 10 (not testet at 8, but pretty sure it's the same thing) does not execute the scripts...


How to sort nodes per domain with the Views module?

Question: I have to display nodes in different order(weight) inside a view per domain on a multi-domain site.
example:
<code>on domain1: view-beverages => 1-Coca Cola, 2-Perrier, 3-Redbull, 4-IceTea ...
on domain2: view-beverages => 1-Perrier, 2-IceTea, 3-Redbull, 4-Coca Cola ...
...
</code>
I thought to use the module Flag Weights, but Flag is per user and not per domain.
Do you think I can do this by using "Draggableviews"?
Can I create a table view for each domain with Draggableviews to manage the order of the node by domain, and make the final display view chose automaticaly the "sort criteria" (Draggableviews : Weight) of the courant domain. I hope I am clear enough.
How can I do this, or there is an alternative?
Answer: You are right: Best ot achieve ordering in views-lists is indeed draggableviews. But beware that this doesn't work with all styles. I am not sure, since it is half a year ago I have needed it for a project, but I think draggableviews is made for tables in mind. But as far as I remember there was an additional module making it possible also for other listing styles.
But the rather real problem is not how to order the views list items. The problem is that you need 2 almost same but a little bit different views (page-views? or block-views?), and how to let the 2 views show up on 2 different domains. I assume you would like to have the kind of same page on the same path but on two different domains in two different orders. The problem here is, if you try to achieve this with overriding paths by 2 different views and different domain conditions, the filtering or conditioning of the view depending the domain will make some trouble... It will always try to load both views and will always take the first arriving and if the condition doesn't fit, it will not change to the other. This is not a bug. It is because of how overriding paths works.
Let me know if you have any idea how to achieve this last part. Maybe I can help then on some further steps on it. But in the moment I see the end of the road here.
Comment: ups. now I see the question was old ... well .. maybe interesting for others ... :-/
Comment: I continue to search a way to achieve this... thank you anyway ;-)


Has Bela Bartok influenced Jazz tremendously?

Question: Bela Bartok rediscovered Modal scales from eastern Europe. Lydian, Phrygian, etc...
What I was wondering was.... was it the first time that these scales were rediscovered and went into mainstream classical music? and did Bela Bartok influenced Jazz music, especially with his modal scales? Miles Davis and Bill Evans comes into my mind in that regard.
Comment: Adam Neely claims many jazz musicians have "great affinity" with Bartók, though he doesn't name anyone in particular: https://www.youtube.com/watch?v=YOcvPaFY9UE
Comment: I know that modern classical musicians that went to America from the hands of Nazis influenced Jazz music greatly. But as of Modal scales, I don't know..
Comment: Oh, this video is so awesome! I'm watching it.
Comment: Would arranging or quoting folk songs that use modes count as them going "into mainstream classical music"? If so, then Gustav Holst and Ralph Vaughan Williams were both arranging English folk songs that use the Dorian mode for concert band within a decade of Bartok's work with Hungarian melodies.
Answer: Jazz musicians in the 50s and 60s were forever searching for new sounds. Trane was known to make use of Slominsky's book.
Given that these modes are simply major scales starting from not the tonic, it is pretty unlikely that musicians in that period would not have started making use of them. Bartok was undoubtably a great, but to credit him with more than the usual amount of influence because of his modal approach seems a bit much. (Stravinsky was also a big influence, Bird is said to have quoted one of his themes in his presence.)
So I would say - no more than other great modern composers.
Answer: Bela Bartok was one of the leading composers writing gypsy music, along with Kerler. While jazz is a more modern style of music, most modern composers before jazz would have influenced the new style.
Comment: It wasn't gypsy music. He didn't like that music. It was the Magyar folk tunes he collected.


Considering $g = \pi$ and its approximation $g_h = \frac{22}{7}$ find the absolute error and relative error.

Question: Considering $g = \pi$ and its approximation $g_h = \frac{22}{7}$ I am trying to find the absolute error and relative error.
Here are my workings, this is the first tie doing this sort of problem so I am not sure if this is correct or not.
$$E_{abs} = \left|\pi - \frac{22}{7}\right| = 0.00126 \approx 0.0013$$
$$E_{rel} = \left| \frac{\pi - \frac{22}{7}}{\pi}\right| = 0.000402 \approx. 0.0004$$
Looking to see if these workings are correct, thanks!
Comment: So what is the motivation for your question, exactly? Do you not know (or are you not sure of) the definition(s)? These are correct, but I don't think you're going to learn anything from that.
Comment: sorry I am just checking to see if my workings were correct
Answer: You have used the definitions of absolute and relative error correctly.
One criticism: I suggest you modify your notation to show that the error is not exactly $0.000402$, perhaps by using ellipsis.
$$E_{rel} = \left| \frac{\pi - \frac{22}{7}}{\pi}\right| = 0.000402\color{red}{\dots} \approx 0.0004$$
Comment: yes you are right I should of used the ellipsis or the approx. again. Thanks for your help!


Finding mean and SD of 2 parts of a whole

Question: I am putting together a review/meta-analysis of body composition in children. The data I will analyze consists of measures of fat-mass (FM) and fat-free-mass (FFM), which when summed  equal total mass. While most papers report the means and SDs for FM and FFM, which is what I want, every so often I get a paper that reports the mean and SD of total mass, and a mean and SD of %FM (i.e. FM/(FM+FFM)).
My question: Can I calcuate the mean and SD of FM and FFM, given I have the mean and SD of total mass, and the mean and SD of FM/(FM+FFM).
Answer: Just a partial answer, adressing one of your questions.
Generally, for probability distributions you have:
$$
E(X+Y) = E(X)+E(Y)
$$
and
V
$$
V(X+Y) = V(X)+V(Y) + 2\text{Cov}(X,Y)
$$
with E and V being the expectation and variance respectively ($SD = \sqrt{V}$).
For you, this means the mean of the sum is just the sums of the means (so you can get it). For the SD of the sum you also need the covariance or correlation between the FM and FFM. One might use sensible guesses to get realistic lower and upper bounds. Your question regarding FM/(FM+FFM) is much more complicated.
I am not even sure that it is possible without knowing the exact distributions. There is an approximate solution using the delta method:
http://en.wikipedia.org/wiki/Taylor_expansions_for_the_moments_of_functions_of_random_variables. But you also require the covariance for that.
Comment: Thanks. There is no way I'll get the covariances, but even just the means can be helpful, given I have sample sizes and can make pretty good guesses about the variances given the other data I have. At the very least you have kept me from hitting my head against the wall all day trying to work this out.


Equivalence of categories preserves subobject classifiers.

Question: This is part of Exercise I.4 of "Sheaves in Geometry and Logic [. . .]" by Mac Lane and Moerdijk.
The Question:

Exercise: Let $F: \mathbf{A}\to \mathbf{B}$ be an equivalence of categories. Prove that a subobject classifier for $\mathbf{A}$ yields one for $\mathbf{B}$.

The Details:
Here equivalence of categories is defined as follows.

Definition: A functor $F:  \mathbf{A}\to \mathbf{B}$ is an equivalence of categories if for any $\mathbf{A}$-objects $A, A'$, we have that
$$\begin{align}
{\rm Hom}_{\mathbf{A}}(A, A')&\to{\rm Hom}_{\mathbf{B}}(FA, FA')\\
p&\mapsto F(p)
\end{align}$$
is a bijection and, moreover, any object of $\mathbf{B}$ is isomorphic to an object in the image of $F$.

A definition of a subobject classifier is given on page 32, ibid.

Definition: In a category $\mathbf{C}$ with finite limits, a subobject classifier is a monic, ${\rm true}:1\to\Omega$, such that to every monic $S\rightarrowtail X$ in $\mathbf{C}$ there is a unique arrow $\phi$ which, with the given monic, forms a pullback square
$$\begin{array}{ccc}
S & \to & 1 \\
\downarrow & \, & \downarrow {\rm true}\\
X & \stackrel{\dashrightarrow}{\phi} & \Omega.
\end{array}$$

My Attempt:
Let $F:  \mathbf{A}\to \mathbf{B}$ be an equivalence of categories. Suppose ${\rm true}_{\mathbf{A}}:1_{\mathbf{A}}\to\Omega_{\mathbf{A}}$ is a subobject classifier of $\mathbf{A}$. Then there exists a functor $G:\mathbf{B}\to \mathbf{A}$ such that there are natural transformations $\alpha: F\circ G\stackrel{\sim}{\to}{\rm id}_{\mathbf{B}}$ and $\beta: G\circ F\stackrel{\sim}{\to}{\rm id}_{\mathbf{A}}$.

Showing $F$ of a terminal object is a terminal object . . .
Consider $Y\in{\rm Ob}(\mathbf{B})$ and $F(1_{\mathbf{A}})$. We have some $Y_{\mathbf{A}}\in{\rm Ob}(\mathbf{A})$ such that $F(Y_{\mathbf{A}})=Y$ (I'm not sure how to justify that) and
$$\begin{align}
{\rm Hom}_{\mathbf{A}}(Y_{\mathbf{A}}, 1_{\mathbf{A}})&\to{\rm Hom}_{\mathbf{B}}(Y, F(1_{\mathbf{A}}))\\
p&\mapsto F(p)
\end{align}$$
is a bijection. But $\lvert {\rm Hom}_{\mathbf{A}}(Y_{\mathbf{A}}, 1_{\mathbf{A}})\rvert=1$ as $1_{\mathbf{A}}$ is terminal. Hence $\lvert {\rm Hom}_{\mathbf{B}}(Y, F(1_{\mathbf{A}})\rvert=1.$ But $Y$ was arbitrary. Thus $F(1_{\mathbf{A}})$ is terminal in $\mathbf{B}$.

Showing $F$ of a monic is monic . . .
For any $M\stackrel{m}{\rightarrowtail} N$ monic in $\mathbf{A}$, for any $$L\overset{p}{\underset{q}{\rightrightarrows}}M\stackrel{m}{\rightarrowtail} N$$ such that if $m\circ p=m\circ q$, then $p=q$.
So $$[{\rm id}_{\mathbf{A}}(m\circ p)={\rm id}_{\mathbf{A}}(m\circ q)]\Rightarrow {\rm id}_{\mathbf{A}}(p)={\rm id}_{\mathbf{A}}(q);$$
that is,
$$[(G\circ F)(m\circ p)=(G\circ F)(m\circ q)]\Rightarrow (G\circ F)(p)=(G\circ F)(q);$$
then,
$$[F\circ(G\circ F)(m\circ p)=F\circ(G\circ F)(m\circ q)]\Rightarrow F\circ (G\circ F)(p)=F\circ (G\circ F)(q);$$
that is,
$$[(F\circ G)(F(m)\circ F(p))=(F\circ G)(F(m)\circ F(q))]\Rightarrow (F\circ G)(F(p))=(F\circ G)(F(q)).$$
But $F\circ G={\rm id}_{\mathbf{B}}$, so we have
$$[F(m)\circ F(p)=F(m)\circ F(q)]\Rightarrow F(p)=F(q),$$
so $F(M)\stackrel{F(m)}{\rightarrow}F(N)$ is monic in $\mathbf{B}$.

I'm not sure how to continue from here. It seems like the rest is diagram chasing but I want to understand it better than that.
Please help :)
Comment: Consider using the functorial description of subobject classifiers instead: An object $X$ is a subobject classifier of ${\mathscr C}$ if it comes with an isomorphism of functors ${\mathscr C}^{\text{op}}\to\textsf{Set}$ between $\text{Hom}_{\mathscr C}(-,X)$ and $\text{SubObj}_{\mathscr C}(-)$. Now check that if you have an equivalence ${\mathbb F}: {\mathscr C}\cong {\mathscr D}$, knowing such an isomorphism of functors for $X$ yields one for ${\mathbb F}(X)$, too.
Comment: I also want to point out that your attempt lacks at least one step : to prove that something is a subobject classifier, you have to prove that for all mono in $B$ there is a condition to be satisfied. You started with a mono in $A$, and showed that its image is a mono in $B$. Although it is true, you also have to show that all monos in $B$ are obtained in that way, up to composition with an iso. But this is because F is an equivalence of categories
Answer: Since you've asked for an answer using only the concepts in the question, I'll do my best to give such a proof. However, before I do, I want to say that Hanno's suggestion in the comments is definitely the best way to prove this.
Also your proofs have some issues. I won't point out all the differences, because this answer will be long enough as is, but please take note of them.

If $F:C\to D$ is an equivalence of categories, $\alpha : 1\to \Omega\in C$ is a subobject classifier of $C$, then $F\alpha : F1\to F\Omega$ is a subobject classifier of $D$.

Proof:
As you've noted, we should prove that $F1$ is a terminal object of $D$, and that $F\alpha$ remains a monomorphism.
$F1$ is terminal:
Let $X\in D$, since $F$ is essentially surjective, there exists $A\in C$ such that $FA\cong X$. Then $$D(X,F1)\cong D(FA,F1)\cong C(A,1)\cong \{*\}.$$ Thus $F1$ is terminal in $D$, since all hom sets $D(X,F1)$ are one element sets.
$F$ preserves (and reflects) monomorphisms: Let's rephrase the property of being a monomorphism.
$i:X\to Y$ is a monomorphism in a category $C$ if for all objects $Z\in C$, $g,h:Z\to X$, $ig=ih \implies g=h$. In other words, the map $i_* : C(Z,X)\to C(Z,Y)$ is injective for all objects $Z\in C$.
Now suppose $i:X\to Y$ is a monomorphism in $C$, so $i_*:C(Z,X)\to C(Z,Y)$ is injective.
Then we have the diagram
$$\require{AMScd}
\begin{CD}
C(Z,X) @>i\circ ->> C(Z,Y)\\
@V\simeq VFV @V\simeq VFV \\
D(FZ,FX) @>Fi\circ - >> D(FZ,FY), \\
\end{CD}
$$
so $Fi_*$ is injective a map from $D(FZ,FX)$ to $D(FZ,FY)$ for all $Z\in C$. This is not quite what we want though, but it's good enough. For any object $A\in D$, we can find $Z\in C$ such that $\phi : A\xrightarrow{\cong} FZ$. Then the composite
$$D(A,FX)\newcommand\toby\xrightarrow \toby{-\circ \phi^{-1}} D(FZ,FX) \overset{Fi\circ}{\hookrightarrow} D(FZ, FY) \toby{-\circ\phi} D(A,FY)$$
is injective, and reduces to just the map $f\mapsto Fi\circ f \circ \phi^{-1}\circ \phi = Fi\circ f$. Thus $Fi$ is a monomorphism in $D$.
In particular, $F\alpha : F1\to F\Omega$ is a monomorphism.
Note also that if $Fi$ is a monomorphism in $D$, then by the commutative square above, we see that $i$ must have been a monomorphism in $C$.
$F\alpha : F1\to F\Omega$ is a subobject classifier:
Let $i : A\to X$ be a monomorphism in $D$. Choose $B,Y\in C$ such that
$A\cong FB$ and $X\cong FY$. Let $J : FB\to FY$ be the conjugate monomorphism of $i$.
Fixing these isomorphisms, then there is a unique morphism $\varphi : X\to F\Omega$
making
$$
\begin{CD}
A @>>> F1 \\
@VVi V @VV F\alpha V\\
X @>\varphi>> F\Omega \\
\end{CD}
$$
a pullback square if and only if there is a unique morphism $\Phi : FY\to F\Omega$
making
$$
\begin{CD}
FB @>>> F1 \\
@VVJ V @VV F\alpha V\\
FY @>\Phi>> F\Omega \\
\end{CD}
$$
a pullback square.
Thus it suffices to prove that there is such a unique morphism $\Phi$.
Now since $F:C(B,Y)\to D(FB,FY)$ is a bijection, there is some morphism $j:B\to Y$ such that $J=Fj$. By the note in the previous section, $j$ is a monomorphism.
Thus since $\alpha$ is a subobject classifier in $C$, we have a unique morphism $\psi:Y\to \Omega$ such that the following diagram is a pullback square:
$$
\begin{CD}
B @>>> 1 \\
@VVj V @VV \alpha V\\
Y @>\psi>> \Omega. \\
\end{CD}
$$
It just remains to prove that $\Phi = F\psi$ has the desired property.
Certainly the square commutes, and if $\Phi$ were a morphism making the square commute, then since $F$ induces a bijection on hom sets, we could find a map $\psi$ such that $F\psi=\Phi$ making the corresponding square in $C$ commute. Thus it suffices to prove that
$$
\begin{CD}
B @>>> 1 \\
@VVj V @VV \alpha V\\
Y @>\psi>> \Omega \\
\end{CD}
$$
is a pullback square if and only if
$$
\begin{CD}
FB @>>> F1 \\
@VVFj V @VV F\alpha V\\
FY @>F\psi >> F\Omega \\
\end{CD}
$$
is a pullback square.
This is the same idea as before when we were proving $F1$ was terminal, or that $Fi$ is a monomorphism if and only if $i$ is a monomorphism. In fact, the general fact is that if $F$ is an equivalence of categories, then it both preserves and reflects all limits and colimits. I'll prove that $F$ preserves and reflects all limits, since the general language of cones to a diagram is more convenient than talking about pullbacks specifically.
$F$ preserves and reflects all limits:

Lemma: Let $I:A\to C$ be a diagram in $C$. Let $F:C\to D$ be an equivalence of categories. Let $(X,\newcommand\set[1]{\left\{{#1}\right\}}\set{f_a})$
  be a cone to $I$. $(X,\set{f_a})$ is a limit cone if and only if $(FX,\set{Ff_a})$ is a limit cone to $FI$.

Proof
First suppose $(FX,\set{Ff_a})$ is a limit cone. Then given a cone
$(Y,\set{g_a})$ to $I$, the cone $(FY,\set{Fg_a})$ induces a unique map
$\alpha_0 : FY\to FX$ such that $Ff_a \circ \alpha_0 = Fg_a$.
Let $\alpha : Y\to X$ be the corresponding map, so that $F\alpha = F\alpha_0$.
Then we have that $f_a \circ \alpha = g_a$, and $\alpha$ is unique, since
if $\tilde{\alpha}$ also had this property, then $F\tilde{\alpha} : FY\to FX$ would
satisfy the same property as $\alpha_0$. So by uniqueness, $F\tilde{\alpha} = \alpha_0= F\alpha$. Hence $\tilde{\alpha}=\alpha$. Thus $(X,\set{f_a})$ is a limit cone.
Therefore $F$ reflects limits.
Now suppose $(X,\set{f_a})$ were a limit cone. If $(Z,\set{G_a})$ is a cone to $FI$ in $D$,
then choose $Y\in C$ with $Z\cong FY$. Then we have a corresponding cone
$(FY,\set{G_a'})$. As usual, we can now reflect the morphisms into $C$ to
get $g_a : Y\to Ia$ such that $(Y,\set{g_a})$ is a cone to $I$ in $C$.
Then the unique morphism $Y\to X$ induced by this cone becomes
a unique morphism $FY\to FX$, and thus a unique morphism $Z\to FX$. Thus $(FX,\set{Ff_a})$ is a limit cone in $D$.
This completes the proof of both the lemma, and the original claim. $\blacksquare$
Comment: @Shaun no worries about leaving the bounty open. Glad to hear the answer was helpful :)
Comment: @Shaun Yep, that was a typo, thanks for catching it.
Comment: Thank you! The bounty is as good as yours right now. Your answer is very clear & helpful. I'll leave the bounty open for a while in case there's another answer on its way. I hope you don't mind :)
Comment: I've inserted an $F$ to make $\varphi $ consistent with the commutative square it's in. Is the edit correct? I'm not sure.
Comment: Why is $D(FA,F1)$ isomorphic to $C(A,1)$?
Comment: @Bob $F$ is an equivalence of categories, so it's fully faithful, meaning that it's bijective on hom sets.


limits at infinity

Question: (a) ♦Write down the precise definitions of
(i) lim f(x) = L, (ii) lim f(x) = ∞. where this two is x approaching ∞
(b) ♦Use the precise definition to show that lim x/(2x+1) = 1, this is also x approaching ∞
i write out the definition of limit at infinity. where M is a number such that f(x) greater than M. but i dont know how to do because all involves algebra instead of numbers. how do i continue or start? thanks.
Comment: in b, we have limit equal to 1/2, not 1
Comment: Also there is not such a thing like limit $L =  ∞$, limit must be real number, if it exist. In  ∞ case, limit don't exists, $f$ grows without bound.
Comment: @Salihcyilmaz The limit does not have to be a real number.  When one writes $\lim f=\infty$ it means that given any number, however large, we can find a point in the domain such that $f$ exceeds that number.
Comment: sorry sorry the first question is approaching negative infinity
Comment: for part I is negative infinity but part ii still is approaching infinity
Comment: Are you sure it's $\frac x{2x+1}$? That's equal to $\frac12-\frac1{4x+2}$, as you can check, so it goes to $\frac12$.
Comment: umm they already clarified in the first comment. thanks
Answer: Definition:  The limit $\lim_{x\to \infty}f(x)=L$ if and only if for any $\epsilon>0$, there exists a number $B>0$, such that $|f(x)-L|<\epsilon$ whenever $x>B$.

APPLICATION:
Claim:  $\lim_{x\to \infty}\frac{x}{2x+1}=\frac12$.
Proof:  Let $\epsilon>0$ be given.  Then, for $x\ge1/2$
\begin{align}
\left|\frac{x}{2x+1}-\frac12\right|&=\left|\frac{1}{2(2x+1)}\right|\\\\
&\le\frac{1}{8x}\\\\
&<\epsilon
\end{align}
whenever $x>B=\max\left(\frac12,\frac{8}{\epsilon}\right)$.  And we are done.
Comment: Interesting, I've always seen $N$ instead of $B$. (Not that it makes the slightest bit of difference.)
Comment: Please let me know how I can improve my answer.  I really want to give you the best answer I can.

limits at infinity


ghc-mod expecting MonadBaseControl to have `StM` associated newtype instead of `StT` associated type

Question: I'm getting this error from installing the latest ghc-mod (188.8.131.52) from Hackage in a sandbox:
[15 of 38] Compiling Language.Haskell.GhcMod.CabalConfig ( Language/Haskell/GhcMod/CabalConfig.hs, dist/dist-sandbox-94286619/build/Language/Haskell/GhcMod/CabalConfig.o )
[16 of 38] Compiling Language.Haskell.GhcMod.CabalApi ( Language/Haskell/GhcMod/CabalApi.hs, dist/dist-sandbox-94286619/build/Language/Haskell/GhcMod/CabalApi.o )
[17 of 38] Compiling Language.Haskell.GhcMod.Cradle ( Language/Haskell/GhcMod/Cradle.hs, dist/dist-sandbox-94286619/build/Language/Haskell/GhcMod/Cradle.o )
[18 of 38] Compiling Language.Haskell.GhcMod.Monad ( Language/Haskell/GhcMod/Monad.hs, dist/dist-sandbox-94286619/build/Language/Haskell/GhcMod/Monad.o )

Language/Haskell/GhcMod/Monad.hs:370:5:
    Wrong category of family instance; declaration was for a type synonym
    In the newtype instance declaration for 'StM'
    In the instance declaration for 'MonadBaseControl IO (GhcModT m)'
cabal: Error: some packages failed to install:
ghc-mod-188.8.131.52 failed during the building phase. The exception was:
ExitFailure 1

I've never seen this error before, so I went digging. In Language/Haskell/GhcMod/Monad.hs, sure enough it's doing something funny:
instance (MonadBaseControl IO m) => MonadBaseControl IO (GhcModT m) where
    newtype StM (GhcModT m) a = StGhcMod {
          unStGhcMod :: StM (StateT GhcModState
                              (ErrorT GhcModError
                                (JournalT GhcModLog
                                  (ReaderT GhcModEnv m) ) ) ) a }
    liftBaseWith f = GhcModT . liftBaseWith $ \runInBase ->
        f $ liftM StGhcMod . runInBase . unGhcModT

If you look at monad-control on Hackage, there is no such StM associated newtype, but only an StT associated type.
Unless there's some other type trickery going on here, I'm stumped. How would this be fixed? Thank you.
Answer: Scratch this, my eyes are fooling me. My mistake, since monad-control-1.x, MonadControl has had an associated type instead of an associated data type, as explained here.
Comment: Ah. Figured it out. I ran `cabal install ghc-mod --constraint='monad-control < 18.104.22.168'` and it worked.
Comment: Is there a way to fix or work around this? I'm just getting started with Haskell and can't install ghc-mod because of this. What can I do?


Proving congruence class

Question:
Let $a$ and $m$ be integers such that $m ≥ 1$. Consider the congruence
  class of $a$, $[a]$ modulo $m$. It follows that $∀ x ∈ [a], \gcd(x, m) = \gcd(a, m)$.

I have my algebra midterm in two days! In my lecturer's note, it was stated the above statement and I have no idea why is it true? I asked my lecturer, but he didn't want to answer, instead asked me to prove it. I have no idea where to start. Any help would be highly appreciated.
Comment: Which particular congruence class of $a$?
Comment: I believe it is $[a]$ modulo $m$. Edited the post.
Answer: If $x \in [a]_m$ then you have $x=a+km$ for some $k$ (or $a = x-km$)
Then if $d \mid a$ and $ d \mid m$, you must have $d \mid x$.
Similarly, if $d \mid x$ and $ d \mid m$, you must have $d \mid a$.
Hence the set of divisors of the pair $a,m$ is the same as the set of divisors of $x,m$ hence the greatest divisors must be the same.
Note: The essential result here is that if you have $c = ax + by$ and you also have $d \mid a$ and $d \mid b$, then you must have $d \mid c$. This follows by writing $a=a_1 d, b=b_1 d$ hence $c = (a_1x+b_1y) d$.

Proving congruence class


Express inequlities in spherical coordinates

Question: The problem is following: Assume that we have a area, lets call it $K$ that is limited by a cone $z=-\sqrt{x^2+y^2}$ and by a sphere $x^2+y^2+z^2 = 16$
Now, in this problem they want me to describe the area K using inequlities. More specifically in spherical coordinates
My attempt:
Spherical coordinates are given by:
$\left\{x = r \sin\theta \cos\phi \\y=r \sin\theta \sin\phi \\z=r \cos\theta\right\}$
where $0 \leq \theta \leq \pi, \space 0\leq \phi \leq 2\pi$
So this gives us: $x^2+y^2 = r^2 \sin\theta$
After that I'm basically a bit lost, the only restriction we have, for the variables $x$, $y$ and $z$ are that they range between $\pm4$.
Answer: Do you mean $K$ is a volume, that is, the three dimensional solid that is bordered by the cone and sphere?  It sounds like it.
You lost a square of the $\sin$ in your expression for $x^2+y^2$.  It equals $r^2\sin^2 \theta$.  Can you do a similar calculation of $x^2+y^2+z^2$?
Then you need to decide which side of the cone and sphere form the region of interest.  This will be shown by changing the equal signs into inequalities.  For example, you probably want the interior of the sphere.  In Cartesian coordinates, this would be $x^2+y^2+z^2 \le 16$ (or $x^2+y^2+z^2 \lt 16$ if you want an open ball).  Similarly, for the cone, you probably want the volume around the negative $z$ axis, so you want $z \le -\sqrt{x^2+y^2}$.  If you substitute your conversions to spherical coordinates into these you are home.


Equal distance grouped bar chart irrespective of scale - chart.js

Question: I have a requirement that need to show up data in bar graph using chart.js like below,

Here, irrespective of x-axis date, the bars should be aligned in equal distance and the date format is same as in the image.
let chartStatus = Chart.getChart(this.WEIGHTS_CHART);
if (chartStatus != undefined) {
  chartStatus!.destroy();
}

const weightsChart = new Chart(this.WEIGHTS_CHART, {
  type: 'bar',
  data: {
    labels: this.objWeights.map(x => x.date),
    datasets: [
      {
        label: "Weight",
        backgroundColor: "#0072bc",
        data: this.objWeights.map(x => x.weightValue)
      },
      {
        label: "BMI",
        backgroundColor: "#84b5e4",
        data: this.objWeights.map(x => x.bmi)
      }
    ]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        type: 'time',
        time: {
          unit: 'day',
          displayFormats: {
            day: 'MMM DD, YYYY'
          }
        }
      },
      y: {
        beginAtZero: true
      }
    }
  }
});
}

with the above code, I'm getting output like this . Can someone help me
I want like this
(https://i.stack.imgur.com/5Aiwj.png)
but with above code, I'm getting like this
(https://i.stack.imgur.com/GkMGO.png)
Answer: Make your x-axis of type: 'timeseries' instead of type: 'time'.

Time Series Axis: The time series scale extends from the time scale and supports all the same options. However, for the time series scale, each data point is spread equidistant.

scales: {
  x: {
    type: 'timeseries',
    time: {
      ...


Como inserir em um memo no lazarus o cabeçalho da NFe e/ou todos produtos de um xml?

Question: Consigo inserir o xml de uma nfe com o código abaixo, mas gostaria de inserir apenas o comprador, ou só os produtos, ou só o fornecedor...
Código testado no lazarus no windows 10.
procedure TForm1.Button6Click(Sender: TObject);
var
  DOC:TXMLDocument;
  i, j: Integer;
  OrderChilds, properties_Node: TDOMNode;
  propChildList: TDOMNodeList;
begin
  ReadXMLFile(Doc, 'C:pastaXML\arquivo.xml');
memo2.Clear;
  for i := 0 to DOC.ChildNodes[0].ChildNodes.Count - 1 do
  begin
    OrderChilds := DOC.ChildNodes[0].ChildNodes[i];
    if OrderChilds.NodeName = 'NFe' then
    begin
      properties_Node := OrderChilds.ChildNodes[0];
      if Assigned(properties_Node) then begin
        propChildList := properties_Node.ChildNodes;
        for j := 0 to propChildList.Count - 1 do begin
          Memo2.Lines.Add(propChildList[j].TextContent);

        end;
      end;
    end;
  end;
end;

Comment: Seja benvindo ao StackOverflow em português! Experimentou fazer a solução após a leitura dos dados?
Comment: Sim, acabei eu mesmo achando a solução. vou postar
Answer: Analisando o código anterior com mais atenção eu mesmo consegui resolver. Lembrado que pra retornar o próximo dado do produto é só aumentar o número do GetChildNodes.Item[2].TextContent
var xDoc: TXMLDocument;
nodedet, nodeInfNfe : TDOMNode;
   i:integer;

begin
    memo3.Clear;
  ReadXMLFile(xDoc, 'c:\pastaDoNFe\nfe.xml');
  nodeInfNfe:=xdoc.ChildNodes[0].ChildNodes[0].ChildNodes[0];
  for i:= 0 to nodeInfNfe.ChildNodes.Count - 1 do
 begin
   if nodeInfNfe.ChildNodes[i].NodeName = 'det' then
   begin
        nodedet:= nodeInfNfe.ChildNodes[i];
        //retorna o primeiro item dos produtos campo cProd
        memo3.Lines.add(nodedet.FindNode('prod').GetChildNodes.Item[0].TextContent

        //retorna o segundo item dos produtos campo cEAN
        +'= '+ nodedet.FindNode('prod').GetChildNodes.Item[1].TextContent

                //retorna o terceiro item dos produtos campo xProd
        +'= '+ nodedet.FindNode('prod').GetChildNodes.Item[2].TextContent);