Is there any mathematical theory of optimal stopping in crowd control situation?

Question: In my work in the tourism sector, I am looking for any relevant reference to the following problem statement.
Due to the current outbreak of Coronavirus, many business and leisure events are either being cancelled or an upper limit is being put of on the maximum number of attendants. In some cities, all events whose expected attendants is more than 1,400 people are being cancelled where as in some other cities events with more than 300 people are being called off. I wonder how do the city authorities decide is 1400 is the right cut off or 300 is the right one.
Question: Suppose that an event originally had $N$ expected number of attendants. Is there any mathematical logic/theory similar to the theory of optimal stopping which says what faction of this $N$ expected attendants should be let inside the event venue?
Something that is vaguely similar is the secretary problem which says if there are $N$ candidates who are interviewed in random order than it recommends ignoring the first $37\%$ of the candidates and then selecting next candidate who better than any of the candidates in the first $37\%$.
Answer: If you want to minimize the probability of further infection the answer is cancel the event, i.e. do not let anyone in. It depends on the threshold, e.g. you want to keep the probability of further infection below some p and maximize the ppl. Let's say the prob of attendee to be infected is q and the  probability that he/she infects someone else is r.  Let A denote the event that during the event someone else is infected. For the sake of simplicity assume that r=1. Given the number of attendees is N the distribution of the number of infected is Bin(N,q). The prob that at least someone is infected is $1-(1-q)^N$. To keep this under p we have to solve $1-(1-q)^N < p$ . Hence
$ \log (1-p) < N \log (1-q)$, i.e. $ N< \log(1-p)/\log(1-q)$.
If $r<1$ then the probability of some being sick is $q$ and infecting some else is $rq$. The number of infecting sicks is Bin(N,rq), hence $N< \log(1-p)/\log(1-qr)$.
Comment: Highly dependent on the transmission model too! Here you are assuming that everyone is equally likely to be by an infected individual. However, with most virus transmissions, if the probability also depends on particular type of interaction.


Load Huge Data to ListViewItem using Backgroundworker

Question: Load Huge Data to ListViewItem using Backgroundworker
I'm having trouble loading huge data when I was about to open a form. So what I did is that I implemented a BackgroundWorker component into my form and this is how my code looks like.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
     for (int x = 1; x <= 100; x++)
     {
         loadDataByAll(); //Loads All Data to ListView
         backgroundWorker1.RunWorkerAsync();
         backgroundWorker1.ReportProgress(x);
     }
}

For the Process Change Event Code
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

