Fazer com que URL abra na mesma Activity

Question: Estou criando uma WebView para Android. Quando carrego o App, a página importada funciona perfeitamente, porém quando clico em algum link da página, esse mesmo link abre em outro navegador.
Gostaria de saber como posso fazer com que todos os links abram na mesma Activity dessa WebView?
Código-fonte:
import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout ll = (LinearLayout) findViewById(R.id.LinearLayout1);

        WebView wv = new WebView(this); //(WebView) findViewById(R.id.webView1);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        wv.setLayoutParams(lp);

        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        ws.setSupportZoom(false);

        wv.loadUrl("http://www.exemplo.com.br/");

        ll.addView(wv);
    }
}

Answer: Defina um WebViewClient na sua WebView para que ele faça o tratamento das URLs:
wv.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return false;
    }
});

Comment: Muito obrigado jovem. Funcionou certinho! :D
Comment: Aceite a resposta do Eduardo como correta então...


Use Excel Userform info for file name

Question: I have a question about userforms. Currently I have a forum button set up with a macro that will show the user a userform, where the user will enter data, and then save 5 out of the 6 sheets as a new book. I want to make it so the file name is based off the value of ProjectName (Me.ProjectName.Value), the first field in the userform. Here is what I have so far:
Private Sub CommandButton1_Click()

Dim iRow As Long
Dim ws As Worksheet
Set ws = Worksheets("Data List")

'find first empty row in database
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

'check for a Name number
If Trim(Me.ProjectName.Value) = "" Then
Me.ProjectName.SetFocus
MsgBox "Please complete the form"
Exit Sub
End If

'copy the data to the database
ws.Cells(iRow, 1).Value = Me.ProjectName.Value
ws.Cells(iRow, 2).Value = Me.ProjectNumber.Value
ws.Cells(iRow, 3).Value = Me.SPVComp.Value
ws.Cells(iRow, 4).Value = Me.Contact.Value
ws.Cells(iRow, 5).Value = Me.ProjMan.Value
ws.Cells(iRow, 6).Value = Me.PODate.Value
ws.Cells(iRow, 7).Value = Me.PONumber.Value
ws.Cells(iRow, 8).Value = Me.PRNumber.Value
ws.Cells(iRow, 9).Value = Me.EstTime.Value

MsgBox "Data added", vbOKOnly + vbInformation, "Data Added"

Sheets(Array("Document Data", "Invoice data", "Hours", "Summary", "Invoice")).Copy
fname = Application.GetSaveAsFilename(Filename:=Me.ProjectName.Value, FileFilter:="Excel Files (*.xlsm), *.xlsm")
ActiveWorkbook.SaveAs Filename:=fname, FileFormat:=52

'clear the data
Me.ProjectName.Value = ""
Me.ProjectNumber.Value = ""
Me.SPVComp.Value = ""
Me.Contact.Value = ""
Me.ProjMan.Value = ""
Me.PODate.Value = ""
Me.PONumber.Value = ""
Me.PRNumber.Value = ""
Me.EstTime.Value = ""
Me.ProjectName.SetFocus

The error I get is name argument not found on Filename:=. I'm still very new to VBA so I'm not exactly sure what to do here. Thank you in advance for the help!
Answer: Method Application.GetSaveAsFileName doesn't support a parameter FileName. If you want to suggest the user an initial file name, please use named parameter InitialFilename instead.
Reference

Use Excel Userform info for file name


Choosing speaker resistance and power handling for a 1W amp head

Question: My objective is to create the classic rock distorted tone/sound for my electric guitar all while maintaining relatively low levels of volume, so I can practice at home.
To that effect, I'm getting a 1W tube amp head that connects to a "4-16 Ohm" speaker. Rather than purchase an existing speaker cabinet, I've decided to create a custom one with a 12" speaker.
Having decided on cone size, there appear to be 2 major parameters for choosing a speaker: impedance and power handling. This is where I'd like some advice. For example, the 12" ET65 is listed at 65W and is available in 3 impedance configurations, 4, 8 and 16 Ohms. I've read that the power of the speaker must exceed that of the amplifier, so any power > 1W would be fine with this amp head. But what's the difference between 15W, 30W and 65W speakers on a 1W head? Also, I've read that a lower impedance speaker will be able to achieve higher volume on an amp that supports multiple impedances. Is this true? Will a 16 Ohm speaker force the amp to distort at lower volume than a 4 Ohm speaker? This would allow me to keep the volume lower.
With regard to my original objective of getting that classic rock sound at low volume, which would be the optimal combination for my 1W amp head: a 16 Ohm 65W speaker, a 16 Ohm 15W speaker, a 4 Ohm 90W speaker, or some other combination of those two parameters?
Comment: Could you add an example or three of "that classic rock sound"? There are many, many different guitar sounds used in music often called "classic rock". Many of them were actually created using pedals, instead of amp distortion. Or are you more interested in understanding how to get the lowest volume, and not as much about the exact tone?
Comment: Man, at the risk of stereotyping, I guess classic rock to me would be ACDC. I'm not too concerned about sounding like a specific artist, rather, I'd like distorted dirty tone at low volume.
Comment: Please don't throw rotten fruit & veg at me for suggesting this... but have you considered a modelling amp [& even headphones, you'd be amazed at the sounds you can get out of an iPhone these days with the right 'amp'] You aren't going to get the acoustic feedback you'd need to achieve a convincing 'pure loud amp, no pedals' sound if you're not generating enough real noise for it to affect the guitar as you're playing it.
Comment: @Tetsujin Already have one. Looking to try something new - tube with a 12"
Comment: Okay, just thought it worth a mention [phew, no rotten fruit ;)
Answer: I'm gonna hit you with three sections here, so please forgive my lengthy answer:
Disclaimer
All of these numbers are sort of approximations and simplifications. That's because audio equipment, like guitar amps, operates across a range of frequencies, and all electrical and electronic components (to a greater or lesser extent) respond differently a different frequencies. So we're going to proceed with an understanding that a "1 Watt amp" has a rated output of 1 Watts into some nominal load impedance.
We say "nominal impedance" because the impedance of a speaker is different at different frequencies, so first we pick an appropriate frequency at which to measure the impedance, and then we round to a reasonable power of two (4, 8, or 16 ohms). It's more like different speakers are in different impedance "classes" or categories.
Now that we have a nominal load, we can connect the amp to that load, and measure the power that the amp can drive into that load at a certain frequency. That's the rated power output. It's a rating of the approximate power in a specific situation. Assuming all your ratings are calculated in a similar way, you can compare different power ratings to get a sense of the power of different amps, but don't spend too much time trying to perform exact calculations based on rated power output or nominal impedances.

The Answer
Now that we agree that we are talking about simplifications and approximations, I can proceed without feeling like I'm being deceptive or imprecise.
When you double the load, you halve the power dissipation. If you know the impedance at which the power output was rated, then you can calculate the (approximate) output power at a different load. If we assume that the "1 Watt" amp was rated into a 4 Ohm load, then it will put out approximately 1/2 Watts into an 8 Ohm load and approximately 1/4 Watts into a 16 Ohm load.
Ok, good, so then the 16 Ohm load will be 1/4 as loud, right? No, not even close. First, dividing the power output by 4 is a drop of about 6 dB in power, which translates (except see the next paragraph) into about a 6 dB drop in acoustic intensity, but you need to drop by 10 dB to be half as loud.
But that's assuming that the different loads have the same efficiency, which is the measurement of how electrical power is turned into acoustic power. So it might be that the 16 Ohm speaker is so much more efficient than the 4 Ohm speaker that it's actually louder! But that's unlikely. Still, it might not be 6 dB quieter, or it could be more than 6 dB quieter.
TL;DR (too late!): The 16 Ohm speaker is generally your "quietest" option, but it might not be that much quieter when all is said and done. Better to choose the speaker that sounds best.

Further Reading
Some points to ponder:

Classic rock "distortion" is usually a lot less gain than most people think it is. AC/DC sounds pretty gainy, but it's really not.
Many classic rock distortion sounds are more about pedals than amps (Jimi Hendrix, Jimmy Page, Stevie Ray Vaughan), although some sounds are pretty much all amp (AC/DC being probably the best example).
Tone chasing will drive you insane, because even with identical gear you'll never sound the same as another guitarist. Using famous tones as guideposts on your way to finding your own tone is a good strategy though. Just don't get too hung up on re-creating something you've heard.
Opinion warning: That 1 Watt amp you linked to seems like more of a gimmick than a low-wattage, high quality tube amp design to me. It looks like the higher end manufacturers are creating all-tube low Watt designs using real power tubes (EL-84, 6V6, etc.) and coming in between 5 and 20 Watts, usually 12 or 15. On the more affordable end of this concept is the Ibanez TSA15H, which also has a Tube Screamer circuit built in (a gimmick but not a terrible one). Fender, Orange, and Engnater also have accessibly priced amps in this category.
If you don't already have woodworking skills and/or speaker cabinet building experience, you might find making a 1x12" cab is a lot more involved than it seems.
Comment: @Megatron The rated dissipation of a speaker is not related to its efficiency or tone, as far as I can tell, besides the fact that it's related to the overall design. One area where there is a correlation is in magnet material. Modern, neodymium magnet based PA speakers are lighter, have cleaner tone, and higher power handling because of the magnet. As opposed to the Celestion Alnico Blue speaker, which has an alnico magnet, lower power handling, and richer tone. The nice thing about the 65 Watt speaker is the cabinet you build from it can be used for lots of different amps, not just this one.
Comment: This is very helpful. Would you mind also addressing the concept of speaker wattage? So if I opt for a 16 Ohm impedance, what would be the difference between a 65W speaker and a 15W one? Thanks!
Answer: You won't run a 15w speaker (let alone a 35w one) into distortion with a 1w amp.  Try a cheap-and-nasty elliptical paper-coned TV-type speaker.  A lot of the classic 'practice amps' used these, and they could distort nicely when pushed hard.
The Blackstar amp you mention has a 'speaker emulated output'.  This may be perfectly satisfactory for practice at home, using either speakers or headphones.  To get what you really crave you need to 'push some air'.  Maybe there's no point in spending too much time and money looking for a low-volume substitute.
Comment: I don't think he's asking about distortion coming from the speaker. He's talking about masterless amps that distort internally but since they have no master volume there's a certain power level at the output where the amp is distorted, and he wants to know how to convert that electrical power to the lowest acoustic intensity (volume) so he can get distortion without loudness.
Comment: The classic rock distorted guitar sound comes partly from driving the amp hard, partly from driving the speaker hard.   Or you can get pretty close to it with a clean amp and an effects box.  In truth, it isn't really satisfying without some VOLUME.
Comment: Thanks for the reply. This is where I'm a bit confused. Are you referring to speaker distortion or amp distortion? If the amp distorts, would that not still be heard through the speaker?


drop event not firing on backbone view

