Show that $[\sum\limits_{k = 0}^n\binom{n}{k}]^2=\sum\limits_{r = 0}^{2n}\binom{2n}{r}$

Question: I'm not sure how to show that $[\sum\limits_{k = 0}^n\binom{n}{k}]^2=\sum\limits_{r = 0}^{2n}\binom{2n}{r}$.
I've heard of $\sum\limits_{k = 0}^n {n \choose k}^2= {2n \choose n}$ but I still get nowhere. I have no idea where $r$ came from or why it's $2n$ above the sum.
Comment: From all the answers below, I understand it now. Thank you everyone!
Answer: Use $$\sum_{f=0}^g{g\choose f}=2^g$$ substituting appropriate values for $f,g$ on both sides of what you want to prove.
Answer: By using a basis propertie of Pascal's triangle the LHS can be written as
$$\left[\sum_{k=0}^n\binom{n}{k}\right]^2=[2^n]^2=2^{2n}=\sum_{r=0}^{2n}\binom{2n}{r}$$
The $r$ is just used as a new index to avoid confusions by naming two different variables $k$ for example.
Answer: $$
\sum_{k=0}^n\binom{n}{r}x^r = (x+1)^n\Rightarrow (x+1)^{2n} = \sum_{k=0}^{2n}\binom{2n}{r}x^r
$$
with $x = 1$
Answer: You could also do a combinatorial proof: given $n$ distinct dogs and $n$ distinct cats, how many ways can you choose a subset of all the animals to take for a walk?


Drupal Commerce Kickstart 2 Mysql problem: "Table XYZ is marked as crashed and should be repaired"

Question: My drupal kickstart 2 site occasionally cause Mysql errors. This is what Drupal Logs say:
"PDOException: SQLSTATE[HY000]: General error: 145 Table './MYSITE/field_revision_body' is marked as crashed and should be repaired: INSERT INTO {field_revision_body} (entity_type, entity_id, revision_id, bundle, delta, language, body_value, body_summary, body_format) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => node [:db_insert_placeholder_1] => 1953 [:db_insert_placeholder_2] => 1953 [:db_insert_placeholder_3] => breaking_news [:db_insert_placeholder_4] => 0 [:db_insert_placeholder_5] => und [:db_insert_placeholder_6] =>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vehicula condimentum placerat. Curabitur vehicula pharetra felis, quis feugiat magna imperdiet non..
 [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => formato_xxxxxx_calcio ) in field_sql_storage_field_storage_write() (linea 452 di /var/www/MYSITE.it/modules/field/modules/field_sql_storage/field_sql_storage.module)."
In this case general error was on table field_revision_body but sometimes it's another table. Hosting Service say that mysql are all ok. So what happend? This site has been online for several months, and only few days ago give me problem.
It seems that mysql dropped, then after a few minutes he recovers tables.
There are specific tools for debugging to see what makes me go down the site?
Pls someone help me.
Comment: I dont see how this is drupal/php related? Do you run the mysql `optimize` command via a system cron task occassionally? Have you done a mysql audit of your mysql configuration settings to assure you're allowing for a good packet size and cache sizes in mysql? If you're on shared hosting you could be over-using your allocated DB resources and being dropped -- consider moving to a VPS or dedicated hosting.
Comment: my point is that you should enable the mysql query log or inspect and audit your mysql setup. Try to replicate the same Commerce Order or Node creation ... There isn't much you can inspect in Drupal or PHP to see how or why MySQL is being corrupted.
Comment: Are your tables InnoDB or MyISAM?
Comment: @tenken I wrote this question coz System Administrator of VPS say me that mysql configuration are fine and all log are ok and he say me is a drupal mistake. So i think was something happens in drupal, i don't know what, furthermore this issue is only from few days. In previous months has always gone ok.
Comment: @MPD I've noticed now that almost all the tables are MyISAM, only some are InnoDB. In your opinion, is this correct?
Answer: I have run into this problem a few times. It is indeed not directly Drupal related. However, since we are looking at MySQL through a Drupal lens, I guess we might as well answer it here.
The real source of the problem is a performance problem for your MySQL server. Drupal might have contributed to the problem by adding too much load. When I ran into a similar problem, I found out that a module I had written was making a huge amount of inserts into the access_log table, which then caused the table (and sometimes other tables) to crash. I ended up migrating to stronger hardware, which made the problem occur less frequently. Then I cleaned up my code to insert only what I really needed and the problem was gone.
I suspect, you will probably see this problem first on the tables that have the fastest growth rate. If so, take a look at which Drupal module inserts into them and find out, if you can optimize your insert strategy. If you can't, you might have to move your MySQL server to a separate machine or upgrade the hardware you are running on.


Fundamental theorem of calculus when the integrand also contains $x$?

Question: I'm struggling with taking the derivative of the function of type $F(x) = \int _0 ^x f(x,t) dt $ with $f(x,t)$ is good: smooth, compactly supported whatsoever. $F: \mathbb R \to \mathbb  R$ and $f: \mathbb R ^2 \to \mathbb R$.
How can I compute $\frac{d }{dx } F(x)$? Any rules or theorems? Any help and references are appreciated.
Comment: I think this question I asked recently has an answer you will find useful: http://math.stackexchange.com/questions/1975516/can-the-fundamental-theorem-of-calculus-be-used-here
Answer: This is known as the Leibniz integral rule.
Note that $F(x+h) - F(x) = \int_0^{x} ( f(x+h,t) - f(x,t)) dt + \int_x^{x+h} f(x+h,t) dt$.
To get an intuition first, replace $f$ by a linear approximation:
\begin{eqnarray}
F(x+h) - F(x) &=& \int_0^{x} {\partial f(x,t) \over \partial x} dt \,h + \int_x^{x+h} ( f(x,t) + {\partial f(x,t) \over \partial x} \,h )dt \\
&=& (\int_0^{x} {\partial f(x,t) \over \partial x} dt  + f(x,t^*))h +\int_x^{x+h} {\partial f(x,t) \over \partial x} dt \, h
\end{eqnarray}
Where $t^* \in [x,x+h]$.
This suggests that $F'(x) = \int_0^{x} {\partial f(x,t) \over \partial x} dt  + f(x,x)$.
If we assume that $f$ and ${\partial f \over \partial x}$ are continuous then
using uniform continuity we establish that this is indeed true.


Oracle - Erro : ORA-24263: Certificate , como tratar?

Question: Envio de https via Oracle
Versão
Oracle Database 12c Standard Edition Release 188.8.131.52.0 - 64bit Production
PL/SQL Release 220.127.116.11.0 - Production
"CORE   220.127.116.11.0  Production"
TNS for Linux: Version 22.214.171.124.0 - Production
NLSRTL Version 126.96.36.199.0 - Production

Obs 1) Wallet Instalado
Obs 2) O problema não seria reproduzível por questões de segurança
Obs 3) Já tentei com o fornecedor
Tento enviar um POST via PLSQL
e recebo o seguinte erro : Erro : ORA-24263: Certificate of the remote server does not match the target address.
Pergunta
Como posso saber o valor de
req := utl_http.begin_request(url, 'POST',https_host =>'???????');
?
é obrigatório ?

create or replace PROCEDURE        "SMS_ENVIO2" (PNUMSMS IN VARCHAR2 ,
                                                 PTEXTO  IN VARCHAR2 ,
                                                 PRETORNO OUT VARCHAR2)
/*alguns dados ocultos*/
AS
  req utl_http.req;
  res utl_http.resp;
  url varchar2(4000) := 'https://messaging.o2c.cloud/api/v2/sms/';--acho que posso citar o site
  name varchar2(4000);
  buffer varchar2(4000);
  content varchar2(4000);
  VS_USUARIO VARCHAR2(11) := '*****';
  VS_SENHA VARCHAR2(20) := '*****';
  VS_SERIAL VARCHAR2(8);--VARCHAR2(100);
  VS_SCHEDULLE VARCHAR2(16) := TO_CHAR(SYSDATE,'DD/MM/YYYY HH24:MI');
  VS_AUTHOR_64 VARCHAR2(20) := '*********';
begin
   UTL_HTTP.SET_WALLET('file:.....', '**********');
   --
   VS_SERIAL := LPAD(SMSENVIO_SERIAL_SEQ.NEXTVAL,8,'0');
   content :=  '   { ' ||
               '     "sendSmsRequest": {' ||
               '     "to": "' || PNUMSMS ||'",' ||
               '     "message": "' || PTEXTO || '",' ||
               '     "id": "' || VS_SERIAL ||
               '    }' ||
               ' } ';
  --
  dbms_output.put_line(url);
  dbms_output.put_line(content);
  --
  --req := utl_http.begin_request(url,'POST');
  req := utl_http.begin_request(url, 'POST',https_host =>'???????');
  utl_http.set_header(req, 'Content-Type', 'application/json');
  utl_http.set_header(req, 'Content-Length', length(content));
  utl_http.set_header(req, 'Authorization', 'Basic ' || utl_encode.base64_encode(VS_AUTHOR_64));
  --
  utl_http.write_text(req, content);
  res := utl_http.get_response(req);
begin
      loop
        utl_http.read_line(res, buffer);
      end loop;
      utl_http.end_response(res);
      exception
      when utl_http.end_of_body then
        utl_http.end_response(res);
      end;
      dbms_output.put_line('retorno ' || buffer);
exception
  when others then
    PRETORNO := 'Erro : ' || UTL_HTTP.GET_DETAILED_SQLERRM;
end;

Answer: Se o certificado não estiver emitido para o endereço que está usando, você coloca no https_hosts o endereco para o qual o certificado foi emitido.
O certificado foi emitido novamente em maio e está igual, deveria funcionar agora sem precisar do https_hosts.
Comment: Acabamos fazendo outra solução , chamamos fora do Oracle. Deveria funcionar mas não funcionava ... , grato pela resposta todavia.
Comment: Resolvemos este problema na versão 19 , wallet habilitado o https funciona.


Area of piece of paper folded around straight line of orientation $\theta$

Question:
Imagine drawing a straight line $l$ through the center of a square piece of paper with area $1$. Now fold the paper along that line.
Q: What is the function for the area covered by the folded piece of paper $A_f(\theta)$, where $\theta$ denotes the orientation of $l$?

This is not a textbook problem, so I don't know how difficult it will be to come up with a solution, but here are my thoughts so far:
The function must have minima when all points of the folded part of the paper are projected on top of all points of the unfolded part, i.e. when $A_f(\theta=0,\frac{\pi}{4},\frac{\pi}{2},\frac{3}{4}\pi,...)=\frac{1}{2}$.
Because of the symmetry, we can restrict our investigation to $\theta \in[0,\frac{\pi}{4}]$.
Here is my strategy:
$1.$ Find the two sets of points, $S_l$ and $S_r$ ("left" and "right" of $l$, respectively), that $l$ divides the square $S$ into, as a function of $\theta$.
$2.$ Reflect $S_l$ around $l$, $S_l \mapsto S_l^*$.
$3.$ Find the area of points that make up the union $S_l^* \cup S_r$.
$1)$ $l=\left(\begin{smallmatrix}x\\y\end{smallmatrix}\right)=t\left( \begin{smallmatrix}1\\ \tan\theta\end{smallmatrix}\right)$
 so $S_l=\{x,y : |x| \leq \frac{1}{2} \wedge y> x\tan\theta \}$ and
