Prove $\forall X [X \subseteq A \land y \in A] \rightarrow \exists X[X \subseteq A \land y \in X]$

Question: Prove: $\forall X [X \subseteq A \land y \in A] \rightarrow \exists X[X \subseteq A \land y \in X]$
proof: Proving by contradiction, suppose
$$\forall X [X \subseteq A \land y \in A] \text{ and } \forall X [ \exists z [z \in X \land z \notin A] \lor y\notin X ]$$
Then because $\forall X [ \exists z [z \in X \land z \notin A] \lor y\notin X ]$, it follows that for ever set $X$, there exists an element say $z$ such that $z \in X$ and $z \notin A$. But this contradicts $\forall X [X \subseteq A \land y \in A]$.
Comment: @user 1 I replaced Z with A.
Answer: Your answer is true. Other answers:
answer 1.
Your assumption is: $\forall X [X \subseteq A \land y \in A]$ and you want to find an $X$ such that $X \subseteq A \land y \in X$.
By assumption $(A\subseteq A) \land (y \in A)$ (choosing $A$ as one of the every $X$ s in assumption). So the $X$ you look after, can be $A.$

answer 2. Take the $X$ you look after as $\{y\}$
Answer: The premisse is not true: there is no set $A$ that contains every set $X$ as a subset.
So the statement is true.
If $p$ is not true then statement: $$p\implies q$$ or equivalently: $$\neg p\vee q$$ is true.


Como trabalhar com Enums do tipo CHAR, utilizando C# e Entity Framework

Question: Gostaria de saber como mapear minha entidade que utiliza um Enum do tipo char pelo Entity Framework, utilizando FluentApi.
Tenho o seguinte Enum:
public enum Zona
{
    Norte = 'N',
    Sul = 'S'
}

E a minha Entidade:
public class Local
{
    public Guid RioId { get; set; }
    public string Nome { get; set; }
    public Zona Zona { get; set; }
}

Configuro da seguinte maneira a entidade:
public class LocalMapping : EntityTypeConfiguration<Local>
{
    public LocalMapping()
    {
        ToTable("Local");

        HasKey(r => r.LocalId);

        Property(r => r.Nome).IsRequired();

        Property(r => r.Zona).IsRequired();
    }
}

