ExtJS: Linked combobox puzzle

Question: I write special combo object to use it as linked combos. Here it is:
comboDivClass = Ext.extend(Ext.form.ComboBox, {
            fieldLabel: 'Divisions',
            anchor: '95%',
            lazyRender:true,
            store:new Ext.data.Store({
                  proxy: proxy,
                  baseParams:{rfb_type:'divisions'},
                  reader: divReader,
                  autoLoad: true
            }),
            displayField:'div_name',
            allowBlank:false,
            valueField:'div_id',
            triggerAction:'all',
            mode:'local',
            listeners:{
                select:{
                    fn:function(combo, value) {

                        if (this.idChildCombo) {
                            var modelCmp = Ext.getCmp(this.idChildCombo);
                            modelCmp.setValue('');
                            modelCmp.getStore().reload({
                                params: { 'div_id': this.getValue() }
                            });
                        }
                    }
                }
            },/**/
            hiddenName:'div_id',
            initComponent: function() {comboDivClass.superclass.initComponent.call(this);}})

As you may see, this combobox load data at child combobox store(which set as idChildCombo).
Ok. Here is how i declare it
new comboDivClass({id:'sub0div',idChildCombo:'sub1div'}),
new comboDivClass({id:'sub1div'})

Yes it works, but it have some odd trouble - it load not only sub1div store, it load at sub0div store too. Why? What im doing wrong?
Comment: `proxy: proxy,`  <--- all instances use one proxy
Comment: no. try it. I tryig to use a different proxy and nothing change. (im trying use different reader too :)
Answer: One thing I see is that you have mode: 'local' config, while it should be remote.
Other thing to consider: Why don't you do it more like this:
var c1 = new comboDivClass({id:'sub0div'});
var c2 = new comboDivClass({id:'sub1div'});
c1.on('select',function(combo, value) {c2.getStore().reload({
  params: { 'div_id': c1.getValue() }
})});

