Is sforzando on two beats sensible? Are there alternatives?

Question: For a piano piece, I want a sforzando (which I interpret as a strong accent on every note in that beat) to be applied to two beats. Until now I have notated it like this, with sffz between the notes:

I think this is understandable, if admittedly non-standard. However this becomes less elegant to write when the division between those notes falls on the border of a bar:

I'm unsure as to workable alternatives. Writing subito ff and subito mf afterwards feels overwritten. Just replacing it with > accent marks seems somehow weaker, and it would require three marks on the left-hand notes (which should be staccato like the others, and I gave them marcato too because I wish the bass to be slightly dominant).
EDIT: two sforzandos after each other also works, though it looks a bit busy.
Comment: Is there some reason you can't just place two *sffz*s?
Comment: @Aaron Fair point, I suppose I could, but I don't think I have seen two of those in a row before. I thought that they implied immediate decrease in volume right afterwards, like *fp*?
Comment: There's not much difference between sfz and an accent mark, right?
Comment: @ToddWilcox In my understanding sfz is stronger, sffz even more so, plus the mark applies to the whole beat, regardless of voices or (in the case of piano) staves.
Comment: @KeizerHarm - Wait, sfz and sffz applied to the whole beat? In my experience, both of them apply to *that note only*, and I swear I've seen multiple sfz's in a row.
Comment: @Dekkadeci To be sure I'm not miscommunicating, let me clarify that by "applies to beat" I mean "every note hit in that exact moment in time". Basically I mean that in piano score the sffz in the middle applies to left and right hand both, like dynamic marks do.
Comment: @KeizerHarm - Given your "Until now I have notated it like this, with sffz between the notes", I thought that, by "applies to the whole beat", you meant "applies to the entire length of one beat as defined by the time signature". By "that note only", I did mean all notes played in that exact moment of time by that instrument (this means grace notes don't get affected by the sfz).
Comment: @Dekkadeci Good to have cleared that up :) I understand that sffz between notes is non-standard and I did not mean to imply that that was regular, it was just a stopgap measure for want of a better alternative. Now it looks like there isn't one except two sffz's in a row.
Answer: How to mark the passages
Sforzando and related markings apply only to individual notes, so the single sffz on two adjacent notes within the same measure is technically incorrect, and I personally would find it confusing. Consider a sub ff followed by a separate marking to return to the prevailing dynamic. That would be unambiguous, especially with the other articulation marks present.
Where the two notes are in separate measures, two sffz markings will be aesthetically fine and clear to read; however, for clarity use the same markings in both parts of the score. That is, if you use sffz in one place, use it in both; likewise with sub ff; but use one or the other, not both.
Duration of sforzando and related markings
Regarding the sffz applying to a full beat — this is not a rule or guideline I've encountered, nor can I find evidence to suggest that interpretation. Here is what Wikipedia has to say on the subject:

Subito can be used to mark suddenly louder changes, like subito forte sf, or subito fortissimo sff, however in these cases it's usually only used to add a particular amount of accent to one note or chord. If subito is used to note a sudden change to an entire louder passage, something like sub. f or sub. ff should be used to leave out any ambiguity.

Forzando/forzato indicates a forceful accent and is abbreviated as fz. To emphasize the effect, it is most often preceded with subito as sfz (subito forzato/forzando, sforzando/sforzato). How these should be interpreted and played in the music is up to the judgement of the performer, but a rule of thumb is that a forzato/forzando can be considered as a variation on marcato while subito forzando/forzato can be considered a variation on marcato with added tenuto.

The Oxford Online Music Dictionary doesn't comment on the duration of a sfortissimo, but Dolmetsch backs up the single-note/chord idea.

sf.: abbreviation for sforzato, applied to a single accented note

Dolmetsch entries for related terms aren't specific about duration, but the above seems to be the ruling entry.
Comment: Thank you for your elaborate answer. The duration part is entirely new to me, and I had indeed always assumed that it applied to a beat (per instrument) rather than a note/chord, just like any dynamic letter mark (*pp, mf*, etc
). Weirdly, the first example of *sf* in piano music I came across (Pictures at an Exhibition 9. Baba Yaga) actually uses *sf* in both ways.
Answer: If you want sffz on two notes, I'm afraid you have to write it twice.
Some would say sffz and a staccato dot were contradictory.
An alternative might be ff with an accent and tenuto line on each note.


How to make Valgrind debugger step through a program

