Mais de um cursor na procedure Mysql

Question: Preciso executar mais de um cursor na mesma procedure? Isso é possível?
begin
DECLARE done INT DEFAULT 0;
declare v_dia, v_rotina int;
declare v_hora time;
declare v_saldo, v_valor decimal(5,2);
declare v_flag tinyint;
declare v_id varchar (100);

DECLARE sexta CURSOR FOR (
select saldo, hora, flag, valor, sexta, id_rotina, id
from tbl_cartao
inner join tbl_dias_uso
on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
inner join tbl_rotina
on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
inner join tbl_usuarios
on tbl_usuarios.id = tbl_cartao.id_usuario
where dayofweek(now()) = sexta and  hora <=  curtime() and flag = 0
);

DECLARE domingo CURSOR FOR (
select saldo, hora, flag, valor, domingo, id_rotina, id
from tbl_cartao
inner join tbl_dias_uso
on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
inner join tbl_rotina
on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
inner join tbl_usuarios
on tbl_usuarios.id = tbl_cartao.id_usuario
where dayofweek(now()) = domingo and hora <=  curtime() and flag = 0
);

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

OPEN sexta;
REPEAT
FETCH sexta INTO v_saldo,v_hora,v_flag, v_valor, v_dia,v_rotina, v_id;
IF NOT done THEN

update tbl_cartao
set saldo = v_saldo - v_valor
where v_id = id_usuario and v_dia =
dayofweek(now());

insert into tbl_desconto_usuarios (id_usuario,saldo_anterior, saldo_apos, data_desconto,hora_desconto)
values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

update tbl_rotina
set flag = 1
where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

END IF;
UNTIL done END REPEAT;
CLOSE sexta;

OPEN domingo;
REPEAT
FETCH domingo INTO v_saldo,v_hora,v_flag, v_valor, v_dia,v_rotina, v_id;
IF NOT done THEN

update tbl_cartao
set saldo = v_saldo - v_valor
where v_id = id_usuario and v_dia =
dayofweek(now());

insert into tbl_desconto_usuarios (id_usuario,saldo_anterior, saldo_apos, data_desconto,hora_desconto)
values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

update tbl_rotina
set flag = 1
where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

END IF;
UNTIL done END REPEAT;
CLOSE domingo;

END

Comment: Não sei se está certo, porém ele não executa nunca os dois cursores
Comment: OPEN domingo;
REPEAT
FETCH domingo INTO v_saldo, v_hora,v_flag, v_valor, v_dia, v_rotina, v_id ;
IF NOT done THEN

update usuarios
set saldo = v_saldo - v_valor
where v_id = id and v_dia = dayofweek(now());

insert into desconto_usuarios (id_usuario,saldo_antes, saldo_apos, data_desconto,hora_desconto)
values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

update rotina
set flag = 1
where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

END IF;
UNTIL done END REPEAT;
CLOSE domingo;
Comment: Em seguida eu colo isso
OPEN segunda;
REPEAT
FETCH segunda INTO v_saldo, v_hora,v_flag, v_valor, v_dia, v_rotina, v_id ;
IF NOT done THEN

update usuarios
set saldo = v_saldo - v_valor
where v_id = id and v_dia = dayofweek(now());

insert into desconto_usuarios (id_usuario,saldo_antes, saldo_apos, data_desconto,hora_desconto)
values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

update rotina
set flag = 1
where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

END IF;
UNTIL done END REPEAT;
CLOSE segunda;
Comment: pronto poste na pergunta
Answer: é possível porém você tem que trabalhar de maneira diferente o loop, não apenas verificando a variável done, pois quando o primeiro cursor for executado ele não irá executar o segundo, então trabalharemos de outra maneira para setar se está completo ou não vamos verifica quantos registros percorrer e vamos setando um contador e quanto passar por todas as linhas setamos as variáveis done1 e done2, ficando assim:
begin
    DECLARE done INT DEFAULT 0;
    DECLARE done2 INT DEFAULT 0;
    DECLARE total_cur1 INT DEFAULT 0;
    DECLARE total_cur2 INT DEFAULT 0;
    DECLARE qtd_cur_1 INT DEFAULT 0;
    DECLARE qtd_cur_2 INT DEFAULT 0;
    declare v_dia, v_rotina int;
    declare v_hora time;
    declare v_saldo, v_valor decimal(5,2);
    declare v_flag tinyint;
    declare v_id varchar (100);

    DECLARE sexta CURSOR FOR (
                                                select saldo, hora, flag, valor, sexta, id_rotina, id
                                                from tbl_cartao
                                                inner join tbl_dias_uso
                                                on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
                                                inner join tbl_rotina
                                                on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
                                                inner join tbl_usuarios
                                                on tbl_usuarios.id = tbl_cartao.id_usuario
                                                where dayofweek(now()) = sexta and  hora <=  curtime() and flag = 0
    );

    DECLARE domingo CURSOR FOR (
                                                        select saldo, hora, flag, valor, domingo, id_rotina, id
                                                        from tbl_cartao
                                                        inner join tbl_dias_uso
                                                        on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
                                                        inner join tbl_rotina
                                                        on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
                                                        inner join tbl_usuarios
                                                        on tbl_usuarios.id = tbl_cartao.id_usuario
                                                        where dayofweek(now()) = domingo and hora <=  curtime() and flag = 0
    );

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

    SELECT
            COUNT(*)
    INTO total_cur1
    FROM tbl_cartao
    inner join tbl_dias_uso
    on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
    inner join tbl_rotina
    on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
    inner join tbl_usuarios
    on tbl_usuarios.id = tbl_cartao.id_usuario
    where dayofweek(now()) = sexta and  hora <=  curtime() and flag = 0 ;

    SELECT
                COUNT(*)
    INTO total_cur2
    FROM tbl_cartao
    inner join tbl_dias_uso
    on tbl_dias_uso.id_usuario = tbl_cartao.id_usuario
    inner join tbl_rotina
    on tbl_rotina.id_usuario = tbl_cartao.id_usuario and tbl_rotina.tipo = tbl_dias_uso.tipo
    inner join tbl_usuarios
    on tbl_usuarios.id = tbl_cartao.id_usuario
    where dayofweek(now()) = domingo and hora <=  curtime() and flag = 0 ;

    OPEN sexta;
        REPEAT
            FETCH sexta INTO v_saldo,v_hora,v_flag, v_valor, v_dia,v_rotina, v_id;
            IF NOT done THEN

                update tbl_cartao
                set saldo = v_saldo - v_valor
                where v_id = id_usuario and v_dia =
                dayofweek(now());

                insert into tbl_desconto_usuarios (id_usuario,saldo_anterior, saldo_apos, data_desconto,hora_desconto)
                values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

                update tbl_rotina
                set flag = 1
                where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

                IF total_cur1 = qtd_cur_1 THEN
                    SET done = 1;
                END IF;

            END IF;

            SET qtd_cur_1 = qtd_cur_1 + 1;
        UNTIL done END REPEAT;
    CLOSE sexta;

    OPEN domingo;
        REPEAT
            FETCH domingo INTO v_saldo,v_hora,v_flag, v_valor, v_dia,v_rotina, v_id;
            IF NOT done2 THEN

                update tbl_cartao
                set saldo = v_saldo - v_valor
                where v_id = id_usuario and v_dia =
                dayofweek(now());

                insert into tbl_desconto_usuarios (id_usuario,saldo_anterior, saldo_apos, data_desconto,hora_desconto)
                values(v_id, v_saldo, v_saldo - v_valor, CURRENT_DATE(),CURRENT_TIME() );

                update tbl_rotina
                set flag = 1
                where hora <= curtime() and v_dia = dayofweek(now()) and v_id = id_usuario;

                IF total_cur2 = qtd_cur_2 THEN
                    SET done2 = 1;
                END IF;

                SET qtd_cur_2 = qtd_cur_1 + 2;
            END IF;
        UNTIL done2 END REPEAT;
    CLOSE domingo;

END

Comment: Cara, muito obrigado só não entendi na parte do select count antes de abrir o cursor
Comment: E o mysql cai toda hora que roda essa procedure, sobrecarrega

Mais de um cursor na procedure Mysql


Force the module "legal" to show a "form_set_error" on path /user/register

Question: I'm using the "legal" module version 6.x-8.5.
This is a great module, but i think there's a form_set_error() message needed, to show the user which's trying to register, why registering cannot be applied, if he forget to click the required checkbox(es).
I'm looking for a possibility to get this working.
Does anybody know where to implement this function(hardcoded, if there isn't a other solution) in the module?
I also tried to do this with rules forms, with this rule:
    array (
  'rules' =>
  array (
    'rules_register_ckeck_agb' =>
    array (
      '#type' => 'rule',
      '#set' => 'event_user_register_form_validate',
      '#label' => 'Register ckeck AGB',
      '#active' => 0,
      '#weight' => '0',
      '#categories' =>
      array (
      ),
      '#status' => 'custom',
      '#conditions' =>
      array (
        0 =>
        array (
          '#settings' =>
          array (
            'element' => 'legal[legal_accept]',
            'value' => '1',
                '#argument map' =>
            array (
              'form' => 'form',
              'form_state' => 'form_state',
            ),
          ),
          '#type' => 'condition',
          '#name' => 'rules_forms_condition_element_value',
          '#info' =>
          array (
            'label' => 'Form element \'legal[legal_accept]\' value check',
            'arguments' =>
            array (
              'form' =>
              array (
                'type' => 'form',
                'label' => 'Formular',
              ),
              'form_state' =>
              array (
                'type' => 'form_state',
                'label' => 'Form state',
              ),
              'element' =>
              array (
                'type' => 'string',
                'label' => 'Form element ID',
                'description' => 'ID of the form element to be targeted. Examples on the "Create Story" form: "title" for the title field or "body_field[body]" for the body field.',
              ),
              'value' =>
              array (
                'type' => 'string',
                'label' => 'Value(s)',
                'description' => 'Value(s) assigned to the form element. If the form element allows multiple values, enter one value per line.',
              ),
            ),
            'module' => 'Rules Forms',
          ),
          '#weight' => 0,
          '#negate' => 1,
        ),
      ),
      '#actions' =>
      array (
        0 =>
        array (
          '#weight' => 0,
          '#info' =>
          array (
            'label' => 'Set form error on element \'legal[legal_accept]\'',
            'arguments' =>
            array (
              'form' =>
              array (
                'type' => 'form',
                    'label' => 'Formular',
              ),
              'element' =>
              array (
                'type' => 'string',
                'label' => 'Form element ID',
                'description' => 'The element that should be marked. Examples on the "Create Story" form: "title" for the title field or "body_field[body]" for the body field.',
              ),
              'message' =>
              array (
                'type' => 'string',
                'label' => 'Nachricht',
                'description' => 'The message that should be displayed to the user.',
              ),
            ),
            'module' => 'Rules Forms',
          ),
          '#name' => 'rules_forms_action_set_error',
          '#settings' =>
          array (
            'element' => 'legal[legal_accept]',
            'message' => 'Please Confirm the...',
            '#argument map' =>
            array (
              'form' => 'form',
            ),
          ),
          '#type' => 'action',
        ),
      ),
      '#version' => 6003,
    ),
  ),
)

But this also does not the job, it should do.
Does anybody know what I'm maybe doing wrong here?
Thanx for all your suggestions.
regards
dennis605
Answer: I've posted my reply to you problem in the Legal issue you created.
I'll go over how you would create an additional validation that will throw a form_set_error()
Create a custom module with this
function example_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == 'user_register') {
      $form['legal']['legal_accept']['#element_validate'] = array('_example_custom_field_validate');
    }
}