$S_r=S \setminus S_l$.
$2)$ I have found the following formula for reflection, $\mathrm{Ref}_l(v) = 2\frac{v\cdot l}{|l|^2}l - v,$ where $v$ is being reflected around $l$. Ideally I would like to replace $v$ with $S_l$, but I've never tried to handle sets this way and don't really know how to proceed from here.
$3)$ Again, I'm not familiar with how this is done (or indeed if it can be done!). It seems to me that there's a long way from the abstract sets to the geometrical figures.

It is very possible that this can be done in a much simpler way; either way, I'd appreciate both alternative methods of solution as well as insights into how my strategy could be executed properly!
Thanks!
Answer: Let $ABCD$ be your square. Let's call $G$ and $H$ the points where $l$ intersects, respectively, the sides $AB$ and $CD$.
We have the two trapezia $GBCH$ and $AGHD$ that both have the same area (half of the original square, so $1/2$).
We now want to reflect $AGDH$ around $l$, let's call $L$ and $K$ the images of $A$ and $B$ after the reflection. The new side $KL$ of the reflected trapezium will intersect $BC$ and $CH$ in one point each ($P$ and $Q$), and $GL$ will intersect $GB$ in one other point ($R$).
The area you need is the area of the half square $+$ the ara of the triangles $RLP$ and $HKQ$.
Now you need just some basic line-line intersections and you are done... if you need I can try to do the calculations, but I'm lazy and it is easy that I do something wrong.
Good luck.
EDIT.
Take it as it is but I think that the total area is: $$
S=\frac{1}{2}+2\tan \theta \left ( \frac{1}{2}-\frac{1}{2}\tan \theta \right )^2
$$
Answer: HINT
You want to reflect lines $ x= \pm 0.5, y= \pm 0,5 $ about $ y = m x , m= \tan \theta .$ Instead of that consider four among the eight rotated lines
$$ \pm x \cos \theta \pm  y \sin \theta = 0.5 ; \, \pm x \sin \theta \pm  y \cos\theta = 0.5  $$


$L^2$ product of Chebyshev polynomials and Legendre polynomials

Question: The following was a problem in a recent numerical analysis exam:

Let $k \in \mathbb{N}\setminus\{0\}$. Prove or disprove:
  $$
\int_{-1}^{1} cos\left(k \operatorname{arccos}(x)\right) \cdot \left(\frac{\partial^{k+1}}{\partial x^{k+1}}(x^2 - 1)^{k+1} \right) dx = 0
$$

Our professor said this was obviously true, since the term on the left is a Chebyshev polynomial and the term on the right is a Legendre polynomial.
I know that Legendre polynomials are orthogonal with respect to the $L^2$ inner product (when $-1 \leq x \leq 1$), but what is the relation here? Is there any reason for using partials in the Legendre polynomials here (besides trying to confuse your students)?
Answer: The Legendre polynomial $P_{k}=C_{k}\frac{d^{k}}{dx^{k}}(x^{2}-1)^{k}$ ($C_k$ is a normalization constant) is orthogonal to all polynomials of lower order with respect to the inner product $(f,g)=\int_{-1}^{1}f(x)g(x)dx$. In fact, the Legendre polynomials can be derived by applying the Graham-Schmidt procedure to $\{ 1,x,x^{2},x^{3},\cdots \}$. So your Professor is correct.
Comment: @jazzinsilhouette : Yes, in short, $P_{k+1}$ is orthogonal to all polynomials of order $k$ or less.
Comment: Thanks. So, since the given Legendre polynomial $P_{k+1}$ is a polynomial of degree $k+1$ and the Chebyshev polynomial $T_k$ is of degree $k$ it can be written as a linear combination of Legendre polynomials (because they span the space of $k+1$-dim. polynomials). However, the $P_i$ are pairwise orthogonal and thus $(T_k, P_{k+1}) = 0$ by bilinearity of the inner product. Am I correct?
Comment: (and especially $P_{k+1}$ is not part of this linear combination...)


ajax call based on the value of 2 input fields to populate jquery autocomplete