For the loadDataByAll() Function
private void loadDataByAll()
{
     try
     {
         lviewGuard.Items.Clear();
         con.ConnectionString = dbcon.getConnectionString();
         con.Open();
         String query = "SELECT guardid AS a, g_firstname AS b, g_midname AS c, g_lastname AS d, g_age AS e, g_gender AS f, g_address AS g, g_contactno AS h, g_licno AS i, g_lic_until AS j, g_assigned_client AS k, g_schedule_from AS l, g_schedule_to AS m, app_no AS n";
         query += " FROM guards";
         query += " WHERE resigned = '0' ORDER BY app_no DESC";
         OleDbCommand cmd = new OleDbCommand(query, con);
         cmd.ExecuteScalar();
         OleDbDataReader rdr = cmd.ExecuteReader();
         while (rdr.Read())
         {
             lviewGuard.BeginUpdate();
             ListViewItem lv = new ListViewItem(rdr["a"].ToString());
             lv.SubItems.Add(rdr["b"].ToString());
             lv.SubItems.Add(rdr["c"].ToString());
             lv.SubItems.Add(rdr["d"].ToString());
             lv.SubItems.Add(rdr["e"].ToString());
             lv.SubItems.Add(rdr["f"].ToString());
             lv.SubItems.Add(rdr["g"].ToString());
             lv.SubItems.Add(rdr["h"].ToString());
             lv.SubItems.Add(rdr["i"].ToString());
             lv.SubItems.Add(rdr["j"].ToString());
             lv.SubItems.Add(rdr["k"].ToString());
             lv.SubItems.Add(rdr["l"].ToString());
             lv.SubItems.Add(rdr["m"].ToString());
             lv.SubItems.Add(rdr["n"].ToString());
             lviewGuard.Items.Add(lv);
             lviewGuard.EndUpdate();
          }
          con.Close();
      }
      catch (Exception)
      {
          MessageBox.Show("MDB Database is not Present", "Microsoft Access Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
          Application.ExitThread();
      }
}

And Lastly My Button Implementation
private void btnGo7_Click(object sender, EventArgs e)
{
    for (int x = 1; x <= 100; x++)
    {
         btnGo7.Text = "Running";
         btnGo7.Enabled = false;
    }
    btnGo7.Text = "Go";
    btnGo7.Enabled = true;
    progressBar1.Value = 0;
    tabControl1.Visible = false;
}

Sorry to waste your time reading this code. I'm really a complete noob about this multithreads and backgroundwork stuff.
Comment: So , what's your problem then ?
Comment: @Zey The problem is that when i click the button, i can't Identify if the backgroundworker is working along with loadDataByAll().
Answer: I advice to load the data into a list and put the listview on virtual mode.
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.virtualmode.aspx
It's useless to create a listviewitem for every row. Try to
reduce the rows selected. (nobody is reading 1 mil listviewitems). Setup a listview in virtual mode..
If you'd like to stick on your version:
If loadDataByAll() is running on a thread, don't touch the listview control!
I would do something like this:  (don't nail me on typo's, not tested)
private void loadDataByAll()
{
 try
 {
     // lviewGuard.Items.Clear();
     con.ConnectionString = dbcon.getConnectionString();
     con.Open();
     String query = "SELECT guardid AS a, g_firstname AS b, g_midname AS c, g_lastname AS d, g_age AS e, g_gender AS f, g_address AS g, g_contactno AS h, g_licno AS i, g_lic_until AS j, g_assigned_client AS k, g_schedule_from AS l, g_schedule_to AS m, app_no AS n";
     query += " FROM guards";
     query += " WHERE resigned = '0' ORDER BY app_no DESC";
     OleDbCommand cmd = new OleDbCommand(query, con);
     cmd.ExecuteScalar();
     OleDbDataReader rdr = cmd.ExecuteReader();
     List<obj> data = new List<obj>();
     while (rdr.Read())
     {
         data.Add( new obj
         {
           a = rdr["a"],
           b = rdr["b"]
         });
      }
      con.Close();

      this.Invoke(new Action(delegate { UpdateListview(data); }));

  }
  catch (Exception)
  {
      MessageBox.Show("MDB Database is not Present", "Microsoft Access Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
      Application.ExitThread();
  }

}
public void UpdateListview(List<obj> data)
{
    lviewGuard.BeginUpdate();
    lviewGuard.Items.Clear();
    foreach(obj o in data)
    {
         ListViewItem lv = new ListViewItem(rdr["a"].ToString());
         lv.SubItems.Add(o.b.ToString());
         lv.SubItems.Add(o.c.ToString());

         lviewGuard.Items.Add(lv);
    }

    lviewGuard.EndUpdate();
}


How to prove $f(x^n)$ is divisible by $x^n-1$

Question: The question states that if $f (x)$ is a polynomial such that $x-1|f(x^n)$ prove that $f(x^n)$ is divisible by $x^n-1$
This is how I proceeded since$x-1|f(x^n)$
$f(1)=0$
$\frac {f (x^n)-f(1)}{x^n-1}=g(x)$
since $f(1)=0$
$\frac{f(x^n)}{x^n-1}=g(x)$
 hence $x^n-1|f(x^n)$
I guess my proof is incorrect  can someone please  point out the mistakes and give the correct proof.
Comment: Have you heard about complex numbers and roots of unity?
Comment: What is the underlying field/ring? Or is it irrelevant?
Answer: $x-1|f(x^n)$ $\quad\Rightarrow\quad$ $f(1)=0$ $\quad\Rightarrow\quad$ $x-1|f(x)$ $\quad\Rightarrow\quad$ $x^n-1|f(x^n)$.
Comment: This should be the most straightforward one +1.
Comment: Yes! The only reason I'm not deleting my own answer is because I want to leave that explanation of OP's error.
Answer: José's solution is nice. And I agree with his assessment that an error you made is that you didn't explain why $g(x)$ is a polynomial. To see the error consider the following piece of faulty reasoning:
A False Fact. If $f(1)=0$ then $(x-1)^2\mid f(x)$.
Proof.
Write
$$
\frac{f(x)-f(1)}{(x-1)^2}=g(x).
$$
Because $f(1)=0$ we see that
$$
\frac{f(x)}{(x-1)^2}=g(x).
$$
If your logic were valid, we could conclude that $(x-1)^2\mid f(x)$. But this result is clearly false in general. For example when $f(x)=x^2-1$ we have $f(1)=0$, but $(x-1)^2\nmid (x^2-1)$.

You can also do the following.
Let
$$
f(x)=a_0+a_1x+\cdots+a_mx^m,
$$
where $m$ is the degree of $f$. Then
$$
f(x^n)=a_0+a_1x^n+\cdots+a_mx^{nm}.
$$
We are given that $x-1\mid f(x^n)$. This means that $x=1$ is a zero of $f(x^n)$, or that $0=a_0+a_1+\cdots+a_m.$
But then
$$
\begin{aligned}
f(x^n)&=f(x^n)-f(1)\\
&=a_0(1-1)+a_1(x^n-1)+a_2(x^{2n}-1)+\cdots+a_m(x^{mn}-1).
\end{aligned}
$$
Here all the binomials $x^{kn}-1$, $k=0,1,\ldots,m$, are divisible by $x^n-1$. Hence so is $f(x^n)$.
Comment: Thank you for that  explanation, earlier I was not able to understand why my assumption  was incorrect
Answer: Your proof is wrong because you did not prove that $g(x)$ is a polynomial.
Let $z\in\mathbb C$ be such that $z^n=1$. Then $f(z^n)=f(1)=0$. So, $z$ is a root of $f(x^n)$. Therefore, $f(x^n)$ is a multiple of$$(x-z_1)(x-z_2)\ldots(x-z_n),\tag{1}$$where $z_1,\ldots,z_n$ are the $n^\text{th}$ roots of unity. But $(1)=(x^n-1)$.
Comment: Why do you assume that the polynomial is over $\mathbb{C}$?
Comment: @freakish I didn't. I only assumed that it was a polynomial over a subfield of $\mathbb C$. Otherwise, replace $\mathbb C$ with an algebraic closure of the field you are working with.
Comment: **If** we go there you also have the problem that some $z_i$s may be equal. Say, if the underlying field has characteristic two, then $x^8-1=(x-1)^8$ et cetera. So technically this works when the zeros of $z^n-1$ are simple.
Comment: @JyrkiLahtonen Yes, you are right.
Answer: Assume the polynomial of degree $m$ has the roots $x_1,x_2,...,x_m$:
$$f(x)=a_0x^m+a_1x^{m-1}+\cdots +a_m=a_0(x-x_1)(x-x_2)\cdots (x-x_m).$$
Then:
$$f(x^n)=a_0(x^n-x_1)(x^n-x_2)\cdots (x^n-x_m).$$
Since $f(1)=f(1^n)$, then $x-1|f(x^n) \Rightarrow x-1|f(x)$. It implies that at least one root of $f(x)$ is $1$, hence $f(x^n)$ will have a factor $(x^n-1)$.


Filling the field with certain criteria before save

Question: I had a case like this.
A Document content type with Taxonomy Term like this
Title
Category :

CAT A
CAT B
CAT C

Doc Number
When user selects CAT A, then do some query to find last number of node with CAT A. If there is no data found then it will give a starting number, if there is data found it will increment last number of node CAT A.
Every category will have its own number format and reset yearly.
This number will be stored in the Doc Number Field.
Whether there is a good idea for this case? I know PHP a little, but what makes me confused is how to know which category is selected before I save this node.
Update
Obstacles that I faced was to make automatic numbering based on the selected category.
Each category has its own number and reset every year. After some reading on Drupal I made my custom module like this.
function custom_node_presave($node) {
//    dsm($node);
//    $test = $node->changed;
//    $term = taxonomy_term_load($tid); // find term
//    $name = $term->name; // get term name
  if ($node->type == 'dokumen') { // if type = dokumen
    if (empty($node->nid)) { // if no nid then this is new
      $tid = $node->field_jenis_peraturan['und'][0]['tid']; // taxonomy id
      // do query to find last number
      $result = db_query_range(
        'select
           n.nid,
           n.type,
           n.title,
           nomor.field_nomor_dokumen_value,
           tahun.field_tahun_value,
           tin.tid,
           term.name
         from node n
         left join field_data_field_nomor_dokumen nomor
           on n.nid = nomor.entity_id
         left join taxonomy_index tin
           on n.nid = tin.nid
         left join taxonomy_term_data term
           on tin.tid = term.tid
         left join field_data_field_tahun tahun
           on n.nid = tahun.entity_id
         where tin.tid = :tid',
       array(':tid' => $tid));

      if (!$result) { // if empty no data found
        $node->field_nomor_dokumen['und'][0]['value'] = 1; // set starting number
        $node->field_tahun['und'][0]['value'] = date("Y"); // set this year
      }
      else {
      // if data found then set data to var $no & $tahun
        foreach ($result as $item) {
          $no = $item->nomor.field_nomor_dokumen_value;
          $tahun = $item->tahun.field_tahun_value;
        }

        $ynow = date("Y"); // get current year

        if ($tahun < $ynow) { // if year in last data < current year
          $node->field_nomor_dokumen['und'][0]['value'] = '1'; // set starting number
          $node->field_tahun['und'][0]['value'] = date("Y"); // set year = current year
        }
        else {
          ++$no; // last number increment by 1
          $node->field_nomor_dokumen['und'][0]['value'] = $no;
          $node->field_tahun['und'][0]['value'] = date("Y"); // set year = current year
        }
      }
    }
  }

I hope I've explained well.
Comment: Welcome to Drupal Answers! This question is also too broad. Then, this site is not for giving _good ideas_, but to answer questions that are not subjective. Since you are asking about code you wrote, we need to see that code.
Comment: thanks for reply, I 've update my issue and show my code
Answer: To do this thing, you have to implement hook_form_alter, and #ajax for the drop down, after that create callback function for the same. In that AJAX callback you can query the database, and produce desired results.
Format is given below:
'#ajax' => array(
  'callback' => 'ajax_example_autocheckboxes_callback',
  'wrapper' => 'checkboxes-div',
  'method' => 'replace',
  'effect' => 'fade',
),


Can I Create a Zabbix Item which Tracks the CKSUM of a File with a Slightly Varying Filename?

Question: Using Zabbix v2.4 on RHEL 6.4
Goal
I'd like to track the checksum of a file across multiple systems where the directory doesn't change, but the filename has very slight variations in it.  In our case, the filename contains a build number for the software, and we have multiple sites at different versions.  (Hence the difference in names.)
Question and Catches
Can I create a single template item which accounts for these varying file names using the built-in Regular Expressions support?

Can't modify the filenames to remove the build number.
Don't have a lot of control over the agent configurations, so adding UserParameters would be a considerable effort.

Example file names:

1234_file.jar
1254_file.jar

What I've Tried
Zabbix has built-in regular expression support, but I haven't been able to find a good example of its use in item keys.  The Regular Expression page says

In those cases where that may lead to misinterpretation when
  referencing (for example, a comma in the parameter of an item
  key) the whole reference may be put in quotes like this

which implies that they can be used in keys, but, perhaps, not the way I'd like to use them.
I defined a custom RE as "FileName" with the proper logical expressions to match my filenames (tests checked out just fine), and my key is as follows:
vfs.file.cksum[/path/to/file/@FileName]

But when I review the Agent logs, it says "check 'vfs.file.cksum[/path/to/file/@FileName]' is not supported" with "no such file or directory," so it doesn't look like the key is expanding/matching which means I probably misunderstood how to use custom RE's in keys (or they only work in certain key types).
Answer: According to item documentation, vfs.file.cksum[] accepts a file name as the first parameter (unlike, for instance, logrt[] item), so a regular expression will not work there.
One possible approach would be to use a user macro here and define the item as follows:
vfs.file.cksum[/path/to/file/12{$VERSION}4_file.jar]

Then define the appropriate {$VERSION} macro for each host.
Alternatively, you can use low-level discovery to discover the files you want, but that would involve writing a UserParameter, which you would rather avoid. Meanwhile, there is a feature request for a built-in file discovery at ZBXNEXT-712 that you can vote on.


Proof of Multivariable Implicit Differentiation Formula

Question: If the equation $F(x,y,z)=0$ defines $z$ implicitly as a differentiable function of x and y, then by taking a partial derivative with respect to one of the independent variables (in this case x), you get
$\large F_x(x,y,z)\frac{\partial x}{\partial x}+F_y(x,y,z)\frac{\partial y}{\partial x}+F_z(x,y,z)\frac{\partial z}{\partial x}=0.$
Because dx/dx = 1 and dy/dx = 0, you can solve for the desired partial derivative:
$\large \frac{\partial z}{\partial x}=-\frac{F_x(x,y,z)}{F_z(x,y,z)} $
The bolded dy/dx = 0 is what I don't get. I mean, it makes sense that an independent variable doesn't change in response to another, but it doesn't seem very formal and I feel like there's more to it than that. So basically, is there a more formal or detailed explanation or is that all there is to it?
Comment: In the described context we have $z=z(x,y)$. So you are taking partially differentiating the (2-variable!!) identity
$$F(x,y,z(x,y))=0.$$ Does that make it clear what happens? The good ole chain rule in action. Implicit function theorem gives other results too. If you had two equations $F(x,y,z)=0=G(x,y,z)$, then you would think $y=y(x)$, $z=z(x)$, differentiate both equations w.r.t. $x$ and solve for $dy/dx$ and $dz/dx$.
Comment: @JyrkiLahtonen: Since you gave the answer in a comment the OP could not accept it. As a consequence this question will be bumped back to the main board every month or so for years to come.
Comment: I asked my calculus teacher the exact same question and he said that because both x and y are independent variables, dy/dx therefore has no relationship and is 0.
Answer: Going from $F(x,y,z)=0$ to $$F_x(x,y,z)\frac{\partial x}{\partial x}+F_y(x,y,z)\frac{\partial y}{\partial x}+F_y(x,y,z)\frac{\partial z}{\partial x}=0\tag{A}$$
is a formal manipulation, we are just applying $\frac{\partial}{\partial x}$ to both sides of $F(x,y,z)=0$. Then we are assuming that $z$, at least locally, can be written as a (smooth) function of $x$ and $y$. If we wish to consider $\frac{\partial z}{\partial x}$, we may recall what a partial/directional derivative stands for: the rate of change of a smooth function along a direction. In particular $\frac{\partial z}{\partial x}$ accounts for what happens to $z=z(x,y)$ when we move from $(x,y)$ to $(x+\varepsilon,y)$. What happens to $y$ during this travel? Absolutely nothing, it does not change. So by assuming $z=z(x,y)$ and recalling the geometric meaning of $\frac{\partial}{\partial x}$ we get that $(A)$ implies
$$ F_x(x,y,z)+F_z(x,y,z)\frac{\partial z}{\partial x}=0 \tag{B} $$
as wanted. Remark: we would have got $(B)$ also by assuming that $F$ is locally linear, and not by chance. Indeed, the differentiable functions are the functions which are well-approximated by their tangent plane at any point.


Parameterized curve describing trajectory of thrown object

Question:
We describe the trajectory of a thrown object (neglecting friction and similiar effects) with the curve
$$k(t) = \left(v_0\cos(\beta)t,\,v_0\sin(\beta)t-\frac{g}{2}t^2\right)$$
with $t\geq 0$. $v_0>0$ is the initial velocity, $\beta\in[0,2\pi]$ the initial angle and $g$ the constant of gravitation. Compute
$$s(t) = \int_0^t \|k'(u)\|\,\mathrm du.$$

I do fail with simple transformations. First the derivative is very simple $$k'(t) = (v_0\cos(\beta),\,v_0\sin(\beta)-gt)$$ and then I wanted to compute the length so my first steps were $$\begin{align}\|k'(t)\| &= \sqrt{v_0^2\cos^2(\beta)+v_0^2\sin^2(\beta)-2gtv_0\sin(\beta)+g^2t^2}\\ &= \sqrt{v_0^2-2gtv_0\sin(\beta)+g^2t^2}\end{align}$$ where I factorized $v_0$ and got $\sin^2(\beta)+\cos^2(\beta)=1$. However this still seems very difficult to integrate, so I am looking for better simplifications or good techniques on how to integrate this properly.
Comment: Try completing the square so that you get something of the form $\sqrt{(a+t)^2+b}$, and then use substitution.
Answer: Hint: Use the method called "completing the square". In your case
$$\tag{1} v_0^2-2guv_0\sin\beta+g^2u^2= \left(gu-v_0 \sin \beta \right)^2+v_0^2 \cos ^2\beta
   . $$
This suggests the substitution $$y= g u-v_0 \sin \beta .$$
Spoiler below:

 We need to calculate $$s(t) = \int_0^t \|k'(u)\|\, du.$$
 Using (1) for the expression  $ \|k'(u)\|$ and performing the above-mentioned substitution yields

 $$\begin{align}s(t) &= \int_0^t \sqrt{v_0^2-2guv_0\sin\beta+g^2u^2}\, du \\ &= \int_0^t \sqrt{\left(gu-v_0 \sin \beta \right)^2+v_0^2 \cos ^2\beta\, }du\\&=\int_{- v_0 \sin\beta}^{gt- v_0 \sin\beta} \sqrt{y^2 + v_0^2 \cos ^2\beta}.\end{align} $$
 The last integral is usually solved via the substitution $y= v_0\cos\beta \sinh x$. We obtain
 $$\begin{align}s(t) &= v_0|\cos \beta|\int_{-\mathop{\rm asinh} \tan \beta}^{\mathop{\rm asinh} (g t/(v_0 \cos \beta)- \tan \beta)} \overbrace{\cosh^2 x}^{(1+\cosh 2x)/2}\,dx\\&= v_0|\cos \beta| \left(\frac{1}{2} x+ \frac{1}{4}\sinh(2x)  \right)\Bigg|_{x=-\mathop{\rm asinh} \tan \beta}^{\mathop{\rm asinh} (g t/(v_0 \cos \beta)- \tan \beta)}\end{align}$$
Comment: Actually I never saw this method, but I think that this yields $\int \|k'(u)\|\,\mathrm du=\frac{1}{2}g\left(u-\frac{v_0\sin(\beta)}{g}\right)^2+v_0\cos(\beta)u+\text{constant}$. Did I understand this substitution right?
Comment: @ChristianIvicevic: no, not exactly. See the edit of my answer...
Comment: I don't know whether this is correct, but we never did such complicated computations in class. I tried to solve this problem now by not factorizing so that I have $\sqrt{v_0^2\cos^2\beta+(v_0\sin\beta-gt)^2}$ and simplify that with other (much easier) approaches. Do you have some other suggestions?
Answer: You're trying to calculate the arclength of a parabola. This isn't easy, but it can be done.
See http://en.wikipedia.org/wiki/Parabola#Length_of_an_arc_of_a_parabola


std::ofstream does not accept const char * for << operator

Question: I've upgraded my C++ project from VS 2010 to 2015 and have some problems compiling it. Method header looks like following:
void CCodeGenerator::GenerateCode(const MachineExArray & AMachineExArray,
    const MachineArrays & AMachineArrays,
    std::ofstream & HeaderFile,
    std::ofstream & SourceFile)

There's a line:
std::string HeaderDefine = path(OutputFilename).filename().generic_string();

for (std::string::iterator Iter = HeaderDefine.begin(); Iter != HeaderDefine.end(); Iter++)
    *Iter = toupper((unsigned char)*Iter);

HeaderDefine = "__" + HeaderDefine + "_H__";

HeaderFile << "#ifndef " << HeaderDefine << "\n"; // <-- This one

Compiler stops here and says:

No operator "<<" matches these operands. Operand types are:
  std::ofstream << const char[9]

I wrote in C++ long ago, but from what I remember, std::ofstream is quite liberal and should accept most of simple types as input. Where's the problem?

When, at the beginning I write HeaderFile., It is immediately marked as error (red underline) and comment says, "Incomplete types are not allowed".
Comment: What is a `HeaderDefine`?
Comment: make sure you have got `#include `
Comment: See if you can make a MCVE that gives the same error
Comment: It *has* to be a missing `#include` then surely?
Comment: Maybe clean and rebuild your project;, the symptoms are consistent with `ostream` not being included so perhaps something has gone wrong with the precompiled headers or something like that. Try having the include actually in the .cpp file, in case there is a circular dependency in headers
Comment: @Bathsheba, found it. In this single file I'm including ``, which seem to have changed (because some `path` methods, like `file_string()` doesn't work anymore). It must have had included ``, so the code worked. I had only to add this one and file compiles. Thanks!
Comment: While you're at it, double-underscores are forbidden in all code that is not part of the standard library implementation, so you probably shouldn't generate them.
Comment: HeaderDefine is std::string.
Comment: Humour me for a moment and replace `HeaderDefine` with `HeaderDefine.c_str()`, then see if the compile error changes to something clearer.
Comment: @Bathsheba, nothing happened, the same error. I've got like 500 lines like this later, each one with exactly the same error.
Comment: @M.M I've got `#include ` in header file. Adding `#include ` didn't change anything, unfortunately.
Answer: An observation on the

"Incomplete types are not allowed"

. error.
#include <ostream>

int main()
{
    std::ofstream HeaderFile;
}

gives this error too, while this
#include <fstream>

int main()
{
    std::ofstream HeaderFile;
}

compiles in VS2015.


Login facebook abrindo sozinho em aplicação android

Question: Estou criando uma aplicação android que faz login com facebook. Isto já está funcionando, mas está acontecendo algo que não estou conseguindo resolver.
Segundo os exemplos da própria documentação do facebook, o código que faz as chamadas pra api do facebook fica dentro do método onCreate(), e isso faz com que assim que eu abra a página de login (que tem o botão de login com facebook) ele já abre automaticamente o facebook pra pedir as permissões mesmo sem eu ter clicado no botão de fazer login com facebook.
O que eu faço para que ele só abra a tela de login quando eu clicar no botão de "Log in with Facebook"?
Seguem os códigos:
LoginActivity.java
public class LoginActivity extends Activity {

CallbackManager callbackManager;
LoginButton loginButton;
LoginManager loginManager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    Log.d("Teste", "onCreate inicio");

    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    loginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
    LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            // App code
            Log.d("Teste", "onSuccess inicio [Token = " + loginResult.getAccessToken() + "], [Permissões = " + loginResult.getRecentlyGrantedPermissions() +
                    "], [Negações = " + loginResult.getRecentlyDeniedPermissions() + "] Json: "+ loginResult.toString());
        }

        @Override
        public void onCancel() {
            // App code
            Log.d("Teste", "onCancel inicio");
        }

        @Override
        public void onError(FacebookException exception) {
            // App code
            Log.d("Teste", "onError( " + exception.toString() + ")");
        }
    });

}