function _example_custom_field_validate($element, &$form_state) {
   if (empty($element['#value'])) {
     form_error($element, t('This is my custom message if `Terms & Conditions` is not checked off.'));
   }
}

If you don't see the message now,  I am worried that you have error messages turned off.
Comment: works like a charm! Thanks for your support! That's exactly what i was looking for.


UItableview shared view

Question: I'd like to know if someone there in the community has ever implemented 2 UItableView in on single view, I've searched a lot trough google but i'm not sure if I'm using the correct words. What I need is lo look like as the Facebook menu where shows 2 table views, here is an screenshot of my idea. Any ideas/tutorials/blogs you can provide me will be useful, Thanks a lot!
http://a1.mzstatic.com/us/r1000/119/Purple/eb/62/0a/mzl.uvhmahke.320x480-75.jpg
Comment: Are you looking for how to have different sections in a UITableview? That is what the image looks like
Comment: yep its sections... not multiple uitableviews
Comment: hi guys, yes, thats why I wasnt so sure how to call them. But yes I'm looking how to implement UItableView in sections, do you have any info that can point me in the right direction? thanks :)
Answer: UITableView is simply a subclass of UIScrollView, which is a subclass of UIView, so, yes, you should be able to have more than one tableView in a single view.  The only 'gotcha' with this is that your delegate and datasource callback methods for the table views need to either be broken out explicitly in each method (using if(tableView.tag == 0) or something) or either have completely different objects be the datasource and delegate callback methods.  The tableviews don't care where they are located.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView.tag == 0){
        //do something for first tableView
    }
    else{
        //do something for other tableView
    }
    return cell;
}

The image you posted does not have two tableViews in a single view.  It looks like there are two tableViews in two separate views, which would more than likely have completely different delegate and datasources.

UItableview shared view


Variable is not incrementing correctly

Question: I want to add numbers (nums) in my distCasas array but idx is inscrementing wrong. I stay with nums in index
0, 2, 4, ...

not
0, 1, 2, ...

The code:
int numCasas, idx, distCasas[10], nums;

scanf("%d", &numCasas);

for (idx = 0; idx < numCasas; idx++)
{
    scanf("%d", &nums);

    distCasas[idx] = nums;
    idx++;
}

Comment: you are incrementing the idx variable two times per iteration of the for-loop. once in the loop-header itself and once at the bottom of the loop.
Comment: Did this help? If it did, it's generally seen as polite to accept an answer.
Answer: You are incrementing idx twice. Get rid of the second idx++ so that your code looks like the following.
scanf("%d", &numCasas);

for (idx = 0; idx < numCasas; idx++)
{
    scanf("%d", &nums);

    distCasas[idx] = nums;
}

Comment: if u do this he will put numbers always in index 1 and dont add a lot of numbers in array...
Comment: @rubcpires: No, as `idx` is incremented exactly once per loop, by the expression `idx++` in the loop's head.
Answer: You are incrementing idx twice. Once inside the {} of the for loop and once inside the () of the for loop.
Remove one of them, preferably the one inside the {} part.
for (idx = 0; idx < numCasas; idx++)
{
    scanf("%d", &nums);
    distCasas[idx] = nums;
}

Variable is not incrementing correctly


XMPP API for Google App Engine connection failure

Question: I have failed completely to get the App Engine XMPP API in an app engine app to talk to an external XMPP Openfire server running on an instance on Compute Engine. I have equally failed to connect with the app engine app from a free jabber server (jabber.at). In both cases the error message returns that the remote server cannot be found, or not found on port 5269. Yet a ncat scan show that 5269 is open on the app engine app.
I have read the Google tutorial, where it says: "The basic sequence of events will go like this: * A user adds firstname.lastname@example.com to their buddy list in Google Talk, or another XMPP client. * The user asks the Amazing Crowd Guru a question, by typing "/tellme Does a duck's quack echo? etc."
I have added all variants of names to roster/buddy lists and nothing happens. And I have checked the addresses for both appspot and appspotchat, they are as prescribed. In both cases I have no trouble using the XMPP servers as normal IM servers independently of App Engine.
Is the XMPP API still working? If so, is there some currently working example java code available anywhere? Is there a better more detailed tutorial or other information available than what is provided on the Google App Engine site at the moment? ( I mean, Python and Java fragments, but only a Python complete example. Why? And 'user adds email@example.com to their buddy list' is less than helpful. No other settings or steps required? Really? )
Any help appreciated. I desire to setup a simple IM or chat function on my app.
May 10, 2015
Comment: The doc is quite detailed, and I'd recommend you read it thoroughly, as well as understand the XMPP protocol, if you want to implement such a thing. Here's the [Java source](https://code.google.com/p/googleappengine/source/browse/trunk/java/demos/crowdguru/#crowdguru) if you're interested, I tracked it down with a google search. Sorry I couldn't be of more help. Finally, perhaps you could include some more technical information in your reply, as despite describing that it "doesn't work", there's not a lot to work with for anybody trying to help :) Have a nice day!
Comment: The doc for reference: https://cloud.google.com/appengine/articles/using_xmpp
Answer: It may be worthwhile noting that the XMPP API will be permanently disabled on October 31, 2017: XMPP API Turndown.
Please see Alternatives to the XMPP API for information on how to replicate functionality with other Google Cloud Platform products. For example, developers using the API for direct messaging with XMPP clients can easily build a similar service using virtual machines on Google Compute Engine. For developers using XMPP for realtime data synchronization, we recommend using the Firebase Realtime Database, which is explicitly designed for this purpose.


Universal Approximation Capabilities of Mixture Models

Question: I am looking for two reference incl. proofs showing
1) that a discrete Mixture of Gaussians can asymptotically approximate any (well behaved) continuous density
2) that a discrete Mixture of Bernoullies can asymptotically approximate any density over binary vectors.
Answer: The answer to 1 is in http://a.co/d/jiJJM0y in either chapter 1 or 2, possibly in section 1.18.
There was a statement and reference to a proof that a Gaussian finite mixture was the PDF-version of an asymptotic approximation.
My personal copy of the book is at home, so I can't look it up at the moment.
Answer: A proof of 2 is given in Dunson and Xing 2009: https://www.ncbi.nlm.nih.gov/pubmed/23606777


npm init error - cannot create application

Question: Totally new to NodeJS
when trying to create a new application getting the following :
it does not create instead exits with a error log at the location
H:\app>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg> --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (app)

H:\app>

Contents of error log :
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'init' ]
2 info using firstname.lastname@example.com
3 info using firstname.lastname@example.com
4 verbose stack Error: read EINVAL
4 verbose stack     at exports._errnoException (util.js:1018:11)
4 verbose stack     at TTY.onread (net.js:568:26)
5 verbose cwd H:\app
6 error Windows_NT 6.1.7601
7 error argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "init"
8 error node v6.11.0
9 error npm  v3.10.10
10 error code EINVAL
11 error errno EINVAL
12 error syscall read
13 error read EINVAL
14 error If you need help, you may report this error at:
14 error     <https://github.com/npm/npm/issues>
15 verbose exit [ 1, true ]

any help is much appreciated!
Comment: The first thing you should do is: read the log yourself. Even if you may not understand all the lines of the log... you could (1) get an idea what's wrong, (2) see a message like `use argument xy when z is not working` or as we have it here (3) see a line that clearly said where you should ask for help -> `If you need help, you may report this error at: `
Comment: Does this help ? https://stackoverflow.com/questions/47087759/getting-error-einval-invalid-argument-read-for-npm-install-save-dev-esli
Answer: Try this command: npm init - y
By default the command above will create a default package.json at the current directory. It seems there is some problem regarding access. Once the default package.json file is created you can update it afterwards.
Answer: Also new to NodeJS. I was unable to prompt the creation of a JSON file and even its questionnaire until I ran:
`npm init --yes`