Como faço para cadastrar meu Enum Zona como varchar(1) no banco de dados, de forma que quando salve um Local com Zona Norte, fique salvo no Banco o caractere N
Comment: C# ñ tem `enum char`. É melhor usar um código.
Comment: Segue o link da solução [Entity Framework Enum Support - Code First ](https://msdn.microsoft.com/en-us/library/hh859576(v=vs.113).aspx)
Answer: Você poderia utilizar de um enum próprio:
public class EnumBase
{
    public EnumBase()
    {
        Locals = new HashSet<Local>();
    }

    public int EnumBaseId { get; set; }
    public string Nome { get; set; }
    public string Codigo { get; set; }
    public int? ValorEnum { get; set; }

    public ICollection<Local> Locals { get; set; }
}

public class Local
{
    public Guid RioId { get; set; }
    public EnumBase Zona { get; set; }
    public int? ZonaId { get; set; }
    public Zona Zona { get; set; }
}

Então você Mapeia no EnumBase:
HasMany(c => c.Locals)
                  .WithOptional(x => x.Zona)
                  .HasForeignKey(c => c.ZonaId);


Java changing image to String with limited characters

Question: Currently, I am trying to work on an automated chat handler for Minecraft, where I can take certain strings / words, and see how close they identify with a set of blacklisted words. Currently, I found the code to turn a string to an image, Convert text content to Image, however, I need to find out how to create a learning mechanism to identify words. So if the word "tèst" is typed, the program will recognize è as the character e, and substitute that letter in to form test, which will cancel the message. Currently, my code based on the previous provided link is as follows:
<code>import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Scan {

    public Scan () {}

    public void scan (String text) {

        BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        Font font = new Font("Arial", Font.PLAIN, 48);
        g2d.setFont(font);
        FontMetrics fm = g2d.getFontMetrics();
        int width = fm.stringWidth(text);
        int height = fm.getHeight();
        g2d.dispose();

        img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        g2d = img.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
        g2d.setFont(font);
        fm = g2d.getFontMetrics();
        g2d.setColor(Color.BLACK);
        g2d.drawString(text, 0, fm.getAscent());
        g2d.dispose();
        try {
            ImageIO.write(img, "png", new File("TEMP_TEXT.png"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
</code>
Ideally, I would hope for something relatively quick, but even if its slow, it'd be nice to learn how to.
Comment: Why do you actually need this, and why are you doing it from images? for instance, I believe you can convert `è` to `e` without doing it as an image
Comment: @Kerooker it was mostly in case users use a character that does not exist in the data, or is custom.
Comment: It's an interesting approach! However, your question is too broad for SO, and it also verges on a request to recommend a library, which is off topic. If you start using something like Tensorflow (their tutorial on recognition of handwritten digits might be relevant to you), and have a specific question about a problem you encounter with it, you could ask here.
Answer: You should implement some Machine Learning to filter that. I recommend this : Google Tensorflow.
While Machine Learning might need steep learning curve, you can follow the tutorial at https://developers.google.com/machine-learning/crash-course/.


Why is the bVII chord said to be borrowed from the parallel minor?

Question: In a chart I am looking at, the bVII chord can come from dorian mode, mixolydian mode and aeolian modes. So why is it said to come from the parallel minor (aeolian mode)?
Let me give an example. In F major, the bVII chord will be Eb which is normally said to come from F minor (F aeolian). But my understanding is that this chord can just as easily come from F dorian, or F mixolydian.
Comment: I think it would help to tell us *where* you heard or read this. The context of the theory is important. If it is music theory based on the common practice period, then your answer is that in the common practice period, the theory is not generally modal, it is focused on major and minor keys. However, if the source were about jazz theory, then we might be a bit more surprised for a bVII chord to be described as borrowed from the parallel minor.
Comment: In the key of F major, the bVII chord is Eb which is said to be borrowed from F minor (IOW: F aeolian). But in modal mixing, the Eb chord can come from F dorian or F mixolydian. So why is the Eb said to be borrowed from Fminor? Clear now?
Comment: Note that in theories of modern music, such as rock or even modern orchestral soundtracks, the theory can be so totally modal that the bVII chord isn't even considered "borrowed" at all, merely from the mode of the piece. For example, the G major chord in "Another Brick In The Wall, Part II" is not considered borrowed, it is merely a chord from D Dorian, in which the song is generally considered to have been written.
Answer: Pretty sure it says it comes from the parallel minor, as relative modes share all chords by definition.
For what is is worth, you could "borrow" any chord from whichever mode it appears in, since you do not have to bring it back :)) - chances are, that one knows aeolian better than mixolydian, that's why.
Comment: sorry, perhaps I wasnt clear, I have amended my question, it should be much clearer now
Comment: Yes, I see now where I was being confusing... I changed the word "relative" to "parallel". you are right and i was meant to say Parallel minor :)
Answer: The borrowed chord comes per definition from the parallel key - if not the melody has modulated. In this case it can be borrowed from any other mode.
https://en.wikipedia.org/wiki/Borrowed_chord
As the name implies, Borrowed Chords are chords borrowed from other modes. These modes can be a music mode or the Parallel mode.
Most of the time, Borrowed Chords come from the parallel mode. For this reason, many authors classify Borrowed Chords as borrowing only from the parallel mode.
https://www.simplifyingtheory.com/borrowed-chords/
Edit:
Before the common practice era there was no way to consider chords as borrowed from other modes. (But we could develop together a theory of borrowed chords from other modes in Renaissance music ;)
Comment: You should probably be more specific. F mixolydian is a parallel mode to F major; we just don't tend to use the term that way.
Comment: Mind that  mode based chord progression were before Bach and the WTC. Only the  system of tonality (all 12 major keys and their minor relatives and parallel keys) allowed to consider e.g. Fm in C major as borrowed  subdominant of the parallel c minor key. It is a question of history of harmony and chord description. Before this era  of common practice chord progressions were used without theory of tonality and borrowing. See e.g. Palestrina's Stabat Mater.
Answer: If the music is in the major/minor system, then the number of modes referenced for various chromatic harmonies is somewhat limited. The phrygian mode can be referenced for things like augmented sixth chord resolutions or Neapolitain chords. Lydian for a raised subdominant. Borrowed chords would generically be referenced from the parallel minor key.
In pop/rock style it's common to refer to the mixolydian mode. bVII in major, in pop/rock style, could be described as "borrowed", or an inflection/coloring, from the mixolydian mode. Blues uses this label too.
Most of these wordings seems to be convention rather than pure logic, except perhaps for phrygian, that is the only tonal mode with a lowered second scale degree (this excludes locrian.) When that alteration is used, you really cannot mistake it for another modal "borrowing."
Answer: Why you would describe the flat 7 chord as borrowed from the parallel Minor instead of one of the modes may have to do with the system being used to describe the harmonic structure.
I've found that there are numerous ways that music theory is described and taught.
In some cases musicians are educated in a Major/Minor only system that doesn't really utilize the modal system, or even excludes it.
For example, Dorian mode music may be described as a form of the relative Melodic Minor and Mixolydian pieces are chord analyzed to the relative Major, calling the Mixolydian One chord the Five of its Major.
In this context, when describing the harmonic structure of a Major key, a borrowed chord is going to be referenced to the available Major or Minor keys only, either the parallel, relative, or a secondary based off of the Dominant.
Answer: There are many different angles from which to explain the bVII chord and how it works. If you're curious, check out my two videos on the so called "backdoor progression" (link below, pardon my German use of "bee" for "flat" :P). One such angle is to explain it as borrowed from the parallel minor:
First, the bVII (Eb in your example) is a dominant seventh chord in most cases. It  is not seldomly preceeded by a iv7 (Bbm7) chord to make it a ii-V progression. In that combination, the modes of F mixolydian and dorian are ruled out. This leaves us with the parallel minor key (i.e. "natural minor" or "aeolian").
The move to bVII is not so much a move to a single chord, but more a temporary shift to the parallel minor key – even if the voicing of your bVII chord does not make that unambiguously clear.
By the way, borrowing chords from the parallel minor key is common for other chords as well (e.g. bIII, bVI or iv).
Comment: Adding the involvement of the iv7 chord really does clarify the mode situation. Very interesting explanation.
Comment: "The move to bVII is not so much a move to a single chord, but more a temporary shift to the parallel minor key"   Only if your system can't tolerate a chromatic chord without re-tonicization.  What do you think of the idea that bVII has acquired 'Honorary Diatonic' status?
Comment: @LaurencePayne it's true and there is always more than one correct explanation  of a phenomenon. Some people will actually feel a new tonic, others will experience a brief chromatic slip. I love the term "honorary diatonic" :D!
Comment: The backdoor cadence is only one use of the bVII chord. You seem to be speaking more about jazz. If you look at many non-jazz songwriters the bVII doesn't have to be a dominant chord at all and I can think of too many examples where the chord is not preceded by the iv7 chord.
Comment: @armani True. The chord does not have to be preceeded by iv (as I also mention in the video). If it is not a dominant chord, it usually has a totally different use and explanation. I sometimes see a major 7th chord used, which still fits with the backdoor explanation. But rock music sometimes uses bIII and bVII which comes directly from the parallel minor and little to do with backdoor.
Comment: @morgler I know that is what they say but I was taught to always look  as close as possible to the home key for the explanation when a chiord is not diatonic. Why look in Fminor when the next door neighbor on the circle of fifths has the chord waiting for us?
Answer: Yes, you could say that ♭VII was 'borrowed' from several other places  as well as the parallel minor.
I wouldn't get too hung up on this 'borrowing' thing.  All it's really saying is 'you have permission to use this non-diatonic chord'.   But you didn't NEED permission!   Really, it's OK not to be diatonic!  It's OK to take a diatonic chord and change one of its notes.  Or two of them.  Or all of them!
Sometimes an 'outside' chord leads us to a new tonal centre.  Sometimes it's just a touch of colour.
Your ♭VII is actually an interesting case.   It's been so common in popular music since around the Beatles era that it's often sensible just to count it as 'honorary diatonic'.  Same way that we don't fuss over the non-diatonic chords in a simple 12-bar Blues.
Comment: "Borrowing" can be a useful notion for explicating the harmonic context or perspective that a musician is thinking about when dealing with notes and chords outside the default scale. It's not _only_ about legitimacy and social acceptance. The OP's problem comes from assuming that one perspective could be a "true" measurable physical fact that exists independently of a subject. And I'd rather have diatonic mean "you don't need to use accidentals to deviate from the default scale".
Answer: There's a tendency in the way music theory is taught - at least at beginner to intermediate level - towards explaining everything in terms of major and minor, rather than talking about the modes. You'll notice, for example, that your typical 'circle of fifths' diagram showing key signatures will tell you that a key sig with one flat can be F major or D minor, but not that it can be 'G dorian', for example.
In general, major and minor have become better-known concepts than the modes through having associated 'keys' as well as just 'scales'. When people talk about borrowing, they may often really be thinking about borrowing from a parallel key, rather than a parallel scale. That's why people would talk about borrowing from minor, rather than  dorian or mixolydian (or even aeolian, for that matter).
Whether or not you find that a helpful way to go about things is up to you! One of the common places you'll find bVII is in a kind of blues-mixolydian-major hybrid tonality commonly found in rock that isn't really major or minor, or any of the modes. In that particular case, I'm not sure that talking about bVII as being 'borrowed' is helpful.
Answer: A common minor is Aeolian - probably more commonly used than Dorian. The Mixolydian mode is major, but would still produce that ♭7 chord. And more people are aware of Aeolian.
Modal mixing is just a way to explain how 'foreign' notes get mixed up. Out of the three, none is any more responsible, but Aeolian wins as the most well-known.
Comment: Yes but... F mixolydian is "closer" to the key of F (one step on the circle of fifths). Why should you go all way to F aeolian (3 steps on the circle of fifths) to theorize about where the non-diatonic chord is coming from?
Comment: Fair comment, but everything doesn't revolve around the circle...
Answer:
In F major, the bVII chord will be Eb which is normally said to come
from F minor (F aeolian). But my understanding is that this chord can
just as easily come from F dorian, or F mixolydian.

It's a matter of perspective. If the person in question looks at the Eb chord as a part of an F minor context with chords like Bbm, Ab, Db, etc. and uses that harmonic palette to draw from - with the intention of quickly returning to the original palette - then that's where it "comes from". And then it is reasonable and logical for the person to say, "I borrowed the Eb chord from the key of F minor".
However, if the person is thinking about, say, F mixolydian, then the right thing is to say "I borrowed the Eb chord from F mixolydian." If you feel like you're moving to the other mode more permanently, then you say you're modulating or changing the mode, not borrowing. Right? You say what you do, if you want others to know what you do if it isn't self evident. If you think you're riding a bike then you say "I'm riding a bike". If you think you borrowed the Eb chord from F minor, then you say "I borrowed the Eb chord from F minor." If you think you borrowed the Eb chord from F mixolydian, then you say "I borrowed the Eb chord from F mixolydian."
An Eb chord alone doesn't make the mode F minor or F mixolydian or anything. But F minor or F mixolydian or F dorian etc. might be on your mind, depending on what other things you do or intend to do.
If your question is, "why do so many people so often think about this one particular mode instead of all these other modes", then maybe it's something cultural. It's a popular thing to do for some reason.


css @media mobile/desktop: ensuring desktop doesn't show mobile css

Question: been making a mobile redesign of a site, simply via CSS.
have the following media queries serving up appropriate css for either desktop or mobile
but, the desktop will still show the mobile css (although it seems only some of the mobile css files) when browser is resized under 855
how do you ensure the desktop never loads the mobile css?
thanks
<link rel="stylesheet" type="text/css" href="css/layout.css" media="Screen and (min-device-width:855px),projection" />
<link rel="stylesheet" type="text/css" href="css/nav.css" media="Screen and (min-device-width:855px),projection" />
<link rel="stylesheet" type="text/css" href="css/type.css" media="Screen and (min-device-width:855px),projection" />

<link href="css/mobile.css" type="text/css" media="handheld, handheld and (max-device-width: 854px), only screen and (max-device-width: 854px), only screen and (max-width:854px)" rel="stylesheet" />
<link href="css/mobile-nav.css" type="text/css" media="handheld, handheld and (max-device-width: 854px), only screen and (max-device-width: 854px), only screen and (max-width:854px)" rel="stylesheet" />
<link href="css/mobile-type.css" type="text/css" media="handheld, handheld and (max-device-width: 854px), only screen and (max-device-width: 854px), only screen and (max-width:854px)" rel="stylesheet" />

kind regards
Answer: You have the following rule at the end of your mobile stylesheet media queries: only screen and (max-width:854px). This applies the stylesheet when a browser is resized under 855px. If you only want the stylesheets to be applied on devices that are 854px or less in width, use the max-device-width property only.
Comment: thank you. had to use max-width in order to get android mobile to work.


Interpreting LRT output

Question: I am comparing the fit of two models:
> lrtest(fullmodel,reducedmodel)
Likelihood ratio test

Model 1: MM ~ x * y + (1 | Replicate)
Model 2: MM ~ x * y
  #Df LogLik Df  Chisq Pr(>Chisq)
1   8 357.35
2   7 368.40 -1 22.095  2.595e-06 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

So from looking at the output the models are significant. How do I tell what model is best - do you use the LogLik value? Do I pick the one with the lowest LogLik value (e.g. in this case Model 2 has the lowest LogLik so that is the best model)?
Answer: The models are not significant. Read There is a significant difference in the two compared models (in log likelihoods). In this particular implementation it appears that you want to maximize the LogLik, so in your case Model 2 (without random effects) is the more parsimonious model.
Comment: I am confused as to how they're aren't different given the P value is less than 0.05? If they aren't different then wouldn't the p value be above 0.05
Comment: @user255144 They are different. My statement was referring to the fact that there is a statistical difference between the models, however this does not guarantee that any of the models is significant on their own. There is a difference.
Comment: @user2974951 deleting my earlier comment, not knowing what "Model B" entails, it could be anything, including a model that is "worse" than null. So I agree that we can't borrow the interpretation of a significant LRT as a global test, in general.

Interpreting LRT output


PhantomJS: require Script and set variables beforehand

Question: I am using PhantomJS for page automation. For my script, I need to load another script which is also used on the actual client-side of my webpage. This script contains some parts where global variables - which are assumed to be set before the script is loaded - are used.
Now my problem is that I can't figure out how to set these variables before I require them within PhantomJS.
This (obviously) didn't do the trick:
variableX = 1024;
var moduleX = require('myScripts.js');

Now what's the proper and intended way ( if there is one) to do this?
Comment: Why do you need to load a script into PhantomJS if it's already used on the client-side?
Comment: I am trying to test my [Bootstrap Tour](http://bootstraptour.com/) tours. For that I need to get the steps - contained in the script - to test it against the client. Maybe it's not clear at the first sight, but it definitely makes sense (at least to me).
Comment: Still not clear. The script you mention - does it have to be run entirely client-side? Is it different from the PhantomJS script?
Comment: The script where my tour is defined, is included within the client-side. Now to test the client-side behavior I am using exactly the same script in PhantomJS, reading an array of so-called 'steps' and iterate over them to test each step. These steps contain `path` properties, which are set using global variables (in the client-side). My goal is to set these variables also within PhantomJS.
Comment: Well, if you prepare you script as a CommonJS module, you *can* require it in Phantomjs. See **Module system** section here: http://phantomjs.org/release-1.7.html
Answer: If you prepare the testing script as a CommonJS module, you can require it and use its methods and variables in PhantomJS.
From the docs: http://phantomjs.org/release-1.7.html

As an example, supposed there is a script universe.js which contains the following code:
exports.answer = 42;
exports.start = function () {
    console.log('Starting the universe....');
}

This module can be used in another script like the following:
var universe = require('./universe');
universe.start();
console.log('The answer is', universe.answer);

And if you want to assign global variables from such a module you can use the global object as in node.js:
exports.start = function () {
    global.success = true;
    console.log('Starting the universe....');
}

Comment: You led me to the solution with this, thank you. Since I wanted to have something like arguments to my export, I replaced the `module.exports` property with a function that takes the global variables as arguments.
Comment: Oh, I think I get it now. You wanted to use `variableX` inside of a module!


remove everything but domain name from url

Question: I am looking if the is an easy way to keep the webpage always with the URL like:
http://example.com

at the time there are request like
http://example.com?target=dirigido
http://example.com/a-quien-va-dirigido/
http://www.example.com/a-quien-va-dirigido/
...

behind.
Anybody could help?
EDIT
The following rule
RewriteRule ^(.*)$ http://example.com/$1 [L,R=permanent]

seems to lose the ?target=dirigido request.
EDIT2
The case is the site is a single-page-application in which I load the needed html file by a a jquery load function. They recently asked me to add a carrousel with a link to the different parts of the site, so I added a request param
?target=<content>

and I load the correspondant content.
I added some rules to make beutify urls
static resources not found when mod_rewrite
But when the user goes to:
http://inside.amimusa.org/el-equipo

firstable it's fine, but since the page it's a single-page application, when he/she navigates throght the menu, he/she is really going to, let's say
http://inside.amimusa.org/programa-integrativo-para-directivos/

but in the address bar it keeps: http://inside.amimusa.org/el-equipo what is awful.
So I was thinking to make all the site works hidden everything under the domain, but the request have still to work.
Comment: No. The URL has to reflect the page that has been loaded. Otherwise how is the web server going to know what to serve? It will just serve the default page every time. I really don't know what you're trying to get at here. There is one way to do this, which would be a single page application all done in javascript, but even they usually use hashed URLs.
Comment: I'll clarify the scenario by editing the question. Thanks
Comment: If your application relies upon the URL or a GET request to function properly, then it can't be made "beautiful". If it relied upon session cookies or a POST request, you could have your way.
Comment: I've changed everything to one request by click. Thanks.
Answer: Assuming Apache:
RewriteEngine On
RewriteRule ^(.*)$ http://example.com [L,R=permanent]

The initial match (^.*$) can be all sorts of things. I chose one that does give you access over the request URI via $1, should it be necessary.
If you simply want to make sure everybody uses the same domain and rewrite all to one, use:
RewriteEngine ON
RewriteCond %{HTTP_HOST}   !=domain.com
RewriteRule ^(.*)$         http://domain.com$1 [L,R=permanent]

Comment: I lose the request, it keeps requesting index.php without the target.
Comment: That's exactly what you asked for. I'l update my answer.


Como passar um array php como paramentro do $.ajax data?

Question: Como passar um array php como paramentro do $.ajax data?
Ex:
<?php $nomes = array('maria','joao','jose'); ?>

  $.ajax({
    url: 'pagina.php',
    dataType: 'json',
    method: 'POST',
    data: {'nomes' : <?php echo json_encode($nomes); ?>},
    sucesss: function(data){
      console.log(data);
           }
     });

E na pagina pegar esse array.
Comment: Eu não acho legal esse negócio de misturar código jquery com php, isso é gambiarra². Transforma o array em json, depois escreve ele dentro de um elemento HTML. capture o valor do elemento via jquery e o esconda. Agora não tenho como formalizar uma resposta, quando eu chegar em casa eu tento postar
Comment: Esse código para mim não faz sentido nenhum. .-.
Comment: Use `$variável = json_decode($_POST['nomes']);`, dessa forma você terá $variável[1], $variável[2], $variável[0].
Comment: A forma como está fazendo está correta...explique melhor sua dúvida
Comment: Bem, pelo o que eu percebi, pelo fato do array em php não conter keys a função json_encode o converte para um array javascript normal. Então no caso talvez minha pergunta deveria ser como converter esse array js para um array php ao pega-lo com $_POST na pagina de destino. Obrigado pelas respostas.
Comment: Vlw pela resposta Adriano, tbm não gosto fazer dessa maneira, por isso postei a pergunta aqui, vou tentar sua dica. Abr.
Answer:

nomes = [];
nomes[0] = 'maria';
nomes[1] = 'joao';
nomes[2] = 'josé';

$.ajax({
   type: "POST",
   data: {nomes :nomes},
   url: "pagina.php",
   success: function(msg){
     console.log(data);
   }
});
Comment: bem vindo ao SOPT, sempre é interessante explicar o que seu código faz, assim melhora o entendimento da solução do problema


Show that $\lim_{x\to 0^+}\int_x^{2x}\frac{\sin t}{t^2}dt=\ln 2.$

Question:
Question: Show that $$\lim_{x\to 0^+}\int_x^{2x}\frac{\sin t}{t^2}dt=\ln 2.$$

Solution: Note that $$\lim_{x\to 0^+}\int_x^{2x}\frac{\sin t}{t^2}dt=\ln 2=\lim_{x\to 0^+}\int_x^{2x}\frac{dt}{t}\\\iff\lim_{x\to 0^+}\int_x^{2x}\frac{\sin t-t}{t^2}dt=0.$$
Thus it is sufficient to prove that $$\lim_{x\to 0^+}\int_x^{2x}\frac{\sin t-t}{t^2}dt=0.$$
Now, expanding $\sin t$ using Maclaurin's formula having remainder in Lagrange's form, we have $$\sin t=t-\frac{\cos\xi}{3!}t^3, \text{ where } \xi=\theta t\text{ and } 0<\theta<1.$$
Now $$\cos \xi\le 1\implies \frac{\cos \xi}{3!}t^3\le \frac{t^3}{3!}(\because t>0)\\\implies t-\frac{\cos \xi}{3!}t^3\ge t-\frac{t^3}{3!}\\\implies \sin t\ge t-\frac{t^3}{3!}.$$
Again since $t>0$, we have $\sin t<t$.
Thus $\forall t\in[x,2x]$ and $\forall x>0,$ we have $$t-\frac{t^3}{3!}\le \sin t\le t\\\implies -\frac{t}{3!}\le \frac{\sin t-t}{t^2}\le 0\\\implies \int_x^{2x} -\frac{t}{3!}dt\le \int_x^{2x}\frac{\sin t-t}{t^2}dt\le 0\\\implies -\frac{x^2}{4}\le \int_x^{2x}\frac{\sin t-t}{t^2}dt\le 0.$$
Now since $\lim_{x\to 0^+} -\frac{x^2}{4}=0$ and $\lim_{x\to 0^+} 0=0$, thus by Sandwich Theorem we can conclude that $$\lim_{x\to 0^+} \int_x^{2x}\frac{\sin t-t}{t^2}dt=0.$$ Hence, we are done.
Is this solution correct and rigorous enough? Are there any alternative solutions?
Comment: Yes, this solution is correct and in fact it's the natural solution in a sense - the idea of why this happens is because to second order near $ 0 $, $ \sin(t) $ is indistinguishable from $ t $, and this is a good way to make that intuition precise.
Comment: For $x \rightarrow 0^{+}$ and $x≤t≤2x$, $\frac{\text{sin(t)}}{t}=1$. So, the integral transforms to $\int_{x}^{2x} \frac{\text{d}t}{t} =\text{ln}2$.
Comment: Another way is to integrate $$\frac{{\sin t}}{{t^2 }} = \frac{1}{t} + \sum\limits_{k = 1}^\infty  {( - 1)^k \frac{{t^{2k - 1} }}{{(2k + 1)!}}}
$$ between $x>0$ and $2x$ and let $x$ approach zero.
Answer: MVT for Integrals:
$\displaystyle{\int_{x}^{2x}}\dfrac{\sin t}{t}\frac{1}{t}dt =\dfrac{\sin s}{s}\int_{x}^{2x}\frac{1}{t}dt=$
$\dfrac{\sin s}{s}\left (\log 2x-\log x \right)$, where $s \in [x,2x]$.
Take the limit $x \rightarrow 0^+$.
Note: $\lim_{x \rightarrow 0^+} s=0,$ and
$\lim_{x \rightarrow 0^+}\dfrac{\sin s}{s}=1$.
Answer: There is an alternative solution.  Integrating by parts with $u=\sin(t)$ and $v=-\frac1t$ we find that
$$\begin{align}\lim_{x\to 0^+}\int_x^{2x}\frac{\sin(t)}{t^2}\,dt&=\lim_{x\to 0^+}\left.\left(-\frac{\sin(t)}{t}\right)\right|_x^{2x}+\lim_{x\to 0^+}\int_x^{2x}\frac{\cos(t)}{t}\,dt\\\\
&=\lim_{x\to 0^+}\int_x^{2x}\frac{\cos(t)}{t}\,dt=\log(2)+\int_x^{2x}\frac{\cos(t)-1}{t}\,dt
\end{align}$$
Then, note that for $t\in [x,2x]$, $|1-\cos(t)|=2\sin^2(t/2)\le t^2/2$.  Therefore, $\lim_{x\to 0^+}\int_x^{2x}\frac{\cos(t)-1}{t}\,dt=0$ and we conclude
$$\lim_{x\to 0^+}\int_x^{2x}\frac{\sin(t)}{t^2}\,dt=\log(2)$$
as expected!
Comment: @sanketbiswas Please let me know how I can improve my answer.  I really want to give you the best answer I can.
Answer: You can use the fact that $y = \dfrac{\sin x}{x}$ is positive and decreasing on $(0,\pi)$ so that if $0 < x < \pi/2$ you have
$$ \frac{\sin 2x}{2x} \ln 2 = \frac{\sin 2x}{2x} \int_x^{2x} \frac 1t \, dt \le \int_x^{2x} \frac{\sin t}{t^2} \, dt \le \frac{\sin x}{x} \int_x^{2x} \frac 1t \, dt = \frac{\sin x}{x} \ln 2.$$ Now apply the squeeze theorem.
Answer: I find it is easier to prove a generalization. Claim: Suppose $f$ is continuous on some $(0,a)$ and $\lim_{x\to 0^+} f(x) =1.$ Then
$$\lim_{x\to 0^+} \int_x^{2x} \frac{f(t)}{t}\, dt = \ln 2.$$
In our specific problem we have $f(t)= \dfrac{\sin t}{t}.$
Proof of claim:
$$\left | \int_x^{2x} \frac{f(t)}{t}\, dt - \ln 2\right | = \left |\int_x^{2x}\left (f(t)-1\right)\frac{dt}{t}\right |$$ $$\le \int_x^{2x}|f(t)-1|\frac{dt}{t}  \le \max_{[x,2x]}|f-1|\cdot \int_x^{2x} \frac{dt}{t}$$ $$ = \max_{[x,2x]}|f-1| \cdot \ln 2.$$
Because $\lim_{x\to 0^+} f(x) =1,$ that maximum $\to 0$ as $x\to 0^+,$ and the claim is proved.
Answer: Let $ x\in\left(0,1\right] : $
\begin{aligned}\int_{x}^{2x}{\frac{\sin{t}}{t^{2}}\,\mathrm{d}t}&=\ln{2}+\int_{x}^{2x}{\frac{t-\sin{t}}{t^{2}}\,\mathrm{d}t}\\ &=\ln{2}+\int_{0}^{2x}{\frac{t-\sin{t}}{t^{2}}\,\mathrm{d}t}-\int_{0}^{x}{\frac{t-\sin{t}}{t^{2}}\,\mathrm{d}t}\\ &=\ln{2}+\frac{1}{2}\int_{0}^{x}{\frac{2u-\sin{\left(2u\right)}}{u^{2}}\,\mathrm{d}u}-\int_{0}^{x}{\frac{t-\sin{t}}{t^{2}}\,\mathrm{d}t}\\ \int_{x}^{2x}{\frac{\sin{t}}{t^{2}}\,\mathrm{d}t}&=\ln{2}+\int_{0}^{x}{\frac{\sin{t}\left(1-\cos{t}\right)}{t^{2}}\,\mathrm{d}t}\end{aligned}
Since $ x\mapsto\frac{x\left(1-\cos{x}\right)}{x^{2}} $ is continuous on $ \left(0,1\right] $, and can be extended to a continuous function $ \left[0,1\right] $, it can be upper-bounded on $ \left(0,1\right] $ by some constant $ M>0 :$ $$ \left(\exists M>0\right)\left(\forall x\in\left(0,1\right]\right),\ \frac{\sin{x}\left(1-\cos{x}\right)}{x^{2}}\leq M $$
Thus $ \int_{0}^{x}{\frac{\sin{t}\left(1-\cos{t}\right)}{t^{2}}\,\mathrm{d}t}\leq Mx\underset{x\to 0}{\longrightarrow}0 $, and hence : $$ \lim_{x\to 0}{\int_{x}^{2x}{\frac{\sin{t}}{t^{2}}\,\mathrm{d}t}}=\ln{2} $$
Answer: Put $t=ux$ to reduce the expression under limit to $$\int_{1}^{2}\frac{\sin ux} {u^2x}\,du$$ The integrand $$f(x, u) =\frac{\sin (ux)} {u^2x},f(0,u)=\frac{1}{u}$$ is continuous in $[0,h]\times[1,2]$ and hence we can switch limit with integral to get the desired limit as $$\int_{1}^{2}\frac{du}{u}=\log 2$$


Imprimindo Porcentagem

Question: Tentei fazer um algoritmo pra imprimir a porcentagem de cada tipo de voto, mas meu codigo dá erro por alguma razao, alguem consegue me explicar o porque?
Segue abaixo:
/*Escreva um algoritmo para ler o número total de eleitores de
um município, o número de votos brancos, nulos e válidos. Calcular e escrever
o percentual que cada um representa em relação ao total de eleitores.*/

var eleitores = 34
var vbrancos = 16
var vnulos = 8
var vvalidos = 10

vbpercentual = (100 * vbrancos) / eleitores
vnpercentual = (100 * vnulos) / eleitores
vvpercentual = (100 * vvalidos) / eleitores

console.log('Votos em Branco: ' vbpercentual)
console.log('Votos Nulos: ' vnpercentual)
console.log('Votos Válidos: ' vvpercentual)

Comment: Você não criou as variáveis `vbpercentual`, `vnpercentual` e `vvpercentual`. Precisa iniciar com a tag `var` se for criar uma variável nova. Fazer desse jeito funciona, mas cria globais implícitas, o que é ruim para seu código e se estiver rodando num validador automático de um site, pode causar erro.
Além disso, para passar mais de um argumento no `console.log()` deve concatenar com `+` ou virgula.
Answer: Segundo podemos observar a documentação do JavaScript para a funcionalidade console, podemos passar vários argumentos pelo console.log(), desde que estejam separados por vírgula.

var eleitores = 34;
var vbrancos = 16;

vbpercentual = (100 * vbrancos) / eleitores;
console.log('Votos em Branco: ', vbpercentual);

Imprimindo Porcentagem


End Zopim chat on inactivity

Question: I would like to end a chat if the user has been inactive for x seconds/minutes in order to free up our agents from having to wait for the chat to close on its own. I would also like to attach a tag to the chat before ending it so I can see that it was due to inactivity.
Answer: Credits to johnnyRose for this one, which you can find here https://stackoverflow.com/a/34516735/11499604 and to vijay for inspiring him!
The majority of this is his code with the zopim javascript inserted. This was the only code that I was able to get to play nice with zopim's javascript API. I saw a lot of people looking for triggers to end chat so I hope this helps others.
The trigger for this code is a user's inactivity. After 10 seconds of being idle on the page, it adds a tag to the user and ends the chat.
You can use this Zopim Javascript page for reference on other things you can do.
https://api.zopim.com/files/meshim/widget/controllers/LiveChatAPI-js.html
<code>    <script>
(function () {
    var minutes = false; // true = minutes; false = seconds
    var interval = minutes ? 60000 : 1000;
    var IDLE_TIMEOUT = 10; // 10 seconds in this example
    var idleCounter = 0;

    window.onmousemove = window.onkeypress = function () {
        idleCounter = 0;
    };

    window.setInterval(function () {
        if (++idleCounter >= IDLE_TIMEOUT) {
              $zopim(function() {
    $zopim.livechat.addTags('timeOut');
    $zopim.livechat.endChat();
  }); // or whatever you want to do
        }
    }, interval);
}());
</script>
</code>

End Zopim chat on inactivity


Does Part of Line Cut Through Square

Question: I am working on a 2D game that involves square creatures and projectiles.
Each projectile moves several creature-lengths per game tick, so I can't just check for any creatures at the projectile's location every tick- this skips any creatures in-between the projectile's starting and ending positions.
Each tick, I have the location projectile_x and projectile_y, delta_time and speed of the projectile, which result in the distance_moved. I also have the direction of the projectile in radians. This allows me to get the trajectory lines starting and ending coordinates, (projectile_start_x,projectile_start_y) and (projectile_end_x,projectile_end_y).
For each creature with center (creature_x,creature_y) and square width creature_size. How can I find out whether a projectile's trajectory has intersected a creature?
Edit: I don't mind approximating to assume that creatures are in fact circles.
Edit Edit: Actually, squares seem simpler from these answers.
Comment: That is to say, they don't move while you're checking for collision
Comment: so your creatures are not moving?
Comment: @SebastianSchulz they do but only every game tick- the variables that I listed are for any set tick, during which an entity moves so little that this is negligible.
Answer: There's a hit if the segment on the line $L$ traversed by the projectile meets an edge of the square.
Find  the equation of $L$ in parametric form: $tV + (1-t)W$, where $V$ and $W$ are the starting and ending positions of the projectile.
The equation for each edge  of the square looks like $sA + (1-s)B$, where $A$ and $B$ are adjacent corners.  Find out where that line meets $L$ (it will unless $L$ is horizontal). If for any edge both $s$ and  $t$ are between $0$ and $1$  then it's a hit.
This is tedious analytic geometry but not hard to program.
Answer: Here's the fastest way that I can come up with from the top of my head:
Write direction vector of the projectile as $(d_x, d_y)$, then you'll get an orthogonal vector via $v := (-d_y, d_x)$. Now, all the points $P$ on the trajectory of your projectile have one thing in common, namely that their inner product with v is $(v,P) = (v,A) = (v,B)$ where $A,B$ are the starting and ending point of the projectile (just trying to abbreviate notation here)
This trajectory divides the plane into two half-planes, and the projectile does NOT hit the creature if the square lies entirely in one of those two half-planes. In that case, all points $p$ of the square would have to satisfy either $(v,p) < (v,A)$ or $(v,p) > (v,A)$ (depending on which half-plane they are in). Note that it is sufficient to check this condition on the four corners of your square!
So what you'd have to do is the following:
1) Compute the direction vector of the projectile
2) Determine an orthogonal vector
3) Compute the inner product with either $A$ or $B$
4) Compute the inner products with the four corners of your square
5) Order those 5 numbers and see whether the number you obtained in 3) is either the largest or the smallest among them: In that case the projectile does NOT hit the creature. In case it is neither the largest nor the smallest, you're one creature down.
Comment: This determines whether the line containing the projectile's path hits the creature, but is there an easy way to leverage this to determine whether the projectile's path, which is a line segment, hits the creature?
Answer: Basically, each frame, we have a line segment from $(p_x,p_y)$ (where those denote projectile_x and projectile_y) in direction $(\cos(\theta),\sin(\theta))$ (where $\theta$ is short for direction. $\theta=0$ refers to the right, horizontally) with length $d$ (which is, you guessed it, distance_moved).
If we are to make this a line opposed to only a line segment, then the following equality would describe its path:
$$(y-p_y)\cos(\theta)=(x-p_x)\sin(\theta)\tag{$*$}$$
We can view creatures as circles instead of squares if we know the direction of the line; a line with direction $\theta$ intersects the circle with center $(c_x,c_y)$ and radius
$$r=\frac s2\cdot ((\sqrt2-1)|\sin(2\theta)|+1)$$
if and only if it intersects a square with side lengths $s$ and center $(c_x,c_y)$.
So first, we find the candidates. What circles intersect the line described at $(*)$? Well, it only intersects a circle if the distance from the line to the center of the circle is less than or equal to the radius. The distance from $(c_x,c_y)$ to $(y-p_y)\cos(\theta)=(x-p_x)\sin(\theta)$ is exactly
$$\left|(c_x-p_x)\sin(\theta)-(c_y-p_y)\cos(\theta)\right|$$
So if this is less than or equal to $\frac{s}{\cos(\theta)}$ (where $s$ is creature_size), then the creature is on the line describing the projectile, but not necessarily on the line segment.
This is the next step. Checking whether or not it reaches the square representing the creature is luckily not very hard. First, note that the end points of the segment are at $(p_x,p_y)$ and $(p_x+d\cos(\theta),p_y+d\sin(\theta))$. Now we need to check:
\begin{align}
\min(p_x,p_x+d\cos(\theta))&<c_x+\tfrac s2\\
\max(p_x,p_x+d\cos(\theta))&>c_x-\tfrac s2
\end{align}
and
\begin{align}
\min(p_y,p_y+d\sin(\theta))&<c_y+\tfrac s2\\
\max(p_y,p_y+d\sin(\theta))&>c_y-\tfrac s2
\end{align}
If those are all true, then the square overlaps the line segment at some point.