Question: I have been stuck with this problem for a while. I would like to pass 2 arguments (the value of 2 input fields of one form) in my ajax call to be used for a jquery autocomplete (the search is based on a mysql query using the values of input1 and input2). I had a few suggestions but so far i have no luck:
here my ajax call trying to pass the 2 arguments input1 and input2. there is no code error showing up but the autocomplete does not work. it is working if i am using only one argument.
function fillbox2(){

$('#input2').autocomplete({
      source: function(request, response ){

          var frmStr={
            input1:$('#input1').val(),
            input2:$('#input2').val()
            requestTerm: request.term
             };

      $.ajax({
      url: './cgi_temp3.cgi',
      dataType: 'json',
      data:{data: frmStr},
      contentType: "application/json; charset=utf-8",

          success: function (data) {
               response ($.map( data.matches, function(item){
                           return {
                              value: item.info2,

                           }
                       }));
              }

          });
      },

          minLength: 2,
          select: function(event, ui){
          $("#prod_term").val(ui.item.value);
          return false;
          }

   });

and here my cgi script that process the MYSQL query
 #!/usr/local/bin/python3

  import cgi, json
  import os
  import mysql.connector

 def main():
   print("Content-Type: application/json\n\n")
   form = cgi.FieldStorage()
   term2 = form.getvalue('input2')

   term1=form.getvalue('input1')

   conn = mysql.connector.connect(user='***', password='***', host='localhost', database='***')
   cursor = conn.cursor()

 qry = """
      SELECT name2, info2
      FROM table2
      join table1 ON
      info2_id=information2_id
      WHERE name2 LIKE %s AND info2_id=%s
"""
cursor.execute(qry, ('%' + term2 + '%',term1))

where could be the problem?
Answer: At first glance I'd say it's possibly a timing issue. The source function isn't going to wait for your ajax call to complete, so you're essentially giving it a blank value. Try initiating the autocomplete inside the ajax success function.
function fillbox2(){
  $.ajax({
    ...
    success: function (data) {
      ...
      $('#input2').autocomplete(...);
  });
}

Comment: thank you for your "out-of-the-box" thinking.  but it is working for one argument. so if it was a timing issue then I should get the same issue that I have with 2 arguments.  i am fairly new to javascript, moving the autocomplete inside  created a lot of formatting issues. ajax is inside source. does that mean that source goes inside ajax as well?
Comment: After looking at the documentation and some other posts, it appears the response parameter is expecting an asynchronous callback. So my next guess would be there's an issue with the data you're sending to response. Try console logging your $.map and make sure it's returning what you expect and that it is formatted correctly.  https://api.jqueryui.com/autocomplete/#option-source  https://stackoverflow.com/questions/5077409/what-does-autocomplete-request-server-response-look-like


Import configuration files in haproxy.cfg

Question: I have almost 200 lines of ACL configurations in haprox.cfg and also contains 150 backends.
To remove this configuration complexity, I want to bundle this configuration in separate files and will import those files in haprox.cfg.
Is this possible in haproxy?
Answer: As far as I know HAproxy does not have anything similar to apache's Include & IncludeOptional directives.
There is no native support for multiple configuration files other than starting HAproxy with repeated -f <config-file> command line switches. see this thread.
You can script something though to merge multiple subsections into a larger file similar to this approach although I would probably go the route and modify the init script to append additional configuration files automatically (untested):
# Load additional configuration snippets from /etc/haproxy.d/*.cfg
OPTIONS=""
for file in /etc/haproxy.d/*.cfg ; do test -f $file && OPTIONS="$OPTIONS -f $file" ; done

start() {
  /usr/sbin/$BASENAME -c -q -f /etc/$BASENAME/$BASENAME.cfg $OPTIONS
  if [ $? -ne 0 ]; then
    echo "Errors found in configuration file, check it with '$BASENAME check'."
    return 1
  fi

  echo -n "Starting $BASENAME: "
  daemon /usr/sbin/$BASENAME -D -f /etc/$BASENAME/$BASENAME.cfg $OPTIONS -p /var/run/$BASENAME.pid
  RETVAL=$?
  echo
  [ $RETVAL -eq 0 ] && touch /var/lock/subsys/$BASENAME
  return $RETVAL
}

Answer: I see the version 1.7.5-2 2017/05/17 has the following help:
       -f <configuration file|dir>
              Specify  configuration  file or directory path. If the argument is a directory the files (and only files) it contains
              are added in lexical order (using LC_COLLATE=C) ; only non hidden files with ".cfg" extension are added.

So in my case editing /etc/default/haproxy so that it contains
CONFIG="/etc/haproxy/"

enables me to put more .cfg files in /etc/haproxy and all is read and configured.
Answer: You can follow this simple step.

Insert one line script (cat /etc/$BASENAME/conf.d/*.cfg > $CFG) in /etc/init.d/haproxy
Here is position where you must insert line
CFG=/etc/$BASENAME/$BASENAME.cfg
 cat /etc/$BASENAME/conf.d/*.cfg > $CFG
 [ -f $CFG ] || exit 1

Reload daemon config with systemctl daemon-reload
Make directory mkdir /etc/haproxy/conf.d
Move default haproxy.cfg to conf.d as global.cfg mv /etc/haproxy/haproxy.cfg /etc/haproxy/conf.d/global.cfg
Create your other .cfg file in conf.d directory
Just restart your haproxy service systemctl restart haproxy
NOTE: /etc/haproxy/haproxy.cfg will be automaticly created from all files in conf.d/


Show the first 4 items in a different format

Question: I have a current view set up that displays a feed of stories and is sorted in descending order. I now need to have the first 4 stories display as a different style then the remaining ones. I have pagination set to 10. I only want the first 4 to show differently on page 1, and then the current style will show on the remaining pages. Is there a way to do this?
Answer: You can use views attachment to have a different styles for the first few item in list. By default, the attachment will be displayed in every pages of list.
If you want to limit the attachment works on the first page only, please implement hook_views_pre_build() in your custom module.
Assuming views name is stories, main display ID is block_1 and attachment display ID is attachment_1.
/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {

    // if 'page' is not defined, we assume it is the first page.
    if (empty($_GET['page'])) {

      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      // Note: get_items_per_page() and get_offset() is not working here.
      $views->set_items_per_page(6);
    }
    else {

      // Remove attachment for other pages.
      $views->is_attachment = TRUE;

      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }

  // We set the item number again because the it seems
  // be overrided by previous call of set_items_per_page().
  if($views->name == 'stories' && $views->current_display == 'attachment_1') {
    $views->set_items_per_page(4);
  }
}

Below is the steps of using views attachment

Add attachment display

In the attachment display, you need to specify how many items you want to have.

Then you need to attach the attachment display to the main display.

Remember to set the  offset in main display for preventing repeating the item in list.
Comment: Thanks for the detail @Jimmy Ko  The only issue I found is that on page 2 I don't want the 4 to be at the top anymore. It's only when people land on page 1. Is this possible.
Comment: Um... I misunderstand your question. If it is a node list, there is a simple solution with [display suite](http://drupal.org/project/ds).
Comment: I will look into that. I haven't worked with Display Suite so was hoping to find a solution with Views. Thanks.
Comment: Please check the updated answer.
Comment: My view name is 'stories', display id is 'block_1' and then the attachment id is 'attachement_1'. When I implement those into the function, and put it into the template.php page, then clear cache, I am not seeing the effects. Do you know what I may have done incorrectly?
Comment: You cannot implement it in template.php. It can only be implemented in custom module.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/42785/discussion-between-jimmy-ko-and-kayzoe).
Comment: You rock @Jimmy Ko. Much appreciated!
Comment: Glad to know that it works :) You are welcome.
Comment: Could you check the chat when you have a moment.
Answer:
In Views, change FORMAT to Show Fields, if you don't have it already.

Add fields, title, body (for formatter you could use Summary or trimmed), post date, comment link, etc...
Add image field twice, one with style x other with style y, if you want the top 4 to have different image style.
In Fields, Add View result counter and start counter at 1.
Create a template for your view fields:
views-view-fields--[view-name]--[machine-name].tpl.php
Example: views-view-fields--hello-world--block-1.tpl.php

In template file you add an if statement to test if counter row is 1, 2, 3, or 4
<?php

if ($fields["counter"]->raw == (1 or 2 or 3 or 4)){

  echo '
' . $fields["title"]->content . '
';
  echo '
' . $fields["body"]->content . '
';
  echo '
' . $fields["field_image"]->content . '
';
  echo '
' . $fields["field_created"]->content . '
';
  echo '
' . $fields["comments_link"]->content . '
';

} else {

  echo '
' . $fields["title"]->content . '
';
  echo '
' . $fields["body"]->content . '
';
  echo '
' . $fields["field_image_1"]->content . '
';
  echo '
' . $fields["field_created"]->content . '
';
  echo '
' . $fields["comments_link"]->content . '
';

}

Place template file in your /sites/all/themes/YOURTHEME/templates folder
Clear/Flush the cache.
Note: Since the view template gets added to your theme, the view preview will not reflect this template because the view preview uses the administration theme. The default admin theme is Seven. You would have to add the template to Seven too, but IMO that's un-necessary.
Go to the page where the view gets displayed to see changes.
Comment: Thank you @NO Sssweat. I have tried this and for some reason all rows after row 4 pick up the last row styling (ie. . Should I be doing something with the counter in addition to above noted? Appreciate your help.
Comment: That's odd, do you have `echo '' . $fields["comments_link"]->content . '';` inside the `else` statement? Did you clear/flush the cache? If yes, maybe try changing the counter to `$fields["counter"]->content`
Comment: Hmmm. Still not working.
Comment: @kayzoe I know, I believe it's the `or`'s as [explained here](http://php.net/manual/en/language.types.boolean.php#allnotes) `This is why you should NEVER use the OR operator without explicit parentheses around the expression where it is being used.` So we can use the other or format `||` or add parenthesies around the `or`'s, updated my answer
Comment: @kayzoe sorry this was my first time using `or`, I normally go with `||` but decided to try `or` here, I wasn't aware of this gotcha. Code should work now.


How to assess drug effects using annual death rate data?

Question: I am planning a study to collect data of patients dying after brain infection versus number of cases for the next 5 years in 2 cities where they manage the disease with different drugs.

Will a year wise t-test be better or year wise Relative Risk of death and meta analysis be better to compare the results of the study?
I am a beginner in statistics. A word of explanation would benefit me.

The data would look like
<code>Year     City 1 Deaths    City 1 cases  City 2 Deaths   City 2 cases
2011     237                1124             10            1226
2012     228                1030             26           1181
2013     1500              6061             10           1122
2014     528                2320             32           1173
2015     645                3024             11           1232
</code>
Comment: I am not sure to figure out what your data look like. Maybe it would be benefit to make it clearer. However, if your variable of interest is of the type "time-to-event", then an analysis that takes time into account is definitely more informative than an analysis that only considers the number of cases. One reason for this is that censoring often occurs in such a study and a "time-to-event analysis" is especially designed for that setting...
Comment: In addtion to @marco 's point, I think what you are looking at is a time-series and the independence assumption for observations of t-test may not hold.
Comment: I meant the data on mortality without any treatment, or with treatment when the same drug was used in both cities. The reason I ask is that with just the current data you cannot distinguish between two possibilities. One possibility is that the drug in city 2 is better, another possibility is that the drug is no better, but something else causes the patients to do better -- maybe weather or overall hospital quality or something else.
Comment: If you can just claim that all other factors are the same, then it's fine to just do a t-test year-by-year or on all 5 years together. This is OK if this is just homework. If this is a real study and real data, then keep in mind that a lot of people will refuse to just believe that all other factors are the same. You will have to convince them somehow. In your previous question you had some pre-intervention data to convince them. Do you have something similar here?
Comment: @DrWho Meta analysis is for combining results from multiple independent studies that have already been performed and published.  This is not such a situation.  (That's why I originally removed the meta-analysis tag from your question, because it will only mislead people who truly are concerned about meta analysis.)
Comment: @whuber: Thank you for making the question better by editing it
Comment: @Marco: Thank you for the thought provoking comment. I have added the expected data. Our variable is survived or dead. We have taken care censoring or missing data problem will not happen. I asked the question because Meta-analysis would have the advantage of pooled Relative Risk, cumulative statistics, one study removed data etc. Kindly comment also on this.
Comment: @suncoolsu: Thank you for the great comment. Since my knowledge of statistics is poor, may be my direction of thinking is inappropriate. The problem with time series is the interference by unknown variables. I asked the question because Meta-analysis would have the advantage of pooled Relative Risk, cumulative statistics, one study removed data etc. Kindly comment also on this.
Comment: Do you have, like in your previous question, the information on mortality before start of treatment?
Comment: @SheldonCooper: Yes. I have an idea how the data would look like partially. I entered those data in the question.
Comment: @SheldonCooper: Thank you for asking for the clarification.The drugs are different. All other known factors are same. The cities are 1000 Kilometers apart.
Comment: @SheldonCooper: I am amazed at your speed of response. Thank you so much. I can get pre-invention data. I will take your advice of doing t-test. Kindly clarify one more thing for my benefit. Why Meta-analysis cannot be used? Meta-analysis would have the advantage of pooled Relative Risk, cumulative statistics, one study removed data etc in addition to relative risk year wise. I have not understood why nobody commented on that. Please be frank and tell me if I am wrong. I want to learn.
Answer: Since your data are categorical, a t test is likely inappropriate for any parameter I can think you might want to do inference on. Here is a brief intro to a very similar problem as yours:
http://walkerbioscience.com/word-files/Categorical%20data.doc
Comment: Thank you very much. I will go though it and get back. i will have to search for the power point file mentioned in that document.
Comment: Thank you very much for the simple but useful reference.


Getting fatal error in drupal when open the site

Question: I am working on a site in which it was perfectly, but now its given this error

Fatal error: require_once(): Failed opening required
  '/var/www/.../includes/sites/all/modules/context/plugins/context_condition_sitewide.inc'
  (include_path='.:') in /var/www/.../includes/bootstrap.inc on line
  3139.

Here we can see the path is changed .../includes/sites/..... where as the "include" and "sites" are on root folder.
So please guide me that how to solve this issue.
Comment: What did you change before the error occured? Did you remove or move files?
Answer: Install Context module using drush en "context".
Your site is not get /context_condition_sitewide.inc file or you may be accidently delete this module without disabling it from module list. Try reinstalling this module again.
Comment: I solve this error, just remove every folders and reupload the files on server...this error cause due to remove or move files.


conexão reversa em C#

Question: Estou tendo dificuldade em usar conexão reversa entre cliente e servidor.
Sempre que eu tento realizar conectar usando Dns ou Ip não conecta, caso eu uso o LocalHost, 127.0.0.1, ele conecta perfeitamente.
Ele ja consegue "resolver" o IP do DNS
Oque preciso fazer para que seja possível conetar ?
private static Socket _clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        public static TcpClient client;
        private const int _PORT = 28562; //  porta

         public static string connectTo = "decodertm.ddns.net";// Não conecta
        // public static string connectTo = "127.0.0.1";// conecta

        public static IPAddress ipaddress = null;

.
 private static void ConnectToServer()
        {

            int attempts = 0;

            bool IsValidIP = IPAddress.TryParse(connectTo, out ipaddress);

            if (IsValidIP == false)
            {

                ipaddress = Dns.GetHostAddresses(connectTo)[0];
                //   Console.WriteLine(Dns.GetHostAddresses(connectTo)[0]);

            }
            client = new TcpClient();

            while (!_clientSocket.Connected)
            {
                try
                {
                    attempts++;
                    Console.WriteLine("Tentativas de conectar " + attempts);
               _clientSocket.Connect("188.8.131.52", _PORT);
                    Thread.Sleep(100);

                }
                catch (SocketException)
                {
                    Console.Clear();
                }
            }
            Console.Clear();
            Console.WriteLine("Conectado !");

            }

Answer: Se em localhost conecta perfeitamente e no dns dinamico não conecta (provavelmente ele está configurado con seu IP), isto é por causa da sua rede!
Se o IP do DDNS for o seu:
Você deve configurar sua rede corretamente, ela deve estar em modo NAT para haver uma conexão. Se não estiver em modo NAT, não vai se conectar!
Não te ensino a fazer isso, pois os roteadores, modens e mais, são diferentes as configurações, olhe o modelo do mesmo e dê uma pesquisada sobre NAT!
Se você está tentando se conectar direto no host:
Tente usar:
var ips = System.Net.Dns.GetHostEntry("microsoft.com").AddressList;
foreach (var ip in ips)
    Console.WriteLine(ip);

Vai retornar um ip ou mais para você para você!
.
Não sei se conseguir te ajudar, mas, espero que sim!

conexão reversa em C#


xslt move node inside sibling node

Question: After a day's research into XSLT, I am admitting defeat!
This is my input:

b1

b1c1

b1d1

b1d2

b2

b2c1

b2d1

b2d2

b2d3

b3

b3c1

b3d1

And this is the output I would like to get:

b1

b1c1

b1d1

b1d2

b2

b2c1

b2d1

b2d2

b2d3

b3

b3c1

b3d1

This is the xslt that I am using:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="@*|node()">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="div[@class='a']">

  <xsl:copy>

   <xsl:copy-of select="@*|node()"/>

   <xsl:apply-templates select="div[@class='c']"/>
   <xsl:apply-templates select="div[@class='d']"/>
  </xsl:copy>
 </xsl:template>

</xsl:stylesheet>

But it's giving me the wrong output:

b1

b1c1

b1d1

b1d2

b2

b2c1

b2d1

b2d2

b2d3

b3

b3c1

b3d1

b1c1

b2c1

b3c1

b1d1

b1d2

b2d1

b2d2

b2d3

b3d1

I understand why it's giving me this output, but I cannot find a way to modify it and get the correct output.
Thank you in advance.
PullingHair
Answer: It looks like you are grouping the "c" and "d" classes by the first preceding "b" class. To do this in XSLT 1.0, you could define a key to capture this grouping.
<xsl:key name="b" match="div[@class!='b']" use="generate-id(preceding-sibling::div[@class='b'][1])" />

So, rather than selecting all child nodes in the template that matches the "a" class, you just select the "b" ones
<xsl:apply-templates select="div[@class='b']" />

Then, in the template that matches the "b" class, you can use the key to get the associated "c" and "d" elements
<xsl:template match="div[@class='b']">
 <xsl:copy>
  <xsl:copy-of select="@*" />
  <xsl:apply-templates select="key('b', generate-id())" />
 </xsl:copy>
</xsl:template>

Try this XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:key name="b" match="div[@class!='b']" use="generate-id(preceding-sibling::div[@class='b'][1])" />

 <xsl:template match="@*|node()">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="div[@class='a']">
  <xsl:copy>
   <xsl:apply-templates select="@*|div[@class='b']" />
  </xsl:copy>
 </xsl:template>

 <xsl:template match="div[@class='b']">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()" />
   <xsl:apply-templates select="key('b', generate-id())" />
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

In XSLT 2.0, you can make use of xsl:for-each-group instead
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="@*|node()">
  <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
 </xsl:template>

 <xsl:template match="div[@class='a']">
  <xsl:copy>
   <xsl:apply-templates select="@*" />
   <xsl:for-each-group select="div" group-starting-with="div[@class='b']">
     <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
      <xsl:apply-templates select="current-group()[position() > 1]" />
     </xsl:copy>
    </xsl:for-each-group>
  </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

Comment: Thank you Tim! It worked perfectly. Thank you for teaching me how to use keys to define grouping. And thank you for teaching me the for-each-group in xslt 2.0. Greatly appreciated.

xslt move node inside sibling node


How does a user subscribe to a group with GCC?

Question: I have the Groups, Communities and Co (GCC) module installed [7.x-1.0-beta2] but I cannot find a way for an authenticated user to subscribe themselves to a group. I have moved the 'GCC Subscription block' so that it's in the sidebar but whatever I do it's still not visible to any user. Has anyone else run into this, probably very simple, issue and found a solution?
Answer:
When you add the GCC Subscription block to the sidebar, It will not show. The only time it shows up is if a user is subscribed to a group. And then the block shows up with the unsubscribe button.

That's not true.
Here are the basic steps to make the subscription block work :

Enable GCC, GCC Context Detection, GCC Node, GCC Block
Go to admin/config/gcc/permissions and make sure NON MEMBER has the "Subscribe" permission
Go to admin/config/gcc/context, check everything and save.
Place the GCC Subscription block where you want.
Create a group.
Go to your group page with another user and you will see the subscription block
Comment: Thanks. Under the Context tab of GCC Configuration I hadn't enabled the following options 'Entity Detectors - Node - Allow to detect node entity' and 'Context Detectors - Group - Determine context by checking if the current entity is a group'. Works now


Parallelise / Threading a big for loop | Python

Question: I have a working Jupyter Notebook that models fake data in the form of a dictionary. Using Faker library and other basic Python.
Reading other posts, parallelism seems to be used on methods. However, I want to apply this technique on the big for loop; as I have many more "key-value lists" applied in the process.
Note: I've appended comments of list slicing included in the process, in case that's needed.
Is it possible to run multiple iterations of a for loop at once? (or as many as possible)
from faker import Faker
faker = Faker()
Faker.seed(1)

import pandas as pd

import random
random.seed(1)

# Key Value lists
biographic_keys = [['Name', 'faker.unique.name()'], ['Aliases', 'faker.unique.user_name()'], ['Date of birth', 'faker.unique.date_of_birth().isoformat()'], ['Phone numbers', 'faker.unique.phone_number()'], ['Addresses', 'faker.unique.address()'], ['Nationality', 'faker.unique.country()'], ['Social Security Number', 'faker.unique.ssn()'], ['Alien File Number', 'random.randrange(1000000, 999999999, random.randint(7, 9))']]
biometric_keys = [['Height', "'{}ft {}inch'.format(random.randint(4, 7), random.randint(0, 11)) if random.randint(0, 1) == 1 else '{}cm'.format(random.randint(100, 200))"], ['Weight', "'{}kg'.format(random.randint(60, 130)) if random.randint(0, 1) == 1 else '{}st {}lb'.format(random.randint(7, 50), random.randint(0, 13))"], ['Eye color', "random.choice(['Amber', 'Blue', 'Brown', 'Gray', 'Green', 'Hazel'])"], ['Hair color', "random.choice(['Brown', 'Blond', 'Black', 'Auburn', 'Red', 'Gray', 'White', 'Bald'])"]]

entries = 4
alien_key_val = []
alien_key_val.append(["Biographic data", biographic_keys])
alien_key_val.append(["Biometric data", biometric_keys])

#print(alien_key_val[0]) # name, subset
#print(alien_key_val[0][0]) # name
#print(alien_key_val[0][1]) # subset
#print(alien_key_val[0][1][0][0]) # key
#print(alien_key_val[0][1][0][1]) # invoke val

# Programmatic key-values
alien_dict = {}

for entry in range(1, entries+1):
    entry_dict = {}
    for i, subset in enumerate(alien_key_val):
        subset_dict = {}
        subset_name = alien_key_val[i][0]
        for data in subset[1]:
            key, invoc = data[0], data[1]
            #if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
            if invoc[-1] != ':': val = eval(invoc)
            else: val = ""
            if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
            subset_dict.update({key: val})
        entry_dict.update({subset_name: subset_dict})
    alien_dict.update({'id_' + str(entry): entry_dict})

print("\nALIEN_DICT:\n", alien_dict)

>>> ALIEN_DICT:
 {'id_1': {'Biographic data': {'Name': 'Ryan Gallagher', 'Aliases': 'david77', 'Date of birth': '1994-03-12', 'Phone numbers': '(317)066-9074x3915', 'Addresses': '806 Tanya Stream\nNew Jeffreymouth, OH 31051', 'Nationality': 'Guatemala', 'Social Security Number': '237-87-3585', 'Alien File Number': 119580763}, 'Biometric data': {'Height': '4ft 7inch', 'Weight': '120kg', 'Eye color': 'Hazel', 'Hair color': 'White'}}, 'id_2': {'Biographic data': {'Name': 'Tiffany House', 'Aliases': 'jmonroe', 'Date of birth': '1992-12-05', 'Phone numbers': '241-586-8344', 'Addresses': '690 Sanchez Union Suite 625\nChristopherhaven, WI 21957', 'Nationality': 'Maldives', 'Social Security Number': '861-51-6071', 'Alien File Number': 177366680}, 'Biometric data': {'Height': '4ft 6inch', 'Weight': '60kg', 'Eye color': 'Hazel', 'Hair color': 'Bald'}}, 'id_3': {'Biographic data': {'Name': 'Allen Williams DDS', 'Aliases': 'kholland', 'Date of birth': '1973-11-13', 'Phone numbers': '038.836.8595', 'Addresses': '890 Bowers View Apt. 883\nHerringfort, MN 75211', 'Nationality': 'Mexico', 'Social Security Number': '205-65-6774', 'Alien File Number': 775747704}, 'Biometric data': {'Height': '175cm', 'Weight': '27st 0lb', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_4': {'Biographic data': {'Name': 'Mr. Gregory Ryan', 'Aliases': 'stephen03', 'Date of birth': '1991-12-27', 'Phone numbers': '(892)184-0110', 'Addresses': '41925 Jones Estate Suite 824\nShawnmouth, NJ 15468', 'Nationality': 'Anguilla', 'Social Security Number': '320-50-5626', 'Alien File Number': 655004368}, 'Biometric data': {'Height': '148cm', 'Weight': '34st 11lb', 'Eye color': 'Amber', 'Hair color': 'Auburn'}}}

Solution appended below. Please add a solution if you believe yours is a better alternative. I'd love to learn other approaches for the future.
Comment: Do you mean that you want to access every element in the loop simultaneously?
How about multi threading ?
Comment: I think you can loop to create thread first. Then, all thread will start running and no longer looping. but I am not sure will it become faster.
Comment: I *think* I do :). Interesting ok, how might I do that? The end goal is to have the process run much faster with maintained stability.
Comment: I have appended a solution below, based on your suggestion. However, how do I add them all together, in order of `id`?
Answer: Inspired by Simple multithread for loop in Python
 top solution.
Using multiprocessing.dummy as mp and converting my for loop grand procedure into a function.
All "entry" dictionaries are collected into list dicts and are added to dictionary big_boi_dict as originally intended.
...

def alien_dict_func(entry):
    # Programmatic key-values
    alien_dict = {}

    entry_dict = {}
    for i, subset in enumerate(alien_key_val):
        subset_dict = {}
        subset_name = alien_key_val[i][0]
        for data in subset[1]:
            key, invoc = data[0], data[1]
            #if ('faker.unique.' in invoc) or ('random.' in invoc) or ('tf.' in invoc) or ("''.join" in invoc) or ("'{}" in invoc): val = eval(invoc)
            if invoc[-1] != ':': val = eval(invoc)
            else: val = ""
            if 'Identification numbers' in key: val = {i[0]: i[1] for i in val}
            subset_dict.update({key: val})
        entry_dict.update({subset_name: subset_dict})
    alien_dict.update({'id_' + str(entry): entry_dict})

    #print("\nALIEN_DICT:\n", alien_dict)
    return alien_dict

import multiprocessing.dummy as mp

if __name__=="__main__":
    p=mp.Pool(4)
    dicts = p.map(alien_dict_func, range(1, entries+1)) # range(0,1000) if you want to replicate your example
    #print("DICTS: ", dicts)
    big_boi_dict = {}
    for d in dicts: big_boi_dict.update(d)
    print("big_boi_dict: ", big_boi_dict)
    p.close()
    p.join()

>>> big_boi_dict:  {'id_1': {'Biographic data': {'Name': 'Jacob Gaines', 'Aliases': 'laurenswanson', 'Date of birth': '2016-04-20', 'Phone numbers': '630-868-7169x899', 'Addresses': '0340 Lydia Passage Suite 898\nAliciaside, NC 54017', 'Nationality': 'Netherlands Antilles', 'Social Security Number': '646-75-5043', 'Alien File Number': 216185864}, 'Biometric data': {'Height': '4ft 3inch', 'Weight': '84kg', 'Eye color': 'Gray', 'Hair color': 'Blond'}}, 'id_2': {'Biographic data': {'Name': 'Carlos Wallace', 'Aliases': 'andreabray', 'Date of birth': '1927-09-11', 'Phone numbers': '069-056-6401x106', 'Addresses': '7567 Timothy Drive Suite 202\nMichealberg, WY 38137', 'Nationality': 'Zambia', 'Social Security Number': '423-34-8418', 'Alien File Number': 472177351}, 'Biometric data': {'Height': '7ft 0inch', 'Weight': '111kg', 'Eye color': 'Amber', 'Hair color': 'Brown'}}, 'id_3': {'Biographic data': {'Name': 'Jason Hill', 'Aliases': 'kimberly73', 'Date of birth': '2002-11-20', 'Phone numbers': '661.123.2301x4271', 'Addresses': '16908 Amanda Key\nLake Taraville, OH 89507', 'Nationality': 'Italy', 'Social Security Number': '855-86-1944', 'Alien File Number': 20427192}, 'Biometric data': {'Height': '125cm', 'Weight': '77kg', 'Eye color': 'Brown', 'Hair color': 'White'}}, 'id_4': {'Biographic data': {'Name': 'Melinda White PhD', 'Aliases': 'hartmanerica', 'Date of birth': '1917-05-19', 'Phone numbers': '(174)876-1971x2693', 'Addresses': '8478 Kristina Road Suite 710\nSaraview, ND 82480', 'Nationality': 'French Southern Territories', 'Social Security Number': '779-13-3745', 'Alien File Number': 501832948}, 'Biometric data': {'Height': '148cm', 'Weight': '128kg', 'Eye color': 'Gray', 'Hair color': 'Auburn'}}}

Answer: For the question of accessing every element in the loop simultaneously. I tried something like that
import time
import threading

class handle_data(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):   # handle_data
      print ("Starting " + self.name)
      print(self.name, 5, self.counter)
      print("Exiting " + self.name)

    def stop(self):
        self.running = False

if __name__ == "__main__":
    for data in range(10):
        handle_data(data,"Thread-"+str(data),data).start()

Comment: @StressedBoi_69420  I just edit the code and delete one of the for loop
Comment: I will try this now


Page cache maximum age

Question: Please  advise me on the correct value to choose for "Page cache maximum age" as a cachin strategy (I'm running a medium Drupal 8.5.3 website).
Comment: What do you mean the correct value? The correct value is whatever one best suits your needs.
Comment: As Kevin said, there's no single, simple correct value for a "medium drupal website." Generally you want to set it to the largest value you can while keeping your content fresh.
Answer: As others have said, there is no "correct value". But if you are really stuck; a fairly simple way to choose is to consider how often content on your site will change, and then divide that by 2.
So if you expect your content to update every 24 hours: 24 / 2 == 12 hours. So set your cache to 12 hours. If you aren't sure how often content will change, set it to a slightly lower value. Is performance is very important, or if your site will be getting a lot of traffic, set a higher value.
You may also want to look at non Drupal caching options such as Cloudflare, varnish cache & memcache. But that's a whole other thing.

Page cache maximum age


Variable's value doesn't change to the new one specified in the actionListener

Question: so I created a variable called savedName and then set the value of this to a new value in the action listener method. It prints the changed value in the action listener but ONLY in the action listener. It seems like once the action listener has taken place, the variable's value is changed back to "null" (the default value). The username_txt is a text field into which the user enters information. But as I stated, the value is only changed temporarily in the action Listener method it seems like and once the action listener has taken place, it changes back to the default value. I have bolded the statements for savedName.
public class LoginWindow extends javax.swing.JFrame {

    /**
     * Creates new form LoginWindow
     */
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    **private String savedName;**
    public LoginWindow() {
        initComponents();
        conn = JavaConnect.ConnecrDb();
    }
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    String user_sql = "select * from Users where Username=? and Password=? ";
    try{
        pst = conn.prepareStatement(user_sql);
        pst.setString(1, username_txt.getText());
        savedName = username_txt.getText();
        System.out.println(savedName);
        pst.setString(2, password_txt.getText());

        rs = pst.executeQuery();
        if(rs.next()){
            JOptionPane.showMessageDialog(null, "Wecome!");
            rs.close();
            pst.close();
            this.dispose();

            UserMainWindow wind = new UserMainWindow();
            wind.setVisible(true);
        }
        else{
            JOptionPane.showMessageDialog(null, "Username and/or Password is not correct");
        }
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null,e);
    }
    finally {
        try{
        rs.close();
        pst.close();
        }
        catch(Exception e){

        }
     }
}

