"Refreshing" asynchronous page every n seconds inside while loop

Question: I'm trying to let my page "refresh" asynchronous (I'm refreshing a div element which contains a partial view) while var edit = true. edit is altered when i click my button which has class: btn. I'm wondering where i should put my code.
Should i put my while loop inside my $(document).ready?
I'm kind off lost because this is ALL new to me.
This is my code:
var edit = true;

while(edit){
    window.setInterval(function(){
      alert('5 seconds');
    }, 5000);
}

$(document).on('click','.btn', function(){
    if(edit ? edit = false : true);
}

Comment: I'll update my question
Comment: What has `if(edit ? edit = false : true);` to do with your question? Even the `alert` has nothing to do with it. In fact, I fail to see what any of this code has to do with your question?
Comment: Also, you have MVC in your tags, but the question doesn't reference that. Are you using Angular or something similar?
Comment: My project is a MVC ASP.NET application, if that doesn't fall under mvc feel free to edit :) im a newbee
Comment: Javascript doesn't work like this. It is single thread language, your `while` loop will never break.
Comment: `I'm trying to let my page "refresh" asynchronous` What do you mean??? Nothing in your posted code is relevant to this
Comment: @A.Wolff update my question, im trying to refresh the div inside my page which contains a partial view
Answer: You don't need a while for a continous refresh. Just use clearInterval whenever you clicked the button and restart it on next click.

var interval, i = 0;

$('button').click(function() {
    if( interval ) {
        interval = clearInterval(interval);
    }
    else {
      interval = setInterval(function() {
          console.log(++i);
      }, 1000);
    }
});

<button>start / stop</button>

As edit to your comment, to start the interval directly I would encapsulate it into a function and use it. Maybe somehow like this:

var interval, i = 0;

function startInterval() {
    if( !interval ) {
        interval = setInterval(function() {
            console.log(++i);
        }, 1000);
    }

    return interval;
}

// start on document load
$(startInterval);

// start / stop on button click
$('button').click(function() {
    interval = interval ? clearInterval(interval) : startInterval();
});

<button>start / stop</button>
Comment: I've added an example with start on page load for you @Roy_Dorsthorst
Comment: Glad it worked for you! I've made another change and added a `if( !interval )` inside the function to prevent the race condition, whenever a user click on the button bevore the page was loaded. Otherwise it would be possible to have two simultanous intervals. This should fix it. @Roy_Dorsthorst
Comment: the button works, thank you! In this code the interval returns true when the button is click for the first time, can i copy `interval = setInterval(function() {
          console.log(++i);
      }, 1000);` into my `$(document).ready` to start the timer once the page is loaded, and will my button still work after that?
Comment: seems to be buggy once you click it several times
Comment: Yes, I've missed the `return` in the function. My fault. ;) @Roy_Dorsthorst
Comment: Works like a charm, accepted as answer. Thanks a bunch
Answer: Below shall refresh the page every while (example: 30 seconds)

<meta http-equiv="refresh" content="30">
...

Comment: I don't think OP is asking about a full page refresh.
Comment: I'm sorry my question wasn't clear enough, my fault. I'm trying to refresh a partial view inside a div element in my current view.


There is no intellisense in vs code node js

Question: There is no intellisence in visual studio code. i have installed and tried many extensions but it does not helping me out. It only shows those functions and variables that are already used in my code file. Here is the list on extension i have installed and the screenshot.
Comment: There is no problem with the vs code i just solve this by npm install  —save @types/node
Comment: VS code only gives intellisense when the function or class you are using has proper documentation. Like `express` npm.
Comment: I have used express before this but its same. Only those functions and variables are in intellisense after "." that are already in the code file, then I decided to reinstall vs code and extensions and start new project.
Comment: VS Code fetches type-definitons for node and you should be getting intellisense there without any of those extensions. Check your VS Code settings under JavaScript and see if anything is disabled that is related to Suggestions and Intellisense.
Comment: Also, node should be in your path for JavaScript Language Service to get those definitions. Further reading: https://code.visualstudio.com/docs/nodejs/working-with-javascript
Answer: There is no problem with the vs code i just solve this by
npm install --save @types/node

This is one of development dependencies and —save is just an argument that reflect the info related to this in your package.json file
Comment: interesting.  is this because it is typescript ?
Answer: Use this command in Mac :
sudo npm install -g --save @types/node --unsafe-perm=true --allow-root


convergence of power series of $S$

Question:
Find the   domain of the  convergence of the  power  series of $S ?$
$$S=\sum_{n=1}^{\infty} \left (\frac {2 + (-1)^n}{ 5+ (-1)^{n+1}} \right )^n x^n$$

My attempt :
I take  $a_n=\left (\frac {2 + (-1)^n}{ 5+ (-1)^{n+1}} \right )^n x^n$
Now  $\frac{1}{R} = \lim_{n\rightarrow \infty} |a_n|^\frac{1}{n}$
Now  i got $\frac{1}{R}=\left (\frac {2 + (-1)^n}{ 5+ (-1)^{n+1}} \right )$
After that im not able to proceed further
Any hints/solution will be appreciated
Comment: The limit does not exist. Instead of the limit, you should take the $\limsup$
Comment: When you take the limit as $n\to \infty$, the definition of $1/R$ will no longer have $n$ as a free variable.  So this "root test" for the domain of convergence is not properly applied.
Comment: okss@hardmath then  what test  will be applied ?
Answer: Split in the even and odd parts (this amount to reordering the series, but inside the disk of convergence the series converges absolutely so this is not a problem):
$$
S=\sum_{n=1}^\infty \frac1{6^{2n-1}}\,x^{2n-1}+\sum_{n=1}^\infty \left(\frac34\right)^{2n}\,x^{2n}.
$$
The radius for the first series is $6$, while for the second one is $\tfrac43$. So the radius that will make the whole series converge is $\tfrac43$.
Alternatively, you can simply calculate that
$$
\limsup_{n\to\infty}\left (\frac {2 + (-1)^n}{ 5+ (-1)^{n+1}} \right )=\frac34.
$$
Comment: thanks u sir @Martin Argerami

convergence of power series of $S$


DirectShow loop video infinitely with C++

Question: I have this small C++ code playing a video clip with DirectShow. What I want is the video to never stop so once it reaches the end I set the position to 0 again. The problem is that between the end and the start of the new loop there's a small delay that I would like to remove. My code looks like this:
#define WM_GRAPHNOTIFY  WM_USER

// Global vars
IGraphBuilder*      g_pGraphBuilder;
IMediaControl*      g_pMediaCtrl;
IMediaPosition*     g_pMediaPos;
IMediaEventEx*      g_pMediaEvent;

HWND                h_MainWindow;

// PlayVideo() - I removed the errors checking lines (irrelevant right now)
RECT grc;
IVideoWindow *pVidWin = NULL;
HRESULT hr = CoInitialize(NULL);

hr = CoCreateInstance(
    CLSID_FilterGraph,
    NULL,
    CLSCTX_INPROC_SERVER,
    IID_IGraphBuilder,
    (void**)&g_pGraphBuilder
);

hr = g_pGraphBuilder->RenderFile(L"Clip.mpeg", NULL);
hr = g_pGraphBuilder->QueryInterface(IID_IVideoWindow, (void **)&pVidWin);
hr = pVidWin->put_Owner((OAHWND)h_MainWindow);
hr = pVidWin->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);

GetClientRect(h_MainWindow, &grc);
pVidWin->SetWindowPosition(0, 0, grc.right, grc.bottom);

hr = g_pGraphBuilder->QueryInterface(IID_IMediaEventEx, (void **)&g_pMediaEvent);
hr = g_pGraphBuilder->QueryInterface(IID_IMediaPosition, (void**)&g_pMediaPos);
hr = g_pMediaEvent->SetNotifyWindow((OAHWND)h_MainWindow, WM_GRAPHNOTIFY, 0);
g_pMediaEvent->SetNotifyFlags(0);

hr = g_pGraphBuilder->QueryInterface(IID_IMediaControl, (void **)&g_pMediaCtrl);
g_pMediaCtrl->Run();

// WndPrc of the main window, the WM_GRAPHNOTIFY message
long EventCode, Param1, Param2;
// ...
case WM_GRAPHNOTIFY:
    while (g_pMediaEvent->GetEvent(&EventCode, &Param1, &Param2, 0)!=E_ABORT) {
        switch (EventCode) {
            case EC_COMPLETE:
                // Going back to the start of the clip
                g_pMediaPos->put_CurrentPosition(0);
            break;
            default:
            break;
        }
        g_pMediaEvent->FreeEventParams(EventCode, Param1, Param2);
    }
break;
// ...

The problem here, as I said, is that there's a noticeable lag when the video stops and starts again. It looks like EC_COMPLETE is not sent exactly when the video stops or maybe it is but put_CurrentPosition() takes some time to set the position back to 0. Anyway, the problem is that and I wonder if there's a solution to it.
Answer: There is no standard solution for looped playback, yet the task is not impossible and is doable with reasonable effort.
The wrong way is to achieve the desired behavior with standard graph/pipeline expecting some magic to perform a seamless seek operation on the upstream part of the graph. The graph streams data in a very efficient way and preloads the pipeline to play data accurately. However once you reached the end of the file, there is inevitable seek and state transition which involves a delay
You need either of the two (both approaches require development effort):

a smart custom filter which intercepts completion (end of stream) message and seeks the upstream part, or in case of small stream, buffers data entirely and continues seamlessly from internal buffer (good for small streams)
a two-graph design where one part is reading from file and sending data to another graph for playback, and the other graph handling endless playback from injected data; you can seek first graph normally without delay propagating to the other graph

Update. Since the media file is short (sort of animation perhaps), the item #1 above looks applicable. The goal is that buffering filter accepts everything up to completion, keeps this on internal buffer, and streams further from internal buffer.

Source -> ... (demultiplexer etc) -> Buffer -> Decompressor -> Video Renderer
Source -> ... (demultiplexer etc) -> Decompressor -> Buffer -> Video Renderer

Both options achieve the goal and you choose between the two depending on memory/speed requirements and preferences.
The best base for the Buffer filter is CBaseFilter.
Comment: Thanks, Roman. My file is only 4 Mb so I would like to create a buffer and seek to it just when EC_COMPLETE occurs. I suppose this link: http://msdn.microsoft.com/en-us/library/windows/desktop/dd758088(v=vs.85).aspx has enough information to guide me through this.
Comment: Source filter does not let you accept input. You need simply custom filter derived from `CBaseFilter`, see my update above. As I said there are many ways to do it, my point is that the way I suggested is actually the easiest.
Comment: Thanks again. Well, it's just a simple animation and it doesn't need any control or input. It just plays until the window is closed.
Comment: Yeah, so you accept frames 0, 1, ... N and on the output pin you stream  them 0, 1, ... N, and then frame 0 again as N+1 and so on. Same data, just new timestamps.


