Set TabBar Item badge count with SwiftUI

Question: Is it possible to show TabItem badge with SwiftUI?
It is easy to achieve with UIKit like described here ->
How to set badge value in Tab bar?
I didn't find a way to do this with a SwiftUI.
The only possible way is to access to UITabBarController using scene rootViewController and modify its tab bar items directly.
  func setBadgeCount(_ count: Int) {
    UIApplication.shared.applicationIconBadgeNumber = count

    guard let delegate = app.connectedScenes.first?.delegate as? SceneDelegate else {
        return
    }

    if let tabBarController = delegate.window?.rootViewController?.children.first {
      tabBarController.viewControllers?.first?.tabBarItem.badgeValue = "\(count)"
    }
  }

Any ideas how to do this with native SwiftUI approach?
Comment: SwiftUI 3 (requiring iOS 15) now has a `.badge` modifier. [See this answer for an example.](https://stackoverflow.com/a/67894115/77567)
Answer: Currently, SwiftUI don't have badge feature so we must custom.
Reference HERE I create My tabar with badge
struct ContentView: View {
    private var badgePosition: CGFloat = 2
    private var tabsCount: CGFloat = 2
    @State var selectedView = 0
    var body: some View {
        GeometryReader { geometry in
            ZStack(alignment: .bottomLeading) {
                TabView {
                    Text("First View")
                        .tabItem {
                            Image(systemName: "list.dash")
                            Text("First")
                        }.tag(0)
                    Text("Second View")
                        .tabItem {
                            Image(systemName: "star")
                            Text("Second")
                        }.tag(1)
                }

                ZStack {
                  Circle()
                    .foregroundColor(.red)

                    Text("3")
                    .foregroundColor(.white)
                    .font(Font.system(size: 12))
                }
                .frame(width: 15, height: 15)
                .offset(x: ( ( 2 * self.badgePosition) - 0.95 ) * ( geometry.size.width / ( 2 * self.tabsCount ) ) + 2, y: -30)
                .opacity(1.0)
            }
        }
    }
}

Comment: If you are compiling for both iPad and iPhone you can replace 0.95 in offset with `(UIDevice.current.userInterfaceIdiom == .phone ? 0.95 : 1.65)`
Comment: Thank you for the solution you provided! It is a pity Apple didn't add support for tab bar item badges support to SwiftUI.
Comment: It's common feature, I think SwiftUI will support it, maybe in some next version
Answer: Now in SwiftUI 3 they added a .badge() modifier
Source: HackingWithSwift
TabView {
    Text("Your home screen here")
        .tabItem {
            Label("Home", systemImage: "house")
        }
        .badge(5)
}

Comment: This only works starting from iOS 15
Answer:  func calculateBadgeXPos(width: CGFloat) -> CGFloat {
        let t = (2*CGFloat(self.selectedTab))+1
        return CGFloat(t * width/(2*CGFloat(TABS_COUNT)))
    }

then use it here:
GeometryReader { geometry in
            ZStack(alignment: .bottomLeading) {
                // make sure to update TABS_COUNT
                TabView(selection: self.$selectedTab) {
                   ...
                }

                NotificationBadge(...)
                .offset(x: self.calculateBadgeXPos(width: geometry.size.width), y: -28)
            }
        }

Looks sth like this on Preview
Answer: The above mentioned .introspectTabBarController modifier worked for me.
Gave a nice native badge on tabItem. Looks great on both orientations.
    .introspectTabBarController { (UITabBarController) in
        self.tabBarControl = UITabBarController
        if let items = UITabBarController.tabBar.items {
            let tabItem = items[2] // in my case it was 3rd item
            tabItem.badgeValue = "5" // hardcoded
        }
    }

Though, when changing tabs, the badge disappears so I saved UITabBarController in @State and when tab changes I set tabItem.badgeValue again.
P.S: iOS 15+ supports .badge modifier. Use it if you're targeting above or iOS 15.
Answer: iOS 15 added support for .badge modifier, but as I need to support iOS 14, I've created UITabBarController wrapper:
struct TabBarController<TabContent: View, Tab: Hashable>: UIViewControllerRepresentable {
    let tabs: [Tab]
    @Binding
    var selection: Tab
    let tabBarItem: (Tab) -> UITabBarItem
    let badgeValue: (Tab) -> String?
    @ViewBuilder
    let contentView: (Tab) -> TabContent

    func makeUIViewController(context: Context) -> UITabBarController {
        let controller = UITabBarController()
        controller.delegate = context.coordinator
        return controller
    }

    func updateUIViewController(_ uiViewController: UITabBarController, context: Context) {
        context.coordinator.viewControllers
            .keys
            .filterNot(tabs.contains(_:))
            .forEach { removedKey in
                context.coordinator.viewControllers.removeValue(forKey: removedKey)
            }
        uiViewController.viewControllers = tabs.map { tab in
            let rootView = contentView(tab)
            let viewController = context.coordinator.viewControllers[tab] ?? {
                let viewController = UIHostingController(rootView: rootView)
                viewController.tabBarItem = tabBarItem(tab)
                context.coordinator.viewControllers[tab] = viewController
                return viewController
            }()
            viewController.rootView = rootView
            viewController.tabBarItem.badgeValue = badgeValue(tab)
            return viewController
        }
        uiViewController.selectedIndex = tabs.firstIndex(of: selection) ?? 0
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(selection: $selection)
    }

    final class Coordinator: NSObject, UITabBarControllerDelegate {
        @Binding
        private var selection: Tab
        var viewControllers = [Tab: UIHostingController<TabContent>]()

        init(selection: Binding<Tab>) {
            _selection = selection
        }

        func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
            guard let newTab = viewControllers.first(where: { $0.value == viewController })?.key else {
                print("tabBarController:didSelect: unexpected")
                return
            }
            selection = newTab
        }
    }
}

filterNot:
extension Collection {
    @inlinable public func filterNot(_ isNotIncluded: (Element) throws -> Bool) rethrows -> [Element] {
        try filter { try !isNotIncluded($0) }
    }
}

Usage:
TabBarController(
    tabs: [1,2,3],
    selection: $selection,
    tabBarItem: { tab in
        UITabBarItem(title: "tab \(tab)", image: UIImage(systemName: "1.square.fill"), tag: 0)
    },
    badgeValue: { tab in
        "\(tab)"
    },
    contentView: { tab in
        Text("\(tab) screen")
    }
).ignoresSafeArea()

Comment: @AlexanderKhitev ah yes, I've added it to my answer - I think `filterNot` makes code more readable, but you can replace it with `filter` too
Comment: hey Phil! Could you please tell what is `filterNot`? Do you use a custom function there?
Answer: struct ContentView: View {
var body: some View {
    TabView {
        Text("Home")
            .tabItem {
                Text("Home")
            }

        Text("Home")
            .tabItem {
                Text("Home")
            }

        Text("Home")
            .tabItem {
                Text("Home")
            }
    }
    .introspectTabBarController { (tabbarController) in
        if let items = tabbarController.tabBar.items {
            let tabItem = items[2]
            tabItem.badgeValue = "1"
        }
    }
}

}


Pra que serve a tag ?

Question: Estava pesquisando algumas informações e vi que existe uma tag chamada <canvas> em HTML5.

O que faz a tag canvas?
Ela só serve para fazer formas geométricas?
Se for possível e viável, poderiam dar um exemplo?

Nessa outra pergunta, o AP fala sobre o mesmo elemento <canvas> ou não tem nada a ver com o do HTML5?
Comment: A tag  é como se fosse um quadro em branco, esperando para ser pintado com um poderoso pincel chamado Javascript. :)  Na verdade, é muito mais do que isso, com a tag  você consegue renderizar imagens, desenhar elementos complexos e criar animações.
Comment: Não serve só para fazer desenhos. Animações também, inclusive jogos. Vou ver se acho um exemplo bom e simples o bastante e se conseguir, posto uma resposta.
Comment: É o tipo de pergunta que já estou ansioso pra ver a resposta +1
Comment: http://www.linhadecodigo.com.br/artigo/3488/entendendo-a-tag-canvas-no-html-5.aspx
Answer: O elemento canvas permite o desenvolvedor criar imagens via código. Tratando-se de uma página Web, controla-se o canvas com JavaScript. Não é limitado à formas geométricas, você pode inserir imagens, textos, vetores e controlar tudo com uma linguagem de programação. Ou seja, você pode criar animações, interações, vídeos e jogos. Varia conforme a necessidade e criatividade.
A sintaxe do elemento é simples:
<canvas>
  Fallback text for non-supported browsers
</canvas>

Isto é, se o navegador não possuir suporte, o texto interno será exibido na página. Por padrão, se suportado, o conteúdo do elemento é ignorado pelo navegador.
Sua configuração padrão de exibição é display: block e é suportado pela grande maioria dos navegadores. Veja no Can I Use.
Tutorial de como utilizar o elemento canvas.
A recomendação W3C do elemento pode ser encontrada aqui: https://www.w3.org/TR/2011/WD-html5-20110525/the-canvas-element.html
Exemplo de prancheta de desenho com Canvas:

function init() {
  var ctx = document.getElementById("canvas").getContext('2d');
  ctx.canvas.width = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  var pinta = false;
  var red = green = blue = 127;
  var rf = 1,
    gf = 1,
    bf = 1;
  var rm = getAleatorio();
  var gm = getAleatorio();
  var bm = getAleatorio();

  function desenha(e) {
    var pos = getPosMouse(canvas, e);
    posx = pos.x;
    posy = pos.y;
    if (pinta) {
      ctx.fillStyle = "rgb(" + red + ", " + green + ", " + blue + ")";
      ctx.fillRect(posx - 4, posy - 4, 8, 8);
    }
  }

  canvas.onmousemove = function(e) {
    desenha(e);
    red += rm * rf;
    green += gm * gf;
    blue += bm * bf;

    if (red >= 255 || red <= 0) {
      rf *= -1;
      rm = getAleatorio();
    }
    if (green >= 255 || green <= 0) {
      gf *= -1;
      gm = getAleatorio();
    }
    if (blue >= 255 || blue <= 0) {
      bf *= -1;
      bm = getAleatorio();
    }

  };

  document.getElementById("canvas").onmousedown = function() {
    pinta = true;
  };

  document.getElementById("canvas").onmouseup = function() {
    pinta = false;
  }

  function getPosMouse(canvas, evt) {
    var rect = canvas.getBoundingClientRect();
    return {
      x: evt.clientX - rect.left,
      y: evt.clientY - rect.top
    };
  }

  function getAleatorio() {
    return Math.floor((Math.random() * 5) + 1);
  }
}

