Inverse Fourier transform of $\exp(4\pi^2i|\xi|^2t)$

Question: I would like to compute the inverse Fourier transform of $\exp(4\pi^2i|\xi|^2t)$.
\begin{equation}
f(x,t) = \int_{\mathbb{R}^n} e^{2\pi i x\cdot\xi} e^{4\pi^2i|\xi|^2t} \,\mathrm{d}\xi
\end{equation}
Can I use the fact that the Fourier transform of $e^{-\pi|x|^2}$ is $e^{-\pi|\xi|^2}$, and then apply to the function above with the change of variable (dilation)? I wonder if it works for complex numbers.
Thank you.
Comment: What is the function (tempered distribution) defined on frequency space of which you want to take the inverse Fourier transform? $(\xi,x)\mapsto e^{4\pi^{2}i\left|\xi\right|^{2}x}$ is defined on $\mathbb{R}^{n}\times\mathbb{R}$.
Comment: You can't transform a function in both $x$ and $\xi$, only one or the other. Unless you want $x$ to be a constant
Comment: My mistake. There should be a "$t$".
Comment: For real $t$ fixed, the function $g(\xi)=e^{4\pi^{2}i\left|\xi\right|^{2}t}$ is not integrable in the Lebesgue sense, so the expression you have above is not a Lebesgue integral. $g$ has an inverse Fourier transform in the sense of tempered distributions.
Comment: @MattRosenzweig Could you please elaborate more? I am solving the Schrodinger equation $iu_t-\Delta u=0$ and $u(x,0)=g(x)$. $g$ is given in $L^2(\mathbb{R}^n)$. I am supposed to find the solution $u\in C^1_tC^2_x\cap L_t^\infty H^2_x$. I used Fourier transform and had a solution, but I do not know how to find the inverse of the kernel.
Answer: Before editing the question you were asking the Inverse Fourier transform of
$\xi\mapsto \exp(4\pi^2i|\xi|^2)$
\begin{eqnarray}
f(x)&=&\int_{\mathbb{R}^n}e^{2\pi ix\cdot\xi}e^{4\pi^2i|\xi|^2}\,d\xi\stackrel{y=2\pi\xi}{=}\frac{1}{(2\pi)^n}\int_{\mathbb{R}^n}e^{i(x\cdot y+|y|^2)}\,dy=\frac{1}{(2\pi)^n}\int_{\mathbb{R}^n}e^{i(|y+x/2|^2-|x|^2/4)}\,dy\\
&=&\frac{e^{-i\frac{|x|^2}{4}}}{(2\pi)^n}\int_{\mathbb{R}^n}e^{i|y+x/2|^2}\,dy\stackrel{z=y+x/2}{=}\frac{e^{-i\frac{|x|^2}{4}}}{(2\pi)^n}\int_{\mathbb{R}^n}e^{i|z|^2}\,dz=\frac{e^{-i\frac{|x|^2}{4}}}{(2\pi)^n}\left(\int_{\mathbb{R}}e^{it^2}\,dt\right)^n\\
&=&\frac{e^{-i\frac{|x|^2}{4}}}{(2\pi)^n}\left(\int_{\mathbb{R}}\cos(t^2)\,dt+i\int_{\mathbb{R}}\sin(t^2)\,dt\right)^n=\frac{e^{-i\frac{|x|^2}{4}}}{(2\pi)^n}\left[\sqrt{\frac\pi2}(1+i)\right]^n\\
&=&\left(\frac{1+i}{\sqrt{2}}\right)^n\cdot\left(\frac{\sqrt{\pi}}{2\pi}\right)^ne^{-i\frac{|x|^2}{4}}=\frac{e^{in\frac\pi4}}{(2\sqrt{\pi})^n}e^{-i\frac{|x|^2}{4}}=\frac{1}{(2\sqrt{\pi})^n}\exp\left(-i\frac{|x|^2-n}{4}\right).
\end{eqnarray}

After editing the question you are asking the Inverse Fourier transform of $(\xi,t)\mapsto \exp(4\pi^2i|\xi|^2t)$ (w.r.t. $\xi$). For $t\ne 0$, let us denote by $s$ the sign of $t$. Then
\begin{eqnarray}
f(x,t)&=&\int_{\mathbb{R}^n}e^{2\pi ix\cdot\xi}e^{4\pi^2i|\xi|^2t}\,d\xi\stackrel{y=2\pi\sqrt{|t|}\xi}{=}\frac{1}{(2\pi\sqrt{|t|})^n}\int_{\mathbb{R}^n}\exp\left(is(s|t|^{-1/2}x\cdot y+|y|^2)\right)\,dy\\
&=&\frac{1}{(2\pi\sqrt{|t|})^n}\int_{\mathbb{R}^n}\exp\left[is\left(\left|y+\frac{s|t|^{-1/2}}{2}x\right|^2-\frac{|x|^2}{4|t|}\right)\right]\,dy\\
&=&\frac{\exp\left(-is\frac{|x|^2}{4|t|}\right)}{(2\pi\sqrt{|t|})^n}\int_{\mathbb{R}^n}\exp\left(is\left|y+\frac{s|t|^{-1/2}}{2}x\right|^2\right)\,dy\\
&\stackrel{z=y+\frac{s|t|^{-1/2}}{2}x}{=}&\frac{e^{-it\frac{|x|^2}{4}}}{(2\pi\sqrt{|t|})^n}\int_{\mathbb{R}^n}e^{is|z|^2}\,dz=\frac{e^{-it\frac{|x|^2}{4}}}{(2\pi\sqrt{|t|})^n}\left(\int_{\mathbb{R}}e^{isu^2}\,du\right)^n\\
&=&\frac{e^{-it\frac{|x|^2}{4}}}{(2\pi\sqrt{|t|})^n}\left(\int_{\mathbb{R}}\cos(su^2)\,du+i\int_{\mathbb{R}}\sin(su^2)\,du\right)^n=\frac{e^{-it\frac{|x|^2}{4}}}{(2\pi\sqrt{|t|})^n}\left[\sqrt{\frac\pi2}(1+si)\right]^n\\
&=&\left(\frac{1+si}{\sqrt{2}}\right)^n\cdot\left(\frac{\sqrt{\pi}}{2\pi\sqrt{|t|}}\right)^ne^{-it\frac{|x|^2}{4}}=\frac{e^{isn\frac\pi4}}{(2\sqrt{\pi|t|})^n}e^{-it\frac{|x|^2}{4}}\\
&=&\frac{1}{(2\sqrt{\pi|t|})^n}\exp\left(-it\frac{|x|^2-sn}{4}\right)=\frac{1}{(2\sqrt{\pi|t|})^n}\exp\left(-i\frac{t|x|^2-|t|n}{4}\right).
\end{eqnarray}
Comment: I am sorry for a change in the problem. For such a change in the exponent, I think the first substitution becomes $y=2\pi\xi t$; is that correct?
Comment: I feel like the 2 should be under the root in the 1D case... In the spirit of cheating, you may try the following in Mathematica: `Integrate[Exp[2*Pi*I*o*x]*Exp[4*Pi^2 I*o^2], {o, -Infinity, Infinity}]` = `((1/2 + I/2) E^(-((I x^2)/4)))/Sqrt[2 \[Pi]]`
Comment: @Mercy Is there $i$ when we subtract $|x|^2/4$?
Comment: @Mercy Thank you for your help. I rated your reply as the answer before you edited it because I was able to do the problem using your method. Thanks again.


Avoid Rounding Error on Double -> Date conversion

Question: In my program, I receive strings that define a time stamp in milliseconds. Now I need to convert this to a proper date. The solution I found looks something like this:
String aTime = "1365504203.0269";
double t = Double.parseDouble(aTime);

Date date = new Date((long)t*1000);
SimpleDateFormat dateFormatDDMMYYYY = new SimpleDateFormat("dd.MM.yyyy");
SimpleDateFormat dateFormatHHMMssSS = new SimpleDateFormat("HH:mm:ss:SS");
String day = new String(dateFormatHHMMssSS.format(date));
String hour = new String(dateFormatDDMMYYYY.format(date));

System.out.println("The Date: "+day);
System.out.println("The Time: "+hour);

Unfortunately, this removes the accuracy of milliseconds from the time stamp. (I'm not sure if the time is even that accurate as I can hardly think about it anymore.)
Has it gone lost due to double->long conversion, or has it never been there at all? Any way to workaround this problem?
Answer: The problem is in this statement:
Date date = new Date((long)t*1000);

It casts the double to a long first, thereby truncating the decimal places, and then multiplies by 1000, which just adds three zeros.  Try this:
Date date = new Date((long)(t*1000.0));

It uses double as the data type for multiplication, which moves the decimal places into the integer part, and then makes the decimal place truncating long conversion.
Using 1000.0 instead of 1000 as the constant forces the constant to be of double type as well, adding an extra level of certainty that the multiplication will happen with doubles.
Comment: +1, Good find! Just a little edit: Multiplying by 1000 adds three zeros ;)
Comment: I would drop the usage of `double` and use `BigDecimal` instead for more precision.


How to select "nearest left" and "nearesr right" values from a dataframe using condition?

Question: I have a dataframe with several columns and rows.
E.g. minimal example to reproduce:
df2 = pd.DataFrame( {'tof': {4875: 553.347572418771, 4876: 554.4911639867169, 4877: 556.2920840265602, 4878: 560.4059228421942, 4879: 560.7254631042018, 4880: 563.528024491697, 4881: 566.9995989172061, 4882: 570.7775523817776, 4883: 572.0685266789887}, 'E': {4875: 21.390025636898983, 4876: 21.301354836365054, 4877: 21.16283071077996, 4878: 20.85142476306085, 4879: 20.82752461774972, 4880: 20.61965532001513, 4881: 20.366451134218167, 4882: 20.096164210524464, 4883: 20.005036194577794}})

             tof          E
4875  553.347572  21.390026
4876  554.491164  21.301355
4877  556.292084  21.162831
4878  560.405923  20.851425
4879  560.725463  20.827525
4880  563.528024  20.619655
4881  566.999599  20.366451
4882  570.777552  20.096164
4883  572.068527  20.005036

I need to select 2 closest points (rows) using some provided value E_provided.
E.g. E_provided = 20.83
closest point(row) left to some value of E_search = closest_left gives
4879  560.725463  20.827525

closest point(row) right to some value of E_search = closest_right
4878  560.405923  20.851425

I understand that it's simple task, and I need to calculate some difference between df2['E']-E_provided and use additional conditions, but I don't get how to do it :)
I have tried this one:
df2.iloc[(df['E']-E_provided).abs().argsort()[:2]]

But it works incorrect because there are points that are close to the provided value just from one side, e.g. for E_provided == 20.1 it will output 2 nearest points both of them are left to E_provided value:
4882  570.777552  20.096164
4883  572.068527  20.005036

While I need to find:
4881  566.999599  20.366451
4882  570.777552  20.096164

Answer: Find values greater than/less than your value:
E_provided = 20.83
mask = df2.E.gt(E_provided)

Use this to get the closet from each direction:
above_id = df2.loc[mask, 'E'].sub(E_provided).abs().idxmin()
below_id = df2.loc[~mask, 'E'].sub(E_provided).abs().idxmin()

Now we can look up those two rows:
out = df2.loc[[above_id, below_id]]
print(out)

Output:
             tof          E
4878  560.405923  20.851425
4879  560.725463  20.827525

Answer: Less elegant, but working solution:
lower_ind = signal[signal['E'] < real_coord]['E'].idxmax()
upper_ind = signal[signal['E'] > real_coord]['E'].idxmin()