In Machine learning, how does normalization help in convergence of gradient descent?

Question: I have read in an article that normalization helps gradient descent to converge faster in machine learning. But I cannot understand why is that.
Any idea?
Comment: For a take on a loosely similar question that is both more general and more elementary see https://stats.stackexchange.com/questions/603855/why-data-scaling-in-range-0-1-is-important
Answer: Rescaling is preconditioning
Steepest descent can take steps that oscillate wildly away from the optimum, even if the function is strongly convex or even quadratic.
Consider $f(x)=x_1^2 + 25x_2^2$. This is convex because it is a quadratic with positive coefficients. By inspection, we can see that it has a global minimum at $x=[0,0]^\top$. It has gradient
$$
\nabla f(x)=
\begin{bmatrix}
2x_1 \\
50x_2
\end{bmatrix}
$$
With a learning rate of $\alpha=0.035$, and initial guess $x^{(0)}=[0.5, 0.5]^\top,$ we have the gradient update
$$
x^{(1)} =x^{(0)}-\alpha \nabla f\left(x^{(0)}\right)
$$
which exhibits this wildly oscillating progress towards the minimum.

Each step is wildly oscillating because the function is much steeper in the $x_2$ direction than the $x_1$ direction. Because of this fact, we can infer that the gradient is not always, or even usually, pointing toward the minimum. This is a general property of gradient descent when the eigenvalues of the Hessian $\nabla^2 f(x)$ are on dissimilar scales. Progress is slow in directions corresponding to the eigenvectors with the smallest corresponding eigenvalues, and fastest in the directions with the largest eigenvalues. It is this property, in combination with the choice of learning rate, that determines how quickly gradient descent progresses.
The direct path to the minimum would be to move "diagonally" instead of in this fashion which is strongly dominated by vertical oscillations. However, gradient descent only has information about local steepness, so it "doesn't know" that strategy would be more efficient, and it is subject to the vagaries of the Hessian having eigenvalues on different scales.
Rescaling the input data changes the Hessian matrix to be spherical. In turn, this means that steepest descent can move more directly towards the minimum instead of sharply oscillating.
Rescaling prevents early saturation
If you're using sigmoidal (logistic, tanh, softmax, etc.) activations, then these have flat gradients for inputs above a certain size. This implies that if the product of the network inputs and the initial weights is too small, the units will immediately be saturated and the gradients will be tiny. Scaling inputs to reasonable ranges and using small values for initial weights can ameliorate this and allow learning to proceed more quickly.

Effect of rescaling of inputs on loss for a simple neural network

A common method is to scale the data to have 0 mean and unit variance. But there are other methods, such as min-max scaling (very common for tasks like MNIST), or computing Winsorized means and standard deviations (which might be better if your data contains very large outliers). The particular choice of a scaling method is usually unimportant as long as it provides preconditioning and prevents early saturation of units.

Neural Networks input data normalization and centering

More Reading
In "Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift", Sergey Ioffe and Christian Szegedy write

It has been long known (LeCun et al., 1998b; Wiesler & Ney, 2011) that the network training converges faster if its inputs are whitened – i.e., linearly transformed to have zero means and unit variances, and decorrelated.

So you might also find that the network gets better results if you decorrelate the inputs in addition to applying zero mean and unit variances.
Following the citations provides more description and context.

LeCun, Y., Bottou, L., Orr, G., and Muller, K. "Efficient
backprop." In Orr, G. and K., Muller (eds.), Neural Networks: Tricks of the trade. Springer, 1998b.
Wiesler, Simon and Ney, Hermann. "A convergence analysis of log-linear training." In Shawe-Taylor, J., Zemel,
R.S., Bartlett, P., Pereira, F.C.N., and Weinberger, K.Q.
(eds.), Advances in Neural Information Processing Systems 24, pp. 657–665, Granada, Spain, December 2011
This answer borrows this example and figure from Neural Networks Design (2nd Ed.) Chapter 9 by Martin T. Hagan, Howard B. Demuth, Mark Hudson Beale, Orlando De Jesús.
Comment: This thing looks very similar to standardization? i.e. ($X- \bar{X}$) divided by the standard deviation?
Comment: @Kashan Zero mean/unit variance inputs is one method, but it's not the only one. See: https://stats.stackexchange.com/questions/421927/neural-networks-input-data-normalization-and-centering/422087#422087 inter alia.
Answer: Gradient descent pushes you towards the steepest direction. If there is scale difference between dimensions, your level curves will typically look like ellipses. If they were circular around the local optimum, the gradient would point towards the center, which is the local optimum; however since they are elliptical, the gradient points towards the steepest direction which might be very off if you consider points around the corner of a very long ellipse. For seeing the steepest directions, just draw an ellipse, pick some points on the boundary draw lines perpendicular to the boundary. You'll see that these directions can be irrelevant of the vector pointing towards the center.


How to edit multiple text lines in a .ini file using batch script

Question: I am very new to batch scripting but i would like to use it to automatically edit following   values in a .ini file
Example.ini (Please note that its a configuration file with lot of other entries before, after and in between these two entries.)
[Log]
Enabled = 0

[Support]
Line1 = ÿ
Lines = 1
SenderAddress = email@example.com

The updated values should look like this : ( [Log] Enabled = 1 & [Support] MailSenderAddress should become blank)
[Log]
Enabled = 1

[Support]
Line1 = ÿ
Lines = 1
SenderAddress =

