Como passar lista de um picklist (bootstrap) via POST (ajax)

Question: Bom dia, não sei como passar os dados deste componente para meu controller java.
Veja imagem:

Por exemplo, eu tenho estes campos que passo por requisição POST ao meu controller e funcionam OK, chega até o controller java:
BoxApp.controller("CadastroCertificadoController", function($scope, $http) {

    $scope.clientes = {};

    $scope.iniciar = function() {
        $http.get('/boxmlV2/cadastrocertificado').success(function(response) {
            $scope.clientes = response;
        });
    };

    $scope.iniciar();
    $scope.clientes2 = [];

    $scope.atribuirUm = function(index, c) {
        $scope.clientes2.push(c);
        $scope.clientes.splice(index, 1);
    }

    $scope.limparUm = function(index, c2) {
        $scope.clientes2.splice(index, 1);
        $scope.clientes.push(c2);
    }

    /*
    * Trecho para validar o form ao submeter.
    */
    $scope.submitted = false;
    $scope.submitForm = function(form) {
        $scope.submitted = true;
        if (form.$valid) {
            $scope.cadastraCertificado();
        }
    };

    $scope.cadastraCertificado = function() {
        $http.post('/boxmlV2/cadastrocertificado/salvaCertificado', {
            urlCertificado : $scope.certificadoIncluirAlterar.urlCertificado,
            dataValidadeCertificado : $scope.certificadoIncluirAlterar.dataValidadeCertificado.toString(),
            senhaCertificado : $scope.certificadoIncluirAlterar.senhaCertificado
            //picklist???
            //certificado
        }).then(function(response) {
            $scope.sucesso();
        }, function(response) {
        });
    };
});

Mas não sei como passar o picklist que já funciona, pegando da base, os dados que preciso coletar é a lista do lado direito.
Como posso fazer isso?
Meu componente picklist:

    Empresas:

        <select multiple="multiple" class="multi-select" id="my_multi_select1" name="my_multi_select1[]">
            <option ng-repeat="c in clientes" value="{{c.idCliente}}" ng-click="atribuirUm($index, c)">{{c.razaoSocial}}</option>
            <option selected ng-repeat="c2 in clientes2" value="{{c2.idCliente}}" ng-click="limparUm($index, c2)">{{c2.razaoSocial}}</option>
        </select>

Obrigado, caso precisem de mais código, eu posto sem problemas.

Editado - botão salvar:

    <button type="button" class="btn btn-default"
        data-dismiss="modal">Cancelar</button>
    <button type="submit" class="btn btn-primary"
        ng-click="submitForm(form)">
         Salvar
    </button>

Após aplicação da resposta fornecida, consigo receber o array OK, mas dá bad request 400 no envio, eu tirei o picklist como teste e consigo passar os outros atributos pro controller java com sucesso.
Estou recebendo no lado do Java, uma lista de String com o mesmo nome, deveria funcionar.
Comment: Como está o botão que você envia os demais dados para o `controller`?
Comment: Celsom, aquele botão do meio é falso, não é clicável. Quando clico no registro do lado esquerdo ele adiciona pro direito e vice versa. Vou postar como ficou meu js pra você ver... nao estou usando ng-model, sei que preciso pra passar...
Comment: Não não, não é isso.. O que eu quero saber é o seguinte, como está o seu botão "Salvar" para salvar todos os dados. O botão que chama a função "cadastraCertificado"
Comment: entendi, postei ele e a função sendo chamada
Answer: Bom, primeiramente, recomendo que você remova a definição dos dados de dentro do $http, use uma variável ao invés disso, assim:
var dados = {
    urlCertificado :     $scope.certificadoIncluirAlterar.urlCertificado,
    dataValidadeCertificado : $scope.certificadoIncluirAlterar.dataValidadeCertificado.toString(),
    senhaCertificado : $scope.certificadoIncluirAlterar.senhaCertificado
};

Agora para definir a lista das empresas selecionadas você tem 2 modos para fazer isso:

Passar como parâmetro pela botão que chama a função;
Pegar diretamente do controller;

A segunda opção só funciona (e no seu caso é até mais simples) pois a manipulação das empresas é feita dentro do mesmo controller. Se fosse feita em outro local, não seria possível usar o segundo método (que é o que vou explicar).
O primeiro método seria assim:
<button type="submit" class="btn btn-primary"
    ng-click="submitForm(form, clientes2)">
     Salvar
</button>

E no controller, ao receber a função, pegue ele também:
$scope.submitForm = function(form, clientes2) { //....

Como o seu já está dentro do controller, você pode pular essa etapa e referenciar ele diretamente através do $scope.clientes2 e mesclar com a sua array de dados já existente (que exemplifiquei acima), assim:
dados['empresas'] = $scope.clientes2; //ou dados['clientes2'], fica a seu critério

Isso irá criar uma nested-array de dados que você pode apenas referenciar no $http e enviar, veja:
$scope.cadastraCertificado = function() {
    $http.post('/boxmlV2/cadastrocertificado/salvaCertificado', dados)
        .then(function(response) {
            $scope.sucesso();
        }, function(response) {
    });
};

Comment: Bom, pode ser algumas coisas, inclusive não relacionada com o lado que está enviando os dados, ou seja, ou seu controller e o $http. Você está enviando so dados no formato json, então certifique-se de que o outro lado vá interpretar esse json corretamente. Outra coisa, os nomes dos campos. Certifique-se de não estar enviando nenhum campo a mais, nenhum campo a menos ou campos com erro de syntax. Você já verificou isso? Lembro que você queria enviar apenas alguns dados da empresa, confere?
Comment: Celsom, obrigado novamente pelo empenho no auxilio, vou aplicar aqui lhe retorno...
Comment: Celsom, editei o post, legal eu recebi o array... só que na hora do envio da lista com 2 registros como teste, dá bad request, 400. Sabe porque? Estou com o mesmo nome de lista no lado do controller no java, deveria funcionar. Tem algo que preciso por na lista, como um .value ou algo do tipo especifico pra lista?
Comment: Obrigado Celsom !
Comment: Não por isso! :)


gradient background doesn't cover under border image

Question: I want background gradient to cover under border image as well. but sounds like It doesn't work at all!
I have realized if I remove Border, It starts working in Mozilla but I want it to work in Google Chrome.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.cont {
  height: 200px;
  position: relative;
  background-image: linear-gradient(
    45deg,
    #f09433 0%,
    #e6683c 25%,
    #dc2743 50%,
    #cc2366 75%,
    #bc1888 100%
  );
  background-clip: border-box;
  background-repeat: no-repeat;

  border: 20px solid orange;
  border-image-source: url("https://interactive-examples.mdn.mozilla.net/media/examples/border-diamonds.png");
  border-image-slice: 25;
  border-image-repeat: round;
  border-image-width: 18px;
}
.cont > .insta {
  text-align: center;
  color: white;
  font-size: var(--default-font-size);
  margin: 0;
  padding: 0;
  position: absolute;
  width: 80%;
  top: 50%;
  right: 50%;
  transform: translate(50%, -50%);
}

       Follow us on Instagram

Answer: You could put the linear gradient as background to the before pseudo element, making that bigger than the actual element by the width of the border and positioning it respectively. It will then go under the border image of the main element.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.cont {
  height: 200px;
  position: relative;
  background-clip: border-box;
  background-repeat: no-repeat;
  border: 20px solid orange;
  border-image-source: url("https://interactive-examples.mdn.mozilla.net/media/examples/border-diamonds.png");
  border-image-slice: 25;
  border-image-repeat: round;
  border-image-width: 18px;
  position: relative;
}