Comment: Your action listener is a private method. Should that be?
Comment: Are you sure your `jButton2ActionPerformed` method has been called?
Comment: That action listener is a login button. I did System.out.println(savedName) in the actionListener and it prints the correct value. I need the savedName variable for another class and whenever I use savedName in the other class, it always uses the default value for savedName. The value is changed temporarily in the actionPerformed method but it is never saved.
Comment: It has to be getting called I am assuming because the user clicks on the login button, which is the actionPerformed method
Comment: If this method should be triggerd in the button click, it should be public and AFAIK you should register this method. Can you please share the code on how you have registered for the event?
Comment: can you post the other code where you have this object created? I am assuming that you are creating a new object everytime rather than calling the previous object... and unless you have encapsulation, savedName should be public if you are going to use it in an another class
Comment: I used a gui editor from netbeans to attach the action event. It automatically created the method name for me and it doesn't let me change the name of the method.
Comment: @Joseph118 which object? savedName? If so, it seems to work in the other class depending on which value it is changed to in this class. For example if I changed the default value of savedName to "test". Then it was getting passed successfully into the other class. Also I tried making it public String savedName and that made no difference either.
Comment: post the entire code inside the action listener as i cannot help you like this.... and yeah you are right! public or private will make no difference.
Answer: Note : I cant comment my thoughts so i just post it as an answer :) comment below for me to update my answer.
After the jButton2ActionPerformed what will happen? it will leave in LoginWindow class and go to another class or not ? if yes then the value of your String savedName will return to null.