Evenutally, I would like to include the code to update these entries in a master .bat script.
Could you guys please help me with this?
Comment: May be more than one line with `Enabled` or `SenderAddress` in the file?
Comment: Thanks a lot for your help. Yes that's right, There are more than one line with Enabled & SenderAddress in the file. That's why i have mentioned [Log] and [Support] blocks which are unique.Also, is it possible to update the same file instead of creating a new file?? Because this particular ini file is a part of a software and i do not want to create another file and play around with the file/folder structure of the software.
Comment: I suggest you to use `python` if possible. `ConfigParser` in `python` supports reading and writing `.ini` style files naturally and robustly.
Comment: Thanks Landys, i have got absolutely no clue of python, i would prefer a batch script because then i could include this code in our master script which basically installs the software by calling setup.exe. Could i do something like this with python and wouldn't it need some sort of service/app/software to be installed in windows? coz batch script can run on windows without the need of any sort of external app or software so we can offer this bat files to any of our clients without having to worry about whether it would run fine on their machine or not coz we know that it would work on windows.
Answer: @ECHO OFF
SETLOCAL
SET "logsection="
SET "supportsection="
(
 FOR /f "tokens=1*delims=" %%a IN (q25635303.txt) DO (
  FOR /f "tokens=1*delims== " %%b IN ("%%a") DO (
   SET repro=Y
   IF "%%c"=="" (
    SET "logsection="
    SET "supportsection="
    IF /i "%%b"=="[Log]" SET logsection=y
    IF /i "%%b"=="[Support]" SET supportsection=y
   ) ELSE (
    IF DEFINED logsection IF "%%b"=="Enabled" (SET "repro="&ECHO(Enabled = 1)
    IF DEFINED supportsection IF "%%b"=="SenderAddress" (SET "repro="&ECHO(SenderAddress =)
   )
   IF DEFINED repro ECHO(%%a
  )
 )
)>newfile.txt

FC q25635303.txt newfile.txt

GOTO :EOF

I used a file named q25635303.txt containing your data for my testing.
Produces newfile.txt
Begorrah, but it's difficult to work with a small target section in isolation, it is, it is.
The above should work - well, does work on your provided data, but without a fuller listing of the .ini file, it's not possible to be very positive.
The fc at the end is simply to compare the before and after version for verification. The sticking point that I have is whether the item which has a value assigned to it may include a space. Adjustments would be required if that is so...
Comment: Thanks a lot for your help. Yes that's right, There are more than one line with Enabled & SenderAddress in the file. That's why i have mentioned [Log] and [Support] blocks which are unique.Also, is it possible to update the same file instead of creating a new file?? Because this particular ini file is a part of a software and i do not want to create another file and play around with the file/folder structure of the software
Comment: The problem with edit-in-place is that when the output file is opened by redirection, it's cleared, so there's no input data available from that file. However, changing `q25365303.txt` in the `for... %%a...` line above to `'type newfile.txt'` (the single-quotes are **required**) buffers `newfile.txt` before it's opened for output, apparently curing the problem (at least, it did for me). Obviously, `copying` q25635303.txt to newfile.txt first allows you to test the changes. When testing is complete, remove the `copy` and substitute your chosen filename for `newfile.txt`.
Answer: Thanks guys but i am using find and replace instead. Much easier


CSS preloading doesn't work except on Google Chrome

Question: I am trying to preload CSS, it's working fine on Chrome but not on Firefox (nor Edge) and I can't find a solution anywhere.
I tested on Google Chrome 74.0.3729.131 and on Firefox 66.0.5 (and on Edge 41.16299.1004.0).
This is working fine everywhere.
<link rel="stylesheet" href="/style.css" media="all" type="text/css" />

But this won't work except on Chrome.
<link rel="preload" href="/style.css" as="style" media="all" type="text/css" onload="this.onload=null;this.rel='stylesheet'" />
<link rel="stylesheet" href="/style.css" media="all" type="text/css" />

I see the CSS is charged but not loaded so the javascript function won't work (and I want to find a real cause and solution instead of bypassing the problem using the onerror javascript event).
Comment: What do you mean "won't work"? Also, why are you changing the rel value? What are you actually trying to do?
Comment: The CSS is not applied when I say "won't work". I am trying to optimize the speed of the website by preloading files such as this CSS. So I've tried to follow [Google's web development documentation](https://web.dev/defer-non-critical-css) and this is working on their Google Chrome but on Mozilla Firefox: the CSS is applied only on Chrome.
Answer: Had a problem with Chrome Firefox last year the web browsers have different  software interpretation of the script on the doc
I had to rewrite script
Put your website through w3c val you could find an answer
https://validator.w3.org
JohnC
Comment: Hi You have a Inline script block between the external css file and another resource chrome ignores it Firefox does not  It could help to put in another css in subdomain rather than linking from main site to subdomain If it was my site I would rewrite scrip
Comment: I've just tried this but I have no error about it, the only errors I have are the missing src attributes for images because I use lazyload.
Comment: I don't care about the  rel attribute, I care about the CSS preloading, I know about the  rel attribute already and I am using it just fine.
Comment: What is the website Ma
Comment: It's as far as I can go hopefully some one else could give you better help and advice
Comment: Thank you for your help, I will have to focus on your answer and try and I will send my resume here.
Comment: It's the  x 4 try taking it out the script it could work JohnC
Answer: tested and seems to work well in Firefox and Chrome
removing  in 4 places in script
Answer: Per this solution, you need to declare the style using two lines, the 2nd line being a fallback for Firefox (2nd line):
<link rel="preload" href="/style.css" as="style" />
<link rel="stylesheet" href="/style.css" />

It is documented that preload is not supported on Firefox.


Clustering Circular area with different angles

Question: Let's say that I have a circular area and n objects deployed randomly in this area. I want to divide the circle into K groups from position of center such that objects in same area treated as member of same group. Moreover, K person assigned to visit K groups from the position of circle center (Specifically, one person for one group). Now, I want to group such a way that, traveling distance of a person for each group close to each other.
If objects are deployed uniformly, it's very easy. Only divide the area into equal angles gives me the desired results. But, for random deployment of objects, I could not divide the circular area (specifically, could not fix the angle) which gives me traveling distance for each person in each group which is close to each other
Comment: How is travel distance defined? As the distance of the shortest path that connects all objects of a group and the circle center? That alone is an NP-hard problem (travelling salesman)
Comment: Yes.distance of shortest path that connects all objects of a group and circle center.Using any well known heuristic, traveling distance can be obtained. But how divide group  such that traveling distance for each group close to each other when deployment is random.
Answer: As mentioned in the comments, the subproblem of finding the shortest path within a group is NP-hard. Hence, the overall problem is NP-hard. I will present a dynamic programming algorithm that can either solve the problem exactly (in exponential time) or approximate it with a heuristic (in polynomial time).
Both variants require a function f(g) that evaluates the travel distance of a group. In the exact variant, you need to solve TSP. In the approximate variant, you use a heuristic. You should try several heuristics and see which one fits best. For example, the area of the objects' bounding ring might be a good start (plus the distance of the closest object to the center).
The actual algorithm looks as follows: Calculate the angular position of each object and sort them with respect to this position. Also, calculate the distance to the center.
For now, we assume that the first group starts at the first object. Then, we want to find the grouping that minimizes the sum of f(g) over all groups. The states of the dynamic program are parameterized by the number of groups specified so far and by the object that belongs to the first next group. This makes a 2D table. You can easily initialize the first column by calculating f() for the resulting group:
       groups | 1           2  3  4  5  6 ... K
next object   |
--------------+------------------------
   o2         | f(o1->o1)
   o3         | f(o1->o2)
   ...        | ...
   on         | f(o1->on-1)
   o1         | f(o1->on)

Then, you fill the subsequent columns. For each entry, you have to compare the group to all groups in the previous column and find the one with the minimum sum:
entry(column i, object j) = min_k (entry(i - 1, k) + f(ok->j-1))

Actually, you don't have to calculate the entire column. You can leave entries at the beginning and end empty if they do not allow to fit in K groups. E.g. in the first column, you only need to calculate up to on-(K-1) because you have to leave K-1 objects unassigned in order to get a valid grouping. You may cache the results of f to avoid duplicate calculations.
After you filled the table, you're interested in entry(K, o1). Follow the path from this entry back to the start and you get the optimal grouping where the first group starts at o1. Do this for the first n-K objects as group starts and you get the overall optimum.
The time complexity of this algorithm is O(n^3 * K * T(f)) where T(f) is the complexity of calculating f(g).
Comment: Thanks a lot Nico.Actually,i am not so clear about your solution.can you explain more?I want to fix the angle for each group also. How can i fix the angle from your algorithm?If you explain more,it helps me much...
Comment: If you mean that you know the angles of the sectors, then this requires a different approach (because you have only one continuous-valued degree of freedom instead of several discrete-valued). About what parts are you having questions?
Comment: Actually,i want to distribute angle among each group such that every group contains the objects that visit a person from center to every group,and distance of person for every group close to each other.Suppose,I have K groups and divide the circle (360/K) angels.Now i want to adjust angel of K groups such that traveling distance of each group nearly equal...
Comment: Then you just need to adjust the objective function. Use variance or standard deviation instead of `entry(i - 1, k) + f(ok->j-1)`. However, time complexity will increase. Have you tried a simple approach like k-means?
Comment: yes.I tried k means.Its not gave the balance distance for every group because deployment is random.


Does the series converge: $\sum_2^\infty\frac{\log n}{n(\log \log n)^2}$

Question: Does the series $$\sum_2^\infty\frac{\log n}{n(\log \log n)^2}$$
converge?
The root and ratio tests are inconclusive, the integral test may be too difficult to apply. I've tried the limit comparison test with $\log n/n$ but that is also inconclusive since $$\frac{\frac{\log n}{n(\log \log n)^2}}{\frac{\log n}{n}}=\frac{1}{(\log \log n)^2}\to 0.$$
Comment: $\sum_n \frac{1}{n}$ diverges thus so does your series
Answer: Using the Cauchy condensation test, (cf Wikipedia), your series diverges.
The transformed series reads :
$$ \sum_{n} 2^n \frac{n}{2^n \log^2 n} = \sum_{n}\frac{n}{\log^2 n}$$
Remark : I interpreted $\log$ as a base two logarithm, which does not affect the result


How to set method onItemClick to open a Google Maps?

Question: I'm building an app, and I run on a problem with Google Maps. I wrote most of the code, but I don't how how to set that when user clicks on item(method onItemClick), in my case I have ListView on Firebase that is showing Tours of concerts, which you can see here:my tours listview to open a specific place and show it on map. For example, user clicks on Anaheim, CA concert and it shows where that place is. Thanks in advance.
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {

private static final int REQUEST_LOCATION_PERMISSION = 10;
private GoogleMap.OnMapClickListener mCustomOnMapClickListener;

private GoogleMap mGoogleMap;
private MapFragment mMapFragment;
@BindView(R.id.lvTours) ListView lvTours;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    this.initialize();
}

public void initialize(){
    this.mMapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.fGoogleMap);
    this.mMapFragment.getMapAsync(this);
    this.mCustomOnMapClickListener = new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            MarkerOptions newMarkerOptions = new MarkerOptions();
            newMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tour));
            newMarkerOptions.title("Tour");
            newMarkerOptions.snippet("It' was here!");
            newMarkerOptions.position(latLng);
            mGoogleMap.addMarker(newMarkerOptions);
        }
    };
}

@Override
public void onMapReady(GoogleMap googleMap) {
    this.mGoogleMap = googleMap;
    UiSettings uiSettings = this.mGoogleMap.getUiSettings();
    uiSettings.setZoomControlsEnabled(true);
    uiSettings.setMyLocationButtonEnabled(true);
    uiSettings.setZoomGesturesEnabled(true);
    this.mGoogleMap.setOnMapClickListener(this.mCustomOnMapClickListener);
}

private boolean hasLocationPermission() {

    String LocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
    int status = ContextCompat.checkSelfPermission(this, LocationPermission);
    if (status == PackageManager.PERMISSION_GRANTED) {

        this.mGoogleMap.setMyLocationEnabled(true);

        return true;

    }
    return false;
}

private void requestPermission() {
    String[] permission = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
    ActivityCompat.requestPermissions(MapActivity.this, permission, REQUEST_LOCATION_PERMISSION);
}

@OnItemClick(R.id.lvTours)
public void onClick()
{

}

}
Answer: Since you have your coordinates, you can build a LatLng(latitude, longitude) object
then you can move the camera of your map like this:
build a new camera position using CameraPosition.Builder() and then ask to your mGoogleMap to animate to that position:
CameraPosition position = CameraPosition.builder()
                .target(location)
                .zoom(16f)
                .bearing(0.0f)
                .tilt(0.0f)
                .build();
mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), null)

using that position you can even put a marker on the map:
mGoogleMap.addMarker(new MarkerOptions().position(position)
            .title("some title"));