.cont::before {
  content: '';
  position: absolute;
  width: calc(100% + 40px);
  height: calc(100% + 40px);
  top: -20px;
  left: -20px;
  z-index: -1;
  background-image: linear-gradient( 45deg, #f09433 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
}

.cont>.insta {
  text-align: center;
  color: white;
  font-size: var(--default-font-size);
  margin: 0;
  padding: 0;
  position: absolute;
  width: 80%;
  top: 50%;
  right: 50%;
  transform: translate(50%, -50%);
}

    Follow us on Instagram

Comment: Way to go! Sounds interesting


Number of 2n-1 equal size partitions up to symmetry

Question: Consider the $K_{2n}$ (or just the set $\{1,\dots,2n\}$) with $S_{2n}$ acting on the vertices. Moreover consider a collection of 2n-1 partitions of the vertices into two equal sized sets (repeated partitions are allowed).
How many different kinds of such collections can there be up to symmetry and how can you construct them?
For example, in the $K_{6}$ the collections (writing just the first set of the partition):
$$\mathcal{S}=\{\{1,3,6\}, \{1,4,5\},\{1,4,6\},\{1,5,6\},\{1,5,6\}\}$$
and
$$\mathcal{S'}=\{\{1,3,6\},\{1,4,5\},\{1,4,5\},\{1,4,6\},\{1,5,6\}\}$$
are different up to symmetry.
Are there papers about this topics or similar results?
Thanks in advance!
Richard
Answer: NOTE to the reader of this post : this answers an interesting question but not the OP's question.  This question is still open.
There are $p = \frac{1}{2}{{2n} \choose n}$ possible distinct partitions - half of all the ${{2n} \choose n}$ partitions since each partition has a symmetric counterpart.
And each collection has $k = 2n - 1$ of them.
Sets (or collections) that allow repetition are called multisets.  So really, this becomes the problem of finding out how many unique multisets of size $k$ you can make out of $p$ elements.
http://en.wikipedia.org/wiki/Multiset_coefficient#Counting_multisets
The answer is ${p + k - 1 \choose k}$.  Or to be specific, ${\frac{1}{2}{2n \choose n} + 2n - 2 \choose 2n - 1}$.
If you want to construct them all, to simplify things, you can give a number to each partition and represent them as the integer set $P = \{1, 2, \ldots p\}$.
Then you should be able to generate all multisets of size $k$ out of $p$ elements (though there are a whole lot of them).
Comment: Thank you for your answer!
Nevertheless the term "up to symmetry" for me means, that I only look at one representative of the orbit of one collection under the group action of $S_{2n}$.
So for example the collection $\mathcal{S}$ under the transposition $\tau_{46}$ becomes
$$\tau_{46}(\mathcal{S})=\{\{1,3,4\},\{1,5,6\},\{1,4,6\},\{1,4,6\},\{1,4,6\}\}$$
So how many different orbits are there?
Comment: Ah I'm sorry - I looked at the definitions only in the set/graph-theoric sense.  But really, it seems this is a group theory question.  I can't help you with that, but I think you should tag this question with 'group theory'.


Print $Messages in node.tpl.php file

Question: In Drupal 7, by default the $messages variable is printed in page.tpl.php.
Is there a way to print $messages in a node.tpl.php file (e.g. $node-mycontenttype.tpl.php).
Just putting <?php print $messages; ?> or
<?php print render($page['messages']); ?> does not work.
There's a tutorial here for printing $messages in a block, but I would like to put it in my node.tpl.php file.
Comment: I think [theme_status_messages](http://api.drupal.org/api/drupal/core--includes--theme.inc/function/theme_status_messages/8) is being called before `template_preprocess_node` so drupal_get_messages is empty when you call it.
Answer: Actually, what you want to do is this:
function YOURTHEME_preprocess_page(&$variables) {
  // This disables message-printing on ALL page displays
  $variables['show_messages'] = FALSE;
}

function YOURTHEME_preprocess_node(&$variables) {
  $variables['messages'] = theme('status_messages');
}

How this works:
Drupal core checks the value of show_messages in theme_process_page. If it is TRUE (default) then it calls theme('status_messages') as above, and effectively empties the messages storage, so calling the same theme function later will just return an empty string. However, if we set that variable to FALSE, this prevents said theme function from being called in process_page, allowing us to get all the messages using the same theme function, in a template of our choosing.
Comment: And if you only want this to take action on node pages, just wrap the $variables['show_message'] = FALSE with a conditional to see if(isset($variables['node'])).
Comment: And you have to do the same for all other pages (views, panels, etc)
Answer: The answer in How to display messages from a block separately from $messages in page.tpl.php which you referenced in your question is a fine way to go. Essentially you need something like this where YOURTHEME is the name of your theme and this function should be in your template.php.  I haven't actually run this code but have a crack at it.
function YOURTHEME_preprocess_node(&$vars) {
  $output = '';
  foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
    $output .= "
\n";
    if (count($messages) > 1) {
      $output .= "
\n";
      foreach ($messages as $message) {
        $output .= '
' . $message . "
\n";
      }
      $output .= "
\n";
    }
    else {
      $output .= $messages[0];
    }
    $output .= "
\n";
  }

  $vars['messages'] = $output;
}

You should then be able to output $messages in your node.tpl.php
Comment: Be careful when taking stuff out of page.tpl.php. The node template is not used for every page, so you might be missing messages that are displayed on non-node pages (like admin pages, for instance). When you're going to do this, I recommend that you keep a fallback in page.tpl.php that will show your messages when they're not intercepted by node.tpl.php yet.
Comment: Thanks for the solution. I've tried it but it doesn't seem to work. I am using the following to print the $messages:  Is that correct?

Print $Messages in node.tpl.php file


Connecting a Keyboard to Record in Audacity

Question: I'm trying setup my Casio CTK-6000 electric keyboard to be able to be recorded through my Windows 10 computer using Audacity. I have this cable connected to the two "L/R Line Out" spots in the keyboard and I have connected the keyboard to the computer. Windows asks if what I am plugging in is a headphone or "speaker out". Whichever I choose, the keyboard appears nowhere under "recording devices".
I turn on the keyboard, open Audacity and go to Edit -> Preferences -> Devices. The option for the keyboard is nowhere in any of the dropdown menus (it's still just the default stuff). How do I get this setup to work?
Comment: Seems that you are connecting it to an output instead of an input. You need to connect the Casio to the microphone input, not to the headphone / speaker output (both share the same type of connection).
Comment: Also, you have to search for your audio card in Audacity (the audio card is the one receiving the audio from your keyboard), not for the keyboard.
Comment: It Archundia's comments don't solve your problem, tell us the exact make and model of your computer, or at least the model of the motherboard if it was home-built.
Comment: @Archundia I don't think my computer has a microphone input. There seem to be two audio inputs, one that I would plug headphones into, and one that I would plug an external speaker into. They have different type of connections (the same plug wouldn't work on both - the external speaker port is smaller). Audio card? Basically I only see the same default options that are available when I don't have anything plugged in (the microphone, "windows input", and such).
Comment: @alephzero My computer is an ASUS UX51. Not sure about more specific information right now since I don't have it in front of me.
Comment: Headphones and speakers go into *outputs*, not inputs.
Answer: <code>Windows asks if what I am plugging in is a headphone or "speaker out".
</code>
I would have expected you had three options, not the two that you mentioned: "headset", "headphones", and "speaker out". The "headset" option should let you record sound, but...
Like many laptops, according to this page https://www.asus.com/sg/Notebooks/UX51VZ/specifications/ your ASUS UX51 has a "combo audio socket". This is not really intended for what you want to do. The fundamental problem is that the computer can't both record and play back sounds through the one audio socket, so at best you would be continually swapping the plugs between your Casio keyboard to record, and your headphones or speakers when checking the recording you made with Audacity.
The cheapest option would be to get a simple "USB audio adaptor" like this one: https://www.scan.co.uk/products/dynamode-external-usb2-sound-card-20-adaptor-(usb-stick)-pc-mac
Note, this is not a recommendation for this specific device (I've never used it) - it's just an example of what these adapters look like, i.e. a "thumb drive plus some audio connectors". There are many similar devices available in the same price range.
That plugs into a USB port and gives you two sockets for "microphone in" and "headphones out". Audacity should recognise it as two Audio devices, one for input and one for output.
There are many similar devices for sale, and some only provide audio out (for example 7-channel surround sound) so make sure you get one that has an audio input socket - and if you don't need surround sound output, don't pay extra for something you will never use!
If you get serious about recordings, you would probably want to upgrade to a USB audio interface (not adapter) but that would be in a price range of say $100 and upwards, rather than $10 for a "get you started" adapter.
Comment: That USB device looks good. So I would plug the stereo end of the cable connected to the keyboard into the yellow port and my headphones into the black port and you think this setup will work?
Comment: Would [this](https://www.amazon.com/Sabrent-External-Adapter-Windows-AU-MMSA/dp/B00IRVQ0F8/ref=sr_1_4?ie=UTF8&qid=1467911376&sr=8-4&keywords=external+usb+sound+card+adapter) work as well? Or are the types of connections this requires different?
Comment: "Woould this work as well?" I would expect so. Note, all these adapters will only record your Casio in mono, if that's important to you. Actually, I only just noticed that the dynamode device also supports 5.1 surround sound output, which you probably don't want.
Answer: This is regarding connecting your Keyboard / Synthesizer to mac computer for recording. Make sure both mac and keyboard are switched on. Connect a stereo cable between the Keyboard and Mac computer. Click on system Preferences > Sound > Input and in the option "Use audio port for " Select Sound Input from the drop down menu. The sound input will change to Line in option and the Type will change to Audio Line-in port. Now open audacity. Increase the Mic volume to max or according to your requirement in Audacity as well as in the keyboard. Now click on the record button and start playing in your keyboard. You can see the keyboard sound getting recorded in Audacity. Once completed you can export it to your required choice.
Answer: If you are using Windows this answer is for you.
Requirements:

aux 3.5mm male to male cable.
USB 2.0 external sound card.
Jack converter 3.5mm female to 6.35mm male.

Setup:
laptop <--> sound card <--> aux <--> jack converter <--> audio output/Phone slot of keyboard.
Setup Images:

Sounds Settings:
It will automatically select the USB device for sound but still, if it does not you can choose it and check whether it's connected or not anytime.

Audacity Settings:
Select 2-USB audio in both speaker and microphone as per shown in the image.

Hope this helps. Enjoy recording.;)
Answer: While USB audio is an option, there is an alternative simpler option that may be a bit more robust, i.e. use a TRRS mic / headphone slitter cable. Sometimes it comes in form of what is called a "Y" cable, that take the TRRS (i.e. a combined mic + headphone) jack, into a combination of TRS (for stereo headphone or speaker output) and TS (for mono mic input).
This combination may be preferable because:

It avoid the mechanical damage that most USB dongles suffer from lateral motion, push and shoves
It uses the high quality DACs that are already on-board most modern PCs
It is one less device to carry around and lose
It leads to slightly lesser battery power consumption on laptops (because most USB audio dongles are bus-powered, i.e. powered by your PC's USB socket itself)
It avoid adding another audio interface in the drop-down audio device selection menu for many audio applications, making it simpler for the user

On the other hand, a USB audio dongle is so inexpensive (only few dollars more than a TRRS Y-splitter cable), that it's perhaps something you won't fret over, if it broke or you lost it.
For those getting the TRRS Y-splitter cable, make sure that the 2 split ends are one for mic, other for headphone. Sometimes, there are Y-splitters available that are really duplicators / replicators, which makes the mic+headset combined connection available on 2 split ends. The latter is not what would help in this case.


Copy Values Between Tables on Cell Change

Question: I am trying to copy values from one row of a table on the first sheet when the value in that row under column "Called" is changed to "Y" to another table on a different sheet. The columns do not match between each table, so I need to define which column goes where in the other table. I want to make a new row in the 2nd table to paste into and only copy values from the row that had its value changed to "Y". This is my simplest code to convey what I'm doing, but I have tried many things, including an array.
"Table1" is on the first sheet, "Master", Table2 is on the second sheet, "Called List".
EDIT: This is my new code, it succeeds in copying the values to the correct columns on "Table2", but it copies all rows instead of just the current row where "Called" is changed to "Y". Is there a way to copy to a new row on "Table2" only the row in "Table1" where "Y" is being inserted?
<code> Private Sub Worksheet_Change(ByVal Target As Range)

   'Application.ScreenUpdating = False
Application.EnableEvents = False 'to prevent endless loop

Dim KeyCells As Range
Dim NewRow As ListRow

Set KeyCells = Range("Table1[Called]")

If Not Application.Intersect(KeyCells, Range(Target.Address)) Is Nothing Then

     If Target.Value = "Y" Then

        Set NewRow = Worksheets("Called List").ListObjects("Table2").ListRows.Add '(AlwaysInsert:=True)

        Worksheets("Called List").Range("Table2[Lessor]").Value = Worksheets("Master").Range("Table1[Lessor]").Value
        Worksheets("Called List").Range("Table2[Phone]").Value = Worksheets("Master").Range("Table1[Phone Number]").Value
        Worksheets("Called List").Range("Table2[Address]").Value = Worksheets("Master").Range("Table1[Address]").Value
        Worksheets("Called List").Range("Table2[Sec]").Value = Worksheets("Master").Range("Table1[Sec]").Value
        Worksheets("Called List").Range("Table2[Twn]").Value = Worksheets("Master").Range("Table1[Twn]").Value
        Worksheets("Called List").Range("Table2[Rng]").Value = Worksheets("Master").Range("Table1[Rng]").Value
        Worksheets("Called List").Range("Table2[County]").Value = Worksheets("Master").Range("Table1[County]").Value
        Worksheets("Called List").Range("Table2[Legal Desc]").Value = Worksheets("Master").Range("Table1[Tract]").Value
        Worksheets("Called List").Range("Table2[Gross Acres]").Value = Worksheets("Master").Range("Table1[Gross Acres]").Value
        Worksheets("Called List").Range("Table2[Assumed NMA]").Value = Worksheets("Master").Range("Table1[Assumed NMA]").Value
        Worksheets("Called List").Range("Table2[Comments]").Value = Worksheets("Master").Range("Table1[Notes]").Value

    End If
 End If

Application.EnableEvents = True
'Application.ScreenUpdating = True

 End Sub
</code>
Comment: What is the problem or error message with your current code?
Comment: I don't get what you are trying to accomplish with `If Not Application.Intersect(KeyCells, Range("Table1[Called]")) Is Nothing`. Didn't you set `KeyCells` to that specific table? Shouldn't you check intersect with  the `Target` range?
Comment: There are no errors, it just doesn't run, which is more frustrating than errors because I don't know what's wrong.
Comment: As per my previous comment, from the code you provided, the conditional will never be true because the intersect of `Range("Table1[Called]")` with itself will never be nothing. Perhaps if the table is empty? Again not sure what you are trying to check with that conditional.
Comment: I'm trying to check if a cell under column "Called" is changed to "Y", and if so, then all relevant values from that current row are copied to a new row on "Table2"
Comment: So I need to be able to define that it is pulling from the current row that has the cell changed to "Y" and putting only values from that row into the new row on "Table2"
Comment: So would `If Not Application.Intersect(Target, KeyCells) Is Nothing Then` work?
Comment: This will indeed make it fire when the change is in `Range("Table1[Called]")`. I have concerns with the rest of your code as you never reference what row of the table you are referencing but rather only reference the column header.
Comment: That is also what I was wondering. I'm not sure how to reference the specific row that the change is in so that only the column values in that row copy. Any advice?
Answer: " Is there a way to copy to a new row on "Table2" only the row in "Table1" where "Y" is being inserted?"
1) "Target.Row" is your reference row on the master sheet, use it in your "Worksheets("Master").Range("Table1[Notes]").Value" statment
2) "NewRow" is your reference row on "called list" sheet, use it in your "Worksheets("Called List")**.Cells(Range("Table2[Lessor]").Value" statement
3) If you convert your Table?[...] to named ranges you can use something like:
<code>Range("T2_Lessor").Cells(NewRow).Value = Range("T1_Lessor").Cells(KeyCells.Row).Value
</code>
Ex. of named range:
"Table1[Lessor]" becomes
'T1_Lessor' =OFFSET('Master'!$B$2,0,0,COUNTA('Master'!$B:$B),1)
"Table2[Lessor]" becomes
'T2_Lessor' =OFFSET('Called List'!$B$2,0,0,COUNTA('Called List'!$B:$B),1)


circle reflections in hyperbolic geometry

Question: Determine the equation of the circle reflection of the circle $x^2 + y^2 = 1$ if the circle of reflection is $x^2 + y^2 + 2x = 0$. I'm learning about circle inversion but I still don't get what this question is saying? Is it saying find an equation that reflects $x^2+y^2=1$ to  $x^2 + y^2 + 2x = 0$?
Comment: No, reflect the unit circle in the other circle (to get another circle).
Comment: so I graphed it on wolfram alpha and both circles intersect at (-0.5,0.866025) and (-0.5,-0.866025). Oh wait im trying to find the equation that's going to be of the form $ax+by+c=0$. I think I get it.
Comment: No,it is saying: find an equation of the reflected circle that reflects this given circle $x^2 + y^2 + 2x = 0$? about a unit mirror circle of inversion $x^2+y^2=1$.
Answer: You have two circles. The second one defines your transformation: it is an inversion in that second circle. The first one is the object to which you want to apply that transformation, resulting in a new object for which you should find the equation. Here is an illustration:

The black circle is $x^2+y^2+2x=0$. The blue circle is $x^2+y^2=1$. Since the blue circle passes through the center of the black circle, a circle inversion will map that central point to the point at infinity (of $\hat{\mathbb C}$). So the resulting object will not be a circle but instead a line (a circle with infinite radius, if you want).
Hence the blue line in the image above is the result of applying an inversion in the black circle to the blue circle.
Finding its equation should be easy from the image, but in order to understand this task, you might want to think about how you'd find that equation without an image, or in cases where deducing the numbers from the image would be less easy.
Comment: yeah i figured it was a line. I got it already. thanks.
Answer: The question as given here on the topic of pure inversion is confused. Reflection and Inversion are  synonymous here. Better to ask the question as:
Determine the equation of the reflected circle from given circle  $x^2 + y^2 + 2x = 0$ when the reflecting circle or circle of inversion is the unit circle $x^2 + y^2 = 1.$
Answer is: x = -1/2.
You can use my code in Mathematica for practice to sketch circles before and after reflections about the Red circle/mirror of inversion.
h = 5.5; R = 3 ;
{x[t_], y[t_]} = {h + R Cos[t], R Sin[t]} ;
c = ParametricPlot[{x[t], y[t]}  , {t, .001,  Pi - .001}];
Rinv = 4;{x1[t_], y1[t_]} = Rinv^2 {x[t], y[t]}/(x[t]^2 + y[t]^2);
c1 = ParametricPlot[{x1[t], y1[t]}  , {t, .001,  Pi - .001}];
cINV = ParametricPlot[Rinv { Cos[t], Sin[t]} , {t, .001,  Pi - .001},
   PlotStyle -> {Red, Thick}];
Show[{c, c1, cINV}, PlotRange -> All]


How can I increase the 128 character limit of a menu path?

Question: I know there are patches to core, but they were never backported to Drupal 6 from what I can tell.

Increasing path length to 255 chars
Menu path length is limited by the UI to 128 characters

How can this be overridden in a theme?
Answer: You should be able to fix this by using hook_form_alter() and override the default maxlength for the input field, and then change the field in the db to varchar(255) if it isn't already.
Another option would be to use a token value for the path and change the value on output using theme_menu_item().
Perhaps the best option after all would be the Custom Tokens module. I haven't tried it so I can't say if it works.
The downside with tokens is that you would have to make one token per URL, or possibly use a part of the URL if it's generally the same.
Comment: Keep in mind that, if you alter the schema of a table defined from another module, you need to also implement `hook_schema_alter()`.


How do I use a properties file with jax-rs?

Question: I've just been getting started setting up a web service with jax-rs running on Tomcat. Is there a way to bundle a properties file with my java project (in eclipse) so that I can read properties out of it at runtime? Also if it's possible, where would be the best location to put it (so that it couldn't be seen via a url), WebContent, WEB-INF, etc?
Thanks.
Comment: Just put it in the classpath (WEB-INF/classes; in a maven project, src/resources is the appropriate location) and load it with the classloader.
Comment: I don't have a maven project, would WEB-INF/lib suffice? What would the path look like at runtime for the file Properties("WEB-INF/lib/jaxrs.properties")
Answer: Several options:
Option 1: You can put it under your classpath (in Eclipse put it under and source folder), so you can access it via the Classloader: MyClass.class.getResourceAsStream("myproperties.properites")
Pay attention that MyClass must also be in the same source folder (actually it's a bit more complex, it must be in the same classloader hierarchy, but any class from the same folder will do the job)
Option 2: Put it in WEB-INF folder. It's a preferred option, since you don't need to deal with the classpath. You'll need a ServletContext to access it: javax.servlet.ServletContext.getResourceAsStream("WEB-INF/myproperties.properites")
In jax-rs you can obtain the ServletContext using the @Context annotation in any registered resource or provider.
Comment: If my class isn't a Resource class that's being returned, rather it is a POJO that's being created (extends Authenticator), would I need to physically pass the servlet context from the resource into it's constructor or via a setter or is there a way to inject it there as well?
Comment: Well, if a class is not created via JAX-RS, then JAX_RS won't help you here. You'll need to do it manually.
Comment: I had to do something like Someclass.class.getResourceAsStream("../../file.properties") but this will need to change if a class is in another package. Is there ta way I can specify an absolute path to the file, ie /src/file.properties or something?
Comment: Just put the properties file under the root package, so you can always write: Someclass.class.getResourceAsStream("file.properties")
Comment: What about the case where I need to write the file?
Comment: What about this case? What exactly do you want to know? If you need the file location, you can use getResource instead of getResourceAsStream, so you get the file's URL. The you can treat it just as a regular file.
Answer: For GlassFish 3.1 users, I was able to get both of Tarlog's options working, but I had to use the file's absolute path. For Option 1 I put the file in the Source Packages folder in NetBeans, which I could then access via:
InputStream is = TestResource.class.getResourceAsStream("/test_model.js");

For Option 2 I put the file under WEB-INF and used:
@Context ServletContext servletContext;
InputStream is = servletContext.getResourceAsStream("/WEB-INF/test_model.js");

Without the leading slash the result was null. HTH
Comment: Is there a way to use a property file or some custom setting file to my war that will be loaded on start but is not inside the project? like for example /etc/myapp/file.conf


Using OAuth2 on non-REST endpoints

Question: I have a custom module which includes a ControllerBase. The controller has a content() function that returns a JsonResponse(). The code for this function returns a complete list of a certain entity type.
I've tried using REST for this, but the entity structure is decently complicated and contains several field collections. By default, REST will just include the ID of a field collection as part of its presentation of this entity, so I've written a FieldFormatter plugin that replaces the field collection ID with a JSON object of its contents. Unfortunately, that requires significant overhead when returning an entire list of the entity type via REST, and takes 40 seconds to load. However, OAuth2 works fine with it.
Alternatively, my existing custom connector takes approximately two to three seconds to load, as it is a single sanitized SQL statement that outputs its results as a JSON. However, I only have Basic Auth working with this, attempting OAuth2 returns a 403 error. I am using the simple_oauth module.
I'm wondering if there is a way to:

A) improve the response time on the REST endpoint to be as good as the custom controller
or
B) use OAuth2 with the custom controller. I've been looking for instructions on this but every OAuth2 resource I've come across so far assumes I'm using a REST endpoint.

edit to update: The REST endpoint is caching, which seems good as it's now loading much faster after the initial fetch, but (as is expected behaviour) the cache is flushed along with all other caches which is something we need to do fairly often, meaning the next person to access the endpoint will see an unusually slow response time. This isn't ideal, and I'd like to still investigate the custom controller I made, however adding _auth: ['oauth2'] to the YAML file is not fixing the 403 error.
2nd edit to update: This is my YAML for the custom controller, which is also not working:
connector.modulename:
  path: '/connector/modulename'
  defaults:
    _controller: \Drupal\connector\Controller\ModuleNameConnectorController::content
  requirements:
    _permission: 'view modulename entity'
  options:
    _auth: ['simple_oauth']

It does not work with _auth: ['simple_oauth'] or _auth: ['oauth2'] (403 error), but does work with _auth: ['basic_auth']. I'm using Postman to connect with a fresh (~30 sec, expiry 5 min) token. The same oauth2 token works for the REST connector. The error message I'm getting in my admin logs states:
League\OAuth2\Server\Exception\OAuthServerException: The resource owner or authorization server denied the request. in League\OAuth2\Server\Exception\OAuthServerException::accessDenied() (line 173 of C:\directory_to_my_site\vendor\league\oauth2-server\src\Exception\OAuthServerException.php).

and also issues a PHP warning stating that access was denied to Guest (not verified).
Comment: I don't have time to dig deeper (and assuming you're using the simple_oauth module), looking at the code and [this](https://drupal.stackexchange.com/questions/244591/custom-authentication-provider-returns-403-for-access-true), it might be as simple as adding `_auth: ['oauth2']` to the `options` of the route for the custom controller (maybe instead of `_access` but I'm not sure)
Comment: @Clive Thank you! I was about to be really embarrassed that it was that easy, but I'm still getting a 403 error after changing the provider to oauth2 (I am using simple_oauth), clearing cache, and using a fresh access token. I will have to look into this tomorrow.
Comment: Have you tried `_auth: ['simple_oauth']`?
Comment: @Jdrupal Thanks for the suggestion, I tried it but it's still giving me a 403 error. I'll update my question in case something's wrong with my YAML itself.
Comment: Why do you have both permission and auth?
Comment: @Jdrupal Not all user roles have access to this entity type, so it should deny them if they are either not logged in, or logged in but don't have the correct role.
Comment: correct me if i am wrong but why not just make a custom rest plugin endpoint and move your code from controller to that ?? Example https://github.com/enzolutions/entity_rest_extra/blob/master/src/Plugin/rest/resource/EntityBundlesResource.php .  ?? then implment your own cashing ?

also what is the method GET , POST ?
Comment: @TaggartJensen basically using any entity methods (such as \Drupal::entityManager()->getStorage) is causing the REST endpoint to operate extremely slowly because of the amount of field collections that need to be expanded, so I need to do this with as few database queries as possible. Using GET.
Comment: then cache it like ....

 $data = NULL;
if ($cache = \Drupal::cache()->get('something')) {
   $data = $cache->data;
 }
  else {
    $data =  (do the expensive slow stuff  here)
    \Drupal::cache()->set('something', $data);
 }

see core/core.api.php line 434 ish.
Comment: This is the most embarrassing thing I've ever posted. I was using a refresh token instead of an access token. That's why I was getting a 403 error. The code was fine all along.
Answer:
A) improve the response time on the REST endpoint to be as good as the
  custom controller