init();
.centralizado {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

  <canvas class="centralizado" id="canvas">your browser is nope!</canvas>

Fonte: É possível salvar o canvas como imagem, e enviar ao servidor?

Exemplo de conversão de texto para imagem com Canvas:

var canvas = document.getElementById("receipt");
var context = canvas.getContext("2d");

const messages = [
  "################################",
  "Central Jogos",
  "################################",
  "Apostador: test",
  "Valor apostado: R$ 5,00",
  "Valor de retorno: R$ 6,15",
  "Data da aposta: 19/02/2017 15:07",
  "Quantidade de jogos: 1",
  "--------------------------------",
  "Vasco X Flamengo",
  "Empate: 1.23",
  "10/03/2017 15:30",
  "================================",
  "Cambista: Cambista Teste",
  "Telefone: (82) 9977-8877"
];

context.font = "12px Courier new";

y = 12;
for (var i in messages) {
  context.fillText(messages[i], 0, y);
  y += 18;
}

document.getElementById("result").src = context.canvas.toDataURL();
h1 {
  font-size: 16px
}

div {
  float: left;
  padding: 20px;
}

Canvas:

  <canvas id="receipt" width="230" height="270"></canvas>

Resultado:

Fonte: Transformar texto de uma string em imagem

Exemplo de animação criado com Canvas e jQuery

var c = document.createElement("canvas"),
  $ = c.getContext("2d");

var w = window.innerWidth,
  h = window.innerHeight;

c.width = w;
c.height = h;

c.addEventListener("mousedown", mouseDown, true);

document.body.appendChild(c);

var part;  //particle
var meshW = 100;  //mesh width
var dispX = -50;  //x disposition
var dispY = -100;  //y disposition
var partX = 0;  //particle x
var partY = 0;  //particle y
var partIndX = 0;  //particle index x
var partIndY = 0;  //particle index y

var col0 = "rgb(74, 1, ";  //shading color-starts
var col1 = "rgb(0, 3, ";

var partList = [];  //particle array
var gridW = w + meshW;   //grid width
var gridH = h + meshW * 2;  //grid height

while(partY < gridH)
{
 while(partX < gridW)
 {
  part = new Object(partX, partY, partIndX, partIndY);
  partList.push(part);

  partX += meshW;
  partIndX++;
 }

 partX = 0;
 partIndX = 0;
 partY += meshW;
 partIndY++;
}

var partArrayL= partList.length;
var rowCt = Math.ceil( gridW / meshW );  //row count
var colCt = Math.ceil( gridH / meshW );  //column count

$.clearRect(0, 0, w, h);

for(var i = 0; i < partArrayL; ++i)
{
 part = partList[i];
 part.next = partList[i + 1];

 if(part.indX % rowCt != rowCt - 1 && part.indY != colCt - 1)
 {
  part.connectAll.push(partList[i + 1]);
  part.connectAll.push(partList[i + rowCt + 1]);
  part.connectAll.push(partList[i + rowCt]);
  part.ready();
 }
}

var int = setInterval(intHandler, 1000 / 30);

function mouseDown()
{
 if(int != undefined)
 {
  clearInterval(int);
  int = undefined;
 }
 else
 {
  int = setInterval(intHandler, 1000 / 30);
 }
}

part = partList[0];

function intHandler()
{
 $.clearRect(0, 0, w, h);

 while(part != undefined)
 {
  part.draw();
  part = part.next;
 }

 part = partList[0];

 while(part != undefined)
 {
  part.fill();
  part = part.next;
 }

 part = partList[0];
}

function Object(pX, pY, pIndX, pIndY)
{
 this.distort = 50;

 this.x = dispX + pX + ( Math.random() - Math.random() ) * this.distort;
 this.y = dispY + pY + ( Math.random() - Math.random() ) * this.distort;
 this.indX = pIndX;
 this.indY = pIndY;
 this.color = "hsla(261, 55%, 5%, 1)";  //part border color

 this.size = 2;
 this.next = undefined;

 this.tracker = (Math.PI / 2) + this.indX * .5;
 this.diffX = Math.random();
 this.diffY = Math.random();
 this.speed = .1;
 this.vol = 30;  //volume  (higher #, more movement)

 this.colRngDiff = 70;  //shading variation
  //color range > changing the 225 to vals between 0 and 255, as well as the color range difference # above,  will change base color
 this.colRng = (225 - this.colRngDiff) + Math.floor(Math.random() * this.colRngDiff);

 this.draw = function()
 {
  this.tracker += this.speed;
  this.tracker = this.tracker == 1 ? 0 : this.tracker;

  this.x += (Math.sin( this.tracker ) * this.speed) * this.vol;
  this.y += (Math.cos( this.tracker ) * this.speed) * this.vol;

 }

 this.readyW = 0;  //start point
 this.readyW1 = 0;

 this.ready = function()
 {
  this.readyW = Math.abs(this.connectAll[0].x - this.x);
  this.readyW1 = Math.abs(this.connectAll[1].x - this.connectAll[2].x);
 }

 this.connectAll = [];

 this.connect = function()
 {
  if(this.connectAll.length > 0)
  {
   $.beginPath();
   $.strokeStyle = this.color;
   $.moveTo(this.x, this.y);

   for(var j = 0; j < this.connectAll.length; ++j)
    $.lineTo(this.connectAll[j].x, this.connectAll[j].y);

   $.lineTo(this.x, this.y);
   $.lineTo(this.connectAll[1].x, this.connectAll[1].y);
   $.stroke();
  }
 }

 this.calcW = 0;
 this.calcW1 = 0;

 this.fill = function()
 {
  if(this.connectAll.length > 0)
  {
   this.calcW = Math.abs(this.connectAll[0].x - this.x);
   this.calcW1 = Math.abs(this.connectAll[1].x - this.connectAll[2].x);

   $.beginPath();
   $.fillStyle = col0 + (Math.floor((this.readyW / this.calcW) * this.colRng)).toString() + ")";

   $.moveTo(this.x, this.y);
   $.lineTo(this.connectAll[2].x, this.connectAll[2].y);
   $.lineTo(this.connectAll[1].x, this.connectAll[1].y);
   $.lineTo(this.x, this.y);

   $.fill();

   $.beginPath();
   $.fillStyle = col1 + (Math.floor((this.readyW1 / this.calcW1) * this.colRng)).toString() + ")";

   $.moveTo(this.x, this.y);
   $.lineTo(this.connectAll[1].x, this.connectAll[1].y);
   $.lineTo(this.connectAll[0].x, this.connectAll[0].y);
   $.lineTo(this.x, this.y);

   $.fill();
  }
 }

}

Fonte: http://www.html5canvastutorials.com/advanced/canvas-shape-and-color-effects/

Exemplo de 'jogo' criado no Canvas

  var C2D, W, H, RC;
  var fps = 24;
  var mspf = 1000 / fps;
  var updateInterval;
  var quit = false;

  function main() {
    var c = document.getElementById('canvas');
    if (c.getContext) {
      initializeCanvas(c);
      var P = new Player(8);
      var L = new Level();
      RC = new RayCaster(C2D, W, H, 4, L, P, input);
      if (initializeLevel()) {
        trace('map loaded successfully.');
        trace("now casting...");
        trace("  \'a\' - turn left");
        trace("  \'d\' - turn right");
        trace("  \'w\' - step forward");
        trace("  \'s\' - step backward");
        trace("  \'q\' - stop casting");
        updateInterval = window.setInterval("update()", mspf);
      }
      else {
        trace("map failed to load");
      }
    }

    else {
      trace('sorry.. you\'ll need a browser that supports the canvas tag,');
      trace('like Safari or Firefox 1.5+ to see this demo.');
    }
  }

  function initializeCanvas(c) {
      C2D = c.getContext('2d');
      C2D.lineWidth = 1;
      C2D.globalAlpha = 1;
      C2D.globalCompositeOperation = 'source-over';
      W = c.width;
      H = c.height;
      trace('canvas initialized');
  }

  function initializeLevel() {
    var mapCells_x = 16;
    var mapCells_y = 16;
    var M = '' +
      '################' +
      '#  @@@@@       #' +
      '#  @   @ % # % #' +
      '#  @       #   #' +
      '#  @  @@       #' +
      '#    &         #' +
      '#   &   P      #' +
      '#  &      &&   #' +
      '#              #' +
      '#  ##  #@%#@%  #' +
      '#  #        #  #' +
      '#  ###      #  #' +
      '#  #        #  #' +
      '#  ######## #  #' +
      '#              #' +
      '################';

    trace('submitting map...');
    return RC.loadMap(M, mapCells_x, mapCells_y);
  }

  function update() {
    if (input.quit) {
      input.quit = false;
      window.clearInterval(updateInterval);
      trace('raycaster halted.');
    }
    else {
      RC.update();
    }
  }
canvas {
  border: 2px solid #000;
  position: absolute;
  left: 33%;
  margin-left: 10px;
}

<link href="https://mdn.github.io/canvas-raycaster/trace.css" rel="stylesheet"/>

RayCaster v.0.0.1

<canvas id="canvas" width="320" height="240"></canvas>

Fonte: https://mdn.github.io/canvas-raycaster/
Comment: Nossa, muito legal mesmo, adorei o jogo, mesmo que seja simples. A explicação como sempre excelente +1 =) Pena que minha criatividade tá falhando ultimamente
Comment: Eu estava pesquisando por exemplos em canvas, mas depois da sua resposta, desisti de procurar. +1
Comment: Acho interessante destacar que `canvas` tem sua etimologia do tecido usado para se pintar quadros
Comment: Boa resposta! já me foi útil pra converter texto em imagem =]
Answer: A tag  é como se fosse um quadro em branco, esperando para ser pintado com um poderoso pincel chamado Javascript. :)
Na verdade, é muito mais do que isso, com a tag  você consegue renderizar imagens, desenhar elementos complexos e criar animações.
O bom mesmo é a possibilidade de fazer tudo isso sem usar qualquer plugin como Flash Player ou Silverlight, é só HTML e Javascript.
Exemplos

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Seu Navegador não suporta tag canvas</canvas>

    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }

   <canvas id="canvas" width="150" height="150"></canvas>

Mais exemplos
Answer:
Em HTML5 Canvas é focado em desenho/processamento de imagens com
contexto 2D e 3D
Definição por @Gabriel Gartz

Basicamente são formas geométricas mas também é composta por imagens (sprites), o melhor exemplo para isso são os jogos escritos em HTML5. No caso dos jogos, escrito lado a lado com o javascript para a atualização do canvas.
Você imaginar que o canvas é um espaço pronto para desenhar.
Um exemplo fácil são os Doodles do Google, normalmente feitos em HTML5.
Exemplo retirado da Web.
https://codepen.io/sethmcl/pen/duGsh

var canvas = document.querySelector('canvas');
var ctx    = canvas.getContext('2d');

var x = 50;
var y = 50;

function clearScreen() {
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}

function drawSquare(x, y) {
  ctx.fillRect(x, y, 100, 100);
}

function draw() {
  clearScreen();
  drawSquare(x, y);
  x = x + 5;
  setTimeout(draw, 50);
}

draw();
html, body {
  height: 100%;
  margin: 0;
}
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
canvas {
  width: 300px;
  height: 150px;
}
<canvas></canvas>

É fácil de concluir também que esse recurso, o canvas, substituiu o nosso velho Flash. E obviamente por se tratar de uma renderização nativa e não precisar de plugins de terceiros, uma melhora na performance.
Answer: É uma tag HTML5 que permite você possa acessar métodos para criação de formas geométricas, fazer animações, etc.
Por exemplo:

var canvas = document.getElementById("minhaCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, 80, 80);
<canvas id="minhaCanvas"></canvas>

Pra que serve a tag ?


Primefaces , botão requer dois cliques para executar ação

Question: Ao executar o código abaixo, tenho que clicar duas vezes no botão para que a ação de exclusão aconteça vi muitos com problemas parecidos, mas nenhuma solução eficaz:
<h:form id="TablePais"  prependId="false" >

                        <f:setPropertyActionListener
                                value="#{pais}"
                                target="#{beanPais.selectedPais}"
                                />

                <h:outputText value="#{pais.cod}" />

                <h:outputText value="#{pais.nome}" />

    </h:form>

Comment: Eu tive o mesmo problema, o que eu tive que fazer foi colocar um `global="false"` no botão, pois assim ele não deixa o ajaxStatus ativar antes de sua ativação. No meu caso, o ajaxStatus estava atualizando um campo antes de executar o botão.
Answer: Você está utilizando ajax=false juntamente com update, e isso é errado.
Update é para ser utilizado com ajax=true ou nem precisa escrever o atributo ajax.
Comment: Troque o update por 'TablePais'
Comment: tentei das duas formas e o problema persiste
Answer: Boa tarde, poderia tentar utilizar o atributo process="@this" e partialSubmit="true"? caso o problema persista tente apenas para teste utilizar o procedimento conforme abaixo:
Altere seu método de excluir para receber um objeto de pais como parâmetro para realizar a exclusão.

Metodo da classe BeanPais:
public void excluir(SeuObjetoPais pais){
   //... Procedimentos de exclusão levando em conta o parametro enviado.
}


MS ACCESS crashes when filling listbox with ADODB.Recordset

Question: I populate a list box on a user form with the following code:
Dim CONSTRING As String
Dim SQL As String
Dim RSSQL As New ADODB.Recordset

CONSTRING = "xxxxxxxxxx"

SQL = "SELECT [ID], [Name] FROM [Table X] WHERE Name <>'' ORDER BY [Name] ASC;"
RSSQL.Open SQL, CONSTRING, adOpenStatic, adLockBatchOptimistic, adCmdText

Set Forms!Cockpit.LB.Recordset = RSSQL

RSSQL.Close
Set RSSQL = Nothing

This code works perfectly. I can run this code as often as I want, it always populates the listbox with the expected data.
BUT: If I select one item in the Listbox and try the run the code again, it crashes everytime without returning any error code.
Any idea how to solve this? Thanks in advance..
Comment: Unselect the listbox before running this code.
Comment: Hi, does not solve the issue..
Comment: Then something else is going on.
Comment: Where are you pulling data from? Why not set a link and reference the link in LB RowSource?
Comment: I tested this and cannot replicate issue. No crash.
Answer: Try 'RowSource':
Dim SQL As String

SQL = "SELECT [ID], [Name] FROM [Table X] WHERE Name <>'' AND NOT Name IS NULL ORDER BY [Name] ASC;"
Set Forms!Cockpit.LB.RowSourceType = "Table/Query"
Set Forms!Cockpit.LB.RowSource = SQL

Comment: Also you can use ...LB.Requery to refresh the listbox.
Answer: More common for listbox - RowSource property. If you use Recordset property, you should be more careful.
I think, listbox items is bounded to recordset rows. When you change LB.Recordset, previous recordset will be closed and binding "will hang in the air" - this cause memory conflict and app crash.
Remove LB items before changing .Recordset property.
Dim i As Long
For i = Forms!Cockpit.LB.ListCount-1 To 0
   Forms!Cockpit.LB.RemoveItem (i)
Next i

Set Forms!Cockpit.LB.Recordset = RSSQL


How to use existing SQL database in my separate project under one solution in ASP.NET MVC application

Question: I have created 2 separate projects under one solution where one project is a class library. I have created an ADO.NET Entity Model from my existing database into this. Another project is an ASP.NET MVC web app.
I have used Individual User Authentication and wanted to use registration and login facility provided by this.
Now I am unable to use my existing database as this project is creating new database by itself when first runs.
Please guide me how to use existing database. I have given reference to my ASP.NET MVC project. These are my connection strings. Please help me.
<connectionStrings>
    <add name="LAPTOP-71D4QMB6"
         connectionString="Data Source=LAPTOP-71D4QMB6;Initial Catalog=VCAdvertiserDB;Integrated Security=True"
         providerName="System.Data.SqlClient" />
    <add name="HBDBEntities"
         connectionString="metadata=res://*/Data.HBModel.csdl|res://*/Data.HBModel.ssdl|res://*/Data.HBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=LAPTOP-71D4QMB6;initial catalog=VCAdvertiserDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
         providerName="System.Data.EntityClient" />
</connectionStrings>

Error thrown is:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Comment: @marc_s, if you feel that this question is useful to other readers on this site then please up vote this. Thank you
Answer: You have to copy the connection string from the app.config of your class library to the web.config of the MVC project. You need to put it in both the root web.config and also have to put it in the shared web.config under the shared views folder. That last may not be needed but it also doesn't hurt.

That worked for me.
Joey
Comment: It does not work into my solution. In last `web.config` there is one auto generated connection string given when project first created.If I remove that string then it gives me the same error. If not then it will create database inside `App_Data`.But the connection string which I added from `App.config` does not do anything. T
Comment: This is defalut ``
Comment: Can you please guide me here. I am still not getting the solution.
Comment: if you feel that this question is useful to other readers on this site then please up vote this. Thank you!


Which is the fastest STL container for find?

Question: Alright as a preface I have a need to cache a relatively small subset of rarely modified data to avoid querying the database as frequently for performance reasons. This data is heavily used in a read-only sense as it is referenced often by a much larger set of data in other tables.
I've written a class which will have the ability to store basically the entirety of the two tables in question in memory while listening for commit changes in conjunction with a thread safe callback mechanism for updating the cached objects.
My current implementation has two std::vectors one for the elements of each table. The class provides both access to the entirety of each vector as well as convenience methods for searching for a specific element of table data via std::find, std::find_if, etc.
Does anyone know if using std::list, std::set, or std::map over std::vector for searching would be preferable? Most of the time that is what will be requested of these containers after populating once from the database when a new connection is made.
I'm also open to using C++0x features supported by VS2010 or Boost.
Answer: For searching a particular value, with std::set and std::map it takes O(log N) time, while with the other two it takes O(N) time; So, std::set or std::map are probably better. Since you have access to C++0x, you could also use std::unordered_set or std::unordered_map which take constant time on average.
For find_if, there's little difference between them, because it takes an arbitrary predicate and containers cannot optimize arbitrarily, of course.
However if you will be calling find_if frequently with a certain predicate, you can optimize yourself: use a std::map or std::set with a custom comparator or special keys and use find instead.
Comment: For anyone just coming to this question like I am. I needed to do roughly a million+ lookups on a set of roughly 1 million values. Using an unordered_set it took around 7 seconds to preform all the lookups. It took over 30 min (I stopped it after finding this answer) using a vector. This is why I love stackoverflow! Thank you R. Martinho Fernandes!
Comment: Even without C++0x you can look for the unordered containers in TR1, i.e. `#include ` and `std::tr1::unordered_map`. You really have to test, though, because the asymptotics (O(1) vs O(log n)) don't tell you the size of the constant, and n might have to be titanic before the unordered container is more efficient!
Comment: Yes, testing is important! If it isn't a lot of data, the "slower" containers may work better. And when using the unordered ones, the quality of the hash function can also make a difference.
Comment: For almost all cases the vectors combined size will be less than 500 elements. They are separate for organization only. I need to be able to search on a name field as well as an id field thus the predicates and `std::find_if` using lambdas.
Answer: A sorted vector using std::lower_bound can be just as fast as std::set if you're not updating very often; they're both O(log n). It's worth trying both to see which is better for your own situation.
Comment: In my experience a sorted vector is noticeably faster than a set (and less memory intensive too); the obvious trade-off being that modifying the stored data is expensive.

If you need to look up by different fields, the simplest solution is to have a different sorted vector for each field (probably vectors of pointers to avoid duplicating a bunch of information)
Comment: This is by far the best answer to the question *actually* asked.
Comment: I failed to mention I would need to find on multiple values which would require re-sorting by name or by id.
Comment: The thing about std::vectors being less memory intensive than a linked list (that has to store indices or pointers to other nodes), is that std::vector can waste a lot of memory themselves. Under a standard allocation model for the vector if it grows to size 257 then it'll next reserve 512 * sizeof('element') bytes of memory, and then all that memory will be wasted, at least the unused portion.
Comment: @Zebrafish wasted memory won't affect the running time.  And you're assuming that the vector grows by a factor of 2 every time it increases, but that's implementation dependent; I've heard of 1.5x being used instead to lower the maximum unused memory.
Answer: Since from your (extended) requirements you need to search on multiple fields, I would point you to Boost.MultiIndex.
This Boost library lets you build one container (with only one exemplary of each element it contains) and index it over an arbitrary number of indices. It also lets you precise which indices to use.
To determine the kind of index to use, you'll need extensive benchmarks. 500 is a relatively low number of entries, so constant factors won't play nicely. Furthermore, there can be a noticeable difference between single-thread and multi-thread usage (most hash-table implementations can collapse on MT usage because they do not use linear-rehashing, and thus a single thread ends up rehashing the table, blocking all others).
I would recommend a sorted index (skip-list like, if possible) to accomodate range requests (all names beginning by Abc ?) if the performance difference is either unnoticeable or simply does not matter.
Comment: The elements are complex so caching of a large amount of elements would be counterproductive it's only useful in this one case as I know the tables have limited data and limited writes. While currently not heavily implemented multi-threading is a real possibility later so I had pretty much ruled hash tables out. There does not need to be a range as there are context based RE2 regex template functions elsewhere for that functionality across table string fields. However I will give Boost.MultiIndex a perusal as I'm unfamiliar but that sounds quite useful.
Answer: If you only want to search for distinct values, one specific column in the table, then std::hash is fastest.
If you want to be able to search using several different predicates, you will need some kind of index structure. It can be implemented by extending your current vector based approach with several hash tables or maps, one for each field to search for, where the value is either an index into the vector, or a direct pointer to the element in the vector.
Going further, if you want to be able to search for ranges, such as all occasions having a date in July you need an ordered data structure, where you can extract a range.
Answer: Not an answer per se, but be sure to use a typedef to refer to the container type you do use, something like typedef std::vector< itemtype > data_table_cache; Then use your typedef type everywhere.
Comment: Containers while similar usually have differing methods and usages. For example if I were to change from `std::vector` to `std::set` I would need to change all references to `push_back` and `empty` at a minimum. So the `typedef` doesn't buy anything `auto` isn't already providing.
Comment: How would the typedef make a difference other than less typing possibly? Template instantiations are resolved at compile time and I use C++0x `auto` keyword liberally for STL iterators to make code more readable.
Comment: Yes, it does many advantages, i.e. using as the type of some function parameter or of a class member.
Comment: Because when you decide you used the wrong container type and you want to change it, you only have to change it in one place.
Comment: The `typedef` (now `using` would be even better) provides naming, an explanation. It tells you what purpose the container serves, what it *is*, instead of how it's implemented. `std::vector` tells me how it's implemented but it doesn't tell me what it's for. `employee_names` and `customer_names` might both be `std::vector` but shows a distinction in code such as function signatures as to what's expected.
Comment: Also, before C++20, you couldn't use `auto` as function parameter, and in most cases, you still don't want to.


Which module for relationships in my particular case?

Question:
Possible Duplicate:
Relation vs. References vs. Entity Reference for managing node-reference-type relationships in D7

I want to figure out which module (and, probably, strategy) will fit my needs best in such a situation.
I've built a site, there are a lot of piece's; each piece is either written or arranged by some person (or has both relations, composer and arranger); each piece can be a part of a collection (think of CD for performed piece's or book for scores in PDF).
Here piece, person, collection are types (post types, or node types in Drupal I believe); score, audio, video, text etc are taxonomies (in media tree). And each piece can have any or all media taxonomies assigned. Also there are genre taxonomies.
A person can be a conductor (if piece presents some performance by choir), soloist etc.
So, piece can be connected with person by a named "role".
Below are some links to demonstrate what I actually want to have (or something like that); the site made with WordPress (using posts-to-posts plugin).
However, I don't like what I have: that was the first my attempt to make a site, I am nor a programmer neither designer... I don't know what I am. Anyway, I don't like that site in terms of code maintainability (I guess that's my fault, not WP's), so I'd like to rewrite it; and I'd like to design new theme and have better ("overall php+mysql") performance.
So, now the question is: which module should I try for this --- Entity Reference or Relations? Or any other? Can I hope I can get better performance (php+mysql)?
Please, take a look (everything in Ukraine, but there are buttons to google-translate, SORRY):

here is Mykola Gobdych's page (conductor of Chamber Choir "Kyiv") --- below the photo there are links to other "views" (listen to pieces conducted by this person, listen to pieces performed by him, listen to his pieces --- either composed or arranged by --- etc)
some collection of piece's
a piece --- please, note, here are two performances... actually these are two piece's connected with "the same piece" relationship
listen to choir view

I really would like to try to do something like this with Drupal; however, I am very new to drupal. And I am not a programmer .)
So, please help; I will appreciate any helpful information or suggestion.
Thanks!
Comment: @PatrickKenny Thanks, I saw that topic. However, I can decide by myself whether I have complex relationships or not. That's why I'm asking you, experts. Moreover, I would like to hear something about performance. I understand that not too much people here tried WP, but... anyway. I am really not a programmer and very new to drupal. Thanks again.
Comment: It could be that the language in the answers is to technical, and needs to be explained better. But as far as I can tell, the linked to Question contains all the necessary information to made an educated choice. @Brownian, please comment on the Q that Patrick linked to if something is unclear. For what it's worth, Patricks answer is the best one, not the accepted answer.
Comment: @Letharion well... after reading Елин's answer and some comments I guessed that those relations which I plan to use "are not too complex" (from drupal masters point of view), and Entity Reference will fit. You suggest that I would better ask in other question's comments "whether my relations are too complex or not"? I said that I know nothing about drupal -- I asked not for comparison of two, but which would be better for my particular picture. Ok, nothing about performance, my fault -- I should not ask whether can I get better performance at all. Sorry.
Comment: @PatrickKenny Sorry, I wanted to write "I can NOT decide by myself whether I have complex relationships or not."
Answer: Both Entity Reference and Relation modules would do the work, but in your case I would suggest to go with Entity Reference module, since you don't have very complex relationships.
Comment: Could be nice to include a direct link to the two modules.
Comment: Just updated, thank you for notice. @KristerAndersson
Comment: @ЕлинЙ. As I need both `piece` to refer to `person` and `person` to refer to `piece` (direct- and back-referencing) -- shouldn't I use Relation module?..
Comment: @brownian No, you don't need to. You should be capable of doing this with Entity Reference module, as well.
Comment: @ЕлинЙ. Sorry, I have to try everything. THANK you for your answer ANYWAY. This topic caused my misunderstanding: http://drupal.org/node/1293792


What's the correct way to decrease a variable within a function?

Question: Is there a way to make this work, or am I going to have to find a different way of logic? I wrote this really fast as an example of the problem I'm running into. Every time the guess function runs, I'd like to add a guess. The problem is that when I exit the function and then re-enter, the guess counter resets to 0. And I can't have the variable "guesses" outside of the defined function, which is what has me stumped.
What's the right way to do this?
def guess():
    x = 5
    guesses = 0
    while guesses < 5:
        guess = input("Guess: ")
        if guess == x:
            print("You win")
        else:
            print("try again")
            guesses = guesses + 1
            movement()

def movement():
    choice = input("left or guess")
    if choice == "left":
        movement()
    if choice == "guess":
        guess()

movement()

I'd like to be able to leave a function and re-enter without resetting the guesses variable.
Comment: A simple but "dirty" solution is to declare `guesses` global. A better solution is to pass `guesses` as a parameter to the function and return its new value.
Comment: A third solution is to make an object that carries state; e.g. a single game might be encapsulated in a class `Game`, which knows how to accept a guess, follow up on movement, or remember guesses. You will make a single object of this class, and the object will implicitly be passed around to all methods as `self`, without you having to juggle it around.
Comment: Python has something for this called a generator. I can give you an example in a second.
Answer: A common way to deal with this is to encapsulate your information in the instance of a class. The instance will hold properties such as the number of guesses and any other state you want to maintain. The methods will create the behavior which includes manipulating these properties.
Here you can create a new instance, including the option of passing the initial number of guesses and the answer:
class Guess:
    def __init__(self, answer = 2, guesses = 5): # 2 and 5 are deafaults if nothing is passed in
        self.guesses = guesses
        self.answer = answer

    def guess(self):
        guess = input("Guess: ")
        if guess == self.answer:
            print("you win")
        else:
            self.guesses -= 1
            print(f"You have {self.guesses} left")
            self.movement()

    def movement(self):
        choice = input("left or guess? ")
        if choice == "left":
            self.movement()
        if choice == "guess":
            self.guess()

g = Guess(answer = 5, guesses = 2) # make a new game using the passed in values
g.movement() # start game

Comment: This is exactly what I needed. Thank you!! Started coding 2 days ago and now I'm blown away at how helpful this community is for learning. Wow. This is very encouraging. Thanks :)
Comment: I was gonna make a comment in my post but the `self.movement()` seems like unnecessary recursion and just consumes stack for no particular reason.
Comment: Yeah, I agree with that @Error-SyntacticalRemorse, I was thinking more about the issue of maintaining state, but this could definitely be refactored to get rid of the recursive call.
Comment: Looks pretty good for two days @ChrisE! Good luck moving forward.
Answer: I like OOP (Object Oriented Programming) so I would go with the other answer.
 That being said if you want, Python has something useful for this called a generator. Think of it as a function that remembers state.
def my_gen():
    x = 0
    while True:
        # Yield acts just like a normal return, the functions stops
        # after returning x.
        yield x
        # Next time the generator is called it will resume
        # right here, add it will remember all the values
        # it previously had (i.e. it remembers the last value for x.
        x += 1
# Note a generator is called differently then a normal function
# then a normal function
g = my_gen()
print(next(g)) # prints 0
print(next(g)) # prints 1
print(next(g)) # prints 2

Also to cover how a generator stops:
def my_gen2():
    x = 2
    while x > 0:
        yield x
        x -= 1
# Note that when a generator function
# has no more yields it will throw a
# StopIteration Exception
g = my_gen2()
print(next(g)) # prints 2
print(next(g)) # prints 1
print(next(g)) # This will cause an StopIteration Exception

# you can get around this either by:
g = my_gen2()
for x in g: # A for loop automatically stops on StopIteration
    print(x)

# Or catch the Exception
try:
    g = my_gen2()
    for _ in range(5): # Just calling next enough times for it to break
        print(next(g))
except StopIteration:
    print("can't call generator any more")

Your Code:
def guess():
    x = 5
    guesses = 0
    num_tries = 1
    while guesses < num_tries:
        guess = input("Guess: ")
        if guess == x:
            print("You win")
            yield 0
        else:
            guesses += 1
        if guesses == num_tries:
            yield 0 # Game over
        else:
            print("Try again")
            yield 1 # Game can continue

# Don't add unneeded recusion.
# Python has a limited stack. Don't consume it
# for something you should do in a loop.
def play():
    g = guess()
    while True:
        choice = input("left or guess: ")
        print(choice)
        if choice == "left":
            continue
        elif choice == "guess":
            try:
                if not next(g):
                    print("Game over")
                    break
            except StopIteration:
                print("Somehow called to many times")
                break
        else:
            print("Invalid Entry")
play()

Comment: You're right that the other answer is easier. But thanks for showing me this too! I learned something new. Very new to this, so it's awesome to see how helpful y'all are :)
Answer: def guess(guesses = 0,x = 5):
    choice = input("left or guess")
    guesses = guesses + 1
    if choice == "left":
        return guess(guesses=guesses)
    elif choice == "guess":
        guessint  = int(input("Guess(int): "))
        if guessint  == x:
            print("You win")
            print('number:', guesses)
            return guesses
        else:
            print("try again")
            return guess(guesses=guesses)
guess()

Comment: The point is to exit and re-enter a function without redefining the x variable. Combining it all into a single function "works," here, but the point was to find a way to move between functions. If you're coding a complicated sequence of events, you're not going to have the entire story within a single function...


Adding a grouped column header to an existing dataframe

Question: How can we add to an existing Pandas dataframe a column header on a supplementary row above two sub column headers ? Here's the searched result:

Here's the current code which adds the CAPITAL header, but does not position it correctly.
import pandas as pd

OWNER = 'OWNER'
CAPITAL = 'CAPITAL'
USD = 'USD'
CHF = 'CHF'
YIELD = 'YIELD AMT'

df = pd.DataFrame({
    OWNER: 2*['JOE']+3*['ROB'],
    USD: [10000, 30000, 4000, 24000, 16000],
    CHF: [9000, 27000, 3600, 21600, 14400],
    YIELD: [100, 300, 40, 240, 160]
    })

print(df)
'''
  OWNER    USD    CHF  YIELD AMT
0   JOE  10000   9000        100
1   JOE  30000  27000        300
2   ROB   4000   3600         40
3   ROB  24000  21600        240
4   ROB  16000  14400        160
'''

df.columns = pd.MultiIndex.from_product([[CAPITAL], df.columns])
print('\nUsing pd.from_product()')
print(df)
'''
  CAPITAL
    OWNER    USD    CHF YIELD AMT
0     JOE  10000   9000       100
1     JOE  30000  27000       300
2     ROB   4000   3600        40
3     ROB  24000  21600       240
4     ROB  16000  14400       160
'''

Comment: You are doing it correctly. It's just how Pandas choose to print the column names. You might get more alignment when exporting your data to excel.
Answer: The solution is to use pd.MultiIndex.from_arrays() instead of pd.MultiIndex.from_product(). Here's the code:
import pandas as pd

OWNER = 'OWNER'
CAPITAL = 'CAPITAL'
USD = 'USD'
CHF = 'CHF'
YIELD = 'YIELD AMT'

df_ok = pd.DataFrame({
    OWNER: 2*['JOE']+3*['ROB'],
    USD: [10000, 30000, 4000, 24000, 16000],
    CHF: [9000, 27000, 3600, 21600, 14400],
    YIELD: [100, 300, 40, 240, 160]
    })

df_ok.columns = pd.MultiIndex.from_arrays([[' ', ' ', CAPITAL, ' '], df_ok.columns])

print('\nUsing pd.from_arrays()')
print()
print(df_ok)
'''
                CAPITAL
    OWNER    USD    CHF YIELD AMT
0     JOE  10000   9000       100
1     JOE  30000  27000       300
2     ROB   4000   3600        40
3     ROB  24000  21600       240
4     ROB  16000  14400       160
'''


Jordan normal form theorem - a question about the proof I've found

Question: I've been reading this proof of Jordan's theorem:
http://www.cs.uleth.ca/~holzmann/notes/jordan.pdf
and there are a few questions I hope you could answer for me.
Firstly, why $(A_{\lambda})_{\mu _i} = A _{\lambda + \mu _{i}} =: A _{\lambda_{ \ i}}$
and secondly, how do we know that $\dim (W \cap Ker A_{\lambda}) \ge 1$?
The problem in the first question is that I'm not sure what $(A_{\lambda})_{\mu _i}$ means.
Thank you.
I understand that we pick a vector $v\neq 0$ with an eigenvalue $\lambda$. $A$ is $n \times n$
$A_{\lambda} = A - \lambda I \ \ \ \ \ \ \ \ \ A_{\lambda}v=0,$ so we have $r = \dim \ker A_{\lambda}>0$
$\dim \ range A_{\lambda} = n-r<n $ , $W := range \ A_{\lambda} $
I undestand that because $W := range \ A_{\lambda} $, then $ A_{\lambda} (W) \subset W$, so
$A_{\lambda} $ induces $T: W \rightarrow W$ and we can apply inductive hipothesis to its matrix. What I don't understand is why all of a sudden there are $\lambda_i$ over the arrows and it is probably because I don't know what $(A_{\lambda})_{\mu _i}$ means
Comment: I coouldn't find what you call "firstly" in that paper, though I didn't read it thoroughly, and I think you should better try to make your question self contained: try to define those $\,A_\lambda\,$ , some of their characteristics and then pinpoint where you're stuck.
Comment: It's the last line of step 1.
Answer: For the first, these are just successive $B_x:=B-xI$ operations, so $_{\mu_i}$ applied to $A_\lambda$. That $(A_\lambda)_{\mu_i}$ is $A_{\lambda+\mu_i}$ follows from definition.
For the second, I don't think we need that at all (and the author doesn't seem to claim anything of the sort). In fact, it might not be true, as $A_\lambda$ can very well be a projection onto its range. Consider the matrix
$$
\begin{pmatrix}
1 & 0 \\
0 & 2
\end{pmatrix}
$$
with $\lambda=1$, for instance.
Comment: @Don: the statement is true even if $q=0$, albeit vacuously so (as there are no $j$ such that $1\leq j\leq q$).
Comment: So why do we assume that "$q = \dim (W \cap Ker A_{\lambda})$ of the $\lambda_i$ strings are $\lambda$ strings, say the first $q: \ \lambda_j = \lambda$ for $1 \le j \le q$"?
Comment: Ok, I see that now. Thank you a lot.
Answer: According to that paper
$$A_\lambda:=A-\lambda I\implies\left(A_\lambda\right)_{\mu_i}:=(A-\lambda I)_{\mu_i}=(A-\lambda I)-\mu_iI=A-(\lambda+\mu_i)I=:A_{\lambda+\mu_i}$$


