PostgreSQL Array inside a JSON object

Question: Im trying to build a custom json, from two tables with left join on a PostgreSQL function, but cant it working.
Table Structure:
post
 id | title | description

postPhoto
 id | postId (FK) | name

json example:
{
    postId: 1,
    title: ''
    description: '',
    postPhotos: [
        {id: 1, name: 'photo1.png'},
        {id: 1, name: 'photo2.png'},
    ]
}

SQL Function:
$BODY$DECLARE
    success boolean;
    msg text;
    var_most_recent json;
BEGIN

SELECT to_json(array_agg(t)) INTO var_most_recent FROM (

    SELECT *
        ( SELECT to_json(array_agg(t)) FROM (
                SELECT * FROM postPhoto AS PP WHERE post.id = PP."postId"
            )t )
    FROM post
    ORDER BY id DESC LIMIT 10

)t;

success = TRUE; msg = 'Successfully Returned Post data';
RETURN (SELECT json_build_object(
    'success', success,
    'msg', msg,
    'body', json_build_object(
        'mostRecent', var_most_recent
    )
));

END;$BODY$

Answer: I think you are missing the json_agg aggregate function. Here's how I would do it:
SELECT json_agg(p)
FROM
   (SELECT
        json_build_object(
            'postId', post.id,
            'title', post.title,
            'description', post.description,
            'postPhotos',
                (SELECT json_agg(json_build_object('id',id,'name',name))
                 FROM postPhoto WHERE postId=post.id)
        ) AS p
    FROM post
    ORDER BY post.id
    LIMIT 10) as t
WHERE json_array_length(p->'postPhotos')>1;

Comment: This works but i need to wrap multiple posts in an array, cause i dont have a where i have a LIMIT by 10 so the json would look like this:
http://pastebin.com/W3MSm8fh
Comment: No problem, we can just wrap it in another `SELECT` query, see my updated answer.
Comment: Can you help me out to select post where postphoto is not null
Comment: @JasminMiftari What can be null exactly?
Comment: So for the moment, i select all posts with their postPhotos, but i want to select all posts where postPhotos count > 1.
Select post which countain postPhotos ( or contain rows in postPhoto )
Comment: @JasminMiftari I added a `WHERE` clause in the outer query to filter out post that have 0 or 1 photos.

PostgreSQL Array inside a JSON object


Uncaught TypeError: $(...).DataTable is not a function when converting table to datatable

Question: i have a table which is created from CSV file using AJAX , so  i just wanted to convert the table to datatable , with multiple column filter or even single filter is fine . The conversion of CSV to HTML table is working fine but it is not able to convert Table to Datatable .
Can anyone help me . Below is my code .
 Last refresh :

 <?php echo date('H:i:s');?>

and i have included javasript and CSS for datatable on top :

 <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">

Comment: Most common reason for such an error is loading another version of jquery.js further down the page which wipes out plugin methods attached to the first
Comment: but still my Table is not converted to Datatable . It just appears to be Normal Table @charlietfl
Comment: Did you resolve the error? Note you should initialize the plugin within the ajax success after you populate it
Answer: You initialize the table before the ajax call returns the answer from the server.
Since you create the HTML inside your success block,
you try to initialize an element that's not exists in your DOM.
Move
$('#myTable').DataTable();

into your success block
Comment: While this is true it doesn't explain the error thrown
Comment: Okay now error is gone , but table is not getting converted to Datatable
Comment: @GowriLakshmi can you give more details or edit your post with the updated code?


Concatenar registros SQL Server

Question: Estou com um problema em uma query, onde preciso concatenar registros de uma tabela. Preciso que o select pegue o FormID e concatene os registros de AcaoID somente se Permitir for 1.
Query:
Declare @Result varchar(MAX)
Declare @FormID varchar(MAX)
Set @Result = ''
Select @FormID = FormID, @Result = COALESCE(@Result + AcaoID + '; ', '') FROM PermissaoAcoesForms
where GrupoUsuario = '{0}' AND FormID = '{1}' AND Permitir = '1'
if  @Result <> '' Begin
Set @Result = SUBSTRING(@Result, 1, LEN(@Result) - 1) end
Select @FormID as FormID, @Result as AcaoID

O problema é que quando eu rodo a query, caso FormID exista e Permitir seja igual a 0, ele não retorna nada.
Nesse caso eu preciso retornar FormID independente do valor de Permitir, mas caso Permitir seja 1 ele tem que concatenar todos os registros onde Permitir seja 1.
Comment: Esses três campos são da mesma tabela? Se sim, eles já não retornam na mesma linha de consulta?
Comment: Sim sim, são da mesma tabela. Eu preciso retornar **`FormID`** independente do valor de **`Permitir`**, na minha query só retornar **`FormID`** caso **`Permitir`** seja 1
Comment: mas você esta declarando isso no where: "AND Permitir" = '1', se o valor de permitir não importa, basta tirar ele da cláusula
Comment: É que meu frontend exibe o resultado somente dos ativos (quando **`Permitir`** é igual a 1)
Answer: Quando você quer fazer condições no SQL utilize CASE
Select CASE WHEN Permitir = '1' THEN CONCAT(FormID, AcaoID) ELSE FormID END
FROM PermissaoAcoesForms

É isto que você precisa?
Comment: Mais ou menos isso, preciso concatenar os valores, Ex:
FormID = CarteiraCompras AcaoID = Imprimir; Visualizar

Concatenar registros SQL Server


How do I print an exposed filter block in a template file?

Question: I have a view with an exposed taxonomy filter. I configured it to be displayed as a separate block so that I can print it another twig template. I tried this.
/**
 * Implements hook_preprocess_block() for block.html.twig.
 */
 function themename_preprocess_block(array &$variables) {
   $variables['featured'] = views_embed_view('view_name', 'contextual_filter_block_machine_name');
 }

Then I used {{ featured }} in the  block template, but it doesn't work.
Is there another way to do this?
Comment: Did you rename `themename` to be your theme's machine name? Also, can you run a `debug(json_encode(views_embed_view('view_name', 'contextual_filter_block_machine_name')))` and then check the "Recent Log Reports" page?
Answer: I used another approach to solve the problem. I overrode the views template to print the exposed filter where I wanted. You can get it as
{{ exposed}}

in the twig template.
Answer: I almost always use the twig_tweak module, there is 3 ways to render a block.
You can see the doc here Twig tweak Block render, you should probably use
drush ev "print_r(array_keys(\Drupal::service('plugin.manager.block')->getDefinitions()));"

find your block in the list and then use
{{ drupal_block('your_block_id') }}


Example of a variation of Hodge structure such that the gradation does not vary holomorphically

Question: The motivation for considering the Hodge filtration as opposed to just the grading is supposed to be that the filtration varies holomorphically in a family, whereas the grading does not always.
Can someone provide an example of a smooth morphism $f \colon X \to S$ such that the fibers are smooth projective complex manifolds where the grading on $ R^k f_* \mathbb{Z}$ does not vary holomorphically over $S$? Ideally, the example would be a family of abelian varieties.
Answer: Almost any interesting example that you can write down will satisfy this property.
E.g. consider a non-trivial family of elliptic curves over some base $S$
(the family $y^2 = x(x-1)(x-\lambda)$ over $\mathbb P^1\setminus \{0,1,\infty\}$
will do).
Then you get a two-dimensional variation of Hodge structure $\mathcal V$ which is a rank two
holomorphic bundle over $S$.  The first step in the Hodge filtration gives a rank one subbundle $\mathcal F \subset \mathcal V$.    This interpolates the $(1,0)$
part of the grading.  It is spanned by the holomorphic differential $\omega := dx/2y$.
If we restrict to a small open subset $U$ of $S$, over which we can trivialize the family of elliptic curves in the smooth category, then we can choose a constant basis for the homology of the family, and integrate $dx/2y$ over it,
to get a pair of functions $\omega_1$ and $\omega_2$, which are the periods of the
elliptic curves in the family; they vary holomorphically, which reflects the
fact that $\mathcal F$ is a holomorphic bundle.   But if we integrate a basis
for the $(0,1)$ part of the grading over this homology basis, we get the pair of anti-holomorphic functions $\overline{\omega}_1, \overline{\omega}_2$.  If the family of elliptic curves is non-trivial, then these will really form non-constant holomorphic functions on $U$, implying that the $(0,1)$ part of the grading cannot be interpolated holomorphically.
Summary: The basic point is that the $(q,p)$ part of the grading is obtained from the  $(p,q)$ part by applying complex conjugation, and this is not a process that will preserve the holomorphicity of a bundle in general.  I.e. the Hodge filtration varies holomorphically but the conjugate filtration $\overline{F}$ does not, and hence neither does the intersection $F^p\cap
\overline{F}^q$, in general.


An Interesting Question about Pythagorean Triples

Question: I have recently thought about a interesting question about Pythagorean Triples.

Consider such a right-angled trapezium formed by 3 right-angled triangle. Determine does it exist integral solutions for lengths of sides $AB, BC, CD, DE, EA, AC$ and $CE$.

Here's my ideas.

I know that Pythagorean Triple can be generated by substituting integer into $x^2-y^2, 2xy, x^2+y^2.$
So let $AB=m^2-n^2$, $BC=2mn$, $CD=2pq$, $DE=p^2-q^2$, $AC=m^2+n^2=u^2-v^2$, $CE=p^2+q^2=2uv$ and $ AE=u^2+v^2.$ To answer the question, I have to show that if $m^2+n^2=u^2-v^2$ and $p^2+q^2=2uv$ have integral solution(*). But I don't know how to show this.
Can anyone tell me if I'm right about (*)? If I'm right, how to show it?
If I'm wrong, how to solve the question?
Thank you.
Sorry, I'm a poor question-tagger.
Comment: What if there's no similar triangles?
Answer: Note that triangles ABC and CDE must be similar if BCD is to be a straight line, so both must be built from integer multiples of the same primitive pythagorean triple T= {a,b,c} with hypotenuse c.
Suppose ABC is $pT$ and CDE is $qT$ then $AC=pc$ and $CE=qc$ and $AE^2=p^2c^2+q^2c^2$ so that $AE$ is divisible by $c$ and equals $rc$.
You can build your trapezium from any pair of pythagorean triples (not necessarily primitive)
T={$a,b,c$} and U= {$p,q,r$}
with ABC = {$pa,pb,pc$}, CDE = {$qb,qa,qc$}, ACE = {$pc,qc,rc$}.
And this is essentially the only way of doing it.
Answer: You have a lots of solutions, just take any triples (for example 3,4,5).
Then multiply by the right amount based on another triple (for example 3,4,5).
BC=9, AB=12, AC=15
DE=12, CD=16, CD=20
Then AE = 25
So for any pythagorean triples (a,b,c) (d,e,f) (g,h,i),
a solution is (agf,bgf,cgf) (dhc,ehc,fhc) and then (icf) for the last length.
Of course, you can divide the obtained solution by the gcd of all lengths...


Como carregar um valor no select

Question:

$scope.init = function() {
$scope.modelo = {};
$scope.marca = {};
$scope.modelo = {};
$scope.modelos = [];
$scope.marcas = [];
$scope.anos = [];
$scope.precocarro=[];

$http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas').success(function(data) {
  $scope.marcas = data;
});
  };
  $scope.carregarModelo = function() {
$http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos').success(function(data) {

  $scope.modelos = data.modelos;
})
  };

  $scope.carregarAno = function() {
$http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo + '/anos').success(function(data) {
  $scope.anos = data;
})
  };

  $scope.consultarPreco = function(){
  var url = 'https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo + '/anos/' + $scope.anos.codigo;
  console.log(url);

  $http.get(url)
  .success(function (data){
      $scope.precocarro = data;
  })
  .error(function (data, status, headers, config) {
      alert('Desculpe, serviço indisponível. Tente novamente mais tarde.')
  });

}
  $scope.init();

        Marca
        <select id="teste" class="customSel" ng-options="marca as marca.nome for marca in marcas" ng-model="marca" ng-change="carregarModelo()">
    </select>

        Modelo
         <select id="modelo" class="customSel" ng-model="modelo" ng-change="carregarAno()" >
        <option ng-repeat="x in modelos" value="{{ x.codigo }}">{{ x.nome }}</option>
    </select>

        Ano
         <select id="modelo" class="customSel" >
        <option value="0" selected>Selecione</option>
        <option ng-repeat="x in anos" value="{{ x.codigo }}">{{ x.nome }}</option>
    </select>

    <button class="button button-block button-positive" ng-click="consultarPreco(modelo)">Consultar</button>

Answer: Você pode fazer uso de chained promises:
$http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas')
  .then(function(data) {
      $scope.marcas = data;
      return $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/'+marca.codigo+'/modelos');
  }).then(function (data) {
       $scope.modelo = data;
       return $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/'+marca.codigo+'/modelos/'+ano.codigo+'/anos');
  }).then(function (data) {
       $scope.ano = data;
  });

Comment: Não funcionou, ele não carregou as listas. Será que é por que falta o $scope.carregarModelo ?
Answer: Na sua solução seria assim:

var app = angular.module("app", []);
app.controller("ctrl", ["$scope", "$http", function($scope, $http) {
  $scope.init = function() {
    $scope.modelo = {};
    $scope.marca = {};
    $scope.modelo = {};
    $scope.modelos = [];
    $scope.marcas = [];
    $scope.anos = [];
    $scope.preco = {};
    $scope.ano = {};
    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas').success(function(data) {
      $scope.marcas = data;
    });
  };
  $scope.carregarModelo = function() {
    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos').success(function(data) {

      $scope.modelos = data.modelos;
    })
  };

  $scope.carregarAno = function() {
    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo + '/anos').success(function(data) {
      $scope.anos = data;
    })
  };
  $scope.consultaPreco = function()
  {

    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo + '/anos/' + $scope.ano).success(function(data){
    $scope.preco = data;
    });
  }
  $scope.init();
}]);

            Marca
            <select id="teste" class="customSel" ng-options="marca as marca.nome for marca in marcas" ng-model="marca" ng-change="carregarModelo()">
        </select>

            Modelo
             <select id="modelo" class="customSel" ng-model="modelo" ng-change="carregarAno()" >
            <option ng-repeat="x in modelos" value="{{ x.codigo }}">{{ x.nome }}</option>
        </select>

            Ano
             <select id="ano" ng-model="ano" class="customSel" ng-change="consultaPreco()" >
            <option value="0" selected>Selecione</option>
            <option ng-repeat="x in anos" value="{{ x.codigo }}">{{ x.nome }}</option>
        </select>

Valor: {{preco.Valor}}

Marca: {{preco.Marca}}

Modelo: {{preco.Modelo}}

Ano Modelo: {{preco.AnoModelo}}

Combustivel: {{preco.Combustivel}}

Codigo Fipe: {{preco.CodigoFipe}}

Mês Referencia: {{preco.MesReferencia}}

Tipo Veiculo: {{preco.TipoVeiculo}}

Sigla Combustivel: {{preco.SiglaCombustivel}}

mas, eu faria assim:

var app = angular.module("app", []);
app.controller("ctrl", ["$scope", "$http", function($scope, $http) {
  $scope.init = function() {

    $scope.modelo = {};
    $scope.marca = {};
    $scope.ano = {};
    $scope.preco = {};

    $scope.modelos = [];
    $scope.marcas = [];
    $scope.anos = [];

    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas').success(function(data) {
      $scope.marcas = data;
    });
  };
  $scope.carregarModelo = function() {
    if ($scope.marca == null) {
      $scope.modelos = [];
      $scope.anos = [];
      $scope.preco = {};
    } else {
      $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos').success(function(data) {
        $scope.modelos = data.modelos;
      });
    }
  };

  $scope.carregarAno = function() {
    if ($scope.modelo == null) {
      $scope.anos = [];
      $scope.preco = {};
    } else {
      $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo.codigo + '/anos').success(function(data) {
        $scope.anos = data;
      });
    }
  };

  $scope.consultaPreco = function()
  {
    if ($scope.ano == null)
    {
    $scope.anos = [];
      $scope.preco = {};
    }
    else
    {
    $http.get('https://fipe-parallelum.rhcloud.com/api/v1/carros/marcas/' + $scope.marca.codigo + '/modelos/' + $scope.modelo.codigo + '/anos/' + $scope.ano.codigo).success(function(data){
    $scope.preco = data;
    });
    }
  }

  $scope.init();
}]);

    Marca
    <select id="teste" ng-disabled="marcas.length <= 0" ng-options="ma.nome for ma in marcas" ng-model="marca" ng-change="carregarModelo()">
        <option value="">-- Escolha a Marca --</option>
    </select>

    Modelo
    <select id="modelo" ng-disabled="modelos.length <= 0" ng-options="mo.nome for mo in modelos" ng-model="modelo" ng-change="carregarAno()">
      <option value="">-- Escolha a Modelo --</option>
    </select>

    Ano
    <select id="modelo" ng-disabled="anos.length <= 0" ng-change="consultaPreco()" ng-options="an.nome for an in anos" ng-model="ano">
    <option value="">-- Escolha a Ano --</option>
 </select>

Valor: {{preco.Valor}}

Marca: {{preco.Marca}}

Modelo: {{preco.Modelo}}

Ano Modelo: {{preco.AnoModelo}}

Combustivel: {{preco.Combustivel}}

Codigo Fipe: {{preco.CodigoFipe}}

Mês Referencia: {{preco.MesReferencia}}

Tipo Veiculo: {{preco.TipoVeiculo}}

Sigla Combustivel: {{preco.SiglaCombustivel}}

Comment: Para consultar o Preço Final, ficaria assim ? Editei a pergunta. Ao executar o campo anos, no consultarPreco, aparece undefined.
Comment: @Tommz feito a edição com a consulta de preço, se preferir use a segunda opção !
Comment: Muito obrigado pela ajuda @Virgili Novic.
Comment: @Tommz se ele foi util assinale como resposta da pergunta
Comment: Feito @Virgili Novic

Como carregar um valor no select


Drop down menus in tabs

Question: Is possible to create a dropdown menu in tabs like the ones in the configuration of apex:

Answer: Yes, see this plug-in component
Comment: i'm tring to put the menus attached to existing page tabs but is giving erros like this:
`SELECT /* Page Tabs */
id ,  pid, text, url,  display_seq
FROM   SURV_MENU
WHERE  application_id       = :APP_ID
AND    list_name = :LIST_NAME
AND    auth_condition_check
      ( p_condition_type        => condition_type
      , p_condition_expression1 => condition_expression1
      , p_condition_expression2 => condition_expression2
      , p_authorization_scheme  => authorization_scheme
      ) = 0`

    ORA-00907: missing right parenthesis
Comment: Sorry but I have no idea why.
Comment: And you know if it is possible to put the menu attached to bar of page tabs?
Comment: You can put it where you want on the page by changing the page template.
Comment: Can you help with that, i'm in standard tab attributes but i dont what to change
Comment: You can't use this solution as part of standard Apex tabs; you can use this solution **instead of** Apex tabs.
Comment: So i have to remove the Apex bar from template?
Comment: You could do that yes, and put a region position e.g. #REGION_POSITION_01# in that place, then assign your new menu region to that position.
Comment: do you know any manual too edit templates i'm having some problems

Drop down menus in tabs


A Rank comparison test?

Question: Is there a test that one can use to perform rank comparison tests.
In other words if I have 2 variables (say income in all 10 regions of country X; and, income in all 10 regions of country Y) and I want to know if the ranking pattern in one variable is similar to that of the other.
Comment: Please tell us what a "ranking pattern" is and how we might possibly compare regions between two different countries with it!
Comment: Please register &/or merge your accounts (you can find
information on how to do this in the **My Account**
section of our [help]), then you will be able to
edit & comment on your own question.
Answer: What comes to mind is Spearman rank correlation analysis, which will generate income ranks within each country, and then determine if the ranks are associated (correlated).  The default test typically determines if correlation, $r_S$, is equal to zero (null hypothesis) or not equal to zero (alternative hypothesis).  Recall, correlation $r_S$ has range [-1,1] so the association between income across countries can be positive, $r_S>0$, or negative, $r_S<0$.  For the computational run, just specify the two variables to use and run Spearman with the original income values, the software will automatically do the within-country ranking internally.

A Rank comparison test?


How thread lock works when modifying an object item in a thread safe object collection through reference

Question: I've a thread safe object  collection, for e.g c#  MemoryCache. As we know, the operations like adding, updating and removing item in this collection is safe. But if I update properties of an object item in the collection through reference , firstly, would it be thread safe? how the synchronization works? would it be locked each line of property update?
<code>class MyClass
{
     public int Val1 { get; set; }
     public int Val2 { get; set; }
}

class Program
{

    public static MemoryCache MyCache = new MemoryCache("test");