Instance variables are declared in a class, but outside a method. They
  are also called member or field variables. When an object is allocated
  in the heap, there is a slot in it for each instance variable value.
  Therefore an instance variable is created when an object is created
  and destroyed when the object is destroyed. Visible in all methods and
  constructors of the defining class, should generally be declared
  private, but may be given greater visibility. click here.

Here is my suggestion .
First :
Create a Class that has a instance variable of public static String savedName = "";
E.g.
package com.sample.classes;
public class SampleClass {
    public static String savedName = "";
}

Then all the class that needed this Variable must extend it like
   public class Sample2 extends SampleClass{

      public void showUserName(){
        System.out.println(SampleClass.savedName);
      }

   }

public class Sample1 extends SampleClass{
    public void pressThisButton (String username){
        SampleClass.savedName = username;
    }

}

public static void main(String [] args){
    Sample1 press = new Sample1();
    // Populate the savedName variable
    press.pressThisButton("My Name is Press");

    // access savedName variable.
    new Sample2().showUserName();

}

in this scenario you can still use the value of savedName even you already left on a certain class.
but im still not sure about this :), just comment if there's a correction TIA
Comment: So what do you suggest I do? The goal is to save the text in the textfield into a variable so I can use it in another class. Basically I am trying to save the username that the user enters into a variable so I can access that username's content from a database in another class
Comment: Thanks for the answer but this suggestion does''t work for me because I am already extending Frame
Answer: You are getting null from the other class is because you are creating a new object rather then passing the value into the other class. This can be done by putting a constructor inside your UserMainWindow class and accepting a String for the name.
If you already have a constructor just accept String as a parameter and create a variable for the string and set it..
example code : (NOTE this is the UserMainWindow class)
private String savedName;
public UserMainWindow(String savedName){
  this.savedName = savedName;
}

now in the class you are creating this object, pass it the string like this: (and this is the class you are creating the userMainWindow class)
UserMainWindow wind = new UserMainWindow(savedName);

Now you should have savedName saved inside your other frame (user main window) while the other frame is discarded.
Comment: Yea that makes sense. But I am having non static variable cannot be referenced from static context error in my public static void main. I understand why its doing this, but is there a way around this?
Comment: In my public static void main (String args) I have UserMainWindow(savedName).setVisible(true). And that is giving me the error because savedName is static
Comment: Actually I got it working. I figure I should be able to change the variable savedName to static in my other class without it affecting other things. And it worked! Thanks so much!!!
Comment: you dont have to put this in your main, use it in the class you have provided here as you already have - UserMainWindow wind = new UserMainWindow(); wind.setVisible(true); inside this class loginWindow. anyway you should have issues with static unless you want to change the value
Comment: Oh yeah that works even better. I just keep forgetting simple solutions and keep trying to implement complex solutions. It works thanks!
Comment: This approach as a whole kinda messes up with the other classes. Some of the methods in UserMainWIndow didn't work properly since I passed a parameter to UserMainWindow.
Comment: give some scenario. :)
Comment: @user3754524 it should work without issues as you are only passing a string into the constructor. Now if you are calling this class using other classes, then that is another issue... you can pass an empty string if that so.
Comment: Well the UserMainWindow has buttons on the frame that serve different functions. For example one button is Hold Book which is supposed to put a book on hold ONLY if the book's availability is yes. But once I passed a parameter to UserMainWindow, the Hold Book button would hold any book, regardless of the book's availability
Comment: Then i don't think its an issue from passing a string... Its probably related to your sql query


Asymptotic elementary expression for the antiderivative of $x^x$