Comment: thanks , but remoting mode: 'local' dont change anything and at your example I get the same result - data loads at both store :(
Answer: ChildCombo.setMasterField( masterField ) {
  masterField.on('change', function(field){
    this.getStore().filterBy( function(){ //filter by masterFIeld.getValue() } );
  })
}

The idea is to link child field to parent not parent to child and this way you can link to any kind form field no only combo.
Here in child combo you have to have store with three columns [group,value,label] where group is value of master field.
This way you can manage to have mode than one master field.

ExtJS: Linked combobox puzzle


Persist DOM tree with JPA as String

Question: I have the following problem. I have a JPA Entity containing a property of type org.w3c.dom.Document. I can't and I also don't want to persist each object of the DOM tree individually. What I rather want is converting the XML represented by the DOM tree to a String and save this String to the database. When I load the object back in I want my object to parse the DOM tree and reinitialize the property. Is this possible with JPA?
Thanks.
Answer: Of course it's possible.
What you need to do is treat the dom tree as a custom type.
Comment: Thanks for your answer. But that is exactly what I wanted to avoid. The org.w3c.dom class hierarchy is rather intricate and I don't want to specify how to persit it as objects to a database. But no problem. I found my answer after some additional searching and reading.
Comment: You are assuming I was saying define the dom as a custom type, I was not: I was saying define your own representation as such, even if it's just a string.
Comment: But this only works with Hibernate. I need to stick to plain JPA.
Comment: Recap: I pointed you to that, you said no, then you edited your answer to take the same approach, but now you don't like that either? Hilarious. Yeah, you are right about it being Hibernate only. Dude, just make a class! Call it something like Dom (in your package) and then just have a Constructor that takes the tree, and one property inside that's a string. That will get persisted properly?
Answer: After some additional search I finally found the answer. You just need to tell JPA to save it as a Blob with the  xml document inside the  element.
EDIT:
As it turns out, this does not work. I think I found a working solution here: Storing Objects in columns using Hibernate JPA

Persist DOM tree with JPA as String


How can I disable caching in nginx?

Question: I'm not familiar with nginx and have trouble editing/fixing a php script served through nginx. My fixes are not visible- it seems the script file (or its output) are cached, probably by nginx. The config files do NOT contain any fastcgi_cache directives though.
What do I need to change to be able to edit the php script and see its updated output?
php version is 5.4, so it's not opcache-related. It's also not browser-related as the same happens with different browsers, wget etc.
nginx config:
user root users;
worker_processes  1;

#error_log  logs/error.log;
error_log  /var/log/nginx/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;

    #access_log  logs/access.log  main;

    sendfile        on;
    #keepalive_timeout  0;
    keepalive_timeout  65;

    gzip  off;
    proxy_buffering off;
    fastcgi_keep_conn on;

    #start server1 section
    server {
    listen       80;
    access_log  /var/log/nginx/access.log;
    location / {
        root   /var/www;
        index  index.php index.html index.htm;
    }

    location /db {
    proxy_pass        http://localhost:81/;
    }

    location /command {
    proxy_pass        http://localhost:82/;
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
    # php5-fpm
    location ~ \.php$ {
        root           /var/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        include        fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_read_timeout 3600;
    }
    } #end server1 section

    #start server2 section [/db]
    server {
    listen       81;
    access_log  /var/log/nginx/db.log;
    location / {
        root   /var/www/db;
        index  index.php;
    }
    # php5-fpm
    location ~ \.php$ {
        root           /var/www/db;
        fastcgi_pass   127.0.0.1:9001;
        fastcgi_index  index.php;
        #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        include        fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_read_timeout 3600;
    }
    } #end server2 section

    #start server3 section [/command]
    server {
    listen       82;
    access_log  /var/log/nginx/command.log;
    location / {
        root   /var/www/command;
        index  index.php;
    }
    # php5-fpm
    location ~ \.php$ {
        root           /var/www/command;
        fastcgi_pass   127.0.0.1:9002;
        fastcgi_index  index.php;
        #fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        include        fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_read_timeout 3600;
    }
    } #end server2 section
}

fastcgi_params
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

UPDATE
It seems that the caching is already happening in the fastcgi server. This is from the nginx error log (the messages are bogus but do indicate that the php file is not the current one):
2015/08/07 12:08:51 [error] 4050#0: *127 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class 'getID3' not found in /var/www/cover2.php on line 8" while reading response header from upstream, client: 192.168.0.66, server: , request: "GET /cover2.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "192.168.0.35"
2015/08/07 12:09:08 [error] 4050#0: *127 FastCGI sent in stderr: "PHP message: PHP Fatal error:  Class 'getID3' not found in /var/www/cover2.php on line 8" while reading response header from upstream, client: 192.168.0.66, server: , request: "GET /cover2.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "192.168.0.35"

Comment: Without knowing your actual setup (nginx & php config), this is impossible to answer. But you could start with making sure [OPcache](https://secure.php.net/manual/en/book.opcache.php) is disabled, and that it isn't your browser that's caching too aggressively.
Comment: If you do not see opcache, then it is probably on. Default value is on. Turn it off.
Comment: I've updated the config. php.ini does not show any opcache settings. It's definitely not the browser, getting old results when using different browser.
Comment: Even if there is no `fastcgi_cache` in your config file, try to force set it `off`.
Comment: Uhh, and please check the included `fastcgi_params` file. Which options are set there?
Answer: Darn. Finally found the culprit:
apc.stat = 0

This prevents IO checking in the FastCGI PHP server. The opcache hint was the clue, although its APC, not opcache.
Answer: It could be a browser doing caching of pages it visits often, if so you could try this:
Edit the HTML meta to tell the browser to stop caching:
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Source

How can I disable caching in nginx?


Prove that the equation has no real roots

Question:
Given $a>0$ and $b>0$, how can we prove that $x^2 - (a+b)x +2ab=0$ has no real roots?

I thought about starting with the discriminant.
I calculated the discriminant and found $\Delta=(a+b)^2-8ab $.
How do I show that $\Delta$ is less than zero?
Comment: Are there further restrictions on $a$ and $b$?  If not, then this equation can have real solutions...
Comment: Are you taking $a, b$ to be integers?
Answer: We need to prove that $$(a+b)^2-8ab<0,$$ which is wrong.
Take $b=0.1$ and $a=1$.
Answer: Well, why not. We want to investigate when $a^2 - 6ab+b^2$ is positive, giving counterexamples to the question. We can start with $(1,0),$ so that $a^2 - 6ab+b^2= 1.$
You might complain that $a,b$ are not both positive. That will be alright, given an $(a,b),$ we get a new pair with
$$ (a,b) \mapsto (6a-b,a) \; .  $$
The value of $a^2 - 6ab + b^2$ does not change when doing this. So, here are an infinite sequence of pairs with $a^2 - 6ab + b^2 = 1 \; :$
$$ (1,0), \; \; (6,1), \; \; (35,6), \; \; (204, 35),\; \; (1189, 204), \ldots   $$
These also follow separate rules for the two letters, namely
$$ a_{n+2} = 6 a_{n+1} - a_n,  $$
$$ b_{n+2} = 6 b_{n+1} - b_n.  $$
Answer: \begin{align}
& (a+b)^2 - 8ab = (a^2 + 2ab + b^2) - 8ab \\[10pt]
= {} &  \underbrace{(a^2 -6ab) + b^2 = (a^2 -6ab + 9b^2) - 8b^2}_{\large\text{completing the square}} = (a-3b)^2 -8b^2
\end{align}
If $a$ is large and $b$ is small then this is positive.
Answer: Multiply by $4$ to obtain $$4x^2-4(a+b)x+8ab=(2x-a-b)^2+8ab-(a+b)^2=(2x-a-b)^2=$$$$=(2x-a-b)^2+(a+b)^2-2(a-b)^2$$
The negative square on the right-hand side is a sign that the expression is not definite (ie will take both positive and negative values). For example, take $a=6b$ then it becomes $$(2x-8b)^2-b^2$$ which is negative when $x=4b$.


Visualização de Variável no Visual Studio não funciona

Question: Boa tarde, poderiam me ajudar, já faz um tempo que o meu Visual Studio está deste jeito
Eu sei que deveria estar com uma setinha para visualizar o objeto, isto está atrapalhando muito, desde já agradeço
Comment: Filipe, eu tive o mesmo problema quando estava usando componentes de terceiros e ele expirou (OZCODE), se voce utiliza Resharper, ou qualquer um desses foi que causou na minha máquina, tente reinstalar os componentes ou atualizá-los.
Comment: Estou vendo se tem atualizações pendentes
Comment: Deu certo, eu tive que apenas atualizar o VS
Comment: Muito obrigado.
Comment: Coloquei a soluçao como resposta pra facilitar p/ quek pesquisar.
Answer: Atualize o VS e todos os componentes, não há necessidade de reinstalar
Answer: Consegui resolver, como o @Thiago Loureiro  disse, eu tive apenas que atualizar o Visual Studio, ainda não sei a causa raiz, mas muito obrigado a todos
Answer: tive o mesmo problema e só resolveu reinstalando o VS2017, mas eu usei a "Janela Imediata" por um tempo pra quebrar o galho que faz a mesma coisa...


Buscar lista de objetos Json do localStorage por parte do nome de suas chaves

Question: sei que o localStorage dos navegadores armazena dados no formato de chave-valor, e que posso recuperar os objetos Json salvos alí através da chave. Agora o que eu preciso fazer é recuperar todos os registros cuja chave começam por "Deposito". Isto porque eu quero criar um gerador de sequência, para que cada chave de objeto depósito tenha acrescentado à ela um  número.
Por exemplo: Depósito01 {...
             Depósito02 {...
Uma vez recuperado todos os registros, eu iria extrair esses dois caracteres finais para descobrir qual foi o último depósito inserido, e incrementar em +1 no nome da chave do próximo depósito...
Também não sei como fazer isso, mas vou tentar. O que eu preciso primeiro mesmo é recuperar os objetos por parte do nome de suas chaves...
Answer: Você pode fazer um loop:
localStorage.clear();

localStorage.Deposito1 = 'item 1';
localStorage.Deposito2 = 'item 2';
localStorage.Deposito3 = 'item 3';

for(let i = 0; i < localStorage.length;) {
    console.log(localStorage[`Deposito${i++}`]);
}

Para pegar o último número é só usar:
localStorage[`Deposito${localStorage.length + 1}`] = 'item n';

Essa é uma forma simples porém, se na sua aplicação você possui outros dados salvos em localStorage pode haver algum erro, para isso tem que ser criado um array apenas com as chaves de depósito, e sempre deve atualizar ele quando houver alguma mudança no localStorage para outras ações não serem prejudicadas:
var deposito = [];

for(let element of Object.keys(localStorage)) {
    if(element.search('Deposito') == 0) {
        deposito.push(element);
    }
}

Comment: Isso, eu não pensei que não precisaria de um loop, achei que teria algum método que pra gerar isso. Outra coisa que eu não sabi: o símbolo que representa "qualquer caractere que vier depois" no javascript, que no caso é o "$" então... Obrigado, ajudou bastante.


MIgrate to drupal 7 join related tables

Question: I am migrating from a another non Drupal CMS. I have 4 tables:

stories (story1, story2, story3)
story_tags (story_id, tag_id)
tags (ABC, NBC, WTOP, CBS, clinton)
tag_types (radio, tv, person)

How can I link tags to stories by tag_type. So that when I open a story I can see all it's related tags, knowing that a story can have several tags.
Any good detailed tutorial of migrate module link will be appreciated also.
update
How can i translate this in a migrate query
SELECT t.name FROM tags t
    join tag_types tt on (tt.id = 3)
    join story_tags stg on (stg.tag_id = t.id) WHERE story_id = $row_id'

Tried but it is not working:
->select('story_tags', 'tags')
->fields('tags', array('tag_id'))
->leftJoin('tag_types', 'tt', '(tt.id = tag.tag_type_id)')
->condition('tag_type_id', '3', '=' )
->condition('story_id', $row->id, '=')
->execute()
->fetchCol();

What am i missing?
Answer: My approach to this would be to have a content type called Story that had 2 taxonomy term references. One tag field could just be called tags and then other could be called tag_types. These 2 fields would be 2 distinct Taxonomy Vocabularies in Drupal.
Drupal 7 actually installs with a tags vocabulary out-of-the-box which is assumed to be free-tagging terms as your legacy site appears to be already using. So you just need to make 1 vocabulary for the tag_types.
Anyways then in your migration class for Stories. Your source SQL statement would figure out the necessary terms for these 2 fields, probably using a sub-select, and the migrate module can set the terms for the content type as Stories are inserted into the system.
So, some psuedocode is:
<?php

class StoryMigration extends Migration
{
  public function __construct($arguments)
  {
    parent::__construct($arguments);
    $query = Database::getConnection('default', 'legacy')
      ->select('stories')
      ->fields('stories', array('pgid', 'page_title', 'page_body'));
    // Create subqueries to get the tags for the story we are on. We will call
    // a fake field in our SQL query as legacy_tags or legacy_tags_type to be
    // passed using Migrate field mappings.
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_terms WHERE page_id = pgid' ,'legacy_tags');
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_term_types WHERE page_id = pgid' ,'legacy_tags_type');
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('page');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'pgid' => array('type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => t('Source ID'),
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'page_title');
    $this->addFieldMapping('body', 'page_body');

    // Import a story's tag(s). Make the term in the vocabulary if it's not
    // there already, ignore the CaSe of the term so sloppy legacy terms
    // come across as 1 term.
    // By specifying this could have a SEPERATOR VALUE this can create any N
    // terms provided by our SQL statement above.
    $this->addFieldMapping('field_tags', 'legacy_tags');
    $this->addFieldMapping('field_tags:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags:ignore_case')
      ->defaultValue(TRUE);

    // Similar steps as for the above term, but for the tags_type reference field.
    $this->addFieldMapping('field_tags_type', 'legacy_tags_type');
    $this->addFieldMapping('field_tags_type:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags_type:ignore_case')
      ->defaultValue(TRUE);
  }
}

Term Reference Fields and the Migrate module are described in the documentation. Adding SQL Expressions to an SQL query is covered in the sql documentation.
My above code is an example and not guarenteed to work. It's simply 1 method of doing this and is to be referenced as an outline. Your SQL schema and php may look different in the end.
Comment: Thanks, I added an update. Do you know how to fix the query?

MIgrate to drupal 7 join related tables


LAMP: slow query via PhpMyAdmin, fast via command line

Question: I have a very strange problem - my server responds quite slowly even though it is basically unused: Apache seems to be less snappy than what I would expect and MySql responds to queries sent via PhpMyAdmin after at least 3/5 seconds even though this could be a simple SELECT and the table only has 10 records. The query itself is fast, but it takes a while before this is run. Interestingly the same query run throuh the command line is instantaneous without any delays.
I've been reading though everything I can find, but none of the solutions seem to apply to my case. Can somebody point me in the right direction?
Answer: It can be a resolution name problem.
Check how phpMyAdmin connects to mysql (ip, localhost, socket ?).
Answer: if anyone coming from google, here you go. (sorry for the necro)
put these lines inside your mysql config's [mysqld] section to disable ipv6 lookup.
skip-host-cache
skip-name-resolve # specially this line

Src: https://stackoverflow.com/a/15436435/9720375


Passar valor de sessão php para Ajax

Question: Preciso pegar uma valor de uma sessão do php que está em uma página onde tenho um formulário de contato e passar por Ajax para uma outra página, nessa página faço a verificação se o valores são iguais ou não, mas não estou conseguindo realizar.
O meu código captcha cria a sessão vejam:
<?php

session_start();

$codigoCaptcha = substr(md5( time()) ,0,9);
$_SESSION['captcha'] = $codigoCaptcha;

$imagemCaptcha = imagecreatefrompng("fundocaptch.png");
$fonteCaptcha = imageloadfont("anonymous.gdf");
$corCaptcha = imagecolorallocate($imagemCaptcha,127,82,53);

imagestring($imagemCaptcha,$fonteCaptcha,15,5,$codigoCaptcha,$corCaptcha);

header("Content-type: image/png");
imagepng($imagemCaptcha);
imagedestroy($imagemCaptcha);

?>

Tentei passar a variável de sessão assim:

O valor dessa variável que é o campo informado com o captcha gerado é enviado para a página processo.php:
var captcha   = $("#captcha").val();

Não sei exatamente como proceder.
Answer: Pelo que entendi da pergunta e do código, você está querendo fazer uma verificação CAPTCHA. Ao criar uma sessão server side (com o PHP), normalmente um cookie no lado do cliente é criado para guardar o ID daquela sessão.
Então: O seu script salva o captcha na sessão:
$_SESSION['captcha'] = $codigoCaptcha;

Tudo que você precisa fazer é enviar a requisição do formulário via AJAX, com o valor do campo que o usuário digitou:
var captcha   = $("#captcha").val();

Ou seja, você não precisa passar outras informações relativas a sessões ou CAPTCHA. O que acontece agora é o seguinte: No lado do servidor, com PHP, você acessa a sessão novamente, e verifica se o valor salvo pelo script gerador do CAPTCHA é o mesmo que o usuário digitou no campo. Exemplo:
processo.php
<?php
session_start();

if($_POST['captcha'] != $_SESSION['captcha'])
    die('O captcha digitado é inválido');

A sessão e seus valores são criadas pelo PHP, e ficam salvas no servidor.
Sugiro uma olhada na documentação sobre sessões aqui e aqui.
Comment: Olá @Calebe Oliveira, obrigado pelas dicas, resolvi meu problema, dei uma limpada no histórico e funcionou.

Passar valor de sessão php para Ajax


angularjs resetting input fields to default values

Question: Have a couple of input fields which are set to default values, want to be able to reset them to their default values with a button if there is any input in the fields.

Continent

<select data-ng-model="ContinentValue">
                    <option value="Asia">Asia</option>
                    <option value="Europe">Europe</option>
                    <option value="South America">South America</option>
                    <option value="North America">North America</option>
                    <option value="Africa">Africa</option>
                    <option value="Oceania">Ociania</option>
                    </select>

Population Greater than

<input type="number" data-ng-model="popValueMin">

Lesser than

<input type="number" data-ng-model="popValueMax">

Government Form

<input type="text" data-ng-model="govForm"></input>

Country name

<input type="text" data-ng-model="countName"></input>

        <button data-ng-click="resetModel()">Reset</button>

Three input values are set to default in my allController:
$rootScope.popValueMax = parseInt("146934000");
        $rootScope.ContinentValue = "Europe";
        $rootScope.popValueMin = parseInt("0");

Using another controller to reset:
controllers.controller("resetCtrl", ["$rootScope", function($rootScope) {

     $rootScope.resetModel = function(){
     $rootScope.popValueMax = parseInt("146934000");
     $rootScope.ContinentValue = "Europe";
     $rootScope.popValueMin = parseInt("0");
     $rootScope.govForm = "";
     $rootScope.countName = "";
   };

  }]);

Been looking around at many similar threads here, tried alot of the solutions available but nothing seems to work.
Comment: Why u adding the things in rootScope?
Comment: Been using since start, getting same results with $scope.
Comment: do you really need another controller just to reset ? Is it ok for you if everything is in one controller ? and to be clear you just want to set the values to initial values and click of a button ryt ?
Comment: Yes, just want to be able to reset the values to default. Been running it in the allController which is the main controller, same result there.
Answer: Change,
From
  <button data-ng-click="resetCtrl.resetModel()">Reset</button>

To
  <button data-ng-click="resetModel()">Reset</button>

EDIT:
It is not recommended to use $rootScope, also with your code you are not resetting any new value, only the default values are assigned again. Change it to something like this,
$scope.resetModel = function() {
    $scope.popValueMax = parseInt("146934000");
    $scope.ContinentValue = "Europe";
    $scope.popValueMin = parseInt("0");
    $scope.govForm = "";
    $scope.countName = "";
  };

DEMO
Comment: Forgot to remove that, not working as "resetModel()" either.
Comment: @Znowman You have done a silly mistake there, you are not actually reseting any value. all the values are same, so you dont see the change on ui. Check the demo i attached
Comment: Resets the input fields, but the search function stopped.
Comment: What do you mean by that
Comment: Printing the objects from the database further down in the html doc, and filtering through the input fields with ng-model="variableName".


Get image from url and place it in imageview - Android

Question: My url: http://www.deepanelango.me/wp%2Dcontent/uploads/2017/06/noyyal1.jpg
How to get image from the above mentioned url and set it in a imageview in android?
I have tried glide and here is my error log:

I/Glide: Root cause (1 of 1)
           java.net.SocketTimeoutException: connect timed out
               at java.net.PlainSocketImpl.socketConnect(Native Method)
               at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:334)
               at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
               at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
               at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
               at java.net.Socket.connect(Socket.java:605)
               at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
               at com.android.okhttp.Connection.connectSocket(Connection.java:196)
               at com.android.okhttp.Connection.connect(Connection.java:172)
               at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:367)
               at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:130)
               at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
               at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:247)
               at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:457)
               at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:126)
               at com.bumptech.glide.load.data.HttpUrlFetcher.loadDataWithRedirects(HttpUrlFetcher.java:102)
               at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:54)
               at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:96)
               at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.startNextOrFail(MultiModelLoader.java:147)
               at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.onLoadFailed(MultiModelLoader.java:141)
               at com.bumptech.glide.load.data.HttpUrlFetcher.loadData(HttpUrlFetcher.java:60)
               at com.bumptech.glide.load.model.MultiModelLoader$MultiFetcher.loadData(MultiModelLoader.java:96)
               at com.bumptech.glide.load.engine.SourceGenerator.startNext(SourceGenerator.java:61)
               at com.bumptech.glide.load.engine.DecodeJob.runGenerators(DecodeJob.java:298)
               at com.bumptech.glide.load.engine.DecodeJob.runWrapped(DecodeJob.java:268)
               at com.bumptech.glide.load.engine.DecodeJob.run(DecodeJob.java:229)
               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
               at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
               at java.lang.Thread.run(Thread.java:761)
               at com.bumptech.glide.load.engine.executor.GlideExecutor$DefaultThreadFactory$1.run(GlideExecutor.java:413)