For the REST endpoint, you can use $response->addCacheableDependency() check this block for example:
https://blog.dcycle.com/blog/2018-01-24/caching-drupal-8-rest-resource/
https://spinningcode.org/2017/05/cached-json-responses-in-drupal-8/
Make sure to add cache context and cache tags, carefully.

B) use OAuth2 with the custom controller. I've been looking for
  instructions on this but every OAuth2 resource I've come across so far
  assumes I'm using a REST endpoint.

Check the example from "simple_oauth_extras" sub module of "simple_oauth"
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/simple_oauth_extras.routing.yml#L22
Controller is:
https://git.drupalcode.org/project/simple_oauth/blob/8.x-3.x/simple_oauth_extras/src/Controller/DebugController.php#L39

Using OAuth2 on non-REST endpoints


Why don't we split the dataset into training and testing set if the sample size is small?

Question: I learned in school that we don't split the dataset into training and testing sets if the sample size is less than 30. I wonder why we don't?
Comment: It might be instructive to think about what you are going to do if the sample size is 31. If you want to learn about about data splitting (why and why not), rather than rules of thumb, you'll find lots on this topic on CV, eg. [1](https://stats.stackexchange.com/questions/410118/cross-validation-vs-train-validation-test), [2](https://stats.stackexchange.com/questions/290808/when-to-not-split-up-your-data-into-training-and-testing).
Answer: Depends on what the task is, but generally, train-test splitting data with small sample size will lead to an even smaller training set. The model can't effectively "learn" on such small dataset. As a result the learned parameters are not what we are looking for. This will especially be more true regarding the classification tasks, which will lead to extensive imbalances in the dependent data as well.