Question: I was happily coding and learning backbone when this #~@@! happened!
I use require to separate my views from models, etc.
In my Backbone view I handle this events:
define(['...'],function(...) {

var DishView = Backbone.View.extend({
    template: _.template(dish),
    tagName: 'div',
    id: 'dish',

    initialize: function() {
        console.log('initializing dishView');
        this.model.on('change', this.render, this);
    },

    render: function(){
        console.log('rendering dishView');
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    },

    events: {
        'click #relations-menu .newItem': 'launch_modal_relations',
        'click #delete' : 'delete_dish',
        'click #save-basic-changes': 'save_basic',
        'drop #dropPicture' : 'dropHandler',
        'dragenter #dropPicture' : 'alertMe'
    },

    alertMe: function () {
        console.log('clicked on image');
    },

    delete_dish: function () {
        this.model.deleteMyself();
        Backbone.history.navigate('/', {trigger: true});
    },

    save_basic: function (event) {
        var name = $('#inputName').val();
        var description = $('#inputDescription').val();
        var price = $('#inputPrice').val();
        this.model.updateBasicInfo(name, description, price);
    },

    dropHandler: function(event) {
        event.preventDefault();
        console.log('drop received');
        event.stopPropagation();

        var e = event.originalEvent;
        e.dataTransfer.dropEffect = 'copy';
        this.pictureFile = e.dataTransfer.files[0];
            ...

    },
return DishView;

});

My drag&drop was working and suddenly when a lot of more functionality was added, it stopped working :( the image file it's opened in the browser.
I've read about the DOM being ready and that this can happen sometimes (if the code gets evaluated when the DOM is ready) but the click events still get fired, also the dragenter event....
Could this be some typo?? I'm going a little bit crazy I can't understand whats going on and can't remember a good commit to go back and check :S
Thank you all if you can show some possible answers :)
For example:
 - how can I debug the drop event???
 - how can I know if an event is tied to my view?
Comment: Also this incredible example that I follow http://nodecellar.coenraets.org/ seems that on the wine detail page I can't drop an image now, I could some days ago... am I going crazy?
Answer: You're not crazy. A recent update in Google Chrome broke the drop-into-browser feature for a lot of sites, including, it seems, the NodeCellar tutorial.
This is quite easily fixable, though. Chrome now requires you to prevent the default action for the dragover event:
$('div').on('drop',function(e){
    e.originalEvent.stopPropagation();
    e.originalEvent.preventDefault();
    $(this).html('A file was dropped!');
}).on('dragover', function (e) {
  e.preventDefault();
});

This JSFiddle demo works for me (Chrome 24.0.1312.52). Here's the Chromium issue #168387, about this problem.
And a pull request to fix this in NodeCellar.
Comment: That was the best answer i could get :) Thank you so much!! How did you know about this issue?? As a dev I always think that it will be more likely to be my fault than browser's...
Comment: @Goofyahead, I didn't know about it until now. I just got curious about your comment it not working in NodeCellar and had to see for myself, because I also have some apps in production that use this feature. After that it was just a quick google search to find the Chrome bug report.
Comment: I can't express how gratefull I am :)
I did review my code, change my functions, go to previous branches or commits...
And I just added the preventDefault on the dragOver and happier dev ever :)
Comment: Also I'm reading that this is the correct behavior, that we all should handle the dragOver event.. funny explanation http://www.quirksmode.org/blog/archives/2009/09/the_html5_drag.html
Comment: Many thanks. Just for the record, you'll need to preventDefault() if you're listening for dragenter
Answer: You can on Backbone add into view this code:
events: {
....
....
    "drop #picture" : "dropHandler",
    "dragover #picture" : "dragOver"
},

dropHandler: function (event) {
    event.stopPropagation();
    event.preventDefault();
....
....
},

dragOver: function (event) {
    event.preventDefault();
}

drop event not firing on backbone view


Comparação com compareTo e Sort

Question: Boa tarde, estou iniciando em Java e estou com um probleminha.
Quero ordenar minha lista por ordem alfabética. Criei uma classe Pessoa e outra classe TestaPessoa.
Pessoa
public class Pessoa implements Comparable<Pessoa> {
    private String nome;
    private int idade;
    private char sexo;

    public Pessoa(String nome,int idade, char sexo) {
        this.nome = nome;
        this.idade = idade;
        this.sexo = sexo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public char getSexo() {
        return sexo;
    }

    public void setSexo(char sexo) {
        this.sexo = sexo;
    }

    public int compareTo(Pessoa comparar) {
        int nomeComparar = this.getNome().compareTo(comparar.getNome());
        if(nomeComparar > 0)
            return -1;
        else if (nomeComparar < 0)
            return 1;
        else return 0;
    }

}

TestaPessoa
import java.util.*;

public class TestaPessoa {