Comment: you can use Glide or Fresco Lib for this.
Comment: @DileepPatel I get error response from glide when I pass the url
My code: Glide.with(ctx).load(imageUrl).apply(RequestOptions().centerCrop()).into(iv)
Comment: @Deepan what error share with question
Comment: Glide.with(yourContext).load(Your Url).into(imageview);
Comment: please share your log error code
Comment: This question is asked many times before, please search before asking a question.
Comment: @RatilalChopda I have tried those solutions too. I get socket timeout exception but my internet is working fine and permissions for internet are also added.
Comment: @Deepan may be your image size is to high just check it
Comment: @FatihOzcan - I know that but my url is not working when I use those methods. That is why i specifically mentioned the url! Check my url before answering such obvious replies!
Comment: share your error log
Comment: @DileepPatel Here's my log!
W/Glide: Load failed for http://www.deepanelango.me/wp%2Dcontent/uploads/2017/06/noyyal1.jpg with size [394x394]
         class com.bumptech.glide.load.engine.GlideException: Failed to load resource
           Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetching data failed, class java.io.InputStream, REMOTE
             Cause (1 of 1): class com.bumptech.glide.load.engine.GlideException: Fetch failed
               Cause (1 of 1): class java.net.SocketTimeoutException: connect timed out
Comment: @VishalYadav Thanks but didnt work
Comment: @DileepPatel may your image size is to high tried load it into webveiw
Comment: @RatilalChopda I will try it!
Comment: @Deepan let me know if it works or not
Comment: check my answer at this link, https://stackoverflow.com/questions/5776851/load-image-from-url/47195793#47195793
Answer: Use Picasso library
Picasso.with(context)
                .load(ImageURL)
                .into(imageView);

Comment: Have tried picasso too! Same as Glide. Check error log ;)
Answer: Add Dependency
compile 'com.github.bumptech.glide:glide:3.8.0'

and
Glide.with(yourContext).load(Your Url).into(imageview);

Comment: Didnt work. Check error log.
Answer: If it is only static images, then download it and add it to your app resources. If you have multiple non-static images, then you are best off using the Glide library, as it will take care of downloading, caching and much more.
Comment: I have tried Picasso, Glide, normal image caching - nothing worked with this url


Finale software: How can I add a measure within a numbered repeat ending?

Question: I'm trying to expand a repeat ending (ending 1) that is currently 1 measure to four measures, but if I try to insert measures they always get inserted outside of the repeat symbols.
A screenshot of the current situation:
Comment: However have you tried removing the first repeat and second ending, expand the first ending, reinsert the second ending then insert, and then place the repeat? Not a very efficient way but for all I know the software has rules on it that prevents any new measures to be created. Edit -- I read finale in its literal definition not as in the piece of software sorry...
Answer: The easiest solution seems to be to use the repeat tool to remove the endings, then to add the measure, then to use the repeat tool to add the endings as you want them.
These are the steps (using the repeat tool):

Highlight both the first and second endings
Right click -> Delete, to remove your endings completely.
Do whatever you need to do (i.e. add your measures).
Select the measures you want to be in the first ending.
Repeat Menu -> Create Ending
This should default to Ending Numbers = 1 and Create Backward Repeat Bar = true (see photo), Click OK.  This will create your first ending and repeat sign.
Highlight the measures you want in the Second ending, Repeat Menu -> Create Ending.
This time it should default to Ending Number = 2 and Create Backward Repeat Bar = false.  Accept these defaults, click OK.

Now you should have the repeats as you want them.


facing the issue with SELECT DML changes in oracle

Question: Please help me to write query in oracle  .
I want to retrieve the records once update the some records, that should be Done in single transaction. i need in oracle.
I have used earlier  DB2 , like the below query .
SELECT * FROM FINAL TABLE(update query ).
What Happens with the above query is update some records based on some condition and will return same list of results, is it possible with Oracle.
Comment: can you elaborate `some`
Answer:
update some records based on some condition and will return same list of results, is it possible with Oracle.

Oracle doesn't automatically maintain any track of the rows which were affected by DML statement. You need to have some mechanism implemented. You could write a trigger to maintain the history of the DML changes.
For example,
CREATE
OR
replace TRIGGER trigger_name AFTER
UPDATE
ON table_name FOR EACH ROW BEGIN IF( Updating( 'COLUMN1' ) ) THEN
INSERT INTO log_table
            (
                        column_name,
                        column_value
            )
            VALUES
            (
                        'COLUMN1',
                        :new.column1
            );

END IF;
IF( Updating( 'COLUMN2' ) ) THEN
  INSERT INTO log_table
              (
                          column_name,
                          column_value
              )
              VALUES
              (
                          'COLUMN2',
                          :new.column2
              );

END IF;
END;

Or you could enable Auditing.
If you are doing the DML in PL/SQL, you could use the returning_clause to get the rows which are affected by the DML.
For example,
SET SERVEROUTPUT ON
DECLARE
  TYPE t_tab IS TABLE OF t1.id%TYPE;
  l_tab t_tab;
BEGIN
  UPDATE t1
  SET    description = description
  RETURNING id BULK COLLECT INTO l_tab;

  FOR i IN l_tab.first .. l_tab.last LOOP
    DBMS_OUTPUT.put_line('UPDATE ID=' || l_tab(i));
  END LOOP;

  COMMIT;
END;
/
UPDATE ID=1
UPDATE ID=2
UPDATE ID=3

PL/SQL procedure successfully completed.

SQL>

Read this article.


How to get a Control byId from a SAPUI5 Fragment