Question: Good morning, I am trying to use the Valgrind debugger to step through a program.
My valgrind command line is valgrind -tool memcheck --leak-check=full --db-enable=yes ./MatchUpAcurate.exe.
I am using valgrind-3.5.0 on Centos Linux release 5.5 with gdb version 7,0.1-23.el5_5.2.
I enter Yes when valgrind asks the question Attach to Debugger. Then, the valgrind debugger returns with: 4428: return new tuple2<int,A>(2, i++, p->next());
When I try to use the gdb step or continue command, valgrind says
[New Thread 0x410fd10 (LWP 6548] Cannot find user-level thread for LWP 6551: generic error.
When I try to use valgrind --single-step=yes debugger option on the valgrind command-line, valgriind says Bad option aborting.
Could any valgrind users show me how  to step through C++ source  code or continue through a program? Thank you.
Comment: I am not using any multithreading in the program I am trying to debug. Thank you.
Comment: Are you by chance trying to debug a 32-bit application on a x86_64 machine? if so, then you might be interested in [this](http://sourceware.org/bugzilla/show_bug.cgi?id=9069).
Comment: @diverscuba, Thank you for your reply. I talked to a valgrind developer and the developer told me how to upgrade valgrind 3.5 to a valgrind 3.6.0 debugger.
Answer: I asked the valgrind developers how to create a valgrind debugger. Here is what they said;

Download the 3.6.0 source files from the valgrind website.
Then you have to apply the patch which is in the bug 214909.
Once properly compiled, you launch your application like this:
valgrind --vgdb=yes --vgdb-error=0 ./prog

and then in another window:
gdb ./prog
target remote | vgdb

Do not start an external gdbserver : what the patch does is to integrate a gdbserver inside valgrind.
This gdbserver integrated inside valgrind is activated by the --vgdb=yes.
Answer: You can also get vgdb in the 3.7.0 release. From the release notes:

GDB server: Valgrind now has an embedded GDB server.  That means it
is possible to control a Valgrind run from GDB, doing all the usual
things that GDB can do (single stepping, breakpoints, examining
data, etc).  Tool-specific functionality is also available.  For
example, it is possible to query the definedness state of variables
or memory from within GDB when running Memcheck; arbitrarily large
memory watchpoints are supported, etc.  To use the GDB server, start
Valgrind with the flag --vgdb-error=0 and follow the on-screen
instructions.

There's more info in the valgrind online manual.


Ajustar valor de centavos

Question: Eu tenho uma variável com a seguinte informação: 100.3
Qual a alternativa melhor para tornar 100.3 para 100.03?
Comment: Isso não faz muito sentido, pelo menos não é arredondamento, isto muda o valor completamente e faz o oposto de arredondar.
Comment: Nós entendemos o que vc quer fazer, só estamos achando estranho a necessidade de fazer isso, pois sem um contexto maior, parece ser uma operação sem sentido. *Talvez* vc esteja tentando resolver um problema e pensou que esta solução é o melhor jeito, mas pode ser que exista uma solução melhor, e por isso pedi que editasse colocando um pouco mais de contexto (em outras palavras, posso até estar enganado, mas *parece* um [problema XY](https://pt.meta.stackoverflow.com/q/499/112052)). Não leve a mal nossos questionamentos, todos estão tentando ajudar da melhor forma possível.
Comment: para isso so precisa fazer n=n.replace(".",".0"); , mas sem sentido essa operacao
Comment: Por que precisa disto? Parece não fazer sentido e provavelmente é a solução errada.
Comment: @Josimara qual a dificuldade de responder as perguntas que nós fizemos para você?
Comment: Perceba que `100.3` e `100.03` são valores completamente diferentes (se fossem valores monetários, por exemplo, seria uma diferença de 27 centavos, bem longe de ser um "arredondamento"). Poderia **[edit]** a pergunta e deixar um pouco mais claro que está tentando fazer e se possível colocar mais alguns exemplos de números e seus respectivos resultados? Talvez com um pouco mais de contexto a gente consiga entender melhor o problema.
Comment: Até da pra entender o que quer fazer, mas não está dando pra entender um exemplo prático pois é completamente diferente `168.9` de `168.09`. Não está buscando `168.90`?
Comment: @Renan basicamente isso, não estou sabendo explixar poque nunca trabalhei com esse tipo de valor antes...
Comment: @Josimara Eu entendo perfeitamente que nem sempre é fácil explicar um problema. Por outro lado, vc tem que entender que se a pessoa não consegue se expressar corretamente, nem todos irão entender o que ela está querendo dizer, e consequentemente pedirão mais detalhes e esclarecimentos. Faz parte... :-)
Comment: @Josimara é muito simples dizer porque precisa fazer isto, você está evitando porque provavelmente esta é uma solução errada para o problema. E sós estamos querendo, infrutiferamente, ajudar a resolver o real problema.
Comment: @Maniero Ok, qual a melhor alternativa se eu tiver que tomar essa solução?
Comment: Caras, estou trabalhando com um valor, $186.9, queria retornar, 186.09 qual a dificuldade de entender a pergunta?
Comment: @Maniero acabei de responder.
Comment: Onde? Não achei essa resposta.
Comment: @hkotsubo entendo, mas vocês tem que saber que nem sempre uma pessoa vai conseguir se expressar corretamente se esta vindo a um fórum pegar um help
Comment: @Maniero Psé tinha um erro, primeiro o erro começo comigo mesmo... mas achei uma solução, https://pt.stackoverflow.com/questions/251509/completar-casas-decimais-00-javascript
Comment: @Josimara Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: É matemática pura (não precisa fazer gambiarras com string, não faz sentido realizar conversões caras que faz mais de uma alocação de memória sem necessidade, fora que a semântica ser incorreta, as pessoas precisam parar de fazer o que apenas funciona e entender o que está fazendo e tomar decisões corretas). Seria isto, apesar de não fazer sentido:

var valor = 100.3;
var inteiro = Math.trunc(valor);
console.log(inteiro + ((valor - inteiro) / 10));

Coloquei no GitHub para referência futura.
Comment: no lugar do Math.trunc pode ser usado parseInt() que da no mesmo.
Comment: @HudsonPH eu só faço gambiarras onde tem vantagem, se a semântica é toda de valores não vou envolver uma função que foi feita pra lidar com *string* e por uma falha filosófica da linguagem coincidentemente funciona. https://i.stack.imgur.com/jgk8Q.png
Comment: @Josimara pode ser, mas sua pergunta não tem informações sobre isto, não temos como saber o que quer. Desde o começo suspeitávamos que ela estava errada.
Comment: Já usei com matemática, achei que encontraria algo mais profundo, mas valeu!
Comment: @Maniero apenas um exemplo, afinal trunc é apenas (n - n % 1) e resto validacoes
Comment: Na verdade oque eu precisava era de um valor.toFixed(2), pode me corrigir se a função tiver errada...
Answer: So fazer isso:

var n = 100.3;
n=n.toString().replace(".",".0");
console.log(n);

Ajustar valor de centavos


ModuleNotFoundError: No module named 'financials_api_get' when trying to run folder location

Question: I have a folder directory that looks as such:
-- show_case
  --airflow
    --dags
      fundamental_data_pipeline.py
  __init__.py
  financials_api_get.py

I am trying to run a function get_fundemental_data from financial_api_get.py within fundamental_data_pipeline.py but I get an import error.
My file fundamental_data_pipeline.py looks like this:
sys.path.insert(1, Path(__file__).resolve().parent.parent.parent)
print(Path(__file__).resolve().parent.parent.parent)
from financials_api_get import get_fundemental_data

A print of the path prints show_case but I still get
ModuleNotFoundError: No module named 'financials_api_get'

Why doesn't this work?
EDIT
I have an __init__.py file that looks as such:
from financials_api_get import get_fundemental_data

Comment: you have char `s` in word `financials` in `from financials_api_get ...` but filename is without `s` - `financial_api_get.py`
Comment: @furas Sorry was a typo in the question
Comment: maybe it treats it as internal module and it needs file `__init__.py`. Do you get `show_case` or `/full/path/to/show_case` ?
Comment: @furas Edited the question as I have an init file that I forgot to add in the original question. The error is: "/full/path/to/show_case\airflow\dags\fundamental_data_pipeline.py", line 11, in
    from financials_api_get import get_fundemental_data
ModuleNotFoundError: No module named 'financials_api_get'
Comment: you may check if file really exists `print( os.listdir( Path(__file__).resolve().parent.parent.parent ) )`
Comment: I tested code and accidently get I found that I have the same problem when I have `symlink` in path (on Linux). I need `os.path.realpath()` to get real path. `p = os.path.realpath( Path(__file__).resolve().parent.parent.parent )` and later I can do `sys.path.insert(0, p)` and it works.
Comment: when I use `print()` to see `Path(__file__).resolved()` then I see it create wrong path.
Answer: Problem is Path because sys.path expects only strings.
If you run print(sys.path) then you should see [Path(...), ...]
So you may need str()
p = Path(__file__).resolve().parent.parent.parent

sys.path.insert(0, str(p) )

or .as_posix()
p = Path(__file__).resolve().parent.parent.parent

sys.path.insert(0, p.as_posix() )


Não consigo ler coluna no pandas

Question: Eu tenho esse Dataframe:
             Nome          CPF      ...        Senha          Cargo
0     Silvio José  10575674451      ...        12345  Administrador
1  Carlos Alberto  10767764330      ...        12345  Administrador
2  Maria Madalena  23323234343      ...        12345     Supervisor
3    Caio Bezerra  10992329221      ...        12345     Supervisor
4  Mateus Alencar  10732393213      ...        12345     Supervisor

Quando utilizo esse comando pessoas_frame['CPF'] ele imprime a coluna normalmente. Mas quando utilizo o comando pessoas_frame['Idade'] ele manda uma mensagem: KeyError: 'Idade'
Agora se eu usar o comando pessoas_frame.iloc[:, 2] ele imprime a coluna normalmente:
0    23
1    21
2    20
3    23
4    22
Name: Idade , dtype: int64

Answer: Eu não sei de onde você tirou essas colunas, mas parece que a coluna do seu dataframe está com o nome de 'Idade ' e não 'Idade'.
Tente utilizar o comando:
pessoas_frame['Idade ']

Não consigo ler coluna no pandas


Ocultar todos os conteudos diferentes do selecionado

Question: Criei um código em javascript que oculta todas as divs diferentes do valor que foi selecionado no select.
$(".filter-target").change(function() {
  var target = $(this).val();
  if (target == 0) {
      $('[data-target]').removeClass('hidden');
      return;
  }
  var self = $('[data-target="'+target+'"]');
  $('[data-target]').not(self).toggleClass('hidden');

});
Quando eu seleciono a opção que eu tenho exibida as outras se ocultam normalmente, porém se eu for testando as demais elas começam a ficar bagunçadas e não obedecem a ordem de "ocultar todos os que não forem x", as que eram para aparecer desaparecem e virse e versa.
o que pode estar errado?
Comment: Seria interessante ter um exemplo no Snippet.
Comment: @nicematt, quando eu digo que fica bagunçado significa que os que não eram para aparecer aparecem, os que eram pra aparecer desaparecem, adicionei mais conteudo para melhorar a pergunta, obg.
Comment: "elas começam a ficar bagunçadas e não obedecem a ordem de "ocultar todos os que não forem x", isso não está muito revelante.
Comment: @WallaceMaxters o conteudo é dinamico em um plugin que estou usando `(fullcalendar)`, fica dificil criar um snippet.
Answer: O que notei foi que:

você esqueceu de exibir os elementos iguais à self;
e que você está sempre alternando a classe "hidden", o que pode pode acabar fazendo elementos que eram para ser invisíveis como "visíveis". Você poderia tentar adicionar em vez.

var $self = $('[data-target="'+target+'"]');

/* torna os elementos iguais visíveis (caso invisíveis) */
$self.removeClass('hidden');

/* torna os elementos diferentes invisíveis (caso visíveis) */
$('[data-target]').not($self).addClass('hidden');

Observação: não posso afirmar, até porque não uso jQuery, mas acho que o método addClass e removeClass já resolvem o problema de várias classes do mesmo nome em um elemento.


type 'Null' is not a subtype of type 'String' flutter on api call

Question: Im using a service to create api from xml. This is my model file:

// To parse this JSON data, do
//
//     final economylistXml = economylistXmlFromJson(jsonString);

import 'dart:convert';

EconomylistXml economylistXmlFromJson(String str) => EconomylistXml.fromJson(json.decode(str));

String economylistXmlToJson(EconomylistXml data) => json.encode(data.toJson());

class EconomylistXml {
  EconomylistXml({
    required this.haberler,
  });

  Haberler haberler;

  factory EconomylistXml.fromJson(Map<String, dynamic> json) => EconomylistXml(
    haberler: Haberler.fromJson(json["haberler"]),
  );

  Map<String, dynamic> toJson() => {
    "haberler": haberler.toJson(),
  };
}

class Haberler {
  Haberler({
    required this.haber,
  });

  List<Haber> haber;

  factory Haberler.fromJson(Map<String, dynamic> json) => Haberler(
    haber: List<Haber>.from(json["haber"].map((x) => Haber.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "haber": List<dynamic>.from(haber.map((x) => x.toJson())),
  };
}

class Haber {
  Haber({
    required this.haberManset,
    required this.haberResim,
    required this.haberLink,
    required this.haberId,
    required this.haberVideo,
    required this.haberAciklama,
    required this.haberMetni,
    required this.haberKategorisi,
    required this.haberTarihi,
    required this.mansetResim,
    required this.izlesId,
    required this.yorumSay,
    required this.okunmaadedi,
    required this.anasayfamanset,
    required this.kategorimanset,
  });

  String haberManset;
  String haberResim;
  String haberLink;
  String haberId;
  String haberVideo;
  String haberAciklama;
  String haberMetni;
  HaberKategorisi? haberKategorisi;
  String haberTarihi;
  String mansetResim;
  String izlesId;
  String yorumSay;
  String okunmaadedi;
  String anasayfamanset;
  String kategorimanset;

  factory Haber.fromJson(Map<String, dynamic> json) => Haber(
    haberManset: json["haber_manset"],
    haberResim: json["haber_resim"],
    haberLink: json["haber_link"],
    haberId: json["haber_id"],
    haberVideo: json["haber_video"],
    haberAciklama: json["haber_aciklama"],
    haberMetni: json["haber_metni"],
    haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
    haberTarihi: json["haber_tarihi"],
    mansetResim: json["manset_resim"],
    izlesId: json["izles_id"],
    yorumSay: json["yorumSay"],
    okunmaadedi: json["okunmaadedi"],
    anasayfamanset: json["anasayfamanset"],
    kategorimanset: json["kategorimanset"],
  );

  Map<String, dynamic> toJson() => {
    "haber_manset": haberManset,
    "haber_resim": haberResim,
    "haber_link": haberLink,
    "haber_id": haberId,
    "haber_video": haberVideo,
    "haber_aciklama": haberAciklama,
    "haber_metni": haberMetni,
    "haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
    "haber_tarihi": haberTarihi,
    "manset_resim": mansetResim,
    "izles_id": izlesId,
    "yorumSay": yorumSay,
    "okunmaadedi": okunmaadedi,
    "anasayfamanset": anasayfamanset,
    "kategorimanset": kategorimanset,
  };
}

enum HaberKategorisi { EKONOMI, DNYA }

final haberKategorisiValues = EnumValues({
  "Dünya": HaberKategorisi.DNYA,
  "Ekonomi": HaberKategorisi.EKONOMI
});

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String>? reverseMap;

  EnumValues ( this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap!;
  }
}

and this is file where i call api

import 'package:flutter/material.dart';
import 'package:halkaarzhisseler/models/apis/economy_api.dart';
import 'package:http/http.dart' as http;

import '../models/apis/economy_xml.dart';
import 'haberdetail.dart';

class Economy extends StatefulWidget {
  const Economy({Key? key}) : super(key: key);

  @override
  State<Economy> createState() => _EconomyState();
}

class _EconomyState extends State<Economy> {
  ScrollController? controller;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://v1.nocodeapi.com/miktadtahir/xml_to_json/htvLvoPDCwIEyTxa?url=https://www.trthaber.com/xml_mobile.php?tur=xml_genel&kategori=ekonomi&adet=20&selectEx=yorumSay,okunmaadedi,anasayfamanset,kategorimanset');
  var counter;
  EconomylistXml? haberResult;

  Future callHaber() async {
    try{

      final response = await http.get(url);

      if(response.statusCode == 200){
        var haberler = economylistXmlFromJson(response.body);

        if(mounted);
        setState(() {
          haberResult = haberler;
        });
        return haberler;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    callHaber();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: Text(
            'Ekonomi Haberleri'
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: counter != null ?

          ListView.builder(
              itemCount: counter,
              itemBuilder: (context, index){
                return Card(
                  child: ListTile(
                    title: Text(haberResult?.haberler.haber[index].haberManset??""),
                    leading: CircleAvatar(
                      backgroundImage: NetworkImage(haberResult?.haberler.haber[index].haberResim??""),),

                    onTap: () => Navigator.push(
                      context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.haberler.haber[index].haberMetni??"", title: haberResult?.haberler.haber[index].haberManset??"",image: haberResult?.haberler.haber[index].haberResim??"")),),
                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}

/*class Economy extends StatefulWidget {
  const Economy({Key? key}) : super(key: key);

  @override
  State<Economy> createState() => _EconomyState();
}

class _EconomyState extends State<Economy> {
  ScrollController? controller;
  final scaffoldKey = GlobalKey<ScaffoldState>();
  final url = Uri.parse('https://api.collectapi.com/news/getNews?country=tr&tag=economy&padding=10');
  var counter;
  Economylist? haberResult;

  Future callHaber() async {
    try{
      Map<String, String> requestHeaders = {
        'Content-Type': 'application/json',
        'Authorization': 'apikey 3fPhNZfVyrl8dOAkT86niI:3g2OzN57bil8vArOdVE3ka'
      };
      final response = await http.get(url,headers:requestHeaders);

      if(response.statusCode == 200){
        var result = economylistFromJson(response.body);

        if(mounted);
        setState(() {
          counter = counter = result.result.length;
          haberResult = result;
        });
        return result;
      } else {
        print(response.statusCode);
      }
    } catch(e) {
      print(e.toString());
    }
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    callHaber();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        automaticallyImplyLeading: false,
        title: Text(
            'Ekonomi Haberleri'
        ),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: counter != null ?

          ListView.builder(
              itemCount: counter,
              itemBuilder: (context, index){
                return Card(
                  child: ListTile(
                      title: Text(haberResult?.result[index].name??""),
                leading: CircleAvatar(
                backgroundImage: NetworkImage(haberResult?.result[index].image??""),),

                      onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) => HaberDetailScreen( subtitle: haberResult?.result[index].description??"", title: haberResult?.result[index].name??"",image: haberResult?.result[index].image??"")),),
                  ),
                );
              }) : Center(child: CircularProgressIndicator(

          )),
        ),
      ),
    );

  }
}

 */

I'm getting this error on console : type 'Null' is not a subtype of type 'String' and CircularProgressIndicator working continuously. How can i fix this?
Thanks for your help
Comment: @YeasinSheikh  when i check the response i see that izlesid and haberviod sometimes returns null. how can i add this to model?
Comment: Can you include your json response
Comment: In your `Haberler` class are all attributes not nullable. This leads to the mentioned error, if there is one of your String attributes null in your response. Check the response and search for the null value.
Comment: @MCB izlesid and habervideo sometimes returns null
Comment: Better make fields nullable or while reading data doing null check and providing default value on it
Answer: The handle null value it is better to make variable nullable data on entities
class Haber {
  String? haberManset;
  String? haberResim;
  String? haberLink;

Or provide empty string on null case while reading JSON
  haberVideo: json["haber_video"]??"", //this
  izlesId: json["izles_id"]??"",

Comment: Only loads CircularProgressIndicator no error in console or anywhere. How it could be? –
Comment: Do you get any error message on `print(e.toString());`
Comment: Nothing happens. just CircularProgressIndicator working
Comment: Can you try using `FutureBuilder`
Comment: Can you write code sample when I ask a question?
Comment: @Yasin Sheikh I mean if i ask this as a new question
Comment: I will try give a try, also it would be easier for others if you could include JSON response as well or the API if it is public
Answer: You can make response != null to the top. And check the debug console for the response. Probably you get some other exception like socket exception.
 try{

      final response = await http.get(url);
if(response != null){ //this line you need to add
 if(response.statusCode == 200){
        var haberler = economylistXmlFromJson(response.body);

        if(mounted);
        setState(() {
          haberResult = haberler;
        });
        return haberler;
      } else {
        print(response.statusCode);
      }
}else{
//stop indicator in here if response is null
//you're code in here
}

    } catch(e) {
      print(e.toString());
    }

I hope this helps
Answer: Change String to String? at not required fields:
class Haber {
  Haber({
    required this.haberManset,
    required this.haberResim,
    required this.haberLink,
    required this.haberId,
    required this.haberVideo,
    required this.haberAciklama,
    required this.haberMetni,
    required this.haberKategorisi,
    required this.haberTarihi,
    required this.mansetResim,
    required this.izlesId,
    required this.yorumSay,
    required this.okunmaadedi,
    required this.anasayfamanset,
    required this.kategorimanset,
  });

  String haberManset;
  String haberResim;
  String haberLink;
  String haberId;
  String? haberVideo; //<-- here
  String haberAciklama;
  String haberMetni;
  HaberKategorisi? haberKategorisi;
  String haberTarihi;
  String mansetResim;
  String? izlesId; //<-- and here
  String yorumSay;
  String okunmaadedi;
  String anasayfamanset;
  String kategorimanset;

  factory Haber.fromJson(Map<String, dynamic> json) => Haber(
    haberManset: json["haber_manset"],
    haberResim: json["haber_resim"],
    haberLink: json["haber_link"],
    haberId: json["haber_id"],
    haberVideo: json["haber_video"],
    haberAciklama: json["haber_aciklama"],
    haberMetni: json["haber_metni"],
    haberKategorisi: haberKategorisiValues.map[json["haber_kategorisi"]],
    haberTarihi: json["haber_tarihi"],
    mansetResim: json["manset_resim"],
    izlesId: json["izles_id"],
    yorumSay: json["yorumSay"],
    okunmaadedi: json["okunmaadedi"],
    anasayfamanset: json["anasayfamanset"],
    kategorimanset: json["kategorimanset"],
  );

  Map<String, dynamic> toJson() => {
    "haber_manset": haberManset,
    "haber_resim": haberResim,
    "haber_link": haberLink,
    "haber_id": haberId,
    "haber_video": haberVideo,
    "haber_aciklama": haberAciklama,
    "haber_metni": haberMetni,
    "haber_kategorisi": haberKategorisiValues.reverse[haberKategorisi],
    "haber_tarihi": haberTarihi,
    "manset_resim": mansetResim,
    "izles_id": izlesId,
    "yorumSay": yorumSay,
    "okunmaadedi": okunmaadedi,
    "anasayfamanset": anasayfamanset,
    "kategorimanset": kategorimanset,
  };
}

Comment: Only loads CircularProgressIndicator no error in console or anywhere. How it could be?
Answer: Try this
 class Haber {
      String haberManset = "";
      String haberResim = "";
      String haberLink = ""

or
  haberVideo: json["haber_video"].toString(),
  izlesId: json["izles_id"].toString(),


Escape variables in command prompt cmd

Question: I set my variable like this:
SET Ant="%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"

:: Set Path variable
setx PATH "%Ant%" /m

Then, the result for the path variable is :
C:\Users\Ruben\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin

As we can see, environnement variables are expanded.
I would like them not to be expanded to set my path variable like this:
%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin

Is there a way to not expand environnement variables ?
Comment: And the question is?
Comment: @Falcon Momot I've edited the question to improve it
Answer: This do the trick on my Win7 :
SET Ant=^%HOMEDRIVE^%^%HOMEPATH^%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin

setx PATH "%Ant%" /m

Let's check if everything is ok :
echo %Ant%
%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin

set | findstr Ant
Ant=%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin

Everything seems ok :)
To makes it work i had to :

Escape % characters using carets (^).
Remove double quotes.

Escape variables in command prompt cmd


Binomial distribution to approximate 90 % successes

Question: A student is taking a multiple choice test where each question has four options for an answer. The student mastered mastered 70% of the material. Assume this means that the student has a 0.7 chance of knowing the correct answer to a random test question. On the other hand, if the student does not know the answer to the question, she randomly selects among the four answer choices. Finally, assume that this holds for each question independent of the others.
What is the probability that a specific question is answered correctly?
P(correct) = 0.7+0.25*0.3 = 0.775
Suppose that at least 90% of the choices has to be correct to pass the test.
If the test has 30 questions, approximate the probability that the student
will get at least 90% of the choices correct?
I tried using the binomial distribution to approximate this:
P(90% correct)=$\binom{30}{27} 0.775^{27}  (1-0.775)^{30-27}$
$\binom{30}{27} = (30!)/((27!)((30-27)!)) = 4060 $
This gives me 0.047 as an result.
Is this the right way of approximating the probability that the student will get at least 90% of the choices correct? 4,7%
Comment: Though it seems you have a good idea of whats going on, remember the question asks for *at least* 90 percent
Comment: Oh, that's right. So I reverse at find the binomial distribution of 10% failures. Matlab = binocdf(3,30,0.225) = 0.0696 or 6,96%
Answer: At least $90$ per cent correct means that the number of correct answers could be $27$, $28$, $29$ or $30$. So to be exact, you're looking for $P(\ge90 \% \, correct)$, which is the sum of probabilities of the four cases computed the way you did for $27$.
Answer: Set up our distribution:
"X has 30 trials, with the probability of success being 0.775".

$ X \sim B (30, 0.775) $

Now for our probability calculation (with 90% = 27 score):
"The probability of X being at least 27, is 1 subtract the probability of X being less than 27".
We do this because most conventional calculators use $ P(X<x) $ as the cumulative inequality, so we have to convert the inequality into this form.

$ P(X \ge 27) = 1 - P(X < 27) = 1 - 0.9304 = 0.0696 $

Our final answer is 6.96% chance of getting at least 27 score, or 90%.
Your answer is correct for $ P(X=27) $, not $ P(X \ge 27) $.
Comment: It makes sence but how do you find P(X<27)?


PrepareforSegue not displaying destinationviewcontroller

Question: Segue destinationviewcontroller pdfviewcontroller not displaying pageviewcontroller
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"MYSegue"]) {

    // Get destination view
    PDFViewController *pdfviewController = [segue destinationViewController];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"paper" ofType:@"pdf"];
    PageViewController *page = [[PageViewController alloc] initWithPDFAtPath:path];
    pdfviewController= page;

}
}

shows only navigation bar and backbuttonitem
and shows semantic issue incompatible pointer types assigning to pdfviewcontroller strong from pageviewcontroller strong.
Thanks for help.
Comment: possible duplicate of [Display pageviewcontroller in Segue destinationviewcontroller](http://stackoverflow.com/questions/17599528/display-pageviewcontroller-in-segue-destinationviewcontroller)
Answer: This line is wrong:

pdfviewController= page;

As the compiler tells you, the type is PDFViewController * and you're trying to assign PageViewController *.
Did you mean something like:
pdfviewController.page = page;

The segue should just do:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"MYSegue"]) {
        // Get destination view
        PDFViewController *pdfViewController = [segue destinationViewController];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"paper" ofType:@"pdf"];

        pdfViewController.path = path;
    }
}

Add some properties to the pdf view controller:
@property (copy, nonatomic) NSString *path;
@property (strong, nonatomic) PageViewController *page;

Then in the pdf view controller
- (void)viewDidLoad {
    [super viewDidLoad];

    PageViewController *page = [[PageViewController alloc] initWithPDFAtPath:self.path];
    page.view.frame = self.view.bounds;
    [self.view addSubview:page.view];
    [self addChildViewController:page];
    self.page = page;
}

Comment: i want to display pageviewcontroller in pdfviewcontroller
Comment: Ok, but what are they? Are they yours? Did you get them from github? How do you think they go together?
Comment: if you will look at my this question http://stackoverflow.com/questions/17599528/display-pageviewcontroller-in-segue-destinationviewcontroller you might understand my problem. Thanks for your time and help.
Comment: You shouldn't repost the same question again, edit the original instead.
Comment: And the other question doesn't say anything about the class definitions. Why are you trying to use 2 view controllers, what is the relationship between them supposed to be (and why isn't it encapsulated in the PDF view controller)?
Comment: Reason is that segue is already set up in the storyboard and there is no need to call presentViewController. In the pdfviewcontroller i had actual code which is this NSString *path = [[NSBundle mainBundle] pathForResource:@"Paper" ofType:@"pdf"];
PageViewController *page = [[PageViewController alloc] initWithPDFAtPath:path];
//[self presentViewController:page animated:NO completion:NULL]; if i remove last statement then it doesn't show pagevc only shows navigation bar and backitem. that is why i moved this piece of code in prepareforsegue
Comment: So why doesn't the PDF view controller still do that and then add the page view controller as a child view controller and the view as a subview?
Comment: if i use this statement [self presentViewController:page animated:NO completion:NULL]; only then it displays pagevc in pdfvc but then doesn't shows navigation bar and back item and if i remove this statement then it doesn't shows pagevc only displays navigationbar and back item
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33299/discussion-between-wain-and-user1120133)


How do I integrate Stripe credit card field with `ng-disabled` attribute of a `button`?

Question: I have a form in my page with AngularJS and Stripe JS.
    <form id="register-form" name="regForm" method="post>
    <input ng-model="reg.email" type="email" name="username">

    {{ ccErrMsg }}

    <button type="submit" ng-model="reg.btn" ng-disabled="!regForm.username.$valid>Register</button>
</form>

I want for my button to be un-clickable unless the user fills out the Stipe credit card section correctly. How do I make it so my button is disabled unless the the Stripe credit card fields are filled out correctly?
Update: Following karthick's answer gives me a new error:
angular.js:13642 TypeError: stripeService.start is not a function
    at Object.<anonymous> ((index):135)
    at Object.invoke (angular.js:4708)
    at P.instance (angular.js:10177)
    at n (angular.js:9096)
    at g (angular.js:8459)
    at angular.js:8339
    at angular.js:1782
    at m.$eval (angular.js:17378)
    at m.$apply (angular.js:17478)
    at angular.js:1780

Comment: why do you need ng-disabled? are you having any custom validations on this form?
Comment: I have other input fields the user must fill out to enable the submission button
Comment: Can you add some code or info related to that?  And what kind of validations are you doing and any extra library if any?
Comment: Updated with more context
Answer: You should use a AngularJS directive in this case. This is nothing to put in a controller, service, factory or component. Once you use a directive your code will be much smarter and become fully supported by AngularJS diggest cycles and DOM bindings. This is how the documentation introduces directives:

What are Directives? At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element (e.g. via event listeners), or even to transform the DOM element and its children.

> Demo fiddle
Your solution could be smart like this one by using a nice directive:
View

    <form name="regForm" id="register-form">
      Mail
      <input ng-model="reg.email" type="email" name="username">

      <button ng-model="reg.btn" ng-disabled="stripeCompleted === false || !regForm.username.$valid">Register</button>
    </form>

AngularJS Application / Stripe.js card validation directive
var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope, $rootScope) {
  //Init stripe state via controller
  $scope.stripeCompleted = false;
});