indx_list = [lower_ind, upper_ind]

out = df2.loc[indx_list]
print(out)


Can I clear cache only for particular domain / URL?

Question: I'm using domain module with several domains. With drush you can clear cache using cc command. I have only one database for all domains.
I'm wondering can I clear cache using only specific domain (with -l option) if I'm using same DB for all domains?
e.g: <code>$ drush -l http://www.example.com cc all</code>
Answer: With just core this is not possible. If you where to write your own cache backend then what you're asking for could be done. An example of a custom cache backend is http://drupal.org/project/adbc


Creating decision statements?

Question: The program is supposed to output the growth yield of the investment. The investment amount, the duration and the base rate are to be provided as user input to the program. The growth rate is applied yearly according to the following table:

All I have so far is the user input code, below,
import javax.swing.JOptionPane;

public class InvestGrowth {
    public static void main(String[] args) {
        double investment, duration, baserate, growth;

        investment = Double.parseDouble(JOptionPane.showInputDialog("Enter Investment Amount:"));

        duration = Double.parseDouble(JOptionPane.showInputDialog("Enter Duration in years: "));

        baserate = Double.parseDouble(JOptionPane.showInputDialog("Enter BaseRate:"));

        if (investment <- 50000){

        }
    }
}

I'm just not sure how to create the decision statements for the table... any help?
Comment: Remove the picture of your code and copy paste it in as a code block
Comment: You don't know how to use an `if` statement?
Comment: Since you are learning I think you should first try to make the core logic work in the console before attempting to make the application in Swing/JavaFX (use this not Swing if you are allowed!).
Answer: Since you are learning I think you should first try to make the core logic work in the console before attempting to create a full graphical application.
Try make it work using the following code:
import java.util.Scanner;

class InvestGrowth {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter Investment ($):");
    double investment = scanner.nextDouble();

    System.out.print("Enter Duration (Years):");
    double duration = scanner.nextDouble();

    System.out.print("Enter Base:" );
    double base  = scanner.nextDouble();

    double growthRate = 0.0;
    double growthYield = 0.0;

    // TODO: Complete actual logic of calculating growthYield
    if (investment <= 50000) {
      if(duration <= 1) { // Investment <= $50000 && Duration <= 1 year

      } else { // Investment <= $50000 && Duration > 1 year

      }
    } else {
      if (duration <= 1) { // Investment > $50000 && Duration <= 1 year

      } else { // Investment > $50000 && Duration > 1 year

      }
    }

    System.out.println("Your growth yield is: " + growthYield);
  }
}

I have left out the core logic as I think that is your homework (so ask your teacher/lecturer/professor/TA etc. If you are stuck) however the part you were stuck on "decision statements for the table" is there :)

Creating decision statements?


generalisation of Knonecker matrix product

Question: In the Kronecker matrix product  $C = A\otimes B$
we have that $C(i,j)=A(i,j)*B$
where the elements $A(i,j)$ are just numeric scalar values.
What if the $A(i,j)$ are matrix operators which act on $B$?  Is there a name for that formalism or matrix product?
Answer: I don't think that this operation has a name. In fact, this operation can be conveniently with the help of the Kronecker product, e.g. for the $2\times 2$ case the product you give is
$$
\begin{bmatrix}
A_{11} B & A_{12}B\\ A_{21}B & A_{22}B
\end{bmatrix}
$$
which is the same as
$$
\begin{bmatrix}
A_{11} & A_{12}\\ A_{21} & A_{22}
\end{bmatrix}
\begin{bmatrix}
B & 0\\ 0 & B
\end{bmatrix} =
\begin{bmatrix}
A_{11} & A_{12}\\ A_{21} & A_{22}
\end{bmatrix}
(I_2\otimes B)
$$
(where $I_2$ denotes the $2\times 2$ identity).
The $n\times m$ case is similar, replace the $2$ by $m$.


getText() method of EditText

Question: I have a problem with getText() method. When I run this app and enter any number, also 9 it displays vcx. Is my if statement invalid or what?
public class Quadratic extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_quadratic, container, false);

    // layout
    Button calc = (Button)rootView.findViewById(R.id.calcbtn); //main  button
    final EditText etfx2 = (EditText)rootView.findViewById(R.id.etfx2); // x^2 etf

    final TextView tbefs = (TextView)rootView.findViewById(R.id.tbefs);

    calc.setOnClickListener(new View.OnClickListener()
    {

        public void onClick (View v){
            String a= etfx2.getText().toString();

            if(a=="9")
            {
                tbefs.setText("asd");}
            else
            {
                tbefs.setText("vcx");
            }

        }

    });
    return rootView;
}}

Comment: Use `.equals()` and not `==` to compare strings. http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
Comment: anyone knows why java developers don't deal with this string equality issue? even I saw 10+ posts about this in SO.
Answer: Instead of a == "9" use:
a.equals("9")

And you also got something to ignore case
a.equalsIgnoreCase("9")

Answer: When using Strings, if you write a=="9", you compare the references. It means 'Is the string pointed by a the same string pointed by "9" ' i.e. are a and "9"stored in the same place in the memory.
Here you want to compare the content of your string so you have to use the equals method.
if("9".equals(a)){
    // do something
}

getText() method of EditText


Como fazer return URL automático no paypal

Question: Tenho uma página com um formulário que, após submetido, envia os dados para o paypal, depois do cliente fazer o pagamento queria que o mesmo fosse redirecionado para o url de retorno que envio junto com esse formulário, no entanto, sempre que o cliente faz o pagamento é enviado para uma página que diz que finalizou o pagamento e o cliente apenas e redirecionado para o url que indico se clicar no link que diz "Clique Aqui para voltar para ...". mas eu queria que ele fosse logo para a pagina que em 10 seg é redirecionado
Segue o o ecrã que queria que saltasse:

Tenho o Return URL ativo e configurado no site do paypal
Eu queria que o utilizador depois de pagar fosse logo reencaminhado para esta página, sendo assim redirecionado diretamente para o site.
Answer: Faça o login na sua conta do Paypal e ative o "Auto Return".
Normalmente encontrará em "Payment Preferences" (Selling Preferences).
Há um campo para inserir uma URL de retorno. Pode colocar qualquer URL pois essa URL pode ser customizada nas requisições de pagamento.
Os parâmetros do checkout
return -> URL absoluta da página de retorno
rm -> 1: GET, 2: POST
custom -> parametro_que_vc_quer_receber=valor_desse_parametro

Exemplo
return: http://foo.bar/order/paypal/return
rm: 2
custom: order_id=10

Isso informará ao Paypal para que retorne pelo método POST (rm == 2) e inclua um parâmetro order_id com valor 10. A URL que receberá é http://foo.bar/order/paypal/return
Para mais referências (inglês): https://www.paypal.com/be/cgi-bin/webscr?cmd=p/mer/express_return_summary-outside
IPN Listener
Para reforçar, é recomendável definir também a URL de notificação.
O parâmetro é notify_url. Para saber mais, consulte: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNSetup/
Comment: Olá, obigado pela disponibildiade, no entanto eu tenho isso configurado, mas sempre que faço um pagamento o utilizador tem de carregar no link para voltar ao site. depois disso vai para a pagina que diz que em 10 seg vai ser reencaminhado. eu queria que o utilizador após pagar fosse logo reencaminhado para o site sem ter de clicar no link
Comment: Você se refere aquele pequeno delay, certo? Não tem muito o que fazer. Pelo menos eu desconheço um redirecionamento instantâneo. O Paypal usa aquele pequeno delay. Acho que é para que o usuário tenha um tempo para poder ver que a transação foi feita, mas dentro do domínio do Paypal.
Comment: não,  eu não falo desse delay, falo da primeira imagem da minha pergunta em que o utilizador fica ali e apenas e reencaminhado para o site se clicar no link.
Apos clicar no link e enviado então para aquela pagina que tem o delay em que espera ate 10 seg e so depois e redirecionado para o meu site, o


Verify directly that are exactly 125 labelled trees on 5 vertices.

Question: I know Cayley's formula. However, I need to count them without using the formula.
Such a tree has $5-1=4$ edges. Let the degrees of vertices be $d_1,d_2,d_3,d_4,d_5$. By handshaking lemma $d_1+d_2+d_3+d_4+d_5=8$.
After from this point I can count them considering every possibility like $d_1 = 4$, then $d_2=d_3=d_4=d_5=1$ etc. However, I need an elegant way to count them.
Answer: Well, I personally wouldn't expect a particularly elegant way to count them, but maybe I'm overlooking a particularly beautiful argument here (different from Cayley's formula).
The problem with considering complete degree sequences is that it is not immediately clear from a given sequence whether or not it occurs as the degree sequence of a graph (though it can be done).
To me, the most obvious line of attack is to first classify all non-isomorphic trees on five vertices, and then determine the number of ways to label each of these (modulo isomorphism). The following hint contains some spoilers:

 Hint. There are only three non-isomorphic trees on 5 vertices. A picture of this classification can be found through a simple Google search. The proof for this classification is explained here: http://math.stackexchange.com/a/537309 . Note that you do indeed use some information about the degrees of the vertices, but not the entire degree sequence.


Adding prettyPhoto Dynamically to img

Question: str_replace( mixed $search , mixed $replace , mixed $subject)
I read that if $replace is array then each time it finds a new $search it uses a new value inside the array... but it is replacing "Array" instead...
foreach($image_name_array as $image_key => $image_value)
{
    $replace_img_fancy []= "config->site->data."articles/images/".$image_value." rel=prettyPhoto[gallery]> <img";
}

$ready_text = str_replace("<img", $replace_img_fancy,$data );

// on the output the "img" is being replaced by Array instead of the value
Comment: what is `$data` variable used as third paramter?
Answer:
I read that if $replace is array then each time it finds a new $search it uses a new value inside the array... but it is replacing "Array" instead...

Wrong. This works for $search or for $replace when $search is an array. You can do something like
foreach($image_name_array as $image_key => $image_value)
{
    $replace_img_fancy []= " <img";
    $search[] = "<img";
}

                               //array1  // array2
$ready_text = str_replace($search, $replace_img_fancy,$data);

Adding prettyPhoto Dynamically to img


Using pivot_wider to get true or false

Question: I'm trying to use pivot_wider to get a binary result for each country in each year between 1991 - 1995 like this table:
+------+-------+--------+--------+
| year | USA   | Israel | Sweden |
| 1991 | FALSE | TRUE   | TRUE   |
| 1992 | FALSE | FALSE  | TRUE   |
| 1993 | FALSE | TRUE   | TRUE   |
| 1994 | FALSE | FALSE  | TRUE   |
| 1995 | TRUE  | TRUE   | TRUE   |
+------+-------+--------+--------+

Of course, any binary indication will be great, besides true/false.
However, my data frame looks like:
 country =  c("Sweden", "Sweden", "Sweden", "Sweden", "Sweden", "Israel", "Israel",
                   "Israel", "USA")
    year = c(1991,1992,1993,1994,1995,1991,1993,1995,1995)
      df = as.data.frame(cbind(year,country))
    df

+---------+------+
| country | Year |
| Sweden  | 1991 |
| Sweden  | 1992 |
| Sweden  | 1993 |
| Sweden  | 1994 |
| Sweden  | 1995 |
| Israel  | 1991 |
| Israel  | 1993 |
| Israel  | 1995 |
| USA     | 1995 |
+---------+------+

I tried the following code and obtained the result below which is not what I'm looking for
  library(dplyr)
    df2 =  df %>%
      group_by(country) %>%
      mutate(row = row_number()) %>%
      pivot_wider(names_from = country, values_from = year) %>%
      select(-row)
    df2

+------+--------+--------+
| USA  | Israel | Sweden |
| 1995 | 1991   | 1991   |
| NA   | 1993   | 1992   |
| NA   | 1995   | 1993   |
| NA   | NA     | 1994   |
| NA   | NA     | 1995   |
+------+--------+--------+

Answer: You can try this:
library(dplyr)
library(tidyr)
df %>% mutate(val=1) %>% pivot_wider(names_from = country,values_from = val) %>%
  mutate(across(-year, ~replace_na(.x, 0))) %>%
  mutate(across(-year, ~ifelse(.x==1, TRUE,FALSE)))

Output:
# A tibble: 5 x 4
  year  Sweden Israel USA
  <fct> <lgl>  <lgl>  <lgl>
1 1991  TRUE   TRUE   FALSE
2 1992  TRUE   FALSE  FALSE
3 1993  TRUE   TRUE   FALSE
4 1994  TRUE   FALSE  FALSE
5 1995  TRUE   TRUE   TRUE

Comment: A better way to do this with dplyr is just to add a "TRUE" column before pivoting and to use values_fill:
df %>%
  mutate("TRUE" = TRUE) %>%
  pivot_wider(names_from = country, values_from = "TRUE", values_fill = FALSE)
Answer: here is a data.table solution
library( data.table )
#custom function, odetermins is the length of a vector >1 (TRUE/FALSE)
cust_fun <- function(x) length(x) > 0
#cast to wide, aggregating with the custom function above
dcast( setDT(df), year ~ country, fun.aggregate = cust_fun )

#    year Israel Sweden   USA
# 1: 1991   TRUE   TRUE FALSE
# 2: 1992  FALSE   TRUE FALSE
# 3: 1993   TRUE   TRUE FALSE
# 4: 1994  FALSE   TRUE FALSE
# 5: 1995   TRUE   TRUE  TRUE

Using pivot_wider to get true or false


read until specific index in a file with RandomAccessFile java

Question: I was trying to read from a file between two specific indices using the RandomAccessFile.
I know I can jump to an index with the seek() function, but i couldn't find the answer how to read then text out of the file until a specific index.
For example i have a huge file and i want to read text from index 100 to index 500, i would start like this:
public String get_text(){
   raf.seek(100) //raf= my RandomAccessFile
   String txt=raf.read(500) //read until index 500 which i don't know how to do
   return txt;
}

Please help me :)
Answer: This is how I solved my Problem:
try {
    int index = 100;
    raf.seek(index); //index = 100
    int counter = 0;
    int length = 400;
    while (counter < length) { //want to read the characters 400 times
       char c = (char) raf.read();
       if (!(c == '\n')) {   //don't append the newline character to my result
           sb.append(c);    //sb is a StringBuilder
           counter++;
       }
    }
} catch (IOException e) {
    e.printStackTrace();
}