Warnings still show on page even after setting Error messages to None in Logging and Errors

Question: I have set the Error messages to display to None

but still the website shows warning messages on top.

Also cleared the cache after this but the anonymous user can still see warning messages.
Is there anything else to be changed?
Comment: Are you have custom coded modules?
Comment: Custom coded modules?
Answer: That's a pretty specific error message, and google says it is coming from this module:
https://www.drupal.org/project/netforum
at these lines: 808-812
<code>  catch (Exception $e) {
    if (isset($cache_max)) { //this implies that we went even further back in the cache and could not connect, so call it quits
      if (variable_get('netforum_hide_error_messages', 0) == 0 || user_access('administer site configuration')) {
        drupal_set_message(t('Could not retreive data from server or cache.'), 'error');
      }
</code>
More specifically to your question, because the above module is using drupal_set_message it is not going to be effected by the 'error_reporting' level since that only impacts errors that would go to the logs. This makes sense as you would want to be able to suppress syntax or PHP errors while still letting system messages like "node was saved" or "subscription processed" still appear to the screen.
Your options to suppress this are to deal with the underlying cause of the error from the module (best case), or remove the 'messages' functionality from your theme, i.e. remove where ever it is that it says:
<code>print $messages;
</code>
but again, that is probably not the best course of action here.
Comment: I totally agree that not printing the messages is a bad idea.
Comment: Yes thanks for pointing towards drupal_set_message. Since this more like an error, I will have it move to the watchdog then print it on the site.


How to use a word at end of function signature?

Question: I'm trying to write a delegate interface like this:
// This delegate is just a sample. It could be any delegate.
// What's important here is the third function's signature.
protocol MyViewDelegate {
    func myView(_ myView: MyView, didDoSomething something: String)
    func myView(_ myView: MyView, didDoAnotherThing thing: String at: Date)
    func myView(_ myView: MyView, didDoYetSomethingElse)
}

However, the third function is invalid syntax. It's used to notify the delegate that some specific event happened, so the signature is important and I want to keep all function signatures consistent.
Question: What's the recommended signature for the third function?
Comment: So what's the *specific* issue? It sounds like you already *know* how to use delegates. But because you can only provide "sample" code it's quite hard to actually help you....
Comment: You can have parameters of a void type `()`, but there is seldom a good reason to use them
Comment: @dfd This is not about delegates. The question title and the goal say it: "How to use a word at the end of a function signature? The goal is for a method signature to be expressive." The delegate here is just the context and the reason why I would want a word at the end of a method signature: to be consistent with the naming of the other delegate methods. I apologize for not being explicit about this.
Comment: To me it sounds like you should be using Obj-C then. Part of it's design - as opposed to how Swift was designed - is just that. Expressiveness. To try to fit a square peg (in this case Swift) to fit in a round hole (in this case dynamic expressiveness in function names) is not something easily done.
Answer: It may not be very satisfying, but you simply can't do that. There is lots of precedent for writing these kinds of methods like this:
func myViewDidAskUserName(_ myView: MyView)

For example, a common one from Apple:
func applicationDidFinishLaunching(_ application: UIApplication)

Answer: You are trying to give the delegate a choice of two kinds of thing that happened: said something, or asked user name. That sort of choice among possibilities, in Swift, is an enum:
enum WhatHappened {
    case didSaySomething(String)
    case didAskUserName
}

Now write your method signature like this:
protocol MyViewDelegate {
    func myView(_ myView: MyView, _ whatHappened: WhatHappened)
}

The method can be called by saying
myView(theView, .didSaySomething("hello"))

or by saying
myView(theView, .didAskUserName)

Comment: That is creative :) I'll keep this solution in mind. It won't apply to this specific project, unfortunately because the delegate may become larger with more methods and different signatures.


Axios post request error: 422 Unprocessable Entity

Question: I've been trying to build this stock prediction web app using Prophet model and FastAPI. I'm stuck at this problem where I'm getting console log error: 422 Unprocessable Entity.
Here's the react code to get API request:
async function GetAPI () {

    const [predData, setPred] = React.useState();
    const [stock_name, setStock] = React.useState();

    const axios = require('axios');

    var data = JSON.stringify({
      "ticker": stock_name
    })

    try{
      let response = await axios({
        method: 'post',
        url:'http://0.0.0.0:8000/predict',
        headers: {
          'accept' : 'application/json',
          'Content-Type' : 'application/json'
        },
        data: data
      },
      )
      if (response.status==200){
        console.log(response.data);
        setPred(response.data);
      }
      return {predData}

    }
    catch(error){
      console.log(error);

    }

}

This is the FastAPI function in my python backend:
@app.post("/predict")
def prediction(payload: StockIn):
    stock_name = payload.stock_name
    pred = stock_prediction(stock_name)
    a = int(pred)
    response_object = {"data" : a }
    return response_object

Can anyone help me out here?
Comment: Are you supposed to stringify before the post?
Answer: First of all, you send {'ticker': '...'}.
And in backend you try to access a property called stock_name.
Most likely this is caused by it.
If that doesn't help, check below.
It seems that your situation is related with your backend, so you can edit the header.
You can check the variables by simply adding
print statements after important parts.
For example;
@app.post("/predict")
def prediction(payload: StockIn):
    print('Payload:', payload)
    stock_name = payload.stock_name
    pred = stock_prediction(stock_name)
    print('Pred:', pred)
    a = int(pred)
    response_object = {"data" : a }
    return response_object

NOTE: It's about backend because axios doesn't interfere with the response codes.
Comment: stock_name is a var passed from a different component, this code worked when I tried to test API using FastAPI interface. It's just I can't make my react code pass a stock name and get an output out of it.
Comment: You don't seem to pass a stock_name from a component, you are sending your data as {'ticker': '...'} and in the server side you can access it by payload.get('ticker') I suppose. Can you try it? And also, as @ConorReid said, "Are you supposed to stringify before the post?"


Couldn't target the organization using CF

Question: i used cf target to get the current target information
but i get this error
'cf' is not recognized as an internal or external command,
operable program or batch file.
i installed the CLI
Comment: i need to Target the Organization and Space in which i created my Node.js Cloud Foundry App
Answer: When you installed the IBM Cloud CLI, all commands start by calling the CLI by either ibmcloud or bx. You can use ibmcloud cf followed by Cloud Foundry commands.
Ue ibmcloud target --cf to interactively pick the org and space. If that does not give the right choices or an error: Are you connected to the correct region? Use ibmcloud target -r the-region to set the region and replace the-region with, e.g., us-south.
Comment: i did it thanks! , but when i tried to push the files everything was ok, until   Waiting for app to start...
TIP: use 'cf.exe logs Tutankhamun-Chatbot --recent' for more information
FAILED
Comment: My answer addresses your question. Please upvote and mark as answered. Then ask your next question. (Tip: include how you pushed and what)
Comment: Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
how i pushed and what?
files like this i just modified but i get an error
https://github.com/lukemccomb/watson-assistant-chatbot-ui#step_8iii
Comment: add that to the new question :) Mark this one as answered (click on the check mark)
Comment: please can you see this problem
https://stackoverflow.com/questions/57774652/node-js-execute-function-before-complete-multiple-lines-of-code?noredirect=1#comment101984810_57774652

