When did the anonymous "you" become popular in western pop music?

Question: This question might sound a bit facetious but I have been wondering for a long time.  Many western pop songs are addressed to an anonymous "you".  Presumably the song writer wants to write a song that could be about anyone and not a particular person, and I do get that.  But I was wondering at what point in the history of western popular music did this become common?
I can think of at least a World War 2 example ("I'll be home for Christmas") in which "you" appears (in the lyrics "you can count on me") but I expect it was long before that.
Was there a particular point where "you" became common, and if so, when?  If not, was it always common?
Comment: It's probably gone on for as long as songs have been written - and sung. Imagine someone singing a song that quotes someone's name to someone of a different name! Using the word 'you' means that a song can be sung to anyone, whilst gazing into their eyes, and the 'you' actually translates as this song is for '*you*'. Now, the anonymity disappears.
Comment: If your lover's name is Johnny, Ida, Gloria, Michelle, or even Linda, you're in luck: there's a song you can sing with that person's name. But that's at most only one or two songs for anyone other than Johnny or Gloria. Many people have no song named after them. You can sing a "you" song to anybody and it fits.
Comment: I'm curious, what made you think it was not always common? And is not all music like this, opposed to western pop music in particular?
Comment: I'm reminded of [Beautiful South - Song for Whoever](https://www.youtube.com/watch?v=J-q_gAM1BXQ) - which, in a very tongue-in-cheek manner, pretty succinctly explains **why** non-specific names work better.
Comment: @IvoBeckers: I suppose I just wasn't sure if it was or wasn't common.  I specified Western pop because I do not have experience with songs from other cultures, so I figured I'd make it specific.  It does appear, though, that "always" is the answer
Answer: I'm going to go with "it was always common". Certainly many Renaissance madrigals are written to "you" (or "thee", as the case may be):

Come again!
  Sweet love doth now invite
  Thy graces that refrain
  To do me due delight.
To see, to hear,
  To touch, to kiss,
  To die with thee again
  in sweetest sympathy.

Come Again, John Dowland, c.1597

Alas, my love, you do me wrong,
  to cast me off discourteously;
  and I have loved you so long,
  delighting in your company.
I have been ready at your hand
  To grant whatever you would crave
  I have wagered both life and land
  Your love and goodwill for to have.

Greensleeves, Unknown c. 1580
And even the oldest love songs/poems are written this way:

Behold, you are beautiful, my love.
  Behold, you are beautiful.
  Your eyes are doves behind your veil.
  Your hair is as a flock of goats, that descend from Mount Gilead.
  Your teeth are like a newly shorn flock, which have come up from the washing,
  where every one of them has twins. None is bereaved among them.
  Your lips are like scarlet thread.
  Your mouth is lovely.
  Your temples are like a piece of a pomegranate behind your veil.
  Your neck is like David's tower built for an armory,
  whereon a thousand shields hang, all the shields of the mighty men.
  Your two breasts are like two fawns that are twins of a roe, which feed among the lilies.
  Until the day is cool, and the shadows flee away,
  I will go to the mountain of myrrh, to the hill of frankincense.
  You are all beautiful, my love. There is no spot in you.

Song of Solomon, attr. to King Solomon, c. 950 BC
Comment: Song of Solomon... nice example! Of course "you" is a translations in English :-)
Comment: One can add a lot of Shakespeare sonnets, many of which are addressed to an anonymous object of interest. "Shall I compare thee to a summer's day?"
Answer: Odes to someone unspecified by name (if not by profession or by pulchritude) date at least to 1914.  Titles of World War I songs include "Oh, You Beautiful Doll," "Your King and Country Wants You," "Don't Bite the Hand That's Feeding You," "Pack Up Your Troubles," "Keep the Home Fires Burning."
Odes in general go back to ancient Greece and have been composed continually since then.  Some of those too omit the addressee's name, for instance
Schubert's 1828 song Der Doppelgänger.
As for when this became common, you'd have to run some statistical analysis of a corpus of song lyrics, and look for a knee in the curve.  Maybe flag lyrics that have plenty of "you" and an absence of proper names.
Answer: Possibly of Canadian origin, Red River Valley was nonetheless very popular in the US.  It was established in Canada by 1896 and may have been composed in the 1870s.  It begins "from this valley they say you are going...."
Stephen Foster's Beautiful Dreamer probably dates from 1862.
The Star Spangled Banner begins "o say, can you see...?"
Another answer notes Schubert's Doppelgänger, which sets an untitled poem by Heine.  There is also Du bist wie eine Blume, by the same poet, writing in the early 19th century.
Schubert also set both of Goethe's poems with the title Wandrers Nachtlied, written in 1776 and 1780.  Both are in the second person, though the first may be addressed to the divine and therefore not anonymous.
Going back a bit farther and returning to English, Shakespeare's song "O Mistress mine" from Twelfth Night, 1601 or 1602, has long been a favorite lyric of composers.  "... where are you roaming? O, stay and hear your true love's coming..."
As noted in the other answer, this is a literary device that has been in use for centuries, and it should not be difficult to find examples of its use throughout the history of western lyrical poetry.

For a little one-upsmanship with the accepted answer, I note that Sumer is icumin in, dating from around 1260, ends with the line

Wel singes þu cuccu
  ne swik þu nauer nu

This means more or less

You sing cuckoo well.
  Never stop now.


Logarithm Via Multiplication By Some Function

Question: This question may be totally rubbish, I'm not sure...
Basically, I'm wondering if I have some expression, say,
$$f(z)A(z)$$
where $A(z)$ is some arbitraryly changing function in $z$ totally out of my control, is there are function, $f(z)$, by which I can multiply $A(z)$, which results in me taking the logarithm of $A(z)$?
I have a feeling the answer is simply no...  and this is a really silly question, but just wanting to make sure.
Thanks.
Comment: I think that $\dfrac{\ln A(z)}{A(z)}$ is the _only_ function that would work. So, if you want a function that doesn't depend on $A$, then the answer is no.
Comment: This may be obvious, but if $A$ is bijective then yes.
Comment: Okay, so I'm an engineering student, so had to look up bijective.  $A(z)$ isn't bijective.
Comment: Well, not to be too sarcastic, but doesn't $$f(z) = \frac{\ln(A(z))}{A(z)}$$ work? I am assuming $A(z)$ is nonzero and positive, since we can take its logarithm.
Comment: Yes, sorry, I don't k now how to write it properly.  $A(z)$ is unknown to me, so I can't choose an $f(z)$ in terms of $A(z)$ because I don't know what $A(z)$ will be.  I'd need to find an $f(z)$ that works for any $A(z)$ I guess.
Comment: For some reason my brain thought $A^{-1}(z) = \frac{1}{A(z)}$; please disregard my last comment.
Answer: How about defining $f(z) = {Log(A(z)) \over A(z)}$ for $A(z) \in \mathbb{R}^+$ (not positive $A(z)$ does not makes sense, since you want $log(A(z))$ to exist.
EDIT:
Since author requires $f(z)$ to work for any $A(z)$, the answer is simply no. There is no constant $c$ such that $c\cdot A(z)= log(A(z))$ for general $A(z)$


Received unknown parameter: stripe_account

Question: I am trying to perform a Stripe payment_intent for a Connect Custom account. But I get this error:
Received unknown parameter: stripe_account

My code snippet is:
public function add_order_amount( &$args, $order, $amount = null ) {
        $args['amount'] = wc_stripe_add_number_precision( $amount ? $amount : $order->get_total(), $order->get_currency() );
        $monto = wc_stripe_add_number_precision( $amount ? $amount : $order->get_total(), $order->get_currency() );
        $args['application_fee_amount'] = round( ($monto * 0.01) + 0.30) ;  // 1% + 0.3 USD
        $args['stripe_account'] = 'acct_1L2zW6PuKflLQEIm';
    }

Comment: It does not look like a typical PHP error, is it perhaps generated by your own code somewhere? Are you sure the exception is thrown in this function (perhaps a stack trace is available)?
Answer: There is no parameter called stripe_account in Stripe's API. Usually, this refers to a separate feature called the Stripe-Account header (see doc) which allows you to make requests on behalf of a connected account.
This means you shouldn't be passing the connected account id this way. Instead, you should be setting the connected account as a request header.
You haven't provided much context on your integration but you seem to be using a WooCommerce plugin and they might have a way to configure the connected account such as this function. Otherwise you'll have to modify the code making the HTTP request to set your own Stripe-Account header


Assumption of independence of two correlations for the purpose of a statistical test of the difference.

Question: I'm having a bit of difficulty grasping the concept of 'independence' for the purpose of testing whether two correlations significantly differ from one another (Zou, 2007).
Consider the following made-up example from a sample of adolescents randomly selected from a school:

Student BMI (kg/m2) is correlated with a non-expert rating of diet quality (i.e., each individual has their diet rated by non-experts).
Student BMI (kg/m2) is correlated with an expert rating of diet quality (i.e., each individual has their diet rated by experts).

In this instance, is it appropriate to assume that each correlation is independent of one another and come from separate groups (although BMI from the same individuals features in each correlation)? The purpose of this would be determine if each correlation significantly differs from one another using the Zou method.
Answer: I don't think these two are independent. The BMIs are (of course) the same in the two correlations and the ratings of diet are clearly related to each other.  I mean a diet of fried chicken, Doritos and Coke is likely to get low ratings from just about anyone, expert or not.
For independence, it would have to be different people being rated.
Comment: Thank you for clarifying. It appears the two correlations are best characterised as overlapping dependent correlations. I believe this means I would need to calculate the correlation between non-expert and expert ratings for inclusion of a difference test using the Zou (2007) method.


This version of ChromeDriver has not been tested with Chrome version 75 error with Selenium ChromeDriver and Chrome through facebook/php-webdriver

Question: I'm using selenium, chromedriver, facebook/php-webdriver
But the server always hang after an error
What could be the problem? selenium or php?
here is the php error:
Fatal error: Uncaught Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"w3c":false,"binary":"","args":["--no-sandbox","--headless","--disable-gpu"]}}} Operation timed out after 51627 milliseconds with 0 out of -1 bytes received in /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:297 Stack trace: #0 /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php(144): Facebook\WebDriver\Remote\HttpCommandExecutor->execute(Object(Facebook\WebDriver\Remote\WebDriverCommand)) #1 /var/www/html/php-selenium/s.php(19): Facebook\WebDriver\Remote\RemoteWebDriver::create('http://localhos...', Object(Facebook\WebDriver\Remote\DesiredCapabilities), 50000, 50000) #2 {main} thrown in /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php on line 297