I saw also another solution, where readFully() was used with a bytes array, that also worked well.
try {
    raf.seek(index);
    byte[] bytes = raf.readFully(new byte[(int) length]); //length of the charactersequence to be read
    String str = bytes.toString();
} catch (IOException e){
    e.printStackTrace();
}

In this solution the length of the bytes array has to be considered within the newline character, so you have to calculate that considering the line length.
->Start in file with line breaks and end index in file with line breaks. length = endInFile-startInFile +1;
Comment: Second solution should use `readFully()`. Otherwise there is no guarantee the buffer was filled.
Comment: hmm, i don't see that if I look at the JavaDocs https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html#readFully(byte[])
read() has more exception catches... can you explain why the buffer could not be filled?
Comment: Because there is nothing that says it *will* be filled in the contract of `read()`. That's why it returns a count. `readFully()` on the other hand is guaranteed to either fill the buffer or throw `EOFException` or another `IOException`, or block until one of these things happens. The `read()` method in your answer is neither of these, and is not provided, which makes your answer at best incomplete.
Comment: @user207421 now I see, thank you, I will correct it. read() doesnt throw an EOFException but it throws IOExceptions:
    IOException - If the first byte cannot be read for any reason other than end of file, or if the random access file has been closed, or if some other I/O error occurs.
Comment: I don't know why you're telling me this. I know this. It is what I am telling you. It returns a count, *instead* of throwing `EOFException`. That is the point. Especially when you ignore the count.
Comment: I'm sorry, I didn't want to upset you, I just wanted to understand what you mean. What I didn't mention is that I had an Index file for the file where I had to read out a RNA Sequence, therefore the length of the Buffer is culculated for the length of the RNA Sequence. In the file was the whole genomic RNA Sequence, if i had a length to read longer than the file is, i would have calculated something wrong, for my purpose it wasnt necessary to check for the end of the File.


How to solve the matrix equation $A\overrightarrow{x}=\overrightarrow{b}$ in Matlab when nullitity$(A)\neq 0$

Question: Say,
$A= \begin{pmatrix}
1 & 0 &1 \\
0 & 1  &1 \\
0 &0  &0
\end{pmatrix}$ and $\overrightarrow{b}= \begin{pmatrix}
8 \\
-5  \\
0
\end{pmatrix}$
and I want to solve the system $A\overrightarrow{x}=\overrightarrow{b}$. The solution is
$\overrightarrow{x}= \begin{pmatrix} 8\\ -5 \\ 0 \end{pmatrix} + k\begin{pmatrix} -1\\ -1 \\ 1 \end{pmatrix}$
How can I solve this kind of systems using Matlab?
The backslash function (x=A\b) of course doesn't work because nullity(A) isn't 0.
I can manage to solve this kind of problems using the Symbolic Toolbox (see below), but isn't there a Matlab built-in function (similar to the backslash) that can solve this directly?

A=[1 0 0; 0 1 0; 1 1 0]'
b=[8 -5 0]'
x=sym('x',[3,1]);
eqn= A*x==b;
[XX(1,1),XX(2,1),XX(3,1),params,conds]=solve(eqn,x,'ReturnConditions',true);
vv1=diff(XX,params(1));
vv0=XX-params(1)*vv1;
X=matlabFunction(XX)
v0=eval(vv0)
v1=eval(vv1)
%the solution is x=v0+k*v1
Comment: Note though that pinv gives you solution even if there is no solution to the system, which means that it's up to you to test that $b$ belongs to the image of $A$.
Comment: What if you take away the last trivial row $0=0$? Alternatively try **pinv(A)*b** But you don't get all the solutions.
Comment: (The trivial row doesn't cause the "problem"). Thanks, pinv(A) is a good start.
Answer: You should use MATLAB pinv() function which solves Least Squares problem using the SVD.
This method is slower yet much more robust than using \ (It always returns the least norm solution).
By itself it can handle problems with large condition number (Having eigen value which is zero -> Condition number which is infinite are included).
If you are dealing with edge cases (Really extreme condition number) you should use the tol parameter.
This parameter allows you to threshold small eigen values.


How to make Kubernetes Network Bridging work like a Hypervisor

Question: I'm trying to get this working for three days now and I just cant come up with a proper solution. I have an existing environment with virtual machines and I want to do a very simple thing:

Create a Container (Pod)
Put it on a specific VLAN Interface on a Bridge that is present and identical on every Kubernetes Node

Thats it! Just as you would do it with any VM on any Hypervisor. You create the VM, say what VLAN it should be in and then start it.
For some reason this feels like the holy grail with Kubernetes and I dont understand why. Everytime there is a Pod IP needed, the IP has to be set on the Worker Node and forwarded to the pod or they want to sell me an internal NAT with Load Balancing etc. This cant be it.
I have tried the following without success:

Using calico in a number of configurations
Using flanell in a number of configurations
Created stuff like "CustomResourceDefinitions" and "NetworkAttachmentDefinitions" with a wide variety of configuration examples and tests.
Tried manually scripting a lot on the node prior to configuring a pod

Custom Resource Definition:
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: network-attachment-definitions.k8s.cni.cncf.io
spec:
  group: k8s.cni.cncf.io
  versions:
  - name: v1
    served: true
    storage: true
    schema:
      openAPIV3Schema:
        type: object
        properties:
          spec:
            x-kubernetes-preserve-unknown-fields: true
  scope: Namespaced
  names:
        plural: network-attachment-definitions
        singular: network-attachment-definition
        kind: NetworkAttachmentDefinition
        shortNames:
        - net-attach-def

Network Attachment Definition with tests:
apiVersion: "k8s.cni.cncf.io/v1"
kind: NetworkAttachmentDefinition
metadata:
  name: macvlan-conf
spec:
  config: '{
    "name": "mynet",
    "type": "flannel",
    "delegate": {
      "bridge": "mynet0",
      "mtu": 1400
    }
  }

#    "cniVersion": "0.3.1",
#    "name": "mynet",
#    "type": "bridge",
#    "bridge": "mynet0",
#    "vlan": 100,
#    "ipam": {}
#  }'

#  config: '{
#    "cniVersion": "0.3.1",
#    "type": "vlan",
#    "master": "enp0s3",
#    "mtu": 1500,
#    "vlanId": 5,
#    "linkInContainer": false,
#    "ipam": {
#      "type": "host-local",
#      "subnet": "172.31.0.0/24"
#    },
#    "dns": {
#      "nameservers": [ "10.1.1.1", "184.108.40.206" ]
#    }
#  }'

SamplePod:
apiVersion: v1
kind: Pod
metadata:
  name: samplepod
  annotations:
    k8s.v1.cni.cncf.io/networks: macvlan-conf
spec:
  containers:
  - name: samplepod
    command: ["/bin/ash", "-c", "trap : TERM INT; sleep infinity & wait"]
    image: alpine