activity_login.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F76B03"
android:scrollbars="none"
android:gravity="center">

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="match_parent"
    android:layout_height="35dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginLeft="25dp"
    android:layout_marginRight="25dp"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="10dp"
    android:layout_marginTop="5dp"
    android:layout_gravity="center_horizontal"
    android:text="ou"
    android:textColor="#000000" />

<EditText style="@style/tvFullParent"
    android:id="@+id/etLogin"
    android:background="@drawable/shapeedittext"
    android:inputType="textEmailAddress"
    android:drawableLeft="@drawable/ic_action_user"
    android:hint="E-mail"/>

<EditText style="@style/tvFullParent"
    android:id="@+id/etPassword"
    android:background="@drawable/shapeedittext"
    android:inputType="textPassword"
    android:drawableLeft="@drawable/ic_action_lock_closed"
    android:hint="Senha"/>

<Button
    android:id="@+id/btnLogin"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="22dp"
    android:layout_marginRight="22dp"
    android:text="@string/btnLogin"/>

androidmanifest.xml

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id" />

    <activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".LoginActivity"
        android:label="@string/title_activity_login"
        android:screenOrientation="portrait">
    </activity>
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@android:style/Theme.Translucent.NoTitleBar"
        android:label="@string/app_name" />
    </application>

Answer: Pelo que eu entendi da documentação, no onCreate você cria e realiza todos os registros, assim como você já fez, mas o método logInWithReadPermissions é a chamada para a ação que realiza de fato a autenticação, porém, somente quando você não utiliza o LoginButton e sim algum botão customizado, assim você coloca este método no OnClickListener.
É o que diz neste trecho, logo antes da indicação deste método:

Then you can later perform the actual login, such as in a custom
  button's OnClickListener:

Como não é o seu caso, já que você está utilizando o LoginButton, você pode eliminar esta linha e deixar que o próprio botão execute o seu método de autenticação ao ser pressionado.


Ok to use 0 and 1 for a varaible in a linear regression?

Question: Ok this is a simple quesion that's been bugging me. The question is how to encode a linear model variable with only two possible values and avoid any trouble introduced by using zero.
Say you have a linear model:
outcomeVariable ~ DayOrNight

How should you properly encode DayOrNight? There are only two choices and they're unordered. You could say DayOrNight is categorical independent variable.
Now, is it bad to fill the variable with entries of 0 or 1 as integers? It feels like an entry of zero would mean that term will always contribute zero to the outcomeVariable, no matter the beta coefficient. So will Beta only be meaningful when DayorNight=1?
If you choose -1 vs 1, or 1 vs 2, then your fit parameters and pvalues change. That troubles me.
If you force that variable to be categorical in statsmodels or R, it's just like using 0 or 1. So maybe I'm paranoid and people have thought about this before and it's ok.
Comment: There are other ways to encode: -1/1, for example. If there are more than two categories, the number of coding schemes proliferate. If you have multiple categorical variables on the right hand side of the model, and you are including interaction terms with them, you will likely want to stick to effect coding to avoid inducing artificial heteroscedasticity.
Comment: Translation: effect coding = -1/1,  dummy coding = 0/1. http://methodology.psu.edu/node/266
Comment: That's effect coding for a single binary variable. Effect coding is a bit more complicated for more than two categories. See Glantz, S. A. and Slinker, B. (2000). *Primer of Applied Regression and Analysis of Variance*, chapter 8: Two-Way Analysis of Variance, pages 339–417. McGraw-Hill Medical, New York, NY, 2nd edition for a discussion of the issues arising when interacting with categorical predictors.
Answer: Not only is it okay to code it as 0/1, it's common to do so.

It feels like an entry of zero would mean that term will always contribute zero to the outcomeVariable, no matter the beta coefficient.

Correct. This is not a problem. The intercept has the mean for the 0 category, and the coefficient for the 0/1 variable has the difference in means between the two categories.

So will Beta only be meaningful when DayorNight=1? If you choose -1 vs 1, or 1 vs 2, then your fit parameters and pvalues change. That troubles me.

The p-value for this variable shouldn't change from such recoding. The estimated coefficient will change, of course, and the coefficient (and p-value) for the intercept will change, because such recoding changes the meaning of the intercept.

If you force that variable to be categorical in statsmodels or R, it's just like using 0 or 1.