Comment: You're welcome. If you need further information on how the camera works I highly suggest you to take a moment and read the official documentation [here](https://developers.google.com/maps/documentation/android-api/views)
Comment: This was helpful, but one problem remains. I have a method onItemClick, which you see at the end of my code. Now, I want whenever I click on any of Tours item, that is, list of objects, to show me a map with that place. Do you know how to do that?
Comment: hum, I'ts since I use Kotlin that I don't use butterknife but, if I didn't recall it wrong, you can do like that: `@OnItemClick(R.id.listView)
public void onItemClick(AdapterView adapter, int position) {
}`. having the position of your clicked element you'd be fine


Split existing LAMP to have a seperate webserver and database

Question: I have a LAMP server currently running. It's been falling over a lot because there is too much stress on the DB. I'd like to split the DB out of there and run it on a separate machine. I have about 100 websites currently running on the server already.
Here's my plan:
1. setup a new server, install mysql on the server
2. on the webserver, open the port 3306 to be an iptunnel to 3306 on the new server
Is this advisable or would it be better to go through and manually change the database server in the scripts to the other one?
If I were to do that, presumably I'd have to adjust all the users in the database to allow access from the webserver now right?
Thoughts?
Answer: You've missed the important bit: transfer all the data across.  Doing this without downtime is difficult (though not impossible, especially if you're willing to wade into the murky world that is MySQL multi-master replication), if you're willing to survive some downtime you can either do it in one big hit, or database by database (which if you've got lots of separate databases can be a good way to test your migration plan with a small, low-value site rather than blowing everything up in a giant mess).
As far as naming goes, the answer is service CNAMEs -- a CNAME 'db' or 'mysql' or something, that points to your database server.
If you're doing a one-big-cutover (or you only have one database), setup this CNAME now and point to 127.0.0.1, and start changing all your scripts to use the CNAME.  Search-n-replace or whatever is needed (also take the opportunity to centralise this sort of configuration if -- as it sounds like -- you've hard-coded your DB info in lots of separate scripts, in case you have to do something like this again in the future), but without actually moving any data to the new server.  Once everything's running through the CNAME, then you can start moving things around, and it's a lot easier to change the CNAME at the end of the maintenance rather than having to change a thousand scripts while in a maintenance window.


How to limit flagging of articles to users with sufficient userpoints using Rules?

Question: I am using User Points and Rules. Users earn points for publishing and commenting but are deducted points for flagging their articles for announcement on the front page (a kind of a fee). The fee per announcement is say 150 points.
Obviously, if they don't have at least 150 points, they should not be able to flag. So I need a rule that would check if the author has at least 150 points and if not - block the flagging action with an error message: Sorry, you don't have enough.
Yet, I just can't figure out how to set up such a rule. Any help would be highly appreciated.
Comment: Hi,did you find a solution?If yes could you post it here?thanks
Answer: Here are the headlines of a possible solution to answer this question:
Step 1 - Create a designated role
Create a new "role" corresponding to users with (say) 150 points, assume you name the role UsersWith150Points.
Step 2 - Limit access to the flag
Secure the access to the flag to users with role UsersWith150Points.
Step 3 - Create some Rules logic
Any time a user gains points, use a rule to check if the user has at least 150 points. If so, have the Rules module grant access to the UsersWith150Points role.
Similarly, if a user looses points, also use a rule to check if user no longer has at least 150 points. If so, have the Rules module remove access to the UsersWith150Points role.
Sounds easy and pretty forward ... except ... there is no (easy) solution to have a Rules Condition to "check the current user points for a user" (unless you're willing to use custom PHP logic in your Rules Condition). However, the clue to make this rule work anyhow, is to use as a very first Rules Action "Load user points of a user". For an example rule, which is close that what you'd need, refer to "How to create rule to change user role based on points (using User Points module)?": you'd only have to add a Rules Action to grant or remove some role (and adapt the user points threshold to your '150').


Alter product variation view

Question: I want to alter product variation view and want to display a new form which value depends on variation price. I can add the field to the node using hook_node_view_alter() but i want to add it to the product variation right after the price field. I just need to display an integer dependent of the price.
Any help with this?
Thank you
Answer: You can try hook_entity_view_alter() API function provided by Drupal Core to alter any entity.
If you want to alter how the entity will look, you can also try using Display Suite or Panels module which are used to override the display.
Comment: I have tried that but can not add field in the product variation only on the node. I want my field to be right next to price and i can not do that with entity_view_alter
Comment: In this case you can go with Display Suite module. It will allow you to attach a layout to particular display under Manage Display in Product Type, after which you can add fields, custom block, Code Field, etc. in your display, which will be visible on node (make variation field display as **render entity**). Check out [Display Suite module documentation](https://www.drupal.org/node/644662) for more details on how to customize the display of entity.

Alter product variation view


Teradata SQL - Adding columns of repeating values to existing table

Question: I have a dataset with 5000 records.  I want to add 3 columns to this dataset: 1st one with values from 1 to 5, 2nd with values from 1 to 4, 3rd with values from 1 to 3 such as follows -
record_id   ser_num5    ser_num4    ser_num3
1           1           1           1
2           2           2           2
3           3           3           3
4           4           4           1
5           5           1           2
6           1           2           3
7           2           3           1
8           3           4           2
9           4           1           3
10          5           2           1
11          1           3           2
12          2           4           3
13          3           1           1
14          4           2           2
15          5           3           3
16          1           4           1
17          2           1           2
18          3           2           3
19          4           3           1
20          5           4           2
….
5000

How can I do this in Teradata SQL? I've tried the following code but it didn't work -
CREATE SEQUENCE Test.SerNum5
    AS Int
    START WITH 1
    INCREMENT BY 1
    MINVALUE 1
    MAXVALUE 5
    CYCLE
;

SELECT NEXT VALUE FOR Test.SerNum5;

Also, is there anyway I can somehow merge this piece into an existing "select columns" statement if i can't make the create sequence to work. Thanks for any help!
Answer: The easiest way is with arithmetic on the id:
select id,
       ((id - 1) mod 5) + 1 as sernum_5,
       ((id - 1) mod 4) + 1 as sernum_4,
       ((id - 1) mod 3) + 1 as sernum_3

If the id is no really contiguous, you can use row_number() instead:
select id,
       ((row_number() over (order by id) - 1) mod 5) + 1 as sernum_5,
       ((row_number() over (order by id) - 1) mod 4) + 1 as sernum_4,
       ((row_number() over (order by id) - 1) mod 3) + 1 as sernum_3


Max Width not working for mobile view, I still get the desktop site version

Question: can someone please open the site www.abeautiful.vision and let me know why the max width media in css is not working? Is it because the mobile opens the desktop version of the site? How do I overcome this? Please let me know. Thanks.
Answer: I forgot to add :
<code><meta name="viewport" content="width=device-width">
</code>
to my html.
Remember to do this guys!


Upstart and pre/post scripts

Question: I run into an issue with upstart where I want to update an init config, but just restarting the job doesn't apply the changes.
For example:

I've got job xyz running
I modify the /etc/init/xyz.conf to do something in pre-stop.
The job gets restarted with restart xyz
pre-stop part is not executed

I tried reloading the config with initctl reload-configuration, but it didn't have any effect. If I manually stop and start the job in two separate steps, things work as expected.
Answer: According to the documentation, the pre-stop stanza is only executed before a stop command, not during a (warm) restart.
Description: Command executed when a job in running state gets stopped (initctl stop or stop on event).

Depending on what you are trying to do you may not be able to avoid this behavior.

Upstart and pre/post scripts


Showing prediction output in Keras

Question: I am doing a image classification with CNN using Keras. The training process was so far so good. But when it comes to the prediction, I couldn't figure out to extract correct prediction results out of numpy array from predict(x). It is binary classification task but I used softmax layer at the end purposefully. The original labels should look like this:

[0 1 0 1 1 1 0 0]

But I have this from predict:

[[  1.00000000e+00 0.00000000e+00]
  [  1.00000000e+00 1.13929331e-32]
  [  1.00000000e+00   0.00000000e+00]
  [  1.00000000e+00   1.51848069e-28]
  [  1.00000000e+00   3.70465143e-38]
  [  1.00000000e+00   5.44319748e-37]
  [  1.00000000e+00  0.00000000e+00]
  [  1.00000000e+00   0.00000000e+00]]

Apparently, there is a pattern in the output with ones and super small numbers that resembles the real labels although these small numbers should be greater than the ones before them. How can I transform it to look like the original one.
Answer: If you are doing binary classification, each row should give you probability on two classes. In other words, each row should sum up to 1.0.
To get the prediction label, for each row, find the max probability and return the index. Can be done using numpy.argmax
https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.argmax.html
Comment: Yes, if I do numpy.argmax(output, axis=1) it gives
[0, 0, 0, 0, 0, 0, 0, 0], because apparently in each row of prediction matrix value of 0th index is always greater the second one and always equals to 1. I don't know why but there is a pattern in output matrix which resembles the original answer.
Comment: ok, I see your question, are are asking the difference between 0 and a super small number, like $1.1\times 10^{-32}$. With this detail, it is hard to answer why this happen for me.

Showing prediction output in Keras


Why do we require ordinality of the response with respect to the predictors in the proportional odds model

Question: I've recently been reading about ordinal regression with a focus on the proportional odds model in the book regression modelling strategies. The author states "A basic assumption of all commonly used ordinal regression models is that the response variable behaves in an ordinal fashion with respect to each predictor. Assuming that a predictor X is linearly related to the log odds of some
appropriate event, a simple way to check for ordinality is to plot the mean
of X stratified by levels of Y . These means should be in a consistent order."
I've had difficulty understanding why we need the response to be ordinal with respect to the predictors, the  response should still be able to be a valid ordinal response without this assumption. As an example, suppose that I wanted to model the severity of symptoms of a disease with respect to age, using a proportional odds model. The severity of symptoms have the following categories.

mild symptoms
intermediate symptoms
severe symptoms

Suppose the population is relatively old and that mostly young people get intermediate symptoms and mostly old people get severe symptoms. Then plotting the average age stratified on the symptoms level would reveal a V-shape and the severity of symptoms would not be consider ordinal with respect to age. However the severity of symptoms have a clear order.

Does this mean that we cannot use age as a predictor and why? Is it because age in some sense poorly explain the ordinality of response?
Where in the model do we get this assumption?

Thanks in advance!
Answer: I'm author of RMS.  The ordinality assessment is a quick and semi-clean way to look at model assumptions.  Mean age stratified by levels of Y is related to score residuals, and score residuals are diagnostic tools for assess the proportional odds (PO) assumption if you are using the PO ordinal logistic model.  A V-shaped relationship in predicting X from Y indicates trouble about to happen when predicting Y from X in a model that assumes parallelism (constant slope; PO).
None of this means you cannot use age in the model, but if age turns about to not act in PO you many need a Peterson-Harrell (1990) partial proportional odds model as implemented in the R VGAM or rmsb packages.
However a better way to go about all this is to assess the impact of making the PO assummption, for which a newer function in the R rms package called impactPO is helpful.  This approach is written up in a blog article here.
Another place to discuss RMS questions is at datamethods.org/rms .  If you go to the ordinal regression chapter link near the top of that page you'll see other discussions about ordinal regression.
Comment: Thank you for an insightful answer and for the resources. I will have to look into score residuals. The link does not work and the reason seems to be that it's missing an m in com.
Comment: I read the post and will definitely try this approach. I also did not know about the PO models relation to the Wilcoxon test which was a nice surprise for me. The PO model appears to be more interesting than I first thought. Thanks for the help.
Comment: Thanks.  I fixed the link.  I suggest not looking into score residuals as much as following the workflow in the link.


the page freeze when uploading file image using ajax

Question: I created a ajax function for uploading file images, everything works except there's an ugly part where the page freezed at the process (ajax file image processing submission), any ideas, help, suggestions, clues? below is my code reference.
$("#form_image_file_submit").submit(function(e){
    var this_current = $(this);
    var formData = new FormData(this_current[0]);
    $.ajax({
     url : this_current.attr("action"),
     data: formData,
     type: 'post',
     cache: false,
     async: false,
     complete: function(data){
        alert(data);
    }
});

Comment: Have you tried to change async to true? You're saying don't let the page do anything until this request is complete, which probably isn't what you want.
Comment: remove the async attribute
Answer: You have async: false. Change it to true
Answer: Use async:true or remove it.

async (default: true)
  Type: Boolean
  By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

Ajax Docs


Invertibility of $A+aI$

Question: Let $A$ be an invertible matrix, $I$ the identity matrix and $a$ a scalar. How can we find if $(A+aI)$ is invertible or not? How does it relate to $a$?
Comment: $A + aI$ is not invertible if and only if $-a$ is an eigenvalue of $A$.
Comment: What can you say about $\det(A+aI)$ if $-a$ is an eigenvalue of $A$?
Comment: Welcome to Math.SE.  Are you familiar with the notion of an eigenvalue?  As the Comments by others suggest, it is a pivotal notion for finding "if $(A+aI)$ is invertible or not".
Answer: Irrespective of whether $A$ is invertible, $A + aI$ will be invertible if and only if $\det(A + aI) \not= 0$. This determinant is a polynomial in $a$, and is thus nonzero for all but finitely many numbers $a$.

Invertibility of $A+aI$


Hudson Subversion Release Manager Plug-in

Question: Has anyone ever tried the Hudson Subversion Release managerplug-in?
I don't see the releases link shown in the page after installing the plug-in.
Answer: Under the configuration of the job, you need to set up the following:

Change your Source Control Management setting to "Subversion Release" (not just Subversion!)
Check "This build is parameterized", and add a "List subversion tags". Point this to path on your SVN server which lists all of your tags.
Check "Use Subversion Release Manager"
Answer: This plugin only works with Non parameterized build , if you have amy pre SCM build script or any other build parameter passed as part of the svn url , nothing comes up in the release link
Answer: Restart Jenkins on Linux will see the Releases link, my problem is it clocks forever when I click the link, nothing happens.


How to pass dynamic file location in Form API?

Question: my requirement is to upload files to specific folders. How can I achieve this by using form api. How can I modify below code such that upload_location should be dynamic. Uploaded file should save into the Folder name provided by the user. I tried below code but not worked.
#submit element is not calling custom_document_submit function.
 $form['folder_name'] = array(
      '#type' => 'textfield',
      '#title' => t('Folder Name'),
  );
  $form['document'] = array(
    '#type' => 'managed_file',
    '#upload_validators' => array('file_validate_extensions' => array('xml')),
    '#upload_location' => 'public://',
    '#submit' => array('custom_document_submit'),
    );
function custom_document_submit($form, &$form_state){
  $destination = $form_state['values']['folder_name'];
  $validators = array();
  $file = file_save_upload('document', $validators, 'public://'.$destination);
}

Comment: `managed_file` does not support `#submit`
Comment: Ohh thank you. May I know how can I achieve that. #upload_location should be dynamic one.
Comment: How about using Form Ajax to rebuild the form with the updated `#upload_location` on `managed_file`?
Comment: If its succeed that will be great.. May I know how can I use form ajax in my case?
Comment: I will answer you, wait.
Answer: I would suggest using ajax to update the #upload_location on demand.
However, ajax on managed_file element is quite tricky. Because managed_file has its own ajax handling for uploading file. It only rebuilds the file element itself and returns lack of data from other fields during during file upload ajax. So it need to be fixed in some hacky way
Example code:
function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];
  $values = &$form_state['values'];

  $form['folder_name'] = array(
    '#type' => 'textfield',
    '#title' => t('Folder Name'),
    '#submit' => array('mymodule_custom_form_folder_name_submit'),
    '#ajax' => array(
      'callback' => 'mymodule_custom_form_folder_name_ajax',
      'wrapper' => 'edit-file-ajax-wrapper',
      'event' => 'keyup',
    ),
  );

  // HACK: manually construct the folder_name value.
  // $form_state['values'] is empty for other field in file upload ajax
  // because it only rebuild the element rather then the whole form.
  if (!isset($values['folder_name']) && !empty($input['folder_name'])) {
    $values['folder_name'] = form_type_textfield_value($form['folder_name'], $input['folder_name']);
  }

  $form['file'] = array(
    '#type' => 'managed_file',
    '#title' => 'File',
    '#disabled' => empty($values['folder_name']) && empty($input['folder_name']),
    '#upload_validators' => array('file_validate_extensions' => array('jpg')),
    '#upload_location' => !empty($values['folder_name']) ? 'public://' . $values['folder_name'] : 'public://',
  );