    public static void main(String[] args) {

        Pessoa pessoa1 = new Pessoa("João Fernandes Ferreia", 46, 'M');
        Pessoa pessoa2 = new Pessoa("Fernanda Rodrigues Ferreia", 23, 'F');
        Pessoa pessoa3 = new Pessoa("Lionice Rodrigues Fernandes", 43, 'F');

        List<Pessoa> lista = new ArrayList<Pessoa>();

        lista.add(pessoa1);
        lista.add(pessoa2);
        lista.add(pessoa3);

        Collections.sort(lista);

        for(int i = 0; i < lista.size(); i++) {
            System.out.print(lista.get(i) + "\n");
        }

    }
}

E o meu retorno está sendo:
Pessoa@17d10166
Pessoa@1b9e1916
Pessoa@ba8a1dc

Comment: ali você está pedindo pra imprimir o Objeto Pessoa, que utiliza o toString() pra imprimir o objeto. O toString() de um Object imprime por default seu endereço de memória. Sua solução é pedir para imprimir o nome no for ou sobrescrever o método toString() na classe Pessoa
Comment: Totalmente! Utilize o toString para este caso, que é um método que deve ser colocado na sua classe para gerar uma representacão textual do seu Objeto.
Answer: Troque isso:
System.out.print(lista.get(i) + "\n");

Por isso:
System.out.print(lista.get(i).getNome() + "\n");

E arrume o seu método compareTo(), aonde você trocou o < com o >. Ficará assim:
    public int compareTo(Pessoa comparar) {
        int nomeComparar = this.getNome().compareTo(comparar.getNome());
        if(nomeComparar < 0)
            return -1;
        else if (nomeComparar > 0)
            return 1;
        else return 0;
    }

Ou se preferir, dá para simplificar ainda mais:
    public int compareTo(Pessoa comparar) {
        return this.getNome().compareTo(comparar.getNome());
    }

E por fim, você ainda pode simplificar o seu loop evitando ter que gerenciar contadores. Assim, ao invés disso:
    for(int i = 0; i < lista.size(); i++) {
        System.out.print(lista.get(i).getNome() + "\n");
    }

Use isso:
    for (Pessoa p : lista) {
        System.out.println(p.getNome());
    }

Comment: Obrigada! Agora apareceu os nomes, mas não em ordem alfabética.
Comment: @FernandaFerreira Resposta editada.

Comparação com compareTo e Sort


Free calendar server?

Question: I am looking for free calendar server who can authenticate to LDAP server. I want our users to use thunderbird lightning with calendar server. We have mail server with devcot and squirlmail for webmail. Could you recommend me calendar server?
Answer: The DAViCal CalDAV server will probably do what you're looking for (and has LDAP authentication). I use it with Mozilla Sunbird and it works great.
Comment: Is it easy for installation and configuration? I am more windows than linux user.
Answer: Zimbra has it all
Comment: I know about Zimbra but if we go with zimbra we have to move all e-mail accounts with zimbra. We have more than 800 users and we just cannot afford this migration. I am interested in DAViCal is it easy for installation adn configuration? I am not advanced linux user I am more a windows guy. Kronolith Calendar Application - can it be install separately from the whole Horde framework?
Comment: Yeah, zimbra might be a bit of an overkill here. I don't know about DaviCal, you'd better ask Evan Anderson
Answer: We use the Horde framework, which also has programs for calendaring, tasks, e-mail, and a bunch of others. Horde.org is the place to go.
Answer: zarafa (http://www.zarafa.com) is a great exchange replacement. You can even synchronize smartphones with it using z-push.

Free calendar server?


Sheet music equivalent of ellipses/etcetera

Question: Let's say you're notating patterns up a scale and it becomes obvious how the pattern continues, but you don't want to write out the full thing. You'd like to use the equivalent of "..." or "etc." to show that it continues, then notate the final instances of the pattern to show how it ends. What is the sheet music equivalent of ellipses or "etc."?
Comment: I'm not aware of a specific term or marking for this and I would assume that most who are taking the time to write something out are willing to write out all of the notes.
Comment: Sometimes, writing everything is not the clearest way to express something.
Comment: @Édouard - I can certainly agree with that point but it sounds from the question like there is a specific set of notes that are expected and they would like a shorthand for it, so I would say that writing out the notes is better than an etc type approach.
Answer: There really isn't something like that. The closest thing is a simile where you could write a rhythm pattern and then put the chord changes over the similes as shown in this answer.
Music notation in general is very exact to make sure the musician playing the song know exactly how to play it.
Comment: There are some minor things, like `tr` and the like.
Comment: @sanchises while true, it does not sound what the op wants as a trill is represeing a common pattern as on note with a tr instead of saying to continue this pattern  with different notes as the OP seems to want.
Comment: Exactly, hence I only added this as a minor comment to show that musicians do consider this, but generally don't use these marks since very little is 'obvious' in music (even `tr` is different in various eras)
Answer: There are several existing forms of shorthand that have been accepted as part of standard notation, such as full-/half-/two-measure repeat symbols, sim. (for articulations and dynamics) and turns (which define note sequences by relative pitch and are probably the closest thing to what you are  looking for [I'll add a pic shortly]), but those assume you've already written out what you want at least once.
Sim.:

Example usages of the one- and two-bar repeat signs:

(source: cnx.org)
It depends on your audience. A jazz guitarist might be able to pick up on "Oh, a two-measure repeat (where the noteheads were slashes but were placed on like the actual lines/spaces) plus a chord change, several times over? I guess I'll just move the scale pattern to fit the chord", but a French horn player or clarinetist is infinitely less likely to interpret your markings that way.
Also, as stated above, trills are shorthand that are universally understood because they've been established. Who knows,  if you use your own invented shorthand enough, people might just catch on.

You could, of course, just write like in the upper or lower margin,

Play an A scale, starting on the " and" of beat 2 and beginning on the fifth scale degree, in sixteenth notes, with accents on the "e" and "a" of 4.
Upon reaching scale degree 1 for the second time, descend back to starting point.

and then afterwards say

same, but relative to E3 and on the E scale, every other 2nd scale degree naturaled.

but that's just way harder to read and also probably to write out.

The kind of shorthand you're looking for that depends on the reader's ability to "pick up on"  or "get" what you mean is good for exercise books,as pointed out in an earlier answer, but not for actual sheet music, where composers are known to "change things up" to make things interesting and music becomes much less predictable and standardized.
Hope this helps; the other answers are great too!
Answer: I have seen "etc." being used in e.g. books of exercises. First there's say two bars establishing the pattern and how it progresses, then one bar with just "etc." written in it followed by the end point of the exercise. But then the type of pattern has been explained earlier e.g. by writing out one exercise fully. So it can be used in certain contexts, but should not be assumed to be a known practice. For scale practice, it should be acceptable I think.
Answer: Miškinis's Pater Noster, which begins with various repeating short motifs by each voice. The motifs do not start together either.
My edition, to express this, writes the motif once, then the first few notes of the next repetition of the motif (to ensure the next motif enters where expected), then use a "percent" sign followed by a black line around in the middle of the staff which continues across pages until the point where everyone stops.
Answer: "Etc." is fine, if it's clear.  The more musical term is "sim.".  Just make sure it IS clear :-)  If in doubt, write it out.


Schwarz–Pick Theorem for Higher-dimensional Hyperbolic Space?

Question: According to Wikipedia, Schwarz–Pick theorem says that that a holomorphic map of the unit disk into itself decreases the distance of points in the Poincaré metric, which also means that it decreases distances of points for a two-dimensional hyperbolic space under Poincaré disk model.
My question is: Is there an analog of this theorem for three or higher dimensional hyperbolic space, probably under higher-dimensional Poincaré disk model?
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/126063/discussion-on-question-by-j-l-schwarzpick-theorem-for-higher-dimensional-hyper).
Answer: There exists an analogue for holomorphic map from the unit ball in $\bf C^n$ to itself, or even every bounded open set in $\bf C^n$.
In fact every complex manifold $M$ (for instance open set in $C^n$) such that every map $\bf C\to M$ is constant (for instance bonded open set) admit a natural distance called the Kobayashi distance which is decreased by holomorphic maps.
See https://en.wikipedia.org/wiki/Kobayashi_metric
The Kobayashi distance of the ball in $\bf C^n$ is the natural generalization of the Poincaré metric :its isometry group is $SU(n,1)$.


The area of a triangle, if the vertices are complex numbers

Question: I need to check for this task, if my logic is correct ?
The task is:
Complex numbers are given, which represent the points of a triangle.
$z_1=2+i$
$z_2=i$
$z_3=\lambda-2i$
$z_1$ and $z_2$ represent fixed points, while $z_3$ depends on $\lambda$.
Calculate the area of the triangle
I tried this:
I took that $\lambda$ for example $1$.
$P_{\triangle z_1z_2 z_3}=\frac{1}{2}\left|\begin{vmatrix} 2 & 1 & 1\\ 0 & 1 & 1\\ 1 & -2 & 1 \end{vmatrix}\right|=\frac{1}{2}\cdot (2+1+0-(1-4+0))=\frac{1}{2}\cdot 6=3$
By taking any other number for the $\lambda$, the same result is obtained.
Can it be done in any other way?
Thanks in advance !
Comment: That looks right, but didn't you just put $\lambda$ in the determinant?  I can't follow the details of your calculation, though I agree with the answer.
Answer: We will assume that $\lambda$ varies over the reals.
Let segment $z_{1}z_{2}$ be the base of this triangle, and note that it has length $2$. It is parallel to the real axis and has imaginary coordinate $i$.
Now note that $z_{3}$ has fixed imaginary coordinate $-2i + \text{Im}(\lambda) = -2i$, so the triangle will have base $2$ and height $3$ without regard to the value of $\lambda$. Thus, $\boxed{\triangle z_{1}z_{2}z_{3}\text{ has area }3.}$
For a general triangle, I would either use determinants or the Shoelace Formula (which is equivalent).
Answer: On Cartesian plane, $z_1=A(2,1)$, $z_2=B(0,1)$ and $z_3=C(\lambda, -2)$ i.e., $C$ is any point on the line $y=-2$ (for real $\lambda$).
$\triangle ABC$ is a triangle with base $AB$ of length $2$ and height (distance of $C$ from horizontal line $AB$) $3$.
$$\therefore [ABC] = \dfrac{1}{2}\cdot 2\cdot 3 = \boxed{3}$$
It becomes clear now why the area is independent of $\lambda$. The height of triangle doesn't depend on $\lambda$ (location of $C$ on line $y=-2$).
Answer: The area of $\triangle ABC$ in terms of the coordinates of its vertices
$(A_x,A_y)$, $(B_x,B_y)$, $(C_x,C_y)$
is  found as
\begin{align}
S&=
\tfrac12\,|(B_x-A_x)(C_y-A_y)-(B_y-A_y)(C_x-A_x)|
,
\end{align}
so, for $A=(2,1)$, $B=(0,1)$, $C=(\lambda,-2)$
\begin{align}
S&=\tfrac12\,|(0-2)(-2-1)-(1-1)(\lambda-2)|
=3
.
\end{align}
In this case $\lambda$ vanishes.
Answer: kludginess says hello via https://en.wikipedia.org/wiki/Heron%27s_formula.
$$A = \left(\frac{1}{4}\right)
\sqrt{4a^2b^2 - (a^2 + b^2 - c^2)^2}
.$$
$z_1 = (2+i), ~z_2 = (i), ~z_3 = (\lambda - 2i).$
$a = |z_1 - z_2| = 2.$
$b = |z_1 - z_3| = |(2 - \lambda) - 3i|
= \sqrt{(\lambda - 2)^2 + 9}.$
$c = |z_2 - z_3| = |\lambda - 3i| = \sqrt{\lambda^2 + 9}.$
$$A = \left(\frac{1}{4}\right)
\sqrt{4(2)^2(\lambda^2 - 4\lambda + 13)
- \left[(4 + (\lambda^2 - 4\lambda + 13) - (\lambda^2 + 9)\right]^2}
$$
$$= \left(\frac{1}{4}\right)
\sqrt{4(2)^2(\lambda^2 - 4\lambda + 13)
- \left[(8 - 4\lambda)\right]^2}
$$
$$= \sqrt{(\lambda^2 - 4\lambda + 13)
- \left[(2 - \lambda)\right]^2}
$$
$$= \sqrt{(\lambda^2 - 4\lambda + 13)
- \left[4 - 4\lambda + \lambda^2\right]}
$$
$$= \sqrt{(13)
- [4]} = 3.
$$


Add association to new record with existing model's ID

Question: I have an M2M relationship established between a users table and a plans table. They're joined through a users_plans table.
When I create a new plan, I want to associate it to a user. I have that user's ID.
So I'm trying to create the association like so:
  def changeset(plans, attrs) do
    plans
    |> Repo.preload(:users)
    |> cast(attrs, [:details])
    |> put_assoc(:users, attrs[:users])
    |> validate_required([:details])
  end

attrs looks like: {"details": "we're going to the mall today", "user_ids": [{"id": 1}]}.
Anyway, all I get is an error message: {"errors":{"users":["is invalid"]}}. I believe this is because put_assoc expects me to provide a full user record. Is this something I should be doing?
Could someone explain how I can create the plans object and associate to the existing user with ID 1?
EDIT:
I've changed the request body to:
{
  "details": "we're going to the mall today",
  "user_ids": [1]
}

And I am querying for the users like so: users = Repo.all(from(u in User, where: u.id in attrs[:users])), but I can't access the users key in attrs.
Answer: This is the solution I ended up going with. Open to other recommendations.
Input:
{
  "details": "lorem impsum",
  "user_ids": [1]
}

changeset function:
  def changeset(plans, attrs) do
    users = Repo.all(from(u in User, where: u.id in ^attrs["user_ids"]))

    plans
    |> Repo.preload(:users)
    |> cast(attrs, [:details])
    |> put_assoc(:users, users)
    |> validate_required([:details])
  end


Table design for a dictionary that can have words with many different spellings

Question: I'm working on a small, personal dictionary database in Microsoft Access (the 2013 version). There are a lot of words in English that have two or even more spellings. Realistically speaking though, there are not that many words with three, let alone, four spellings. Nevertheless, they do exist. Examples include aerie/aery/eyrie/eyry (a word with four spellings) and ketchup/catsup/catchup (a word with three spellings). Not to mention that English is literally rife with words that have two spellings. Everybody knows that (the differences between the English and British spelling systems come immediately to mind). So, I need to design my tables in such a way that there are no significant flaws with the design. I'm going to explain step by step what the database should look like and introduce the problems I have found with my current design along the way. So, here we go.
All words, obviously, should be stored in the same table. And I'm not going to include irrelevant aspects of the design such as other columns that might be part of the table (in reality, the database is much more complex). Let's focus on the most important parts. Here's what the Words table with some pre-filled sample data will look like:
+---------+-----------+
| word_id | word      |
+---------+-----------+
|       1 | ketchup   |
|       2 | catsup    |
|       3 | catchup   |
|       4 | moneyed   |
|       5 | monied    |
|       6 | delicious |
+---------+-----------+

To keep track of a group of words that are the same, but just have different spellings, it is probably wise to choose one of them as the main word and the other ones as its child words. Here's the diagram to show you how I envision that (here, ketchup and moneyed are main words, all the others child words):

All this information will be placed in a new table which we shall call the Alternative Spellings table (The columns word_id and alt_spell_word_id are going to be part of the table's compound primary key):
+---------+-------------------+
| word_id | alt_spell_word_id |
+---------+-------------------+
|       1 |                 2 |
|       1 |                 3 |
|       4 |                 5 |
+---------+-------------------+

Here's how all this looks in Access's Relationships panel (notice that I have enforced referential integrity between the word_id column of the Words table and the word_id column of the Alternative Spellings table and checked off the Cascade Delete Related Records option):

Although straight-forwardly simple, that's the only design I've been able to come up with so far. And I think that will basically do it. This is as simple as it gets. The problem with this design, however, is threefold:
1: This is not a serious problem, but I'd still like to hear your thoughts anyway. Every time I'm making a lookup of a word to see it in the Word Details form, I have to go through the entire Alternative Spellings table to see if it has other spellings associated with it or if it is a child word. So, I'd have to search both the word_id and alt_spell_word_id columns. And this process will be talking place for each and every word in the database every time I want to check the details of it. One possible solution is in the Words table to create an additional Boolean column that will keep track of whether a word has alternative spellings. This will indicate if we should scan the Alternative Spellings table at all when opening it up in the Word Details form. Here's what this would look like:
+---------+-----------+------------------+
| word_id | word      | has_alt_spelling |
+---------+-----------+------------------+
|     101 | ketchup   | yes              |
|     102 | catsup    | no               |
|     103 | catchup   | no               |
|     104 | moneyed   | yes              |
|     105 | monied    | no               |
|     106 | delicious | no               |
+---------+-----------+------------------+

I think that's a good design, but, as I said, I'd very much like to hear what you've got to say about this: a problem/not a problem? Your solution?
2: The other problem, which is of more serious nature, has to do with primary keys. word_id and alt_spell_word_id should be part of a compound primary key, of course. We don't want duplicate rows in the table. We all understand that. Not a problem. But here's what happens when we try to enforce referential integrity between the Words table and Alternative Spellings table (see the screenshot above). Everything is fine except that now we can associate a word with the id of a nonexistent word and the database is not going to complain because, for example, the last record in word_id has 4 in it, which is true, we do have a record with the id of 4 in the Words table, but there is no way to impose any kind of constraint on the alt_spell_word_id column. We can put any kind of nonsense in there:
+---------+-------------------+
| word_id | alt_spell_word_id |
+---------+-------------------+
|       1 |                 2 |
|       1 |                 3 |
|       4 |                 5 |
|       4 |             34564 |
+---------+-------------------+

I think that breaks the referential integrity of the database schema and thus is a serious problem. What kind of solution would you like to offer?
3: Another problem with this design is that if we want to delete a certain word from the Words table, the deletion will cascade through the Alternative Spellings table and delete all related records there, which is perfectly fine, but here's the catch: since we agreed that different words in the database can actually be just one word with different spellings, they all should be deleted along with the main word. But that's not going to happen as things stand at the moment. For instance, if I were to delete ketchup in the Words table, all related records in the Alternative Spellings table would be deleted. Fine. But we'd really get two dangling records, catchup and catsup—they can't exist on their own because they are part of the group where ketchup is the main word, but now it has been deleted:
+---------+-----------+
| word_id | word      |
+---------+-----------+
|       2 | catsup    |
|       3 | catchup   |
|       4 | moneyed   |
|       5 | monied    |
|       6 | delicious |
+---------+-----------+

+---------+-------------------+
| word_id | alt_spell_word_id |
+---------+-------------------+
|       4 |                 5 |
+---------+-------------------+

Here's the actual database (simplified version) if you want to play with it.
Thank you all in advance.
Answer: I think that I would use a model in which another table defines word_spelling_groups, so that for every word that can mean the same as "ketchup", there is an entry in this table with the same value of word_spelling_group as "ketchup"s value of word_spelling_group.
An advantage of this would be that a word can be a member of multiple spelling groups, in case it had alternative spellings only in the context of a particular meaning (I struggle for an example).
Answer: 1) For 1, if you add indexes to the database, it is probably not a big concern (since your look-ups of a word then joining to get the alternate words will be fast). However, if a child word can have only one parent, then you do not need an additional table:
The word table can just be:
+---------+-----------+------------------+
| word_id | word      | parent_word_id   |
+---------+-----------+------------------+
|     101 | ketchup   |                  |
|     102 | catsup    | 101              |
|     103 | catchup   | 101              |
|     104 | moneyed   |                  |
|     105 | monied    | 104              |
|     106 | delicious |                  |
+---------+-----------+------------------+

A query for a word and its children would then be:
select wordGroup.word
from word w join word wordGroup on
    (w.word_id = wordGroup.parent_word_id
     or wordGroup.word_id = w.word_id)
where w.word = {your_word};

A query for a word and associated words regardless of whether it was the child word or not would be:
select wordGroup.word
from word w join word wordGroup on
    (w.word_id = wordGroup.parent_word_id
    or wordGroup.word_id = w.word_id)
where wordGroup.word_id = {your_word};

2 The right way of doing this is to place a foreign key constraint (referential constraint) on the tables. In my example for 1, the parent_word_id would have a referential constraint back to word(word_id). For your example, alt_spell_word_id would have a referential constraint back to the word table and the word_id. You could then place a unique constraint on the combination of word_id and alt_spell_id. See (on Access constraints): https://msdn.microsoft.com/en-us/library/bb177889(v=office.12).aspx
3 I think deletion of a primary word has a meaning problem in your design. What does it mean to delete the primary word and keep the grouping? In theory, you would have to do a series of operations: 1-decide on a new primary word; 2-delete the old one. This would be true of almost any design including a primary word.
Another option, is to not have a primary word but to have groups. This alters the db design from a one-to-many relationship between primary word and other words to a many-to-many between words. In this case, deletion is easy because you just cascade all associations to the word out of the word_groups table.
The resulting tables would be:
word:
+---------+-----------+
| word_id | word      |
+---------+-----------+
|     101 | ketchup   |
|     102 | catsup    |
|     103 | catchup   |
|     104 | moneyed   |
|     105 | monied    |
|     106 | delicious |
+---------+-----------+

word_groups:
+---------+-----------+
| word_id |sibling_word_id
+---------+-----------+
|     101 | 102       |
|     101 | 103       |
|     102 | 101       |
|     102 | 103       |
|     103 | 101       |
|     103 | 102       |
|     104 | 105       |
|     105 | 104       |
+---------+-----------+

Foreign key constraints protect referential integrity while indexes will make look-ups fast.


How to determine which text classification algorithm is most appropriate for a given problem?

Question: As someone very new to NLP, I'm curious to know what types of things people consider before building text classification models to help determine an appropriate starting point.
For example, I see people may use a GRU or an LSTM, but are there any questions to consider before training any models that might inform whether I should expect either the GRU or LSTM to be the more appropriate model?
When attempting to look online for guidance, I see lots of articles like this, where the approach is to just train dozens of models and pick which performs best. And not that this is invalid, but I'd like to be a bit more intentional if possible.
Answer: The rule of thumb is: the more difficult the classification is for you as a human being, the more complex model you would need.

Can you guess the label from the presence of few keywords? → If yes, it is probably enough to use a BoW representation (e.g., TF-IDF) and your favorite traditional ML algorithm.
Can you guess the label from the words in the sentence, but it seems it would be hard to come up with a list of keywords? → If yes, word embeddings (probably without stopwords) + your favorite traditional ML algorithm or a feed-forward neural net should be enough.
Can you guess the label the presence of few word phrases, and and need to be aware of simple negations? → If yes, word embeddings (pre-trained or not) + convolutional classifier will be a good choice.
Do you need the structure of the sentence (know who is the subject, who does what, etc.) to assign the label correctly? → If yes, do some serious deep learning.

Currently, the best choice is the pre-trained Transformers (such as BERT or RoBERTa). Their main advantage is that fine-tuning requires much less training data than training the models from scratch, which you would probably need to in the case of RNNs.
Comment: No, I meant Transformers and RNNs.
Comment: Super helpful -- when you say "serious deep learning" is that then where you are referring to transformers/RNNs, or would there be other methods as well to consider?


How to view two dialog boxes on the linux console, running on the same time?

Question: I want to view on the Linux console two dialog windows on the same time.
I want a window that views the progress BAR, and the a second tailbox that view the logs are running.
The problem is that the dialog appears always in the center of the console.
What I want is

to view the two dialog boxes on the same time on the console,
while the progress bar is on the top of the screen,
and the the box should present down in the screen.

How to implement this?
How to place the dialog window up or down and not in the central?
    dialog --title "RUN TASKS FROM TEXT TABLE" --gauge "Please wait..." 10 70 0
    dialog --tailbox file.log 10 100

Answer: You can use screen program.

Executing screen manually
After installing screen, execute it by typing screen in your console.
Split your screen by pressing ctrla then S (uppercase S, with shift
Enter your first command
After having the fist command executed, press ctrla then tab to switch to the another window.
Press ctrla then c
Enter the second command.
Done.

Using a script
Create a new directory where you would want to put the script, ie. ~/test/
Create a .screenrc file with the following content:
startup_message off
screen dialog --title "RUN TASKS FROM TEXT TABLE" --gauge "Please wait..." 10 70 0
split
focus down
screen dialog --tailbox /var/log/syslog 10 100

Then just enter screen command to execute the script.
Comment: the problem is that I not want to edit it manual , is shuld be run by bash script , can you please advice how to use the screen command in bash script to do the same as you explain here but from script ?
Comment: I have modified the answer, take a look please
Comment: startup_message off isnt valid in linux the same about focus down
Comment: It is valid, you can take a look here: http://linux.die.net/man/1/screen

The script I have show you works on my Debian box (screenshot attached in the answer).
Comment: HOW IT IS VALID: ( run this on linux and tell me what you see - startup_message off )
Comment: any way its not valid on my linux ( the same on all linux versions )
Comment: From what I see, you are trying to execute `.screenrc` file directly. It is NOT a sh/bash script file, it is a script file for `screen` program. All you need to do is to create `.screenrc` file with the contents I have posted, and then execute `screen` command in the same directory.
Comment: you say here that I need to enrer the screen comand , is it possible to run the screen also from script ?
Comment: Yes, you can create a `script.sh` file with following content: `chdir /your/directory && /usr/bin/screen`.
Comment: I run this screen .screenrc ( but without results )
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/17264/discussion-between-maihabunash-and-adam).
Comment: I not understand how you run the two windows , I run the screen command alone and screen .screenrc , both are not works!
Comment: You need to execute `screen` command inside directory where `.screenrc` file is located
Comment: YES I did it and its not works!
Comment: any other ideas?


Como atribuir os elementos de uma lista a diferentes variáveis em Python?

Question: Tenho uma lista, como a seguinte:
lista = [1, 2, 3, 4, 5]

Mesmo sem saber quantos elementos tem dentro da lista, como faço para atribuir cada elemento da lista a uma variável distinta? (como no exemplo abaixo)
elemen1 = '1'
elemen2 = '2'
elemen3 = '3'
elemen4 = '4'
elemen5 = '5'

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo.
Answer: Isto?
lista = [1, 2, 3, 4, 5]
a, b, c, d, e = lista

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
É possível fazer com o mecanismo de tuplas, onde você pode definir variáveis em sequência e a lista fará a população delas automaticamente. Claro, precisa bater o número de elementos com a de variáveis, caso contrário ou alguns elementos não entrarão nas variáveis ou algumas variáveis ficarão sem valor.
Quase sempre isso não faz sentido e não traz vantagens. Uma variável acessada pelo seu índice não deixa de ser uma variável. Especialmente uma variável com o mesmo nome diferenciado apenas um número sequencial mostra que é a opção errada. Em bem poucos casos onde uma API funciona de um jeito e há muita vantagem em outra forma é que deveria fazer isso.
Comment: Não ofendeu, nem imagino como poderia. O que você quer de fato é outra coisa e fica mais claro que não precisa de variáveis isoladas, quer só acessar a lista. Eu respondi o que perguntou, que serve quase que apenas como curiosidade de como funciona.
Comment: @BrunoSantos Para "executar funções em cada elemento" você usa um `for` e não precisa de variaveis soltas. Algo como `for elemento in lista: funcao(elemento)`. No fim está a provar exatamente o que o Maniero disse, que o seu exemplo não é o que você quer e as variaveis soltas não ajudam só desajudam.
Comment: Aí você quer o impossível (dentro da normalidade) ou ou completamente desnecessário, conforme eu citei. Na verdade respondi para indicar a curiosidade, com este comentário fica claro que deseja fazer algo sem sentido. Até é possível usar reflexão, mas aí faz menso sentido ainda, porque a única justificativa para fazer isto é uma possível ínfima melhoria de performance, que depende inclusive de implementação e poderia nem ocorrer. Com reflexão ficará bem mais lento sempre, então acabaria a única motivação hipostética. E ainda não teria sentido acessar variáveis que nem sabe se existem ou não
Comment: O código citado não funcionaria, pois quero fazer sem saber quantos elementos tem na lista
Comment: Entendi. Desculpe se ofendi. É pouco conhecimento no tema. Eu poderia acessar os elementos da lista pelo índice, ainda assim, quero fazer um código que, neste novo caso, conte a quantidade de elementos da lista, e faça o pipeline seguinte para cada elemento da lista. Ou seja, não quero ter que saber quantos elementos tem na lista, para posteriormente executar as funções para cada um deles.


Level of Parallelism present in multiple threads per core

Question: So i have been looking into some of the technologies that implement multiple threads per core (like intel's hyperthreading) and I am wondering whats the extent of parallelism in these kinds of technologies. Is it true parallelism or just more effective concurrency? It seems they still share the same execution units and core resources, basically seems like its just virtualizing the usage. So I am unsure how true parallelism could occur. And if this is the case then what is the benefit? You can achieve concurrency through effective thread context switching.
Answer: I'm no expert, but from what I've read (Long Duration Spin-wait Loops on Hyper-Threading Technology Enabled Intel Processors):

Each physical processor has two logical processors. The logical processors each have their own independent architectural state, but share nearly all other resources on the physical processor, such as caches, execution units, branch predictor, control logic and buses.

So, basically, if one logical processor is using a physical unit (e.g., FPU, the Floating-point unit), the other logical processor is allowed to use another resource (e.g., ALU, the arithmetic logic unit).
From what I've read, you can expect a performance increase of 15-20% best case scenario. I don't have any actual numbers, but don't expect the same level of performance increase as you'd expect from adding another physical processor.
Comment: Don't forget that these days a computer's RAM system is quite a bit slower than its CPU.  L1, L2, L3 caches help, but sometimes a thread needs to access a piece of memory that is not present in any of the caches, and there is nothing for the thread to do except wait until the required data is fetched from RAM, which can take several thousand cycles.  With hyper threading (and another thread that's ready to run) the CPU can simply put that thread aside and let another one run until the data gets to the CPU -- without hyper threading, the CPU would be idle during that period.
Comment: Thanks for the response. I don't really understand why that would be useful, with dynamic scheduling and out of order execution I would imagine that most of the resources present would be utilized. Furthermore, I would expect the overhead incurred for monitoring resource utilization would marginalize the benefits.
Comment: @PandaRaid I admit I don't know much about the details, but it seems modern processors really do have a huge surplus of resources, so much that it became perfectly feasible to have 2 threads running on the same CPU simultaneously. Here's another good explanation: http://www.tomshardware.co.uk/answers/id-1694436/hyperthreading-work.html#.
Comment: @PandaRaid "I would imagine that most of the resources present would be utilized" - not if there's more than one resource of a given kind (e.g., multiples ALUs)
Comment: Even if there are multiple functional units, they are still being utilized. Most modern processors use out of order execution, dynamic scheduling and multiple issue which requires either pipelined or duplicated hardware.
Comment: @JeremyFriesner How would that be any different from a thread context switch? The processor becomes idle while thread waits for data, so it is preempted until the data arrives and then it resumes operation. Or out of order execution, where the operands are not ready so it lets the next instruction execute while the data is being buffered.
Comment: No difference, it's just another reason why the CPU might do a thread context switch.  (Unless by "thread context switch" you mean the OS-level version of a context switch, which is a different thing that is not handled directly/entirely within the CPU)
Comment: Exactly, context switching is a problem handled both by modern OS and hardware. So i don't get the effectiveness of adding an extra "logical" processor per core for concurrent thread execution when it is something that is already addressed. Seems like added overhead for no benefit, in fact a lot of things I have read make it seem as though theres a performance penalty in many cases.
Answer: So there are a lot of factors that determine the benefits present in Hyperthreading. First off since they are sharing resources there is obviously no true parallelism but their is some increase in concurrency depending on the type of processor.
There are three types of hardware threading. Fine grained which switches threads in a round robin fashion with the goal of increased throughput, at the cost of increased individual thread latency. Switching is done on a clock to clock basis. There is course grained which is more like a context switch, where the processor switching the thread when a stall or some sort of memory fetching occurs. Then there is simultaneous in which thread switching occurs in the same clock, meaning there is multiple thread data in the Reorder Buffer and Pipeline at the same time. They are depicted as follows.

Hyperthreading corresponds to the SMT in this diagram. And as seen, the effectiveness of the design depends primarily on one thing: how busy the pipeline is. In dynamically scheduled processors, where the goal is to keep the pipeline and execution units as busy as possible, the advantages see diminishing returns of around 0 to 5 percent from what I have seen. For statically scheduled processors, where the pipeline has a lot of stalls the benefits are much more prevalent and see gains of around 20 to 40% depending on the capabilities of the compiler reordering the instructions.


How to schedule http invocation of authenticated cloud function?

Question: I have a sort-of infrequently used cloud function that has a slow cold start latency. I want to reduce this latency by keeping the function warm. This function is normally only called by an app engine app, so it has restricted Cloud Invoker permissions. Cloud Scheduler seems like a good candidate for pinging the function to keep it warm. It seems that direct http invocation of the function is necessary. Even though the common convention is to schedule functions useing pub/sub, a single function can't be both http-triggered and pubsub-triggered.
I set my Cloud Scheduler job as follows, but still getting PERMISSION_DENIED error when it runs. Is something configured wrong, or is Cloud Scheduler not able to call an authentication function directly over http? One suspicion is that the Audience parameter is not really the "target_audience" parameter that Cloud Functions expects, but the standard "aud" parameter.
Answer: There are several potential problems to investigate:
1) Do you have the permission iam.serviceAccounts.actAs for the service account?
When Cloud Scheduler creates tokens from a service account, it needs the permission iam.serviceAccounts.actAs. This is in the role roles/iam.serviceAccountUser. Add this role to the Cloud Scheduler Service Agent (notice the word Agent).
2) Is Cloud Run allowing this service account permissions?
Unless you have enabled the allUsers you need to add the service account to Cloud Run.
This is in the "Show Info Panel" under the "Permissions" tab. You can also add this via the CLI with the --service-account command-line option.
Comment: Thanks! Bullet point 1 fixed the issue. I didn't realize Cloud Scheduler also has its own service account that needs to be configured.
Comment: BTW, ignore my original comment about it not working that is now deleted. I was still getting failure, but didn't look deeper into the logs to see that it was no no longer an auth issue but rather a 400 from a missing query string param my function requires.
Comment: Just an update, you can no longer add a certain permission on a role created by GCP. Only custom roles can be edited.
Comment: @DonnaldCucharo - How does your comment apply to my answer? Google Cloud has never supported editing Google Cloud preconfigured roles.
Comment: @JohnHanley you mentioned adding a certain role to Cloud Scheduler Service agent. Could you clarify what it meant? I know that this answer worked for OP but from what I understand, you were asking us to add a role to a role (which I find slightly confusing). Do you mean adding the role on a service account with `Cloud Scheduler Service Agent` role?
Comment: @DonnaldCucharo - Service Agents are service accounts. You can add one or several roles to a service account. Do not confuse with roles with similar names.


How to give permissions to local computers using computers' MAC addresses in Windows Server 2016 for file sharing

Question: I have the following issue:
I have a server with Windows Server 2016, and I need to use it only for saving, reading, and modifying files with file sharing.
The way I have the restrictions is with logging in from client computers and logging with the local server accounts, but I need the authentication to be the MAC Addresses of the Computers clients which access to file sharing in order to be easy for the user.
Is there any way I can authenticate to access file sharing in the Windows Server with the client MAC address to give their respective permissions by MAC address from Windows Server?.
Comment: This is one of the things Active Directory is meant for, giving permissions by user.
Comment: Using MAC addressing for security just means you are fooling yourself that you have security. Security by MAC address is no security.
Comment: You know that MAC addresses are sniffable on the network, and settable by each host?
Comment: Can i give permissions to Mac Address ??
Answer: I'm not sure why you would want to use the MAC address to designate share permissions but the short answer is no. MAC addresses can be spoofed so that wouldn't be a very secure setup. Anybody would be able to clone anyone else's MAC address to grant themselves access to another user's share.
You would use Active Directory Users and Computers to assign permissions on each share to either the user or machine. Also it's better to create groups/OUs and give the group permission to the file share. You would then add any user (or computer) who should have access to the file share to that group.


Wrong distance calculation with MongoDB

Question: I am executing the following raw query with MongoDB:
qry = {"position" : SON([("$near", [52.497309,13.39385]), ("$maxDistance", distance/111.12 )])}
locations = Locations.objects(__raw__=qry)

The position in the database is set to [52.473266, 13.45494].
I get a result once I set the distance to 7.3 or higher, so it seems the two locations must at least be 7.3 kilometer away from each other.
When I calculate the distance of those two geo locations with Google Maps (for example going by car) it's telling me it's only 5.2 kilometer away from each other.
I tested it with loads of different locations and there is always a big difference in the distance calculation of google and Mongodb
Am i missing anything or can somebody explain please where this difference is coming from?
I already checked this answer but it's not working for me...
Comment: Hi, i'm executing this call from within django/tastypie so SON is working for me and I cannot use .getIndexes(). maxDistance with the legacy coordinate pairs is using radians. ...."If you query for legacy coordinate pairs, specify $maxDistance in radians." So to calculate a distance in km I need to convert it to radians with the division of 111.12
Answer: MongoDB assumes that coordinates are in (long, lat) format. If you compute distances by hand using Great-circle distance you'll see what is going on:
> from math import acos, sin, cos, radians
>
> long_x, lat_x = [radians(y) for y in [52.473266, 13.45494]]
> long_y, lat_y = [radians(y) for y in [52.497309, 13.39385]]
>
> acos(sin(lat_x) * sin(lat_y) + cos(lat_x) * cos(lat_y) * cos(long_x - long_y)) * 6371.0
7.27362435031

Google takes coordinates in (lat, long) format so if you provide the same input Google interpretation will be like below:
> acos(sin(long_x) * sin(long_y) + cos(long_x) * cos(long_y) * cos(lat_x - lat_y)) * 6371.0
4.92535867182

Wrong distance calculation with MongoDB


How to scrape data from each product page from Aliexpress using python selenium

Question: I am trying to scrape each product page from this website: https://www.aliexpress.com/wholesale?catId=0&initiative_id=SB_20220315022920&SearchText=bluetooth+earphones
Especially I want to get comments and customer countries as I mentioned in the screenshot:
enter image description here
The main issue is that my code does not inspect the right elements  and this is what I am struggling with .
First, I tried my scraping on this product : https://www.aliexpress.com/item/1005003801507855.html?spm=a2g0o.productlist.0.0.1e951bc72xISfE&algo_pvid=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad&algo_exp_id=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad-8&pdp_ext_f=%7B%22sku_id%22%3A%2212000027213624098%22%7D&pdp_pi=-1%3B40.81%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch
Here is my code :
from selenium import webdriver
from selenium.webdriver.common.by import By
from lxml import html
import cssselect
from time import sleep
from itertools import zip_longest
import csv

driver = webdriver.Edge(executable_path=r"C:/Users/OUISSAL/Desktop/wscraping/XEW/scraping/codes/msedgedriver")
url = "https://www.aliexpress.com/item/1005003801507855.html?spm=a2g0o.productlist.0.0.1e951bc72xISfE&algo_pvid=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad&algo_exp_id=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad-8&pdp_ext_f=%7B%22sku_id%22%3A%2212000027213624098%22%7D&pdp_pi=-1%3B40.81%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch"

with open ("data.csv", "w", encoding="utf-8") as csvfile:
    wr = csv.writer(csvfile)
    wr.writerow(["Comment","Customer country"])

driver.get(url)
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')

review_buttom = driver.find_element_by_xpath('//li[@ae_button_type="tab_feedback"]')
review_buttom.click()

html_source = driver.find_element_by_xpath('//div[@id="transction-feedback"]')
tree = html.fromstring(html_source)

#tree = html.fromstring(driver.page_source)
for rvw in tree.xpath('//div[@class="feedback-item clearfix"]'):
    country = rvw.xpath('//div[@class="user-country"]//b/text()')
    if country:
        country = country[0]
    else:
        country = ''
    print('country:', country)

    comment = rvw.xpath('//dt[@id="buyer-feedback"]//span/text()')
    if comment:
        comment = comment[0]
    else:
        comment = ''
    print('comment:', comment)

driver.close()

Thank you !!
Answer: What happens?
There is one main issue, the feedback you are looking for is in an iframe, so you wont get your information by calling the elements directly.
How to fix?
Scroll into view of element that holds the iframe navigate to its source and interact with its pagination to get all the feedbacks.
Example
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd

url = 'https://www.aliexpress.com/item/1005003801507855.html?spm=a2g0o.productlist.0.0.1e951bc72xISfE&algo_pvid=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad&algo_exp_id=6d3ed61e-f378-43d0-a429-5f6cddf3d6ad-8&pdp_ext_f=%7B%22sku_id%22%3A%2212000027213624098%22%7D&pdp_pi=-1%3B40.81%3B-1%3B-1%40salePrice%3BMAD%3Bsearch-mainSearch'

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.maximize_window()
driver.get(url)

wait = WebDriverWait(driver, 10)

driver.execute_script("arguments[0].scrollIntoView();", wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.tab-content'))))
driver.get(wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#product-evaluation'))).get_attribute('src'))

data=[]

while True:

    for e in driver.find_elements(By.CSS_SELECTOR, 'div.feedback-item'):

        try:
            country = e.find_element(By.CSS_SELECTOR, '.user-country > b').text
        except:
            country = None

        try:
            comment = e.find_element(By.CSS_SELECTOR, '.buyer-feedback span').text
        except:
            comment = None

        data.append({
            'country':country,
            'comment':comment
        })
    try:
        wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, '#complex-pager a.ui-pagination-next'))).click()
    except:
        break

pd.DataFrame(data).to_csv('filename.csv',index=False)


ANOVA within subsets of data

Question: My dataset consists of gene expression values recorded over 3 timepoints
I am trying to apply a anova test with tukey correction to look for differential expression of a gene across the timepoints. So for each gene i want a comparison like:
    gene a timepoint 1 vs 2
    gene a timepoint 2 vs 3
    gene a timepoint 3 vs 1
My data is in the below format:
    > head(rf)
                gene      expn timepoint rep
2  EG620009  // EG620009  8.428851      x0hr   0
3                 LYPLA1 10.386500      x0hr   0
21 EG620009  // EG620009  8.582346      x0hr   1
31                LYPLA1 10.379710      x0hr   1
22 EG620009  // EG620009  8.566248      x0hr   2
32                LYPLA1 10.399080      x0hr   2
    > tail(rf)
                gene      expn timepoint rep
23 EG620009  // EG620009  8.561409     x24hr   0
33                LYPLA1 10.233400     x24hr   0
24 EG620009  // EG620009  8.750639     x24hr   1
34                LYPLA1 10.023780     x24hr   1
25 EG620009  // EG620009  8.560267     x24hr   2
35                LYPLA1 10.025980     x24hr   2

If I were to do:
TukeyHSD(aov(rf$expn ~ rf$timepoint * rf$gene))

this would give me a comparison between every timepoint across all of the genes
ie. including comparisons such as
gene a timepoint 1 vs gene b timepoint 2
I have been trying to work out how to apply the aov function to the data subsetting by gene. I have defined a function that gives the p value as output and tried to apply that to each gene individually using the by function as below;
> gene.aov = function(x) {TukeyHSD(aov(expn ~ timepoint, data = x))}
> aov.pval = function(y) {y$timepoint[,4]}
> gene.pval = function(z) {aov.pval(gene.aov(z))}
> pvals = by(rf$expn,list(rf$gene),gene.pval)
> Error in eval(predvars, data, env) :
   numeric 'envir' arg not of length one

Any hint why this doesn't work? Or should i be approaching this problem in a completely different way?
Thanks!
Answer: it's not working because by expects it's first argument to be a data.frame or matrix, you are passing is rf$exp which is a numeric vector. You could do this and it will work fine (I abandoned the multiple functions for readability).
by(rf, rf$gene, function(x) {TukeyHSD(aov(expn ~ timepoint, data = x))}, simplify = F)

rf$gene: EG620009
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = expn ~ timepoint, data = x)

$timepoint
              diff       lwr      upr     p adj
x24hr-x0hr 0.09829 -0.123391 0.319971 0.2857424

---------------------------------------------------------------------------
rf$gene: LYPLA1
  Tukey multiple comparisons of means
    95% family-wise confidence level

Fit: aov(formula = expn ~ timepoint, data = x)

$timepoint
                 diff        lwr       upr     p adj
x24hr-x0hr -0.2940433 -0.4876756 -0.100411 0.0135193

ANOVA within subsets of data


Como obter o próximo elemento em um foreach em PHP

Question: Como faço para obter o próximo elemento de um array usando foreach?
Por exemplo, estou iterando em um array e preciso saber se o próximo elemento desse array é igual ao que eu to para fazer alguma operação em relação à isso.
Comment: Eu usaria um for no lugar do foreach. Aí você faz: for ($i=0; $i<$numero_elementos_do_array) { if ($array[$i] == $array[$i+1]) { comandos que você quer;} } Mas, já adianto, você deveria postar qual o problema real. Porque do jeito que você postou não tem como saber se isso funcionaria.
Comment: Cara, como assim? Explica melhor qual o caso.
Comment: Por exemplo, estou iterando em um array e preciso saber se o próximo elemento desse array é igual ao que eu to para fazer alguma operação em relação à isso.
Comment: Ah OK, vou modificar minha resposta! :)
Comment: Você está falando de arrays numéricas, associativas, ou ambas?
Comment: Boa pergunta bfavareta, mas se ele usa um foreach, acho ele usa um array associativa. Por isso, "precisa ler array[$i+1]" não da certo.
Answer: O php possui uma biblioteca interna chamada SPL (Standard PHP Library)
Ela tem diversos objetos e interfaces que ajudam a resolver problemas comuns que encontramos.
Temos diversos Iterators para resolver seu problema, dois em especial: ArrayIterator e CachingIterator
O ArrayIterator cria um objeto a partir de um array com métodos para as funções como current, next, rewind, etc.
Já o CachingIterator é um iterator com "um olho no peixe e outro no gato", tendo uma posição a frente em relação ao iterator.
Dentro do foreach seu código ficaria assim:
<?php

$arr = [
    'eu'    => 'tenho',
    'sou'   => 'keys',
    'um'    => 'para',
    'array' => 'comparar',
    'assoc' => 'galera'
];

$iterator = new CachingIterator(new ArrayIterator($arr));

var_dump($iterator->current());                      // null
var_dump($iterator->getInnerIterator()->current());  // string(5) "tenho"

foreach($iterator as $key => $value){

    echo "Atual: $value - ";

    $proximoValue = $iterator->getInnerIterator()->current();
    echo "Proximo: $proximoValue \n";

    // Sua lógica aqui

}

Answer: Com o foreach talvez não seja a melhor solução, mas pode fazer com o each(), que retorna o elemento atual e avança o ponteiro um elemento. Ficaria assim:
$arr = array("a","b","c","c","d");

while($a= each($arr)){

    //o each() avançou um e guardou o anterior
    $b = current($arr);

    if($a['value'] == $b)
    {
        echo "OK
";
    }
    else
    {
        echo "NOT OK
";
    }
}

Um olhada no manual pode ajudar a entender melhor http://php.net/manual/en/function.each.php
Answer: Simples.
Você faz o foreach normal, mas usa também um next no array para passar sempre para o próximo.
<?php

// Array
$itens = array('foot', 'bike', 'car', 'plane');

// Lista array completo
echo "Array completo: ".implode(',',$itens)."

";

// Percorre o array
foreach($itens as $item){
    // Exibe o item atual baseado no foreach
    echo "Item atual: ".$item." - ";

    // Exibe o próximo item
    echo "Item Proximo: ".current($itens)."
";
    next($itens);
}

?>

Ele vai retornar.
Array completo: foot,bike,car,plane

Item atual: foot - Item Proximo: bike
Item atual: bike - Item Proximo: car
Item atual: car - Item Proximo: plane
Item atual: plane - Item Proximo:

Answer: Usando um array básico, não tem dificuldade (precisa ler o index $x e $x+1). Mas com um array associativo (o que acho e o caso aqui) e um pouco mas complicado. Depois de pesquisar, aqui tem uma resposta:
<?php
$tab["A"] = 12;
$tab["B"] = 15;
$tab["C"] = 8;
$tab["D"] = 23;

foreach($tab as $key => $value)
{
    echo "Key e valor desta vez: ".$key. "-" .$value."
";

    $key =  key($tab);   // proximo index
    $val = $tab[$key];   // valor
    next($tab);          // avancar

    echo "Key e valor a proxima vez: ".$key."-".$val."

";
}
?>

O ponto estranho e que precisa colocar o next() se não, ficamos cada vez com o mesmo "próximo", como se tinha 2 index (um para o foreach e um para o key).


How to have a single component route default to a component Angular

Question: I have an angular application, In there I have a component that needs show on two routes before each subsequent components: i.e.
Service > List (same Component) > Request
Floor > List (same Component) > Floor request
When the user selects the service route, I want the list component to show as default and the same with the floor route.
Would I do something like this:
{
    path: 'service',
    component: serviceComponent,
    children: [
      { path: 'list', component: listComponent },
    ]
  },

But how would it default to the list if service was selected?
Comment: you want to call same component from 2 different route?
Comment: Not sure I understand, but maybe what you want is simply to replace `path: 'list'` by `path: ''`.
Answer: First method:
You can achieve it by using parameter
{path: 'service', component: ServiceComponent},
{path: 'floor', component: FloorComponent},
{path: 'list/:type', component: ListComponent}

ListComponent
To be able to get the parameter you need to follow few steps.
Add this import
import {ActivatedRoute} from '@angular/router';

Inject it to constructor()
constructor(private route: ActivatedRoute) {}

And add to constructor() or into ngOnInit() subscribe on params
this.route.params.subscribe((params) => {
      console.log(params.type);
      // Here you can make request based on params.type
    });

The URL will look like this http://localhost:4200/list/service or http://localhost:4200/list/floor
Second method:
Or you can set data property to route in Angular Router.
{path: 'service',
    component: ServiceComponent,
    children: [
      {path: 'list', component: ListComponent, data: {requestType: 'service'}}
]},
{path: 'floor',
    component: FloorComponent,
    children: [
      {path: 'list', component: ListComponent, data: {requestType: 'floor'}}
]},

ListComponent

The rest is very similar to first method

Add this import
import {ActivatedRoute} from '@angular/router';

Inject it to constructor()
constructor(private route: ActivatedRoute) {}

The only difference will be here because you need to subscribe to data
this.route.data.subscribe((data) => {
  console.log(data.requestType);
  //Here you can make request based on data.requestType
});

Answer: {path: 'service',
    component: serviceComponent,
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: listComponent}
]},
{path: 'floor',
    component: floorComponent,
    children: [
      {path: '', redirectTo: 'list', pathMatch: 'full'},
      {path: 'list', component: listComponent}
]},

