Delay with your hands

Question: I recently watched a youtube video where John 5 was going over his rig. They turned to his pedal board and he talked about how he is not over reliant on pedals and that he likes to produce effects himself.
The interviewer asked him about not even having a delay pedal to which John 5 replied that if he needed a delay he would use his hands.
My question is how exactly is this possible to create a delay effect yourself?
Comment: Which part of the video is that? It's a 20 minute long video
Comment: Just a note - adding e.g. #t=3m08s to a YouTube link allows people to instantly find the relevant segment.
Comment: it is at the beginning where they discuss the pedals
Answer: I'm assuming he's talking about playing the same note, chord, or phrase more than once, possibly playing the second and subsequent repeats more and more quietly. Some kinds of delay sound can't be replicated this way, but you can definitely sound like a ducker (where the delayed notes automatically are lowered in volume behind any new notes that are played). So you would only play "delay" notes when you're not busy playing anything else.
Comment: That is very interesting. Is this an old technique? I have never heard a guitarist talk about it even.
Comment: I know my brother was doing it on keys ten years ago and I've seen famous singers do it. Usually guitarists don't eschew the pedals so this is the first time I've heard of a guitarist doing it too.
Answer: Look at the Boss RC-505 - it's hand-driven, has to be given it's 5 consynchronous channels. You can add a foot pedal, if you're that old school.
The old picker trick for that one was Bob Marley's, using the fret hand while plucking ahead with the main driver hand.
Comment: Sorry if my question was ambiguous I'm asking how it is possible to use some sort of picking technique to get a delay sound without the use of a pedal.

Delay with your hands


Getting JQuery Masonry to work with Drupal 7 Views

