Filtrar elementos se elemento-filho dos mesmos tiver determinada classe

Question: O título da questão já é bem autoexplicativa. Eu estou tentando filtrar elementos (div) dependendo de se os elementos filhos deles tiver determinada(s) classe(s).
Encontrei o simples código abaixo que filtra muito bem, mas não exatamente do jeito que preciso - ele filtra as divs de acordo com as suas próprias classes, vejam:

var $boxs = $("#divs > .tr");
var $btns = $(".btn").on("click", function() {

  var active =
    $btns.removeClass("active")
      .filter(this)
      .addClass("active")
      .data("filter");

  $boxs
    .hide()
    .filter( "." + active )
    .fadeIn(450);

});
* {
  box-sizing: border-box;
}
body {
  background: #ecf0f1;
  font-family: helvetica, sans-serif;
  font-weight: 200;
}
.btn {
  border: none;
  background: linear-gradient(to bottom, #3498db, #2980b9);
  border-radius: 3px;
  font-family: Arial;
  color: #ffffff;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
  margin: 5px;
}

.active {
  background: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}
.tr {
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  padding: 10px;
  margin: 3px;
  text-align: center;
  border-radius: 3px;
  color: #fff;
}

<button class="active btn" data-filter="tr">Show All</button>
<button class="btn" data-filter="a">Show A</button>
<button class="btn" data-filter="b">Show B</button>
<button class="btn" data-filter="c">Show C</button>
<button class="btn" data-filter="d">Show D</button>

A e B

A

B

C e A

C

D

Como podem ver nas linhas

A e B

... então, quero que a div-mãe (.tr) seja filtrada dependendo das classes de suas filhas (.a .b), e não das dela mesma.
Alguma ideia?
Desde já sou grato.
Answer: Use o método .has(), que busca os elementos que possuem elementos filhos que casam com o seletor especificado.
A linha .filter( "." + active ) busca as divs que possuem uma classe, então trocando para:
.filter( function(){ return $(this).hasClass(active) || $("." + active, this).length } )

Irá buscar também as divs que possuem filhos com a classe. O callback function retorna os elementos que possuem a classe (.hasClass()) ou que possuem algum elemento filho com a mesma classe. O código $("." + active, this).length conta os elementos filhos com a classe especificada e retorna 0 (se não existir) ou maior que 0 (se existir). Ou seja, uma das duas condições separadas pelo || deve ser true.

var $boxs = $("#divs > .tr");
var $btns = $(".btn").on("click", function() {

  var active =
    $btns.removeClass("active")
      .filter(this)
      .addClass("active")
      .data("filter");

  $boxs
    .hide()
    .filter( function(){ return $(this).hasClass(active) || $("." + active, this).length } )
    .fadeIn(450);

});
* {
  box-sizing: border-box;
}
body {
  background: #ecf0f1;
  font-family: helvetica, sans-serif;
  font-weight: 200;
}
.btn {
  border: none;
  background: linear-gradient(to bottom, #3498db, #2980b9);
  border-radius: 3px;
  font-family: Arial;
  color: #ffffff;
  padding: 5px 10px 5px 10px;
  text-decoration: none;
  margin: 5px;
}

.active {
  background: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}
.tr {
  background-image: linear-gradient(to bottom, #3498db, #2980b9);
  padding: 10px;
  margin: 3px;
  text-align: center;
  border-radius: 3px;
  color: #fff;
}

<button class="active btn" data-filter="tr">Show All</button>
<button class="btn" data-filter="a">Show A</button>
<button class="btn" data-filter="b">Show B</button>
<button class="btn" data-filter="c">Show C</button>
<button class="btn" data-filter="d">Show D</button>

A e B

A

B

C e A

C

D

Comment: Da forma que tem no momento apenas mostra os que tem descendentes com a classe escolhida, mas não os próprios elementos que tem a classe também. Ou seja quando clica no "Show A" deve mostrar o "A e B" assim como o "A" e o "C e A"
Comment: Mas isso vc não falou na pergunta
Comment: Na pergunta vc diz que quer filtrar pelos filhos e não pela div principal
Comment: Atenção que eu não sou o AP! O que interpretei pelo exemplo é que ele queria filtrar pelo próprio e pelos filhos, mas o melhor é mesmo deixar o AP se pronunciar.
Comment: Muito obrigado Sam, perfeito! O @Isac não é o autor da resposta, se é o que deu a entender.
Comment: O @Isac tem razão rsrs, foi assim mesmo que eu quis dizer. Mas marquei como correta porque nesse meio tempo achei uma solução alternativa. De qualquer forma, obrigado a ambos!!
Comment: @ThiagoSoubra Blz! Eu editei a resposta. Abs!


How to fix inode 2 on a FreeBSD ufs filesystem

Question: My FreeBSD 11.1 system keeps panic-ing with this:
kernel: panic: ufs_dirbad: /mnt: bad dir ino 2 at offset 0: mangled entry
For such an error most forums suggest an older article (http://phaq.phunsites.net/2007/07/01/ufs_dirbad-panic-with-mangled-entries-in-ufs/) where the final solution is clearing the broken inode using the filesystem debugger.
So bad I am more or less confident that inode 2 is not a simple, regular inode but it is related to the root filesystem so I am not that willing to clear it.
Does anyone have any alternative ideas how to fix this? A have already run fsck in single user mode both using and not using the journal but still no luck.
Comment: Whatever you do, backup your system now by taking a disk image with an USB-bootable emergency util of your choice, and only then attempt to fix your system.
Answer: This indicates structural problems of the drive sometimes. Sometimes it happens after power failure. No matter what you do - first backup immediately. Second is boot into single user mode and perform the fsck -yf on drive. After fsck backup again. It can work further or you can replace it with another known good drive.


Finding Theft in Tender Sales

Question: I am a bit new to this, but I was hoping to get some guidance.  I have a large dataset of cash register sales.  It shows items sold, returned, or given away for free by the sales person.  The 3rd item is what I want to look at to see if 1: this can be used to predict theft?  2: Is a manager at a given store more likely to appease a customer or over generous.
I would like to do this with sklearn's models.   I was thinking an using Outlier detection to find managers who tend to give more items away than the other managers.  Is this a valid way to look at it? Should I normalize the the data somehow because some stores do more sales than others?  If so, what is a good way to normalize the data?  Percent given away? or some other scoring method?
Answer: I'd suggest you don't actually bother with the fancy approach. Sum up how much each manager has given away, divide by the total revenue of the store, and see if any managers have a very different number than the rest by hand. Remember:

Things you find out via machine learning are often, often overfit or (especially in cases like this) aren't quite answering the question you think you're answering. The best case for a real-world situation like this would  be it highlights managers who you should look more into personally.
Given that, if you desperately want to run scikit-learn on it, then one possible solution I see for you is indeed with outlier detection. Assuming you can link all give-aways to the manager in charge during them, and assuming your daily numbers are independent of each other (which is patently untrue but may work anyway, since time series modeling is difficult), what you can do is generate a vector per manager, in which each feature is the number of items given away for a particular day. So your vector would be of size (number of days in the dataset)x1. Then you could, assuming you have enough managers and stores, use a one-class SVM.
Answer: This question is a bit subjective. Anyway, I do not think that you can/should assume theft based on such statistical numbers (So Q1: no it is not a 'very objective' valid way). But for sure you can use it to see where relatively more or less generous behavior occurs (without making a statement of good/bad).
Sklearn seems good if you have sufficient data. In that case you won't need to make a model yourself which may be difficult/impossible/subjective/etc
Take care that

The data collection is done carefully.
Sufficient confounding variables are taken care of (Q2: So yes you should "normalize" somehow. I believe if you add factors to your classification problem then the normalizing thing is dealt with. For specific details you should re-ask or update your question).
You do not fall into the trap of the prosecutor's fallacy

While this answer is quite general, and does not give you a specific solution (which I believe is difficult), I would like to add a link to a legal case that has some connections with your problem and is very interesting to read since it provides very good insights into careful statistical thinking. Several errors and simplifications had been made in that legal case, and there is lots of subjectivity behind the numbers and calculations with different views (such as Bayesian probabilities) providing completely different outcomes.

'Elementary Statistics on Trial (the case of Lucia de Berk)' 2010 by Gill, Groeneboom and de Jong
'On the (ab)use of statistics in the legal case against the nurse Lucia de B' 2006 by Meester, Collins, Gill and van Lambalgen
Answer: I don't know what skleans models are. What I glean from your post is that you want to detect unusual activity in " daily given away" taking into account the total sales for a particular day for a particular manager. To do so one might need to take into account daily/weekly/monthly factors and perhaps holiday factors while dealing with level shift, trends and unusual values while incorporating memory (ARIMA structure). The idea is simple and profound .. identify typical response to assess/detect unusual activity via Intervention Detection. see this URL for an introduction http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html . His examples are purely univariate but the approaches have been easily extended to causal models . See this http://www.math.cts.nthu.edu.tw/download.php?filename=569_fe0ff1a2.pdf&dir=publish&title=Ruey+S.+Tsay-Lec1 where transfer function models are discussed and here for an overview http://autobox.com/cms/images/dllupdate/TFFLOW.png.
This can be accomplished by identifying/building a causal model this is normally called a Transfer Function model which is a combination of regression structure and time series featutes.
If you wish to post data for 1 example (real or contrived) I and others might be able to help further as this looks to me like very promising problem in search for a very promising solution leading to value. Essentially what you are trying to do is to convert data to information to action.
As a warning be aware that many regression type solutions premise data that is free of autocorrelation i.e. non-time series but that assumption is usually not disclosed . One has to be concerned with model assumptions and their validation.
Models need to be complex enough (fancy enough) but not too complex (fancy). Assuming that simple methods work with complex problems is not consistent with  scientific method following Roger Bacon and tons of followers of Bacon.

Finding Theft in Tender Sales


Quero pegar multiplos checkbox com ids de items para AJAX em select all

Question: Tenho um checkbox de selecionar tudo.
Embaixo dele tenho dois checkbox.
O selecionar tudo eu não fiz ainda mas não é o problema, eu preciso só que, ao clicar no botão, envie o post com todos os checkbox selecionados!
Código do botão para envio do AJAX:
<button onclick="checkbox_items_select_all_javascript();">enviar selecionados</button>

O botão vai capturar pelo JavaScript quais os items abaixo (checkbox) estão selecionados, e enviar como post para o arquivo PHP (AJAX)
Tentei o código deste tópico e não consegui fazer funcionar!
https://stackoverflow.com/questions/9493531/send-multiple-checkbox-data-to-php-via-jquery-ajax#
Meus dois checkbox (item 1 e item 2 de exemplo)
<input type='checkbox' name='checkbox_items[]' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >
<input type='checkbox' name='checkbox_items[]' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >

Meu ajax:
function checkbox_items_select_all_javascript() {
    var checkbox_items = new Array();
    $("input:checked").each(function() {
       checkbox_items = data['checkbox_items[]'].push($(this).val());
    });

  var dataString = 'checkbox_items='+ checkbox_items;
    $.ajax({
      type: "POST",
      url: "aj/checkbox_items_select_all_ajax.php",
      data: dataString,
      cache: false,
      success: function(result){
       alert(result);
      }
    });
    return false;
}

Erro JavaScript (console):

Uncaught ReferenceError: data is not defined
      at HTMLInputElement. (checkbox_items_select_all_javascript.js:4)
      at Function.each (jquery-2.1.3.min.js:2)
      at n.fn.init.each (jquery-2.1.3.min.js:2)
      at checkbox_items_select_all_javascript (checkbox_items_select_all_javascript.js:3)
      at HTMLInputElement.onclick ((index):1) mais_opcoes.css:1 Failed to load resource: the server responded with a status of 404 ()
Answer: Esse data['checkbox_items[]'] não existe. Você deveria fazer o .push() no checkbox_items que é uma array.
Não precisa, neste caso, usar array no name. Na verdade nem precisam de name os checkboxes (talvez nem de id), basta:
<input type='checkbox' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >
<input type='checkbox' id='select_{$anuncio['id']}' value='{$anuncio['id']}' >

E na função você vai fazer:
var checkbox_items = new Array();
$("input:checked").each(function() {
   checkbox_items.push($(this).val());
});

Vai adicionar cada value de cada checkbox checado na array checkbox_items.
O resultado no PHP ($_POST['checkbox_items']) será uma string com os values separados por vírgula, algo como:
"valor1,valor2"

Que você pode converter em array com explode():
explode(",", $_POST['checkbox_items']);


Customize Search Form Block Text

Question: I'm attempting to customize the search form block. I'd like to be able to change the search submit button, by either changing the text, or turning it into an icon and other various changes.
I assumed I'd be able to make these changes within a template, but the default block--search-form-block.html.twig only contains
<code>{%
  set classes = [
    'block',
    'block-search',
    'container-inline',
  ]
%}
<div{{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {% if label %}
    <h2{{ title_attributes }}>{{ label }}</h2>
  {% endif %}
  {{ title_suffix }}
  {% block content %}
    {{ content }}
  {% endblock %}
</div>
</code>
I don't see anyway I can change anything such as the submit text. Is there any way to make direct changes to the search form block?
Comment: Is there a way to perform those actions within the theme file instead of creating a custom module for it?
Comment: Yes, you can put the form alter hook in `mytheme.theme`
Answer: try something like
<code>#search-block-form input[type="submit"] {
background-color: white;
padding: 15px 25px;
color: black;
border-radius: 0px;
border: 1px grey dotted;
background-image: url(http://cashbin.win/sites/default/files/favicon.ico);
background-size: 30px 30px;
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
}
</code>
This is an example obviously replace the image and/or border, color, background, position, and padding options.
Add this into you /sites/all/themes/CURRENT_THEME/css/style.css
Hope this helps, God Bless!
Comment: This doesn't change the submit text and is oddly specific CSS without knowing the theme.
Comment: @Kevin matt hasn't answered yet but to someone who actually needs help they will be thankful for specifics I think.  I just decided to show what css options were available to him. He could change the setting and/or remove any.

Customize Search Form Block Text


Pinterest V3 API Endpoints

Question: I am trying to access the Pinterest API but their documentation is scarce and does not provide the functionality I am looking for.
I'd like to pull JSON of all pins for any given board. I've found this endpoint:
<code>https://api.pinterest.com/v3/pidgets/boards/highquality/travel/pins/
</code>
But this seems to only want to return 50 pins from the board. I've tried several schemes for pagination with no success.
Has anyone had experience with this API? Thanks for your help.
Answer: I know this is an old post, but in case someone else needs some documentation: https://developers.pinterest.com/docs/redoc/pinner_app/#operation/v3_board_pins_GET
The endpoint: https://api.pinterest.com/v3/boards/{board}/pins/
The response returns a "bookmark" value to provide pagination.

Pinterest V3 API Endpoints


Inserir um Intervalo de Datas

Question: Bom dia, estou fazendo um sistema que preciso registrar as presenças de usuários em um evento, separando por período do dia e data. A parte do período foi simples, porem a da data me vem um problema, eu preciso pegar a data do formulário que insere a Data Inicial/Data Final e inserir todas as datas nesse intervalo(alem das datas já inseridas), para registrar a presença do usuário em cada um dos dias por exemplo.
Ficaria tipo assim:
   idevento  |        datainicial     |          datafinal
       1     | $_POST["datainicial"]  | $_POST["datafinal"]
       1     |         20/02/2016     |        25/02/2016

Ai no banco ficaria assim:
       |idevento|   datas  |
       |   1    |20/02/2016|
       |   1    |21/02/2016|
       |   1    |22/02/2016|
       |   1    |23/02/2016|
       |   1    |24/02/2016|
       |   1    |25/02/2016|

Achei em algumas perguntas algo semelhante mas era somente o select, o que me adiantaria na hora de pegar as datas do banco para registrar a presença, porem eu precisava ter as datas inseridas no banco pra poder registrar a presença em cada uma separada e gerar um Relatório final de presença, então tentei adaptar, porem não obtive resultado.
EDIT 1: @Gabriel Herning Fiz o codigo desta forma, porem não sei se estou mandando errado ao banco ou coisa parecida. Devo criar uma nova coluna pra armazenar o valor das datas certo? Alem da de data inicial e data final
$dataInicial = $_POST['data'];
$dataFinal = $_POST['datafinal'];
$start = new DateTime($dataInicial);
$end = new DateTime($dataFinal);

$periodArr = new DatePeriod($start , new DateInterval('P1D') , $end);

foreach($periodArr as $period) {
    $end = $period->format('d/m/Y');
    $sql = mysqli_query($conn, "INSERT INTO evento (id, datas) VALUES('$id', '$end);
}

A tabela tem os campos idevento, datainicial, datafinal, e datas, preciso passar qual delas no insert?
EDIT2: Esse e o codigo atual
function presenca($datas){
        include "conectar.php";
        $dataInicial = $_POST['data'];
        $dataFinal = $_POST['datafinal'];
        $start = new DateTime($dataInicial);
        $end = new DateTime($dataFinal);
        $periodArr = new DatePeriod($start , new DateInterval('P1D') , $end);
        foreach($periodArr as $period) {
            $period->format('d/m/Y');
            $sql = mysqli_query($conn, "INSERT INTO datas (datas) VALUES('$period')");
        }
        $conn = null;

}
if($_POST["pagina"] == "inserirEve"){
    presenca($_POST['data'], $_POST['datafinal']);
}

<form method="POST" action="input.php">
<input type="hidden" name="pagina" value="inserirEve"/>
Data Inicial: <input type="date" name="data">
Data Final: <input type="date" name="datafinal">

<input type="submit" name="Inserir" value="Cadastrar">
</form>

E ocorre esse erro aqui:
Catchable fatal error: Object of class DateTime could not be converted to string in C:\xampp\htdocs\semana\input.php on line 53
EDIT3:
function presenca($datas){
            include "conectar.php";
            $start = new DateTime($_POST['data']);
            $end = new DateTime($_POST['datafinal']);
            $periodArr = new DatePeriod($start , new DateInterval('P1D') , $end);
            foreach($periodArr as $period) {
                $period = $period->format('d/m/Y');
                $sql = mysqli_query($conn, "INSERT INTO datas (datas) VALUES('$period')");
            }
            $conn = null;
}

Answer: Utilize a biblioteca Date\Time para isso. A Date\Time é uma biblioteca nativa do PHP que lhe oferece tudo que é necessário para se trabalhar com datas. Nela, você encontrará a classe DatePeriod.
Com DatePeriod, você poderá calcular todas as datas dentro de um perído:
$start = new \DateTime('2016-02-20');
$end = new \DateTime('2016-02-25');
$periodArr = new \DatePeriod($start , new \DateInterval('P1D') , $end);

foreach($periodArr as $period) {
    echo $period->format('d/m/Y H:i:s').'
';
}

//data de término
echo $end->format('d/m/Y H:i:s');

Saída:
20/02/2016 00:00:00
21/02/2016 00:00:00
22/02/2016 00:00:00
23/02/2016 00:00:00
24/02/2016 00:00:00
25/02/2016 00:00:00

Um detalhe é sobre a data de término, ela deve ser considerar como "data de corte", ou seja, não é considerada "dentro de um período". Por isso, ela é impressa separadamente
Caso você precisa só utilizar o período interno, visto que já possui início e fim, pode remover a data inicial através da opção DatePeriod::EXCLUDE_START_DATE:
$start = new \DateTime('2016-02-20');
$end = new \DateTime('2016-02-25');
$periodArr = new \DatePeriod($start , new \DateInterval('P1D') , $end , DatePeriod::EXCLUDE_START_DATE);

foreach($periodArr as $period) {
    echo $period->format('d/m/Y H:i:s').'
';
}

Saída:
21/02/2016 00:00:00
22/02/2016 00:00:00
23/02/2016 00:00:00
24/02/2016 00:00:00

Comment: Então, eu preciso passar o Post da data inicial para start, a da final para end e dentro do foreach mandar um insert para o banco, com o valor de periodoArr? Ou mando no insert o valor de ambos?
Comment: @Coelho sim, você passará o $_POST para o $start e o $end. Dependendo do formato que vier, utiliza [DateTime::createFromFormat()] (http://php.net/manual/en/datetime.createfromformat.php) para definir o formato. Após, faça o foreach do resultado e insira linha a linha.
Comment: @GabrielHerning Eu fiz de um jeito, está dando alguns erros, editei a pergunta com o codigo atual.
Comment: @Coelho seu código está com vários problemas. Primeiro, o retorno de DatePeriod é um array de DateTime, como tal, devem ser tratados como objetos. Ou seja, ser usado o método [format](http://php.net/manual/en/datetime.format.php). Outro erro, é a falta de apóstrofo ao fechar o código `'VALUES('$id', '$end);'`. E, por último, mas não menos importante, você está utilizando a variável $end, no lugar aonde deveria ser $period. Outro ponto, o que realmente pretende salvar na coluna datas? Acredito que esteja com um sério problema de modelagem.
Comment: Bom, a unica coisa que eu preciso salvar são as datas no intervalo entre a primeira Data(inicial) e a data Final,                                           `$periodoArr = $periodoArr->format('d/m/Y'); $periodArr = new DatePeriod($start , new DateInterval('P1D') , $end);` Algo assim? E na parte do `$end = $period->format('d/m/Y');` deixo somente `$period->format('d/m/Y');` Em relação ao fechar o código foi erro de atenção mesmo.
Comment: O problema da sua implementação é que não está de acordo com a [1ª Forma Normal ](http://www.luis.blog.br/primeira-forma-normal-1fn-normalizacao-de-dados.aspx). Nesse caso, você teria que ter uma segunda tabela (que poderia ser chamada de "evento_datas"), ela salvaria, linha a linha, cada data do período. O problema, é que não faço a menor ideia de como você quer salvar no formato atual. Se você adicionar `$period->format('Y-m-d')` no lugar de onde está o `$end` no insert, talvez já resolva do jeito que você quer.
Comment: Sim sim, era essa a ideia mesmo, nessa nova tabela eu devo mandar o insert com as datas e criar dois campos, um com o `idevento int`` e outra com `datas date`, e inserir nesses dois campos?
Comment: Isso. Você deve inserir na tabela `evento`. Recuperar o id inserido, já que está utilizando mysqli, pode usar [http://php.net/manual/en/mysqli.insert-id.php](mysqli_insert_id). Após, adicione ao foreach inserindo período por perído.
Comment: Eu ainda não consegui inserir, vou continuar tentando, enquanto isso vou deixar aberto aqui. Deixei o código como esta no momento no principal, mas obrigado pela ajuda até aqui.
Comment: `$periodArr->format('d/m/Y');` não existe. $periodArr é um array, apenas isso.
Comment: Você deve passar $period->format e não $periodArr (conforme dito anterior). Outro detalhe é utilizar prepared statements conforme o exemplo no link: http://stackoverflow.com/a/9629364/1628790
Comment: Continuo sem conseguir solução, não aparece erro algum, porem não manda ao banco. devo estar mandando o insert errado ou passando os parametros em em  `if($_POST["pagina"] == "inserirEve"){
    presenca($_POST['data'], $_POST['datafinal']);`, dei um edit novo no principal.
Comment: De onde está vindo a sua variável $conn? Ela não existe no escopo da função. Adicione a linha ` or die(mysqli_error($conn));` ao final de mysqli_query conforme http://stackoverflow.com/a/17053489/1628790 para exibir qualquer erro no insert.
Comment: Elá vem do conectar.php, que e o arquivo / função que conecta com a db, e mesmo com o or die(mysqli_error($conn));, continua sem mostrar erro nenhum. `$conn = new mysqli($servername, $username, $password, $dbname);`
Answer: Você pode utilizar uma função para retornar todas as datas entre o inicio e o fim antes de inserir no banco de dados:
function createDateRangeArray($strDateFrom,$strDateTo) {
    // formato esperado: YYYY-MM-DD
    $aryRange=array();

    $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
    $iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));

    if ($iDateTo>=$iDateFrom)
    {
        array_push($aryRange,date('Y-m-d',$iDateFrom));
        while ($iDateFrom<$iDateTo)
        {
            $iDateFrom+=86400;
            array_push($aryRange,date('Y-m-d',$iDateFrom));
        }
    }
    return $aryRange;
}

//chamando a função da seguinte forma
$dt_inicial = date('Y-m-d', strtotime($_POST["datainicial"]));
$dt_final = date('Y-m-d', strtotime($_POST["datafinal"]));
$array_datas = createDateRangeArray($dt_inicial , $dt_final);

foreach($array_datas as $data){
    //insere os dados no banco
}

Referência
Comment: `foreach($array_datas as $data){                                                    include "conectar.php";                                                                        $sql = mysqli_query($conn,"INSERT INTO datas(idevento, datas) VALUES('$idevento', '$array_datas')"); $conn = null; }   `A parte de inserir no banco, eu preciso inserir o array_datas dentro da minha tabela de datas, ou tanto a final quanto a inicial?

Inserir um Intervalo de Datas


Use local Git LFS repo to check if any file changed without copying under .git

Question: I have a folder with lots of binaries. I would like to save the current state, make some changes and see which files are changed by git status. I think it is a good idea to use Git LFS, because it only keeps 3 lines for each file with size and hash information.
The problem is that git add . command takes a lot of time and makes a backup. Is it possible to commit only pointer files without creating LFS objects?
The commands I use:
$ git init
$ git lfs install
$ git lfs track "*"
$ echo ".gitattributes filter= diff= merge= text" >> .gitattributes
$ git add .
$ git commit -m "previous state"
$ rm -rf .git/lfs/objects/

I am okay with low level (plumbing) commands if there is not a porcelain solution.
In case anyone wonders how a file is saved with Git LFS, FILENAME is committed in the following format.
version https://git-lfs.github.com/spec/v1
oid sha256:$(sha256sum $FILENAME | awk '{print $1;}')
size $(du -b $FILENAME | awk '{print $1;}')

Comment: Please provide a feedback when you are downvoting a post so that I can improve the post or elaborate the problem. I found no simple way to achieve a simple task which is version controlling of big files without unnecessarily waiting for hours (creating objects takes a lot of time, and space).
Answer: After moving the .git folder, the files are shown modified in git status, and only way to fix the situation as for as I know is to call git add ., which updates the git index file. Git LFS recreates the object file if it is missing when a file is modified, so unfortunately the solution below is no different than using the commands in the question except this is multithreaded. On Windows, it is recommended to turn real-time protection off to avoid high CPU usage of Antimalware Service Executable.
#!/bin/bash
set -e

task() {
    REPO="$1"
    FILE="$2"
    BASE=$(cd $REPO; pwd)
    FILEPATH="$BASE/$FILE"
    SHA=$(sha256sum "$FILEPATH" | awk '{print $1;}')
    SIZE=$(du -b "$FILEPATH" | awk '{print $1;}')
    NEWFILE="$BASE.git/$FILE"
    cat > "$NEWFILE" <<-EOF
version https://git-lfs.github.com/spec/v1
oid sha256:$SHA
size $SIZE
EOF
    echo "  Wrote out $FILE"
}

if [[ $# -ne 1 ]]
then
    echo "Please provide the path"
    exit 2
fi
REPO="$1"

GITFILES=($(find "$REPO" -name ".git*" -exec basename {} \;))
if [[ ${#GITFILES[@]} -ne 0 ]]
then
    echo "The path contains .git files. Aborting..."
    echo "Path: $REPO"
    for GITFILE in "${GITFILES[@]}"
        do echo "  $GITFILE"
    done
    exit 2
fi
FILES=($(find "$REPO" -type f -exec basename {} \;))
echo "Found ${#FILES[@]} files"

N=$(nproc --all)
echo "Number of threads: $N"

BASE=$(cd $REPO; pwd)
echo "Creating directory $BASE.git"
mkdir "$BASE.git"
for FILE in "${FILES[@]}"
do
    (i=i%N); ((i++==0)) && wait
    task "$REPO" "$FILE" &
done
wait
WRITTEN=($(find "$BASE.git" -type f -exec basename {} \;))
if [[ ${#WRITTEN[@]} -ne ${#FILES[@]} ]]
then
    echo "${#WRITTEN[@]} out of ${#FILES[@]} files are written. Aborting..."
    exit 2
fi
echo "All files written"

echo "Committing the previous state"
cd "$BASE.git"
git init
git add .
git commit -m "previous state"

echo "Using Git LFS to track these files"
git lfs install
git lfs track "*"
echo ".gitattributes filter= diff= merge= text" >> .gitattributes
git add .
git commit -m "git lfs track all files"

echo "Moving .git to $REPO"
cp -r "$BASE.git/.git/" "$BASE/.git/"
cp "$BASE.git/.gitattributes" "$BASE/.gitattributes"
cd "$BASE"
git add $(git status --porcelain | awk '{print $NF;}')
echo "Erasing temporary folder $BASE.git"
rm -rf "$BASE.git"
echo DONE


$\int x^n \sin x dx$

Question: I attempted solving this using parts and after using it twice I get:
$$(-x^n)\cos x + nx^{n-1}\sin x - n \int \sin x(n-1)x^{n-2} dx$$
can this indefinite integral be solved using typical under division Calculus I-II coursework?
Comment: You will have to do it $n-2$ more times.
Comment: This is the right idea.  Just keep doing it until you see the pattern.
Answer: Define $$ I_n = \int x^n\sin(x)dx $$
$$U_n = \int x^n\cos(x)dx$$
Integration by parts
$$ I_n =-x^n\cos(x)+n\int x^{n-1}\cos(x)dx=-x^n\cos(x)+nU_{n-1}$$
$$U_n=x^n\sin(x)-n\int x^{n-1}\sin(x)dx=x^n\sin(x)-nI_{n-1}$$
with
$$I_0= -\cos(x)$$
$$U_0=\sin(x)$$
Now substitute until you get to $I_0$ or $U_0$ depending on the parity of $n$.
Answer: Consider that:
$$ \int f(x)\,e^{-x}\,dx = C-\left(f(x)+f'(x)+f''(x)+\ldots\right)e^{-x}\tag{1}$$
and by setting $x=iy$:
$$\begin{eqnarray*}\int x^n\sin x\,dx &=& \text{Im}\int x^n e^{ix}\,dx = \text{Im}\left(i^{n+1}\int y^n e^{-y}\,dy\right)\tag{2}\end{eqnarray*}$$
from which it is easy to recover the final expression.

$\int x^n \sin x dx$


Make small pages fill browser height

Question: How do you make small pages fill the browsers height so that the footer will be at the bottom not in the middle
for example

      <%= render 'layouts/navigation' %>

       <%= render 'layouts/messages' %>

            <%= yield %>

About

Twitter

Privacy Policy

Contact

Sitemap

© 2011–2014 Acme, Inc. All rights reserved.

<%= javascript_include_tag "application" %>

When there is a smaller yield the footer ends up in the middle of the page.  I'm okay with the footer being on the bottom, and I'm also okay with it being after a bunch of content, so scrolling is okay. I have searched and most poeple want a sticky footer which is not what i want.  I dont always want it on the bottom, i Just want each page to be a minimum of 1 page in height.
How can I achieve this?
Answer: Like this:
CSS
html,
body,
.off-canvas-wrap,
.inner-wrap {
    position: relative;
    min-height: 100%;
}

.inner-wrap {
    padding-bottom: [hight of your footer]px;
}

.footer-bottom {
    position: absolute;
    bottom: 0px;
}

Note: You're using class="" wrong. Unique elements should use id="", if you're picky :-)
Comment: Just a fast dribbled down answer based on what you've provided. Could you please link to the actual page, post your current CSS or make a JSFiddle?
Comment: i usually use id when unique probably an oversight.  I'll try this out. thx
Comment: This appears to make it sticky and prevents page scrolling, also seems to overlap content
Answer: html, body should have height: 100%;
use min-height: calc(). You need to know the height of the footer.
http://jsfiddle.net/michaelburtonray/by10fkm9/
HTML

      <%= render 'layouts/navigation' %>

        <%= render 'layouts/messages' %>

            <%= yield %>

About

Twitter

Privacy Policy

Contact

Sitemap

© 2011–2014 Acme, Inc. All rights reserved.

CSS
html,
body {
    height: 100%;
}

.top {
    background: red;
    min-height: calc(100% - 156px);
}

.footer-bottom {
    background: green;
    overflow: hidden;
    height: 156px;
}

Make small pages fill browser height


Cello: Is it possible to play a double stop of a major 9th on the I and II strings?

Question: The cello is using scordatura, the tuning is Cb Ab Eb Ab (from the fourth to the first string).
I want to know if the following passage is possible, tempo is around 220~240 quarter notes per minute:

The question arises because I think this is too high to play on the II and III strings (although clearly I am no cellist so I don't really know), and if it is played on the I and II strings then the cellist needs to play a major 9th in order to get the 8ve.
If the passage is not possible at all, then I need to know what makes it impossible to play (or very difficult), be it a problem of excessive hand stretch required or the piece is too fast to ask for an awkward and unfamiliar position and would require a virtuoso to play it, or whatever reason applies.
Comment: It does depend to some extent on the performer -- I can reach a 9th very easily even in first position (using thumb), while my rather petite teacher can do so only with some difficulty. Question: are you planning on changing the key of your piece to "move" this double-stop up the fingerboard? That would seem to be counter to your desire for pitch/timbre combinations in going scordatura in the first place.  Would it be out of the question to allow the performer to use II and III (D and G) to play this double-stop?
Comment: You mean, thanks to the scordatura, the 9th *fingers* like an octave? I mean, a ninth sounds like a ninth; anything that sounds like an octave isn't a ninth.
Comment: Is this an interval, or a double stop? What is the tempo and what duration notes are these? Quarters? Sixteenths? Do the notes have to be legato, or can there be a gap between them?
Comment: Kaz brings up some good points - there are many variables to consider: tempo, preceding material, the figure you intend to write, whether it is a double stop, multi-stop, an arpeggiated chord, etc.  More information is needed before a proper answer can be given.  Thanks!
Comment: I'm lacking some specific terminology because english is not my first language, but to clarify, due to the scordatura, a major 9th is played but it sounds like an octave (the I string is lowered half-tone and the II is raised half-tone). And the idea is that the two notes have to sound at the same time. If there is a way to append an image and show a measure it would be great because it would make things so much clearer, if this function exists please let me know.

Before talking about note duration and articulation, I want to know if it is possible to just play the notes.
Comment: I've searched and yes, what I want is a double stop. I'll edit the question to avoid future confusion.
Comment: @CarlWitthoft Thank for the input, so this is at least physically possible. I don't think it can be done on the II and III, but I added a passage so you can judge for yourself. Regarding your first question, I think the scordatura shines on the rest on the movement because of the sonority and because it allows the use of natural harmonics and open strings. This passage is the only case where the scordatura might seem counterproductive. It facilitates many passages which are more important than this one, so I'd rather change this passage if needed instead of going for standard tuning.
Comment: @CarlWitthoft I'm reviewing the situation and the problem is that a shift from the II and the III to the I and the II is required at some moment... unless that high Eb and Ab were possible on the II. If they are, then I think that is the best solution. Kodaly asks on the ending of his Sonata for Cello Solo Op.8 a B on the I string which is three octaves and a major second higher than the open string. With that reference, the high Ab would be possible on the II since it would be "only" three octaves high, and this whole passage could be played between the II and the III as you suggested.
Comment: FWIW I have successfully fingered II-F to I-F (which if I understand correctly will sound Eb-Eb in your tuning), using thumb position.  In fact, in the Third (CMaj) Bach Suite, I play fingered Eb-Eb during the descending arpeggios in the first movement.  So I think your sample is doable.
Comment: II-F and I-F will sound a F#-E, since the second string is raised a half-tone and the first is lowered a half-tone (I-Ab II-Eb III-Ab IV-Cb). The Bb-Bb on measure 359 would be played I-B II-A.
Did you see my comment regarding the possibility to play this passage on the II and III strings related to the high note asked in Kodaly's Sonata for Cello Solo Op.8?
Answer: A major 9th double stop is not possible using just the four fingers in conventional position -- in that case the maximum double stop would be a minor seventh (or a major seventh with an extension).  However, it is possible using an extended thumb position, especially if the notes are high (e.g. the lower note around an octave above the string on which it's played).  See http://en.wikipedia.org/wiki/Thumb_position for more.
That said, because the passage requires a bunch of these 9th-fingered double stops in rapid succession, requiring an already awkward hand position to shift with every note change, this passage would require virtuosic ability.
Comment: Ah, I see.  The average cellist will never have played a major 9th double stop at all. Now that you've added the passage (and it's clear that you want not just an isolated stop but a bunch of 9ths rapidly moving from pitch to pitch), I'd have to say this passage would require a virtuosic player.
Comment: I already know that the use of the thumb is required, but it is still not clear if a major 9th double stop is something that is achievable for an average cellist or if it would require a virtuoso. I need to know this to decide if it is worth it to use in the music I'm writing.
Answer: The best advice I can offer here would be to find someone that plays cello (well) and ask them to re-tune their instrument and try and work through the passage in question.  I greatly suspect this passage will lead to copious amounts of frustration and head-shaking on the instrumentalist's part.

First:
Strings are used to reading / thinking in sharps because of their
open strings.  Scordatura has its own problems to begin with, but
such awkward intervals mixed with asking the player to think of the
strings as all flats is just begging for your piece to never be
played ever after its premiere.  Not being mean here, just being
practical.
Second:
Are you notating what you want to be sounding when they play with
scordatura tuning or are you notating what you want them to play
with scordatura - regardless of how it sounds?  There seem to be some
notation inconsistencies here.
Third:
Here are some reasons that make your passage extraordinarily
difficult:

Notational inconsistency
Suggested tempo
Range of instrument
Scordatura tuning
Awkward gesture

Cellos have thicker strings, intervals are wider apart, instrument is bigger, and gestures easily done on the violin sound typically less effortless on larger instruments.
Personally, I think this passage is unnecessarily difficult to get the effect that you might be looking for.  Again, I strongly recommend you have someone play this so you can learn first-hand.  I predict that they would end up omitting your octaves in mm.357-358 entirely and arpeggiating the intervals in the remaining measures in order to make the gesture work.
Asking a cellist to meet all of the demands above, as well as marking the notes tenuto with detaché bowing at the specified tempo is at best going to make those measures sound clunky.
Instead, you may want to look into bariolage with legato bowing indications which might give you the effect you're looking for (not to mention emphasize the scordatura - after all, that's the point of scordatura right?)
Also, it's not necessarily my business, but why would you ask such an awkward scordatura and then mark the key signature so traditionally?
Comment: I respectfully disagree with some of this.  quarter=240 means 80 per measure, so look at this as a fast andante triplet pattern.  Transposition is a pain, but is a fact of life for musicians. Violinists occasionally tune up a full step ("voice of the devil" or some such), and as a former clarinetist, I transposed Bb-A, A-Bb, Bb-Eb, Bb-C and more. It's really no tougher than swapping clefs on the fly.
Comment: @CarlWitthoft - Yes, I am aware of the math...my issue regarding tempo wasn't so much for the 2nd half of the excerpt in question, but the first two measures, which is going to be very difficult to get the connected sound the OP is looking for at that tempo.  My point there was for the OP to think about using slurs. Scordatura and transposition are similar but handled differently. The scordatura would be more manageable if it only affected 1 or 2 strings (like much music) or if the OP had retained the original intervals between the strings.
Comment: @CarlWitthoft - By tuning to non-standard intervals, the OP is completely changing all note placement / scalar patterns on the instrument.  This will make learning / playing the piece much less reflexive, and passages / figures that might have worked with normal tuning may no longer be feasible due to new note placement. The resulting scalar patterns would almost be like trying to play an A Cl. in the bottom third of it's range, an F Horn in the middle range, and an English Horn in the upper range - all while reading concert pitch. Yes, it's manageable, but possibly unnecessarily difficult.
Comment: @jjmusicnotes All answer point by point. Regarding notation (the second item you listed), I'm aware that this should be written as you would write a transposing instrument: you write what the player needs to play in order to get the desired result. I can't write it that way yet because I don't know how this passage should be played (if using the I and II strings, or the II and III, or when to switch from a pair of strings to the other), so what I showed as the musical example are the notes that have to sound. I need to know how the passage will be played to be able to write it properly.
Comment: The tuning on each string is self-consistent, but I appreciate your comment on having to learn to play with different intervals between strings.  I admit that it took me a while to get comfy on bass (4ths) after studying cello (fifths).
Comment: @jjmusicnotes Regarding the use of flats, what do you suggest, that I rewrite everything using more sharps than flats? Because if I use an "open key signature" the flats will still be there. The open key in general makes more sense for the piano to me, since the cello plays a lot of melodies that are clearly tonal.
Comment: @jjmusicnotes Bariolage can be an excellent replacement if I have to rewrite the passage, thank you for that suggestion! With the I and the II being a fourth, the unison would not be difficult, right?


Fourier series for a non-periodic function

Question: My textbook says that:
'If we which to find the Fourier series of a non-periodic function only within a fixed range then we must continue the function outside the range so as to make it periodic.'
In the questions at the end of the chapter it then asked you to find the Fourier series for $f(x)=x$ for the range $-\pi<x\le\pi$. So I did what they said and made the function periodic turning it into $f(x)=|x+\pi|-\pi$  for the range $2\pi<x\le2\pi$ which represents a triangular wave.
When I checked the answers they had found the Fourier series straight on the original function without making it periodic.
Which is the right method? If they are both right which do we use when? thanks.
(Here is a link to a website that did it the same way as my textbook did it http://www.sosmath.com/fourier/fourier1/fourier1.html)
Comment: Actually, there are many ways to make a function periodic. The simplest is to take the interval on which it is defined as one period (what your textbook did), but it may happen that it's discontinuous on the border. You may also complete first by symmetry, then by periodicity, and it's what you have done. Both ways are correct. Notice also that in some cases, you can complete to an odd periodic function, or an even periodic function: then you have resp. a decomposition in sine and in cosine.
Comment: Which to use? Whichever you want. Anyway, if it converges, it will always converge to your function in its original interval (or the regularized $(f(a+)+f(a-))/2$ at discontinuities).
Answer: If you consider the function $f(x)=x$ on the interval $[-\pi,\pi)$, and you continue it periodically, then you don't get a triangular wave but you get a ramp (sawtooth) function. It has a positive slope everywhere except at the discontinuities at odd of multiples of $\pi$.
Comment: @Joseph If $f$ is periodic and has a finite number of discontinuities on any interval, then since $\Bbb R$ is an interval, it must have no discontinuities at all. The correct statement is *"a finite number of discontinuities on any **bounded** interval"*.
Comment: But if it has an infinite amount of discontinuities as this would I thought (due to the Dirichlet conditions http://en.wikipedia.org/wiki/Dirichlet_conditions) that we could not use the Fourier series??
Comment: @Joseph: The number of discontinuities is finite *in any given interval*. At the discontinuities the Fourier series converges to the arithmetic mean of both limits.
Comment: @MattL. I edited the Wiki page, as the statement is obviously wrong. Notice $\Bbb R$ **is** an interval.
Comment: @Joseph Don't trust Wikipedia too much (see comment above).
Comment: @Jean-ClaudeArbaut sorry which statement is wrong?


RecyclerView in a ScrollView on Android 4.x, RecyclerView can not scroll

Question: I put a RecyclerView in a ScrollView, set the RecyclerView a explicit height,  When I run on android 5.0, it's ok, the RecyclerView can scroll, but on 4.x, only the outside ScrollView scrolling.
I find out the 5.0 sdk updated the ScrollView source code to support nested scroll, I want to find out way to use the new feature in 4.x.
So I tried to change the ScrollView to android.support.v4.widget.NestedScrollView, but still not working. 5.0 and 4.x have same problem: RecycleView can scroll, but when RecyclerView touched, the outside NestedScrollView cannot scroll anymore unless I drag the view what without click event. Touch on the view which has click event, the NestedScrollView not scroll.
Then I try to update support.v4 to latest version
compile 'com.android.support:support-v4:23.1.1'
Still use android.support.v4.widget.NestedScrollView instead ScrollView, now it works good on 5.0, but 4.x still has the same problem as the early support.v4 version.
This is my code. A whole NestedScrollView outside, some layouts or fragments at top, a ViewPager with fragments at the bottom, the RecyclerView is in the ViewPager's fragment. The code has different running behaviour between 5.0 and 4.x.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="hz.rrs.shop.ShopIndexActivity">

    <hz.rrs.common.views.TitleView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/asi_sc"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/title">

        <LinearLayout
            android:id="@+id/asi_ll_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <fragment
                android:id="@+id/fragment4"
                android:name="hz.rrs.shop.ShopHeaderFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:layout="@layout/fragment_shop_header" />

            <ImageView
                android:id="@+id/asi_iv_service"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:adjustViewBounds="true"
                android:onClick="onClick"
                android:scaleType="fitCenter"
                android:src="@mipmap/shopindex_img_service" />

            <fragment
                android:id="@+id/fragment2"
                android:name="hz.rrs.shop.HeadlineFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                tools:layout="@layout/fragment_headline" />

            <fragment
                android:id="@+id/fragment3"
                android:name="hz.rrs.shop.PuzzleFragment"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                tools:layout="@layout/fragment_puzzle" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:id="@+id/asi_ll_drag"
                android:layout_marginTop="8dp">
                <android.support.design.widget.TabLayout
                    android:id="@+id/tabLayout"
                    style="@style/CustomTablayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

                <android.support.v4.view.ViewPager
                    android:id="@+id/viewPager"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </LinearLayout>

        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

    <ImageButton
        android:id="@+id/asi_ibtn_contact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:background="@null"
        android:onClick="onClick"
        android:src="@mipmap/shopindex_btn_contact"
        android:layout_alignParentRight="true" />

</RelativeLayout>

Comment: Without code is impossible to help you, the question is not clear and you can't use a RecyclerView inside a ScrollView.
Comment: No need to put RecyclerView in ScrollView or NestedScrollView. Because it already implemet these interfaces. Try without them.
Comment: In ScrollView I put some views like RecyclerView's header view,and I need both the outside ScrollView and the inside RecyclerView respond scroll event
Comment: You can attach the header in RecyclerVeiw, then why are you doing something like this?
Look At this Example https://android-arsenal.com/details/1/1841
Comment: thanks for help, but I can't solve it with add headers. Question edited.
Answer: Qustion solved.I update the sdk to newer version, everything is ok.
Set compile sdk version and build tools version to:
compileSdkVersion 23
buildToolsVersion '23.0.2'

Set target sdk version to
targetSdkVersion 23

Also update support.v4 to 23
compile 'com.android.support:support-v4:23.1.1'

Then the RecyclerView can nested scroll in a v4.NestedScrollView on 5.0 and 4.x.
So maybe is a bug of 5.x SDK.


how to by pass Python key error even when key is present?

Question: error
python code
I am getting an key error even when there's a key present.
print (dict_month[0:4])

[{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

'January' in dict_month

False

'january' in dict_month

False
Comment: You have a list of dictionaries, not a dictionary ... January is not a key of dict_month, it's a key for all of your dictionaries.
Comment: or `'January' in i for i in dict_month`
Answer: Simple one liner :
>>> any(['January' in ele for ele in l])

#driver values :
IN : l = [{'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}, {'January': 'Sun'}]

OUT : True

The problem with your approach was as A.Joly mentioned, that you have a list of dictionary. Your approach would have been correct for a dictionary.


Como personalizar o CSS (tr:hover) em uma tabela com thead?

Question: Eu estou criando um projeto para exercitar umas coisas, e fiz uma tabela com dados fictícios, onde, ao passar o mouse, a linha correspondente muda de cor. Só que eu não queria que isso acontecesse com a linha de título.
O que eu posso fazer?
Tentei de tudo mas não deu certo.
HTML:

DADOS

ABC
22.7%

DEF
42.5%

GHI
12%

JKL
54.6%

E O CSS:
#esttt{
    width:300px;
}

#esttt tr{
    line-height:30px;
}

#esttt tr:hover{
    background:#6B6BB6;
    color:#FFF;
}

#esttt thread{
    color:#FFF;
    font-weight:bold;
}

#esttt thread:hover{
    color:#FFF;
    font-weight:bold;
}

Comment: Jovem o pessoal esta te negativado lá a sua pergunta não esta clara, tente no mínimo edita-la e colocar o código que vc ja tem até agora html/CSS isso vai ajudar para te dar uma resposta
Comment: editado. vc pode me ajudar agr?
Answer: Roberto primeiro veja que vc escreveu errado o nome do elemento no CSS... onde está thread deveria estar thead
Antes de mais nada achei a estrutura da sua tabela um pouco estranha... aqui vc pode ocnsultar a documentação da Mozilla https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/table
O esperado seria algo tipo isso separando thead e tbody:

      Header content 1

      Body content 1

Agora sobre o problema e para o :hover pegar em todas as tr menos na primeira vc pode usar o seletor :not() por exemplo e "retirar" da regra css apenas o primeiro th (:first-child) então ficara assim: #esttt tr:not(:first-child):hover
Veja como ficou o resultado com esse modelo usando o :not():

#esttt {
    width: 300px;
}

#esttt tr {
    line-height: 30px;
}

#esttt tr:not(:first-child):hover {
    background: #6B6BB6;
    color: #000;
}

#esttt thead {
    color: #000;
    font-weight: bold;
}

#esttt thead:hover {
    color: #000;
    font-weight: bold;
}

            DADOS

            ABC
            22.7%

            DEF
            42.5%

            GHI
            12%

            JKL
            54.6%

Comment: E se eu quisesse aplicar isso para qualquer outra linha da tabela?
Comment: @RobertoAraujo vc pode simplesmente declarar qual filho não vai receber usando o nth-child da própria regra tipo só a segunda não recebe: `tr:not(:nth-child(2)):hover` ou então fazer uma classe exclusiva pra TR que vc não que que receba o evento tipo: `DEF`
Comment: Ah ok. Justamente porque classe não funciona nesse caso. Já testei. Obrigado.
Comment: @RobertoAraujo se a resposta te ajudou de alguma forma e vc acha que a dúvida foi resolvida considere marcar a resposta como Aceita. Assim evitamos deixar no site perguntas já resolvidas, mas sem resposta aceita pendente.


Wildcard SSL not working for multiple subdomains

Question: I have a wildcard SSL for my website, but I'm getting a strange error in my web browser(s).

You attempted to reach app.dev.mysite.com, but instead you actually reached a server identifying itself as *.mysite.com.

(This is what Chrome tells me is going on)
I don't understand this error.  I thought wildcard SSLs meant that it would work on any subdomain of my site?  How the heck does app.dev.mysite.com not match *.mysite.com?
Oddly enough, app.mysite.com works just fine with this SSL.  What is going on here?  Is there an apache setting for this?
P.S. My domain/SSL is through GoDaddy.
Comment: as @splaer said.  `*` doesn't match `.` .
Answer: You would need another ssl certificate for *.dev.mysite.com per http://www.ietf.org/rfc/rfc2818.txt
Section 3.1

Matching is performed using the matching rules specified by
  [RFC2459].  If more than one identity of a given type is present in
  the certificate (e.g., more than one dNSName name, a match in any one
  of the set is considered acceptable.) Names may contain the wildcard
  character * which is considered to match any single domain name
  component or component fragment. E.g., .a.com matches foo.a.com but
  not bar.foo.a.com. f.com matches foo.com but not bar.com.
Comment: That's what I was afraid of.  I assume I can't just "add" `*.dev.mysite.com` to the SSL, can I?  I'll guess I can ask GoDaddy how I should go about fixing this.  Thanks.
Comment: Correct. The ssl is only valid for base sub domains.
Comment: Guess I'll contact GoDaddy, I assume they can help.
Comment: also just FYI.  cheapssls.com  you can get wildcard certs for way less $ than godaddy.  you might be able to get godaddy to change the cert to *.dev, as opposed to *, but you probably won't get them to do both without buying another cert .  good luck


Do minor penalties become penalty shots when there is "insufficient playing time"?

Question: A couple of situations that call for minor penalties in the rulebook become penalty shots if they are committed when there is "insufficient playing time" to serve them (applies to regulation and overtime). For example, one situation is a defending player displacing the goal frame intentionally; from the 2017-2018 Rulebook, Rule 63.5, Penalty Shot:

If by reason of insufficient time in the regular playing time or by
  reason of penalties already imposed, the minor penalty assessed to a
  player for deliberately displacing his own goal post cannot be served
  in its entirety within the regular playing time of the game or at any time
  in overtime, a penalty shot shall be awarded against the offending
  team

Does this mean that 1:59 or less must be remaining in regulation for a minor penalty to become a penalty shot? Technically, the rule doesn't even mention two minutes; it mentions "insufficient playing time." Does this mean if two minutes remain exactly, the minor penalty can be served in its entirety?
Answer: In the NHL, certain penalties become penalty shots if there is insufficient time remaining, but the vast majority do not. The only penalties that I know of which result in this rule are Delay of Game via intentional displacement of the goal posts and Deliberate Too Many Men, as seen in rule 74.4.

74.4  Deliberate Illegal Substitution
If by reason of insufficient playing
time remaining, or by reason of penalties already imposed, a bench
minor penalty is imposed for deliberate illegal substitution (too many
men on the ice) which cannot be served in its entirety within the legal
playing time, or at any time in overtime, a penalty shot shall be
awarded against the offending team.

This rule means that if there is 1:59 or less remaining on the clock, it defaults to a Penalty Shot, but if it's 2:00 or greater, it's just a minor penalty. The reason the rule book does not specify 2:00 remaining is similar but subtle.
In the NHL, any given team cannot play with fewer than 3 skaters on the ice an a time. This means that if a team is already down 2 skaters, and they receive a 3rd penalty, that penalty time does not actually start until the 1st penalty expires. The player will still be placed in the box and the team will be allowed to continue with 3 players. If it's the case that the team is already down 2 players, and receives a penalty for Delay of Game - Displacing the Goal Posts such that the penalty time won't start until there is 1:59 left, then it's a penalty shot instead.


s3proxy in a closed kubernetes network

Question: I'm using an s3proxy to manage s3 api to blob storage.
It's used by mongodb to store backup.
I'm installing s3proxy with RADAR-Base/s3proxy helm chart with this values file
s3:
  identity: $S3_PROXY_ID
  credential: $S3_PROXY_CRED

target:
  provider: azureblob
  endpoint: $S3_PROXY_AZURE_ENDPOINT
  identity: $S3_PROXY_AZURE_ID
  credential: $S3_PROXY_AZURE_CRED

everything works fined with a port-forward of the s3proxy service and using aws cli
➜  deployment git:(main) ✗ k port-forward -n s3proxy svc/s3proxy-s3-proxy 8000:80
Forwarding from 127.0.0.1:8000 -> 80
Forwarding from [::1]:8000 -> 80
puis que je tape dessus avec aws cli j'ai une bonne sortie
➜  deployment git:(main) ✗ aws s3 ls s3://mycontainer --endpoint http://localhost:8000
2024-02-06 16:20:16         66 fruits.json

but When I tried to do it in a pod I'm getting a forbidden http error
sh-5.1# echo $SECRET_KEY
s3proxy
sh-5.1# echo $ACCESS_KEY
s3proxy
sh-5.1# mc alias set my-s3 http://s3proxy-s3-proxy.s3proxy.svc.cluster.local ACCESS_KEY SECRET_KEY

(I tried to wget to check if it was the dns resolution that might cause the issue, but it resolves with a 403 forbidden)
(yes I'm using s3proxy as an access and secret key)
I thought it might be due to cors origines.
Answer: I just had to use --api s3v4.

s3proxy in a closed kubernetes network


replace rpm with yum while rpm using replacepkgs flag

Question: I use the following rpm syntax in order to install few rpm' syntax that exist under pkgs
rpm -ivh --replacefiles --replacepkgs /home/pkgs/*.rpm

unfortunately in case of rpm dependencies rpm failed , so we want to use yum in order to solve dependencies
in order to use yum , what is the equivalent approach for the above rpm syntax ?
Answer: To reinstall a package with yum is trivial:
yum reinstall <name>


É possivel ter Java SE e Java EE na mesma máquina?

Question: Posso instalar o Java SE e o Java EE na mesma máquina?
Comment: Sim, pode. Na verdade o Java EE é o Java SE com algumas bibliotecas a mais. Já fez algo até o momento?
Comment: Removi da pergunta informações irrelevantes. Se tiver comentários, faça nos campos corretos (estes aqui, embaixo da pergunta, antes do espaço para as respostas). Seria bom esclarecer se tentou e deu algum erro/problema, ou ao menos descrever qual das duas você tem instalada já, assim as respostas e/ou comentários podem dar uma orientação mais específica caso haja algum cuidado ou observação necessários ao instalar.
Answer: O Java EE é uma extensão para o Java SE.
Por exemplo, o Java Standard Edition inclui a API chamada JDBC para acesso ao banco de dados. O Java Enterprise Edition inclui a API chamada JPA para mapeamento objeto-relacional, que, por sua vez, usa o JDBC para acessar o banco de dados.
As APIs do Java SE, em geral, já estão disponíveis quando você instala o Java  na sua máquina. As APIs do Java EE, em geral, precisam ser incluídas à parte. Algumas APIs do Java EE são disponibilizadas pela própria Oracle, que mantém o Java, mas a maioria possui implementações alternativas que podem ser superiores em qualidade ou desempenho. Os Servidores de Aplicação como JBoss/Wildfly, Glassfish, WebSphere, Weblogic, são exemplos de servidores Java EE onde você pode instalar sua aplicação e usar  os recursos do Java EE.
Portanto, sempre que você executa algo usando Java EE, diretamente ou usando algum Servidor de Aplicação que implemente suas APIs, você já tem automaticamente o Java SE disponível.
Além disso, numa mesma máquina, você pode ter um processo do Java (JVM ou Máquina Virtual do Java) executando somente Java SE e outro processo que inclui no classpath as bibliotecas do Java EE.
Comment: Já tenho o Java SE instalado, posso simplesmente instalar o EE?
Comment: @user59673 Você está falando em instalar um servidor de aplicação, tal como o glassfish? Ou está confundindo JRE e JDK com JSE e JEE?


How to generate URL alias without %20 in URL?

Question: We have a custom field that is being used to generate the URL alias.
One issue we have found is that when we set the page to "Autogenerate URL Alias" and set the URL pattern to "[node:field_custom_url]", we are still getting "%20" where the space should be.
We have done the following, but nothing seems to work. We needed assistance to see what else needs to be configured. Ideally, any spaces should be replaced with a "-" instead of "%20". Any thoughts?
Current settings (found in admin/config/search/path/settings):

Path pattern = "[node:field-custom-url]" (we even tried [node:field_custom_url], but it did not work)
Create a new alias. Delete the old alias. = Enabled
Separator = "-"
Transliterate prior to creating alias = Enabled
Reduce strings to letters and numbers
Answer: It is proved that I wrote wrongly in the beginning, thanks @Beebee.

I have read through the code of pathauto module. The module
  implements the token replacement after replacing the space with
  defined separator. So there is no clue by configuration. I would
  consider it is a design fault of the module.

pathauto module clean the url only when the token name does not match with the pattern /(path|alias|url|url-brief)\]$/. You can find it in the function pathauto_clean_token_values(). Obviously, the module author would like to prevent the url alias to be clean twice. As your field name is custom_url, so it is escaped from the checking.
You can fix this by changing your field name or writing your own module as I stated before.

If you know how to create custom module. I would recommend you to implement hook_pathauto_alias_alter for the purpose.
/**
 * Implements hook_pathauto_alias_alter().
 */
function mymodule_pathauto_alias_alter(&$alias, array &$context) {
  $separator = variable_get('pathauto_separator', '-');
  $alias = preg_replace('/\s+/', $separator, $alias);
}

Comment: I don't think we're reading the same code... pathauto replaces spaces with the separator during `token_replace` using a callback `pathauto_clean_token_values`, specifically by calling `pathauto_cleanstring` on the token value.
Comment: You are right, I missed some part of the code. I will edit this answer. Thanks for your sharing.
Answer: Have a look at the Transliteration module. Some details about it (from its project page, with some bold markup added to it):

Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.
Whether you use transliteration for URLs (when using Pathauto 2.x), however, is a matter of personal taste. ...
Answer: Your field token is failing the condition inside pathauto_clean_token_values, specifically as the token name has the reserved word url].
See function pathauto_clean_token_values:
function pathauto_clean_token_values(&$replacements, $data = array(), $options = array()) {
  foreach ($replacements as $token => $value) {
    // Only clean non-path tokens.
    if (!preg_match('/(path|alias|url|url-brief)\]$/', $token)) {
      // Convert language object into language code before pathauto_cleanstring().
      if (isset($options['language']->language)) {
        $options['langcode'] = $options['language']->language;
      }
      $replacements[$token] = pathauto_cleanstring($value, $options);
    }
  }
}

There's a preg_match which looks for:

path]
alias]
url]
url-brief]

in the token names, and your [node:field_custom_url] token will fail the 3rd pattern: url]. That's why your spaces are never replaced by the separator. You need to change your field machine name to be something not ending with the list above.
Comment: thank you for that information. When we created a new field with a different machine name it was working.


Why in the study of counterpoint by johan fux are minor sixths allowed but not augmented fifth?

Question: If augmented fifths and minor sixths are enharmonically equivalent why does johan fux in his book study of counterpoint allow minor sixths but not augmented fifths if they sound the same? How does one distinguish between the two an augmented fifth and minor sixth when composing?
Answer: Fux does allow them in counterpoint.  As I pointed out in one of my comments, confusion comes from voice-relationships:
A minor-sixth is of course allowable between two voices because it is an imperfect consonant interval.
A minor-sixth is not allowable within the same voice because it is a leap greater than a perfect-fifth and is therefore inexcusable in strict counterpoint.
Comment: Minor sixths and octaves are the only leaps greater than a perfect fifth that are allowed in Fux's rules.
Answer: If you're looking at Alfred Mann's translation, he's using standard notation.
This is one of those cases where using standard notation can be really helpful.
In standard notation, something is a fifth if you count 4 lines/spaces up from the starting note.
Fifth
It is a sixth interval is you count 5 lines/spaces up from the starting note.
Sixth
In the natural modes, there are no naturally occurring augmented fifths. However, there are a few natural occuring minor sixths.
In the book, fux says to avoid non-diatonic notes if possible and if you sharpen a note to get an augmented sixth chord, you are adding a non-diatonic note to the music.
In the book, tritones are harmonically forbidden by fux. He either avoid tritones, or he sharpens the fifth(or flattens to lower note), thereby making it a perfect fifth. Most of the time he uses accidentals to change a tritone to a perfect fifth, or at the end of the phrase where it is necessary to get the leading tone.
By the way: For melodies, skips should not be larger than a fifth, OR you can have skips of an octave OR you can have skips of minor sixths ONLY if its going up. I don't recall seeing a skip of greater than an octave but I'd like to know if there is. Tritone skips are also forbidden.


Website, versão mobile

Question: Tenho um website desenvolvido em flash que não têm versão mobile, desenvolvi uma versão mobile em html5, queria que cada vez que o index.html fosse carregado num aparelho mobile fosse esta versão mobile a abrir, como fazer?
Obrigado
PL
Comment: Você pode fazer um if para verificar se é mobile e redirecionar para sua aplicação responsiva.
Comment: É o mesmo site só muda os estilos? se for da pra usar o @media do css -http://www.devmedia.com.br/utilizando-css-media-queries/27085
Comment: hoje em dia já não se perde tempo com código para saber que tipo de browser o utilizador está a usar, pois cada vez são mais e custa imenso manter tal tabela... o que se faz é saber se o browser do utilizador suporta **x** ou **y**... por exemplo, se o tamanho horizontal é menor que 360px... ou se é de 360 a 760... e con isso ter estilos diferentes para cada. Pode sempre tambem saber se o browser suporta ou nao features... procure por "Browser detection versus feature detection"
Answer: Você pode fazer isso com JavaScript ou com Jquery, fica a seu critério.
<code><script type="text/javascript">
var url_mobile = "http://SEU_SITE_MOBILE";
(function(a,b){if(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))window.location=b})(navigator.userAgent||navigator.vendor||window.opera,url_mobile);
</script>
</code>
Jquery:
<code>(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);
</code>
Answer: Você pode detectar o userAgent e redirecionar da forma como queira. Dê uma olhada no Detect Mobile Browsers, utilizando-o seria da seguinte forma:

No index.html, adicione o script detectmobilebrowser.js
Abra o arquivo que foi baixado no fim do texto, altere a URL "http://detectmobilebrowser.com/mobile" para onde quer que seu site redirecione a versão mobile.
Comment: muito obrigado!
Comment: resultou em pleno.

Website, versão mobile


Convertendo JSON para HTML via AJAX em CodeIgniter

Question: Como faço para usar o retorno JSON no HTML? Seguem os códigos.
Função Ajax:
$(document).ready(function(){
  $.ajax({
    url:"<?=base_url('pedido/listar');?>",
    dataType: "html",
    success: function(data)
    {
      $('#pedidos').html(data);
    }
  });
});

Controler:
public function listar()
{
    $this->pedido_model->listarPedidos();
}

Model:
public function listarPedidos()
{
    $this->db->select('*');
    $query = $this->db->get('pedidos');

    foreach ($query->result_array() as $pedido){
        $result[] = array('dados' => '

            '.$pedido['cliente'].'

'.$pedido['idPedido'].'

Aberto

');
    }

    echo  json_encode($result);
}

Comment: O melhor a fazer é retornar o objeto com as informações e usar essas informações no javascript para montar o seu html.... Vou montar um exemplo e colocar como resposta.
Answer: O select do seu model ficaria assim (evitar de consumir banda "internet") com informações que não usa para montar o HTML:
$this->db->select('cliente, idPedido');

O foreach do model você não usaria.
E no ajax você monta o elemento adicionando com um foreach no retorno;
$(document).ready(function(){
   $.ajax({
    url:"<?=base_url('pedido/listar');?>",
    dataType: "json",
    success: function(data)
    {
      console.log(data);
      // loop do conteudo da variavel data aqui
      $('#pedidos').append('
'+
        '
HTML da lista vai aqui
'+
      '
');
    }
  });
});

Comment: Vou fazer aqui pra ver. Obrigado
Comment: So uma dúvida, em js sou meio ruim, como usaria o foreach nele?
Answer: Altere o dataType para "json" e depois faça uma iteração com for...of montando o html para depois inserir tudo de uma vez no elemento #pedidos:
$(document).ready(function(){
  $.ajax({
    url:"<?=base_url('pedido/listar');?>",
    dataType: "json",
    success: function(data)
    {
       var html = '';
       for(var item of data) html += item.dados;
      $('#pedidos').html(html);
    }
  });
});

Comment: Deu certinho. Obrigado :D


C# : How to design a UI that couples to a dynamically generated object?

Question: I have an issue with the software I am developing at work. I am creating a dll file after the user does the following steps.

Specify certain parameters and computation code into a win form.
Specify name of the dll.

Once this is done, I create all the necessary code files (using codeDOM) and compile the source files to generate the dll.
Now, my problem is with the UI. I want to present parameters within the objects of the dll in my UI, but I do not know what parameters the user is going to add.
I want a system where I can maybe specify configuration files to couple the UI elements (which i know in advance) and the objects within the dll (which i have no prior knowledge of, except for the information i can glean off from using Reflection).
So, in effect, I want to bring the coupling between UI elements (label.text, etc) outside of my code and into, maybe an xml file, and my UI should use this xml file to populate data from objects within the dynamically loaded dll.
Please help.
Thanks in advance.
Comment: why dont you use Key Value Pairs? Tuple? or Dictionary?
Comment: You've kinda answered your own question. Use reflection to look for the method name defined in your XML file.. and bind the results to the control name in your text file.. ?
Comment: @DarthVader : Shouldn't the key value pairs be coded in the program. Here, the user might generate a new dll at a later point of time. In such a case, he must be able to just modify the xml configuration file for the UI and then the program must run as it is i.e no recompilation is required.
Comment: @SimonWhitehead : Can you give me an example. I'm new to using reflection. Do you want me to code the 'search and fill' part in the UI and then populate it's 'search' parameters from the XML file?? Is that what you mean? I have considered it, but wouldn't it make the progam slow??
Comment: The idea is to have two programs. One is the admin program that generates the dlls.( I will be the person generating the dlls ). The users will have a client program and will add functionality to their programs by requesting dlls from me.
Comment: Could you use something like a custom attribute to decorate the dll being generated, then reflection can just home into those? You can then use params on the attributes for additional context
Answer: Here is a short code snippet to get you started:
Assembly asm = Assembly.LoadFrom("generated_asm.dll");
// or if the assembly is already loaded:
// asm = AppDomain.CurrentDomain.GetAssemblies().First(a => a.GetName().Name == "Generated.Assembly");

var type = asm.GetType("InsertNamespaceHere.InsertTypeNameHere");

// creates a table layout which you can add to a form (preferable you use the designer to create this)
var tbl = new TableLayoutPanel { ColumnCount = 2 };

// enumerate the public properties of the type
foreach(var property in type.GetProperties())
{
  tbl.Add(new Label(property.Name));

  var input = new TextBox { Tag = property };
  input.TextChanged = this.HandleTextChanged;
  input.Enabled = property.CanWrite;

  tbl.Add(input);
}

and in the handler you could use this:
void HandleTextChanged(object source, ...) {
  var input = source as TextBox;
  var property = input.Tag as PropertyInfo;
  property.GetSetMethod().Invoke(this.instanceOfThatType, new object[] { Convert.ChangeType(input.Text, property.PropertyType) });
}

Hope this helps :)
Answer: I think you might want to look at Prism or MEF (Managed Extensibility Framework).  There's definitely support for the kind of late binding that you're describing. In fact, this is the technology stack we use at work to shimmy in the assemblies for late-binding (more or less like a plug-in architecture).


Updating content types using Features

Question: If I have a series of existing content types in a website and I want to update those content types using a new Feature module (I added some fields), what is the correct method?

Add the entire node?  Will this update the existing content type?
Add just the new and/or modified fields?

Also, these content types were originally created by hand and not by a Feature module.  I just want to add the new fields using the Features module
Answer: With the newest version of Features, it makes it really easy to just add the fields of the content type to the feature. Features are not meant to hold content, like entire nodes. Here's a good example of a feature I've built.
(https://i.stack.imgur.com/rYC7l.png)
Comment: What version of Features are you using?
Comment: I believe that's the newest version of Features, 7.x-2.0-rc1

Updating content types using Features


Inner product of 4 Legendre Polynomials

Question: Is there a closed form for the quadruple inner product of Legendre Polynomials such as:
\begin{align}
\int_{-1}^{1}P_k(x)P_l(x)P_m(x)P_n(x)dx
\end{align}
I am aware of solutions for the triple inner product for Legendre Polynomials.
Answer: Take a look at "J. Miller, Formulas for Integrals of Products of Associated Legendre or Laguerre Functions, Mathematics of Computation, Vol. 17, No. 81 (Jan., 1963), pp. 84-87" and take $m=0$ and $r=4$.

Inner product of 4 Legendre Polynomials


How to build Boost 1.57 for Windows Phone 8 with Visual Studio 2013 Pro?

Question: I want to build Boost 1.57 for Windows Phone 8 but when I run b2 like so
b2 toolset=msvc-12.0 variant=release architecture=arm windows-api=phone

I get strange errors similar to this one for every target
'/Zm800' is not recognized as an internal or external command, operable program or batch file.

My guess is that the build system has not set the compiler properly. It compiles without errors using b2 like so
b2 toolset=msvc-12.0 variant=release

What am I missing? How to compile Boost for Windows Phone 8?
Comment: Yes, I'm going to provide an answer now.
Answer: I found the problem. It seems there is a directory missing in Visual Studio 2013. The solution is to download and copy the files that come with this blog article to the right place:

Please note Visual Studio 2013 didn't include vcvarsphone setup scripts so you won't be able to target Phone 8.1 out of the box. With this blog post I've included phone setup scripts that can be used when targeting Windows Phone 8.1. To setup them up create the folders called WPSDK\WP81 under the VC Visual Studio installation directory, C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\, and copy the phone setup script files in.

BoostSample.zip
Comment: Anyway, I tried to build as in the blog, and I get a errors like this:  fatal error C1083: Cannot open include file: 'boost/thread/futures/is_future_type.hpp': No such file or directory. did this also happened to you?
Comment: I got errors during build, but I don't think this one because I have the following binaries: atomic, chrono, date_time, exception, math, serialization, signals, system, and thread.


p-columnFilter is not a known element

Question: I have also included the TableModule in my module file but still getting this error
Answer: ColumnFilter is a new component. You need to use Angular 11, PrimeNg11, and import into app.module file.

p-columnFilter is not a known element


How to get p-values for the zero-inflated part of a model?

Question: I am having a problem that I am not finding an answer anywhere online.
I used glmmTMB to fit a mixed-model. My data is zero-inflated and I am including 3 variables in the zero-inflated formula.
I was using the Anova in the car package to extract p-values for each of my variables (I know that there are some limitations to it!). However, this only allows me to extract the p-values for the conditional model, and not for the zero-inflated or hurdle model. The summary of the model gives me some p-values but I have categorical variables and, therefore, I get a value for each level of the factors.
Is there any way I can get p-values for the zero-inflated part of the model? And if not, what would be the best way to report a zero-inflated or a hurdle model?
Any help would be greatly appreciated.
Answer: If you check the vignette, you can specify the component using component = :
library(glmmTMB)
library(car)

m1 <- glmmTMB(count ~ spp + mined + (1|site),zi=~mined,family=poisson, data=Salamanders)

car::Anova(m1,component="cond")
Analysis of Deviance Table (Type II Wald chisquare tests)

Response: count
        Chisq Df Pr(>Chisq)
spp   125.625  6  < 2.2e-16 ***
mined  22.238  1  2.408e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

car::Anova(m1,component="zi")
Analysis of Deviance Table (Type II Wald chisquare tests)

Response: count
       Chisq Df Pr(>Chisq)
mined 34.509  1  4.243e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

It is written:

car::Anova constructs type-II and type-III Anova tables for the fixed
effect parameters of the conditional model (this might work with the
fixed effects of the zero-inflation or dispersion models, but has not
been tested)

Don't know if it is tested now..
Comment: Thank you @StupidWolf. Not sure what to do with the "not tested yet" part, though...
Comment: You can simulate your model under the null and see whether anova test makes sense
Comment: unfortunately I do not quite understand what you mean or how to do it. Would it be possible to be more specific? For instance, using your example above...


Java, how to recognize a part of a token as a separate token?

Question: Hopefully my title isn't completely terrible. I don't really know what this should be called. I'm trying to write a very basic scheme parser in Java. The issue I'm having is with implementation.
I open a file, and I want to parse individual tokens:
while(sc.hasNext()) {
   System.out.println(sc.next());
}

Generally, to get tokens, this is fine. But in scheme, recognizing the begining and end of a list is crucial; my program's functionality depends on this, so I need a way to treat a token such as:
(define

or
poly))

As multiple tokens, where any parentheses is its own token:
(
define
poly
)
)

If I can do that, I can properly recognize different symbols to add to my symtab, and know when/how to add nodes to my parse tree.
The Java API shows that the scanner class doesn't have any methods for doing exactly what I want. The closest thing I could think of is using the parantheses as custom delimiters, which would make each token clean enough to be recognized more easily by my logic, but then what happens to my parentheses?
Another method I'm thinking about is forgoing the Java tokenizer, and just scanning char by char until I find a complete symbol.
What should I do? Try to work around the Java scanner methods, or just do a character by character approach?
Comment: related posts on SO: http://stackoverflow.com/questions/17376475/antlr-grammar-for-scheme-r5rs, http://stackoverflow.com/questions/6344766/antlr-resolving-non-ll-problems-and-syntactic-predicates/6349009#6349009.
Comment: it's not only whitespace and parens, but various quotation marks too. Delimiter based scanning won't work there.
Comment: @WillNess Those links would be more helpful if they weren't so advanced. The program I'm working on is for a prequisite course for compiler design, which is not even a required course at my university. I also understand now that I can't use a delimiter based approach, so I think a character based one is my only option...
Comment: looks like it; you can always cook up something ad-hoc, for a basic syntax (without recognizing, say, advanced number syntax e.g. (radix etc.)). Or without the backquote even.
Comment: @WillNess This is the approach my partner and I took. The code is slightly convoluted and probably a little inefficient, but it works. The assignment doesn't call for much beyond recognizing reserved words and some of the syntax. Now I just have to write the rest of it...
Answer: First, you need to get your terminology straight.  (define is not a single token; it's a ( token followed by a define one.  Similarly, poly)) is not a single token, it's three.
Don't let java.util.Scanner (that's what you're using, right?) throw you for a loop -- when you say "Generally, to get tokens, this is fine", I say no, it's not.  Don't settle for what it provides if it's not enough.
To correctly tokenize Scheme code, I'd expect you need to at least be able to deal with regular languages.  That would probably be very tough to do using Scanner, so here's a couple of alternatives:

learn and apply a tried-and-true parsing tool like Antlr or Lex.  Will be beneficial for any of your future parsing projects
roll your own regular expression approach (I don't know Scheme well enough to be sure that this will work) for tokenizing, but don't forget that you need at least context-free for full parsing
learn about parser combinators and recursive descent parsing, which are relatively easy to implement by hand -- and you'll end up learning a ton about Java's type system


Complete Directed Graph and Decision Theory

Question: In decision theory, condition $ \beta $ is defined as follows: If $a,b \in A \subset B, a, b \in C(A)$, and $b \in C(B)$, then $a \in C(B) $. $C(.)$ here is the choice correspondence of a decision maker from a set.
The decision maker has in mind a complete directed graph $\rightarrow$. If the set A contains an element $a$ such that $a \rightarrow x$ for all $ x \in A − \{a\} $, then $C(A) = \{a\}$. Otherwise, $C(A) = A$. Unless $\rightarrow$ is transitive, the correspondence satisfies condition $\beta$.
I don't understand why this is true. For example, I have a counterexample: for $A \subset B$,  $x$ is connected to all elements in B and it is the only element to be so, which makes $C(B) = \{x\}$. Consider another element $y$ that is connected to all elements in $A$. However, since $x$ is connected to all elements in B, it is also connected to all elements in A. Since there are two elements (not one) in A that satisfy the results
, $C(A) = A$, which also includes $x$ and $y$. However, $y \notin C(B)$. Where did I go wrong?
Answer: I understand "complete directed graph" here to be meant as follows: take a complete graph, and orient each edge as you like. (In other words, a tournament.) In such a case, it is impossible to have $v \to w$ and $w \to v$ at the same time.
The proposed counterexample does not work, because we cannot have two elements $x \in A$ and $y \in A$ such that $x \to a$ for all $a \in A - \{x\}$ and $y \to a$ for all $a \in A - \{y\}$. If this were true, then we would have to have $x \to y$ and $y \to x$, which is impossible. In general, for any tournament and any set of vertices $A$, exactly one of the two cases holds:

There is exactly one $x \in A$ such that $x \to a$ for all $a \in A - \{x\}$.
There are no $x \in A$ with this property.

Here is a proof that the choice correspondence $C$ defined from a tournament always satisfies condition $\beta$.
Suppose we have two sets $A, B$ with $A \subset B$. If $C(A) = A$ and $C(B)=B$, then condition $\beta$ definitely holds for all $a,b \in C(A)$. If $|C(A)|=1$, then condition $\beta$ holds trivially: there are no pairs $a,b \in C(A)$ for it to apply to. Therefore the only case we can be worried about is the case that $C(A)=A$, but $C(B) = \{x\}$ for some $x \in B$.
What does such a situation mean? It means that $x \to b$ for all $b \in B - \{x\}$. In particular, if $x$ were an element of $A$, because $x \to a$ for all $a \in A-\{x\}$, we'd conclude that $C(A) = \{x\}$ as well. But we're assuming $C(A) = A$, so we conclude that $x$ cannot be an element of $A$. In particular, $x \notin C(A)$, because $x \notin A$.
Therefore condition $\beta$ still holds for the sets $A$ and $B$. It holds because there cannot be $a,b \in C(A)$ with $b \in C(B)$ as well: $b \in C(B)$ can only happen if $b=x$, but $b \in C(A)$ is incompatible with $b=x$.

As a side note, the claim is "unless $\to$ is transitive, $C(\cdot)$ satisfies condition $\beta$", but it satisfies condition $\beta$ if $\to$ is transitive as well. For a transitive tournament, we can number the vertices $x_1, x_2, \dots, x_n$ such that $x_i \to x_j$ whenever $i < j$. In this case, for every set $A$, there will be a vertex $x \in A$ such that $x \to a$ for all $a \in A-\{x\}$: it will be the vertex with the smallest label. Therefore $|C(A)|=1$ for all sets $A$, and condition $\beta$ holds trivially: there are no pairs $a,b$ for it to apply to.


Using unnest function in R language to split excel cells of a certain column based on regex, getting repetitive results

Question: I have a question, currently I am trying to split cells in an excel file, in a way that I can split each line if that line begins with a digit (and the plus for double digit numbers) and the number is followed by full stop ".", that is, defined by a regular expression that is defined in this function. However, when the actual splitting happens, the output is repetitive (looped) based on other columns.
Here you can find my input data, current output and this is the desired output.
# Load libraries
library('tidyverse')
library('readxl')
library('openxlsx')

# Set functions
do_split = function(x, pattern = "\\d+\\.\\s{1}"){
if( is_tibble(x) ){ x = pull(x) }
num_bullets = x %>% str_extract_all("\\d+\\. ") %>% unlist
x %>% str_split(pattern) %>% unlist %>% .[.!=""] %>% str_c(num_bullets,.) %>% list %>% return
}
# Read data
df = read_excel(path = '~/Desktop/master.xlsx')

# Wrangle data
o = df %>%
mutate(Result = Result %>% do_split, Steps  = Steps %>% do_split) %>%
unnest(Result, Steps)
# Output file
write.xlsx(x = o, file = "out.xlsx")

Comment: Welcome to SO! Please don't provide links to files: they go stale (e.g., disabled/deleted), at which point this question goes unreproducible. Could you provide a sample of each? I don't think the use of `openxlsx` is relevant for your question, so it would be useful to provide the output something like `dput(head(df))`,  and the same for `current` and `expected` outputs. (You might need to change the number of lines to `head` if you need more for practical purposes, such as to properly show variety in the data.)
Comment: also please dont copy `rm(list=ls())` in your questions
Answer: use rowwise() so your mutate command is used on one row at a time...
df %>%
  rowwise() %>%
  mutate_at(vars(Result, Steps), funs(do_split(.))) %>%
  unnest()

if you don't need the delimiter (in your case the leading number, e.g. "1. "), tidyr::separate_rows() might be easier/cleaner...
df %>%
  separate_rows(Result, Steps, sep = "\\d+\\. ") %>%
  filter(Result != "")


flask / flask_restful : calling routes in one blueprint from another route in a different blueprint

Question: I'm working on a very basic Web Application (built using flask and flask_restful) with unrelated views split into different blueprints.
Different blueprints deal with a different instance of a class.
Now I want to design a page with status(properties and value) of all the classes these blueprints are dealing with. The page is a kind of a control panel of sorts.
For this I want to call all the status routes (defined by me) in different blueprints from a single route(status page route) in a different blueprint. I have been searching for a while on how to make internal calls in Flask / Flask_restful, but haven't found anything specifically for this. So....

I would love to find out how to make these internal calls.
Also, is there any problem or convention against making internal calls.
I also thought of making use of the requests calls using Requests module, but that feels more like a hack. Is this the only option I got??? If yes, is there a way I dont have to hard code the url in them like using something close to url_for() in flask??

Thanks..  :)
Answer:

I would love to find out how to make these internal calls.

Ans: use url_for() or Requests module, as u do for any other post or get method.

Also, is there any problem or convention against making internal calls ?

Ans: I didn't find any even after intensive searching.

I also thought of making use of the requests calls using Requests module, but that feels more like a hack. Is this the only option I
got??? If yes, is there a way I don't have to hard code the url in
them like using something close to url_for() in flask??

Ans: If you don't wanna use Requests module, url_for() is the simplest and cleanest option there is. Hard coded path is the only option.