Question: I have a dialog which is in a Fragment. So after entering the details into it and clicking the submit button, the text which was filled into the input should be displayed as a MessageToast. But I am getting the error : ' Cannot read property 'getValue' of undefined '.
Below is the code :
    onAddMovie: function() {
        var view = this.getView();
        var createDialog = view.byId("CreateDialog");
        var oDummyController = {
            // This is when I clicked the Submit button in dialog
            submitDialog: function() {
            var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();
                MessageToast.show(user);
                createDialog.close();
            },
            closeDialog: function() {
                createDialog.close();
            }
        };

        if (!createDialog) {
            createDialog = sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);
        }
        view.addDependent(createDialog);
        createDialog.open();
        if (!createDialog.isOpen()) {
            //do sth
        }
    },

Above is the function in which the dialog is getting displayed and after pressing submit button , the text in the input should be displayed in a MessageToast.
XML :
        <core:FragmentDefinition  xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">

        <Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
            <l:VerticalLayout class="sapUiContentPadding" width="100%">
            <l:content>
                <Input width="100%" placeholder="Movie Name" id="movie_name"/>
                <HBox alignItems="Center" renderType="Bare">

                    <ActionSelect selectedItem="Element sap.ui.core.ListItem#__item0" selectedKey="item1" class="sapUiLargeMarginBegin" selectedItemId="__item0" id="__select0" width="50%">
                        <items>
                            <core:ListItem text="2017" key="item1" id="__item0"/>
                            <core:ListItem text="2016" key="item2" id="__item1"/>
                            <core:ListItem text="2015" key="item3" id="__item2"/></items>
                    </ActionSelect>
                </HBox>
                <HBox alignItems="Center" renderType="Bare">

                    <DatePicker class="sapUiLargeMarginBegin" width="50%" id="__picker0"/>
                </HBox>
                <HBox alignItems="Center">

                    <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="__group0">
                        <buttons>
                            <RadioButton selected="true" groupName="__group0" text="Universal" id="__button0"/>
                            <RadioButton groupName="__group0" text="Adult" id="__button1"/>
                            <RadioButton groupName="__group0" text="U/A" id="__button2"/></buttons>
                    </RadioButtonGroup>
                </HBox>
                        <HBox alignItems="Center" width="100%" renderType="Bare">

                <CheckBox id="__box0" width="30%" textDirection="LTR"/>
            </HBox>
                <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">

                    <SegmentedButton selectedButton="__button3" id="__button21">
                            <buttons>
                                <Button text="Submit" id="__submit" press="submitDialog"/>
                                <Button text="Cancel" id="__button41" press="closeDialog"/></buttons>
                        </SegmentedButton>
                            </FlexBox>
                </l:content>
            </l:VerticalLayout>
        </Dialog>

    </core:FragmentDefinition>

Comment: Getting the control from the fragment depends on how you created the fragment: https://stackoverflow.com/a/47872515/5846045 In your case, calling `this.byId("movie_name")` returns the control.
Answer: Since you are creating the dialog with the views id
sap.ui.xmlfragment(view.getId(), "Admin.view.Dialog", oDummyController);

all control ids in that fragment will be prefixed with the views id (this.getView().getId(), e.g. __xmlview1).
That has the big advantage that all fragment controls are accessible via this.getView().getId() and therefore really 'feel' like they were part of the view and can be treated as such (esp. useful when using fragments to structure view code).
That is why you need to use
this.getView().byId("movie_name");

Which will end up querying for a control with an id like __xmlview1--movie_name (-- is used as separator by SAPUI5).
General Behaviour of byId methods
Generally speaking the byId methods behave like this:
this.getView().byId(sId) === sap.ui.getCore().byId(sViewId + '--' + sId));
sViewId + '--' + sId === this.getView().createId(sId)
sap.ui.core.Fragment.byId(sFragmentId, sId) === sap.ui.getCore().byId(sFragmentId + '--' + sId));

HINT
Be aware of potential ID conflicts between the controls of your view(s) and your fragment(s)!
Answer: Fragment
<core:FragmentDefinition xmlns="sap.m" xmlns:core="sap.ui.core" xmlns:l="sap.ui.layout">
<Dialog id="createDialog" title="Input Movie Details" width="100%" class="sapuiMediumMargin" confirm="handleClose" close="handleClose">
    <l:VerticalLayout class="sapUiContentPadding" width="100%">
        <l:content>
            <Input width="100%" placeholder="Movie Name" id="movie_name"/>
            <HBox alignItems="Center" renderType="Bare">

                <ActionSelect selectedKey="item1" class="sapUiLargeMarginBegin" id="select0" width="50%">
                    <items>
                        <core:ListItem text="2017" key="item1" id="item0"/>
                        <core:ListItem text="2016" key="item2" id="item1"/>
                        <core:ListItem text="2015" key="item3" id="item2"/></items>
                </ActionSelect>
            </HBox>
            <HBox alignItems="Center" renderType="Bare">

                <DatePicker class="sapUiLargeMarginBegin" width="50%" id="picker0"/>
            </HBox>
            <HBox alignItems="Center">

                <RadioButtonGroup width="100%" columns="3" selectedIndex="-1" id="group0">
                    <buttons>
                        <RadioButton selected="true" groupName="group0" text="Universal" id="button0"/>
                        <RadioButton groupName="group0" text="Adult" id="button1"/>
                        <RadioButton groupName="group0" text="U/A" id="button2"/></buttons>
                </RadioButtonGroup>
            </HBox>
            <HBox alignItems="Center" width="100%" renderType="Bare">

                <CheckBox id="box0" width="30%" textDirection="LTR"/>
            </HBox>
            <FlexBox alignItems="End" alignContent="Center" justifyContent="End" class="sapUiTinyMarginTop">
                <SegmentedButton id="button21">
                    <buttons>
                        <Button text="Submit" id="submit" press="submitDialog"/>
                        <Button text="Cancel" id="button41" press="closeDialog"/></buttons>
                </SegmentedButton>
            </FlexBox>
        </l:content>
    </l:VerticalLayout>
</Dialog>

Controller
sap.ui.define([
    "sap/ui/core/mvc/Controller"
], function(Controller) {
    "use strict";
return Controller.extend("test001test001.controller.View1", {
    _oNewProcessDialog:null,
    onAddMovie: function() {
    this._getNewProcessDialog().open();
    },
    submitDialog:function(){

    sap.m.MessageToast.show(sap.ui.getCore().byId("movie_name").getValue());
    },
    closeDialog: function() {
            this._getNewProcessDialog().close();
        },

        _getNewProcessDialog: function() {
        // create dialog lazily
        if (!this._oNewProcessDialog) {
            // create dialog via fragment factory
            this._oNewProcessDialog = sap.ui.xmlfragment("test001test001.view.CreateDialog", this);
            // connect dialog to view (models, lifecycle)
            this.getView().addDependent(this._oNewProcessDialog);
            jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._oNewProcessDialog);
        }
        return this._oNewProcessDialog;
    },
});

});
Wiew
<Button press="onAddMovie"></Button>

Answer: Instead of using :
 var view = this.getView();
var user = sap.ui.core.Fragment.byId("createDialog", "movie_name").getValue();

I used :
 var view = this.getView();
 var user = view.byId("movie_name").getValue();
                MessageToast.show(user);

And it worked !!


Materialize CSS - label fixo no topo

Question: Como faço pra fixar meu label sempre no Topo?
Comportamento normal: fica no input, quando clicamos no input (focus) ele fica em cima do input

      <input placeholder="Placeholder" id="first_name" type="text" class="validate">
      First Name

Comment: Sempre quando? Aparentemente ele já está no topo, mesmo quando o `input` está vazio... Ele só tem um efeito quando aperta F5 que é fazer o `label` subir para antes do `input`, é esse efeito que vc quer remover?
Comment: Você poderia editar sua pergunta, colocando trecho do que você já tem desenvolvido? assim fica mais fácil para te ajudarmos.
Comment: Não há necessidade, mais colocarei um trecho qualquer encontrado no mesmo site do Materialize css. é que é algo que quem conheçe a ferramente, sabe do que falo
Comment: Exatamente
quem conhece a ferramenta ou seja seu materialize especifico
coloque pelo menos o link para ele para podermos ver quais classes ele usa
pois provavelmente exite uma classe que define isso na propria ferramenta
Answer:
Versão 1.0.0 (mais recente)

Na versão mais atual do Materialize para deixar a label no topo basta adicionar nela a classe active, por exemplo Label Active

Outro detalhe importante é que para a label ficar no topo, o input que vem antes dela deve estar com o placeholder vazio, então no input que antecede essa label vc tem que deixar a propriedade vazia placeholder="". Isso acontece pq automaticamente quando vc usa placeholder no input a label relacionada já fica no topo.
Seque código da imagem acima.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

 <form class="col s12">

    <input placeholder="" id="first_name" type="text" class="validate">
    Label Active

    <input id="first_name2" type="text" class="validate">
    Labem padão

    <input placeholder="texto do placeholder" id="first_name2" type="text" class="validate">
    Labem padão

 </form>

Versão 0.100.2 (versão antiga)

Pelo que entendi da sua pergunta, se vc quer o Label do input sempre no topo sem a animação vc tem que colocar no .input-field label os mesmo valores do .input-field label:not(.label-icon).active
.input-field label {
    -webkit-transform: translateY(-14px) scale(0.8);
    transform: translateY(-14px) scale(0.8);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
}

Execute o Snippet e veja o exemplo funcionando com o Label sempre no topo

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      <input value="" id="first_name2" type="text" class="validate">
      First Name

Answer: Luiz Felipe, esse exemplo foi tirado do showCase do MaterializeCSS:

    <input placeholder="Placeholder" id="first_name" type="text" class="validate">
    First Name

    <input id="last_name" type="text" class="validate">
    Last Name

Na primeira div o label fica fixo na parte de cima e o placeHolder fica dentro do input
Na segunda div o label fica dentro do input e sobe para cima do input quando foca

A sua pergunta está um pouco confusa pois o código que você postou deverá ter o comportamento esperado. Você não está confundindo algo da pergunta? O código ou o comportamento esperado?