    static void Main(string[] args)
    {

        MyCache.Add("1", new MyClass() {Val1 = 0, Val2 = 0}, new CacheItemPolicy());

        new Thread(() => {

            MyClass item = (MyClass)MyCache["1"];
            for (int i = 0; i < 100000; i++)
            {
                item.Val1 =  item.Val1 + i;
            }

        }).Start();

        new Thread(() =>
        {
            MyClass item = (MyClass)MyCache["1"];
            for (int i = 100000; i < 200000; i++)
            {
                item.Val1 =  item.Val1 + i;
            }
        }).Start();
</code>
any advice is really appreciated.
Comment: @SriramSakthivel He states that he did his research, found out that it wasn't safe, assumed it was safe despite being told that it wasn't, asked again, and was told what he had already found before, that it's not safe.
Comment: You already have the code to test it.  What happened when you ran it?
Comment: The result looks all thread safe. But I read in few blogs it is not, so just want to check more comments.
Comment: So you knew the answer to your question before you asked it?  Then why did you bother asking the question if you already knew the answer?
Answer:
But if I update properties of an object item in the collection through
  reference , firstly, would it be thread safe?

No.

how the synchronization works?

There will be no synchronization write reading/writing the property.

would it be locked each line of property update?

No.
Comment: @JustinMathew How were you validating the result?
Comment: Thanks dugas, but when I ran the test code (above), it gives a thread safe result. How that would be?
Comment: There are several reasons you could have appeared to get a correct result (for example a single core cpu, cpu architecture,  memory model, etc...). Your example is absolutely not thread safe.
Comment: @Servy - I'm not sure that my test is proper or not, what I did, I've created three threads to do a sum of one property (Val1) and get the right sum after execution. Could you tell me ? how I can prove it's not thread safe.


How to pause rxjava Observable.interval when underlying activity pauses

Question: Im using MVVM architecture, my data layer / repositories are using RxJava but view model to view layer is using LiveData.
In my view model, I poll server using rxjava Observable.interval.
Currently my issue is that how to pause the polling when underlying view (fragment) goes to paused state?
Would it make things easier if I remove the rxjava to liveData conversion and observe rxjava directly on view?
public class MyViewModel extends ViewModel {

    private final CompositeDisposable disposables = new CompositeDisposable();
    private final MediatorLiveData<Resource<DataItem>> dataItems = new MediatorLiveData<>();

    MyViewModel(...) {
        disposables.add(Observable.interval(0, 10, TimeUnit.SECONDS) // How to pause this?
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(n -> loadData())
                .subscribe());
    }

    void loadData() {
        disposables.add(dataRepository.getData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(__ -> dataItems.setValue(Resource.loading()))
                .subscribe(dataResp -> dataItems.setValue(Resource.success(dataResp)),
                        throwable -> dataItems.setValue(Resource.error(throwable))));
    }

    // This is observed by view
    LiveData<Resource<DataItem>> getDataItems() {
        return dataItems;
    }
}

Answer: You can just call resume/stop from your controller, from your viewmodel change to :
...
private final Disposable poolingDisposable;
...

MyViewModel(...) {
    resumePooling()
}

public void resumePooling(){
    if(poolingDisposable == null){
        poolingDisposable = Observable.interval(0, 10, TimeUnit.SECONDS)
           .observeOn(AndroidSchedulers.mainThread())
           .doOnNext(n -> loadData())
           .subscribe();

        disposables.add(poolingDisposable)
    }
}

public void stopPooling(){
    if(poolingDisposable != null){
        poolingDisposable.dispose();
        poolingDisposable = null
    }
}

@Override
protected void onCleared(){
    disposables.dispose()
}

from your controller (if an activity or fragment)
@Override
public void onResume(){
    super.onResume();
    viewModel.resumePooling();
}

@Override
public void onPause(){
    super.onPause();
    viewModel.stopPooling();
}


Audio classification with neural networks

Question: I would like to classify bird species from audio recordings. To do this, I am calculating a number of features in a frequency spectrum: I take certain block size (say, 2048 samples) and compute mel spectrum coefficients, spectral rolloff, LSF coefficients, spectral flux etc. - they make together a very good description of the sound.
A bird call typically lasts a few seconds, meaning it consists (with 16 kHz sampling) of easily 30000 samples. Can you provide some hints on what architecture I could use to tackle the problem?
I was thinking of the following:

Calculate features for the 2048 block size.
Calculate next block with half overlap (1024).
Repeat the process until I have captured 2 seconds of features. If in a single block I get 50 features, then the complete vector would have roughly 1500 features (because of the 30k samples in a typical call).
The 1500 features will constitute my input to the ANN. It covers 2 seconds of a recording. With half of overlap I would then take next 2 seconds and repeat the process.

I was then thinking of ANN with 1-2 hidden layers, likely much smaller than the input vector. What do you think?
As an alternative I am considering making a spectrogram and working with CNNs.
Comment: I think [LSTMs](https://en.wikipedia.org/wiki/Long_short-term_memory) are the way too go. Secondly, you say 'compute spectrum coefficients, spectral rolloff, etc.' ( I have no clue what some of those things are'. But why do you NEED to compute these? You can let the neural network figure that out through backpropagation.

With LSTM, you can sample `x` samples every time you input. Just check which `x` works best for you.
Comment: LSTM could be a way to go if I were using raw data as you are suggesting, as then it would be a proper time series. Why not using raw data then? Because then I would have huge input vector which would make my network very expensive to train. Besides, one of the points of using ANN is that they can create features for us. However, in this case I am able to build features myself.
Answer: In a similar project for auto-tagging of audio files I used spectrograms and worked with CNNs as, according to my research, these choices resulted in many  state of the art models.
I have uploaded my code on GitHub accompanied by a detailed description of the whole process, if it helps.


Working with data from a form

Question: I am trying to create a module with a simple form. The form allows the user to enter their address, from there I need to take the user's address, make a geocoding request, then send the data to another api, and then I need to display the data from the api request.
The part I am having issues with is taking the submitted address so I can do the requests with it. How do I take the data from the form so I can use it? I do not need or want to save the data into my database.
Thanks in advance.
Answer: In the form submit handler, look in the form state. The values array will contain submitted values.
So for a form element, 'foo', generated like this:
$form['foo'] = [
  '#type' => 'textfield',
  '#title' => t('Foo'),
];

You get the value like this:
function MYMODULE_form_submit($form, &$form_state) {
  $value_of_foo_field = $form_state['values']['foo'];
}

Working with data from a form


Collinearity in Classification Model for Churn Prediction

Question: I'm working on evaluating various classification algorithms to help predict customer churn (or at least ID interesting features to use in later strategy).
The goal is to identify accounts who are at risk for not buying again. As a first step, I took:
<code>a) all customers who were active between 250 and 120 days ago (somewhat arbitrary)
b) classified them as churned or not churned based on whether they were active in the last 110 days.
</code>
One of my features is "days since last logged in". In order to purchase, you need to log-in. But, you may log-in to do a variety of things that have nothing to do with ordering (for instance, account mgmt, download receipts, etc....).
Since there's a clear relationship between "not churned" and logging in, what are your thoughts on how valuable this feature is? So far, my arguments for including it:

It's valid and accessible real-time information. If a customer has not
  purchased in 5 months and we saw they logged in yesterday, why offer a
  discount or take action to re-engage the client?

Has anyone dealt with similar cases where the feature is somewhat dependent on the labeling criteria?
Comment: "What are your thoughts" is not a great fit for CV. Can you make your question more focused & concrete?
Comment: @gung - did you read the question? I provided a concrete use case and was looking for specific advice regarding the treatment of a potentially useful feature in a classification model. How is this a bad fit for CV?
Comment: I did read the question, & I did not downvote or vote to close. It's just the "what are your thoughts on how valuable this feature is" that is potentially problematic. You may want to edit that.
Comment: I would suggest that "collinearity" may not be the correct word to use in the title. Collinearity refers to dependence among the predictors that can degrade model fit insofar as it will inflate the standard errors of the parameter estimates. A better term might be "endogeneity" which reflects undesirable dependence between predictors and a target or dependent variable. That said, and as @Vishal notes, in this case, it's neither a theoretical nor applied issue.
Answer: It's perfectly okay to use "days since last log-in" as one of the independent variables in the churn model. This independent variable does not, in and of itself, define churn. And it's obvious that if a customer has not logged on for a long time (i.e., lagged) then she is more likely to churn in the near future.
The important distinction here is that the "days since last log-in" is extracted from a time frame that is mutually exclusive – and it precedes – the model observation window from which the outcome event (churn) is defined. Since there's no overlap between the two, "days since last log-in" is truly a leading indicator, and hence it should be okay to use this, or any other such feature, for that matter.
This is a common practice in such models that use Recency/Frequency/Monetary (RFM) variables to make a prediction.
By the way, in the past, when I built churn models (and I have built many) using such 'recency' fields, one of the issues that I ran into is the difficulty of building a strong churn model that can satisfactorily outperform a baseline churn "model" that simply ranks order customers based on recency.
If we simply rank order all customers by their recency of purchase, this "model" would be able to capture the churners in the top decile very efficiently (and parsimoniously). So the real test of the churn model is not how well it performs against a random ranking (i.e., AUC), but how well it can outperform the single-variable (recency) model.
Another important factor is the definition of churn itself. You mentioned that the choice of 250—120 days was arbitrary. However, you might want to consider defining a specific window of inactivity as churn. You can look at periods of inactivity from historical data to determine this window. For instance, you might find something like this: "95% of the customers who stayed inactive for 40 days did not make any subsequent purchase" – based on this, you may define churn as 40 consecutive days of inactivity. (The business point of view might add some more nuances/justification to this.) Once you define churn this way, you can select the historical window more systematically, instead of the arbitrary choice of 250—120 days.
Comment: Awesome feedback - thinking this over. I had the same intuition that a grid which just ranks customers by LTV and recency, is likely the measure to beat, at least in practical terms.
Comment: Glad you found it useful. Would you mind accepting my answer then?


Trazer a segunda e terceira linha de uma consulta

Question: Oracle-SQL
Tenho uma tabela que grava os registros de ponto que cada funcionário faz.
A tabela traz as seguintes informações:
(TABELA QUE ESTOU FAZENDO A CONSULTA)
Contrato | Data         | Hora
1        | 10/05/2018   | 07:00
1        | 10/05/2018   | 11:30
...

Preciso agora transpor essas colunas, trazendo essas batidas como colunas
(TABELA COMO EU QUERO):
Contrato   |   Data     | Hora 1 | Hora 2 | Hora 3 | Hora 4

Só que estou com dificuldade para trazer os registros, vejam ate onde eu fui:
(QUERY ATUAL)
select distinct ponto.contrato CONTRATO,
       ponto.datamarcacao DATA,
       (select min(ponto1.horamarcacao)
               from metaminu.rhmarcpontoreg ponto1
                      where ponto.contrato = ponto1.contrato
                      and ponto.datamarcacao = ponto1.datamarcacao) HORA1,
        (select max(ponto2.horamarcacao)
               from metaminu.rhmarcpontoreg ponto2
                      where ponto.contrato = ponto2.contrato
                      and ponto.datamarcacao = ponto2.datamarcacao) HORA2,
        (select max(ponto3.horamarcacao)
               from metaminu.rhmarcpontoreg ponto3
                     where ponto.contrato = ponto3.contrato
                     and ponto.datamarcacao = ponto3.datamarcacao) HORA3,
        (select max(ponto4.horamarcacao)
               from metaminu.rhmarcpontoreg ponto4
                    where ponto.contrato = ponto4.contrato
                    and ponto.datamarcacao = ponto4.datamarcacao) HORA4
                                from metaminu.rhmarcpontoreg ponto
                                     where ponto.contrato = 7878
                                     order by ponto.datamarcacao

Claro, mantive os "max" só como exemplo, pois os únicos campos corretos são o primeiro e último (que utilizei o min e o max). Como faria para popular os dados da 2 e 3 colunas? Alguma dica?
Obrigado.
Answer: Depende muito de como é o funcionamento do seu sistema... e se a pessoa bater o ponto mais de 4x no dia... teria ver como fica isso aí...
Seguindo o código que você já colocou de exemplo, poderia ficar assim:
select
t.contrato,
t.data,
(select min(e1.hora) from tabela e1 where e1.contrato = t.contrato and e1.data = t.data) entrada1,
(select min(s1.hora) from tabela s1 where s1.contrato = t.contrato and s1.data = t.data and s1.hora > (select min(e1.hora) from tabela e1 where e1.contrato = t.contrato and e1.data = t.data)) saida1,
(select max(s2.hora) from tabela s2 where s2.contrato = t.contrato and s2.data = t.data and s2.hora < (select max(e2.hora) from tabela e2 where e2.contrato = t.contrato and e2.data = t.data)) entrada2,
(select max(e2.hora) from tabela e2 where e2.contrato = t.contrato and e2.data = t.data) saida2
from tabela t

Coloquei no SQLFiddle

Resultado:

CONTRATO    DATA                    ENTRADA1    SAIDA1  ENTRADA2    SAIDA2
1           2018-01-01 00:00:00.0   7           12      13          17
1           2018-01-01 00:00:00.0   7           12      13          17
1           2018-01-01 00:00:00.0   7           12      13          17
1           2018-01-01 00:00:00.0   7           12      13          17
2           2018-01-01 00:00:00.0   8           12      14          18
2           2018-01-01 00:00:00.0   8           12      14          18
2           2018-01-01 00:00:00.0   8           12      14          18
2           2018-01-01 00:00:00.0   8           12      14          18
1           2018-01-02 00:00:00.0   7           11      14          18
1           2018-01-02 00:00:00.0   7           11      14          18
1           2018-01-02 00:00:00.0   7           11      14          18
1           2018-01-02 00:00:00.0   7           11      14          18

ps. Usei um campo numeric como hora, apenas de exemplo
Comment: Resolvido Rovann, obrigado.
Answer: Assumindo que voce tenha algo como:
CREATE TABLE tb_foobar
(
    id INTEGER PRIMARY KEY
);

INSERT INTO tb_foobar( id ) VALUES ( 1 );
INSERT INTO tb_foobar( id ) VALUES ( 2 );
INSERT INTO tb_foobar( id ) VALUES ( 3 );
INSERT INTO tb_foobar( id ) VALUES ( 4 );
INSERT INTO tb_foobar( id ) VALUES ( 5 );

Você pode ordernar o conteúdo da tabela de forma decrescente e recuperar apenas os dois primeiros registros:
SELECT
  *
FROM
  tb_foobar
WHERE
  ROWNUM <= 2
ORDER BY
  id DESC

Saída:
| ID |
|----|
|  5 |
|  4 |

SQLFiddle: http://sqlfiddle.com/#!4/c92f75/3
Comment: Resolvido Lacobus, obrigado.


Harmonic and geometric mean convergence to $L$ $\Rightarrow$ the series converges to $L$

Question: Given that the series $a_n > 0$, and its Harmonic mean and Geometric mean converges to L, does this indecate that $\lim_{n \to \infty}a_n = L$ ?

given $a_n$, the Harmonic mean is defined as :
  $$
\frac{n}{a_1^{-1}+a_2^{-1}+\ldots+a_n^{-1}}
$$
  and the Geometric mean is defined as :
  $$
\sqrt[n]{a_1 \cdot a_2 \cdot\ldots\cdot a_n}
$$
Answer: Hint: consider for example the sequence
$\;\displaystyle
a_n =
\begin{cases}
\frac{1}{2} \quad \text{if } n = 2^k \text{ for some } k \in \mathbb{N} \\[5px]
1 \quad \text{ otherwise}
\end{cases}
$
The harmonic and geometric means both converge to $\,L=1\,$ (why?), but $a_n$ itself is not convegent.


5 power k in binary form 1's and 0's density for large k.

Question: Suppose you have a very large k. By observation (thousands of digits), 5 power k in a binary form tends to have half 1's, and half 0's. Is this observation easy to prove?
Answer: In general, very little is known about the fraction of $1$'s in binary expansions of expressions such as $5^k$.  One would expect that these fractions should approach $1/2$ unless there's a good reason for them not to do so,
but proving anything is going to be extremely difficult.
The numbers of $0$'s and $1$'s in this case are OEIS sequences A118737 and A118738.
Comment: The OEIS sequences suggest that "tends to have" would need careful expression to allow for the apparent empirical variability
Comment: Thanks a lot Robtert for this clarifications. In fact, I have been working on an open math problem, and this part is what remains (or close to it). I have been wondering if it is an easy problem or not. Regarding what Mark Bennel is saying. The observation I have tested approaches thousands of digits. It begins with high variability between 0 and 1 and then it approaches 0.5.
Comment: Also, if you take another number that has 2 in it like 10 you will have other fractions. In case of 10, it approaches 0.35. What would be the best theory to tackle such question ?
Comment: For each integer $d\ge 1$, the $2^d$'s bit of $5^k$ is periodic in $k$ with  period $2^{d-1}$.  Except for the $2^1$'s bit which is always $0$, it seems half the values in each period are $1$ and half $0$.
Comment: After taking some of the keywords you mentionned I came across [this](http://www.ams.org/journals/proc/1978-071-01/S0002-9939-1978-0495823-5/S0002-9939-1978-0495823-5.pdf). It seems that the problem is still open with some conjectures. I will take a look at them. Thanks Robert for the help.


Kotlin return@forEach from nested forEach

Question: I want to make something like break in the nested forEach loop to filter data in my searchView (if data content contains any word in my search).
val filtered = mutableListOf<EventEntity>()

rawDataList.forEach {data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@forEach // **There is more than one label with such a name in this scope**
        }
    }
}