from selenium log:
[1561345982.225][WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.
    03:13:06.892 WARN - Exception thrown
    org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
    Build info: version: '3.8.1', revision: '6e95a6684b', time: '2017-12-01T19:05:32.194Z'
    System info: host: 'shadowsocks-server', ip: '10.140.0.2', os.name: 'Linux', os.arch: 'amd64', os.version: '3.10.0-957.21.3.el7.x86_64', java.version: '1.8.0_212'
    Driver info: driver.version: unknown

Version Info:

ChromeDriver 2.35.528139
Chrome --version Google Chrome 75.0.3770.80

+++++++++++++++++++++
updated June 29th, I have updated chromdriver to 75.0.3770.90, but the problem still persists. nothing changes.
+++++++++++++++++++++ June 30th,2019
I have solved this, with "top" command, I saw a progress whose name was kswapd0 consumed too much CPU. It is a progress which is related to swap, so I add this line to /etc/sysctl.conf:
vm.swappiness=5
and got more RAM, the service has been running for a day. and no hanging any more.
I didn't realize that 1.8GB RAM was not enough for chrome with default configration.
Comment: `[WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.`  What versions of chrome and chromedriver are you running?
Comment: Hi orde,
Starting ChromeDriver 2.35.528139
 chrome --version
Google Chrome 75.0.3770.80
Comment: Please [edit the question](/posts/56729580/edit) to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the [How to Ask](https://stackoverflow.com/help/how-to-ask) page for help clarifying this question.
Comment: `chrome` and `chromedriver.exe` are mismatched: https://sites.google.com/a/chromium.org/chromedriver/downloads.  The concise instructions should point you...
Answer: This php error message...
Fatal error: Uncaught Facebook\WebDriver\Exception\WebDriverCurlException: Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY","chromeOptions":{"w3c":false,"binary":"","args":["--no-sandbox","--headless","--disable-gpu"]}}} Operation timed out after 51627 milliseconds with 0 out of -1 bytes received in /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php:297 Stack trace: #0 /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/RemoteWebDriver.php(144): Facebook\WebDriver\Remote\HttpCommandExecutor->execute(Object(Facebook\WebDriver\Remote\WebDriverCommand)) #1 /var/www/html/php-selenium/s.php(19): Facebook\WebDriver\Remote\RemoteWebDriver::create('http://localhos...', Object(Facebook\WebDriver\Remote\DesiredCapabilities), 50000, 50000) #2 {main} thrown in /var/www/html/php-selenium/vendor/facebook/webdriver/lib/Remote/HttpCommandExecutor.php on line 297

and this selenium error message...
[WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.
03:13:06.892 WARN - Exception thrown
org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException

...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.
Your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using chromedriver=2.35
Release Notes of chromedriver=2.35 clearly mentions the following :

Supports Chrome v62-64

You are using chrome=75.0
Release Notes of ChromeDriver v75.0 clearly mentions the following :

Supports Chrome version 75

So there is a clear mismatch between ChromeDriver v2.35 and the Chrome Browser v75.0

Solution

Upgrade ChromeDriver to  current ChromeDriver v2.75 level.
Keep Chrome version at Chrome v75 level. (as per ChromeDriver v2.75 release notes)
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.

Outro

Curl error thrown for http POST to /session with params: {"desiredCapabilities":{"browserName":"chrome","platform":"ANY" with Selenium and PHPUnit
Facebook\WebDriver Curl error thrown for http POST to /session with params: {"desiredCapabilities"} error
Comment: Thanks for reply. I have installed the new chromedriver. chromedriver -v
ChromeDriver 75.0.3770.90,  the service is still not stable. always thrown "Operation timed out after 50000 milliseconds with 0 out of -1 bytes received", "tab crashed" etc. However, it is better than before because it doesn't crash the server
Comment: @LeeBill Nice to hear _it is better than before_. For the error `tab crashed` see this [discussion](https://stackoverflow.com/questions/53902507/unknown-error-session-deleted-because-of-page-crash-from-unknown-error-cannot/53970825#53970825).


How to deal with missing libraries on Linux? [No Admin privileges and PIP is blocked]

Question: For my work I need to write a GUI using PySide6 for a remote system. The OS is RHEL 7.9 and I have neither admin privileges nor PIP working (blocked by admins), so i can't install anything by myself (and i'm not allowed to anyways).
The script runs perfectly on Windows and Fedora, but it doesn't work on RHEL 7.9:

Since the machine doesn't allow pip, I've included PySide6 in my virtual environment, but there are missing libraries in the system itself, like CXXABI_1.3.9 and GLIBC_2.33 that Shiboken6 needs.
It also didn't work in compiled form (with PyInstaller) because the GLIBC_2.29 is missing.
Naively I copied libstdc++.so.6 and libc.so.6 from a Fedora machine to RHEL and redirected the linking to the libraries with the LD_LIBRARY_PATH environment variable, but because of other dependencies it didn't work.

Is there a solution to make the script work cross-platform and independently?
Answer: One way may be to put the (binary) files in the user bin.
The path for that (at least on my system) is /home/.local/bin
Make sure this is in your $PATH variable, if it isn't already (it should be).
If these are just Python modules, you can just drag the source file into the aforementioned path (make sure they have a shebang so they run). If not, you may have to compile them and then put them there.
Explaination of local bin
Note: This is from my experience
The local bin (/home/.local/bin) is where you can put programs you want to run without installing them globally. It's similar to doing ./file.py, except you don't need to be in the same directory as the file (and you don't have to include ./) I assume, if you include a compiled version of the dependencies you want, it should work.
Comment: Thanks, that helped with another issue i had. But my problem here is that essential libraries are missing from the system itself because it's not up to date (and I'm not allowed/can't update it). PySide6 (like probably other modules) does not contain all necessary files and uses the standard libraries e.g. /lib64/libstdc++.so.6.
Comment: @Niemand Is it possible to put an up-to-date version of these packages in your user bin?
Comment: Yes, i can put files in /home/.local/bin, but some dependencies are missing form the system itself and i can't get all needed files since some are system specific like ld-linux-x86-64.so.2. The python packeges themselves unfortunately don't have all needed dependencies included.
Answer: This won't answer your question about the missing libraries, but I hope it helps solve your current issue with PySide.
I've had a similar problem before, you should always develop on the target platform to get comparable results.
This means that you theoretically have to write, compile and package your program on the RHEL machine. You also need to always develop on the older platform. Forward compatibility is not always guaranteed. I therefore suggest, that you install CentOS 7 in a virtual machine and if your program is not too complicated try to use PySide2 instead of PySide6.


Sufficient condition for holomorphic branch

Question: I am trying to solve the following question:

Find sufficient conditions on $a,b \in \mathbb{R}$ such that there exists an holomorphic branch of $z^a(1 - z)^b$ in the domain $\mathbb{C}\setminus[0,1]$

and I am not really sure how to approach it.
And I understand informally that our definition of $Log(z)$ and $z^\alpha$ on the complex plane is such that they are sets, and a branch is a continuous function into these sets (which means the branch cannot be defined on the entire plane). But I have no idea how to work with these definitions formally.
How do I prove that a branch exists (or does not exist) in a domain? What should be my conditions in this case?
Thanks! :)
Answer: Well one sufficient condition on a and b is to take a and b to both be zero. But it seems clear that there is a "necessary and" missing from the question, so let's move on and try to find necessary and sufficient conditions on a and b.
Well first let's make things a bit easier for ourselves and think about what happens when $b=0$. Then we just have zed to the aye which is equal to $e^{a log(z)}$.
Let's situate ourselves at a (nonzero) point in the complex plane and think about what happens to our function if we go for a wander about a closed loop encircling the origin just once.
Well this is basically increasing the argument of $z$ by $2\pi$, so $log(z)$ increases by $2\pi i$. And so our function is multiplied by $e^{a\pi i}$. I'll pause and point out that this is the key observation. And for a holomorphic branch to exist, of course we must get the same value for our function both before and after we took our little walk.
Now the general case is no harder. You have two factors, but when going for a walk around the interval $[0,1]$, we're just multiplying our function now by $e^{a\pi i}e^{b\pi i}$, which we need to equal one, hence $a+b$ is an integer.
Then WLOG(!) $b=-a$, note that the image of $\mathbb{C}\setminus[0,1]$ under sending $z$ to $z/(1-z)$ is equal to the complex plane with the nonnegative real numbers removed, which is a set on which the logarithm can be consistently defined as an analytic function, so you're OK in this case.


pegar todas as chaves em um array de json com js

Question: tenho um array de json, que atualmente pego os valores dessa forma:
for(element in data){
    data[element]['productor']
}

e minha duvida é a seguinte, teria como eu jogar no html, todas as minhas chaves e valores sem necessariamente saber quais são?
se eu tiro o ['productor'] na tela aparece assim [object Object]
obrigado
Comment: O que seria a variavel `element`?
Comment: Pelo que percebi, data é um array em que seus elementos sao objetos correto? se possível poste um exemplo do array data. Ai consigo de da uma resposta exata de como resolver. Faço esse tipo de acesso diariamente em meus programas.
Answer: Utilizando o método keys da classe Object você obtém um array contendo todas as chaves do array passado. Aí basta efetuar seu loop nessa lista:

//declaro o array "x" e insiro alguns valores
var meuArray = [];
meuArray['a'] = 1;
meuArray['b'] = 2;
meuArray['c'] = 3;
meuArray['d'] = 4;

//array de chaves
var chaves = Object.keys(meuArray);

//loop
for (i of chaves) {
  console.log('exemplo 1:', i, meuArray[i]);
}

Utilizando métodos como forEach, dá para resumir tudo em uma só cadeia.
Para jogar no HTML, basta escolher o elemento que conterá os dados e incrementar seu innerHTML:

var meuArray = [];
meuArray['a'] = 1;
meuArray['b'] = 2;
meuArray['c'] = 3;
meuArray['d'] = 4;

Object.keys(meuArray).forEach(chave => {
  console.log('exemplo 2:', chave, meuArray[chave]);
  document.querySelector('#container').innerHTML += `Chave ${chave}, valor: ${meuArray[chave]} <br>`;
});

Answer: {"productor":"Bush Chemist","genre":"UK Roots","singer":"Culture Freeman","rpm":"45","name":"King David Style","label":"Conscious Sounds","description":"teste","release_date":"2003","inch":"12"}

meu json vem nesse formato, mas ele pode vir isso, menos registros, ou mais registros, precisava pegar a chave e valor dele e colocar no html.
Meu metodo de preencher a tabela recebe o json como parametro
function fillTable(data){
for(element in data){
    //resultSet.innerHTML += JSON.stringify(data[element]);
    resultSet.innerHTML += `
        ${JSON.stringify(data[element])}
    `
}

}
que capturo da minha requisição
function listAll(){
$.ajax({
    type: "GET",
    dataType: "json",
    url: "http://localhost:8000/findAllSource",
    success:function(data){
        fillTable(data);
    },
    error:function(data){
        alert("Error")
        console.log(data);

    }
});

}


Como contar elementos de um Arquivo em C?

Question: Eu tenho o seguinte problema para resolver da faculdade, porém até o momento não enxerguei uma solução válida... Fiz o seguinte código até o momento do envio desde pedido de ajuda.

<code>//
//  2.c
//  IFTM Exercises
//
//  Created by Lelre Ferreira on 10/17/19.
//  Copyright © 2019 Lelre Ferreira. All rights reserved.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, const char * argv[]){

    FILE *p;
    char texto[20];
    char pular = '\n';
    int i = 0, count = 0, rpt = 1;

    p = fopen("Text.txt", "w");
    if (p == NULL) {
        printf("Erro na leitura");
        exit(1);
    }

    while(rpt != 0){
        printf("Digite uma linha: ");
        scanf("%s",      texto);
        fprintf(p, "%s", texto);

        printf("Deseja repetir? ");
        scanf("%d", &rpt);
    }
    fclose(p);

    p = fopen("Text.txt",  "w");
    fread(&texto, sizeof(char), 20, p);
    for (i = 0; i < strlen(texto); i++) {
        if (fscanf(p, "%s\n", &texto[i]) == pular) {
            count++;
        }
    }
    fclose(p);

    printf("Total de linhas: %d\n", count);
    return 0;

}
</code>
Alguém poderia me dar uma dica de como resolver o problema acima?
Comment: Não tem sentido você usar fread e fscanf misturados no mesmo arquivo. Certamente fread não é a melhor opção para a leitura de um arquivo texto. Outra consideração: se for detectado o fim do arquivo e o caractere lido imediatamente antes não for um '\n' você não deveria somar 1 à quantidade de linhas?
Answer: Leire,
Abaixo um exemplo comentado de como efetuar essa leitura, sendo que o nome do arquivo será solicitado ao usuário:
<code>#include<stdio.h>

int main(int argc, char *argv[]) {
  //Nome do arquivo
  char nomeDoArquivo[50];

  printf("Qual o nome do arquivo: ");

  //Solicita o usuário o nome do arquivo que será avaliado a quantidade de linhas
  scanf("%s", nomeDoArquivo);

  //Abre o arquivo como leitura
  FILE *fp = fopen(nomeDoArquivo,"r");

  if (fp == NULL) {
    //Sai do programa caso o arquivo não tenha sido aberto
    printf("Erro ano tentar abrir o arquivo.");
    return 1;
  } else {
    int ch = 0;
    int linhas = 0;

    linhas++;

    //Efetua a contagem de linhas lendo o arquivo e procurando a quebra de linha
    while (!feof(fp)) {
      ch = fgetc(fp);

      if (ch == '\n') {
        linhas++;
      }
    }

    //Fecha o arquivo
    fclose(fp);

    //Exibe a quantidade de linhas
    printf("Quantidade de linhas: %d\n",linhas);

    return 0;
  }
}
</code>
Aqui você consegue executar esse código:
https://repl.it/repls/VividEarnestShelfware

Esse é apenas um exemplo, sempre existem formas distintas de chegar ao mesmo resultado, veja aqui um outro exemplo:
Contar as linhas de um arquivo txt em c / c++
Comment: Daniel! Obrigado, estou começando a ver arquivos agora. Na verdade já foi passado as explicações mas acabei faltando e estou tentando me recuperar. Não tinha conhecimento ainda sobre feof, fgetc dentre outros. Tenho mais algumas atividades similares a essa vou botar em prática! Obrigado.


I have a list of tuples containing dictionaries. How do I edit my code to find the values in a separate list, inside these dictionaries?

Question: I have a data structure L = [(int, dict{key: values}), (int,dict{key: values})...].
Given an input list [0,1] I want to find any dictionary key where both/all values of the input list [0,1] exist.
Currently, my bug is that if I use input_list = [0,1], the function will return a match where the dictionary values are just [0] and where values are [0,1]. Only this second result is desirable. I feel like this is a minute change, but I can't grasp it. What do I change to make this happen?
Code
#Python3
L = [(0, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4]}), (1, {0: [1, 0], 1: [1], 2: [5, 1, 2,], 3: [1, 3], 4: [1, 4]}), (2, {0: [2, 0], 1: [2, 1], 2: [2], 3: [2, 3], 4: [2, 4]}), (3, {0: [3, 0], 1: [3, 1], 2: [3, 2], 3: [3], 4: [3, 4]}), (4, {0: [4, 0], 1: [4, 1], 2: [4, 2], 3: [4, 3], 4: [4]})]

#input_list = (eval(input('Enter your list: ')))
#input_list = ([0,1])
print('Input: ' + str(input_list))
for tupl in L:
    dict_a = (tupl[1])
    matching_key = ([key for key, value in dict_a.items() if all(v in input_list for v in value)])
    print('Node: ' + str(tupl[0]) + ' Match at key(s): ' + str(matching_key))

Output
L = [(0, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4]}), (1, {0: [1, 0], 1: [1], 2: [5, 1, 2,], 3: [1, 3], 4: [1, 4]}), (2, {0: [2, 0], 1: [2, 1], 2: [2], 3: [2, 3], 4: [2, 4]}), (3, {0: [3, 0], 1: [3, 1], 2: [3, 2], 3: [3], 4: [3, 4]}), (4, {0: [4, 0], 1: [4, 1], 2: [4, 2], 3: [4, 3], 4: [4]})]