Referência:
http://materializecss.com/forms.html

Materialize CSS - label fixo no topo


How to bring Ample guitar onto FL studio piano roll?

Question: I have Ample guitar M II lite.
I created a strumming pattern in the guitar plugin, and I want to 'bring' that strumming pattern onto my piano roll and play it with the song. I can't figure out how to do that so please help me.
Answer: The notes that the Ample Guitar plugin provides for patterns and chords are not accurate to FL Studio. They are off by two octaves.

Function
Ample Plugin Notes
FL Studio Notes

Patterns
C3 - D#4
C5 - D#6

Chords
C1 - B2
C3 - B4

It seems that you can add two to the Ample plugin's octave to find the correct FL Studio octave.
I myself didn't discover this.
Answer: Just put root note to C3, then draw notes as AGM did say.

Put Root note to C3
Turn on the strum mode button
In piano roll, draw note C3(for play SEQ1), and here you have 24 chords to play from C1 to B2.


Custom user profile titles interfering with user views block

Question: I'm using this function to replace the titles on user pages with a user text field:
function MYMODULE_user_view($account, $view_mode, $langcode) {
  $wrapper = entity_metadata_wrapper('user', $account);
  $auth_name = $wrapper->field_account_auth_name->value();
  if ($auth_name) {
    drupal_set_title('Profile overview for ' . $auth_name;
  } else {
    drupal_set_title('Profile overview for ' . $account->name);
  }
}

It works as it should, but when I add a view block with user entities it makes every page have the same title. It's Profile overview for ' . $auth_name; for the first user with a non-empty field_account_auth_name. If I delete that user the next user takes its place. This is for all pages too, not just ones with the block in it.
If it matters I'm using this function
  function MYMODULE_preprocess_user_profile(&$vars) {
    if ($vars['elements']['#view_mode'] == 'auth') {
      $vars['theme_hook_suggestions'][] = 'user_profile__auth';
    }
  }

with a user entity "auth" I created using Entity View Mode, with this in user-profile--auth.tpl:
<div class="authProfile"<?php print $attributes; ?>>
  <?php print render($user_profile); ?>

and setting auth as the view mode in the view block. But the title problem happens with the user account view mode as well.
Answer: You could check the url using the arg function and only set the title if the current page is a user/* page. You could try something like the following.
function MYMODULE_user_view($account, $view_mode, $langcode) {
  if (arg(0) == 'user') {
    $wrapper = entity_metadata_wrapper('user', $account);
    $auth_name = $wrapper->field_account_auth_name->value();
    if ($auth_name) {
      drupal_set_title('Profile overview for ' . $auth_name;
    } else {
      drupal_set_title('Profile overview for ' . $account->name);
    }
  }
}

Comment: Are you using arg(0) as a placeholder? I don't know php very well. I know of current_path() but AFAIK it only allows for specific URLs, not path/1, path/2, etc.
Comment: Nevermind I messed up. It's no longer on all pages, but it's still just using the first user with a non-empty field_account_auth_name on all user pages. I tried `if (empty($auth_name))  . . . $account->name) else . . . $auth_name` but it's the same. Any ideas?
Comment: arg is a Drupal function that returns the ith part of the current path. So arg(0) returns the first part of the path (everything after the domain and before the first slash). See https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/arg/7
Comment: I'm not sure what the problem is. Are you having problems on pages with multiple users? I imagine that on those pages it would be the last user's name that gets rendered.
Comment: Okay gotcha. No it's on single user pages, just the regular ?q=user/*. If the view block is in a region then every user page's title is "Profile overview for x's field_account_auth_name", x being the oldest user if I set the sort criteria to User: Created date (desc), and newest if I set it to asc. I'm pretty confused.
Comment: Could it be the way I'm using views pages/blocks in combination? To be more semantic and consistent with template files/paths I make views pages then use page--path.tpl, instead of an article / custom path / page--node--x.tpl. Within that page--path.tpl I call the regions, and in the regions are views blocks. Seems unlikely it's that but I don't know.
Comment: If you call drupal_set_title multiple times, the actual title will be the string passed the last time it was called. So this makes sense that the title would be the oldest user. In this case you probably don't want to call drupal_set_title at all if you're on a user page so you should change my code sample to have the following line instead. if (arg(0) != 'user') {
Comment: With (arg(0) != 'user') no title change is made though. It's just "username | site name". I want the title of ?q=user/* to be "Profile overview for username | sitename" if the field is empty and "Profile overview for field | sitename" if it isn't. It works as it should without the view. If views templates weren't so limiting I would just use user fields, but I have to render custom profiles to theme it properly. Frustrating!
Comment: Hmm, maybe it would be easier to just change the title by creating a page-user.tpl.php file, where you replace the standard title with your custom php code. Not a great solution but i know it would work. Or you could use drupal_static to count how many times your function has been called and only call drupal_set_title the first time (which will be the real user).
Comment: I went back and really looked at the views templates, and I was able to get it how I needed it with fields. All of the if statements just threw me off the first time. Still some unnecessary divitis going on but I don't mind.


Como que eu posso medir o tempo de execução de um programa em c++?

Question: Fiz um programa que gera um vetor aleatoriamente e depois o ordena, usando bubble sort, agora tenho que medir o tempo gasto com a ordenação.
Answer: Você pode calcular o tempo de execução de funções utilizando C++11 com alta precisão utilizando a biblioteca <chrono>. Por ex:
auto inicio = std::chrono::high_resolution_clock::now();
...SEU CÓDIGO AQUI...
auto resultado = std::chrono::high_resolution_clock::now() - inicio;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(resultado).count();

Sendo que você pode substituir std::chrono::microseconds (microsegundos) por std::chrono::milliseconds (milissegundos), std::chrono::seconds (segundos) ou até mesmo std::chrono::nanoseconds (nanosegundos).
Answer: Voce está usando linux como SO? Para um programa simples como esse eu sugiro que use time ./a.out no terminal, onde a.out é o executavel do seu programa. Esse comando imprime 3 linhas (explicadas bem resumidamente):

real: Tempo real do comeco ao fim da execucao;
sys: Tempo gasto pelo kernel do sistema no processo de execucao do seu programa;
user: Tempo usado no user-mode. É o tempo que seu computador gasta no processo fora do kernel;
Comment: To usando o Windows


Send/Receive Data to server in C#

Question: In my programe I have a need for requesting data from server and upon collecting the response, use the returned data for further processing.
I am using "system.net.webrequest" class for the same. I have few questions on this:

after I receive the data (data is of 0.5MB size in minimum) I have to process this entire data to derive some result. I was thinking to store the returned data in a "txt" file and then read the data from that file and process.

Is this a better idea? If not, can you please suggest.

I am making post request to several servers (>10 servers) and using data from them. I observed that for some reason if the server is not reachable then my programe stops throwing an exception
Server Not Reachable
A first chance exception of type 'System.Net.WebException' occurred in System.dll

How can I solve this problem? Any idea?
Appreaciate your help.
Thanks,
Rahul
Answer: With regards to the exception; implement a try/catch region, and take appropriate action (perhaps logging the error and queuing it for a retry in a few moments).
I'm not entirely sure of what the first question is since we don't know what the data/system is - but some thoughts:

to reduce bandwidth, if the server supports compression, make sure you are telling it - set the accept-header accordingly (request.Accept = "gzip,deflate"; on your request, if using HttpWebRequest); or maybe  a denser serialization format if you control both ends of the pipe
make sure you are making appropriate use of things like Dictionary<,> when processing the data; I can't tell you what "appropriate" is without knowing what "processing" or "the data" means in your specific context ;p
Comment: Hi Marc, Yes, I got the 2nd question; using try/catch/finally ... solved. 1st question: return data from server is in XML format and I am getting the data returned fine ... but was thinking for a better way of using that data ... as I said no.of servers I am quering is > 10. So, like I will be keep on requesting data from servers and process then until all the servers is processed.
Comment: @Rahul you could try parallel if you are being constrained by each (independent) server's bandwidth; of course, if you are constrained by **your** bandwidth, or the "10 servers" are all actually the same one, this isn't going to help.
Answer: Saving the data to a file is only necessary if you don't want to, or cannot, process it as you receive it or if you want to keep that data around after processing for debugging purposes. I typically avoid creating files like this if I can as it adds to the maintenance overhead.
To continue processing data from other servers in case of an exception on one, you will need to use a Try/Catch block as follows (pseudo):
foreach (var server in serverList)
{
    try
    {
        ... fetch data and process ...
    }
    catch (Exception ex)
    {
        // handle exception (log, requeue, etc)
    }
}

Comment: Bill, agree ... even I don't like that, storing data in files. So, are you suggesting me use the returned data directly instead of saving it in txt file. Sorry for asking you but can you please provide some sample code blocks on how to use the data directly. Thank You.

Send/Receive Data to server in C#


Performance do INNER JOIN em SQL

Question: Olá, alguém saberia me dizer se há alguma diferença significativa de performance nas duas maneiras de fazer INNER JOIN abaixo?
Maneira 1:
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

Maneira 2:
SELECT column_name(s)
FROM table1, table2
WHERE table1.column_name=table2.column_name;

Eu creio que a resposta deve depender do SGBD, estou mais interessado em bancos Oracle que são os que eu uso com mais frequência, mas se alguém souber a resposta para outros também seria legal saber!
Answer: Em performance, não, mas em expressão de linguagem, sim. A Oracle recomenda sair das operações não-ANSI porque elas são mais limitadas que as operações ANSI.
Além disso, como a sintaxe ANSI é um padrão aplicável a todos os bancos de dados, escrever tudo em ANSI facilita a portabilidade para outros bancos de dados, se isto for desejável no futuro.

Performance do INNER JOIN em SQL


Why te conditional formatting rules doesn't work in excel?

Question:
Hi everyone,
I'm trying to do the conditional formatting for the percentage column which is more than 30%. However, it seems like highlighted all the cells for me even though it is a negative percentage. May I know why is it so?
Comment: Perhaps the cells are text representations.  What is the result of the formula `=ISNUMBER(cell_ref)` when excuted against each cell?
Comment: The answer is false, but I already formatted it to percentage, so what did I did wrong actually?
Comment: Seems like no matter what format I set, ISNUMBER() will always give me FALSE
Comment: Formatting does not change the data type.  What do you see in the formula bar when you select a cell?
Comment: I found a way to solve it already. I insert a value function to change the text to a number. Thanks for your remind and advise!
Comment: Glad to help out
Answer: Perhaps the cells are text representations. What is the result of the formula =ISNUMBER(cell_ref) when excuted against each cell?


Abrir página diretamente em um determinado slide

Question: Tenho uma página que é inteiramente um slide, apenas com o menu ao lado. Gostaria de saber como faço para abrir essa página diretamente em um determinado slide. Já tentei pelo método comum e mais conhecido, acrescentando um ID a cada item do slide, que é uma lista (li) e depois chamo a página passando o link da mesma + o id do slide que quero abrir. Porém nada acontece e sempre abre no primeiro item do slide. Se alguém tiver ideias seria de grande ajuda. Obrigado.

Chamando o item:

Comment: Qual lib você está usando? Você precisa verificar a API da sua lib para realizar tal ação. Quando utilizamos o [Slick](http://kenwheeler.github.io/slick/), podemos usar `initialSlide: 2`, por exemplo.
Answer: Você pode usar o jQuery, detectando a distancia do topo da página para a li, e depois fazendo a pagina rolar até esse ponto.
Veja esse exemplo https://jsfiddle.net/diancabral/t9fx77b5/


Java StreamCorruptedException

Question: I have a client and server application that transfer message using serialization over TCP.  I got the following error when deserializing an object:
Any ideas to the cause or possible next steps in analyzing this problem?
<code>java.io.StreamCorruptedException: invalid stream header: 383D4649
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at com.aqua.NmsApi.ResiliantTCPServer$ServerThread.run(ResiliantTCPServer.java:248)
    at java.lang.Thread.run(Unknown Source)
</code>
Answer: There's something wrong with the magic number at the head of the serialized data.  You're probably going to need to capture the serialized data and look it over yourself to start with.  That ascii stream is '8=FI'.
Comment: these are remote logs of the server process.  the user restarted the server and it started working.  but i'm still analyzing the cause.
Comment: It's not too improbable then that there was a transient comms issue.  You should add exception handling around the original exception location, see if you can capture more data.
Answer: There are two possible reasons for that:

The stream has actually been corrupted (i.e. what you are reading is different from what you wrote at the other end). In that case you should write in a local file each contents (emitted and received), and compare them.
The magic numbers required by the implementation(s) of ObjectInputStream you are using at are different at either end, for instance because you are using different versions of the Java base packages. Those constants are declared in ObjectStreamConstants, you should check them.
Answer: are you using exactly one ObjectInput/OutputStream per socket Input/OutputStream?  recreating these on the same input/output stream is a common cause of such an error.
Comment: Only when you do it out of synchronization.

Java StreamCorruptedException


Let $X_t$ be a solution of a SDE. Does the set $\{X_t \in \{p\}\}$ has null measure?

Question: This question was previously posted on https://math.stackexchange.com/questions/3981156/let-x-t-be-a-solution-of-a-sde-does-the-set-x-t-in-p-has-null-meas.
I think this question is easy. However, I have not been able to solve it.
Let $a,\sigma:\mathbb{R}\times \mathbb R\to\mathbb{R}$, smooth functions such that $\sigma>0$. Consider the 1-dimensional SDE,
$$dX_t = a(X_t,t) dt + \sigma(X_t,t) dW_t$$
$$X_0 = x_0\in\mathbb{R}. $$
where $W_t$ is the standard Brownian motion.
Fixing $y\in\mathbb R$ and $t>0$, I was interested in showing that$$\mathbb{P}\left(\{\omega \in \Omega;\ X_t = y\}\right)=0.$$
Where $(\Omega,\mathcal F, \mathbb P)$, is the probability space being considered.
Does anyone know if the above equation is true? A reference would be enough for me.
Comment: More generally though, one easy way to proceed is to begin by "forgetting" about the fact  that $X_t$ is defined from an SDE in the first place. Then $X_t$ is just a bona fide random variable, so the usual things you can say about random variables apply to $X_t$ as well. In particular, $\mathbb P(\{\omega \in \Omega, X_t = y\}) = 0$ would certainly be true as long as $X_t$ was a continuous random variable, which would certainly be true, for example, if $W_t$ were Brownian motion.
Comment: What assumptions on $W_t$ are you making? With literally no assumptions, the answer could be "no" by the (not so interesting) counterexample $W_t = 0, \forall t$, $a(X_t, t) = 0$, and $x_0 = y$.
Comment: @stats_model $W_t$ is the Brownian motion sorry. Are you able to provide a proof of such a fact, or provide a reference? I really want to know how to prove this.
Answer: With my washed-up SDE knowledge from option pricing, I came up with the following. I am not sure if it is correct reasoning, but I am open to discuss it so I can also learn the right answer If I am wrong.
We have:
$$X_t - X_{t-1} = a(X_{t-1}, t-1)(t - t + 1) + \sigma (X_{t-1}, t-1)(W_t - W_{t-1})$$
$$X_t = X_{t-1} + a(X_{t-1}, t-1)(t - t + 1) + \sigma (X_{t-1}, t-1)(W_t - W_{t-1})$$
From the properties of Brownian motion, we know that:
$$(W_t - W_{t-1}) \sim N(0, 1)$$
Also note that because we are at time $t$, $X_{t-1}$ is realized, thus $a(X_{t-1}, t-1)$ and $\sigma (X_{t-1}, t-1)$ is deterministic and the only random component is Brownian motion increment. Thus, distribition of $X_t$ is given by:
$$X_t \sim N(X_{t-1}+a(X_{t-1}, t-1), \sigma (X_{t-1}, t-1))$$
Since it is a normal distribution and normal distribution is a continuous distribution. And for all continuous distributions, we have:
$$P(X=x) = 0 \ \forall x$$
Thus:
$$P(X_t=y) = 0 \ \forall y$$
Looking forward to your feedback
Edit:
This is the explanation of what @stats_model commented.
Comment: I was not able to understand why $X_t = X_{t-1} + a(X_{t-1},t-1) (t-t+1) + \sigma (X_{t-1},t-1) (W_t - W_{t-1})$. Does it hold in general or is it only in a discrete context?
Comment: @MatheusManzatto This is called discretizing the SDE, and as far as I know it holds in general. It is discretizing a continous process.
Comment: Discretizing would be an approximation even if the timestep is very small. If the timestep is fixed at 1, this doesn't seem correct.
Comment: @S.CatterallReinstateMonica Result holds in limit because brownian motion increment follows normal distrb. holds in limit. That is take $W_t, W_{t-k}$ as $k \to 0$ increment converges to normal dıstrb. I just gave 1 as example, time gap can be anything.
Comment: That's true, the time gap could be anything - but it's a fixed constant in what you've written. To rigorously prove the required result you would have to study what happens as the time gap converges to zero.
Answer: You say that this question is 'easy' but I would say that it is not so easy, having had a quick look at the relevant literature. Possibly the most elementary and accessible answer to this question is contained in the paper by N. Fournier, J. Printems,
Absolute continuity of some one-dimensional processes,
Bernoulli, 16 (2010), pp. 343-360. Section 3 of the paper considers SDEs of the form $$X_t=x+\int_0^t \sigma(X_s)\kappa (s,(X_u)_{u\leq s} H_s) \text{d}B_s+\int_0^t b(s,(X_u)_{u\leq s},H_s)\text{d}s$$ for suitable functions $\sigma$, $\kappa$ and $b$ and an auxiliary process $(H_t)_{t\geq 0}$. Theorem 3.1 states that, given suitability nice coefficient functions, the law of $X_t$ has a density on $\{x\in\mathbb{R}: \sigma(x)\neq 0\}$ whenever $t>0$. I think that this theorem should cover your situation if you place suitable restrictions on your coefficient functions e.g. that they have at most linear growth. The paper also has references to alternative approaches such as the use of the Malliavin calculus.


Applying comparison theorem to limits when inequality is known

Question: I somehow confuse myself whenever I apply the comparison lemma.  I know there is the comparison lemma that says the following:

Let the sequence $\{a_{n}\}$ converge to the number $a$. Then the sequence $\{b_{n}\}$ converges to the number $b$ if there is a non-negative number $C$ and an index $N$ such that $$\lvert b_{n} - b \rvert \leq C \lvert a_{n}-a\rvert$$

Somehow i accidentally apply this wrong. For example let's say I'm applying it to the sequence $a_n$, to say that it converges to $0$,
$$a_n=\frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}$$
and
$$b_n=\frac{1}{\sqrt{1+\frac{1}{n}}+1}$$
Obviously, since $n\ge1$, then I can say
$$\frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}<\frac{1}{\sqrt{1+\frac{1}{n}}+1}$$
Subtracting $1/2$ from both sides, I can see that
$$\frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}-\frac{1}{2}<\frac{1}{\sqrt{1+\frac{1}{n}}+1}-\frac{1}{2}$$
Since I know that $$\frac{1}{\sqrt{1+\frac{1}{n}}+1} \longrightarrow \frac{1}{2}$$  then the comparison lemma seems to be telling me that $a_n$ converges to $1/2$, when in fact I know that it converges to $0$.  Where am I going wrong in this logic?
Comment: Your comparison lemma is an immediate consequence of the squeeze theorem. And you should try to apply squeeze directly rather than this (not so useful) Lemma
Answer: The problem is that $$\sqrt{1+\frac{1}{n}} + 1 > 2$$ for all $n\in\mathbb N$, and therefore
$$\frac{1}{\sqrt{1+\frac{1}{n}}+1}-\frac{1}{2} < 0$$
When you compare the absolute values of both sides of your last inequality, the "$<$" becomes "$>$", and the theorem does not apply.
Namely, because the values inside the absolute value sign are negative, we have that
$$\left| \frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)} - \frac{1}{2} \right| = \frac{1}{2} - \frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}$$
$$\left| \frac{1}{\sqrt{1+\frac{1}{n}}+1} - \frac{1}{2} \right| = \frac{1}{2} - \frac{1}{\sqrt{1+\frac{1}{n}}+1}$$
But, starting from the inequality (that does indeed hold):
$$\frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}-\frac{1}{2}<\frac{1}{\sqrt{1+\frac{1}{n}}+1}-\frac{1}{2}$$
and multiplying both sides by -1, and remembering that we have to flip the inequality sign, we arrive at
$$\left| \frac{1}{\sqrt{n}\left(\sqrt{1+\frac{1}{n}}+1\right)}-\frac{1}{2} \right| > \left|\frac{1}{\sqrt{1+\frac{1}{n}}+1}-\frac{1}{2} \right|$$
Therefore, the sequences $a_n$ and $b_n$ do not satisfy the conditions of the theorem.
Comment: @guimption Well, you cannot. Because the sequence converges to 0. I will add more clarification in my answer.
Comment: @guimption Just use that $\frac{1}{\sqrt{1+1/n}+1} < 1$, yielding $a_n=\frac{1}{\sqrt n \left( \sqrt{1+1/n}+1 \right)} < \frac{1}{\sqrt n}$. Now you have that $0\leq a_n \leq \frac{1}{\sqrt n}$. Knowing that $1/\sqrt n \to 0$, using the squeeze theorem you get that $a_n \to 0$.
Comment: Okay, so how do I use the knowleddge that his converges to 1/2?
Comment: Then what is an easy way to the sequence of interest converges to 0?
Comment: @guimption Have I answered your question?


How to move the logic from component to service (Angular)

Question: I have components that save data to local storage and i want to move all the logic from the component to service.
This is my Components:
I Want to move all the stuff from ngOnInit to service.
   import { Component, OnInit, Input } from '@angular/core';
    import { Report } from 'src/app/shared/entity/report.entity';
    import {Utils} from '../../../../shared/utils';

    @Component({
      selector: 'app-kit-header',
      templateUrl: './kit-header.component.html',
      styleUrls: ['./kit-header.component.sass']
    })
    export class KitHeaderComponent implements OnInit {
      @Input() reportData: Report;
      public dateCreate: any;
      public year: string;
      public deadLine: any;
      public typeName: string;
      public hour: any;
      public date: any;
      constructor() { }

      ngOnInit() {
        if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate', JSON.stringify(this.reportData.dateCreated));
          localStorage.setItem('year', JSON.stringify(this.reportData.year));
          localStorage.setItem('deadLine', JSON.stringify(this.reportData.deadLine));
          localStorage.setItem('typeName', this.reportData.name);
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        } else {
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        }
        this.deadLine = new Date(JSON.parse(this.deadLine));
        this.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        this.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
      }

      formatedDate(deadLine: Date) {
        return Utils.parseHebrewDate(deadLine);
      }

    }

Service:
saveKitData(dateCreated, year, deadLine, name) {
???
}

thanks
Comment: First read the angular doc about service (https://angular.io/tutorial/toh-pt4), stackoverflow is not a place where developer will write your code for you. You have to try to build the service and if it's doesn't work provide a stackblitz or something else and we will help you.
Answer: You need to move the whole logic to that method,  instead of passing each property, you can pass the whole object reportData
saveKitData(reportData : any) {
if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate', JSON.stringify(reportData.dateCreated));
          .....
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        } else {
          this.dateCreate = localStorage.getItem('dateCreate');
          this.year = localStorage.getItem('year');
          this.deadLine = localStorage.getItem('deadLine');
          this.typeName = localStorage.getItem('typeName');
        }
        this.deadLine = new Date(JSON.parse(this.deadLine));
        this.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        this.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
}

Answer: It is better to write a service and use dependency injection to use it in your component like below:
at first, encapsulate data in a class :
export class CustomDataDto{
      public dateCreate: any;
      public year: string;
      public deadLine: any;
      public typeName: string;
      public hour: any;
      public date: any;
}

Then move your code into a Service:
@Injectable()
export class YourDataStorageService {
  public CustomDataDto myGetDataMethod(reportData : any){
      localStorage.setItem('dateCreate',
                            JSON.stringify(reportData.dateCreated));
          .....
      let data=new CustomDataDto ();
      if (localStorage.getItem('dateCreate') === null) {
          localStorage.setItem('dateCreate',
          JSON.stringify(this.reportData.dateCreated));
          localStorage.setItem('year', JSON.stringify(this.reportData.year));
          localStorage.setItem('deadLine', JSON.stringify(this.reportData.deadLine));
          localStorage.setItem('typeName', this.reportData.name);
          data.dateCreate = localStorage.getItem('dateCreate');
          data.year = localStorage.getItem('year');
          data.deadLine = localStorage.getItem('deadLine');
          data.typeName = localStorage.getItem('typeName');
        } else {
          data.dateCreate = localStorage.getItem('dateCreate');
          data.year = localStorage.getItem('year');
          data.deadLine = localStorage.getItem('deadLine');
          data.typeName = localStorage.getItem('typeName');
        }
        data.deadLine = new Date(JSON.parse(this.deadLine));
        data.hour = new Date(JSON.parse(this.dateCreate)).toLocaleTimeString();
        data.date = new Date(JSON.parse(this.dateCreate)).toLocaleDateString();
        return data;
}
}

In the Next step,you must declare it in NgModule:
@NgModule({
  providers: [YourDataStorageService ];
})

At the end, you can use it in your component :
export class KitHeaderComponent implements OnInit {
    constructor( injector: Injector,
                 private _yourDataStorageServiceProxy: YourDataStorageService) {
         super(injector);
     }
    ngOnInit() {
      let data = this._yourDataStorageServiceProxy.myGetDataMethod();
  }
}


dynamically add and removing div with javascript

Question: presently stuck in situation. trying to create a form where one can dynamically add and remove div elements where necessary,so far have been a to DYNAMICALLY ADD, problem is if i try to REMOVE div,only the last created gets to delete whilst others remain(excluding the parent div)KINDLY ASSIST.
 <!doctype html>

Degree Level: <select id="dropdown">
            <option value="Doctorate Degree">Doctorate Degree</option>
            <option value="Masters">Masters</option>
            <option value="Bachelors Degree">Bachelors Degree</option>
            <option value="SSCE">SSCE</option>
        </select>

School Name
<input type="text" placeholder="Your Role"">
From
<input type="text" id="from" name="from">

to
<input type="text" id="to" name="to">

<button id="submit1">Add new div</button>
 <input type="button" value="Remove Element"
 onClick="removeElement('box','div');">


Generating certificate for iLO

Question: I want to generate a proper certificate for iLO web console (iLO is a management engine for HP servers) using letsencrypt. AFAIK there's no way to install private key into iLO, so I've generated CSR from iLO. It contains the following field:
Requested Extensions:
    X509v3 Subject Alternative Name:
        DNS:ilo.example.com, IP Address:192.168.1.11

I've found no way to exclude IP Address part from CSR. I don't need it, I'll use only ilo.example.com. Now I issued
certbot certonly --manual --staging --preferred-challenges=dns --csr csr

command, completed DNS verification, but got error:
An unexpected error occurred:
The request message was malformed :: Error creating new cert :: CSR contains one or more IP address fields
Please see the logfiles in /var/log/letsencrypt for more details.

AFAIK CSR is signed by private key, so I can't edit it. Can I ask letsencrypt to ignore IP address and issue certificate only for ilo.example.com? Or is there other way?
Comment: I've found a post in HPE forums, that in the future it'll be possible: https://community.hpe.com/t5/Remote-Lights-Out-Mgmt-iLO-2-iLO/Anyway-to-change-the-Subject-Alternative-Name-on-iLo-SSL-Cert/m-p/6952270/highlight/true#M7892 I guess it's not possible now.
Answer: Here you go: https://community.letsencrypt.org/t/how-to-automatic-certificate-install-on-an-hp-ilo4-management-processor/31038

Generate CSR
Submit CSR to LE
Install resulting cert
Answer: Please use my utility that deals with CSR generation and DNS challenge (only with GoDaddy here).
The utility requires Powershell and is made by three scripts, of which one is Certbot itself.

A script that will request iLO to generate a CSR and download
Certbot will request the certificate upon CSR
A utility updates GoDaddy DNS to acknowledge DNS challenge

Please note that with HPE iLO it is only possible to perform DNS challenge.
The script I have made leverages the HPE iLO APIs to request the generation of a CSR without the IP address. It worked on two of my servers.
Disclosure. I made the tool and released under MIT License on GitHub

Generating certificate for iLO


Confidence intervals and standard error for binary data/proportions

Question: I'm doing some research into degrees held by professionals of different types, based on survey data. I'd like to be able to provide confidence intervals for some of the subgroups of professionals as they are of variable sample sizes, to work out whether the data is significant. The data is confidential, so i've made up some mock data below to demonstrate.
In the data you can see that 26% of teachers have at least one of the qualifications, 19% of lawyers and 66% of doctors. How do I work out the confidence intervals for this data?
I'm working in stata, and the information is stored as a person by person basis, with a 0 if they don't have a degree, and a 1 if they have one, so I worked out the percentage by adding up and dividing from the total, just can't work out how you get a CI. (does it require SE and SD?)

Teachers n=115

PhD :3
Masters :5
Diploma :22
Any of the above qualifications :30

Lawyers n=220

PhD :4
Masters :15
Diploma :23
Any of the above qualifications :42

Doctors n=15

PhD :3
Masters :6
Diploma :1
Any of the above qualifications :10
Answer: There are at least three different ways of doing this:
<code>/* (1) Just Using Counts */
cii proportion 15 10, jeffreys
cii proportion 220 42, jeffreys
cii proportion 115 30, jeffreys

/* (2) Using The Variables */
/* Fake Data */
clear
input total_n str10 occupation q1
115 "teachers" 30
220 "lawyers" 42
15  "doctors" 10
end
gen q0 = total_n - q1
drop total_n
reshape long q, i(occupation) j(any_quals)
expand q
drop q
sort occupation any_quals
sencode occupation, replace
tab occupation any_quals, row chi2
bys occupation: ci proportion any_quals, jeffreys

/* (3) Using a probit/logit: helpful for comparing groups */
quietly probit any_quals i.occupation
margins occupation
margins ar.occupation
margins r.occupation
</code>
Here I used the Jeffreys binomial confidence intervals since the doctors group has such a small sample size, but you could have also used Wilson or Agresti–Coull intervals. You can read more about these in the Stata manuals. Examples 6 and 7 go into this a bit and provide a reference.
The probit/logit CIs won't exactly match the binomial CIs, but they will allow you to test a richer set of hypotheses.


Check if jQuery object has html element in it

Question: Maybe I miss something but anywhere I read it is suggested that if I want to check whether a jQuery constructor returns a jQuery object is done by:
if(jQuery('.something').length){...}
but how would I validate if it is an html element in the jQuery object that it returns?
what I mean is that this also returns true:
if(jQuery(44551).length){...}
although it returns jQuery object it doesn't have html element in it.
Comment: jQuery's selectors return only HTML elements.
Comment: but what if I provide a number to the jQuery constructor, it won't return html element.
Answer: You could use is() to check if the collection contains an element matching a certain selector
var someelement = $(....); // unknown

if ( someelement.is('.something') ) {...

Check the current matched set of elements against a selector, element,
  or jQuery object and return true if at least one of these elements
  matches the given arguments.
Comment: ok that solves my problem. `$('.never-mind').is('.never-mind')` returns true (of course after validating that .never-mind exists), and `$(555).is(555)` returns false. thank you mate
Answer: To check if there are html elements inside a jQuery element, then do:
if ( $('.el').html().length ) { ...

Comment: if I provide a number to the jQuery selector your code throws an error, I could wrap it in a try-catch statement, but @adeneo's solution is simpler. thanks though.


Spring/Hibernate fails to initialize the EntityManager when using mix of annotations and hbm for entities

Question: I have a Spring/Hibernate project with entities defined using both hbm's and annotations.
When I am trying to deploy the project I get the following error message:
Caused by: org.hibernate.MappingException: Following super classes referenced in extends not found: hibernate.examples.model.Task
    at org.hibernate.cfg.Configuration.processExtendsQueue(Configuration.java:1768) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1690) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1426) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1846) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425) ~[hibernate-core-4.3.11.Final.jar:4.3.11.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849) ~[hibernate-entitymanager-4.3.11.Final.jar:4.3.11.Final]
    ....................