Does elegant solution exist in my case?
Answer: If you ever encounter this error and won't be able to fix it with built in function you can apply custom labels to lambdas by adding name@ before the block:
rawDataList.forEach outer@{data ->
    text.split(' ').forEach { word ->
        if (data.content.contains(word, ignoreCase = true)) {
            filtered.add(data)
            return@outer
        }
    }
}

Answer: Seems like the any extension method is what you're looking for. From the javadoc:
Returns true if at least one element matches the given [predicate].
val filtered = rawDataList.filter { data ->
    text.split(' ').any { data.content.contains(it, ignoreCase = true) }
}.toMutableList()

Comment: `run(filtered::add)` - none of following functions can be called with the arguments supplied
Comment: run function gets the string but I want to get EntityEvent reference, @raven


Issue when changing Locale to ARABIC in Android application

Question: My Android application supports two languages: Arabic and English. Arabic is the default language.
Now, to make Arabic as default language, i am changing my app locale to Arabic in Splash Screen. And i have maintained both English and Arabic string files for the locale change. But, when i click on some other random fragments (eg. Navigation menu item), my app static strings changes back to English locale.
I assume this is because my app default locale might have been changed to English. This issue is generated randomly, no specific scenarios are noted.
Can you suggest any solution?
Edit: I am using Shared preferences to save the language.
Answer: First step you wand to save the language in your sqlite (ex: language saved in table settings at sqlite):
<code>mDatabase = new SqliteItemDatabase(getApplicationContext());

        final List<Setting> allsettings = mDatabase.listSettings();
       String the_lang = "";
       if(position == 0)
       {
           the_lang = "en";

       }
        else if(position == 1)
        {
            the_lang = "ar";

        }
LocaleHelper.setLocale(LAngSelect.this, the_lang);// =>set language

        mDatabase.updateSettings(new Setting(allsettings.get(0).getId(),the_lang));
mDatabase.close();
</code>
Second step: to set activity right-to-left you want to add in every activity:
<code> mDatabase = new SqliteItemDatabase(this);
        final List<Setting> allsettings = mDatabase.listSettings();
        String langs = allsettings.get(0).getLang() ;
        if(langs.equals("ar")) {
            //HERE CHECK CONDITION FOR YOUR LANGUAGE if it is AR then
//change if it is english then don't
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
                //Resources res = getResources(); //resource handle

            }
        }
</code>
Comment: when you choose arabic language force the app to go to mainactivity, and in mainactivity get the language(lang) and write:          LocaleHelper.setLocale(MainActivity.this, langs);
Comment: This might be a solution, but i strictly don't want to use/rely on sqlite database. I am using Shared preference instead to save my locale language. And when the default language is set to ARABIC, i am not facing any issues related to  "right-to-left" support, as i have given value true to rtl support in Manifest file. So no need to do extra coding for that. If you have any other solution then suggest. Thanks.
Comment: Thanks for the suggestion, i am doing the same. Still it gets back to English randomly sometimes.


Do composers arrange an entire score without parallel perfect intervals or is this only when you have few voices and need them to all be independent?

Question: In harmony class one is taught not to use parallel perfect intervals as it undermines the independence of the voices. I have come to completely understand this and see why it is so important but when working with entire scores and lots of "voices" how do composers and arrangers stick by this rule?
Of course if you are doubling voices like a melody or bass part, each voice is no longer independent and this is done as a textural effect or to bring out melodic lines by doubling them at the octave etc. But are there other instances where parallel perfect intervals or other voice leading rules no longer matter and it is just about "filling out" the rest of the harmoni spectrum?
For example, I am currently working on a song where I started out with 4 part harmony and the texture is rather low. For the chorus of the song I want to include a piano part or guitar chops in the 5th octave to fill out the high end of the frequency spectrum and create more energy. I believe in the orchestra they call this "tutti" where everyone kind of joins in. How would a classical composer/ orchestrator have done this?
Would the higher piano chords (or higher woodwinds etc) be part of the voice leading in the sense that the lines would have to still have good voice leading. How is this possible? If you have 10 lines or more in the score are only some of those considered as part of the voice leading and the rest just given place in the various registers as "doubled" notes or did the classical composers treat each and every single line independently?
I find it hard to imagine how one might voice that higher piano part while still keeping all the voice leading rules in place. Maybe since the piano part is just part of the accompaniment it doesnt really matter if there are parallel 5ths or if there is parallel motion with the bass line. Or maybe not. Maybe those extra chords I want to use in the chorus still would sound much better adhering to some of the voice leading principles laid out in 4-part harmony. So which is it?
Comment: Real compositions do not need to strictly adhere to the rules of 4 part harmony.
Comment: You call it a song. Are you wanting to orchestrate it the way a classical composer might have? Anyone in particular? Have you looked at any scores? Which ones?
Comment: Old Yes, It is a song and all I am trying to figure for now is when you have a score with a whole orchestra playing with a string section, woodwinds and brass and all the other instruments, how many of those are actual independent voices and which ones arent independent? I have looked at some scores but if you have any famous ones that might be helpful then please post a reply.
Answer: A full orchestra playing usually has lots of doubling, especially a classical or early romantic symphony. Basically, a classical symphony is often written as four-part harmony, following the "rules" of the style, and the different instruments enter and exit playing one of the four parts to change the tone color.
That's over-simplified, but in many ways, orchestration is less complicated than it might seem.
One interesting example of how orchestration can sound more complex than it is would be the final "chord" of Beethoven's ninth symphony, which is simply every instrument in the orchestra playing a D.
Using a piano and a guitar complicates things, and you probably want to understand four part voice leading while also not exactly adhering to it. One way to understand voice leading for more lines is to review literature with more independent voices.
I've started using Pictures at an Exhibition as a model because there is the original piano version and it has a lot of chorale-style voice leading but with "big" chords and "newer" harmonic ideas compared to the classical period (e.g., "Promenade" ends with ii V I). Comparing the piano with the orchestration really helps me understand the relationships between the voices and how the doubles are split out.
Also keep in mind that the "rules" from harmony class are actually just practices of the specific era - they don't by themselves tell us what will always sound bad or always sound good. The mid and late romantic period saw the use of many parallel perfect intervals, but not randomly. Specific voice leading that uses the sound of parallel perfect intervals for certain effects were developed. So you can use parallel perfect intervals, but if you're not sure how or why you're using them, you might not end up with the desired sound.