neither: npm init, nor: npm init --y, worked for me. (I'm on Windows ).
Hope this helps newbies !


Unable to DataBind to ListView because of SelectMethod

Question: I have a ListView and i use the SelectMethod of the ListView to populate it. I am looking to apply filters to the data returned from a DropDownList.  The problem that i am facing is i cannot DataBind() on this ListView because of the SelectMethod that is uses.
So figure i would change that and DataBind() the whole time instead of using the SelectMethod(Is that better?). Then the problem I face is my method was grabbing [RouteData]. Right now i am grabbing the [RouteData]as a param to my method. Please see below.
   public IQueryable<Product> GetProducts([RouteData] string categoryName, , [RouteData] string brandName, [RouteData] string subCatName)
{
       //Do stuff
}

below is the ListView
   <asp:ListView ID="productList" runat="server"
     DataKeyNames="ProductID"
     ItemType="E_Store_Template.Models.Product"
     SelectMethod="GetProducts">
       // do stuff
</asp:ListView>

How can I use DataBind() and still grab the [RouteData] from URL? Or do i have to use QueryString to do this?
Answer: I was able to grab the route data by using the code below. This allowed me to grab that data and use Databind() instead of having to use the selectmethod to get this data.
Convert.ToString(Page.RouteData.Values["categoryName"]);

Convert.ToInt32(Page.RouteData.Values["scID"]);


Drupal 7 | Associate dynamic user to a content type

Question: I have a  content type "Article", with a field "author".
Is it possible to assign users with "writers" role dynamically with this field ?
The goal is to display in the article node, a link which redirects to the writer(user) profile.
For example :
-Article Title
-MM/DD/YYYY
-Written by : randomWritter (dynamic link)
Answer: References module will enable you to do that.
It allows you to create fields and associate them with existing content/users on the site. It also features integration with Views so you can have more complex logic to filter out the available options.
The field can also be displayed as an autocomplete.
Comment: Views with Views bulk operations can do the magic


Proof that $\operatorname{ker}(A^{T}A) = \operatorname{ker}(A)$?

Question: Is there a proof that can help me understand why this is the case? I can't conceptualize the reason for this in my mind. Thanks.
Comment: It's a double inclusion, can you prove any?
Comment: All of the things I have tried have been using definitions for $n\times n$ matrix $A$. But I am struggling to prove it for a non-square matrix.
Comment: What's your definition of the kernel of a matrix? Knowing that ought to help.
Answer: For
$\vec v \in \ker A \tag{1}$
we have
$A \vec v = 0, \tag{2}$
whence
$A^TA \vec v = 0, \tag{3}$
showing that $\vec v \in \ker A^TA$; thus $\ker A \subset \ker A^TA$.  To go the other way, note that
$A^TA \vec v = 0 \tag{4}$
implies that
$\vec v^T A^TA \vec v = 0, \tag{5}$
or
$(A \vec v)^T(A \vec v) = 0; \tag{6}$
but $(A \vec v)^T(A \vec v)$ is a scalar quantity which if written out in terms of components is
$0 = (A \vec v)^T(A \vec v) = \sum (A \vec v)_i^2, \tag{7}$
where $(A \vec v)_i$ is the $i$-th component of $A\vec v$.  Thus we must have
$(A \vec v)_i = 0 \tag{7}$
for each and every $i$, implying
$A \vec v = 0 \tag{8}$
or
$\vec v \in \ker A, \tag{9}$
as desired.  QED.
Hope this helps.  Cheers,
and as always,
Fiat Lux!!!
Answer: Hint:  Try using $A^{T}Ax=0\implies x^{T}A^{T}Ax=0\implies (Ax)\cdot(Ax)=0$.
Answer: $$S:=\text{ker}(A^TA) = \{\textbf{x} \in \mathbb{R}^n : (A^TA)\textbf{x} = 0 \}$$
$$S':=\text{ker}(A) = \{\text{x} \in \mathbb{R}^n: A\textbf{x} =0 \}$$
$(1) \ \ S' \subset S$: This is fairly easy since, $A\textbf{x} = 0 \Rightarrow A^TAx =A^T\cdot0 =0$
$(2)$ Can you show $S \subset S'$?
Answer: The key is showing that if $A^T Ax = 0$, then $Ax = 0$.  There is a geometric interpretation to this statement.  Consider the vector $Ax$.  Since it is a linear combination of the columns of $A$, it clearly belongs to the column space of $A$.  And since $A^T (Ax) = 0$, $Ax$ belongs to the nullspace (kernel) of $A^T$.  But the column space of $A$ (also known as the row space of $A^T$) and the nullspace (kernel) of $A^T$ are orthogonal complements, and so in particular, the only vector that belongs to both subspaces is $0$.  Therefore, $Ax = 0$.


Clustering - Different algorithms, same results

Question:
I'm working on my first clustering assignement and I've ran K-Means, Spectral clustering, Hierarchical clustering and Mini-Batch K-Means on same data and received the exact same results (cluster sizes, Calinski-Harabasz criterion, Silhouette). Does anyone have any idea, why would this be? Could this be only dependant on my dataset (6 variables, 2400 entities)?
Initialization of algorithms:
<code>k_means = KMeans(init='k-means++', n_clusters=2)

mini_batch_k_means = MiniBatchKMeans(init='k-means++', n_clusters=2,n_init = 10, max_no_improvement = 10)

hierarchical_clustering = AgglomerativeClustering(n_clusters=2, linkage='ward')

spectral_clustering = SpectralClustering(n_clusters=2)
</code>
Thank you for your answers!
EDIT: Correction, cluster sizes, Silhouette and CH index are the same, but not the actual clusters. The actual clusters are just extremely similar with some differences on borders.
As suggested I projected my data points to 3D plane (with PCA), but as you can see from the image below, there is no clear distinction of the two clusters.

Curiously enough, when I made a decision tree on clustered data (for better visualization), I noticed that the decision tree only uses one variable to classify to which cluster does the data belong.
Comment: Correction, cluster sizes, Silhouette and CH index are the same, but not the actual clusters. The actual clusters are just extremely similar.
Comment: Welcome to the site. Regarding your correction, it's best to edit this into your question, rather than post it as a comment. This way, the question will be self-contained and people reading it can understand the situation more easily.
Comment: If your data has very obvious, well separated clusters, all the methods tens to work. Differences become more pronounced when you have difficult data with noise, non-convex clusters, overlapping clusters, large size and density differences of clusters, etc.
Comment: I edited the question, thank you for your suggestion! @Anony-Mousse thank you for your answer!
Comment: When the scores are "the same", maybe they are equally bad? A Silhouette of 0.2 does not mean much, if anything... But maybe also your evaluation code is wrong.
Answer: It does indeed depend on the dataset. Not knowing the dataset it is difficult to know the exact reason, but most probably the 2 clusters you're trying to estimate do indeed exist in your data and are clearly distinguishable.
To get an insight into whether this is the case, you could try to project the data points onto the 2D or 3D plane (e.g. via PCA or t-SNE) and visually inspect the data.
The difference in clusters you mention may be due to bordering data points fluctuating between both clusters depending on the algorithm initialization. You could run multiple times each algorithm and get an estimate of the average values for your metrics. Another option is to plot different runs of the algorithm (after projecting on 2D) to check for consistency across runs.
In summary, yes. You are obtaining almost identical results because of your dataset but that's not the rule. Distance, density and hierarchical clustering algorithms tend to produce different results (also because of the hyperparameters).
Comment: Thanks! I edited my question and added projection to 3D plane and a detail that might help with resolving this question. To comment your answer, most probably all the algorithms estimate the same clusters, which might indeed suggest that they are there. The reason why I asked the question is because I can't see the difference between them. Furthermore, if I run the algorithms multiple times I always get the exact same cluster sizes, Silhouette and CH index.


Best algorithm to determine added and removed items when comparing to collections

Question: I am looking for the best algorithm to compare 2 collections and determine which element got added and which element got removed.
private string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement, ICollection<UserInvolvement> oldInvolvement)
{
    //I defined the new and old dictionary's for you to know what useful data is inside UserInvolvement.
    //Both are Dictionary<int, int>, because The Involvement is just a enum flag. Integer. UserId is also Integer.
    var newDict = newInvolvement.ToDictionary(x => x.UserID, x => x.Involvement);
    var oldDict = oldInvolvement.ToDictionary(x => x.UserID, x => x.Involvement);

    //I Want to compare new to old -> and get 2 dictionaries: added and removed.
    var usersAdded = new Dictionary<int, Involvement>();
    var usersRemoved = new Dictionary<int, Involvement>();

    //What is the best algoritm to accomplish this?

    return GetInvolvementLogging(usersAdded, usersRemoved);
}

private string GetInvolvementLogging(Dictionary<int, Involvement> usersAdded, Dictionary<int, Involvement> usersRemoved)
{
    //TODO: generate a string based on those dictionaries.
    return "Change in userinvolvement: ";
}

Comment: think simplest and naive algorhitms should be fine. Iterate each dictionary and check presence of item in another dictionary
Comment: What should happen if an entry in the list is changed - ie the key is in both lists, both the Involvement value is different?
Comment: @PaulF , good question! The Involvement is a enum flag. Change in value means flags have been added and or removed. I want those to reflect in the Dictionary.
Comment: @Tony_KiloPapaMikeGolf show definition of class `UserInvolvement`
Answer: Added elements are only in newDict removed only in oldDict
var intersection = newDict.Keys.Intersect(oldDict.Keys);

var added = newDict.Keys.Except(intersection);
var removed = oldDict.Keys.Except(intersection);

EDIT
I modify your base function, dictionaries is no neded.
Example UserInvolvement implementation
class UserInvolvement
{
    public int UserId;
    public string Name;
    public string OtherInfo;

    public override bool Equals(object obj)
    {
        if (obj == null)
        {
            return false;
        }

        UserInvolvement p = obj as UserInvolvement;
        if ((System.Object)p == null)
        {
            return false;
        }

        return (UserId == p.UserId) && (Name == p.Name) && (OtherInfo == p.OtherInfo);
    }

    public override string ToString()
    {
        return $"{UserId} - {Name} - {OtherInfo}";
    }
}

And example function:
private static string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement,
            ICollection<UserInvolvement> oldInvolvement)
{
    var intersection = newInvolvement.Select(x => x.UserId).Intersect(oldInvolvement.Select(x => x.UserId));
    var addedIds = newInvolvement.Select(x => x.UserId).Except(intersection);
    var removedIds = oldInvolvement.Select(x => x.UserId).Except(intersection);

    List<UserInvolvement> modifiedUI = new List<UserInvolvement>();

    foreach (var i in intersection)
    {
        var ni = newInvolvement.First(a => a.UserId == i);
        var oi = oldInvolvement.First(a => a.UserId == i);

        if (!ni.Equals(oi))
        {
            modifiedUI.Add(ni);
        }
    }

    List<UserInvolvement> addedUI = newInvolvement.Where(x => addedIds.Contains(x.UserId)).Select(w => w).ToList();
    List<UserInvolvement> removedUI = oldInvolvement.Where(x => removedIds.Contains(x.UserId)).Select(w => w).ToList();

    StringBuilder sb = new StringBuilder();

    sb.AppendLine("Added");
    foreach (var added in addedUI)
    {
        sb.AppendLine(added.ToString());
    }
    sb.AppendLine("Removed");
    foreach (var removed in removedUI)
    {
        sb.AppendLine(removed.ToString());
    }
    sb.AppendLine("Modified");
    foreach (var modified in modifiedUI)
    {
        sb.AppendLine(modified.ToString());
    }

    return sb.ToString();
}

And my test function:
static void Main(string[] args)
{
    List<UserInvolvement> newUI = new List<UserInvolvement>()
    {
        new UserInvolvement()
        {
            UserId = 1,
            Name = "AAA",
            OtherInfo = "QQQ"
        },
        new UserInvolvement()
        {
            UserId = 2,
            Name = "BBB",
            OtherInfo = "123"
        },
        new UserInvolvement()
        {
            UserId = 4,
            Name = "DDD",
            OtherInfo = "123ert"
        }

    };

    List<UserInvolvement> oldUI = new List<UserInvolvement>()
    {
        new UserInvolvement()
        {
            UserId = 2,
            Name = "BBBC",
            OtherInfo = "123"
        },
        new UserInvolvement()
        {
            UserId = 3,
            Name = "CCC",
            OtherInfo = "QQ44"
        },
        new UserInvolvement()
        {
            UserId = 4,
            Name = "DDD",
            OtherInfo = "123ert"
        }

    };

    string resp = GetInvolvementLogging(newUI, oldUI);
    WriteLine(resp);

    ReadKey();

    WriteLine("CU");
}

Result is:
Added
1 - AAA - QQQ
Removed
3 - CCC - QQ44
Modified
2 - BBB - 123

Comment: See OPs answer to my comment - changes in Value are important too.
Comment: @PaulF so, this is a little more complicated, but doable :) and this info shoud be in question
Comment: Which is why I asked the question :-)
Comment: @BWA : I thought because I mentioned it was a enum flag, that it was logical. But yeah I could have mentioned.
Comment: @BWA I think your variable names got mixed up ("removed" should be "added" and vice versa).
Comment: @CBri thanks, but I'm writing new code with modified ;-)
Comment: @Tony_KiloPapaMikeGolf improved, with modified users
Answer: You could try with Linq:
var usersAdded = newDict.Except(oldDict);
var usersRemoved = oldDict.Except(newDict);

If you need dictionaries as a result you can cast:
var usersAdded = newDict.Except(oldDict).ToDictionary(x => x.Key, x => x.Value);
var usersRemoved = oldDict.Except(newDict).ToDictionary(x => x.Key, x => x.Value);

Comment: Except will return ```IEnumerable```, but OP need ```IDictionary```
Comment: Think combination ```Except``` and ```ToDictionary``` make whole algorithm a little bit slower :)
Comment: If OP only wants to generate a string based on the results (as per comment) - then the GetInvolvementLogging method could take IEnumerable parameters.
Comment: @PaulF could, but then OP should to change variable declaration ```var usersAdded = new Dictionary();``` But yep, it is not a big deal )
Comment: @tym32167: or just directly assign the result as per this answer, no need for the initial assignment.
Comment: @PaulF actually, this is exactly what I meant :)
Answer: Think best algorithm will be
foreach (var newItem in newDict)
    if (!oldDict.ContainsKey(newItem.Key) || oldDict[newItem.Key]!=newItem.Value)
        usersAdded.Add(newItem.Key, newItem.Value);