Why don’t we split the dataset into training and testing set if the sample size is small?


How to read the music staff with key signatures included?

Question: I am reading an introduction of music theory recently. From the first few chapters I learn the fundamental idea about notes, time signatures, music staff, treble & bass clef, interval and scale. But it is still quite confusing when I try to read the music sheet regarding major and relative minor. Let me break my question in pieces
The book states that the music stave is created with notes (pitches) arranged in major scale. The treble clef tells where the G note should be. Each line and space on the staff is then label each note on major scale one by one. Here is what I get from the book to identify the arrangment of notes for G major

The G clef locates the G note and according to major scale (C-D-E-F-G-A-B-C), I have each note landed as above. My first question is: is it sufficient to identify the above pattern to be a G major?
This question is not bothering me until I finish the chapter about the Circle of Fifths. With the help of the Circle, we could figure out how many sharp should be added to make a certain major key. To make a G major, we should add 1 sharp (i.e. F#) as the key signature as below (I copy that from the book)

If this is correct, I wonder what is the difference between the first and the second staff except for the key signature. The whole chapter of the Circle of Fifths tells that each stop on the circle counted from the top one (C note), and thus if I need a G major, shall I layout the notes on the staff with the key signature as below?

I add more detail on the question. I copy the following stave from the book

which is claimed as a F# minor (i.e. A major relative minor). I saw that there is a common # on the F line so the very last F will be sharped but the very first F is still a F (not F#), so in what sense should we call this F# minor instead of F minor. Thanks.
Comment: Your last sentence is wrong. Accidentals in the key signature (as opposed to single ones occurring elsewhere, see [here](https://music.stackexchange.com/q/17389/2600)) apply to all octaves.
Answer: Firstly, the top stave is misleading. If it states that that is the G major scale, it's wrong. The scale goes from G to higher G, but they didn't include the fact that G major always has an F♯ note, not an F.
That fact can be shown in two ways. By putting the sharp sign (♯) on the F line at the top of the stave, at the beginning of each line, or by putting the same sign just before the F note. Note - the latter will only affect an F note in that bar, on that particular line, whereas at the beginning (called the key signature), it affects every F note in the piece.
This is where books and websites fall down - you can't ask questions, and sometimes there's erroneous information. That's where teachers come in handy.
So the second example is fine.The last example is confusing. There's an F♯ at the beginning, therefore it's the key sig., but the scale notes go C to C. C major has no sharps or flats in the key sig., so really what's written isn't the G major scale. it's not C major either. In fact, but don't worry about it, it's C Lydian...but that's for another day!
Comment: Yes, it's sort of shorthand for 'we're in G/Em, so every F we play needs to be F#'. Although with piano music, there needs to be a # sign on the bass clef too.
Comment: I really appreaciate your answer. The statement "by putting the sharp sign (#) on the F line ... " clear my doubt like a click, I got some idea now. Thanks Tim.
Comment: Thanks, but give it some time. There may well be a better answer - there's good folk on this site!
Comment: Thanks a lot. I am just beginning, I don't have any background of music theory though I play guitar (I don't really try to understand the theory behind). I wonder if you would take a look on anohter of my question (just added to the thread). Thanks.
Comment: Read my 2nd para. I hinted at this there. 'The sharp on the top line at the beginning of the line) affects *every* F in the piece'. A bit strange, but otherwise there could be ####### everywhere!
Comment: Ok. I think I misunderstand that before. So when you state affects every F in the piece, it mean any F's that even not line up with where the accidentals landed on, right? So the first F and the last F will be affected, I think I get it now, right?


Mock busboy with jest

Question: I have an express POST route set-up in index.js as following
  import * as Busboy from 'busboy';
  public publish = async (req: Request, res: Response) => {
    const busboy = new Busboy({ headers: req.headers });
    const pl = { title: '' };
    busboy.on('field', (fieldname, val) => {
      switch (fieldname) {
        case 'title':
          pl.title = val;
          break;
      }
    });
    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      // Process files
    });
    busboy.on('finish', async () => {
      // Process request
      res.send({payload: pl});
    });
  }

In test index.test.js using jest how do i mock this module in such a way that i can validate the response containing the form field title sent in request?
Currently i use jest.mock('busboy'); but nothing gets invoked due to this.
jest.mock('busboy');
let service: ServiceController;
describe('Mosaic Research Capture Service', () => {
  it('should publish', async () => {
    service = new ServiceController();
    const req = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      body: {}
    };
    const res = {
      send: jest.fn()
    };
    await service.publish(req, res);
  });
});

The React client invokes this request as follows
 const formData = new FormData();
 formData.append('title', 'SomeTitle');
 const header = {
   credentials: 'include',
   'Content-Type': 'multipart/form-data',
 };
 const response =  await axios.post('/publish, formData, header);

Answer: You need a "trick" to mock a event-listener action. As a issue https://github.com/airbnb/enzyme/issues/426
You abuse async/await many times, just use these keywords if you working with Promises.
Here is my suggest update for your case:
index.js : Just remove all async keywords
 import * as Busboy from 'busboy';
  public publish = (req: Request, res: Response) => {
    const busboy = new Busboy({ headers: req.headers });
    const pl = { title: '' };
    busboy.on('field', (fieldname, val) => {
      switch (fieldname) {
        case 'title':
          pl.title = val;
          break;
      }
    });
    busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
      // Process files
    });
    busboy.on('finish', () => {
      // Process request
      res.send({payload: pl});
    });
  }

index.test.js
import { ServiceController } from "./handler";
import * as Busboy from 'busboy';

jest.mock('busboy');
describe('Mosaic Research Capture Service', () => {
  let service: ServiceController;
  const mockedEvenMap = {};

  beforeAll(() => {
    Busboy.mockImplementation(() => {
      return { // mock `on` event of Busby instance
        on: (event, callback) => {
          mockedEvenMap[event] = callback;
        },
      };
    });

    service = new ServiceController();
  });

  afterAll(() => {
    Busboy.mockRestore();
  });

  it('should publish', () => {
    const expectedTile = "MY_TITLE";
    const filenameToTest = 'title';

    const req = {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      body: {}
    };
    const res = {
      send: jest.fn()
    };
    service.publish(req, res); // remove await

    // fire simulate event
    mockedEvenMap['field'](filenameToTest, expectedTile);
    mockedEvenMap['finish']();

    // you expect send function will be call with a payload with includes the title
    expect(res.send).toBeCalledWith({ payload: {title: expectedTile} });
  });
});