To summarize, first check
  $$\left|(c_x-p_x)\sin(\theta)-(c_y-p_y)\cos(\theta)\right|\leq\frac s2\cdot ((\sqrt2-1)|\sin(2\theta)|+1)\tag{1}$$
  and then check, if the previous expression was true,
  \begin{align}
\min(p_x,p_x+d\cos(\theta))&<c_x+\tfrac s2\\
\max(p_x,p_x+d\cos(\theta))&>c_x-\tfrac s2\tag{2.1}
\end{align}
  and if those are true,
  \begin{align}
\min(p_y,p_y+d\sin(\theta))&<c_y+\tfrac s2\\
\max(p_y,p_y+d\sin(\theta))&>c_y-\tfrac s2\tag{2.2}
\end{align}
  and if those last ones are true too, then your box collides with the line.

You could do these three checks in any order you like, however, since the first seems less computationally heavy, I'd go with my suggested order. A different order would be more efficient if you expect many of the creatures to be in the line the projectile is moving but not necessarily in range of the projectile.
Answer: Here's another approach.
First note that the intervals $[m,M]$ and $[n,N]$ overlap if and only if $m\le N$ and $n\le M$.
Using this test, determine whether or not the $x$-range of the projectile,  $[\min(\text{projectile_start_x}),\max(\text{projectile_end_x})]$, overlaps with the $x$-range of the square.
If it doesn't, there's no intersection. If it does, determine in the same way if the $y$-range of the segment overlaps with the $y$-range of the square.
If it doesn't, there's no intersection. If there are overlaps in both coordinates, determine for each of $x$ and $y$, "when" the line extending the projectile's segment is within each of the coordinate ranges of the square.
To do this, parameterize the projectile as moving during a time interval $t=0$ to $t=1$ as $$\text{position}(t)=\\(\text{projectile_start_x}+t(\text{projectile_end_x}-\text{projectile_start_x}),\\\text{projectile_start_y}+t(\text{projectile_end_y}-\text{projectile_start_y}))$$ and solve the four simple equations for when its $x$-coordinate equals the square's left and right $x$-coordinate and when its $y$-coordinate is equal to the square's bottom and top $y$-coordinate. (Be careful not to divide by zero if the projectile is moving horizontally or vertically, in which case the time intervals are either empty or $(-\infty,\infty)$.)
Now you have two time intervals, one for when the line the projectile lies in is within the square's $x$-range and one for when it's in the $y$-range.
See if those time intervals overlap. If so, the segment intersects the square. Otherwise, it doesn't.
You might be tempted to skip the preliminary checks, but first of all, they are easy and eliminate many projectile-creature possibilities. Second of all, the time intervals could overlap outside the range $[0,1]$ (if the projectile is aimed toward the square but stops short), so you still have something else to check if the time intervals overlap. You don't have to make this last check if you did the initial check.