What I did was just setting the default route to those components. And it will redirect you to list.


Swiper React | How to create custom navigation/pagination components using React refs?

Question: SwiperJS documentation states that navigation prevEl/nextEl can either be of type "string" or "HTMLElement". Using string selectors is easy enough as:
const MySwiper = (props) => (
  <Swiper
    navigation={{
      prevEl: '.prev',
      nextEl: '.next',
    }}
    {...props}
  >
    <SwiperSlide>slide 1</SwiperSlide>
    <SwiperSlide>slide 2</SwiperSlide>

  </Swiper>
)

However, how would this be correctly implemented with React refs? Using HTML nodes instead of string selectors allows for navigation prevEl/nextEl to be scoped to each rendered instance of MySwiper.
const App = () => (

    <MySwiper className="mySwiper1" />
    <MySwiper className="mySwiper2" />

)

In the App example above, navigation prevEl/nextEl from .mySwiper2 should not trigger sliding of .mySwiper1, which is what would happen with string selectors.
My current sad & hacky workaround:
const MySwiper = () => {
  const navigationPrevRef = React.useRef(null)
  const navigationNextRef = React.useRef(null)

  return (
    <Swiper
      navigation={{
        // Both prevEl & nextEl are null at render so this does not work
        prevEl: navigationPrevRef.current,
        nextEl: navigationNextRef.current,
      }}
      onSwiper={(swiper) => {
        // Delay execution for the refs to be defined
        setTimeout(() => {
          // Override prevEl & nextEl now that refs are defined
          swiper.params.navigation.prevEl = navigationPrevRef.current
          swiper.params.navigation.nextEl = navigationNextRef.current

          // Re-init navigation
          swiper.navigation.destroy()
          swiper.navigation.init()
          swiper.navigation.update()
        })
      }}
    >
      <SwiperSlide>slide 1</SwiperSlide>
      <SwiperSlide>slide 2</SwiperSlide>

    </Swiper>
  )
}