The reason I have to keep using both is because some of the code is legacy and I cannot touch that at the moment. And we have to start using the annotations for creating any new entities moving forward.
This is how I am registering both kinds of mappings into the configuration:
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
        final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource());
        em.setPackagesToScan("hibernate.examples.model", "models");
        em.setMappingResources("Task.hbm.xml");
        em.setMappingResources("HealthTask.hbm.xml");

        final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        em.setJpaProperties(hibernateProperties());
        return em;
    }

The setPackagesToScan method scans for all the entities marked by annotations and setMappingResources is supposed to take care of the hbm files.
When I comment out the em.setMappingResources..... then the project gets deployed without any issues.
Also, the weird part to note is that when I run it as a standalone application i.e. using public static void main(String[] args) I do not have any issues working with both kinds of mapping. All the entities get registered and schema gets created.
Here is how I run the project:
public class ConceptRunner {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();

        ctx.register(HibernateConfiguration.class);
        ctx.refresh();

        System.exit(0);

    }

}

But as soon as I deploy the project, it fails to register the hbm files.
Here are my hbm files:
Task.hbm.xml
<hibernate-mapping>
    <class name="hibernate.examples.model.Task" table="TASKS" abstract="true">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0"/>
            <generator class="identity"/>
        </id>
        <discriminator column="TYPE" type="string"/>
        <property name="type" type="java.lang.String" insert="false" update="false">
            <column name="TYPE" length="10"/>
        </property>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="50"/>
        </property>
        <property name="description" type="java.lang.String">
            <column name="DESCRIPTION" length="250"/>
        </property>
    </class>
