PHP Generate dynamic HTML based on bidimensional array values

Question: I have the following $MessagesArray PHP bidimensional indexed array of one-dimensional associative inner arrays:
Array
(
    [0] => Array
        (
            [id] => 1
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/27
            [time] => 11:00
            [ampm] => AM
            [specialcontent] => none
            [content] => Hello
        )

    [1] => Array
        (
            [id] => 2
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/27
            [time] => 11:00
            [ampm] => AM
            [specialcontent] => none
            [content] => How are you?
        )

    [2] => Array
        (
            [id] => 3
            [from] => Person 2
            [to] => Person 1
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/27
            [time] => 6:00
            [ampm] => PM
            [specialcontent] => none
            [content] => Oh, hey there. I'm fine
        )

    [3] => Array
        (
            [id] => 4
            [from] => Person 2
            [to] => Person 1
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/27
            [time] => 6:01
            [ampm] => PM
            [specialcontent] => none
            [content] => What about you?
        )

    [4] => Array
        (
            [id] => 5
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/28
            [time] => 8:00
            [ampm] => AM
            [specialcontent] => none
            [content] => It's been a while.
        )

    [5] => Array
        (
            [id] => 6
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2016/11/30
            [time] => 2:00
            [ampm] => PM
            [specialcontent] => none
            [content] => Hello?
        )

    [6] => Array
        (
            [id] => 7
            [from] => Person 2
            [to] => Person 1
            [platform] => Instagram Direct Messaging
            [date] => 2016/12/01
            [time] => 3:00
            [ampm] => PM
            [specialcontent] => none
            [content] => Sorry, I'm traveling 'till next year.
        )

    [7] => Array
        (
            [id] => 8
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2016/12/05
            [time] => 1:00
            [ampm] => PM
            [specialcontent] => none
            [content] => Fine by me.
        )

    [8] => Array
        (
            [id] => 9
            [from] => Person 2
            [to] => Person 1
            [platform] => Instagram Direct Messaging
            [date] => 2017/01/04
            [time] => 3:00
            [ampm] => PM
            [specialcontent] => none
            [content] => I'm back.
        )

    [9] => Array
        (
            [id] => 10
            [from] => Person 1
            [to] => Person 2
            [platform] => Instagram Direct Messaging
            [date] => 2018/01/15
            [time] => 1:00
            [ampm] => PM
            [specialcontent] => none
            [content] => I'm back too, one year later too.
        )

)

Whose actual code is (although I actually created the previous array from a database in a XML file):
<?php
    $MessagesArray = array(
        array(
            "id" => "1",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/27",
            "time" => "12:00",
            "ampm" => "AM",
            "specialcontent" => "none",
            "content" => "Hello"
        ),
        array(
            "id" => "2",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/27",
            "time" => "11:00",
            "ampm" => "AM",
            "specialcontent" => "none",
            "content" => "How are you?"
        ),
        array(
            "id" => "3",
            "from" => "Person 2",
            "to" => "Person 1",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/27",
            "time" => "6:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "Oh, hey there. I'm fine"
        ),
        array(
            "id" => "4",
            "from" => "Person 2",
            "to" => "Person 1",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/27",
            "time" => "6:01",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "What about you?"
        ),
        array(
            "id" => "5",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/28",
            "time" => "8:00",
            "ampm" => "AM",
            "specialcontent" => "none",
            "content" => "It's been a while."
        ),
        array(
            "id" => "6",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/11/30",
            "time" => "2:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "Hello?"
        ),
        array(
            "id" => "7",
            "from" => "Person 2",
            "to" => "Person 1",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/12/01",
            "time" => "3:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "Sorry, I'm traveling 'till next year."
        ),
        array(
            "id" => "8",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2016/12/05",
            "time" => "1:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "Fine by me."
        ),
        array(
            "id" => "9",
            "from" => "Person 2",
            "to" => "Person 1",
            "platform" => "Instagram Direct Messaging",
            "date" => "2017/01/04",
            "time" => "3:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "I'm back."
        ),
        array(
            "id" => "10",
            "from" => "Person 1",
            "to" => "Person 2",
            "platform" => "Instagram Direct Messaging",
            "date" => "2018/01/15",
            "time" => "1:00",
            "ampm" => "PM",
            "specialcontent" => "none",
            "content" => "I'm back too, one year later too."
        )
    );
?>

And I'd like to somehow have a code that automatically creates HTML, with the following example:

  2016

    Month 11

      Day 27

      Day 28

      Day 30

    Month 12

      Day 01

      Day 05

  2017

    Month 01

      Day 04

  2018

    Month 01

      Day 15

As you can see, it isn't really that hard, I'm just having a problem figuring out how to use nested foreach functions.
The code should produce a
 HTML element for each unique year, then its corresponding
 HTML element for each unique month of that year, and then at the same time its corresponding
 HTML element for each day month of that month of that year.