Answer: While Pierrat's answer did initially solve it for me, I was encountering a bug where the navigation buttons wouldn't do anything until after I'd paused and restarted the Swiper.
To fix, I created my own functions for handling the updates and used those instead.
const MyComponent = () => {
  const sliderRef = useRef(null);

  const handlePrev = useCallback(() => {
    if (!sliderRef.current) return;
    sliderRef.current.swiper.slidePrev();
  }, []);

  const handleNext = useCallback(() => {
    if (!sliderRef.current) return;
    sliderRef.current.swiper.slideNext();
  }, []);

  return (

      <Swiper ref={sliderRef}>
        <SwiperSlide />
        ...slides
        <SwiperSlide />
      </Swiper>

  )
}

Comment: i encountered the same bug as you did at pierrat.dev's solution and this solved my problem. thanks.
Answer: just watch out for a little mistake with onBeforeInit into sample of Amine D.
corrected code:
const MySwiper = () => {
  const navigationPrevRef = React.useRef(null)
  const navigationNextRef = React.useRef(null)
  return (
    <Swiper
      navigation={{
        prevEl: navigationPrevRef.current,
        nextEl: navigationNextRef.current,
      }}
     onBeforeInit={(swiper) => {
          swiper.params.navigation.prevEl = navigationPrevRef.current;
          swiper.params.navigation.nextEl = navigationNextRef.current;
     }}
    >
      <SwiperSlide>slide 1</SwiperSlide>
      <SwiperSlide>slide 2</SwiperSlide>

    </Swiper>
  )
}