If you're trying to understand how classical symphonies were composed, you would do well to go right to the source. All the scores for the European composers of the 18th and 19th centuries are available free on imslp.org. Pick your favorite work, get the score, and start analyzing. There are also piano reductions for many works that you can get to be able to more easily see the parts, lines, and harmony.
Comment: Thanks Todd, will check out that link. The way I see it is that parallel perfect intervals are fine if you dont care about independence of the lines so if you dont care about that then thats when you can use them. In an accompaniment you I don't really hear voices or different lines which is why most songwriters that actually studied counterpoint say the bassline and ,melody is where you want to stick to counterpont rules as much as possible, the rest kind of just fills in the harmonic spectrum. That is with modern music however and I was curious about orchestras to see how they did it  then.
Answer: If you are writing 4-voice harmony in the 17th century style, parallel perfect intervals are prohibited.
In other styles they are permitted, even exploited.  Just be aware of how their type of ultra-similar motion sounds.  Here is my favourite example of (largely) 4-part harmony infested with parallel 5ths.  It's lovely.  But beware of doing it by mistake in the middle of a piece otherwise in 'Bach chorale' style.

But you asked about orchestration.  If writing a section of block harmony in a style where parallels are frowned upon, the rules still apply.  But don't confuse parallel octaves within the harmonic texture with octave doubling between different instruments.  That's completely allowed.  And, as you say, when dealing with a 'song' - melody, bass line and fill-in chords - all rules are off.

"I was curious about orchestras to see how they did it then."

Shame on you!  Go to IMSLP and find out!
https://imslp.org/


When to include a random effect in a model

Question: I'm new to mixed modelling and I'm confused as to whether its appropriate to use a random effect in an analysis I'm doing. Any advice would be appreciated.
My study is testing how well a newly developed index of mammal abundance can predict the value of an established but more labour intensive index. I've been measuring these indices in multiple forest patches, with multiple plots in each forest patch.
Because I'm not directly interested in the effect of forest patches, and because my sample plots are nested within forest patches, I've been using forest patch as a random effect. However, I've got a couple of questions about this:

First, I know that random effects allow you to generalise your
results across all possible levels of the random factor, not just
the ones you sampled. But it seems to me that to make this kind of
inference your levels would have to be randomly sampled? My forest
patches were not randomly sampled, so can I still use them as a
random effect?
Second, Ive read that you can test whether it is necessary to have a
random effect by doing, e.g., a likelihood ratio test to compare
models with and without the effect.  I've done this, and it suggests
that the random effect model does not explain the data as well as a
fixed effects only model. My issue with this is that my plots are
still nested within forest patches, and so presumably not
independent. So, can I use this LRT approach to justify excluding
the random effect, or do I still need to include it to account for
nestedness? And if I do end up removing the random effect, is there
a way to verify that plots within forest patches can be considered
independent?
Comment: I think the main conceptual thing with random effects is that they should all be about the same magnitude and be exchangeable - this is what makes the inference about non-sampled random effects possible.
Also, you should be careful using LR tests for random effects as there may be considerable uncertainty regarding the variance component even if the ML/REML estimate is zero or close to zero.
Comment: Great thanks for that.So would there be some way to work out if its necessary to keep the random effect in?
Comment: From what I understand, it is best to not do LR comparisons with models fit by REML. In R's lmer, for example, you should set REML=FALSE when doing LRT. (It defaults to TRUE, which is otherwise better.)
Answer: As I understand, you have a simple nested observational design (plots within patches) and your interest is in a correlation/regression between two continuous variables (the two indices). Your sample size is m patches x n plots = N pairs of observations (or the appropriate sumatory if unbalanced). No proper randomization was involved, but maybe you can/should/want to consider that (1) the patches were "randomly" selected from all the patches of this kind or in some area, and then (2) the plots were "randomly" selected within each patch.
If you ignore the random factor Patch, you may be pseudoreplicating by considering that you have randomly selected N plots "freely", without constraining them to be (in number or type) in those (previously) selected patches.
So, your first question: yes, that is what a random factor allows. The validity of such inference depends on the validity of the assumption that haphazard selection is equivalent to random selection of patches (e.g., that your results would not be different if a different set of forest patches was selected). That puts a limit also on your space of inference: the kind of forest or geographical area up to which your results extend depends on the maximal (imaginary) population of patches from where your sample is a credible "random" sample. Maybe your observations are a "reasonable random" sample of the mammals of the forest patches in your region but would be a suspiciously aggregated sample of the mammals of the whole continent.
The second one: the test will depend on "the degree of pseudoreplication", or the evidence in your sample that plots "belong" to patches. This is, how much variation there is among patches and among plots within patches (search for intraclass correlation). In an extreme, only variation among patches is present (plots within a patch are all the same) and you have "pure pseudoreplication": your N should be the number of patches, and sampling one or many plots from each of them does not provide new information. On the other extreme, all variation happens between plots, and there is no extra variation explained by knowing to which forest patch each plot belongs (and then the model without the random factor would appear more parsimonious); you have "independent" plots. NONE of the extremes are very likely to happen... particularly for biological variables observed on the ground, if only because of spatial autocorrelation and geographical distributions of the mammals. I personally prefer to keep factors by design anyway (e.g., even when patches is not a relevant source of variation IN THIS SAMPLE) to sustain the "experimental-observational" analogy explained above; remember: not having evidence in your sample to reject the null hypothesis stating that variation among patches is zero does not mean that variation is really zero in the population.
Answer: Random effects induce heteroskedasticity and correlation in "error terms" in the model
A useful way to look at random effects models is to use some mathematical manipulation to mash them back onto the form of a traditional model without a random effect term.  This can be accomplished by absorbing the random effects terms into the error terms of a traditional fixed effect model.  We can then examine the properties of the new error term in the traditional fixed effect model form, to see what happens with this variation.
To illustrate this technique, consider a Gaussian linear random effects model with observations $Y_{i,j}$ taken over categories $j=1,...,k$.  The model can be written as:
$$Y_{i,j} = \beta_0 + \beta_j + u_j + \varepsilon_{i,j}
\quad \quad \quad
u_j \sim \text{N}(0,\sigma_j^2)
\quad \quad \quad
\varepsilon_{i,j} \sim \text{N}(0,\sigma^2),$$
where the random effects terms and error terms are mutually independent.  Since both the error terms and the random effect terms are random variables in the model, we can combine them into a single alternative error term and write the model in a form that does not show a separate random effect.  Specifically, we write the model in the traditional fixed effect form:
$$Y_{i,j} = \beta_0 + \beta_j + \eta_{i,j},$$
where we have defined the quantities:
$$\eta_{i,j} = z_j + \varepsilon_{i,j}
\quad \quad \quad \quad \quad
\rho_j = \frac{\sigma_j^2}{\sigma_j^2+\sigma^2}
\quad \quad \quad \quad \quad
\sigma_{j*}^2 = \sigma_j^2+\sigma^2.$$
In this latter form, the error terms $\eta_{i,j}$ are still (jointly) normally distributed with zero mean, but they are no longer homoskedastic and uncorrelated --- they have covariance values:
$$\mathbb{C}(\eta_{i,j},\eta_{i',j'})
= \mathbb{C}(z_j + \varepsilon_{i,j}, z_{j'} + \varepsilon_{i',j'})
= \begin{cases}
\sigma_{j*}^2 & & \text{if } i = i' \text{ and } j = j', \\[6pt]
\rho_j \sigma_{j*}^2 & & \text{if } i \neq i' \text{ and } j = j', \\[6pt]
0  & & \text{otherwise}. \\[6pt]
\end{cases}$$
This form means that there is heteroskedasticity in the model (i.e., with variance $\sigma_{j*}^2$ for observations in category $j$) and the errors within a group are positively correlated (with correlation coefficient $\rho_{j}$).

Should you use a random effects model? As you can see from the above, a Gaussian linear random effects model using categorical predictors is equivalent to a traditional Gaussian linear regression model using categorical predictors, where the latter has heterosedasticity across the categories of observations and positively correlated errors within each category.  Consequently, your choice of whether or not to include random effects terms can be framed equivalently as a choice of whether or not to generalise the behaviour of the error terms in the model to allow heteroskedasticity across categories and correlation of error terms within categories.
In the study you are conducting, your forest patches are the categories and your plots within these forest patches are your individual observations.  In this case, including a random effect in your model (taken at the level of the forest patches) is equivalent to allowing heteroskedasticity across different forest patches and also having positive correlation of the mammal abundance of different plots within each forest patch.  In order to decide whether or not this is appropriate, you merely need to ask yourself if this type of heteroskedasticity/correlation might plausibly occur in this case.
You have also noted that your forest patches were not randomly sampled.  This is not necessarily a problem for the random effects model, and it is no more of a problem than to a fixed effects model.  In assessing your sampling method you should consider whether your choice of sites was influenced by any of the variables under study, and consider the types of biases this could induce.  However, there is nothing inherent in the random effects model (as opposed to the fixed effects model) that presents an analytical difference here.
I would suggest that in the present case this kind of heteroskedasticity/correlation might plausibly occur, owing to the closeness of the plots within a patch and the possible movement behaviour of the mammals under study.  Different plots within the same forest patch might plausibly have positively correlated mammal abundance due to  the movement of mammals around a forest patch, breeding of mammals from amongst nearby plots within a forest patch, and common conditions/threats to mammals within the same forest patch.  You have noted that you tried both the random effects and fixed effects models and conducted a likelihood-ratio test, finding that there was no significant evidence of the presence of random effects.  That is perfectly fine, and it is one way to conduct your analysis --- you have an initially plausible model form and then you find that it does not operate better than a simpler model form.


IMAP URL fetch body structure

Question: I need to fetch mailbox information using an IMAP URL request. These are detailed in RFC5092. I have succeeded in fetching parts of the body with URLs such as
imaps://imap.gmail.com:993/INBOX/;UID=4/;SECTION=1

which is equivalent to the command
UID FETCH 4 BODY.PEEK[1]

Is there a way, using only a URL to fetch the bodystructure (UID FETCH 4 BODYSTRUCTURE) of a message?
Answer: No, there isn't any such way. 5092 only provides access to some IMAP entities, and the bodystructure is not one of them.
Comment: Thank you. I found another solution using cURL.

IMAP URL fetch body structure


lme versus aov repeated measures variance specification

Question: I am performing a repeated measures ANOVA in R, where the experimental design is composed of a between-subjects factor (Prodotto, three levels), the within-subjects factor is time (Tempo, four levels&mdahsan ordered factor) and each Product * Time is repeated on eleven patients (idPaziente).
The aov() syntax would be:
myAov<-aov(valore ~ Tempo*Prodotto + Error(idPaziente/Tempo),data=mydata)

whilst the lme() (from the nlme package) syntax would be
myModel <- lme(valore ~  Tempo*Prodotto,data=mydata, random= ~ 1 | idPaziente/Tempo)

In Finch (2014) Multilevel Modeling with R,  I find a specification of a longitudinal model that would be written as:
myModel <- lme(valore ~  Tempo*Prodotto,data=mydata, random= ~ 1 | idPaziente)

I guess the equivalent aov version would have Error(idPaziente) instead of Error(idPaziente/Tempo).
I would like to ask:

What is the correct specification for my repeated measures model, both for aov() and lme()?
Why are (1 | idPaziente/Tempo) and Error(idPaziente/Tempo) more appropriate than (1 | idPaziente) and Error(idPaziente)?
How can I perform post hoc analysis taking on the Prodotto term?
Comment: This is borderline, but IMO it may have just enough statistical content to be considered on topic here.
Comment: Hi Giorgio - Just out of curiosity, did my answer worked for the problem you were experiencing? Or can I update it somehow?
Answer: This depends on your nesting structure (example dataset):
set.seed(123)
df <- data.frame(
  idPaziente = rep(c(1:12), each = 11),
  Tempo = rep(c(1:4),33),
  Prodotto = rep(letters[1:3], 11, each = 4),
  valore = rnorm(132, 6, 1)
)

Using random = ~ 1 | idPaziente/Tempo:
fit <- lme(valore ~  Tempo * Prodotto, data = df, random = ~ 1 | idPaziente/Tempo)

To get the ANOVA table you could do:
library(car)
Anova(fit)

If your idPaziente and Tempo is explicitly nested,
df$newID <- with(df, paste(idPaziente, Tempo, sep = "-"))

you only need to specify random = ~ 1 | newID
fit2 <- lme(valore ~  Tempo * Prodotto, data = df, random = ~ 1 | newID)

Anova(fit2)

then:
summary(fit) and summary(fit2) will give you the same results. Also have a look at the Number of Groups: statement. This is a good check to see whether your nesting worked out correctly and reflects your data structure.
If Prodotto is significant, you could follow up with:
library(lsmeans)
lsmeans(fit, pairwise ~ Prodotto)
lsmeans(fit2, pairwise ~ Prodotto)

And the same should hold for the aov() function, too.


Could anybody give me an example of finite measure which has non-zero value for all non-empty measurable set?

Question: I'm trying to construct a finite measure defined on Borel sigma algebra of $[0,1]$ such that every nonempty set has nonzero measure.
Can anybody give me a help to find out such measure?
Thanks in advance.
Comment: Your title says "non-negative", your question says "nonzero".  Which did you mean?
Comment: Non-zero. I edited. Thanks.
Answer: Such a measure doesn't exist.
Assume that $\mu([0, 1]) = M < \infty$. Then the cardinality of $T_n = \{x \in [0, 1] \mid \mu(\{x\}) > \frac{1}{n}\}$ is at most $Mn$ and therefore finite. Since every nonempty set is supposed to have a positive measure, the identity $[0, 1] = \bigcup \limits_{n \in \mathbb{N}} T_n$ holds. But this is impossible, since $[0, 1]$ is uncountable and the countable union of finite sets is at most countable.
Comment: It even follows, that such a measure can't be $\sigma$-finite at all.
Comment: @kdbanman If you could pick $Mn + 1$ elements out of the set, their union would have a mass of at least $(Mn + 1)/n = M + 1/n > M$, which contraditcs $\mu([0, 1]) = M$.
Comment: +1, but: Possibly not the best choice to use $M$ as a real number and $M_n$ as sets.
Comment: @ThomasAndrews You are right, I've changed $M_n$ to $T_n$. Thanks for the suggestion!
Comment: Quite illuminating. Thanks!
Comment: Sorry if this should be obvious, but why is it that $|T_n| \leq Mn$?


CGSize sizeSpace = [@" " sizeWithFont:self.fontHashtag constrainedToSize:rect.size lineBreakMode:self.lineBreakMode];

Question: CGSize sizeSpace = [@" " sizeWithFont:self.fontHashtag constrainedToSize:rect.size lineBreakMode:self.lineBreakMode];

How to remove deprecated warning from code ?
I'm a fresher so can you please explain elaborately?
Answer: sizeWithFont is depreciated so you need to use sizeWithAttributes method.
CGSize sizeSpace = [@" " sizeWithAttributes:@{NSFontAttributeName:self.fontHashtag}];

Comment: Thank you It worked
Comment: Welcome mate. You can check here for other [attribute](http://stackoverflow.com/a/19197903) Happy Coding :)


What do the different reverb parameters mean?

Question: Inspired by this question:
How to make a sound appear to be more distant?
What do all the different reverb parameters (like "ER" and "Diffusion") actually mean?
Answer: Reverb effects can be fairly simple (spring reverb in a guitar amp*) or very complicated (like a Lexicon studio reverb unit).
Here's a run-down on the most common reverb parameters taken from: http://www.emusician.com/gear/1332/cheat-sheet-reverb-parameters/38871
*Note that guitar amp spring reverbs usually have a control just called "reverb" that functions as a wet/dry mix control as described below.

TYPE
Hall and Room are self-explanatory. [Todd: In case they are not, "Hall" is meant to re-create the sound of a large concert hall. Most hall types have longer decay times and higher diffusion, for a smooth spacious sound. "Room" types are meant to re-create a smaller room, which means they normally have shorter decay times, more noticeable early reflections, and a more pingy or metallic sound. Both types usually have a lot of variation that can overlap in sound with larger rooms sounding like smaller halls.] Plate emulates the plate reverbs common in the '60s, which were often used for vocals. Inverse creates a reverse reverb effect, where the reverberation starts at a lower level and increases to a higher level. Spring types emulate old mechanical reverbs known for a "sproingy," metallic sound. Gated reverb has a decay that cuts off abruptly below a certain level. Convolution reverbs load a sample (also called impulse) that defines a room's characteristics, and impresses these characteristics on the signal being reverberated.
ROOM SIZE
Larger sizes typically correlate to longer reverb times and possibly a wider stereo image. As even synthetic rooms can have standing waves, if the reverb sound has flutter (a periodic warbling effect), vary this parameter in conjunction with decay time (described later) for a smoother sound.
EARLY REFLECTIONS (ER) LEVEL
This parameter sets the level of the first group of echoes that occurs when sound waves hit walls, ceilings, etc. These reflections tend to be more defined and sound more like "echo" than "reverb." Prominent early reflections tend to work better with sustained sounds, such as vocals and pads, than percussive sounds. Balance the early reflections so they are neither obvious discrete echoes, nor masked by the decay. Lowering the early reflections level also places the listener further back in the room, and more toward the middle.
PRE-DELAY
Simulates the amount of time it takes for a sound to leave its sound source and create a first reflection. Setting a slight pre-delay offsets the reverb from the dry signal, which can prevent reverb from "stepping on" the signal being reverberated. Also, increase pre-delay to give the feeling of a bigger space; for example, large room sizes tend to work well with significant pre-delay.
DECAY TIME
This determines how long it takes for the reflections in the room to run out of energy. Long reverb times may sound impressive on instruments when soloed, but rarely work in an ensemble context (unless the arrangement is sparse). Reverb presets often link the decay time and room size parameters so you don't end up with, for example, a small room with a very long decay. However, "wrong" settings can sometimes create useful sounds.
DAMPING
With softer surfaces (e.g., a hall packed with people), the reverb tails will lose high frequencies as they bounce around, producing a warmer sound with less "edge." If your reverb has an artificial-sounding high end, add damping to create a warmer sound. Damping affects overall tone, so setting it "oppositely" often works well (lots of damping with a bright-sounding song to warm it up, little damping if the song needs more "air").
HIGH FREQUENCY ATTENUATION
This reduces the high frequencies going into the reverb. If your reverb sounds metallic, reduce the highs starting at 4–8kHz. Remember, many great-sounding plate reverbs didn't have much response over 5kHz.
LOW FREQUENCY ATTENUATION
Use this to reduce low frequencies entering the reverb. This can prevent a muddy, indistinct sound that takes focus away from the kick and bass. Try attenuating from 100–200Hz on down.
WIDTH
Some reverbs allow expanding or collapsing the stereo image.
LOAD IMPULSE FILE
This is found only in convolution reverbs. A convolution reverb will not function without having a reference impulse audio file loaded.
MODULATION DEPTH
To create more variation in reverb sounds, modulation adds subtle changes to the reverb characteristics. Increase modulation depth if the reverb sound needs more "animation."
MODULATION RATE
For reverbs with modulation, this determines the rate at which modulation changes occur.
EARLY REFLECTIONS DIFFUSION
Increasing early reflections diffusion pushes the early reflections closer together, thickening the sound. Reducing diffusion creates more discrete echoes. For percussive instruments, lots of diffusion avoids the "marbles bouncing on a steel plate" effect caused by too many discrete echoes. However, for vocals and other sustained sounds, reduced diffusion can give smooth reverberation that doesn't overpower the source and maintains clarity.
REVERB DECAY DIFFUSION
This is similar to early reflections diffusion but affects the reverb "tail." Many reverbs use a single control for both diffusion parameters.
REVERB DENSITY
Lower densities give more space between the reverb's first reflections and subsequent reflections. Higher densities place these closer together. Generally, as with diffusion, higher densities work better for percussive content, and lower densities for vocals and sustained sounds.
HIGH FREQUENCY DECAY
With reverbs having separate decay times for high and low frequencies, this sets the decay of high frequencies. A longer high frequency decay gives a brighter, more ethereal type of reverb that can sound great on vocals as it adds more reverb to sibilants and fricatives, while minimizing reverb on plosives and lower vocal ranges.
LOW FREQUENCY DECAY
With reverbs having separate decay times for high and low frequencies, this sets the decay of low frequencies. A longer low frequency decay gives a bigger, more "massive" type of reverb that's more like a large live space, but when used to excess, can give a "muddy" sound.
CROSSOVER FREQUENCY
This sets the dividing point between the high and low frequencies mentioned  above.
(WET/DRY) MIX
Use this to edit the balance of dry and reverberated sound. If the reverb serves as an insert effect, set this for the desired blend. If the reverb is a send effect, this is usually set to reverb only, with the return control determing the overall reverb level in the mix.
GATE
For gated reverb, this sets the level below which the reverb tail is cut off. Using relatively high gate settings was a popular effect in '80s synth-pop.
GATE DECAY
When using gated reverb, this adjusts how long it takes for the reverb tail to decay after the reverb signal passes below the gate threshold.
Comment: This answer is very informativ and clear also for users of synthesizers.


How to repeat passages in Falk's №1?

Question: I'm trying to play R. Falk's №1. I don't understand how repetition works here with multiple coda signs/brackets. Could someone give me a hint? The music goes like this:
Answer: Here is your chart with bar numbers in blue and important landmarks highlighted in yellow:

This chart has repeat signs, repeat endings, two D.S. (Dal segno) and three coda signs. Here is how they work:

Start at the beginning and play through bar 8 (the first ending with repeat sign) Go back to bar 1 (repeat sign) and continue.

Play bar 1-7, skip bar 8, play bar 9 (to second ending) and continue.

Play through bar 18 (first ending) then repeat back to bar 11. Play again but skip bar 18 (to second ending) and play bar 19.

At this point it says D.S. to coda 1 so you go back (D.S.) to bar 1

Repeat step 1

Play bar 1-7, skip bar 8, play bar 9 (second ending) and then jump to bar 20 (coda to coda 1)

Play bars 20-37 then jump back to bar 1 (D.S. al coda 2)

Same as before, play 1-8 then 1-9 skipping bar 8 then after bar 9 jump to bar 38 (coda to coda 2) and play to the end.

That's it!
Answer: A simpler, and possibly clearer explanation:

Play from the beginning (with repeats) until you get to the D.S.
play from the segno sign  (repeats are optional) jumping from the coda  sign to coda 1
play coda 1 until you get to the second D.S
play from the segno sign (repeats still optional) jumping from the coda sign to coda 2
play coda 2

The repeat brackets are played like this:

How to repeat passages in Falk's №1?


PL/SQL return record in procedure

Question: I have a procedure which called "gps_coord". It takes two parameter and must return record . But I don't know how I can do it . Thanks in advance ;)
CREATE OR REPLACE PROCEDURE gps_coord(v_x IN FLOAT,
                                      v_y IN FLOAT, v_result out result_type)
IS
TYPE result_type IS RECORD(
     v_km VARCHAR2(50),
     v_objID VARCHAR2(50)
);

v_out result_type;
BEGIN

select P.KM , P.OBJECTID INTO v_out  from SDE.POINTS p where        sde.st_intersects(P.SHAPE,sde.st_buffer(sde.st_transform( sde.st_point(v_y,v_x,4326),32639) ,5000))=1;
 dbms_output.put_line('km: ' || v_out.v_km || 'objid: ' || v_out.v_objID );
END;

Comment: As above...If you place your procedure in a package you can then declare the record type in the package spec.
Comment: The record type must be declared outside the procedure...
Comment: @ammoQ is right, in your case you have an standalone  procedure, to use record type as parameter it must be declared at schema level.
Comment: Please look over [this](http://stackoverflow.com/questions/13225532/is-it-possible-to-use-return-in-stored-procedure) question & answer.
Comment: Sorry a little mistake, record as I remember can't be schema level, as above declare in package specs or as a schema level object type.
Comment: yeah thank you to all. I declare my type above . And added my procedure  out param with my created type
Answer: CREATE OR REPLACE TYPE result_type IS OBJECT
(
   v_km NVARCHAR2(50),
   v_objID NVARCHAR2(50)
 )

CREATE OR REPLACE PROCEDURE gps_coord(v_x IN NVARCHAR2, v_y IN NVARCHAR2,    v_result out result_type)
 IS
  BEGIN
   select P.KM , P.OBJECTID INTO v_result.v_km ,  v_result.v_objID from SDE.POINTS p where sde.st_intersects(P.SHAPE,sde.st_buffer(sde.st_transform( sde.st_point(v_y,v_x,4326),32639) ,5000))=1;
  end;

Answer: Try this. Hope it helps.
    --Object type creation
CREATE OR REPLACE TYPE result_type
IS
  OBJECT
  (
    v_km    VARCHAR2(50),
    v_objID VARCHAR2(50) );

--Table type
CREATE OR REPLACE type result_tab
IS
  TABLE OF result_type;

  --Procedure creation and out the collection
CREATE OR REPLACE
PROCEDURE gps_coord(
    v_x IN FLOAT,
    v_y IN FLOAT,
    v_result OUT result_tab)
AS
  v_out result_tab;
BEGIN
  SELECT result_type(P.KM , P.OBJECTID) BULK COLLECT
  INTO v_out
  FROM SDE.POINTS p
  WHERE sde.st_intersects(P.SHAPE,sde.st_buffer(sde.st_transform( sde.st_point(v_y,v_x,4326),32639) ,5000))=1;
  FOR i IN v_out.FIRST..v_out.LAST
  LOOP
    dbms_output.put_line(v_out(i).v_km||' '||v_out(i).v_objID);
  END LOOP;
END;

Comment: Thank you @AvrajitRoy  ;) Can I ask question ? I have another problem.When I test my procedure it show me error : "Variant conversion error for value v_x" . Can you help me ? Thanks in advance
Comment: What is the input you are passing to the procedure?
Comment: v_x=40.889786  and v_y=45.994247

PL/SQL return record in procedure


Splitting data into an array

Question: public class ImportDoctorFile  {

    public ImportDoctorFile() {
              System.out.println("Starting Cons");

     List<Doctor> doctorList = new ArrayList<>();
            Scanner scanner;
      try
        {
             scanner= new Scanner(new File("Doctors.csv"));
              scanner.useDelimiter("\n");
             while (scanner.hasNextLine())
            {
                String temp = scanner.nextLine();
                String [] tempDetails = temp.split(",");

                Doctor myDoctor;
                Surgeon mySurgeon;

                if(tempDetails.length == 5)
                {
                    myDoctor =new Doctor (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4]);
                    doctorList.add(myDoctor);
                    System.out.println(myDoctor);
                }
                else if(tempDetails.length ==6)
                {
                    mySurgeon =new Surgeon (tempDetails[0],tempDetails[1],tempDetails[2],tempDetails[3],tempDetails[4],tempDetails[5]);
                    doctorList.add(mySurgeon);
                    System.out.println(mySurgeon);
                }
            }
        }
      catch(FileNotFoundException e)
        {
            System.out.print("Error, unable to locate the CSV File!");

        }
    }
}

I am having a problem when trying to load the data from my .csv file into an array and split it up. When outputting the details it skips some of the doctors and miss places the 6th index when creating a surgeon. I have pasted the csv file above.
Conor Murphy    12 Front Road Leeds Telephone   firstname.lastname@example.com   Surgery      12/05/2016
Carol McKee 79 The Green Birmingham Skype   Cmckee-25   Neurology
Robert Jones    165 Main Street Glasgow Facetime    email@example.com    Orthopedics
Mary Shelley    297 Peartree Grove Guildford     Skype  m-shelly1   Cardiology
John Smith  13 Value Avenue Bristol Telephone    +44(0)7987545352    Surgery     12/05/2016
Laura Penny 87 Primrose Way Ipswich Facetime    email@example.com    Pulmonology
Mark Matthews   2 The Strand Dublin Skype   Matthews-m15     Int.Care Medicine
Ciaran Bell 58 Windy Ridge Folkstone    Telephone   +44(0)8452126984     Infectious Disease
Nicola Johnson  128 Ash Park Coleraine  Skype   Nicky-j123  Surgery     24/11/2015
Comment: Your example data doesn't even contain a `,` as far as i can see. And you don't need a FILE fore that. Put your input into a single static string, and work from there. That also helps to put up a [mcve] for us. Beyond that: dont reinvent the wheel. CSV parsing is a solved problem. Take a library that does it for you. Believe me: doing it yourself is **much** harder than you think it is.
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the "edit" link to improve your *question* - do not add more information via comments. Thanks!
Answer: You can use StringBuilder class
StringBuilder class has the property of converting its content into tokens.
Simply add ',' as the delimiter and you will get the tokens.

Splitting data into an array


Problem ignoring in a view the images inside the .views field body and the minimum number of characters?

Question: I need to remove the images appears in the view in the field body. I have tried the following code.
<code>.view-mydisplay .views-field-body {
    display:none;
}
</code>
However, I cannot see the image but the "maximum length of characters" of my field-body are not showing completely. If I remove the image manually in the body, then the characteres are complete in the view.   Seems how if the image were counted like character.
For example if I have 300 max. characters in my view and I put an image only are showed 100 characters, after remove the images with css.  If I don't put the image in my body, the view shows the 300 characters configured in the view.
Answer: The Smart trim module might be helpful. You'll be able to trim units by words or characters on stripped HTML.

After installing and enabling Smart Trim, you should see a "Smart
  trimmed" option in the format dropdown for your text fields. With
  smart trim, you have control over:

The trim length
Whether the trim length is measured in characters or words
Appending an optional suffix at the trim point
Displaying an optional "More" link immediately after the trimmed text
Stripping out HTML tags from the field
Comment: Hi, Thanks very much for your option.  I don't want to affect the body of the node, only the view, I want if in the body of the node I put an image, this image not be showed in my view, however, when I remove the image with css the characters showed in my view are changed. For example if I have 300 max. characters in my view and I put an image only are showed 100 characters, after remove the images with css.  Thanks very much for your help.
Comment: This module is integrated with Views. Please install this module and edit your view field which you're going to trim. Select formatter `Smart trimmed`. Trim units `characters`. Check `strip html`. All should work without any additional css settings.


How do I make the nodes referenced by organic group content also be OG content?

Question: I have an organic group called 'newsletter'.
I have two content types - 'issue' and 'article' - in 'issue' (which is set to be a group content type), there is a node reference field to articles, and many articles in a single issue, using an inline entity reference form.
I want to put an issue inside an organic group, for access control. I also want the articles that the issue references inherit that group content relationship without having to explicitly set the group for every single piece of content.
The group is public, but the content is private. I don't want anyone to access group content until they go though a process and purchase access via the commerce_licence_og module.
The article (content referenced in entity reference field) isn't added to the group content, though the issue itself is. I felt that a group reference for every article is redundant, and I would rather the article inherit the issue's access and status as group content rather than have a bunch of redundant fields and is automatic, not requiring additional admin steps.
Is there an easy way to do this?
Do I HAVE TO make the articles group content in the UI?
Comment: You could possibly do this with rules or cer maybe, you would still have to set the OG field and make it OG content but may could set it automatically instead of with og context or entity reference pre-populate. Is there a specific reason why you don't want to set the field on that piece of content?
Comment: You could always write a custom module as well to do this, when the node is accessed you could check the reference and run it through OG access and fake the same access.
Comment: Yes, I was thinking of a custom module. I want the interface to be as simple as possible - I don't want the admins to see anything superflous. However, I think you're right, and I need to add the og fields for all the content.

I was wondering if anyone had done something similar. I'll post something when I have it done. Shouldn't be too difficult.
Answer: Here is the solution I've come up with.
It works, but might not be the most elegant solution. I didn't think that this would matter too much, since it's only being called on node save, but I'm open for comments and suggestions.
<code>/**
 * Ensure that referenced nodes belong to the same organic group
 *
 */
function MODULE_node_presave($node) {

  if ($node->type == NODE_TYPE) {

    $og = og_get_entity_groups('node', $node);
    $nids = get_referenced_nodes($node);

    foreach($nids as $nid){

      $child_node = node_load($nid);

      //Set the values
      $values = array(
        'entity_type' => 'node',
        'entity' => $child_node,
        'state' => OG_STATE_ACTIVE,
      );

      //Add this node to the group
      $gid = array_values($og['node']);
      $result = og_group('node', $gid[0], $values);

    }
  }
}

/**
 * Helper function - get all node reference fields of a node
 * @param $master_nid - the node id of the referencing node
 */
function get_referenced_nodes($master_node) {

  $fields = field_info_instances('node', $master_node->type);

  $items = array();

  foreach($fields as $field){

    if($field['widget']['module'] == 'inline_entity_form'){
      // Get the node reference items for this field
      $items[] = field_get_items('node', $master_node, $field['field_name']);

    }

  }

  // Loop through and grab the nids
  foreach ($items as $field) {
    foreach($field as $target){
      $nids[] = $target['target_id'];
    }
  }

  return $nids;

}
</code>


Can one find a stronger norm on a Banach space?

Question: Given a Banach space $V$ of infinite dimension with norm $\|\cdot\|_1$, is that possible to find a norm $\|\cdot\|_2$ on $V$ such that the topology induced by $\|\cdot\|_2$ is strictly stronger than that of $\|\cdot\|_1$?
I guess the answer is no, but I can only prove that $\|\cdot\|_2$ cannot be complete (simply  by open mapping theorem). Any idea will be appreciated.
Answer: Yes, assuming the axiom of choice, one can find a stronger norm.
Use the axiom of choice to construct a linear operator $T : (V, \|\cdot\|_1) \to (V, \|\cdot\|_1)$ which is discontinuous.  Define $\|x\|_2 = \|x\|_1 + \|Tx\|_1$.  It's easy to check this is a norm, and since $\|x\|_2 \ge \|x\|_1$, it follows that the topology induced by $\|\cdot\|_2$ is at least as strong as the topology induced by $\|\cdot\|_1$.
If the topologies are the same, then the identity map, considered as a map from $(V, \|\cdot\|_1)$ to $(V, \|\cdot\|_2)$ is a continuous linear map and hence bounded.  This means there is a constant $C$ such that for all $x \in V$ we have $\|x\|_2 \le C \|x\|_1$.  But this implies $\|Tx\|_1 \le (C-1)\|x\|_1$, contradicting the assumption that $T$ was discontinuous.
Hence $\|\cdot\|_2$ induces a strictly stronger topology than $\|\cdot\|_1$.
If you reject the axiom of choice, then it is consistent that no stronger norm exists.  (If it did, then the identity map would be a discontinuous linear map from a Banach space to a normed space.  In a model like Shelah's or Solovay's, where every subset of every Polish space has the property of Baire, no such maps exist.)
Comment: An elegant solution! Thank you very much.
Answer: Do you mean, can you always find a strictly stronger norm? Or does there exist a strictly stronger norm of some Banach norm?
In the first case, I do not know. But in the second case, we can take the example of measurable functions on an interval: $(L^1([0,1],||\cdot||_1)$ where here the $1$ doubles as your "first norm" and also the $L^1$ norm ($||f||_1 = \int|f|$) then take $||f||_2$ to be the essential supremum of |f| (i.e. $||f||_\infty$ adapted to measurable functions).
So note that $||f||_1 \leq ||f||_2$, so $||\cdot||_2$ is stronger. But here we see that for $f_n(x) = 1$ for $x\in [0,\frac{1}{n}]$ and $f_n(x) = 0$ for $x\in [\frac{1}{n}, 1]$, $||f||_1 = 1/n$ and $||f||_2 = 1$, so we can't find a $c$ such that $c||f_n||_2 \leq ||f_n||_1$ for every $n$. Thus $||\cdot||_1$ is strictly stronger.
I believe this works as an example.
Comment: are the notion of stronger norm and stronger induced topology the same? I feel like Censi LI is asking for something different..
Comment: Ah, I guess I selectively read and skipped over "the topology induced by". However, I do believe that a stronger norm implies a stronger topology.
Comment: The underlying vector space isn't the same, since $L^1[0,1]$ properly contains $L^{\infty}[0,1]$.
Comment: Right...crap. I forgot about things like $\frac{1}{\sqrt{x}}$...and switching $L^1$ to $L^\infty$ removes the hypothesis that it is Banach to start with. Hmm...
Comment: I don't require $\|\cdot\|_2$ being complete. In fact, I can disprove it when $\|\cdot\|_2$ is complete simply by open mapping theorem.
Comment: I agree that the open mapping theorem definitely tells us that if $||\cdot||_2$ exists then it must not be complete. The problem with my example is that my $||\cdot||_1$ wasn't defined for everything in $L^1$.
Answer: I'm inclined to say no. The identity map from $V$ under $||\cdot||_2$ to $V$ under $||\cdot||_1$ is continuous, linear, and onto, but if we pick a set $A$ that's open in the $||\cdot||_2$-topology but not the $||\cdot||_1$-topology, then it seems the open mapping theorem is violated.
Comment: But I think open mapping theorem is applicable only when $(V,\|\cdot\|_2)$ forms a Banach space. So when $\|\cdot\|_2$ is not complete, it leads no contradiction.


How to find what values of x and y create the greatest value of $\ z$ where $\ z=(x+1)y$ and $\ 20x+5y=1000$

Question: How do I find the the values of x and y that create the greatest value of $z$ where
$z=(x+1)y$
$20x+5y=1000$
assuming $x$ and $y$ are positive. I tried a few 3D calculators but the ones I found only graph one function at a time. I can't see a way to solve this other than trial and error.
Comment: Solve for $y$ in terms of $x$ using the second equation, and then you must maximize a quadratic function of $x$
Comment: A technique learned in multivariable calculus for this scenario is Lagrange multipliers, but that's not needed for this problem
Answer: From the second equation, $y=200-4x$, so we have to maximize
$z=(x+1)(200-4x)=-4(x+1)(x-50)$.
Can you take it from here?
Comment: Thank you! this is exactly what I was looking for


Redirects only the main shop page (excluding search) to another page in WooCommerce

Question: I tested following code to redirect my shop main page to an another page, home.
It works but it also redirects search result to home so people can't see the search result.
add_action('template_redirect', 'bc_010101_redirect_woo_pages');
function bc_010101_redirect_woo_pages() {
    if (is_shop())
   {
     wp_redirect('/');
     exit;
   }
}

How to resolve it?
Answer: You can add is_search() to your if condition, which determines whether the query is for a search.
So you get:
function action_template_redirect() {
    /**
     * is_shop() - Returns true when on the product archive page (shop).
     * is_search() - Determines whether the query is for a search.
     *
     * (redirect to home)
     */
    if ( is_shop() && ! is_search() ) {
        wp_safe_redirect( home_url() );
        exit;
    }
}
add_action( 'template_redirect', 'action_template_redirect' );

OR as a product search adds 's' query variable in URL, you can try to use:
function action_template_redirect() {
    /**
     * is_shop() - Returns true when on the product archive page (shop).
     *
     * (redirect to home)
     */
    if ( is_shop() && ! isset( $_GET['s'] ) ) {
        wp_safe_redirect( home_url() );
        exit;
    }
}
add_action( 'template_redirect', 'action_template_redirect' );


Obter diferença entre horas Definida/Atual

Question: Gostaria de obter quantas horas se passou, de uma determinada data, para a data atual. Por exemplo:
day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

Variável day possui a data inicial, a partir dessa data gostaria de começar a contar as horas. E a variável today possui a data atual.
Answer:

day = new Date("Thu May 19 2016 05:00:00 GMT-0300");
today = new Date("tue May 23 2016 09:00:00 GMT-0300");

document.write(diferencaDias(day,today));

function diferencaDias(data1, data2){
    var dif =
        Date.UTC(data1.getYear(),data1.getMonth(),data1.getDate(),0,0,0)
      - Date.UTC(data2.getYear(),data2.getMonth(),data2.getDate(),0,0,0);
      dif=Math.abs((dif / 1000 / 60 / 60));
      difH=Math.abs(today.getHours()-day.getHours());
      difM=Math.abs(today.getMinutes()-day.getMinutes());
      difS=Math.abs(today.getSeconds()-day.getSeconds());
    return ((dif+difH)+"Horas   "+difM+"Minutos    "+difS+"Segundos");
}
Comment: Dessa forma, ele pega os dias, não as horas certo ? Pq no exemplo que eu coloquei, o resultado é 3 dias e 20hs, então 92hs
Comment: +1 pelo uso de abs para garantir que não haverá diferença "negativa" de tempo. Agora, o Jonathan está certo... remover a divisão por 24 no final do código fará com que ele retorne as horas, como a pergunta pede.
Comment: Já alterei e está a funcionar, dá a diferença em horas, minutos e segundos.
Answer: Você pode usar a biblioteca Moment.js e fazer algo parecido com isso:

var today  = moment("Tue May 23 2016 09:00:00 GMT-0300 (BRT)");
var day = moment("Thu May 19 2016 05:00:00 GMT-0300 (BRT)");

var duracao = moment.duration(today.diff(day));
var horas = duracao.asHours();
console.log(horas)

Comment: Diz que o objeto `today` não possui o método diff. Sabe me dizer pq?
Comment: Você instalou a biblioteca?
Comment: Sim. Mas o problema é no objeto `today`, e não na parte do `moment`. Ai acho que não interfere mesmo se eu não tivesse instalado.
Comment: Interfere pois o método `diff` é parte do `moment`. De uma analisada no código, talvez vc esteja esquecendo de algo.
Comment: Exemplo funcionando no jsfiddle: https://jsfiddle.net/sinkz/koznnzvo/2/
Answer: Resposta simplista talvez, mas se só queres as horas de diferênça podes fazer :
var horas = Math.abs(data_A - data_B) / 36e5;

Math.abs para dar um numero positivo e ser assim indiferente a ordem das datas
/ 36e5 porque esse valor é o mesmo que 3600000 que é 60 segundos x 60 minutos x 1000 milisegundos. Isto porque datas em javascript são em milisegundos.

Exemplo:

var day = "Thu May 19 2016 05:00:00 GMT-0300 (BRT)";
var today = "tue May 23 2016 09:00:00 GMT-0300 (BRT)";

var horas = Math.abs(new Date(day) - new Date(today)) / 36e5;
alert(horas); // 100