app.directive('stripeValidator', function() {
  return {
    restrict: 'A',
    template: `

      {{ ccErrMsg }}
      <input type="hidden" name="stripeToken" ng-value="stripeToken" />`,
    scope: {
      "stripeComplete": '=',
      "stripeFormId": '@',
      "stripeError": '=',
      "stripeToken": '=',
    },
    link: function(scope, element, attrs) {

      //Init
      var stripe = Stripe("pk_test_6pRNASCoBOKtIshFeQd4XMUh");
      var elements = stripe.elements();
      var card = elements.create("card");
      var form = document.getElementById(scope.stripeFormId);

      //mount card element https://stripe.com/docs/stripe-js/reference#element-mount
      card.mount("#card-element");

      //add event listener
      card.addEventListener('change', function(event) {

        //check for errors
        if (event.error) {
          scope.ccErrMsg = event.error.message;
        } else {
          scope.ccErrMsg = '';
        }

        //check for complete
        scope.stripeComplete = event.complete ? true : false;

        //apply scope
        scope.$apply();
      });

      //inject form submit event
      form.addEventListener("submit", function(event) {

        //prevent form submit
        event.preventDefault();

        //handle token, handle error and form submit forward
        stripe.createToken(card).then(function(result) {

          if (result.error) {
             scope.ccErrMsg = event.error.message;
             scope.stripeToken = '';
          } else {
             scope.ccErrMsg = '';
             scope.stripeToken = result.token;
          }

          //apply scope
          scope.$apply();

          //forward submit
          form.submit();
        })
      });
    }
  }
});

