Reset input-field when click outside the element

Question: I have the following code that enables inline editing
$('.edit_td').click(function() {
    resetEditedCells();
    $(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});

function resetEditedCells() {
        $('.edit_td.active').html(function() {
        return $(this).find('input').val();
    });
}

This works fine when switching from td to td. But when I click anywhere else, outside the table, I want the input fields, to transform back to the regular tds.
Ive tried like this:
$(document).on('blur', function(e) {
    if($('.edit_td').hasClass('active')) {
        $('.active').remove();
    } else {
        alert("false");
    }

});

The .blur() is not triggered. Anyone?
Comment: Do you know you are bluring the document itself? Not the edit field...
Comment: maybe your are looking for `$(this).removeClass('active').empty().text(original_text);`
Comment: Try `$('input').on('blur'`
Answer: Try something like this to replace the code you have
$(document).on('click', function(e) {
    var edit_td = $(e.target).closest('.edit_td');

    if ( edit_td.length > 0 ) {

        resetEditedCells();
        edit_td.addClass('active')
               .html('<input type="text" value="' + edit_td.html() + '">');

    }else{

        $('.edit_td.active').removeClass('active').empty();

    }
});

This uses closest() to determine if the click originated from inside or outside a TD.
Comment: that's how i usually do it.
Answer: You need to use click event instead of blur:
$(document).click(function() {
 if($('.edit_td').hasClass('active')) {
     $('.active').remove();
 } else {
     alert("false");
}});

also modify td click event to  stopPropagation:
$('.edit_td').click(function(e) {
 e.stopPropagation();
 resetEditedCells();
 $(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});

Comment: It's better to bind a blur event directly on the field. If you bind to the document, the function will be called anytime the webpage is clicked. This uses needless processing power.
Comment: That don't work. When I click on the td, the click on the document is fired, and the td is not transformed to an input field. When you first click on a td, the td should transform to an input field. When you click outside the table itselfe, the input-field should reset to an td.
Comment: @user500468: have you added  stopPropagation in td click event??
Comment: @MilindAnantwar: Thank you. But how can I capture the value of the input-field before removing it?

EDIT: Never mind. I solved it :)
Comment: @MilindAnantwar: How can I restore the the td and it's value when I have removed the class? When I click outside the element, the content inside the td is removed.
Comment: Instead of removing, you should hide `$('.active')` this will allow you to retain the value later on.
Comment: @MilindAnantwar: When I write $('.active').hide(), the content of the TD is still lost. I want the value of the td to appear back.
Comment: `hide()` should not remove the content. on showing back the td. its content should reappear
Comment: @MilindAnantwar: What do you mean?
Answer: try this js code where edit_td class applied to every td and active class is there on a active td and blur function is bind to the td having "edit_td" and "active" class applied on them.
$('.edit_td.active').on('blur', function(e) {
       $('.active').remove();
    });

Comment: Add some explanation to code so that it is helpful to OP
Comment: @CasperSky explanation added.


Given series $a_n$ converges absolutely, then how to prove series $\log(1+a_n^4)$ converges

Question: Given series $a_n$ converges absolutely, then how to prove series $\log(1+a_n^4)$ converges.
Which test should I use?
Thanks for helping.
Comment: Hint:$$\log(1+x)\sim x$$ for small $x$.
Comment: Soi have to prove if $a_n$ is convergent then $a_n^4$ is convergent
Comment: yes and it is trivial.
Comment: @Vim how is it trivial?
Comment: well, $\sum a_n$ converges *absolutely* implies $|a_n|\to 0$, which again implies $|a_n|^4<1^3|a_n|$ for $n$ large enough, then...
Comment: Did you mean that $\sum_n a_n$ converges absoulutely?
Answer: Hint 1: if $\sum\limits_{n=1}^\infty a_n$ converges, then $\lim\limits_{n\to\infty}a_n=0$.
Hint 2: $\lim\limits_{x\to0}\frac{\log(1+x)}x=1$.
The Comparison Test should work.
Comment: Alternatively: $0 \le \log(1+x) \le x$ for $x \ge 0$.
Comment: @Vim: the other language (series, absolute convergence) indicated a series, not a sequence.
Comment: Would the downvoter care to comment?
Comment: OP just says $a_n$ converges, not $\sum a_n$ I think.
Comment: @Vim i meant the summation one, wrote series
Comment: @SophieClad then you should use $\sum$
Comment: @robjohn Altight. Though I think it will be less ambiguous with a $\sum$ notation
Answer: We have from the absolute convergence of the series $\Rightarrow$ $|a_n| \to 0 \Rightarrow |a_n| \leq 1, n > N\Rightarrow |a_n|^4 \leq |a_n|, n > N\Rightarrow \log(1+a_n^4) \leq a_n^4 \leq |a_n|$, and the comparison test can be used to conclude.


Justin is setting a password on his computer. He is told that his password must contain at least 4 but no more than 6 characters.

Question:
Justin is setting a password on his computer. He is told that his password must contain at least 4 but no more than 6 characters. He may use either letters or numbers (0–9).
  How many different possibilities are there for his password if each character can only be used once?
  Suppose that Justin's computer randomly sets his password using all of the restrictions given above. What is the probability that this password would contain only the letters in his name?

I have some doubt about the second question. I know that the  probability that a randomly chosen password would include only the letters from Justin's name should be found. I think it should be $6!+5!+4!$, while the correct answer is $6!$ and I do not know why. Could anyone explain this?
Comment: The probability is $6!$? That's a serious problem. Formatting tips [here](http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: If your password must have at least $4$ characters and $6$ at most, it can either have $4, 5$ or $6$. I am assuming you are using the alphabet abcdefghijklmnopqrstuvwxyz which has $26$ letters. Adding the numbers $(0, ..., 9)$ you have $36$ possible characters.
Let's calculate separately how many passwords contain $4$, $5$ and $6$ passwords.
Let us build a password with $4$ characters. For the first character there are 36 possible options. You pick some character and you are left with 35. For the second character, you have 35 options, so there are $36\times35$ ways of building a password with 2 characters. You still have 34 characters left so there are $36\times35\times34$ unique passwords with 3 characters, and with no repeated characters. Since 33 characters are left, we pick the last one and get a password with 4 characters. Hence there are $36\times35\times34\times33$ passwords with 4 characters.
Repeating for 5 and 6 characters we get a total of $36\times35\times34\times33\times32$ 5-character passwords and $36\times35\times34\times33\times32\times31$ 6-character passwords.
We add the totals up to $36\times35\times34\times33\times32\times31 + 36\times35\times34\times33\times32 + 36\times35\times34\times33 = \frac{36!}{30!} + \frac{36!}{31!} + \frac{36!}{32!}$
Now on to the second question. How many passwords contain only the letters of his name? Since all letters in his name are unique and his name has 6 letters, then such a password can only be a permutation of his name. There are $n!$ permutations of $n$ unique objects.
Since you are talking about probability, it should be
$$P(password\ with\ letters\ in\ justin) = \frac{passwords\ that\ satisfy\ your\ criteria}{total\ number\ of\ passwords}$$
Hence the probability is
$$\frac{6!}{\frac{36!}{30!} + \frac{36!}{31!} + \frac{36!}{32!}}$$
Comment: Thank you! Your answer is very helpful.


Avoid update data outside of repository

Question: I would like to know what's the correct way of updating a data inside a service layer or repository and avoid to make changes to the object outside service/repository.. example:
public class PersonRepository{
     public class Insert(Person person){
          //code
          _db.SaveChanges();
     }
}

public class TaskRepository{
     public class Insert(Task task){
          //code
          _db.SaveChanges();
     }

     public void Update(Task task){}
}

and an example code in controller:
public ActionResult Insert(Task task)
{
     _taskRepository.Insert(task);

     task.Title = "foo";

     _personRepository.Insert(new Person()); //here the problem!
}

when I save a new person automatically entity will update the title of task!!!
So how can I control it? I want deny insert/update outside the main repository(in this case, task MUST the inserted/updated only inside the taskRepository).
Should I disable proxy? or change tracking? or else?
Answer: It looks like the repositories are sharing a a DBContext. Therefore calling  _db.SaveChanges(); in the PersonRepository will cause the DBContext object to save all changes made to entities it is tracking - this includes the task object.
There are various ways to avoid this, but wrapping the DBContext object in a using statement will ensure it is disposed after it performs its job and will not be tracking the objects it has returned.
public class TaskRepository
{
     public class Insert(Task task)
     {
          using(var db = new YourContext())
          {
              //code here
              db.SaveChanges();
          }
     }
}

Note that this can have performance implications as creating and destroying DBContexts can be expensive.
Comment: I see. have you thought about call the DbContext Detach() method after SaveChanges, this would stop EF tracking the entity after it has been saved.
Comment: thank, I thought it, but in my project I would like to use unit of work, so I can't do this. +1 anyway.
Comment: Yes :) but is a bit boring isn't?

Avoid update data outside of repository


Analyzing function $\;y=\large\frac{(x-a)^2(x+a)^2}{(x-a)}$

Question: Which of these statements about this function is true?
$$y=\frac{(x-a)^2(x+a)^2}{(x-a)}$$

There is a hole at $x=a$.
There is a repeated zero at $x=-a$.
The function "behaves" like $y = x^4$ (is even, etc...)

I know the first statement is true, are the others true too? thanks!
Comment: Do you mean to state "there is a hole" and "there is a repeated zero"? I still don't understand what 3. is supposed to mean.
Comment: correct. and I think 3 means that since y=x^4 is even, then the function is also even. I'm not sure if they funtion is even or odd though. I think it is odd though
Comment: What does "end behaviour" mean?
Comment: whether the function is odd or even
Answer: Hints:

Simplify (canceling terms), presuming $x \neq a$ (where the function is undefined - i.e., "where there is a hole"). For help with simplifying, scroll over the "grey" box below.

 $$\displaystyle y=\frac{{(x-a)^2}(x+a)^2}{{(x-a)}} = (x-a)(x+a)^2,\quad x\neq a$$

What is the value of $\,y\,$ when $\,x = -a\,?\;$ How many factors of $\,(x + a)\,$ does the function have? So how many zeros at $x = -a$?
Expand the factors (multiply the factors) to determine whether the simplified function is even or odd (is it anything "like $y = x^4$"?).

 $$\quad(x-1)(x+1)^2 \;=\; (x - 1)(x^2 + 2x + 1) \;=\;\;$$?

Also helpful when investigating a function like this (where $a$ is not necessarily known): let $a$ be some value, say $\,a = 1,\,$ and $\,a = -1.\;$ Then graph each of these functions; that may help you visualize what's going on.
Comment: Thank you for your help! So (if I did this right), I did get a hole at x=a. I got zeros at x=a and x=-a (twice), so is that considered a repeated zero? And, the highest power is x^3, which would mean that the graph is not like x^4, right?
Comment: Everything correct, except "zero at x = a". As you note, there is a "hole" at $x = a$: where the function is undefined. So $x = a$ cannot be a "zero". But there are repeated zeros at $x = -a$, and correct, the function is not like $y = x^4$!
Comment: +1 it is so funny to me that the notation gets hide. ;-)