I think we need to use nested foreach functions. Suppose we have the code foreach ($MessagesArray as $item) {}, then, inside the function, we could get the year, month, and day as $year = substr($item['date'], 0, 4);, $month = substr($item['date'], 5, 2);, and $day = substr($item['date'], 8, 2);, respectively. I also think we need to someone know the value of the previous iteration.
Comment: @ggorlen I just added it to my post!
Comment: Can you do a `var_export()` of your array? Will make it easier to copy/help you.
Comment: Additionally, you should be able to do something like [this post](https://stackoverflow.com/a/12706456/4875631) to convert your array into something more meaningful to you. Then loop through your array.
Comment: @FrankerZ Do you mean to add the actual code of the array to my post? If so, I just did it //  With the post you linked, do you mean that I sort the array by its IDs?
Answer: Yes, you will need to write code that is aware of the previous row's data.  This can be accomplished with a single loop and some logically positioned condition statements.
Code: (Demo)
$MessagesArray = [
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/28"],
    ["date" => "2016/11/30"],
    ["date" => "2016/12/01"],
    ["date" => "2016/12/05"],
    ["date" => "2017/01/04"],
    ["date" => "2018/01/15"]
];
$yr = null;
$mo = null;
$dy = null;

foreach ($MessagesArray as $row) {
    if ($row["date"] == "$yr/$mo/$dy") {
        continue;  // if repeat of previous date, move to next iteration
    }
    [$y, $m, $d] = explode("/", $row["date"]);
    if (($m != $mo || $y != $yr) && $mo !== null) {
        echo "
";
    }
    if ($y != $yr) {
        if ($yr !== null) {
            echo "
";
        }
        echo "<class='year'>$y";
    }
    if ($m != $mo || $y != $yr) {
        echo "
Month $m";
    }
    echo "
Day $d
";
    $yr = $y;
    $mo = $m;
    $dy = $d;
}
if (sizeof($MessagesArray)) {
    echo "

";
}

Output:

2016

Month 11

Day 27

Day 28

Day 30

Month 12

Day 01

Day 05

2017

Month 01

Day 04

2018

Month 01

Day 15

Comment: This is also the most accurate. I don't really know which one to choose.
Comment: Hahaha, perhaps I ask another question and you answer it? It is a complement of this one, except that it includes echo-ing the messages.
Comment: I'll be rechecking all three answers and check which one is the best of the best.
Comment: **Dude!** There is one problem, your code is repeating days from the same month of the same year, which I dont want. However I think I can fix that myself.
Comment: Thats as simple as just checking days as well as month/year.
Comment: @alej27 whoops, that was silly of me.  I didn't read the question closely enough.  I've corrected my code logic.
Comment: Do you actually want this to be saved as a concatenated string to be `return`ed instead of echoed? Are you running this inside of a custom function or something?  I can adjust again.
Answer: Reformat your array:
$formatted = [];

foreach ($MessagesArray as $Message) {
    $year = substr($Message['date'], 0, 4);
    $month = substr($Message['date'], 5, 2);
    $formatted[ $year ][ $month ][] = $Message;
}

print_r($formatted);

Then it's a simple as looping through:
foreach ($formatted as $year => $months) {
    //Echo year text
    foreach ($months as $month => $messages) {
        //Echo month text
        foreach ($messages as $message) {
            //Echo each text
        }
    }
}

See this php playground.
Answer: Here's a naive approach:
$messages = [
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/27"],
    ["date" => "2016/11/28"],
    ["date" => "2016/11/30"],
    ["date" => "2016/12/01"],
    ["date" => "2016/12/05"],
    ["date" => "2017/01/04"],
    ["date" => "2018/01/15"]
];

$parsed = [];

foreach ($messages as $k => $v) {
    [$y, $m, $d] = explode("/", $v["date"]);
    $parsed[$y][$m][$d] = 1;
}

$html = [];

foreach ($parsed as $y => $v) {
    $html[] = "
$y";

    foreach ($v as $m => $v) {
        $html[] = "
Month $m";

        foreach ($v as $d => $v) {
            $html[] = "
Day $d
";
        }

        $html[] = "
";
    }

    $html[] = "
";
}

echo implode($html);

Output:

2016
Month 11
Day 27

Day 28

Day 30

Month 12
Day 01

Day 05

2017
Month 01
Day 04

2018
Month 01
Day 15

Explanation:
Parse the structure in one loop, then loop over it again to generate the HTML. Note that I simplified your data structure but it'll work the same on any other as long as the "date" key exists. Also, the HTML is minified but identical--if you would like a pretty version, that's not much trouble.
Comment: Why do you create a `$html` array? Why not simply just echo it out?
Comment: Why would you echo it? OP asked to create the HTML, not echo it. I'd rather not write code with side effects unless specifically asked to--keeping it in array or string format gives OP the most options for what to do next, like send it with some JSON or XML to the front end, for example.


Try & Except, maneira correta

Question: A maneira correta de usar o try e except no Python é como?
try:
  variavel = funcao()
except:
  return 'error'

Ou eu faço:
variavel = funcao() e depois eu trato, dessa forma
variavel = funcao()

try:
 return variavel
except:
 return 'error'

Tanto faz? Sou iniciante no Python, e no PHP nunca usei try e catch
Answer: Primeiro o correto é nunca usar um except sem nada - em Python 3 (que é o que você deveria estar usando - Python 2 é incompatível e é uma linguagem no limite pra sair de linha -use Python 3), "except" vazio é erro de sintaxe.
Mesmo o except Exception - que é uma exceção que 'pega tudo' deve ser evitado,a não ser que no bloco de tratamento de erro esteja incluído uma forma de registrar o erro para análise posterior.
A forma correta é: ter a menor quantidade de código possível dentro do bloco try, e ter as exceções mais específicas possível no Except. A ideia nunca é "fingir que não viu o erro" - e sim, impedir que o programa pare dentro de uma situação que já estava prevista e que não depende do programa: um timeout de rede, uma resposta de indisponível de um servidor, um arquivo protegido contra escrita, uma conta feita com números providos pelo usuário que chega numa divisão por zero, etc...
E por fim, quanto a sua pergunta específica - não tem tanta importância assim, mas é melhor você manter menos pontos de return dentro de uma função, por que fica mais fácil entender o que está acontecendo para debugar e dar manutenção -
então:
try:
    resultado = funcao()
except ValueError:
    resultado = "erro"

return resultado

Note como o ideal é ter exceções específicas-  se dentro da função acabar a memória disponível para o processo, isso dá um MemoryError e o programa para. Quando o programa para, o traceback vai dizer onde ocorreu o erro, e é só ir lá e corrigir o trecho que está criando um objeto maior do que é possíbel. Se fosse um Except genérico, o desenvolvedor acharia que era um ValueError, que poderia acontecer mesmo, e ia ficar horas em cima disso tentando achar o problema.
Comment: em Python 3, `except:` sem um nome de exceção da erro de sintaxe.
sim - a sugestão é deixar um único `return` na função - mas isso não é regra. Há casos em que o contrário é preferível - tem que usar o bom senso. Eu gosto de usar mais de um return quando a  tarefa principal da função depende de vários condicionais - então cada coisa que "falha" no caminho, já coloco um `return`  - aí no final da função é garantido que está tudo certo, os dados limpos, e ela pode fazer a ação principal dela sem precisar se preocupar com nenhuma condição a mais.
Comment: Ok, acabei de acordar, tô lesado, então é bom evitar o uso de retorno dentro do except e sim atribuir algo a variável? O correto seria tratar o erro fora do bloco `try`? Ahhh, eu estou usando python 3
Comment: Opa, vou começar a ter este hábito, valeu jsbueno.

Try & Except, maneira correta


Same as shipping checkbox in admin is not showing

Question: While creating an order from Drupal admin section, "Same as shipping" checkbox is not showing, but for normal checkout it is showing.
How do I show the checkbox in the administrative page?
Answer: I'm guessing this checkbox is meant to copy the address from the billing address to the shipping address?
As Ryan pointed out on the frontend this will require ajax as the shipping and billing profiles could be on different steps, however on the backend they are both on the same page so all that is required is some javascript.
For example...
Add the checkbox and custom javascript to the page in a hook_form_alter:
<code>/**
 * Implements hook_form_FORM_ID_alter() for commerce_order_ui_order_form.
 */
function MY_MODULE_form_commerce_order_ui_order_form_alter(&$form, &$form_state, $form_id) {

  // Add the checkbox
  $form['commerce_customer_billing'][LANGUAGE_NONE]['profiles'][0]['copy_from_shipping'] = [
    '#type' => 'checkbox',
    '#title' => t('Copy address from shipping'),
    '#attributes' => ['class' => ['copy-address-from-shipping']],
  ];

  // Attach our custom js
  $form['#attached']['js'][] = drupal_get_path('MY_MODULE', 'taronga') . '/js/copy-address-from-shipping.js';

}
</code>
And then for the javascript:
<code>(function($) {

    /**
     * The Drupal behaviors to copy address from shipping to billing on admin order edit page.
     */
    Drupal.behaviors.copyShippingAddress = {
        attach: function(context) {

            // Only bind our click event handler once
            $('.copy-address-from-shipping').once(function(){

                // Bind the click event
                $('.copy-address-from-shipping').click(function () {

                    var $shipping = $('#edit-commerce-customer-shipping-und-profiles-0');
                    var $billing = $('#edit-commerce-customer-billing-und-profiles-0');

                    if($(this).is(':checked')) { // Copy values from shipping

                        // Loop over inputs & select in shipping fieldset
                        $shipping.find('input, select').each(function () {
                            // Skip any inputs without a name attribute (e.g. chosen)
                            if($(this).is('[name]')) {
                                // Get the name of this field and convert it to the billing name
                                var billing_name = $(this).attr('name').replace('shipping', 'billing');
                                var $billing_field = $billing.find('[name="' + billing_name + '"]');
                                // Make sure the billing field exists
                                if($billing_field.length) {
                                    // Replace the value
                                    $billing_field.val($(this).val());
                                }
                            }
                        });

                    }
                    else { // Clear values

                        $billing.find('input, select').each(function(){
                            $(this).val('');
                        });

                    }
                });

            });

        }
    };

})(jQuery);
</code>
Comment: @RyanSzrama yes, on the front end you are right, ajax will be needed as the billing and shipping profiles could be on different steps. But on the backend they are both on the same page so just straight javascript will do the trick. I've updated my answer with an example.
Comment: It's actually more than just JavaScript; it's an Ajax enabled form that interacts specifically with the checkout form to work across checkout pages and more. There's no simple way to enable it on the back end.
Answer: Make sure to specify whether you're using Drupal 7 or Drupal 8 in your questions, as the feature sets in the Commerce modules do diverge. That said, in either case, this functionality is currently not possible. I doubt it will be added in Drupal 7 given the constraints of how the checkbox was implemented to be unique to the checkout form, but look for address book support on the back end in Commerce 2.x as soon as we resolve some tricky profile select element issues.


How do I check if a path is a directory using Okio?

Question: I am using Okio in Kotlin/Native. How do I check if a path (for example /path/to/directory) denotes a directory?
The scope of the check has to involve using the file system to check if the path denotes a file or a directory.
Example:
"/path/to/directory".toPath().isDirectory // should be true if it exists as a directory
"/path/to/file.txt".toPath().isDirectory // should be false if it does not exist or exists but is a file

Answer: Here are two extension functions. They use FileSystem.metadataOrNull to retrieve metadata about the path and then proceed with checking if the path is a directory/regular file.
In case the file does not exist or there is an error, false will be returned.
val fs = FileSystem.SYSTEM

val Path.isDirectory get() = fs.metadataOrNull(this)?.isDirectory == true
val Path.isRegularFile get() = fs.metadataOrNull(this)?.isRegularFile == true

Comment: Metadata is the correct approach.


Receiving a static URL from blob in AppEngine

Question: In my app, I am creating a blob which is correctly uploaded in the App Engine Dashboard. However, this created file needs to be send to the respective person via email. In order to do this I either need the file itself as an attachment or a static URL where this person can download it. I have trouble figuring out how to obtain a static URL from the blobkey.
This is the code to create a file, it's nothing special though:
    file_name = files.blobstore.create(mime_type='text/csv')
with files.open(file_name, 'a') as f:
  f.write(dataset)
files.finalize(file_name)
blob_key = files.blobstore.get_blob_key(file_name)
blob_info = blobstore.BlobInfo.get(blob_key)

new_url = blob_key.urlsafe()

Answer: If you want to serve the file, look at the Blobstore Overview - Serving a Blob.
If you want to send it as an attachment see the Attachments Documentation. You will need to fetch the contents of the blob and then attach it to the mail.
from google.appengine.ext import blobstore

# blob_key = ...

# Instantiate a BlobReader for a given Blobstore value.
blob_reader = blobstore.BlobReader(blob_key)

# Read the entire value into memory. This may take a while depending
# on the size of the value and the size of the read buffer, and is not
# recommended for large values.
blob_contents = blob_reader.read()

Comment: ignore my (deleted) answer. This answer and it's link explains it all.
Answer: Take a look at the AppEngine Blobstore docs, they do a good job of explaining how to retrieve and work with Blobstore entries. Here is the example from the docs.
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
  def get(self, resource):
    resource = str(urllib.unquote(resource))
    blob_info = blobstore.BlobInfo.get(resource)
    self.send_blob(blob_info)

Answer: My use case is different, but I am serving static content from the blobstore by looking up the url path.  Here is the model and the get function.
class StaticContent(db.Model):
    body = db.BlobProperty()
    content_type = db.StringProperty()
    last_modified = db.DateTimeProperty(required=True, auto_now=True)
    etag = aetycoon.DerivedProperty(lambda x: hashlib.sha1(x.body).hexdigest())

def get(path):
    return StaticContent.get_by_key_name(path)

You can see my wepapp2 handler on step1 tag of my master branch in my git hub repo
For a detailed explanation, you might also check out Nick Johnson's blog post on serving static content via a blogstore.


Fazer um If em c++ limitando as respostas

Question: O usuário digita o ano, mês, dia e temperatura, mas preciso limitar as respostas.

ano não pode ser menor que 1850 e maior que 2021
mes não pode ser menor que 1 e maior que 12, dia não pode ser menor que 1 e não pode ser maior que 31
temperatura não pode ser menor que -50 e maior que 65.

Tentei essa verificação mas não vai ...
cout<<"\nPor favor digite o dia: ";
cin>>dia[i];
cout<<"\nPor favor digite o mês: ";
cin>>mes[i];
cout<<"\nPor favor digite o ano: ";
cin>>ano[i];
cout<<"\nPor favor digite a temperatura: ";
cin>>temperatura[i];
cout<<"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";
if ((dia[i] > 30) || (mes[i] > 12) || (ano[i] < 1850 > 2021)) {
    cout<<"\nAlgo esta inválido";
}

O programa imprime uma mensagem dizendo que algo está inválido.
Comment: Você poderia colocar o restante do código para conseguirmos ter uma visão geral do problema?
Comment: Além de você não estar validando algumas coisas, isso é inválido: `ano[i] < 1850 > 2021`. Precisa verificar uma parte de cada vez: `ano[i] < 1850 || ano[i] > 2021`.
Comment: boa tarde, então não coloquei inteiro porque é um switch e esta incompleto, eu peço essas informações para o usuario e diante disso ele escolhe uma opção que vai usar essas informações por exemplo média das temperaturas...
Comment: legal talvez isso que fiz errado mesmo de não verificar uma coisa de cada vez... obrigada
Answer: Bom, como você deixou apenas uma parte do código, tive que assumir algumas coisas para poder trabalhar em uma solução para você, como você deixou os dados como um array, e construí a solução com base nisso, usando um array int de apenas 2 elementos para facilitar a visualização, e a utilização de um bool para a construção de um loop para continuar pedindo dados até tudo estar correto.
#include <iostream>
#include <locale.h>

using namespace std;

int main(){

    setlocale(LC_ALL,"Portuguese");

    int dia[2], mes[2], ano[2], temperatura[2];
    bool errado;
    //Vai pedir dados para os dois arrays, facilmente modificavel de usar uma variavel ou define no lugar do 2
    for(int i=0; i<2 ;i++){
        do{
            cout<<"Set de dados " << i+1 << "\n";

            cout<<"\nPor favor digite o dia: ";
            cin>>dia[i];
            cout<<"\nPor favor digite o mês: ";
            cin>>mes[i];
            cout<<"\nPor favor digite o ano: ";
            cin>>ano[i];
            cout<<"\nPor favor digite a temperatura: ";
            cin>>temperatura[i];
            cout<<"\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n";

            if ( (dia[i] > 30 || dia[i] < 1) || (mes[i] > 12 || mes[i] < 1) || (ano[i] < 1850 || ano[i] > 2021) || (temperatura[i] < -50 || temperatura[i] > 65)  ) {
                cout<<"\nAlgo esta inválido! Digite novamente!\n";
                errado = true;
                i--;
            }else errado = false;
        }while(errado);

    }

    return 0;
}

Porém como o Rafael Tavares mencionou, você não pode comparar mais de 2 coisas ao mesmo tempo no C, tem que fazer uma por uma, assim como exemplifiquei


Neuro fuzzy system for classification

Question: I am applying a Neuro-fuzzy system for classifying objects. I found only a single paper "Rough-Neuro-Fuzzy System with MICOG Defuzzification," and it is tough to follow how the output, which is the class, is defuzzified and the interpretation of the defuzzified class.
For example: If object{color} is Green And object{size} is small And object{shape} is Square Then Object is GreenBox. Hence, the Situations are the class labels {GreenBox, RedCup, Table}. The application is that these represent situations where the shopper is at a particular counter. That is, the shopper is shopping for boxes or cups, or furniture.
I have questions regarding the defuzzification step of the neuro-fuzzy system used in classification. Neurons in layer 1 provide input values to the network. Neurons in layer 2 represent fuzzy sets defined on the input variables: each neuron receives the input value and computes a membership value through a Gaussian function. Each neuron in layer 3 corresponds to a rule; it is connected to the neurons in layer 2, which implement the fuzzy sets and computes the activation strength as a product of the membership values. Layer 4 is the class variable. Say there are 3 classes C1: [0 1 0]; C2: [0 0 1]; C3: [0 1 1]; and there are 5 input nodes. According to fuzzy set theory, after the variables are fuzzified, there should be a module for defuzzification. So, how is the class label defuzzified? And then, we can confidently say that there is an 85% probability that the shopper is shopping for furniture if the input patterns are labeled under Class 3. I shall be grateful for your insights. Thank you
Answer: Your question, as I understand it, is this:
So, how is the class label defuzzified and then we can say with a confidence that 85% probability that the shopper is shopping for furniture if the input patterns are labelled under Class 3.
I use the following to understand defuzzification:
 - http://www.mathworks.com/help/fuzzy/examples/defuzzification-methods.html
 - http://www.cse.dmu.ac.uk/~rij/newrep/node16.html
Have you considered something like this:
 - http://sipi.usc.edu/~mendel/publications/FLS_Engr_Tutorial_Errata.pdf
It contrives the FL problem so they allow direct and parallel comparison with feedforward neural networks.
Have you considered radial basis function networks?  They can be trained to give outputs of mahalanobis distance given inputs of the parameters.  Mahalanobis distance can be converted to probability density.
Answer: Since you want a probability distribution to be output in the last layer, you make the last layer be a differentiable normalization function that sums to 1.
One function that is well used and well understood in this regard is the SoftMax function, and it is used widely as the last layer of the neural network, with a negative log-likelihood cost function.
Comment: Apply the following function to your last layer's neurons:
f_i(x) = exp(x_i-shift) / sum_j exp(x_j-shift), where shift = max_i x_i.

Here f_i(x) is your i-th neuron's output, and x_i, x_j are your neurons, i.e. loop over all neurons x1, x2, ... xi
Comment: Thank you for providing the function information. Is it possible for you to explain how to actually apply it and the implication with an example? The theory is quite complicated and difficult to visualize.

Neuro fuzzy system for classification


how to get only value json file text website by python

Question: My file json :
{"Id":94477,"StrId":"\u003ca class=\u0027title-8 \u0027 title=\u002794477\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e94477\u003c/a\u003e","Quan":"\u003ca class=\u0027title-8 \u0027 title=\u0027Bình Tân\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eBình Tân\u003c/a\u003e","Duong":"\u003ca class=\u0027title-8 \u0027 title=\u0027Liên Khu 2-10\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eLiên Khu 2-10\u003c/a\u003e","Gia":"\u003ca class=\u0027title-8 cred\u0027 title=\u00272.8 Tỷ\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e2.8 Tỷ\u003c/a\u003e","DienTich2":"\u003ca class=\u0027title-8 \u0027 title=\u00274x12\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e4x12\u003c/a\u003e","LoGioi2":"","Huong":"\u003ca class=\u0027title-8 \u0027 title=\u0027Đông\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eĐông\u003c/a\u003e","Url":"\u003ca class=\u0027title-8 \u0027 title=\u0027Chi tiết\u0027 target=\u0027_blank\u0027 href=\u0027https://www.facebook.com/media/set/?set=oa.2342022366052447&type=3\u0027\u003eChi tiết\u003c/a\u003e","ChuNha":"\u003ca class=\u0027title-8 \u0027 title=\u0027Chị Tuyết\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eChị Tuyết\u003c/a\u003e","SoNha":"\u003ca class=\u0027title-8 \u0027 title=\u0027đã bán.17/19 (Hình+Sổ A.Hùng)\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eđã bán.17/19 (Hình+S\u003c/a\u003e","ViTri":null,"HienTrang":"","Email":"","LuotXem":6,"DienThoai":"\u003ca class=\u0027title-8 \u0027 title=\u00270934942927\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e0934942927\u003c/a\u003e","Phuong":"\u003ca class=\u0027title-8 \u0027 title=\u0027Bình Hưng Hoà A\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003eBình Hưng Hoà A\u003c/a\u003e","NgayTao":"\u003ca class=\u0027title-8 \u0027 title=\u002706/09/2019\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e06/09/2019\u003c/a\u003e","IsHot":true,"HienTrang2":"\u003ca class=\u0027title-8 \u0027 title=\u00271 Tấm\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e1 Tấm\u003c/a\u003e","LoGioi":"\u003ca class=\u0027title-8 \u0027 title=\u00276M\u0027 target=\u0027_blank\u0027 href=\u0027/Detail.aspx?Index=94477\u0027\u003e6M\u003c/a\u003e","CurrentMember":{"Id":10229,"Role":"Member","Username":"quang032018","Ten":"Quang Btra"},"OwnerId":10154,"ChoiceItemIds":[75877,60468,84656,83414,84419,83007,60545,83357,84699,83012,79450,60644,92436,92437],"Map":null,"Cancel":"","Choose":"\u003ca href=\u0027javascript:void(0);\u0027 class=\u0027pointer inblock w4\u0027 ref=\u002794477\u0027 onclick=chooseItem(this);return false;\u0027\u003eChọn\u003c/a\u003e","Sua":"","Xoa":"","Up":"","CanEdit":false,"IsChose":false}

My code :
import json

data = json.load(open("tem.txt", encoding='utf-8-sig'))

for x in data:
    print("%s: %s" % (x, data[x]))

How to get only value , dont have
Comment: what is your expected result? what means that "dont have"?
Answer: You should validate the json text first, and
import json

data = json.load(open("test.txt", encoding='utf-8-sig'))

for k, v in data.items():
    if v is None:
        print(k, v)
    elif v == '':
        print(k, v)

gives the results
LoGioi2
ViTri None
HienTrang
Email
Map None
Cancel
Sua
Xoa
Up


Axum vs TPL, Async

Question: Axum is a language of its own based on subset and superset of C# 3.0 and TPL is extentions added to .Net 4.0. My question is, how does Axum compare to TPL in terms of performance, implementation and architecture.
Same question for the C# 5.0 Async.
I realize Axum is not automatically available such as TPL is, so assume that one has already installed Axum.
To me it seems like Async is trying to band-aid a problem where as Axum is preventing the wound from occuring in the first place.
Answer: Axum is dead:

Those who have followed this blog will have noticed that it's been a long time since we posted anything new about Axum, and the time has come to state publicly that which may have been clear to some but not others, that we're not currently pursuing productization.

That doesn't mean it's not interesting for study of course, but if you're looking for what's going to be useful and released, you should be looking at TPL and async. (Obviously for async you still need to install the CTP as well.)
In terms of the "prevention vs band-aid" question, I think you're broadly right:

On the other hand, the concepts around safe parallelism and agent-based programming were seen by many as too far outside the mainstream to be adopted now in languages like C# and VB. The idea of Axum was to not force these concepts on general-purpose languages, so those of us who have work on Axum are not surprised.

In terms of the speed of async in C# 5 vs TPL - async builds on the TPL, so the performance is broadly comparable. I believe that the Parallel team have been optimizing Task<T> so that it works better with async in terms of avoiding some of the object instantiation which currently occurs to schedule a continuation etc. In other words, any gap in performance between hand-crafting async code using TPL and using C# 5's asynchronous methods is likely to narrow for the final release.
If you're interested in how async uses TPL behind the scenes, you might want to read my Eduasync blog series.
Comment: Dang. I didn't see that notice, That's what I get for reading a 2009 MSDN magazine :)