Comment: "TS2339: Property 'prevEl' does not exist on type 'boolean | NavigationOptions'.   Property 'prevEl' does not exist on type 'false'."
Comment: To solve @cordial 's TS issue: `import {NavigationOptions} from 'swiper/types/modules/navigation'` and use a cast: `const navigation = swiper.params.navigation as NavigationOptions`
Answer: Important update: Swiper v8.4.4
Most of the answers to this question refer to the API v6, but a later version (which is at the time of writing this answer is v8.4.4) for example doesn't have a swiper.params.navigation.prevEl instead you should access navigation property directly from the swiper instance like so: swiper.navigation.prevEl.
Here's an updated example using React v18 + Swiper v8.4.4 (not recommended)
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper';

import 'swiper/css';

const Carousel = () => {
  const navigationNextRef = useRef(null);
  const navigationPrevRef = useRef(null);

  return (

      <Swiper
        modules={[Navigation]}
        navigation={{
          prevEl: navigationPrevRef.current,
          nextEl: navigationNextRef.current,
        }}
        onBeforeInit={(swiper) => {
          swiper.navigation.nextEl = navigationNextRef.current;
          swiper.navigation.prevEl = navigationPrevRef.current;
        }}
      >
        <SwiperSlide>
          Slide 1
        </SwiperSlide>

        <SwiperSlide>
          Slide 2
        </SwiperSlide>
      </Swiper>

        <button ref={navigationNextRef}>Next</button>
        <button ref={navigationPrevRef}>Prev</button>

  );
};