Does Part of Line Cut Through Square


Syntax error in LP Solve IDE trying to solve binary problem

Question: objective function
whenever I run the program it gives me a syntax error in line 2 of the objective function (image attached)
I can't work out the reason for it
Comment: I'm voting to close this question as off-topic because this is not a math question, but a programming syntax question.
Comment: Have you tried to replace the colon by an $\text{equality sign}$? If a syntax error is still reported then insert $\text{multiplication signs}$ between the coefficients and the variables.
Answer: You cannot use expressions and parentheses in an LP format. I.e. instead of
0.02(x1 + x2)

you should use
0.02 x1 + 0.02 x2

Anyway, as always first read the documentation on the input format before guessing.


Differences between primitive central idempotents and primitive orthogonal idempotents

Question: I asked this question in mathoverflow. But it was closed. So I ask it here.
If we have a complete set of primitive orthogonal idempotents of an algebra $A$, then we can obtain simple modules, indecomposable projective modules, indecomposable injective modules of $A$.
If we obtain a complete set of primitive central idempotents of $A$, what modules can be obtain?
I found that some papers compute a complete set of primitive orthogonal idempotents of an algebra while some other papers compute primitive central idempotents. What are the differences between primitive central idempotents and primitive orthogonal idempotents? Thank you very much.
Answer: A complete set of centrally primitive idempotents $\{e_1,\ldots, e_n\}$ in $R$ furnishes a decomposition of of $R$ into directly indecomposable rings, namely the indecomposable rings $e_iRe_i$. A ring may have a complete set of centrally primitive idempotents without having a complete set of primitive idempotents.
These idempotents do not connect well with the category of $R$ modules. For instance, in any simple ring (or finite product of simple rings) you always have a complete set of centrally primitive idempotents. Modules for simple rings vary a lot, so you can't say much about their modules.
In contrast, a complete set of primitive idempotents provides a much finer grained picture of the left and right ideals of $R$, and therefore of the category of modules.
Comment: thank you very much. Usually when we want to study the ordinary quiver of an algebra, we compute a complete set of primitive orthogonal idempotents. Does a complete set of primitive idempotents contain a complete set of primitive orthogonal idempotents?