Axum vs TPL, Async


URLConnection.getInputStream() : Connection timed out

Question: I use the code from Sun's java tutorial
import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL yahoo = new URL("http://www.yahoo.com/");
        URLConnection yc = yahoo.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

Stack trace is same as Connection timed out. Why?
I suspect that might be problem with firewall but

ping to google.com is okay
it works in browser
this approach fails for every URL I provide
I use DJ WebBrowser component in other program and it works okay as a browser

How can I investigate more about this problem?
Can I get to know which port numbers are going to be used when I run the code?
Thanks
Comment: It is a company network. Yes, with high probability. I have not tested it anywhere else.
Comment: If you are using Firefox, go to Tools > Options > Advanced > Network > Settings and see if there is any proxy url being configured.
Comment: What about any firewall settings? What OS are you on?
Comment: In Google Chrome it says there is Automatic Configuration Script configured and not Proxy Server directly.

I am using Windows 7, there is no personal firewall, but I am sure there is company's firewall.
Comment: Are you running this code on your companies server or its just on your local machine? If its on server I think that its a firewall issue.
Answer: Find the proxy that is used by your company and set it in your program. Quoting code from [1]
//Set the http proxy to webcache.mydomain.com:8080

System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");

// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();

// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);

// From now on http connections will be done directly.

[1] - http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
Comment: that's correct! thanks. The last unset property should have "", not null.
Answer: There is also a HttpURLConnection that might work better in some cases. It doesn't appear to disconnect in the same way.
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(callTimeout);

and so on.


Unir o resultado de uma query na mesma linha a partir do sequencial

Question: Tenho a seguinte consulta:
<code>SELECT *
FROM SERQUENCIAL
WHERE DATA BETWEEN '2017-01-01' AND '2017-01-19'
</code>
Ela retorna:
<code>+--------------+-------+------------+-----------------------+
| ID_PESS NOME | DATA  | DATA_HORA  |      SEQUENCIAL       |
+--------------+-------+------------+-----------------------+
|         8788 | JOAO  | 2017-01-01 | 2017-01-01 13:01:01 1 |
|         8788 | JOAO  | 2017-01-01 | 2017-01-01 15:07:01 2 |
|         8788 | JOAO  | 2017-01-01 | 2017-01-01 17:08:01 3 |
|         8788 | JOAO  | 2017-01-01 | 2017-01-01 19:03:01 4 |
|         8533 | MARIA | 2017-01-03 | 2017-01-03 11:01:01 1 |
|         8533 | MARIA | 2017-01-03 | 2017-01-03 14:07:01 2 |
|         8533 | MARIA | 2017-01-03 | 2017-01-03 16:08:01 3 |
|         8533 | MARIA | 2017-01-03 | 2017-01-03 18:03:01 4 |
|         8935 | JOSE  | 2017-01-05 | 2017-01-05 13:01:01 1 |
|         8935 | JOSE  | 2017-01-05 | 2017-01-05 19:07:01 2 |
|         8935 | JOSE  | 2017-01-05 | 2017-01-05 20:08:01 3 |
|         8935 | JOSE  | 2017-01-05 | 2017-01-05 22:03:01 4 |
|         8935 | JOSE  | 2017-01-05 | 2017-01-05 23:03:01 5 |
+--------------+-------+------------+-----------------------+
</code>
Como faço para unir os retornos por pessoa da seguinte forma por exemplo:
<code>+---------+------+------------+---------------------+------+---------------------+------+---------------------+------+---------------------+------+
| ID_PESS | NOME |    DATA    |    DATA_HORA_01     | SEQ1 |    DATA_HORA_02     | SEQ2 |    DATA_HORA_03     | SEQ3 |    DATA_HORA_04     | SEQ4 |
+---------+------+------------+---------------------+------+---------------------+------+---------------------+------+---------------------+------+
|    8788 | JOAO | 2017-01-01 | 2017-01-01 13:01:01 |    1 | 2017-01-01 15:07:01 |    2 | 2017-01-01 17:08:01 |    3 | 2017-01-01 19:03:01 |    4 |
+---------+------+------------+---------------------+------+---------------------+------+---------------------+------+---------------------+------+
</code>
Ou seja, os dados da pessoa juntos na mesma linha.