Reference the swiper and control it from wherever you want!
Even though the example above works, sometimes the references didn't get the right value, so instead of creating two refs for navigation and/or using a setTimeout() to assign the right values, you can reference the swiper itself and control it using slideNext() and slidePrev(), see James Hooper's answer, you can omit the use of useCallback() in the mentioned answer like so:
import { useRef } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation } from 'swiper';

import 'swiper/css';

const Carousel = () => {
  const swiperRef = useRef();

  return (

      <Swiper
        modules={[Navigation]}
        onBeforeInit={(swiper) => {
          swiperRef.current = swiper;
        }}
      >
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
      </Swiper>

        <button onClick={() => swiperRef.current?.slidePrev()}>Prev</button>
        <button onClick={() => swiperRef.current?.slideNext()}>Next</button>

  );
};

Typescript:
Here's the same example above using Typscript:
/* eslint-disable import/no-unresolved */

// The rule above to shut ESLint from complaining
// about unresolved Swiper's CSS imports
// Why? see: https://github.com/import-js/eslint-plugin-import/issues/2266

import { useRef } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Swiper as SwiperType, Navigation } from 'swiper';

import 'swiper/css';

const Carousel = () => {
  const swiperRef = useRef<SwiperType>();

  return (

      <Swiper
        modules={[Navigation]}
        onBeforeInit={(swiper) => {
          swiperRef.current = swiper;
        }}
      >
        <SwiperSlide>Slide 1</SwiperSlide>
        <SwiperSlide>Slide 2</SwiperSlide>
      </Swiper>

        <button onClick={() => swiperRef.current?.slidePrev()}>Prev</button>
        <button onClick={() => swiperRef.current?.slideNext()}>Next</button>

  );
};

Comment: @YassineSedrani good job. Works like a charm!
Comment: Thank you for this. I was wondering if there is a way to get the swiper instance at the root component like this. In the docs I can only find the `useSwiper()` so far.
Comment: @Guinevere You can create the ref in the root component and pass it down, or alternatively you can use `Forwarding Refs`.
https://reactjs.org/docs/forwarding-refs.html
Answer: I think I fixed the issue, I also faced the same problem, but finally, let's start
 1. import SwiperCore, { Navigation} from 'swiper'
 2. SwiperCore.use([Navigation])
 3. i will use your exmaple:

    const MySwiper = () => {
      const navigationPrevRef = React.useRef(null)
      const navigationNextRef = React.useRef(null)
      return (
        <Swiper
          navigation={{
            prevEl: navigationPrevRef.current,
            nextEl: navigationNextRef.current,
          }}
         onBeforeInit={{
              swiper.params.navigation.prevEl = navigationPrevRef.current;
              swiper.params.navigation.nextEl = navigationNextRef.current;
         }}
        >
          <SwiperSlide>slide 1</SwiperSlide>
          <SwiperSlide>slide 2</SwiperSlide>

        </Swiper>
      )
    }

that's it, so if you check Swiper duc there is a page only for API, where you can find a section talking about events that swiper provide, anyway i hope this was helpful
Comment: The question is  asking about both pagination &  navigation!
Comment: thanks for the ```onBeforeInit``` , helped me because swiper was showing prev and next slide buttons but click action was not working
Answer: Passing refs directly is apparently not possible in Swiper v6.2.0.
I created a Github issue as well for anyone ending up here where the library author answered.
https://github.com/nolimits4web/swiper/issues/3855
Answer: As per the previous answers, the following one is the complete code. That may help you to implement as you want.
import React from "react";
import SwiperCore, { Navigation } from 'swiper';
import { Swiper, SwiperSlide } from "swiper/react";

SwiperCore.use([Navigation]);

const MySwiper = () => {
      const navigationPrevRef = React.useRef(null)
      const navigationNextRef = React.useRef(null)
      return (
        <Swiper
          navigation={{
            prevEl: navigationPrevRef.current,
            nextEl: navigationNextRef.current,
          }}
         setTimeout(() => {
          // Override prevEl & nextEl now that refs are defined
          swiper.params.navigation.prevEl = navigationPrevRef.current
          swiper.params.navigation.nextEl = navigationNextRef.current

          // Re-init navigation
          swiper.navigation.destroy()
          swiper.navigation.init()
          swiper.navigation.update()
        })
        >
          <SwiperSlide>slide 1</SwiperSlide>
          <SwiperSlide>slide 2</SwiperSlide>

        </Swiper>
      )
    }

const App = () => (

    <MySwiper className="mySwiper1" />
    <MySwiper className="mySwiper2" />

)

ReactDOM.render(<App/>, document.getElementById('root'));