It doesn't matter whether it's numeric or a factor. In R, if you use a two level factor (Say with levels Day and Night), it simply creates a 0/1 variable itself. You can see this by calling model.matrix on the RHS of your model formula.
Comment: You didn't mention *anything* about interaction in your question. The only model you mention in your question is: `outcomeVariable ~ DayOrNight`. My answer relates to that model, not to the infinity of models you didn't mention. (I'm not a mind-reader!)
Comment: I'm seeing the pvalue for one term change in an interaction model.
Comment: outcomeVariable=DayNight+eastWest+DayNight*eastWest. DayNight and DayNight*eastWest are staying consistent, but eastWest changes when I use -1/1 or 1/2 or 0.25/0.75.
Comment: Yes. Thank you. In a simple interaction model, does it make sense that one of the interacting terms might be changing while the other term and the interaction term are fixed relative to recoding?
Comment: Interaction terms should change yes.


Passar código base64 para outra página

Question: Já testei passar como get só que o código possui barra e da erro, preciso apenas passar o código base64 de uma pagina para outra página.
Obs** Este codigo base64 esta sendo gerado na página A com crop. E tenho que passar para a página B para outro tratamento.
Alguem teria alguma sugestão de como eu poderia fazer isso utilizando javascript/jquery
Answer: Acredito que tu podes utilizar a sessionStorage. Uma vez que tu estás trabalhando no lado do cliente e alguns cenários têm devem ser considerados.
http://www.w3schools.com/html/html5_webstorage.asp
É simples a utilização da sessionStorage tanto para jquery quando javascript!
Comment: Cara se eu te contar que no momento que você enviou seu resposta eu estava lendo sobre a session do html5 kkk

Mais é isso mesmo, vou ter que utilizar ele mesmo... Obrigadão pela Ajuda...

Passar código base64 para outra página


Formataçao PYTHON

Question: podem me dar uma dica de como imprimir o seguinte problema da maneira correta?
while True:
    m = int(input())
    mlen = m
    sm = 1
    aux = 1
    matriz = []

    if m == 0:
        print()
        break

    for i in range(m):
        linha = []
        for j in range(m):
            linha.append(sm)
        matriz.append(linha)

    while m - 2 > 0:
        for i in range(aux, m - 1):
            for j in range(aux, m - 1):
                matriz[i][j] = sm + 1
        sm += 1
        aux += 1
        m -= 1
    for i in matriz:
        for j in i:
            print('{:4}'.format(j), end='')
        print('')

Preciso que a matriz impressa tenha 2 espaços do lado esquerdo, 3 espaços entre os valores e nenhum espaço no final de cada linha. É um exercício do URI Online Judge - 1435.
    Accepted Output             Your Output
1   ··1···1···1···1         1   ···1···1···1···1
2   ··1···2···2···1         2   ···1···2···2···1
3   ··1···2···2···1         3   ···1···2···2···1
4   ··1···1···1···1         4   ···1···1···1···1
6   ··1···1···1···1···1     6   ···1···1···1···1···1
7   ··1···2···2···2···1     7   ···1···2···2···2···1
8   ··1···2···3···2···1     8   ···1···2···3···2···1
9   ··1···2···2···2···1     9   ···1···2···2···2···1
10  ··1···1···1···1···1     10  ···1···1···1···1···1

Desde já agradeço pela ajuda!
Comment: Edite sua pergunta e adicione o enunciado completo do exercício, também, pois facilitará no entendimento da questão.
Comment: Atenção que a forma como disse o que precisa não está certa. Os valores são justificados à direita em tamanho `3` e separados por espaço. Logo se tiver o numero `11`, vai ter 1 espaço antes devido à justificação e outro para separar dos restantes elementos.
Answer: Esta questão se refere ao problema de número "1435", cujo título é "Matriz Quadrada I", disponibilizado por "Uri Online Judge" (Maratona Online de Programação).
Veja aqui a íntegra do enunciado.
Para resolver esta questão você tem que saber como montar uma matriz quadrada. Além disso, deve levar em consideração as restrições que o problema nos faz.
Para resolver esta questão, podes utilizar o seguinte algoritmo...
# Problema: 1435
# Título: Matriz Quadrada I
# Categoria: Iniciante
# Disponibilizado por: https://www.urionlinejudge.com.br/judge/pt/problems/view/1435

while True:
    N = int(input())

    if N == 0:
        break

    resultado = []

    for i in range(N):
        tmp = []
        for j in range(N):
            tmp.append(1)
        resultado.append(tmp)

    valor = 1
    cima = 0
    esq = 0
    baixo = N - 1
    direita = N - 1

    if N % 2 == 0:
        meio = N / 2

    else:
        meio = (N + 1) / 2

    while valor <= meio:
        i = esq
        while i <= direita:
            resultado[cima][i] = valor
            resultado[baixo][i] = valor
            i += 1

        i = (cima + 1)
        while i < baixo:
            resultado[i][esq] = valor
            resultado[i][direita] = valor
            i += 1

        valor += 1
        cima += 1
        baixo -= 1
        esq += 1
        direita -= 1

    for i in range(N):
        tx = ''
        for j in range(N):
            tx += " %3d" % resultado[i][j]
        print(tx[1:])
    print("")

Veja aqui o funcionamento do algoritmo.
Este algoritmo já foi testado, submetido e devidamente aprovado no site Uri, sobe linguagem de programação Python 3.
Answer: while True:
m = int(input())
mlen = m
sm = 1
aux = 1
matriz = []

if m == 0:
    print()
    break

for i in range(m):
    linha = []
    for j in range(m):
        linha.append(sm)
    matriz.append(linha)

while m - 2 > 0:
    for i in range(aux, m - 1):
        for j in range(aux, m - 1):
            matriz[i][j] = sm + 1
    sm += 1
    aux += 1
    m -= 1
for i in matriz:
    for pos, j in enumerate(i): # pos vai ser o endereço do valor j
        if pos == 0: # se for a primeira coluna pos = 0
            print('{:3}'.format(j), end='')
        else:
            print('{:4}'.format(j), end='')
    print('')

Formataçao PYTHON


Matching PA system

Question: Hope someone could help. not sure if this is the right place, but I'l give it a go.
I'm trying to figure out if my amp will be suitable for my speakers or its going to fry them up haha.
amp: PV-2600 delivering 900w && 4om per channel.
speakers: 150w 4-8 om's (that's is what listed on them)
Cheers to all,
Comment: @skinny peacock Cheers for the great answer appreciate
Answer: The answer to your question is the amp can easily burn up the voice coils in your speakers unless you either multiply the number of speakers power handling capabilities (more speakers) to equal the power output of the amp, or operate the amp at lower power output to match the power capabilities of your speakers. The key is to know the limitations of the system as a unit and operate it within those limitations. In this instance, it seems the speakers are the limiting factor, at least until you can obtain enough of them to handle the full output of that amplifier. You may reduce the output of the amp by wiring your speakers in series to present the amp with a higher impedance load and also just use the volume control to keep within the capabilities of the system. A safety precaution for those speakers is to always keep your volume controls turned completely down when turning the system on or off. This will prevent power transients from damaging your speakers.
Comment: Am I wrong in saying that whatever other speakers are added, pushing potentially 900 watts through the original 150 watt speakers will probably wreck them?
Comment: @Tim Thanks, you right, but I was just wondering if its possible cheers :)
Comment: It is feasible, but if it was my gear, I'd make sure it never went above a quarter power on the amp. And, I'd be looking for some replacement speakers or a big power sink.
Answer: The Peavey PV 2600 Power Amp is 2 x 900W RMS @ 4 ohms, 540W RMS @ 8 ohms, or 1800W RMS bridged mono.  What is your amp config?
The speaker combination in watts must be greater than amp output
Comment: Hey Peter Thanks,

I have 4 150W Speakers rated @ 4-8 ohms.
Comment: Unless you keep your amp low, you're going to charcoal these speakers

Matching PA system


Another benefit of Lighttpd in front of Apache

Question: I have read in a site that another benefit of having Lighttpd in front of Apache is lower number of child processes. Lighttpd will handle keep-alive and client requests while child processes of Apache gets to serve dynamic pages faster because of the very low latency communication between Lighttpd and Apache. I am trying to find the link but I am having a hard time.
Given that I already have a dedicated Lighttpd server for my static contents (img, vid, css, js, html, etc.) and another dedicated Apache server for my dynamic pages (php), I would like to implement this technique if it really has some performance gain.
1) Has anybody put a Lighttpd in front of Apache for the same purpose as explained above?
2) Is there really a performance gain on this? How much?
3) What about the overhead of Lighttpd handling down the request to Apache, is it really worth it?
Thanks!
Answer:
We had lighty serving static content, and forwarding the dynamic requests to Apache on the same server but listening on another port
the "forward to apache for dynamic" was not done for the purpose of performance, but just to have a single server from the point of the client, serving everything. However if you can avoid excess connections to Apache, it's a good side benefit. More connections = more processes = more memory (especially with mod_php). So, no numbers, sorry.
the overhead seemed negligle compared to the hog that is Apache

That said, you should consider the Varnish reverse proxy instead of (or in front of) lighty as your frontend. It's very fast and efficient. Especially interesting for caching dynamic pages (or page fragments, using ESI), it helps reducing the backend load and absorbing the traffic spikes.
And possibly use nginx (with PHP-FCGI) as a backend instead of Apache (although it's a more complicated task than adding a Varnish frontend) (nginx can be used as frontend too, but isn't as good as a dedicated reverse proxy like Varnish). Disclaimer: I don't have nginx experience ;)
Comment: Upboat, use Varnish for this and not lighthttpd.
Answer: I have used to be in the same situation, suing lighttpd next to apache)for reducing load on apache.
It's better to serve static content with a light web server, as it requires less resources. Also have to mention, that PHP requires apache to run in pre-forked mode, which disables apache from running efficiently. You can distribute the load over to two, differently set up web servers, each handling the traffic it's best in.
Some implementation notes:
You have three options:

modify your code and segment traffic on IP layer
 don't modify your code and segment traffic on application (http) layer
get one of the web servers to pass requests coming to the other web server for actual serving

The first is quicker, the second requires less configuration, the third is like a mule.
I would not consider the third option if I were you, as it comes with a configuration nightmare, also, if you misconfigure something at the first web server, nothing will work and it's harder to spot where the problem is.
In the past, I needed to have a solution urgently, so I went with option 2, and utilized a reverse proxy called pound to segment requests upon static/dynamic content and distribute the load to the two different web servers.
Although it works, it requires actively monitoring the http content, which takes it toll on performance (an extra daemon running).
With option 2, you can get better performance with utilizing an extra IP for static content (static.domain.org) and get the clients refer to this static.domain.org for the content. It will still require a reverse proxy, but the proxy does not have to check the Host: header in any of the requests, so it will be quicker.
here is a configuration snippet of pound for your reference:
<code>ListenHTTP
        Address 22.214.171.124
        Port 80
        Client 30
        RewriteLocation 2

        Service
                HeadRequire "^[Hh]ost:\s*www.nasa.gov$"
                URL "^/static/content"
                BackEnd
                        Address 127.0.0.1
                        Port 81
                        TimeOut 300
                End
        End
        Service
                HeadRequire "^[Hh]ost:\s*www.nasa.gov$"
                BackEnd
                        Address 127.0.0.1
                        Port 80
                        TimeOut 300
                End
        End
ListenHTTP
</code>


Why is it desirable to have linear separability in SVM?