Observação:
Os dados da pessoa podem se repetir em outro dia. Caso aconteça será
uma nova linha da pessoa.
Comment: Não seria possível utilizar o `Group by` na coluna `ID_PESS`
Comment: Não porque ai vai unir e não iria listar os outros campos data e sequencial
Comment: Algumas dúvidas, o Sequencial pode ser quebrado em dois campos? Um com o date e outro com o incremento? Esse número final é gerado como, a partir da aplicação?
Answer: Considerando-se que o número de linhas por pessoa/data é variável, a solução ideal deve empregar o uso de pivoteamento com comando SQL dinâmico.
Eis solução que funciona com nível de compatibilidade 80 (SQL Server 2000) em diante.
<code>-- código #1 v4
-- define período de emissão
declare @DataInicial date, @DataFinal date;
set @DataInicial= Convert(date, '1/1/2017', 103);
set @DataFinal= Convert(date, '19/1/2017', 103);

-- obtém maior valor de sequencial
declare @maxSequencial int, @I int;
set @maxSequencial= (SELECT max(SEQUENCIAL) from tabela);

-- monta o comando sql dinâmico
declare @SQL nvarchar(4000);

set @SQL= N'SELECT ID_PESS, NOME, DATA, ';

set @I= 1;
while (@I <= @maxSequencial)
     begin
     set @SQL+= N'max(case when SEQUENCIAL = ' +
                Cast(@I as nvarchar) +
                N' then Cast(DATA_HORA as smalldatetime) end) as [' +
                Cast(@I as nvarchar) + N'], ';
     set @I+= 1;
     end;
set @SQL= Left(@SQL, Len(@SQL) -1);

set @SQL+= N' from tabela where DATA between @Data1 and @Data2' +
           N' group by ID_PESS, NOME, DATA;';
--
--print @SQL
Execute sp_executesql @stmt= @SQL,
                      @params=N'@Data1 datetime, @Data2 datetime',
                      @Data1= @DataInicial, @Data2= @DataFinal;
</code>
Answer: Boa tarde.
Eu faria o seguinte:
1- não deixaria o nome do empregado/cliente/empregado, mas usaria o ID deles (previna os homônimos); e
2- tu fará uma busca com INNER JOIN (não sei como funciona no SQL Server).
Lembre-se que todo sequencial possui um ID e dependendo do tipo de relatório que tu gerará, vale a pena tê-lo. Já para ordenação, utilize um ORDER BY composto pelo ID (prevenindo homônimos) e o número sequencial.
Answer: @José Diz ,
 Optei por essa que também foi uma dica sua, pois precisei implementar mais coisas na consulta e rodou bem com ela. Obrigado pela ajuda.
<code>-- código #2 v2
-- define período de emissão (formato dd/mm/aaaa)
declare @DataInicial date, @DataFinal date;
set @DataInicial= Convert(date, '1/1/2017', 103);
set @DataFinal= Convert(date, '19/1/2017', 103);

--
SELECT ID_PESS, NOME, DATA,
       max(case when SEQUENCIAL = 1 then Cast(DATA_HORA as smalldatetime) end) as [1],
       max(case when SEQUENCIAL = 2 then Cast(DATA_HORA as smalldatetime) end) as [2],
       max(case when SEQUENCIAL = 3 then Cast(DATA_HORA as smalldatetime) end) as [3],
       max(case when SEQUENCIAL = 4 then Cast(DATA_HORA as smalldatetime) end) as [4],
       max(case when SEQUENCIAL = 5 then Cast(DATA_HORA as smalldatetime) end) as [5],
       max(case when SEQUENCIAL > 5 then 'MAIS DE 5 DATAS!' else '' end) as [Obs]
  from tabela
  where DATA between @DataInicial and @DataFinal
  group by ID_PESS, NOME, DATA;
</code>


What does the union symbol (∪) before the set builder notation mean?