ASP.NET WebApi Routes and parameters types

Question: I have read many articles and similar questions but none of those decisions do not fit me.
I have 3 methods:
public string GetA()
{
   return "Hello from GetA";
}
public string GetB(int id)
{
   return "Hello from GetB";
}
public string GetC(sting all)
{
   return "Hello from GetC";
}

I need to configure route like:
1.http://localhost:63087/api/Test/
2.http://localhost:63087/api/Test/all
3.http://localhost:63087/api/Test/1
4.http://localhost:63087/api/Test/1/all

How can I implement it?
I know this may be a duplicate (1, 2, 3), but I need help with it.
Thank you in advance
Comment: @CliffBurton Did you read the question? I know and a wrote "I know this may be a duplicate (1, 2, 3), but I need help with it." and there are a links. Link number 3 is the same. Please read the question
Answer: Try this code:
    public static class WebApiConfig
    {
       public static void Register(HttpConfiguration config)
       {
                config.SuppressDefaultHostAuthentication();
                config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

                // Web API routes
                config.MapHttpAttributeRoutes();

                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/Test",
                    defaults: new { controller = "Test", action = "GetA"}
                );

                config.Routes.MapHttpRoute(
                    name: "WithID",
                    routeTemplate: "api/Test/{id}",
                    defaults: new { controller = "Test", action = "GetB", id = UrlParameter.Optional }
                );

                config.Routes.MapHttpRoute(
                    name: "ALL",
                    routeTemplate: "api/Test/all",
                    defaults: new { controller = "Test", action = "GetC"}
                );
            }
    }

Comment: Thanks but it is not help me. `http://localhost:58052/api/test` - Ok, `http://localhost:58052/api/test/all` - The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'..., `http://localhost:58052/api/test/1` - Ok, `http://localhost:58052/api/test/1/all` - HTTP 404.0 - Not Found
Answer: So, you can not have two routes with same parameter count.
2.http://localhost:63087/api/Test/all
3.http://localhost:63087/api/Test/1

In this way, you can use in all your methods parameters type string:
public string GetA()
{
   return "Hello from GetA";
}
public string GetB(string id, string all = "")
{
   if (id.Equals("all") || all.Equals("all"))
   {
       return "Hello all from GetB";
   }
   return string.Format("Hello {0} from GetB", id);
}

Route config:
 config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

   config.Routes.MapHttpRoute(
        name: "RouteWithParam",
        routeTemplate: "api/{controller}/{id}/{all}",
        defaults: new { all = RouteParameter.Optional }
   );

Comment: Ok. It is just one of the possible solution
Comment: Thank you. I think it won't be proper to use string type for ID values
Answer: Other solution is to add static segment to route:
1.http://localhost:63087/api/Test/
2.http://localhost:63087/api/all/Test/
3.http://localhost:63087/api/Test/1
4.http://localhost:63087/api/all/Test/1

Implementation:
    public string GetA()
    {
        return "Hello from GetA";
    }
    public string GetB(int id)
    {
        return "Hello from GetB";
    }

    [Route("api/all/{controller}/{id}")]
    [Route("api/all/{controller}")]
    public string GetC(int id= 0)
    {
        return "Hello from GetC";
    }

Route config:
config.Routes.MapHttpRoute(
       name: "AllRoute",
       routeTemplate: "api/full/{controller}/{id}",
       defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
       name: "DefaultApi",
       routeTemplate: "api/{controller}/{id}",
       defaults: new { id = RouteParameter.Optional}
);

Comment: Where do you use inheritance?
Comment: See [MVC Attribute Routes & Route Inheritance](http://stackoverflow.com/q/23431043/4275342)
Comment: I like this solution. An its work. Thanks. Thanks. Thanks
Comment: But now I have another problem with inheritence. Because Route attributes not inherited. Can U help me?
Answer: Configure your routes like this
http://localhost:63087/api/Test
http://localhost:63087/api/Test/1
http://localhost:63087/api/Test/1/all

Something like this:
config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/Test",
                defaults: new { controller = "Test", action = "GetA"}
            );

            config.Routes.MapHttpRoute(
                name: "Route2",
                routeTemplate: "api/Test/{id}",
                defaults: new { controller = "Test", action = "GetB" }
            );

            config.Routes.MapHttpRoute(
                name: "Route3",
                routeTemplate: "api/Test/{id)/{all}",
                defaults: new { controller = "Test", action = "GetC"}
            );

Comment: You cannot have two routes with same parameter count. Event if you have so the route engine will consider only the first route. So, both 2 and 3 cant be achieved at the same time.
Comment: Try to achieve the functionality of 2 and 4 with the same route. For `http://localhost:63087/api/Test/all` try using some default value for id (say 0 or -1) which means for all id's. Now your 2nd route becomes `http://localhost:63087/api/Test/0/{all}` and 4th becomes `http://localhost:63087/api/Test/{id}/{all}`
Comment: No, it is not my routes. Please see the question. I have 4 routes
Comment: Yes, you are right. That's why I create questions. I need a solution to this poblemy
Comment: Thank you, this solution is working. What other ways can you offer me? Because 0 is not very nice


How to configure php5 on apache2.2?

Question: I want to configure PHP5 on apache2.2 server.
I added

LoadModule php5_module "c:/php/php5apache2_2.dll"
AddHandler application/x-httpd-php.php
# configure the path to php.ini
#PHPIniDir "c:/php"

these lines on my apache httpd.conf file. But it is not restarting apache server.
What is the problem? Can anybody help me?
Comment: What do you mean by "is not restarting" - does it crash when you try to restart it? If yes, there should be an error in `error.log` telling you more
Answer: You are missing the space after application/x-httpd-php
AddHandler application/x-httpd-php .php

Comment: Hi how can we change htdoc folder out side of apache folder?
Comment: Just change parameter DocumentRoot in VirtualHost directive of your configuration file of site.
  http://httpd.apache.org/docs/2.2/vhosts/examples.html
Answer: Replace
application/x-httpd-php.php

by
application/x-httpd-php .php

Comment: May I know how to change htdoc folder from apahce?
Comment: What do you mean "from Apache"? Web interface? Using web-based file manager like PHPfileNavigator or by hosting administration system (webmin, cPanel...).

How to configure php5 on apache2.2?


SQL - data containing a list of things?

Question: I'm working on a Database of collectible cards. So far I'm walking in the dark, but I think I somehow manage it. What I stumbled upon is a huge problem, I can't seem to find a solution on the internet:
There is a table of different cards, which has id of card (Primary Key), and columns containing info of cards.
There is also a table of users, and those users can have cards in their collection.
Now question: how to build a table/tables that shows that a certain user has some cards in certain numbers, which data are in cards table.
Link to DB image below:
http://imageshack.com/a/img856/2404/ogu0.png
The same problem I have with decks: There is an owner of a deck, and that deck have many cards in different numbers.
Any ideas on how to achieve that?
Comment: Add a "cardsdecks" table with id_card, id_deck, quantity columns.  You could do the same thing for collections.
Answer: You can create a table called user_card_relations( For example ) with the following fields

relation_id( Primary Key).
card_id( Foreign key to cards table).
user_id( Foreign key to user table ).

Inorder to list the details you can use SQL JOIN commands.

SQL - data containing a list of things?


read notification automatically when the activity is on the foreground

Question: I looking for a way to read notification message automatically, and displaying it, on receiving a message from the server, when the activity is on the foreground, just like a chat application.
I got GCM working, and i am able to create a notification when the client app receives a message from the server.
anyone guide me how to get this done?
Answer: If I understand your question when the server send the device a message and your application on foreground u want to get the message into your application and avoid from create a notification.
when you get a call to your GCM Receiver you should know if your application is on the foreground.
look here for know if the application in background/foreground.
now, if the application on background create notification else don't :)
hope it's help u.
Comment: I am extending IntentService, should i do this check in HandleIntent()?
Comment: u are talking about the receiver?
Comment: yeah from there i'm creating a notification, so could i make the checking there? a little more google-ing lead me to an example of LocalBroadcastManager. So, correct me if i'm wrong, i could check if the application is on the foreground, if so i could do a localbroadcast, else create a notification.
Comment: first of all you should extends BroadcastReceiver for getting the message from GCM. and if the application on foreground u can to transfer the information with another receiver that, and your activity should register to this receiver.
Comment: Its working! I did it like u said, put the checking in BroadcastReceiver and use the LocalBroadcastManager to broadcast the message if the activity is on the foreground. Many thanks to you. :)


Async functions not being recognized

Question: I have some async functions that I have used in multiple projects, however when I added them to another project they suddenly aren't working.
An example of one of these functions is:
const ddbGet = async (params) => {
    try {
        const data = await docClient.get(params).promise();
        return data;
    } catch (err) {
        console.log("Failure", err.message);
        return false;
    }
};