Question: I want to do this without porting the fluid grid module to 7 from 6. I can't for the life of me get a view page of images to work with Masonry.
Does anyone has experience with this and know how to get it working with just masonry.js and not a module?
Thanks
Comment: Why no module?  [Masonry](http://drupal.org/project/masonry) would do everything you need.
Answer: There's actually a Masonry module now

Makes the jQuery Masonry plugin available to Drupal as a library.
Answer: i just took a short look at masonry ..,
you can add the masonry.js to your theme, and add a custom .js with a drupal.behavoir containing your masonry code - but this will be used on every page.
the
you can do the same in a custom module for dedicated includes; only when your view is displayed.
Comment: yeah - a custom module from scratch, using fe. [hook_views_post_render](http://drupalcontrib.org/api/drupal/contributions!views!views.api.php/function/hook_views_post_render/7) to attach the js for your identified view.
Comment: Could you explain in detail how to do it? Does it require to make a module from scratch?


Python Comparar lista de meses com a da base e mostrar as duas

Question: Tenho uma lista de meses de janeiro a dezembro. Tenho uma outra lista que tem o mês e um valor. Por exemplo:
Jan = 12.00

Fev = 15.00

Ago = 10.00

Quero exibir o ano todo e mostrar todos os meses. Os meses que não tem valor nenhum devem aparecer como 0.
Comment: Poste seu código, fica mais fácil para ajudar vc.
Comment: É uma lista ou um dicionário?
Comment: Essa lista dos meses que tenho é um dicionario meses = [Jan,Fev...] .. e a outra lista é resultado de uma consulta, se tem tem o valor ele exibe o mês
Answer: Suponho que seja algo desse tipo:
meses = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul',
                         'ago', 'set', 'out', 'nov', 'dez']

valores = {'jan' : 12, 'fev' : 15, 'ago' : 10}

for mes in meses:
    if mes in valores:
        v = valores.get(mes)
    else:
        v = 0

    print(mes + " " + str(v))

Comment: valeu isso mesmo! Obriagdo Pedro


opening files with different extensions with Cocoa

Question: I have an NSDocument based app that already handles *.txt files. I can drag and drop those files in the dock and my app will launch correctly.
Now I want to be able to open *.text files too. So I have added:
<key>CFBundleTypeExtensions</key>
    <array>
        <string>.txt</string>
        <string>.text</string>
    </array>

to my *plist
However I can't open *.text files by drag&dropping them in the dock. (I can do MyApp> File>Open> myFile.text )
I can open *.txt  as usual, and drag and drop them in the dock.
I have tried implementing these NSApp delegate methods but now I get an error and I can't open any kind of file.
- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename{
    NSURL *url = [NSURL URLWithString:filename];
    NSError *error = nil;
    [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:url display:YES error:&error];
    if (error) {
        NSLog(@"error: %@", [error localizedDescription]);
        error = nil;
        return NO;
    }
    return YES;
}

- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames{
    for (NSString *filename in filenames) {
        [self application:sender openFile:filename];
    }
}

Error:

typeForContentsOfURL:error: must be
  overridden for your application to
  support non-'file:' URLs.

I am not subclassing NSDocumentController, so do I really need to? or is there a better/easier way of doing this?
Thanks in advance
Answer: The file extensions in the Info.plist file should not contain a period character (.). What happens if you do this?:
<key>CFBundleTypeExtensions</key>
    <array>
        <string>txt</string>
        <string>text</string>
    </array>


Existence of complementary subspaces for $dim(V) = 2k$

Question: I would like to show that, for any vector space $V$ with $dim(V) = 2k$ (in other words, with an even dimension)  there exist three pair-wise complementary subspaces $S1,S2,S3$ such that:
$$V= S1 \oplus S2=S2\oplus S3=S3\oplus S1 $$
Is there a way of proving this with the help of linear self transformations, and if so, where would I start?
Answer: Chose a basis $v_1,\dotsc,v_{2k}$ of $V$ and define
$$\begin{align*}S1:=&span(v_1,v_2,\dotsc,v_k),\\ S2:=&span(v_{k+1},v_{k+2},\dotsc,v_{k+k})\\ S3:=&span(v_1+v_{k+1},v_2+v_{k+2},\dotsc,v_k+v_{k+k})\end{align*}$$
Answer: If $k=1$ just take three vectors $v_1$, $v_2$ and $v_3$ such that every pair of them is a basis of $V$ (e.g. $v_3=v_1+v_2$ once a basis $\{v_1,v_2\}$ is chosen).
Now work by induction in the case $k+1$.
Choose any splitting $V_{k+1}=V_k\oplus V_1$ where $V_1$ has dimension $2$.
Given an inductive choice of $S_1$, $S_2$ and $S_3$ for the $2k$-dimensional space $V_k$, let $\{v_1,v_2,v_3\}$ be three vectors in $V_1$ as in the $k=1$ case.
Then the spaces $S_i^\prime=\langle S_i,v_i\rangle$, $i=1,2,3$, solve the problem.


MSSQL Como descobrir qual tabela um registro foi incluido ou modificado

Question: Existe meio de descobrir via consulta qual tabela em um banco de dados sofreu alteração de Update ou Insert?
Comment: Sua pergunta não está clara. Explique o problema pra podermos propor uma solução.
Comment: Existe os Triggers (Gatilhos)
Comment: https://docs.microsoft.com/pt-br/sql/relational-databases/security/auditing/sql-server-audit-database-engine
Answer: Pelo que conferi nos foruns de SQL SERVE, esta consulta retornará o valor do ultimo insert:
<code>SELECT o.name as ObjectName, last_user_update,*
FROM sys.dm_db_index_usage_stats s
join sepm01.sys.objects o on s.object_id = o.object_id
WHERE database_id = DB_ID( 'sepm01')
</code>
Além disso encontrei um componente que vai te dar u mtrack mais preciso sobre isso:
SQL Server - Change Tracking


Categoria e subcategoria na listagem PHP

Question: Tenho a seguinte função:
public function listar($tipo=null){
    $this->db->select('p1.*, p2.titulo as subcategoria, p2.id as id2');
    $this->db->join("produto_categoria as p2", "p1.id=p2.id_categoria", "LEFT");
    $consulta = $this->db->get('produto_categoria as p1')->result();
    return $consulta;
}

Minha Tabela

Meu resultado atual

Eu preciso que, ao listar, cada subcategoria fique dentro da sua categoria, exemplo: Cílios > fio a fio, Cílios > 3D. E as demais que não tem subcategoria, liste apenas. O que eu fiz errado?
Listagem

            Cod
            Titulo
            Ações

        <?php foreach($lista as $s_lista){ ?>

<?php echo $s_lista->id; ?>

                <?php if($s_lista->subcategoria==""){ ?>
                    Principal Raiz
                <?php } else { ?>
                    <?php echo $s_lista->titulo; ?>

                <?php } ?>
               <?php echo $s_lista->subcategoria; ?>

                <button type="button" class="btn btn-info" title="Editar"></button>
                <button type="button" data-type="confirm" class="btn btn-danger js-sweetalert" title="Deletar"></button>

        <?php } ?>

Resultado esperado:
> Cilios
> Cilios > 3D
> Cilios > Fio a Fio
> Pentes
> Toucas

Answer: Cara mudei um pouco sua query o único "problema" é que o CI não trabalha muito bem com UNION por isso eu montei ela e usei o $this->db->query().
public function listar($tipo=null){
    $query = "SELECT Id, IdCategoria, Titulo, Ordem, SubCategoria, Id2 FROM
            (
            SELECT id, IdCategoria, Ordem, Titulo, NULL AS SubCategoria, NULL AS Id2 FROM produtocategoria
            UNION
            SELECT p1.id, p1.IdCategoria, p1.Ordem, p1.Titulo, p2.Titulo, p2.id FROM produtocategoria AS p1 LEFT JOIN produtocategoria AS p2 ON p1.id = p2.idcategoria ORDER BY Id, SubCategoria
            ) AS tab
            WHERE IdCategoria = 0"

    return $this->db->query($query)->result();
}

Precisa mudar os nomes das colunas para se enquadrar no seu caso mas a lógica é essa. Segue resultado.


How to perform synchronous api call in retrofit 1.9

Question: I am getting android.os.NetworkOnMainThreadException exception while calling api synchronously. I cannnot use Async call as I have many apis and next api is dependent on output of previous api call.
What to do?
Answer: Declare the method in your retroft interface as following:

@GET("/v1/user_info/{id}")
  UserSummaryResponse getSummary(@Path("id")
  String uId);

You need to start a new thread in your networking request calling, and don't forget try catch.
<code>    new Thread(new Runnable() {
      @Override
      public void run() {
      try {
        GetSummaryResponse summaryResponse = HttpClientManager.getInstance().userInterface.getSummary(uId);
        userInfo = summaryResponse.userInfo;
                            setupUserInfo();
      } catch (Exception e) {
        withoutException = false;
        Log.e(getTag(), e.getMessage());
      }

 }}).start();
</code>


Check if a list of values are plus or minus 1 of each other

Question: I have a list of values scores = [80,90,50,60,70]
Trying to write an all statement to determine if the values are +/- 2 of each other.
I've figured out how to code if they are +/- 2 of some value say 82, but not sure if it is even possible to do +/- 2 of each other.
I am not sure where to start the below is how I would write it if I am getting +/- 2 of 82
all(79 < x < 84 for x in scores)

Comment: you want to know if there are a semi-continuos list? as in there are not two continuos integer that are not in the list?
[1,2,3,5,4] is True
[1,2,2,5,6] is False because 2 < 5-2
Answer: If you're trying to figure out if all of the values are within a range with some particular magnitude, take the difference of the min and max.  For example, given a bunch of numbers that are all within +/- 2 of 82:
>>> nums = [80, 82, 84, 83, 81]

we can subtract the min from the max to see that the upper bound is only 4 away from the lower bound:
>>> max(nums) - min(nums)
4

That means that all the numbers are within 4 of each other (since by definition the min and max are the furthest apart from each other), and all the numbers are within 2 (i.e. half of 4) of some number in the middle (in this case 82).
If you already know the number in question (82) and are interested in how far the other numbers are from that specific number, take the difference from that number:
>>> max(nums) - 82
2
>>> min(nums) - 82
-2

Comment: Thanks this is exactly what I am looking for.  I am no math genius and I would have probably never figured this out.  This probably doesn't take a math genius to figure out but you are a savior.  Thanks.  Also this makes sense to me as well.


ImportError: cannot import name 'WebSocketApp' from 'websocket' (/Users/raphaelhen/Desktop/websocket.py)

Question: I am new here, and in programing. until toady I got all my answer here, but I was not able to find id this time so this is my code
from bitmex_websocket import BitMEXWebsocket
ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1",symbol="XBTUSD", api_key=None, api_secret=None)
fuNd = ws.funds()
print(fuND)

I got this error:
ImportError: cannot import name 'WebSocketApp' from 'websocket' (/Users/raphaelhen/Desktop/websocket.py)

I downloaded all the Websocket package so I really don't understand the problem?
thanks!
Answer: Check your module is not imported by "WebSocketApp". Usually import errors are caused by circular references. Module A imports Module B, but Module B is trying to import something from A.
Answer: Maybe it is a little late for this answer, but perhaps other people are reading this question.
I assume you want to use this api connector: https://github.com/BitMEX/api-connectors/tree/master/official-ws/python and i think you have not installed the correct websocket package.
look at the setup.py:
  install_requires=[
      'websocket-client==0.53.0',
  ],

This is the correct websocket-package and with this installed the import statement raises no error anymore.
Answer: In my case, the error was, that I had another module called websocket in my code and it was clashing with the actual websocket package.
If you have the same, try renaming your module to a different name.


Matrices - Inverse of the principal square root of a covariance matrix (^-1/2)

Question: Say you have a square (variance)covariance matrix S
How would one go about working S^-1/2 (inverse of the principle square)?
Bearing in mind, I'm trying to understand a paper which states:

I've tried multiple suggestions, such as:

square root, then take the inverse of the square root: Inverse Square Root Of Matrix
reciprocal of the square root of each term in the diagonal: Raising a square matrix to a negative half power
plus tried (^-1/2) directly on multiple online matrix calculators

However, none of them seem to hold true for the latter part of the what's stated on the paper.
Answer: You can obtain the square root of a matrix M using the Cholesky Decomposition, M = LL'. Then compute the inverse of L.
Comment: What is the inverse square root actually is? If $S =ULU^T$ then why $S^{-1/2} =UL^{-1/2}U^T$
Answer: @Avv, if $S=U L U^{T}$, then $S^{-1}=(U L U^{T})^{-1} = U L^{-1} U^{T} = U L^{-1/2} L^{-1/2} U^{T} = U L^{-1/2} U^T U L^{-1/2} U^{T} = (U L^{-1/2} U^T) (U L^{-1/2} U^{T})$,
thus $S^{-1/2} = U L^{-1/2} U^T$
Note that $U$ is orthonormal, and $L$ is diagonal


VBA Excel - Object does not support this property or method

Question: Option Explicit
Dim wb1 As Workbook
Dim shtDisplay As Worksheet

Public Sub Main()
    Set wb1 = ActiveWorkbook
    Set shtDisplay = wb1.Worksheet("Sheet1")
    Call Main2
End Sub

Public Sub Main2()
    shtDisplay.Cells(1, 1).Value = "YES"
End Sub

I'm trying to declare aliases (variables) early in the module so I can use the same alias later in within the module without having to always declare in every sub/function.
As I understand scope, by the time the above code gets to Main2, shtDsplay would be set so I don't have to type out ActiveWorkbook.Worksheets("Sheet1").Cells(1,1).Value = Yes and yet before the program even gets that far Excel throws the Object does not support this property or method error at line Set shtDisplay = wb1.Worksheet("Sheet1")
What am I not understanding?
Thank you in advance for what is probably the most simple problem in the world and I can't get past it.
Comment: You want the collection... plural...  `wb1.Worksheets("Sheet1")`
Answer: You want the collection, not the object.
Worksheet (singular) is an object
Worksheets (plural) is a collection of objects
Simply add the s to make it plural.
wb1.Worksheets("Sheet1")

Answer: See if the code below makes more sense in what you are trying to achieve, I have comments inside the code to clarify some of the point.
Option Explicit

' these are only recognized within the Module, not outside the module
Dim wb1 As Workbook
Dim shtDisplay As Worksheet

Sub Main()

' ~~~ Call Sub that initializes all Worksheet, Ranges as other objects ~~~
Init  ' there's no need to use 'Call'

shtDisplay.Cells(1, 1).Value = "YES"

End Sub

Sub Init()

' this Sub initializes and sets all Objects, such as Worksheets, Ranges, Flag, etc...

Set wb1 = ThisWorkbook ' if you want to set-up the workbook that has the VBA code
Set shtDisplay = wb1.Worksheets("Sheet1")

End Sub


Memory referenced by rvalue references

Question: Given a function
int foo()
{
   return 15;
}

it is OK to use:
int&& ref = foo();

but not OK to use:
int& ref = foo();

which is understandable since the return value of foo() is an rvalue. However, how I am able to use the following?
#include <iostream>

template<typename T>
void f(T&& param)
{
   param *= 2;
}

int foo()
{
   return 15;
}

int test1()
{
   int&& ref = foo();
   std::cout << "ref = " << ref << std::endl;
   f(ref);
   std::cout << "ref = " << ref << std::endl;
}

int main()
{
   test1();
   return 0;
}

with the following output, which looks reasonable:

ref = 15
ref = 30

It seems that ref points to memory that is writeable. Does the line:
   int&& ref = foo();

allocate writeable memory for use by ref?
Is this standard compliant?
The code was tested using g++ 4.8.2.
Answer: Yes, the behavior is well-defined because by binding the return value to an rvalue reference, you've extended the lifetime of the temporary to match that of the reference it is bound to.
From §12.2 [class.temporary]

4   There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. ...
5   The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except:
... (list of exceptions, none of which apply to this case)

Note that the lifetime extension rule only applies to prvalues, and not xvalues (refer to §12.2/1). So if your example did the following, you'd have a dangling reference:
int&& ref = std::move(foo());

Comment: I take your word for it, but I haven't quite grasped the difference `std::move()` makes for `ref` to be a dangling reference.

Memory referenced by rvalue references


Proving that "If $n^2$ is even, then $n$ is even" without using proof by contradiction.

Question: If $n$ is an integer and $n^2$ is even, then $n$ is even
I am reading a book on proofs and the above statement motivates the author to introduce Proof by Contradiction. I am a little confused as to why this proof motivates the introduction of a new proof strategy.
The previous method that the author has been using (which he claims "fails us" for this proof), is something he refers to as the Forward-Backward Method. As far as I can tell, the Forward-Backward Method is still valid and works like so:

if $n$ is even, then there exists an integer $k$ such that $n=2*k$
if $n^2$ is even, then there exists an integer $m$ such that $n^2=2*m$

now, my objective is to show that I can rewrite $n^2$ in the form of $n=2*k$, which the author claims I cannot do using the forward-backwards method. However, I would proceed as such:

take the square root of $n^2$ to generate: $n=\sqrt{2*m}$
this can be rewritten as $n = \sqrt{2*2*\frac{m}{2}}$
then we have $n=2*\sqrt{\frac{m}{2}}$
so let's have $k = \sqrt{\frac{m}{2}}$
however, recall that $k$ has been defined as an integer...so, keeping in mind that $m$ must also be an integer, let's let $m$ be defined as: $m = 2*(\mathbb N^2)$. ...where the fancy $N$ is any natural number

Step 7 guarantees that $m$ and $k$ will always be integers which therefore let's us confirm that:

$n = 2k$

If anyone could confirm that this is logically valid, and that I am correct in thinking that I do not need to utilize Proof By Contradiction in order to prove this statement, I would greatly appreciate it!
Edit: Upon further reflection, I think this proof may only be valid for $n$ greater than or equal to $0$.
Comment: $n^2-n = n(n-1)=\text{even}$
Comment: What do you mean by "$k$ has been defined as an integer"?  The only definition of $k$ is $k=\sqrt{m/2}$  Why should this be an integer?  It's equal to $n/2$.  Saying that it's an integer is asserting that $n$ is even.  You are assuming what you need to prove.
Comment: I have no idea what you mean at step 7.
Comment: A direct proof should at some point use (that $n$ is an integer and) the uniqueness of a multiplicative decomposition in prime factors (and the fact that $2$ is prime in $\Bbb Z$).
Comment: @Blue That is so wonderfully elegant. I will keep that for further teaching reference.
Comment: You can't take as an principle that $n$ is even, since you are trying to prove that... @Blue - I deleted my other comment, because it was stupid!
Comment: @Blue Now that's cute and slick as well.
Comment: Step 7 is my way of constructing a very specific $m$ such that $m$ will always be an integer (which I assumed to be true) and that $k$ will always be an integer(which I assumed to be true). The fancy $N$ was my way of denoting "Natural Number". This ensure that $n$ ranges from 0 to infinity at integer intervals. Is there a more clear way of conveying "Natural Number"?
Comment: in Step 1, I say "then there exists an integer k"
Comment: That is to say, $n$ is even.  Why not stop right there?
Comment: At the beginning of the proofs, part of the definitions of $k$ and $m$ that I impose are that they are integers.
Comment: @DonThousand. As usual, I gave an A that's longer & more complicated.
Answer: There exist integers $m, r$ with $r\in \{0,1\}$ and $n=2m+r.$ Therefore   $$n^2/2\in \Bbb Z \iff$$ $$\iff r^2/2=n^2/2-(2m^2+2mr)\in \Bbb Z \iff$$ $$\iff r^2/2\in \Bbb Z \iff$$ $$\iff [(r=1\land r^2/2\in \Bbb Z)\lor (r=0\land r^2/2\in Z)] \iff$$ $$\iff  [(r=1\land 1^2/2\in \Bbb Z)\lor (r=0\land 0^2/2\in \Bbb Z)]\iff$$ $$\iff [r=0\land 0\in \Bbb Z] \iff r=0 \iff$$ $$ \iff n/2=(2m+r)/2=m\in \Bbb Z \iff$$ $$\iff  n/2\in \Bbb Z.$$
Comment: You didn't misunderstand. Sometimes I just post an alternate proof.
Comment: sorry if I misunderstood what the tag, "Proof Verification", entailed...but I just wanted to know whether or not my proof is accurate. Thank you for the supplementary proof nonetheless.
Answer: If $n=0$ we are done!  Without loss of generality, assume $n>0$.
The integer $n$ has a unique prime factorization of the form:  $$n=p_1^{k_1} \cdot p_2^{k_2} \cdots p_L^{k_L} \quad (\textrm{ with } p_1<p_2<\cdots < p_L).$$
So $$n^2=p_1^{2k_1} \cdot p_2^{2k_2} \cdots p_L^{2k_L}$$
Since $n^2$ is even, $p_1=2$.  Thus $n$ is even.


loop problems in fetched json

Question: I'm still fighting with this code, actually i'm trying to find a solution, everywhere, i tried many times all the whole day.
So, i have this code, i used the fetch API in order to get the values, i can iterate the first json because i need to get the id (from album json).
now i would use the loop in order to get the values from the 2nd json in order to put under each id got from the first json the values with the same id from the second json so "albumId" from photo.
Thanks in advance

async function getUsers() {
  let url = "https://jsonplaceholder.typicode.com/photos?albums";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function getPhotos() {
  let url2 = "https://jsonplaceholder.typicode.com/photos?photos";
  try {
    let res2 = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function renderUsers() {
  let albums = await getUsers();
  let html = "";
  albums.forEach((album) => {
    let htmlSegment = `<div class="user"><h2>${album.id}</h2></div>`;

    html += htmlSegment;
  });

  let container = document.querySelector(".container");
  container.innerHTML = html;
}

renderUsers();

Comment: It's not clear from your post what your actual question is. If you have problems with your code, please explain what they are; what should your code do vs what does it actually do
Comment: Is there any relationship between the two JSONs?
Comment: Between the 2 json there's only a relation, pratically the json albums has an "id" the same value can be found in photos with the name of albumiD, looks like the only common value, the problem is that what i would achieve is to have all the photos belonginf to id1 then all the photoes belonging to id 2 and so on.
Comment: What it actually does is to take the id's from albums, and sort them. now i would use a loop where i can put all the photoes that belongs to id1 under the id 1 and so on....
Answer: Call both getUsers() and getPhotos() in renderUsers(). Then you can find the elements of photos with the matching albumId and add the images to the HTML.

async function getUsers() {
  let url = "https://jsonplaceholder.typicode.com/photos?albums";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function getPhotos() {
  let url = "https://jsonplaceholder.typicode.com/photos?photos";
  try {
    let res = await fetch(url);
    return await res.json();
  } catch (error) {
    console.log(error);
  }
}

async function renderUsers() {
  let [albums, photos] = await Promise.all([getUsers(), getPhotos()]);
  let html = "";
  albums.forEach((album) => {
    html += `<div class="user"><h2>${album.id}</h2>`;
    let albumPhotos = photos.filter(p => p.albumId == album.id);
    albumPhotos.forEach(photo => {
      html += `<img src="${photo.url}">`;
    });
    html += '
';
  });

  let container = document.querySelector(".container");
  container.innerHTML = html;
}

renderUsers();

loop problems in fetched json


Let $\{x_n\}$ be a sequence in a metric space such that $\{x_{2n}\}$, $\{x_{2n+1}\}$ and $\{x_{3n}\}$ all convergent. Show that $\{x_{n}\}$ converges

Question: I don't know how to begin this. My thoughts are that since there are three convergent subsequences, we could use some knowledge about their limits to construct our convergent sequence but I'm not sure how to prove $x_n$ also converges. Is there a property of metric spaces I should use, or something about Bolzano-Weierstrass theorem (for metric spaces)?
EDIT: As noted in a comment I am not allowed to assume they all converge to the same limit.
Comment: You can't assume, but you can prove it. Assume that "even" and "odd" subsequences have different limits, and use convergence of the third subsequence to arrive to a contradiction.
Comment: You can't assume that all the subsequences converge to the same limit $L$.
Comment: True.. Is there something to notice about the $2_n$, $2_{n+1}$,$3_n$ that I should take advantage of?
Answer: Assume that
$x_{3n}\rightarrow L$ and $x_{2n}\rightarrow M$, $x_{2n+1}\rightarrow N$, then the sequence $\{x_{6n}\}$ is a convergent subsequence of both $\{x_{3n}\}$ and $\{x_{2n}\}$, so $L=M$. The sequence $\{x_{6n+3}\}$ is a convergent subsequence of both $\{x_{3n}\}$ and $\{x_{2n+1}\}$, so $L=N$, so $L=M=N$.
Comment: $\{x_{3n}\}$ isn't actually a subsequence of either of those, is it?
Comment: Split again to get $\{x_{6n}\}$ and $\{x_{6n+3}\}$ then it goes through, thanks for reminding.


Get the closes coordinates to (0,0)

Question: I'm making a system where I'm drawing a cube and I need to get the correct cordinates. Im trying to calculate the width and height correctly
There 4 case scenario:

Correct scenario

x1=10
y1=10
x2=30
y2=40
width=(x2-x1)=20
height=(x2-x1)=30
This would be correct as the x1,y1 are closes to 0,0

Bad scenario's

x2=5
This would result in Width= -5 and therefore the closes point to 0,0 would no longer be x1,y1 and an imagery on that dost exist. Same with y2 or both.
How can I calculate this correctly?
Comment: Can't you just use absolute value to fix this?
Answer: Why do you need the closest point to $(0,0)$? It shouldn't be difficult to modify the drawing code to handle negative widths.
Alternatively, assuming that all of the coordinates are positive, you could do something like
if(x1 > x2)
  std::swap(x1,x2);
if(y1 > y2)
  std::swap(y1,y2);

and then call your old code.

Get the closes coordinates to (0,0)


Loading and modifying svg within Inkscape plugin

Question: I am currently writing an Inkscape plugin using Python. Within this plugin, I would like to load a template (an existing svg) from the plugin folder and access some objects within this template by name or key. Then I would like to change the border and/or fill color of the object and add some text to it. How would I do this using the python scripting interface of inkscape? I found just a few examples (see below) on how to write a plugin for inkscape, but they all work on existing, already opened documents.

http://www.hoboes.com/Mimsy/hacks/write-inkscape-extension-create-multiple-duplicates/
http://wiki.inkscape.org/wiki/index.php/Script_extensions
http://ospublish.constantvzw.org/blog/tools/inkscape-plugins-in-python
http://wiki.inkscape.org/wiki/index.php/Generating_objects_from_extensions
http://wiki.inkscape.org/wiki/index.php/PythonEffectTutorial
Answer: Can you use lxml?
t = etree.parse("path/test.xml")

You could then either

manipulate the properties of t directly -- this can be done from python without actually opening inkscape. Your tree could be saved with t.write("filename")
add  t to the currently open document using self.document.getroot().append(t)

Also, this is not what you asked for, but may come in useful: an inkscape plugin that allows you to write short python snippets from within Inkscape: http://www.smanohar.com/inkscape.php


Difference between family = gaussian() and family = cox.ph(link='identity') in GAM and family = binomial(link="logit")

Question: I wonder how do u decide if family = gaussian() or family = cox.ph(link='identity') or family = binomial(link="logit") in GAM ( generalized additive model ) is suitable for the analysis? For my case, my dependent variable is in the form of percentage from 0 - 100%. Stage is a form of time variable. comparison_type is the two different activities performed by the same individual over a specific stage, which means time.
My end goal is to see if there is any significant difference in patterns between the two activities performed by the same individual over time.
library(gam)
library(mgcv)

b <- gam(ssim_exp ~ s(stage, k = 4, fx = TRUE, by = comparison_type) + comparison_type, data = df, family = cox.ph(link='identity'))
summary(b)

The distribution of my dependent variable looks like the below

Any input?
Answer: The choice of the conditional distribution of the response should be motivated by the features of the response variable you are modelling. The Gaussian distribution can be used for data that are continuous and over the whole real line (not integers and can be positive or negative), whereas the gamma, inverse Guassian, or Tweedie distributions are for positive (non-negative in the Tweedie case) continuous random variables. Distributions such as the Poisson or negative binomial are for non-negative, integer valued responses. Binomial is for counts from a total (number of heads out of m coin tosses, for example). The Cox PH family is for modelling survival data (time to event data), where you are interested in modelling the hazard of an event.
None of these distributions are suitable for the data you describe, which are bounded at some upper and lower value, but are continuous between the two bounds. If the data were recast to the interval 0-1, then you could look at the beta distribution (family = betar()) in {mgcv}, but you can't have true 0s and 1s (100%) in that family ({mgcv} will adjust the data so that the 0s are just slightly greater than 0, and the 1s slightly less than 1). If you have many such values, then zero-one-inflated beta models (which combine separate models for the 0s, 1s, and everything else) would be a starting point. But that distribution is not available in {mgcv}; you could look at {brms} for example as an option in that case.
I've taken you to have a continuous bounded value as the response, but there is some wiggle-room in your use of "form of"; if there is something specific you think we should know then edit your question to include it.


How does network pricing work exactly in cloud platforms? And how should I avoid dedicated pricing attacks?

Question: I am pretty new to cloud platform infrastructures. For the sake of discussion simplicity, let's say the only two platforms I am discussing are AWS and Google Cloud.
Now say I have an HTTP server that mainly handle HTTP response through an open API for an online game. Let's say the average response size is 10KB and there will be around a million responses being sent per day.
Based on my understanding the monthly price depends on the amount of data transferred in terms of GB. Now my problem is that if someone writes a script that keeps getting response from my server repeatedly the price will just grow to sky high.
I am sure any good server avoids this problem but I am not sure how exactly is this problem avoided. Based on my observation, many real life large online-game API servers do not optimize their response size when its just a few KBs. There must be some kind of "fixed monthly payment or payment based on the amount of data transferred per second" thing happening that does not depend on the amount of data transferred.
However I simply just couldn't find any reference on the platform websites for such options.
Any help would be appreciated.
Comment: "payment based on the amount of data transferred per second" is called "95 percentile billing" and that's how wholesale IP transit is sold.  However, none of the big cloud providers have public pricing for it. Pricing is a major reason why people still rent cabinets at a colocation facility instead of using cloud services. Btw most cloud providers only charge for outbound data so the attacker can't just send random packets. If you had a magic oracle that told you which incoming packets are bad, you could choose not to respond to them. Real implementations have loads of tradeoffs.
Answer: Cloud services provide awesome benefits for projects, which are specially built for using them. If we are talking about application/web hosting, then cloud pricing models suit businesses, which acquire their main income from users, who use said application/web-site.
Unless that is your main source of income (in which case you should easily convert between raw web traffic and profits), then cloud hosting might not suit you at all.
Keep in mind that if your application was not built for cloud infrastructure (like the said game server), you won't have any benefits over single-instance VPS/Dedicated hosting, unless you spent some amount of time doing devops work. The same devops work is needed to effectively prevent attack on your bandwidth you described.
Since that kind of attack has already got a name - you can find some more or less viable advises by searching for "Denial of Wallet"
Comment: Thank you for the answer. If I assume the main source of income is indeed user, is it the case that such"Denial of Wallet" attack does not make my cost much higher than the income? If it is the case how much the income will need to be to make such an attack ineffective in terms of income ratio?
Comment: Well, usually applications are made that way, that it would be pretty hard to just exhaust them by traffic alone. The easiest way to prevent such abuse would be rate limiting requests with something like nginx. And for those who really count every penny, there are companies, which claim to provide just those means to control every bit of traffic and its costs, while still using GCP. Not sure if its a good courtesy to point to an actual commercial products, but you shoud search for something like "Cloud Volumes ONTAP alternatives" to get an understanding what those companies offer
Comment: "that you it would be pretty hard to just exhaust them by traffic alone" Can you elaborate a bit more on what "exhaust" mean? Does that mean financially? If true does that mean keep getting 10KB/s response from a single home network for a month will only have minimal effect on the server total price?
Comment: 10 kb/s would be 24 GB/month, which would in the worst case cost you around $6.25. And since cloud computing is by all means the opposite thing of something that can save you money, you should be absolutely prepared to easily pay that sum. In no way you can ever ever save money by using cloud computing (unless you're running some niche applications like f.e. irc bot (in which case it indeed may be near free to run on gcp). any other use case would definitely cost less with a single instance vps)
Comment: The cloud has actually made many things cheaper. In the **old** days (year 2000), a single T-1 was $1,500 per month. We could not imagine the speeds and pricing that we have today. The raw cost of cloud computing is one component of total costs. Often personnel cost an order more than the resources they manage. When deploying a system, a cost analysis is performed, a risk analysis is performed, etc. Since you are concerned about networking costs, hit the books and learn networking self-defense 101.
Answer: Neither cloud vendor offers XX bandwidth at a fixed price. Pricing is consumption based.
You are responsible for controlling client access to your resources.
This means deploying authentication or throttling or other technologies but you choose how and with what products.
Cloud services are much like building a house. Home Depot does not give you unlimited nails and lumber. You purchase what you need to build your house. You then purchase fuel to heat your home.
I have been working in the cloud since day zero. Before that private data centers. Your concern is possible, but in the real world, it does not happen enough to stop most of us from deploying in the cloud. In order to consume your bandwidth, I need to consume my available network bandwidth. If a hacker wants to take you down, there are many more painful methods they can deploy that are a lot cheaper for them and that are more difficult to track who/where they are located.
Comment: It seems that you got a preconception, that cloud computing is a service, which only a couple of IT-giants provide, but actually if you care about traffic that much, but still want to have CDN, you can easily (and I mean in a day or two of work) get yourself a private kubernetes kluster running on VPS-es with unlimited traffic all around the world. All it takes is signing up for a cheapest unlimited traffic hosting in every country you want and then issuing a single ansible/terraform command to get it running. [More info](https://kubernetes.io/docs/setup/production-environment/tools/_print/)
Comment: Thank you for the answer but I am still unclear. Based on my understanding home networks can be contracted via fixed bandwidth per month. So if the purpose of the attacker is to cause the server "total amount of data per month" to increase, he can send not so concentrated data but send consistently over a month. How is this avoidable? As for the authentication case, there are real-corporate high profile servers that I myself can even get the server response now for some API so I don't thin that's how they solve the issue.
Comment: Absolute majority of customers don't need that kind of limits (since they use cloud exacly because it can provide MORE & FASTER download speeds for endusers). Those who some reason want to limit bandwidth instead of getting an unlimited traffic vps (which IS certainly a much better way for them to reach their goals), can easily do that with the means of iptables/tee/htb in their instance themselves
Comment: Thank you. Does that mean even if a single "bad hacker" person keeps sending get response script (say get 10KB data per second) for a month via a home network, it won't affect much the total price for those majority of customers?
Comment: One example of such script I found is https://github.com/thesadru/genshinstats for a large real life game called Genshin Impact. I am just wondering why there isn't any rival company personnel attacking this game via the method I mentioned. It must be ineffective whilest the API is totally publicly accessible (there are cookies needed but that's obtainable for anyone).
Comment: Sorry if I did not state clearly. I myself actually don't really care about traffic that much but am just curious about why the kind of attack I mentioned do not work for large company servers. The two premises assumed to be true and I believe are true are: (1) those companies have a lot of rivalries with other companies (2) their server APIs are publicly available to get HTTP responses.
Comment: Nah, if you was a large company, you definitely would had been able to get a LIR status and your own AS-number along with some peers around the world, which would have made traffic essentially free for you. But since nowadays anyone can get their private kubernetes cloud running, anyone can nullify their traffic costs. There is no problem with not paying for the traffic. The reason why people pay for traffic is not because they got no other choice, but because GCP/AWS has really reliable and fast network (which in absolute majority of cases is faster that the one you can get for free)
Answer: On the server side, the ways to avoid this are:

Require authentication for requests. IOW, make it such that you can track down who is making such attacks, and make such attacks a bannable offense. Then properly lock down your account creation so that it's not easy to get new credentials after you get banned.
Implement rate limiting. Usually this is done in multiple stages, often rate-limiting per authenticated account (so any user has a rate limit), per API endpoint (so computationally expensive endpoints that don't get called very often can't be easily abused for DoS attacks), and possibly overall per IP. You should be doing this for other reasons (most notably protecting against smart DoS attacks and the possibility of timing-based attacks on the game logic).
Utilize good compression in the protocol. For your stated response size, Brotli is probably worth looking into (or possibly snappy or LZ4), it should be fast enough to meet your performance needs but still shave a few kB off of the response size, and at the point of dealing with millions of requests per month, that's a nontrivial amount of data saved.

As far as mitigating it elsewhere, that's not as easy to do. Full cloud providers like what you are talking about often provide some minimal 'free tier' to let developers easily experiment without costing an arm and a leg. I think for AWS it's 5GB per month outbound (they don't charge for inbound data at all) for example. That's as close as you can get in such a full cloud setup to block usage as you are talking about, because most users will benefit from having exact usage prorated as opposed to buying in 'chunks'.
If you really want a big chunk though, look into AWS Lightsail. There, you buy a package deal of a virtual node that includes some fixed number of CPUs, fixed amount of RAM and integrated storage, and a specified network usage cap. Network usage below that cap in a billing cycle costs nothing, while above is prorated just like in a full cloud setup.  I do not know if GCP has an equivalent, but most VPS providers (such as Vultr, Linode, or Digital Ocean) work the same way for their primary offerings and I would actually suggest looking there instead if you go this route. The network caps on these are usually in the multi-terabyte range, and the norm is that only the direction that has higher usage gets tracked for accounting.


drupal7 Webservices create a node

Question: I am using Drupal 7 and creating a webservice.
and using http://delta.indivar.info/tanenttest/drupalgap/node this webservice. i am trying to create a node using poster plugin of Firefox
and i am passing parameters as
type='page'
it shows  ["Access denied for user anonymous"]
i can't give permission for Anonymous user. is there is any way so that only authenaticate user can create node.
Answer: When using the Poster plugin for Firefox, you need to be logged into your Drupal site in another tab. Then you can use the Node Create resource. Keep in mind that you'll need to pass along the X-CSRF-Token in the header of the request. You can get the token from here, after logging in:
http://www.example.com/?q=services/session/token

drupal7 Webservices create a node


Reestablishing development workflow with GIT after doing it wrong

Question: At one point, I had the following proper Drupal development workflow: local development environment (using Mamp), dev server for testing and a production server, and I used GIT to deploy the changes from the local to the repository and then I would pull from the repository into the dev or production server. MAMP was causing me a lot of issues so I uninstalled it in favor of setting up a LAMP stack in a more traditional way. But I'm using a Mac and things got really wonky. I basically messed up my local dev environment beyond all repair and wasn't able to use it but I had an aggressive deadline for a project.
I began to make many changes to the website on the dev server and then doubling the work on the live site, no longer using the local environment or pushing the changes up using GIT. During this time, I didn't commit any of the changes to GIT either. Basically, GIT and the local dev have been out of the picture for the last several months.
Since my last commit, the following situations have changed.

created a new git repository that I want to use
my local dev stack is still non-functional
I want to set up a new host so I can test my existing dev site for current hosting issues

Where do I go from here in order to get back on track so that I can move the current website to a new host and preserve the GIT history without being able to use a local dev environment?
Comment: Basically to preserve git history, you need to retain the .git folder in the project. It's hidden unless you look with command line or git GUI. If you've deleted that, any past history is gone.
Answer: Commit the changes on the live site to the master git branch and then branch off this to create a develop branch.
The master branch should mirror live and development takes place on individual branches, when you're ready merge or pull request onto the develop branch. When ready to go live merge or pull request into master.
Comment: You will need to generate a new public/private key pair for the production server and then add them into the Git repository
Comment: How is it possible to push from a remote host to the repository? I am using Debian and all access is done via public ssh key. Thus, if I try to push code from the production site to the new Git repository, I get access denied.
Comment: This is the right answer. I ran into a different snag wherein I can't push because of some large included several commits back. I'll have to search for that.
Comment: It's covered at https://git-scm.com/book/en/v2/Git-Internals-Maintenance-and-Data-Recovery#_removing_objects but can be quite difficult


Problema com acentuação no IIS 10 (Windows 10) usando ASP clássico

Question: Fiz várias pesquisas há 2 dias e tentei de tudo mas não consegui resolver o problema, que é o seguinte:
eu ativei o IIS no Windows 10 home 64 bits para usar páginas locais em ASP clássico. Até aí tudo beleza, funcionando direitinho, porém percebi que ao enviar um texto com acentuação através de um POST num formulário e capturando ele por um REQUEST, onde tem acento ele retorna caracteres estranhos, como se o servidor não reconhecesse acentos.
Por exemplo: a palavra "capítulo" vem no REQUEST como "cap�tulo", e no banco MySQL é gravado como "cap?tulo". Se eu coloco a QUERY direto na URL (Ex. ?nome=capítulo), o REQUEST retorna errado também "capítulo" mas grava corretamente no banco de dados.
Sou um pouco inexperiente nisso e já fucei tudo e não consegui resolver. Alguém saberia como corrigir isso?
Comment: O seu problema parece ser **_encoding_** (inglês). Olharia configurações de _localização_ ou _globalização_ no IIS e no MySQL a opção **CHARACTER SET**. Recomendo a leitura do texto [O Mínimo Absoluto que todos os Programadores de Software precisam, absoluta e positivamente, saber sobre Unicode e conjuntos de caracteres (sem desculpas!) — The Joel on Software Translation Project](http://local.joelonsoftware.com/wiki/O_M%C3%ADnimo_Absoluto_Que_Todos_os_Programadores_de_Software_Precisam,_Absolutamente,_Positivamente_de_Saber_Sobre_Unicode_e_Conjuntos_de_Caracteres_(Sem_Desculpas!))
Answer: Obrigado pela ajuda mas consegui resolver. O problema não era na configuração do servidor. Era uma include que estava sem o charset, e por isso "bagunçando" o resto da página.


Cello string crossing from open string to fourth finger: unwanted harmonics

Question: I've been practicing slurred bows in 1/8th notes on cello for Pachelbel's canon, and there are many places where there is a string crossing in one bow either from fourth finger on the D string to the open A string or the other way around. Every time I cross strings this way, I can't help but produce harmonics from my pinky barely touching the A string or D string while going to the next note.
Is there a way for that not to happen? I'm always confused with those kind of problems on the cello as I also play violin, and never encountered this type of problem. One thing my teacher mentioned a while ago was to pre-place the fourth finger while still playing the open A string so that it doesn't touch the A string at all, like as if playing a chord, but I just can't make it work :/
Thanks in advance!
Answer: This is a matter of left-hand shaping. You are by no means alone in this difficulty with the pinky finger.   What you want to practice is keeping your fingers and hand in a "high arch", while not raising your elbow too far. Keep your fingers, as much as possible, curved.   Concentrate as well on letting your left hand "lean" a bit towards the bridge, which will make it easier to keep the pinky curved rather than flattening out.
And finally, remember to let your left hand and arm move as a unit from left to right so your arched fingers are always above the string being fingered.
It takes a lot of practice and observation, so give it time.   One thing I do on occasion is to play, e.g., simple passages on the D-string while double-stopping with the A string.  If I hear a clean "A" I know I'm ok, but if the pinky harmonic pops up, then I know my hand position has strayed.
Comment: I will add that having strong finger muscles helps you maintain this shape.  There is a reason you see cellists carrying one of those small spring-loaded finger strengtheners and squeezing them.
Comment: Thanks for the answer and the ideas of things to work on. Having a curved pinky is definitely something I struggle with on the violin as well, as soon as I press down with some precision or strenth, it doesn't flatten out, but gets straight and only the last phalange bends... I'm not sure if it's because it's naturally shorter than the other fingers, or just me having trouble getting the same curvy shape as with the other fingers.

I'll give that double-stop exercise a spin!


how to create unit vector by scaling two components

Question: I have a 3D vector with length != 1 but all components lie within [-1, 1].
now I want to create a unit vector such that this unit vector has the same x coordinate as the original vector and the cross product between the x-axis and the new vector shall point in the same direction as the cross product between the x-axis and the original vector.
How do I need to scale the y and z coordinates to achieve this?
Answer: Let see, suppose the original vector is
$$v=(a,b,c)$$
and the unit vector is
$$u=(a,d,e)$$
such that
$$u \times (1,0,0)=\lambda\cdot v \times (1,0,0) \iff e \hat y-d\hat z=\lambda c \hat y-\lambda b\hat z$$
that is
$$u=(a,\lambda b,\lambda c)$$
with the condition
$$a^2+(\lambda b)^2+(\lambda c)^2=1 \implies \lambda=\sqrt{\frac{1-a^2}{b^2+c^2}}$$
Comment: so, how do I solve for λ? there should be only one solution (the one in which the vector points in the same direction, not in the opposite one)
Comment: @user1282931 By $\lambda^2=\frac{1-a^2}{b^2+c^2}$ we obtain $2$ solutions which lead to two opposite vectors for $u\times (1,0,0)$.
Comment: @user1282931 The $\lambda$ positive should be the correct one.


PySide2 erro ao usar o metodo QWidget.render(), como contornar?

Question: Estou tendo problemas para imprimir um widget. Ao executar o código abaixo é retornado um erro.
<code>    #p é uma instancia QPrinter

    painter = QPainter(p)
    painter.setRenderHint(QPainter.HighQualityAntialiasing)
    xscale = p.pageRect().width()/ self.width()
    yscale = p.pageRect().height()/ self.height()
    scale = min(xscale, yscale)
    painter.translate(p.paperRect().center())
    painter.scale(scale, scale)
    painter.translate((self.width()/2)*-1,(self.height()/2)*-1)
    self.render(painter)
    painter.end()
</code>
O error retornado é:

TypeError: 'PySide2.QtWidgets.QWidget.render' called with wrong argument types:
PySide2.QtWidgets.QWidget.render(QPainter)
PySide2.QtWidgets.QWidget.render(PySide2.QtGui.QPaintDevice, PySide2.QtCore.QPoint = Default(QPoint), PySide2.QtGui.QRegion = Default(QRegion), PySide2.QtWidgets.QWidget.RenderFlags = Instance(QWidget.RenderFlags(QWidget.DrawWindowBackground | QWidget.DrawChildren)))

O que não estou entendendo é, esse mesmo código no PyQt5 funciona sem problemas. Alguém poderia ajudar ?
obs: não gostaria de usar o pyqt5
Answer: tente passar os parametros do metodo render explicitamente, tente o seguinte:
<code>    painter = QPainter(p)
    painter.setRenderHint(QPainter.HighQualityAntialiasing)
    xscale = p.pageRect().width()/ self.width()
    yscale = p.pageRect().height()/ self.height()
    scale = min(xscale, yscale)
    painter.translate(p.paperRect().center())
    painter.scale(scale, scale)
    painter.translate((self.width()/2)*-1,(self.height()/2)*-1)
    self.render(painter,QPoint(0,0),painter.viewport()) #parametros expliclitos
    painter.end()
</code>


What do the red and green dots mean on the property symbol in Structure view in Android Studio

Question: What do the red and green dots in the lower left of the symbol indicate?

The documentation for symbols in IntelliJ / Android Studio does not mention their meaning.
Answer: Green = getter, red = setter.
If I have
<code>private boolean mBacon = false;

public boolean getBacon() {
    return mBacon;
}

public void setBacon(boolean b) {
    mBacon = b;
}
</code>
I get


kernel panic - no idea how to fix

Question: My Alfresco server suddenly stopped booting and gave me this message upon bootup:
ACPI: Getting cpuindex for acpiid 0x5
ACPI: Getting cpuindex for acpiid 0x6
ACPI: Getting cpuindex for acpiid 0x7
Red Hat nash version 184.108.40.206 starting
    Reading all physical volumes. This may take a while...
    Found volume group "VolGroup00" using metadata type lvm2
    3 logical volume(s) in volume group "VolGroup00" now active
ata1.00: exception Emask 0x0 SAct 0x0 SErr 0x0 action 0x0
ata1.00: BMDMA stat 0x24
ata1.00: cmd c8/00:00:3d:19:86/00:00:00:00:00/e0 tag 0 dma 131072 in
ata1.00: status: { DRDY DF ERR }
ata1.00: error: { ABRT }
ata1.00: revalidation failed (errno=-5)
ata1.00: revalidation failed (errno=-5)
ata1.00: revalidation failed (errno=-5)
JBD: Failed to read block at offset 21726
EXT3-f: error loading journal.
Buffer I/O error on device dm-0, logical block 2057
mount: error mounting /dev/root on /sysroot as ext3: Invalid argument
setuproot: moving /dev failed: No such file or directory
setuproot: error mounting /proc: No such file or directory
setuproot: error mounting /sys: No such file or directory
switchroot: mount failed: No such file or directory
Kernel panic - not syncing: Attempted to kill init!

This is my first time encountering this. Is it safe to say that the problem is with the hard drive? I'd like to try and mount the hard drive to another system so I can retrieve the files. How do I fix this system? Or, should I just start creating a new server to replace this one if you think this is irrepairable?
Answer: I'm really sorry for your loss.
That disk has died.
ata1.00: cmd c8/00:00:3d:19:86/00:00:00:00:00/e0 tag 0 dma 131072 in
ata1.00: status: { DRDY DF ERR }
ata1.00: error: { ABRT }

That's pretty much the swan song of a dying SATA disk.
You should probably create a new server, restore from your last known good backup, and carry on.
You might want to investigate RAID for multiple disks on your server to give you  resilience against disk failure..
Comment: @dashmug You might get a few things off the drive, or you might just make it worse. If it's that important, send it to a professional data recovery service.
Comment: R.I.P., faithful drive.
Comment: Ouch! It's really bye, bye then.
Comment: Yes, I think that's it. It's an old server that I inherited.
Comment: I was just told that there are very important files that need to be retrieved. What are the chances that the files are recoverable?

kernel panic - no idea how to fix


How to articulate on a Saxophone with the mouthpiece upside down?

Question: I'm trying to learn to play the saxophone with the mouthpiece upside down because of nerve damage in my lower lip and roots of my lower teeth.
  Tonguing is difficult.  What are some suggestions?  Are there different ways of articulating?
Comment: Having to tongue with the upper jaw no doubt takes some getting used to....
Answer: First, I strongly recommend that you find a teacher who has experience working with people with physical ailments like this. This is highly nonstandard and trying to make recommendations based on written descriptions is going to have limited value. Anything a qualified teacher says should override anything I or anyone else says here.
That being said, I have played like this as a joke. There was a music video that made the rounds a few years ago where someone was miming playing a soprano sax with the mouthpiece upside down, and I demonstrated playing this way to show that it wasn't actually impossible like many people thought. I even got pretty good tone and articulation. The main problems I ran into were:

I had to hold the instrument tipped way up for the reed to enter my mouth at a good angle. A custom neck could solve this problem.
The vibration of the reed tickled my upper lip horribly, to the point that I couldn't bear to hold a note for more than a fraction of a second.

Articulating the proper way (with the tongue hitting the reed) is basically impossible, but you can instead tongue against the roof of the mouth right behind the reed. This effectively makes every note an air attack, but this type of tonguing serves to build up pressure behind the tongue which mitigates that negative effect. This is akin to how brass players tongue, and it's very possible to get clean, strong attacks on those instruments, so I feel like it should be viable on single reeds with some practice.
Comment: Do you know who makes custom necks for tenor saxophone?


Tennis movement while opponent is serving?

Question: Our opponent was serving to my partner.
I was moving my feet in place just to keep from being sedentary. Not moving wildly, just kind of shuffle back and forth in place.
The server missed and blamed me for moving and said that I am not allowed to move while the opponent is in the service motion.
I let her take the serve over but I don't think that is right.
What is the rule on this?
Answer: Note: This is regarding the partner of the receiver, not the receiver themself.
It is possible under the rules to be called a hindrance according to the ITF Rule book
Rule 26

HINDRANCE

If a player is hindered in playing the point by a deliberate act of the opponent(s), the player shall win the point.
However, the point shall be replayed if a player is hindered in playing the point by either an unintentional act of the opponent(s), or something outside the player's own control (not including a permanent fixture).

Case 5: In doubles, where are the server's partner and receiver's partner allowed to stand?
Decision: The server's partner and the receiver's partner may take any position on
their own side of the net, inside or outside the court. However, if a player is creating a hindrance to the opponent(s), the hindrance rule should be used.

As to whether the movement of the partner of the receiver is hindering could be up for debate, but consider this... how far does it go? Could they start jumping up and down waving their arms or yelling out at the time of the serve be considered a hindrance?
In a recreational match, such rules are hard to enforce as there typically is no umpire and it is down to the players themselves being honest and fair.


Heartbeat should not shut down spare webserver

Question: I have a simple heartbeat setup that watches my 2 servers and transfers the ip public to another server in case of a crash
/etc/heartbeat/haresources
server1 192.168.1.203 nginx

However I would like nginx to be active on both servers (192.168.1.201 and 192.168.1.202) so that I can balance the backsteam load (why not, server is up anyway !)
unfortunately nginx takes over startup and shutdown of niginx leaving nginx not started on one server.
What is the best way to deal with this ?
Thx !
Answer: You can simply remove the word nginx from /etc/heartbeat/haresources. So, the line will read:
server1 192.168.1.203

Don't forget to make sure nginx is started automatically during system startup.
Comment: thx, but please correct me if im wrong (and I probably am) but adding nginx to the line make heartbeat monitor nginx right ? So in case the server is up but nginx is down this wouldn't cause the ip to switch ?
Comment: @Floortje: heartbeat does not monitor services by default unless you combine it with some other tool like pacemaker. You can try to use [monit](http://mmonit.com/monit/) if you don't want to go into the complications of adding service monitoring to heartbeat.
Comment: Ok thx ! Great awnser I will go and study more !!


Android toolbars and whether they are nullable

Question: As seems to be typical for Android development, it doesn't work.
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val toolbar: Toolbar = findViewById(R.id.toolbar)
        //setSupportActionBar(toolbar)  Why doesn't this work? Type mismatch: inferred type is android.widget.Toolbar but androidx.appcompat.widget.Toolbar? was expected

        setSupportActionBar(findViewById(R.id.toolbar))
    }
}

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"    >

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</LinearLayout>

However:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.rwb.toolbarhide, PID: 3989
    java.lang.NoClassDefFoundError: android.widget.Toolbar
        at com.rwb.toolbarhide.MainActivity.onCreate(MainActivity.kt:13)
        at android.app.Activity.performCreate(Activity.java:5231)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
        at android.app.ActivityThread.access$800(ActivityThread.java:135)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

Is this something to do with androidx and different Toolbars?
How can you tell if this is so?
What can be done to fix it?
What I wanted to know, however, was why the line commented out doesn't work.
How can we tell if findViewById is returning a Toolbar or a Toolbar? (in VisualStudio you would just hover the mouse, but not so in AndroidStudio -- it seems to be impossible).
So, if indeed we do have a Toolbar and not a Toolbar? then how can we pass it to setSupportActionBar?
(I want a Toolbar not a Toolbar? because it's a right nuisance having to ? and !! all over the place.)
Comment: Which type of Toolbar used in imports section? I suppose it should be `import androidx.appcompat.widget.Toolbar`
Answer: import android.widget.Toolbar. It would have been done by the intellisense if it wasn't there as standard because I have no idea what I'm doing. Did it guess the wrong one?
This seems to have pacified it:
import androidx.appcompat.widget.Toolbar


WMI win32_physicalmedia or win32_diskdrive result prob

Question: I'm using visual c++ 2010.
Im trying to retrieve harddisk serial number using win32_physicalmedia or win32_diskdrive and it's working normally but on alot of pcs it displays the serial number more than once and sometimes with symbols and characters.
The code i'm using is as follow :
<code>pSvc->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT SerialNumber FROM Win32_PhysicalMedia"), // or Win32_DiskDrive
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&pEnumerator);

 IWbemClassObject *pclsObj;
ULONG uReturn = 0;

while (pEnumerator)
{
HRESULT hr = pEnumerator->Next(WBEM_INFINITE, 1,
    &pclsObj, &uReturn);

if(0 == uReturn)
{
    break;
}

VARIANT vtProp;

hr = pclsObj->Get(L"SerialNumber", 0, &vtProp, 0, 0);
    wcout << " Physical Drive SN : " << vtProp.bstrVal << endl;
    VariantClear(&vtProp);

    pclsObj->Release();
}
</code>
The result is sometimes like this :
Physical Drive SN : 325a323565222565226500
Physical Drive SN : 325a323565222565226500
Physical Drive SN : 3
Physical Drive SN : 3
Physical Drive SN : 3
Physical Drive SN : ♥
Physical Drive SN : ♥
As you can see the serial is correct but it's repeated twice in 2nd line and the other lines are showing symbols knowing that i have only 1 Hard Disk.
Please advise.
Comment: You need error checking...
Answer: Ohh guys i guess after some researches i found out that the code is also trying to get serial number of all removable devices too not only the harddisk!!
Can anyone tell me how to specify the mediatype only to fixed hard disk ! ?


Distance of two lines in $\mathbb{R}^3$

Question: Using vector methods show that the distance between two non parallel lines $l_1$ and $l_2$ is given by $$d=\frac{|(\overrightarrow{v}_1 - \overrightarrow{v}_2) \cdot (\overrightarrow{ a}_1 \times \overrightarrow{a}_2)|}{||\overrightarrow{a}_1 \times \overrightarrow{a}_2||}$$ where $\vec{v}_1$ and $\vec{v}_2$ are random points of $l_1$ and $l_2$ respectively, and $\vec{a}_1$ and $\vec{a}_2$ are the directions of $l_1$ and $l_2$.
HINT:
We consider the plane that contains $l_1$ and is parallel to $l_2$. Show that $\frac{\vec{a}_1 \times \vec{a}_2}{\|\vec{a}_1 \times \vec{a}_2\|}$ is unit perpendicular to that plane. Then take the projection of $\vec{v}_2-\vec{v}_1$ to that perpendicular direction.
How can the plane that contains $l_1$ be parallel to $l_2$ while the line $l_1$ is non parallel to $l_2$??
$$$$
EDIT:
We consider the plane that contains $l_1$ and is parallel to $l_2$. That means that the plane passes through the point $\overrightarrow{v}_1$ and has as parallel vector the vector $\overrightarrow{a}$.
To find the distance between the two lines, we have to find the distance between the points $\overrightarrow{v}_1$ and $\overrightarrow{v}_2$.
The vectors $\overrightarrow{a}_1$ and $\overrightarrow{a}_2$ produce the plane, so the vector $\overrightarrow{a}_1 \times \overrightarrow{a}_2$ is perpendicular to the plane.
So, the unit perpendicular vector to the plane is $\frac{\overrightarrow{a}_1 \times \overrightarrow{a}_2}{||\overrightarrow{a}_1 \times \overrightarrow{a}_2||}$.
A vector from the plane to the point $\overrightarrow{v}_2$ is $\overrightarrow{v}_2-\overrightarrow{v}_1$.
The distance that we are looking for the length of the projection of this vector onto the normal vector to the plane.
So, $$d=\frac{|(\overrightarrow{v}_1 - \overrightarrow{v}_2) \cdot (\overrightarrow{ a}_1 \times \overrightarrow{a}_2)|}{||\overrightarrow{a}_1 \times \overrightarrow{a}_2||}$$
Is this correct?? Could I improve something at the formulation??
Comment: Because you can rotate the plane about the line $l_1$ until it is parallel to $l_2$
Comment: Because planes are $2$ dimensional and lines are only $1$ dimensional.
Comment: Imagine the two lines intersect in 3D. A point on each line together with the intersect point define a plane containing both lines. Now translate one of the lines so they no longer cross. The translated line is not in the original plane but it is parallel to it.
Comment: Take unit vector perpendicular to $l_1 $ and $l_2$ from cross product.
Comment: I haven't understood it yet... Could you explain it further to me??
Comment: I tried to solve the exercise and added at my initial post what I have done... Could you take a look??
Comment: @MaryStar: The method and formula in your edit are perfectly correct. :)
Answer:
Given two lines in ${\mathbb{R}^3}$ by:
$$\begin{gathered}
  X = P + r \cdot U \hfill \\
  Y = Q + s \cdot V \hfill \\
\end{gathered} $$
Here we use $P,Q \in {\mathbb{R}^3}$ as "starting" points and $U,V \in {\mathbb{R}^3}$ as directions.
We take the blue line for our first paramtrization and the orange one for second. Both lines have edges of the cube in common, but different ones.
Blue line has bottom face and orange line has top face from the cube in common.
So these planes are parallel to each other.
Because lines have different directions, they aren't parallel.
We want to calculate the shortest distance of the two given lines.
The distance of two arbitrary points (here the red segment) seems not
to have shortest lenght. The green segment looks much better.
But what can we say about the green segment? The cube help's us to find the
answer quickly: The green segment is that edge of the cube, that joines
the blue line with the orange one and is perpendicular with both lines.
This makes the green segment very special. But why?
There is one very good reason. From the given directions $U,V \in {\mathbb{R}^3}$ we can build the vector or cross product $U \times V$
and we know the dots from  $U \times V$ with $U$ and from $U \times V$
with $V$ are zero. That is $U \times V \bot U$ and $U \times V \bot V$.
This is important for our calculation. Let's go:
The red segment starts in point $X$ from the blue line and ends in point
$Y$ from the orange line. We write for direction vector from $X$ towards
$Y$:
$$\begin{gathered}
  \overrightarrow {XY}  = Y - X \hfill \\
  \overrightarrow {XY}  = s \cdot V - r \cdot U + \overrightarrow {PQ}  \hfill \\
\end{gathered} $$
And of course, here $\overrightarrow {PQ}  = Q - P$ is the vector which starts
in  $P$ and ends in $Q$.
For the green segment we use point $A$ from the blue line as starting point and
$B$ from the orange line as ending point. And we write $\overrightarrow {AB}  = B - A$ as usual for direction.
But, do you remember? $\overrightarrow {AB} $ has same direction as $U \times V$! We can say this more precise:
$$\overrightarrow {AB}  = t \cdot U \times V$$
for a number $t \in \mathbb{R}$.
And now, we want the direction $\overrightarrow {XY} $ to be $\overrightarrow {AB} $. Well that is
$$\begin{gathered}
  \overrightarrow {AB}  = \overrightarrow {XY}  \hfill \\
   \hfill \\
  t \cdot U \times V = s \cdot V - r \cdot U + \overrightarrow {PQ}   \hfill \\
\end{gathered}$$
Why are we doing this? We want to find that number $t \in \mathbb{R}$.
And in less than a second, we are done. Applying the dot with $U \times V$
in last equation gives instantly:
$$\begin{gathered}
  t \cdot \left( {U \times V \cdot U \times V} \right) = s \cdot \left( {V \cdot U \times V} \right) - r \cdot \left( {U \cdot U \times V} \right) + \overrightarrow {PQ}  \cdot U \times V \hfill \\
   \hfill \\
  t \cdot {\left\| {U \times V} \right\|^2} = \overrightarrow {PQ}  \cdot U \times V \hfill \\
\end{gathered} $$
because $U \cdot U \times V = V \cdot U \times V = 0$. At this point we can't calculate on without an assumption. To eliminate for $t$ we have to divide with
${\left\| {U \times V} \right\|^2}$. If the directions $U,V \in {\mathbb{R}^3}$ for our lines are linear independent, then $U \times V \ne \vec 0$ and has a length different from zero. So we get for $t$:
$$t = \frac{{\overrightarrow {PQ}  \cdot U \times V}}{{{{\left\| {U \times V} \right\|}^2}}}$$
And also we get the shape for
$$\overrightarrow {AB}  = \frac{{\overrightarrow {PQ}  \cdot U \times V}}{{{{\left\| {U \times V} \right\|}^2}}} \cdot U \times V$$
What about the length for this $\overrightarrow {AB} $? Here it is:
$$\begin{gathered}
  \overrightarrow {AB}  \cdot \overrightarrow {AB}  = {\left\| {\overrightarrow {AB} } \right\|^2} = \frac{{\overrightarrow {PQ}  \cdot U \times V}}{{{{\left\| {U \times V} \right\|}^2}}} \cdot \frac{{\overrightarrow {PQ}  \cdot U \times V}}{{{{\left\| {U \times V} \right\|}^2}}} \cdot {\left\| {U \times V} \right\|^2} \hfill \\
   \hfill \\
  {\left\| {\overrightarrow {AB} } \right\|^2} = \frac{{{{\left( {\overrightarrow {PQ}  \cdot U \times V} \right)}^2}}}{{{{\left\| {U \times V} \right\|}^2}}} \hfill \\
   \hfill \\
  \left\| {\overrightarrow {AB} } \right\| = \frac{{\left| {\overrightarrow {PQ}  \cdot U \times V} \right|}}{{\left\| {U \times V} \right\|}} \hfill \\
\end{gathered} $$
And if we re-write: $\overrightarrow {PQ}  = Q - P$
$$\left\| {\overrightarrow {AB} } \right\| = \frac{{\left| {(Q - P) \cdot U \times V} \right|}}{{\left\| {U \times V} \right\|}}$$
So:
Given two lines in $\phi ,\psi  \subset {\mathbb{R}^3}$ with points $P,Q \in {\mathbb{R}^3}$ and directions $U,V \in {\mathbb{R}^3}$, that are of shape:
$$\begin{gathered}
  \phi  = P + r \cdot U \hfill \\
  \psi  = Q + s \cdot V \hfill \\
\end{gathered}$$
then, if $U$ and $V$ are linear independent, their distance is given by:
$$d(\phi ,\psi ) = \frac{{\left| {(Q - P) \cdot U \times V} \right|}}{{\left\| {U \times V} \right\|}}$$
In my opinion it's important to make a difference between points and vectors. Because points are no vectors. Points can not be added. The difference between two points is a vector. And if I add to a point a vector I get a point. In your formula I would replace "vectors" $\overrightarrow {{v_1}} ,\overrightarrow {{v_2}} $ by points, because these are points. And points didn't have overarrows.
Thank you for listening!
Comment: Excellent figure +1
Comment: @HeeKwonLee Tried to make relevant points to get an idea for this problem visible. We all are living in three-dimensional space. We should know the facts. Thank you.
Answer: we are looking for two pints $P_1 = v_1 + t_1\, a_1, P_2 = v_2 + t_2\,  a_2 $ where $t_1, t_2$ are real numbers so that $\vec{P_1P_2}$ is orthogonal to both $a_1$ and $a_2.$  in other words, $$\vec{P_1P_2} = (v_2 -t_2 a_2 )-(v_1-t_1a_1)=( v_2 - v_1) -t_2a_2 + t_1a_1= k a_1 \times a_2 \tag 1$$  taking dot product of $(1)$ with $a_1\times a_2$ gives
$$(v_2 - v_1)\cdot(a_1 \times a_2) = k\, |a_1 \times a_2|^2 $$ that is
$$|k| = \frac{|(v_2 - v_1)\cdot(a_1 \times a_2)|}{|a_1 \times a_2|^2}  $$
and the shortest distance between the lines is $$|\vec{P_1P_2}| = |k||a_1 \times a_2| =  \frac{|(v_2 - v_1)\cdot(a_1 \times a_2)|}{|a_1 \times a_2|}$$ as required.
Answer: As to your hint, consider the line through the point $\overrightarrow v_1$ parallel to $l_2$.  Since that line and $l_1$ both pass through the point $\overrightarrow v_1$, they determine a plane which is parallel to $l_2$.
What you actually want is the distance between this plane and the point $\overrightarrow v_2$, which will be the shortest possible distance between $l_1$ and $l_2$.  A unit vector perpendicular to this plane (which you had right) is
$$\frac{\overrightarrow a_1\times\overrightarrow a_2}{\|\overrightarrow a_1\times\overrightarrow a_2\|}$$
You are also correct that the length of the projection of the vector $\overrightarrow v_2-\overrightarrow v_1$ onto this vector
$$\left|(\overrightarrow v_2-\overrightarrow v_1)\cdot\frac{\overrightarrow a_1\times\overrightarrow a_2}{\|\overrightarrow a_1\times\overrightarrow a_2\|}\right|$$ is the required distance.
(I think your only point of error is where you say, "we have to find the distance between the points $\overrightarrow v_1$ and $\overrightarrow v_2$.")
Answer: The distance between two lines is defined by
$$d=\inf_{\substack{\vec w_1\in l_1\\\vec w_2\in l_2}}\|\vec w_1-\vec w_2\|.$$
This infimum is actually a minimum, which means that there are two points $\vec w_1\in l_1$ and $\vec w_2\in l_2$ such that $\|\vec w_1-\vec w_2\|=d$.
The vector $\vec a_1\times\vec a_2$ is orthogonal to both $\vec a_1$ and $\vec a_2$. We will assume in the following that $\vec a_1\times\vec a_2\neq\vec0$. In this case, the vector $\vec u=\frac{\vec a_1\times \vec a_2}{\|\vec a_1\times \vec a_2\|}$ is a unit vector.
For any $x_1\in\mathbb R$, let us consider the point $\vec r_1\in l_1$ such that $\vec r_1-\vec w_1=x_1\vec a_1$. Let us consider  $$\begin{split}\|\vec r_1-\vec w_2\|^2&=\|\vec r_1-\vec w_1\|^2+\|\vec w_1-\vec w_2\|^2+2(\vec r_1-\vec w_1)\cdot(\vec w_1-\vec w_2)\\&=x_1^2+d^2+2x_1\vec a_1\cdot(\vec w_1-\vec w_2).\end{split} $$
The minimum of this function of $x_1$ must be reached at $x_1=0$ by definition of $\vec w_1$. The second order polynomial $x_1^2+d^2+2x_1\,\vec a_1\cdot(\vec w_1-\vec w_2)$ reaches its minimum at $x_1=-\vec a_1\cdot(\vec w_1-\vec w_2)$. We conclude that $\vec a_1\cdot (\vec w_1-\vec w_2)=0$, that is $\vec w_1-\vec w_2$ is orthogonal to $\vec a_1$. We can make the same reasoning and obtain that $\vec w_1-\vec w_2$ is also orthogonal to $\vec a_2$. As a conclusion, $\vec w_1-\vec w_2$ is colinear to $\vec u$.
To get the norm of $\vec w_1-\vec w_2$, since $\vec u$ is a unit vector, we can take the absolute value of the scalar product of $(\vec w_1-\vec w_2)\cdot \vec u$. Therefore
$$d=\left\lvert(\vec w_1-\vec w_2)\cdot u\right\rvert.$$
In this last equation, we can replace $\vec w_1$ by $\vec v_1$ and $\vec w_2$ by $\vec v_2$ because
$$\begin{split}(\vec v_1-\vec v_2)\cdot\vec u&=(\vec v_1-\vec w_1+\vec w_1-\vec w_2+\vec w_2-\vec v_2)\cdot\vec u\\
&=(\vec v_1-\vec w_1)\cdot\vec u+(\vec w_1-\vec w_2)\cdot \vec u+(\vec w_2-\vec v_2)\cdot u\\
&=0+(\vec w_1-\vec w_2)\cdot\vec u+0.\end{split}$$
We remark that $\vec r_1-\vec w_1=x_1\vec a_1$ for a certain $x_1\in\mathbb R$.
Note that we have shown a stronger result: $\vec w_1-\vec w_2=\pm d\vec u$.
If $\vec a_1\times\vec a_2=\vec0$, the lines $l_1$ and $l_2$ are either confounded or distinct and parallel. In that case, the distance between the lines id $d=\left\lvert(\vec v_1-\vec v_2)\times \vec a_1\right\rvert/\|\vec a_1\|$. Could you prove it using the same technique ?
Answer: There is a formula for the shortest distance between a plane and the origin. If that plane is expressed as a vector function: $\boldsymbol{\Pi} = \boldsymbol{\Pi}_0 + \boldsymbol{d}_1\lambda + \boldsymbol{d}_2\mu$, then the formula is $\left|\boldsymbol{\Pi}_0 \cdot \frac{\boldsymbol{d}_1 \times \boldsymbol{d}_2}{|\boldsymbol{d}_1 \times \boldsymbol{d}_2|}\right|$. Part 1 of this answer will find the shortest distance between two lines, by reducing it to finding the shortest distance between a plane and the origin. Part 2 of this answer will derive the formula for the shortest distance between a plane and the origin.
Part 1:
Given two lines:
$\boldsymbol{X} = \boldsymbol{X}_0 + \lambda \boldsymbol{X}'$
$\boldsymbol{Y} = \boldsymbol{Y}_0 + \mu \boldsymbol{Y}'$
The problem is to find the minimum value of $|\boldsymbol{X}-\boldsymbol{Y}|$. But $\boldsymbol{X}-\boldsymbol{Y}$ is the equation of a plane, and then the minimization problem is finding the shortest distance from the origin to that plane. We get that the shortest distance is $\left|(\boldsymbol{X}_0 - \boldsymbol{Y}_0)\cdot\frac{\boldsymbol{X'}\times\boldsymbol{Y'}}{|\boldsymbol{X'}\times\boldsymbol{Y'}|}\right|$. The result is proven.

Part 2 (deriving the formula for the shortest distance from origin to plane):
Let $\boldsymbol{\Pi} = \boldsymbol{\Pi}_0 + \boldsymbol{d}_1\lambda + \boldsymbol{d}_2\mu$.
The shortest distance from the origin to the plane is the perpendicular distance from the origin to the plane (why?). Let $\boldsymbol{\hat{n}}$ be the normal of the plane. The shortest distance is $\boldsymbol{\hat{n}} \cdot \boldsymbol{\Pi}_0$. And $\boldsymbol{\hat{n}} = \frac{\boldsymbol{d}_1 \times \boldsymbol{d}_2}{|\boldsymbol{d}_1 \times \boldsymbol{d}_2|}$.
This part would be clearer with a diagram.
Answer: Take two parallel planes and draw an arbitrary line in each. Both lines are parallel to both planes, but they needn't be parallel to each other.
Comment: I got stuck right now... How can that hold?? Could you explain it further to me??
Comment: Take two sheets of carton and draw a line on each.
Comment: I added as an anser a picture... Is that what you mean?? @YvesDaoust
Comment: I tried to solve the exercise and added at my initial post what I have done... Could you take a look?? @YvesDaoust
Comment: Why these downvotes ??
Answer: Do you mean the following @YvesDaoust ??
Comment: He exactly meant that. (Assuming the two planes do not intersect but are parallel)
Comment: Yep, two parallel planes, two skew lines.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post.
Comment: Thanks for the prompt reply @hjhjhj57. That is a distinct possibility. OTOH there is a fresh bounty by the OP here, so looks like everything is not clear yet. I will wait for a response from Mary. Sorry about the tone of my comment. It's 1:20 am here, and looks like I'm becoming crankier by the minute...
Comment: Ok... I tried to solve the exercise and added at my initial post what I have done... Could you take a look?? @PatrickDaSilva
Comment: @hjhjhj57: I was summoned here by a flag - not from you, but I'm asking you as well as the flagger :-). How do you recommend that I convert this to a comment under Yves' post? Mary, this is essentially a follow-up question to Yves. But others may also be able to help. You could consider adding the image and this extra request for a clarification to your main question. Make it a separate paragraph, marked as a follow up or whatever.
Comment: @JyrkiLahtonen I actually think this post has served its purpose (which wasn't to answer the question), so it should be deleted.
Answer: First, we will find a distance between a plane and a point. And we will apply.
(1) Distance $d$ between plane $P\ :\ Ax+By+Cz=D$ and a point $p$ :
There exists a point $q=(x,y,z)$ in the plane : $$ |p-q|=d
$$
Note that $$\overrightarrow{pq}\perp P$$
Hence $$ q\in \bigg\{ p+ d\frac{(A,B,C) }{|(A,B,C)|},
 p-
d\frac{(A,B,C) }{|(A,B,C)|}\bigg\}$$
Hence $$ (A,B,C)\cdot q=D\Rightarrow d=\frac{ | D-(A,B,C)\cdot p
|}{|(A,B,C)|} $$
(2) Let $V_1\in l_1,\ V_2\in l_2 $ s.t. $ |V_1-V_2|$ is the distance
$d$ between $l_i$.
Note that $$ \overrightarrow{V_1V_2}\perp l_i $$
Let $$ l \ :\ \overrightarrow{V_2V_1} +l_2 $$ which passes through
$V_1$. So let $P$ to be a plane containing $l,\ l_1$ : Then
normal to $P$ is $$ \overrightarrow{a}_1 \times \overrightarrow{a}_2
$$
Since $P$ contains $V_1$ so $$ P\ :\ [(x,y,z) - V_1] \cdot
\overrightarrow{a}_1 \times \overrightarrow{a}_2 =0 $$
or $$ P\ :\  [(x,y,z) - v_1] \cdot \overrightarrow{a}_1 \times
\overrightarrow{a}_2 =0 $$
(3) Application : $$ D=v_1 \cdot \overrightarrow{a}_1 \times
\overrightarrow{a}_2 $$
$$ (A,B,C) = \overrightarrow{a}_1 \times
\overrightarrow{a}_2
$$
$$ p = v_2 $$

Distance of two lines in $\mathbb{R}^3$


Digital Signatures of XML, PDF and Office Documents on every platform

Question: I'm trying to develop a website that performs digital signatures on client-side and then sent the signed document to the server-side.
I want to do the signatures on client, due to the fact of not sending away the user's private key. This key (in theory) must be always with the user and it must not be sent to the web (even if protected with SSL, for example).
I want that every platform may be able to sign the documents. I've already developed a Java Applet with the signing algorithms, but Java is not supported in iOS or Android.. In .NET is impossible too. So I think I'm restricted to JavaScript, but I'm not aware of any javascript library that signs XML, PDF and Office documents.. What should I do? Only with Javascript every platform works..
Can u help me?
Regards,
William.
Comment: As Security in JavaScript is a flawed approach (as discussed here: http://www.matasano.com/articles/javascript-cryptography/ ), you are out of luck.
Comment: Link is broken.
Answer: Disclosure: I work for CoSign.
The solution is to use a secure, hardware hardened digital signature appliance.
You're raising the common question of digitally signing data at the network "edge."
Good luck on the idea of signing at the client/edge, for the reasons that you discuss. And forget Javascript, it is completely insecure from the cryptography point of view.
You're right that the signers' private key shouldn't be sent anywhere.
Good news: there is an alternative architecture that will:

Not require that the private keys be sent anywhere
Protect the private keys
Enable signing from clients of all types including mobile, Android, .Net, iOS, etc.
Decrease administrative costs by centralizing the keys and key management

The answer: use a centralized signing appliance. The appliance is hardened at the hardware level: if you try to open the box, the keys are destroyed. Signing appliances are made by my company and some others.
In this system, the document (or better, just its hash) is sent from the edge device to the centralized signing appliance. The user also authenticates with the appliance (using any one of a number of techniques). The appliance holds the private keys. It signs the hash, and returns the digital signature to the edge client.
Depending on the capabilities of the client, it can:
Assemble the signed document itself (combining the digital signature with the source document). Benefit: less data needs to be sent between the edge client and the signing appliance. Issue: requires more sw on the client. Or:
The appliance can return the complete signed document. Benefit simpler implementation on the client but requires that the document be sent to the signing appliance from the edge client.
Note that an entire PDF document doesn't have to be sent back--the PDF digital signature is simply appended to the source document. So the flow can be:

Send the entire PDF for signing. (Or just send the hash if the client can calculate it.)
Receive back either the entire PDF (signed), or just a "tail" that, when appended to the source PDF creates the signed document.

Multiple data types
My company supports signing of PDF, Word, Excel, XML and other document types out of the box. Eg Word documents are signed using the Word "standard" -- a digitally signed Word document can be verified by a recipient (relying party) without installing anything beyond Word. No plugins, etc.
Signer Authentication
Signers need to authenticate themselves with the centralized appliance. My company supports multiple types of authentication including OTP and 2FA.
Comment: Just one question: how do you ensure that the document/hash sent is righteous (i.e. has not been modified by someone, while sent) ?
Comment: All connections to the appliance use SSL to prevent data tampering. In addition, clients can verify the box's id by checking its SSL cert with a known good local copy of the cert. That protects against someone masquerading as the box to your sw.


C: why should I declare a pointer?

Question: It seems there are many questions of the form "should I declare X?" but not this specific one. I hope it is ok to ask this.
The title says it all: why should I declare a pointer? Even better: there are risks if I do not declare the pointer? Consider the following examples:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <time.h>
#include <string.h>

void func(int *ptr);

int main (int argc, char **argv)
{

  int a;
  int *PTRa;

  a = -1;
  PTRa = &a;

  func(PTRa);
  printf("%d\n", a);

  return 0;

}

void func(int *ptr)
{
  *ptr = 1;
  return;
}

I get a=1. In this case I would say the pointer is declared (and assigned as well): I have the line int *PTRa; (declaration) and the line PTRa = &a; (assignment). The results is correct. I don't get any warning.
Imagine now to replace the main with the following:
int main (int argc, char **argv)
{

  int a;

  a = -1;

  func(&a);
  printf("%d\n", a);

  return 0;

}

Here I do not declare the pointer but just give the address of a to func. The result is correct and I don't get warnings.
My understanding is that the two approaches are identical: func always gets the same input, the address of a. I would even dare to say that I feel the second approach to be better, as I feel it to be clearer and I feel the variable PTRa to be useless and somewhat redundant. However, I always see codes where the first approach is used and I have the feeling I will be told to do so. Why?
Comment: Both versions have exactly the same effect, and will probably be compiled the same with optimizations.  Whether you want the temporary variable is just a matter of which way you feel is more clear to read.
Comment: Q: why should I declare a pointer?  A: You shouldn't declare *ANYTHING* unless you *NEED* it.  1) `void func(int *ptr)` is silly: it should probably be `int func(int i)`, and return an int.  It *DEFINITELY* shouldn't have a (superfluous) "return". 2) declaring `PTRa` just so you can use it as a parameter to "func()" is silly.  Your second example, where you just call `func(&a);` is much better.
Comment: But  Nate Eldredge is 100% correct: `Whether you want the temporary variable is just a matter of which way you feel is more clear to read.`  There is no "one true answer".  Ultimately, it's just a matter of "preference".
Answer: In this case there's no benefit in creating a separate pointer variable.
It might be necessary in more complex cases, just like it's sometimes necessary to create variables of any other type.
Comment: could you elaborate a little more on these complex cases?
Comment: @GRquanti See the other answer. We could give you more examples, but I suggest to just continue studying, and eventually you'll stumble upon them yourself.
Answer: You are correct: there's no point in declaring a pointer in your example. A pointer is just a variable that holds an address. The cleaner approach is to pass directly the address of the variable: func(&a) instead of doing one extra step and declaring PTRa.
Note that not all cases are this simple. For example, if you want to have an array of ints, but you want to be able to grow that array dynamically because you don't know how big it should be you have to declare a pointer:
int count = ...; // get the count from the user, from a file, etc
int *list_of_ints = malloc(sizeof(int) * count);
if (list_of_ints == NULL)
{
    // malloc failed.
    printf("Not enough memory!\n");
    exit(1);
}

// Now `list_of_ints` has enough space to store exactly `count` `int`s

EDIT: as @paulsm4 pointed out in a comment, the question Why use pointers? is a great source of information related to this topic.
EDIT 2: one good reason to want a pointer to the address of a variable might be that you want a pointer inside a structure or array:
struct foo
{
    int x;
};

struct bar
{
    int y;
    struct foo f;
};

struct bar b;
struct foo *ptr_foo = &b.f;

You can now work more easily with b.f because you're just working with a struct foo.
Comment: You're correct,  In general, "there's no reason...and the more compact syntax is probably better".  HOWEVER: this isn't an Absolute Rule.  Like  Nate Eldredge said (it's worth repeating): there are often very good reasons to create temp variables.  It's entirely a matter of preference.  Please *DO* read the responses in the [thread](https://stackoverflow.com/questions/162941/why-use-pointers/162988#162988).  They're enlightening :)
Comment: Thank you for the answer. I am aware of `malloc` and how it works. My focus was specifically on pointers to a single address.
Comment: @GRquanti Then let's say you're making a linked list. You'll need pointers to nodes.
Comment: Nice! I am not aware of what a linked list is. I'll look at it. Thank you!
Comment: @GRquanti: I didn't realize your question was really that basic: "Q: What are pointers, and when/why should I use them?"  A: I encourage you to look at the replies in this thread: [Why use pointers?](https://stackoverflow.com/a/162988/421195)
Comment: @paulsm4 Oh, but I am aware of what pointers are and why to use them. I know the example I posted is not a good example of when a pointer should be used. You were correctly noting that in this case a function returning int works and is thus better. The example was just to express the syntax. The question, if you want, is "why people declare and assign pointers to a single address?". My current understanding is "there is no reason and a more compact syntax (as `func(&a)`) is probably better", as I originally suspected.
Comment: As another example you may want or need a pointer inside and array or a structure. I added an example in my answer.
Answer: From the title, I thought you're talking about pointer type, but actually, you are asking if declaring a variable is needed.

Variable is a piece of memory, storing some numbers(bytes), and the type of the variable, indicating how you and your program interpret those bytes: integer? float? character? etc.
Pointer is the memory address, it could be of a variable, or a function, or something else.
A variable of pointer is a small area in the memory, storing the address of other(or even same) memory.
You decide if you need an extra variable to store the pointer. It's the same to the decision that if you want a variable to store an integer:

int v = -1;
abs(v); // use variable
abs(-1); // use constant

Comment: I'm getting confused. My understanding is that pointer is a type, not a memory address. The type pointer stores a memory address, in the same way `int` stores a natural signed number and so on. A memory address, on the other hand, I would not say it is a type but rather a value. A value telling where the memory cell is, in the same way in `int a=-1` the `-1` is a value telling how much `a` amounts to.
Comment: @GRquanti That's correct. `int *` is your pointer type, `PTRa` is your variable, whose type is `int *`. `&a` is the constant.
Comment: Pointer stores address bytes, similar to int stores integer and char stores character as bytes in the memory.

C: why should I declare a pointer?


Conditional Custom Text Filter plugin

Question: I have created a custom text filter plugin by extending FilterBase class. The process() function looks like
 public function process($text, $langcode) {
    // Get the current node to determine if it has the glossary field and if
    // that field is enabled.
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node && $node->hasField('field_glossary') && $node->field_glossary->value) {

      // Get all the terms in the Glossary vocabulary.
      $terms = $this->getTerms('glossary');

      // Make all the replacements.
      $new_text = $this->doReplace($text, $terms);

      // Create a filtered text object with the updated text.
      $result = new FilterProcessResult($new_text);
      return $result;
    }
    else {
      // Don't do the replacement.
      $result = new FilterProcessResult($text);
      return $result;
    }
  }

I am letting editor to choose to turn off/on text filtering via plugin by creating a flag field as used in code $node->field_glossary->value. The problem comes when I need to check the field value on non-node page, as on node page I can get the node object and check the value but for other entites like blocks how can I get the source entity for text?
Answer: That's not so easy, because the filter is normally not aware from which field it is called from.
The token filter module does this trick:
/**
 * Implements hook_preprocess_HOOK().
 */
function token_filter_preprocess_field(&$variables) {
  if (isset($variables['element']['#object']) && $variables['element']['#object'] instanceof ContentEntityInterface) {
    $entity = &drupal_static('token_filter_entity');
    $entity = $variables['element']['#object'];
  }
}

The parent entity of the field is stored in a static variable and can be used in the filter:
  public function process($text, $langcode) {
    $entity = drupal_static('token_filter_entity', NULL);
    if (!is_null($entity) && $entity instanceof ContentEntityInterface) {
      // use entity
    }
  }

http://cgit.drupalcode.org/token_filter/tree/token_filter.module?h=8.x-1.x
This may not be the best solution for most cases. If possible look for a better place for the code where you have direct access to the entity. For example in hook_entity_view_alter().

Conditional Custom Text Filter plugin