Question: I am reading Robert André's book Axioms and Set Theory and, maybe starting at chapter 12, he uses the notation like $\mathbb{N}=\cup\{n \mid n \in \mathbb{N}\}$, where he puts a union symbol (∪) before the set builder notation. I do not know what it means, though I suspect it is a typo.
Hence, my question: what does $\cup\{x \mid \phi(x)\}$ mean?
Comment: @littleO It is not nonsense in the standard set theory building of the natural numbers, see my answer
Comment: @Alan: It is not an abuse of notation. It is the notation.
Comment: The notation $\mathbb N = \cup \{ n \mid n \in \mathbb N \}$ is almost nonsense, and seems unlikely to be written in a math book. I'd like to see a screenshot. I would interpret it to mean that you are taking a union of a single set, which is $\{ n \mid n \in \mathbb N \}$. Of course, that set is just $\mathbb N$.
Comment: @littleO  It's lazy abuse of notation to write $\cup x$ instead of $\cup_{x\in I} x$ when the index set is obvious
Comment: $\bigcup X=\{y:\exists z\in X\,(y\in z)\}$. And in set theory everything is a set, including any member of $\Bbb N.$
Comment: @user21820, the answer does say something wrong, which the author corrects in the comments. I do not see why you would close the question instead of asking me to unaccept the answer or ask the author to change the answer, or even suggest an edit. But I am not putting responsibilities onto you nor saying you should.
Comment: @Schilive: Alan did **not** admit any mistake in the comments, and the last comment ("No, I meant ⋃x, it's the union of all the sets x that are a member of the obvious superset, in this case ℕ") is **plain WRONG**. If you unaccept that answer and accept egreg's instead, I'm fine with it. Otherwise this thread is not worth keeping because it is extremely misleading to all future readers.
Comment: @littleO, if you want you check it here: [The book](https://www.math.uwaterloo.ca/~randre/1aaset_theory_140613.pdf#page=137) or the [screenshot](https://drive.google.com/file/d/1okRZ9jZ05LW329zzOMY2RRVfQkF1asZe/view?usp=sharing). It is the 14th exercise.
Comment: @Alan I think that I am making a more basic point.  If $S$ is a set, and I write $\cup S$, what does that mean? I would think it means that we are taking a union of a single set; but then it is strange to write $\cup S$ rather than simply $S$.
Comment: Oh, now I think I am starting to understand— as you mentioned, since each natural number is a set, this union is not as pointless as it seemed to me at first.
Comment: @littleO Exactly. I added a second addendum to my answer to explain the abuse of notation
Comment: I'm voting to close this question because the asker accepted a bogus answer, as already adequately pointed out by Asaf and David.
Answer: In a set theory development of the natural numbers,  what we do is we start with nothing but sets and then build structures within that mimic our knowledge of numbers and operations on them.  The standard construction for the natural numbers is to set
$$0:=\emptyset $$
and then inductively define each following natural number by the successor function $s(x)$ which gives the next number after $x$ as
$$s(x+1)=x\cup \{x\}$$
So   $0=\emptyset$ $1=\{0\}=\{\emptyset \}$,  $2=1 \cup \{1\}=\{0\}\cup \{1\}=\{0,1\}$, etc.
Note in this construction the only objects are the empty set and sets built from the empty set,  the numbers are just names we assign to certain configurations of the sets.   In this configuration,  it is true that any natural number is just the set of all the previous numbers
$$n=\{0,1,2,...,n-1\}$$
Thus it makes the sense to take the union of the numbers because numbers are just names for special sets.   And when you take the union of all of them, you get all natural numbers.
Added: For your exercise, you just want to show the two sets are equal, so as usual, show they are subsets of each other.  So show any natural number is in that union,  and then show that any member of that union is in fact a natural number
Second addendum:   Technically the author should have written
$$\bigcup_{x\in \mathbb N}x$$
but when the context of the index set is obvious, we often do abuse of notation and skip writing the index set and go straight to
$$\bigcup x$$
Comment: Technically, $\bigcup_{x\in X} x$ is the abuse of notation. Since $\bigcup$ is a new function symbol that is added as a conservative extension to the language of set theory (under the axioms of Union and Extensionality), using the subscript is an abuse of notation.
Comment: Your last comment sounds like you think that $\bigcup_{x\in\Bbb N}x=\bigcup x$. In fact $\bigcup_{x\in\Bbb N}x=\bigcup\Bbb N$.
Comment: @Schilive No problem, and yeah,  it's the notion of a "transitive" set.  If this fully answered your question,  go ahead and mark the check box next to it to acceptit
Comment: Thank you very much for the answer. It is a funny concept, that the union of the all the elements of a set is the set itself.
Comment: @DavidC.Ullrich Yes,  I was going back and forth in real time, the latter is what I meant
Comment: @AsafKaragila I keep meaning to go back and study some actual formal logic on my own. I only had one grad school course on set theory for foundational stuff and always felt like I was missing out not having taken logic first
Comment: @Alan, could you, please, change $\bigcup x$ to $\bigcup \mathbb{N}$, since I believe that was that you wanted to say? Thank you for the answer either way.
Comment: @Schilive No, I meant $\bigcup x$,  it's the union of all the sets $x$ that are a member of the obvious superset, in this case $\mathbb{N}$
Comment: @Alan, I do not understand, then, how your answer would answer the question, since you did not mention the notation used in the question text, which was $\cup\mathbb{N}$. I thought it was a mistake because of what you said to David C. Ullrich, and before what the [site](https://proofwiki.org/wiki/Definition:Set_Union/Set_of_Sets#Definition) said.
Answer: The notation is not mysterious and is not "technically wrong" or "abusive" as others commented. You find it in several books; I learned it in the appendix of Kelley's book "General Topology".
If $A$ is a set, then
$$
\mathop{\cup}A=\{x\mid \exists y\,(y\in A\land x\in y)\}
$$
For instance, if $A=\{\{a,b\},\{c\}\}$, then $\mathop{\cup}A=\{a,b,c\}$.
The book you link is not very consistent in notation, I should say.
In the "almost formal" set theory that's developed in the book, everything is a set. And the natural numbers are defined recursively by
$$
0=\emptyset,\quad n^+=n\cup\{n\}
$$
and collecting what's obtained in this way in the set $\mathbb{N}$. Let's see what happens when the union is applied to $1=\{0\}$ instead of $\mathbb{N}$:
$$
\mathop{\cup}\{n\mid n\in 1\}=0=\emptyset
$$
With $2=\{0,1\}$ we get
$$
\mathop{\cup}\{n\mid n\in 2\}=1
$$
There seems to be a pattern. And indeed there is: if $n$ is a natural number and $y\in n$, then $y\subset n$. Since, by definition,
$$
0\subset 1\subset 2\subset\dotsb
$$
you have that, when $m=k^+$
$$
\mathop{\cup}\{n\mid n\in m\}=k
$$
which you can prove by induction. It follows that
$$
\mathop{\cup}\{n\mid n\in\mathbb{N}\}=\mathbb{N}
$$

The notation $\mathop{\cup}A$ is justified by a specific axiom of set theory: the axiom of union states that for any $A$ there exists $B$ such that, for every $x\in B$, there is $y\in A$ with $x\in y$ (probably not the same notation of your book). Using specification, we can isolate from that (possibly big) set the one that we need to use and denote it as shown above.
The "binary union" $A\cup B$ is defined to be $\mathop{\cup}\{A,B\}$.
Answer: It means the union of all such sets which are described by {$x | \phi(x)$}.
Comment: I think this Does Not make Sense because all These Sets are Equal.
Comment: Unless you're trying to define $\mathbb{N}$ as $\bigcup_{n\in\mathbf{N}} \{ n \}$, there is nothing wrong with it appearing on both sides of the equal sign.
Comment: @nomen what do you mean both side of the equal sign? There is no equal sign in my answer
Comment: @insipidintegrator: i mean the left side and the right side.  I agree with you, I am gently replying to miracle173, who is wrong.
Comment: insipidintegrator (If I said this correctly), thank you for the answer. Though I do think FShrike's answer is better, we all want everyone to try to contribute. So, please, if you want to contribute, do it!
Answer: Your notation is undefined (I think) as you need to state what $x$ ranges over (context dependent). But Robert is not making a typo. You might recognise it more if I rewrite it like this:
$$\Bbb N=\bigcup_{n\in\Bbb N}\{n\}$$
Which is true of all sets. $\cup$ just means union, and sometimes people don't put [the set or property which indexes the union] on the bottom, but rather to the side, as Robert has done. That's what "$| \phi(x)$" means: the union is taken over those sets $x$ such that $\phi(x)$. It would be equivalent (provided you had a background from where $x$ will come, like a universe or some other set $A$) to write: $$\cup\{x\in A:\phi(x)\}=\bigcup_{x\in A:\phi(x)}\{x\}$$
Comment: @Schilive $\cup A$ is not $A$, it's a merging of the elements of $A$. If $A$ is a set of sets, e.g. $A=\{\{x\},\{y\},\{z\}\}$, then $\cup A$ usually denotes, in my experience, $\{x,y,z\}$.
Comment: In general $\bigcup_{x\in S}x\ne\bigcup_{x\in S}\{x\}$. The two are equal for $S=\Bbb N$ because of special properties of $\Bbb N$.
Comment: In this case since it is a set theory book, they are probably defining each natural number as the set of all previous numbers, with $0=\emptyset$.  In which case, it is actually true that the natural numbers is the union of the numbers themselves, not the singleton sets (though that's also true,  just trivial)
Comment: @FShrike, then I believe you made a mistake on the text: you meant $\mathbb{N} = \bigcup_{n \in \mathbb{N}} n$ instead of $\mathbb{N} = \bigcup_{n \in \mathbb{N}} \{n\}$. Sorry if I am wrong.
Comment: The set $S = \{ x \in A \mid \phi(x) \}$ is one particular set. Writing $\cup  \{ x \in A \mid \phi(x) \}$ should be equivalent to writing $\cup S$, which is a strange thing to write because we are taking the union of a single set $S$. We might as well just write $S$ instead of $\cup S$.
Comment: Also as I commented above,  the notation is technically ambiguous but is  a very standard abuse of notation when the index set is obvious from context..   The author meant $\cup_{x\in \mathbb{N}}x$ and omitted the index set by abuse of notation
Comment: FShrike, thank you a lot for the answer. I do not understand the reasoning behind the notation, if it makes nothing, which is why I ask: are you that $\cup A = A$ for any set? I think I did not understand you answer; if so, sorry.
Comment: @FShrike, is it not the case that $\bigcup_{n \in A} \{n\} = A$ for any set $A$? or did  you want to say $\cup A = \bigcup_{n \in A} n$?
Comment: @Schilive In my experience of the notation, both sentences that you typed are true
Comment: Under the standard construction of natural numbers using sets, both statements are true, although the first is harder to understand @Schilive but in hindsight is maybe what Robert intended


Can AUC score decrease with the addition of more variables in logistic regression within the training dataset?

Question: I'm building a logistic regression model and am attempting to select the correct variables. One thing that is puzzling to me is the AUC score is decreasing as I add more variables even within the training set. I would expect this to happen in the testing set due to over-fitting, but I don't understand why or how it would occur within the training set.
I am using the sklearn library in Python. Below I use three predictor variables and get an AUC score or ~.83 within the training set
predictors = ["lsat", "gpa", "urm"]
X = train[predictors] #select predictor variables
y = train[["was_accepted"]] #select target variable
logreg = linear_model.LogisticRegression() #create logistic regression model
logreg.fit(X, y) #fit model to the data
predictions = logreg.predict_proba(X)[:,1] #get predictions
auc_score = roc_auc_score(y, predictions)
print(auc_score)
#output = 0.8341757855809823

However, when I run the same code again with four additional predictor variables, I get an AUC of only ~.72.
predictors = ["lsat", "gpa", "urm", "is_military", "softs", "is_international", "years_out"]
X = train[predictors] #select predictor variables
y = train[["was_accepted"]] #select target variable
logreg = linear_model.LogisticRegression() #create logistic regression model
logreg.fit(X, y) #fit model to the data
predictions = logreg.predict_proba(X)[:,1] #get predictions
auc_score = roc_auc_score(y, predictions)
print(auc_score)
#output = 0.7205734302381707

I'm confused as to how the AUC could go lower with the addition of more variables. Even if the new variables have zero predictive power, why wouldn't the coefficients just be set to zero and the AUC stay at ~.83?
I did see this post, which provides some helpful context with a similar issue, but I'm hoping someone here could provide a more definitive answer or direct me to materials that could.
Thank you.
Answer: I think there are a couple of reasons:

Logistic regression does not have a deterministic closed form solution and must be solved iteratively, starting from some random initialization. The solutions are stochastic and depend on their random seed (hence the random_state argument). There's no guarantee that a given search will converge on the lowest cost, i.e. optimal, solution.
The algorithm, as implemented in sklearn anyway, has L2 regularization applied by default. This penalty tries to smooth the coefficients of the logistic function and essentially prevents the model from finding a perfect (and possibly overfit) solution.

I just tried some experiments and I reckon that if you switch to L1 regularization, which tries to push as many coefficients as possible to 0, and ramp up the regularization  penalty, then I think you will find the model stops behaving this way. For example, try instantiating the model like this:
LogisticRegression(penalty='l1', solver='liblinear', C=0.001)

Is it a 'better' model? That's the $64,000 question!

Not sure whether to include my experiment or not, since this isn't really a programming question. But it's here if you're interested.
Comment: Thank you - this is incredibly helpful.
Answer: The logistic regression optimizes the log loss between the predicted probabilities and categories (coded as $0$ and $1$). The true observations are the $y_i$, and the predictions are the $\hat y_i = \dfrac{1}{
1 + \exp\left(-x_i^T\hat\beta\right)
}
$, where $\hat\beta$ is the vector of estimated parameters for the regression model.
$$
L(y,\hat y) = -\dfrac{1}{N}\overset{N}{\underset{i=1}{\sum}}\left[
y_i\log(\hat y_i) + (1 - y_i)\log(1 - \hat y_i)
\right]
$$
Notice that this is not the $AUC$. That is, logistic regression parameter estimation does not seek out the smallest $AUC$. If some parameter values decrease the $AUC$ yet also decreases the log-loss, those parameter values with the higher $AUC$ will be preferred. This can happen if some ability to discriminate between the categories is exchanged for better calibation of the predicted probabilities, as $AUC$ only cares about the ability for the model to distinguish between the two categories.
Therefore...

I'm confused as to how the AUC could go lower with the addition of more variables. Even if the new variables have zero predictive power, why wouldn't the coefficients just be set to zero and the AUC stay at ~.83?

If you train by maximizing the $AUC$, you will observe this, short of numerical issues that arise from doing this kind of strange optimization. However, the default of logistic regression is to find the parameters that optimize log-loss, not $AUC$.
Another answer mentions that logistic regression lacks a closed-form solution and must be solved numerically, putting some of the blame on the merely approximate "solution" given as the logistic regression parameters. While it is true that logistic regression lacks a closed-form solution, modern implementations of the numerical optimization are so good that it almost might as well.
Comment: somewhat related: https://stats.stackexchange.com/q/422784/232706


Is matrix $B$ an image of matrix $A?$

Question: Consider the following two matrices:
$$A=\begin{pmatrix}   e^s&0\\   0&e^{-s}   \end{pmatrix}$$
$$ B=\begin{pmatrix}   e^{e^s} &0\\   0&e^{e^{-s}}   \end{pmatrix} $$
Is $B$ an image of $A?$ If we let $e^s\leftrightarrow s$ then does this imply that $B$ is an image of $A?$ I'm a little confused about this.
Comment: What does it mean to say that a matrix is an image of another matrix?
Comment: I was thinking since $A$ defines a hyperbolic rotation, maybe $B$ would be an image of a hyperbolic rotation?
Answer: Since $B=e^A$, the matrix $B$ is the image of $A$ by the exponential map.

Is matrix $B$ an image of matrix $A?$


Recreate admin user

Question: My login to Drupal 8 instance has failed. ive had a look in the DB and in the users table are 3 entries i dont recognise and the admin username (say 'adminuser') ive been using for the last year (but not accessed for several months) isnt there.
Ive contacted the hosting Co  - they can backup the whole DB to a time when 'adminuser' existed   but i could lose some data . Not too helpful about sorting out what has happened and when though.
Ive got cpanel access . can I recreate my adminuser through  phypmyadmin ? '
Comment: @leymannx, yes, I think so too, if this is Drupal <8.5.3. Then ask your hosting company to restore the site (database and code base) back to April 25th and update before going online again.
Comment: What D8 version is this exactly?
Comment: where can I find that in the DB ?
Comment: `drush uli -l www.example.com` will output you an one-time login link to access your site as admin.
Comment: Apart from that: your site probably got hacked.
Comment: does your server have Drush installed on it?
Comment: dont think so .
Answer: Yes...
But know. The password field has been hashed.
Now their are a few ways to get the correct hashed value to manually add the updated/correct info. For example:
You can use a basic install on a localhost for example to create the user and export that table's content. On your live server via myphpadmin delete the user entery that has UID 1 and import the contents you exported. It will replace the username and password for you to be able to login.

Recreate admin user


Seletor css com nth e not

Question: Tenho um formulário com flexbox, só que quando da um erro é inserida uma div de alert, quebrando o layout.
Tem alguns campos que são 50% na mesma linha
<form method="post" action="XXX" class="form-login">
    @if($message = session('message'))

            {{ $message }}

    @endif

        E-mail
        <input type="email" name="xxx" value="{{ old('xxx') }}">

        Senha
        <input type="password" name="xxx" value="{{ old('xxx') }}">

    <button class="btn btn-logar">
        Logar
    </button>
</form>

E no css tenho
 .form-login.form-group:nth-of-type(1),
 .form-login.form-group:nth-of-type(2) {
     width: 48.3%;
     flex: 1 0 auto;
 }

Isso acontece pois estou usando nth-of-type, qual seria um workaround?
Comment: Poderia por favor postar o código que você tem no momento?
Comment: Um momento, estou pelo celular, já acrescento
Comment: Coloquei um código de exemplo
Answer: Uma solução mais simples, para não usar nth-of-type, é usar as classes form-group que você já tem nos grupos de campos. Então seu CSS ficaria assim:
.form-login .form-group {
    width: 48.3%;
    flex: 1 0 auto;
}

Caso queira usar o nth, poderia ser feito assim:
.form-login .form-group:nth-of-type(n+1) {
    width: 48.3%;
    flex: 1 0 auto;
}

Comment: gostei da solução e funcionou mto bem! obrigado!

Seletor css com nth e not


jQuery - Timer will not delay

Question: In my game I have added a snowflake icon to freeze the time for 3 seconds. I have added this to the script
<code>$(".character").click(function() {
    if ($(this).hasClass("freeze")) {
    $('#timer').delay(3000);
}
</code>
Any ideas why it will not work?
Here is a fiddle.. http://jsfiddle.net/pUwKb/30/
Answer: You missunderstood delay. You have to clear the countdown interval, and set timeout after which the countdown interval will be activated again
<code>$(".character").click(function() {
    if ($(this).hasClass("freeze")) {
    window.clearInterval(countdown);
    window.setTimeout(function(){
      countdown = window.setInterval(...)
    }, 3000);
}
</code>
and you'll have to name the function in order to do so
as for the $.delay it's used to delay execution of jQuery animations
Comment: Ahh I see. Thanks!! For some reason it is saying syntax error now for the (...) part. What is supposed to go there? @Darhazer
Comment: @Milo-J  Here is the working version of your program - http://jsfiddle.net/n5cz4/3/
Comment: Thanks!! What about if I wanted all the other divs to freeze for 3 seconds as well. I have tried to just add $('.character').stop(); but it doesnt work. How would you do that? @Darhazer

jQuery - Timer will not delay


Probability , one on uniform distribution

Question: Let X, Y be two random uniform variates in (0,1).  For $\alpha > 0$, find the probability $P(\max(X,Y) > \alpha \min(X,Y))$.
I tried like the below
$$P(\max(X,Y) > \alpha \min(X,Y)) = 2\int_{0}^{\frac{1}{\alpha}} \int_{\alpha x}^{1} dy dx = \frac{1}{\alpha}$$
Should I multiply by 2 or not?
Someone verify the answer for me, pleasse.
Comment: Your answer is correct if $X$ and $Y$ are independent. Otherwise you cannot determine this probability.
Comment: Thanks Sir, i really appreciate it
Answer: For $0<\alpha\leqslant 1$ we have $\mathbb P(X\wedge Y>\alpha (X\vee Y))=1$, since $X>\alpha X$ and $Y>\alpha Y$. For $\alpha>1$ the region $$\{(x,y)\in[0,1]^2: x\wedge y>\alpha (x\vee y)\}$$ is composed of two equilateral right triangles (one above and one below the line $x=y$). Plotting the region for sample values of alpha, we see that the first region $R_1$ is bounded by the $y$-axis, the line $y=1$, and the line $y=\alpha x$. Similarly, the second region $R_2$ is bounded by the $x$-axis, the line $x=1$, and the line $y=\frac1\alpha x$. The area of a right triangle is $\frac12 bh$ where $b$ is the base and $h$ the heigh. $R_1$ has a base $\frac1\alpha$ and height of $1$, so its area is $\frac12\cdot\frac1\alpha\cdot 1 =\frac1{2\alpha}$. By symmetry, the area of $R_2$ is also $\frac1{2\alpha}$, so the combined area is $$\frac1{2\alpha}+\frac1{2\alpha} = \frac1\alpha. $$
For problems like this I think it is more intuitive to think geometrically than to compute integrals. You are much more likely to make an error in setting up the integration bounds than reasoning with simple geometry. Of course, this approach is not always suitable, but it is a useful tool in cases like these.


Puppet-Dashboard Doesn't Load With Ruby Gem Passenger 5

Question: Has anyone encountered problem of running Puppet Dashboard on Ruby Passenger 5? If yes does it really work with that Passenger version?
I've already setup and configured the necessary files required to run Puppet Dashboard via Passenger. Currently, the Apache test page is shown instead of the dashboard menu. This will not appear if Puppet-Dashboard is run in the lightweight Webrick server.
While scouring most of the installation samples and the manuals on how to install and configure it for Centos 6. I've seen most of them were based on Passenger 3 / 4. I am currently using 5.0.10 as it is used in conjunction with Puppet 3.8.1. One thing certain is that RailsAutoDetect is deprecated in version 5 and that has been commented out.
Below my puppet-dashboard.conf file (the load module has been moved to another file to avoid double-instantiation)
On the logs, the first error reported is that the path of /usr/share/puppet-dashboard/public/reports/upload is not there, so I've created those sub-folders to see if what would be the next error.
The next error in the log file after that is now shown like: Attempt to serve directory: /usr/share/puppet-dashboard/public/reports/upload/
External node and node terminus option has been commented out as not to disrupt normal puppet run-interval activities during office hours.
PassengerHighPerformance on
PassengerMaxPoolSize 6
PassengerPoolIdleTime 1500
PassengerStatThrottleRate 120

Listen 3000
<VirtualHost *:3000>
   ServerName mi-cloud-mgmt-config-01
   ServerAlias mi-cloud-mgmt-config-01.mimos.local
   RailsBaseURI /
   PassengerAppRoot /usr/share/puppet-dashboard/
   DocumentRoot /usr/share/puppet-dashboard/public/

# UPDATE THIS TO YOUR FQDN
<Directory /usr/share/puppet-dashboard/public/>
    Options None
    Order allow,deny
    allow from all
</Directory>

ErrorLog /var/log/httpd/dashboard_error.log
LogLevel debug
CustomLog /var/log/httpd/dashboard_access.log combined
ServerSignature Off
</VirtualHost>

Answer: I had this issue and noted that /usr/share/puppet-dashboard/config.ru didn't exist. I was able to correct the issue by doing
cp vendor/rails/railties/dispatches/config.ru .

while in /usr/share/puppet-dashboard.


How to display value in View global text field if another field has specific value

Question: In my scenario I'm trying to display a flag (Font Awesome icon) in Views Global Text Field if another field in the same row of a type "Date" has a value of, say, a week from now.
I tried Views Table Highlighter but it has some bugs with filters I'm using, so I thought that using the above approach would be better.
Answer: You can use views conditional module.

Views Conditional is a simple module that allows you to define conditionals (if xxx then yyy)
  with fields in views


Compute gradient for the SVM

Question: I am working on Java implementation of the SVM.
Suppose that I have the following loss function that needs to be minimized on weight-space:
$$\frac{1}{N} \sum\limits_{i=1}^N \left(\frac{\lambda}{2}\cdot \|w\| + \max(0,1-y_i \cdot f(x_i) )\right)$$
where

$N$ - number of the features
$x_i$ - the particular feature (basically it is a vector with the length $M$);
$w$ - weights that have to be found by gradient descent method;

Based on the following presentation http://www.robots.ox.ac.uk/~az/lectures/ml/lect2.pdf
The update rules are the following:

$w_{t+1}\leftarrow w_t-\eta (\lambda w_t-y_i  x_i)$, when $y_i
   (w^Tx_i+b)<0$
$w_{t+1}\leftarrow w_t-\eta \lambda w_t$, otherwise

However, I don't understand the following:
$y_i$ might contain only ${0,1}$ - it is scalar, but $x_i$ is vector. How can I simply multiply vector by a scalar and get a vector?
Is it simply the following multiplication
$y_i x_i = (y_i x_i^1,..., y_i x_i^M)$?
Comment: I think y_i should be either 1 or -1 under the SVM context.
Answer: Yes, it is as you conjectured, i.e., each element of the vector is multiplied by the scalar, with the understanding that if $x_i$ is a column vector, as it is in this case, then $y_i x_i$ is also a column vector (which is not clear from your notation).
Given that $y_i$ is either 0 or 1, then $y_i x_i$ will be the M by 1 column vector of zeros if $y_i = 0$, and will be the M by 1 column vector $x_i$, if $y_i = 1$.

Compute gradient for the SVM


Help with using universal instantiation/generalization when variable ocurrence is unknown.

Question: For example:
$\forall x(\varphi \land \psi)\rightarrow (\forall x\varphi \land \forall x\psi)$
Now I would try to drop the forall, and deduce $\varphi$, $\psi$ from $(\varphi \land \psi)$ and then use universal generalization to get to the right side, but I don't know whether the formulas contain $x$ or not. Looking at examples which do contain $x$, it doesn't seem to make a difference, but how do I go about writing that down correctly?
Answer: In general it is a theorem that $\forall x (\varphi \wedge \psi) \implies (\varphi \wedge \psi)$


Formula for extra investment combined with divided reinvestment

Question: I am struggling generalizing a sequence into a generic formula. The idea is to find a way to represent the account balance for a recurring investment into a dividend stock.
The assumption I am making are: 1) constant return of $p\ \%$ each period; and 2) consistent extra regular investment of $x_{ri}$.
$f(x_0)=x_{ri}$
$f(x_1)=x_{ri} + x_0* (1+p)=x_{ri} + x_{ri} * (1+p)$
$f(x_2)=x_{ri} + x_1*(1+p) = x_{ri} + (x_{ri} + x_{ri} * (1+p))* (1+p)$
$...$
$f(x_{period\ number})\ =\ ... ?$
I have a spreadsheet which calculates the account balance for a set duration of investments, but it would be more convenient to find a single formula to compute the balance.

If I only need to know how the compound interest will affect a one time investment, the formula is as simple as $f(x_{period\ number}) = x_{investment} * (1 + p)^{period\ number}$.
It is the regular investment which make the formula complicated.
Answer: You are trying to compute the accumulated value of an annuity.  The formula is straightforward to derive if you concentrate instead on the accumulated values of each contribution in the cash flow.
For instance, the initial contribution of $x$ at time $t = 0$ has accumulated value at time $t = n$ of $$x(1+p)^n.$$  The following contribution at time $t = 1$ has accumulated value at time $t = n$ of $$x(1+p)^{n-1}.$$  In general, a contribution of $x$ at time $t = k$ will have accumulated value $$x(1+p)^{n-k}.$$  So the total accumulated value of a series of regular payments will be
$$x(1+p)^n + x(1+p)^{n-1} + \cdots + x(1+p) = x(1+p)\frac{(1+p)^n - 1}{(1+p) - 1} = x(1+p)\frac{(1+p)^n - 1}{p}$$
if we do not count the final payment at time $t = n$ that has no time to accrue interest.  This formula corresponds to the accumulated value of a level annuity-due of $x$ per period for $n$ periods at effective interest rate $p$.


How to assign a variable in a switch statement in typescript?

Question: I want to use a switch statement to assign a new variable some value.
Example:
let name: string

switch(index) {
    case 0:
       name = "cat"
    case 1:
       name = "dog"
    ....
}

But it is telling me 'name' is declared but its value is never read. Not sure how to fix this...anyone know the proper way to go about this?
Comment: You need to actually use `name` somewhere (other than assigning values to it)
Comment: Also remember to add a `break`.
Comment: [Here is the tslint doc regarding this rule](https://palantir.github.io/tslint/rules/no-unused-variable/) and here is the complimentary [eslint rule regarding this rule](https://eslint.org/docs/rules/no-unused-vars), which gives a slightly more complete explanation.  The problem isn't with the assigning-- it's that you assign it but then do nothing with it, which is like writing your name on a nametag then throwing it in the garbage-- if you're not going to use it, why write your name?
Answer: You can find a similar question with the answer here:
How to get return value from switch statement?
As far as I know, there is no way to use it like e.g. in Java.


O que seria o next desse código?

Question: Estou fazendo alguns exercícios para treina Java e me caiu esta questão:

Given the head of a singly linked list, return the middle node of the
linked list. If there are two middle nodes, return the second middle
node.

 public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Fiquei algum tempo e não consegui fazer, fui ver a resposta para descobrir no que estava errando e me apareceu esta reposta:
class Solution {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null) {
            slow = slow.next;
            if (fast.next == null) {
                fast = fast.next;
            } else {
                fast = fast.next.next;
            }
        }
        return slow;
    }
}

Esse next, ele é um método do Java? Ou um atributo da class ListNode? ou os dois? Só quero entender melhor o código para consegui pega a logica.
Comment: Por favor, esclareça seu problema ou forneça detalhes adicionais a fim de destacar exatamente o que você precisa. Da forma como está escrito atualmente é difícil dizer com exatidão o que você está perguntando.
Answer: Não é um método de Java, até porque métodos possuem () logo após o nome (existem situações que isto pode não ocorrer, mas não é o caso), e este não possui. Não tem como algo ser duas coisas tão distintas ao mesmo tempo.
Ele não é um atributo porque esse é o termo que quase todo mundo aprende errado. Mas é um campo da classe ListNode, isto está bem claro no código no segundo campo.
Como isso é uma lista ligada, cada nó tem um valor e onde está o próximo nó, por isso ela é ligada. Veja na ilustração abaixo que o next está representado aqui por uma bolinha onde teria o endereço do objeto que tem o próximo nó (é a melhor representação gráfica para um ponteiro):

Note que o tipo de next é o tipo da classe, ou seja, ali vai guardar uma referência para um objeto igual a este que ele pertence, porque esta é a característica deste tipo de lista que não vou explicar já que tem links que já o fazem. O construtor mais completo mostra a atribuição do objeto do mesmo tipo em next.
Como em todos os nós o campo existe, você pode acessá-lo em qualquer circunstância, até mesmo pode acessar o next que indica um objeto que tem um next, por isso tem o código fast.next.next que pega o próximo nó que está sendo indicado no próximo nó indicado por fast.
Lembrando que se o nó tem valor null ele é o último da lista, ou seja, não tem um próximo nó. Então precisaria do devido tratamento aí.
Veja também: O que é cabeça da lista encadeada?.
Comment: Nossa muito obg pela explicação e pelos links, me ajudou muito mesmo.
Comment: @Alan veja no [tour] a melhor forma de dizer obrigado, ou seja, marcando a resposta como correta no verdinho ali do lado esquerdo abaixo das setas dos votos, que você logo poderá dar também.

O que seria o next desse código?


How to insert xml data into existing xml in c#?

Question: i added xml file in my windows application, i want to add values to that from textbox..
i used the following code,
string path = "codedata.xml";
        XmlDocument doc = new XmlDocument();
        if (!System.IO.File.Exists(path))
        {
            //Create neccessary nodes
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            XmlComment comment = doc.CreateComment("This is an XML Generated File");
            doc.AppendChild(declaration);
            doc.AppendChild(comment);
        }
        else //If there is already a file
        {
            //    //Load the XML File
            doc.Load(path);
        }

        //Get the root element
        XmlElement root = doc.DocumentElement;

        XmlElement Subroot = doc.CreateElement("data");
        XmlElement Companycode = doc.CreateElement("Companycode");
        XmlElement Productcode = doc.CreateElement("Productcode");
        XmlElement Productname = doc.CreateElement("Productname");
        XmlElement Brandcode = doc.CreateElement("Brandcode");
        XmlElement Brandname = doc.CreateElement("Brandname");

        Companycode.InnerText = txt_companycode.Text;
        Productcode.InnerText = txt_productcode.Text;
        Productname.InnerText = txt_productname.Text;
        Brandcode.InnerText = txt_brandcode.Text;
        Brandname.InnerText = txt_brandname.Text;

        Subroot.AppendChild(Companycode);
        Subroot.AppendChild(Productcode);
        Subroot.AppendChild(Productname);
        Subroot.AppendChild(Brandcode);
        Subroot.AppendChild(Brandname);
        root.AppendChild(Subroot);
        doc.AppendChild(root);

        //Save the document
        doc.Save(path);

        //Show confirmation message
        MessageBox.Show("Details  added Successfully");

it showing error near  root.AppendChild(Subroot); can any one help me, wer i made mistake.
Comment: object reference not set to an instance...
Comment: LINQ to XML is really nice in such a situation :)

You get this error because there is no instance of `Subroot` try add this line : `Subroot sub = new Subroot();` before this line`Subroot.AppendChild(Companycode);
` and change all `Subroot` to `sub`
Answer: You can use Linq to XML, here is an example :
var xDoc = XElement.Load("FilePath");
if (xDoc == null)
   return;

var myNewElement = new XElement("ElementName"
   new XAttribute("AttributeName", value1),
   new XAttribute("AttributeName", value2)
   //And so on ...
);
xDoc.Add(myNewElement);
xDoc.Save("FilePath");

Answer: The root is null. Try to add Root element when you create XML file.
 if (!System.IO.File.Exists(path))
        {
            //Create neccessary nodes
            XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
            XmlComment comment = doc.CreateComment("This is an XML Generated File");
            doc.AppendChild(declaration);
            doc.AppendChild(comment);
            doc.AppendChild(doc.CreateElement("Root"));
        }

Or use LINQ-XML
string _file=@"c:\sample.xml";
XDocument doc;

if (!File.Exists(_file))
{
    doc = new XDocument();
    doc.Add(new XElement("Root"));
}
else
{
    doc = XDocument.Load(_file);
}

doc.Root.Add(
      new XElement("data",
                   new XElement("CompanyCode","C101"),
                   new XElement("ProductCode","P101")
            )
      );
doc.Save(_file);

Comment: You either have set physical path `c:\file.xml` or have a look at `Debug/Bin` folder if your app is winform or console.
Comment: hi, i used, it returns saved, but no data in xml file
Comment: hai, when i test using break point, it shows the xml file with data i saved.but if i see in codedata.xml,its empty. Where it is saving?
Comment: Try to set absolute path and see what happen?
Answer: In null XML DocumentElement is null. Try add Subroot to Document:

XmlElement root = doc.DocumentElement;
root.AppendChild(Subroot);
doc.AppendChild(root);
// new code
doc.AppendChild(Subroot);

Comment: i tried ur idea, its shows the msg saved, but in xml file...no data is there empty only with  i added my xml file by add new item
Comment: @chitra: I tested my code and its works correctly. check output xml.
Comment: should i add any element in xml, before saved btn


Mudar nome do botão

Question: No meu código tenho um botão salvar para cada option que eu fiz
e agora preciso que, ao salvar, o nome do botão mude para alterar.
Como devo proceder?
código:

    // aqui eu verifico o nome do botão
    if(isset($dados) && ($dados['ecocodigocolecao2']!= '' || $dados['ecocodigocolecao1'] != '')){
    $nomebotao == 'Alterar';
    }else{
    $nomebotao == 'Salvar';
    }

    <?php echo $db->monta_combo("ecocodigocolecao1", $adesao->listarLivros($disciplina['codigocomponente'],1,""), $podeeditar,  "Selecione...", "", "", "", "500", "N", $padrao_id."_1", "", isset($dados)?trim($dados['ecocodigocolecao1']):'""',"","","onchange=  \"buscarsegundaop(this.value,{$disciplina['codigocomponente']},{$disciplina['codigoetapa']})\"");?>

    <?php echo $db->monta_combo("ecocodigocolecao2", $dados2, isset($dados)&& trim($dados['ecocodigocolecao2'])==""?"N":"{$podeeditar}", "Selecione...", "", "", "", "500", "N", $padrao_id."_2", "", isset($dados)?trim($dados['ecocodigocolecao2']):'""');?>

    <input type="button" id="salvar" name="salvar"
    <?php echo $podeeditar=="N"?'disabled="disabled"':''?> onclick="salvarcolecao(
<?php echo $disciplina['codigoetapa']?>,
<?php echo $disciplina['comid']?>,
<?php echo $row['adeid']?>,$(this));" value="$nomebotao"/>

Comment: Acho que a pergunta será para javascript/jquery e não de php.
Comment: O que faz a função salvarcolecao? será ai que deverá mudar o nome
Comment: @TiagoGomes

faz uma requisição ajax, e retorna a mensagem de sucesso ou falha.
Answer: Você pode adicionar um novo parâmetro e passar o campo usando o this:
HTML:

    <input type="button" id="salvar" name="salvar"
    <?php echo $podeeditar=="N"?'disabled="disabled"':''?> onclick="salvarcolecao(
    <?php echo $disciplina['codigoetapa']?>,
    <?php echo $disciplina['comid']?>,
    <?php echo $row['adeid']?>, this);" value="<?php echo $condicao ? 'salvar' : 'alterar' ?>"/>

JS:
function salvarcolecao(codigoetapa,comid,adeid, campo){
    $("#ecocod_"+codigoetapa+"_"+comid+"_2").attr('disabled',false);
    ecocodigocolecao1 = $("#ecocod_"+codigoetapa+"_"+comid+"_1").val();
    ecocodigocolecao2 = $("#ecocod_"+codigoetapa+"_"+comid+"_2").val();
    if (verificarRegras(ecocodigocolecao1,ecocodigocolecao2)){
        //alert(ecocodigocolecao1+"---"+ecocodigocolecao2+'=-===='+"#"+codigoetapa+"_"+comid+"_1");
        jQuery.ajax({
            type: "POST",
            url: "pddeinterativo2015.php?modulo=principal/escolha/principalEscolha&acao=A&aba=Escolha",
            data: "action=salvarEscolha&ecocodigocolecao1="+ecocodigocolecao1+'&ecocodigocolecao2='+ecocodigocolecao2+'&comid='+comid+'&adeid='+adeid,
            async: false,
            success: function(msg){
                alert(msg);

                // alterando o valor do campo
                campo.value = (campo.value == "salvar" ? "alterar" : value);
            }
        });
    }
}

Comment: Deveria passar o this e mudar dentro da função. Se o ajax falhar? não deve mudar o botão
Comment: @TiagoGomes

pode me auxiliar com um exemplo?
Comment: Vou alterar já posto.
Comment: @Laerte
uma outra situação é: fazendo desta forma ao atualizar a página o nome do botão volta a ser salvar, e deveria ser alterar..
o que acontece, após eu salvar, sempre que recarregar a página os meus options já vem carregados com o valor salvo, mas o botão permanece com o nome salvar.
Comment: Como você sabe que ele alterou o dado? Pois na hora de renderizar com o PHP você pode por essa condição no input.
Comment: Atualizei, caso você me passe qual é o campo que você verifica pra saber se já salvou assim eu altero a resposta.
Comment: @Laerte
fiz o seguinte:

no meu PHP eu adicionei a variável $nomebotao no lugar do value="salvar" do input.
e no onclick eu adicionei o $(this) com parâmetro.

na minha função js eu adicionei o btn como parâmetro do this e as seguinte linha após o sucess do ajax:
 btn.val('Alterar');
Comment: Obrigado! Deu certo aqui.
Comment: Marque como resposta para ajudar os outros. ;)