</hibernate-mapping>

HealthTask.hbm.xml
<hibernate-mapping>
    <subclass name="hibernate.examples.model.HealthTask"
              extends="hibernate.examples.model.Task" discriminator-value="HEALTH">
        <property name="requestServed" type="java.lang.Long">
            <column name="REQUEST_SERVED"/>
        </property>
        <property name="requestFailed" type="java.lang.Long">
            <column name="REQUEST_FAILED"/>
        </property>
        <property name="totalRequest" type="java.lang.Long">
            <column name="TOTAL_REQUEST"/>
        </property>
    </subclass>
</hibernate-mapping>

Please let me know if there is any other information that you would like from me..
Comment: You should call `setMappingResources` once. It is a `set` not an `add`. In short the only one registered is the `HelathTask.hbm.xml` because it overrides the previously set values... Instead do `setMappingResources("Task.hbm.xml", "HealthTask.hbm.xml");`
Comment: post your project structure for once
Comment: @M.Deinum I cant thank you enough. It had me stuck for the longest time. Appreciate it.
Comment: Stack Overflow a question and answer site, not a question and solution in question site. Thus write an answer, instead of writing the solution into the question.
Comment: @M.Deinum If you post an answer, I will remove mine and accept yours.
Answer: @Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan("hibernate.examples.model", "models");
    em.setMappingResources("Task.hbm.xml");
    em.setMappingResources("HealthTask.hbm.xml");

    final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(hibernateProperties());
    return em;
}