Comment: Is it also possible to send form data thru `$http.post()` instead of `form.submit()`? I've posted more details in another question here: https://stackoverflow.com/questions/49062620/how-do-i-send-a-post-request-with-all-parameters-from-a-form-in-an-angularjs-dir


Apache Redirect (using .htaccess)

Question: I'm sort of a novice at using mod_rewrite in .htaccess, please forgive me. I've searched far and wide for an answer but perhaps I'm not looking in the right places, or perhaps .htaccess isn't even the right place to do this kind of thing.
Let's say I own two domains: joebloggs.com and bloggs.com.
When you put joebloggs.com into your browser I'd like it to redirect to https://www.bloggs.com/joe.
However, if you go to joebloggs.com/foobar, I'd like to redirect to https://www.bloggs.com/foo/bar.
note: I know this seems counterproductive, going from a shorter URL to a longer one, but the problem is that marketing materials were already disseminated with the URL joebloggs.com/foobar... :-/
The way I've tried to structure this in the .htaccess file hasn't worked thus far.
<IfModule mod_rewrite.c>
RewriteEngine on
#
# redirect joebloggs.com/foobar to https://www.bloggs.com/foo/bar
RewriteCond %{HTTP_HOST} ^joebloggs\.com\/foobar [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.joebloggs\.com\/foobar [NC]
RewriteRule ^(.*)$ https\:\/\/www\.bloggs\.com\/foo\/bar [L,R=301,NC]
#
# redirect joebloggs.com to https://www.bloggs.com/joe
RewriteCond %{HTTP_HOST} ^joebloggs\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.joebloggs\.com$ [NC]
RewriteRule ^(.*)$ https\:\/\/www\.bloggs.com\/joe [L,R=301,NC]
</IfModule>

When I put joebloggs.com into a browser, it redirects correctly to https://www.bloggs.com/joe - but when I try to go to joebloggs.com/foobar, the URL remains intact and thus goes to a 404 page (because it doesn't exist).
What am I doing wrong? Am I not doing this the optimal way, or not using .htaccess/mod_rewrite as it was intended?
Sorry for being long-winded, I hope I gave enough information. Thanks for any help and time spent on this!
Answer: The first set of rules is entirely useless. Update the second set to:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?joebloggs\.com$ [NC]
RewriteRule ^/?$ https://www.bloggs.com/foo [R=301,L,NC,QSA]

RewriteCond %{HTTP_HOST} ^(www\.)?joebloggs\.com$ [NC]
RewriteRule ^foo(.*)$ https://www.bloggs.com/foo/$1 [R=301,L,NC,QSA]

Comment: Thanks - I'll try this and see how it works!

In the meantime, what about the first set of rules makes it useless? Is it just that it's redundant when replaced with the set that you provided?
Comment: @theRBF The variable `HTTP_HOST` does not receive the URL path.
Comment: Okay, thanks @hjpotter92, that explanation makes sense. I tried your suggestion and it didn't work for me, but... I just edited my problematic code a little bit above because I realized that the way I was presenting it was a little confusing and maybe misled you a bit (sorry about that).

In summary, I'd like to redirect `joebloggs.com/foobar` to `https://www.bloggs.com/foo/bar`, but also `joebloggs.com` to `https://www.bloggs.com/joe`.
Comment: @theRBF Updated above.
Comment: thanks again @hjpotter92 - but, I'm afraid the second rule doesn't seem to go where I need it to go, it still 404s on me with the URL unchanged.
Comment: @theRBF It'd help if you actually show what you're trying to do.
Comment: I tested this elsewhere on a test environment setup and it worked, so thanks for the help! There must be some other overriding or inherited rule somewhere that's messing me up. I'll have to check with the original designers. Thanks again.

Apache Redirect (using .htaccess)


Modals not displaying correctly when updating to NG-Bootstrap 15 and bootstrap 5

Question: REWRITTEN after deeper investigation:
I am updating our application from NG-Boostrap v11 with bootstrap 4 to NG-Boostrap v15 with Bootstrap 5 and popper. We are also updating Angular 15 to Angular 16. Needless to say there are/were a lot of breaking changes with the bootstrap update, but we are solving them except for the fact that all the Bootstrap variables are coming back as undefined.
All the correct scss files are imported correctly and everything seems to be correctly configured as we ran "ng add @ng-bootstrap/ng-bootstrap" to set it up, but the variables continue to come back as undefined.
I should also note that the css files are compiling without errors. The variables are undefined in the browser
Comment: ng-bootstrap don't need "popper" nor "bootstrap 5" (only boostrap.min.css). Check the z-index you get when you open the ngb-modal, and check if you're override this property with a own .css
Answer: Finally found the issue. We were using css-vars-ponyfill to support old browsers and it was rewriting the variables and causing the issue. Remove this and all is well. Leaving here in case anyone else runs into same problem.


At what speed should the ferry be operated in order to minimise the cost per kilometre?

Question: A ferry operator wishes to minimise the cost per unit distance travelled of operating the ferry. When the ferry is travelling at speed v km $h^{-1}$, the cost in fuel per hour is $\dfrac {v^3}{10}$ dollars. The other costs of running the ferry (wages, maintenance, etc.) are $675 per hour. At what speed should the ferry be operated in order to minimise the cost per kilometre?
So for this question, I think that we first have to find a function for 'cost per unit distance'. So if C is the cost, t is the time in units of hours and d is the distance, then $\dfrac {dC}{dd}$ would be the 'cost per unit distance'. From the question, 'cost in fuel per hour' is given by $\dfrac{dv}{dt}$ = $\dfrac {v^3}{10}$, and 'other costs' is $\dfrac{dC}{dt}$ = $675$. So $\dfrac{dC}{dd}$ = $\dfrac {dv}{dt}$ $\times$ $\dfrac {dC}{dt}$, therefore $\dfrac {dC}{dd}$ = $\dfrac {v^3}{10}$ $\times$ $675$. Then to minimise the speed, find the second derivative of 'cost per unit distance travelled' and find the speed. But I don't know if my setting of the given values are correct.
Comment: Using $d$ as a variable when you are going to take derivatives is an invitation to mistakes.
Answer: As we are working in km and hours, we may as well take the unit distance as $1$ km.  When we are traveling at speed $v$, it takes $\frac 1v$ hour to travel $1$ km.  The cost for fuel is then $\frac 1v \cdot \frac {v^3}{10}=\frac {v^2}{10}$ per km.  The cost for crew is $\frac 1v \cdot 675=\frac {675}v$ per km.  The total cost is $\frac {v^2}{10}+\frac {675}v$.  Now take the derivative, set to zero...


Beginner iphone question: drawing a rectangle. What am I doing wrong?

Question: Trying to figure out what I'm doing wrong here.  Have tried several things, but I never see that elusive rectangle on the screen.  Right now, that's all I want to do -- just draw a single rectangle on the screen.
I'm getting an "invalid context" on everything but the CGContextSetRGBFillColor().  Getting the context after that seems kinda wrong to me, but I'm not at home looking at the examples I was using last night.
Have I messed up something else as well?  I really would like to get at least this much done tonight...
<code>- (id)initWithCoder:(NSCoder *)coder
{
  CGRect myRect;
  CGPoint myPoint;
  CGSize    mySize;
  CGContextRef context;

  if((self = [super initWithCoder:coder])) {
    NSLog(@"1");
    currentColor = [UIColor redColor];
    myPoint.x = (CGFloat)100;
    myPoint.y = (CGFloat)100;
    mySize.width = (CGFloat)50;
    mySize.height = (CGFloat)50;
    NSLog(@"2");
    // UIGraphicsPushContext (context);
    NSLog(@"3");
    CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
    context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, currentColor.CGColor);
    CGContextAddRect(context, myRect);
    CGContextFillRect(context, myRect);
  }

  return self;

}
</code>
Thanks,
Sean.
Answer: Starting with a View-based template, create a project named Drawer. Add a UIView class to your project. Name it SquareView (.h and .m).
Double-click DrawerViewController.xib to open it in Interface Builder. Change the generic view there to SquareView in the Identity Inspector (command-4) using the Class popup menu. Save and go back to Xcode.
Put this code in the drawRect: method of your SquareView.m file to draw a large, crooked, empty yellow rectangle and a small, green, transparent square:
<code>- (void)drawRect:(CGRect)rect;
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0.0, 1.0); // yellow line

    CGContextBeginPath(context);

    CGContextMoveToPoint(context, 50.0, 50.0); //start point
    CGContextAddLineToPoint(context, 250.0, 100.0);
    CGContextAddLineToPoint(context, 250.0, 350.0);
    CGContextAddLineToPoint(context, 50.0, 350.0); // end path

    CGContextClosePath(context); // close path

    CGContextSetLineWidth(context, 8.0); // this is set from now on until you explicitly change it

    CGContextStrokePath(context); // do actual stroking

    CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 0.5); // green color, half transparent
    CGContextFillRect(context, CGRectMake(20.0, 250.0, 128.0, 128.0)); // a square at the bottom left-hand corner
}
</code>
You don't have to call this method for the drawing to happen. Your view controller will tell the view to draw itself at least once when the program launches and the NIB files are activated.
Answer: You are not supposed to put CG code in initWithCoder. That message should only be used for INITIALIZATION purpose.
Put your drawing code in:
<code>- (void)drawRect:(CGRect)rect
</code>
If you are subclassing a UIView...
Comment: Also, you should not call drawRect directly, but call setNeedsDisplay instead, so the OS picks it up and redraws the view later.
Comment: Yes, moving your code to **drawRect** would definitely cause the rectangle to draw. I think you should follow some basic tutorials on iPhone DEV since this is pretty basic stuff. Take a look at the examples that come with the SDK.
Comment: The drawRect method is the only place where you are guaranteed to have a context that you can draw into. And only if you don't directly call drawRect yourself.
Comment: Okay, so I shouldn't use initWithCoder() to draw stuff.  But does that actually answer my question?  Is moving the CG code to another function going to make any difference in whether or not the rectangle gets drawn?