Answer: 2022 Solution source
Here is latest version solution for adding custom pagination or navigation
import { Swiper, SwiperSlide } from 'swiper/react';
import { Pagination } from 'swiper';
import 'swiper/css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';

And:
<Swiper
    modules={[Pagination]}
    pagination={{
        el: '.custom-pagination',
        clickable: true
    }}
    navigation={{
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    }}
>

And you can put your element anywhere you want with any styles!

Comment: maybe you want to add ```
``` elements to your answer. Thanks.
Answer: This code is from an answer from the creator of the library and it's what has worked for me.
  const prevRef = useRef(null);
  const nextRef = useRef(null);

  return (
    <Swiper
      onInit={(swiper) => {
        swiper.params.navigation.prevEl = prevRef.current;
        swiper.params.navigation.nextEl = nextRef.current;
        swiper.navigation.init();
        swiper.navigation.update();
      }}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>

Prev

Next

    </Swiper>
  );

Answer: Here is the best solution
 import React, { useRef } from "react";
 // For Typescript
 // import SwiperCore from "swiper";
 import { Swiper, SwiperSlide } from "swiper/react";
 import "swiper/css";

 const SliderComponent = () => {
 const swiperRef = useRef();

// For Typescript!
// const swiperRef = useRef<SwiperCore>();

const sliderSettings = {
  440: {
    slidesPerView: 1,
    spaceBetween: 30,
  },
  680: {
    slidesPerView: 2,
    spaceBetween: 30,
  },
  1024: {
    slidesPerView: 3,
    spaceBetween: 30,
  },
};

return (

      <button onClick={() => swiperRef.current?.slidePrev()}>Prev</button>

      <Swiper
        slidesPerView={3}
        breakpoints={sliderSettings}
        onBeforeInit={(swiper) => {
          swiperRef.current = swiper;
        }}
      >
        <SwiperSlide>
          Slide 1
        </SwiperSlide>
        <SwiperSlide>
          Slide 2
        </SwiperSlide>
        <SwiperSlide>
          Slide 3
        </SwiperSlide>
        <SwiperSlide>
          Slide 4
        </SwiperSlide>
        <SwiperSlide>
          Slide 5
        </SwiperSlide>
      </Swiper>

      <button onClick={() => swiperRef.current?.slideNext()}>Next</button>

  );
};

export default SliderComponent;

Answer: For those who none of these solutions worked for your case (like me):
Just use React Refs, but keep in mind that React refs are null on the first render.
So you need to trigger a re-render during the swiper initialization, and all will work as expected:
 //Add a state that will trigger a re-render later
 const [_, setInit] = useState(false)

 const prevRef = useRef(null);
  const nextRef = useRef(null);
  return (
    <Swiper
       //assign the refs to the swiper navigation buttons
        navigation={{
          prevEl: prevRef.current,
          nextEl: nextRef.current,
        }}
        //trigger a re-render by updating the state on swiper initialization
        onInit={() => setInit(true)}    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>

Prev

Next

    </Swiper>
  );

Answer: Works in this way:
  const prevRef = useRef(null);
  const nextRef = useRef(null);
  return (
    <Swiper
      onInit={(swiper) => {
        swiper.params.navigation.prevEl = prevRef.current;
        swiper.params.navigation.nextEl = nextRef.current;
        swiper.navigation.init();
        swiper.navigation.update();
      }}
    >
      <SwiperSlide>Slide 1</SwiperSlide>
      <SwiperSlide>Slide 2</SwiperSlide>

Prev

Next

    </Swiper>
  );

Answer: Just simple and clear way
//import { Swiper, SwiperSlide, useSwiper } from 'swiper/react';

 <Swiper className="mySwiper2">
    <SwiperSlide>...</SwiperSlide>
    ...slides

    <SwiperNavigations />
 </Swiper>

.....

const SwiperNavigations = () => {
  const swiper = useSwiper();

  return (

      <button onClick={() => swiper.slidePrev()} >PREV</button>
      <button onClick={() => swiper.slideNext()} >NEXT</button>

  );
};

Answer: Use id instead of class
 `navigation={{
     prevEl: "#prev_slide",
     nextEl: "#next_slide",
  }}`

Answer: For react / ts

navigation={true}
onNavigationNext={(swiper: any) => (navEvent(swiper, "N"))}
onNavigationPrev={(swiper: any) => (navEvent(swiper, "P"))}
Answer: We had a similar issue in Vue where this code wasn't working:
<swiper-container
  navigation-prev-el=".button-prev"
  navigation-next-el=".button-next"
>

</swiper-container>

<button class="button-prev" />
<button class="button-next" />

It wasn't working because when the <swiper-container> is rendered, the buttons still haven't been rendered, because they're later in the DOM.
The solution was simple: move the buttons higher up the DOM so they exist by the time the <swiper-container> is rendered:
<button class="button-prev" />
<button class="button-next" />

<swiper-container
  navigation-prev-el=".button-prev"
  navigation-next-el=".button-next"
>

</swiper-container>

Answer: Here is an example of a Swiper slider with external Prev and Next buttons, using React and Swiper Element instead of Swiper React components (as recommended in the docs):
import React, { useRef, useCallback } from "react";
import { register } from "swiper/element/bundle";

register();

function Slider() {
  const swiperRef = useRef(null);

  const handlePrev = useCallback(() => {
    swiperRef.current.swiper.slidePrev();
  }, [swiperRef]);

  const handleNext = useCallback(() => {
    swiperRef.current.swiper.slideNext();
  }, [swiperRef]);

  return (

        <button onClick={handlePrev}>Previous</button>

      <swiper-container ref={swiperRef}>
        <swiper-slide>Slide 1</swiper-slide>
        <swiper-slide>Slide 2</swiper-slide>
      </swiper-container>

        <button onClick={handleNext}>Next</button>

  );
}

export default Slider;


Controlling for number of days when calculating medication adherence

Question: I am trying to evaluate the success of a medication adherence intervention. I am trying to assess the success of the program before and after the intervention in terms of number of days a patient took the medication relative to how long they were observed (i.e. # of days medication was taken / # of days observed). The challenge I have is that periods of observations (before and after the program)is different for every patient in the data set.
I would like to control for the number of days to make the assessment to see the actual impact.
One way I thought of doing this is to normalize the data (using min/max) for each patient before and after the program. For instance for the observations before the intervention, I would take the max and min number of days observed before intervention among all the patients and normalize the days medication taken and days observed for each patient (to get it between 1 and 0). Similarly I would do the same for post intervention observations (with min/max of days observed of post intervention).
I am wondering if this is logically correct? One reason I could be wrong is that I am taking the range of "days observed" and using that to normalize "days medication taken". Any suggestions or thoughts?
Answer: This should be treated as a longitudinal binary Y problem with a flexible nonlinear time trend.  It can be misleading to just summarize with a ratio because adherence tends to be higher early and lower late.  The time trend can be e.g. a regression spline, and Y=0,1 can be assessed daily or weekly.  Then use a Markov model or a random effects model.  See here for more.  Such a model will allow you to estimate the probability of adherence as a function of time and patient baseline characteristics.  This provides much more information than a univariate ignore-time-trends analysis.
Comment: Thanks for help!
Answer: Why not just a linear regression of y on x, where:
y: measure of medication success (e.g. % improvement).
x: # of days medication was taken / # of days observed
Maybe if (# days observed) < (some threshold), discard those observations, e.g. if you observed them for 1 day and they took the medication for 1 day, probably won't do much, so maybe establish some lower bound.
Comment: Thank you, agree with discarding values below a certain threshold..
Comment: thank you, agree with discarding values below a certain threshold..will think about the linear regression approach..my initial thoughts are that since medication success in this case is also defined as the difference of (# of days med taken/# days of observed) before and after the intervention, this might not help normalize it for different time periods
Comment: Respecting the longitudinal nature of the data will make interpretation clear, do away with the need to ignore patients with short follow-up, and make the assumptions clear (e.g., missingness at random).


Why was the marathon World Record not 2:03:02 in 2011?

Question: Why exactly was Geoffrey Mutai's 2:03:02 in Boston (2011) not deemed the marathon World Record at the time?
Comment: Just waiting for someone to run faster so the real answer can become, "Because so-and-so ran 2:03:01 in Berlin on $DATE."
Comment: :) and there it is.
Answer: The course for the Boston Marathon does not meet two of the criteria necessary for ratification of world or American records:

"The start and finish points of a course, measured along a theoretical straight line between them, shall not be further apart than 50% of the race distance." [i.e., 13.1 miles (21.1 km) for the ~26.2 mile (~42.2 km) marathon distance]
"The decrease in elevation between the start and finish shall not exceed an average of one in a thousand, i.e. 1m per km." [i.e., 42.2 m for the ~42.2 km marathon distance]

The Boston course has an endpoint about 24.3 miles (39 km) from the start point, and the endpoint is also 459 feet (139 m) lower than the start point.
source: wikipedia
Comment: [IAAF COMPETITION RULES 2012-2013](http://www.iaaf.org/mm/Document/06/28/89/62889_PDF_English.pdf): rule 260.28 (approximate page 244).
Comment: The second point makes sense, but what is the reason for the first point?
Answer: Due to the fact that the Boston course is a net downhill in excess of the limit allowed by the world record setting body.
His time is recognized as the fastest marathon ever...but not the world record.
Comment: The [IAAF Site](http://www.iaaf.org/LRR11/news/newsid=59806.html) has more details.
Answer: Because Dennis Kimetto ran 2:02:57 in Berlin on September 28, 2014.
Comment: Just in case nobody gets the joke: the answer selected as accepted was correct at the time of asking. For 3+ years, Mutai's time was the fastest ever, but not the WR; now Kimetto's mark from Berlin is both (pending ratification).
Comment: ...and now that Eliud Kipchoge has run sub-2:02, even this answer is wrong. :)


Tabs for Media:youtube multiple videos of single node

Question: I am using Media:youtube in a content type and the field in which I embed youtube videos might have multiple values.
I am trying to put those multiple youtube videos belonging to a node in tabs dynamically.
Eg: I have a node created with title: example of tabs
underneath that I have embedded two youtube videos in the node
output should be in tabs with part1 as first horizontal tab and part-2 as second horizontal tab.
Part1|part2
with part1 loaded first and i should click part2 for second video
When there are 3 videos loaded in a node, then I should have like part1|part2|part3
I think using Display Suite with a add code field which i think should have a forloop with delta values of video will solve the purpose.I have no php coding knowledge
Can someone please help me to achieve this.
Answer: Maybe you use could use the Field Collection Tab formatter module with Field collection?
Here are some more details about these modules (quotes included are from their project pages):

Field Collection Tab formatter:

... provides a field formatter that allows you to output a multi value field collection field as a tabset, with one tab per field collection item.

Field collection:

... Provides a field-collection field, to which any number of fields can be attached. A field collection is internally represented as an entity, which is embedded in the host entity. Thus, if desired field collections may be viewed and edited separately too.