Mock busboy with jest


How to change part of numpy array without reshaping

Question: I have the the following array
import numpy as np
import CustomClass

# Total = 24
height = 4
width  = 6
a = np.empty((height, width), dtype=object)

for row in range(self.height):
    for col in range(self.width):
        self.a[row, col] = CustomClass()

I would like to change the attribute for part of the array (filled with my custom class).
For example, I would like to change 12 elements starting from element[0,0], then from row to row. Ideally, I would do something comparable to
change=11
for i in range(change):
   a[i].value=True

The result would be something like the following (0: unchanged, x: changed)
x x x x x x
x x x x x 0
0 0 0 0 0 0
0 0 0 0 0 0

The problem with my array is that I first need to flatten it before I could do something like this. Or I should calculate how many columns and rows I before I can index the array itself. Is there a numpy function such that I can just iteratre over the array element by element (row by row).
I hope my explanation is clear?
Comment: Reshaping or flattening the array doesnt change it in memory, it only changes the metadata. You can flatten and reshape as much as you like without performance hits.
Comment: If your numpy is 2-d, then you can calculate the mod of (number of rows) and also columns to do that. But any specific reason not to use flatten and reshape?
Comment: Perforamance and _trying to learn new functions_ were the reason to ask this question. But It seems that flatten and reshape is enough. However, I still need to use a for loop to change te values. Any suggestions to do this differently or can I not avoid the for loop
Comment: After you flatten you can use slicing like `full_array[0:change] = new_values` as long as the shapes match
Comment: Thank you for the suggestion, however my array consist of objects from which I would like to change the attribute and not replace it with new_values
Comment: you can calculate `x = number % width` , `y  = number // width` and you don't have to flatten it. `arr[y,x] = ...`. OR use variable count and count how many values you changed and then use `break` to exit loop.
Answer: You can do this a couple of ways, but one approach would be to use np.unravel_index to get the two-dimensional indices that correspond to the flattened one-dimensional ones. I'll show you how to do this below.
First create your data:
from dataclasses import dataclass
import numpy as np

height = 4
width  = 6

@dataclass
class myClass:
    value: bool = False

data = np.asarray([myClass() for _ in range(height * width)])
data = data.reshape(height, width)

Now, make change an array of indices that you want to change, rather than the number of elements you want to change:
change = np.arange(11)

Determine the two-dimensional indices that correspond to those in change:
rows, columns = np.unravel_index(indices=change, shape=(height, width))

And then you can use these indices to iterate over the elements you want to change:
for element in data[rows, columns]:
    element.value = True

Comment: I like this answer as it learned me something new (`np.ravel_index`) and gets the job done. Thanks
Answer: You can use variable to count how many elements was changed and use break to exit loops
import numpy as np

height = 4
width  = 6
a = np.empty((height, width), dtype=object)
a[:] = '0'

count = 0

for row in range(height):
    for col in range(width):
        count += 1
        a[row, col] = 'x'
        if count == 11:
            break
    if count == 11:
       break

print(a)

Result:
[['x' 'x' 'x' 'x' 'x' 'x']
 ['x' 'x' 'x' 'x' 'x' '0']
 ['0' '0' '0' '0' '0' '0']
 ['0' '0' '0' '0' '0' '0']]

To make it simpler you can set count = 11 at start and later substract until you get 0.
This way you have to set 11 only in one place.
import numpy as np

height = 4
width  = 6
a = np.empty((height, width), dtype=object)
a[:] = '0'

count = 11

for row in range(height):
    for col in range(width):
        count -= 1
        a[row, col] = 'x'
        if count == 0:
            break
    if count == 0:
       break

print(a)

EDIT:
You could also calculate how many full rows you have to change and how many elements you have to change in last row.
import numpy as np

height = 4
width  = 6
a = np.empty((height, width), dtype=object)
a[:] = '0'

count = 11

rows = count // width
rest = count % width

a[:rows] = 'x'
a[rows,:rest] = 'x'

print(a)

But this will not work if you want to start in different place then [0,0]
Comment: Using nested loops doesn't sound very numpy-esque at all...
Comment: That seems better already. You can do `rows, rest = divmod(count, width)`, though. ;-)
Comment: @AKX if it would create rectangle then it could use numpy function for this. But meanwhile I created other method which use more numpy-esque method `a[:rows] = 'x'
a[rows,:rest] = 'x'`
Comment: Thank you for the suggestion, I like the small edited version. Interesting, especially with the divmod.

However, I'm changing an attribute and not setting an value. Will that work?
`object.value = True`, is the goal


Firestore Rules

Question: I have the following rules in my Firestore database. But I still keep getting a notification from Firestore that the rules I set in my database are not secure. Please see the codes below. Any suggestions or recommendations to make the database more secure?
<code>    rules_version = '2';
    service cloud.firestore {
    match /databases/{database}/documents {

match /{document=**} {
  allow read: if true;
  allow write: if userIsAdmin();
}

match /Basket/{Basket} {
  allow read, update, delete: if userOwnPost();
  allow create: if request.auth.uid != null;

}

match /AllOrders/{AllOrders} {
    allow read, create, update: if userOwnPost();

}

 match /Items/{Items} {
    allow update: if userOwnPost();

}

match /Voucher/{Voucher} {
    allow update: if userOwnPost();

}

match /User/{User} {
    allow read, update: if userOwnPost();
  allow create: if request.auth.uid != null;
}

function userIsAdmin() {
    return getUserData().userRole == 'Admin';
}

function getUserData() {
    return get(/databases/$(database)/documents/User/$(request.auth.uid)).data;
}

function userOwnPost() {
  return getUserData().objectId == request.auth.uid;
}

      }
    }
</code>
Answer: You have some overlapping match statements in your rules:
With
<code>match /{document=**} {
  allow read: if true;
  allow write: if userIsAdmin();
}
</code>
you allow read access on all documents in your Firestore database.
As explained in the doc (section "Overlapping match statements"), "in the case where multiple allow expressions match a request, the access is allowed if any of the conditions is true".
So all your other security rules are just overlapped by this one.

Firestore Rules


Alterar a cor do texto de um iframe

Question: É possível mudar a cor do texto de um iframe?

Comment: Por medida de segurança, não, salvo de você integrá-los (neste caso, você terá que poder alterar o código fonte do site que está carregando via `iframe`)
Answer: A função do iframe é abrir um documento externo em sua página web, seja ele localhost ou externo. Algumas soluções em javascript podem ajudar a fazer o que você quer, mas apenas se for um documento no mesmo servidor.
Portanto, a resposta é não, pois é a mesma coisa que você querer editar um facebook que não é seu, já pensou?!.
Mas, você pode criar uma cópia da página externa no seu servidor usando PHP:
file_get_contents(/* string: url da página */)

E aplicar os estilos CSS que quiser na string retornada, podendo criar até uma "versão" da página original no seu servidor, com seus próprios estilos e scripts.

Alterar a cor do texto de um iframe


images not rendering in production

Question: I have deployed my node.js express app to production via a docker file, however, the images are not being rendered, and browser standard placeholder images are being rendered in-place of these.
In order for my app to render these images, is there something I am doing wrong? Is there a piece of code I need to include?
My file structure is as follows

base directory > public > icons
base directory > index.js

Relevant portion of my index.js server file
 const { join } = require("path");
    app.set('views', join(__dirname, 'views'));
    app.use(express.static(join(__dirname, 'public')));

    const port = 3000

    var cookieParser = require('cookie-parser')
    app.use(cookieParser())

    const bodyParser = require('body-parser');
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }))
    app.use(cookieParser());

    process.env.NODE_ENV === 'production'

    app.set('view engine', 'ejs');

    app.get('/',(req,res)=>{
      res.render('index',{
          data: 'name'
      })
    })

Here is the error message I get when I try to open the image file

ejs file:
<% data.countries.forEach(function(count){ %>

                  <img class="img" src="/icons/<%= count.icon %> " width="25" height="25"  />  <%= count.name %>

                <%= count.categories.map(cat=>cat.name).join(' | ') %>

        <% }); %>

Comment: @FelixFong added to the question
Comment: Hello, could you show us your `index.ejs` file please, thank you
Answer: Can you open the file directly by his path?
Comment: Added to the question
Comment: You can just leave comments here instead of editing your answer.... But opening the icon link points to the error... not sure what you mean
Answer: One possible answer is because inside your EJS file, your image is pointing at a URL that looks something like /icons/HK.png, but your ExpressJS public path is set to /public indeated here:
app.use(express.static(join(__dirname, 'public')));
So one possible solutions is to add a new public path for your icons set by adding this code:
app.use('/icons', express.static(join(__dirname, '/public/icons')))

Comment: Don't I want to give the server access to all of the public folder however?
Comment: And sorry, but where are you getting `images` from?
Comment: 1) Sorry for the `/public/images` thing, it was my mistake, I updated my code.

2) You are not full access to the entire public directory, you are only giving the public access to the icons directory if traffic is coming from the `/icons` route
Comment: But my CSS is also in my public directory, so thus I lose that when pushing live

images not rendering in production


How can I build AST from Scala code?