Enter your list: [0,1]
Input: [0, 1]
Node: 0 Match at key(s): [0, 1]
Node: 1 Match at key(s): [0, 1]
Node: 2 Match at key(s): []
Node: 3 Match at key(s): []
Node: 4 Match at key(s): []

Enter your list: [1,5,2]
Input: [1, 5, 2]
Node: 0 Match at key(s): []
Node: 1 Match at key(s): [1, 2]
Node: 2 Match at key(s): [1, 2]
Node: 3 Match at key(s): []
Node: 4 Match at key(s): []

Thank you:)
Comment: Do you actually want ```input_list == value```?  Or if ```value``` contains all items in ```input_list```?
Answer: You have the code checking if value contains all the items in input_list the wrong way around. all(v in input_list for v in value) checks that all the items in value can be found from input_list. If you change it the other way around it will work as you expected:
all(v in value for v in input_list)

Note that if you would convert input_list to set you could easily check if input_list is a subset of value. That would be easier to understand and more efficient:
L = [(0, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4]}), (1, {0: [1, 0], 1: [1], 2: [5, 1, 2,], 3: [1, 3], 4: [1, 4]}), (2, {0: [2, 0], 1: [2, 1], 2: [2], 3: [2, 3], 4: [2, 4]}), (3, {0: [3, 0], 1: [3, 1], 2: [3, 2], 3: [3], 4: [3, 4]}), (4, {0: [4, 0], 1: [4, 1], 2: [4, 2], 3: [4, 3], 4: [4]})]

input_list = set([0,1])

for tupl in L:
    dict_a = tupl[1]
    matching_key = [key for key, value in dict_a.items() if input_list <= set(value)]
    print('Node: ' + str(tupl[0]) + ' Match at key(s): ' + str(matching_key))

Output:
Node: 0 Match at key(s): [1]
Node: 1 Match at key(s): [0]
Node: 2 Match at key(s): []
Node: 3 Match at key(s): []
Node: 4 Match at key(s): []

Comment: Thank you! This worked perfectly. I see what you did, good lesson
Answer: You can use set subtraction to solve:
#Python3
L = [(0, {0: [0], 1: [0, 1], 2: [0, 2], 3: [0, 3], 4: [0, 4]}), (1, {0: [1, 0], 1: [1], 2: [5, 1, 2,], 3: [1, 3], 4: [1, 4]}), (2, {0: [2, 0], 1: [2, 1], 2: [2], 3: [2, 3], 4: [2, 4]}), (3, {0: [3, 0], 1: [3, 1], 2: [3, 2], 3: [3], 4: [3, 4]}), (4, {0: [4, 0], 1: [4, 1], 2: [4, 2], 3: [4, 3], 4: [4]})]

input_list = (eval(input('Enter your list: ')))
#input_list = [1,5,2]
print('Input: ' + str(input_list))
for tupl in L:
    dict_a = (tupl[1])
    matching_key = []
    for key, lst in tupl[1].items():
        if not (set(lst) - set(input_list)):
            matching_key.append(key)
    print('Node: ' + str(tupl[0]) + ' Match at key(s): ' + str(matching_key))

And I would recommend you to avoid constructions like this [key for key, value in dict_a.items() if all(v in input_list for v in value)] because it confuses, it makes your code hard to understand.
Comment: How would you edit this to improve readability, and keep it efficient? (in reference to niemmi's sollution)
Comment: I think Niemmi's solution is pretty good. Sometimes it's better to avoid expressions like `[key for key, value in dict_a.items() if input_list <= set(value)]`. They are readable though but also they may confuse especially if you want to make some changes in your scipt. The other disadvantage is if you have an error in a line like `[key for key, value in dict_a.items() if input_list <= set(value)]` you don't know exactly which operation led to the exception. But if you do as I showed, the traceback will show you the exact line with the error.
Answer: Please read:
Check if two unordered lists are equal
and How can I compare two ordered lists in python?
Depending on the semantics you want to use when checking for equality you can use one solution or the other. If you are going for a simple ordered list comparison, I would go with:
for tupl in L:
    dict_a = (tupl[1])
    if dict_a != input_list:
        continue
    print('Node: ' + str(tupl[0]) + ' Match at key(s): ' + str(matching_key))

Comment: ```dict_a``` is a dictionary, when would it be equal to a list?
Comment: oops, my bad. Then we would go back to:
Comment: oops again, we would go back to:
    for tupl in L:
        dict_a = (tupl[1])
        matching_key = ([key for key, value in dict_a.items() if v == iinput_list ])
        print('Node: ' + str(tupl[0]) + ' Match at key(s): ' + str(matching_key))


gprc client async response NodeJS

Question: I'm trying to call a simple grpc request in a function but I don't know how to wait for the response and pass it outside the grpc call.
It should be something like that:
Client: (parent, args, context, info) =>{
      client.Get({thing, objects, properties}, function(err, response) {
            //how to return the response outside?
          });
      //await for the response function.
};

Is it possible to return the response in some way outside the client.Get function?
Does someone have some suggestions?
Thank you in advice!
Answer: You have two ways:

Wrap the methods of gRPC from error first callback to promise by yourself.

new Promise((resolve, reject) => client.Get({thing, objects, properties}, function(err, response) {
  if(err) {
    return reject(err)
  }
  resolve(response)
}))

Use grpc-promise to promisify the methods of gRPC client.

const grpc_promise = require('grpc-promise');;
grpc_promise.promisifyAll(client);

Then, you can pass this promisified gRPC client to GraphQL context. (Guess you are using GraphQL based on the function signature).
Then you can return a promise in a GraphQL resolver.
Client: (parent, args, context, info) =>{
  return context.client.Get({thing, objects, properties})
};

gprc client async response NodeJS


How to read string from file and tokenise it into an array?

Question: My question is: How do i read a string that is on multiple lines as one line of string from a file in C? I'm trying to do a binary map and my 1d array is represented as a 2d array. So this is in my "level_1.txt":
//start of file
WIDTH: 4
HEIGHT: 5

11,12,13,14,
21,22,23,24,
31,32,33,34,
41,42,43,44,
51,52,53,54,
// eof

and i would like to get the string "11,12,13,14,21,22...."
And this is my code:
int ImportMapDataFromFile(char *fileName, Map *self)
{
    FILE *pFile;
    char* myStr;

    pFile = fopen(fileName, "r");

    // Check if the file exists:
    if(pFile)
    {
        // scanf width and height
        //fscanf(pFile, "%*s %i %*s %i", &self->width, &self->height);
        /*
        // this doesnt work
        fscanf(pFile, "%*s %i %*s %i %s", &self->width, &self->height, &myStr);
        */
        //printf("%i %i", self->width, self->height);

        // initialise the array
        (self->theScreenMap) = (Grid*)malloc(sizeof(Grid) * self->width * self->height);

        // scan the whole remaining file
        /*
            I dont know how to do this. I tried using fscanf and had a look at fgets
            but i cant seem to make it work sorry.
        */

        // tokenise it
        /*
            Pretty sure i have to use strtok right?
            http://www.cplusplus.com/reference/cstring/strtok/
        */

        // close it
        fclose(pFile);
        printf("%s \n", &myStr);

        return TRUE;
    }
    else
    {
        fclose(pFile);
        return FALSE;
    }
}

What i want to do is read the file, get the size from the 1st 2 lines and use those values to create the 1d array. Then once that's done, i want to read the remaining string and assign it to the array. Eg.
theScreenMap[0] = 11; // first element has 1st token
theScreenMap[1] = 12;
theScreenMap[size - 1] = 54; // last element has last token

Thanks to anyone helping me out. But if anyone has a better way of doing this (read from file and init an array to create binary map), then feel free to tell me so. Thanks! :)
Answer: This is just a basic implementation of what you want. The end result would read as many lines as 'height', and concatenate them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 1024
#define MAXLINE 256