foreach (var oldItem in oldDict)
    if (!newDict.ContainsKey(oldItem.Key) || newDict[oldItem.Key]!=oldItem.Value)
        usersRemoved.Add(oldItem.Key, oldItem.Value);

Comment: See OPs answer to my comment - changes in Value are important too.
Answer: Finally this is my implementation of GetInvolvementLogging:
(the implementation of the string builder method is irrelevant for my question here)
private string GetInvolvementLogging(ICollection<UserInvolvement> newInvolvement, ICollection<UserInvolvement> oldInvolvement)
{
    //I defined the new and old dictionary's to focus on the relevant data inside UserInvolvement.
    var newDict = newInvolvement.ToDictionary(x => x.UserID, x => (Involvement)x.Involvement);
    var oldDict = oldInvolvement.ToDictionary(x => x.UserID, x => (Involvement)x.Involvement);

    var intersection = newDict.Keys.Intersect(oldDict.Keys); //These are the id's of the users that were and remain involved.
    var usersAdded = newDict.Keys.Except(intersection);
    var usersRemoved = oldDict.Keys.Except(intersection);

    var addedInvolvement = newDict.Where(x => usersAdded.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
    var removedInvolvement = oldDict.Where(x => usersRemoved.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);

    //Check if the already involved users have a changed involvement.
    foreach(var userId in intersection)
    {
        var newInvolvementFlags = newDict[userId];
        var oldInvolvementFlags = oldDict[userId];

        if ((int)newInvolvementFlags != (int)oldInvolvementFlags)
        {
            var xor = newInvolvementFlags ^ oldInvolvementFlags;
            var added = newInvolvementFlags & xor;
            var removed = oldInvolvementFlags & xor;

            if (added != 0)
            {
                addedInvolvement.Add(userId, added);
            }
            if (removed != 0)
            {
                removedInvolvement.Add(userId, removed);
            }
        }
    }

    return GetInvolvementLogging(addedInvolvement, removedInvolvement);
}


POSTFIX how to use a relayserver just for a specific domain?

Question: I have two email servers: mx1.example.com (IMAP, SMTP) and mx2.example.com (SMTP gateway).

mx1.example.com is handling email for example.com,
example.net and example.org.
mx2.example.com is configured as a gateway for mx1.example.com
(I want him to send out all mails that originate from
mx1.example.com)

Now I want to send the emails

from example.com and example.net via mx1.example.com normally
from example.org via mx1.example.com (password auth) to the gateway  mx2.example.com (IP).

How can I configure this?
UPDATE: Please hurry up guys, the bounty expires in 2 days.
To be more clear:
I know how to relay via mx2.example.com (how to send everything via mx2.)
I just have to put the IP of mx2 in relayhost in the main.cf in mx1. But I want to make this selectively, just for example.org.
Answer: you cannot use transport as it is used to transport emails to the MAILBOX, you need to use
sender_dependent_relayhost_maps

it works like this in your main.cf:
relayhost = mx1.example.org, mx2.example.org
relay_domains = example.com, example.org, example.net

smtp_sender_dependent_authentication = yes
sender_dependent_relayhost_maps = hash:/etc/postfix/relaymap

/etc/postfix/relaymap looks like this :
@example.com    mx1.example.com
@example.net    mx1.example.com

@example.org    mx2.example.com

Comment: Need to put all config or with smtp_sender and sender_dependent it's ok?
Comment: Only configuring relay_domains it's enough riight?
Comment: I get the following error message ```postmap: fatal: relayhost parameter setting must not contain multiple values: example1.mail.protection.outlook.com, example2.mail.protection.outlook.com```
Answer: by using the selective relay feature:
on mx1.example.com:

add a line : example.org        smtp:mx2.example.com to /etc/postfix/transport
add a line : transport_maps = hash:/etc/postfix/transport to /etc/postfix/main.cf
run postmap /etc/postfix/transport
run postfix reload

on mx2.example.com :

add mx1.example.com to mynetworks  in /etc/postfix/main.cf
make sure you have something like:
smtpd_relay_restrictions = permit_mynetworks, reject_unauth_destination
in /etc/postfix/main.cf  it is missing
run postfix reload

Postfix to relay mails to other SMTP for particular domain
http://www.postfix.org/STANDARD_CONFIGURATION_README.html
http://www.postfix.org/SMTPD_ACCESS_README.html#lists
https://xdeb.org/post/2017/12/20/mail-relay-mx-backup-and-spam-filtering-with-postfix/
https://www.howtoforge.com/community/threads/postfix-relay-one-domain-to-smarthost-a-all-else-to-smarthost-b.62955/
http://verchick.com/mecham/public_html/spam/relay_recipients.html
Comment: for some reason it is not working. I followed your proposal exactly It does not send the example.org via the mx2. It sends it out via mx1 like all other.
Comment: please look in your `/var/log` folder , there should be files named ''mail.err mail.log` , in which you find essential information on what went  wrong , please also check with `postconf -n` or by manually looking into the files that there is no parameter duplicate , also we might start a chat and you could send snippets of logs as suggested here : https://serverfault.com/questions/466461/postfix-transport-not-getting-triggered
Answer: Check, this settings must be:
mydestination =
relayhost =


Decypt des-sunos5.7 ecncrypted file by using OpenSSL in Linux

Question: One of the shell scripts in our old Solaris 10 server uses below command to decrypt a file.
des-sunos5.7 -d -u -k password enc_filename.tar.gz dec_filename.tar.gz

Now we are migrating to RHEL 6 and have trouble in finding the exact command to decrypt the file. We receive this file from external source and i don't have the cypher they used to encrypt the file.
I have used below commands
openssl enc -d des3 -in filename -out filename;
openssl enc -d -des-cbc -iv 0 -d -in filename -out filename;
openssl enc -des-ede3 -iv o -d in filename -out filename;

I have also tried with -des-ecb, -des-cbc, -des-ede-cbc, -des-ede3-cbc, -desx-cbc, -des. All I get is "Bad magic Number".
$file des-sunos5.7
des-sunos5.7: ELF 32-bit MSB executbale SPARC32PLUS Version 1, V8+ Required, UltraSPARC1 Extensions Required, dynamically linked, not stripped

As per various articles, i understand that i am not using correct decryption cypher here. Can anyone help here to find the correct openssl cypher which can decrypt the file which is encrypted with des-sunos5.7 on a RHEL6 server. we have OpenSSL 1.0.1e.fips installed on Linux server
Comment: `bad magic number` is because `openssl enc` defaults to 'password-based' encryption which derives the actual key from the password by a complicated process based on PBKDF1 using salt which must be in a header in the ciphertext. It *can* do PBE without the salt by specifying `-nosalt` but that isn't terribly likely to be correct for ECB and can't be correct for CBC (because OpenSSL follows original PKCS#5 in deriving the IV but @V's link says Solaris des does CBC with IV all-0).
Comment: Dunno. But OpenSSL tentatively claimed compatibility with Solaris des(1) until [that DES code was thrown out](https://github.com/openssl/openssl/commit/24956ca00f014a917fb181a8abc39b349f3f316f). From old `crypto/des/INSTALL` file: *"des(1) should be compatible with sunOS's but I have been unable to test it."*.
Answer: From the name, I'm guessing that is the des(1) command included with Solaris, that someone pulled forward from Solaris 7 to your Solaris 10 installation (unclear why, as it is also available out of the box from Solaris 10u4 and up, and in SUNWcry before).
des(1) encrypted data with single-DES, but the file format will not match OpenSSL's file format. the des(1) command is quite old. Solaris 10 included the encrypt/decrypt commands with modern ciphers as a replacement.
This article may help you discover more background:
https://blogs.oracle.com/darren/entry/encrypting_files_in_solaris_10
I would decrypt using the des command on Solaris, reencrypt using OpenSSL on Solaris and then transfer the files.  OpenSSL is available on Solaris 10.
Comment: OP is apparently receiving files on an ongoing basis but retiring the Solaris system -- although worst case you could keep Solaris in a VM on the RHEL, used only for this. That blog says single-DES and ECB or CBC with IV all-0 which helps, but doesn't say if the 'password' is actually the key or undergoes any (nontrivial) deriviation.
Comment: I should thank every one for their inputs.
We had reached out sender of the file and asked them to use openssl for encryption. We got an answer saying that we can use ssh and there will be no need of any additional encryption on the file.


Injectivity of composition and its elements

Question: Let $X,Y,Z$ be sets, let $f:X\to Y$, $g:Y \to Z$. If composition of $g\circ f$ is injective, the so is $f$.
This question has been asked many times:
Show that if $g \circ f$ is injective, then so is $f$.
Composition of functions injective implies one of them is injective?
If g(f(x)) is one-to-one (injective) show f(x) is also one-to-one (given that...)
Every answer suggests a proof, where we argue by contrapostive and assume $x\neq x'$ is true and $f(x)=f(x')$ is true. Why is that so? I mean if the injectivity assumption is false, then we could also have the case where $x\neq x'$ is true but $f(x')$ is simply not defined. In this case the injectivity assumption is still false, just as the statement $x \neq x' \Rightarrow 3=5/0$ is false.
Answer: If $f(x')$ is not defined, with $x'\in X$, then $f$ is not a function from $X$ to $Y$.
Answer: Just as a complement: most of these proofs are erroneously called 'proofs by contradiction'.
Actually, they're proofs  'by contrapositive', which are much easier to understand for beginners: they prove that if $f$ is not injective, then $g\circ f$ can't be injective either.
Comment: Thanks, I corrected the mistake!
Answer: A function $f:X\to Y$ is called injective if $f(x)=f(y)\implies x=y$. This is equivalent with showing that $f$ is injective if $x\neq y\implies f(x)\neq f(y)$. Of course, in your example we can not take $x'$ such that $f(x)$ is not defined. That is, if $X$ consists of more than two elements, we can Always pick $x'\in X$ with $x'\neq x$ such that $f(x')$ exists, since otherwise $f$ would not be a function (you can check this using the definition of function). If $X$ consists of only one element, the function is of course injective, so your argument does not break down the proof given in the other posts.


Find Polynomial coefficients

Question: How can I find the real coefficients a,b if the polynomial
$ P(X)=X^4-5X^3+8X^2+aX+b $ is divisible by $ Q(X)=(X-1)^2 $
So if 1 is a solution, I get a+b=-4; where should i look for other roots?
Comment: Show that if Q divides P, then 1 is a root of P'(X).
Comment: @Yilun: you probably meant divide by $(x-1)^2$ first.
Comment: The root is double.
Comment: try: divide by x-1 first, and then divide the rest by x-1 again
Answer: Just compute $Q(x)\cdot(x^2+cx+d)-P(x)=0$ and compare coefficients. This gives
immediately $a=-5$, $b=1$, $c=-3$ and $d=1$.
Answer: If (x-1)^2 divides p(x) it is also root of p'(x) . Therefore 1 is a root of the functions differential by which u can find a then b
Answer: Using synthetic division:
\begin{array}{rrrrrrr}
       & | &   1 &  -5 &   8 &   a     & b \\
     1 & | &   0 &   1 &  -4 &   4 &   a+4 \\
       & + & --- & --- & --- & --- & ----- \\
       &   &   1 &  -4 &   4 & a+4 & a+b+4 \\
\end{array}
So $a+b+4 = 0$.
Dividing again by $(x-1)$ :
\begin{array}{rcrrrr}
       & | &   1 &  -4 &   4 & a+4 \\
     1 & | &   0 &   1 &  -3 &   1 \\
       & + & --- & --- & --- & --- \\
       &   &   1 &  -3 &   1 & a+5 \\
\end{array}
So $a+5= 0$, hence $a = -5$ and $b=1$.

Find Polynomial coefficients


Prove that $\inf(\{A, B\}) = A \cap B$

Question: Say we have the partial order $\subseteq$ over the power set $P(X)$ from the set X. Prove that $\inf(\{A, B\}) = A \cap B$.
So I've started with proving that $\inf(\{A, B\}) \subseteq A \cap B$ as follows:
Take $M = \inf(\{A, B\})$, then by definition $M \subseteq A$ and $M \subseteq B$, so $M \subseteq (A \cap B)$, therefore $\inf(\{A, B\}) \subseteq (A \cap B)$. Is this part of the proof correct? And I could use some help on finding a proof for $A \cap B \subseteq \inf(\{A, B\})$. Thanks.
Answer: You can do a little bit better then that: You don't need to assume additionally, that $\inf(A,B)$ already exists. Simply show that $A\cap B$ has the property of being an infimum:
Certainly $A\cap B \subseteq A$ and $A\cap B \subseteq B$, and if $C$ is another set with $C \subseteq A$ and $C\subseteq B$ then for all $x\in C$ we have $x\in A$ and $x\in B$, hence $x\in A\cap B$. Therefore $C\subseteq A\cap B$. This proves that $A\cap B$ is an infimum of $A$ and $B$.
Answer: Yes, the first part is correct.
For the second part, show that $A \cap B$ is a lower bound for $\{ A, B \}$. Then, by the definition of infimum, $\inf \{ A, B \}$ is larger than any lowerbound.

Prove that $\inf(\{A, B\}) = A \cap B$


Sql server Pivot and create multiple records from one field and split other field

Question: What my data looks like:
Name:   Animals(One-Column):
Bill    Dog, Cat, Horse
Bob     Dog, Giraffe, Snake , Horse

What I need to transform it to:
Name:   Animal:
Bill    Dog
Bill    Cat
Bill    Horse
Bob     Dog
Bob     Giraffe
Bob     Snake
Bob     Horse

I am unsure of the steps to take, there are anywhere from 0 - 100 values in the actual csv field.
You will notice that the csv's are not consistent (Horse is word 3 for Bill but word 4 for Bob), so I need a solution like:
1st Name  1st Word
1st Name  2nd Word
2nd Name  1st Word
2nd Name  2nd Word
2nd Name  3rd Word
...

Comment: This is nothing to do with `PIVOT`. You just need to `CROSS APPLY` on a split function.
Comment: If you have SQL Server 2016, there is a function STRING_SPLIT(), for older versions just google for string splitting functions, there are plenty available to download.
Answer: create function [dbo].[udf_splitstring] (@tokens    varchar(max),
                                         @delimiter varchar(5))
returns @split table (
  token varchar(200) not null )
as
  begin
      declare @list xml

      select @list = cast(''
                          + replace(@tokens, @delimiter, '')
                          + '' as xml)

      insert into @split
                  (token)
      select ltrim(t.value('.', 'varchar(200)')) as data
      from   @list.nodes('/a') as x(t)

      return
  end

  CREATE TABLE #TABLE1
    ([NAME] VARCHAR(4), [ANIMALS] VARCHAR(27))
;

INSERT INTO #TABLE1
    ([NAME], [ANIMALS])
VALUES
    ('BILL', 'DOG, CAT, HORSE'),
    ('BOB', 'DOG, GIRAFFE, SNAKE , HORSE')
;
SELECT * FROM #TABLE1

SELECT NAME ,TOKEN FROM #TABLE1 AA
CROSS APPLY (SELECT * FROM UDF_SPLITSTRING(ANIMALS,','))A

output
name    token
Bill    Dog
Bill    Cat
Bill    Horse
Bob     Dog
Bob    Giraffe
Bob    Snake
Bob    Horse

Comment: Msg 317, Level 16, State 1, Procedure UDF_SPLITSTRING, Line 16 [Batch Start Line 0]
Table-valued function 'NODES' cannot have a column alias.
Comment: Thank you.... so why did .nodes need to be lowercase? What does that have to do with column aliases?
Answer: One method is a recursive CTE:
with cte as (
      select name, animals, 1 as lev,
             left(animals, charindex(',', animals + ',')) as animal
      from t
      union all
      select name, animals, lev + 1,
             left(animals, charindex(',', animals + ',')) as animal
      from cte
      where animals <> ''
     )
select name, animal, lev
from cte;

You may have to set the max recursion option if you actually have 100 items in the list.


How to execute logstash commands from a java program?

Question: I'm using logstash to extract data from log files. I wish to call logstash from a java program. How can I perform such task?
Comment: possible duplicate of [Run Logstash in Java Program](http://stackoverflow.com/questions/35504385/run-logstash-in-java-program)
Comment: What does this have to do with MongoDB? And also, what do you want to achieve? There are HTTP APIs available for Logstash: https://www.elastic.co/guide/en/logstash/current/monitoring.html
Comment: Wow. great. I'm storing the logstash output data directly in a mongoDB database.
Comment: Possible duplicate of [Run Logstash in Java Program](http://stackoverflow.com/questions/35504385/run-logstash-in-java-program)
Answer: This code worked.
<code>        ProcessBuilder b1 = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\elk\\logstash-5.1.2\\bin\" && logstash -f first-pipeline.conf --config.reload.automatic");
        b1.redirectErrorStream(true);
        Process p1 = b1.start();
        BufferedReader r1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
        String line1;
        while (true) {
            line1 = r1.readLine();
            if (line1 == null) { break; }
            System.out.println(line1);
        }
</code>


Get data from table and Insert into another table from while loop

Question: I am having a little issue getting data from a table with while loop. What i want to do is simple I want to take all data from table cart with cookie value from table orders that matches a cookie value and query tables cart to extract data that matches the cookie value in the cart table and place them in table orders_final  . Now this is  . Now the final part after querying cart table with cookie value gotten from order table, i now want to place the data into orders_final table with all that matches that cookie value from order and cart
$zomo = $_COOKIE['shopa']; // this is the cookie that is stored in the cart table and updated when the transaction is successful
$get_products = "SELECT * FROM `cart` WHERE cookie_value = '$zomo'";
$limo = mysqli_query($con, $get_products);

while($colo = mysqli_fetch_array($limo)){
    $product_id = $colo['product_id'];
    $order_quantity = $colo['order_quantity'];
    $cookie_value = $colo['cookie_value'];
    //var $dance is when i update the table with data after payment and data gotten from my payment processing company
    $dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',`reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";
    $uii = mysqli_query($con, $dance);

    if ($uii){
        //this variable insert is where i want to insert all data gotten from cart table above and insert into orders_final, where order table holds the cookie value which was created during shopping which is cookie name shopa held in the variable zomo
        $insert = "INSERT INTO `orders_final`(`product_id`, `cookie_value`, `trx_id`, `order_quantities`) VALUES ('$product_id','$zomo','$r_reference','$order_quantity')";
        $bena = mysqli_query($con, $insert);

        if ($bena){
            $delc = "DELETE FROM `cart` WHERE cookie_value = '$zomo'";
            $tipee = mysqli_query($con, $delc);

            if ($tipee){
                perform_success();
            }
        }
    }
}