Question: How can I turn scala program into AST and operate with it programatically, from java/scala?
Comment: Are you talking about [AST (abstract syntax tree)](https://en.wikipedia.org/wiki/Abstract_syntax_tree)?
Comment: Yes, I am. Sorry I got the title wrong.
Comment: Take a look at [scala reflection API](http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html) -- it allows you to manipulate with scala as AST (trees section in particular)
Comment: Is the program already compiled? In the source code, you can inject a macro to get hold of the corresponding AST of some expression.
Comment: It's source code. I know little about the macro. Could you please show me some examples? Thanks!
Answer: You can parse scala program source code.
Take a look to parboiled2 PEG parser. As an examle it have scala parser implementation
https://github.com/sirthias/parboiled2/tree/master/scalaParser/src/main/scala/scalaparser
Answer: I know this is an old question but you can have a look at scalameta :
https://scalameta.org/

Library to read, analyze, transform and generate Scala programs

How can I build AST from Scala code?


What is an orthogonal design?

Question: I am a little bit confused about what an orthogonal design is and how it relates to the model matrix. It appears that there are many perspectives into the definition of orthogonal inside this post but none exactly helps me understand my problem. I am seeking an explanation with an experimental design context.
In Bailey 2008 pg 179, It introduces two factors G and F as orthogonal iff  the subspaces $V_G \cap(V_F \cap V_G)^\bot$ and $V_F \cap(V_F \cap V_G)^\bot$ are both orthogonal to each other (or $V_G \cap V_{G \wedge F}^\bot$ and  $V_F \cap V_{G \wedge F}^\bot$ is orthogonal)
A more intuitive theorem in the same book says (in terms of factors and levels) that
F and G on the same set are orthogonal to each other iff

every F-class meets every G-class
all these interesections have size proportional to the product of the sizes of the relevant F-class and G-class

However, the problem with these definitions is that it does help with 3 factors being orthogonal to each other or or when continuous covariates are included in your model. I was guessing that perhaps the model matrix when encoded can reveal something about orthogonality. However, my guess is that this is not true because It is obvious that when dummy coding the columns of the model matrix is not orthogonal to each other.
So my question is,

What is a general definition of an orthogonal design? Is there a more general definition of orthogonal design? Including continuous covariates
What are the advantages of orthogonal designs?
Does the model matrix reveal anything about orthogonality?
Comment: I am not surprised that there is confusion about what is an Orthogonal Design. Orthogonal Designs were the subject of the 1979 book
A.V.Geramita and Jennifer Seberry, Orthogonal Designs: Quadratic forms and Hadamard matrices, Marcel Dekker, New York - Basel, (1979), viii, 460 pages. This has now been republished as
Jennifer Seberry, Orthogonal Designs, Springer Nature, 2017
Comment: The orthogonality of two factors in a design is a concept subtler than people would think of. A mathematical rigorous and intuitive definition (which has similar flavor to the definition you listed in your question) of orthogonality of design is given in Section 2.3 of *The Coordinate-Free Approach to Linear Models*. Though it might be quite abstract at the first reading, this is the best exposition of orthogonal design I have ever encountered. If I got time, I would like to summarize the author's idea therein.
Answer:
Perhaps you haven't fully grasped the definition yet. The requirements for orthogonal designs are that the blocking is orthogonal and the treatment is orthogonal. This simply means that crossproducts total to zero, whether the blocking or treatment is continuous, pseudo-continuous, polytomous, or binary. As @whuber correctly points out, statisticians often call dot products cross products, and furthermore often assume blocking and treatment factors have mean 0. So any blocking factor or treatment factor "crossed" with any other will come out to 0.
Efficiency.
Absolutely. We would expect that cross products between any two columns of the design matrix will total out to zero.
Comment: +1 In (2) it might perhaps be at least as important to list *interpretability*.
Comment: tintin, in the regression context the term "cross product" often is used to refer to dot products: that is, a sum of squares or products.  And yes, of course you can design a non-orthogonal experiment (almost surely a random design matrix will not be orthogonal): but that possibility seems to have no relevance to your questions.
Comment: In addition to efficiency, if the design matrix is not orthogonal, there is no unique partition of the sums of squares. I think this is what @whuber means by interpretability: there would be different possible tests (w/ possibly different outcomes) & the data would not necessitate that 1 of them was the 'right' test.
Comment: @tintinthong I neglected to mention that one should consider all factors to be mean-centered. That is an (unfortunately) common omission. You're right about dot product.
Comment: @AdamO thanks for the reply. 1. I definitely haven't grasped the definition. Cross products of what exactly? 2. I am guessing that you mean dot product and not cross product (or do you really mean cross product). 3. Surely, one can make a design matrix (using dummy coding) such that dot product of two cols will not be zero.
Comment: @whuber I can create an experimental design eg 2 factorial. I run the model in R. I usually get that the factors are dummy coded into the design matrix. ie the cols of the design matrix are non-orthogonal. Does that mean that I did not create an orthogonal design? (Still unsure with definition)
Comment: As AdamO pointed out in a comment, orthogonality depends on how the variables are coded.  Just as it's possible to find linear combinations of regressors that are orthogonal--but have no clear interpretation--it is, conversely, possible to create linear combinations of orthogonal regressors that are no longer orthogonal.  Perhaps it would help to study the options offered by `R` for coding categorical variables.
Comment: @whuber What does it mean "any blocking factor or treatment factor "crossed" with any other will come out to 0."? E.g. let's have a latin square with rows 123,231,312. How can I see that here?

What is an orthogonal design?


Load images from "HTTPS" type of url and display in UIImageview

Question: I am developing an iOS app in which I receive "HTTPS" URLs from server for images. I am now unable to load images from those URLs. I have tried several frameworks like AFNetworking, SDImageView, etc. But none of them are able to load image from these type of URLs.
Update:
Code sample
[cell.imgVwPhoto setImageWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[arrayImages objectAtIndex:indexPath.row]]] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        [UIView transitionWithView:cell.imgVwPhoto
        duration:0.2
        options:UIViewAnimationOptionTransitionCrossDissolve
        animations:^{
            cell.imgVwPhoto.image = image;
        }
        completion:NULL];
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
        NSLog(@"Error");
    }];

Here URL is of HTTPS type.
So, this is not working.
Any help would be much thankful.
Comment: show some code, how do you load those images? Did you tried to load from another https resource? What's the error that occurs when loading those images, if any?
Comment: Would you please share your complete image url
Comment: Sorry i cant share it
Comment: Are you sure you having an image on this url? No html as a result o hotlinking protection?
Comment: What error are you getting? Maybe change your NSLog to `NSLog(@"Error: %@", error);`
Answer: try this
NSURL *url=[NSURL URLWithString:@"yourURL"];
NSData *data=[NSData dataWithContentsOfURL:url];
UIImage *aImage=[UIImage imageWithData:data];

Answer: This will work
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageWithData: imageData]];

hope it helps.
Comment: its not working, i have already tried this.
Error Shown for your code : NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Comment: can I see your code and url your passing to image view?
Comment: I have tried your code and URL is any general URL but of HTTPS type.
Comment: Check your url your not getting data in response to your url.
Comment: I can open the image in browser from that URL but not in iOS code.
So, there is no problem with URL.
Answer: Issue resolved by modifying some parameters into the framework for webservice calling created by me.
All those changes were as per the server which I was calling to.
Thanks
Comment: Can you please share what changed you made?


Setting current node url as default value for "Link" field

Question: I have a content type with a field type Link. I would like to set default text and url for the field. Under:

Structure » Content types » MY CONTENT TYPE » Manage fields

I tried entering # and [current-page:url:absolute]. Both of them were not accepted and the below are the respective error messages:

The value [current-page:url:absolute] provided for MY FIELD NAME is not a valid URL.
The value # provided for MY FIELD NAME is not a valid URL.