The error that gets thrown is:
const ddbGet = async (params) => {

                     ^

SyntaxError: Unexpected token (
However I know there are no problems with the functions' syntax as they are used successfully elsewhere.
I have seen some answers to other questions that have suggested some issues with JSHint and ESLint however I don't believe I was using either of these, but just to be sure I installed ESLint and specified the ECMA version as suggested in those answers and this error was still thrown.
I have also made sure I'm using the latest version of Node.js.
And if I remove those functions an error gets thrown due to an asynchronous function in the node_modules folder.
async handshake(transportName, req, closeConnection) {
   `^^^^^^^^^`

SyntaxError: Unexpected identifier
Does anybody know what the problem could be? Thanks.
Comment: If you're using an IDE (for example WebStorm, as I only know for it), be sure that the config aren't mixed up in .idea. You could very well have an old NodeJS interpreter for one project and the newest one for another. Be sure to re-do the configs if you're running your script via said IDE. EDIT: Last comment of OP made mine pretty useless but keeping it for others that might come across this problem.
Comment: What does `node -v` tell you? Your problem is clearly that your JavaScript platform is dated for some reason.
Comment: What is throwing the error? The browser? The build?
Comment: The example code doesn't throw any errors in [eslint](https://eslint.org/demo)
Comment: @Pointy v17.2.0, I installed the latest version when the error was first thrown hoping it would solve it! Sadly it didn't
Comment: @epascarello The build. I'm using an AWS Cloud9 environment if that helps
Comment: @UdoE. its the first parenthese before the params argument
Comment: Since you mentionned `AWS Cloud9`, I assume you followed their "Getting Started". What does `nvm ls` output?
Comment: @GaëtanBoyals This isn't a new project, it's actually 4 years old or so and I've inherited it so I wasn't involved in the set up.
Comment: @GaëtanBoyals  nvm ls gave me this output:
v6.15.1
->      v17.2.0
         system
default -> 6 (-> v6.15.1)
node -> stable (-> v17.2.0) (default)
stable -> 17.2 (-> v17.2.0) (default)
iojs -> N/A (default)
lts/* -> lts/argon (-> N/A)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.24.1 (-> N/A)
lts/erbium -> v12.22.9 (-> N/A)
lts/fermium -> v14.18.3 (-> N/A)
lts/gallium -> v16.13.2 (-> N/A)
Comment: Gotcha, I'm writing a full answer.
Answer: Since the documentation, or rather AWS Cloud9's Getting Started isn't kept up-to-date (using an old script to install NVM) and seeing that the project was very old (as per the extended comment section of the question), it surely was the NodeJS version.
This is confirmed by the nvm ls output the OP gave us (I only formatted it):
v6.15.1
-> v17.2.0 system
default -> 6 (-> v6.15.1)
node -> stable (-> v17.2.0) (default)
stable -> 17.2 (-> v17.2.0) (default)
iojs -> N/A (default)
lts/* -> lts/argon (-> N/A)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.24.1 (-> N/A)
lts/erbium -> v12.22.9 (-> N/A)
lts/fermium -> v14.18.3 (-> N/A)
lts/gallium -> v16.13.2 (-> N/A)

The line default -> 6 (-> v6.15.1) informs us that the default NodeJS version used (for the whole system) is v6.15.1.
Unfortunately, NodeJS does NOT handle async/await syntax natively before v7.6.
You could run nvm install 17.2.0 and then nvm use 17.2.0 (or simply the nvm use part, but I don't know if the v17.2.0 we see in the output have effectively been installed via NVM), which is likely to fix this particular problem.
Comment: Thank you for your answer, I shall try this when I return to the office tomorrow morning :)
Comment: I've found the solution thanks to your guidance, posting it now
Comment: Sure, keep me updated!
Comment: This is was the output after the `nvm use 17.2.0` command: Now using node v17.2.0 (npm v8.3.0)
Answer: I've found the solution with a little more research after Gaëtan Boyals put me on the right path!
He was correct that the default version of Node.js was the issue and the solution to fix this was nvm alias default 17.2.0
Comment: Great! Glad I could at least help!
Comment: @GaëtanBoyals Yes thank you! I'll upvote your answer as it was still helpful to me :)

Async functions not being recognized


let $z$ be a complex number such that $|z+9|=3|z+1|$. Find $|z|$

Question: I am fairly new with complex number. I tried to do $|z+9|^2 = 9|z+1|^2$ and solved for everything and ended with $|z| = \sqrt(-9)$  I believe that is indeed the solution but I have it just seems fishy to me.
Comment: $|z|$ is always a non-negative real number.
Comment: Thank! figured out where I was wrong
Answer: Let $z=x+iy\in \mathbb{C}$. Then,
$$|z+9|=3|z+1|\Rightarrow |x+iy+9|=3|x+iy+1|$$
$$\Rightarrow |(x+9)+iy|=3|(x+1)+iy| $$
then,
$$ \sqrt{(x+9)^2+y^2}=9\sqrt{(x+1)^2+y^2}$$
$$\Rightarrow x^2+18x+81+y^2=9x^2+18x+9+9y^2 $$
$$\Rightarrow 8x^2+8y^2=72 \Rightarrow x^2+y^2=9$$
Then, we have:
$$|z|=|x+iy|=\sqrt{x^2+y^2}=\sqrt{9}=3. $$
Answer: We have:
\begin{eqnarray}
0&=&9|z+1|^2-|z+9|^2=9(z+1)(\bar{z}+1)-(z+9)(\bar{z}+9)\\
&=&9(|z|^2+z+\bar{z}+1)-[|z|^2+9(z+\bar{z})+81]\\
&=&8|z|^2-72=8(|z|^2-9)=8(|z|-3)(|z|+3),
\end{eqnarray}
hence $|z|=3$.


appropriate test for comparison between two variables

Question: I have two variables ,  Variable1 and Variable 2.
Variable 1 has three levels { Pizza, Pasta, Breadstick }
Variable 2 has five levels { American, German, Spanish, Japanese, Chinese }
The response distribution is as follows
<code>             Pizza       Pasta       Breadstick
  American   2           1           28
  German     0           0           8
  Spanish    0           0           2
  Japanese   1           0           0
  Chinese    0           1           1
</code>
We can apply Chi-Square test to compare association between these two variables. However I am not sure about using Chi-Square test when there are a lot of zeros. I am wondering if anybody has any suggestions for any other test that could be applicable here other than Chi-Square test for this scenario with many zeros?
Comment: Not the best answer (see @LambdaPsi for starters), but you should consider combining Spanish, Japanese, and Chinese into an 'other' cell -- that would reduce your number of cells with E[0] rather dramatically. It would also reduce the number of tests you are implicitly performing, thus improving your power somewhat substantially.
Answer: You are in the right direction. Chi-square tests are not appropriate when you have small expected values in many cells.
Instead, you can try a Poisson regression by treating the value in each cell as a count value, and predicting the count variable with dummy-coded Variables 1 and 2.
Comment: How will this help in testing Independence?


Are bone breaks in MMA more common nowadays than in the past?

Question: I read on https://www.mmamania.com/2021/7/15/22572007/joe-rogan-bone-break-conor-mcgregor-chris-weidman-ufc-264-mma-news (mirror), quoting Joe Rogan:

There's been a ton of breaks over and over again. People are getting good at breaking people's bones

Are bone breaks in MMA more common nowadays than in the past?
Answer: Perhaps! But it really depends what specific time period you're referring to. Just saying "Past" doesn't specify what time period you (or Joe Rogan in this case) are referring to. I'm not gonna provide any numbers to confirm or dispute that hypothesis in this answer.
There have been a number of bone breaks in the past few UFC events, notably the bone breaks of Jacare Souza, Chris Weidman, and Connor Mcgregor. But to truly be able to compare increase of bone breaks (or any statistical event) you need a large enough control group and experiment group. I don't think there's a big enough sample size of the experiment group in this case, just looking at the past couple of pay-per-view events. Whilst this hypothesis may be true, there has been a number of bone breaks to some of the more known names in UFC recently, promoting jumping to conclusions without supporting data. Also need to narrow down what is considered a bone break. Is a broken nose counted too? Or are you just referring to limbs?
Interestingly, Chael Sonnen did a video just on the same topic today. And he pointed out that greatest Jiu Jitsu skill differential existed when Royce Gracie fought in early days of UFC. Although that put him in a huge advantage to break opponent bones, he didn't, as he let his opponents tap under submissions.
There are a few things in my mind to note, comparing bone breaks of now, to the past:

Need to define "now" and "past" with similar amount of fights between those 2 periods
Many bone breaks go without becoming a major talking point. Far more common bone breaks, in days past, and present, are those not often talked about. Many fights result in broken noses, jaws, hand, toes, ribs, orbital bones, etc. I doubt there's been a huge spike of such bone breaks overtime, though I wouldn't be surprised if there's been a steady rise in those. I don't think that's what you're asking either, and you're rather thinking of major limb bones.
The quality of athletes has raised steadily, so the technique and aggression should be at higher levels. This means the defensive skills have also been raised too. So I'm not sure how this relates to bone breaks.
There has been a number of notable limb bone breaks recently, but how many more in the past 2 years? Yes we've seen a number of those recently, but the sample size is very small.
There are more fighters that either don't tap under submissions which results in broken bones or torn ligaments (ex: Tony Ferguson), or fights go on far longer than should've due to referees not stopping the fight soon enough or the corners not throwing in the towel (ex: Anthony Smith getting mauled by Glover Teixeira to the point his teeth were falling out)
The style of fighting goes over changes every few years and also over time. We're in a era where kicks are very common, and they inherently increase odds of injury, including broken bones, specially when checked. Or creating so much pain in a leg that the opponent becomes relatively stationary and more prone to KOs.
There are far more fights nowadays than decades ago. In all of the 90s UFC had 27 events. But the UFC does that now in just over 2 years, but if you include the weekly fight nights, 27 events happen just over 6 months. So with the increase in number of fights, occurrences of events, such as bone breaks have also increased. But has the rate also increased?
Recency bias is a thing and we tend to remember recent events in more details then past, and over exaggerate them.

In summary, without proper sample sizes and exact criteria for bone breaks, we can't answer if they've become more common. MMA fights are happening at a higher rate than before, so the occurrence of such event is higher, but we need to look at the rate of such events. If there's a database that keeps track of broken bones in MMA over time, we could study the data and see if there truly has been a raise in amount of broken bones. Otherwise, we can debate and speculate.
Comment: Thanks! "Need to define "now" and "past" with similar amount of fights between those 2 periods" -> one way could be to look at the evolution of bone break frequency over time.
Comment: Knowing bone break frequency over time would really simplify things in this scenario
Comment: @CGCampbell thanks, fixed it


ember serve and browser reload results in "cannot GET /foo" with custom Ember.Location

Question: TL;DR: Added custom location type to environment.js then ember serve -> open browser to route /foo -> cannot GET /foo
Followed the instructions at https://www.emberjs.com/api/classes/Ember.Location.html#toc_custom-implementation and copied the code exactly as it appeared into a file called app/locations/history-url-logging.js, added a line to config/environment.js that said:
ENV.locationType = 'history-url-logging';

For reference, the code given in the docs is simply:
import Ember from 'ember';

export default Ember.HistoryLocation.extend({
    implementation: 'history-url-logging',

    pushState: function (path) {
        console.log(path);
        this._super.apply(this, arguments);
    }
});

I decided to restart the server, did the usual CTRL+C to ember s then did ember s again. I went back to my browser sitting on one of the routes, hit F5, and received the cryptic error:
Cannot GET /contacts
So, after MUCH Googling and trial and error (and posting a previous question here which I just edited with this text you're reading), I discovered that to FIX that error, all I had to do remove the config line ENV.locationType = 'history-url-logging';, restart the server (ember s), and suddenly the app worked fine!
What's even more odd is that if I start the app without that line in environment.js, then once the app is running (and the browser window reloads just fine, etc), then I re-add the line that says ENV.locationType = 'history-url-logging'; (which triggers a live reload), and the app still works fine! (E.g. hitting F5 to reload the page doesn't vie me the "Cannot GET /contacts" (or whatever the route is) error.) And, of course, the console gives me the "console.log" output as expected from the code above.
So, long and short of it, using a custom location totally seems to screw up ember serve - which is really sad and frustrating! Any ideas how to fix this?
Comment: Where did `"page-stack"` implementation come from? I believe that the implementation string should be the same as the file name, meaning `"history-url-logging"`.
Comment: Sorry, you're absolutely right, that was an error in my copy-pasting. I copied my code before I reverted it for testing. In the test, the `implementation` **is** `history-url-logging`, guarantee it. Still same problem. :-/ - I'll edit my question so other's aren't confused - thanks for catching that.
Answer: Ember built-in server looks at the environment.js locationType property to figure out if it must serve routes after the rootURL path. By default, if the locationType is history it will do it. It uses string matching.
In your case you wrote your own location, inheriting from HistoryLocation therefor the locationType property in the environement.js is now history-url-logging. The built-in server doesn't recognize it as a history based form of location just by the name. It will default to hash location. It doesn't analyze your code.
For this scenario, we have to help the built-in server to understand that the locationType is equivalent to a history location.
You need to add historySupportMiddleware: true in your environment.js file right after the locationType property.
Comment: Welcome to Stack Overflow! Are you able to add an explanation of why/how your solution helps answer the OP's question?
Comment: @MattShepherd I got your point. I edited my response. Hopefully it will help.


How to fix this code for a Java program that simulates a simple calculator?

Question: Kindly help me to fix this code for a Java program that simulates a simple calculator.
It reads two integers and a character. If the character is a +, the sum is printed; if it is a -, the difference is printed; if it is a *, the product is printed; if it is a /, the quotient is printed; and if it is a %, the remainder is printed.
import java.util.Scanner;
class calc {
    private int a,b,and;
    private char c;
    public static void main (String args[])
    {
        System.out.println ("Enter the first Integer");
        Scanner scan = new Scanner (System.in);
        a=scan.nextInt();
        System.out.println("Enter the second Integer");
        b=scan.nextInt();
        System.out.println("Enter the operation sign");
        c=scan.nextChar();
        if (c=='+')
            and=a+b;
        else if (c=='-')
            and=a-b;
        else if (c=='*')
            and=a*b;
        else if (c=='/')
            and=a/b;
        else if (c=='%')
            and=a%b;
        else
        {
            System.out.println("Wrong operation");
        exit(0);
        }
        System.out.println("The result is "+ ans);
        }
    }

Comment: This code is riddled with spelling errors. At least check your code before you post it here.
Comment: spelling mistake   c=scna.nextChar(); Also why not you are using Switch case to avoid so many 'if else'
Comment: i do not know how to use "Switch", this is my first java
Answer: Change
c=scna.nextChar();

to
c=scan.nextChar();

Also change
exit(0)
to
System.exit(0)
b=scan.newxInt(); to b=scan.nextInt();
Change all Out to out
Comment: Yeah I'm getting on it :D
Comment: I admire your effort, but posting code that is so far from runnable is an insult to the people trying to assist here on SO.
Comment: I literally need to kill time before I go in a few minutes lol so I kinda dc
Answer: Couple of things:

Make all your variables static so that you can use them within main or i would suggest move them within main.
Use nextLine().charAt(0) instead of nextChar which isn't defined in Scanner.
Instead of newxInt(); use nextInt(); api of Scanner
out is a static field (note lower case o), so change System.Out to System.out.
do an import static java.lang.System.exit; so you could use exit(0); without any issues from compiler.

Edit: Just for OP (Make sure you give meaningful name to variables) -
import static java.lang.System.exit;
import java.util.Scanner;

public class calc {

    public static void main(String args[]) {
        int a, b, ans = 0;
        char c;
        System.out.println("Enter the first Integer");
        Scanner scan = new Scanner(System.in);
        a = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter the second Integer");
        b = scan.nextInt();
        scan.nextLine();
        System.out.println("Enter the operation sign");
        c = scan.nextLine().charAt(0);
        if (c == '+')
            ans = a + b;
        else if (c == '-')
            ans = a - b;
        else if (c == '*')
            ans = a * b;
        else if (c == '/')
            ans = a / b;
        else if (c == '%')
            ans = a % b;
        else {
            System.out.println("Wrong operation");
            exit(0);
        }
        System.out.println("The result is " + ans);
    }
}

Output:
Enter the first Integer
10
Enter the second Integer
20
Enter the operation sign
+
The result is 30

Comment: See my edited answer. Dont just copy paste it. Just have a look at it and modify it accordingly. Make sure you use appropriate variables names and follow camel case and coding conventions.
Comment: Can you please write the complete right code, I changed point No.4 but I am afraid to mess thing up if I edit more , kindly write the complete right code so I can compare and learn form my mistakes
Comment: I can learn now from my mistakes because of you make it so obvious what I did wrong , you are the best, thank you very much . I will make sure of variables and case and conventions


How can I calculate coordinates of the perpendicular line?

Question: Lines (x1, y1), (x2, y2) and (x3, y3), (x4, y4) are perpendicular. I have coordinates of points (x1, y1), (x2, y2), (x3, y3) and length in pixels of a line (x3, y3), (x4, y4). I need to find coordinates of point (x4, y4). What is the pseudocode for calculating (x4, y4)?
Comment: You shouldn't draw P3 on the line segment P1P2, this is misleading.
Comment: @Yves Daoust. But (x3,y3) is located on the line (x1, y1), (x2, y2). How I can draw it other way?
Comment: If P3 is guaranteed to be on P1P2, then one of P1 or P2 is extraneous.
Comment: @Yves Daoust There is line from P1 to P2. On that line there is P3. So P1,P2,P3 are the points that are located on line P1P2.
Answer: Calculate vector A where
 A = (x2 - x1,y2 - y1)

A vector perpendicular to this is given by
 B = (y1 - y2, x2 - x1)

find the normalised vector
 C = B/|B|

where |B| is simply the modulus of vector B calculated using pythagoras
Your point (x4,y4) will then be given as
 (x4,y4) = (x3,y3) + K*C

where K is the length of the line (x3,y3) to (x4,y4) (which you say in the question that you know). Depending on the orientation of your points, you may need to set the value of K to
 K = -K

in order for the point to be correct to your needs.
Comment: @vasili111 you have a mistake. it should be b = x2-x1
a = y1 - y2   . You should see it work now.
Comment: Thank you for a help. I think I did it the way you said but it did not worked. The line(x1, y1), (x2, y2) is not perpendicular to line (x3, y3), (x4, y4). What is wrong here? http://pastebin.com/ZSwy4e2J
Comment: It works fine. Thank you again. Also, if someone wants to implement that algorithm should keep in mind that, if points (x1, y1) and (x2, y2) have some values, the result will be "undefined" or something like that depending on the implementation of programming language used. That is because you cant divide number by 0.


Setting uniform  width in all browsers

Question: What combination of CSS or attributes are needed?
Answer:
Hide the actual control
Made a DIV with the controls and styling you want on top of it

The button is not a standard HTML control.
See: http://www.quirksmode.org/dom/inputfile.html
Comment: Browsers don't allow to delegate clicks on file input as a security feature. So, we need the opacity for the hack
Comment: There is absolutely no need to use opacity - you can simply delegate the click on a display:none element - much simpler and you don't have to take the (varying) input size into account.
Comment: so there's no way to achieve this using the native control itself?
Answer: what's wrong with
<input type="file" size="50" .... />

?
Will look same except safari on mac i guess (on mac, all upload controls looks different, on all browsers)
Comment: W3C fails to validate attribute `size`, because it only allowed on `text, search, url, tel, e-mail, or password` type of fields.
Comment: input-width does nothing. You may be thinking of input-size, which does change the width, but not in units that you can standardise across browsers.
Comment: This works...it handles firefox..while CSS width propery handles Chrome, IE, and Safari
Comment: If you want to set a more exact size, could use visibility hidden while binary search for the desired size using javascript...!  I doubt it's worth it, but I would prefer this rather than hiding the actual control.
Comment: a "file" input looks and smells like an "text" input, so i wonder whats the point of non-validation, really. Yes i know that doesnt act like a "text" but still takes characters and is a box in a pretty same way...
Answer: In addition to the quirksmode tutorial, here's another good resource:
http://www.shauninman.com/archive/2007/09/10/styling_file_inputs_with_css_and_the_dom
If you're hiding the actual control, remember that it is very important to set the opacity of the control to zero, and not actually use visibility: hidden. Doing that will actually hide the element, disabling the click action.
Also, if you're covering up the control with a graphic button, do be aware that in some browsers (Firefox and IE, I believe), you will not be able to change the cursor type to a hand when it's over the text-input part of the file control (it will always default to the input or the regular non-link pointer). And yes, I've tried using cursor: pointer (and cursor: hand).
Personally, I've struggled with customized upload boxes, and there is no silver bullet for getting their appearance or customization perfect. (especially concerning the behavior of the cursor, as I consider that a UI deal-breaker). At the end of the day, I think it's just easier to  accept that different browsers will render the control differently, and that's just how it is.

Setting uniform  width in all browsers


Product of two hypergeometric functions

Question: For $\Re a, \Re b, \Re c, \Re a', \Re b', \Re c'>0$,  I would calculate the following product
$$ {}_2 F_1(a, b; c; x^{-1}) \times \, {}_2 F_1(a', b'; c'; 1-\frac{x}{y}) $$
For all $y>x>1$.
Is there a formula that allows me to calculate the above product
Thanks in advance.
Answer: This product of two Gaussian hypergeometric functions can be expressed by a sum over generalized hypergeometric functions ${}_{4}F_{3}$ according to formula 4.3.(14) on page 187 in "Higher Transcendental Functions, Vol. 1" by A. Erdelyi (Ed.). I reproduce it here for your convenience. (I've slightly changed the notation of the original.)
$$
{}_{2}F_{1}(a,b;c;p z) \ {}_{2}F_{1}(a',b';c';q z)= \\ \sum_{n=0}^{\infty}\ \frac{(a)_{n} (b)_{n} (pz)^{n}}{n!\ (c)_{n}}\ {}_4F_{3}(a',b',1-c-n,-n;c',1-a-n,1-b-n;\frac{q}{p}),
$$ where $(a)_{n}$ etc denotes the Pochhammer symbol. Note that for negative integer $a$ (and euivalently $b$ and per symmetry also for negative integer $a'$ and/or $b'$) the sum terminates. By setting $z=1$ and substituting $p$ and $q$ you get the solution that you are looking for.
Comment: The formula I posted is a special cae of this formula: http://functions.wolfram.com/07.31.16.0001.01
Comment: Thanks very much, Johannes. I'll try to apply it to the problem I just posted https://math.stackexchange.com/questions/2792124/simplify-re-express-if-possible-the-product-of-2f1-and-3f2-hypergeometric-func (also see my other related posting (without the added parameter k)  https://mathoverflow.net/questions/279867/perform-an-integration-involving-the-product-of-two-hypergeometric-functions   . I've now incorporated the product in question in a later version (yet to be posted) of https://arxiv.org/abs/1803.10680
Comment: What about the product of a 2F1 and a 3F2?
Comment: Johannes, I don't think it is algebraically possible, in the particular case, in my indicated posting https://math.stackexchange.com/questions/2792124/simplify-re-express-if-possible-the-product-of-2f1-and-3f2-hypergeometric-func to have a z, such that $c z= t^2$ and $d z=1-\frac{1}{t^2}$--so, I don't think I can make use of the Wolfram formula.
Comment: Maybe I miss the point, but isn't it possible to choose $z=1$ and $c=t^2$, $d=1-\frac{1}{t^2}$ ?
Comment: Thanks, Johannes! I'm pursuing your suggestion in the context of that https://math.stackexchange.com/questions/2792124/simplify-re-express-if-possible-the-product-of-2f1-and-3f2-hypergeometric-func problem.

Product of two hypergeometric functions


Sunspot Solr: Match multiple attributes together from a same has_many association?

Question: Let's pretend we have two users,
User A, with:

skill of 'Ruby' and experience_years of '5'
skill of 'HTML' and experience_years of '7'

User B, with:

skill of 'Ruby' and experience_years of '2'
skill of 'HTML' and experience_years of '5'

I only want to match User A, that is, the user with 5 years of Ruby experience.
The controller and model code below matches both User A and B, because the skill and experience_years is evaluated separately and both users have 'Ruby' and '5', just not together.
How do I write the controller (or model) part to only match User A?
Models
class User < ApplicationRecord
  has_many :user_skills

  searchable do
    text :skill do
      user_skills.map { |r| r.skill.name }
    end
    text :experience_years do
      user_skills.pluck(:experience_years)
    end
  end
end

class UserSkill < ApplicationRecord
  belongs_to :user
  belongs_to :skill
end

class Skill < ApplicationRecord
end

Controller
class UsersController < ApplicationController
  def index
    sunspot = User.search do
      fulltext 'Ruby' do
        fields(:skill)
      end
      fulltext '31' do
        fields(:experienceYears)
      end
    end

    @users = sunspot.results
  end
end

Answer: The solution is to use a dynamic integer.
Model (inside searchable block):
# skill + experienceYears composite field:
dynamic_integer :skill_composite do
  if skills
    skills.inject({}) do |hash, e|
      hash.merge(e.skill.skill_code => e.experience_years)
    end
  end
end

Controller:
with(skill_code).equal_to experience_years

Note the use of skill_code instead of name, this is because special characters like spaces in a string will cause troubles. skill_code is a sort of parameterized value of name in this case.


Nuget - Packages.Config utilizar últimas versões dos pacotes

Question: Cenário
Tenho um projeto onde as minhas Libraries (outros componentes do projeto) são pacotes Nuget, e sempre que tem alguma atualização é gerado no Proget uma nova versão.. e todos os desenvolvedores tem que dar um update packages manualmente para que o TeamCity por exemplo utilize a última versão especificada no package.config.
Segue exemplo simplificado do meu arquivo packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="BibliotecaX" version="2.0.1" targetFramework="net461" />
</packages>

Gostaria de fazer de uma forma onde ao invés de especificar essa versão, utilizar o version por exemplo version="2.0.*" ou version="2.*.*" para quando o VisualStudio for fazer restore pegar sempre a última versão (apenas de pacotes específicos) onde eu faria essa configuração.
Se alguém tiver alguma sugestão.
Comment: Pelo que eu sei, isso que está tentando fazer não funciona, todo pacote tem que ter sua versão, é além das versões finais (release) tem as versões beta, ou seja, o arquivo tem que identificar o que precisa ... !!! Eu até pesquisei, por desencargo, porque crio pacotes não tem isso não ou não achei.
Comment: @VirgilioNovic o jeito vai ser fazer manualmente no prebuild com os comandos do nuget mesmo e atualizar, ta dando certo aqui estou testando, se eu conseguir finalizar com sucesso posto aqui a resposta detalhada.
Obrigado pela ajuda
Comment: Qual a versão do nuget?
Comment: NuGet Version: 184.108.40.20679
Estou tentando contornar fazendo no PreBuild Events e chamando o comando dessa forma:
nuget update projeto.csproj -Id PacoteNuget
Comment: Tentou deixar o número de versão vazio?
Comment: **``**
Comment: Invalid package version for package id 'Newtonsoft.Json': '10.0.'
tentei com espaco tambem, ele ignora e nao funciona
Comment: @LINQ nao deu certo , infelizmente
Answer: Resolvi da seguinte forma:
Converti o packages.config para packagereferences
Utilizei essa extension para me ajudar na migração:
https://marketplace.visualstudio.com/items?itemName=CloudNimble.NuGetPackageReferenceUpgrader
Feito isso, dentro do CSProj fiz da seguinte forma: (o nome dos componentes são apenas exemplos)
  <ItemGroup>
    <PackageReference Include="Castle.Core" Version="4.2.*" />
    <PackageReference Include="Newtonsoft.Json" Version="10.0.*" />
    <PackageReference Include="NSubstitute" Version="3.1.*" />
   </ItemGroup>

Resolvido, no build ele baixa a última versão de acordo com a minha condição (1.0.*)


How do I validate form elements in a modal without closing?

Question: I'm using Drupal 8 and I have defined a custom entity type 'my_entity_type', with form handlers defined in the @ContentEntityType annotation:
 * @ContentEntityType(
 ...
 *   handlers = {
 *     "form" = {
 *       "add" = "Drupal\my_module\Form\MyEntityForm",
 *       "edit" = "Drupal\my_module\Form\MyEntityForm",
 *       "delete" = "Drupal\my_module\Form\MyEntityDeleteForm",
 ...

where:

MyEntityForm extends ContentEntityForm
MyEntityDeleteForm
extends ContentEntityConfirmFormBase

These are routed in my_module.routing.yml leveraging the _entity_form element:
_entity_form: my_entity_type.add

I am rendering the form from another form as a modal:
$form['add_my_entity_button'] = [
  '#type' => 'link',
  '#title' => t('Add NewEntity'),
  '#url' => Url::fromRoute(
    'my_module.add_entity',
    array(
      'node' => is_numeric($node) ? $node : NULL,
    )
  ),
  '#attributes' => [
    'class' => ['button', 'use-ajax'],
    'data-dialog-type' => 'modal',
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

All works as imagined. The '#required' type validator appears in the form in the modal.
Goal
To add custom validation to this form's elements ('live' validation that does not close the modal). I recognize that this type of problem isn't novel, and I've done it often in non-modal forms. The methods I would usually leverage are:

'#element_validate' form element callback
validateForm() type form callback

Both appear to require submission of the form, close the modal, and render the errors in a flat form display. I then combed through Core for ideas and embarked on a remarkably twisted yak-shaving journey:

Adding validation via BaseFieldDefinition::addConstraint in the
entity baseFieldDefinitions() : This still submitted the form and led to a flat (non modal) form with errors correctly thrown. Once I solve this problem, I will likely leave this in to serve as a gatekeeper at the storage level.
Extending the 'number' FieldType via Plugin, extending the widget, type or storage : This seemed overly complex for something as simple as adding a validator. I bailed on this before getting too far, since I considered:
Injecting a generic '#ajax' 'replace' callback to the element inside buildForm() in MyEntityForm : I could NOT get ajax inserted in this manner to fire here.
Injecting a generic '#ajax' 'replace' callback to the element in hook_form_alter : I could NOT get ajax callbacks inserted in this manner to fire either.

Questions
What have I missed? I feel this is simple. Is there something I've missed in Form that defines simple ajax validation?
Is there a standard way for validating form elements inside modals without closing the modal?
Can AJAX 'replace' callbacks be attached to forms defined and routed via the @ContentEntityType annotation? Is there a restriction here in the render pipeline?
Answer: This is a excellent article which you can read for "fixing" your issue:
http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8
Keep in mind this lines:
First, we wrap our form with a div
public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  // It is important this id
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  // The status messages that will contain any form errors.
  $form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
  ];

  // more code

  $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit modal form'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      // Function to call when the users click on submit button.
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // more code
}

Second, we show the errors:
/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    // Remember the previous id ? Here it is
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}


Loopback mysql and facebook login understanding

Question: I new to loop-back platform. I follow this tutorial loop-back official tutorial for third-party and this tutorial also a tutorial that i find.
What i want to do is to build a rest API using loop-back as one project and a client side using angular as another project then to wrap it for mobile. In this tutorials they are using loop-back passport for make the oath connection with Facebook.
now my questions are :

They save all the models involved in the authentication in the memory and not in the database. is it good approach? don't i need to save all the access-tokens, identities and credentials on the database ?
is there another tutorial that you can direct me to or you can explain me , where in loop-back i get the information return from Facebook after authentication because i want to save it in my user model ?

Thanks
Answer: 1.) It's not recommended to save authentication-data in memory in production, you can easily change this in server/model-config.json (or model-config.production.json) with the variable "dataSource" for each model. So instead of "memory" change it to the name of your datasource.
2.) In the example you provided, the "customProfileToUser"-function seems like an excellent place to save eventual extra data to your own User-model.
Comment: where can i find the customProfileToUser function that you mention ?
Comment: https://loopback.io/doc/en/lb2/Third-party-login-using-Passport.html#customize-loopback-user-created
Comment: It is however for Loopback 2, I'm positive it's applicable to LB3 aswell.
Comment: i see that you control in the loop-back platform. have you done a project with it ? something that i can see and learn from ? because there isn't to much examples that i can learn from . loop-back looks amazing but i find it very frustrating that i cannot find good place to see good tutorials.


Drupal 7 views add one field as a URL to another

Question: I am using Drupal 7. I have a view where i filer a certain content type say "A" and display the below 2 fields
  Content: Title
  Content: File attachments
My File attachment formatter is set "Url to file".
What i am trying to achieve is to make 'Title' as a link with the 'File Attachment' URL
Thanks in advance!
Answer:
for the Title, set it 'Exclude from display'
for the File attachments, 'Rewrite the output of this field' using the token for Title

Make sure the Title field appears above the file attachment, or the file attachment won't recognize it as a valid token when rewriting the output
Comment: Great, worked fine!


função getBy do JpaRepository

Question: eu tenho uma classe chamada pessoa
public class Pessoa{
   private Long id;
   private String nome;
   private String email;

   //construtores e getters e setters
}

no JpaRepository tem uma função chamada getBy() .
como posso usar essa função para pegar uma pessoa por exemplo pelo email? pelo id sei como é.
Comment: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
Answer: Antes de mais nada, JpaRepository precisa de uma Entity, não sei se é o caso, mas você nos mostrou um simples POJO
Enfim... Tendo uma entity você pode sim construir querys a partir de nomes de métodos, basta adiciona-los a sua interface JpaRepository
DOC do Spring Data:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords
Guia um pouco mais mastigado:
https://www.javaguides.net/2018/11/spring-data-jpa-query-creation-from-method-names.html
Espero ter ajudado.
Answer: Crie um metodo chamado findByOneEmail(String email) na classe Repositorio que será utilizada.
interface PessoaRepository implements JpaRepository<String, Long> {
 Pessoa findByOneEmail(String email);
}

função getBy do JpaRepository