function mymodule_custom_form_folder_name_submit(&$form, &$form_state) {
  unset($form['file']['#disabled']);
  $form_state['rebuild'] = TRUE;
}

function mymodule_custom_form_folder_name_ajax(&$form, &$form_state) {
  return $form['file'];
}

Comment: Hi, I am getting disabled file upload on the page. One more thing is I am doing this thing on admin page. So form function I cant use I guess. I have written ur  form elements inside mymodule_admin() function.
Comment: @Suraj Yes, I make it disabled by default. You can remove the `#disabled` code if you don't want this feature. And, if you are using form API to construct form in admin page. It should work.
Comment: Thanks for your information. I am bit new to this thing. How can i use form api in admin page. I know only hting is to display in admin page we have to use mymodule_admin function. Whatever i will write inside this function that will display on admin page. So where can i use form api here.
Comment: @Suraj You can read [Creating a module configuration (settings) page](https://www.drupal.org/node/206761) first.


Codeigniter Form validation problem

Question: Please please please can someone help me
<code>$this->load->library('form_validation');
  $this->load->helper('cookie');

  $data = array();

  if($_POST) {
   // Set validation rules including additional validation for uniqueness
   $this->form_validation->set_rules('yourname', 'Your Name', 'trim|required');
   $this->form_validation->set_rules('youremail', 'Your Email', 'trim|required|valid_email');
   $this->form_validation->set_rules('friendname', 'Friends Name', 'trim|required');
   $this->form_validation->set_rules('friendemail', 'Friends Email', 'trim|required|valid_email');

   // Run the validation and take action
   if($this->form_validation->run()) {
    echo 'valid;
   }
  }
  else{
   echo 'problem';
  }
</code>
Form validation is coming back with no errors can cany one see why?
Answer: Is it actually echoing 'valid'?  (you're missing an apostrophe there, btw)
The code you show will only echo 'problem' when $_POST is false, not when validation fails.
Without knowing more, it may be as simple as:
<code>// Run the validation and take action
if($this->form_validation->run()) {
 echo('valid');
} else {
 echo('invalid');
}
</code>
Answer: Try like this without checking if $_POST is set - not really needed:
<code>//validation rules here
//
if ($this->form_validation->run() == TRUE) {
     //do whatever that shall be run on succeed
} else {
     $this->load->view('form'); //load the form
}
</code>
Read more about the controller part here

Codeigniter Form validation problem


Conics in real projective plane and application to Poncelet's theorem

Question: I know that all  conics (ellipse, hyperbola and parabola) are equivalent in real projective plane. But when we  are drawing things from projective plane on piece of paper, are we still allowed to draw hyperbolas and parabolas as we know them in $\mathbb{R}^2$?
And if so. I am trying to figure out Poncelet's  theorem.
It states: "Let  K and C be nondegenerate conics in general position (two tangents from intersection points to both conics are different for all intersection points). Suppose there is an n-sided polygon inscribed in K and circumscribed
about C such that none of its vertices belongs to C (in the case when K and C intersect
or meet). Further suppose there is an (n − 1)-sided polygonal chain with vertices
on K such that all its sides are tangent to C and none of its vertices belongs to C.
Then the side, which closes the polygonal chain, is also tangent to C."
If I draw hyperbola $x^2 - y^2 = 1$ and ellipse $x^2+3y^2 =4$, then  we can find 4-gon inscribed in ellipse and circumscribed in hyperbola. This can not be done if we take one of intersections as vertex of 4-gon or some other points on ellipse, but the theorems assumptions take care of that. Since this can be done for hyperbolla and ellipse, it sholud be possible for two ellipses that have 4 common points, lets say $4x^2+y^2=4$ and $x^2+4y^2=4$. But I dont see how is this possible.
Another thing. Let's say we do not have to have conics in general case. So we  can have hyperbola $x^2 - y^2 = 1$ and ellipse $(x+1)^2+4y^2 =4$ (they have same tangent in (1,0)). It seems obvious (in this case), that we can not find such polygon and polygonal chain as Poncelet's theorem states. But is this an exception or a rule? How can we be sure, that if conics are not in general case, Poncelet's theorem can not be  applied? (Therefore it is not necessary to say they are in general position.)
Answer: Poncelet's closure theorem (porism) states that if there is an $n$-sided
polygon of a certain kind, then there are an infinite
number of them. For any given pair of conics and integer
$n\ge 3$ there may not be an $n$-sided Poncelet polygon.
For example, for two non-intersecting circles in the plane
there is a certain condition on the radii and distance
between the centers that must be satisfied for a triangle
to be inscribed in one circle and circumscribed around the
other.
The theorem does not state that it is always possible
to draw an $n$-sided polygon that is inscribed in one of
the conics and circumscribed around the other conic. It
states that if it is possible, then it is possible to
do so with any starting point. There may be some obvious
exceptions if the conics intersect each other. Also, the
theorem may not always hold in the real plane.
The Wikipedia article Conic section states:

... That is, there is a projective transformation that will map any non-degenerate conic to any other non-degenerate conic.
The three types of conic sections will reappear in the affine plane obtained by choosing a line of the projective space to be the line at infinity. The three types are then determined by how this line at infinity intersects the conic in the projective space. In the corresponding affine space, one obtains an ellipse if the conic does not intersect the line at infinity, a parabola if the conic intersects the line at infinity in one double point corresponding to the axis, and a hyperbola if the conic intersects the line at infinity in two points corresponding to the asymptotes

Thus, in the real projective plane there is only type of non-degenerate conic,
but when passing back to the affine or Euclidean plane by an arbitrary choice of
a line "at infinity", the three different types appear. Also, in the Euclidean
plane, the circle is a special case of an ellipse.


If $f$ is continuous, nonnegative on $[a, b]$, show that $\int_{a}^{b} f(x) d(x) = 0$ iff $f(x) = 0$

Question: If $f$ is continuous, nonnegative on $[a, b]$, show that $\int_{a}^{b} f(x) dx = 0$ iff $f(x) = 0$
"$\Rightarrow$" Assume by contradiction that $f(x) \neq 0$ for some $x_0 \in [a, b]$. Without loss of generality, assume that $f(x_0) > 0$. Since $f$ is continuous, $\exists \delta > 0$ such that $f(x) > 0,  \forall x \in (x_0 - \delta, x_0 + \delta)$. Since $f$ is continuous on $[a, b]$, then it is Riemann integrable. Therefore $\int_{a}^{b} f(x) dx = \sup L(f, p)$ for some partition $p$. Now what I want to do is to show that the lower sum, $L(f, p) > 0$, in that case its supremum is $>0$, and that contradicts the condition that $\int_{a}^{b} f(x) dx = 0$. However, I don't know how to articulate it.
"$\Leftarrow$" If $f(x) = 0, \forall x \in [a, b]$, then $\int_{a}^{b} f(x) dx = \int_{a}^{b} 0 dx = 0$
Comment: "Without loss of generality"... You might want to note that $f(x_0)\geq 0$ and $f(x_0)\neq 0$ is equivalent to $f(x_0)>0$.
Answer: Using continuity of $f$ at $x = x_0$, you can find an open interval $(x_0-\delta,x_0+\delta)$ such that $|f(x)-f(x_0)| < \dfrac{f(x_0)}{2} \to f(x) > \dfrac{f(x_0)}{2} \to \displaystyle \int_{a}^b f(x)dx \geq \displaystyle \int_{x_0-\delta}^{x_0+\delta} f(x)dx > \displaystyle \int_{x_0-\delta}^{x_0+\delta} \dfrac{f(x_0)}{2}dx = \delta\cdot f(x_0) > 0$
Answer: I would work not with the lower Riemann sums but with the upper Riemann sums instead. Here is an outline. Without loss of generality assume there is an $t$ in $(a,b)$ instead of $[a,b]$ with $f(t)>0$. Use continuity of $f$ to find a neighborhood $(c,d)$ such that $(c,d)\subset (a,b)$ and $f(x)>\frac{f(t)}{2}$ for all $x$ in $(c,d)$. Now given any partition $P=\{a=p_1,\dots,b=p_n\}$, let $i$ be such that $p_i<c\leq p_{i+1}$ and let $j$ be such that $p_{j-1}<d\leq p_j$. The upper Riemann sum on $P$ is then bounded below by $(d-c)*\frac{f(t)}{2}>0$, so the integral is bounded above by $(d-c)*\frac{f(t)}{2}$.


What happens if a receiver is beyond the end zone in football?

Question: I suspect that this is just "out of bounds", but what happens when a receiver catches a pass and has two feet out of the end zone at the far end? Is this just out of bounds or is there more forgiveness in the end zone?
Answer:
What happens if a receiver is beyond the end zone in football? I suspect that this is just "out of bounds"

Your suspicions are accurate.

What happens when a receiver catches a pass and has two feet out of the end zone at the far end?

A player who catches a pass and has two feet out of the end zone at the far end had either touched a boundary line or touched outside a boundary line, and thus, is out of bounds.

Rule 3, Section 22, Article 1 in the NFL Rule Book addresses this (emphasis mine).

A player or an Official is Out of Bounds when he touches:
(a) A boundary line; or
(b) Anything other than a player, an official, or a pylon on or outside a boundary line.

Rule 2, Section 12, Article 4 in the NCAA Football Rule Book addresses this (in a clearer fashion, in my opinion).

Boundary Lines
ARTICLE 4. The boundary lines are the sidelines and the
  end lines. The area enclosed by the boundary lines is "in bounds,''
  and the area surrounding and including the boundary lines is "out of
  bounds.''
Answer: edmastermind29's answer is correct, save an exception.
If a receiver catches the ball but is carried out by a defender before he can land both feet inbounds, the pass is complete.
Rule 8, Section 1, Article 3, Item 6 in the NFL Rule Book addresses this.

Carried Out of Bounds: If a player, who is in possession of the ball, is held up and carried out of bounds by an
  opponent before both feet or any part of his body other than his hands touches the ground inbounds, it is a completed
  or intercepted pass.

NCAA (college) rules are slightly different--the player needs only one foot to make contact inbounds for the completion.
Rule 2, Section 4, Article 1 of the NCAA Football Rulebook:

Player Possession: The ball is in player possession when a player has the ball firmly in his grasp
  by holding or controlling it while contacting the ground inbounds.

Regarding the Carried Out of Bounds rule from the NFL, I could not find any references that suggests this also applies in college.
Comment: There is a distinction between "carried" and "pushed".  If a receiver is pushed out before he can get his feet in bounds, the pass is incomplete.  If he is carried by a defender out of bounds then the pass is complete.  The push rule is relatively new.  A push out used to be considered a completion.
Comment: @diggers3 wasn't pushing out a completion at one point, before the rule changed?
Comment: @TrevorD I see the rules digest, but the force out rule was changed in 2008.  I don't know why the digest doesn't seem to have been updated. [NFL Rule Changes 2008](http://www.nfl.com/news/story/09000d5d809f6279/article/new-nfl-rules-for-2008)  The rule only applies to literally carrying someone, not pushing (or forcing) them out of bounds. [Breif explanation of the rule change](http://www.arrowheadpride.com/2008/4/2/16112/65451)
Comment: @edmastermind29 [Some more discussion](http://www.pro-football-reference.com/blog/?p=197) *"In college, where they don't have a similar rule, wide receivers have been carried out of bounds occasionally when two defenders who were trying to cover them simply caught them while they were in the air."* ... *"the rule shows a willingness to delve into speculative matters to ensure fairness. It's about fault; if the receiver clearly makes the catch and clearly would have landed in-bounds, then he shouldn't be penalized because of something out of his control"*
Comment: I've never heard about this "carry" clause until now.  If a receiver catches the ball while in the air in the end zone, it seems it'd be much easier for a defender to push him out of bounds.  I don't know why a defender would ever try to catch him and carry him out of bounds.
Comment: @pacoverflow If he's 10 yards from the boundary, it'd be a lot easier to carry him than to push him.
Comment: @edmastermind29 No idea how feasible - carrying an opposition player does occasionally happen in rugby, but maybe not 10 yards. It was just what popped into my head in response to "why would they even *have* that rule?"
Comment: Also, let's not lose sight of the question of, "what happens when a receiver catches a pass and has two feet out of the end zone at the far end?" The initial answer to address the exception was fine, but the added detail is going off tangent.
Comment: @edmastermind29 agreed, thats why I wouldn't add it to an answer, but sometimes it is nice to expand on things, especially rules.  There are many little things within the rules that someone else may be wondering about.
Comment: @diggers3 While not explicitly stated in the rulebook, the [NFL's Rules Digest](http://www.nfl.com/rulebook/forwardpass) states `If a receiver would have landed inbounds with both feet but is carried or pushed out of bounds while maintaining possession of the ball, pass is complete at the out-of-bounds spot.` My NCAA edits were included for just the reason you mentioned.
Comment: @Rawling how feasible or reasonable is that?
Comment: @Rawling Right. It's heads up thinking, but it does not seem to be practical in a general sense.
Comment: @Rawling After watching [this play](https://nesncom.files.wordpress.com/2014/11/jimmy-graham.gif?w=600&h=331), would have it been "a lot easier" to carry him out of bounds, considering he is 10 yards from the boundary and there are two plus defenders around him?
Comment: @edmastermind29 Easier to catch and carry him than to push him from there, yes.
Comment: @Rawling The point I was trying to make is that I would think the player who catches the ball would squirm enough such that the defenders carrying him would have an (already) arduous task doing so. To the contrary, it would take one gigantic push to force him out of bounds from 10 yards away.


'MyhomePage({Key key, this.title}) : super(key: key);' in Flutter - what would be a clear explanation with an example?

Question: In Flutter, what would be a clear explanation with an example?
My confusion is about key, as in the code below.
MyHomepage({Key key, this.title}) : super(key: key);

Comment: https://stackoverflow.com/questions/50080860/what-are-keys-in-the-stateless-widgets-class
Comment: Can you explain what you don't understand?
Answer: The code is the constructor of the MyHomepage widget.
{Key key, this.title}

It declares two optional named parameters (optional named because of {}) where

the first is of name key with type Key
the second is of name title with the type of the field this.title and automatically initializes this.title with the passed value. This is nice syntactic sugar that saves some writing.

: starts the initializer list.
The initializer list allows some to execute some expressions before the call is forwarded to the constructor of the super class.
When a class is initialized, read access to this is forbidden until the call to the super constructor is completed (until the body of the constructor is executed - in your example the constructor has no body).
The initializer list is often use to validate passed parameter values with assert(key != null) or to initialize final fields with calculated values (final fields can't be initialized or updated later).
super(key: key) forwards to the constructor of the super class and passes the parameter key passed to MyHomepage to the super constructors key parameter (same as for MyHomepage({Key key})).
Comment: for those who don't know what's the meaning of `super` keyword. `super` is just like `this` keyword that indicates to the parent class.
another point is once we use inheritance with `extends` keyword; constructor of child class will be executed after parent's constructor execution.
Answer: Thanks for Günter's detailed explanation which helped me at the very beginning. Here I would like to explain the background for this question, and especially the punctuation as syntax a little bit.
The mentioned line of code,
MyHomepage({Key key, this.title}) : super(key: key);

should come from the auto-generated Flutter application boilerplate.
The complete context is:
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

For me, the weird punctuation (curly brackets{ } and two colons :) is what prevented me from comprehending its syntax.
Curly brackets of {Key key, this.title}: is the syntax for declaring optional parameters while defining function in Dart.
The first colon of MyHomepage(...) : super(key: key) is a separator that specifies the initializer list (super(key: key)) of constructor function MyHomepage(...)
The second colon within super(key: key) is the way how you pass a parameter to a named function (super() in this case).

For example, a function enableFlags is defined as follows

void enableFlags({bool bold, bool hidden}) {...}

To call the function, the way Dart passes parameter to the function, is by declaring parameterName before value, separated with colon :, which is safer for developer than the Pythonic way. The counterpart syntax in Swift should be external parameter.

enableFlags(bold: true, hidden: false);

I wish this could help.
All the definitions and examples can be found in Dart's official document.
Comment: I'm new to Flutter/Dart, but from Dart docs I understood `{Key key, this.title}` is the syntax for declaring named parameters not optional parameters (aldo it's true that named parameters are optional by default).
What I'm confused about is the use of `this.title` in a named parameter declaration. As I understant it, this syntax declares a parameter named `title` and also initialises the `title` property of the object with the value passed for the `title` parameter.
Comment: @Sorin I have to say  that the latter is really an ugly syntax even though it looks like more brief.
Answer: Flutter uses Keys for a lot of things inside the framework. Since your widget extends StatelessWidget or StatefulWidget, this is the way of your widget having a key so that the framework knows what to do with it (the super function is passing the key to the superclass widget - which can be understood by the framework).
Except for that is only Dart syntax (which is awesome by the way).
You can learn more about Keys here: https://www.youtube.com/watch?v=kn0EOS-ZiIc
Another example is the testing framework. Flutter driver needs a key to know which widget to look for and interact with it. With this syntax your widget will have a key and it will work!
Comment: That video, while not perfect, is certainly useful for someone new to flutter trying to figure out what keys in widgets are all about.  Thanks!
Answer: just look my pictures including two cases :


Been using rand.int for a while and seeing unexpected results

Question: I've been running some code for an hour or so using a rand.int function, where the code models a dice's roll, where the dice has ten faces, and you have to roll it six times in a row, and each time it has to roll the same number, and it is tracking how many tries it takes for this to happen.
success = 0
times = 0
count = 0
total = 0

for h in range(0,100):
    for i in range(0,10):
        times = 0

        while success == 0:

            numbers = [0,0,0,0,0,0,0,0,0,0]

            for j in range(0,6):

                x = int(random.randint(0,9))
                numbers[x] = 1

                count = numbers.count(1)

            if count == 1:
                success = 1
            else:
                times += 1

        print(i)
        total += times
        success = 0

    randtst = open("RandomTesting.txt", "a" )
    randtst.write(str(total / 10)+"\n")
    randtst.close()

And running this code, this has been going into a file, the contents of which is below
https://pastebin.com/7kRK1Z5f
And taking the average of these numbers using
newtotal = 0
totalamounts = 0

with open ('RandomTesting.txt', 'rt') as rndtxt:
    for myline in rndtxt:              ,
        newtotal += float(myline)
        totalamounts += 1

print(newtotal / totalamounts)

Which returns 742073.7449342106. This number is incorrect, (I think) as this is not near to 10^6. I tried getting rid of the contents and doing it again, but to no avail, the number is nowhere near 10^6. Can anyone see a problem with this?
Note: I am not asking for fixes to the code or anything, I am asking whether something has gone wrong to get the above number rather that 100,000
Comment: @Gergo Pseudorandom numbers are perfectly acceptable in statistical contexts, just not for crypto.  PRNGs are preferred for non-crypto purposes specifically because of their speed and reproducibility (which useful for both debugging and confirmability by independent researchers) while being indistinguishable from real randomness based on statistical testing.  Use of a PRNG is not going to be the source of the problem here.
Comment: This is pseudorandom. Check the documentation and change to real random :)  https://docs.python.org/3/library/random.html
Comment: Could you please elaborate on what you mean with "This number is incorrect"?
Comment: Correct if I'm wrong, but the same position in the list being chosen six times is the same, is that not the same as rolling the dice six times and it landing on the same face. I believe that numbers.count(1) is counting the numbers of 1s in _numbers_ ,not count.
Comment: @BoarGules Why does this not look like the correct way to check for successive rolls?
Comment: @BoarGules When it rolls the dice, it will change one of the elements to a 1. This is our first roll. On the second roll, it changes one of the elements to 1. If this happens ten times, our dice has landed on the same face ten times in a row, and if it has landed ten times in a row, there should only be one `1` in the list, hence `numbers.count(1)`. Does this explain it?
Comment: @pjs you are right. random should be enough in this case. If he gets same seed he will have more frequently the same result.
Comment: @Gergo "If he gets same seed he will have more frequently the same result." Only if he keeps re-seeding, in which case he's misusing the concept of seeding.  Unless you really know what you're doing and want to play games with so-called variance reduction via correlation induction schemes, you should only seed a PRNG one time in your program.
Comment: @pjs What I'm saying is that if it rolls the same number, it will change the _same_ one leaving the amount of `1`s  as one. Though I don't know about the sampled dice rolls bit.
Comment: The answer to your added note is given as point 1 in my answer - the code you wrote doesn't perform the task you described. it's solving a completely different problem, so it will give a completely different answer.
Answer: There are several issues working against you here. Bottom line up front:

your code doesn't do what you described as your intent;
you currently have no yardstick for measuring whether your results agree with the theoretical answer; and
your expectations regarding the correct answer are incorrect.

I felt that your code was overly complex for the task you were describing, so I wrote my own version from scratch.  I factored out the basic experiment of rolling six 10-sided dice and checking to see if the outcomes were all equal by creating a list of length 6 comprised of 10-sided die rolls. Borrowing shamelessly from BoarGules' comment, I threw the results into a set—which only stores unique elements—and counted the size of the set. The dice are all the same value if and only if the size of the set is 1. I kept repeating this while the number of distinct elements was greater than 1, maintaining a tally of how many trials that required, and returned the number of trials once identical die rolls were obtained.
That basic experiment is then run for any desired number of replications, with the results placed in a numpy array. The resulting data was processed by numpy and scipy to yield the average number of trials and a 95% confidence interval for the mean. The confidence interval uses the estimated variability of the results to construct a lower and an upper bound for the mean. The bounds produced this way should contain the true mean for 95% of estimates generated in this way if the underlying assumptions are met, and address the second point in my BLUF.
Here's the code:
import random
import scipy.stats as st
import numpy as np

NUM_DIGITS = 6
SAMPLE_SIZE = 1000

def expt():
    num_trials = 1
    while(len(set([random.randrange(10) for _ in range(NUM_DIGITS)])) > 1):
        num_trials += 1
    return num_trials

data = np.array([expt() for _ in range(SAMPLE_SIZE)])
mu_hat = np.mean(data)
ci = st.t.interval(alpha=0.95, df=SAMPLE_SIZE-1, loc=mu_hat, scale=st.sem(data))
print(mu_hat, ci)

The probability of producing 6 identical results of a particular value from a 10-sided die is 10-6, but there are 10 possible particular values so the overall probability of producing all duplicates is 10*10-6, or 10-5.  Consequently, the expected number of trials until you obtain a set of duplicates is 105.  The code above took a little over 5 minutes to run on my computer, and produced 102493.559 (96461.16185897154, 108525.95614102845) as the output. Rounding to integers, this means that the average number of trials was 102493 and we're 95% confident that the true mean lies somewhere between 96461 and 108526. This particular range contains 105, i.e., it is consistent with the expected value.  Rerunning the program will yield different numbers, but 95% of such runs should also contain the expected value, and the handful that don't should still be close.
Comment: Bravo. I admire your approach of critiquing both (1) the algorithm and (2) the lack of a statistical basis for the expectation, and even more (3) your demonstration of the right way to do it. I have deleted my comments as not being in the same league as your answer. I wish the people who taught me my (now mostly forgotten) statistics had been as crisp.
Comment: @BoarGules I'm sorry you deleted your comments, they were definitely value added for me.
Answer: Might I suggest if you're working with whole integers that you should be receiving a whole number back instead of a floating point(if I'm understanding what you're trying to do.).
##randtst.write(str(total / 10)+"\n") Original
##randtst.write(str(total // 10)+"\n")
Using a floor division instead of a division sign will round down the number to a whole number which is more idea for what you're trying to do.
If you ARE using floating point numbers, perhaps using the % instead. This will not only divide your number, but also ONLY returns the remainder.
% is Modulo in python
// is floor division in python
Those signs will keep your numbers stable and easier to work if your total returns a floating point integer.
If this isn't the case, you will have to account for every number behind the decimal to the right of it.
And if this IS the case, your result will never reach 10x^6 because the line for totalling your value is stuck in a loop.
I hope this helps you in anyway and if not, please let me know as I'm also learning python.


Is homoscedasticity met?

Question: I'm fairly new to statistics. Could you help me, please?
I've got the scatterplot of residuals versus predicted value. It seems that the data points aren't scattered around zero with a constant width.
Am I right that homoscedasticity hasn't been met? What should I do? I have 5 independent variables, two of which are categorical. Can I make a prediction in this case?
Comment: What is the model? Regression, ANOVA, something else? How to judge such a plot of residuals can depend on what model is used.
Comment: The apparent heteroscedasticity in the figure implies prediction--which certainly is possible (after all, you have constructed the plot from predicted values!)--will have a level of uncertainty that varies with the predicted value itself.  Would that be a problem for you?
Comment: @BruceET a multiple linear regression model for sales
Answer: This looks reasonable to me.  Heterogeneity of variance is only an issue for inference, not prediction.  If you're worried about homogeneity of variance being violated, you could use a sandwhich estimator instead.  In the case where there is no heterogeneity of variance and you use the sandwhich, you lose a bit of power.  Seems like a worth while tradeoff to me.
Comment: It appears that the data are bounded below by zero, and this is what is causing the heteroscedasticity. After all, when the data are forced toward a boundary, there is necessarily less variance. (cf, SJ Gould, "Full House".)
Comment: Two statements that may seem contradictory: 1. If the scatter is strongly heteroscedastic that will leap out at you. 2. Just eyeballing the graph may not be enough, as it's hard to adjust mentally for variations in frequency across the graph. Consider smoothing (residual$^2)^{1/3}$ -- where squaring first makes all residuals 0 or positive and cube rooting damps outlying values -- as a function of fitted.
Comment: In the example a wedge shape s evident for low values. Sometimes this implies you would be better off with logarithmic scale.
Answer: Just from Visual inspection, I cannot detect heteroskedasticity. But I advice you to run some statistical tests like White Test
Comment: The heteroscedasticity looks clear to many of us, so your statement to the contrary needs to be backed up by an explanation of what method you are using to detect it.  What features are you examining in your visual inspection to assess heteroscedasticity?

Is homoscedasticity met?


Porque o MongoDB (nodejs + mongoose) não atualiza propriedade de objeto de um documento?

Question: Tenho um documento (dados do MongoDB) de user que tem um campo tags que armazena as tags ja usada pelo usuario. É um array de objeto no formato {text: 'tag1', count: 0}. O problema é ao atualizar os dados o valor das propriedades dos objetos permanecem os antigos, mesmo que no console.log mostre os novos valores.
Pego o usuario especifico com: users.findOne({name: 'exemplo'})
Exemplo 1: Funciona se eu fizer isso.
user.tags = []
await user.save()
//No caso, definindo as tags para um array vazio

Exemplo 2: Funciona se eu fizer isso.
user.tags = [{text: 'tag1', count: 0}, {text: 'tag2', count: 0}]
await user.save()
// Colocando um array real, atualiza normalmente.

Exemplo 3: NÃO funciona se eu fizer isso (o valor continua 0 zero)
user.tags[0].count = 5
await user.save()
/** Se eu fizer um console.log(user.tags) depois que salvar o count da posição zero mostra como 5 (correto), mas no banco de dados continua 0, nao atualiza */
//Ou seja, no console.log mostra certo, mas no DB nao

Exemplo 4: Só o incremento nao funciona se eu fizer isso (o valor continua 0 zero)
// valor atual de user.tags = [{text: 'tag1', count: 0}, {text: 'tag2', count: 0}]
user.tags = [{text: 'tag1', count: 1}, {text: 'tag2', count: 0}, {text: 'tag3', count: 0}]
/** Repare que agora a tag1 tem o count como 1, antes era zero. E agora tem a tag3, nesse exemplo a tag3 é adicionada significando que esta funcionando, mas o count da tag1 continua como zero */
// Não entendo porque nao muda ja que estou colocando um novo array completo
await user.save()

A "solução" que eu econtrei foi uma gambiarra apagando todo array e colocando o novo. Mas até agora não entendi porque eu preciso apagar para adicionar o novo array.
// solução na gambiarra
user.tags = []
user.tags = [{text: 'tag1', count: 1}, {text: 'tag2', count: 0}, {text: 'tag3', count: 0}]
await user.save()

ModelSchema
const mongoose = require('mongoose')
mongoose.Promise = global.Promise

const modelSchema = new mongoose.Schema({
    name: { type: String, required: true, trim: true, min: 3},
    tags: { type: Array },
)

const modelName = 'users'

if (mongoose.connection && mongoose.connection.models[modelName]) {
    module.exports = mongoose.connection.models[modelName]
} else {
    module.exports = mongoose.model(modelName, modelSchema)
}

Answer: Os Documents do Mongoose utilizam setters para identificar quais campos do seu documento foram mutados, e optimizam o update no banco de dados para não enviar mais do que o necessário.
Se o count não está sendo atualizado no banco de dados, é porque ele não possui um setter, provavelmente decorrente de como você declarou esse Schema/Model.
É possível marcar manualmente que um campo foi alterado com o método markModified:
user.tags[0].count = 5;
user.markModified('tags');
await user.save();

Porém trabalhar com um setter devidamente configurado deve ser preferível.
Para isso, ao invés de simplesmente declarar tags como sendo do tipo Array, crie um Schema específico para essa propriedade:
const TagSchema = new mongoose.Schema({
    text: { type: String },
    number: { type: Number },
);

const UserSchema = new mongoose.Schema({
    name: { type: String, required: true, trim: true, min: 3 },
    tags: { type: [TagSchema] },
);

Comment: adicionei como esta o schema, tem mais campos, como senha e outos. Mas a estrutura principal é essa. Como faria essa configuração no schema?
Comment: @DhenysonJhean, veja se a informação que eu adicionei te ajuda.
Comment: Ajudou sim, muito obrigado. Não sabia que poderia declarar um schema dentro de outro.


How long will the previous core version supported?

Question: I want to start a new project at the beginning of 2018 but I don't know if it is better to start this project with Drupal 7 or Drupal 8. Actually, I am not familiar with Drupal 8 coding and template engine.
Even though there are lots of modules that aren't available in Drupal 8 right now, such as admin menu, Date Converting module and others, I finally decided to start my project with Drupal 7, but the point that disturbs me is not knowing how long Drupal 7 will be supported. Is it 2020, 2021, or later?
Comment: Are you asking about "official" support or unofficial support? There are several companies now that continue to support Drupal 6.
Answer:

Drupal 7 is currently on LTS.
Drupal 7 LTS will end when Drupal 8 enters LTS, at which point Drupal 7 enters security fixes only mode.
Drupal 7 security fixes only mode ends when Drupal 8 enters security fixes only mode, and Drupal 9 enters LTS.
Essentially: Drupal 7 won't be EOL before development has started on Drupal 10.

Source: Has the EOL (end of life) for Drupal 7 been announced?
The simple answer is: We don't know, yet, exactly.
Check out the following articles:

When is Drupal 7 End-of-Life?
Understanding the Drupal 8 and 9 Release Cycle.

Drupal 7 will likely get bug-fixes until October 2017, and official
  security support until 2019 or 2020 at least.


How and when to use filter_xss() and check_plain()?

Question: There are lots of template files like this one views-view-fields--magazine--magazine.tpl.php in my website. how and when I should use the filter_xss()  and check_plain() to improve security? for example this is the code:

<?php print $fields['title']->content; ?>

<?php print $fields['field_magazine_body']->content;?>

<?php print $fields['field_magazine_image']->content;?>

How do I can apply those functions in it?
Comment: Use `filter_xss()` when you want to filter XSS from potentially dangerous content (i.e. content from an untrusted user), and `check_plain()` when you want to escape HTML special characters from a string
Answer: First, read up about these in the Drupal API:

filter_xss
check_plain

So check_plain() encodes special characters that has special meaning in HTML (such as < and &) into plain text entities (i.e. < and & respectively) that will make these be rendered literally (not interpreted as HTML) when that string that is then displayed as part of a page with HTML-markup. The function filter_xss() filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities. It does four things:

Removing characters and constructs that can trick browsers
Making sure all HTML entities are well-formed
Making sure all HTML tags and attributes are well-formed
Making sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)

Both functions are used to sanitize data from users to make sure that any user injection is neutralized before the data is rendered on your site.
You never pass the same string through both.
If you use check_plain() then the string passed to the function is supposed to be used as plain text (not HTML). Then filter_xss() is not needed, since check_plain() will always make the string plain text.
If you use filter_xss(), then the string passed to the function is supposed to be HTML, and check_plain() will mess it up.
When I look at the template you use as example, it looks to me as if all three fields passed to print() comes from content that is already sanitized, and need no more sanitation.
However, if you create your own module that collects user input without passing it through a "safe" text filter such as "Filtered HTML" or "Plain", you must use these functions for sanitation purposes.
Comment: @ARUN, no. Standard Drupal practice is to *always* save exactly what the user types in the DB, and to sanitize text before rendering.
Comment: Where do I can check for inputs come from users? for example there is a content type and anonymous users are allowed to create that kind of nodes.
Comment: @Drupalist, you should never allow the Anonymous user to use an "unsafe" text format.  Navigate to *Administration » Configuration » Content authoring » Text Formats*.  The "safe" text formats that comes with Drupal are "Filtered HTML" and "Plain text". If these are the *only* formats allowed for the Anonymous user, Drupal performs the required checks for you for any built-in node type and any node type you create with the core **Fields** feature.  If your use case is different from this, ask a new question spelling out the use case.
Comment: Anonymous users are only allowed to use `plain text`
Comment: @Drupalist, that's fine. There is no need to use these functions to sanitize Plain text.
Comment: "ordinary user input into an entity is santized upon input" - this is wrong. Text filters work on output. If input were sanitised then you would see something other than your original input when you edit a field in which you have entered something disallowed.
Comment: ...but that was a succinct explanation of the difference between check_plain and filter_xss so I found your answer very useful. Thank you.
Comment: @crantok, you're right of course (I've corrected the answer).
Comment: Should we use check_plain/filter_xss functions before saving data in to db? or only need to use before render it in the site?


chrome não depura com netbeans conecttor

Question: Instalei a extensão (plugin) Netbeans conector para o navegador Chrome porém não abre nada, somente uma tela branca com a mensagem "netbeans conecttor" esta fazendo a depuração desta guia.
Alguém já passou por isso? Tem uma solução?
Comment: Estranho porque eu a utilizava e não precisei fazer nada extra, somente instalar o *plugin* mesmo. O Netbeans, por padrão, vai executar uma página chamada `index.html` (na raiz do diretório web) e se não existir um arquivo com esse nome ele abrirá uma página em branco, não será isso? Se você excluiu o arquivo mencionado antes e criou outros arquivos html/jsp, eu até posso dar uma resposta.
Comment: tem o arquivo index.xhtml na raiz da pasta "paginas web" é um projeto jsf que fiz na faculdade. acredito que tudo esta correto pois foi todo desenvolvido pelo professor, somente no meu not esta com o este problema no lab da faculdade abre normal... sera que tenho que configurar algo na ide?
Comment: No arquivo `web.xml` tem alguma tag ``?
Comment: seria esta?

faces/index.xhtml
Comment: Hum, ja foi definido o arquivo de boas vindas. Se o projeto ta ok, não seria o servidor? Ta usando o tomcat?
Comment: Sim estou usando o tomcat na porta 8084.
segue print do log: http://prntscr.com/7ebyr6
Comment: Então o problema não é o *plugin* e sim algo na sua aplicação que está lançando uma `NullPointerException`. Dá uma olhada no método `doFilter` na classe `FiltroBD`, sem o código não tem como dar uma resposta.
Answer: Comigo também aconteceu quando estava tentando subir um "index.php".
Resolvi da seguinte forma:
na barra de ferramentas do NETBEANS abra os navegadores que podem ser usados escolha: "Chrome Browser Default do IDE".
O meu não funcionava pois estava marcado somente Chrome.
Answer: Aconteceu o mesmo problema comigo, resolvi da seguinte maneira:

Abra a opção Ferramentas => Opções => Web Browser selecione Chrome => Clique em Ok.

Ao lado esquerdo do ícone executar projeto, existe um ícone de navegador, selecione "Browser default do IDE", ícone relacionado ao navegador selecionado anteriormente.


CSS style sheet error

Question: Whats wrong with my code below.my code below doesn't  work fine

 Text 1

Answer: Font-color isn't a valid HTML tag or style declaration. Syntactically, it's illegal.
Instead, it should be something like:
foo

However, it is almost always better to move styles into their own stylesheet, and use a class name instead:
HTML

foo

CSS
.my-class { color: red; }

As @JanDvorak noted, try to use descriptive names for classes like "highlight".
You can also use other selectors to style your elements, such as an ID selector:
HTML

foo

CSS
#item1 { color: red; }

Comment: Suggested class name: `highlight`
Comment: Agree, class names should be descriptive. Not sure what the OP's intent was, but I'll add a note.
Answer: It should be:

 Text1

Answer: Font is not a self closing tag.  Also it's deprecated so you should look at changing that if possible.  It should look like this:

 Text 1

Comment: Instead of showing deprecated/unsupported tags, you could show how to do it correctly. IDK who is upvoting this answer. The question is tagged HTML5. This answer will not work.
Comment: I showed them how to do what they were attempting to do.  It's not invalid and it actually will work.  It's not what I would do though.
Comment: http://www.w3.org/wiki/HTML/Elements/font "HTML5 classifies it as a non-conforming feature" i.e. entirely obsolete.

CSS style sheet error


Passagem de Parametros entre um jsp e dois servlts?

Question: Tenho uma duvida talvez um pouco difícil de ser esclarecida!!!
Estou a utilizar uma metodologia de programação chamada MVC, como  toda a gente conhece, e que nesta situação (Java EE) no controller fica os handler (servlts) no model ficam as classes e a view que neste caso e os JSP´s.
E a minha duvida é o seguinte:
Possou um form num jps em que, o que quero que aconteça quando carregar em submit, é fazer o seguinte:

Passar os parâmetros do formulário para um servelt que utilizo para criar um objeto.
Passar estes mesmo parâmetros para um outro servlet para ser mostrado num jsp a parte.

Sei porem que existe uma forma de passar estes parâmetros tal como utilizar uma variável de sessão, porem como sabem, não é muito aconselhável utiliza-la.
Comment: Sugiro utilizar então o jQuery
Answer: Você não precisa de dois servlets, seu problema é mais fácil de resolver do que isso:

Envie os valores do seu formulário para a servlet
Crie o respectivo objeto na servlet, persista ele, faça a mágica acontecer
Coloque o seu objeto no request, por exemplo request.setAttribute("produto", produto);
Redirecione para a sua jsp:
RequestDispatcher rd = request.getRequestDispatcher("/produto.jsp");
rd.forward(request,response);

Agora você tem acesso ao objeto produto que está no request para expor a informação que você precisa.