char mainArray[MAXSIZE];
char line[MAXLINE];

char *strdup(const char *s) {
    char *str = malloc(strlen(s) + 1);
    if(str) { strcpy(str, s); }
    return str;
}

int main(int argc,char* argv[])
{
    int width,height;
    unsigned int i=0;
    unsigned int count=0;
    char **grid;
    FILE *fp = fopen("multiline.txt","r");
    if(!fp) {perror("multiline.txt");return -1;}
    /* Read the width and height */
    fscanf(fp,"WIDTH: %d\n",&width);
    fscanf(fp,"HEIGHT: %d\n",&height);
    printf("Width: %d,\tHeight: %d\n\n",width,height);
    while(!feof(fp))
    {
        fgets(line,MAXLINE,fp);
        strncat(mainArray,line,strlen(line)-1); /* get rid of newline */
        printf("Line:: %s",line);
        printf("MainArray:: %s\n\n",mainArray);
    }
    /* Get the number of elements */
    for(i=0;i<strlen(mainArray);i++)
    {
        if(mainArray[i]==',')
            count++;
    }
    /* Allocate the grid and tokezine */
    grid = malloc(sizeof(grid) * count);
    grid[0] = strdup(strtok(mainArray,","));
    for(i=1;i<count;i++)
    {
        grid[i] = strdup(strtok(NULL,","));
    }
    /* Display */
    for(i=0;i<count;i++)
    {
        printf("grid[%2d]:: %s\n",i,grid[i]);
        free(grid[i]); /* free the malloc-ed string */
    }
    free(grid);
    fclose(fp);
    return 0;
}

Output for your sample:
Width: 4,   Height: 5

Line:: 11,12,13,14, MainArray:: 11,12,13,14,

Line:: 21,22,23,24, MainArray:: 11,12,13,14,21,22,23,24,

Line:: 31,32,33,34, MainArray:: 11,12,13,14,21,22,23,24,31,32,33,34,

Line:: 41,42,43,44, MainArray::
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44,

Line:: 51,52,53,54, MainArray::
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44,51,52,53,54,

Line:: 51,52,53,54, MainArray::
11,12,13,14,21,22,23,24,31,32,33,34,41,42,43,44,51,52,53,54,51,52,53,54,

grid [ 0]:: 11
grid [ 1]:: 12
grid [ 2]:: 13
grid [ 3]:: 14
grid [ 4]:: 21
grid [ 5]:: 22
grid [ 6]:: 23
grid [ 7]:: 24
grid [ 8]:: 31
grid [ 9]:: 32
grid [10]:: 33
grid [11]:: 34
grid [12]:: 41
grid [13]:: 42
grid [14]:: 43
grid [15]:: 44
grid [16]:: 51
grid [17]:: 52
grid [18]:: 53
grid [19]:: 54
grid [20]:: 51
grid [21]:: 52
grid [22]:: 53
grid [23]:: 54

Comment: That's weird I could've sworn I already commented on this post. Well anyway...

Hello Binayaka! Thanks for the help. It works a treat :D
Comment: But i have a question though @BinayaChakraborty . Why do you use strdup? Whats the difference between that and strcpy? I tried to understand by researching abt it but i cant really grasp the "why" though (if that makes sense).