Mudar nome do botão


Como usar jquery em uma diretiva angularjs?

Question: Tentei colocar uma função em jQuery dentro de uma diretiva, mas não está funcionando.
Pesquisei e achei em vários lugares falando sobre jqLite, mas não soube converter o jQuery para jqLite.
$('[data-toggle="tooltip"]').mouseleave(function () {
    $(this).tooltip('hide')
});

$('[data-toggle="tooltip"]').on("click", function () {
    $(this).tooltip('hide')
});

Comment: Você já tem o jquery instalado na sua aplicação?
Comment: Sim! preciso encapsular esse código na diretiva, mas não estou sabendo como fazer
Answer: Eu uso jquery em algumas directivas do angularjs e funciona perfeitamente. Da uma olhada em um exemplo que tenho aqui:
app.directive("scrollToTopButton", function () {
    return function (scope, element, attrs) {
        $(element).addClass('scrollToTop');

        $(window).on("scroll", function () {
            if (this.pageYOffset > 300) {
                $(element).fadeIn();
            }
            if (this.pageYOffset <= 0) {
                $(element).fadeOut();
            }
        });

        element.on("click", function () {
            $('html, body').animate({
                scrollTop: 0
            }, 800);

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

Comment: Está basicamente a mesma coisa do meu, mas não está funcionando.
Answer: angular.module("components").directive("clearTooltip", function () {
  return {
    link: function (scope, element) {
      element.mouseleave(function () {
        $(this).tooltip("hide");
      });

      element.on("click", function () {
        $(this).tooltip("hide");
      });
      element.addClass("teste");
    },
  };
});


People Column (Allow Multiple Selections) in HTMLText Control

Question: I am creating an HTMLText form so that I could integrate my form with MS Flow to allow my form to be printable.
However, the Stakeholders variable does not work because I think it is treated as an array instead of Text. My other people columns worked fine but that's because it only allowed single selection.
I tried using the ClearCollect, Collect, and Listbox Control but none seem to work
The prompt always says "Invalid Argument: Expecting Text..."
Answer: Even though you've set the ComboBox to allow only one selection, you will still need to specify that only the first selected item is passed in.
Syntax is:
<code>First(COMBOBOX_NAME.SelectedItems).FieldName
</code>


Check if App is Using DevAPP

Question: I'm trying to figure out how to check if my Ionic app is running on DevAPP (DevAPP is a testing platform that runs your app locally on your device).
This is important because I'm using a plugin that is not available in DevAPP, so it crashes the app. I want to be able to perform some kind of check to see if the app is being run with DevAPP. And, if it is, I just won't call the code for the unavailable plugin.
I've tried checking platform.platforms(), but it just says "mobile,android,phablet,mobileweb". Those don't seem to suggest that DevAPP is running.
Another possible solution would be a way to check if a plugin is installed. I tried just checking if the injected variable was truthy if( this.fcm ), but this still crashes the app.
Answer: All right. Well, I wasn't able to figure out how to specifically check within the code whether or not the app is currently running on DevAPP. But I did manage to find a solution to my problem. It was actually pretty straight-forward.
Since the native plugin I was trying to use returns a promise, I just used the .catch() method available on promises:
this.fcm.getToken().then( token => {
    console.log( 'token: ', token ); //@DEBUG
})
.catch( error => { // Catch error that FCM is not available in DevAPP and web
    console.log( 'Error Getting FCM Token: ', error ); //@DEBUG
});

This can also work with Observables by processing the error response option:
this.fcm.onNotification().subscribe(
    data => {
        console.log( 'data: ', data ); //@DEBUG
    },
    error => {
        console.log( 'Error Subscribing to FCM Notification: ', error ); //@DEBUG
    }
);

After implementing this code, my app no longer crashed while running in DevAPP.

Check if App is Using DevAPP


Maximum number of unsuccessful reviews allowed in test cricket

Question: In ODIs where DRS is used, each side is allowed at most one unsuccessful player review in an inning. What is the corresponding rule for test cricket?
Answer:
In ODIs where DRS is used, each side is allowed at most two unsuccessful player reviews in an inning.

This is incorrect. Quoting from the current ODI playing conditions, Appendix 6, Section 3.5(a):

Each team is allowed to make one unsuccessful Player Review requests per innings.

(my emphasis). Exactly the same section in the current Test Match playing conditions answers your question:

each team is allowed to make a maximum of two unsuccessful player review requests in the first 80 overs of the innings, and a maximum
  of two unsuccessful player review requests after 80 overs for the remainder of the innings.
Comment: Right, corrected the question. Moreover, sticking to the words the rule states, I find it odd that the rule is just "the 80th over" and not "every 80th over" (like 80, 160,...), although innings with 160+ overs are not very common


Clear object variables after use (pooling) c#

Question: I am working on a pooling algorithm which takes an allocated object and recycles it allocation for later. However, one of the issues of recycling an object is for instance:
 someObject obj = pool.alloc(); //gives me a new object if no previous allocations, If an allocation has been recycled, returns a previous allocation
 obj.someVariable = "foo";
 pool.recycle(obj);

The above code will take an existing allocation and save it so that I don't have to allocate any extra ram in case I was to have another someObject. However, the following creates an issue:
 someObject obj = pool.alloc(); //gives me the above allocation
 obj.otherVariable = "bar";
 obj.dump();

As a result, I will get the following result:
  someVariable = foo
  otherVariable = bar

The above approach creates an issue. If I for some reason (or someone else) have an algorithm that doesn't use certain variables inside of an object, the old values can cause unnecessary behavior. I have poked around a little bit to see if there is some way I can call the default constructor again (bad idea) and C# (thankfully) doesn't seem to allow you to do so. However, I was wondering if there was some way to use reflection to do this? Also, does clearing the variables in an object defeat the purpose of avoiding malloc (new)? In other words, if I spend the time clearing variables does the performance gain become minimal? I am trying to teach myself pooling so any criticism and advice is greatly appreciated!
Comment: Do you have evidence that you need this pooling *at all*?
Comment: You probably don't want to do this.  If a variable can be trivially re-used the compiler/JITter will likely do it without you knowing, if not, it's likely to be more expensive and also have a higher probability of not working (and also putting a higher burden on the programmer to tell your app when it's done with each item).
Answer: Here's one way of looking at pooling:
Pooling is only really necessary when you are reusing some complicated setup work that you can avoid by retrieving an already existing object.  For example, one of the best known applications for object pooling is in the form of "Database Connections".
Pooling works for Database Connections (DBConns) because 1) a DBConn can be trivially identified by a connection string; and 2) a DBConn takes a lot of work and time to establish.   The trivial identification is done by matching connection strings - if two connection strings are identical, the connections they establish should also be identical.  Also, once you have a connection string, it can take hundreds of milliseconds to lookup the server address, open a socket to it, authenticate, and establish the connection. This means that pooling works well for database connections because when a connection is released, it can be reused the next time a connection is requested for the same connection string.
The .NET runtime environment is exceptionally good at allocating objects quickly and releasing them so you don't have memory issues.  If all you're worried about is memory use or the speed of allocation, don't; you can't beat the compiler's performance by zeroing out memory on your own.  However, if your objects have some complex, lengthy setup that can be avoided by retrieving an existing object from a pool, you can find some benefit.
Another good example of pooling is a particle system in a videogame.  You have hundreds of particles that have to be created, go through a lifecycle, and be destroyed, only for new particles to be created after the old ones die.  A typical particle system will create X number of objects as an array, and have a Reset() function that returns a dead object to life as a newly created particle in the original location.  The reason this works is again because particles can be trivially identified, and the setup work (giving the graphics system the texture, putting locations, etc).
Does your application have both a "trivial match identification" capability and a lengthy setup process that can be avoided?  If not, just allocate the objects new each time - I would wager you won't see any performance degradation.
EDIT: From a performance perspective, let's look at this here:
Resetting variables = O(N) assignment statements; using reflection can increase that significantly
Instantiate a new object = One malloc call, one constructor call; the complexity level is dependent on the constructor code, and memory fragmentation.
Using reflection to reset variables can work, but you have to know in advance that O(N) for assignments is faster than your malloc and constructor.  For a database connection, I know that condition is satisfied; but is that true for your pool?
EDIT: From your comments below, you may indeed have found a case where pooling is appropriate.  If that's the case, I would suggest the ideal approach is to create a Reset() function for any class that you are pooling.  Try creating an IPoolable interface that defines a function Reset().  Then, for each class you pool, define the Reset() function so that it zeroes out all key variables.  Because it compiles, it won't incur reflection overhead, and you can maintain object-specific optimizations that wouldn't be possible with dynamic code.
For the pool, define the pool class as MyPool<IPoolable>; then whenever an object is retrieved that was previously recycled, you can call Reset()  on it before handing it back to the caller.
Comment: Right now its a huge ASPX application that grabs data from a database. A lot of it is not my code and from working with it I find that everything is mallocing objects, usually the same type over and over again usually to just discard it very quickly. A few users is still OK but after a while it becomes a burden. Also, no, from working with videogame code the GC Is pretty bad a managing allocations.
Comment: For an ASPX web server that's allocating too many objects, you probably want to start caching objects likely to be re-requested in some future location rather than pooling.  Although the garbage collector is very well optimized, avoiding unnecessary allocations / deallocations will get you the biggest benefit.
Comment: I've already built in a caching system that has improved performance. Trying to take a step further because in the future this application will grow even bigger. The only way to fix old code is to rewrite it, but I don't have the time or will to do that.