What is the right way to enter the current node URL as a default value into a Link type field?
Comment: Are you doing it in code, or on settings form? If in code, please post your code. If in settings form, please post a screenshot.
Comment: you need to use module [field default token](https://www.drupal.org/project/field_default_token) to work global as well local token.
Comment: you can do by using rules module
Comment: @Mołot added additional info to the question.
Comment: What Drupal version? [If 8, this is not yet possible](https://www.drupal.org/node/1070878).
Comment: I am using Druapl 7
Comment: try using  #[site:current-page:?] this will work
Comment: @VimalGoradiya same issue it didn't work...
Comment: @VimalGoradiya you should make your comment into an answer, I just tried the module and it does allow you to enter token values for link fields default values. And it worked with the `[current-page:url:absolute]` token as well
Answer: You need to use module field default token to work global as well local token in field value. You can use your previous token i.e. [current-page:url:absolute].


Managing Android layouts, there must be a better way

Question: I'm trying to sort the layout for one of my Android apps, but I'm finding layouts a nightmare.
Principally I have to have a portrait and landscape layout for normal, small and large screens.  So thats 6 layouts to maintain to start with, let alone having to launch the app on three emulators each time because my UI widets don't load in the built in previewer.
I might be showing my ignorance as a fairly new developer, but there must be a better way!
Are there any tools out there to help with Android layouts?
Thanks
Comment: In general, if your layout is fairly simple you shouldn't need to create separate ones from small, medium and large screens. What are you doing that you found you needed to do so?
Comment: Sorry, Falmarri, but +1 from me
Comment: Although it seems to me that the author is missing (some) of the basics (I believe that Blindstuff answer nailed it), I think that this question is good enough considering the answers that we can (and did) get... it reveals more than it seems to, IMHO. I think that the Eclipse layout design is a bit cumbersome and could be improved, to make it easier/faster (for designers, mockups etc.). Anyway... that's what the tools mentioned here are for.
Answer: You dont need to have that many layouts. Design only as many as you need, and never use absolute values, aditionally try to make everything look nice using fill_parent and wrap_content for you layout_width & layout_height tags. Android does most of the work it self.
This article contains a lot of usefull info:
Supportng multiple screens
Answer: You may find this applicaiton helpful for designing your layouts:
http://www.droiddraw.org/
Also, if you don't specify a layout for each rotation, android will use one - infact it can use one for everything. If you use fixed values it makes it much harder. Try using fill_parent and wrap_content, you android will take care of scaling the view for each screen type and rotation too.
As a tip, don't forget to include:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

above your relative or linear layout, and:
</ScrollView>

at the end - that way if the view doesn't fit on the screen (ie too much content) it will allow the user to scroll.
Comment: In my experience using droid draw, its a great tool to do some basic design work just to get a mock up or basic layout idea, but the best way to edit the layout is still old fashion text editing the XML. Since list views and dynamically generated content is a big thing in android these things dont show up unless you are runing the app and hence droidraw wont give you the full picture.
Answer: Eclipse's built in layout "editor" shows a reasonably good example of what a layout looks like.  I would assume you're writing your application in Eclipse.  If not, I highly recommend it.  While not perfect, it's the best environment I've found.
Answer: you just need to master the proper use of RelativeLayout's and LinearLayout's. Almost all of my Layouts will start with a Relative and have Linear nested inside.
 I generally don't use LinearLayouts without having either height or width set to 0 and using the weight attribute to make everything the same size.


How do I associate multiple nodes to a user?

Question: I have some users, and I have a "product" content type, which has the following fields: "name," "type," and "description."
I want to associate specific nodes of this content type to a user. How do you suggest I should do this?
Shall I create a new table and store the user and the product ID?
Answer: There is a module for handling relationships between entities for Drupal 7 which shows great promise called relation. At the current time it's still in alpha and I haven't tested it out for a while, so I am not sure where it is at. When I last tried it out, it wasn't quite suitable.
A more stable version which could be made obsolete by the relation module is the references module, which is a port of the Drupal 6 CCK node reference field. I've used that with great success.
Comment: Thanks for these suggestions. I have tried references module, however I get the error 416 - `Requested Range Not Satisfiable

None of the range-specifier values in the Range request-header field overlap the current extent of the selected resource.` When you played with this module it was ok?
Comment: Resolved: The problem was that I have not views installed... strangely he has not complained about it.
Answer: Possibly look into using a 'user reference', part of CCK in Drupal 6 to link products to users.
Comment: Might not work so well on Drupal 7 ;)
Comment: missed the D7 tag, doh!


How should I stack up optical flow along axes to pass it to a neural network

Question: I have extracted the optical flow along x and y axes. I want to pass them into a ConvNet. The thing I cannot understand is whether these should be two different input channels or should I combine them in some way, like stacking them, adding them or averaging them
Paper- Two-Stream Convolutional Networks
for Action Recognition in Videos
Answer: Stack them so that it is an input with two channels. This is the standard approach.
Comment: Do you mean the optical flow images will have 6 channels, 3 for each ?
Comment: No, one channel is for the $x$ component of the flow, one channel is for the $y$ component of the flow. There are two channels in total.


What are the pitfalls of including a continuous variable and a discretized version of the same variable within a regression?

Question: Besides the issue of collinearity - making coefficients kinda useless and p-values non interpretable, I was wondering, what would be the issue of including a continuous variable and the discretized version of that variable in the same model?
For example, let's say X1 is continuous.  I want to include a categorical variable, X2, where X2 is the quartiles of X1.  The reason for this is, I want to use X2 to interact with other categorical variables in the model, as opposed to X1.
I'd imagine the upside of doing this is, more observations for the interaction term itself.  I also have the hypothesis, that maybe the 4th quartile has an especially strong interaction effect with other variables, as opposed to the other 3 quantiles - and I want to bring out the effect of that quartile.
My goal here is to improve prediction accuracy, and the coefficients themselves aren't as important.  The only important thing about the coefficient is if the sign is positive or negative.   I know for a fact X1 is significant based on the data I am working with.
Comment: It's probably a waste of information. Your model can be characterized as including $X_1$ as a "discontinuous linear spline of constant slope." It requires 4 parameters (assuming there's an intercept already in the model). With this many parameters you could use, say, a quadratic spline *and* identify a breakpoint (if you really believe there are any discontinuities). In short, instead of asking whether this approach might possibly work, think about what is *meaningful* to accomplish in your application with the four parameters you're willing to expend on $X_1.$
Comment: The more parameters you include, the greater your risk of overfitting.  That's one reason it's worth paying attention to how many parameters you use.
Comment: Yes, that's always possible.
Comment: If the goal is prediction, you could really use any transformation or combination. (say at the extreme use every value of your variable x1 as a dummy). The problem there will be, how do you know if the improvement for the in-sample prediction will improve out of sample prediction (the one you should care about). One option...Cross-validation. This is related to @whuber "overfitting"  problem.
Comment: Thanks!  In reality, I'm probably more interested in just the 4th quartile as opposed to all 4 quartiles so it would increase the model by one dummy.  I was just wondering if there were any huge pitfalls of doing this when ultimately the goal is prediction and secondary is interpretation of coefficients.   Unfortunately, I need the original variable X1 in the model for sure, as that's how things have been done previously, and it'll be tough to explain why I changed it/removed it for something else.
Comment: @whuber Even if I have a training/test set, I could run the risk of overfitting the test set?
Answer: I would say that in principle there is no problem at all. You are simply making a different set of assumptions regarding the functional form.
For instance, rather than modeling as:
$$y=a_0+ a_1 * x + a_2 *z+e$$
you are modeling:
$$y=a_0+ a_1 * x + a_2 *z + a_2 *z * 1(x>0)+e$$
So a different model that is, perhaps more flexible. The problem I would say, is how to estimate marginal effects.
Consider a simpler model:
$$y=a_0+ a_1 * x + a_2 * 1(x>0)+e$$
So $X $ enters linearly, and as a dummy. So lets assume that this is indeed the Population model. The question is, how do you obtain (and what do you report for the marginal effects of $X$?
$$ \frac{\partial y}{\partial x} = a_1 $$
for any values below or above 0, but
$$ \frac{\partial y}{\partial x} = a_1 + a_2 $$
For values exactly at 0 (technically just below.
So what do you do? what do you report as an average marginal effect? or do you report at specific values?
I think this is the biggest problem here.
HTH
Comment: I'll probably just explain that the coefficients and p-values may not be accurate.  My final model will have many variables and I know some will be correlated with each other - I was hoping that's good enough of an argument to keep them in the model even though p-values may not be significant.  For those with high p-values, I plan to do a simple regression to show that on a standalone basis, it is significant.  Unless the two variables are extremely related - I plan to do some Chi2 tests of independence or correlation tests, I was thinking of just keeping then in the model.
Comment: Why do you care about significance if you intend to use the model for prediction?


Deserializing XML File & storing the type (Crashing)

Question: I'm having a problem which I've been stuck on for days now. I'm deserializing an XML from another developer into a class and I keep getting the exception "InvalidOperationException: The specified type was not recognized: name='string', namespace='http://www.w3.org/2001/XMLSchema', at .".
This triggers at 'Tag' in the code below in 'DevListViewItem'. If I make 'Tag' as a string, it gets the text fine, but this means I can't store the type for serialization back later.
Any help is truly appreciated.
An example of my XML file:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDevListViewItem xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <DevListViewItem>
    <Index>0</Index>
    <Key>0</Key>
    <Tag xsi:type="xsd:string">[Category] = 0 And [CanOpen] = False</Tag>
    <Group />
    <Text>Can Open?</Text>
    <Subitem1>[Category] = 0 And [CanOpen] = False</Subitem1>
    <Subitem1Integer>0</Subitem1Integer>
    <Subitem2Integer>0</Subitem2Integer>
    <Subitem3Integer>0</Subitem3Integer>
    <ExtraData />
    <IsRead>true</IsRead>
    <Iconindex>0</Iconindex>
    <Sort />
    <Condition>false</Condition>
    <Checked>false</Checked>
    <HasInfoButton>false</HasInfoButton>
    <HasExecuteButton>false</HasExecuteButton>
    <IsBold>false</IsBold>
  </DevListViewItem>
</ArrayOfDevListViewItem>

My C# Code:
   public class FilterXMLSchema
    {
        public class Tag
        {
            [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string Type { get; set; }

            [XmlText]
            public string Text { get; set; }
        }

        public class DevListViewItem
        {

            [XmlElement(ElementName = "Index")]
            public int Index { get; set; }

            [XmlElement(ElementName = "Key")]
            public string Key { get; set; }

            [XmlElement(ElementName = "Tag")]
            public Tag Tag { get; set; }

            [XmlElement(ElementName = "Group")]
            public object Group { get; set; }

            [XmlElement(ElementName = "Text")]
            public string Text { get; set; }

            [XmlElement(ElementName = "Subitem1")]
            public string Subitem1 { get; set; }

            [XmlElement(ElementName = "Subitem1Integer")]
            public int Subitem1Integer { get; set; }

            [XmlElement(ElementName = "Subitem2Integer")]
            public int Subitem2Integer { get; set; }

            [XmlElement(ElementName = "Subitem3Integer")]
            public int Subitem3Integer { get; set; }

            [XmlElement(ElementName = "ExtraData")]
            public object ExtraData { get; set; }

            [XmlElement(ElementName = "IsRead")]
            public bool IsRead { get; set; }

            [XmlElement(ElementName = "Iconindex")]
            public int Iconindex { get; set; }

            [XmlElement(ElementName = "Sort")]
            public object Sort { get; set; }

            [XmlElement(ElementName = "Condition")]
            public bool Condition { get; set; }

            [XmlElement(ElementName = "Checked")]
            public bool Checked { get; set; }

            [XmlElement(ElementName = "HasInfoButton")]
            public bool HasInfoButton { get; set; }

            [XmlElement(ElementName = "HasExecuteButton")]
            public bool HasExecuteButton { get; set; }

            [XmlElement(ElementName = "IsBold")]
            public bool IsBold { get; set; }

            public override string ToString()
            {
                return string.Format("{0}", Text);
            }
        }

        public class ArrayOfDevListViewItem
        {
            [XmlElement(ElementName = "DevListViewItem", Namespace = "")]
            public List<DevListViewItem> DevListViewItem = new();

            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2001/XMLSchema")]
            public string Xsi;

            [XmlAttribute(AttributeName = "xsd", Namespace = "http://www.w3.org/2001/XMLSchema")]
            public string Xsd;

            [XmlText]
            public string Text;
        }
    }

Comment: Try `public object Tag { get; set; }` because `xsi:type="xsd:string"` is just a way of storing what the type name is if it doesn't match the actual property type
Comment: @Charlieface Thank you! If you reply as an answer rather than a comment I'll mark it as such!
Answer: Change the Tag property to
public object Tag { get; set; }

Because xsi:type="xsd:string" is just a way of storing what the type name is if it doesn't match the actual property type. So you need to use object so that it will use that to work out the real type.
Answer: You will need to modify your class to handle the xsi:type attribute on the Tag element. You can create separate class for the Tag element that can handle the xsi:type attribute.
For that I removed the tag property first and replaced it with the name of my new class. Call is TagWrapper.
[XmlElement(ElementName = "Tag")]
public TagWrapper TagWrapper { get; set; }

Then created the new class within DevListViewItem.
public class TagWrapper
{
    [XmlText]
    public string Value { get; set; }

    [XmlAttribute(AttributeName = "type", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
    public string Type { get; set; }

    public static implicit operator string(TagWrapper tagWrapper)
    {
        return tagWrapper.Value;
    }

    public static implicit operator TagWrapper(string value)
    {
        return new TagWrapper { Value = value };
    }
}

The Value property will hold the text of tag and type the value of xsi:type


Cannot convert undefined or null to object in Next.js

Question: Hey I am building a login page with Next.js and next-auth
I have also written in providers array in [...nextauth].js.
But when I run the code (given below):-
import { getProviders, signIn } from "next-auth/react";

function Login({ providers }) {
  return (

      {Object.values(providers).map((provider) => (

          <button
            onClick={() => signIn(provider.id, { callbackUrl: "/" })}>
            Login With {provider.name}
          </button>

      ))}

  );
}

export default Login;

export async function getServerSideProps() {
  let providers = await getProviders();

  return {
    props: {
      providers,
    },
  };
}

I get the

This is the console at compilation
[next-auth][error][CLIENT_FETCH_ERROR]
https://next-auth.js.org/errors#client_fetch_error request to https://localhost:3000/api/auth/providers failed, reason: write
EPROTO 12752:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:
 {
  error: {
    message: 'request to https://localhost:3000/api/auth/providers failed, reason: write EPROTO 12752:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\\ws\\deps\\openssl\\openssl\\ssl\\record\\ssl3_record.c:332:\n',
    stack: 'FetchError: request to https://localhost:3000/api/auth/providers failed, reason: write EPROTO 12752:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\\ws\\deps\\openssl\\openssl\\ssl\\record\\ssl3_record.c:332:\n' +
      '\n' +
      '    at ClientRequest.<anonymous> (E:\\Coding\\VSCode\\Next JS\\spotify-2.0\\node_modules\\node-fetch\\lib\\index.js:1461:11)\n' +
      '    at ClientRequest.emit (node:events:390:28)\n' +
      '    at ClientRequest.emit (node:domain:475:12)\n' +
      '    at TLSSocket.socketErrorListener (node:_http_client:447:9)\n' +
      '    at TLSSocket.emit (node:events:390:28)\n' +
      '    at TLSSocket.emit (node:domain:475:12)\n' +
      '    at emitErrorNT (node:internal/streams/destroy:157:8)\n' +
      '    at emitErrorCloseNT (node:internal/streams/destroy:122:3)\n' +
      '    at processTicksAndRejections (node:internal/process/task_queues:83:21)',
    name: 'FetchError'
  },
  path: 'providers',
  message: 'request to https://localhost:3000/api/auth/providers failed, reason: write EPROTO 12752:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\\ws\\deps\\openssl\\openssl\\ssl\\record\\ssl3_record.c:332:\n'
}

Any help would be appreciated.
Note: I tried using
Comment: Can you attach what `providers` returns?
Comment: Make sure that the Object exists before trying to map the object:
`{Object && Object.values(providers).map((provider) => (`
Comment: Does this answer your question: [Error in Postman: Error: write EPROTO 8768:error:1408F10B:SSL routines:ssl3\_get\_record:wrong version number:](https://stackoverflow.com/questions/61916754/error-in-postman-error-write-eproto-8768error1408f10bssl-routinesssl3-get)? Change your `localhost` URL to use `HTTP` instead.
Answer: I also had the same issue. I was able to get the providers object inside getServerSideProps but it was not passing down as it should be inside the page. So it has to do with how my _app.tsx was configured to receive the pageProps.
I was following along a tutorial and below was how my app was configured to receive page props which was the problem:

function MyApp({ Component, pageProps:{ session, pageProps} }: AppProps) {

    console.log(session);
    return (
        <SessionProvider session={session}>
            <Component {...pageProps} />
        </SessionProvider>
    )
}

export default MyApp

I changed the app function to below which actually made sure my pages are receiving the pageProps without any problem:

function MyApp({ Component, pageProps }: AppProps) {
    return (
        <SessionProvider session={pageProps.session}>
            <Component {...pageProps} />
        </SessionProvider>
    )
}

export default MyApp
Answer: Can you post your next.js version as next-auth/react implementation is different based on its version.
I doubt if there is already another application is running on your localhost with the same port number. Or you are using https instead of http for the next.js dev server.
Comment: This should be added as a comment and not as an answer. Answers are strictly for solving the OP's problems.


How to load one physical CPU in a system with virtual cores?

Question: I have an AMD processor with 4 physical cores and SMT enabled. Because of the latter, I see 8 virtual cores in a Linux box.
For example, stress command can spawn a number of workers spinning on sqrt(). If I run stress with -c 1 option, using mpstat I would see that one virtual core usage is 100%. Thus, from my understanding, one virtual core is loaded fully, which basically means that one physical core is loaded fully. Do I get it right?
Is there any way to certainly load one physical CPU? I want to see how Linux shows it in the metrics.
PS. I want to understand how to monitor the CPU load on a system with virtual cores and, I'm not sure If my approach is right, but I don't have any other ideas so far.
Answer: Very few single threads can fully load all resources on a CPU. This is why SMT exists, to drive utilization up by oversubscribing logical processors on physical cores. However, SMT threads are weaker than cores.
A conservative thing to do is plan capacity based on cores, not threads. That way, tasks minimize contention over processor resources.
Watch your application's performance metrics, the user experience focused ones like user response time or job throughput. When those start to degrade, look at performance counters like load average or CPU busy. As well as all the other subsystems, like memory, storage and file system, network, and so on. Look for bottlenecks and symptoms. Brendan Gregg's Linux performance page is a good reference for a comprehensive approach to analyzing performance.
Linux is SMP (and NUMA) aware, the scheduler will avoid expensive core and socket transitions where possible. And load each core up with one task first. Verify a system has more than 1 "Thread(s) per core" with lscpu.  Start a couple of CPU heavy jobs.  Per CPU monitoring tools like  mpstat -P ALL 5 will show a pattern of some CPUs are loaded, and some not.


Techniques to practice?

Question: I'm struggling trying to play a song fully. I can't do it, even thought I know the song. My question is what techniques should I practice to not make a mistake picking the wrong string and fret/note. I was playing the Nightwish's solo, Walking In The Air. I play it slowly, but sometimes I play it perfect, but slowly, sometime not. I wanna play the song fully but without struggling. I think that there should be some techniques to practice, to accomplish this.
I've been practicing electric guitar for over 3 to 4 weeks and I know I should struggle. So some techniques, a to-do list to practice? I wanna play all day, but I need some guidance. I know there are tones of resources out there, but I want your guidance first, to know what to go for and what not. I don't wanna find a mentor because I can't afford it.
I play 1 and a half hours a day, sometimes I play 3 hours.
And thanks for all.
Comment: Related: https://music.stackexchange.com/questions/33443/how-should-one-practice-a-piece-that-is-learned-but-not-fully-mastered
Answer: What is practice? That's a topic that's too big in itself to have a dedicated question/answer. Even though the title of this site is 'Music: Practice and Theory'... Some irony there!
Firstly - 'pracising' for three hours isn't twice as effective as practising for an hour and a half. A new student asked 'how long do Ipractise each day/week? An impossible one to answer clearly. As long as it takes to get it right/be comfortable with it/never to be able to make a mistake/say your two times table at the same time/play it blindfolded/play it twice as fast as it should be/the list grows!
Secondly - find out how you learn. There are many different ways, and one will work better than another for you. I've said it before (and no doubt again) that when you are aware of what is most effective, use that method more. For me it's repetition; for others that induces boredom - which is counter-productive.
Vary what you play. When you find what key your piece is in, play other stuff in that same key. Play up and down the scales and arpeggios in that same key. Make up your own stuff in that same key. Swap notes from that piece around, to make other phrases.
Answer: If you can play the song well most of a time at a certain slow speed, find the metronome marking you are at.  If you don't have a metronome, you can get a free app on your phone.  Next time you play the song, notch the metronome up and see if you can still play through comfortably.  Don't be in a hurry to get it fast.  Go up a notch or two only each day.
Also, isolate the bars (measures) that you find are tripping you up, and practise them individually over and over nice and slow until you are confident with them.  Then put them back into the context of the song.  Hope it helps.
Comment: When starting out, practice so slow it's almost painful. Concentrate only on playing the correct note. The speed will come on it's own, don't push it, or you start playing notes you don't want to play and your brain will be learning to play notes that you don't want. Time well spent learning the right techniques pays off many times over as you become more advanced.

Techniques to practice?


Why might the "fatal error C1075" error occur intermittently when using msbuild?

Question: Possibly related to my other question (note: different error code):

Why might the "fatal error C1001" error occur intermittently when using msbuild?

Our buildbot slave compiles our source code nightly and works most of the time, but intermittently, we see this error:
c:\Program Files\Microsoft Visual Studio 9.0\VC\include\xtree(223) : fatal error C1075: end of file found before the left brace '{' at '..\lib\net\CSocketMultiplexer.cpp(62)' was matched
        c:\Program Files\Microsoft Visual Studio 9.0\VC\include\xtree(427) : see reference to class template instantiation 'std::_Tree<_Traits>::const_iterator' being compiled
        with
        [
            _Traits=std::_Tmap_traits<ISocket *,CSocketMultiplexer::CJobCursor,std::less<ISocket *>,std::allocator<std::pair<ISocket *const ,CSocketMultiplexer::CJobCursor>>,false>
        ]
        ..\lib\net\CSocketMultiplexer.cpp(75) : see reference to class template instantiation 'std::_Tree<_Traits>::iterator' being compiled
        with
        [
            _Traits=std::_Tmap_traits<ISocket *,CSocketMultiplexer::CJobCursor,std::less<ISocket *>,std::allocator<std::pair<ISocket *const ,CSocketMultiplexer::CJobCursor>>,false>
        ]

See the full log output and CSocketMultiplexer.cpp -- Is there anything that I can change in CSocketMultiplexer.cpp that might stop this from happening in future?
Also, probably not worth mentioning, but later on in the log, we see this error (which makes total sense, since the file wasn't compiled):
Copyright (C) Microsoft Corporation. All rights reserved.
BSCMAKE: error BK1506 : cannot open file '.\synergy.dir\Debug\CSocketMultiplexer.sbr': No such file or directory

Comment: Why is CNetworkAddress.cpp being compiled if the error is in CSocketMultiplexer.cpp? Could it be that there is funny #include of cpp file? Also, does this error happens only sometimes with same source (like a compiler bug), or always with specific version of source?
Comment: @Dialecticus Sorry that was misleading; CNetworkAddress.cpp was the file that was compiled (successfully) before CSocketMultiplexer.cpp - I removed this from the snippet since it most likely has nothing to do with the error.
Answer: Judging by this and your other question, I'm starting to put my money on "hardware failure". Could be that one bit in one of your RAM chips is faulty, so if you just happen to hit this very byte, a '}' will turn into something else. I'd run a RAM test tool.
Does this machine exhibit other weird behavior? Rare random crashes, for example?
Comment: Just to reiterate from my other question: Running memtest86+ has revealed 2 errors in the first 2 minutes of running. Perhaps it's time for some new RAM.
Comment: Yep, I figured. That's typically the explanation for random failures like that.
Comment: Haha, I was going to replace the RAM first to be 100% sure you were correct. Don't worry, I won't forget.
Comment: Haha, no problem :) Sorry, didn't mean to push you. Good luck with the RAM. Had that happen to me a bunch of times. One of the most frustrating things to debug since it's the last place you suspect.
Answer: I had the same problem.
The compilation errors were:
*main.cpp(325): error C2601: 'FLAG' : local function definitions are illegal
main.cpp(323): this line contains a '{' which has not yet been matched
main.cpp(326): fatal error C1075: end of file found before the left brace '{' at 'main.cpp(323)' was matched*
But there was nothing wrong with my code. I counted all brackets and the number matched. There weren't any function inside another function.
I solved it by removing all "//" comments from the source code. It seems that the reason for that is bad line formatting which causes the compiler to miss a line break, so the line after a comment is treated as a comment as well.
For example:
// This is a comment

This_is_a_line;

is treated as:
// This is a comment This_is_a_line;

Comment: Glad to be of help