// this are the ones that make more sense to me than the rest.
[link](http://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c)
[link](http://stackoverflow.com/questions/4079850/why-do-we-need-strdup)

I understand that it will return a char pointer to a new "string", which is a duplicate of the "string" pointed to the 's' (the argument) but why?
Comment: @mh4: Think about the scope. If you wanted to use the string pointer afterwards, using a valid return address is necessary. Otherwise, it may SEGFAULT


adding comment box in bottom page tab

Question: i make a page test.php with image slide jquery cycle effect, beatport player and other effect all is ok and run..
i try to add comment box on bottom with this code

fb:comments href="https://www.facebook.com/pageadresse" num_posts="8" width="500"></fb:comments>

and positionning comment box via Css
when i test http://myserver/iframe/test.php its ok comment box appears ..
but when i add application to my page comment box dissapears
any help??
thank you.
Answer: First, make sure you have added an xml namespace to the HTML tag of your doc ->

Second, the code you provided is missing an opening '<' tag, so it should be ->
<fb:comments href="https://www.facebook.com/pageadresse" num_posts="8" width="500"></fb:comments>

Third, you don't need to put it in a

, the fb-root div is only needed somewhere on the page for the facebook js-sdk to work.
You can include the javascript sdk and the comment plugin all in one like this ->

<fb:comments href="https://www.facebook.com/pageadresse" num_posts="2" width="500">
</fb:comments>

More info here -> http://developers.facebook.com/docs/reference/plugins/comments/

adding comment box in bottom page tab


Testing a Non-blocking Queue

Question: I've ported the non-blocking queue psuedocode here to C#. The code below is meant as a near verbatim copy of the paper.
What approach would you take to test the implementation?
Note: I'm running in VS2010 so I don't have CHESS support yet.
Edit:
I've removed the code in question so some unsuspecting developer doesn't use it -- it required quite a few changes to get it bug free... and I still wasn't 100% confident that it was bug free. With brute force testing I could not get it to perform better than a lock based solution.
Also, since I'm targeting 3.5 I thought I was SOL with the 4.0 concurrent queue. The 3.5 RX framework includes a ConcurrentQueue so this was indeed just a fun little programming exercise and nothing more.
Answer: If you're using VS 2010 and .NET 4, you can use ConcurrentQueue<T>.
Comment: the question was how to test their implementation.
Comment: Yes, but if the port is avoidable, and you can get a good, tested implementation for free, it'll avoid the reason for the question entirely...
Comment: @jsw: This, btw, is also included for .NET 3.5 in the Rx Framework, and available here: http://msdn.microsoft.com/en-us/devlabs/ee794896.aspx
Comment: Unfortunately I'm targeting .NET 3.5. I actually took a look at their .NET 4.0 implementation in reflector and the queue in question takes a completely different approach; it's the algorithm Joe Duffy recommended in his Parallel Data Structures article...
Answer: when i tried to create non-blocking queue i tested queue this way. i created 10 threads and concurrently called Enqueue 1000 times. At the end i checked size of queue, it was != 10 000. Or sometimes it threw exceptions. Then i tried concurrent deques. Same result. This clearly means that queue is not thread safe.

Testing a Non-blocking Queue


Grouping particular nodes to their parent nodes inside XML

Question: Below given is my Sample XML:
<Response>
    <Transactions>
        <Upload>
            <DocumentID>1</DocumentID>
            <Name>A</Name>
            <DocumentID>2</DocumentID>
            <Name>B</Name>
        </Upload>
        <Upload>
            <DocumentID>3</DocumentID>
            <Name>C</Name>
            <DocumentID>4</DocumentID>
            <Name>D</Name>
        </Upload>
        <Upload>
            <DocumentID>5</DocumentID>
            <Name>E</Name>
            <DocumentID>6</DocumentID>
            <Name>F</Name>
        </Upload>
    <Transactions>
</Response>

Below given is my coming output:
<Total>
    <DocumentID>1</DocumentId>
    <DocumentID>2</DocumentId>
    <DocumentID>3</DocumentId>
    <DocumentID>4</DocumentId>
    <DocumentID>5</DocumentId>
    <DocumentID>6</DocumentId>
</Total>

I am using the following given code for getting my output:
var downloadfolder = @"C:\Users\KUMARMOHANTA\Desktop\New folder\test.xml";

var masterfile = new XDocument();
XElement newDocument = new XElement("Total");
masterfile.Add(newDocument);

XDocument xdoc = XDocument.Load(downloadfolder);

masterfile.Root.Add(xdoc.Descendants("DocumentId"));
masterfile.Save(@"C:\Users\KUMARMOHANTA\Desktop\merged_.xml");

But my desired output should be something like this:
<Total>
    <Transactions>
        <Upload>
            <DocumentID>1</DocumentID>
            <DocumentID>2</DocumentID>
        </Upload>
        <Upload>
            <DocumentID>3</DocumentID>
            <DocumentID>4</DocumentID>
        </Upload>
        <Upload>
            <DocumentID>5</DocumentID>
            <DocumentID>6</DocumentID>
        </Upload>
    <Transactions>
</Total>

Answer: Rename the element Transactions to Total. Remove elements with name Name. Then save the file.
Try this:
var downloadfolder = @"C:\Users\KUMARMOHANTA\Desktop\New folder\test.xml";

XDocument xdoc = XDocument.Load(downloadfolder);
xdoc.Root.Name = "Total";
xdoc.Descendants("Upload").Elements("Name").Remove();

xdoc.Save(@"C:\Users\KUMARMOHANTA\Desktop\merged_.xml");

Note that your XML example does not close the Transactions element.


Encontrar um item mais vendido juntamente com outro

Question: Encontrar um item mais vendido juntamente com outro. Sql server
TABELA VENDA CAMPOS =  ttcupomfiscalitem

TABELA PRODUTO CAMPOS = ( tcprodutos)

Tentei fazer a seguinte consulta sqlserver
SELECT TOP (10) c.chavecontrole   AS cupom,
                p.descricao,
                c.produto,
                Sum(c.quantidade) AS quantidade
FROM   tcprodutos p
       INNER JOIN ttcupomfiscalitem c
               ON p.produto = c.produto
                  AND c.produto = '222110165'
GROUP  BY c.chavecontrole,
          p.descricao,
          c.produto
ORDER  BY quantidade DESC;

Resultado =

Os resultados aparecem o mesmo produto, como fazer para aparecer os outro itens do mesmo cumpom por quantidade?
Comment: Selecione os distintos "cupom" que tem o produto x , faça um select destes "cupom" ( in , exists etc) contando os produtos que não sejam o produto x. Conte os maiores . Devem existir umas 564 outras soluções possíveis deste problema recorrente.    https://pt.stackoverflow.com/questions/226495/achar-o-item-mais-vendido-juntamente-com-determinado-item
Comment: vc tá filtrando pra só um produto... `c.produto = '222110165'`
Comment: @RovannLinhalis, No entanto queria saber qual produto vende mais junto com '222110165',
Como faço para aparecer os outros itens do cupom que tenha o produto = 222110165 no mesmo cupom. Não sei se ficou claro. Não sei como fazer esse filtro.
Comment: Isto responde à sua pergunta? [Achar o item mais vendido juntamente com determinado item](https://pt.stackoverflow.com/questions/226495/achar-o-item-mais-vendido-juntamente-com-determinado-item)
Answer: SELECT TOP(1) p.descricao,
              SUM(i.quantidade) AS quantidade_total
  FROM ttcupomfiscalitem i
       INNER JOIN tcprodutos p ON p.produto = i.produto
 WHERE i.produto <> '222110165'
   AND EXISTS(SELECT 1
                FROM ttcupomfiscalitem i2
               WHERE i2.cupom = i.cupom
                 AND i2.produto = '222110165')
 GROUP BY p.descricao
 ORDER BY 2

Referência: Achar o item mais vendido juntamente com determinado item


Calculate percentage based on two fields, one of which is an embedded view

Question: I am trying to calculate a percentage based on two fields in my table. I am using views and I have a table which has 2 fields, one field is an aggregation of of all records and the other is an embedded view which has another number - I used the Views Field View module for embedding the field.
How can i get a percentage between these 2 fields. The Math Expression field is not supported in drupal 8 and I have also tried the views_simple_math_field and it didn't help me at all. Please help!
Answer: i tried in output code:
<?php
echo count($row->field_a) + count($row->field_a) ;
?>

and the result is:

I modified the view, and used aggregation.

I modified the field a:

I modified the field b:

I modified the field php:

And the code:

And result:
Answer: if you want sum two field, you install the module:
https://www.drupal.org/project/views_php
As an example, add two fields in your content "basic pages":

field_a
field_b

I create a content of example: nid = 43

Please create a new view as is the image.

in your field "Global: PHP (php)"
in the section: "Output code".
sum two fields please use the following code
<?php
echo $row->field_a +$row->field_a ;
?>

preview
Comment: Thamk you very much for your response, But my fields are aggregated as COUNT so its not working


In R, line slope changes when only x values as shifted

Question: I'm new to R, and trying out few examples in it.
I'm trying to find the slope of a plotted graph, using lm function.
My code:
Xvalues: int 1 2 3 4 5 6 7 8 9..
Yvalues: int 202 247 296 336 376 479 553 756 861 957 ...

There are totally 38 values, x ending with 38, y with 4000.
So I did:
> fit<-lm(yval ~ xval)
> fit

Call:
lm(formula = yval ~ xval)

Coefficients:
(Intercept)         xval
     -118.2        106.6

So 106.6 is the slope m in y = mx + c,
but when I start my x values from say 201410 till 201448, I got this:
Call:
lm(formula = yval ~ xval)

Coefficients:
(Intercept)         xval
 -2.145e+07    1.066e+02

the value changes by 170, of course when I do arctan I get angle close to 90, that isn't an issue, but I'm trying to understand why is this large difference in slope, essentially it should be same with variation in Y-intercept c.
Can anyone explain how it calculates the values.
Any help would help me significantly.
Thank you.
Comment: Where does that "170" come from? Note that `106.6=1.066e+02` to the quoted accuracy. It is possible you're unfamiliar with the meaning of the "e+02" part. Can you clarify how you got 170?
Comment: Yes thank you, my bad, I interpreted in a different way,. thank you for the prompt response.
Comment: Should I expand on that a little as an answer?
Comment: That's fine I get it,. I was not familiar with the representation. Thank you. BTW, how do I mark it as solved?
Comment: You can't unless someone answers. Once you have an answer you can indicate you have an answer that solves your problem by clicking the grey check mark (turning it green). I'll write an answer shortly.
Answer: (I just noticed I never came back and answered this, sorry)
The problem appears to be that you're not familiar with how computers represent scientific notation.
In scientific notation, we could write $106.6$ as $1.066\times 10^{2}$. That's just two different ways of representing the same quantity. On a computer that's usually shown as 1.066e+02, so 106.6 = 1.066e+02 to the quoted accuracy.
Which is to say that the two slopes are actually the same.


Need help scheduling my compute engine to start at a certain time

Question: I need someone who can help me script and config my server to where my compute engine vm can boot up Monday - Saturday 7Am in the morning all the time.
If someone can help or guide me, i will really appreciate it.
I only know the most basic scripting language.
I am also willing to pay if that's the only option.
thank you
Answer: First, you need a way to initiate API commands to stop/start your GCE instance. The simplest way to do this is probably to use the gcloud CLI, specifically:

gcloud compute instances start [names] to start virtual machine instance(s)
gcloud compute instances stop [names] to stop virtual machine instance(s)

Next, you need a way to run these commands on a schedule, e.g. to start your VM(s) at 7am Monday through Saturday. You'll need another computer (or service, for example Cloud Functions) to do this. If you have a computer that runs 24x7 (e.g. your home laptop, or another cloud VM) then you can use cron or its equivalent to do this scheduling.


SSIS Flat File Source - Add Line column

Question: In my Flat File source, i have all the columns mapped to output columns with the right type and all.
After retriving the data, i check if the reference contained in the file exists in the database, if they don't, i have to log the line and write which value did not find a match.
So, in order to log the line, I would like top have a column containing the complete original line, just like the error output "Flat File Source Error Output Column".
So my question is: Is there a way to add a column to my Flat File Source, that would contain the complete line, without formatting in the data?
Answer: I would use a Derived Column Task and specify a new column to be added by concatenating all the columns from the text file.
For example, if your text file has the following structure:
Col1, Col2, Col3, Col4, Col5
Your derived column would specify the following Expression:
[Col1] + [Col2] + [Col3] + [Col4] + [Col5]
You could optionally add a delimiter if you wanted to break apart the columns.
This would return an addition column to be used in subsequent data flow tasks.
Comment: that was my first option, but since I added the type of the columns, for eample int fied contains 000123 in file, and it just keeps 123 in the output column. i don't want to change that and use derived columns to format all my fields...
Comment: I see. What if you stuck a Multicast task so that you could split the output into two different branches, one for capturing the original rows, and the other for actual processing?
Comment: I followed your suggestion, since I have no better option, thx.
Comment: No problem. Glad it helped. I would be curious to know if you ever find a better solution, as I have come across a similar situation.

SSIS Flat File Source - Add Line column


Making entities under another entitytype

Question: Suppose, I've created    -name
    -machine_name an entity_type myentity with its schema as:
-name
-machine_name

Next, I want to create another entity subentity that will be grouped under myentity.
I've create both the entities, but somehow during the form making, I'm clueless how to retrieve the myentity data under which I'm creating the subentity and save it.
subentiy schema:
-name
-parent (parent == myentity->machine_name)

Comment: Which entity is the reference field attached to?
Comment: @Clive: I've updated the question. The `subentity` `parent` field should be attached to `myentity` `machine_name`
Answer: I'm not sure if your case is closer to the typical bundle/config entity > content entity use case (because you mention machine name, so that sounds like a config entity to me) or content entity > content entity but the way this works is pretty much the same.
You need to define a route that contains the parent entity ID, then create your entity with the reference to that and then display the add form for it.
Examples for the first use case are for example node type/node or vocabulary/term, the second are comments. While the first is usually not seen as a hierarchy/grouping, it's essentially that.
Route from node.routing.yml:
node.add:
  path: '/node/add/{node_type}'
  defaults:
    _content: '\Drupal\node\Controller\NodeController::add'
    _title_callback: '\Drupal\node\Controller\NodeController::addPageTitle'
  requirements:
    _node_add_access: 'node:{node_type}'
  options:
    _node_operation_route: TRUE

NodeController::add
public function add(NodeTypeInterface $node_type) {
  $account = $this->currentUser();
  $langcode = $this->moduleHandler()->invoke('language', 'get_default_langcode', array('node', $node_type->type));

  $node = $this->entityManager()->getStorage('node')->create(array(
    'uid' => $account->id(),
    'name' => $account->getUsername() ? : '',
    'type' => $node_type->type,
    'langcode' => $langcode ? $langcode : $this->languageManager()->getCurrentLanguage()->id,
  ));

  $form = $this->entityFormBuilder()->getForm($node);

  return $form;
}

The only relevant part is passing through the entity reference value ($node_type) to the new sub-entity. There are issues to make the uid/name and the langcode default value handling work by default.


promox ufw ip routing

Question: I try to setup a proxmox node with an external ip class map to an internal ip class :
62.xxx.yyy.zzz/24 <--> 192.168.yyy.zzz/24
each external ip match on internal ip, so each VM got her own external ip.
the proxmox host got is own external ip (outside the /24 range) and got a web access by himself.
if I use :
    # NAT table rules
    *nat
    :POSTROUTING ACCEPT [0:0]
<code># Forward traffic through eth0 - Change to match you out-interface
-A POSTROUTING -s 192.168.0.0/16 -o vmbr0 -j MASQUERADE

# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT
</code>
all the VM with ip 192.168.x.x can access the web but with the ip address of the host.
If I change the -A POSTROUTING LINE with :
<code>-A PREROUTING  -o vmbr0 -d 62.xxx.yyy.0/24 -j DNAT --to-destination 192.168.yyy.0/24
-A POSTROUTING -o vmbr1 -s 192.168.yyy.0/24 -j NETMAP DNAT --to-destination  62.xxx.yyy.0/24
</code>
I got an error for the DNAT destination not being an ip but a class, it seems that the NETMAP is not supported ...
any idea to point me to ?
Thanks !
Stéphane
Comment: I did try this : [http://stackoverflow.com/questions/35222304/proxmox-kvm-routed-network-with-multiple-public-ips](http://stackoverflow.com/questions/35222304/proxmox-kvm-routed-network-with-multiple-public-ips) with no luck ...
Answer: You should try using iptables 1:1 NAT.
You will need a rule like this:
<code>iptables -t nat -A PREROUTING -i internet_interface -d 62.xxx.yyy.0/24 -j NETMAP --to 192.168.yyy.zzz/24
</code>
I think the link bellow will definetely help you to achieve your goal:
https://serverfault.com/questions/109569/iptables-massive-11-nat
ufw is just an easy way to implement ip tables rules. In your case I think the best approach is to create your own iptables rules without using ufw or any other similar firewall utilities (on linux they are all based on iptables).

promox ufw ip routing


How i show list data from laravel controller

Question: How I can show list data like this one, with list for product, Unit of measure, adjustment quantity, and note.

with this code
<code>$stock = StockAdjustment::with('product_adjustment')->get();
    $data = array();
    foreach ($stock as $list) {
        $row = array();
        $sku = array();
        $product_name = array();
        $available = array();
        $adjust_qty = array();
        $total = array();
        $note = array();
        $date = Carbon::parse($list->create_at);
        $row[] = $date->format('d-m-Y');
        foreach($list->product_adjustment as $product){
            $sku[] = $product->product['sku'];
            $product_name[] = $product->product['product_name'];
            $available[] = $product->available;
            $adjust_qty[] = $product->adjustment_qty;
            $total[] = $product->total;
            $note[] = $product->note;
        }
        $row[] =  $sku;
        $row[] =  $product_name;
        $row[] =  $available;
        $row[] =  $adjust_qty;
        $row[] =  $total;
        $row[] =  $note;
        $row[] = $list->user['name'];
        $data[] = $row;
    }
    return DataTables::of($data)->escapeColumns([])->make(true);
</code>
this is what I got, I can't make list for product name, adjusment quantity, total, and note. It give a coma, not list
Answer: You need to achieve this by adding some stylings
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


svn: Repository moved permanently error - apache configuration issue

Question: I've read all other topics that "seemed" similar on stackoveflow and I couldn't find solution.
When I issue command in local network svn co ip/svn/repo All works fine.
But sometimes I do checkout on remote servers so I need domain set-up with dyndns. I've setup apache long time ago to support this, but have never seen this error before.
So if I do:
svn info https://svn.idev.ge/gamoicanies/

It gives me error: Repository moved permanently to 'https://svn.idev.ge/gamoicanies/'; please relocate
But if I do:
svn info https://svn.idev.ge/gamoicanies/logo

It works just fine.
So my problem is that I cannot checkout root of repository. But I can do fine with sub directories.
Directory structure for my repo is such:
/var/svn/repo1
/var/svn/repo2

My subdomain svn.idev.ge goes directly to /svn/ dir. And I presume this is the root of all my troubles. Any ideas how to fix my apache config to maintain subdomain without adding extra useless svn dir like https://svn.idev.ge/svn/gamoicanies/ And be able to checkout?
Apache file looks like this:
<VirtualHost *:80>

   ServerName svn.idev.ge
   ServerAlias www.svn.idev.ge
   Redirect permanent / https://svn.idev.ge/

</VirtualHost>

<VirtualHost *:443>

  ServerAdmin firstname.lastname@example.com
  ServerName svn.idev.ge
  ServerAlias www.svn.idev.ge

   DocumentRoot /var/svn/

       SSLEngine On
       SSLCertificateFile    /etc/apache2/ssl/server.crt
       SSLCertificateKeyFile /etc/apache2/ssl/server.key

   <Directory />
    Order allow,deny
    allow from all
   </Directory>

    <Location />
      DAV svn
      SVNParentPath /var/svn/
      SVNListParentPath On
      AuthType Basic
      AuthName "Subversion Repository"
      AuthUserFile /etc/apache2/passwords
      Require valid-user
      AuthzSVNAccessFile /var/svn/svnusers.conf
    </Location>

</VirtualHost>

Please this is very frustrating.
Answer: You're not using that DocumentRoot for anything, just change it to something else that's not a parent of the SVN directory, or remove it altogether and let the server's default (probably /var/www/ or /var/www/html) be used instead.  The directory overlap is the cause of the problem.
By the way, this block:
<Directory />
  Order allow,deny
  allow from all
</Directory>

..is probably not what you want to do; putting an allow on the filesystem root is never necessary and potentially a serious security problem.
Put your Order and Allow directives within the <Location /> block instead.
Comment: Can you please give me example of how you would rewrite my apache file? I'm new to server administration, and frankly I don't understand much... Would not it be equal security risk to put allow directive under location? I thought directory was the location :S
Comment: @SandroDzneladze Just two changes to what you have there.  1) Remove the `DocumentRoot /var/svn/` line.  2) Remove `` and move the stuff inside it to inside `` - directory is actually the filesystem, so you're setting the service to allow access to everything on the entire server.
Comment: 1 more question, I'm running apache with www-data user, this user doesn't have ability to write to filesystem other than specific files and folders. Even if I give apache write access to filesystem it won't be, because of user it is running under, correct? or am I completely out of the concept here? :)
Comment: @SandroDzneladze Right - the `Order` and `Allow` directives are controlling what resources a user can request; that doesn't have any bearing on where the processes running under the `www-data` user can read/write data on the filesystem.  For that, you'll just want to give the user the access to do what it needs to do; for `mod_dav_svn` to operate correctly for instance, you should `chown -R www-data:www-data /var/svn/`.


Python base64 72 chachters per line

Question: How can I encode a binary file in base64 and have 72 characters per line?
This is what I have tried but it is not working and i do not know if I am  properly formatting the output so that it can be decoded.
import base64

fin = open("/Users/kyle/one_time_pad/encrypt/cipher_text.txt", "rb")
binary_data = fin.read()
fin.close()

b64_data = base64.b64encode(binary_data)
file = b64_data

def split_len(seq, length):
    return [seq[i:i+length] for i in range(0, len(seq), length)]

def organize():
    for a in split_len(file, 72):
        print a

open("/Users/kyle/Desktop/test.txt", "w").write(organize())

It gives the error TypeError: expected a character buffer object
Comment: In the future, please don't just quote the error, tell us _where_ the error occurs. (The simplest way to do that is by just quoting the whole traceback.)
Answer: def organize():
    return "\n".join(split_len(file, 72))

should return a string which is what write is expecting
on a side note it is probably better to do
with open(filename,"w") as f:
        f.write(organize())

as this will ensure the file is closed when finished (although tbh your version would likely be garbage collected fairly quick)
Comment: `a in foo` is not a valid generator expression. If you meant `a for a in foo`, that's valid, but it's the same as just using `foo` in the first place. So it's not clear what you were trying to do here.
Comment: whoa I must be tired :P
Answer: It's always worth skimming the stdlib before trying to reimplement the wheel. The textwrap module is perfect for this purpose:
file = b64_data
file72 = textwrap.fill(b64_data, 72)
open("/Users/kyle/Desktop/test.txt", "w").write(file72)

There are two things wrong with your existing code.
First, you're creating a list of strings from split_len, but trying to write it out as a single string with write.
Second, your organize function tries to fix this… but it actually doesn't return anything, it just prints out a bunch of stuff, so what actually gets passed to write is the default return value of None.
Anyway, you need to actually accumulate the values into something. You could to that explicitly:
def organize(f):
    result = ''
    for a in split_len(f, 72):
        if result: result += '\n'
        result += a

… or you could again turn to the included batteries and look for a function that already does this:
def organize(f):
    return '\n'.join(f)

Or, you could just do the write once each time through the loop:
with open("/Users/kyle/Desktop/test.txt", "w") as f:
    for a in split_len(file, 72):
        f.write(a + '\n')

Or you could just leave it as a list and call writelines with that list (but then you'll have to change split_len so it adds the \n at the end of each line, or call writelines on a comprehension that does that for you).

A few side notes:
You should always close your files when you open them, and using a with statement makes that easier:
with open("/Users/kyle/Desktop/test.txt", "w") as f:
    f.write(file72)

In general, a function like your organize that just does something to a global variable that you're only going to call once is not helping anything, because it's no more reusable than just running the code inline. If you want it to be reusable (and debuggable, etc.), have it take a parameter. If you don't need it to be reusable, just write it inline.

Python base64 72 chachters per line


an alternate formulation of power set axiom

Question:
(Analysis 1 by Tao) Show that Axiom 3.10 can in fact be deduced from Lemma 3.4.9 and the other axioms of set theory, and thus Lemma 3.4.9 can be used as an alternate formulation of the power set axiom. (Hint: for any tow sets $X$ and $Y$, use Lemma 3.4.9 and the axiom of specification to construct the set of all subsets of $X \times Y$ which obey the vertical line test. Then use Exercise 3.5.10 and the axiom of replacement.)
Axiom 3.10 (Power set axiom). Let $X$ and $Y$ be sets. Then there exists a set, denoted $Y^X$, which consists of all the functions from $X$ to $Y$, thus
  $$f \in Y^X \iff (\text{$f$ is a function with domain $X$ and range $Y$}).$$
Lemma 3.4.9. Let $X$ be a set. Then the set
  $$\{Y: \text{$Y$ is a subset of $X$}\}$$
  is a set.
Exercise 3.5.10. If $f: X \to Y$ is a function, define the graph of $f$ to be the subset of $X \times Y$ defined by $\{(x, f(x)) : x \in X\}$. Show that two functions $f: X \to Y$, $\tilde{f}: X \to Y$ are equal if and only if they have the same graph. Conversely, if $G$ is any subset of $X \times Y$ with the property that for each $x \in X$, the set $\{y \in Y: (x,y) \in G\}$ has exactly one element (or in other words, $G$ obeys the vertical line test), show that there is exactly one function $f: X \to Y$ whose graph is equal to $G$.

Attempt: We know the existence of $2^X$ and $2^Y$ from Lemma 3.4.9. Then, we can create the set $\{X \times Y: X \in 2^X, Y\in 2^Y\}$ (?). Using the axiom of specification with ($P(X \times Y) \iff \text{there exists a unique $y$ for each $x$ for $(x,y) \in X \times Y$}$), we have  $\{X \times Y: X \in 2^X, Y\in 2^Y ;  \text{$P(X \times Y)$ is true}\}$. Each element of this set is the same as the set $G$ in Exercise 3.5.10. Therefore, similarly with Exercise 3.5.10, using the replacement theorem (?), we have $\{y \in Y: (x,y) \in X\times Y; X \in 2^X, Y\in 2^Y ;  \text{$P(X \times Y)$ is true}\}$.
I am first wondering if my argument sounds okay. Also, my attempt fails to derive Axiom 3.10. How can I proceed from here?
Answer: I did something similar but applied the property to a subset of $X \times Y$ instead of applying it directly to $X \times Y$. Not 100% about it but here is my full answer:
Let $X, Y$ be sets. Let $G$ be a subset of $X \times Y.$ If $G \subseteq X \times Y$, then $G \in 2^{\{X\times Y\}}$ (Lemma 3.4.9). For all the ordered pairs in $G$, we can apply the axiom of specification to form the subset of $G$ with the property $P(x,y)$ such that for each $x \in X$ there is at most one $y \in Y$ for which $P(x,y)$ is true $(\forall x \exists !y((x,y)\in G))$. Hence, we get the subset {$z \in G: P(x,y)$ is true}. From exercise 3.5.10 and the axiom of substitution, we know that given the existence of such a property, $P(x,y)$, there is a function $f: X \rightarrow Y$, and the image of the domain under the function generates a new set. Thus, for each
        $x \in X$, the set $\{y \in Y: (x,y) \in G\}$ has exactly one element, and $G$ is indeed associated with a unique function (proved in last exercise). From this we get our definition of the graph of $f$ (still a subset of $X \times Y$) as $G_f = \{(x,f(x)):x \in X\}.$ Then the collection of all the functions from $X \rightarrow Y$, is the collection of all the subsets of $X \times Y$ (like $G$), with a property $P(x,y)$ satisfying the vertical line test: $\forall x \forall y \forall z ((P(x,y) \wedge P(x,z)) \implies y = z)$.


Creating automatic crud grid and actions with Sylius (Symfony bundle)

Question: I tried to use Sylius Grid system to make my articles management easy.
So, I followed the Sylius doc and I see the grid with my articles displayed. Then I've added action buttons but when I want to use them, I have an error (only for edit and create. Delete works well): Class "form" is not configured for resource "blog.article".
I understand that it can't find any FormClass to render my Article, but there is not this information in the doc, and I think I saw on a doc (I don't remember which) that the form is rendered automatically according to the Entity.
Here is my code :
Declaration of the resource :
sylius_resource:
    resources:
        blog.article:
            driver: doctrine/orm
            classes:
                model: BlogBundle\Entity\Article

The grid config :
sylius_grid:
    grids:
        blog_admin_article:
            driver:
                name: doctrine/orm
                options:
                    class: BlogBundle\Entity\Article
            sorting:
                date: asc
            fields:
                titre:
                    type: string
                    label: sylius.ui.title
                    sortable: ~
                date:
                    type: datetime
                    label: sylius.ui.date
                    sortable: ~
                resume:
                    type: string
                    label: sylius.ui.resume
                    sortable: ~
            filters:
                search:
                    type: string
                    label: sylius.ui.search
                    options:
                        fields: [titre, resume ]
            actions:
                main:
                    create:
                        type: create
                        label: sylius.ui.create
                item:
                    update:
                        type: update
                    delete:
                        type: delete
                    show:
                        type: show

The route :
blog_admin_article:
    resource: |
        alias: blog.article
        section: admin
        templates: SyliusAdminBundle:Crud
        except: ['show']
        redirect: update
        grid: blog_admin_article
        vars:
            all:
                subheader: blog.ui.articles.subtitle
            index:
                icon: 'newspaper icon'
    type: sylius.resource

Does anyone know what is the problem  ?
Thanks for your help !
Answer: Since the autogeneration of forms was disabled in the beta1, there are 2 ways to solve your problem:

Create and declare your own form type like here in the docs (ArticleType).
Use dev-master branch of Sylius instead of beta1, where the autogeneration is back.
Comment: Thanks CoderMaggie, I will try this.
How can I know there is newer version ? I saw on the composer doc there is a "outdated" option, but it does not work with my composer...
Comment: Changing "sylius/sylius": "^1.0@beta" to "sylius/sylius": "dev-master", I have an error when I want to show the articles at the url "/articles" which worked before : `"Unable to generate a URL for the named route "blog_admin_article_show" as such route does not exist."`
Comment: Ok, it was the `show:
                        type: show` that was a problem in my grid config.
Comment: Glad you've managed to fix it. :) When it come to releases, you have to follow Sylius (blog, twitter, github, slack, whatever you want).


How do I create a link to a view in Commerce Order listing?

Question: I want to create a link on an order dropdown menu in commerce order that is attached to a view.  So for example, when you are looking at the list of orders, there is a drop down menu which has Quick Edit, Payment, Delete, etc.  I want to another element to this drop down menu which points to a view that I have created.
I have successfully added a link this dropdown menu using the following code, but it links to a form.
<code>$items['admin/commerce/orders/%commerce_order/cancel'] = array(
    'title' => 'Cancel',
    'page callback' => 'bh_order_handling_ui_order_cancel_form_wrapper',
    'page arguments' => array(3),
    'access callback' => 'bh_order_handling_ui_cancel_access',
    'access arguments' => array(3),
    'type' => MENU_LOCAL_TASK,
    'weight' => 30,
    'context' => MENU_CONTEXT_INLINE,
);
</code>
What I want to do is link to a view that I have created at the path admin/commerce/orders/%/takehomeitems.
I have tried the following, using suggestions from http://zufelt.ca/blog/embedding-view-menu-hook-drupal
<code>$items['admin/commerce/orders/%/takehomeitems'] = array(
        'title' => 'Take Home Items',
        'page callback' => 'views_embed_view',
        'page arguments' => array('bh_view_customer_donation_line_item','default',3),
        'access callback' => 'bh_donate_takehomeorder_access',
        'access arguments' => array(3),
        'type' => MENU_LOCAL_TASK,
        'weight' => 10,
        'context' => MENU_CONTEXT_INLINE,
        'file path' => drupal_get_path('module', 'views'),
        'file' => 'views.module',
);
</code>
Answer: I needed to call views_embed_view in my own page callback because I needed to pass the commerce order id for my contextual filter.  Here is what I did:
I first defined the menu item.  Note that the path has %commerce_order instead of just %. This is needed to access the order object which has the id.
When creating the view, I put in in a separate path, not the path I used for the $items.  When I tried to use the same path, it didn't work.  I think it is because the $items path is needed to create the listing in the dropdown menu.
I defined the path of my view as something that was not admin/commerce/orders/%commerce_order/takehomeitems
It is important that your view have a contextual filter which takes the order id. My path was /admin/hubadmin/takehomeitems/%
See the bottom of my posted answer for the exported view example.
Then in hook_menu, i defined the following:
<code> $items['admin/commerce/orders/%commerce_order/takehomeitems'] = array(
   'title' => 'Take Home Items',
   'page callback' => '_bh_donate_takehome_lineitems',
   'page arguments' => array(3),
   'access callback' => 'bh_donate_takehomeorder_access',
   'access arguments' => array(3),
   'type' => MENU_LOCAL_TASK,
   'weight' => 10,
   'context' => MENU_CONTEXT_INLINE,
 );
</code>
I then defined the page callback which calls views_embed_view and by passing in the %commerce_order, I am able to get the order id
<code>function _bh_donate_takehome_lineitems($order) {
  return views_embed_view('YOURVIEWNAME', 'YOURDISPLAYID', $order->order_id);
} //DISPLAYID is usually default. To find this out, choose to export your view and look at $handler = $view->new_display('default', 'Master', 'default'); The last parameter is the display id.
</code>
This creates a item in the dropdown menu of the order which links to a view. The breadcrumb path points to the order.
Here is my exported view that worked for an example.
<code>$view = new view();
    $view->name = 'bh_view_customer_donation_line_item';
    $view->description = '';
    $view->tag = 'default';
    $view->base_table = 'commerce_order';
    $view->human_name = 'BH View: Customer Take Home Line Items';
    $view->core = 7;
    $view->api_version = '3.0';
    $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

    /* Display: Master */
    $handler = $view->new_display('default', 'Master', 'default');
    $handler->display->display_options['title'] = 'Customer Take Home Line Items';
    $handler->display->display_options['use_more_always'] = FALSE;
    $handler->display->display_options['access']['type'] = 'none';
    $handler->display->display_options['cache']['type'] = 'none';
    $handler->display->display_options['query']['type'] = 'views_query';
    $handler->display->display_options['exposed_form']['type'] = 'basic';
    $handler->display->display_options['pager']['type'] = 'full';
    $handler->display->display_options['pager']['options']['items_per_page'] = '10';
    $handler->display->display_options['style_plugin'] = 'table';
    $handler->display->display_options['style_options']['columns'] = array(
        'vendor_user_reference' => 'vendor_user_reference',
        'commerce_product' => 'commerce_product',
        'quantity' => 'quantity',
        'commerce_unit_price' => 'commerce_unit_price',
        'commerce_total' => 'commerce_total',
    );
    $handler->display->display_options['style_options']['default'] = '-1';
    $handler->display->display_options['style_options']['info'] = array(
        'vendor_user_reference' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_product' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'quantity' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_unit_price' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
        'commerce_total' => array(
            'sortable' => 0,
            'default_sort_order' => 'asc',
            'align' => '',
            'separator' => '',
            'empty_column' => 0,
        ),
    );
    $handler->display->display_options['style_options']['empty_table'] = TRUE;
    /* Relationship: Commerce Order: Referenced line items */
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['id'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['table'] = 'field_data_commerce_line_items';
    $handler->display->display_options['relationships']['commerce_line_items_line_item_id']['field'] = 'commerce_line_items_line_item_id';
    /* Relationship: Commerce Line item: Referenced products */
    $handler->display->display_options['relationships']['commerce_product_product_id']['id'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['relationships']['commerce_product_product_id']['field'] = 'commerce_product_product_id';
    $handler->display->display_options['relationships']['commerce_product_product_id']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Product: Vendor User Reference */
    $handler->display->display_options['fields']['vendor_user_reference']['id'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['field'] = 'vendor_user_reference';
    $handler->display->display_options['fields']['vendor_user_reference']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['fields']['vendor_user_reference']['label'] = 'Vendor ';
    $handler->display->display_options['fields']['vendor_user_reference']['element_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['vendor_user_reference']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['vendor_user_reference']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Product */
    $handler->display->display_options['fields']['commerce_product']['id'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['table'] = 'field_data_commerce_product';
    $handler->display->display_options['fields']['commerce_product']['field'] = 'commerce_product';
    $handler->display->display_options['fields']['commerce_product']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_product']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_product']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_product']['type'] = 'commerce_product_reference_sku_link';
    $handler->display->display_options['fields']['commerce_product']['settings'] = array(
        'show_quantity' => 0,
        'default_quantity' => '1',
        'combine' => 1,
        'show_single_product_attributes' => 0,
        'line_item_type' => 'product',
    );
    $handler->display->display_options['fields']['commerce_product']['field_api_classes'] = TRUE;
    /* Field: Commerce Line Item: Quantity */
    $handler->display->display_options['fields']['quantity']['id'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['table'] = 'commerce_line_item';
    $handler->display->display_options['fields']['quantity']['field'] = 'quantity';
    $handler->display->display_options['fields']['quantity']['relationship'] = 'commerce_line_items_line_item_id';
    /* Field: Commerce Line item: Unit price */
    $handler->display->display_options['fields']['commerce_unit_price']['id'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['table'] = 'field_data_commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['field'] = 'commerce_unit_price';
    $handler->display->display_options['fields']['commerce_unit_price']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_unit_price']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_label_colon'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_unit_price']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_unit_price']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_unit_price']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_unit_price']['field_api_classes'] = TRUE;
    /* Field: Commerce Line item: Total */
    $handler->display->display_options['fields']['commerce_total']['id'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['table'] = 'field_data_commerce_total';
    $handler->display->display_options['fields']['commerce_total']['field'] = 'commerce_total';
    $handler->display->display_options['fields']['commerce_total']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['fields']['commerce_total']['element_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_wrapper_type'] = '0';
    $handler->display->display_options['fields']['commerce_total']['element_default_classes'] = FALSE;
    $handler->display->display_options['fields']['commerce_total']['click_sort_column'] = 'amount';
    $handler->display->display_options['fields']['commerce_total']['settings'] = array(
        'calculation' => FALSE,
    );
    $handler->display->display_options['fields']['commerce_total']['field_api_classes'] = TRUE;
    /* Contextual filter: Commerce Line Item: Order ID */
    $handler->display->display_options['arguments']['order_id']['id'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['table'] = 'commerce_line_item';
    $handler->display->display_options['arguments']['order_id']['field'] = 'order_id';
    $handler->display->display_options['arguments']['order_id']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['arguments']['order_id']['default_action'] = 'empty';
    $handler->display->display_options['arguments']['order_id']['title_enable'] = TRUE;
    $handler->display->display_options['arguments']['order_id']['title'] = 'Order %1';
    $handler->display->display_options['arguments']['order_id']['default_argument_type'] = 'fixed';
    $handler->display->display_options['arguments']['order_id']['summary']['number_of_records'] = '0';
    $handler->display->display_options['arguments']['order_id']['summary']['format'] = 'default_summary';
    $handler->display->display_options['arguments']['order_id']['summary_options']['items_per_page'] = '25';
    /* Filter criterion: Commerce Product: Vendor User Reference (vendor_user_reference) */
    $handler->display->display_options['filters']['vendor_user_reference_uid']['id'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['table'] = 'field_data_vendor_user_reference';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['field'] = 'vendor_user_reference_uid';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['relationship'] = 'commerce_product_product_id';
    $handler->display->display_options['filters']['vendor_user_reference_uid']['operator'] = 'not empty';
    /* Filter criterion: Commerce Line Item: Type */
    $handler->display->display_options['filters']['type']['id'] = 'type';
    $handler->display->display_options['filters']['type']['table'] = 'commerce_line_item';
    $handler->display->display_options['filters']['type']['field'] = 'type';
    $handler->display->display_options['filters']['type']['relationship'] = 'commerce_line_items_line_item_id';
    $handler->display->display_options['filters']['type']['value'] = array(
        'product' => 'product',
    );

    /* Display: Page */
    $handler = $view->new_display('page', 'Page', 'page');
    $handler->display->display_options['path'] = 'admin/hubadmin/takehome-items/%';
</code>


Show that every algebraic subset of $\Bbb A^2(\Bbb R)$ is equal to $V(F)$ for some $F∈\mathbb R[X,Y]$.

Question:
Show that every algebraic subset of $\Bbb A^2(\Bbb R)$ is equal to $V(F)$ for some $F∈\mathbb R[X,Y]$.

Suppose $X=V(S)$ for some set $S \subseteq \Bbb R[X,Y]$. Now $V(S)=V(<S>)$ where $<S>$ is the ideal generated by $S$. Now $\Bbb R[X,Y]$ being Noetherian $<S>=<\{f_1,...,f_n\}>$. Now how to create a single polynomial out of this?
Is this be $F=f_1+ \cdots + f_n$? Because $V(S)= \cap_{i=1}^n V(f_i)$..
But one thing is to think that if the underlying field $\Bbb k$ is algebraically closed then what will happen?
Answer: Note that $\sum_i f_i$ will not work in general, for the different $f_i$ could cancel, e. g. we have that $V(X) \cap V(-X) \ne V(X - X) = V(0) = \mathbf A^2(\mathbf R)$. But $\sum_i f_i^2$ will do.

Addendum (thanks to @Hoot): If $k$ is algebraically closed, the corresponding result over $k[X,Y]$ does not hold, consider $A = \{0\} \subseteq \mathbf A^2(k)$. $A$ is algebraic, as $A = V(X,Y)$, but for any $F \in k[X,Y]$, we have $V(F) \ne A$: For suppose there were $F \in k[X,Y]$ with $A =  V(F)$ given, then $F$ is not a constant. Write $F(X,Y) = \sum_{k=0}^N a_k(X)Y^k$ with $a_N(X) \ne 0$. W.l.o.g. we have $N > 0$ (otherwise exchange the roles of $X$ and $Y$). Then for $x \in k \setminus \{0\}$, $f(Y) := f(x,Y)$ is a non-constant polynomial in $k[Y]$, hence has a root $y \in k$ due to algebraic closure. Hence $(x,y) \in V(F) \setminus A$. Contradiction.
Comment: But what is the case if $k$ is algebraically closed? Is the result still holds?
Comment: @user152715 Try to find a single polynomial that cuts out the origin in $\mathbf C^2$.
Comment: $f(x,y)=x$ will cut the origin in $\Bbb C^2$ right?
Comment: @user152715 Added something.


Rank of Noetherian modules

Question: Suppose $M$ is a Noetherian left-module, why is the rank of $M$ unique? that is if $M^{r} \cong M^{s}$ as left modules then why $r=s$? Is this true if $M$ is Artinian?
Comment: Dear user, if indeed  $M^{r} \cong M^{s}$ implied $r=s$, how would you then define the rank of $M$ if $M$ is not free? (If $M$ is free then all is clear since you reduce to $M=R^n$)
Comment: Dear user: all right,  I'll post an answer in the commutative case
Comment: Dear user: Take $M=0$.
Answer: The property you ask about is true if  the base ring $R$ is commutative.
Indeed,  if $\mathfrak m\subset R$ is maximal, consider the field $k=R/ \mathfrak m$.
If $M$ is a finitely generated non-zero $R$ module, then from $M^r\cong M^s$ , you deduce that $(M\otimes_R k)^r=M^r\otimes_R k\cong M^s\otimes_R k=(M\otimes_R k)^s$.
Since $M\otimes_R k$ is finite-dimensional, the isomorphism  $(M\otimes_R k)^r\cong (M\otimes_R k)^s$ forces $r=s$.
Generalization
The above proof generalizes to the case where there exists  a ring morphism $\phi: R\to k$, where $k$ is a commutative field.
For example this is the case when $R=k[G]$ is the group ring over an arbitrary group $G$ and $\phi(\sum q_g \cdot g)=\sum q_g$.
Comment: Dear Georges, Two minor points: you are implicitly assuming that $M$ is f.g., and that $M$ is non-zero.  Best wishes,
Comment: Dear @Matt, you are absolutely right and have outbourbakied me! I have  now edited my answer. Thanks for your interest.
Answer: For the general (not necessarily commutative case), the key concept seems to be that of Hopfian module, a concept that has appeared several times before on this forum (although I don't have time to find the links now).
Label the numbers $r$ and $s$ so that $r > s$.
Since $M$ is Noetherian, so is $M^s$; thus it is also Hopfian (see the above link). The composite $M^s \cong M^r \to M^s$, in which the first arrow is the presumed isomorphism, and the second arrow is projection onto the first $s$ places, is a surjective endomorphism of $M^s$, which is thus necessarily injective, since $M^s$ is Hopfian.  The only way this can happen is if $M = 0$, or else  if $r = s$.
Thus if $M^r \cong M^s$, then either $M = 0$ or $r = s$.

Rank of Noetherian modules


Getting coverage using OpenCover for Selenium tests

Question: The background:
We have a project starting a service that gets controlled from the web interface GUI.
We're not using a specific (from a commercial point of view) web server, but an in-house created wrapper around the windows service that manages all the web interface interactions.
What we have:
Now we've started using Selenium & MSTest for testing the web interface and we're trying to get a coverage for these kind of tests, and OpenCover seemed to do the deal. The problem is that is not (or we're doing something different or wrong).
The only code coverage that I'm not getting is the one for the method used to start the windows service and all others that get called in the process (since I have all access to all the PDBs too), but afterwards nothing is covered, based on the action that take place from the Selenium's interaction with the browser.
Any hints/ideas or maybe other tools that are able to do the job (if even possible) are appreciated.
Answer: If you're running an ASP.net app, you're going to need to attach OpenCover to IIS or IISExpress to get accurate code coverage with selenium. That makes it a little hard to use MSTest with. You may want to consider moving as much logic into your services, and write unit tests against those.
Here's a quick example hot to attach open cover to IIS
OpenCover.Console.exe -target:C:\Windows\System32\inetsrv\w3wp.exe -targetargs:-debug
-targetdir:C:\Inetpub\wwwwoot\MyWebApp\bin\ -filter:+[] -register:user


How to generate SQL from fixture YMLs in Symfony 1.0?

Question: I am trying to build a script to automate the update process for symfony projects. E.g. apply any patches from one revision to another including any possible model updates and new fixtures without re-loading the entire database.
I have completed most of it, but I have been unable to find a way to generate an SQL file containing the INSERT statements that get executed by propel load data when it inserts the fixture.
I know that I could dump the database to get the info, but that's not the point and that wouldn't work in my case because I'd need an empty db that has no other data on it.
So in short, my question is: Is there a way to take a fixture YML and generate the SQL inserts necessary?
I know this could be done by processing the yml and building the logic, but the build process it does it somewhere and there's no reason to write that again..
Any help would be much appreciated.
Answer: Perhaps I did not understand your question correctly, but couldn't you just call the task that loads the fixtures into the db, or alternatively write code that calls sfPropelData::loadData() (I'm assuming Propel here).
<code>$loader = new sfPropelData();
$loader->loadData(sfConfig::get('sf_data_dir').'/fixtures');
</code>
Even sfPropelData and its parent sfData do not generate sql code when loading fixtures, but rather do it using the ORM (as can be seen in sfPropelData::loadDataFromArray().
If you explained your problem more, and why this solution isn't enough, I may be able to help.
Comment: Hi,

Thanks for your comments... My problem is outlined in the question itself:

I am trying to build a script to automate the update process for symfony projects. E.g. apply any patches from one revision to another including any possible model updates and new fixtures without re-loading the entire database.

Thanks!!


Is there an alternative way to import data into Postgres than using psql?

Question: I am under strict corporate environment and don't have access to Postgres' psql. Therefore I can't do what's shown e.g. in the SO Convert SQLITE SQL dump file to POSTGRESQL. However, I can generate the sqlite dump file .sql. The resulting dump.sql file is 1.3gb big.
What would be the best way to import this data into Postgres? I also have DBeaver and can connect to both databases simultaneously but unfortunately can't do INSERT from SELECT.
Comment: You can use `psql` on a remote machine to connect.
Comment: What can you access other than a crippled DBeaver? Perl?  Python?  R?
Comment: @jjanes I have Python available
Answer: I think the term for that is 'absurd', not 'strict'.
DBeaver has an 'execute script' feature.  But who knows, maybe it will be blocked.
Comment: Thanks but DBeaver 'execute script' is based on `psql` :((( so it complains that `psql` isn't available.
Answer: EnterpriseDB offers binary downloads. If you unzip those to a local drive you might be able to execute psql from the bin subdirectory.
Answer: If you can install psycopg2 or pg8000 for python, you should be able to connect to the database and then loop over the dump file sending each line to the database with cur.execute(line) .  It might take some fiddling if the dump file has any multi-line commands, but the example you linked to doesn't show any of those.