Question:
Ref to above image, clearly a circle can separate the two classes(left image). Why then  take so much pain to map it to a function to make it linearly separable (right image) ?
Can anyone please explain ? I really couldn't find anything on the web or youtube lectures on the why
Answer: Well, that is the whole idea behind support vector machines! svm are searching for a hyperplane that separates the classes (why the name), and that can of course be done most effectively it the points are linearly separable (that's not a deep point, it is a summary of the full idea).  In the example you show, point lie on concentric annular rings, which cannot be separated by any plane, but by introducing a new variable RADIUS---distance from center---you get complete linear separation.
Comment: Classes can be non-linearly separable in an infinite number of ways, so yes, linear separation is clearly easier to handle!  And, that is the complete idea behind SVM, so that they work better for data which comply with the asumptions behind the method should hardly be a surprise ...
Comment: @hdx1101 - The kernel trick makes a lot of stuff feasible, computationally, but that's a big boon to implementation, not the idea behind the method itself.
Comment: You mean to say that linear seperability of classes is better/easier than non-linear seperability?
Comment: @kjetilbhalvorsen I think the key idea behind SVM is kernel trick to save time for computation. But not "using polynomial basis expansion".
Answer:
Why is it desirable to have linear separability in SVM?

SVCs are inherently a linear technique. They find linear boundaries separating (as best possible) different classes. If there is no natural linear boundary for the problem, the choices are either to use a different technique, or to use SVCs with transformed features into a space where there indeed is a linear boundary.

Ref to above image, clearly a circle can separate the two classes(left image). Why then take so much pain to map it to a function to make it linearly separable (right image) ?

This is a classic example. The data classes are separated by a circle, but an SVC cannot find circles directly. However, if the data are transformed using a radial basis function, then in the resulting space, the classes are separated by a linear boundary.
Answer: Not directly answer your question but,
It is important to keep in mind the difference between basis expansion and Kernel method / SVM.

We can "expand data" using basis expansion in different ways. For example, polynomial expansion, splines, Fourier series, etc. These basis expansion have little to do with SVM, kernel trick.
SVM with polynomial kernel provides use a "computational effect" ways to do polynomial basis expansion. Search Kernel trick for details.
Answer: SVCs were originally defined to be linear classifiers which tried to find maximum margin hyperplanes. The optimization problem is derived starting with an equation of a plane and calculating the distance of points from it, and finding out its parameter matrix w. See here for details. In a 2 dimensional case(left figure) a 1D hyperplane i.e. a straight line clearly can't separate the two classes, but with careful projection of data into 3rd dimension, support vectors are easily separated by a 2D hyperplane, as for these points x^2 + y^2 is near constant.
Answer: You are correct.  When the field says "linearly separable", they mean that the data should be "differentiable": that there exists some filtering function that you can overlay onto the dataset to create two or more distinct groupings (with some small error tolerance).
That's all.  But you should point out to the academics to clean up thier language.


Can i update the windows registry entries for HKEY_CURRENT_USER values without elevated privileges?

Question: Links such as the following suggest that I should be able to edit the registry without elevated privileges, as long as I only update HKEY_CURRENT_USER.
https://blog.codeinside.eu/2015/08/11/reg-exe-or-how-to-import-reg-files-without-admin-privileges/
However, my observation is that a command like this gets an error:
<code>reg add "HKEY_CURRENT_USER\SOFTWARE\Policies\Google\Chrome\AutoSelectCertificateForUrls" /v 1 /d {"pattern":"https://[*.]somedomain.com","filter":{"SUBJECT":{"CN":"MyCNValue"}}}
</code>

Is this expected, i.e. only administrators are permitted to update registry entries for anything, including HKEY_CURRENT_USER?  Or have I overlooked something?
For what it's worth ... read queries of HKEY_CURRENT_USER are working fine without admin privileges:
Answer: The subkey HKEY_CURRENT_USER\SOFTWARE\ Policies is special.
Please check the security on it, you will notice your username is read-only and the built-in administrator's group is read/write.
This is done that way as GPO in domain environment that push per-user setting write there. To allow the user to erase or change them will yield no value to enforce enterprise policy per user.
For reference please see that Excel document,  Group Policy Settings Reference Spreadsheet for Windows 10 May 2020 Update (2004), you will see all per-user setting all go there.
In your case if your customer got a domain, I would suggest to use Chrome .ADMX to set such settings. That way it's managed centrally, and the user got no prompt as it's the gpo that apply the settings to that registry place. You can get the ADMX there inside that pack, https://chromeenterprise.google/browser/download/#windows-tab.


Example for simple shooting method

Question: Intro
Simple shooting methods for boundary value problem of the form:
$$
x'(t)=f(x(t),t), \quad r(x(a),x(b))=0
$$
with $f:\Omega \times I \rightarrow\mathbb{R}^m, \quad r: \mathbb{R}^m \times \mathbb{R}^m \rightarrow \mathbb{R}^m, \quad I=[a,b]$
try to find a starting vector $s$ so that the solution for
$$
x'(t)=f(x(t),t), \quad x(a)=s
$$
provides a solution for $x(t)$ with $r(x(a),x(b))=0 $. The first step for that is that if $x(t;s)$ is the solution for $x(t)$ of  $x'(t)=f(x(t),t), \quad x(a)=s$ with start value $x(a)=s$, we have to find the roots of the function
$$
F(s):= r(s;x(b;s))
$$
Task
I have given the system
$$
x''(t)=\gamma x, \quad x(0)=1, \quad x(1)=2
$$
and need to formulate $F(s)$.
My try
I am absolutely clueless. The only thing I would say ist that $a=0, b=1$ but from there on I don't know what to do. Do I really need to simply put down
$$
F(s):= r(s;x(b;s))= r(s;x(1;s))
$$
I cannot imagine that it would be this simple. I don't know how to go further, only using Wikipedia I would assume that
$$
F(s)=x(1;s)-2
$$
would be the solution but I don't really know if this is right or why. I would appreciate your help!
Answer: In the full formalism as given you have $s=(s_1,s_2)=(x(0),x'(0))$ and $F(s)=(x(0;s)-1,\,x(1;s)-2)$.
Of course you can reduce that boundary function to a scalar function by always setting $s_1=1$. But this is a less general formulation.

Example for simple shooting method


Cannot copy scripts from index.js to assets folder in react native

Question: Everytime when I create and run a sample app in react native I'm getting this error "Unable to load scripts from assets index.android.bundle". So I tried this solution
1.mkdir assets with android/app/src/main
2.react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res
3.react-native run-android
But getting this error Plugin 0 specified in "E:\\SampleReact\\node_modules\\babel-preset-react-native\\index.js" provided an invalid property of "default" (While processing preset: "E:\\SampleReact\\node_modules\\babel-preset-react-native\\index.js").Before this i was getting the error unable to find Accessibility info within react-native so i downgraded the RN version from 0.56 to 0.55.4.Then i tried but getting the above error.Stuck with this.Please help.The problem is that i just installed windows 10 so that i need to install all the dependencies(node,android studio, react-native, java sdk etc..) from the beginning.So please help.
Answer: change your dev settings ip, if its emulator its like(10.0.2.2:8081), if device(yoursystemip:8081). try this it ll work
Comment: Thank you for the reply, I tried this but still getting the same.
Comment: else change the port number, if firewall is there, it might not work


I am trying to write templatized code to compare two vector but i am getting these error

Question: #include <iostream>
#include <string>

#define BLOCK_SIZE 5

template<typename T>
class vec {
 T*ptr;
    int size;
    int capacity;
    public:

    vec():size(0),capacity(BLOCK_SIZE)
    {
        ptr = new T[capacity];
    }
    vec(int size1)
    {
        capacity=size1;
        ptr = new T[capacity];

    }
    void push_back(T val)
    {
        if(size==capacity)
        {
            T*ptr1 = new T[capacity];
            for(int i=0;i<size;i++)
            {
                ptr1[i]=std::move(ptr[i]);
            }
            delete[] ptr;
            ptr = nullptr;
            capacity+=BLOCK_SIZE;
            ptr = new T[capacity];
            for(int i=0;i<size;i++)
            {
                ptr[i]=std::move(ptr1[i]);
            }
            delete[] ptr1;
            ptr1= nullptr;
        }
        ptr[size++]=val;
    }

    T& operator[] (int num)
    {
        return ptr[num];
    }
    bool operator == (vec<T> obj)
    {
    if (this->size != obj.size) {
        return false; // Different sizes, not equal
    }
    else
    return true;
    }
    template<typename U>
    friend bool operator==(const vec& lhs, const vec& rhs);
};

template<typename T>
bool operator==(const vec<T>& lhs, const vec<T>& rhs) {
    if (lhs.size != rhs.size) {
        return false;
    }

    for (int i = 0; i < lhs.size; ++i) {
        if (lhs.ptr[i] != rhs.ptr[i]) {
            return false;
        }
    }

    return true;
}

int main() {
    vec<std::string> vec1;
    vec<int> vec2(10);
    vec2.push_back(100);
    vec1.push_back("abhinav");

    std::cout << vec1[0] << std::endl;
    std::cout << vec2[0] << std::endl;

    if (vec1 == vec2) {
        std::cout << "Same vectors" << std::endl;
    } else {
        std::cout << "Different vectors" << std::endl;
    }

    return 0;
}

below is error i am getting in gcc compiler
main.cpp: In function 'int main()':
main.cpp:86:14: error: no match for 'operator==' (operand types are 'vec >' and 'vec')
   86 |     if (vec1 == vec2) {
      |         ~~~~ ^~ ~~~~
      |         |       |
      |         |       vec<int>
      |         vec<std::__cxx11::basic_string<char>>
main.cpp:50:10: note: candidate: 'bool vec::operator==(vec) [with T = int]' (reversed)
   50 |     bool operator == (vec<T> obj)
      |          ^~~~~~~~
main.cpp:50:30: note:   no known conversion for argument 1 from 'vec>' to 'vec'
   50 |     bool operator == (vec<T> obj)
      |                       ~~~~~~~^~~

How to modify this code so i can compare any two types of vector
Comment: Why do you have an `operator==` declared both inside the class and outside? Either can work (although outside is better) but having both makes little sense.
Comment: If you really want to compare different types of vector then that would be `template
bool operator==(const vec& lhs, const vec& rhs)` though obviously this will still not work for `std::string` and `int` because there is no `operator==` defined for those two types. But it should work for `vec` and `vec` for example.
Comment: A side note: instead of a `#define` for your constant value, you can use a more modern `inline constexpr int BLOCK_SIZE = 5;`. See more info here: https://stackoverflow.com/questions/54466591/replacing-constants-when-to-use-static-constexpr-and-inline-constexpr.
Comment: @user265906 - following the comments under my answer below, can you explain why you actually need to compare these types of different vectors ? It might be an XY problem.
Comment: `bool operator == (vec obj)` -- This is broken, all due to your `vec` class violating the [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three).  You ae passing `obj` by value, meaning a copy will be made.  Your class lacks a user-defined copy constructor, assignment operator, and destructor.  '
Answer: Your operator== is expecting both vecs to be of the same type T.
This actually makes sense.
In this line:
if (vec1 == vec2) {

You are attempting to compare a vec<std::string> to a vec<int>.
The compiler is emitting an error because it does not comply to your operator== declaration.
Even if you did implement a operator== for such a case I don't see much point in it.
The only case in which you can consider them really equal is if they are both empty, which is something you can easily test without convoluting the semantics of operator==.
Having said that, if for some reason you need some special sematics like comparing a vec<int> to vec<string> after converting the strings to ints you should implement a specific overload for it.

Update:
As john commented above one use case for supporting comparison between different vec types could be for comparing numeric values (e.g. ints and floats).  In this case you need to change the declaration to use 2 template parameters (like T, U):
template<typename T, typename U>
bool operator==(const vec<T>& lhs, const vec& rhs) { /*...*/ }

Comment: I'm not the downvoter.  But I'm guessing it's to do with the fact that the question from the op was "How to modify this code so i can compare any two types of vector?", and the answer given seemed to be: "you don't need to do that".
Comment: @wearetherobots thanks for the feedback. I focused on explaining the compiler error and questioning the motive, but I see the reason in what you wrote.
Comment: For your answer to be more complete: If the operator == is invoked from template code, it may make sense to define it for vectors of different types.  In this situation, defining it would make sense, presumably returning false.
Comment: @wearetherobots you are right that it could be done. But as I mentioned in my answer, I don't see much use for such an implementation. The only reasonable case IMHO is for different numeric types as john commented above. Updated my answer with it.
Comment: even with `std::string` and `int` they could have a `operator==` that returns `false` when `T != U` and compares the elements otherwise


Error using uic to convert .ui file to .py file in Python

Question: I am trying to write a program in python that will convert a .ui file in the same folder (created in Qt Designer) into a .py file. This is the code for this extremely basic program:
# -*- coding: utf-8 -*-

from PyQt4 import uic

with open('exampleinterface.py', 'w') as fout:
    uic.compileUi('exampleinterface.ui', fout)

It gives the following error (with long path names shortened):

Traceback (most recent call last):
File "", line 1, in
File "...\Python32_3.5\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
      execfile(filename, namespace)
File "...\Python32_3.5\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 88, in execfile
      exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
  File ".../Documents/Python/UiToPy/minimalconvert.py", line 11, in
      uic.compileUi('exampleinterface.ui', fout)
File "...\Python32_3.5\lib\site-packages\PyQt4\uic__init__.py", line 173, in compileUi
      winfo = compiler.UICompiler().compileUi(uifile, pyfile, from_imports, resource_suffix)
File "...\Python32_3.5\lib\site-packages\PyQt4\uic\Compiler\compiler.py", line 140, in compileUi
      w = self.parse(input_stream, resource_suffix)
File "...\Python32_3.5\lib\site-packages\PyQt4\uic\uiparser.py", line 974, in parse
      document = parse(filename)
File "...\Python32_3.5\lib\xml\etree\ElementTree.py", line 1182, in parse
      tree.parse(source, parser)
File "...\Python32_3.5\lib\xml\etree\ElementTree.py", line 594, in parse
      self._root = parser._parse_whole(source)
  xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 1

Can anyone tell me why this isn't working, and if there is a solution?
Note: I know that there are other ways to convert a .ui file into a .py file, but I am looking for one that I can easily integrate into a python program, without calling an outside file.
Comment: Works fine for me. Obviously there is something wrong with your `ui` file - but since you didn't provide it, there's not much more that can be said.
Comment: You should check if the same file can be converted in the regular way using `pyuic4` in the command line. If it doesn't work there either, your .ui file is the problem.
Answer: This error popped because my .ui file was not saved with the recent changes that i had done. The file name showed the asterisk(*) mark in the file name. Once i saved the file with changes it could be converted into a .py file.
Answer: Thanks to ekhumoro and mwormser. The problem was indeed the .ui file.
I retried it with a new .ui file and everything worked fine.


Windows Server to Server copy, executed remotely, process overview

Question: Ok so I've got 3 servers in this example
Server_A, Server_B, Server_C
I want to move data over the network from Server_A to Server_B by executing a batch script on Server_C, it would be something like this.
robocopy "\\Server_A\Share\" "\\Server_B\Share\"

1.) How is the data actually written to Server_B, does it get copied from Server_A to Server_C in a temp folder or memory then written to Server_B? Or does Server_C somehow actually tell Server_A to copy the file to Server_B directly.
My thoughts would be the data has to be read to a temp folder or memory on Server_C before it can then be written to Server_B which would mean that you effectively double the amount of data traveling over the network by using Server_C to manage the transfer it becomes an additional hop?
2.) Is it faster to run this data copy on server_A vs running on Server_B assuming all aspects of both servers are the same? Ie: When you copy from one server to another, does managing the copy on the source vs destination server have any real world impact?
I would guess running the copy from the source server is faster because it has the fastest access to the file allocating tables being they are stored locally, vs querying a remote server.
Thanks in advance for any input you can provide.
Answer: Running the robocopy command you show in your question from "Server_C" causes the data to be read over the wire from "Server_A" and sent to "Server_B" by "Server_C". All the data traverses the network interface(s) on "Server_C". The data moves through buffers in RAM-- there is no "temp folder" or such-- it's more ephemeral than that.
You are correct, though, in that you're creating a "hop" that causes more traffic to be generated overall. "Server_C" has no particular need for that data to move through it if "Server_A" and "Server_B" are able to communicate directly.
In such a scenario it would be faster to run the robocopy command on either "Server_A" or "Server_B". You won't be creating a "hop" that the traffic moves through unnecessarily. There's definitely a "real world impact", though whether it makes any practical difference in visible speed depends on how much data you're moving and the network topology.
Running the command on the source versus destination server makes no particular difference because the same data will be read from disk and transferred over the network. There's nothing about the "access to the file allocating tables" being faster for the source versus the destination-- the same data is moving regardless of where you initiate the copy from in that case.


Exibir miniaturas de arquivos

Question: Alguém conhece algum plugin que permita a pré-visualização de arquivos TXT, PDF, DOC, e XLS para exibir numa página Web?
Na imagem exemplo, está sendo exibido um PDF e uma imagem
Comment: Você consegue ser mais especifico? fale mais sobre o seu problema e compartilhe o código que você já produziu.
Comment: +1 Acho uma boa pergunta. Eu não faço nem ideia de como fazer isso. E to muito curioso de saber como se faz. Pena que a pergunta está para ser fechada, provavelmente for falta "do que você já tentou".
Comment: Na verdade Felipe, não implementei nada relacionado, não consegui e não achei nada referente. Tenho vários arquivos numa pasta, entre eles, pdf, xls, doc, jpg, png, entre outros, eu preciso exibi-los em miniatura, mostrando parte ou seu conteúdo.
Answer: Cara, existe o Bootstrap File Input:
HTML 5 para Bootstrap 3.x com pré visualização para vários arquivos, oferece a seleção múltipla, e muito mais. O plugin permite-lhe uma maneira simples de configurar um controle selecionador de arquivo/upload avançado construído para trabalhar especialmente com estilos Bootstrap CSS3. Ele melhora a funcionalidade de entrada de arquivo ainda mais, oferecendo suporte para pré-visualizar uma grande variedade de arquivos, ou seja, imagens, texto, html, vídeo, áudio, flash e objetos. Além disso, ele inclui uploads baseados AJAX, drag-drop de arquivos, vendo o progresso do upload, e seletivamente a visualização, adicionar ou excluir arquivos. :
http://plugins.krajee.com/file-input
Outra opção seria utilizar essa robusta API:
http://filepreviews.io/
Começando
O serviço FilePreviews.io é composto de uma API muito simples organizado voltada para REST.
Pode ser usado para solicitar uma pré-visualização, que acontece de forma assíncrona. Os resultados retornados são úteis para diferentes cenários, permitindo que você visualize os metadados solicitados e verificar se estão disponíveis, ou utilize webhooks.
JSON será devolvido em todas as respostas a partir da API, incluindo erros.
Exemplo basico:
Código:
<code>import FilePreviews from 'filepreviews'

const fp = new FilePreviews({
  debug: true,
  apiKey: 'XXXX-YOUR-SERVER-KEY-HERE-XXXX',
  apiSecret: 'XXXX-YOUR-SERVER-SECRET-KEY-HERE-XXXX'
})

const options = {
  pages: "all",
  format: "png"
}

fp.generate('https://www.filepicker.io/api/file/asTSNPAiR4qnknj7UgAP', options (err, result) => {
  if (err) throw new Error(err)
  console.log(result)
})
</code>
Resultado:
<code>{
  "id": "46d6fbcf-83be-47ee-9eb1-2579f1d1a306",
  "url": "https://api.filepreviews.io/v2/previews/46d6fbcf-83be-47ee-9eb1-2579f1d1a306/",
  "status": "success",
  "preview": {
    "url": "https://s3.amazonaws.com/demo.filepreviews.io/dcc8ad4e46ffecf17474466cba8fa9de9c7beda2fb0518d8fe5440b4ee38db81/46d6fbcf-83be-47ee-9eb1-2579f1d1a306_original_1.png",
    "size": {
      "height": "842",
      "width": "595"
    },
    "page": 1,
    "original_size": {
      "height": "842",
      "width": "595"
    },
    "requested_size": "original",
    "resized": false
  },
  "thumbnails": [
    {
      "url": "https://s3.amazonaws.com/demo.filepreviews.io/dcc8ad4e46ffecf17474466cba8fa9de9c7beda2fb0518d8fe5440b4ee38db81/46d6fbcf-83be-47ee-9eb1-2579f1d1a306_original_1.png",
      "size": {
        "height": "842",
        "width": "595"
      },
      "page": 1,
      "original_size": {
        "height": "842",
        "width": "595"
      },
      "requested_size": "original",
      "resized": false
    }
  ],
  "original_file": {
    "metadata": {
    },
    "encoding": "binary",
    "name": "JSday Recife",
    "extension": "pdf",
    "total_pages": 1,
    "size": 39736,
    "type": "application",
    "mimetype": "application/pdf"
  },
  "user_data": null
}
</code>
Comment: Show de bola cara, é isso que eu quero, pena que os outros caras do forum não entendem muito e acham que não é programação. Vou começar a usar o http://filepreviews.io/. Vlw
Comment: Que pena as pessoas não tem tanta paciência....

Exibir miniaturas de arquivos


What is the purpose of nested classes in Java?

Question: I've seen this sample code from Oracle Website about Java ?
public class Parent {
    class InnerClass {
        void methodInFirstLevel(int x) {
           // some code
        }
    }

    public static void main(String... args) {
        Parent parent = new Parent();
        Parent.InnerClass inner = parent.new InnerClass();
    }
}

What is the purpose of the construct parent.new InnerClass()?
What kind of classes would be suited to such construction?

The title may be misleading: I understand everything about this construct.
I just don't understand where and when to use this Java feature.
I found another syntax to do the same: Java: Non-static nested classes and instance.super()
There are lot's of references about this structure, but nothing about the application.
[References]

Java inner class and static nested class
Java: Static vs non static inner class [duplicate]
what is the use of inner classes in java ? is nested classes and inner classes are same? [duplicate]
Java: Static vs non static inner class [duplicate]
Comment: Not specific for Java 8, has existed probably since the first Java version
Comment: @MarkRotteveel: Oh, yes indeed. There's a "Why use nested classes" section in the page. Not sure how an answer could explain what several pages of the tutorial can't.
Comment: @JBNizet Seems to be down the middle in version 1.1 :) http://en.wikipedia.org/wiki/Inner_class#Programming_languages
Comment: One good use is a static inner class named `Builder` for the Builder design pattern...
Comment: The official Java tutorial covers them: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Comment: @JBNizet That is the page he is linking to.
Comment: @MarkRotteveel: Since Java 1.2, IIRC.
Comment: @BalusC I have tested this snippet on JDK6, and it does not compile. For me it's working since Java 7... Any info ?
Answer:
What is the purpose of parent.new InnerClass()?

This is for demonstration - using this mechanism to construct an inner class is rare. Normally inner classes are created only by the outer class when it is just created with new InnerClass() as usual.

What kind of classes would be suited to such construction?

Look at Map.Entry<K,V> for a classic example. Here you can see an inner class called Entry that should be created by all classes that implement Map.
Comment: I'm next to @chepseskaf and we fully undestand what an inner non-static class is and its relation to its parent. What we can not figure out is why would somebody instanciate a Parent and then __need to__ instanciate an InnerClass from the Parent instance. This is very different from the Map.Entry example. What use case would need such a technic?
Comment: The structure provided in the sample require to create an instance of `Parent` before create an instance of `InnerClass`. I do not understand the link with Map.Entry ?
Comment: @chepseskaf - for non-static inner classes, each one has a connection to its parent so that it can access the parent's fields and methods so a parent **must** already exist for each child to attach to. It makes sense to enclosed the `Entry` class in the `Map` class because each type of `Map` is likely to have have different kinds of `Entry`.
Comment: @Pigelvy - For demonstration mostly. I do not recall ever needing to do it this way in real life.
Answer: I see many answers here explaining the use of inner classes, but as far as I can see, the question is about the specific construct parent.new InnerClass().
The reason for that syntax is very simple: an instance of an inner class must belong to an instance of the surrounding class. But since main is a static method, there is no surrounding Parent object. Therefore, you must explicitly specify that object.
public static void main(String[] args) {
    // this results in an error:
    // no enclosing instance of type Parent is available
    InnterClass inner = new InnerClass();

    // this works because you specify the surrounding object
    Parent parent = new Parent();
    InnerClass inner = parent.new InnerClass();
}

I'm searching for a use of this construct in the standard packages, but so far I haven't found an example.
Comment: @Pigelvy you are right. The reason is that I don't see a use for this syntax. Every example I come up with can be solved easier without it...
Comment: You seem to understand the question but your answer is all about the technic itself, not the pertinence/usage of this technic.
Answer: Inner classes nest within other classes. A normal class is a direct member of a package, a top-level class. Inner classes, which became available with Java 1.1, come in four flavors:

Static member classes
Member classes
Local classes
Anonymous classes

the most important feature of the inner class is that it allows you to turn things into objects that you normally wouldn't turn into objects. That allows your code to be even more object-oriented than it would be without inner classes.
public class DataStructure {
    // create an array
    private final static int SIZE = 15;
    private int[] arrayOfInts = new int[SIZE];

    public DataStructure() {
        // fill the array with ascending integer values
        for (int i = 0; i < SIZE; i++) {
            arrayOfInts[i] = i;
        }
    }

    public void printEven() {
        // print out values of even indices of the array
        InnerEvenIterator iterator = this.new InnerEvenIterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.getNext() + " ");
        }
    }

    // inner class implements the Iterator pattern
    private class InnerEvenIterator {
        // start stepping through the array from the beginning
        private int next = 0;

        public boolean hasNext() {
            // check if a current element is the last in the array
            return (next <= SIZE - 1);
        }

        public int getNext() {
            // record a value of an even index of the array
            int retValue = arrayOfInts[next];
            //get the next even element
            next += 2;
            return retValue;
        }
    }

    public static void main(String s[]) {
        // fill the array with integer values and print out only
        // values of even indices
        DataStructure ds = new DataStructure();
        ds.printEven();
    }
}