auto submit won't run

Question: edit: change of question
if my code is like this:
<form name="login" action="https://login.extremebb.net/login" method="post"

                >

                <input type="hidden" name="dst" value="/status.html" />

                    Username:

                    <input class="field" type="text" name="username" value="" size="23" />

                    Password:

                    <input class="field" type="password" name="password" size="23" />

                    <input type="submit" name="submit" value="Login" />

                <input type="hidden" name="redirect_to" value="/status.html"/>

                </form>

what should i do to make it auto submit after page load or a set of time?
note: saved username and password in browser
Comment: You want the form to be submitted as soon as the page loads?
Comment: yes, i want it to be submitted as soon as the page loads. there is something i want to try about it
Comment: Would you like to have jQuery solution?
Comment: llia Rostovtsev, by how you mean? i prefer a clean solution such as the line i used in the code
Comment: jQuery has a .ready() event, which means to fire it right after the page (DOM) loads
Comment: If using as document.subfrm, Form must have id attribute
Answer:

    <form name="subfrm" action="../New%20folder%20(3)/success.html">
        <input type="hidden" name="dst" value="/success.html" />
        Username:
        <input class="field" type="text" name="username" value="" size="23" />
        Password:
        <input class="field" type="password" name="password" size="23" />
        <input type="submit" name="submit" value="Login" id="submit" />
        <input type="hidden" name="redirect_to" value="../New%20folder%20(3)/success.html"/>
    </form>

Answer: I think your error is at your submit button which has name="submit"! Changed it to ANYTHING_ELSE and worked!

    <form name="subfrm"  action="../New%20folder%20(3)/success.html">
    <input type="hidden" name="dst" value="/success.html" />

        Username:

    <input class="field" type="text" name="username" value="" size="23" />

        Password:
    <input class="field" type="password" name="password" size="23" />
    <input type="submit" name="ANYTHING_ELSE" value="Login" />
    <input type="hidden" name="redirect_to" value="../New%20folder%20(3)/success.html" />
    </form>

Answer: you can click the submit button manually, but you need to give it an id to use getElementById.  I am not sure, but I think the document.[name of element] is not cross browser compliant.

        <title></title>

    <form id="subfrm"  name="subfrm" action="/Quantifi/" >
        <input type="hidden" name="dst" value="/success.html" />
        Username:
        <input class="field" type="text" name="username" value="" size="23" />
        Password:
        <input class="field" type="password" name="password" size="23" />
        <input type="submit" id="submitButton" name="submit" value="Login" />
        <input type="hidden" name="redirect_to" value="/Quantifi"/>
    </form>

Edit: as others have mentioned, naming your submit button "submit" also causes problems.  If you give the button and id/name of something else, the following would work on the onload event:

auto submit won't run


Map User input in Scala, is there any good way for taking user input for Map Elements?

Question: I am trying to take String key and Boolean values from user, by below method, is there any better way of doing it?
<code>val sc = new Scanner(System.in)

println("Please enter First User Name and Boolean value")

val sc1:String  = sc.next();
val sc2:Boolean = sc.nextBoolean()

println("Please enter Second User Name and Boolean value")

val sc3:String  = sc.next();
val sc4:Boolean = sc.nextBoolean()

println("Please enter Third User Name and Boolean value")

val sc5:String  = sc.next();
val sc6:Boolean = sc.nextBoolean()

val map:Map[String,Boolean] = Map(sc1->sc2,sc3->sc4,sc5->sc6)
</code>
Answer: Sure.
<code>    println("Please enter names and values separated by `=`, each pair on its own line. Press ^D when done.")
    val map = Source
       .fromInputStream(System.in)
       .getLines
       .map(_.split("="))
       .map { case Array(a,b) => a -> b.toBoolean }
       .toMap
</code>


In the ring of Gaussian integers $\mathbb{Z}[i]$, show that $2\in J$ where $J$ is the ideal $\langle i + 1\rangle$

Question: In the ring of Gaussian integers $\mathbb{Z}[i]$, show that $2 \in J$ where $J$ is the ideal $\langle i + 1\rangle$.
My thought was that $(1+i) \in J$ and $(1-i) \in \mathbb{Z}[i]$. Then if $\langle i + 1\rangle$ is an ideal, then $$\forall j\in J:\forall k\in \mathbb{Z}[i] :jk\in J\land kj\in J.$$ So it must be that $2 = (1+i)(1-i) = (1-i)(1+i) \in J$.
My problem is that when I list the elements of $\langle i + 1\rangle$, I don't see $2$.
Any help is appreciated finishing this.
Comment: @Nid: Those are the powers of $i+1$, which are certainly elements of the ideal $\langle i+1\rangle$... but the ideal $\langle i+1\rangle$ is comprised by all ***multiples*** of $i+1$, not just the powers. For example, the ideal $\langle 3\rangle$ in the ring $\mathbb{Z}$ consists of
$$\langle 3\rangle=\{\ldots, -2\cdot 3 = -6,\;-1\cdot 3=-3,\;0\cdot 3 =0,\;1\cdot 3 = 3,\;2\cdot 3=6,\;\ldots\}$$
not
$$\langle 3\rangle=\{3^1=3,\;3^2=9,\;3^3=27,\;\ldots\}\quad \textbf{(incorrect)}$$
Comment: I don't know what you mean by list. Certainly since  $(1+i)(1-i)=2$, it follows  that $2\in J$.
Comment: @Nid What Zev has said above is correct. You have listed the powers, not the entire ideal. The ideal may be related to the set of powers in some manner but it certainly is not equal. Maybe you are confusing the cyclic group notation with the ideal notation.
Comment: How did you list the elements of $\langle 1+i \rangle$? $2$ must have appeared somewhere, because your first part is correct.
Comment: What do you mean by ''list the elements of $\langle i+1 \rangle$? This is an infinite subset of $\mathbb{Z}[i]$, so I'm not sure what you wrote down. Regardless, your proof looks fine, if a bit on the verbose side...
Comment: @астонвіллаолофмэллбэрг $ = \{ (i+1)^1 = (i+1),(i+1)^2 = -1 +1 -2i = -2i, (i+1)^3 = 2 -2i...,   \}$
Comment: @ZevChonoles Oh ok. I see. So then what are the elements of the ring $⟨i+1⟩$?
Comment: @Nid: All the multiples of $i+1$ in the ring $\mathbb{Z}[i]$. That is, all of the Gaussian integers that can be produced by
$$(a+bi)\cdot (i+1)$$
for some $a+bi$ comprise the ideal $\langle i+1\rangle$.
Comment: @ZevChonoles Ok I see. My issue was with notation then. When I learned abstract algebra, in group theory, $<>$ referred to powers but apparently, it as a ring is different. Thank You everyone so much.
Comment: The user @астонвіллаолофмэллбэрг seems to have found the source of confusion, the notation $\langle x\rangle$ can be used for "cyclic subgroup of a group $G$ generated by $x\in G$" and for "the ideal of a ring generated by $x\in R$".
Answer: Whatever you're doing to list the elements of $\langle 1+i\rangle$ is incorrect, since everything else you wrote is the completely correct argument as to why $2\in\langle 1+ i\rangle$.
Answer: To "list" the elements, you have to use the ring $R=\mathbb{Z}[i]$, and not only $\mathbb{Z}$, or only the powers. There is no integer-mutiple of $(i+1)$ which is equal to $2$, but there is indeed an element $x\in R$ with $r(i+1)=2$, namley $x=1-i$.


How to write user defined options in shell script?

Question:
Possible Duplicate:
Using getopts in bash shell script to get long and short command line options

This is the code i've written
#! /bin/bash

getopts master $1

while getopts ":master" opt; do
  case $opt in
    master)
      echo "-master was triggered! $1 was entered" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