And as for the using/not using drawRect, you've now managed to confuse me.  Are you saying that I should put all the parameters for my rectangle in drawRect?  That doesn't seem right, either -- what if I want to draw more than one rectangle?

If there is a simple example app out there that *just* draws a rectangle or circle or something, I'd like to take a look at it.

Sean.


Requiring client certificate issued by a specific intermediate CA in Apache

Question: I have a CA hierarchy like this:

               Root-CA
          ________|_____________
         |                      |
      TEST-CA             PRODUCTION-CA
    _____|_____             ____|____
   |           |           |         |
TEST-SRV   TEST-CLI    PROD-SRV   PROD-CLI

From the perspective of the production server identified by the PROD-SRV server certificate, how would I setup Apache mod_ssl to require the PROD-CLI client certificate signed by the PRODUCTION-CA and not allow a client with the TEST-CLI certificate signed by the TEST-CA?

Currently I have:

SSLCertificateFile      prod_srv.crt
SSLCertificateKeyFile   prod_srv.pem
SSLCADNRequestFile      prod_ca.crt
SSLCACertificateFile    root_ca.crt

This looks like it is working because the server asks the browser for the PROD CLI  certificate but if I provide TEST CLI certificate a valid certificate path is constructed and a test client is accepted onto the production system.
Answer: Look into the SSLRequire directive - the following rule should look at the Issuer field (i.e. the CA certificate) of the certificate presented, pick out the CN, and match it against the name of your PRODUCTION-CA certificate.
SSLRequire %{SSL_CLIENT_I_DN_CN} == "PRODUCTION-CA"

Comment: Is this solution vulnerable to implicit trust attacks? (i.e. if someone manages to obtain a CA certificate you trust, with the name `PRODUCTION-CA`.) Can you check against a specific public key here, or maybe there is some other way to tell Apache "only trust certificates issued by this specific CA certificate"?
Comment: Never mind. Looks like you'd do it with [SSLCACertificateFile](http://httpd.apache.org/docs/2.0/mod/mod_ssl.html#sslcacertificatefile) set to `PRODUCTION-CA`. And in your case this might be fine because you have `root_ca.crt` (your own) specified in the configuration. I was worried about implicit trust from a public CA. I guess from a general security perspective it's better to trust *less*, so why not use the production CA and just exclude everything else?
Comment: Thanks meulop! This solution works when `SSLVerifyClient` is set to `optional`. I was hoping there would be a way to implement this simply through defining trust, making the chain validation fail without explicitly checking parts of the certificates. If nobody provides such a solution I shall accept yours in a few days. I appreciate your help!
Answer: I wanted to authenticate clients with certs issued by sub-CAs of an intermediate CA, i.e. like the following:
               Root-CA
                  |
            Intermediate-CA
          ________|_____________
         |                      |
      SUB-CA 1               SUB-CA 2
    _____|_____             ____|____
   |           |           |         |
TEST-SRV   TEST-CLI    PROD-SRV   PROD-CLI

You can use the SSL_CLIENT_CERT_CHAIN_n variable to inspect the chain, and e.g. do the following:
SSLRequireSSL
SSLVerifyClient require
SSLCACertificateFile ".../root-ca.cert.pem"
Require expr %{SSL_CLIENT_CERT_CHAIN_1} == file(".../intermediate.cert.pem")