Comment: This sentence "allows you to turn things into objects that you normally wouldn't turn into objects" doesn't make a lot of sense to me.
Comment: Please see my edit, with an example illustrating perfectly this sentence
Comment: I don't see how this illustrates that sentence; one could wonder though if creating an iterator here is needed and wanted.


Views and empty parameter in Path to link

Question: I know my title isn't explicit, but i will explain my problem. I created a view that displays me all documents(content) of my website, some documents are linked to a project(content) via entity reference, and in my view I display a link to a document. if there is a project the link looks like : node/100?project=5 . If there is no project the link needs to look like : node/100.
So in my view I added field excluded from display with the id of the project, and a second field which is the id of the node document and I rewrite the link  to :
node/[nid]?project=[field_doc_project]

My problem is: This works fine for document with projects only. good url: node/100?project=5 bad url, without project: node/100?project=.
Can I check in view if the project id exists and rewrite the url to node/100?
thanks
Answer: almost there,

add a link to the original content as a field, exclude it from display
add a path to the original content as a field, exclude it from display

rewrite the term reference to the full url you want to have using replacements [path]?something=[someid]

add a no results behavior and output the link from 1) [view_node]


Nested Attributes: why validate nested models if you're using reject_if?

Question: I'm a rails noobie and I'm trying to sort out the differences between rejecting an instance based on an empty attribute and creating a validation that checks the attribute is present.
Students have many exams. A critical attribute of an exam is the score. Without that, the exam should not be accepted into the database.
My exam model has the following line:
validates :score, presence: true