and this is the output i'm getting-
]$ ./test123.sh -master 123
./test123.sh: line 3: getopts: `-master': not a valid identifier

How do i define a user defined option?
Answer: I think there are a couple of problems.

I don't understand what this (getopts master $1) is doing and you can remove it
I think you need single char arguments (i.e. -m vs -master)

e.g. the below seems to work:
#!/bin/bash
while getopts ":m" opt; do
  case $opt in
    m)
      echo "-m was triggered! $1 was entered" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

Comment: when i run the script the output i get is `-m was triggered! -m was entered`, but i want the output to be `-m was triggered! 123 was entered`
Comment: got it. i must writ it as `echo "-m was triggered! $2 was entered" >&2`


Ler e exibir um PDF dentro de uma pasta zipada sem extrair ela

Question: É possível fazer isso ou eu realmente tenho que extrair o arquivo antes para depois lê-lo?
No meu código estou fazendo assim:
  string zipPath = @"C:\Users\Analistas\Desktop\ZipFile.zip";

        using (ZipArchive archive = ZipFile.OpenRead(zipPath))
        {
            var sample = archive.GetEntry("PdfFile.pdf");
            string pdfContent = ReadPdfFile("PdfFile.pdf");
            if (sample != null)
            {
                using (var zipEntryStream = sample.Open())
                {
                    MessageBox.Show(pdfContent);
                }
            }
        }

E o método para ler PDF:
        public string ReadPdfFile(string fileName)
        {
            StringBuilder text = new StringBuilder();

            if (File.Exists(fileName))
            {
                PdfReader pdfReader = new PdfReader(fileName);

                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                }
                pdfReader.Close();
            }
            return text.ToString();
        }

Não está exibindo nada.
Comment: acredito que pelo `fileName`, teria que extrair um stream e constuir um clone do pdf a partir dele.
Answer: É possível ler o pdf que está dentro de uma pasta zipada sem ter que extraí-lo.
Basta instanciar o objeto PdfReader usando o objeto Stream do arquivo desejado.
var pdfReader = new PdfReader(ZipFileStream);

Uma sugestão seria alterar o seu código para passar o objeto Stream para o método ReadPdfFile
var archive = ZipFile.OpenRead(zipPath);
var sample = archive.GetEntry("PdfFile.pdf");
var zipEntryStream = sample.Open();

var pdfContent = ReadPdfFile(zipEntryStream);

E o método ReadPdfFile deve ser alterado para ler objeto Stream.
public string ReadPdfFile(Stream fileStream)
{
    ...
    PdfReader pdfReader = new PdfReader(fileStream);
    ...
}


Getting Node.js/Geddy app set up with CoffeeScript support

Question: Just getting started with Node.js and I'm using the Geddy framework (I like the similarity to Rails). But I'm having some trouble getting it to work properly with CoffeeScript. I see Geddy is now "supporting" coffee files. But when I start converting even the default js to coffee, I get errors:
/usr/local/lib/node_modules/geddy/lib/app.js:108
      ctor.origPrototype = ctor.prototype;
                               ^
TypeError: Cannot read property 'prototype' of undefined
at _registerControllers (/usr/local/lib/node_modules/geddy/lib/app.js:108:36)
at async.AsyncBase.runItem (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:108:10)
at async.AsyncBase.next (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:113:12)
at async.AsyncBase.execCallback (/usr/local/lib/node_modules/geddy/node_modules/utilities/lib/async.js:148:54)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

I have CoffeeScript installed, but I don't really know what else I'm supposed to do here. The documentation on this is pretty much non-existant.
Any idea what I'm missing here?
Comment: Try search issues https://github.com/mde/geddy/issues , wiki
https://github.com/mde/geddy/wiki/_pages
Comment: Thanks, Paul. I've already looked through it, no dice.
Comment: Looks like you're not exporting your controller. Maybe paste your code?
Look at the [example](https://github.com/mde/geddy/blob/master/examples/todo_app_coffee/app/controllers/main.coffee)
Answer: Have a look at geddy-coffee-templates. You can create a new base app from coffeescript. Adding a model and controller is working now, but the scaffold and resource generators are not working at the moment.
For an existing app, simply add a dependency to coffee-script on your package.json file. (Example). Then npm install.
Answer: this question is probably a bit old but I just ran into this problem.
In my case, all I did was added a controller file called fruits.js but inside my fruits.js I defined it as:
var Fruit = function () {

...

};

exports.Fruit = Fruit;

The problem is in the naming of the file and the actual variable name not matching.
In my case, the simple fix was:
either rename "Fruit" to "Fruits"

or
change the file name from "fruits.js" to "fruit.js"

So the lesson learned is Geddy expects the controller file name to match the actual variable definition inside the file.
Hope you were having the same problem.


Clarifying the relation between Device Pixels & CSS pixels

Question: This question presumes: device-pixels are absolute (fixed, not relative to anything).
Following reading this article,

My device (MacBook Pro 2019) has a pixel ratio of 2 (2 device pixels in every CSS pixel when zoom-level 100%; calculated by .devicePixelRatio). At 100% zoom-level, CSS pixels (as measured with .innerWidth) are the same as device pixels (as measured with screen.width & Cmd + Shift + 4 + click). I was expecting CSS pixels to be half the value of device pixels.

Why does MDN say CSS pixel is an absolute value when zooming in actually increases the size of a CSS pixel (by increasing the amount of device pixels it equals to)? Why is this in MDN?
Comment: How do you know "My device (MacBook Pro 2019) has a pixel ratio of 2"? At 100% zoom level, one device pixel equals one css pixel.
Answer: In your case the scaling is done at the OS level, so everything will "lie" because your OS is set to lie to every applications, including the browsers.
The window.screen.width value will be the one reported by your OS, but in your system preferences, it says that you want the resolution of your display to be set to half of its real resolution, that's what you'll get.
So even these values are not device pixels, but some kind of CSS pixels (well window.screen.width is really 'CSS pixels', the one from the ScreenShot app isn't).
However, while "lying" about the number of pixels, it correctly exposes the pixel density (number of physical pixel used per px). That's what you'll have in window.devicePixelRatio when the browser doesn't apply any zoom by itself.  Unfortunately, we don't know when the browser applies such a zoom, so as web-devs, we can't know the OS pixel density, nor the true resolution of the device.

As for the second point, I will assume you asked why MDN says CSS pixels are absolute rather than relative as written in your question.
This doesn't mean that a CSS pixel will always have the same physical dimension outputted (which is impossible btw, think of a video-projector), it's in contrast with relative lengths like %, em, vw, etc. which are relative to an other length.
CSS pixels are absolute in that they don't rely on any other length, even though the physical output may vary.
Comment: Okay, thanks. They're same as CSS pxs when 100% zoom. And they seem to represent device pixels (with OS' 'lie').
Comment: 1. what does the screenshot app measure? 2. Interesting point in how `devicePixelRatio` does change based on zoom but as developers have no way of knowing when a user zooms. This might explain my observation that web-developers don't really account for when a user zooms that much. The only thing I've seen is that you don't set `font-size` just in viewport dimension (like `vh` or `vw`) otherwise it'll never get bigger. 3. Okay, they don't vary based on any other length but do vary on zoom. I can accept that.
Comment: The screenshot app measures the OS px values, which are not CSS pixels because these are just relevant in the context of a web page that knows about CSS, but which are a very similar concept.


Where is source code of advanced search form?

Question: I can't find where in Drupal 7 search module is the source code of advanced search form that appears on search result site.
Below is code of search_form. You can see there is basic key in renderable array. In output of dpm is even advanced key, but i can't find from where it comes.
It should be probably somewhere in search module, but it is not big module and i checked it last 4 hours and can't find it.
function search_form($form, &$form_state, $action = '', $keys = '', $module = NULL, $prompt = NULL) {
  $module_info = FALSE;
  if (!$module) {
    $module_info = search_get_default_module_info();
  }
  else {
    $info = search_get_info();
    $module_info = isset($info[$module]) ? $info[$module] : FALSE;
  }

  // Sanity check.
  if (!$module_info) {
    form_set_error(NULL, t('Search is currently disabled.'), 'error');
    return $form;
  }

  if (!$action) {
    $action = 'search/' . $module_info['path'];
  }
  if (!isset($prompt)) {
    $prompt = t('Enter your keywords');
  }

  $form['#action'] = url($action);
  // Record the $action for later use in redirecting.
  $form_state['action'] = $action;
  $form['#attributes']['class'][] = 'search-form';
  $form['module'] = array('#type' => 'value', '#value' => $module);
  $form['basic'] = array('#type' => 'container', '#attributes' => array('class' => array('container-inline')));
  $form['basic']['keys'] = array(
    '#type' => 'textfield',
    '#title' => $prompt,
    '#default_value' => $keys,
    '#size' => $prompt ? 40 : 20,
    '#maxlength' => 255,
  );
  // processed_keys is used to coordinate keyword passing between other forms
  // that hook into the basic search form.
  $form['basic']['processed_keys'] = array('#type' => 'value', '#value' => '');
  $form['basic']['submit'] = array('#type' => 'submit', '#value' => t('Search'));

  return $form;
}

Answer: The advanced form is altered in node.module and not in search.module. you can find the below function for advance search in node.module, Please have a look in the below hook:
 function node_form_search_form_alter(&$form, $form_state)


How do I stop my  404 "ExecuteURL" mapping from breaking my form?

Question: I've got a custom 404 page, and I'm having a problem where the 404 mapping breaks a form on that page.
I've configured my site to execute and return my custom 404 page on every page not found:
 <httpErrors existingResponse="Auto">
      <remove statusCode="500" subStatusCode="-1" />
      <remove statusCode="404" subStatusCode="17" />
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" prefixLanguageFilePath="" path="/404.aspx" responseMode="ExecuteURL" />
      <error statusCode="404" subStatusCode="17" path="/404.aspx" responseMode="ExecuteURL" />
      <error statusCode="500" path="/500.aspx" responseMode="ExecuteURL" />
 </httpErrors>

My master page includes a form wrapping all content:
<form runat="server">

If I go to /xyz (i.e. not a real page), the form action is given as pointing to that non-existing page:
<form method="post" action="xyz?404%3bhttp%3a%2f%2fsite.example.com%3a80%2fsite%2fxyz" id="ctl01">

So if I submit a postback (e.g. a button onclick) on that page, the postback is POST'ed to /xyz  – which, of course, isn't an actual page, so we get redirected to our 404 before form processing takes place. As a result, the onclick never gets called.
I'm guessing that I need to somehow force the form action to point at the actual page (/404.aspx) instead of the missing page (/xyz) – but how do I do that?
Comment: Why does your 404 page have a postback option?
Comment: @MikeSmithDev: it's the "search" form in the header. I'd really like it to work, because I'm assuming that one of the first things users are going to do when they hit a 404 page is to search the site for what they were originally looking for.
Answer: From your comment, your problem is with a site-search form on your master page.
I would recommend you move that site-search form outside of the form tag with runat="server". Here is why:

The new form will then always submit to your search page (or I've done it where it executes a JavaScript function).
This will fix any issues you have with people pressing "enter" and it submitting the wrong form. This way, "enter" on the search form will submit the search form, and "enter" on a form inside the form tag with runat="server" will submit that form... and you don't have to mess around with default buttons or catching enter-button presses.

Side note: You can have multiple forms on a page, just not a form within a form, and you can't have two forms with runat="server" on them.
Comment: Thanks @MikeSmithDev, this was good advice. I've moved the search form out of the form runat server, and that's solved my problem.
Answer: Another option which I found that works is to just redirect the forum action to the correct URL. Quick and easy solution.
Form.Action = "/500.aspx"


Profile Completeness reminder to the user

Question: Hi i need to send an mail reminder to the user whoever not been completed the profile information. Is there any module available  for this? or how do i do this?
Can we do this using rules?
Answer: You could take a look at Profile Complete Percent (for core Profile module) Content Complete (if using Content Profile).
If you are using Content Profile, here is an article to assist setting up with Rules: Measure node completion in Drupal, part 3.  I'm sure you could probably get a Rules workflow going with core Profile module as well.
Comment: Thanks Laxman13. `Content Complete` worked for my requirements.
Answer: If you are using Drupal 7 (for the benefit of those coming to this at a later date) you can use the Field Complete module. It has Views and Rules support as well as additional Field module integration. (For the sake of transparency, I wrote it.)
Answer: I would build a module that checks the db tables to see if they dont have the default values in them.
If the default value exists, then setup mailing on cron to send reminder mail. just be careful cause if you run cron 10 times in a day that could get very irritating for you users ;)


Pop-up calendar option does not display when I add Date field in webform

Question: I am using Date and Calendar module. When I add a component to webform, I selected the Date field > click Add. But I do not see the Pop-up calendar option. However, when I add a content type (structure > Add content > I see the Pop-up calendar option display for the date field).
How I can display the pop-up calendar option when I add Date component to webform?
Answer: The Popup Calendar option in Webform is entirely separate from the Date module, so it should always work regardless of whether you have installed Date module (or Date Popup module).
Make sure you've added a date component to your Webform, then under "Display" there is a checkbox for "Enable popup calendar". This option is enabled by default. Now a little calendar icon should appear next to your date component when viewing the node.
Comment: Instead of the default select options for date, month and year, is it possible to use a text field along with pop-up?


Using page field value in a metatag in

Question: I would like to edit my html.html.twig template to assign a value to a metatag in  according to the value of a field of a page. Is that possible?
I was trying things like {{ page.myfield.value }}, but with no success and haven't found anything helpful online.
Comment: Is the field part of a node?
Comment: The field is a part of a page / content type that is being displayed, if that is what you mean.
Comment: Content types are nodes, so yeah, that answers my question. I'll post an answer below.
Answer: You need to attach the tag in hook_node_view() (which is derived from hook_ENTITY_TYPE_view(), when the view mode is full (which makes the assumption that the full view mode is only ever used on node pages).
You can do that as follows:
function hook_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $mpde, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode)
{
  // Check if the view mode is full
  if($view_mode == 'full')
  {
    // Create the tag. You can set the content of the
    // metatag from the node
    $tag = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'name attribute of metatag',
        // Note that 'value' will differ depending on the
        // field type.
        'content' => $node->get('field_something')->value,
      ],
    ];

    // Attach the meta tag to the header.
    $build['#attached']['html_head'][] = [$tag, 'some_key_to_represent_tag'];
  }
}

Comment: You cannot use the function name hook_node_view(), you need to alter it for the module/theme in which it resides, according to Drupal hook naming conventions: https://www.drupal.org/docs/7/creating-custom-modules/understanding-the-hook-system-for-drupal-modules
Comment: This looks good, thank you. Sorry for asking basic questions, but I have added to my mytheme.theme changed the 'name' appropriately, as well as the 'field_something', cleared the drupal caches, but still nothing. Is there any step I'm missing?
Comment: Still nothing :-( I have put the code with my adjustments here: https://codeshare.io/5vANrK. I'd be really grateful for any help fixing this.
Comment: yes, I renamed the function to mytheme_hook_node_view, where mytheme is the right name of my theme, but still no difference, the metatag does not appear in the code (of course, clearing caches)
Comment: It should be THEMENAME_node_view(). Remove 'hook'.
Comment: Silly mistake. I did that, but still nothing.
Comment: Looks fine to me. Time to do some debugging. Is your function even called?

Using page field value in a metatag in


Number of colorings using inclusion–exclusion principle

Question: Let's say there are $21$ possibilities to color an object using an inventory of the colors red, green and blue. (By 'inventory' I mean that we don't have to use all three colors, we can also only use 1 or 2 of these colors.)
And let's say there are $6$ possibilities to color this object for each inventory of 2 of the above colors. (so $6$ possibilities for the inventory consisting of red+green, 6 possibilities for the inventory consisting of red+blue, 6 possibilities for the inventory consisting of green+blue)
I want to determine the number of colorings using

(a) exactly 3 colors
(b) at least 2 colors

(a)
Let
$A...$ set of all colorings using an inventory consisting of the color red
$B...$ set of all colorings using an inventory consisting of the color green
$C...$ set of all colorings using an inventory consisting of the color blue
So we have $$|A|=|B|=|C|=1\\|A\cap B|=|A\cap C|=|B\cap C|=6\\|A\cap B\cap C|=21$$
My solution is $1+1+1-6-6-6+21=6$. Is that correct?
For (b) my idea was to compute the number of colorings using exactly $2$ colors and add it to my solution of (a). How can I compute the number of colorings using exactly $2$ colors using the inclusion-exclusion principle? I thought we have $1+1+1-6-6-6$ but this is obviously wrong.
Answer: Your mistake is in how you have defined the sets. You write $|A| = |B| = |C| = 1$. If $|A| = 1$, how is $|A \cap B| = 6$ possible when $A \cap B \subset A$?
For $(b)$, you can simply subtract number of ways to color with exactly one color which is $3$. So the answer to $(b)$ is $~21 -3 = 18$.
Given the question, I would define $A$ as set of all colorings with exactly one color, $B$ with exactly two colors and $C$ with exactly three colors. Note they are disjoint sets.
$|A| + |B| + |C| = 21$
$|A| = 3,  ~ |B| = 3 \cdot (6 - 2) = 12$
$|C| = 21 - 12 - 3 = 6$
Answer to $(b)$ is,
$|B| + |C| = 12 + 6 = 18 ~$ or $~21 - |A| = 18$


Using GET parameters with clean urls

Question: I have module where I'm creating a custom path in hook_menu. When the user visits this page, they are supposed to be redirected to another site, with GET query parameters attached to the redirect URL. So for instance, if they visit http://mysite.com/site-search?query=blah, we are supposed to redirect them to http://othersite.com/different-path?query=blah.
However, we have clean URLs enabled; while I can hit the page http://mysite.com/site-search, it gives a page not found when I try to hit http://mysite.com/site-search?query=blah.

The requested page "/site-search?query=blah" could not be found.

I tried adding another path for site-search/%, just to get that extra part of the URL, but that didn't work either.
Am I able to get the URL parameters while using clean URLs?
Edit: Here's the code:

function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  // testing to see if this will allow me to capture get parameters
  // in the form http://site.com/site_search/q=blah
  $items['site_search/%'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  return $items;
}

function my_redirect_redirect() {
  // see if we can get the get paramters
  return "
" . print_r($_SERVER,1) . "
";
}

Edit 2 In my example, I transcribed the query string in correctly. It looks like it's a conflict between drupal wanting to use ?q= for its menu routing, and our search host URLs also using ?q= for their queries. If I do query=blah, I am able to hit the page.
Comment: May you show the code used by the module? Without seeing it, it is not possible to say what is wrong. I am not clear why you are making an example for http://mysite.com/site-search?query=blah, but the error message is for /site-search?q=blah.
Comment: @Kiamlaluno in writing this question I transcribed my query strings incorrectly. It appears to be a conflict with both the drupal site and our search host wanting to use `?q=`.
Answer: I use $_GET variables as needed in my clean-url installs without issue. Views uses $_GET variables, too. Drupal uses $_GET['q'] so you don't want to use that ID, but you should be able to do something like:
function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_redirect_redirect() {
  return $_GET['query'];
}

This is working for me locally. The 2nd item you present in hook_menu only matches for /site_search/foo?query=bar so you only want the first. Be sure to set the 'type' property as well.
Answer: Sorry to be VERY late to the party. For anybody still looking for the answer:
function my_redirect_menu() {
    $items['site_search/%'] = array(
      'title' => 'Edit Product Details',
      'page callback' => 'my_redirect_redirect',
      'page arguments' => array(1),
      'access arguments' => array('access content')
    );
}

function my_redirect_redirect($id) {
   return t("your url % value was:".$id);
}

Using GET parameters with clean urls


Linking content types

Question: Can someone please tell me if this is possible? I have 2 content types, with the following fields.

Asset

Title
Serial Number
Model

Event

Title
Event Type (taxonomy)
Asset ID (a plain text field used to store links to Asset nodes)

Is there a way in views 3 to create a view that looks like Asset Title : Asset Serial Number : Asset Model : Event Type, basically a view linking both content types on one line. I've heard you need to use relationships, but I can't seem to get anything working.
Answer: A better way to do it is replacing the asset ID field with an entity reference field which refers to the other content type (Asset) and use view relations to get the relation. In short, create a relation between the content types, and you will be able to use view relations.
For advanced uses, you can take a look to the Relation module, which I don't recommend, in your case.
Answer: You need to create an event view with the asset ID as relationship.
Then, add the field Asset serial number and select the right relationship, which should be below or above the Label setting.
I don't think this is the best option. It could be really performance consuming.
First you need to create an event field view with event type and asset ID (the asset ID should be excluded from display). Go into the view folder, open theme,  copy the views-view-unformatted.tpl.php file and paste it into you theme folder with the other template files (sites/all/theme/YOURTHEME/template).
In the third column, click on theme and look for the style output (views-view-unformatted.tpl.php). There will be many of this. Use the more specific for that view (usually the last one), something like views-view-unformatted--event--page_1.tpl.php.
Rename the file you copied in your template. Create an asset field view with the serial number and the node ID as contextual filters.
This is how a views-view-unformatted.tpl.php file looks like.
<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $row; ?>

<?php endforeach; ?>

You should modify it in this way
    <?php if (!empty($title)): ?>

<?php print $title; ?>

    <?php endif; ?>
    <?php foreach ($rows as $id => $row): ?>
      <div class="<?php print $classes_array[$id]; ?>">

        <?php print $row;
print views_embed_view('ASSET_VIEW', 'page_', $view->result[$id]->YOUR_FIELD);
?>

    <?php endforeach; ?>

Test it.
print views_embed_view('ASSET_VIEW', 'page_', $view->result[$id]->YOUR_FIELD); will print the asset view. $view->result[$id]->YOUR_FIELD will print the asset ID from the event view.
Comment: Thanks for the response, however I'm not sure what you mean by 'select the right relationsip'. All I see is Create Label , Label, Place a colon after label, Exclude from display, Formatter?
Comment: Is the ID Asset field a node reference type?
Comment: Nope plain text and I don't think I can convert it now that the content is in, right?
Comment: I'm not sure you can convert it from text to node reference. Probably you should create a new one.
Comment: Yeah that's not really an option with 50,000 nodes unless there is a way to automatically move the data from the text field to the node reference field.

Linking content types


Scaling odds ratios and converting them to probability

Question: I'm trying to calculate a scaled odds ratio and convert them into percentages for an analysis I am doing.
I have just one independent variable in the model, SAT score. Dependent variable is college acceptance. The SAT score is in 1-point increments, so odds ratio calculated was for 1-point change.
However, I want to make this into something more interpretable in real life. The odds ratio for 1-point change in SAT score was 1.08.
How do I calculate the odds ratio for 10-point or 25-point increase in SAT score?
My understanding is just raising OR to the power of the point increase, i.e. 1.08^10 and 1.08^25.
Can I convert the odds ratio into percent change in college acceptance for a 10 or 25-point increase in SAT score?
Thank you.
Answer:
How do I calculate the odds ratio for 10-point or 25-point increase in
SAT score?

From your question, I assume you have the following logistic model:
$$
\mathrm{logit}(\texttt{Acceptance})=\beta_0 + \beta_1\texttt{SAT_score}
$$
The odds ratio for one unit increase in $\texttt{SAT_score}$ is $\exp(\beta_1)$, where $\beta_1$ is the coefficient for $\texttt{SAT_score}$ on the log-odds scale. The odds ratio for $u$ units increase in $\texttt{SAT_score}$ is $\exp(\beta_1\cdot u)$. So for $u=10$ or $u=25$, you have $\operatorname{OR}_{10}=\exp(10\beta_1)$ and $\operatorname{OR}_{25}=\exp(25\beta_1)$.

Can I convert the odds ratio into percent change in college acceptance
for a 10 or 25-point increase in SAT score?

Not in general, no. Remember that the logistic regression fits a logistic curve on the probability scale which looks like this:

You see that the probability increases by different amounts for a 1-unit increase, depending on where you start. In other words: The slope of the curve is different at all points. What you could say is something like this: "When the SAT score increases from 500 to 510, the probability of acceptance increases from 7% to 8.56%". In order to calculate this, simply predict the two probabilities for the different SAT scores based on the model. If you want to quantify the uncertainty of the difference of two predicted probabilities, see the answers to this post.


printing a div using jQuery

Question: How do I just print the article on my web page using jQuery, article is inside a div
window.print() will print the entire window.
So little confused with that...!
Answer: Don't use jQuery ... use css and media=print.  Here is an article for reference, and here.
Basically, create a new stylesheet for what you want to show when you print, and set the media to print:
<link rel="stylesheet" type"text/css" href="print.css" media="print">

Answer: You could probably put the content in an iframe and call print() on that window.
A quick google gave me http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=449 which mentions you must focus() before you print(). Note that that page is a few years old.
Also see How do I print an IFrame from javascript in Safari/Chrome.
Answer: Styling html for printing is commonly achieved using a different style sheet, e.g. in your head element:

    ...

    <link rel="stylesheet" type="text/css" media="screen" href="style.css">
    <link rel="stylesheet" type="text/css" media="print" href="print.css">
    ...

The style sheet style.css is used to style your html on screen, while print.css is used to style your html for print. By providing the appropriate styling in print.css you can easily show or hide html elements to achieve the output you are looking for.

printing a div using jQuery


Get value of div and other elements on button click

Question: I have a HTML form which consists of divs and ul element. I want to get all the data on a button click. I know how to get when there is input type element involved but how to deal with only div's and list elements?
html

    <form id="my_form" method="POST">

      %s

      %s

            %s

&#9899%s - %s

      <input type="submit" value="Click" name="ws_butt" />

    </form>

python script
request_body_size = int(environ.get('CONTENT_LENGTH', 0))
request_body = environ['wsgi.input'].read(request_body_size)
d = parse_qs(request_body)

How to get all the elements in the request body and retrieve while parsing? Is there any other way to tackle this?
Answer: I thought of putting input type="hidden" with every value I need and that will do the job for me.
 <form id="my_form" method="POST">
 <input type="hidden" name="name" value="%s">

Answer: You cannot.
The body of your POST request will only contain values from input elements, and it does not contain other information.
If you must do this, you have two basic options:

Create actual form fields (best option); and then style them accordingly.
Create hidden form fields, and then using javascript add the value of the respected divs to the form field's value before the form is submitted.

As you are using POST in your example, make sure you have a mechanism to stop CSRF. The easiest way to do this would be to use a Python framework.
Comment: when I tried doing it and get the values in the post request, I was able to get all the values. Also, is there any way to stop CSRF without framework?
Answer: Form data are only sent with HTML input elements.
Use hidden fields for each of Div, Li etc. Then use the load event of window to capture their values into the hidden fields.

$(window).load(function(){
var a = $('#div1').text();
$('#div1Value').val(a);
});

<form method='post'>
<input type='hidden' id='div1Value'>

Some text

<input type='submit' value='Submit'>
</form>

Then use this JQuery code :


Player with debut match perfect Hat-trick?

Question: Over the years in football there have been many players who have scored hat-tricks in their clubs in their international debut matches.
For example: Serge Gnabry and Dieter Müller scored hat-tricks on their international debuts, Wayne Rooney on his Manchester United debut in 2004.
Is there any player who has scored a perfect hat-trick, which is achieved when a player scores one right-footed goal, one left-footed goal and one headed goal within one match, in debut match for a club or a country? If there is one who is he?
Answer: There may be many players with debut match perfect hat-tricks but the only one that I have found so far is Didier Drogba scoring perfect hat-trick on MLS debut in a 4-3 win over Chicago Fire for Montreal Impact. Youtube
There have been 33 perfect hat-tricks in premier league so far but I'm not sure whether any of them is in debut match. Players list
Other articles concerning perfect hat-tricks: bleacherreport, fifa
Answer: Akwasi Asante scored perfect hat-trick on his debut for Chester FC in November 2018 against Darlington FC.

Asante netted on 27 minutes with a header, followed by a left and then right foot effort in the second half ...

Reference: Chester FC 3 Darlington 1: Sublime Akwasi Asante hat-trick


Javascript constructor function creating object vs regular object

Question: Sorry about the maybe misleading title, but I wonder why is this approach of creating objects and adding properties and methods:
//A)
var myObjCreatedByFunction = function() {
  this.prop1 = "a";
  this.func1 = function() {
   alert("a");
  }
};

and then using prototype to create additional methods
myObjCreatedByFunction.prototype.func2 = function() { ... }

preferred over simple and plain creating object:
//B)
var myObj = {
  prop1: "a",
  func1: function() {
   alert("a");
  }
};

and just adding new method by
myObj.func2 = function() { ... }

as I see some skilled developers use the first approach and use prototypes even if they never create new instances later.
Furthermore, is the use of IIFE preferred over both examples and if so, why? (I see a lot of this usage lately)
var myObjIIFE = (function() {
return {
  prop1: "a",
  func1: function() {
   alert("a");
  }
}
})());

Can someone explain please when should I use first approach, second and third and why? Thank you!
Comment: See http://stackoverflow.com/questions/9772307/declaring-javascript-object-method-in-constructor-function-vs-in-prototype
Comment: Thank you, but that is just partial answer. There's no IIFE approach and doesn't explain the difference between A and B approach.
Comment: "*use prototypes even if they never create new instances later*"??? No, those are not skilled developers.
Comment: Mix ins and inheritance could be a reason to use prototype and constructor even though only one instance is created, more info here: http://stackoverflow.com/a/16063711/1641941 Sometimes you can wrap (some of) your prototype declaration in an IIFE to create private functions or other private shared members like a box object to be used to simulate protected members
Answer: B is useful only for a single instance.  It does not offer a means to create multiple instances of that type with those methods and properties like A does.   If all you want/need is a single instance, then B is just fine and perhaps simpler to express and follow.
There are long discussions about whether to use the prototype for methods or assign them in the constructor (see prior reference and there are many, many other such discussions).  Using the prototype and then creating a new object using the new operator will conserve memory (since all methods are shared by all instances).  Assigning them in the constructor allows access to private instance variables (the local variables in the constructor) and has slightly better performance when executing a given method.
An IIFE is a pattern some people choose to adopt.  It offers no benefit for what you are doing, but does provide a scope to store "private class variables" which are shared by all instances, but not accessible to the outside world.  The way you show it, it is not my favorite because there is no type information on the object all.  It's just a plain object with properties.  In some cases (particularly in debugging, but sometimes in coding), it can be useful to know what type of object you have.
Comment: Note that `Object.create` can be used to create new instances of object literals, but it's much slower than using `new` and a constructor.


$64 = a^2-b^2$, how many solutions are there

Question: $64$ was written as a sum of two squares of two natural numbers. How many solutions does this equation have?
$$64 = x^2-y^2 = (x+y)(x-y)$$
For example this works for $10$ and $6$, but how can I determine other solutions instead of just putting random numbers in there?
Answer: Hint:
$$ 64 = 2^6 $$
So we have, $64(1)$, $32(2)$, $16(4)$, $8(8)$.
Answer: Note that each of $x-y,x+y$ has to be a positive divisor of $64$.
Hence, noting that $x-y\le x+y$, we have
$$(x-y,x+y)=(1,64),(2,32),(4,16),(8,8)\Rightarrow (x,y)=(17,15),(10,6),(8,0).$$
(Note that $(x-y,x+y)=(1,64)$ does not lead integer solution.)


Importance Sampling

Question: I want to solve the integral
$$I =\int_{0}^{3} \frac{\exp(-s)}{1+\frac {1}{s}} \text{d}s $$
using importance sampling.
I'm unsure as to how implement it.
I have sampled random variables from an exponential distribution.
$$ x = -\log(1-U)\ \text{with}\ U \sim \mathcal{U}(0,1) $$
Am I right in thinking that
$$ \hat{I} = \frac{1}{N}\sum f(x)/g(x)   $$
is a proper importance sampling approximation, where $$f(s)=\frac{\exp(-s)}{1+\frac {1}{s}}$$
and $g$ is the pdf of the standard exponential distribution.
Answer: Pretty close. Remember that exponentials have support on the positive reals.
$$
\frac{1}{N}\sum_i f(x_i)/g(x_i) \to E_g[f(x)/g(x)] = \int_0^{\infty}f(x)/g(x) g(x)dx = \int_0^{\infty}f(x) dx \neq \int_0^3 f(x) dx.
$$
Instead try computing $\frac{1}{N}\sum_i f(x_i)/g(x_i)1(0 < x_i < 3)$.
Comment: Ok great, that makes sense.

Importance Sampling


Retirar o focus/outline do input (CSS)

Question: Como retiro esse focus/outline do input?
Esse é o meu HTML
Estou usando ReactJS, Bootstrap-react

                        Parâmetros
                        assignment_return
                        cached

                         <FormGroup className="viewInstrument-formSearch">
                            <InputGroup>
                                <InputGroup.Addon>
                                    search
                                </InputGroup.Addon>
                                <FormControl placeholder="Pesquisar instrumento" type="text" />
                            </InputGroup>
                        </FormGroup>

Ele fica assim quando clico dentro do input:
Comment: Já testaste com CSS `input:focus{
    outline: none;
}`?
Comment: Já tentei, mas não deu certo!
Comment: Podes criar um jsFiddle?
Comment: Vou criar um...
Answer: Olha, pelo que já responderam pra ti e pelo que vejo na imagem que tu mandou, isso não é um outline, e sim um box-shadow, ou talvez até uma borda com opacidade diferenciada. Coloca um border: none, e também um box-shadow: none no seu elemento.
Em situações como essa, roda a página, clica com o botão direito no elemento, vai em "Inspecionar Elemento" (talvez tenha que fazer isso 2x, porque o primeiro inspecionar elemento pega no body normalmente), e olha as classes/CSS dele na direita. Ali você deve encontrar o que tá causando essa borda/outline do elemento.
Answer: É so fazer assim no CSS
Tudo isso vira HTML, então funcionara, se preferir, voce também pode add uma className direto do FormControl
    handleFocus: function(event) {
  event.target.select();
},

render: function() {
  return (
    <input type='text' value='Some something' onFocus={this.handleFocus} />
  );
},

Comment: Não funciona...#search{
                        outline: none;
                    }
Comment: Ele continua com o focus...
Comment: tentou colocar um !important?  input{outline: none !important}
Comment: Coloquei tbm com !important... mas não tira... não sei se é pq estou usando o bootstrap.
Comment: Tenta isso

handleFocus: function(event) {
  event.target.select();
},

render: function() {
  return (

  );
},
Comment: Exatamente isso, obrigado!
Answer: declare uma classe css em seu elemento. Ex: <button class="button"></button>
daclare uma classe css com a popriedade outline:none :
.button{
   outline: 0;
}
Ao clicar no button, não aparecerá mais as linhas de focus.
Answer: Bota a propriedade outline como none. Em css normal ficaria:
input:focus{
outline: none;
}

Retirar o focus/outline do input (CSS)


Python Multiprocessing File Read

Question: I have a list of keywords and I want to validate if any of these keywords are inside a file containing more than 100,000 domain names. For faster processing, I want to implement multiprocessing so that each keyword can be validated in parallel.
My code doesn't seem to be working well as single processing is much faster. What's wrong? :(
import time
from multiprocessing import Pool

def multiprocessing_func(keyword):

    # File containing more than 100k domain names
    # URL: https://raw.githubusercontent.com/CERT-MZ/projects/master/Domain-squatting/domain-names.txt
    file_domains = open("domain-names.txt", "r")

    for domain in file_domains:
        if keyword in domain:
            print("similar domain identified:", domain)

    # Rewind the file, start from the begining
    file_domains.seek(0)

if __name__ == '__main__':

    starttime = time.time()

    # Keywords to check
    keywords = ["google","facebook", "amazon", "microsoft", "netflix"]

    # Create a multiprocessing Pool
    pool = Pool()

    for keyword in keywords:
        print("Checking keyword:", keyword)

        # Without multiprocessing pool
        #multiprocessing_func(keyword)

        # With multiprocessing pool
        pool.map(multiprocessing_func, keyword)

    # Total run time
    print('That took {} seconds'.format(time.time() - starttime))

Comment: @kyriakosSt Didn't notice the code was doing a "keyword in ".  Mis-read as "keyword in " which could use a set.
Comment: you should just do `pool.map(multiprocessing_func, keywords)`
Comment: Note that much of the delay of the parallel method is due to printing. The printing messages are ordered which takes a huge amount of time. If I comment out the print statement in the function, I get a x60 speedup in the parallel task on my machine. (However that time  is still x2 the time of the single thread solution. For that, refer to the answer)
Comment: @MarkTolonen I agree that reading the file multiple times is hugely unnecessary, but I think there are a few things that need to addressed in the set approach you suggested: 0. this code is clearly a multithreading exercise and not an application, so the goal is to use multi processing. 1. How would you use a set to search for substrings?? would you insert the whole domain? if so the set is useless as it has to be iterated. would you split by some notion of words? How would you define them? And if so, a trie data structure is a better option. [1/2]
Comment: ... 2. Asymptotic complexity is not a relevant measurement in most cases when we are talking about multiprocessing, as it disregards linear-time speedups - which are crucial in many non-algorithmic applications. [2/2]
Comment: Hello guys, thanks for the tips... this is a "learning code" so that I can learn how to multiprocess. Based on Tim's tip, I did fix my code however I am not getting the performance improvement that I expected. Iterating the code once to a List is definitely much better than reading the file multiple times, thanks for the tip!
Answer: Think about why this program:
import multiprocessing as mp

def work(keyword):
    print("working on", repr(keyword))

if __name__ == "__main__":
    with mp.Pool(4) as pool:
        pool.map(work, "google")

prints
working on 'g'
working on 'o'
working on 'o'
working on 'g'
working on 'l'
working on 'e'

map() works on a sequence, and a string is a sequence.  Instead of sticking the map() call in a loop, you presumably want to invoke it only once with keywords (the whole list) as its second argument.

Python Multiprocessing File Read


How to calculate standard error given mean and confidence interval for a gamma distribution?

Question: I am a health economist. I often look at information on costs, which is generally assumed to come from a Gamma distribution because costs are constrained to be zero or positive. Typically this information is taken from the literature, where a point estimate is reported with a range around this estimate (a max and a min, say 50% larger, and 50% less than the point estimate).
I would like to calculate the standard error (se) value when I come across the mean and this range, as typically reported. The following post: https://math.stackexchange.com/questions/2873763/is-it-possible-to-determine-shape-and-scale-for-a-gamma-distribution-from-a-mean
Suggests:
se <- ((Maximum) - (Mean)) / 2
se

This post didn't provide the intuition for this approach, but I assume that because the central limit theorem states that the distribution of a sample mean will approach a normal distribution regardless of the population distribution, I can assume a normal distribution of the sample mean m such that the confidence interval is CI = m ± t*SE. Thus, this formula can be solved for the SE: CIupper = m + t*SE ---> SE = (CIupper-m)/t. While the t-quantile can be looked up for the level of confidence when the total sample size (n)/the number of coefficients in the model (k) are known, for large n (and 95% CI) the quantile approaches 2.0, which is why I assume the post suggests a division by 2.
(Above formula and rearrangement comes from a post by Jochen Wilhelm here: https://www.researchgate.net/post/Formula_for_calculate_Standard_errorSE_from_Confidence_IntervalCI)
To investigate this approach for calculating the standard error I use:
Goldstein, D. A., Chen, Q., Ayer, T., Howard, D. H., Lipscomb, J., Harvey, R. D., ... & Flowers, C. R. (2014). Cost effectiveness analysis of pharmacokinetically-guided 5-fluorouracil in FOLFOX chemotherapy for metastatic colorectal cancer. Clinical colorectal cancer, 13(4), 219-225. https://www.sciencedirect.com/science/article/abs/pii/S1533002814000978
In the attached Table they report the max, min and average cost values. Crucially, they report the gamma distribution shape and scale values for these cost parameters. This lets me test the standard error I create when following the above approach, by entering this into the methods of moments, along with the mean supplied in the paper, and determining if I get the same shape and scale values.
I can replicate almost all of their results as follows using the R programming language:
Maximum <- SOMEVALUEHERE
Mean <- SOMEVALUEHERE

se <- ((Maximum) - (Mean)) / 2
se

mean <-Mean
mean

mn.cIntervention <- mean ## mean cost of intervention
se.cIntervention <- se ## standard error of cost of intervention

a.cIntervention <- (mn.cIntervention/se.cIntervention)^2 ## alpha value for cost of intervention (shape)
b.cIntervention <- (se.cIntervention^2)/mn.cIntervention ## beta value for cost of intervention (scale)

a.cIntervention
b.cIntervention

Bar the first row, when I generate the standard error as per the above my resulting shape and scale values are identical to those reported by the author down to the decimal point, so I conclude my standard error is calculated appropriately.
For the first row they report:
Administration cost MEAN: 284.77 MIN: 177.70 MAX: 375.44  gamma(28.295, 10.064), whereas with the above method I get: gamma(39.45674, 7.217271).
Knowing that CI = m ± t*SE, I assume that the formula can be solved for the SE: as CIupper = m + t*SE ---> SE = (CIupper-m)/t, but also as CIlower = m - t*SE ---> SE = (m-CIlower)/t.
Thus, I also assume that where the difference between the upper interval and the mean, and the lower interval and the mean wasn't symmetric, the authors checked which of what they call the max or the min (per attached Table) was further away, and chose to calculate the standard error using the lower interval (minimum) as SE = (m-CIlower)/t, because this was further away and thus incorporated more of the variability in the SE.
My questions is thus, is my approach to calculating a standard error for a gamma distribution correct where only the mean and a min/max range about this mean is reported?
Attached Table 4 as image, per comments:
Comment: Maybe I'm not reading carefully enough but are you considering `Cllower` the same as `min` and `CLupper` the same as `max` ?  And if you're given the confidence interval for the mean (as opposed to a prediction interval for a single observation), do you know the sample size used to calculate the interval?
Comment: Hi @JimB good question, yes I am considering the `Cllower` the same as `min` and `CLupper` the same as `max`.  When given the confidence interval for the mean (as opposed to a prediction interval for a single observation), the sample size used to calculate the interval is rarely reported. I attach an image of the Table from the study I quote which reflects the information that is typically supplied in the literature (albeit the shape and scale are generally not included, only the mean, min and max).
Answer: The minimum and maximum values in that table relate to the values:
$$\mu \pm 2 \sigma $$
where $$\begin{array}{}\mu = k \theta \\ \sigma = \sqrt{k\theta^2}\end{array}$$ and $k$ and $\theta$ are the parameters for the $\gamma$ distribution.
there is a little typo in the table, with the values $k=28.295$ and $\theta = 10.064$ you should get $391.83$ as the maximum. But the formula matches the rest, so I guess that this is a typing error.

In the article they write:

Utilities were varied over their 95% confidence intervals.

It is not very clear how they did that exactly. They used 10 000 samples in the sensitivity analysis and should have roughly 500 samples outside the min and max values. Possibly they used some sort of truncated distribution.

Your approach is correct. And using the $t$ value instead of the factor $2$ (which was a simplification) is even better.
However,
I would like to note that, while those values in the table happen to correspond with $\pm 2\sigma$, the minimum and maximum values do not generally follow such simple formula with mean plus-minus some standard deviation.
In this case, the minimum and maximum values only correspond to the interval $\mu \pm 2 \sigma$ because the distribution seems to have been truncated at those values.
Comment: I've figured out a simple test for whether the max/min reported is ±2σ:
`se <- ((Max) - (Mean)) / 2
MaxMatch <- Mean + 2*se
MinMatch <- Mean - 2*se`
I can then check if the max/min reported in a Table match the above, and if so I know that the max/min reported is ±2σ. But, in situations where studies report just a point estimate, how could I construct a max/min ±2σ? My R thought process is something like:
`Mean<- SOMEVALUEHERE
Max <- Mean + 0.95*Mean
Min <- Mean - 0.95*Mean`
Because approx 95% of data fall within two standard deviations of the mean. Thank you @Sextus Empiricus.
Comment: Ok, I've done some trial and error and when I do the following: `Max <- Mean + 0.20*Mean` and `Min <- Mean - 0.20*Mean` I can replicate the max and the min values just from the mean reported the Table, but I'm not sure why this works? Is this a standard formula? If you have the mean, you can multiply it by this percentage and add or subtract this to get a min and a max that is ±2σ?
Comment: I took the @SextusEmpiricus point that the min/max values correspond to the interval μ±2σ as indicating that a confidence interval must be symmetric about the mean to generate the se using the above method. However, as I have shown in the question for Row 1 (administration costs) although the 95% CI wasn't symmetric about the mean, when calculating the se using the interval furthest from the mean I got the same shape/scale as reported in the Table. Does this mean that I can also apply the above method for a non-symmetric CI, provided I use the furthest interval to calculate the standard error?


the name of a game

Question: I saw a two-player game described the other day and I was just wondering if it had an official name.  The game is played as follows: You start with an $m \times n$ grid, and on each node of the grid there is a rock.  On your turn, you point to a rock.  The rock and all other rocks "northeast" of it are removed.  In other words, if you point to the rock at position $(i,j)$ then any rock at position $(r,s)$ where $r$ and $s$ satisfy $1 \leq r \leq i$ and $j \leq s \leq n$ is removed.  The loser is the person who takes the last rock(s).
Answer: This game is called Chomp.

the name of a game


How to run reports between Azure SQL and Azure AD/B2C?

Question: Our project is using Azure B2C for customer identity/information and Azure SQL for transactions and such.  We need to run reports that pulls from both places (i.e. a transaction report).
What is the best way to create such reports?  Is there a pattern for this?
I could copy just the fields needed to B2C into SQL but that introduces consistency issues.
Thank you for any information!
Answer: You can use Azure Active Directory  for authentication with your Azure SQL Database , Not Azure AD B2C.
If you would like to use Azure AD authentication with your SQL database please refer the document


Prove $\mathbb{P}\left(\lim _{n \rightarrow \infty} X_{n}=0\right)=1.$

Question: Let $(X_n)$ be a sequence of random variables. If $\sum_{n \geqslant 1} \mathbb{P}\left(\left|X_{n}\right|>\varepsilon\right)<\infty$ for each $\varepsilon>0$, prove $\mathbb{P}\left(\lim _{n \rightarrow \infty} X_{n}=0\right)=1$.
I have already tried this several times. Here's my last and most improved attempt.
\begin{align*}
        \sum_{n \geqslant 1} \mathbb{P}\left(\left|X_{n}\right|>\varepsilon\right)<\infty,\text{ }\forall\varepsilon>0\implies&\mathbb{P}(\left[|X_{n}|>\varepsilon\right]\text{ i.o.})=0\\
        \implies&X_{n}\overset{\underset{a.s.}{}}{\rightarrow}0\\
        \iff&\mathbb{P}\left(\lim _{n \rightarrow \infty} X_{n}=0\right)=1.
    \end{align*}
Answer: You are missing one important step.
$\mathbb{P}(\left[|X_{n}|>\varepsilon\right]\text{ i.o.})=0$ implies  $\mathbb{P}(\bigcup_k \left[|X_{n}|>\frac 1 k\right]\text{ i.o.})=0$ which implies $X_n \to 0$ a.s.
It is important to let $\epsilon \to 0$ through a sequnce so that you don't have uncountably many sets of probability $0$.
Answer: It's not wrong but short of details. In particular, the first "$\Rightarrow$" needs "$\forall\epsilon$" on both sides, and this is subtle.
To be completely rigorous, we write the complement event of $\lim_{n\rightarrow\infty} X_n=0$ as $$\cup_{k=1}^\infty \cap_{n=1}^{\infty}\cup_{m=n}^\infty(|X_m|\ge \frac{1}{k})$$ (If you don't know yet, the translation from $\epsilon-\delta$ to the set operation is straightforward: $\forall\rightarrow \cap$ and $\exists\rightarrow\cup$ in a suitable way. This is also the standard way to show that $X_n\rightarrow 0$ is indeed measurable, hence its probability can be discussed.)
Note the first two set operations above are monotone, hence we may apply the measure $\mathbb P$ to have $$\mathbb P([\lim_{n\rightarrow\infty} X_n=0]^c)=\lim_k \lim_n \mathbb P(\cup_{m=n}^\infty(|X_m|\ge \frac{1}{k}))\le\lim_k\lim_n \sum_{m=n}^\infty\mathbb P(|X_n|\ge \frac{1}{k})=\lim_k 0=0$$


Time series Forecasting in Python - comparing different models

Question: I have a large number of different timeseries and I need to create a forecast for each one of them.
Are there packages that enable:

Auto tuning of models?
Cross validation of different tuned models - both classical models and Neural Nets models (ARIMA, Holt, Holt-Winters, Prophet, LSTM, etc) using a chosen measurement/s (For example MAPE, RMSE) and choosing for each timeseries the prediction of the best fitted model?

Editing: I found pyAF which is nice, but it's not well documented and it seems there is still some work on it - hence it's not good enough for me.
Thanks.
Answer:
Auto tuning of models?

For ARIMA models, there is Pyramid which duplicates R's auto.arima function, but it is still not mature.
Statsmodels has a pretty decent implementation of Holt-Winters.
For the other methods, auto-tuning the models is still an open question.

Cross validation of different tuned models

Scikit-learn comes with a time series split method that can be used for times series cross validation. However it doesn't do much besides that, it doesn't do model evaluation or model selection.
If PyAF doesn't meet your criteria, I doubt you will find anything better than that, unfortunately there's still a lot of work to be done for time series in Python (compared to what's available in R).
Comment: Thank you very much.
Assuming I will use R instead, what would you recommend in order to automatically choose the best model (and perhaps auto tune them first)?
Comment: @QueenP the forecast package in R is your best bet.
Answer: Check out AnticiPy which is an open-source tool for forecasting using Python and developed by Sky.
The goal of AnticiPy is to provide reliable forecasts for a variety of time series data, while requiring minimal user effort.
AnticiPy can handle trend as well as multiple seasonality components, such as weekly or yearly seasonality. There is built-in support for holiday calendars, and a framework for users to define their own event calendars. The tool is tolerant to data with gaps and null values, and there is an option to detect outliers and exclude them from the analysis.
Ease of use has been one of our design priorities. A user with no statistical background can generate a working forecast with a single line of code, using the default settings.
The tool automatically selects the best fit from a list of candidate models, and detects seasonality components from the data. Advanced users can tune this list of models or even add custom model components, for scenarios that require it. There are also tools to automatically generate interactive plots of the forecasts (again, with a single line of code), which can be run on a Jupyter notebook, or exported as .html or .png files.
Check it out here:
https://pypi.org/project/anticipy/


Criar Páginas de produtos - PHP + MySql

Question: Boa noite!
Estou fazendo uma loja virtual e gostaria de saber se existe a possibilidade de fazer uma página de produtos única onde o usuário clica no produto e as informações são carregadas dinamicamente. Ou se eu tiver 100 produtos cadastrados vou ter que fazer 100 páginas de produtos diferentes?
Answer: O correto seria fazer uma página de produtos única onde o usuário clica no produto e as informações são carregadas dinamicamente, de acordo com as informações que há no banco.
Caso você não tenha muito conhecimento em desenvolvimento, recomendo começar algo com PHP, talvez você acabe fazendo algo "macarrônico" com um pouco de XGH, mas caso precise disso o mais rápido possível é o melhor caminho.
Comment: Bruno, Criei uma página chamada produto.php onde ao clicar no produto enviei o ID dele no banco pela url e consegui resgatar via $_GET nessa página.
Comment: Obrigado pela dica Bruno. Nessa pagina passo somente id e categoria do produto.
Comment: Fico feliz que tenha conseguido!
Só não se esqueça que se for passar algo que se for enviar dados que não podem aparecer no link use $_POST.

Criar Páginas de produtos - PHP + MySql


How to write If condition where the value is character data

Question: I have a dataframe "weather" where i have weekday information (Monday to sunday). I have to mutate a new column dummy weekday where it's = 1 if it is Saturday or Sunday, and = 0 otherwise. this is what I write
for (i in 1:nrow(weather)) {
  if (weather$weekday[i] == "Saturday" || weather$weekday[i] == "Sunday") {
    weather$weekend_dummy = 1
  } else {
    weather$weekend_dummy = 0
  }
}

but it has this error : Error in if (weather$weekday[i] == "Saturday" || weather$weekday[i] ==  :
missing value where TRUE/FALSE needed
Comment: Please read the information at the top of the [tag:r] tag page and in particular note that all inputs should be provided using `dput `so that anyone can just copy the code in the question and paste it into their session to run it.  As presented currently only you can run it as the input is missing.
Answer: I have my local R on German, sorry for that. But should be easy to adapt as the days sound very similar :-)
Base R solution:
your_df$weekend_dummy = ifelse(your_df$wday == "Samstag" | your_df$wday == "Sonntag", 1, 0)

data.table solution:
library(data.table)

dt = data.table(your_df)
dt[, weekend_dummy:=ifelse(wday == "Samstag" | wday == "Sonntag", 1, 0)]

Output:
> dt
         wday weekend_dummy
1:     Montag             0
2:   Dienstag             0
3:   Mittwoch             0
4: Donnerstag             0
5:    Freitag             0
6:    Samstag             1
7:    Sonntag             1

In most cases you don't need loops in R, because R is much faster when calculating vector based.
PS, please provide next time some data like:
your_df = data.frame(wday=weekdays(as.Date(c("2021-01-04", "2021-01-05", "2021-01-06", "2021-01-07", "2021-01-08", "2021-01-09", "2021-01-10"))))

Comment: thank you so so much


Find $A^{50}$ for a $3\times 3$ matrix

Question:
If $$A=\begin{bmatrix}1&0&0\\1&0&1\\0&1&0\end{bmatrix}$$ then $A^{50}$ is:

$\begin{bmatrix}1&0&0\\25&1&0\\25&0&1\end{bmatrix}$

$\begin{bmatrix}1&0&0\\50&1&0\\50&0&1\end{bmatrix}$

$\begin{bmatrix}1&0&0\\48&1&0\\48&0&1\end{bmatrix}$

$\begin{bmatrix}1&0&0\\24&1&0\\24&0&1\end{bmatrix}$

For $A$, the eigenvalues are $1, 1, -1$, but I don't know the procedure any further.
Comment: A matrix satisfies its characteristic equation it can help you get a relation between a matrix and its higher powers.
Answer: Sometimes a good way to start a problem like this is just to try a few multiplications and look for a pattern.
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 0 & 1 \\
0 & 1 & 0 \end{array} \right)$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 0 & 1 \\
0 & 1 & 0 \end{array} \right)$$=$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 1 & 0 \\
1 & 0 & 1 \end{array} \right)$ $=A^2$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 1 & 0 \\
1 & 0 & 1 \end{array} \right)$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 0 & 1 \\
0 & 1 & 0 \end{array} \right)$$=$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
2 & 0 & 1 \\
1 & 1 & 0 \end{array} \right)$ $=A^3$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
2 & 0 & 1 \\
1 & 1 & 0 \end{array} \right)$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
1 & 0 & 1 \\
0 & 1 & 0 \end{array} \right)$$=$
$\left( \begin{array}{ccc}
1 & 0 & 0 \\
2 & 1 & 0 \\
2 & 0 & 1 \end{array} \right)$ $=A^4$
Now the pattern should be clear enough to be able to solve the multiple-choice question.  If not, do two more.
Answer: Hints:

If $D$ is a diagonal matrix, what is $D\cdot D$? What is $D\cdot D\cdot D$? From that, can you conclude what $D^{50}$ is?
If $A=PDP^{-1}$, then what is $A\cdot A$? What is $A\cdot A\cdot A$? From that, can you conclude what $A^{50}$ is?
Comment: @rujulmankad You could calculate $A^2, A^3$ by hand and hope to spot a pattern and guess your answer from there. If you want to be _certain_, then diagonalization is the fastest way.
Comment: but this will be lengthier is there any other shortcut method? because this one is MCQ and we have very less time to solve
Comment: @rujulmankad It's a very very simple and quick method once you have enough practice.
Comment: Sorry, but the matrix is not diagonalizable. So we can't proceed with this procedure. Thanks.

Find $A^{50}$ for a $3\times 3$ matrix


Regex invalid on match

Question: I need regex to return invalid on a match. Specifically, the match is a string that starts with an A or an M and is followed by four numbers ie, A1223. The four numbers could be any random sequence.
I'm sure lookarounds are the way to handle this but I haven't grasped regex as a concept just yet. Thus far I've discovered how to capture the matched strings separate from other strings with the following.
<code>([\s\S]*?)(A[\d][\d][\d][\d]|M[\d][\d][\d][\d])
</code>
Appreciate the help.
Comment: You need to provide some sample data, indicating which should and which should not be matched. It's unclear what exactly you mean by *return invalid on a match*. Do you want it to return false if there is a match and true if there is not? Or return true if there is a match and false if not? Are you trying to capture the part that consists of an A or M followed by 4 digits? Or capture the parts around it? Or something else entirely? Also, what regex flavor are you using?
Answer: to match all strings not starting with A or M followed by 4 digits:
with negative lookahead:
<code>^(?![AM]\d{4}).*
</code>
with consuming pattern using <code>()</code> capture groups:
<code>[AM]\d{4}.*|(.+)
</code>
Comment: Thanks a lot. Consuming pattern is a new concept for me. This works beautifully.
Answer: Regex doesn't really have match negation, but you can (ab)use a negative lookahead assertion to do inverted matching:
<code>^((?!\s[AM]\d{4}).){6}
</code>

Regex invalid on match


WPF Bound TextBox value not updating when other TextBox is changed

Question: I have a WPF window that allows the user to edit the Date of Birth of an employee, in this window is also a TextBox to display the age from the DoB entered.
The DoB textbox is bound to my EmployeeModel Dob property
The Age textbox is bound to my EmployeeModel Age property and cannot be set, and the get using the Dob value.
The problem I'm facing is when the user changes the DoB, the Age textbox does not get updated.
I have found that if I implement INotifyPropertyChanged in my EmployeeModel, and add OnPropertyChanged("Age") in the Dob property, then the Age value gets updated.  But this goes against what I have been advised that my Models should be business logic only and should not implement INotifyPropertyChanged.
How should I set this up so Age updates when DoB is changed without modifying the Model?

EmployeeModel
class EmployeeModel
{
    public DateTime? Dob { get => _dob; set => _dob = value; }
    public int Age
    {
        get
        {
            if (_dob == null)
                return 0;

            DateTime now = DateTime.Today;
            int age = now.Year - _dob.Value.Year;
            if (now < _dob.Value.AddYears(age))
                age--;

            return age;
        }
    }
}

EmployeeViewModel
class EmployeeViewModel : INotifyPropertyChanged
{
    private EmployeeModel _employee;

    public EmployeeModel Employee
    {
        get => _employee;
        set
        {
            if (_employee != value)
            {
                _employee = value;
                OnPropertyChanged();
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName]string caller = null)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
    }

View

<DatePicker SelectedDate="{Binding Employee.Dob, TargetNullValue=''}" />

<TextBox Text="{Binding Employee.Age, Mode=OneWay}" />

Comment: When the employee birthdate changes, just raise property changed on the age property.
Comment: "Models should be business logic only and should not implement INotifyPropertyChanged", this is opinion based. Look at [this](https://stackoverflow.com/questions/772214/in-mvvm-should-the-viewmodel-or-model-implement-inotifypropertychanged/4574762). The accepted answer says you shouldn't, but the answer with the most votes says you can.
Comment: The binding mode of the `TextBox` must be `TwoWay` in order to send the user input back to the `Age` property. Just remove the mode from the binding since it is `TwoWay` by default for the `TextBox` class. Otherwise if you just want to display the age to the user, then better use a `TextBlock`, since it is cheaper resource and performance wise (but at least set `IsReadOnly=True`).
Comment: Also if you don't like to bind directly to your model, which is right, then why do you expose it as a public property in your `EmployeeViewModel` class? The property must be private. You have to duplicate the properties of the model on the view model and delegate property calls to the private model like `Age { get { return this._employee.age; } set { this._employee.Age = value; } }`.
Comment: @Hyarus Since in programming you always _can_ do anything (as long your compiler let's it go), the _should_ and _shouldn't_ are important. It's referred to as best practice. You can't introduce MVVM to your application and the bind to your models. This is not MVVM, since it encourages strict separation of the model from the view model for some good reason (e.g. to improve testablity and extensibility). You can implement it in your model but shouldn't ever `bind` to it.
Comment: @Hyarus The point is `INotifyPropertyChanged` is a generic event that is introduced for one purpose only in mind: data binding (framework internal). The framework doesn't care what the purpose of a property is, since it just 'transports' the data from binding source to binding target. As a programmer or user of some API your very interested in which particular event was raised or which particular property changed. That's why you should introduce specific events (e.g. AgeChanged).
Comment: @Hyarus `INotifyPropertyChanged` would require you to filter the proper property by name in order to identify the property that actually changed, which is not very convenient. Therefore the dedicated changed event everywhere when possible. Maybe you even add an explicitly named event to your view model (that duplicates the PropertyChanged event) when you depend on it (and in this case to improve your code). That's why when mentioning INotifyPropertyChanged everybody thinks of binding in first place.
Answer: If you don't want to implement INotifyPropertyChanged in EmployeeModel you shouldn't bind to a property of an EmployeeModel but to a property of the view model that wraps the property in EmployeeModel, e.g.:
class EmployeeViewModel : INotifyPropertyChanged
{
    private EmployeeModel _employee;

    public DateTime? Dob
    {
        get { return _employee.Dob; }
        set { _employee.Dob = value; OnPropertyChanged(); OnPropertyChanged(nameof(Age)); }
    }

    public int Age
    {
        get { return _employee.Age; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName]string caller = null)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
    }
}

XAML:

<DatePicker SelectedDate="{Binding Dob, TargetNullValue=''}" />

<TextBox Text="{Binding Age, Mode=OneWay}" />

Comment: Along with this, we need to add UpdateSourceTrigger=PropertyChanged to DataPicker
Comment: Is doing your suggested method a requirement for all the fields.  My view actually has over 50 editable fields.  Age and FullName are the only ones that requires information from fields not related to their own.  (FullName is slightly different as it is a label, and fullname does not exist in my EmployeeModel)
Comment: @smally: Yes, of course. You need to raise the `PropertyChanged` event for all data-bound properties that you want to refresh.
Answer: I am also using your approach to calculate the age and it works properly.
I have a Patient model which is defined in a separate class
Here is the ViewModel:
class PatientRecordDetailsViewModel : INotifyPropertyChanged
{
    public DateTime PatientDateOfBirth
    {
        get => m_patientDateofbirth;
        set
        {
            m_patientDateofbirth = value;
            OnPropertyChange("PatientDateOfBirth");
            OnPropertyChange(nameof(PatientAge));
        }
    }

    public int PatientAge => CalculateAge();

    private int CalculateAge()
    {
        if (m_patientDateofbirth == null)
        {
            return 0;
        }
        else
        {
            int CurrentYear = DateTime.Now.Year;
            int BirthYear = m_patientDateofbirth.Year;
            m_patientAge = CurrentYear - BirthYear;
            return m_patientAge;
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
     private void OnPropertyChange(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here is the Xaml
<DatePicker Name="Date" Grid.Column="0" SelectedDate ="{Binding Path = PatientDateOfBirth, UpdateSourceTrigger=PropertyChanged}" Style="{StaticResource DatePickerStyle}" VerticalAlignment="Center" Height="30" Padding="3,0,5,0"/>
<TextBox  Name="Age" Grid.Column="1" Text="{Binding Path = PatientAge, Mode=OneWay}" Style="{StaticResource TextBoxStyle}"/>


how to authenticate using username password with django and django rest framework

Question: Good day, I'm not sure of being wrong or right. I've an django which authenticate the user with password and email, I override the form forthis case as shown in the django tutorial.
However, I do have a part in which I'd like to integrate the rest framework, and which will require the user to be logged in with the same username and password in order to view the api in the browser. Is it feasible to use the same credentials on both authentication method ?
Answer: Yes- did you include the URLs for the Django REST Framework browsable API when you followed the install guide? From the install docs:
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py file.
urlpatterns = [
    ...
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

If you followed all the steps:
You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.
Try navigating to the root of your API- assuming you have the UserViewset defined from the install, this would be something like /api/ and you should see users in the list.


How do you find a non zero vector in Linear Algebra?

Question: The question is;
The vectors $a_1 = (1, 1, 0)$ and $a_2 = (1, 1, 1)$ span a plane in $\Bbb R^3$. Find the projection matrix P onto the plane, and find a nonzero vector $b$ that is projected to zero.
I found the matrix $P$ as shown below, but I can't figure out how to find a nonzero vector $b$, I found only the zero vector, help me out?
Comment: Taking the cross product of $a_1$ and $a_2$ is the easiest way to find such a vector, but another way would be to calculate the [null space of the matrix](https://www.khanacademy.org/math/linear-algebra/vectors_and_spaces/null_column_space/v/introduction-to-the-null-space-of-a-matrix).
Comment: i guess null space is quicker. thanks
Comment: I didn't calculate it, but I would have assumed that the cross product was quicker.  The only reason I suggested you could calculate the null space, instead, was that it works in any dimension, while the cross product only works in $\Bbb R^3$ -- so if you later have a similar question about projections onto some subspace of say $\Bbb R^4$ then you'll already know how to answer it.
Answer: You need a vector that is perpendicular to the plane; i.e. perpendicular to the two vectors. Their cross product is perpendicular to the vectors!
Answer: In this case, there's a shortcut:
We observe the vectors $(1,1,0)$ and $(1,1,1)$ have the same first two components.  So $$(a,-a,0) \cdot (1,1,0)=0$$ and $$(a,-a,0) \cdot (1,1,1)=0$$ for any $a \in \mathbb{R}$.
Comment: Just a suggestion, but you might consider editing in that you figured out that $(a,-a,0)$ would be the space of orthogonal vectors because the two vectors having the same 1st two components means that their projections onto the $xy$-plane are on the same line and thus that a vector in that plane orthogonal to that line will be orthogonal to both vectors (or use your own words to make it more intelligible), or else I doubt the OP will be able to see where you got $(a,-a,0)$ from and won't be able to apply this technique elsewhere.


Image resize to browser without cropping or loosing aspect ratio

Question: I am working on a responsive template.
I have pages with images and I want them to look like this : http://www.chanel.com/fr_FR/
I can't figure out a css way to achieve it so I am trying jquery although I ain't the best jquery coder...
This is what I end up with :
html

some text

css
div.text {
position : absolute;
width : 40%
left : 0;
top : 0;
}

div.image{
    position: absolute;
    top : 0;
    right : 0;
    left : 40%;
    width : 60%;
    bottom : 150px;
}

This seems to work when I enlarge the browser but when I make it smaler, the image flickers and its ugly...
If some pro jquery coder can explain this problem to me, I would be very graitfull.
Answer: If you download Google Chrome, browser to that page again, and look under the resources tab in developer tools, view the author's styles.css file.  Around line 800 and lower, you will see that the author is using media queries to get that responsive feel that you are looking for.  The author is also taking advantage of percentages to design width, height, margin and padding of elements and various items.  No need for jQuery just yet.  Simply dive into the world of media queries first to get a feel for true responsive design.  Then when you become comfortable, go ahead and apply some creative animations via jQuery to spice things up.
Comment: If you see more deeply in source, you will see that author (Clement Caillard) is using some nice javascript/jquery functions to keep it fully functional, just like you said.
Comment: ok I'll have a closer look at it but can the flickering effect be solved by modifuing my code?
Comment: Flickering tends to be a common issue on various jQuery frameworks.  I honestly do not know the answer to fixing that.