Question: It is well known that there exists no elementary function $f$ with
$$\int x^x\,dx \quad = \quad f$$
Is there an elementary function $g$ such that
$$\int x^x\,dx \quad \tilde{} \quad g$$
in the sense that the quotient of both sides converges to $1$ as the argument goes to infinity? Results like Liouville's theorem do not apply to such expressions as there is no rigid algebraic structure to work with.
(For the purposes of this question, Wikipedia's definition of "elementary function" is used.)
Answer: The answer can be found in the paper : https://fr.scribd.com/doc/34977341/Sophomore-s-Dream-Function
A special function, called "Sophomore's dream" function is defined as :
$$\text{Sphd}(\alpha,x)=\int_0^x t^{\alpha t}dt$$
From the properties of this function, an asymptotic expansion is derived Eq.(6:4). The first term, Eq.(9.2) is :
$$\text{Sphd}(\alpha,x)\sim \frac{x^{\alpha x}}{\alpha\big(1+\ln(x)\big)}$$
So, for $x$ large $$\int x^x dx \sim \frac{x^x}{1+\ln(x)}$$
Comment: This is awesome! (I noticed that you are the author of that paper – how fortunate that you happened to log in just today.)
Comment: The follow-up question would now be whether every elementary function has an *asymptotically* elementary antiderivative. For exponentials, this now appears very plausible. What about, say, $\sin(x)/x$?
Comment: Of course , special functions for the antiderivatives of all elementary functions have not been defined and standardized. $\text{Si}(x)$ is the antiderivative of $\frac{\sin(x)}{x}$ : http://mathworld.wolfram.com/SineIntegral.html . A paper for general public about special functions  is available on Scribd : https://fr.scribd.com/doc/14623310/Safari-on-the-country-of-the-Special-Functions-Safari-au-pays-des-fonctions-speciales
Comment: What I meant is, does the antiderivative of $\sin(x)/x$ have an elementary asymptotic expression like $x^x/(1+\ln(x))$ is for $\int x^x\,dx$?
Comment: The asymptotic expression of Ei(x)=antiderivative of sin(x)/x is common in the handbooks of special functions. On line : http://www.wolframalpha.com/input/?i=Si%28x%29 See the formula "series expansion at $x=\infty$ ".


How to parameterize jenkins DSL job with pipeline script & docker-compose.yaml

Question: I've created a DSL job nv_dsl.groovy as below,
import groovy.text.SimpleTemplateEngine

def fileContents = readFileFromWorkspace "nv_pipeline.groovy"
def fileContents1 = readFileFromWorkspace "docker-compose.yaml"
def engine = new SimpleTemplateEngine()

template = engine.createTemplate(fileContents).make(binding.getVariables()).toString()

template1 = engine.createTemplate(fileContents1).make(binding.getVariables()).toString()

pipelineJob("${DSL_JOB}") {

  definition {
    cps {
        script(template)
    }
  }
}

nv_pipeline.groovy as follows,
pipeline {
  agent any

  environment {
    REPO = repository
  }

  parameters {
    choice name: "ENVIRONMENT", choices: environments
  }

  stages {
    stage('Deploy') {
      steps {
          echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
      }
    }
  }
}

Below is my docker-compose.yml file
version: "3.3"
services:
${SERVICES}:
    restart: always
    container_name: ${CONTAINER_NAME}
    build:
      context: ${CONTEXT}
      args:
        NODE: ${NODE_ENV}
    ports:
        - ${PORTS}
    environment:
      NODE_ENV: ${NODE_ENV}
    volumes:
      - ${VOLUMES}

Here, how can I add my docker-compose.yml file to Jenkins DSL i.e nv_dsl.groovy, so that I can able to pass parameters from Jenkins DSL that apply to the docker-compose.yml file?
While building a pipeline job, I'm getting the error "The CONTAINER_NAME variable is not set. Defaulting to a blank string".
Answer: I've added environment variables in Jenkins script whose variables I need to parameterize to YAML file as below and it worked for me as expected,
pipeline {
  agent any

 environment {
   CONTAINER_NAME = "${CONTAINER_NAME}"
   PORTS = "${PORTS}"
   VOLUMES = "${VOLUMES}"
   NODE_ENV = "${NODE_ENV}"
   IMAGE = "${IMAGE}"
 }

 parameters {
   choice name: "ENVIRONMENT", choices: environments
 }

 stages {
   stage('Deploy') {
     steps {
       echo "Deploying ${env.REPO} to ${params.ENVIRONMENT}..."
     }
   }
 }
}


How does Symfony2 session fixation work?

Question: According to the standard 2.4 documentation, the security.yml config file allows for the following configuration option:
<code>session_fixation_strategy: none | migrate | invalidate
</code>
source: http://symfony.com/doc/current/reference/configuration/security.html
However, I fail to find any details in the official documentation (or elsewhere) on what this option actually does, or how it works in practice.
So, if I set this option to either "migrate" or "invalidate", how will this affect session handling in my system? For example, if I set it to "invalidate", would this mean that a context-local session is invalidated when the user navigates to a different security context?
Answer: In short:

NONE: the session is not changed
MIGRATE: the session id is updated, attributes are kept
INVALIDATE: the session id is updated, attributes are lost

In detail:

None strategy:
Nothing is (supposed to be) done in the default session implementation, thus the session is maintained from one context to the other.
Migrate strategy:
"Migrates the current session to a new session id while maintaining all session attributes."
(The session storage should regenerate the current session.)
"Regenerates id that represents this storage.
This method must invoke session_regenerate_id($destroy) unless this interface is used for a storage object designed for unit or functional testing where a real PHP session would interfere   with testing. Note regenerate+destroy should not clear the session data in memory only delete the session data from persistent storage."
Thus the session is retained from one context to the other.
Invalidate strategy:
"Clears all session attributes and flashes and regenerates the session and deletes the old session from persistence."
Thus the session is regenerated from one context to the other.

It was not revealed by your question what kind of session data you are trying to fetch.
But in any case, no separate session is generated for different security contexts:
http://symfony.com/doc/current/reference/configuration/security.html#firewall-context
Security (authentication) related data is stored under a separate key (based on the firewall name). So for example if you have a firewall with a name 'main', the authentication token will be stored under '_security_main', if you have a firewall (a separate context) with a name 'foo', the user and related token data will be stored under '_security_foo', etc.
So besides ->getToken ->getUser (etc.) the rest of the session variables will be available in different contexts provided you use the 'none' or the 'migrate' session strategies.
Take a look at the session interface for details (quotes are from these files)
vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/SessionInterface.php
And the default implementation:
vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/Session/Session.php
Comment: But _when_ does the migration or invalidation described here occur?  Is it when the user navigates to a different security context?  (And, if so, what does that mean in practice?)
Comment: It occurs "after an interactive authentication attempt was successful and Before the SecurityContext is populated with a Token, and only by classes inheriting from AbstractAuthenticationListener." See `SessionAuthenticationStrategyInterface` for further info.

No, it is not invoked when the user navigates to a different security context. (as I already stated in my reply above.)
Comment: Thanks for taking the time to explain!
Comment: In plain words a simple example 1. session started (no user yet), 2. user navigated to restricted area, 3. redirected to form login, 4. login successful.
Then we already have a session with possible values in it, plus now we have an authenticated user. This is when the session migration takes place and this is when we can decide what to do with the 'previous' session. discard, merge, etc.


The spectra of weighted shifts

Question: Since weighted shifts are like the model-operators in operator theory and people have been studying them for so long, I think there should be quite a large literature on the spectra of such operators. However, after some search I hardly found anyone which gives a complete picture of what the spectra of a weighted shift.
Most of the papers I found deal with some specific properties of their spectra, but the question I have in mind is what the spectra are, exactly.
I wonder whether there is some good reference on this.
Thanks!
Answer: I've found that some good material on this subject can be found in Paul Halmos' A Hilbert Space Problem Book. Chapter 11, entitled Spectral Radius, contains some of the basic results in operator theory along with some specific problems about weighted shifts. In particular, the exercises work through the norm, spectral radius, point spectrum and the approximate point spectrum of a weighted shift. Some other exercises in this section utilize weighted shifts to construct examples and counterexamples to various questions presented.
One nice fact about weighted shifts is that given weights, $a_n,b_n$, if $|a_n|=|b_n|$ for all $n$ (either in $\mathbb{N}$ or $\mathbb{Z}$ depending on whether it is the unilateral or bilateral shift), then the weighted shifts determined by $a_n$ and $b_n$ are unitarily equivalent (This is exercise 89). A direct corollary to this is that the spectrum of a weighted shift is radially symmetric about zero.
The questions contained here don't answer in its entirety the question: "what is the spectrum of a weighted shift." However, they do contain some particularly illuminating facts and examples. A Hilbert Space Problem Book contains exercises, hints, and solutions. I highly recommend it for a better understanding of many aspects of operator theory.
Edit: After doing a little light reading, I came across an article that gives a much more complete picture of the the spectra of weighted shifts. The paper is entitled Approximate Point Spectrum of a Weighted Shift by William C. Ridge. It gives a very explicit breakdown of the parts of the spectra of weighted shifts based on different conditions on their weights. But, for the big picture, the spectrum of a unilateral weighted shift is always a closed disk centered at the origin; the spectrum of a bilateral weighted shift is always connected.
Comment: I'm sorry, I was inherently thinking of unilateral shifts when I posted this. Of course, a bilateral shift with constant nonzero weights is invertible, so the its spectrum cannot be a disk centered at zero. I've edited my post to reflect as much. The result comes from the paper I cited. It should be noted that this paper deals with the case of bilateral weighted shifts as well.
Comment: After reading halmos' book, I can understand that the spectrum of a weighted is centered at the origin and has rotational symmetry around the origin. But why is it always a disk? Could you please explain a little bit?
Answer: For complete description of the spectra of weighted shifts, see either
1: A.L. Shields, Weighted Shift Operators and Analytic Function Theory, in Topics in Operator Theory, Mathematical Surveys, N0 13 (ed. C. Pearcy), pp. 49-128. American Mathematical Society, Providence, Rhode Island 1974
Or
2: http://surface.syr.edu/cgi/viewcontent.cgi?article=1138&context=mat
Or
3: https://www.impan.pl/shop/publication/transaction/download/product/90721

The spectra of weighted shifts


$\int_1^\infty\frac 1{\ln x}dx$

Question: How do I show that $\int_1^\infty\frac 1{\ln x}dx$ diverges? I'm thinking to break up the integral into two parts, say, over $[1,2]$ and $[2,\infty)$, but how do I integrate the integrand?
I'm stumped partly because the author claims part (f) is proved similarly as part (a)/(b). But how can this be!? Part (f) is so much more non-trivial than (a)/(b).
Comment: On the one hand, you have a non-integrable singularity at $1$, on the other, the integrand is larger than $\frac1x$, and the divergence of the latter shows the divergence.
Answer: Hint: For appropiate values of $x$ it holds that $x\ge \log (x)$ and $\dfrac 1{\log (x)}\ge \dfrac 1 x$.
Comment: On the other side, a similar hint: $\frac{1}{\log x}>\frac{1}{x-1}$.
Answer: Notice that
$$\frac{1}{\ln x}\geq\frac{1}{x\ln x}\,\;\forall x\geq1$$
and
$$\int_1^a \frac{1}{x\ln x}dx=\ln(\ln a)\to+\infty$$
so your integral is divergent.
Answer: Apply the Limit Comparison Test for improper integrals to the functions $f(x)=\frac{1}{\log x}$ and
$g(x)=\frac{1}{x}$. Since

by L'Hôpital
\begin{equation*}
\lim_{x\rightarrow \infty }\frac{f(x)}{g(x)}=\lim_{x\rightarrow \infty }
\frac{x}{\log x}=\lim_{x\rightarrow \infty }\frac{1}{1/x}=\infty ,
 \end{equation*}
at the singularity of $f(x)$, i.e. at the lower limit of integration
\begin{equation*}
\lim_{x\rightarrow 1^+ }\frac{f(x)}{g(x)}=\lim_{x\rightarrow 1^+ }
\frac{x}{\log x}=\infty ,
 \end{equation*}
and by (a)
\begin{equation*}
\int_{1}^{\infty }g(x)\, dx=\int_{1}^{\infty }\frac{1}{x}dx
\end{equation*}
diverges, then so does
\begin{equation*}
\int_{1}^{\infty }f(x)\, dx=\int_{1}^{\infty }\frac{1}{\log x}dx.
\end{equation*}
Comment: Thank you so much for the link. I had been looking for a formal statement of the comparison test for improper integrals. Speaking of which, are you merely offering your answer as an alternative to the more straightforward direct comparison test?
Comment: @Ryan This was an alternative to the direct comparison test (DCT), but sometimes it is easier to find the limit than to deal directly with the inequality of the DCT.
Answer: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
With $x = \expo{z}$:
\begin{align}
\int_{1}^{\infty}{\dd x\over \ln\pars{x}}
&=\int_{0}^{\infty}{\expo{z}\,\dd z \over z}\quad\mbox{diverges !!!}
\end{align}
Comment: Nice!! %%%%%%%%%%%%%%%

$\int_1^\infty\frac 1{\ln x}dx$


What is difference between escape sequences and string operator?

Question: What is difference between escape sequences and string operator except for regular expressions?
Below is my test code:
<!DOCTYPE html>

    <title>test</title>

    <?php
    $a = "Im Google";
    $b = "Im Google, too";
    echo "$a
$b";
    ?>

Result:
result
More result:
Two href of the a elements has double quotes
Comment: Concatenating costs more I guess.
Comment: What does the result look like? It's not identical, if you expect that...
Comment: Also `http://www.google.com` will not have quotes the way you're applying on the second option. You can use single quotes and add quotes inside of it, or do the reverse.
Comment: I like how you make that sound like it's just a side detail rather than the actual difference, @Phiter Fernandes.
Comment: Yeah I know the actual difference is huge, I'm just commenting.
Comment: @PhiterFernandes No, It has double quotes like first code.
Comment: @chlusher *1 character more than the other*. Remove the `, too` and you'll see; it's just one character difference.
Comment: @chlusher No, it does not. Don't look at it through your *DOM inspector*, look at the **raw source.** The DOM inspector gives you a reconstructed, normalised representation of the current DOM tree, not your original source.
Comment: @Fred-ii- that's rather inaccurate to say, if the URL was different the results would be differently in action, see my comment on the below answer.
Comment: @deceze You are right.
Comment: @Prix *Poh-tay-toe, poh-tah-toe*. Escaping double quotes renders proper HTML markup. If you were to copy OP's code and gotten rid of the extra `, too`, you'll see there's only 1 character difference than the other, so there's no real "speed" gain, or any gain for that matter really. I always use proper HTML markup in PHP.
Comment: @Fred-ii- you're not paying closer attention to the differences in $a and $b.
Comment: I'm sorry for I didn't know difference of the developer tool and raw source.
Comment: @Fred-ii- [clearly not :) but feel free to disagree](https://eval.in/551214). Keep in mind that we are talking about how the PHP prints it and not whether today's browse are able to understand and render the HTML properly even if printed wrongly.
Comment: @Fred-ii- [Just to further improve my point, here is a JSFiddle example of what I meant as to why your assumption is wrong](https://jsfiddle.net/1g4sa0ds/) see the 3rd link. `If you were to copy OP's code and gotten rid of the extra , too, you'll see there's only 1 character difference than the other, so there's no real "speed" gain, or any gain for that matter really.` so by your logic the 3rd link should have worked but its clearly missing part of it...
Answer: Well, let's look at the result:
$a = "Im Google";

is:
Im Google

while this:
$b = "Im Google, too";

is:
Im Google, too

Apples and oranges.
Both happen to have the same meaning in HTML, since none of the arguments contain spaces. But if they did, you'd have noticed the difference yourself very quickly.
Comment: I just want to know that any difference between two things.
Comment: Not to mention if the URL had a space it would break the URL and perhaps even the html code depending on what the URL was. For example: `$b = "test";` In this case your link would become `http://yoursite.com/some` instead of `http://yoursite.com/some link/`
Comment: @chlusher One escapes a special character, and the other concatenates two strings. I'm at a loss for what you want to hear, to be quite honest.
Answer: The backslash \ is used in "string context" to escape some characters to either have the same character inside the string which the string is encapsulated with, or to insert some special character, like a new-line \n.
There is a difference between "embedded code" and "regular expressions":

the source-code you provided is PHP code embedded in HTML
regular expressions ("regex") implies some logic that can be defined in a string like this: ^[a-zA-Z0-9_]{1,}$ and the "special characters" inside it can also be "escaped" with the backslash, including the backslash itself - (with another backslash) - same as "normal" strings.

You can escape your quotes the way you did - as the first example (a), but that makes your code more complex. You can simply use the double, or single quotes as needed like this:

"Monica's attractive... car"
'Sandy says: "Hi!"'

Remember to use "curly braces" { } when embedding variables inside a double-quoted string context like this:
$foo = 'bar';
echo "I like Cadbury's lunch-{$foo}";

Edit
As pointed out in the comments:
The "curly braces" reference is just good practice as it prevents nasty surprises when using variables directly before some alpha-numeric characters, which if left out you may get an "E_NOTICE" error, or you will have to resort to concatenation.
Comment: Fair enough, but that distinction is important IMO. Don't blindly prescribe it, point out the *why*. Personally I forgo the braces *unless and until they're necessary* for disambiguation.
Comment: On that last point: *why?* :) Curly braces aren't *needed* per se to interpolate values...
Comment: @deceze :: It's good practice as it prevents some characters that interfere with your variable names, like i.e: "{$foo}bells", where `$foo='bar'` so that will be "barbells"; however, if you skip the `{ }` you may get a notice about variable "foobells" being undefined; or you have to split up the string and use concatenation methods.. so, just good practice I guess ;)


I tried to solving this it became 4th power of equation

Question: Kindly see this image and solve it.

I solved this. But it form fourth power of equation. It is a 10th grade math. It seems any other techniq ond logic will apply please solve it. I didn't sleep whole night for this question
Comment: Yes and the solution isn't super nice: https://imgur.com/n1vRVvU
Comment: Please at least show what you've tried. And the solution is never going to be all that nice with sums of square roots.
Comment: I outsourced it to Wolfram Alpha: https://www.wolframalpha.com/input/?i=sqrt%28x%2F%281-x%29%29%2Bsqrt%281-x%29%3D3%2F2
Comment: Can you describe any other method because it a tenth grade math..kindly solve this please..i also found the answer by forthpower of equation
Comment: What is $2\frac12$, please clarify
Answer: I am going to prove that the only real solution of the equation:
$\sqrt\frac{x}{1-x}+\sqrt{1-x}=1$
is $x=0$.
Proof:
It is necessary that $x\in\left[0,1\right[$ in order that the values inside the two square roots are nonnegative.
Squaring both sides of the equation, we obtain:
$\frac{x}{1-x}+1-x+2\sqrt{x}=1$
$\frac{x}{1-x}-x+2\sqrt{x}=0$
$\frac{x-x+x^2}{1-x}+2\sqrt{x}=0$
$\frac{x^2}{1-x}+2\sqrt{x}=0$
But $\frac{x^2}{1-x}\ge0$ and $2\sqrt{x}\ge0$, so there is only a possibility which is:
$\frac{x^2}{1-x}=2\sqrt{x}=0$
Therefore $x=0$.
As a matter of fact $x=0$ is a real solution of the equation and it is actually the only one.
Comment: I think we should interpret $2\frac{1}{2}$ as $2\cdot\frac{1}{2}$ otherwise the solutions are not very nice especially for a tenth grade.
Comment: So you're interpreting $2\frac12$ as $2\times\frac12$?
Comment: You mean the only *real* solution, others are complex, right?
Comment: Is $2\frac{1}{2}$ egual to $\frac{5}{2}$ ?
Comment: @Angelo Oh wait I wrote $3/2$ in WA for some reason but it shouldn't be much nicer with $5/2$
Comment: I think the question is miss printed by publishers.in denomineter there will be sqrt{x} then it will be a tenth grade question


Imprimir mensagem na próxima pagina

Question: Como faço para imprimir uma mensagem ao abrir uma página, por exemplo:
Estou na pagina Cliente/View e ao ser redirecionado para a página Nfe/index, quero que seja impresso uma mensagem com instruções sobre o que deve ser feito, puxando alguns dados da Cliente/View.
Tentei usar o
$this->Session->setFlash('mensagem');

Mas continuei sem resultados, só é exibido a mensagem quando eu volto para a página Cliente/View novamente.
Answer: Para este mesmo caso, a seguinte resposta me ajudou, veja ela abaixo:
Ao usar o setFlash, você poderá fornecer um valor chave, por exemplo:
$this->Session->setFlash('This message is for form 1.', 'default', array(), 'form1');

Então você pode imprimir o flash acima de cada formulário. Ele só será exibido se a chave especificada tiver um valor.
<?php echo $this->Session->flash('form1') ?>

Para mais informações consulte Criando Mensagem de Notificação.
Comment: Cara eu testei aqui e só funciona se ele tiver na mesma `controller`, se a `View` estiver em `controller` diferente, isso não funciona.

Imprimir mensagem na próxima pagina


Point on the bisector and excenter

Question: Given a triangle ABC, $\angle BAC = 20^{\circ}, \angle ACB=30^{\circ}$. M is a point inside the triangle such that $\angle MAC=\angle MCA=10^{\circ}$. L is a point on AC (L is between A and C) such that $AL=AB$. If $AM \cap BC =K$, prove that $K$ is the center of the excircle of $\triangle ABL$. Find $\angle AMB$.
Proving that $K$ is the excenter of $\triangle ABL$ is easy. However, I cannot find $\angle AMB$.
Comment: It's $140^\circ$, but I used trig (law of sines and observations like that triangle $ABL$ is isosceles, etc.) to find it.
Comment: when you write $AM\cap BC=K$, do you mean to say that if you extend the line segment $AM$ to pass through $BC$, it hits point $K$ on $BC$?
Comment: I think yes.That's what the OP meant.
Comment: Yes, $K$ is the intersection point of $AM$ and $BC$. I need a solution without trigonometry.
Comment: I managed to solve it using the law of sines. But I have to solve without it. There must be some way to solve this with additional construction.
Comment: I'm not seeing a non-trigonometric solution at the moment, but the Law of Sines can be derived from considering triangle area, so perhaps looking at areas will give a way around the Law of Sines.
Answer: $\hspace{2cm}$
Since $\overline{AB}=\overline{AL}$, $\triangle ABL$ is isosceles. $\overline{AK}$ bisects $\angle BAL$; therefore, $\overline{BL}\perp\overline{AK}$. Let $J$ be the intersection of $\overline{BL}$ and $\overline{AK}$. Drop perpendicular $\overline{KN}$ to $\overline{AB}$ and perpendicular $\overline{KP}$ to $\overline{AC}$.
$\angle ABC=130^\circ$ and $\angle ABJ=80^\circ$; therefore, $\angle JBK=50^\circ$. Being an external angle of $\triangle ABC$, $\angle NBK=50^\circ$. Therefore, $\triangle BJK=\triangle BNK$. Thus, $\overline{NK}=\overline{JK}$. $\triangle ANK=\triangle APK$; therefore
$$
\overline{PK}=\overline{NK}=\overline{JK}
$$
Thus, $K$ is the center of the excircle to $\triangle ABL$ tangent to $\overline{BL}$.

Being an external angle of $\triangle AMC$, $\angle KMC=20^\circ$. Therefore, $\triangle KMC$ is isosceles, giving $\overline{MK}=\overline{KC}$.
Because $\triangle CKP$ is a $30{-}60{-}90$ triangle, we can place $Q$ so that $\triangle CQP$ is also $30{-}60{-}90$ and $\triangle KQC$ is equilateral. Therefore, $\overline{KQ}=\overline{KC}$. Furthermore, $\overline{KP}=\overline{QP}=\frac12\overline{KQ}$. Thus,
$$
\frac{\overline{JK}}{\overline{MK}}=\frac{\overline{KP}}{\overline{KQ}}=\frac12
$$
Therefore, $\overline{MJ}=\overline{JK}$, and $\triangle MBK$ is isosceles. Since $\angle MBJ=\angle JBK=50^\circ$, we have that $\angle BMJ=40^\circ$, which leaves $\angle AMB=140^\circ$.

Point on the bisector and excenter


How to match optional group at the end of string with regex?

Question: I have the strings like below:
(1) Pay for zone 1234 for 1 hour
(2) Pay for zone 4567
(3) Pay for zone 1234 for 1 hour 30 minutes

and the following regex (https://regex101.com/r/MBWJUq/1):
(\d{4}).*(30 minutes|1 hour(?: 30 minutes)?|(?:[2-9]|1[0-9]|2[0-4]) hour(?: 30 minutes)?)

It works well with cases (1) and (3), but doesn't work with case (2). How should I fix it?
It works with case (2), if I make last group optional. But then it doesn't capture first group with cases (1) and (3).
Comment: Perhaps shorted the pattern to include 1 in the range of `[2-9]` and make the part including `.*` optional https://regex101.com/r/pSJZM1/1 `(\d{4})(?:.*((?:[1-9]|1[0-9]|2[0-4]) hour(?: 30 minutes)?))?`
Comment: Change the order and add an optional non capture group, https://regex101.com/r/MBWJUq/3
Answer: If you want to keep the 2 capturing groups and you want to match a range from 1-24 followed by hour and optionally a space and 30 minutes, you might shorten the pattern to:
(\d{4})(?:.* ((?:[1-9]|1[0-9]|2[0-4]) hour(?: 30 minutes)?))?

In parts

(\d{4}) Capture group 1 Match 4 digits (You might prepend a word boundary \b)
(?: Non capturing group

.*  Match any char 0+ times followed by a space (Or use .*\b)
( Capture group 2

(?:[1-9]|1[0-9]|2[0-4]) hour Match a range 1-24 followed by hour
(?: 30 minutes)? Optionally match 30 minutes

) Close group 2

)? Close on capturing group and make it optional

Regex demo
Answer: I didn't change your pattern a lot because you didn't explain what you want to extract exactly.
When you make second group optional everything will be consumed by .* because it's greedy, so you need to fix this first .*?.
now the second group should be also put in a non capturing group to match either the text ends with something like for 1 hour or end of line \n.
check this:
import re

text = """
(1) Pay for zone 1234 for 1 hour
(2) Pay for zone 4567
(3) Pay for zone 1234 for 1 hour 30 minutes
"""

RE = r'(\d{4}).*?(?:(30 minutes|1 hour(?: 30 minutes)?|(?:[2-9]|1[0-9]|2[0-4]) hour(?: 30 minutes)?)|\n)'
# same thing using compile with flags MULTILINE
# RE = re.compile(r'(\d{4}).*?(?:(30 minutes|1 hour(?: 30 minutes)?|(?:[2-9]|1[0-9]|2[0-4]) hour(?: 30 minutes)?)|$)', flags=re.MULTILINE)

print(re.findall(RE, text))

OUTPUT:
  [('1234', '1 hour'), ('4567', ''), ('1234', '1 hour 30 minutes')]


What is to unwrap a variable?

Question: I have been trying to get my head around the concept of optionals and implicitly unwrapped optional but I just don't get the terminology? My questions are:

What is wrapped in programming? What would a wrapped String be?
What is unwrapping?
What is the difference between an Optional (?) and a implicitly unwrapped functional (!)
When do you use ? or !
What do they mean with implicitly in the term implicitly unwrapped optional?

Is unwrapping just revealing a variable's true value whether it is nil or a value?
Comment: Possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language)
Comment: "You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn't a value at all." See Optionals discussion: https://developer.apple.com/library/prerelease/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330
Comment: This kind of question has a lot of value for beginners in iOS/swift ! Good question
Answer: 1.Wrapped mean that you put the value in a variable, which maybe empty. For example:
let message: String? // message can be nil
message = "Hello World!" // the value "Hello World!" is wrapped inside the message variable.

print(message)  // print the value that is wrapped in message - it can be null.

2.Unwrap means you get the value of the variable to use it.
textField?.text = "Hello World!" // you get the value of text field and set text to "Hello World!" if textField is not nil.
textField!.text = "Hello World!" // force unwrap the value of text field and set text to "Hello World!" if text field is not nil, other wise, the application will crash. (you want to make sure that textField muse exists).

3.Optional: is a variable that can be nil. When you use its value you need to unwrap it explicitly:
let textField: UITextField? // this is optional
textField?.text = "Hello World" // explicitly tells the compiler to unwrap it by putting an "?" here
textField!.text = "Hello World" // explicitly tells the compiler to unwrap it by putting in "!" here.

Implicitly unwrap optional(?) is an optional (value can be nil). But when you use it you don't have to tells the compiler to unwrap it. It will be forced unwrapped implicitly (default)
let textField: UITextField!
textField.text = "Hello World!" // it will forced unwrap the variable and the program will crash if the textField is nil.

4.Try to always use optional(?) in most case if you think the value can be nil. Use implicitly unwrapped optional(!) only when you are 100% sure that the variable can't be nil at the time you use it (but you can't set it in Class constructor).
5.Implicitly means automatically, you don't have to tell the compiler, it will do it automatically, and it's bad because sometime you don't know that you are unwrapping an optional that may cause the program crash. In programming, explicit always better that implicit.
Comment: Really nice explanation thanks. However, why would you ever unwrap your text when it can cause crashes when I can just refer with the wrapped textField, like textField?.text
Comment: For example if you are sure textField is not nil, when you want to get String instead of String?. For example: `let message = textField?.text` -> returns String?. But `let message = textField!.text` -> returns String. Safer way should be `let message = textField?.text ?? ""` or you can use `if let messageText = textField?.text {  }` // would be safer.

What is to unwrap a variable?


jQuery change form action doesn't work for some IE 7 users

Question: I'm having a puzzling issue with Javascript/jQuery and a handful of IE 7 users.  I'm lost since I can't reproduce the issue with any IE 7 installation.  Here's the code:
<code>   $("form").submit(function() {
            $(this).attr("action",$(this).attr("action").replace(/^\/foo/,""));
            $("input[type=submit]", this).attr("value","Please wait...");
            $("input[type=submit]", this).attr("disabled","true");
            return true;
    });
</code>
This removes for /foo from the form action and submit's the form without issue in all modern browsers.  But for some reason with SOME IE 7 users it doesn't update the action and submits it to the original.
I thought it was an issue with loading jQuery from Google, but I've moved it locally and other jQuery code executes from this same file without an issue.
Comment: Have you tried putting IE8 on those IE7 users' machines and running the debugger in compatibility mode? That's generally how I solve IE7 nonsense.
Comment: It's not internal so I can't force them to upgrade. This would probably fix it though since I haven't heard of anyone with IE 8 having the issue.
Answer: Try making the regex case insensitive.  (<code>/^\/foo/i</code>)


Migrate: Create term(s) if they do not yet exist

Question: Question similar to this question here, but this time, I am not doing a separate migration later.
I want to create taxonomy terms if they do not exist while processing a record. Does entity_lookup do this in the same way migration_lookup does for stubbing? In this case, I won't be doing another migration to fill in a stub, but surely there must be a way to create a term and keep going.
I don't see anything in entity_lookups plugin indicating it will create if not found.
Comment: Use `entity_generate`, it is basically lookup + generate if not exists [Doc](https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/list-of-process-plugins-provided-by-migrate-plus)
Answer: Wow, ok, getting better at parsing the docs/code for migrate plus. I found it as soon as I posted. The entity_generate plugin will do this behavior.
  field_paper_jel_codes:
    plugin: entity_generate
    source: jel_codes

Now I have a system full of taxonomy.


Queue sequential UI Jobs and show them in UI

Question: How can I display several sequential Jobs in a single UI ?
My use case is the following one:

User Action
Start first Job (unknown length)
Wait for first Job to finish and start second Job (known length)
Wait for second Job to finish and start third Job (known length)

I want to show this to the user in the following way:

Have a main "User Action" dialog without global progress bar (because of the 1st job unknown and really variable upon executions length I can't get an accurate total length)
In this dialog have 3 sub parts one for each job with one progress bar for each one of this jobs and off course with IProgressMonitor.UNKNOWN style for the first job.
In this dialog the progress bars will be updated sequentially as the underlying jobs.

This will allow the end user to immediately see that its action is spitted into 3 sub-tasks (the sub-tasks are meaningful for end users)  and each time a new sub-task is started he can see the length of this sub-task (unknown of course for the first).
After many searches I was not able to implement that, and today I am reporting these 3 sub-tasks as 3 individual successive dialogs with the drawback that the end user may initially thinks that his action will be completed at the end of the first unknown sub-task.
Answer: Can't you implement your own scheduling rules to control the order of execution of your jobs, and effectively block the second job while the first one is being executed, and the third one while the second one is running?
Look at http://www.eclipse.org/articles/Article-Concurrency/jobs-api.html for details and code snippets.
From the article above:

Any time a scheduling rule is acquired, execution of that thread might be blocked until the rule can be obtained. In situations like these, the user would benefit from seeing a dialog that shows the progress for the running task and provides feedback if the task is blocked by some other task.

While I haven't implemented this myself, I have seen this in Eclipse. When the workbench is saving its state, while a project is still building, for example, Eclipse is reporting progress on the build, while blocking the state persistence job until the build has finished. It displays the jobs as separate entries within the same dialog, and makes it clear that the second job is blocked by the first one.
Comment: Thanks for the answer. I just tried to add scheduling rules between nmy jobs but unfortunately it doesn't show up in the same dialog. If setuser(true) is called on all jobs I have several dialogs and if only called on the first job I have one dialog withh all my jobs but it is closed as soon the first job is finished
Comment: Can't you use the jobs view instead of the individual progress dialogs? You can even implement your own dialog to host the view, if necessary. Take a look at this - http://www.richclient2.de/2006_09_28/using-the-eclipse-jobs-api/ for scheduling the jobs, and this - http://wiki.eclipse.org/FAQ_How_do_I_prevent_two_jobs_from_running_at_the_same_time%3F for the scheduling rules.
Comment: This may help too - http://wiki.eclipse.org/FAQ_How_do_I_switch_from_using_a_Progress_dialog_to_the_Progress_view%3F Sorry, forgot to add it to my comment above.
Answer: Why not just divide one process bar into three parts. The first third for the first job, then the second and the third.
Anyway it's simple! :)