My student model has this:
accepts_nested_attributes_for :exams,
:reject_if => proc { |exam| exam['score'].blank? }

It seems that the second example quietly "rejects" the exam from being entered into the database, whereas the first example spits out an error message and asks you to try again.
But really, what's the difference here....it seems that they both ultimately block an instance from being entered into the database -- would I ever benefit from including both lines?
Answer:
But really, what's the difference here...

The difference is absolute :) You isolate the logic to where it belongs.
What you have in Exam model concerns only Exam model.
What you define in Student model, well, concerns only Student model.
This said, say, you have passed the reject_if in Student model and allow the saving transaction to move forward. It won't save the nested object if it fails validations in its model (Exam, which is independent by definition).

would I ever benefit from including both lines?

Having validations in Exam model allows you to avoid saving invalid objects into db, and it has nothing to do with validating nested object creation in Student model.
In any way these things are separate, different and have no connection.


Having different sections with List for each element

Question: I want to have different sections for each element i have in List and each different section have different data sheet to display too. This is my tried code i made my sections like i wanted but the data sheet did not display.

<code>  struct ListsView: View {

 @State var states: [String] = ["CA", "MA"]
 @State var block1: [String] = ["John", "Emma", "Winny"]
 @State var block2: [String] = ["Supreme", "Jax", "Louis"]
var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            List(block1, id: \.self) { b1 in
                Text(b1)
            }
            List(block2, id: \.self) { b2 in
                Text(b2)
            }
        }
    }
  }
 }
</code>
Answer: You do not need sub lists inside your first List. Instead you can achieve this design with a condition logic plus one section inside the first List.
Code is below the image:

<code>struct ListsView: View {
@State var states: [String] = ["CA", "MA"]
@State var block1: [String] = ["John", "Emma", "Winny"]
@State var block2: [String] = ["Supreme", "Jax", "Louis"]
 var body: some View {
    List(states, id: \.self) { state in
        Section(header: Text(state)) {
            ForEach(state == "CA" ? block1 : block2, id: \.self) { b in
                Text(b)
            }
        }

    }
  }
}
</code>


Alguém pode me ajudar, eu não estou conseguindo digitar no input

Question: Então, eu tenho esses códigos aqui, a minha div está draggable/moveable, porém por algum motivo eu não consigo digitar neste input, alguém pode me achar? Agradeço  desde já :)

//Make the DIV element draggagle:
dragElement(document.getElementById("ajuda"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;

  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;

  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;

  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";

    // CÓDIGO (início)
    var ww = window.innerWidth; // largura da janela
    var wh = window.innerHeight; // altura da janela
    var ew = elmnt.offsetWidth; // largura do elemento
    var eh = elmnt.offsetHeight; // altura do elemento

     // se a posição for maior ou igual do que a largura da tela menos a largura do elemento
    if(elmnt.offsetLeft - pos1 >= ww-ew){
        elmnt.style.left = ww-ew +"px";
    }

     // se a posição for maior ou igual do que a altura da tela menos a altura do elemento
    if(elmnt.offsetTop - pos2 >= wh-eh){
        elmnt.style.top = wh-eh +"px";
    }

    // se a posição for menor ou igual que zero ao topo
    // ou a altura do elemento for maior que a altura da janela
    if(elmnt.offsetTop - pos2 <= 0 || eh >= wh){
        elmnt.style.top = "0";
    }

    // se a posição for menor ou igual que zero para a esquerda
    // ou a largura do elemento for maior que a largura da janela
    if(elmnt.offsetLeft - pos1 <= 0 || ew >= ww){
        elmnt.style.left = "0";
    }
    // CÓDIGO (fim)

  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;

  }
}
.ajudaConteudo {
    background-color: white;
    height: 400px;
    position: absolute;
    margin-top: 100px;
    width: 350px;
    overflow-y: scroll;
    cursor: auto;
    overflow-x: hidden;
}

.ajudaTitulo {
    background-color: #1ab3ff;
    height: 90px;
    width: 335px;
    font-family: Arial;
    font-size: 30px;
    color: white;
    position: absolute;
    padding-top: 10px;
    padding-left: 15px;
}

.pesquisaAjuda {
    position: absolute;
    top: 60px;
    padding: 6px;
    width: 280px;
    left: 50%;
    transform: translate(-50%);
    z-index: 9999;
    border-radius: 5px;
    border: 1px solid transparent;
}

.ajudinha {
    background-color: white;
    margin-left: 8px;
    margin-right: 8px;
    box-shadow: 1px 1px 7px grey;
    margin-top: 10px;
    height: 80px;
}

.ajudinha h1 {
    color: gray;
    font-weight: 600;
    word-break: break-all;
    font-size: 16px;
    text-align: center;
}

.ajudinha p {
    padding-top: 5px;
    color: gray;
    padding-left: 10px;
    padding-right: 7px;
    overflow: hidden;
    text-overflow: ellipsis;
}