look at my comments please.


Probability of HTHT in n coin flips

Question: What is the probability of finding the sequence HTHT in $n$ flips of a coin? By brute force I get

$n=4: \frac{1}{2^4}$
$n=5: \frac{2(2)}{2^5}$
$n=6: \frac{2^2(3)-1}{2^6}$
$n=7: \frac{2^3(4)-2}{2^7}$
$n=8: \frac{2^4(5)-6}{2^8}$

I hoped to extract a pattern but counting gets messy.
EDIT: My original counts for $n=7$ and $n=8$ are, as noted in the comments, incorrect. Recounting I get
\begin{align}
\frac{2^3(4)-4}{2^7}\ \text{for}\ n=7\ \text{and}\ \frac{2^4(5)-12}{2^8}\ \text{for}\ n=8
\end{align}
which agrees with the comment below.
Comment: $1,4,11,28,68,158,357...$ Sequence not found in OEIS. Note that your counts for $n=7$ and $n=8$ are incorrect.
Comment: Sorry, could you be clearer when stating your problem?
Comment: @DanielMathias If you take each term minus twice its predecessor, so $1,2,3,6,12,22,41$ etc., I think you get [OEIS A112575](https://oeis.org/A112575)
Comment: @Henry Nice find. The relation is confirmed.
Comment: and $\frac{1}{2^4},\frac{2}{2^5},\frac{3}{2^6},\frac{6}{2^7},\frac{12}{2^8},\frac{22}{2^9},\frac{41}{2^{10}}, \ldots$ are the probabilities of needing $n$ rolls *but not fewer*.
Answer: Let $A_n$ be the number of sequences that don't include the pattern $HTHT$. Then
$$A_n = \pmatrix{1 & 1 & 1 &1} T^n  {\pmatrix{1 & 0 & 0 &0}}^{t} \tag1$$
where
$$T= \pmatrix{
1 & 0 & 1 & 0 \\
1 & 1 & 0 & 1 \\
0 & 1 & 0 &0 \\
0 & 0 & 1 &0
} \tag2$$
Eq $(1)$ is obtained by counting recursively the "allowed" sequences that have $(0,1,2,3)$  trailing matching characters.
Some values for $A_n$, from $n=0$ to $n=10$: $(1, 2,4,8,15,28,53,100,188,354,667)$
This is OEIS sequence A118870.
Then the desired probability is
$$ p_n = 1 - \frac{A_n}{2^{n}}$$
I don't think there is a simple formula to express $(1)$ for arbitrary $n$
I'd expect that $p_n \le 1 - (15/16)^{n-3}$
Comment: The generating function $\frac{1+z^2}{1-2z+z^2-2z^3+z^4}$ is given in the OEIS entry; we can also find it from your matrix $T$, since $\sum_{n\ge 0}A_n z^n = (1,1,1,1)(\sum_{n\ge 0} z^n T^n) (1,0,0,0)^t = (1,1,1,1) (I - zT)^{-1} (1,0,0,0)^t$. We can use this to get an explicit formula, but it's not nice; the dominant term of $A_n$ is proportional to $\left(\frac{1}{2} \left(\sqrt{2}+\sqrt{2 \sqrt{2}-1}+1\right)\right)^n$.
Comment: @MishaLavrov that dominant term can also be obtained from the largest eigenvalue of $T$
Comment: Sir, please help me with the problem at https://math.stackexchange.com/questions/3797044/distribution-of-the-number-of-trials-required-for-the-first-occurrence-of-the-ev
Answer: I think the following works.
Let $N_k$ be the number of sequences of length $k$ that end for the first time in HTHT.
Now, the number of sequences of length $k$ that end in HTHT (possibly not for the first time) is $2^{k-4}$.  However, many of these had proper prefixes that ended in HTHT, and we have to subtract these out:

$N_{k-2}$, the prefixes of length $k-2$ that end in HTHT.
$N_{k-4}$, the prefixes of length $k-4$ that end in HTHT.
$2N_{k-5}$, twice the prefixes of length $k-5$ that end in HTHT (because they are followed by an arbitrary result on flip number $k-4$).
$4N_{k-6}$, four times the prefixes of length $k-6$ that end in HTHT (because they are followed by an arbitrary result on flips number $k-5$ and $k-4$).
And so on.

We therefore have, for $k \geq 8$,
$$
N_k = 2^{k-4}-N_{k-2}-\sum_{j=4}^{k-4} 2^{j-4}N_{k-j}
$$
leading to OEIS A112575 (with an offset), with values
$$
1, 2, 3, 6, 12, 22, 41, 78, 147, 276, 520, 980, 1845, 3474, \ldots
$$
for $k \geq 4$.  The desired probabilities are then
$$
p_k = \frac{N_k}{2^k}
$$

Probability of HTHT in n coin flips


Ionic Native Geolocation not working on Android

Question: I have the following code using Ionic Native Geolocation:
import { Geolocation } from 'ionic-native';

    this.platform.ready().then(() => {
        alert('loadMap about to getCurrentPosition');
          Geolocation.getCurrentPosition(options).then((position) => {
        alert('loadMap getCurrentPosition');
            let latLng: google.maps.LatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            bound.extend(latLng);
            this.load(bound);
          });
    });

When I run this as ionic serve in a browser, or I build it and run it on iOS Simulator (Xcode), it works. However, when I build this for Android, and try run it, the first alert gets fired, but not the second.
That means for Android only, Geolocation.getCurrentPosition... is not working.
I do have another page that can render a map via this.map = new google.maps.Map(htmlElement, mapOptions);, so it looks like the issue is with getting the current position. When I install the app, I do get this message however:

Allow AppName to access the device's location?
DENY    ALLOW

To which I click Allow.
Does anyone know what I am doing incorrectly, or if there are some missing steps in the Android install and build process?
Thanks
Comment: I have been using this for a while and it worked. Now suddenyl it does not work anymore. No code changes. I think your code is fine, but I think somethone else is unstable. SOOOOOOO frustrating. No time out nothing
Comment: @Harry sir i am also frustrated  last 3 days in my case function is not trigged?
Answer: Ok, so I have struggled with this for a while now. Some times it works, some times it does not. Try to add options to it:
let options = {timeout: 10000, enableHighAccuracy: true, maximumAge: 3600};
Geolocation.getCurrentPosition(options).then((resp) => {

Comment: Sir i have tried above code but not working for me getCurrentPosition function not fire for me it working only after run android but after generate build its not working tell me sir what's the problem?
Comment: This worked for me, without this option setting my App was silently failing in Android 12 without any exception(annoyingly..), thank you!
Answer: These following steps did the trick for me:
Install the two latest ionic-cli plugins:
sudo npm install -g ionic@latest
npm install --save-dev --save-exact @ionic/cli-plugin-cordova@latest
npm install --save-dev --save-exact @ionic/cli-plugin-ionic-angular@latest

Then install the geolocation plugin:
npm install @ionic-native/geolocation --save
ionic cordova plugin add cordova-plugin-geolocation

Then remove the '/node_modules' folder and clean the cache of npm:
rm -rf node_modules/
npm cache clean --force

And finally reinstall the packages:
npm install

Hope it will help someone :)
Comment: Is it necessary to remove node_modules everytime the packages are updated ? lot time consuming & ambiguous thing
Comment: You can do `npm update`. To check if any packages in your Node.js project are outdated, run `npm outdated` in the root folder (where the package.json file is). This command will output the current installed versions of all packages, the wanted version (`npm update` would want to update to this version) [link](https://www.mariokandut.com/how-update-node-dependency-npm/)
Answer:

let options = {timeout: 10000, enableHighAccuracy: true, maximumAge: 3600};

this seem run the geolocation but can not catch the lat and lng return {}
Answer: Try Background Geolocation instead of Geolocation it solved my problem
for more detail read the document
https://ionicframework.com/docs/native/background-geolocation/
Comment: Please provide some additional information, add some code and maybe a link to the docs.
Comment: Your App may get rejected or can be removed if you dont give proper reasoning for background location usage. lets stick to the question which is foreground usage only


Linear Programming Problem, notation confusion

Question: While trying to implement an algorithm from here I must solve a linear programming probelm. linear programming problem.
I am confused about what the vertical lines indicate. I believe that this is not the vector norm since the equations are linear. I would be grateful if someone could help.
Answer: It does look like vector norm.  This does not destroy linearity because the argument of the norm does not contain any decision variables.
Comment: could you please elaborate on what you mean by decision variables?
Comment: Here, $\rho$ and $x$ are the decision variables, which the solver is free to determine.  But everything else ($\tau_r$, $c$, $a(y)$, and $b(y)$) are fixed constants.


P-values of A/A Test with dependence does not obey uniform distribution?

Question: Suppose we have a large population (U.S. people). I divide population into 100 subgroups. Note that all people in each of the subgroups are i.i.d..
Suppose I make 50 tests for mean height between 100 subgroups(Group1 vs. Group2, Group3 vs. Group4, etc.), then I will get 50 independent p-values. When the null hypothesis is true (it really is), p-values obey a 0-1 Uniform distribution.
My question is:

If we make tests between the combination of 100 subgroups, which means 1000*99/2 = 4950 tests(Group1 vs. 2/3/.../100, Group2 vs. 3/4/.../100, etc.). P-values are dependent, and what is the distribution of these dependent A/A Tests' p-values?

From my simulations:

independent p-values obey uniform distribution
dependent p-values are not(can not pass ks-test)

But I can not prove it, or make a very intuitive explanation for this problem, so I need your help ;)
Code on colab
import scipy.stats as stats
from scipy.stats import ttest_ind
import matplotlib.pyplot as plt
from scipy.stats import kstest,ks_2samp, anderson_ksamp, anderson
from itertools import permutations, combinations

n_bkt = 1000
data = stats.norm.rvs(size =100000)
bucket = np.random.randint(0,n_bkt, size = 100000)
res = []
for i in range(0,n_bkt//2):
    control = data[bucket == (i*2)]
    treatment = data[bucket == (i*2 + 1)]
    res.append(ttest_ind(control, treatment))

res2 = []
for i,j in combinations(range(0,n_bkt),2):
    control = data[bucket == i]
    treatment = data[bucket == j]
    res2.append(ttest_ind(control, treatment))

fig, axs = plt.subplots(2,2,figsize=(10, 8))
fig.suptitle('Two A/A Test methods')

axs[0,0].hist([i[0] for i in res])
axs[0,0].set_title('T-Statistics of Independent A/A Tests')
axs[0,1].hist([i[1] for i in res])
axs[0,1].set_title('P-values of Independent A/A Tests')
axs[1,0].hist([i[0] for i in res2])
axs[1,0].set_title('T-Statistics of Dependent A/A Tests')
axs[1,1].hist([i[1] for i in res2])
axs[1,1].set_title('P-values of Dependent A/A Tests')

# Test whether T-statistic obey standard normal distribution
## independent
print(kstest([i[0] for i in res],lambda x: stats.norm.cdf(x,loc = 0, scale = 1)))
## dependent
print(kstest([i[0] for i in res2],lambda x: stats.norm.cdf(x,loc = 0, scale = 1)))

# Test whether P-values obey 0-1 Uniform Distribution
## independent
print(kstest([i[1] for i in res], lambda x: stats.uniform.cdf(x,loc = 0, scale = 1)))
## dependent
print(kstest([i[1] for i in res2], lambda x: stats.uniform.cdf(x,loc = 0, scale = 1)))

Comment: Forgive my poor english, we can get 50 independent p-values and 4950 dependent p-values based on 100 subgroups. The former "paired" 100 subgroups into exclusive 50 tests; the latter test on combination of 100 subgroups.
Comment: I think we can get 50 independent p-values at most, beacase 2 p-values are dependent when one subgroup is testing against 2 other subgroups. In other words, each subgroup can only be used in one test.
Comment: "Suppose I make 50 tests for `mean height` between 100 subgroups(Group1 vs. Group2, Group3 vs. Group4, etc.), then I will get 50 independent p-values." This does not follow. If you have $k = 100$ subgroups, then there are $m = \frac{k^2 - k}{2} = 4,950$ different two-way tests.
Comment: Ah! I think that makes sense! Thank you! To be clear: there are more than 50 possible independent tests, but the moment you choose one, you foreclose on many others, so that at most 50 can be realized?
Answer:
In fact your p-values look at least as uniform for the dependent tests; it seems that K-S rejects uniformity there because of the large sample size (number of p-values), i.e., even a small deviation from uniformity is detected.

The distribution theory of the t-test requires observations to be distributed Gaussian. As your data are drawn from real observations, they are not precisely Gaussian distributed, and the t-test theory will only hold approximately, resulting in small deviations from the uniform distribution for p-values (regardless of whether tests are dependent or independent, however these deviations may be so small that you didn't detect them with the smaller number of independent tests).

There is an additional reason why dependent p-values of this kind may be less uniform. If one of your groups has an unusually high "mean height", not only is it involved in 99 tests, also as the mean of all group means is the overall mean, this means that there also must be one or more other groups with exceptionally small means, leading to a somewhat higher amount of p-values near 0 or 1 than expected. On the other hand your 100 groups may be unusually similar regarding their means (if, say, 50 of them are similar to the overall mean, the mean of the remainder also must be similar to the overall mean), in which case fewer p-values close to 0 or 1 may occur than expected. These should be small effects not affecting uniformity big time, but they can happen either way with a larger probability than expected under independence.
Comment: - For 2, actullay I generate data with normal distribution and keep sample size large enough to have a better convergence in CLT.
- For 3, I agree with you, dependence may cause that p-values does not obey uniform distribution, just like outliers' effect in A/A test. However, I am wondering the reason and an very intuitive explanation
Comment: Thank you a lot!
- For 1, KS-test is a very low power test, when it rejects H0, it gives us strong evidence that p-values are not uniform. Sample distribution does have small deviation compared with population distribution, but we shall not reject H0 with a very small p-value in KS-test in A/A test situation(H0 is true)


Jquery, $(this) outside function

Question: I would like to trigger a function inside an each loop.
The problem comes from the $(this) which is outside the each loop
function look () {
    $(this).css("color","blue");
};

$(".text").each(function(){

    look();
    // other functions()
    //...
});

I know I can place my $(this), inside the each loop, but I would like to proceed like this because I have many small functions to place. How can I do ? Thanks. Nicolas.
Answer: Try this:
function look (el) {
    el.css("color","blue");
};

$(".text").each(function(){

    look($(this));

});

Answer: You can use look.call(this) to change the context of this; From this way, you don't need change your function look().
Look: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

Jquery, $(this) outside function


Proving that $B(L)$ is regular if $L$ is regular

Question: $L$ is a binary language.
$$B(L) = \{ w | w ∈ L \text{ and }|w|>10 \}$$
I need to prove the following:

If $L$ is regular $\rightarrow$ $B(L)$ is regular

I thought about doing it using Nerode's theorem:
We know that $L$ has a finite number of equivalence classes (let's call it $N$).
Every word in $B(L)$ is also in $L$ with the condition that it's longer than $10$.
so can I say that the number of equivalence classes in $B(L)$ is at most $N+11$ because we're only adding classes that are distinguishable by whether or not $wz$ adds up to $11$ or not. (in the case that all words in $L$ are already greater than $10$ - the number of equivalence classes in $B(L)$ is also $N$)
Therefore, $B(L)$ has a finite number of equivalence classes $\rightarrow$ $B(L)$ is regular?
Answer: It actually is $11N + 1$, because for each class we originally had, we potentially need to distinguish cases when length of word is $1, 2, \ldots, 10$ or more from this class, and possibly move empty word to it's own class, but otherwise it's correct.
However I think Myhill–Nerode is an overkill here: all you need is that intersection of two regular languages is regular and the fact that language consisting of words with length greater than $10$ is regular.
Comment: Brilliant I'll just use the intersection, thanks!


Classical Guitar Exercises for Proper Tab Fingering?

Question: Related: Figuring the Classical Fingering from Sheet Music
Are there any classical guitar exercises, (for classical music), that also include the Tab as well as proper frettting-hand fingering numbers, (with harmonies, chords, etc.)?
I am working on Pachelbel's Canon in D, (beginner), and I am discovering more efficient fingering as I practice. It would be awesome to find some exercises so that I can find these fingerings more naturally over time.
Comment: related - https://music.stackexchange.com/questions/51300/correct-way-of-practicing-giulianis-120-right-hand-studies/52550#52550
Comment: @NeilMeyer: I think the OP is mostly interested in fretting-hand instructions, not picking hand instructions, which occur far less.
Answer: I'm assuming you're talking about fretting-hand information here, since picking fingers are usually as p-i-m-a, not numbers.
Given the size of the internet, there surely must be some resources, but a generalized one? Doubtful.
It's more important to keep in mind that all fingerings in sheet music are partly hints & guidelines. No two hands are the same, and what fits & comes easy to one hand, might just not fit your hands. So you should not be surprised to find alternate fingerings that work better for you. At least not for isolated instances.
But: Keep in mind that the one adding the fingering to the sheet music (hopefully) knows more about the piece, and has the benefit of fore- and hindsight: There might be fingerings that feel awkward first, but that, when employed in a phrase of the piece, make complete sense, because it allows for easier transitions or smoother execution or, in short, a net benefit to the ease of execution of the entire piece.
I tend to practice a piece with the fingerings presented, drop 50% of the suggested fingering, only to reinstate at least 25% of the suggested fingering. There's a personal learning curve there, where you become more aware of what your hand(s) can and can not do, and you'll be able to decide on which guidelines to follow and which not.
In summary: Never discard the provided information, always judge and adjust. Then reevaluate the provided information. There's a reason they put it there. The value of which depends on the source.
Answer: Most proper classical guitar music, arrange by guitarists for guitarists, will contain numerical indicators in the sheet music for (1) the position, (2) which left hand finger to use for a note, (3) which string the note should be played on, and (4) which right hand finger should be used to pluck the note.  This is a lot of information and is essentially TAB.  Most classical music that I am used to seeing is not TAB (or at least not TAB only).  This method of decorating notes still assumes that you know how to read music.  There is so much information in this notation that it can make sight reading impossible so these indicators are used when the fingering might get tricky.  To learn to play guitar and sight read at the same time there is a standard method that's been around for 100 years or more that teaches the student the "most common" or "most useful" fingering in a given position.  So it is assumed that the guitarist knows this.  Then when there is a big change in position or a strange chord is introduced the aforementioned notations are used to help the guitarist get over that spot.  Then everything should follow the standard method.
As an example 6 Pavans and a Fantasia by Luis Milan, the Andrew Barrow transcription, has a lot of this notation in each piece.  So much so that there isn't much room for reinterpretation.  The approach is covered in standard books like Carcassi, Parkening's beginner book on guitar, and even Mel Bay's modern guitar method.
As for true TAB, I am not sure.  I actually have an old print of Romance from the 1950's or 60's that has the entire song completely in TAB but I think this is a rare item for classical.  If you are looking at sheet music that you want to learn and the fingering is not set then you need to do some arranging.  If you read standard music notation then you can either search for a guitarist's arrangement of the piece or do the arranging yourself and annotate the sheet music you do have once you get a fingering that you like.  If you doe not read SMN you are at a bit of a deficit.
As for "exercises" there really aren't any that will make you able to find the most efficient fingering on a first read.  My advice would be to work through books like Carcassi, Parkening, Romero, and exercise like 20 Etudes by Sor (the Segovia edition has enough fingering to be helpful).  And I did mention Barrow's version of 6 Pavans etc.  That is a very comprehensive arrangement that is heavily notated.  The problem is, and other's have said it, you may disagree with Barrow's choices.  But by working through his arrangement you will at least get to experience the thought process behind those choices.  Really, experience is the only guide here.
Comment: Thank you very much.  I can read sheet music, and didn't have any idea that there were notations like that.  I have been using tab to learn how to map notes between the fretboard and sheet music.  Thank you for all of these examples I never knew about.  I will try to find some pachelbel and Bach like what you mentioned.  Do you have any suggestions for the Cannon in D?   This is incredibly helpful.  Thank you.


Adding random effect influences coefficient estimates

Question: I have always been taught that random effects only influence the variance (error), and that fixed effects only influence the mean. But I have found an example where random effects influence also the mean - the coefficient estimate:
require(nlme)
set.seed(128)
n <- 100
k <- 5
cat <- as.factor(rep(1:k, each = n))
cat_i <- 1:k # intercept per kategorie
x <- rep(1:n, k)
sigma <- 0.2
alpha <- 0.001
y <- cat_i[cat] + alpha * x + rnorm(n*k, 0, sigma)
plot(x, y)

# simulate missing data
y[c(1:(n/2), (n*k-n/2):(n*k))] <- NA

m1 <- lm(y ~ x)
summary(m1)

m2 <- lm(y ~ cat + x)
summary(m2)

m3 <- lme(y ~ x, random = ~ 1|cat, na.action = na.omit)
summary(m3)

You can see that the estimated coefficient for x from model m1 is -0.013780, while from model m3 it is 0.0011713 - both significantly different from zero.
Note that when I remove the line simulating missing data, the results are the same (it is full matrix).
Why is that?
PS: please note I am not a professional statistician, so if you are about to respond with a lot of math then please make also some simple summary for dummies :-)
Comment: I guess you want to say "from model `m3` it is 0.0011713" instead of `m2`.
Comment: I am sorry @user11852, yes you are correct, thanks. (BTW, for `m2` it is valid also (which is subject of [another question](http://stats.stackexchange.com/q/65386/5509)).
Answer: "I have always been taught that random effects only influence the variance (error), and that fixed effects only influence the mean."
As you have discovered, this is only true for balanced, complete (i.e., no missing data) datasets with no continuous predictors. In other words, for the kinds of data/models discussed in classical ANOVA texts. Under these ideal circumstances, the fixed effects and random effects can be estimated independent of one another.
When these conditions do not hold (as they very very often do not in the "real world"), the fixed and random effects are not independent. As an interesting aside, this is why "modern" mixed models are estimated using iterative optimization methods, rather than being exactly solved with a bit of matrix algebra as in the classical mixed ANOVA case: in order to estimate the fixed effects, we have to know the random effects, but in order to estimate the random effects, we have to know the fixed effects! More relevant to the present question, this also means that when data are unbalanced/incomplete and/or there are continuous predictors in the model, then adjusting the random-effects structure of the mixed model can alter the estimates of the fixed part of the model, and vice versa.
Edit 2016-07-05. From the comments: "Could you elaborate or provide a citation on why continuous predictors will influence the estimates of the fixed part of the model?"
The estimates for the fixed part of the model will depend on the estimates for the random part of the model -- that is, the estimated variance components -- if (but not only if) the variance of the predictors differs across clusters. Which will almost certainly be true if any of the predictors are continuous (at least in "real world" data -- in theory it would be possible for this to not be true, e.g. in a constructed dataset).
Comment: Could you elaborate or provide a citation on why continuous predictors will influence the estimates of the fixed part of the model?
Comment: @robin.datadrivers Okay I added a little bit about that
Answer: On first level, I think all you are ignoring shrinkage toward the population values; "the per-subject slopes and intercepts from the mixed-effects model are closer to the population estimates than are the within-subject least squares estimates." [ref. 1]. The following link probably will also be of help (What are the proper descriptives to look at for my mixed-models?), see Mike Lawrence's answer).
Furthermore, I think you are marginally unlucky in your toy example because you have a perfectly balanced design that cause you to have the exact same estimate in the case of no missing values.
Try the following code which has the same process with no missing value now:
 cat <- as.factor(sample(1:5, n*k, replace=T) ) #This should be a bit unbalanced.
 cat_i <- 1:k # intercept per kategorie
 x <- rep(1:n, k)
 sigma <- 0.2
 alpha <- 0.001
 y <- cat_i[cat] + alpha * x + rnorm(n*k, 0, sigma)

 m1 <- lm(y ~ x)
 m3 <- lme(y ~ x, random = ~ 1|cat, na.action = na.omit)

 round(digits= 7,fixef(m3)) ==  round(digits=7, coef(m1)) #Not this time lad.
 #(Intercept)           x
 #      FALSE       FALSE

Where now, because your design is not perfectly balanced you don't have the same coefficient estimates.
Actually if you play along with your missing value pattern in a silly way ( so for instance: y[ c(1:10, 100 + 1:10, 200 + 1:10, 300 + 1:10, 400 +1:10)] <- NA) so your design is still perfectly balanced you'll get the same coefficients again.
 require(nlme)
 set.seed(128)
 n <- 100
 k <- 5
 cat <- as.factor(rep(1:k, each = n))
 cat_i <- 1:k # intercept per kategorie
 x <- rep(1:n, k)
 sigma <- 0.2
 alpha <- 0.001
 y <- cat_i[cat] + alpha * x + rnorm(n*k, 0, sigma)
 plot(x, y)

 # simulate missing data in a perfectly balanced way
 y[ c(1:10, 100 + 1:10, 200 + 1:10, 300 + 1:10, 400 +1:10)] <- NA

 m1 <- lm(y ~ x)
 m3 <- lme(y ~ x, random = ~ 1|cat, na.action = na.omit)

 round(digits=7,fixef(m3)) ==  round(digits=7, coef(m1)) #Look what happend now...
 #(Intercept)           x
 #       TRUE        TRUE

You are marginally misguided by the perfect design of your original experiment. When you inserted the NA's in a non-balanced away you changed the pattern of how much "strength" could the individual subjects borrow from each other.
In short the differences you see are due to shrinkage effects and more specifically because you distorted your original perfectly-balanced design with non-perfectly-balanced missing values.
Ref 1: Douglas Bates lme4:Mixed-effects modeling with R, pages 71-72


Frequentist probability: Can we prove mathematically what we are setting probabilities equal to, or are they just assumptions/definitions?

Question: Just as an example, let's say I am modeling the rolling of a die.
We can use the frequentist definition of probability to define a probability of an event, say rolling a 6, as the $\lim_{n\to\infty}$$\frac{n_6}{n}$, where n is the total number of rolls and $n_6$ is the number of times we obtain a 6.
I usually then see a logical conclusion that, ok this number will obviously be 1/6, in other words, if we roll a die (infinitely) many times, we would get 6 1/6 of the time. So we define P(6) = 1/6.
I am not questioning this logic -- this obviously makes common sense to me. However what I am wondering is -- we theoretically do not know this to be true? i.e., we cannot roll a die infinitely many times. Then would it not be possible that the true limit becomes something else? Basically, are we just logically deducing this to be true (or colloquially, 'as good as true' for our purposes) and defining this to be the probability, or is there actually a mathematical proof deeper in probability theory/statistics that would allow us to draw a conclusion of 1/6 based on the starting assumptions?
Comment: You might benefit from a look at [Can we think of a probability in both the classical and subjective sense simultaneously?](https://stats.stackexchange.com/questions/332026/can-we-think-of-a-probability-in-both-the-classical-and-subjective-sense-simulta/332218#332218)
Comment: David J. Blower has written extensively(!) on this matter, and many related questions. You can download his books from www.bayesinaction.nl. I suggest that you explore his ideas by first reading the sections "Connections to the Literature."
Comment: Here is an approach to motivating probability via [Cox's theorem](https://en.wikipedia.org/wiki/Cox%27s_theorem): [*One Probability to Rule them All?*](https://www.youtube.com/watch?v=HCG57e7Ogv8).
Comment: Persi Diaconis have thought deeply about this https://www.youtube.com/watch?v=xit5LDwJVck
Answer: You are correct, the assumption of equal probability on a dice roll is a heuristic argument, not to do with science at all. In an experimental setting, we (frequentists) define probability according to the law of large numbers. We therefore concede it's not possible to experimentally obtain such a value, and then we use a pragmatic assumption as to what it is.
A few hundred tosses would usually convince us that 1/6 is a reasonable assumption. Yet we don't actually believe the event probabilities for events {1, 2, 3, 4, 5, 6} to be exactly equal. They are only practically equal. Similarly, no two dice are identical, and if you did the required experimentation - rolls on the order of billions if not trillions to even determine that roll probabilities are not equal - the dice would deform or degrade from use.
Comment: Perhaps interesting: 20000 rolls of two dice and the non-uniformity of the outcomes [here](https://www.lesswrong.com/posts/zd89utY4afA59p58k/wolf-s-dice)
Answer: The underlying argument for $\frac16$ is essentially based on symmetry of an ideal cube, from which you could argue that you can exploit the various symmetries of faces, edges and vertices to be able to interchange the face-labels without changing the relative outcome probabilities. (You would also need assumptions about uniformity in the physical composition of the die.)
It's a logical argument that is *not actually true of any physical die, since physical dice are subject to imperfect manufacturing processes; they are not exactly cubic (though you can get away with less symmetry than that of a cube, they don't attain that less-demanding symmetry either). The long run frequency will typically show up as some level of unequal probability; the best you could perhaps hope for is you could not distinguish a die from a fair die within the lifetime of the die (many thousands of rolls, perhaps).
Casino dice are manufactured very carefully and are typically so close to fair  that you might not be able to readily distinguish their probabilities from uniform in even tens of thousands of rolls (by which time the dice would start to be altered by the repeated throwing), but dice used in some of my boardgames and tabletop roleplaying games are not. I have two wooden dice in my Settlers of Catan game that manage to roll an exceptionally high number of 7's (to the extent that it makes the game pretty much unplayable with those dice, since rolling a 7 has a very particular consequence). I also have a pink and black 20-sided die that turns right angles when you roll it; its bias toward 4 (among other outcomes) is strong enough that you can pick it up quickly, for all that the die is visually very close to symmetric. Presumably there's inconsistent density of material inside the die.
More generally, any model for a process (Bernoulli, Poisson, etc, not just ones based on symmetry arguments) are just that $-$ models. That is, they're approximations of some real process, not exact descriptions.
They abstract away details that you hope are not substantial in their impact, but in practice enough data will reveal imperfections. Take, for example, what is typically treated as one of the most ideal examples we know $-$ treating the number of clicks in a classical Geiger counter for detecting ionizing radiation when pointed at (say) a rock as a homogeneous Poisson process. It isn't quite an accurate model. For one thing, the absolute and relative amounts of different radioactive elements changes over time, and the counter itself doesn't produce two clicks for particles that are very close together in time. So we don't have an actual homogeneous Poisson process for the observed clicks, albeit its typically an excellent approximation.
Since essentially none of these models are actually true, we cannot prove them in the sense of applying to the physical process we observe, even though they do follow from their axioms (/assumptions) and enough data will reveal the failure of assumptions (i.e. a long-enough but very much finite run, rather than the technical sense of "in the long run").
This is not a problem as long as the answers we obtain are close enough for our specific purposes. For a physical die, it won't actually have a probability to roll a $6$ of $\frac16$; but that's not especially important, as long as it's close enough that the model will yield answers that are close enough for our specific purposes.
As George Box elegantly put it "Remember that all models are wrong; the practical question is how wrong do they have to be to not be useful".
Answer: It sounds like you are asking about the fundamental difference between probability and statistics.

In probability, we assume a probability model to be true and we use this to answer questions about specific outcomes.
In statistics, we acknowledge that there are things we don't know about the probability model, and we use data to try to learn the underlying distribution.

To use a die roll as an example, in probability we assume a model for the die, such as
$$p(x) = \begin{cases}
\frac{1}{6}, & x\in \{1,2,3,4,5,6\} \\
0, & \text{otherwise}
\end{cases}$$
Of course, this isn't the only valid model. If you have a weighted die, perhaps the model will look like
$$p(x) = \begin{cases}
\frac{1}{2}, & x=1 \\
\frac{1}{10}, & x\in \{2,3,4,5,6\} \\
0, & \text{otherwise}.
\end{cases}$$
In either case, we can answer questions like the following:

What is the probability that a roll of the die is at most 2?
What is the probability that the sum of 3 independent rolls is at least 3?
etc.

In statistics, we start by parameterizing a model (note: there are other ways to do statistics, but this is a common and straightforward approach) for the result of the die
$$p(x) = \begin{cases}
p_x, & x\in \{1,2,3,4,5,6\} \\
0, & \text{otherwise},
\end{cases}$$
subject to $\sum_{x=1}^6 p_x = 1$. The next step is to collect data, say $x_1, x_2, \ldots, x_n$ by rolling the die $n$ times and recording the result. This let's us answer questions about the "true" probability model itself.

Is the "fair die" model consistent with the data?
What value(s) for $p_1$ is (are) most likely?
Given our uncertainty about the model, what can we say about the probability questions discussed above?
Answer: The fact that there exists a fixed probability (equivalent to the limiting relative frequency of the outcome) for each outcome on the die follows from an assumption of exchangeability using a famous mathematical result called the "representation theorem" (see related answers here, here and here).  Essentially, this says that if the outcomes on the die rolls are exchangeable (i.e., the order of a result doesn't affect the overall probability) then those outcomes are independent conditional on some underlying fixed probability for each outcome (which is then equal to the limiting relative frequency).  If exchangeability does not hold then there is not a fixed probability for an outcome (see related answer here looking at a coin-flip instead of a die roll).
Absent some strong theoretical reason or empirical analysis, we cannot know that the die roll is "fair" and so the assertion that the probability of a six is $1/6$ is just an assumption.  In fact, there are some cases of statistical analysis which allows for some possibility of bias in the allegedly "fair" mechanism.  This was examined in a series of papers on the "gambler's fallacy" and broader methods of binomial prediction under the Bayesian paradigm (see O'Neill and Puza 2005; O'Neill 2012; O'Neill 2015).  Of course, if we are satisfied that the outcomes of the tosses are exchangeable then we can toss the coin a large number of times to estimate the probability of getting a six, but the idea that this probability is exactly $1/6$ is highly specific and is typically just an assumption.