Comment: You can probably avoid having two queries and a loop, by doing a `INSERT INTO..SELECT` query instead. Some sensible formatting of the code (indenting properly) would make it a lot easier to read, too.
Comment: You want to do what???
Comment: You're already using an API that supports **prepared statements** with bounded variable input, you should utilize parameterized queries with placeholders (prepared statements) to protect your database against [SQL-injection](http://stackoverflow.com/q/60174/)!
 Get started with [`mysqli::prepare()`](http://php.net/mysqli.prepare) and [`mysqli_stmt::bind_param()`](http://php.net/mysqli-stmt.bind-param).
Answer: A better approach is to run fewer queries, that do more. Instead of selecting an entire table and looping over it to run up to 3 queries per iteration (which quickly becomes a lot of queries!), you can use a INSERT INTO...SELECT query instead. Using a transaction, it's also possible to ensure that everything goes through before committing the changes - so you don't end up deleting something that didn't transfer properly.
The code below has been altered to reduce the amount of queries down to three (and none is looped!), and usage of prepared statements has been implemented.
$stmt = $con->prepare("INSERT INTO orders_final (`product_id`, `cookie_value`, `trx_id`, `order_quantities`)
                                            SELECT product_id, ?, order_quantity, ?
                                            FROM cart
                                            WHERE cookie_value=?");
$stmt->bind_param("sss", $zomo, $r_reference, $zomo);
if ($stmt->execute()) {
    $stmt->close();

    $stmt = $con->prepare("UPDATE orders
                            SET status=?, time=?, date=?, reference=?, transaction_status=?,
                                 transaction_method=?, final_price=?, order_id=?,
                                 currency=?, referrer=?
                            WHERE cookie_bought=?");
    $stmt->bind_param("sssssssssss", $r_status, $r_time, $r_date, $r_reference, $r_transaction_status, $r_transaction_method, $r_final_price, $r_order_id, $r_currency, $r_referrer, $zomo);

    $dance = "UPDATE `orders` SET `status`='$r_status',`time`='$r_time',`date`='$r_date',
    `reference`='$r_reference',`transaction_status`='$r_transaction_status',`transaction_method`='$r_transaction_method',`final_price`='$r_final_price',`order_id`='$r_order_id',`currency`='$r_currency',`referrer`='$r_referrer' WHERE cookie_bought = '$zomo'";

    $stmt = $con->prepare("DELETE FROM cart WHERE cookie_value=?");
    $stmt->bind_param("s", $zomo);
    $stmt->execute();
    $stmt->close();
}

mysqli::prepare()
mysqli_stmt::bind_param()
MySQL INSERT INTO..SELECT


Where does Drupal 7 clear my custom set cookies and how do I stop this?

Question: I have parts of my website that are not controlled by drupal that set cookies.
When I access a drupal-run page, my cookies get cleared. I tried to investigate which script does this by placing print_r($_COOKIE) all over the place in html.tpl.php, but no luck.
Anybody know whats happening here and how I could set my own custom cookies with PHP in drupal template files?
cheers
Answer: Please find more about setting cookies using php setcookie function.
As explained in above link, please look into third and fourth params in above function
Path
The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain. If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.
Domain
The domain that the cookie is available to. Setting the domain to 'www.example.com' will make the cookie available in the www subdomain and higher subdomains. Cookies available to a lower domain, such as 'example.com' will be available to higher subdomains, such as 'www.example.com'. Older browsers still implementing the deprecated » RFC 2109 may require a leading . to match all subdomains.
Please check your code where you are setting cookies matches Drupal Site Domain name and Path where you are trying to access or print them.
You can set cookies in Drupal using user_cookie_save function.
For Example
<code>user_cookie_save(array('key'=>'value'));
print $_COOKIE['Drupal_visitor_key']; //outputs value
</code>
Comment: Just to stress the key points. Drupal won't touch your custom cookies. For some reason they cannot be read on the pages you are concerned with. That implies they are being created in such a way they are not accessible. The path and domain settings are the most likely cause (also consider the security settings).


A question in Dynamical systems

Question: Considering the discrete time logistic growth model,
$$N_{t+1} = \lambda N_t\left(1-\frac{N_t}{K}\right)$$
where $\lambda = 1+ b -d >0$ is the net reproductive rate and $K>0$ is a parameter that affects how the population grows when the population is large.
I have determined the two equilibrium points of this system which are,
$$N^*=0$$
$$N^* = K\left(1-\frac{1}{\lambda}\right)$$
found the conditions for each of the equilibria that I found above to be unstable.
Here is my explanation below,
$$f'(x) = \lambda -\frac{2x\lambda}{K}$$
Using $x=0$
$$f'(0) = \lambda$$
So it is unstable when $\lambda>1$
Using $x = K\left(1-\frac{1}{\lambda}\right)$ it is unstable when $\lambda >3, 0 < \lambda <1$
I believe I have done everything correct to this point.
My question is how do I give the values of $N_0>0$, $K>0$ and $\lambda>0$ such that $N_1<0$, and how do I calculate $N_1$? Thanks!
Answer: Yes. All of your assumptions are correct. I checked it. But according to your problem if $N_0, K$ and $\lambda$ are positive, then from the first iteration $$N_1=\lambda N_0\left(1-\frac{N_0}{K}\right),$$ you always get $N_1$ as non negative since $N_0<K$ (the population is at most its carrying capacity).
But what is your actual motivation according to the problem? I think it may be positiveness of population in the model.
Comment: how did you calculate $N_1$?
Comment: but from the question isn't $N_1<0?$
Comment: @user123 You just put $t=0$ in the discrete time  logistic growth model and get $N_1$ as i mentioned in the answer (Here note that $t$ is non negative interger).
Comment: No. $N_1\nless0$ if $N_0,K$, $\lambda$ are positive and $N_t<K$ at all population level $t$ due to ecological significance.

A question in Dynamical systems


Why the derivative of a complex function is a "Strong Demand"

Question: It is said that differentiability of a complex function is a "strong" demand why is there?
In the case of a single real variable function it is understood, as the complex number is like differentiability of two real variables function
In the case of multivariable function, is it because a complex number can be defined on different branches?
Answer: If a function of two real variables is differentiable, it may not be twice-differentiable. Indeed, its derivatives might not even be continuous.
If a function of a complex variable is differentiable, then it is infinitely differentiable, indeed analytic – it has a power series that converges to it.
Answer: Apart from the analytical reason (power series expansions) explained by Gerry, there is also a purely geometric one.
In a nutshell, real differentiability is the property that a mapping can be locally approximated by linear ones. One linear map for each point of the domain. Complex differentiability is real differentiability, combined with the strong requirement that all those linear mappings are similitudes of the complex plane, that is, combinations of a rotation and a dilation.
I recommend digging the book "Visual complex analysis" by Tristan Needham. It contains lots of pictures which explain this geometric point of view very vividly.
Answer: A  differentiable map $${\bf f}:\quad{\mathbb R}^2\to{\mathbb R}^2\tag{1}$$ has at each point ${\bf p}$ of its domain a Jacobian matrix $J_{\bf f}({\bf p})$.  This matrix changes from point to point, but can at any point ${\bf p}$ be any real $2\times2$-matrix.
On the other hand, if you have a complex differentiable function $f:\>{\mathbb C}\to{\mathbb C}$ and view this function as a map of type $(1)$ then the Jacobian of this resulting ${\bf f}$ has at each point ${\bf p}$ the special form
$$J_{\bf f}({\bf p})=\left[\matrix{a&-b \cr b&a\cr}\right]\ ,$$
whereby $a+ib=f'(p)$. (This is the content of the CR equations.) In other words, for a complex differentiable function at each point we only have two real degrees of freedom in $J$, whereas for a real differentiable function we have four degrees of freedom.


Por que o programa não reconhece o "N"?

Question: class primao:
    from random import randrange

    def __init__(self, N=randrange(2,100), divisor=0, pontos=0, laco=True, prova_cabal= N%divisor):
        self.N= N
        self.divisor= divisor
        self.pontos= pontos
        self.laco= laco
        self.prova_cabal= prova_cabal

    def gerar_primo(self):
        for i in range(1,self.N,+1):
            self.divisor += 1
            if self.prova_cabal == 0:
                self.pontos += 1
            if self.pontos > 2:
                self.laco= False
        if laco == False:
            gerar_primo()
        if pontos <= 2:
            self.laco = True
            return self.N

A= primao()
A.N_Primo()

Answer: O erro está sendo gerado porque você não inicializou as variáveis N e divisor na sua classe ou fora antes de serem usadas para definir o parâmetro prova_cabal = N % divisor.
Eu não sei qual o seu objetivo com esse código, mas se você inicializar essas variáveis, o erro será eliminado. Exemplo:
class Primao(object):
    from random import randrange

    N = 1
    divisor = 1

    def __init__(self, N = randrange(2,100), divisor=0, pontos=0, laco=True, prova_cabal = N % divisor):

        self.N = N
        self.divisor = divisor
        self.pontos = pontos
        self.laco = laco
        self.prova_cabal = prova_cabal

    # Código restante...

Fora isso o seu código está cheio de erro. Você está chamando o método N_Primo() que não existe, você esqueceu de usar self ao chamar o atributo laco e o método gerar_primo, e mesmo com esses detalhes corrigidos, o seu código ainda gera o seguinte erro:

RecursionError: maximum recursion depth exceeded in comparison

Esse erro está sendo gerado porque você ultrapassa o máximo de chamadas permitidas do mesmo método em Python.
Sugiro que revise o seu código direito, procurando por erros de digitação para corrigi-los e melhore a lógica do seu código.

Por que o programa não reconhece o "N"?


Harmony: why does transforming a ii minor chord into II major chord work?

Question: I accidentally composed a song that uses the same harmony "trick" as the song The Odyssey from Symphony X. Both are in the key of Eb (I know it's C minor, but I like to think major for simplification)
So the harmony and my analysis at the last minutes in The Odyssey (23:25) is:

Cm  Bb  Ab  Bb  Cm
Eb  Bb  F

vi  V   IV  V   vi
I   V  II

And in my song I have something similar:

Ab  Gm   Fm        Eb
Ab  F    Dm7(b5)   Cm

IV  iii  ii        I
IV  II   vii7(b5)  vi

This major II (F major) that thrills me. In both cases I feel that those transformations work in a very interesting way, first I tried explaining it with the functional harmony I know (which is not much). I thought that maybe some other chord was either being the secondary dominant for the F major, or preparing/omitting the secondary dominant somehow. But I don't think that was the case for either of them.
Then I thought about "pivot" chords (I call them like that, I don't know the official name), like how the Bb major is the V of the Eb major key, but also the IV of the F major key. But it doesn't apply to my song, only for Symphony X's song.
The only remaining option that I know would be some form of "picardy", obviously not the classic picardy third, just a fun surprise expecting a minor chord and getting a major chord. But I find those two explanations kind of lazy.
Is this a common progression or a trick that I'm missing?
Comment: I learned to play tunes by ear and I learned how music worked. When learning, I never, ever, ever, ever, felt a need to ask "why". Not even once. The only thing I was ever interested in was, WHAT happens in this tune. What notes are there. After I learned what notes there were, I was able to reproduce the same pattern in other songs and other keys. What more could one possibly need? After many decades, I encounter people who ask "why does this work. " What does that even mean? What do you mean "why"? What could that possibly mean.
Comment: Theory is mostly about trying to explain why things sound good or bad and in some ways the real answer is "that's just how things sound". That said, it might be that it sounds like a secondary dominant (V/V) especially when you follow it with the vii dim chord which is also the upper structure of a V7 chord. That means we might hear the Bb below the vii chord even thought it's not really there, and that makes it a downwards circle of fifths progression. Following with the vi is almost a deceptive cadence.
Comment: There's a chromatic alteration. It's a normal common thing that happens all the time. Keep playing songs and don't care about "understanding". Your brain will eventually figure out the pattern. It's like learning to ride a bike. You keep trying until you can do it.
Answer: You admit that both pieces/excerpts are actually in C minor, not E flat major. Therefore, you are not transforming ii into II, but iv into IV instead.
The Symphony X "The Odyssey" excerpt is therefore analyzed as this:
Cm Bb Ab Bb Cm
Eb Bb F
i VII VI VII i
III VII IV
Your excerpt is therefore analyzed as this:
Ab Gm Fm Eb
Ab F Dm7(b5) Cm
VI v iv III
VI IV ii-half-diminished-7 i
Both iv and IV function as subdominant chords, so the transformation between them is slick and effortless.
(I've always thought the use of IV instead of iv in Kirby Air Ride's "The Legendary Air Ride Machine" was more striking, anyway - see this similar analysis of the start of its main theme after the introduction:
Fm C Fm Fm
Bb Fm Bb Bb
Bbm Eb Ab Ab
Gm Fm G C
i V i i
IV i IV IV
iv III VI VI
ii i V/V V)
Comment: Nailed it! We have always to treat the tonic as I (or i) in this framework.
Comment: Nice explanation and example! I'll definitely try to look at pieces from a minor perspective from now on. I didn't know the Kirby piece you mentioned. Loved it. Kirby's piece sounds plagal for me, and now that I see that way, both pieces seem to have a plagal-like flavour. Thanks!
Answer: For a start, if you feel a song is in C minor, analyse it in C minor. We seem to be talking about IV in a minor key, not II in a major one.    In some contexts this may not matter.  But it does matter if we're indulging in harmonic analysis.
So.  We've encountered a chromatic chord.  One that uses notes not in the basic scale of the home key.   Common, and absolutely 'allowed'.  And yes, as a slightly 'outside' chord, it WILL catch your ear!   You find it thrilling!   Great!
One school of thought is satisfied by finding a related scale that this chord can be 'borrowed' from.   OK, let's play that game.  Home key is C minor.   Obviously an F major could be 'borrowed' from the parallel major key, C major.  If the music was moving towards this key, that could be a useful way of looking at it.  (But it isn't, is it?  So that's not going to get us anywhere.)   What about 'borrowing' it from the C harmonic minor scale, or the ascending C melodic minor scale?   Ok, that's a very basic concept, 'It's OK to mix the different types of minor scale'.   Let's take it a bit further, 'It's OK to modify one note of any diatonic triad, to give a new flavour'.
Beware of inventing functional justifications.   That F major chord COULD be a secondary dominant, leading to Bb major. Two problems.  Secondary dominants tend to be dom7 shape chords not plain triads.  And DOES it lead to a Bb chord?  No.
In your song, we have F, Dm7♭5, Cm.   Will you let me rewrite that as F, Fm/D (or Fm6), Cm?   IV, iv, i.  (You really MUST let a tonic be i, otherwise the whole framework's askew.)  There's a nice melody line in there (I hope), A, A♭, G.
So where do we end up? The F chord can be justified as 'borrowing', though I don't see that helps much beyond granting permission to use it!   'Dominant of B♭' is a bit of a dead end. Will you settle for 'chromatically altered diatonic triad'?
Answer: TL;DR
In both cases, the F chord is an unresolved secondary dominant to Bb.

The Odyssey
TL;DR explanation (move on for the real point)
There are multiple interpretations here.
For example, just considering the chords in isolation, one could consider that the progression is actually in Bb major:
ii  I  bVII  I  ii  IV  I  V
This provides a very clean explanation in that it's all in one key (allowing that bVII is considered part of a major key in much pop and jazz), but it doesn't reflect the actual sound of the song.
The initial part really does sound like C minor, and that's reinforced by the final chord of the piece, which is C major. (There's the "picardy third" mentioned in the question.)
So we have i  bVII  bVI  bVII  i. That much matches what the ear tells us.
The next chord, Eb major, by itself, sounds like we've shifted to that key. The preceding chords seem self-contained, as opposed to involving some sort of pivot or other transitional moment. The modulation sounds direct.
The following Bb major chord would seem to confirm Eb major.
But the F major chord then remains problematic, because it's not part of Eb major. (F minor would "make more sense", since it could act as a pivot from Eb [ii chord] back to C minor [iv chord].)
What's going on
We're actually shifting momentarily to Bb major, with the Bb chord acting as the pivot. We hear the Eb chord as an arrival in Eb major, but the Bb chord functions both as the IV chord of Eb and the I chord of Bb. This isn't clear until the F major chord sounds.
Thus we have:
i  bVII  bVI  bVII  i  bIII  IV/bIII = I/bVII  V/bVII
with a direct modulation back to C minor.
Song by OP
I hear the progression this way:
IV  iii  ii  I  /  IV  V/V  vii7b5  vi
I came up with this interpretation by altering second part of the progression:
Ab  F  Bb9 = Dm7b5/Bb  Cm then ending Ab  Bb  Eb.
This keeps us more solidly in Eb major by using the true V chord. In the actual progression, though, the resolution of the secondary dominant, F, to Bb is defeated by moving to the Dm7b5.
Another interpretation is that we're momentarily in Bb major. To hear this more clearly, another altered progression is handy:
Ab  F  Dm7b5  G7  Cm  F7  Bb (or bVII  V  iii-7b5 = ii-7b5/ii  ii  V7  I).
In either case, the F chord is an unresolved secondary dominant for Bb.
Answer:
Cm Bb Ab Bb Cm
Eb Bb F

If the tonic is C, then analyze it in C

i ♭VII ♭VI ♭VII i
♭III ♭VII IV

I used jazz style analysis and put flats before minor mode chord roots.
All the chords are diatonic to a C minor key signature except the last one.
The chromatic alteration from the C minor key signature in the last chord is a change of the tone A♭ to A natural.
In C minor A♭/A is the sixth scale degree, the submediant, which is one of the modal scale degrees.
When you alter modal scale degree this way, especially when it results in major/minor/diminished triad quality changes swapping chords from the relative major/minor modes, you can call it mode mixture.
You could describe the F chord, the IV as "borrowed" from C major. Technically that is the correct use of music theory terminology. But, you could also say that the F chord shifts the music into the dorian mode (C D E♭ F G A B♭ C).
The harmony of the quoted passage doesn't use tonic/dominant harmony. So rather than calling it functional harmony, and we certainly don't want to start talking about modulations and secondary dominants, because none of that style harmony is happening, we can say it's modal style harmony. In that case, personally, I think it's a little more helpful to call this mode mixture and mention dorian mode, rather than calling it borrowed harmony.
I think you can "test" the mode mixture/dorian idea. Just ad lib with the lower portion of a minor mode C D E♭ F G and accompany with dorian chords Cm and F. I think you get the "sound", the tonality, of this passage of the song. The actual vocal part of the song moves about that lower minor scale region then drops from B♭ to A natural for the "finally home" lyric, accompanied by the F chord. Then it goes back to Cm. That's dorian harmony.
The ending is interesting. If I hear it correctly it is A♭ B♭ G♭ Ab+ C. That second to last chord is A flat augmented. The chords are not entirely derived from a C whole tone scale, but a whole tone feel is pretty strong. That doesn't really fit in with the mode mixture stuff, but the whole tone scale can lend a mystical quality and I imagine that fits the mood of overall piece.

The only remaining option that I know would be some form of "picardy", obviously not the classic picardy third, just a fun surprise expecting a minor chord and getting a major chord. But I find those two explanations kind of lazy.

The very last chord changes the tonic Cm chord to C major, and that would be the classic picardy third usage.
For the use of F major rather than Fm, I would not call it picardy third, but mode mixture.
I think there is a sort "surprise" element with mode mixture, although I tend to call it "colorful." The "surprise" comes from the A having been flat at one point, but then a moment later becomes A natural. A lot of people won't consciously recognize the music theory details, but their ears recognize something is going on. You can find this type of harmony in Renaissance music and styles that emulate Renaissance music.
I think a big part of the "mixing", the alteration of certain tones from a strict mode, was to avoid diminished intervals both harmonic and melodic. I don't see that was necessarily the case in this song, but it's something to be aware of. Notice how the chord roots in Cm B♭ A♭ B♭ Cm move by steps rather than fourths and fifths? That's a common thing in modal harmony. Depending on where you do that in a mode, you can run into diminished intervals. When those diminished (or augmented) intervals are altered to keep everything perfect and major/minor intervals, the end result is mode mixing. For example, in C, descending Dm C Bdim, drop the B to B♭ to get Dm C B♭ and now it's in C mixolydian.
I don't mean to digress so far from the song, but I think this is an important part of the modal/mode mixture "trick." Mode mixture by diminished interval avoidance.
Of course that doesn't mean total avoidance. Symphony X introduced augmented intervals for the ending. You use a half diminished chord in your progression.
Another "trick" to point out in your progression is the A♭ F movement. That is a chromatic mediant, which has some similarity to borrow chord harmony, another good way to get harmonic color.
Answer: It's very common for any piece to stray from the diatonic notes/chords that we seem to expect to be the norm. They are the basis of any key, but are not exclusive to that key, as the 'home' note/chord is far more telling.
There's lots of reasons given for extra chords that occur. Secondary dominants are one such, as well explained by Aaron. But there are others, too. Moving into the parallel is one - which, given the piece is in Cm, you say, would reveal a whole new set of chords, including F major.
Another theory (there are no rules) of modesC Dorian. That contains the notes F A and C - making up your F major again, from a different perspective.
The secondary dominant is a bit of a misnomer, as it hints that it's V/V (which it is), but that ought to lead to V (which it doesn't here, and often doesn't). Sort of hinting of a mini-modulation, which never matures.


How to make an auto-complete list when I start to type in the textfield?

Question: I have a textfield and if I want to write something to the field, it will show me the list of possible options regarding to that letter and I think this is called an auto complete.
Could someone give me an idea or a sample on how to do it?
Thanks..
Comment: Where do you want to implement it? In HTML or QT or any other GUI mode. Without this, it is difficult to answer this question
Comment: @Koran - the question is tagged (plain) java so I expect AWT/Swing
Comment: only in GUI. And then later i will use the words from my database because im making a translation program.
Comment: what GUI? even in java, it has SWT in eclipse and swing. It's different. if it's swing, it should tag swing not intellij-idea.
Answer: Take a combo box and listen to all changes in the textfield. On every event, read the actual content and query your source list for possible matches. Then use the result to populate the associated list.
You may want to start autocompletion once the user has entered two or three letters, otherwise the list may get too long..
Comment: is it ok if I use Jlist instead of Combo box? Do I still need to use JPopupMenu for this one?
Comment: Sure, if you accept to keep the text field separated from the list of suggestions. But usually this is done within *one* widget: you type something and the suggestions appear right below your fragments. - (2), no, with JComboBox you won't need a popup menu.
Comment: yeah.. all you said is what really I need, do you have any idea how to put the list of suggestions below the textfield? I mean do I have to use other window for this one or just make some x, y coordinations in order to appear just below the textfield when I type something to the field?
Comment: [JComboBox](http://download.oracle.com/javase/tutorial/uiswing/components/combobox.html) already provides a combination of textfield and list. That's why it's called *combo box*.
Comment: Do you have any sample about autocomplete using JComboBox? even just an easy sample, I'll only just get an idea in the sample. thanks.;-)
Answer: look here is AutoCompleteComboBox / JFextField, and there are two classes one for JComboBox, second for JTextField, notice auto-complete functionality requires both classes for that
Comment: how can I run? it needs a main.
Comment: you have to define some array e.g List, then setDataList(myList)
Comment: check my profile I posted more than once here (autocompleted or JComboBox or Table with autocompleted combobox or  JTable with autocompleted combobox)
Comment: I already check your profile but I do not see any sample there.
Answer: I feeling generous as you really should google ...
As the user types, you'd need to query your DB with a like '<userInput>%' and return the results into a pulldown. You probably want to wait for a pause in the user's typing so as not to hammer your DB.
In the absence of a database, a data structure that would work well for this is called a Trie as you can traverse it past the initial input and present all the subsequent words.
Comment: thanks but i will use only from GUI. When I type something to the textfield, a list of suggestions will appear just below the textfield. And the list of suggestions will be coming from my database but for the meantime i can try a string of array before applying it in my DB. Could you help me or any idea about this one? Thanks..
Comment: Same thing ... you're going to have to capture input from the textfield as the user types (keyevents) and search whatever data source you're using for matches. Using an array is expensive because your performance is O(n*m) (because you're going to have to search each string within the array), but for testing it would be fine.
Comment: yeah.. I already tried some unit test and now I want it to try in GUI. its quietly hard thats why I'm asking this kind of stuff. Well, I'll try what you said. tnx.. ;-)


Resolvent of a Semigroup

Question: Let $A$ be the generator of a Semigroup of linear contractions on $L$.
Then, $(R_{\lambda}, \lambda  \in \rho(A))$ is called the resolvent of the semigroup $(P_t)_{t \geq 0}$.
($L$ is in the following  our considered Banach space)
And for $g \in L_0 = \{ f \in L: \text{s-lim}_{h \rightarrow 0} (P_hf-f)=0\}$  we can write
$R_{\lambda}g= \int_0^\infty e^{-\lambda t}P_tg ~dt$
It follows that $R_{\lambda}g \in L_0$. But in a paper I read that $R_{\lambda}g \in D(A)=\{f \in L_0: \text{s-lim}_{h \rightarrow 0} \frac{1}{h}(P_hf-f) \text{ exists in } L\} $.
But $D(A) \subset L_0$. Because of that I can't understand the implication.

Is the implication $R_{\lambda}g \in D(A)$ satisfied?
If yes, why is $R_{\lambda}g \in D(A)$?
Answer: \begin{align}
\lVert P_h (R_{\lambda}g) - R_{\lambda}g \rVert & = \lVert \int_0^{\infty} e^{-\lambda t} (P_{t+h}g - P_t g) \,d t \rVert \\
& \le  \int_0^{\infty} e^{-\lambda t} \lVert P_t (P_h g - g) \rVert \,d t\\
& \le \int_0^{\infty} e^{-\lambda t} \lVert P_h g - g \rVert \,d t \\
& \le C \lVert P_h g - g\rVert \to 0
\end{align}
as $h \to 0$, using the fact that $g \in L_0$. So $R_{\lambda}g \in L_0$.
I think you need $g \in D(A)$ to conclude $R_{\lambda}g \in D(A)$. When $g \in D(A)$ write $$ G = \lim_{h \to \infty} \frac{P_h g - g}{h} \in L$$ and you can proceed similarly as above and get
\begin{align}
\lVert \frac{1}{h}[P_h( R_{\lambda}g) - R_{\lambda}g]  - R_{\lambda G}\rVert &  \le \int_0^{\infty} e^{-\lambda t} \lVert P_t( \frac{1}{h}[P_h g - g] - G)\rVert \,d t \\
& \le C \lVert \frac{1}{h}[P_h g - g]- G\rVert \to 0
\end{align}
as $h \to 0$.

Resolvent of a Semigroup


Connecting multiple data entities to the user object

Question: I need to create a simple order system in Drupal 7. This will be a site for a meat wholesaler so I don't need a webshop.
Users are able to register and fill in a webform to order products. However I'll need to handle different shipping addresses for the users, and let them choose a shipping address upon ordering.
What I have in mind is connecting the shipping addresses to the user object (billing address is already on the user form).
Which method is better?

Create a field collection entity for the shipping addresses and add it to the user form
Leave the user form alone and create a new content type that can be added/edited by users and use the UID to decide which address belongs to which user

I'd like to let users edit their shipping addresses anytime on their user page, preferably independently from the other datas.
If anyone done something like this before, please share some ideas.
Answer: You would probably be best to create a Shipping Address content type. You should also look at the Address Field module to collect the addresses rather than field collection.
Then you can create a simple view to list the shipping addresses (Node Tile not linked) using a contextual filter on uid. Then set up a node reference field in your webform using the view to provide the values. The user can then select which shipping address to use for his order.
On the user page you mav use the same view (separate display listing titles as edit links) to let them edit their shipping addresses, and give them a link to add new addresses if necessary.


How do I restore a schema in Cassandra?

Question: This is an example scenario and we wanted to understand if it would be possible to recover it. And also understand better about the schema.
In a hypothetical scenario of just 1 node, Cassandra 3.11. I have 1 keyspace and 1 table.
root@dd85fa9a3c41:/# cqlsh -k cycling -e "describe tables;"
rank_by_year_and_name

Now I reset my schema and restart Cassandra: (I have no nodes to replicate it again)
root@dd85fa9a3c41:/# nodetool resetlocalschema

With the new schema, I no longer "see" my keyspace+table:
root@dd85fa9a3c41:/# cqlsh -e "describe keyspaces;"
system_traces  system_schema  system_auth  system  system_distributed

I lost my original schema, where was my keyspace+table. But, they are still on disk:
root@dd85fa9a3c41:/# ls -l /var/lib/cassandra/data/cycling/
total 0
drwxr-xr-x 1 root root 14 Nov 22 11:32 rank_by_year_and_name-4eedbbf0

How could I restore that keyspace in this scenario? With sstableloader I could recreate keyspace+table and import.
I would like to recover this schema and see my keyspace+table again.
I haven't found any way to do this without manually recreating and importing with sstableloader.
Thank you if you help me!
Comment: Welcome to Stack Overflow! A friendly reminder that this site is for getting help with coding, algorithm, or programming language problems so I voted to have your post moved to DBA Stack Exchange. For future reference, you should post DB admin/ops questions on https://dba.stackexchange.com/questions/ask?tags=cassandra. Cheers!
Answer: On-disk data and schema are two different things in Cassandra.
To be able to restore a keyspace schema, you need first to back it up using nodetool snapshot. It will do a back up of the sstable (hard link) and create a schema.cql file containing the schema.
See the official doc here: https://cassandra.apache.org/doc/3.11/cassandra/operating/backups.html
Answer: I realise it's a hypothetical scenario but running resetlocalschema on a single-node cluster is a bad idea. The node is supposed to drop its copy of the schema and request the latest copy from other nodes but in the case of a single-node cluster, there are no nodes to get the schema from.
You really shouldn't run resetlocalschema on a single-node cluster unless you're doing some specific test or edge case activity as discussed in CASSANDRA-5094.
Now to your question on how you would restore the schema, most enterprises have a copy of their schema usually in a Change Management system (or CI/Config Management System). Before updates can be made to the schema in production, it usually goes through testing, peer-review, staging/pre-production validation, and finally deployed to production through an approved Change Request (terms might differ between organisations but the net intent is the same).
Similarly when you perform regular backups, the nodetool snapshot command stores a copy of the schema together with the SSTable backups. In this example I posted in https://dba.stackexchange.com/questions/316520/, you can see that the snapshots/ folder contains both a manifest.json (inventory of SSTables included in the snapshot) and a schema.cql (the schema at the time of the snapshot):
data/
  community/
    users-6140f420a4a411ea9212efde68e7dd4b/
      snapshots/
        1591083719993/
          manifest.json
          mc-1-big-CompressionInfo.db
          mc-1-big-Data.db
          mc-1-big-Digest.crc32
          mc-1-big-Filter.db
          mc-1-big-Index.db
          mc-1-big-Statistics.db
          mc-1-big-Summary.db
          mc-1-big-TOC.txt
          schema.cql

From the above you should be able to see that you have two options available:

recreate the schema from a copy that's been submitted/peer-reviewed in your Change Management System, or
recreate the schema from the snapshot.

The choice depends on what you're trying to achieve. Cheers!

How do I restore a schema in Cassandra?


While Ajax JQuery

Question: Tenho o seguinte código:
$.ajax({
    type:"post",
    url:"../connect/post/infoClienteTask.php",
    data:'infoClienteTask='+fantasy,
    success:function(responseData){
        console.log(responseData);
           $(".historic-cliente").html('
'+responseData.Project+' - '+responseData.Delivery+'
');
    }
});

Que ao clicar em uma lista de clientes, ele mostra todo o histórico do cliente, mas com esse código eu só consigo achar o primeiro da busca.
No PHP eu tenho os seguintes códigos.
POST:
header( 'Content-Type: application/json; charset=UTF-8' );

$selInfoClienteTasks= new Tasks();

if($_SERVER['REQUEST_METHOD']=='POST'){

    $fantasy = $_POST['infoClienteTask'];
    $stInfoClienteTasks = $selInfoClienteTasks->selectInfoClienteTask($fantasy);

    echo json_encode($stInfoClienteTasks);

    exit();
}

SELECT:
public function selectInfoClienteTask($fantasy){
        try {
            $stmt = $this->conn->prepare("SELECT tasks.*, DATE_FORMAT( tasks.Delivery , '%d/%m/%Y' ) as Delivery FROM Tasks WHERE CompanyFantasy = '$fantasy'");
            $stmt->execute();
            return $stmt->fetch(PDO::FETCH_ASSOC);

        }catch (PDOException $exception){
            header("Location: ./error.php?err=Unable-to-find-info");
            echo 'Error: '.$excption->getMessage();
            return null;
        }
    }

Preciso fazer um While/Foreach/For neste Ajax para continuar buscando até achar todos as informações, alguém tem uma ideia?
Comment: O que dá esse `console.log(responseData);`? ou melhor: `console.log(JSON.stringify(responseData));`
Comment: Todos os dados correspondente da tabela do cliente em questão, mas existe duas tarefas para o mesmo cliente, mas só aparece a primeira.
Answer: Faça as seguintes alterações no seu código:
Select:
public function selectInfoClienteTask($fantasy){
    try {
        $stmt = $this->conn->prepare("SELECT tasks.*, DATE_FORMAT( tasks.Delivery , '%d/%m/%Y' ) as Delivery FROM Tasks WHERE CompanyFantasy = '$fantasy'");
        $stmt->execute();
        $data = array();
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $data[] = array('Project' => $row['Project'], 'Delivery' => $row['Delivery']);
        }

        return $data;

    }catch (PDOException $exception){
        header("Location: ./error.php?err=Unable-to-find-info");
        // Removi as linhas na sequencia pois se você faz o redirect nada na sequencia será executado
    }
}

Ajax:
$.ajax({
    type:"post",
    url:"../connect/post/infoClienteTask.php",
    data:'infoClienteTask='+fantasy,
    success:function(responseData){
        $('.historic-cliente').html('');
        console.log(responseData);
           $.each(responseData, function(i, item) {
               $(".historic-cliente").append('
'+responseData[i].Project+' - '+responseData[i].Delivery+'
');
           });
    }
});

Comment: Com a parte do PHP apareceu os dois dados do mesmo cliente, mas na hora de imprimir, ele só paga o ultimo dado inserido.
Comment: Desculpe, esqueci de alterar para utilizar o método correto, corrigi agora!
Comment: Fiz uma pequena mudança `$('.historic-cliente').html('');`,  antes do `$.each`, para limpar, se não ele sempre vai adicionar.
Comment: Perfeito, adicionei também!
Answer: Acesse o índice do seu response através de um for:
responseData[i].Project

O foreach também é possível, precisaria ver qual o conteúdo desde response para montar um codigo de exemplo para você.
Utilize o código passado pelo amigo Sergio (console.log(JSON.stringify(responseData));) para obtê-lo.

While Ajax JQuery


Server moved,got error

Question: I had a laragon installed on my laptop. Now I'm on an other one where is running Ubuntu. I moved evertyhing,but I got an error:

[2018-04-22 11:51:34] local.ERROR:
  DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::registerBreadcrumbs():
  Failed opening required 'C:\laragon\www\proba1\routes/breadcrumbs.php'
  (include_path='.:/usr/share/php') {"exception":"[object]
  (Symfony\Component\Debug\Exception\FatalErrorException(code: 64):
  DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::registerBreadcrumbs():
  Failed opening required 'C:\laragon\www\proba1\
  outes/breadcrumbs.php' (include_path='.:/usr/share/php') at
  /var/www/html/laravel/vendor/davejamesmiller/laravel-breadcrumbs/src/BreadcrumbsServiceProvider.php:92)
  [stacktrace]
0 {main} "}  [2018-04-22 11:53:41] local.ERROR: DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::registerBreadcrumbs():
Failed opening required 'C:\laragon\www\proba1\routes/breadcrumbs.php'
  (include_path='.:/usr/share/php') {"exception":"[object]
  (Symfony\Component\Debug\Exception\FatalErrorException(code: 64):
  DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::registerBreadcrumbs():
  Failed opening required 'C:\laragon\www\proba1\
  outes/breadcrumbs.php' (include_path='.:/usr/share/php') at
  /var/www/html/laravel/vendor/davejamesmiller/laravel-breadcrumbs/src/BreadcrumbsServiceProvider.php:92)
  [stacktrace]
0 {main} "}

After this log,I got a now folder in a basic folder of the laravel. I tried,maybe a definied variable,with this path,but nowhere. Any idea?
Answer: Managed. I had to delete the

cache

files from the

/bootstrap/cache

folder.
Answer: Try it:
create these folders under storage/framework:
sessions
views
cache
Answer: Same error, I deleted files inside bootstrap/cache, except .gitignore and run in CLI
    composer dumpautoload

Answer: Problem Image Showing problem in the image
Problem Statement
 require()
 vendor\davejamesmiller\laravelbreadcrumbs\src\BreadcrumbsServiceProvider.php:94

DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::registerBreadcrumbs()          vendor\davejamesmiller\laravelbreadcrumbs\src\BreadcrumbsServiceProvider.php:63
**Solution of this Problem that works 100%**

Remove files from the cache folder inside the bootstrap folder and run composer dump-autoload. It will work.

Answer: Run this artisan command on your projects root directory:
php artisan cache:clear

Comment: :| just run in your Terminal.

Server moved,got error