As the setMappingResources is a setter each call to it will replace the current set of resources. As you are calling it twice in your code only the last one will remain (the HealthTask.hbm.xml and the Task.hbm.xml will be ignored).
If you take a look at the setMappingResources of the LocalContainerEntityManagerFactoryBean you will notice it takes a String... as an argument (a varargs argument to be exact).
So instead of calling it twice call it once with 2 arguments.
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan("hibernate.examples.model", "models");
    em.setMappingResources("Task.hbm.xml", "HealthTask.hbm.xml");

    final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(hibernateProperties());
    return em;
}

Comment: Thanks a lot again.


Case createdon is being populated by the related Accounts overriddencreatedon date? - Dynamics 365

Question: When users are creating cases for an account, the cases created have a createdon date that matches the related accounts overriddencreatedon field?
Has anyone ever seen this behavior or have a solution to this problem?
I can band-aid the issue by removing the related accounts overriddencreatedon value but I would like to understand why this is happening.
Thank you.
Comment: Are you sure you don't have any plugin which was developed for some data migration still enabled?
Answer: Update:
Posting in case anyone else experiences similar issues. The issue was caused by data mappings that were defined under an entities 1:N relationship.
Not sure how the mappings got there. Maybe due to a migration like Arun stated above.


Only one Title name displayed on multiple Receipt Items of Receipt Card

Question: I am working on the bot framework technology in one of my project and I want to display the Receipt Card following the below link https://docs.botframework.com/en-us/csharp/builder/sdkreference/attachments.html for adding receipt card in my project.
This is my code about Receipt Card.
<code> #region Receipt Card
            ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
            Activity replyToConversation = activity.CreateReply("Welcome to **** Hotels.");
            replyToConversation.Recipient = activity.From;
            replyToConversation.Type = "message";
            replyToConversation.Attachments = new List<Attachment>();
            //List<CardImage> cardImages = new List<CardImage>();
            //cardImages.Add(new CardImage(url: "http://cache.*****.com/propertyimages/h/hydcy/hydcy_main02.jpg",alt: "The **** Hyderabad welcomes guests to the heart of the city centre with an array of amenities and comfortable, sophisticated lodging."));
            List<CardAction> cardButtons = new List<CardAction>();
            CardAction plButton = new CardAction()
            {
                Value = "http://www.*****.com/hotels/travel/hydcy-courtyard-hyderabad/",
                Type = "openUrl",
                Title = "Confirmed"
            };
            cardButtons.Add(plButton);
            ReceiptItem lineItem1 = new ReceiptItem()
            {
                Title = "***** Hyderabad",
                Subtitle = "*****, Hyderabad, IN 500 080",
                Text= "The **** Hyderabad welcomes guests to the heart of the city centre with an array of amenities and comfortable, sophisticated lodging."
            };
            ReceiptItem lineItem2 = new ReceiptItem()
            {
                Title="Executive Deluxe,Guest Room",
                Image = new CardImage(url: "http://cache.****.com/propertyimages/h/hydcy/hydcy_main02.jpg"),
                Price = "7000.25",
                Quantity = "1",
                Tap = null
            };

            List<ReceiptItem> receiptList = new List<ReceiptItem>();
            receiptList.Add(lineItem1);
            receiptList.Add(lineItem2);

            ReceiptCard plCard = new ReceiptCard()
            {
                Title = "**** Hyderabad Hotel Reservation Confirmed",
                Buttons = cardButtons,
                Items = receiptList,
                Tax = "27.52",
                Total = "7027.77"
            };
            Attachment plAttachment = plCard.ToAttachment();
            replyToConversation.Attachments.Add(plAttachment);
            var reply = await connector.Conversations.SendToConversationAsync(replyToConversation);
            #endregion
</code>
In the above I have added the two Receipt Item's with different Titles but at the end it was displayed only one title name on two Receipt Item's in my Receipt Card like this below figure.

Please tell me, how to resolve the above issue.
I think there may be a bug in Bot Framework Channel Emulator.
-Kishore.
Comment: What channel are you using?
Comment: I am not using any channel, just i have tested my bot in latest bot emulator.
Comment: Looks like a bug.  Investigating
Answer: Thank you for identifying a bug in the emulator.  It has been fixed and should be published shortly.