I'm feeling like I'm missing something very simple here. I verified that vlan and bridging is possible on my nodes. I do not have any errors either in Logs on the nodes or in journalctl. It appears that it just ignores the macvlan-conf.
Does anyone have this environment or knows what I need for that?
Thanks!
Edit: Logs from Creating the Pod
Oct 06 08:31:53 debian kubelet[793]: I1006 08:31:53.995353     793 reconciler_common.go:258] "operationExecutor.VerifyControllerAttachedVolume started for volume \"kube-api-access-5hbf8\" (UniqueName: \"kubernetes.io/projected/d7c2b05a-a1a6-424d-b626-0d7f5b1ffebc-kube-api-access-5hbf8\") pod \"samplepod2\" (UID: \"d7c2b05a-a1a6-424d-b626-0d7f5b1ffebc\") " pod="default/samplepod2"
Oct 06 08:31:54 debian containerd[721]: time="2023-10-06T08:31:54.165145664+02:00" level=info msg="RunPodSandbox for &PodSandboxMetadata{Name:samplepod2,Uid:d7c2b05a-a1a6-424d-b626-0d7f5b1ffebc,Namespace:default,Attempt:0,}"
Oct 06 08:31:54 debian kernel: IPv6: ADDRCONF(NETDEV_CHANGE): eth0: link becomes ready
Oct 06 08:31:54 debian kernel: IPv6: ADDRCONF(NETDEV_CHANGE): cali68b9b56a958: link becomes ready
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.244 [INFO][358123] plugin.go 327: Calico CNI found existing endpoint: &{{WorkloadEndpoint projectcalico.org/v3} {debian-k8s-samplepod2-eth0  default  d7c2b05a-a1a6-424d-b626-0d7f5b1ffebc 245039 0 2023-10-06 08:31:53 +0200 CEST <nil> <nil> map[projectcalico.org/namespace:default projectcalico.org/orchestrator:k8s projectcalico.org/serviceaccount:default] map[] [] [] []} {k8s  debian  samplepod2 eth0 default [] []   [kns.default>
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.244 [INFO][358123] k8s.go 74: Extracted identifiers for CmdAddK8s ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.275 [INFO][358141] ipam_plugin.go 228: Calico CNI IPAM request count IPv4=1 IPv6=0 ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" HandleID="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Workload="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.287 [INFO][358141] ipam_plugin.go 268: Auto assigning IP ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" HandleID="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Workload="debian-k8s-samplepod2-eth0" assignArgs=ipam.AutoAssignArgs{Num4:1, Num6:0, HandleID:(*string)(0xc000298240), Attrs:map[string]string{"namespace":"default", "node":"debian", "pod":"samplepod2",>
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.287 [INFO][358141] ipam_plugin.go 356: About to acquire host-wide IPAM lock.
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.287 [INFO][358141] ipam_plugin.go 371: Acquired host-wide IPAM lock.
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.288 [INFO][358141] ipam.go 107: Auto-assign 1 ipv4, 0 ipv6 addrs for host 'debian'
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.290 [INFO][358141] ipam.go 660: Looking up existing affinities for host handle="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.294 [INFO][358141] ipam.go 372: Looking up existing affinities for host host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.299 [INFO][358141] ipam.go 489: Trying affinity for 192.168.245.192/26 host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.301 [INFO][358141] ipam.go 155: Attempting to load block cidr=192.168.245.192/26 host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.303 [INFO][358141] ipam.go 232: Affinity is confirmed and block has been loaded cidr=192.168.245.192/26 host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.303 [INFO][358141] ipam.go 1180: Attempting to assign 1 addresses from block block=192.168.245.192/26 handle="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.305 [INFO][358141] ipam.go 1682: Creating new handle: k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.308 [INFO][358141] ipam.go 1203: Writing block in order to claim IPs block=192.168.245.192/26 handle="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.315 [INFO][358141] ipam.go 1216: Successfully claimed IPs: [192.168.245.206/26] block=192.168.245.192/26 handle="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.315 [INFO][358141] ipam.go 847: Auto-assigned 1 out of 1 IPv4s: [192.168.245.206/26] handle="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" host="debian"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.315 [INFO][358141] ipam_plugin.go 377: Released host-wide IPAM lock.
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.315 [INFO][358141] ipam_plugin.go 286: Calico CNI IPAM assigned addresses IPv4=[192.168.245.206/26] IPv6=[] ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" HandleID="k8s-pod-network.7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Workload="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.317 [INFO][358123] k8s.go 383: Populated endpoint ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0" endpoint=&v3.WorkloadEndpoint{TypeMeta:v1.TypeMeta{Kind:"WorkloadEndpoint", APIVersion:"projectcalico.org/v3"}, ObjectMeta:v1.ObjectMeta{Name:"debian-k8s-samplepod2-eth0", GenerateName:"", Namespace:"default", SelfLink>
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.317 [INFO][358123] k8s.go 384: Calico CNI using IPs: [192.168.245.206/32] ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.317 [INFO][358123] dataplane_linux.go 68: Setting the host side veth name to cali68b9b56a958 ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.318 [INFO][358123] dataplane_linux.go 473: Disabling IPv4 forwarding ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.356 [INFO][358123] k8s.go 411: Added Mac, interface name, and active container ID to endpoint ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0" endpoint=&v3.WorkloadEndpoint{TypeMeta:v1.TypeMeta{Kind:"WorkloadEndpoint", APIVersion:"projectcalico.org/v3"}, ObjectMeta:v1.ObjectMeta{Name:"debian-k8s-samplepod2-eth0", Ge>
Oct 06 08:31:54 debian containerd[721]: 2023-10-06 08:31:54.365 [INFO][358123] k8s.go 489: Wrote updated endpoint to datastore ContainerID="7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681" Namespace="default" Pod="samplepod2" WorkloadEndpoint="debian-k8s-samplepod2-eth0"
Oct 06 08:31:54 debian containerd[721]: time="2023-10-06T08:31:54.388979383+02:00" level=info msg="loading plugin \"io.containerd.event.v1.publisher\"..." runtime=io.containerd.runc.v2 type=io.containerd.event.v1
Oct 06 08:31:54 debian containerd[721]: time="2023-10-06T08:31:54.389077005+02:00" level=info msg="loading plugin \"io.containerd.internal.v1.shutdown\"..." runtime=io.containerd.runc.v2 type=io.containerd.internal.v1
Oct 06 08:31:54 debian containerd[721]: time="2023-10-06T08:31:54.389088977+02:00" level=info msg="loading plugin \"io.containerd.ttrpc.v1.task\"..." runtime=io.containerd.runc.v2 type=io.containerd.ttrpc.v1
Oct 06 08:31:54 debian containerd[721]: time="2023-10-06T08:31:54.389223823+02:00" level=info msg="starting signal loop" namespace=k8s.io path=/run/containerd/io.containerd.runtime.v2.task/k8s.io/7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681 pid=358182 runtime=io.containerd.runc.v2
Oct 06 08:31:54 debian systemd[1]: Started cri-containerd-7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681.scope - libcontainer container 7f1e4e55ae12bd9d257a47ecb7630ea59029f5da8ef89b3937dec19cbf11d681.

Answer: There are a couple of stuff to consider:

Pods that host your containers in Kubernetes are internal resources in the node.
VLANs are layer2 (broadcast domains)
You seem to be trying to solve a cloud-native scenario with VM area solutions. (It is not impossible, but it might be a bit difficult)
Remember that Calico is a Layer3-based networking and security solution for cloud-native environments.

VLAN-based solution using macvlan plugin:
Your CNI configuration should look something like this:
{
    "name": "mynet",
    "cniVersion": "0.3.1",
    "type": "vlan",
    "master": "eth0",
    "mtu": 1500,
    "vlanId": 5,
    "linkInContainer": true,
    "ipam": {
        "type": "host-local",
        "subnet": "10.1.1.0/24"
    },
    "dns": {
        "nameservers": [ "10.1.1.1", "18.104.22.168" ]
    }
}

annotate your deployment with
  annotations:
    k8s.v1.cni.cncf.io/networks: mynet

Your Pods should be hooked to that VLAN at this point.
Note: If you like to assign vlans to your Pods directly, change the linkInContainer to true and add the proper annotation to your deployments.

Cloud-native way with Calico:
While the previous solution works, I would suggest using a true cloud-native way to accomplish your task.
Benefits:

Simpler management
Better scalability

Install Calico, and configure IPPools

Note: That natoutgoing is disabled for this IPPool.

kubetl create -f -
apiVersion: projectcalico.org/v3
kind: IPPool
metadata:
  name: ippool-1
spec:
  cidr: <CIDR>
  ipipMode: Always
  natOutgoing: false
EOF

Note: natoutgoing is turned off, that means each Pod will send a request to the outside using its own IP and if the GW is not aware of that IP it will be dropped.
Use BGP peering to establish Layer3 routing with your GW. (Static routing works too)
Consider using the Calico eBPF dataplane if you like to preserve the Client IP inside your cluster.
Comment: Thank you very much! The first thing that popped in my sight was "linkInContainer": true which I have set to false. The other solution looks very interesting as well, I need to try that. I'm not sure if I can build the network as I want with solution 2. I basically need to integrate the Pod IP into an already present VLAN and CIDR with DHCP. Its needs to be just another instance in that L2. I will update when tried.
Comment: By the way I'm using Debian 12.1 for Master and Nodes, Am I on the right path with the NetworkAttachmentDefinition? Because your CNI conf is only the JSON and I figured to put the JSON in that YAML like above
Comment: From a security standpoint there might be an issue with `linkInContainer` approach in `macvlan` model, which is all your containers can communicate with the host network card. If you are forced/adamant to use a layer2 approach `ipvlan` might be a bit better.
CNI conf is a JSON blob in the form of a YAML.
https://www.cni.dev/plugins/current/main/ipvlan/#notes


Sort retrieved YouTube videos from recent to old with postedAt

Question: I want my Discord bot to retrieve few YouTube videos from a specific channel. Until there, that works fine, but I want it to retrieve from the recent one to the old one.
Here is my code:
    if(command === "meps") {
    var opts = {
        maxResults: 5,
        key: 'API KEY',
        channelId: 'UCcgvwZgeQIRQ-g9WDqgwXFw',
        type: 'video'
    };
    const lawMeps = new Discord.RichEmbed()
        .setAuthor("lawAMV", "https://yt3.ggpht.com/-464n3t5gsuw/AAAAAAAAAAI/AAAAAAAAAAA/csBjGhz51gY/s176-c-k-no-mo-rj-c0xffffff/photo.jpg")
        .setDescription("Recent MEPs")
        .setThumbnail("https://yt3.ggpht.com/-464n3t5gsuw/AAAAAAAAAAI/AAAAAAAAAAA/csBjGhz51gY/s176-c-k-no-mo-rj-c0xffffff/photo.jpg")
        .setColor("#553B82");
    search('lawAMVs mep', opts, function (err, results) {
        if (err) return console.log(err);
        for (var resultCount = 0; resultCount < opts.maxResults; resultCount++) {
            var publishedAt = new Date(results[resultCount].publishedAt);
            if (results[resultCount].title.startsWith("MEP"))
            {
                lawMeps.addField(results[resultCount].title, results[resultCount].link + "\nPublished at: " + publishedAt, true);
            }
        }
        message.channel.send(lawMeps);
    });
}

And here the screen on how it looks:
Comment: If you're going to list videos in order by a certain criteria (date, rating, relevance, title, etc.), you need to use [Search.list](https://developers.google.com/youtube/v3/docs/search/list) as it has the date (Resources are sorted in reverse chronological order based on the date they were created) filter.
Comment: Already seen this. But even with this, i still don't get it tbh.
Answer: Well it's fixed guys.
I've just added this : order: 'date', between maxResults: 5, and the key line.
For some reasons it didn't worked before, but now it goes well ! :D


Difference in behaviour between primary constructors in F# classes and structs?

Question: If I try this type definition in Visual Studio Express 2013, I get an error:
type Foo(bar : int) =
   struct
      member x.bar = bar
   end

If I change it so that it is a class instead, I don't get any errors:
type Foo(bar : int) =
   class
      member x.bar = bar
   end

The error I get is:
The member 'bar' can not be defined because the name 'bar' clashes with the field 'bar' in this type or module"

The error goes away if I change the constructor parameter's name slightly. I understand the differences between CLR structs and classes in general, but I don't quite understand the reason for this difference in behaviour. Can anyone explain it?
I'm mostly asking in case the answer dispels some deeper misunderstanding that I have about F#. Thanks.
Answer: Although I can't find a pertinent reference in the spec offhand, a little experimentation with a decompiler shows that primary constructor parameters on structs are always compiled as fields with the same name. For classes, a more complex set of rules (see §22.214.171.124) is used to determine their compiled form, which includes munging field names when they would otherwise clash with members.
Compare the compiled forms of this struct and class:
type S(bar: int) = struct end

type C(bar: int) =
    member x.bar = bar

public class C
{
    internal int bar@12;

    public int bar
    {
        get
        {
            return this.bar@12;
        }
    }

    public C(int bar)
    {
        this.bar@12 = bar;
    }
}

public struct S : IEquatable<Program.S>, IStructuralEquatable, IComparable<Program.S>, IComparable, IStructuralComparable
{
    internal int bar;

    public S(int bar)
    {
        this.bar = bar;
    }
}

The struct's primary constructor parameter is compiled as a field (and assigned!) even though it's unused. The class, on the other hand, allows a member and parameter with the same name. Admittedly, this doesn't explain why, but may help to clarify the observed behavior.
Comment: As you said, this doesn't explain why, but it's still great to know what's actually going on. Thanks!


VS Code, change NodeJS version for debugger

Question: I want to change NodeJS version from 4.5.0 to 7.7.2 for VS Code specifically for different projects.
I am using nvm on Mac, and I have two versions stated above. They are for different projects.
Even though I can change from terminal with nvm, VS Code uses default version. I need to change the default version every time and completely restart the VSCode.
Is there a way to alter configuration so it picks up the version I wanted
both for in-app terminal and for running project?
Answer: After VS Code 1.21, there is a better solution than the original answer.
You can set "runtimeVersion": "7.7.2" and if you have nvm/nvs installed, it will be able to find that version of Node. Details: https://code.visualstudio.com/updates/v1_21#_node-debugging
--- Original answer ---
In your launch config, you can set a path to a Node executable from nvm like this: "runtimeExecutable": "/Users/me/.nvm/versions/node/v7.7.1/bin/node"
Comment: thanks very the answer, this can solve the problem. Please mark as the correct answer.
Comment: Thnx! Helped me a lot
Comment: sorry for the stupid question, how to find the launch config?
Comment: @fotoflo check this out -> https://code.visualstudio.com/docs/editor/debugging


AWS SDK: manually install thrid-party tools

Question: Issue Error while build AWD SDK (C++) library.
I am  trying to build the AWD SDK packages, and getting errors.
It seems that something is wrong with the 'automatically download' of third party tools, and the install procedure gets stalled. (maybe my IT department is blocking a port!)
This is what I'm using:

git: v1.9.9
cmake: v3.8.2
curl: v3.8.2
gcc: v6.3

Here is the output log:
-- Found Git: /grid/common/pkgs/git/latest/bin/git (found version "1.9.0")
-- TARGET_ARCH not specified; inferring host OS to be platform compilation target
-- Building AWS libraries as shared objects
-- Generating linux build config
fatal: Not a git repository: '/home/dargollo/aws/aws-sdk-cpp-master/.git'
-- Building project version: 1.7.42
-- The C compiler identification is GNU 6.3.0
-- The CXX compiler identification is GNU 6.3.0
-- Check for working C compiler: /grid/common/pkgs/gcc/v6.3.0/bin/gcc
-- Check for working C compiler: /grid/common/pkgs/gcc/v6.3.0/bin/gcc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /grid/common/pkgs/gcc/v6.3.0/bin/g++
-- Check for working CXX compiler: /grid/common/pkgs/gcc/v6.3.0/bin/g++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/dargollo/aws/blddir/.deps
Scanning dependencies of target AwsCCommon
[  4%] Creating directories for 'AwsCCommon'
[  8%] Performing download step (git clone) for 'AwsCCommon'
Cloning into 'AwsCCommon'...
Cloning into 'AwsCCommon'...
Cloning into 'AwsCCommon'...
-- Had to git clone more than once:
          3 times.

Question
Is it possible to bypass the automatically git download? I can download the packages individually, and copy then somewhere....

aws-c-common-master.zip
aws-c-event-stream-master.zip
aws-checksums-master.zip
Comment: Looks like it might be failing because you downloaded the project via github instead of using git clone? The package name of `aws-sdk-cpp-master` tells me this
Comment: You're following?: https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/setup.html
Comment: yes - I am following the setup guide: In the section "To build the SDK from source" it allows the download of the zip file without clone.
Answer: The issue was related to old versions of curl, and git installed on my system.
Hit was getting sucked and not able to download. I did not find a way to build/install the AWS/SDK without using git for the 3rd party tools.
After I downloaded and built those packages, the aws sdk installation performed fine without any problem.
I have used:
curl from: https://github.com/curl/curl/tree/curl-7_63_0
git from https://github.com/git/git

with versions:
curl 7.63.0-DEV (x86_64-unknown-linux-gnu) libcurl/7.63.0-DEV OpenSSL/1.0.1e
git version 2.20.GIT


Redirecionar para outra página

Question: Colegas.
Como eu faria para que o usuário ao fechar o browser ou aba, fosse direcionado para outra página, porém que não funcionasse quando desse o F5. Digo isso pq tenho um sistema do qual tem o status online e offline e muitos deles estão fechando pelo navegador ou aba e o status continua online. A ideia e quando fechar o browser ou aba, ser direcionado para uma página onde eu pudesse desligar ele do sistema e dali fechar o navegador.
Procurando daqui e dali, achei esse código,  porém nao está funcionando, mas pode ser um ponto de partida... vejam:

Comment: Parece que você quer algo impossível, mas não sei se entendi direito. Você só pode interceptar a saída da página pelos eventos `unload` e `beforeunload`, e eles rodam tanto ao fechar a aba ou janela, quanto ao recarregar a página. Mas não entendi bem a ideia de redirecionar quando a pessoa tenta fechar o browser. Se ele será fechado, nem adiantaria redirecionar. E obviamente uma página não pode impedir ninguém de fechar o browser.
Comment: rs rs... pensei que com jquery ou ajax nada fosse impossível... mas vamos lá... com jquery encontrei esse código: $(window).unload(function(){
    alert("Goodbye!");
});
Encontrei também esse código:

Porém preciso apenas desligar o usuário do sistema, colocar uma url('sair.php') por exemplo, apenas ler esse arquivo e continuar a execução do fechamento da página...
Answer: O ideal seria não redirecioná-los, mas fazer uma requisição via ajax para esta página e de lá atualizar o status.
Para interceptar quando o browser está fechando e fazer uma requisição AJAX, pode-se usar o seguinte código:
window.onunload = function(ev) {
  var request = new XMLHttpRequest();
  request.open('POST', '/caminho/para/update/do/status.php', true);
  request.send();
  request.onreadystatechanged = function(e) {
     if(this.status === 200 || this.statusText === 'OK') {
       // deu tudo certo
     } else {
       // muito provável que algo tenha dado errado
     }
  }
}

Embora não seja 100% necessário, jQuery também poderia ser usado no lugar de VanillaJS.
Comment: Olá thepanuto...no body coloco alguma coisa ou apenas esse código?
Comment: não é necessário... na página que está sendo fechada, somente uma tag script com esse código dentro. Na sua página `caminho/para/update/do/status.php` tem que haver um código PHP pra atualizar o status, de online pra offline.
Comment: Quase..rrsrsr... consigo agora mudar o status, porém o que está ocorrendo é que se eu sair pelo browser, outras pessoas acabam perdendo a sessão também... alterei linha request.open('POST', 'sair.php', true);  ...
Comment: Teria algum meio disso não acontecer?
Comment: Tenha certeza que não está alterando o status de mais ninguém ao fazer o update na página `sair.php`.
Comment: No sair.php eu pego a sessão de cada usuário, do qual acredito que rode somente no browser dele, mas mesmo assim desloga os outros. Depois tentei passar por querystring a variável de cada usuário para forçar o desligamento individual: sair.php?Key=$idUsuarios; ... mas também não funcionou...
Comment: Usando $_SESSION, você tem acesso somente à sessão do usuário que está atualmente visualizando a página. Para passar dados para a página, mande uma query string no `.send` do objeto, e.g. `request.send('keys=1,2,3');`
Comment: Olá thepanuto. Perdoe-me a ignorância mais uma vez. Nesse caso eu teria que pegar dess forma? "request.send()"... o e.g coloco antes do request.send?
Comment: sim, mas no caso teria que ser uma query string, ou seja, no formato `'key1=foo&key2=bar'`. Antes do `.send`, vem todo o código da minha resposta, mas em vez do `.send()` vazio, você passa o resultado do php, e.g. `.send('')` e antes, atualize a variável `$minhaVar`.
Comment: Certo... só não consegui entender o e.g.. rs rs ... ficaria dessa forma? e.g.request.send(...)?
Comment: e.g. é latim para "exempli gratia", que significa "por exemplo", somente. O código da requisição é como está na resposta, mudando somente o `request.send`, que fica assim: `request.send('')`
Comment: certo thepanuto... foi testar aqui... obrigado pela ajuda...

Redirecionar para outra página


Selecting item dynamically added to Menu Item List

Question: I'm using the below loop to add items to a Menu Item Strip dynamically on program load
For Each specs In My.Computer.FileSystem.GetFiles(My.Settings.SpecsLoc, FileIO.SearchOption.SearchTopLevelOnly, "*.pdf*")
        SpecsToolStripMenuItem.DropDownItems.Add(IO.Path.GetFileName(specs))
    Next

This will populate the Menu item with, on average, 20 items. I've been searching on how to now open the files from the list.
Thanks
Answer: The constructor can also take an event handler, so you can just add it like this:
SpecsToolStripMenuItem.DropDownItems.Add(IO.Path.GetFileName(specs), _
                                         Nothing, _
                                         Sub()
                                           Process.Start(specs)
                                         End Sub)


Executing drush in a bash script

Question: I'm under MacOSX and I'm struggling for hours trying to figure out how to make drush run from a bash script.
So let's say I create a named build, then I make it executable.
now I begin the script like this:
#!/bin/bash
drush cc drush

In the terminal if I make ./build, it brings me result like : Drush: command not found
So how can I make it work?
Thank you for your answers!
Comment: See: https://superuser.com/a/618442/31654
Comment: This is probably related to the path setting. Does `source build` still work if you open a new terminal?
Comment: the question is about executing the script, of course you have to be in the path where the script is logically. So if you want to execute it everywhere you can always create an alias.
Answer: Got it!
If you call the script directly it doesn't work, better if ou source it like this: source build, then it works.
Anyway, I don't know if it's the better way to call this script.
Comment: https://superuser.com/a/618442/31654
Answer: You need to make sure that drush command is within your PATH environmental variable.
If you're on macOS, place it in /usr/local/bin folder, then run this command to check that:
$ type -a drush
drush is /usr/local/bin/drush

And make sure that /usr/local/bin folder is part of your `PATH variable, e.g. by:
$ tr : "\n" <<<$PATH | grep usr.local.bin
/usr/local/bin

Executing drush in a bash script


Why do folks get different answers for 48/2(9+3)?

Question: I did 48/2(9+3) as I thought I had been taught and got the incorrect answer of 2. There's got to be a reason why so many are not only getting the wrong answer but consistently getting the same wrong answer. This came up once before when another equation became an internet meme. Math rules didn't change so something else was different for those who get the right answer and those who get 2 for an answer. I suspect it has something to do with when we were taught math and how the problem is presented. I'm 65 and was never taught MDAS. Was it considered unnecessary when I was taught because this problem would have been presented in an alternative fashion to make the mistake unlikely? It would be interesting to do a study of the ages of those who get 2 and those who get 288. I sought an answer to this question back when the last "math problem meme" hit the Net and could not only not get an answer but no one could even understand my question. Hope I have better luck this time.
Comment: Because 48/2(9+3) is awfully written. You either want 48/[2(9+3)] or (48/2)(9+3). Parenthesis are there to be used!
Comment: @Pedro: Could I get to vote for that as an answer, please?
Answer: Because 48/2(9+3) is awfully written. You either want 48/[2(9+3)] or (48/2)(9+3). Parenthesis are there to be used!
Answer: Some people don't pay a lot of attention to parentheses.  The $(9+3)$ is not in the denominator.  If we wanted it in the denominator, we have to have $48/(2(9+3))$.  The extra set of parentheses puts it in the denominator.
Answer: It's the $2(9+3)$ part that makes things screwy. If you follow PEMDAS, you get this:
$$\frac{48}2(9+3)$$
Which is 288, as it's supposed to be. The problem is that a lot of people colloquially use $a(b+c)$ as if it was it's own self-contained expression, like it was actually written as $(a(b+c))$. If you're used to writing and reading it that way (super, super common in physics and other natural sciences), you automatically parse the expression as
$$\frac{48}{2(9+3)}$$
Which is the incorrect answer 2. I'd bet a lot of money that if you rewrote the problem as $48/2\cdot(9+3)$, people would be much less likely to treat the $2(9+3)$ as its own expression.


Photo Gallery / Grid for Twitter Bootstrap v2.1.1

Question: I'm really liking Twitter Bootstrap so far and am finding it fairly easy to implement. The next step is to implement some-type of photo gallery for some pages and for future blog posts. Ideally I would like rows of photos (perhaps 4/row) with nice small borders and pop-up enlarged images either when (a) clicked on or (b) hovered over. I did some research and was unable to find any tutorials or ways how to do this.
Many thanks.
Comment: Have you looked at [the](http://twitter.github.com/bootstrap/components.html#thumbnails) [doc](http://twitter.github.com/bootstrap/components.html#media) ? Or at [those](http://www.1stwebdesigner.com/css/fresh-jquery-image-gallery-display-solutions/) [articles](http://vandelaydesign.com/blog/web-development/jquery-image-galleries/) ?
Comment: Yes, I've looked at the documentation. However, it doesn't include information about any pop-up image viewer. If you could make a suggestion as to which script(s) to use that would be great. Thanks.
Comment: It includes link to such information. Try [fancybox](http://fancyapps.com/fancybox/#examples), or search the web a bit more, try the scripts you find, and then come back if you encounter a specific problem that you can't resolve by looking at previously asked questions.
Comment: Sherbrow -- could you please show me where on "http://twitter.github.com/bootstrap/components.html#thumbnails" there is a link to "such information" like Fancybox? Just want to clarify. I will give fancybox a try, thanks!
Answer: check out https://github.com/blueimp/Bootstrap-Image-Gallery
it demonstrates a simple image gallery for bootstrap theres also https://github.com/jbutz/bootstrap-lightbox for a lightbox almost effect.


stop youtube videos opening youtube app in xcode/cordova 1.6.1

Question: I am building an app in xcode using the Cordova/phonegap framework for ios which displays some html that has some embeded youtube player code in it. iOS seems to redirect the user to the youtube app when it hits this youtube player. In cordova 1.5.0 the following code worked, but in 1.6.1 it doesn't seem to. Any ideas why or what needs changing to get it to work?
code to stop youtube opening up and links to behave selves
- (BOOL)webView:(UIWebView *)theWebView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];

    // Intercept the external http requests and forward to Safari.app
    // Otherwise forward to the PhoneGap WebView

    NSString* urlString = [url absoluteString];
    if([urlString rangeOfString:@"http://www.youtube.com/embed"].location != NSNotFound) {
        return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
    }
    else if (([[url scheme] isEqualToString:@"http"] || [[url scheme] isEqualToString:@"https"])) {
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    else {
        return [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
    }
}

Answer: I would put logging in for url at the beginning of the method, and then a log statement in each clause of the if/elseif/else so you can see what urls are being intercepted and what the method then does with each one.
Maybe the string for the youtube request doesn't match the hardcoded "http://www.youtube.com/embed" any more? Worth a look.
Answer: look at http://apiblog.youtube.com/2009/02/youtube-apis-iphone-cool-mobile-apps.html
this might help.
It says to do this:
NSString *htmlString = @"
<meta name = \"viewport\" content = \"initial-scale = 1.0, user-scalable = no, width = 212\"/>

<object width=\"212\" height=\"172\">
<param name=\"movie\" value=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"></param>
<param name=\"wmode\" value=\"transparent\"></param>
<embed src=\"http://www.youtube.com/v/oHg5SJYRHA0&f=gdata_videos&c=ytapi-my-clientID&d=nGF83uyVrg8eD4rfEkk22mDOl3qUImVMV6ramM\"
type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"212\" height=\"172\"></embed>
</object>
";

[webView loadHTMLString:htmlString baseURL:[NSURL URLWithString:@"http://www.your-url.com"]];


DataReader exception : Invalid attempt to call Read when reader is closed

Question: Why am I getting an datareader exception: Invalid attempt to call Read when reader is closed. When I stepped through using the debugger the program crash on            while (dbReader.Read()). dbReader is wrapped around a using statement so I don't understand how the reader is closed.
 using (OleDbDataReader dbReader = dbCommand.ExecuteReader())
 {
    if (dbReader.HasRows)
    {
       dataTable.Load(dbReader);

       while (dbReader.Read())
       {
          //Processing
       }
    }
 }

Comment: Not sure but didn't `dataTable.Load()` already read all the data?
Comment: I want to load the data into the datatable but also perform business logic for each row
Answer: A reader can only be consumed once. If you used the reader to populate a DataTable : that's it - the data is gone. It is basically a sequence over a socket - it isn't repeatable.
So: run your business logic on the data you've already loaded.
Answer: As Marc Gravell♦ already pointed out in his answer you only can read once.

But answering your comment:

I want to load the data into the datatable but also perform business logic for each row

You can create your DataTable manually by iterating over all received fields like:
var dataTable = new DataTable(tableName);

for (int field = 0; field < dataReader.FieldCount; field++)
{
    var column = new DataColumn(dataReader.GetName(field), dataReader.GetFieldType(field));
    dataTable.Columns.Add(column);
}

and after that, you can start reading the data one row after the other and filling your DataTable rows like:
while ( dataReader.Read() )
{
    var dataRow = dataTable.NewRow();

    // Option 1
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
        dataRow[i] = dataReader[i];
    }

    // or Option 2
    dataRow["col1"] = dataReader["col1"];
    dataRow["col2"] = dataReader["col2"];
    dataRow["col3"] = dataReader["col3"];

    // or something else
    // ...

    dataTable.Rows.Add(dataRow);
}

You can also find some examples at the Docs - DataTable.Load-Examples.
Or for a more detailed look see DataAdapters and DataReaders.


Inverse of Short-time Fourier transform

Question: The Gabor transform (i.e. Short-time Fourier transform with some Gaussian window) can be defined by  (see http://en.wikipedia.org/wiki/Gabor_transform) :
$G_x(t_0,\xi) = \int_{-\infty}^\infty e^{-\pi(t-t_0)^2}e^{-2i\pi \xi t}x(t)\,dt$
On this page it is mentioned that the Gabor transform is invertible, and that the original signal can be recovered by the following equation :
$ x(t_0) = \int_{-\infty}^\infty G_x(t_0,\xi) e^{2i\pi t_0 \xi}\,d\xi$
Can somebody help me for a proof of that ?
I thought we would need $G_x(u,\xi)$ for all $\xi$ and $u$ in a wide range in order to reconstruct $x(t_0)$,  but here it seems that only $G_x(t_0,\xi)$ for all $\xi$ is needed. Is this true ?
Answer: Ok according to a book:
the Windowed Fourier transform is obtained by the formula:
$$Sf(u,\epsilon)=\int_\mathbb{R}f(t)g(t-u)e^{-i\epsilon t}dt$$
where $f$ and $g$ are the signal and window respectively:
and the reconstruction formula is given by:
$$f(t)=\frac{1}{2\pi}\int_\mathbb{R}\int_\mathbb{R}Sf(u,\epsilon)g(t-u)e^{i\epsilon t}d\epsilon du$$.
So I reckon you will need both $u$ and $\epsilon$, to reconstruct $f$.
Comment: @Basj: A wavelet tour of signal processing
Comment: Or maybe is there some magical thing that makes that **only one** integral is needed at the end when the window $g$ is a Gaussian window (Gabor transform) ?
Comment: yes! I also thought 2 integrations will be required in order to recover $f(t)$, so I don't understand how it could be possible with only $1$. Is there a mistake in Wikipedia here : http://en.wikipedia.org/wiki/Gabor_transform#Inverse_Gabor_transform ?
Comment: just for information, which book is it ?
Comment: @Basj: I think there is a mistake there.
Comment: Thanks. I don't know so much about Wikipedia editing. Can we put a "May contain a mistake, needs to be verified" sign there ?
Comment: No it should be true for all types of windows
Comment: Ok so it's a true mistake on wikipedia ?
Comment: @Basj, you can try editing on Wikipedia haha

Inverse of Short-time Fourier transform


I can't change the user's password

Question: If I want to change the password, the codes are working properly, do not
show any mistakes, but it looks incorrect if you want to log in with a new
password. I saw in the database, there was no password change.
<code>public function postPasswordReset(Request $request)
{
    $validator = validator::make($request->all(), [
            'email'     =>  'required|exists:users,email',
            'password' => 'required|alpha_num|between:6,32',
            're-password' => 'required|same:password'
        ]);

    if($validator->passes()){

        $user = User::where('email', $request->email)->first();
        $user->update(['password' bcrypt($request->password)]);

        return redirect()->route('auth.login');
    }
     return redirect()->back()->withErrors($validator->errors())-
     >withInput();
}
</code>
Comment: typo : missing =>        $user->update(['password' =>bcrypt($request->password)]);
Comment: thanks JYoThi, it's work. thanks for your supporting.
Comment: glad to help you
Answer: In your update method you are using an array to update in a wrong format. Try this one
<code>$user->update(['password' => bcrypt($request->password)]);
</code>

I can't change the user's password


table view scrolls under view above it not with it

Question: I have a view at the top of the screen(below the navigation bar).
Below the view is a table view.
The problem is that when I scroll down through the table, it scrolls under the view at the top of the screen.
I would like for the view at top to scroll along with the table view.
Can anybody recommend some direction?
I tried to google it and nothing useful came up. I hope I am explaining it well enough here.
Answer: It can be solved easily. Please try to put the view into the tableview as a subview. You could add a view to TableView at top and bottom. The view added to Tableview will be scrolled.
Comment: Even if I have a header for the table view?
I tried to pull the view in the table view and I can't see it anymore.
Comment: Strange, but it works. I just tried in Playground. If I remember correctly, this method didn't work in earlier versions of iOS.
Comment: Oh my, this worked! I wouldn't have expected to be able to do this. Thanks!
I marked your answer as correct as you were the first to suggest this.
Comment: small follow up question bugging me right now: what if I need to hide the view?
right now it leaves with with a blank space at the top of the table.
how to i hide the view and make the table start from where the view was?
Comment: You can change the height of the view with the instance of it in code. It will work.
Answer: There are two solutions that I can think of here:
Solution 1: Add a prototype cell in your table, and use that as the view you want to display at the topmost part of your table. Then in your code, you can load that cell at the index 0 to ensure that it will be loaded at the topmost part of your table.
Code sample:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        TopMostTableCell *tableCell = (TopMostTableCell *)[tableView dequeueReusableCellWithIdentifier:@"TopMostTableCell"];

        return tableCell;
    }

    else
    {
        OtherTableCell *tableCell = (OtherTableCell *)[tableView dequeueReusableCellWithIdentifier:@"OtherTableCell"];

        return tableCell;
    }
}

Solution 2: Add the view you want to be the topmost part of the table which you can scroll along to the table header.
You can add the view through coding, or loading the nib file.
Code sample:
- (void)viewDidLoad
{
    [super viewDidLoad];

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 200, 50)];

    //loading from nib file
    UIView *headFromNib = [[[NSBundle mainBundle] loadNibNamed:@"Header" owner:self options:nil] objectAtIndex:0];

    [header setBackgroundColor:[UIColor blackColor]];
    _table.tableHeaderView = header;
}

Hope this helps you. :)
Comment: Thank you for your answer.
If the table has a header, should I add the view to the header or directly to the table?
Comment: You should add that to the header. Otherwise If you have a separate layout for your header, and you want that view(you are talking about) on top of your table header, then you might as well join the layout of your header and that view and then put that joined view(header + the view) at the header section of the table.
Answer: You can intercept scrolling implementing scrollViewDidScroll method in your table view delegate and in this method update frame (or constraints, if you are using AutoLayout) of this overlaying view.


Acoustic guitar, chip in rosette wood, how to avoid in future?

Question: I was performing this afternoon when I felt a sharp pain in my right thumb. I looked down, and there was a big hunk of wood (about half an inch long) sticking out from my right thumbnail. There was a similarly-sized hole inside the rosette, next to the soundhole.

The wood there is pretty dry and crappy. The rest of the guitar sounds great and looks fine, but I'd like to avoid this happening again.
My question: How can I repair this? What do I have to do to moisturize the wood in this area? I'm not concerned with how the guitar looks, but this damage looks like an accident waiting to happen again.
(The guitar is a Seagull "Grand" parlor acoustic. And yes, I finished the song, and managed to pull the splinter out while playing.)
Answer: In order to fix this, you will probably need to take the guitar to a luthier and have him fit a "patch" over it.
If the reason for the damage is that the wood has become dry and brittle, you should probably invest in a guitar humidifier. There are a number of options available on the market - some are designed to be placed in the soundbox, others should be placed in the guitar case. Consult the luthier when getting the chip fixed.
Comment: To follow up: I have been keeping the guitar in its case with a humidifier and have been moisturizing the wood, paying special attention to this area. Will have the chip looked at the next time I bring this guitar in for a setup.
Answer: Congratulation for the feat of finishing the song in these conditions, and I presume without others noticing.
In complement to Faza's answer
If I interpret your photograph well, it means that you play with you right hand and your right thumb advanced over the rosette and the fretboard. Could be a good idea to train yourself to move your hand and arm a little toward your right and the bridge. It will help you avoid this unfortunate incident before having the instrument repaired and it is usually quite beneficial in term of power and articulation of sound when playing an acoustic guitar by uncovering the rosette and forcing a more deliberate action on the strings. There may be other little technique elements you could reconsider to make this kind of accident less likely (such as having the hand movements kept more parallel to the strings, retracting the thumb a little when striking with the full hand, ...)
Comment: Maybe nobody would have noticed, but for me complaining loudly and frequently after the song ended.


Derivative of standard gaussian hypergeometric function $_2F_1$

Question: I have a very simple question on the first derivative of a standard guassian hypergeometric function.
When I input the following command
D[Hypergeometric2F1[x, a, b, c], x]
Mathematica returns
$Hypergeometric2F1^{(0,1,0,0)}[x, a, b, c]$
Could anyone tell me what the above hypergeometric function means, especially the superscript?
Thank you so much for your help!
Comment: Derivative of the function  wrt $a$, I guess.
Comment: I agree. Are you sure you want to differentiate $$\phantom{}_2 F_1\left(a,b;c;x\right) = \sum_{n\geq 0}\frac{(a)_n (b)_n}{n!(c)_n} x^n $$ with respect to the first parameter ($a$)?
Comment: Yes, I'd like to differentiate it wrt the first parameter (a). Thank you!
Comment: Indeed, the final target is to show the hypergeometric function is an increasing function of the first parameter. So I'd like to differentiate it wrt the first parameter a. Do you have any other solutions to show this?
Answer: According to K. Oldham, J. Myland, & J. Spanier, An Atlas of Functions, Ch. 60, Springer,
$$\frac{d}{dx}~_2F_1(a,b;c;x)=\frac{ab}{c}~_2F_1(a+1,b+1;c+1;x)\\
\frac{d^n}{dx^n}~_2F_1(a,b;c;x)=\frac{(a)_n(b)_n}{(c)_n}~_2F_1(a+n,b+n;c+n;x)
$$
where $(a)_n$ is the Pochhammer polynomial, of course.
Comment: This should be easily established via series.
Comment: But I'd like to differentiate it wrt the first parameter a. Thank you anyway!
Comment: @JunyuLiu Be that as it may, the Mathematica code you wrote was D[Hypergeometric2F1[x, a, b, c], x] (differentiation w.r.t. $x$). Given the nature of the Pochhammer polynomials, I would think you will be limited to cases where closed form solutions are available, such as $F(a,b;c;1), which can be expressed in terms of gamma functions.


Spock - How to check method invocation count on a Spy object?

Question: I'm having tough time get this spock test to work.
I have a Spring repo/DAO class that invokes stored procedures multiple times. I'm trying to write a unit test that validates if the SP is invoked 'x' number of times (3 invocations to createSP() method).
public class PlanConditionRepositoryImpl{

    ....

    public void write() {
        for (int i=0; i<3; i++) {
            createSP(new ConditionGroup(), new Condition()).call();
        }
    }

    protected StoredProcedure<Void> createSP(ConditionGroup planConditionGroup, Condition planCondition) {
        return new StoredProcedure<Void>()
                .jdbcTemplate(getJdbcTemplate())
                .schemaName(SCHEMA_NAME);
    }
}

However the below implementation is not doing that. How do I achieve the invocation count check? Or how do I avoid calling the actual implementation of createSP() method.
def write(){
    def repo = Spy(PlanConditionRepositoryImpl){
        createSP(_, _) >> Spy(StoredProcedure){
            call() >> {
                //do nothing
            }
        }
    }
    when:
    repo.write()

    then:
    3 * repo.createSP(_, _)
}

This is how I solved it using a hack. But is there a solution using Spock's interaction-based testing without introducing an extra variable?
def "spec"() {
    given:
    def count = 0
    def spy = Spy(PlanConditionRepositoryImpl){
        createSP(_, _) >> {count++}
    }

    when:
    spy.write()

    then:
    count == 3
}

Answer: What you need is a partial mock, have a look at the docs. However as I said partial mocking is basically bad practice and may indicate a bad design:

(Think twice before using this feature. It might be better to change
  the design of the code under specification.)

And about partial mocking:
// this is now the object under specification, not a collaborator
def persister = Spy(MessagePersister) {
  // stub a call on the same object
  isPersistable(_) >> true
}

when:
persister.receive("msg")

then:
// demand a call on the same object
1 * persister.persist("msg")

Here's how the test should be written:
@Grab('org.spockframework:spock-core:1.0-groovy-2.4')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {
    def "spec"() {
        given:
        def mock = Mock(StoredProcedure)
        def spy = Spy(PlanConditionRepositoryImpl)

        when:
        spy.write()

        then:
        3 * spy.createSP() >> mock
        3 * mock.run()
    }
}

class PlanConditionRepositoryImpl {

    void write() {
        for (int i = 0; i < 3; i++) {
            createSP().run()
        }
    }

    StoredProcedure createSP() {
        new StoredProcedure()
    }
}

class StoredProcedure {
    def run() {}
}

Comment: I'm afraid `PlanConditionRepositoryImpl` is in Java. So I can't use Closure return type for createSP.
Comment: It's just an example, return what is needed.
Comment: And (BTW) you can return an instance of `Closure` from java - you just need to include groovy dependency and use appropriate syntax.
Comment: I tried executing your code and it calls `createSP()` in `PlanConditionRepositoryImpl` 3 times. But what I'm looking for is different. I don't the actual implementation of the `createSP()` method invoked. How can I replace it with a custom closure in Groovy test case and ensure it is called 3 times?
Comment: Sorry, don't understand. The spec I provided verifies if `createSP` method was invoked three times. If you chnage `3 *` to `4 *` you will see the test fails. Please clarify what you need to achieve or even provide a failing test.
Comment: Sorry if I was not clear. What I'm trying to ask is, on the Spy object, instead of calling the concrete implementation of a method in it, how do I pass in a custom implementation from Groovy.
Comment: Sorry, still don't get it. If you don't want to call a concrete implementation you'd rather need a `Mock` or a `Stub`. But you can't both mock a class and test it - it doesn't make sense. What I can suggest is to move the `createSP` method outside of `PlanConditionRepositoryImpl` (it may be a `SPFactory` e.g.), then you can mock it and return whatever you need and it'll be better designed + easier to test. I may still help you, but I need to understand what you need to test/do.
Comment: The unit test I'm intending to write needs to ensure the following: when `write()` method is called, then check `createSP()` is called 'n' number of times irrespective of the input or output. It so happens, my `createSP()` method has external DB dependency.  So my thought process was to use a Spy and replace `createSP` concrete impl with some mock implementation. I tried Mock, Stub and Spy and yet I'm not able to get the desired results.
Comment: Please see the original question with the hack I used to get around it.
Comment: @MFIhsan, I've completely rebuilt my response. Hope it solves your problem now. But mind what I wrote about design.
Comment: Excellent. This should do @Opal. Thank you.
Comment: You're welcome! Ask your mates to upvote :D Glad, it's finally worked out.


Update/Add string values based on another string

Question: I'm trying to create manual browser cookie emulation using Node.js.
Basically I have two strings, once containing the current cookie and the other containing new or updated values to be added to the cookie. I want to update the old string with the new one by replacing or adding values. How can I achieve this via javascript?
For example:
PREF=ID=2191324fe41c6152:FF=0:TM=1320223272:LM=1320223272:S=H6-vdbEpgEzHAknb;
Foo=kfjaofjiof382f3gio;
expires=Fri, 01-Nov-2013 08:41:12 GMT; path=/; HTTPonly;

Is updated with
PREF=ID=435:FF=2:TM=1320223272:LM=1320223272:S=zzHAknb; Name=23;
expires=Fri, 01-Nov-2013 08:41:12 GMT; path=/; HTTPonly;

Returns
PREF=ID=435:FF=2:TM=1320223272:LM=1320223272:S=zzHAknb; Name=23;
Foo=kfjaofjiof382f3gio;
expires=Fri, 01-Nov-2013 08:41:12 GMT; path=/; HTTPonly;

Comment: Split strings, put data of first in object, overwrite keys with second object, stringify again?
Comment: May I recommend checking out [this question](http://stackoverflow.com/questions/1162153/how-do-i-parse-a-variable-or-multi-value-cookie-in-selenium)?
Answer: function string_replace(haystack, find, sub) //replaces all occurences of find with sub
 {
    return haystack.split(find).join(sub);
 }

function string_add(haystack,upgrade){return haystack+upgrade;}

I think you can do the rest.
Thanks to bobnice of Javascript - how to replace a sub-string?.
Comment: or if you want to replace the values, go with a regex approach.


When running the program in netBeans the font looks extremely weird

Question: I set up netBeans and a SceneBuilder on my new MacBook M1 and everything works, except of the font when running the program.
It looks like this:

and I have no clue why.
The Button should say: "Click me" and the Label: "Hello".
The Error message I get is:
<code>März 31, 2021 6:33:04 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 16 by JavaFX runtime of version 11.0.2
2021-03-31 18:33:05.466 java[4349:140717] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:].
2021-03-31 18:33:05.466 java[4349:140717] CoreText note: Set a breakpoint on CTFontLogSystemFontNameRequest to debug.
2021-03-31 18:33:05.471 java[4349:140717] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:].
2021-03-31 18:33:05.641 java[4349:140751] CoreText note: Client requested name ".SFNS-Regular", it will get Times-Roman rather than the intended font. All system UI font access should be through proper APIs such as CTFontCreateUIFontForLanguage() or +[NSFont systemFontOfSize:].
</code>
Comment: so I made it work the right way. I changed the font in the SceneBuilder to "SansSerif" and now it displays the text as it should be displayed. But I still get one warning: Loading FXML document with JavaFX API of version 16 by JavaFX runtime of version 11.0.2
Comment: okay, so I also fixed it. In my FXML I put: xmlns="http://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml/1" instead of xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1"
Comment: What was the "right way" -- I am running into this issue currently.
Intel MBP - Latest ( Monterey ) - but Im using Intellij CE
Answer: I also had the same issue, but in my case, the problem was with JDK 11. First, I tried to switch to JDK 8 and everything worked fine, but then I found that another version of JDK 11 (AdoptOpenJDK(HotSpot) 11) also fixes it.
Answer: In my case that crap came up when I run programm on mac (on pc was all good).
For me shortest way to solve this was one record in stylesheet:
<code>.root{
-fx-font-size: 11pt;
-fx-font-family: "Arial";
}
</code>
Comment: adding the font-family fixed my issue - i tried a number of different jvms, but the warnings show it's all about the font
Answer: In my case, I was using the JavaFX 11 with the JDK11 and that was giving the weird characters, so I changed it to JavaFX 16 and also started using the JDK16 and that fixed my problem!
Answer: I have also switched my Module setting back to : 11.0.8 instead of 11.0.12 as shown below:
Comment: Please add further details to expand on your answer, such as working code or documentation citations.
Comment: For both question and answer, keep the whole documentation and screenshots on this site. If the other one goes down this post will be useless.
Answer: I was able to resolve the issue by adjusting the JDK version. Although I did not have JDK 8, JDK 14 worked fine and JDK 17 did not. It will work fine if you change the project structure to a more compatible JDK version with JavaFX.
Answer: You can install the AdoptOpenJDK from this link https://formulae.brew.sh/cask/adoptopenjdk
(Note: you need to have Brew installed).
Then you go to the project module settings and then go to 'Project'.
There you will see the label 'SDK'. Click there and next select 'Add JDK'.
It will redirect you to the JDKs and next select the 'AdoptOpenJDk' folder.


Writing a query that contains variable WHERE based on user input

Question: I'm having trouble with a query. What I would like it to do is check that each variable exists, and ignore them if they don't. I also want to display the results in a table. Any help would be greatly appreciated!
What I have so far: This is my code. At the moment, it returns an array with all results from the database, but if I change the ORs in the WHERE clause to AND, all fields need to be filled. I want the user to be able to input as much information as they know, in order to display all possible results.
<?php require("common.php");?>
<?php
if(!empty($_POST))
{
$sth = $db->prepare("SELECT * FROM customer WHERE First_name LIKE '%$First_name%' OR Surname LIKE '%$Surname%' OR DOB LIKE '$DOB' OR Street LIKE '%$Street%' OR Suburb LIKE '$Suburb' OR State LIKE '$State' OR Postcode LIKE '$Postcode' OR Phone LIKE '$Phone'");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

$First_name = $_POST['First_name'];
$Surname = $_POST['Surname'];
$DOB = $_POST['DOB'];
$Street = $_POST['Street'];
$Suburb = $_POST['Suburb'];
$State = $_POST['State'];
$Postcode = $_POST['Postcode'];
$Phone = $_POST['Phone'];
}
?>
<fieldset><legend>Find a customer</legend>
<form name="querycustomerform" method="post" action="qcustomer.php">

Please fill out as many details as possible

                <input type="text" name="First_name" maxlength="30" size="30" placeholder="First name">

                <input type="text" name="Surname" maxlength="30" size="30" placeholder="Surname">

            Date of Birth:

                <input type="date" name="DOB">

                <input type="text" name="Street" maxlength="40" size="30" placeholder="Street Address">

                <input type="text" name="Suburb" maxlength="15" size="30" placeholder="Suburb">

                <select name="State">
                <option value="">State</option>
                <option value="ACT">Australian Capital Territory</option>
                <option value="NSW">New South Wales</option>
                <option value="NT">Northern Territory</option>
                <option value="QLD">Queensland</option>
                <option value="SA">South Australia</option>
                <option value="TAS">Tasmania</option>
                <option value="VIC">Victoria</option>
                <option value="WA">Western Australia</option>
                </select>

                <input type="text" name="Postcode" maxlength="4" size="30" placeholder="Postcode">

                <input type="text" name="Phone" maxlength="15" size="30" placeholder="Phone Number">

                <input class="button" type="submit" value="Search">

</form>
</fieldset>

Comment: check what the filled in, add to query if info provided
Comment: And what would that look like?
Answer: The OR condition requires that any of the conditions (ie: condition1, condition2, condition_n) be must be met for the record to be included in the result set.Whereas the  AND condition requires that all of the conditions (ie: condition1, condition2, condition_n) be must be met. For your requirement the OR condition is required.
You need to build a dynamic query to perform this. Start with a basic stub
$sql = "SELECT * FROM customer";

Then you need to set the initial clause to  WHERE.
$clause = " WHERE ";//Initial clause

You need an array to store parameters
$paramArray =array();

Start building the query.Note I have changed from POST to GET as it is easier to test
Also see PDO WIKI for use % in placeholders.ie placeholders cannot represent an arbitrary part of the query, but a complete data literal only.
if(isset($_GET['First_name'])){
    $First_name = $_GET['First_name'];
    $sql .= "$clause First_name LIKE ?";
    $clause = " OR ";//Change clause
    array_push($paramArray,"%$First_name%");
}

Continue with next clause
if(isset($_GET['Surname'])){
    $Surname = $_GET['Surname'];
    $sql .= "$clause Surname LIKE ?";
    $clause = " OR ";
    array_push($paramArray,"%$Surname%");
}

Add remainder of clauses as above
Test result, Remove after testing & change GET to POST
echo $sql ;
echo "
";
print_r($paramArray);

Prepare and execute query
$sth = $db->prepare($sql);
$sth->execute($paramArray);

Typical Test Result from test.php?First_name=dave&Surname=smith
SELECT * FROM customer WHERE First_name LIKE ? OR Surname LIKE ?
Array ( [0] => %dave% [1] => %smith% )

from test.php?Surname=smith
SELECT * FROM customer WHERE Surname LIKE ?
Array ( [0] => %smith% )

Answer: Try changing
$sth = $db->prepare("SELECT * FROM customer WHERE First_name LIKE '%$First_name%' OR Surname LIKE '%$Surname%' OR DOB LIKE '$DOB' OR Street LIKE '%$Street%' OR Suburb LIKE '$Suburb' OR State LIKE '$State' OR Postcode LIKE '$Postcode' OR Phone LIKE '$Phone'");

to
$sth = $db->prepare("SELECT * FROM customer WHERE First_name LIKE '%'".$First_name."'%' OR ...

Take $First_name out of the literal string, and concatenate it with the literal string. What you were doing was literally searching for "$First_name", not the value of the $First_Name variable. It's a bit messy from an appearance perspective, but I have found it safer to concatenate text with variables rather than expand variables within quotes.
Darryl
Comment: Everything is wrong in this answer. It's not answering the question and is giving a wrong advice (the value of $First_name variable IS being used, since it's inside a double quote, not single). This might be a little old, but if a newbie stumbles upon this might get confused.


Number of possibilities to seat $3$ pairs of husbands and wives so that at least one husband and wife sit together

Question: Question: There are $6$ people that consist of $3$ sets of husbands and wives. How many possibilities are there to seat all of them on a bench if at least one couple sits next to each other?
Initially, I thought I could just subtract from the total number of possibilities to seat $6$ people which is $6!$, the complement of the question which is "How many possibilities are there to seat those same people where no couple sits next to each other?". To evaluate how many possibilities there are for the complement, I'll have to first seat all three women on the bench. There are ${{6}\choose{3}} \cdot 3!$ ways to do it. Next, I'll have to seat the guys accordingly (so neither of them sits next to their spouse). The number of possibilities to seat each of them is exactly $2$, thus resulting in $2^{3}$ possibilities for the three of them.
So according to my calculation, the total number of possibilities is: $$6! - {{6}\choose{3}} \cdot 2^{3} = 560$$
However, after comparing my answer to what is written in the textbook, the answer should be: $$3 \cdot 2 \cdot 5! - 3 \cdot 2^{2} \cdot 4! + 2^{3} \cdot 3! = 480$$
Looks like the textbook's answer uses inclusion/exclusion. Before comparing my answer to the textbook's one, I was certain that inclusion/exclusion was unnecessary (I still do in fact), because there was only one exclusion to make - the complement (which I've described above). I really don't get why someone would apply this principle here. Clarifications on the matter will greatly appreciated.
Answer: Finding the complement is not so easy. For example assuming $3$ women is sitting together (by together I mean between them there is no men), for the women in middle, the condition for the complement already satisfied. So your calculation must change in this case and this is not the only case where your calculation must change (For example if one of the women is on the leftmost place and there is a woman in right of her, then the woman on the leftmost side also satisfies the condition for complement and obviously, number of ways are different for these two cases).
Instead, you can use Inclusion-Exclusion Principle by considering the events $A_1, A_2, A_3$ where $A_i$ is the event that $i^{th}$ couple is sitting together. So we have to find
$$|A_1 \cup A_2 \cup A_3| = 3|A_1|-3|A_1 \cap A_2|+|A_1 \cap A_2 \cap A_3|$$
since $|A_1| = |A_2| = |A_3|$ and $|A_1 \cap A_2| = |A_1 \cap A_3| = |A_2 \cap A_3|$ by renumbering.
Now, we have $|A_1| = 2! \cdot 5!$ (because first pair is sticked so we have $5$ things to permute with $5!$ and we can switch the man and woman with $2!$), $|A_1 \cap A_2| = 2^2 \cdot 4!$ and $|A_1 \cap A_2 \cap A_3| = 2^3 \cdot 3!$ by similar arguments. So the result follows.
Comment: Okay, but now you only calculated the number of possibilities for which none of them may sit together. That does not calculate what the question asked for, that is where I get confused. Am I missing something?
Comment: $|A_1 \cup A_2 \cup A_3|$ is the number of ways at least one pair is sitting together. Is your question about the part where I explained why we cannot find the complement so easy?
Comment: The problem is $|A_1 \cup A_2 \cup A_3| = |\overline{A_1 \cap A_2 \cap A_3}| \neq | \overline{A_1}| \cap | \overline{A_2}| \cap | \overline{A_3}|$.
Comment: Okay, I thought about it some more and I get it now. In my mind, the way to use inclusion/exclusion was as if each $A_i$ was each couple not sitting next to each other. I wansn't thinking correctly. Thanks for the great explanation!
Comment: No, what is in your mind is correct and mathematically, it is represented by $|\overline{A_1 \cap A_2 \cap A_3}|$. Before explaining Inclusion-Exclusion Principle in my answer, I explained why it is not easy to find the size of the complement directly. If it was easier to find, I would have suggested a method by calculating the size of complement.
Comment: You are correct, thanks for pointing it out. Your method is indeed much easier and much understandable.
Comment: You're welcome, again you asked a detailed question so it was easier for us to see the point where you were stuck. I thank you, too :)