or even multiple first-level intermediate CAs:
Require expr %{SSL_CLIENT_CERT_CHAIN_1} in { file(`".../intermediate.cert.pem"), file(".../intermediate2.cert.pem") }


How to implement a Comment Reply Form through Views and using JS?

Question: We have a comment body, using views, where we have the name, comment, picture, and date for each of the posted comments. At the end of all comments we have a comment body, where one can add a comment.
Now this works great for a linear comment system, but we want a threaded system in place. In views, I can add a reply comment link, but that takes me to a new page.
What I want is JavaScript based action, such that the comment form, goes below the reply link when reply button is clicked. Is this possible via views?
If not, what's my best option?
UPDATE
I enabled a module called ajax comments. This works great with default drupal comment system, but not so much with views. I added the required classes, and got the basic thing to work but the newly added comment doesn't appear until you refresh the page. Also the message (queued for moderation) comes at the bottom of the page.
If someone has set this module up successfully with views, please let me know.
Answer: Have you looked at Inline Ajax Comments?
Answer: Pratik,
Using AJAX comments with default settings is a good idea, but any modifications to it can really cause things to break. When I worked, it did not even provide any hook() for data modification.
It is better to do it in a custom way, which is much easier and flexible as per needs.
Comment: Ajax Comments is so buggy that we had to give up. I cannot believe Drupal doesn't have a lovely comment system by default - reply takes you to a separate page instead of an ajax/js functionality. I feel like I should be contributing this to D8 if I can. We usually use Disqus, but the clients insisted on no Disqus, so we had to go through this approach. Right now we are just framing, the reply to open in a lightbox.
Answer: I just want to add something to your updated portion, may be it will help you.
If you are able to appear the message bellow you can bring it up by using the custom template of comment-wrapper.tpl.php and to display message without refreshing the whole page you can refresh the
 on reply submit/save using drupal_add_js.
Comment: Thanks, Was this your first answer? :-)  We are looking to do something exactly like that, but opening in a lightbox instead. No offence to Drupal, but wordpress handles 4 things so much better than Drupal, right out of the box mainly being wysiwyg, subscription, media, and comments. Though CKEditor and Media with it's latest patch, is so much better!
Answer: you can render your form in th template file of your view.You can include this code in your views--view-YOUR_VIEW_NAME.tpl
$build = drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));

print render($build);

Answer: For this use Entity collection module, where make comments as entity and make collection of entities, by that you can perform threaded comment system.
Answer: just add Comment: Thread (asc) to your sort criteria. It keeps all comments of same thread together


Should I use a mixed effects model or something simpler?

Question: I'm running a study in which participants rate various items using 4 different scales, one of which is the dependent variable (all 0-100). There are 8 items in total. The hypothesis I want to test is that one of the independent variables, call it IV1, is the strongest predictor.
What is the simplest sort of analysis to conduct here?
Initially, I had thought of running a mixed effects model, with item as a random effect, but a colleague suggested that with only 8 items, that would basically be pointless (like trying to estimate the variability in height based on only 8 people).
Should I just run a mixed effects model with a random intercept for participant? So, something like the following:
lmer(DV ~ 1 + IV1 + IV2 + IV3 + item + (1|Participant)
Alternatively, would it be better to use something like DAGs to test my hypothesis?
Answer: When you measure a variable using a scale, one thing you could do is to summarize the scale using factor analysis and use factor score as the independent variable instead of the raw score items. Assuming each scale is unidimensional (meaning only results in only 1 latent factor), then you can simple run a linear regression to examine the effect size of each factor, as there will only be 1 row for each of your participant in your data.
Structural equation modeling could be another solution, where the latent structure and the fixed effects are fit together.
Comment: Thanks. That's very helpful. What's the drawback of just using the raw scores and running the mixed effects model I've specified above?


socket io erro client side

Question: Ao fazer a conexão com o server via socket io o browser retorna o seguinte erro:
http://localhost:3010/socket.io/?EIO=3&transport=polling&t=NOeqJv8 400 (Bad Request)

O seguinte código já foi adicionado no server side para poder aceitar qualquer tipo de conexão infependente de sua origem:
const io = require("socket.io")(http, {
     cors:{
         origins: '*:*',
         withCredentials:false
        },
        transport : ['websocket']
    });

E no client side eu conecto da seguinte forma:
 socket = io('ws://localhost:3010/',{
        transport : ['polling'],
        withCredentials:false
    })

Tentei tanto com o transport em websocket e polling como sem também já que por padrão seguindo a documentação do socket.io.
Já li inumeros foruns porém nenhum encontrei solução para esse problema, se alguem puder me ajudar, só preciso que o client se comunique com o server, já que a parte de envio funciona quando o client é rodado via node
Informações adicionais :
Porta do servidor express é aberta junto com o socket.io dessa forma
const express = require("express")
const app = express()
const port = 3010
const http = require("http").createServer(app)

Answer: Esse problema ocorreu devido a uma versão utilizada no client side, quando atualizada para a mais recente o problema foi sanado

socket io erro client side


Bayesian Linear Regression, trouble with posterior. Variance equal identity

Question: I am trying to solve the following problem.
If $y | \beta \sim N(X \beta, I_n)$ and $\beta \sim N(0, g^{-1}(X^t X)^{-1})$ for $g>0$. Find $ \pi(\beta|y)$ and show that $E(\beta|y)$ is a function of MLE of $\beta$.
My approach,
I proved that to maximize the likelihood, it is equivalent to minimizing the SSE, so the OLS is equal to the MLE.
I know normal is conjugate prior. So, $$\pi(\beta|y)= \frac{f(y|\beta)\pi(\beta)}{m(y)} \propto f(y|\beta)\pi(\beta) $$
$$ \pi(\beta|y) \propto \exp\{ - \frac{1}{2}(y-X\beta)^t (y-X\beta) - \frac{1}{2}\beta^t(g^{-1}(X^tX)^{-1})^{-1}\beta   \} $$
$$  =  \exp\{  - \frac{1}{2}( y^t y -2y^tX \beta+(1+g)\beta^t(X^tX)\beta  )  \}$$  and I get stuck. I read about g-priors and I think the a posterior is $N(\frac{1}{1+g}\hat{\beta}, \frac{1}{1+g} (X^t X)^{-1})$ but I'm not sure.
Comment: self-study? https://stats.stackexchange.com/tags/self-study/info
Answer: You may consult any textbook on Bayesian econometrics (e.g.) to find the conditional posterior distribution for $\beta$ given $\sigma^2$, given "conjugate priors" for $\beta$ and $\sigma^2$, i.e.,
$$\pi \left( \beta ,\sigma ^{2}\right) =\pi \left( \beta |\sigma ^{2}\right)\pi \left( \sigma ^{2}\right) $$
with
\begin{eqnarray}
\beta |\sigma ^{2} &\sim &N\left( \beta _{0},\sigma ^{2}B_{0}\right) \\
\sigma ^{2} &\sim &IG\left( \alpha _{0}/2,\delta _{0}/2\right),
\end{eqnarray}
as
\begin{eqnarray*}
\beta |\left( \sigma^{2},y\right) &\sim& N\left( \beta _{1},\sigma^{2}B_{1}\right)
\end{eqnarray*}
where
\begin{eqnarray*}
B_{1} &=&\left( X^{\prime }X+B_{0}^{-1}\right) ^{-1} \\
\beta _{1} &=&B_{1}\left( X^{\prime }y+B_{0}^{-1}\beta _{0}\right)
\end{eqnarray*}
Here, it seems to be the case that $\sigma^2$ is known to be one, so will disappear from these expressions. Also, your prior mean is zero and $B_0=g^{-1}(X'X)^{-1}$.
Thus,
\begin{eqnarray*}
B_1 &=& (X'X + ((g\cdot X'X)^{-1})^{-1})^{-1}\\
& = &(X'X + g\cdot X'X)^{-1} = ((1+g)X'X)^{-1}\\
&=& 1/(1+g)(X'X)^{-1}
\end{eqnarray*}
and
\begin{eqnarray*}
\beta_1 &=& B_1(X'y+g\cdot X'X\beta_0)\\
& = & B_1 X'y = ((1+g)X'X)^{-1}X'y\\
& = & 1/(1+g)(X'X)^{-1}X'y = 1/(1+g)\hat\beta
\end{eqnarray*}
The part regarding the posterior mean should follow immediately.


Is it possible and sensible to use IBM MQ without a local queue manager?

Question: My team is in the process of building an application that will be deployed on AWS EC2, and will communicate with on-premise legacy systems via IBM MQ (formerly known as WebSphere MQ, formerly known as MQSeries).
We already have IBM MQ queue managers on our premises. Do we also need to deploy one in EC2? Do we need to deploy them on the EC2 boxes where our application will run?
I am new to IBM MQ, although i have some experience with RabbitMQ. There are people in the company with a lot of experience with IBM MQ, but none of cloud applications. I've been told several times by them that we need to run a queue manager on the box with our application, which can then forward to other queue managers, but on a cloud machine with an ephemeral disk, that doesn't make any sense to me - it doesn't add any reliability.
We could deploy a queue manager on an EC2 machine with an EBS volume, which would make a bit more sense, and have our applications talk to that. But is that really any better than just talking directly to the existing queue managers on our own premises?
To add some bonus fun, we're not deploying the application directly on EC2, but on Cloud Foundry deployed on EC2, so the app instances are running inside containers that we don't have much influence over.
Answer: Worrying about the type of volume that the queue manager will be deployed to isn't what you should be worried about.  IBM MQ has specific guidelines on what volumes are supported and what volumes are not supported.  Have a look in the MQ Knowledge Center for more information.
MQ applications can run either locally or remotely (to a queue manager).
(1) MQ applications that connect locally (bindings mode) to a queue manager, can make application development and support a lot easier because there is NO network involved in getting and/putting messages.
(2) MQ applications that connect remotely (client mode) to a queue manager, is a lot more complex.  Someone else recently posted a similar question on the MQ ListServer and here is T.Rob Wyatt's excellent response.

There are a whole host of issues when consolidating from stand-alone
  QMgrs to shared hubs.  The one you are asking about is among the most
  mechanical and uninteresting of the bunch.  As FJ points out there are
  some security implications and the connectivity issues you yourself
  have stumbled across.  Let me give you a high-level round-up of some
  others.  The degree to which you experience most of these depends on
  how much the environment is currently stand-alone and how much sharing
  it currently has.  The exception is data integrity when switching to
  client so I'll talk about that first.
No messages lost or duplicated, order mostly assured:
This requires XA
  transactionality.  XA imposes its own set of design constraints, among
  which is that the app in question cannot fail over to a different
  QMgr.  MQ generally behaves as everyone seems to expect in that no
  messages are duplicated, lost or disordered under normal
  circumstances.
Dupe messages, disordering possible:
This requires at least
  single-phase commit.  If you GET a message off a queue under syncpoint
  and the client app gets a 2059 on the next API call, then you can be
  assured that the message will be rolled back and not lost.  But the
  app will see it again and if it was processed correctly the first
  time it will appear to be a dupe.  Also, if the app got a 2059 on a
  COMMIT after PUTting a message, it has no choice but to assume the
  COMMIT failed and issue the PUT again.  Unlike the "functional
  duplicate" from the GET, this generates multiple identical messages.
The channel agent holding the transaction with one or more GETs won't
  release the messages until MQ or TCP times it out and kills the orphan
  connection.  Since the rollback doesn't necessarily happen before the
  app reconnects, it is likely to get subsequent messages not under that
  syncpoint.  When the orphaned channel is killed and the messages
  reappear on the queue, they will be delivered but the order will be
  disrupted.
Dupe, missing messages, disordering possible:
  Client connections that
  use no XA and no single-phase COMMIT can lose or duplicate messages or
  disorder them for the reasons stated above.
Comment: It's also worth noting that the issues raised are endemic to async messaging and not to IBM MQ specifically.  So much so that the JMS specification makes an exception that dupe messages caused by session exceptions are "functional duplicates" and do not violate once-and-only-once QOS.


Object with same memory reference LiveData with Room DB and DiffUtil

Question: I am trying to integrate the list with Room DB and Diff Utils,

Issue Facing:

When an item(s) is updated, LiveData got triggered but existing items in the adapter are the same as newItems.
eg. OldList = [0 : "zero", 1: "one"] NewList = [0: "0", 1:"1"] when update triggered Adapter.currentList = [0:"0", 1:"1"] issue happening without setting items to adapter list
Old List same as NewList without set

Code:
Room - Listening Changes :
@Query("SELECT * FROM tbl_topic_list ORDER BY created_at DESC")
abstract fun getTopicListLiveData():LiveData<List<FilteringTopicEntity>>

LiveData - Listening Changes:

viewModel.getTopicListLiveData().observe(this, { list: List<FilteringTopicEntity> ->
            itemAdapter?.let {
                it.setData(list.toMutableList())
            }.orElse {
                itemAdapter = TopicListingAdapter(list
                    .toMutableList(), itemListener)
                itemTopicRecyclerView.adapter = itemAdapter
            }
            Log.e(TAG, "Item Received ${list.size}")
        })

Inserting into DB
@Update(onConflict = OnConflictStrategy.REPLACE)
abstract fun updateFilterTopic(copyDataEntity: FilteringTopicEntity)

Updating DB Row value
    override fun updateTopic(topicEntity: FilteringTopicEntity) {
        topicEntity.updatedAt = DateTime()
        topicListDao.updateFilterTopic(topicEntity)
    }

class MediaDiffCallback(
        private val oldList: MutableList<FilteringTopicEntity>,
        private val newList: MutableList<FilteringTopicEntity>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int = oldList.size

        override fun getNewListSize(): Int = newList.size

        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition].id == newList[newItemPosition].id
        }

        override fun areContentsTheSame(oldPosition: Int, newPosition: Int): Boolean {
            return oldList[oldPosition].updatedAt ==  newList[newPosition].updatedAt
        }

        @Nullable
        override fun getChangePayload(oldPosition: Int, newPosition: Int): Any? {
            return super.getChangePayload(oldPosition, newPosition)
        }
    }

Adapter complete code : link
I tried several solutions nothing works for that issue

I tried toMutableList() & toList()
I tried data class and converting it into objectList.map {it.copy}.toList()
Extracting values and adding to another object instance and new list
Tried to update latest livedata, room dependencies

LiveData received items present already in the adapter without set

Please help to find out notifying list item changes without notifyDataSetChanged() method to integrate things properly with DiffUtils.
Answer: Problem Solved
Initially, list items loaded within the adapter and selected item changed and replaced to DB.
    @Update(onConflict = OnConflictStrategy.REPLACE)
    abstract fun updateFilterTopic(copyDataEntity: FilteringTopicEntity)

Here, the problem is I used the same item instance which room DB returned before.

So. I reassigned values to the new instance and updated it to DB, now updates receiving as expected.

open class FilteringTopicEntity() : com.support.room.BaseEntity(), Parcelable {
    fun copy(filteringTopicEntity: FilteringTopicEntity): FilteringTopicEntity {
        filteringTopicEntity.id = id
        filteringTopicEntity.updatedAt = updatedAt
        filteringTopicEntity.createdAt = createdAt
        return filteringTopicEntity
    }
}

Here I showed, how I copied a value
    filteringTopicEntity.copy(FilteringTopicEntity()

Comment: Hey @MerlinJeyakumar can you please look at my [issue](https://stackoverflow.com/q/70095578/11560810)


Choosing between HLS or MPEG-DASH for a video app

Question: We are working on a mobile video app and need to decide on the video protocol between HLS or MPEG-DASH.
Our key consideration is which of the 2 has a better support and compatibility for browsers and mobile platforms (iOS, Android)?
The video content is recorded/uploaded/watched on a mobile app, but also needs to be shared for viewing on browsers.
It seems initially that HLS has a wider range of platforms support, but would love to hear from anyone's experience.
Thanks!
Comment: Hi, I have worked on the streaming app before, HLS will be really good. if you are using native iOS player and you need CC then definitely HLS is the best option
Comment: 2nd @SanjeevSundaravarathan - HLS has much better support, you can use hls.js to support in browsers.
Comment: thanks for the comments and tip re hls.js. Would u then suggest going with HLS and on Android using DASH?
Answer: You will most likely find you have to support both at this time if you want to reach as many users as possible, especially if the content is encrypted.
iOS and Safari typically use HLS and FairPlay, Android, Firefox and Chrome use DASH and Widevine and Windows and Edge use DASH and PlayReady.
At this time, Apple iOS devices must use HLS for content greater than 10 mins over a mobile network:

2.5.7 Video streaming content over a cellular network longer than 10 minutes must use HTTP Live Streaming and include a baseline 192 kbps HTTP Live stream.
  (https://developer.apple.com/app-store/review/guidelines/)

For this reason streams served to Apple devices are usually HLS, while DASH is used for other devices.
If you streams are not encrypted you can use CMAF a single source file. If they are encrypted then it will be some time before devices support a single CMAF encrypted source - See more detail here: https://stackoverflow.com/a/62020034/334402
CMFA info here: https://developer.apple.com/documentation/http_live_streaming/about_the_common_media_application_format_with_http_live_streaming


Estimating the uncertainty on the difference of two random variables

Question: Let $(X_0, X_1)$ a pair of (non-independent) random variables and $Z\in\{0,1\}$ a Bernoulli random variable, independent from $(X_0,X_1)$. Let $\Delta = X_1 - X_0$. We're interested in the distribution of $\Delta$.
Consider $(X_{0,i}, X_{1,i}, Z_i)_{1\leq i\leq n}$ i.i.d. copies of these random variables and $\Delta_i = X_{1,i} - X_{0,i}$.
Now assume that we only observe $(Z_i,X_{Z_i,i})_{1\leq i\leq n}$. In other words, for each $i$, we observe either $X_{0,i}$ or $X_{1,i}$, but not both. We know which one we have observed but we don't have access to the other.
Based on this information, we can estimate the expected value of $\Delta$ by computing
$$\frac{1}{\#\{i:Z_i=1\}}\sum_{i:Z_i=1}X_{1,i} - \frac{1}{\#\{i:Z_i=0\}}\sum_{i:Z_i=0}X_{0,i}.$$
However, I want to obtain a measure of dispersion of the distribution of $\Delta$, e.g. by estimating its variance. I'm not sure how to do this, and I'm not even sure this is possible because we have no way to assess the dependence relationship between $X_0$ and $X_1$, as we never observe both of them. Any idea or related literature?
Comment: The dependence relationship among the $X_i$ isn't relevant here.  Part of the problem is the overly elaborate notation: for instance, $Y$ is superfluous.  Just use the [Law of Total Variance](https://en.wikipedia.org/wiki/Law_of_total_variance).
Comment: I removed any mention to $Y$. I don't understand how to use the law of total variance here. What would be an estimator of $\mathbb{V}(\Delta)$ based on the data $(Z_i, X_{Z_i, i})_{1\leq i\leq n}$?
Comment: Condition on $Z.$
Comment: $Z$ is independent from the other variables.
Comment: Maybe: but *what you observe* is obviously not independent of $Z,$ and that's what matters.
Answer: The comment thread suggests that one insightful way to frame this problem is to distinguish the underlying random variables from what is observed.  Let's begin, then, by doing exactly that.
We will model the sample by means of the bivariate random variable $(X_0,X_1)$ in the usual way, by supposing the observations are associated with a sequence of iid versions of this variable $(X_{0i},X_{1i}),$ $i=1,2,\ldots,n.$  The observations are determined independently by parallel iid sequence of a third variable $Z$.  Thus, what is observed is a sequence
$$Y_i = (1-Z_i) X_{0i} + Z_iX_{1i}.$$
The equations
$$Z_i Y_i = Z_i X_{1i}$$
and
$$(1-Z_i)Y_i = (1-Z_i) X_{0i}$$
enable us to express the estimator of the mean of $X_0-X_1$ in the question as
$$\widehat{E[\Delta]} = \frac{\sum_{i=1}^n (1-Z_i) Y_i}{\sum_{i=1}^n (1-Z_i)} - \frac{\sum_{i=1}^n Z_i Y_i}{\sum_{i=1}^n Z_i}.$$
(In order for this to be well defined, we must understand either of these fractions to equal zero whenever its denominator is zero.)
Let's begin by computing the expected value of this estimator conditional on the $Z_i.$  Writing $\mathbf{Z}=(Z_1,\ldots,Z_n),$
$$E\left[\widehat{E[\Delta]}\mid \mathbf{Z}\right] = \frac{\sum_{i=1}^n (1-Z_i) \mu_0}{\sum_{i=1}^n (1-Z_i)} - \frac{\sum_{i=1}^n Z_i \mu_1}{\sum_{i=1}^n Z_i}=\mu_0-\mu_1,$$
as we would hope.  Similarly, because all the $X_{0i}$ are uncorrelated with all the $X_{1j},$ its conditional variance is
$$\begin{aligned}
\operatorname{Var}\left(\widehat{E[\Delta]}\mid \mathbf{Z}\right) &= \frac{\sum_{i=1}^n (1-Z_i) \sigma_0^2}{\left(\sum_{i=1}^n (1-Z_i)\right)^2} + \frac{\sum_{i=1}^n Z_i\sigma_1^2}{\left(\sum_{i=1}^n Z_i\right)^2} \\
&= \sigma_0^2\frac{1}{\sum_{i=1}^n (1-Z_i)} + \sigma_1^2\frac{1}{\sum_{i=1}^n Z_i}
\end{aligned} \tag{*}$$
(because $Z_i^2 = Z_i$ and $(1-Z_i)^2 = 1-Z_i$).
The Law of Total Variance (which follows, upon applying a little algebra, from the standard formulas for variance) asserts
$$\begin{aligned}
\operatorname{Var}\left(\widehat{E[\Delta]}\right) = E\left[\operatorname{Var}(\widehat{E[\Delta]}\mid \mathbf{Z})\right] + \operatorname{Var}\left(E\left[\widehat{E[\Delta]}\mid \mathbf{Z}\right]\right)
\end{aligned}.$$
The second term is the variance of constant and so drops out.  Evaluating the first term requires us to compute the expectations of the fractions in $(*).$  There is no closed form, but the values can be exactly calculated for small to medium $n$ because $\sum Z_i$ has a Binomial distribution with parameters $n,p$ and $\sum (1-Z_i)$ has a truncated Binomial distribution with parameters $n,1-p.$  Thus, bearing in mind the fraction is treated as $0$ when all the $Z_i$ are $0,$
$$E\left[\frac{1}{\sum_{i=1}^n Z_i}\right] = 0 + \sum_{k=1}^n \left(\frac{1}{k}\right)\binom{n}{k}p^k(1-p)^k = \int_0^1 \frac{(1 - (1-x)p)^n - (1-p)^n}{x}\,\mathrm{d}x.$$
The integral is useful for computations when $np$ is small to medium.  Otherwise, the Normal approximation to the Binomial distribution ($np$ and $n(1-p)$ are large) gives
$$E\left[\frac{1}{\sum_{i=1}^n Z_i}\right] \approx \int_1^\infty \frac{1}{x}\phi\left(\frac{x-\mu}{\sigma}\right)\,\mathrm{d}x$$
where $\phi$ is the standard Normal density.
By analyzing either integral it's easy to see that to first order this expectation equals the reciprocal of the expectation of the denominator, or $1/(np).$
The calculation involving the $1-Z_i$ is identical but with $p$ replaced by $1-p.$  Thus, to first order, the following formula gives a reasonable answer to the question:

$$\operatorname{Var}\left(\widehat{E[\Delta]}\right) \approx \frac{\sigma_0^2}{(1-p)n} + \frac{\sigma_1^2}{pn}.$$

If necessary (for small $n$ or extreme values of $p$) it can be improved using either of the two exact formulas (binomial sum and integral).
You can, of course, estimate $\sigma_0^2$ and $\sigma_1^2$ separately from the data for which $Z_i=0$ and $Z_i=1,$ respectively.


Openfire admin port and HTTP binding port

Question: I just install installed openfire and webchat plugin.The webchat plugin working fine in HTTP binding port of openfire. Can i set same port for both admin  and HTTP binding ?
Answer: i think its not possible,
because admin console and HTTP-binding both are totally different services of openfire.
So if you will try to set same port for both , it might throw error like 'port already in use'.


rvest: filter nodes based on subsequent node

Question: I'm trying to scrape links from a webpage. The webpage has hyperlinked images and hyperlinked h3 headers. I want to discard the links for the images. Unfortunately, there are no classes, ids, or attributes of the divs to identify the image hyperlinks. Is there some logic in rvest or bs4 to filter out the links based on the subsequently nested HTML elements? For example, if the next element is a img then ignore, if the next element is a h3 then keep?
html <- '<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

                 Smiley Face

              https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png

Harvard Business School

https://www.hbs.edu

'

my_page <- read_html(html)
my_page %>%
  html_nodes("a") %>%
  html_attr("href")

# [1] "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png" # Want to ignore this
# [2] "https://www.hbs.edu" # Want to keep this

Answer: With rvest you might wish to use xpath (parent axis) so as to specify the parent child (anchor tag h3 tag) relationship as follows:
library(rvest)
library(magrittr)

html <- '<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

                 Smiley Face

              https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png

Harvard Business School

https://www.hbs.edu

'

my_page <- read_html(html)
my_page %>%
  html_elements(xpath = "//h3/parent::a[@href]") %>%
  html_attr("href")

With bs4 you can use :has pseudo class selector with > child combinator to specify relationship of anchor tag with direct child h3 element. You can swop the child combinator for a descendant combinator if can be any child and not a direct child (potential difference in DOM depth)
from bs4 import BeautifulSoup as bs

html =  '''<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

                 Smiley Face

              https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/SNice.svg/1200px-SNice.svg.png

Harvard Business School

https://www.hbs.edu

'''

soup = bs(html, 'lxml') # pip install lxml if missing
print([i['href'] for i in soup.select('a[href]:has(> h3)')])

In either case, I have specified that the parent anchor tag must have an href attribute.


Excel Formula for Matching Cells

Question: I have an excel spreadsheet as such:
 - A  Column A - AB 12
 - B  Column B - AB 12
 - C  Does Column A match Column B? - Y

However, the column information is being pulled via query, from a database system and sometimes the values are as such:
 - A  Column A - AB12
 - B  Column B - AB 12
 - C  Does Column A match Column B? - N

I actuallity they do match and I need to accomodate for that? is it possible to do so? my current column 3 has this formula:
=IF(A3=B3,"Y","N")
that returns a no when it should be a yes. Help?
Answer: ... You could always use the Substitute function to remove all the spaces from your cells before comparing them:
=IF(SUBSTITUTE(A3," ","")=SUBSTITUTE(B3," ",""), "Y", "N")

Comment: +1 since that's the exact answer I tried to give before I was blocked by the captcha and didn't notice. :)
Comment: Had that happen to me a bunch of times - I'm just glad you agree with my solution :)

Excel Formula for Matching Cells


Como acessar tabela de chave estrangeira no Laravel para retornar em uma View

Question: Eu estou trabalhando em projeto no laravel e não consigo resolver o seguinte problema:
Tenho uma lista de Atendimento que esta sendo mostrada assim:

Eu queria colocar o nome no lugar do código nas colunas. Porém o nome esta em outra tabela, não sei como acessar.

Eu já recebi as Models da chave estrangeira no meu controller, como vocês podem ver ja tenho acesso ao código, mas não sei como fazer o nome do lugar deles, alguma idéia?
Comment: Estás usando relacionamento nessas tabelas ?
Answer: Eu não consigo visualizar, como você está realizando a query para buscar esses elemtentos, provavelmente se você fizer um inner join entre essas tabelas dê para resgatar. Exemplo:
select * from atendimento
inner join "aqui vai o nome da tabela" on atendimento.atendimento_id = "nome da tabela"."nome da coluna";

Depois tente resgatar os valores no foreach.
Answer: La no seu model atendimento voce precisa definir o relacionamento por exemplo
public function pessoa()
{
    return $this->belongsTo('Model\Pessoa', 'foreign_key_id');
}

ai la na sua view dentro do foreach voce consegue acessar assim:
@foreach($atendimentos as $atendimentoC)
{{ $atencimentoC->pessoa->nome }}
@endforeach

veja a documentação do laravel https://laravel.com/docs/5.8/eloquent-relationships
Comment: Obrigado faltava justamente a relação!


Xcode: Cocos2d: Can't create world with Box2D

Question: My project originated as the cocos2d Box2D template and I'm having issues as soon as I tried to create a world:
world = new b2World(gravity,doSleep);

Gives the error: No matching constructor for initialization of 'b2World'.
The file is .mm, I assume it's some issue about library linking maybe? If so I'm using xCode 4, how can I check the lib is properly linked?
Thanks.
Comment: Which cocos2d version are you using? If it's cocos2d 2.0 alpha then that should come with an updated "cocos2d with box2d" project template.
Answer: You are using Box2D v2.2 or newer. The b2World constructor no longer takes two arguments, just one (gravity). You have to set doSleep separately:
world = new b2World(gravity);
world->SetAllowSleeping(doSleep);

This won't be the only change you'll need to make to transition from Box2D v2.1.x to v2.2.x. Kobold2D has a working Box2D 2.2.1 sample project, even if you don't use Kobold2D you can get updated source code for Box2D basics. In particular the GLESDebugDraw class and how to setup a screen bounding box with a body using multiple shapes.
Comment: Thank you Steffen. It seems Box2D official reference misses the update. http://box2d.org/manual.pdf  page 8 still has the old way of creating the world. BTW, you have set a very nice "listener port" for Cocos2D questions :).


Erro ao alterar pela interface o tipo de dados de uma coluna

Question: Tento alterar o tipo de dados de VARCHAR para outro tipo de dados pela interface do sistema (não quero alterar via SQL) mas não consigo.
Tenho a seguinte tabela criada:
  CREATE TABLE `Usuarios` (
  `id_usuario` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) DEFAULT NULL,
  `sobrenome` varchar(100) DEFAULT NULL,
  `documento` varchar(100) DEFAULT NULL,
  `data_nascimento` date DEFAULT NULL,
  `campo_int` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id_usuario`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

E gostaria de mudar o campo_int de VARCHAR(100) para INT(11), mas não encontrei a opção de remover o charset e o collation referente ao campo. Não quero utilizar SQL para isso, quero modificar pela interface do DBeaver. Como devo proceder?
Comment: O simples fato de mudar pra INT já deveria eliminar ambos. Se teve algum problema ao tentar a mudança, clique em [edit] e descreva na postagem, aí fica mais fácil uma solução.
Comment: Bom dia amigo alterei a imagem, realmente era para aceitar a mudança quando altero o tipo de dados para INT
Answer: Após entrar em contato com o desenvolvedor do Dbeaver "serge-rider" o mesmo reportou que era um bug do sistema e já foi efetuada a correção.
Realmente é um ótimo software.


Force TR CSS over TD

Question: I understand that by definition, TD's CSS definition overrides TR's CSS.  Is there a way to do so otherwise?
My situation is as follows.  I have rows of information.  In one particular column, the text is in Green.  However, I want to "lock" a row, the whole row will be Grey regardless.  Is there a way to do this?
I'm trying to achieve this via !important but its not working.
Sample code:
CSS
.locked {
    color: #6D6D6D !important;
}
.count {
    color: #08C420;
}

HTML

    10,000

20,000

Right now, all cells with class count are showing green.  How do I fix this?
Answer: Hierarchiy?
.locked > .count {
    color: #6D6D6D;
}
.unlocked > .count {
    color: #08C420;
}

see jsfiddle
Comment: Thanks! That solved the problem. Is this compatible on all browsers?
Comment: its a css2 selector, should work in all css2 capable browsers: [caniuse](http://caniuse.com/#feat=css-sel2)

Force TR CSS over TD


get the text of the selected option using php

Question: in the following:
<form  action="test.php"  method="POST">
    <select id="test" name="test">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>
</form>

in test.php, I can get 1 or 2 as follow:
$result=$_POST['test'];

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using php
Comment: If you want the text, why not make the text the value?
Comment: Would you mind naming the specifics of the situation (ie Why you need both)? Maybe we can brainstorm a solution.
Comment: If you want to use the 1 and 2 value in JavaScript you can assign it to a different attribute such as title, alt, or anything you want.
Comment: I assume it's a typo, but your `select` element is missing its (mandatory) `name` attribute, which should be `id` (after your update it should be `test`).
Comment: We can give you all the possibilities you want, but until you tell us what you are truly trying to accomplish by passing both values, nobody can give you the best answer possible.
Comment: @powerbuoy -  Good catch. If the user is able to access it in the POST array he must have just missed it when typing up the question (i've updated it).
Answer: This is not something that can be done through PHP alone. The PHP script can only "see" the information which is posted (the value for the selected option that is posted). You can use javascript to alter a hidden input field with the text contents of a selected option, and this will be included in the $_POST array:
<form  action="test.php"  method="POST">
    <select id="test" onchange="document.getElementById('text_content').value=this.options[this.selectedIndex].text">
     <option value="1">Test One</option>
     <option value="2">Test Two</option>
    </select>

<input type="hidden" name="test_text" id="text_content" value="" />
</form>

This will make the $_POST['test_text'] available with the selected index (but you should also force the onchange() function when the page loads so that it will be populated even if the user leaves the select field at the default value.
Comment: @powerbuoy - it doesn't. It's a rare issue these days, but yours is the better solution (+1)
Comment: And how does this work for devices which do not support JS?
Answer: Only the value of the form control will be sent to the server. An easy way to send both is to simply include both in the the value:
<select name="test">
    <option value="1|Test one">Test one</option>
    <option value="2|Test two">Test two</option>
</select>

And then:
$test = explode('|', $_POST['test']);

Then you'll end up with $test[0] being "1" and $test[1] being "Test one".
Comment: I tried and works also very well
Answer: You can't; that information is not sent back to the server. You will need to look at how you generated the HTML in the first place and get the text from there.
Answer: It is not sent so the only way to get it is having an array mapping values to titles in your PHP code.
Answer: This is a solution I could use except I already have the onChange calling a function to show a hidden  block based on the selected building type in a  statement.
I have building types I need the user to select.  Several building types have a unique set of questions, e.g. Bank Branch, Data Center, Courtroom, etc.  But there are many that have the same set of questions which I call Other Type.  Each option has their associated value, e.g. Bank Branch has a value of "Bank_Branch", Data Center has "Data_Center", but Other Type has a value of "Other_Type".  The text for "Other_Type" differs based on the building type, such as Convention Center, Museum, Performing Arts, etc.  So I need the value "Other_Type" to "show" the questions in the "Other_Type" DIV block while using the text value to send in an email identifying the type of building, e.g. Convention Center, Museum, Performing Arts, etc.
Any way to use PHP to get the text value of the selected item?  I'm already using the following inside the HTML
   var sele = document.getElementById('building_type');
   var seleVal = sele.options[sele.selectedIndex].value;
   var seleTxt = sele.options[sele.selectedIndex].text;
   document.getElementById("other_text").innerHTML = seleTxt;

I'm not seeing a way to do this.
SOLVED:  I can simply create the hidden div and in my check for Other Type set the innerHTML for the hidden div.
Comment: I spoke too soon:

I added:

Then set document.getElementById("hidden_text").value = seleTxt;

If I make the "hidden_text" filed visible the value I want is there.  But when I try to use it, $_POST['hidden_text'] is empty.

Any ideas why $_POST['hidden_text'] would be empty?
Answer: The text for the selected option is not passed through the HTML form.  If you want the text, you have to store that in a hidden HTML input on your page, or you need to add some business logic in your PHP code to translate the value of ìd into the text (through a switch statement, or by querying a database, etc.)
Answer: Unfortunately when you submit a form and a variable it only takes one parameter which is it's value. You would need to make the value. Test One the value in order for it to pass on to the PHP script. What is the purpose of value="1" cause you can probably use it in a different attribute?
Answer: Im not a experienced php programer, but u can check the value selected in SELECT tag with php.
i dont know why people say u can not.
if ( $_POST['test'] == 1)
{ do something }
else
{ option value 2 is selected, do something else }

Im sure this will work.
Answer: Try it if 1, 2 not needed. you will get required text as value
<form  action="test.php"  method="POST">
    <select id="test" name="test">
     <option value="Test One">Test One</option>
     <option value="Test Two">Test Two</option>
    </select>
</form>


Does playing 12 bar blues require two players and two instruments?

Question: I am trying to play the 12 bar blues. From the manual I use, the idea seems to play the chord progression (CCCCFFCCFGCC) and at the same time it is possible to improvise or use some existing patterns on the pentatonic scale (halftone intervals 232232 starting from C).
I however cannot figure out how it would be possible to play the soloing pattern and the background progression with the same instrument at the same time. Is it true that two instruments and two players are always required?
Answer: It will depend to a degree on what the instruments are, and how advanced the player is.On piano/keyboard, it's quite easy to play both parts.On guitar, which is,I guess, what you play, it's not easy.Especially in C. You may well be able to transpose the key to E, using E,A and B(7). Or A, using A,D and E.That way, at least, you can put a bass pattern in on open strings underneath a blues tune using the top 2,3 or 4 strings.
If the player is someone like Martin Taylor, then one instrument is all that is needed - he'll put in bass, chords and tune at the same time. Us mere mortals tend to use another person to play the 'missing' parts.
The pattern you quote sounds better if the last F and G are swapped over, and usually the last chord is a G, used as a turnaround to get into the next verse.Leave it as C the last time though !
The pentatonic you quote isn't clear (to me), and is (in C) C,D,E,G,A for the major, and C,Eb,F,G,Bb for the minor. To make your tunes sound more bluesy, play Gb as well.
Comment: And to add to this, quite often you can play the progression in a simplified way (fifths etc) and use your this and fourth fingers to lead over it. This is very common from blues guitarists.
Comment: Lenny Breau did this really nicely (more jazz or bebop, stylistically, than blues) and with a fairly accessible approach actually: https://www.youtube.com/watch?v=LJdYOYSTG1E is a pretty good lesson on that kinda thing.
Answer: No, you don't need more than one player for the blues, as a lot of recordings show. Just playing the chords one time through will make most people recognize the tune form. If you would then solo using the C, F and G blues scales, changing scale where the chords change, people would still recognize the tune form. Adding the chords at different places in your solo will reinforce the structure if needed.