#ajuda {
    width: 350px;
    height: 500px;
    background-color: red;
    position: absolute;
    z-index: 99999;
    right: 20px;
    top: 10%;
    cursor: all-scroll;
    box-shadow: 2px 2px 10px gray;

}

.fecharAjuda {
    position: absolute;
    top: 0px;
    transition: all .4s;
    left: 92%;
    font-size: 35px;
    cursor: pointer;
}

.fecharAjuda:hover {
    color: #777;
}

    <input type="text" id="pesquisaAjuda" class="pesquisaAjuda" placeholder="Pesquisa aqui">

        Ajuda

x

           ss

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Answer: A função dragElement está impedindo que o campo seja focável por causa do evento onmousedown na div pai. É preciso cancelar o evento temporariamente ao clicar sobre o campo, e ao sair dele, habilitar novamente. Adicionei os eventos no início da função para fazer isso (veja explicações no código):

//Make the DIV element draggagle:
dragElement(document.getElementById("ajuda"));

function dragElement(elmnt) {

   // habilitar a pesquisa (início)
   var pesquisa = document.getElementById("pesquisaAjuda"); // seleciona o campo de pesquisa

   pesquisa.onclick = function(e){
      e.stopPropagation(); // evita o evento click na div
      elmnt.onmousedown = null; // remove o evento onmousedown
      this.focus(); // foca o campo
   }
   pesquisa.onmouseout = function(){
      dragElement(document.getElementById("ajuda")); // reabilita o drag
   }
   elmnt.onclick = function(){
      pesquisa.blur(); // força o blur ao clicar na div pai
   }
   // habilitar a pesquisa (fim)

  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;

  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;

  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;

  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";

    // CÓDIGO (início)
    var ww = window.innerWidth; // largura da janela
    var wh = window.innerHeight; // altura da janela
    var ew = elmnt.offsetWidth; // largura do elemento
    var eh = elmnt.offsetHeight; // altura do elemento

     // se a posição for maior ou igual do que a largura da tela menos a largura do elemento
    if(elmnt.offsetLeft - pos1 >= ww-ew){
        elmnt.style.left = ww-ew +"px";
    }

     // se a posição for maior ou igual do que a altura da tela menos a altura do elemento
    if(elmnt.offsetTop - pos2 >= wh-eh){
        elmnt.style.top = wh-eh +"px";
    }

    // se a posição for menor ou igual que zero ao topo
    // ou a altura do elemento for maior que a altura da janela
    if(elmnt.offsetTop - pos2 <= 0 || eh >= wh){
        elmnt.style.top = "0";
    }

    // se a posição for menor ou igual que zero para a esquerda
    // ou a largura do elemento for maior que a largura da janela
    if(elmnt.offsetLeft - pos1 <= 0 || ew >= ww){
        elmnt.style.left = "0";
    }
    // CÓDIGO (fim)
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;

  }
}
.ajudaConteudo {
    background-color: white;
    height: 400px;
    position: absolute;
    margin-top: 100px;
    width: 350px;
    overflow-y: scroll;
    cursor: auto;
    overflow-x: hidden;
}

.ajudaTitulo {
    background-color: #1ab3ff;
    height: 90px;
    width: 335px;
    font-family: Arial;
    font-size: 30px;
    color: white;
    position: absolute;
    padding-top: 10px;
    padding-left: 15px;
}

.pesquisaAjuda {
    position: absolute;
    top: 60px;
    padding: 6px;
    width: 280px;
    left: 50%;
    transform: translate(-50%);
    z-index: 9999;
    border-radius: 5px;
    border: 1px solid transparent;
}

.ajudinha {
    background-color: white;
    margin-left: 8px;
    margin-right: 8px;
    box-shadow: 1px 1px 7px grey;
    margin-top: 10px;
    height: 80px;
}

.ajudinha h1 {
    color: gray;
    font-weight: 600;
    word-break: break-all;
    font-size: 16px;
    text-align: center;
}

.ajudinha p {
    padding-top: 5px;
    color: gray;
    padding-left: 10px;
    padding-right: 7px;
    overflow: hidden;
    text-overflow: ellipsis;
}

#ajuda {
    width: 350px;
    height: 500px;
    background-color: red;
    position: absolute;
    z-index: 99999;
    right: 20px;
    top: 10%;
    cursor: all-scroll;
    box-shadow: 2px 2px 10px gray;

}

.fecharAjuda {
    position: absolute;
    top: 0px;
    transition: all .4s;
    left: 92%;
    font-size: 35px;
    cursor: pointer;
}

.fecharAjuda:hover {
    color: #777;
}

    <input type="text" id="pesquisaAjuda" class="pesquisaAjuda" placeholder="Pesquisa aqui">

        Ajuda

x

           ss

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Como eu faço para cadastrar um aluno?

Para cadastrar um aluno vc precisa ir no botão alunos localizado no menu lateral e preencher o formulário que aparecerá.

Comment: Muito Obrigado, cara, me ajudou muito :)


Discriminant function for general polynomials

Question: According to Wikipedia... (terrible intro)
The discriminant of a 6-degree polynomial has 246 terms.
The article claims that the relationship between the terms in the discriminant has an exponential relationship to the degree of the equation. On the contrary, I put in the available data into Wolfram Alpha (2,2),(3,5),(4,16),(5,59),(6,246), used interpolate polynomial, and it gave me the equation (11 x^4)/3-(142 x^3)/3+(685 x^2)/3-(1433 x)/3+364.
Plugging 7 into this equation yields 777. Is the number of terms in a general septic discriminant 777, or is it something else? Or is there no discriminant for a general septic equation?
Comment: See [math notation guide](http://math.stackexchange.com/help/notation). You can [edit] your question to improve its readability.
Answer: The septic discriminant has 1103 terms.  See OEIS sequence A007878 for more.


Can't run docker-container 'failed to create endpoint frosty_varahamihira on network bridge'

Question: When I try to run the hello-world docker image I get the following error:
ubuntu@ubuntu:~$ sudo docker run hello-world
docker: Error response from daemon: failed to create endpoint frosty_varahamihira on network bridge: failed to add the host (vethc6c068f) <=> sandbox (veth82a7475) pair interfaces: operation not supported.
ERRO[0000] error waiting for container: context canceled

I red this post which seems to be the exact same problem but I can't manage to install a different kernel.
I tried the following to install a new kernel, which led me to the next error:
ubuntu@ubuntu:~$ sudo wget https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.7.5/amd64/linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb
--2021-10-22 13:47:14--  https://kernel.ubuntu.com/~kernel-ppa/mainline/v5.7.5/amd64/linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb
Resolving kernel.ubuntu.com (kernel.ubuntu.com)... 220.127.116.11
Connecting to kernel.ubuntu.com (kernel.ubuntu.com)|184.108.40.206|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1223448 (1.2M) [application/x-debian-package]
Saving to: 'linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb'

linux-headers-5.7.5-050705-generic_5.7.5-05070 100%[===================================================================================================>]   1.17M  2.53MB/s    in 0.5s

2021-10-22 13:47:20 (2.53 MB/s) - 'linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb' saved [1223448/1223448]

ubuntu@ubuntu:~$ sudo dpkg -i *.deb
dpkg: error processing archive linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb (--install):
 package architecture (amd64) does not match system (arm64)
dpkg: error processing archive linux-image-unsigned-5.14.9-051409-generic_5.14.9-051409.202109300934_amd64.deb (--install):
 package architecture (amd64) does not match system (arm64)
Errors were encountered while processing:
 linux-headers-5.7.5-050705-generic_5.7.5-050705.202006220832_amd64.deb
 linux-image-unsigned-5.14.9-051409-generic_5.14.9-051409.202109300934_amd64.deb

For that error I found this for example, which did not help.
This might also help
ubuntu@ubuntu:~$ ls -l /boot
total 33299
-rw------- 1 root root  5112454 Sep 29 07:51 System.map-5.13.0-1008-raspi
-rw-r--r-- 1 root root   241335 Sep 29 07:51 config-5.13.0-1008-raspi
drwxr-xr-x 4 root root     2560 Jan  1  1970 firmware
lrwxrwxrwx 1 root root       28 Oct 13 13:29 initrd.img -> initrd.img-5.13.0-1008-raspi
-rw-r--r-- 1 root root 19242515 Oct 13 13:30 initrd.img-5.13.0-1008-raspi
lrwxrwxrwx 1 root root       28 Oct 13 13:29 initrd.img.old -> initrd.img-5.13.0-1008-raspi
lrwxrwxrwx 1 root root       25 Oct 13 13:29 vmlinuz -> vmlinuz-5.13.0-1008-raspi
-rw------- 1 root root  9492544 Sep 29 07:51 vmlinuz-5.13.0-1008-raspi
lrwxrwxrwx 1 root root       25 Oct 13 13:29 vmlinuz.old -> vmlinuz-5.13.0-1008-raspi

I am using Raspberry Pi 4 Model B Rev 1.2. Here other versions:
Docker
ubuntu@ubuntu:~$ docker --version
Docker version 20.10.7, build 20.10.7-0ubuntu5

Ubuntu OS-Version
Ubuntu 21.10 aarch64

Kernel
ubuntu@ubuntu:~$ uname -rn
ubuntu 5.13.0-1008-raspi

I am thankful for any hint and idea!
Comment: sorry bro, but you're trying to install an amd64 kernel on an arm64 system. Did your read the error messages ? [ package architecture (amd64) does not match system (arm64) ]. Also your current kernel is more recent than the one you are trying to install. Is it really what you want to do ?
Comment: please post output of command `grep VETH /boot/config-5.13.0-1008-raspi` and `lsmod|grep veth`
Comment: the virtual ethernet module may not be loaded, that's what I'd like to see. => `sudo lsmod | grep veth` to see if the module is loaded and `sudo modprobe veth` to load it
Comment: Thank you for your answer! No that's not what I want and you're, my kernel is quite up to date.
What I want is to solve the error I get when I run a Docker-Container.
The output for ` grep VETH /boot/config-5.13.0-1008-raspi` is `CONFIG_VETH=m`.
For `lsmod|grep veth` I do not get an ouput.

Could you explain to me what I can conclude from that?
Comment: Here the output for `sudo modprobe veth`:
`modprobe: FATAL: Module veth not found in directory /lib/modules/5.13.0-1008-raspi`
For `sudo lsmod | grep veth` I do not get an output.
Comment: This is the issue. `CONFIG_VETH=m` means that you kernel was built with veth support as a module. So you should have in `/lib/modules/5.13.0-1008-raspi/kernel/drivers/net` a file named `veth.ko`. But if `sudo modprobe veth` fails, it means that the file `veth.ko` is not present. Can you post the output of `sudo dpkg -l|grep kernel`
Answer: install the linux-modules-extra-raspi package to get the veth module.
Comment: This solved this issue for me, thanks!