How to show pending (unpublished) revision fields in views in Drupal 7?

Question: I am using Drupal 7 and I have a CT with revisioning and workbench moderation enabled.
I want to create a view for administrators, showing the latest revision of the nodes with various fields, even if the latest revision is not published (pending).
I have created a node revisioning view with relationships on revision and revision node, but it seems to fetch field values only for the published/current revisions and not for the latest.
The administrators have access to unpublished content, and they can view the latest revisions with their fields through the revisioning interface.
To better understand how the revisioning works with views, I created a test view showing all the revisions of a specific node, having some archived revisions, then a published/current one and then some pending ones. I can view field values only for the published one.
Is there any way to show field values for all node revisions in views?
The view results are the following:

My view export code is the following:
$view = new view();
$view->name = 'test_revisions_2';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node_revision';
$view->human_name = 'test revisions 2';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'test revisions 2';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'view revisions';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '50';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['pager']['options']['id'] = '0';
$handler->display->display_options['pager']['options']['quantity'] = '9';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'nid',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'body' => 'body',
  'nid' => 'nid',
  'vid' => 'vid',
  'name' => 'name',
  'state' => 'state',
  'state_1' => 'state_1',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'body' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'nid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'vid' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'state' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'state_1' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Revision */
$handler->display->display_options['relationships']['vid']['id'] = 'vid';
$handler->display->display_options['relationships']['vid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['vid']['field'] = 'vid';
$handler->display->display_options['relationships']['vid']['ui_name'] = 'Revision';
$handler->display->display_options['relationships']['vid']['label'] = 'Revision';
/* Relationship: Revision node */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'node_revision';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['ui_name'] = 'Revision node';
$handler->display->display_options['relationships']['nid']['label'] = 'Revision node';
/* Relationship: Country */
$handler->display->display_options['relationships']['field_ef_country_iso2']['id'] = 'field_ef_country_iso2';
$handler->display->display_options['relationships']['field_ef_country_iso2']['table'] = 'field_data_field_ef_country';
$handler->display->display_options['relationships']['field_ef_country_iso2']['field'] = 'field_ef_country_iso2';
$handler->display->display_options['relationships']['field_ef_country_iso2']['relationship'] = 'vid';
$handler->display->display_options['relationships']['field_ef_country_iso2']['ui_name'] = 'Country';
$handler->display->display_options['relationships']['field_ef_country_iso2']['label'] = 'Country';
/* Field: Content revision: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node_revision';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['link_to_node_revision'] = TRUE;
/* Field: Content: Body */
$handler->display->display_options['fields']['body']['id'] = 'body';
$handler->display->display_options['fields']['body']['table'] = 'field_data_body';
$handler->display->display_options['fields']['body']['field'] = 'body';
$handler->display->display_options['fields']['body']['relationship'] = 'vid';
$handler->display->display_options['fields']['body']['type'] = 'text_summary_or_trimmed';
$handler->display->display_options['fields']['body']['settings'] = array(
  'trim_length' => '100',
);
/* Field: Content revision: Nid */
$handler->display->display_options['fields']['nid']['id'] = 'nid';
$handler->display->display_options['fields']['nid']['table'] = 'node_revision';
$handler->display->display_options['fields']['nid']['field'] = 'nid';
/* Field: Content revision: Vid */
$handler->display->display_options['fields']['vid']['id'] = 'vid';
$handler->display->display_options['fields']['vid']['table'] = 'node_revision';
$handler->display->display_options['fields']['vid']['field'] = 'vid';
/* Field: Countries: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'countries_country';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'field_ef_country_iso2';
/* Field: Content revision: State */
$handler->display->display_options['fields']['state']['id'] = 'state';
$handler->display->display_options['fields']['state']['table'] = 'node_revision';
$handler->display->display_options['fields']['state']['field'] = 'state';
$handler->display->display_options['fields']['state']['label'] = 'Revision state';
/* Field: Workbench Moderation: State */
$handler->display->display_options['fields']['state_1']['id'] = 'state_1';
$handler->display->display_options['fields']['state_1']['table'] = 'workbench_moderation_node_history';
$handler->display->display_options['fields']['state_1']['field'] = 'state';
$handler->display->display_options['fields']['state_1']['label'] = 'Moderation state';
$handler->display->display_options['fields']['state_1']['machine_name'] = 0;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['relationship'] = 'nid';
$handler->display->display_options['filters']['type']['value'] = array(
  'ef_national_contribution' => 'ef_national_contribution',
);
$handler->display->display_options['filters']['type']['group'] = 1;
/* Filter criterion: Content revision: Nid */
$handler->display->display_options['filters']['nid']['id'] = 'nid';
$handler->display->display_options['filters']['nid']['table'] = 'node_revision';
$handler->display->display_options['filters']['nid']['field'] = 'nid';
$handler->display->display_options['filters']['nid']['value']['value'] = '1405';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'test-revisions-2';
$translatables['test_revisions_2'] = array(
  t('Master'),
  t('test revisions 2'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Revision node'),
  t('Country'),
  t('Body'),
  t('Nid'),
  t('Vid'),
  t('Name'),
  t('Revision state'),
  t('Moderation state'),
  t('Page'),
);

Update 1:
I'm posting a screenshot of my view UI:
Answer: You have mentioned "published/current" as if both are same. But in workbench moderation published refers to the revision that is published and current refers to the revision that is latest.
So, if you want to show the latest revision then create a view of node revision as you have done and add the fields you want to display. The important thing is to add a filter Workbench Moderation: Current and select the value Yes, this will make sure only the latest revisions are displayed.
Edit:
        Normally if you create content revision view for your scenario you will get the values, try removing all the relationship except Content Revision: Content. If you do that you will get the values, title and other fields, but the problem will be that title will change as per revision but other fields will only display the published revision content.
For eg: assume you had three revisions of a node, first: archived, second: published, third: review, then the result will look like this
eg:
     Title V1, Field V2
     Title V2, Field V2
     Title V3, Field V2
To change, add a field with the label historical like Content (historical data): Field this will display the way you want
     Title V1, Field V1
     Title V2, Field V2
     Title V3, Field V3
Comment: I was referring to revisioning's current revision which is the published revision, as shown in the attached table too.

If I add the Workbench Moderation: Current filter, then in my example the result will be the latest revision with vid 1639, but the Body and Name/Country fields will be empty, although they actually have values. What I want is revision 7, but with values in all fields.
In my real view I'm going to add this filter, but in this test view I wanted to see what it shows for each revision.
Comment: can you post the screenshot of your view ui
Comment: I have updated my question with a screenshot.
Comment: The Content (historical data) solution worked perfectly. I had never used this type of fields and filters and I cannot even find any documentation for this.
Answer: Since I have been poking around for something similar, this post was helpful in clarifying the "Content (historical data)" :
How to pull node history into a view
Comment: please try to avoid link only answers - if the link dies, so does the answer


The limit of an integral (with statistical backgrounds)

Question: I would like to compute the following limit of an integral $$I=\lim_{n\to+\infty}\int_0^n\frac{x^n\text{e}^{-x}}{n!}\text{d}x$$
which I encountered in a statistics problem. I can easily do this using Gamma distribution and Central Limit Theorem:

 Consider a random variable $X_n$ with PDF $f_n(x)=\frac{x^n\text{e}^{-x}}{n!}$. From the properties of Gamma distribution, it can be decomposed into exponential distributions, $X_n=\sum_{k=1}^n X_k$ where $X_k\sim\text{Exp}(1)$. Now let $F_n(x)=\text{P}(\frac{X_n-n}{\sqrt n}\leq x)$; from Central Limit Theorem, $$\lim_{n\to+\infty}F_n(x)=\lim_{n\to+\infty}\text{P}\left(\frac{\sum_{k=1}^n X_k -n}{\sqrt n}\leq x\right)=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^x\text{e}^{\frac{-t^2}{2}}\text{d}t$$ Plugging $x=0$ in gives $I=\frac 1 2$.

Nevertheless, I would like to know if there are any pure math methods for solving this (that don't involve anything statistical). The integral itself, from Wolfram|Alpha, is $$\int_0^n\frac{x^n\text{e}^{-x}}{n!}\text{d}x=\frac{\Gamma(n+1)-\Gamma(n+1,n)}{n!}$$
which doesn't seem to be very useful (it's just rewriting this integral in a Gamma function form). Any help would be appreciated.
Comment: The rewriting of the integral in terms of the incomplete Gamma function does have one interesting implication: Since $\Gamma(n+1)=n!$ for nonnegative integer $n$, the desired limit amounts to showing $$1-\frac{\Gamma(n+1,n)}{\Gamma(n+1)}\to \frac12,$$  or $\Gamma(n+1,n)/\Gamma(n+1)\to 1/2$ as $n\to\infty$.
Answer: Not sure it is as pure math as you'd wish but here goes. Let:
$$
I_{m,n} = \int_0^m \frac{x^ne^{-x}}{n!}\text{d}x
$$
Using a simple integration by parts yields, for $n>0$:
$$
I_{m,n} -I_{m,n-1} = -\frac{m^ne^{-m}}{n!}
$$
Furthermore:
$$
I_{m,0} = \int_0^m e^{-x}\text{d}x = 1 - e^{-m}
$$
Then:
$$
I_{m,n} = I_{m,0} + \sum_{k=1}^n (I_{m,k} - I_{m,k-1})
$$
$$
I_{m,n} = 1 - e^{-m} - \sum_{k=1}^n \frac{m^ke^{-m}}{k!}
$$
Which, when setting $m$ to $n$:
$$
I_{n,n} = \int_0^n \frac{x^ne^{-x}}{n!}\text{d}x =  1 - e^{-n} \sum_{k=0}^n \frac{n^k}{k!}
$$
That was the rather easy part. You can then conclude using the result of this question (where most of the answers essentially go back the other way, so really you're just better off just picking up from where your integral appears).
Comment: Wow that's a good method. +1


shellcode resutado "Segmentation fault"

Question: Bom tenho um arquivo chamado teste.asm com o codigo (para windows):
section .text
    global _main
    extern _printf

msg:
    db "%d", 0

_main:
    mov eax, 10
    add eax, 20

    push eax
    push msg
    call _printf
    add esp, 8
    ret

compilando usando o nasm: nasm -f win32 teste.asm -o teste.o
e depois usando o objdump do gcc tenho o seguinte:
00000000 <msg>:
   0:   25 64 00 b8 0a          and    $0xab80064,%eax

00000003 <_main>:
   3:   b8 0a 00 00 00          mov    $0xa,%eax
   8:   83 c0 14                add    $0x14,%eax
   b:   50                      push   %eax
   c:   68 00 00 00 00          push   $0x0
  11:   e8 00 00 00 00          call   16 <_main+0x13>
  16:   83 c4 08                add    $0x8,%esp
  19:   c3                      ret

usando agora no arquivo shellcode.c
#include <stdio.h>

const char shellcode[] = "\x25\x64\x00\xb8\x0a\xb8\x0a\x00\x00\x00\x83\xc0\x14\x50\x68\x00\x00\x00\x00\xe8\x00\x00\x00\x00\x83\xc4\x08\xc3";

int main( void )
{
  int (*func)();
  func = (int (*)())shellcode;

  (int)(*func)();
}

compilando: gcc shellcode.c -o main
e executando: ./main
tenho o seguinte:

Segmentation fault

alguém pode me ajudar?
Answer: O código binário do shellcode, declarado na variável shellcode[], fica armazenado na memória
em uma página destinada a dados, portanto, sem permissão para execução de código
(somente leitura+escrita).
Quando o programa chama a função func(), que aponta para a página de dados, ocorre um erro de
segmentação (General Protection Fault), devido à falta de privilégio de execução na página
de destino.
Caso você queira apenas testar o shellcode, é necessário:

Incluir o header Windows.h
Alocar uma página de memória e atribuir a permissão de execução+escrita a esta página
Copiar o código binário que está na variável shellcode[] para a página alocada
Apontar a função para o início dessa página
Chamar a função

O código (comentado) fica da seguinte forma:
#include <stdio.h>
// Incluir o header Windows.h
#include <Windows.h>

const char shellcode[] = "\x25\x64\x00\xb8\x0a\xb8\x0a\x00\x00\x00\x83\xc0\x14\x50\x68\x00\x00\x00\x00\xe8\x00\x00\x00\x00\x83\xc4\x08\xc3";

int main( void )
{
    int (*func)();

    // Cria um ponteiro para a página de memória que será alocada
    LPVOID page;

    // Aloca a página de memória com permissão de escrita e execução
    page = VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    // Copia o shellcode para a página alocada
    CopyMemory(page, shellcode, 256);

    // Aponta func para a página e não para a variável shellcode
    func = (int (*)())page;

    // Chama a função
    (int)(*func)();

    // Desaloca a página
    VirtualFree(page, 0, MEM_RELEASE);

    return 0;
}

No código assembly, você declarou a função _printf como extern, porém, ao compilar o programa, o linker não tem como descobrir ou alterar o endereço desta função, pois ela está embutida dentro do shellcode, por isso, ao chamar o programa em assembly ele irá dar erro.
A dica aqui é evitar declarar funções externas.
Comment: Ok. Obrigado !!

shellcode resutado "Segmentation fault"


Is there an C# equivalent to the PHP function `parse_str`?

Question: Is there an C# equivalent to the PHP function parse_str?
I couldn't find anything and wrote my own function but is there something in the C# framework?
public Dictionary<string, string> parse_str(string query) {

    Dictionary<string, string> data = new Dictionary<string, string>();

    foreach(string set in query.Trim('?').Split('&'))
        data.Add(set.Split('=')[0], set.Split('=').Length < 2 ? "" : set.Split('=')[1]);

    return data;
}

Answer: I think you are looking for HttpUtility.ParseQueryString()
Comment: I knew it. Why does it seem PHP's manual is easier to navigate and discover than C#'s? Thanks!
Comment: Google is your C# manual/MS documentation in general search utility - you just have to know what to search for, which is not always easy. It helps to add a `site:msdn.microsoft.com` clause you your Google search term
Comment: Unfortunately the `NameValueCollection` doesn't `JavaScriptSerializer().Serialize` like a `Dictionary` does. And it would seem the only way to convert `NameValueCollection` to a `Dictionary` would be a for loop which makes my `parse_str` function more relevant. C# < PHP for web development.
Answer: If you're taking it from the browser's query string, you can use Request.QueryString
You can get a list of all the keys: Request.QueryString.Keys
Get a value of a key: Request.QueryString["KeyName"]
Comment: It covers the 95% use case much better than any alternative, despite not having identical functionality to what was asked.  It's rather uncommon for a site to parse the query strings of a page other than 'itself'.
Comment: @iambriansreed C# is not php.  You're not always going to find an exact port for everything.  Rather than looking for, "how what C# code does the same thing as this PHP code" you should be asking, "how do I accomplish this *task* in C#".  If the answers happen to be the same, so be it.
Comment: I figured you were overlooking that the querystring was already parsed for you and that you may want to use `Request.QueryString` over retrieving it and passing it into `HttpUtility.ParseQueryString()`.  Can you explain how this is irrelevant?
Comment: Can you look up [`parse_str`](http://php.net/manual/en/function.parse-str.php) mentioned in the question and explain how your answer was relevant.
Comment: @Servy explained the reason for my answer better than I could have.
Comment: @iambriansreed He answered the question that you should have asked, and addressed the underlying problem rather than the specific technical question.  That gets a +1 in my book.
Comment: @Jeff Sorry, I should have stated clearly at the beginning why your answer was not only wrong but irrelevant. I referenced the `parse_str` function because it does what exactly what I need. @DaveRandom didn't assume my lack of knowledge and answered the question. He didn't think my question was wrong and should be fixed. Just because you may have never had the need to parse a string into variables doesn't mean the rest of the web developer world hasn't. Please think twice before assuming my question is wrong. Thanks for attempt.
Comment: @iambriansreed I am only responding in hopes to educate you in your error.  You did not post a "wrong" question and I did not post a "wrong" answer.  The only action which was wrong, was your choice to downvote my answer.  My answer can be helpful to people who ask a similar question to yours, but are not looking for the specific answer you are.  Please read: http://stackoverflow.com/privileges/vote-down


EM Algorithm - E step

Question: In the E-step, why are there 2 different thetas ? Isnt the expectation of a function $ E[x] = \int xp(x) ?$ If I know x then I would know p(x) as well right ? Based on what I am reading $ E[x] = \int xp(x') $. Can someone explain to me what is going on ?
Also, how do I maximize the expectation of a gaussian function ? Solving the integral gives me the solution, i.e. the mean of the gaussian. I have no variable left like what is doing in the maximization step in the EM algorithm.
Answer: First of all you have a function $Q(\Theta, \Theta^{(t)})$ that depends on two different thetas: $\Theta$ which is the new one. One strategy could be to insert multiple $\Theta$ into the function and take the one with the maximal value for example. Then there is $\Theta^{(t)}$. This is the 'current' estimate of the parameters. The idea of the EM Algorithm is to proceed from the current estimate of the parameters $\Theta^{(t)}$ to (basically, any) new estimation $\Theta$ that 'improves the situation'. Now the situation means to make the likelihood
$$p(x|\cdot) = \sum_z p(x,z|\cdot)$$
better than before, i.e. the goal is to make a step from $\Theta^{(t)}$ to $\Theta$ such that
$$p(x|\Theta) > p(x|\Theta^{(t)})$$
if notation confuses you then you can safely redefine $\Theta^{(t)}$ to $\Theta^{(\text{old})}$ and $\Theta$ to $\Theta^{(\text{new})}$.
Remark: There is a concept of 'conditional expectation' which is something like a generalization of the usual expected value you are referring to but it is NOT THE SAME! The object the EM algorithm is referring to is
  $$E[\log p(x,Z|\Theta) | X=x]$$
this is a really complicated object! It is the factorization of the random variable $E[\log p(x,Z|\Theta) | \sigma(X)]$ at $x$.
However, one can show mathematically that
  $$E[g(x,Z)|X=x] = \int_{\mathcal{Z}} g(x,z) p(x|z) dy$$
Also, the usual notation might be confusing. Let us write $p_\Theta(...) = p(...|\Theta)$. Then what we want is
  $$Q(\Theta|\Theta^{(\text{old})}) = E[\log p_{\Theta}(x,Z^{\Theta^{(\text{old})}}) | X^{\Theta^{(\text{old})}}=x]$$
i.e. the density is the one of the random variables with the 'new' density but the actual random variables that we put in are the ones with the 'old' parameter. Hence,
$$E[\log p_{\Theta}(x,Z^{\Theta^{(\text{old})}}) | X^{\Theta^{(\text{old})}}=x] = \int_{\mathcal{Z}} p_\Theta(x,z) p_{\Theta^{(\text{old})}}(x|z) dz = \sum_z p_\Theta(x,z) p_{\Theta^{(\text{old})}}(x|z)$$
For the Gaussian mixture model you should study https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm#Gaussian_mixture.
Comment: Note: when people speak about 'Gaussian' in terms of the EM algorithm then they usually mean a mixture model of Gaussian densities, not a single (collection of) random variable(s) with a Gaussian density!

EM Algorithm - E step


How to find accuracy in multi-GPU Tensorflow training?

Question: When we do training in Tensorflow multi-GPU environment, how do we find test accuracy and display them in terminal next to the training loss?
1. Can we find test accuracy on single GPU?
2. Should we find test accuracy on all available GPUs and then calculate the average?
Answer: You have to average the accuracies on all GPUs and that will give you the overall accuracy. Suppose you have 64 exemplars on each of 4 GPUs for a batch size of 256 (= 4 * 64 ). If 50,48,56,52 are accurately labeled in each of them respectively, then your overall accuracy is 50 + 48 + 56 + 52 = 206 / 256 = 80.47%.
Sometimes, when you want to calculate something more complicated than accuracy, you might suppose that the result from one GPU is a good approximation of the overall value and save yourself the trouble of getting all the values from all GPUs. For that to be valid, there are two conditions that have to be satisfied:

The batch should be randomly assigned to each GPU, normally they are shuffled for that purpose.
The batch should be large enough for each GPU to receive at least 32 exemplars.


variable might not have been initialized

Question: I don't understand what is wrong with my code and why it produces error:

variable k might not have been initialized

import java.util.*;
public class kk
{
    public static void main(String [] args)
    {
        Scanner scan=new Scanner(System.in);
        int m=scan.nextInt();
        for(int q=0;q<m;q++)
        {
        int a=scan.nextInt();
        int b=scan.nextInt();
        int n=scan.nextInt();
        scan.close();
        int k;
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=i;j++)
            {
               k=j*b;
            }
            k=k+a;
            System.out.println(k);
            k=0;
        }}
    }
}

Comment: The error is quite clear; you're declaring the variable but not initializing it with a value before the loop.
Comment: What should the value of `k=k+a;` be if `k` was never given an initial value?
Comment: As the warning says. the variable `k` is not initialized. In Java, **local variables** are not initialized as default unlike **instance variables**. Local variables have to be initialized manually, e.g, `int k = 0`
Answer: Not sure what your main method/code is trying to accomplished but the variable int k is being considered as a local variable in your case. Please consider initializing your int primitive data type variable k with the default value of 0 before using it in the nested for-loop code block.
int k = 0;

From the Java documentation:

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
Answer: public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int m = scan.nextInt();
    for (int q = 0; q < m; q++) {
        int a = scan.nextInt();
        int b = scan.nextInt();
        int n = scan.nextInt();
        scan.close();
        int k;
        for (int i = 1; i <= n; i++) {
            k = 0;
            for (int j = 1; j <= i; j++) {
                k = j * b;
            }
            k = k + a;
            System.out.println(k);
        }
    }
}

Comment: Solves  "k might not have been initialized" but **changes the meaning** of the program.
Comment: That both have 'k=0;` somewhere in them doesn't make them the same,
Comment: Kevin Anderson - are you sure ?
Comment: Am I sure the order of statements in a program matters?  Uh, yeah.
Comment: Look closely at the logic of the original program, @pranav after printing on console the result of k set its value to 0 (causing it to restart), therefore to avoid "k might not have been initialized" and get the result that it is expected to initialize to "k" in that position.


Unable to access SMTP port 25

Question: After restarting my VPS, the email server I recently setup is not working. In particular, it is not accepting connections on port 25. Before the restart it was. I've tried several things, but I'm not sure what is wrong. I'm hoping it is something simple, but I'm concerned that it might be an incompatibility between SystemD, FirewallD, and OpenVZ, the virtualization type used*.
To clarify, before the restart I had been able to us telnet to send mail to my server. I had also been able to send/receive mail to/from the server from/to my gmail account.
I'm hoping someone can help me diagnose the issue.
I think the problem is with the firewall. Here is a successful telnet connection from the VPS to itself:
[root@VPS ~]# telnet mydomain.com 25
Trying <Server IP>...
Connected to mydomain.com.
Escape character is '^]'.
220 mail.mydomain.com ESMTP Exim 4.84_2 Mon, 13 Jun 2016 00:38:39 -0400
> HELO test
250 mail.mydomain.com Hello mydomain.com [Server IP]
> QUIT
221 mail.mydomain.com closing connection
Connection closed by foreign host.

The connection fails when trying from a different machine. Note that the domain does resolve and this is the Windows machine that I am using to ssh to the VPS using ssh firstname.lastname@example.com.
C:\Users\Liam>telnet mydomain.com 25
Connecting To mydomain.com...Could not open connection to the host, on port 25: Connect failed

Here is the firewall zone information:
[root@VPS ~]# firewall-cmd --zone=public --list-all
public (default)
  interfaces:
  sources:
  services: dhcpv6-client imaps pop3s smtp ssh
  ports: 25/udp 587/udp 80/tcp 465/udp 465/tcp 25/tcp 587/tcp 9418/tcp 53/tcp 53/udp
  masquerade: no
  forward-ports:
  icmp-blocks:
  rich rules:

Here is the current status of FirewallD
[root@VPS~]# systemctl status firewalld
* firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2016-06-12 23:14:35 EDT; 1h 30min ago
 Main PID: 941 (firewalld)
   CGroup: /system.slice/firewalld.service
           `-941 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

Jun 12 23:14:34 hostname systemd[1]: Starting firewalld - dynamic firewall daemon...
Jun 12 23:14:35 hostname systemd[1]: Started firewalld - dynamic firewall daemon.
Jun 12 23:14:35 hostname firewalld[941]: 2016-06-12 23:14:35 ERROR: ebtables not usable, disabling ethernet bridge firewall.

I'm not sure if that error was there before the restart, but *this post has some relevant information about the error as well as FirewallD + OpenVZ.
Here are the statuses of exim and dovecot, as well as named.
[root@VPS~]# systemctl status {exim,dovecot,named}
 * exim.service - Exim Mail Transport Agent
   Loaded: loaded (/usr
 * List item

/lib/systemd/system/exim.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2016-06-12 22:08:27 EDT; 2h 38min ago
 Main PID: 172 (exim)
   CGroup: /system.slice/exim.service
           `-172 /usr/sbin/exim -bd -q1h

Jun 12 22:08:27 hostname systemd[1]: Starting Exim Mail Transport Agent...
Jun 12 22:08:27 hostname systemd[1]: Started Exim Mail Transport Agent.

* dovecot.service - Dovecot IMAP/POP3 email server
   Loaded: loaded (/usr/lib/systemd/system/dovecot.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2016-06-12 22:08:27 EDT; 2h 38min ago
 Main PID: 182 (dovecot)
   CGroup: /system.slice/dovecot.service
           |-182 /usr/sbin/dovecot -F
           |-205 dovecot/anvil
           |-206 dovecot/log
           |-866 dovecot/auth
           `-869 dovecot/ssl-params

Jun 12 22:08:27 hostname systemd[1]: Starting Dovecot IMAP/POP3 email server...
Jun 12 22:08:27 hostname systemd[1]: Started Dovecot IMAP/POP3 email server.

* named.service - Berkeley Internet Name Domain (DNS)
   Loaded: loaded (/usr/lib/systemd/system/named.service; enabled; vendor preset: disabled)
   Active: active (running) since Sun 2016-06-12 22:08:27 EDT; 2h 38min ago
 Main PID: 191 (named)
   CGroup: /system.slice/named.service
           `-191 /usr/sbin/named -u named

Jun 12 22:08:27 hostname named[191]: zone 184.108.40.206.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa/IN: loaded serial 0
Jun 12 22:08:27 hostname named[191]: zone localhost.localdomain/IN: loaded serial 0
Jun 12 22:08:27 hostname 967277 named[191]: zone localhost/IN: loaded serial 0
Jun 12 22:08:27 hostname named[191]: zone mydomain.com/IN: loaded serial 0
Jun 12 22:08:27 hostname named[191]: all zones loaded
Jun 12 22:08:27 hostname systemd[1]: Started Berkeley Internet Name Domain (DNS).
Jun 12 22:08:27 hostname named[191]: running
Jun 12 22:08:27 hostname named[191]: zone domain.com/IN: sending notifies (serial 0)
Jun 12 22:15:21 hostname systemd[1]: Started Berkeley Internet Name Domain (DNS).
Jun 12 23:08:27 hostname named[191]: listening on IPv4 interface venet0:0, <VPS IP>#53

An excerpt from my exim.conf file:
[root@VPS~]# cat /etc/exim/exim.conf | grep daemon_smtp
daemon_smtp_ports = 25 : 465 : 587

And, I'm not sure if this is relevant, but here is some iptables information.
[root@VPS~]# iptables -L | grep smtp
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:smtp ctstate NEW
ACCEPT     udp  --  anywhere             anywhere             udp dpt:smtp ctstate NEW
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:smtp ctstate NEW
[root@VPS~]# iptables -L -n | grep 25
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:25 ctstate NEW
ACCEPT     udp  --  0.0.0.0/0            0.0.0.0/0            udp dpt:25 ctstate NEW
ACCEPT     tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:25 ctstate NEW

I'm happy to provide any more information that may be relevant. Also, this is my first post to the site. I think this is on-topic, but I briefly debated Unix or Superuser as well.
UPDATE
I turned off the firewall:
[root@domain~]# systemctl stop firewalld
[root@domain~]# systemctl status firewalld
* firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: inactive (dead) since Mon 2016-06-13 01:52:47 EDT; 4s ago
  Process: 941 ExecStart=/usr/sbin/firewalld --nofork --nopid $FIREWALLD_ARGS (code=exited, status=0/SUCCESS)
 Main PID: 941 (code=exited, status=0/SUCCESS)

Jun 12 23:14:34 hostname systemd[1]: Starting firewalld - dynamic fire....
Jun 12 23:14:35 hostname systemd[1]: Started firewalld - dynamic firew....
Jun 12 23:14:35 hostname firewalld[941]: 2016-06-12 23:14:35 ERROR: eb....
Jun 13 01:52:47 hostname systemd[1]: Stopping firewalld - dynamic fire....
Jun 13 01:52:47 hostname systemd[1]: Stopped firewalld - dynamic firew....
Hint: Some lines were ellipsized, use -l to show in full.

I then checked for an iptables service
[root@domain~]# systemctl status iptables
* iptables.service
   Loaded: not-found (Reason: No such file or directory)
   Active: inactive (dead)
[root@domain~]# service iptables status
Redirecting to /bin/systemctl status  iptables.service
* iptables.service
   Loaded: not-found (Reason: No such file or directory)
   Active: inactive (dead)

I still got the same error when trying to telnet to the VPS on port 25.
Comment: Try to telnet on the SMTP server of your ISP. You should see the banner. Try with Gmail servers too.
Comment: Really I don't understand those 'downvote trolls' in the community :(
Thinking in troubleshoot the problem: Do you have firewallD + iptables? can you disable them and try it?
Comment: @Dom You're right, it does seem to be my computer. I turned the firewall back on and the VPS can both send and receive email.
Comment: Can I get the reason for the immediate downvote? (otherwise how will I learn)
Comment: @HEDMON Thanks. *facepalm* I don't know why I didn't already try disabling the firewall. I've updated the page with the results. This leaves me at a bit of a loss, because if the firewall isn't the issue, I'm not sure what is. However now I'm even more positive that it is something simple that I'm missing. I probably forgot to permanently turn something on and the reboot removed it...
Comment: can you reach other services in other ports? 80, 8080, 21, 22? (http, https, ftp, ssh)
Comment: @HEDMON yes, I can SSH to the server and I have apache running giving "Hello, World!" at the web address in a browser. I can also `telnet mydomain.com 22`
Comment: Your windows machine is maybe filtered by your ISP. In France, most ISP block the outgoing 25/tcp from the clients users to not send the spam from not managed PC.
Comment: @Dom is right. You can try http://mxtoolbox.com/SuperTool.aspx
Comment: @Dom Okay, That is odd. Earlier I was using that tool and it showed an unable to connect on port 25 error. Perhaps it was the firewall. However I am still unable to connect via my own computer, and I was able to do this earlier. Would my ISP have blocked this within the last day or something? (That doesn't sound likely)
Comment: @Dom I guess will be good if you write the answer and Liam accept it ;)
Answer: The problem could coming from outside of your machine. You can try to telnet your ISP SMTP server or Gmail servers to test if it's working.
Some ISP block the SMTP connections, to not allow the virus to propagate from non managed computers.
In you case, you may ask your ISP to open the connection from your computer to your server.

Unable to access SMTP port 25


Merge codes from different authors on github

Question: I am new to GitHub so please excuse my dumb question.
I have a repository on GitHub with 2 contributors (one is me and the other is X).
I had pushed some code in the repository with say 5 files(a,b,c,d,e).
Now both of us (X and me) downloaded that code and modified it.
X modified the files a,b and c and added a new file f and she committed and pushed the changes.
Meanwhile, I modified the file a and added a new file g.
Now I want to manually change the code in a, but I would like to have the repository with the files,
a(manually updated by merging changes from both me and X), b(updated by X), c(updated by X), d, e, f(added by X), g(added by me).
I hope my question is clear.
Everything is in the master branch.
Please tell me what steps to take.
Thank you.
Comment: Try pushing your changes. You'll get an error message explaining what you must do.
Answer: If your changes are local only so far, and her changes are on the remote repo, you need to pull her changes into your local clone, then merge the changes (manually or automatically), then commit and then push the cleaned up repo to the remote server.
That's a standard workflow for anyone collaborating on a common repo.
So first do a git pull - this should try to automatically merge the remote changes into your local master branch. Then fix any merge conflicts using a text editor.
Once that is done, commit the local changes and follow the instructions - Git prints quite a few comments (e.g. how to abort/continue a merge).
Once everything is cleaned up, push your changes to the remote repo: git push origin master.
Long-term, you should probably start looking into using feature branches for your work. Everybody works on their own branch and only merges into master once the feature is complete. Here's a nice tutorial that compares some popular Git workflows, including how to merge incoming changes like in your case: https://www.atlassian.com/git/tutorials/comparing-workflows


How to save a js file with the variable values set?

Question: I'm a beginner so I lack the proper vocabulary to clearly express what I want to try - or search for it so the right answers come up. But I'll try to explain:
I have a simple javascript application that has a bunch of variables that are filled with values from a database via jQuery ajax depending on initial user choices. Now, once the application is properly loaded with all the values retrieved from the db, I want to save it in this state for offline use.
The application would work fine without internet access if I hardcoded all the variable values, but as they depend on user choices upon start, this is not really an option. So I thought, maybe I could just save the loaded state as a js file. Is there any technology like that?
My fallback solution would be to do the hard work in php once the user clicks "download for offline use". Like keeping a copy of the js file as a string with placeholders for variable values and then replace them with the values from the database after the user made his initial choices. But to be honest, I feel like there must be a more elegant solution.
Comment: JavaScript files have no state. They're only text files. (Sorry if I misunderstood)
Comment: Sounds like you need a "backend" language. ... Just seeing you mention PHP. That would be the way to go. Not sure what you mean by "elegant" tho.
Comment: @GetSet I have yet to find anyone who can agree on what "elegant code" actually is.
Comment: Yes many takes on that subject.
Comment: `I want to save it in this state for offline use` with that requirement see @Aplet123 below
Comment: there's a perfect solution and it's called a service worker.
Answer: In browser Javascript, you cannot save files for security reasons. There is, however, an API called localStorage which allows you to store persistent information in the browser. You can put all your variables in an Object, stringify it to JSON, then save it in localStorage, then retrieve them by parsing the JSON:
// saving variables
var myVariables = {a: 1, b: "foo", c: [4, 5, 6]};
localStorage.setItem("vars", JSON.stringify(myVariables));
// retrieving variables
var retrievedVariables = JSON.parse(localStorage.getItem("vars"));
console.log(retrievedVariables.b); // "foo"

Comment: You can look into [service workers](https://developers.google.com/web/fundamentals/codelabs/offline) to make the website available offline.
Comment: That sound good, but does this require the user to keep the tab open or try to access the website while offline? Or can I create a 'clickable' file for him to open?` ... most users are not very techy and just need an icon to click on to start the application.


Writing shorter, readable, pythonic code

Question: I'm trying to produce shorter, more pythonic, readable python. And I have this working solution for Project Euler's problem 8 (find the greatest product of 5 sequential digits in a 1000 digit number).
Suggestions for writing a more pythonic version of this script?
numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()

nums = [int(x) for x in numstring]

best=0
for i in range(len(nums)-4):
    subset = nums[i:i+5]
    product=1
    for x in subset:
        product *= x
    if product>best:
        best=product
        bestsubset=subset

print best
print bestsubset

For example: there's gotta be a one-liner for the below snippet. I'm sure there's a past topic on here but I'm not sure how to describe what I'm doing below.
numstring = ''
for line in open('8.txt'):
    numstring += line.rstrip()

Any suggestions? thanks guys!
Answer: I'm working on a full answer, but for now here's the one liner
numstring = ''.join(x.rstrip() for x in open('8.txt'))

Edit: Here you go! One liner for the search. List comprehensions are wonderful.
from operator import mul
def prod(list):
    return reduce(mul, list)

numstring = ''.join(x.rstrip() for x in open('8.txt'))
nums = [int(x) for x in numstring]
print max(prod(nums[i:i+5]) for i in range(len(nums)-4))

Comment: Where Python offers a built-in like `operator.mul`, it is generally more efficient to use that rather than a `lambda`.  For something like this, the efficiency doesn't really matter; your computer will find the answer in the blink of an eye, so you can use what you prefer.  But in general, it's not bad to be in the habit of importing from `operator` when you are doing things with `reduce()` or `map()` or whatever.
Comment: That's really slick. what do you think of using a lambda instead of mul?
i.e. `def prod(list): return reduce(lambda x,y: x*y, list)`
Comment: That works well too. I don't know why python didn't build it in - it's a pretty common requirement (even more so for Project Euler!), and it really helped having it as a built-in in R.
Answer: from operator import mul

def product(nums):
    return reduce(mul, nums)

nums = [int(c) for c in open('8.txt').read() if c.isdigit()]
result = max((product(nums[i:i+5]) for i in range(len(nums))))

Comment: @thebjorn:  I intentionally didn't subtract 4 because it didn't impact the result.  If I was going to subtract I would have probably done something like `range(len(nums) - 5 + 1)` and maybe even named the magic number at that point.
Comment: There are some rather elegant tricks being used here.  But your use of `max()` with a `key` means that your `result` is set to the sequence of 5 numbers, not to their product.  It would be better to simply use `result = max(product(nums[i:i+5]) for i in range(len(nums)))`
Comment: I have to say I really like the list comprehension that creates `nums`.  Never mind using `.replace()` to get rid of line endings; just pull only the digits and convert them to integers in one go.  Elegant.
Comment: @steveha.  I misread the problem.  I thought it needed the actual sequence.   I'll edit the answer.
Comment: @steveha.  Ah.  I see.  The OP keeps the actual sequence, but the Project Euler problem does not require it.
Comment: @stevenrumbalski yeah that was left in because I was curious. I should have taken it (i.e. `print bestsubset`) out before posting here.
Answer: Here is my solution.  I tried to write the most "Pythonic" code that I know how to write.
with open('8.txt') as f:
    numstring = f.read().replace('\n', '')

nums = [int(x) for x in numstring]

def sub_lists(lst, length):
    for i in range(len(lst) - (length - 1)):
        yield lst[i:i+length]

def prod(lst):
    p = 1
    for x in lst:
        p *= x
    return p

best = max(prod(lst) for lst in sub_lists(nums, 5))
print(best)

Arguably, this is one of the ideal cases to use reduce so maybe prod() should be:
# from functools import reduce   # uncomment this line for Python 3.x
from operator import mul
def prod(lst):
    return reduce(mul, lst, 1)

I don't like to try to write one-liners where there is a reason to have more than one line.  I really like the with statement, and it's my habit to use that for all I/O.  For this small problem, you could just do the one-liner, and if you are using PyPy or something the file will get closed when your small program finishes executing and exits.  But I like the two-liner using with so I wrote that.
I love the one-liner by @Steven Rumbalski:
nums = [int(c) for c in open('8.txt').read() if c.isdigit()]

Here's how I would probably write that:
with open("8.txt") as f:
    nums = [int(ch) for ch in f.read() if ch.isdigit()]

Again, for this kind of short program, your file will be closed when the program exits so you don't really need to worry about making sure the file gets closed; but I like to make a habit of using with.
Comment: Yeah I think that the definition of `sub_lists(lst, length)` makes a lot of sense. It was confusing to use the magic number as in `len(nums)-4`.
Comment: Using a definition of prod like that is significantly slower than using the builtin `mul` from `operator`.
Answer: As far as explaining what that last bit was, first you create an empty string called numstring:
numstring = ''

Then you loop over every line of text (or line of strings) in the txt file 8.txt:
for line in open('8.txt'):

And so for every line you find, you want to add the result of line.rstrip() to it. rstrip 'strips' the whitespace (newlines,spaces etc) from the string:
    numstring += line.rstrip()

Say you had a file, 8.txt that contains the text: LineOne    \nLyneDeux\t\nLionTree you'd get a result that looked something like this in the end:
>>>'LineOne' #loop first time
>>>'LineOneLyneDeux' # second time around the bush
>>>'LineOneLyneDeuxLionTree' #final answer, reggie

Comment: Thanks for the thoughtful explanation @TankorSmash. I should have been clearer in my question, what I meant was: I dont know how to describe what I'm doing here succinctly enough to search for past topics on it.
Answer: Here's a full solution! First read out the number:
with open("8.txt") as infile:
    number = infile.replace("\n", "")

Then create a list of lists with 5 consecutive numbers:
cons_numbers = [list(map(int, number[i:i+5])) for i in range(len(number) - 4)]

Then find the largest and print it:
print(max(reduce(operator.mul, nums) for nums in cons_numbers))

If you're using Python 3.x you need to replace reduce with functools.reduce.
Comment: you can just replace `'\n'` with `''`
Comment: @JBernardo: sure, but that'll split on __any__ whitespace, and `"\n"` makes the intent more clear.
Comment: @JBernardo: ah now I see, yeah that's probably better.
Comment: @nightcracker:  `range(len(number) - 5)` is a bug.  Test it on '123456789'.  It misses the digit `9`.
Comment: map, reduce, and lambda aren't consider Pythonic by Guido ( http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ).
Comment: @thebjorn:  Read your link.  Guido says "So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly."  Multiplication is an associative operator, so it's perfect here.  Later he says "We already have sum(); I'd happily trade reduce() for product() ..."  Python 3 moved `reduce` to `functools`.  "Use functools.reduce() if you really need it; however, 99 percent of the time an explicit for loop is more readable."  This is the 1 percent exception.
Comment: I'm not uncle timmy, so my channeling of Guido might be faulty, but I believe the preferred way would be `max(reduce(operator.mul, nums) for nums in cons_numbers)` the key/lambda construct is rather obscure.
Comment: I don't think you tested this code.  (0) you need to do `infile.read().reduce` rather than `infile.reduce`  (1) you need to `import operator` (maybe you just left that to the reader) (2) your final result is a list of 5 integers; instead of using a key with `max()` it would be better to use a generator expression that applies the product code to each sublist, so that the result is the desired number.
Comment: @steveha & thebjorn: you are right, the __product__ is asked by the question, not the source. Let me fix that.


How to open view page in popup in yii2?

Question: I have to open view page contain in popup instead of page.After click on view open view contain in popup yii2
Answer: You should try this code for opening popup. and also you need to render with ajax view using this $this->renderAjax().
controller
public function actionView($id)
{
    if (Yii::$app->request->isAjax) {
        return $this->renderAjax('view', [
            'model' => $this->findModel($id),
        ]);
    } else {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }
}

View
<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
       ...................
        [
            'class' => 'yii\grid\ActionColumn',
            'buttons' => [
                'view' => function ($url, $model) {
                                 return Html::a('', $url , ['class' => 'view', 'data-pjax' => '0']);
                            },
            ],
 ....................
 ]);

$this->registerJs(
  "$(document).on('ready pjax:success', function() {  // 'pjax:success' use if you have used pjax
    $('.view').click(function(e){
       e.preventDefault();
       $('#pModal').modal('show')
                  .find('.modal-content')
                  .load($(this).attr('href'));
   });
});
");

 yii\bootstrap\Modal::begin([
    'id'=>'pModal',
]);
 yii\bootstrap\Modal::end();
?>

Comment: Thanks this one working but how to cancel this popup and data id not display proper format
Comment: put following code for close popup    `
×
`
Comment: jQuery.load() loads the entire web page (with header and footer). In this way you need to create a special layout for this view in order to load like a partial render.
Comment: See property for header and footer on ` yii\bootstrap\Modal` for more info. @DanA.S.
Comment: I was talking about the header and footer of the main layout of the web page that is loaded together with the body with $.load ()

How to open view page in popup in yii2?


C compiling error with homemade library

Question: it has been several years since the last time I wrote in C so I am sure the error I get is very stupid even so I thoroughly checked the search engine. Sorry in advance if that is the case.
The program I am writing is getting bigger and bigger so I decided to export some basic functions into a homemade library "stackmat.c"
Here is the code with two functions,
stackmat.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
//#include "stackmat.h"

double *stackmat(double *A, int sizeA[2], int dim)
// dim = 0, output is 1 row of sizeA[0] elements
// dim = 1, output is 0 column of sizeA[1] elements
{   double *B;
    int i;
    B = calloc(sizeA[dim],sizeof(double));
    if (dim == 1)           // size sizeA[1]
    {   for (i=0; i<sizeA[0]*sizeA[1]; i++) B[i%sizeA[1]] += A[i];
    }
    else                // size sizeA[0]
    {   for (i=0; i<sizeA[0]*sizeA[1]; i++) B[i/sizeA[1]] += A[i];
    }
    return B;
}

double *SumMat(double *A, double *B, int sizeA[2], int sizeB[2])
{   int i;
    double *C;
    C = calloc(sizeA[0]*sizeA[1],sizeof(double));
    for (i=0; i<sizeA[0]*sizeA[1]; i++) C[i] = A[i] + B[i];
    return C;
}

The header
stackmat.h
#ifndef STACKMAT_H_INCLUDED
#define STACKMAT_H_INCLUDED

double *stackmat(double *A, int sA[2], int dim)
double *SumMat(double *A, double *B, int sizeA[2], int sizeB[2])

#endif

And a simple calling program
checkslantlib.c
#include <stdio.h>
#include <stdlib.h>
#include "stackmat.h"

void main()
{   double *A, *B;
    int i, sA[2] = {4,3};
    A = malloc(12*sizeof(double));
    for (i=0; i<12; i++)    A[i] = (double) 0.5+i;
    for (i=0; i<12; i++)    printf(" %.1f",A[i]);
    B = stackmat(A,sA,1);
    for (i=0; i<3; i++) printf(" %.1f",B[i]);
}

When compiling with "gcc -c stackmat.c", everything is fine.
But "gcc checkslantlib.c -o stackmat.o" returns an error that I cannot understand
checkslantlib.c: In function 'stackmat':
checkslantlib.c:6: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
checkslantlib.c:13: error: expected '{' at end of input

If I include the header call in the library, this time it's the library compiling that returns pretty much the same error.
Can anyone see what I'm doing wrong please?
Comment: Aren't the Semicolons missing at the end of the decls in Stackmat.h ?
Comment: It's unfortunate that the error of using `void main()` is commonly not diagnosed. `int main(void)` is the correct form. `void main()` is useful (a) in some embedded systems, and (b) for detecting textbooks and tutorials whose authors do not know the C language as well as they think they do. I don't know where the idea started; the very same 1989 standard that introduced the `void` keyword also stated that `int` is the correct return type for `main`.
Answer: -o specifies the output file. Never mind what gcc does to your existing stackmat.o, you need to include stackmat.o in compliation by doing:
> gcc checkslantlib.c stackmat.o -o checkslantlib
or having in compiled as well as
> gcc checkslantlib.c stackmat.c -o checkslantlib
Comment: Sorry to be blunt, but what semi-colons exactly? I though prototype didn't need them.
Answer: You're missing semicolons after the function definitions.
#ifndef STACKMAT_H_INCLUDED
#define STACKMAT_H_INCLUDED

double *stackmat(double *A, int sA[2], int dim);
double *SumMat(double *A, double *B, int sizeA[2], int sizeB[2]);

#endif

It's not giving an error when you compile stackmat.c because you have the #include commented out.
Comment: ok, it's working, thanks everyone. I knew that was a stupid mistake on my part.
Answer: The two files should be compiled separately:
gcc -c stackmat.c producing stackmat.o
gcc -c checkslantlib.c producing checkslantlib.o
Then you link them together to produce the final executable:
gcc -o myprogram checkslantlib.o stackmat.o
Also check the missing semicolons as mentioned in other answers & comments.

C compiling error with homemade library


Question about what Z/6Z actually means?

Question: I have an abstract algebra exam tomorrow, and I'm having a little bit of difficulty deciphering the difference between $\mathbb Z/6 \mathbb Z$, $\mathbb Z_6$ and $6\mathbb Z$.
Can someone please explain this to me? As far as I thought, $\mathbb Z_6$ was the cyclic group of order $6$ and $\mathbb Z/6\mathbb Z$ was the quotient group.... but in an assignment, my professor wrote that $\mathbb Z/6\mathbb Z = \mathbb Z_6$, so I just wanted to clarify
Also, please excuse my formatting here. I'm new to this website!
Comment: For some basic information about writing math at this site see e.g.
[here](http://meta.math.stackexchange.com/questions/5020/),
[here](http://meta.stackexchange.com/a/70559/155238),
[here](http://meta.math.stackexchange.com/questions/1773/) and
[here](http://math.stackexchange.com/help/notation).
Comment: I am going to assume that by "Z6", you mean $\mathbb{Z}_6$, which is indeed the cyclic group of order 6. In addition, $\mathbb{Z}/6\mathbb{Z}$ is also the cyclic group of order 6, where you take integers "modulo 6" (it is generated by the image of 1 in the quotient). As for $6\mathbb{Z}$, this is the additive subgroup of $\mathbb{Z}$, obtained by multiplying everything by $6$.
Comment: I see that you (sort of) fixed the "Z6" thing.
Comment: I'm sorry about the editing! I went to the links Chantry included, but I couldn't figure out how to fix it.
Comment: Thanks for your help John!
Answer: $\mathbb{Z}_6$ is the integers modulo $6$, as you know. $\mathbb{Z}/6\mathbb{Z}$ is the integers modulo the (normal) subgroup generated by $6$. They are the same group. To see this, just define define the homomorphism from the second to the first by $x+<6>\leadsto x \rm{mod} 6$, and look at the kernel then use the first isomorphism theorem. To check that this is well defined you will need to use the division algorithm.
This should not be suprising as two integers are in the same coset if and only if they have the same remainder modulo $6$. Also note that this is pretty much a tautology.
Comment: Well, I'm guessing that you're treating $\mathbb{Z}_6$ as a collection of formal symbols with the operation of addition modulo $6$. The difference isn't really important. The two aren't \emph{equal}, they are \emph{isomorphic}.
Comment: So, just to make sure I'm getting this, ℤ6 = {0,1,2,3,4,5}, correct? And because ℤ/6ℤ is equal to {6ℤ, 6ℤ+1... 6ℤ+5}, they're the same thing?


Mailcore2: How to add signature to message

Question: Is there any API available in MailCore2 library for adding signature in email message?
Comment: you might like to check source in this post https://github.com/MailCore/mailcore2/issues/495
Answer: Get your email body as is:
NSString *oldEmailBodyString = [emailWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];

Then add you signature to it:
NSString *signature = @"
Sent from my iPhone
";
NSString *newEmailBodyString = [NSString stringWithFormat:@"%@ %@", oldEmailBodyString, signature];

Load your new email body from string:
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:bundlePath];
[emailWebView loadHTMLString:newEmailBodyString baseURL:baseURL];


Hands-on argument for base p version of Legendre's formula

Question: A formula that I never memorized by heart is $v_p(n!) = \frac{n-s}{p-1}$ where $s$ is the sum of the digits of $n$ in base $p$.
While it follows in a few lines from Legendre's formula, the reason I didn't memorize the above is that I do not yet grasp it intuitively. Is there a "hands-on" argument from which one "immediately" sees that this fraction has to be the correct term (other than the straightforward computation from Legendre's formula)?
Comment: We have $v_p(n!)  - v_p((n-1)!) = v_p(n)$, and rearranging $s_p(n) - s_p(n-1) = 1 - (p-1)\cdot v_p(n)$ gives $$v_p(n) = \frac{1 - s_p(n) + s_p(n-1)}{p-1} = \frac{\bigl(n - s_p(n)\bigr) - \bigl((n-1) - s_p(n-1)\bigr)}{p-1}\,.$$
Comment: Is the Wikipedia article's [proof](https://en.wikipedia.org/wiki/Legendre%27s_formula#Proof_2) for this what you mean by "in a few lines from Legendre's formula"? I just want to make sure that if I try answering this, then I know what specifically I am to compare my solution with to confirm I am actually addressing your stated concerns.
Comment: @JohnOmielan Yes, it is.
Comment: @DanielFischer Your suggestion is simpler than mine. As such, since I assumed you won't be adding an answer yourself, I took the liberty of adding a community wiki answer expanding on it.
Answer: With
$$\nu_p(n!) = \frac{n - s}{p - 1} \tag{1}\label{eq1A}$$
I don't know of any argument allowing you to "immediately" see this is true. Nonetheless, here's a alternate explanation which may not be more "hands-on", but it doesn't directly use the Legendre's formula proof and you may find it more intuitive.
As is done in the linked proof, define
$$n = \sum_{i=0}^{l}n_{i}p^{i} \tag{2}\label{eq2A}$$
A key element is the net contribution to $\nu_p(n!)$ from each $n_{i}p^{i}$ term in \eqref{eq2A} (as specified by $g(j)$ in \eqref{eq4A} below) is independent of all of the other terms' contributions. To see this, first $\forall \; 0 \le j \le l$ define
$$f(j) = \sum_{i=0}^{j}n_{i}p^{i} \tag{3}\label{eq3A}$$
$$g(j) = \begin{cases}
\emptyset & \text{ if } j = 0, n_0 = 0 \\
[1, f(j)] & \text{ if } j = 0, n_0 \gt 0 \\
[f(j-1) + 1, f(j)] & \text{ if } j \gt 0
\end{cases} \tag{4}\label{eq4A}$$
For $j \gt 0$, the # of factors of $p$ in the product of the elements of $g(j)$ is given by
$$\begin{equation}\begin{aligned}
\nu_p\left(\prod_{i=f(j-1)+1}^{f(j)}i\right) & = \sum_{i=f(j-1)+1}^{f(j)}\nu_p(i) \\
& = \sum_{i=1}^{n_jp^j}\nu_p(i) + \sum_{i=n_jp^j + 1}^{f(j)}\nu_p(i) - \sum_{i=1}^{f(j-1)}\nu_p(i) \\
& = \sum_{i=1}^{n_jp^j}\nu_p(i) + \sum_{i=1}^{f(j-1)}\nu_p(n_jp^j + i) - \sum_{i=1}^{f(j-1)}\nu_p(i) \\
& = \sum_{i=1}^{n_jp^j}\nu_p(i) + \sum_{i=1}^{f(j-1)}\left(\nu_p(n_jp^j + i) - \nu_p(i)\right) \\
\end{aligned}\end{equation}\tag{6}\label{eq6A}$$
Note $\nu_p(m)$ is equal to the power of the right-most (i.e., smallest power) non-zero term in the base $p$ expansion of $m$. Since $\forall \; 1 \le i \le f(j-1)$ the right-most non-zero term in the base $p$ expansion of $n_jp^j + i$ and $i$ are the same, you get $\nu_p(n_jp^j + i) - \nu_p(i) = 0$. Thus, the second summation in \eqref{eq6A} is $0$, which means
$$\nu_p\left(\prod_{i=f(j-1)+1}^{f(j)}i\right) = \sum_{i=1}^{n_jp^j}\nu_p(i) \tag{7}\label{eq7A}$$
Among the integers from $1$ to $n_jp^{j}$, there are $n_jp^{j-1}$ with at least one factor of $p$. Among these, there are $n_jp^{j-2}$ integers with at least two factors of $p$. Continue this until you get to there being $n_j$ integers with $j$ factors of $p$. Adding these together gives
$$\begin{equation}\begin{aligned}
\sum_{i=1}^{n_jp^j}\nu_p(i) & = \sum_{i=0}^{j-1}n_jp^{i} \\
& = n_j\left(\frac{p^{j} - 1}{p - 1}\right) \\
& = \frac{n_jp^{j} - n_j}{p - 1}
\end{aligned}\end{equation}\tag{8}\label{eq8A}$$
With $j = 0$, \eqref{eq8A} gives $0$ so it also applies for $g(0)$. Since each set of $g(j)$ in \eqref{eq4A} is disjoint, and the union of them is all the integers up to $n$, then summing \eqref{eq8A} for $0 \le j \le l$ gives the number of factors of $p$ in the product of all integers up to $n$, i.e., $\nu_p(n!)$. Thus,
$$\begin{equation}\begin{aligned}
\nu_p(n!) & = \sum_{j=0}^{l}\left(\frac{n_jp^{j} - n_j}{p - 1}\right) \\
& = \frac{\sum_{j=0}^{l}n_jp^{j} - \sum_{j=0}^{l}n_j}{p - 1} \\
& = \frac{n - s}{p - 1}
\end{aligned}\end{equation}\tag{9}\label{eq9A}$$
Comment: Thank you! Though as far as I can see, this proof is heuristically not much different from the proof linked in Wikipedia. (Also, as in the other post, I think "smallest non-zero term" is ambiguous and "right-most" is better - alternatively, one could simply argue with $\pmod{p^j}$ which is of course exactly the same argument.)
Comment: @QiZhu You're welcome. As with the other answer, I've fixed the wording re: the right-most or lowest power term which is non-zero.
Answer: As Daniel Fischer's question comment outlines, consider the sum of digits in base $b$ of $i - 1$ compared to $i$. The smallest power (i.e., right-most) non-zero digit of $i$ is decreased by $1$ and all of the $0$ terms, if any, to the right of it are changed to $b - 1$. For example, in base $10$, you get $2100 - 1 = 2099$. Since the number of $0$ terms to the right of the lowest power non-zero one is $\nu_{b}(i)$, this means there's a net change in the digits sum of $-1 + (b - 1)\nu_{b}(i)$. Having $s_p(j)$ be the sum of digits of $j$ in base $p$, this gives for any $i \gt 0$ that
$$\begin{equation}\begin{aligned}
s_p(i - 1) & = s_p(i) - 1 + (p - 1)\nu_{p}(i) \\
(p - 1)\nu_{p}(i) & = - s_p(i) + s_p(i - 1) + 1 \\
\nu_{p}(i) & = \frac{- s_p(i) + s_p(i - 1) + 1}{p - 1} \\
\nu_{p}(i) & = \frac{i - s_p(i) + s_p(i - 1) + 1 - i}{p - 1} \\
\nu_{p}(i) & = \frac{(i - s_p(i)) - ((i - 1) - s_p(i - 1))}{p - 1} \\
\end{aligned}\end{equation}\tag{1}\label{eq1B}$$
Since
$$\nu_p(n!) = \sum_{i = 1}^{n}\nu_p(i) \tag{2}\label{eq2B}$$
then \eqref{eq1B} shows \eqref{eq2B} is summing a telescoping series. Thus, each first positive term cancels with the negative term of the next summation item, so all which is left is the positive term of the largest summation item, i.e., $n - s_p(n)$, and the negative term of the first summation item, i.e., $0$. Thus, \eqref{eq2B} becomes
$$\nu_p(n!) = \frac{n - s_p(n)}{p - 1} \tag{3}\label{eq3B}$$
Comment: Very nice :-) There is a little error/typo (or maybe just ambiguous language): Not the smallest non-zero digit is changed but rather the right-most non-zero digit. E.g. $1200 - 1 = 1199$ in base $10$.
Comment: @QiZhu Thanks for pointing out that issue. I had worded it improperly as I meant the lowest power, i.e., right-most, non-zero digit. I've now updated the answer to make this more clear.


Excel formula -> how to change SUMPRODUCT formula to skip null cells

Question: context is
I am using adjusted sumproduct formula to calculate weighted average.
problem is
sumproduct includes empty cells in arrays. => weighted average is calculated incorrectly.
question is
How to edit sumproduct to exclude empty cells in arrays?
alternatively
Is there another clean and neat solution?
Comment: You can normally solve this kind of thing using arrays. Could you post your current formula so I can gauge its complexity?
Answer: In the sumproduct, to exclude empty cells, suppose you're using it on range A1:A100, you could do the following:
= Sumproduct((A1:A100),--(A1:A100<>""))

That second criteria will ensure that you're only looking at cells that have a value in them...
As an explanation (A1:A100<>"") will return an array of True False, where, if there is a value in the cell, it returns true, otherwise, false. Then, including the -- before it, it converts True/False to 1/0. So, in effect, you're multiplying empty cells by a zero (excluding from the formula) and non-empty cells by 1 (including them in the formula).
The --(logical statement for my array) is a very useful trick to use with SumProduct() in MANY different ways!!


12 String guitar going out of tune around the 8th fret on the high e, b and g

Question: I just bought my 12 string guitar and the g,b and high e string go out of tune when i play it around the 8th fret i'm really getting worried. I'm wondering if its a problem with the type of strings it has
Comment: It is not a problem with your strings. It may be a problem with your intonation. Have a look at the questions in the intonation tag.
Answer: It's all but impossible to play 12 strings in tune. The problem is usually the intonation. Each string needs to be a subtly different length - even on a humble 6 string, you'll notice each saddle is placed differently. That's easy on an electric, solved by having 6 separate saddles. Even acoustics get round this by having a sort of slanting bridge.
Problem's caused by the gauge of each string differing. With 12 strings, the top two pairs are o.k., as they're the same gauge, but the 3rd strings are rather different, and a compromise is used, that's often exacerbated further up the neck, as they get more and more out with each other.
Of course, it may just be that it's been set up for one gauge of strings, and those were changed with no re-set up.
Comment: I think that a lot of older 12-string acoustic guitars ignored the intonation issue altogether.
Answer: I recently learned that if your tuner key is loose, it will affect tuning. It can be tightened and therefore the string will stay in tune longer.
Answer: Usually the guitarneck gets bent because of the strength of the strings:. "If your string and sixth fret form a gap larger than 1/64th of a inch (.4 mm), the neck is warped. Hold the sixth string at the first fret and slowly slide down the fretboard with your other hand. As you slide down the frets, if the gap at your sixth fret decreases, the neck is warped and will need to be straightened."
https://www.google.com/url?sa=t&source=web&rct=j&url=https://m.wikihow.com/Fix-a-Warped-Guitar-Neck%3Famp%3D1&ved=2ahUKEwiwovLv0eHfAhVSPFAKHQf4AXgQFjAKegQIBBAB&usg=AOvVaw18j7DPXEThRTkKY_Pvrcsv&ampcf=1&cshid=1547069287502


How do I PUT update on a node using services 3

Question: I have a node with field_order_status field(not required) in list(text) type and radio button widget and I want to update a node(nid:95) but my sample JSON PUT content(application/json) throws Status 406 Error:
<code>{"form_errors":{"field_order_status][und":"An illegal choice has been detected. Please contact the site administrator."}}
</code>
my content is:
<code>{
  "field_order_status":{
    "und":[
      {
        "value": "1"
      }
    ]
  }
}
</code>
sample url:
<code>http://localhost/caesarschickencms/createorder/node/95
</code>
Services 3.4, Drupal 7.22
Notes:
When I tried replacing und with other values like 'en', it accepts but not updates, refer to drupal 7 + services 3 - inserting nodes with select fields
And Devel page vars dump:

What would be missing?
Answer: What Services version do you use?
Since Services 7.3.4 we deen to set Cookie & X-CSRF Token on header for every (PUT/POST) execution
Please check this comment too
https://drupal.org/comment/6491362#comment-6491362
Answer: I don't think it's an issue with X-CSRF Token because the error send by server will be different.
But Drupal expect a value like "payment_to_valid", "order_shipping", "checkout_login" or "Pending".


Drupal Pager Error Causing WSOD When Viewing Term or Edit Term

Question: I have recently been through the ordeal of updating D6 to D7. Things went better than I had previously encountered but I have a problem thats really holding me back and I can't work out how to sort it.
When I try to view a taxonomy/term/ page or edit a term I get a WSOD. I managed to show the error which was:

Fatal error: Call to a member function use_pager() on a non-object in /home/oddeba/public_html/onlinebanter.co.uk/sites/all/modules/views/includes/view.inc on line 690

Line 690:
    function init_pager() {
         if (empty($this->query->pager)) {
           $this->query->pager = $this->display_handler->get_plugin('pager');

        Line 690>>>  if ($this->query->pager->use_pager()) {
            $this->query->pager->set_current_page($this->current_page);
           }

Things are fine with Views disabled. I can for the life of me think how I needed a pager about my taxonomy before.
Could anyone suggest anything that could be causing it?
Comment: Is this a D6 view upgraded to D7?
Comment: reverted taxonomy default view and things are fine now :) dont mind me.
Comment: Check Drupal log.
Answer: If you ever run into a WSOD error, follow the directions here and it will generally tell you the file name and the line number that is causing the WSOD. Or, it will tell you that your server resources are too limited (out of memory).
Here are the instructions:
http://drupal.org/node/158043
Or just Google 'Drupal WSOD' and it's the first link on the SERP.
Comment: As he says above, the problem is not a generic WSOD but a specific error.
Answer: I just encountered this use_pager() problem again. This time with the frontpage view. I solved it by going to the view, opening the pager settings and choosing the same option again, then saving the view.


How do you check that servers/pcs are not infected

Question: Simple question. Developers PCs have to have free access to network, including servers etc., and they have to have administrative access to perform work effectively.
However developers also use a lot of non-Microsoft tools which are available as GPL, LGPL, MIT, free-for-all etc.
Any of them can actually contain harmful code. Even LGPL libraries someone might use for, say, parsing XML.
And we all know that the the very moment someone clicks "yes" on UAC prompt, or does "sudo", the PC/Server can get compromised. And compromised servers can do a lot of bad things, including information leakage, data loss, etc.
How do system administrators battle these problems? Do you trust antivirus software, other tools?
Answer: This is a constant battle that you will never win, but you must keep fighting.  A few things any Microsoft shop should definitely do:

Have a corporate anti-virus software that is enforced using GPO and other means and cannot be disabled or bypassed.  The minute you allow users to turn it off, you're not protected.
Always filter inbound and outbound traffic.  Many malicious applications attempt to "phone home".
Use a proxy for web traffic.  Even if you don't install web filtering software on it, it's handy to see what sort of traffic patterns are emerging (a lot of requests to an unknown asiapac page using the POST method might indicate malicious software, for example).
Lastly, and perhaps most importantly, educate your users.  Really good developers are not always paying attention to security concerns while performing their job duties.  It's helpful to remind people that UAC isn't just a test to see how fast you can click "Yes", and that sudo isn't just a polite way to start all of your commands.

Good luck.. :)
Answer: I sincerely hope these devs have local admin only and have only regular user accounts in the Active Directory.
Devs may need access to servers etc, but if you're not doing so already, you can use a separate VLAN for the dev environment; no access to production servers, only to dev/qa/staging.
Have the devs use another workstation to access regular, production servers.
Alternatively, and less securely, you can try to separate things at the logical level (e.g. different Active Directory forest, maybe domain).
If devs do have/get access to production systems, increase your logging and monitoring of prod systems and do some user education: "Why did you log on to that production database and copy the table with all password hashes?" kind of thing.
Note: this obviously depends on size & complexity of your organization.
Just a remark: you seem to suspect open source tools as being dangerous. They can be, but the real issue is not controlling the storage and use of executable code on dev pcs. Can be closed source too ;)


firebird 2.5 selecting records with date closest to today

Question: I have query result/table with columns: id, date. Like:
id    ,     date
0001  , 2012.01.20
0001  , 2014.10.12
0001  , null
0001  , 2017.05.21
0001  , 2017.08.15
0002  , null
0002  , 2013.06.05
0002  , 2017.08.11
0003  , null
0004  , 2011.12.25
0005  , 2017.12.10
0006  , null
0006  , 2013.04.23
.
.
.
etc...
It's an example - in real world there are couple thousand of id's and over one and half million records. How to find records with closest to today future date (id's 0001, 0002, 0005) and these only with null (id 0003), past dates (id 0004) or null and past dates (id 0006) replace with some text. The result should look like:
id     ,  date
0001   ,  2017.05.21
0002   ,  2017.08.11
0003   ,  'replaced text'
0004   ,  'replaced text'
0005   ,  2017.12.10
0006   ,  'replaced text'
.
.
etc...
I hope this example shows exactly what I need.
Thank you for any clues.
Comment: SO is not a 'code for me'-service. What have you tried and where are you stuck?
Answer: It seem the table has no primary key.
Do not use field names as type name, like "DATE".
Anyway, here is an example how to do that you want, no claims that it is best.
Note that if there is many records,this procedure will be slow, so make sure the correct indexes are placed.
<code>SET TERM ^ ;

create or alter procedure TEMP_TEST_PROC (
    IDATE date)
returns (
    OID varchar(4),
    DATE_BEFORE date,
    DATE_AFTER date,
    CLOSEST_DATE date,
    OTEXT varchar(32))
as
begin
  for select distinct id from test_table_wo_pk
  into :oid
  do
  begin
    date_before = null;
    date_after = null;
    /* get closest past date*/
    select first 1 t."DATE" from test_table_wo_pk t
    where ((t."DATE" <= :idate) and (t.id = :oid))
    order by t."DATE" desc
    into
      :date_before;

    /* get closest future date*/
    select first 1 t."DATE" from test_table_wo_pk t
    where (t."DATE" >= :idate) and (t.id = :oid)
    order by t."DATE"
    into
      :date_after;

    /* bonus - get closest future or past date */

    ... You may check date_before, date_after for NULL here, and set closest_date value here....

    if ((datediff(day,:date_before,:idate)) < (datediff(day,:idate,date_after))) then
      closest_date = :date_before;
    else
      closest_date = :date_after;

    /* set text column */
    if (:date_after is not null) then
      otext = :date_after;
    else
      otext = 'replased text';
    suspend;
  end
end^

SET TERM ; ^
</code>
The result:


Using Joda's LocalDate or DateTime in a Class

Question: I'm attempting to build a generic Event class which models a calendar event.  The event has either a full start date/time, represented by a Joda DateTime, or just a start date, represented by a Joda LocalDate.
I'd like to make Event generic and simplify a lot of the current if an all-day event then do this otherwise do that logic scattered throughout the code but can't find a superclass of DateTime and LocalDate which still contains useful methods to obtain information such as the start date.  Is there some way to do this or do I need to keep my current way of doing things?
Answer: What about replacing DateTime + LocalDate with just:
org.joda.time.Interval

It is essentially a pair of instants which could represent the start/end of any Event.  Should cover 30 minute events, or 5 day events.
Comment: The end result of the processing is an `Interval`, however given that `LocalDate` is not an instant I'm still stuck with the problem of how to handle events which start on the same day regardless of timezone.


Have no MIDI monitoring while playing MIDI Controller or OnScreen Keyboard - Cubase 10.5 Artist

Question: Have no MIDI monitoring while playing MIDI Controller or OnScreen Keyboard

Tracks set: input: "All MIDI In" - output: VST Rack
MIDI is checked as "MIDI thru"
VST Rack - channel 1 - same as track
Tried with both instrument and rack
MIDI Controller registers in side meters upon hitting a note
MIDI filter all are unchcked in MIDI thru
Recording and playback works - no MIDI monitor

Cubase 10.5 Artist - previously Cubase 7.5(LE) where everything worked properly
Answer: If all the inputs are set up correctly, I guess we need to look at the outputs.
Is the 'audio' channel for the VST instrument assigned to the Stereo Out bus?   Is the Stereo Out bus assigned to a physical audio output on your system?
Comment: Yes all set to my Line 6 Helix, input output are working correctly over audio tracks and midi tracks. The problem is when I try to write the MIDI notes or play them the VST Rack/Instrument do not play, but when I activate the session play they do.


Python selecting multiple ranges with numpy\pandas

Question: Is there anyway to select multiple ranges in numpy arrays or pandas dataframe efficiently all in one go?
import pandas as pd
import numpy as np
from time import time

data = pd.DataFrame(np.random.sample((10000,10)))

%timeit -n 10000 result = pd.concat((data[100:150], data[200:300]))
10000 loops, best of 3: 1.47 ms per loop

In the above example, how can I select from 100 to 150 and 200:300 without using concat? Is this even possible?
The above operation, has a bottleneck when using pd.concat and can eventually been speed up using np.vstack...but still I'd like to select the two ranges all at once without copy the underling data as concat would do.
TIME is crucial, as I'd like to get as closer as possible as the time you'll get if you access directly to the continuos range as below:
%timeit -n 10000  result = data[100:150]
10000 loops, best of 3: 94 µs per loop

Answer: There are a few approaches I can think of.  We can try them and see which is fastest.  However, you aren't going to be able to avoid a copy.  There is no way to handle discontinuous ranges without a copy.
concat
>>> %%timeit -n 10000  data = pd.DataFrame(np.random.sample((10000,10)))
... result = pd.concat((data[100:150], data[200:300]))
...
10000 loops, best of 3: 3.81 ms per loop

List of indexes
>>> %%timeit -n 10000  data = pd.DataFrame(np.random.sample((10000,10)))
... result = data.iloc[list(range(100, 150))+list(range(200, 300))]
...
10000 loops, best of 3: 479 µs per loop

Logical indexing:
>>> %%timeit -n 10000  data = pd.DataFrame(np.random.sample((10000,10)))
... result = data[((100 <= data.index) & (data.index < 150)) |
...               ((200 <= data.index) & (data.index < 300))]
...
10000 loops, best of 3: 580 µs per loop

slice and drop
>>> %%timeit -n 10000  data = pd.DataFrame(np.random.sample((10000,10)))
... result = data[100:300].drop(np.arange(150, 200))
...
10000 loops, best of 3: 1.22 ms per loop

So it seems like providing a list of indexes or logical indexing are the fastest, with roughly equivalent speed (I wouldn't put any weight on a speed difference that small).
Comment: When using `%%timeit`, the code on the `%%timeit` line is considered setup code and is not counted in the timing.  I do it this way to make sure that the data is re-generated each repeat.   `pandas` and/or `numpy` does some caching that screws up the timing if I don't do it this way.
Comment: Why are you including creation of the data in your `timeit` loop?
Comment: Interesting.  Thanks for your response.
Comment: thanks for extensive comment! So there is no way to get any close to the time you'll get if you access directly to a continuos range? I've edited my answer to include the timing of (%timeit -n 10000  x = data[100:150]; 10000 loops, best of 3: 94 µs per loop) as the indentation in the comment is orrible
Comment: @AlessandroMariani  I am afraid not. You can think of numpy arrays (which pandas uses) as a contiguous block of memory, with the `nth` element `n` being in the `nth` region of memory in that black (technically it only has to be strided).  The algorithms that numpy uses for fast computation require this.  A slice is just a "view" into a part of that memory block without having to copy anything.  But in order for it to work like an array it still has to be contiguous.  If you want to use non-contiguous pieces, these need to be copied to a new contiguous block of memory, which is slow.
Comment: I see, the alternative would be use boolean indexing which apparently is slower than using list of indexing... and probably would also depends on how many rows are selected. thanks!
Comment: As I said, I wouldn't put any credence in the difference between the list and boolean indexing.  The timings depend a large part on what is going on in the computer at the time so they jump around quite a bit.  They are essentially the same speed within the margin of error of the test.  The memory copy is going to be the big performance penalty, and it will be the same in both cases.
Answer: You can combine boolean conditions, and pass them to the subscript operator:
data[((100 <= data.index) & (data.index < 150)) | ((200 <= data.index) & (data.index < 300))]

(Note the parentheses, BTW - they are unseemly, but the order of precedence requires them.)
Answer: I believe you first need to make a list of the target rows and then use iloc.
rows = [i for i in list(range(100, 150)) + list(range(200, 250))]
>>> data.iloc[rows, :]
            0         1         2         3         4         5         6         7         8         9
100  0.936412  0.875215  0.626169  0.362366  0.086108  0.709103  0.748132  0.696450  0.814539  0.502694
101  0.011131  0.733182  0.127739  0.743762  0.954454  0.018809  0.119522  0.319173  0.546778  0.982340
102  0.412659  0.977685  0.981917  0.319247  0.626653  0.845410  0.828058  0.506033  0.283324  0.495679
..        ...       ...       ...       ...       ...       ...       ...       ...       ...       ...
247  0.827967  0.803476  0.637800  0.603473  0.968779  0.976671  0.747728  0.029828  0.391113  0.381155
248  0.394331  0.120555  0.875771  0.529207  0.143756  0.334991  0.989489  0.584157  0.730615  0.187992
249  0.634841  0.624685  0.746429  0.374769  0.632195  0.922843  0.200508  0.024452  0.223971  0.457757

[100 rows x 10 columns]

%timeit rows = [i for i in list(range(100, 150)) + list(range(200, 300))]; data.iloc[rows, :]
1000 loops, best of 3: 283 µs per loop

%timeit pd.concat([data[100:150], data[200:300]])
1000 loops, best of 3: 927 µs per loop

Comment: @AmiTavory You can't add ranges like that in Python 3.
Comment: 1. Some of your comprehensions are redunant: it's just `range(100, 150) + range(200, 250)` (shorter too). 2. IINM, you're moving from pandas speeds to Python speeds with what you wrote.
Comment: @AmiTavory Thanks.  I didn't know one could add ranges like that.
Comment: @TheBlackCat Thanks. So in Py3 it would be `list(range(...)) + list(range(...))`?
Comment: @AmiTavory Yes, although that will work equally well in Python 2 and Python 3.  I try to write my code as generically as possible.