docker-compose "up" vs. "run" yields different mounted volume

Question: Update 2: I have created a sample project on Git to reproduce this issue.   Upon further testing, the test case is slightly different than what I've described in my original post.
I am including the contents of the README I wrote on the github repo below.

Use Case

One simple nodejs project with a Dockerfile.
One local NPM dependency used by the above project (copied to container via Dockerfile). The project refers to the dependency via a local path.
The nodejs project has one web route (/) that prints the version of the local npm dependency from its package.json.  This is used to verify the results of the test case procedure.
docker-compose uses this volume technique to overlay the host machine's source tree
on top of the container's source tree and then overlaying the node_modules from the container on top of the first volume.

Steps to Reproduce

Clone this repo.
Clean up any previous containers and images related to this repo's project via docker rm and docker rmi.
Check out the test2_run1 tag. This state represents the project using version 1.0.0 of the local NPM dependency.
Do a docker-compose build.  All steps should run without any cache usage if step 2 was followed correctly.
Note the version of the local NPM dependency during the npm install command, e.g. +-- email@example.com.
Do a docker-compose up.  Browse to http://localhost:8000.  The page should report version 1.0.0.
Stop the running containers. (Ctrl-C on the terminal from which the up command was issued.)
Check out the test2_run2 tag. This introduces a small change to the NPM's index.js file, and a version
bump in its package.json to 1.0.1.
Do a docker-compose build.  Only the instructions up to COPY ./my-npm ... should use a cache. (E.g., the docker output prints ---> Using cache for that instruction.)  All subsequent steps should be run by docker.  This is because the changes introduced in step 7 to the NPM package should have invalidated the cache for the COPY ./my-npm ... command, and, as a result, subsequent steps too.  Confirm that during the npm install command, the new version of the NPM is printed in the summary tree output, e.g. +-- firstname.lastname@example.com.
Do a docker-compose up.  Browse to http://localhost:8000.  The page should report version 1.0.1.

Expected behavior: Page in step 9 should report 1.0.1.  That is, a change in the local npm should be reflected in the container via docker-compose up.
Actual behavior: Page in step 9 reports 1.0.0.
Note that docker itself is re-building images as expected.  The observed issue is not that docker is re-using a cached image, as the output
shows it re-running NPM install and showing the new version of the local NPM dependency.  The issue is that docker-compose is not seeing
that the underlying images that comprise the dctest_service1 container have been updated.
In fact, running bash in the container allows us to see that the container has the updated my-npm module files, but the node_modules
version is stale:

  # docker exec -it dctest_service1_1 bash
  app@6bf2671b75c6:~/service1$ grep version  my-npm/package.json  node_modules/my-npm/package.json
  my-npm/package.json:  "version": "1.0.1",
  node_modules/my-npm/package.json:  "version": "1.0.0"
  app@6bf2671b75c6:~/service1$

Workaround: Use docker rm to remove the dctest_service1 container.  Then re-run docker-compose up, which will re-create the container using the existing images.  Notable in this step is that no underlying images are re-built.  In re-creating the container, docker-compose seems to figure out to use the newer volume that has the updated node_modules.
See the output directory for the output printed during the first run (steps 4 and 5) and the second run (steps 8 and 9).

Original Post
I've got a nodejs Dockerfile based on this tutorial ("Lessons from Building a Node App in Docker").  Specifically, note that this tutorial uses a volume trick to mount the node_modules directory from the container itself to overlay on top of the equivalent one from the host machine. E.g.:
volumes:
 - .:/home/app/my-app
 - /home/app/my-app/node_modules

I am running into a problem where an update to package.json is triggering a npm install as expected (as opposed to using the docker cache), but when starting the service with docker-compose up, the resulting container somehow ends up with an older version of the node_modules data, as the newly added NPM package that had been added is missing from the directory.  Yet, if run the specified CMD by hand via docker-compose run --rm, then I do see the updated volume!
I can confirm this a few ways:
node_modules Timestamp
Container started via "up":
app@88614c5599b6:~/my-app$ ls -l
...
drwxr-xr-x 743 app app 28672 Dec 12 16:41 node_modules

Container started via "run":
app@bdcbfb37b4ba:~/my-app$ ls -l
...
drwxr-xr-x 737 app app 28672 Jan  9 02:25 node_modules

Different docker inspect "Mount" entry Id
Container started via "up":
"Name": "180b82101433ab159a46ec1dd0edb9673bcaf09c98e7481aed7a32a87a94e76a",
"Source": "/var/lib/docker/volumes/180b82101433ab159a46ec1dd0edb9673bcaf09c98e7481aed7a32a87a94e76a/_data",
"Destination": "/home/app/my-app/node_modules",

Container started via "run":
"Name": "8eb7454fb976830c389b54f9480b1128ab15de14ca0b167df8f3ce880fb55720",
"Source": "/var/lib/docker/volumes/8eb7454fb976830c389b54f9480b1128ab15de14ca0b167df8f3ce880fb55720/_data",
"Destination": "/home/app/my-app/node_modules",

HostConfig -> Binds
I am unsure if this is related, but I also did notice (also in docker inspect) that the Binds section under HostConfig differs between both cases:
Container started via "up":
"Binds": [
   "180b82101433ab159a46ec1dd0edb9673bcaf09c98e7481aed7a32a87a94e76a:/home/app/my-app/node_modules:rw",
  "/Volumes/my-mount/my-app:/home/app/my-app:rw"
],

Container started via "run":
"Binds": [
  "/Volumes/my-mount/my-app:/home/app/my-app:rw"
],

(Both show the host source mounted on the image, but only the "up" shows the secondary overlay volume with node_modules, which seems like another odd wrinkle.)
Theory
Per the docker-compose CLI reference:

If there are existing containers for a service, and the service's
  configuration or image was changed after the container's creation,
  docker-compose up picks up the changes by stopping and recreating the
  containers

Thus, it appears docker-compose up does not think the configuration or image was changed.  I am just not sure how to debug this to confirm.  Of course, I could use --force-recreate to work around this, but I wish to resolve what about my configuration is incorrect that is causing the problem.
Update: If I do an explicit docker-compose build prior to docker-compose up, the problem still persists.  Thus I am feeling less confident about this theory at the moment.
Here is the entire Dockefile:
FROM node:6.9.1

RUN useradd --user-group --create-home --shell /bin/false app

ENV HOME=/home/app
ENV APP=my-app
ENV NPM_CONFIG_LOGLEVEL warn

RUN npm install --global gulp-cli

COPY ./package.json $HOME/$APP/package.json
RUN chown -R app:app $HOME/*

USER app
WORKDIR $HOME/$APP
RUN npm install && npm cache clean

USER root
COPY . $HOME/$APP
RUN chown -R app:app $HOME/* && chmod u+x ./node_modules/.bin/* ./bin/*

USER app

ENTRYPOINT ["/home/app/my-app/bin/entrypoint.sh"]
CMD ["npm", "run", "start:dev"]

Comment: Could you post your `docker-compose.yml` file too? so we can compare that file with your `Dockerfile`. See my answer below
Comment: @Pitt the file is quite big.  That being said, I have noticed that if I delete the container via "docker rm ", then when d-c builds, it uses the correct images to create the container.  So something about d-c is causing it to not realize the underlying images have been changed.  I am going to create a smaller/simpler project to try and reproduce.
Comment: I looked closer at the tutorial you linked, if your docker-compose.yml uses the uses the directive `build: .` it means that rather than using only a pre-build image to instantiate your docker container it will build the `.` (current) directory. So if you change something you'd have to run `docker-compose build` before running `docker-compose run` otherwise an older, cached build is used.
Comment: Also if you just want to use one command you can use `docker-compose up --build`.

To really see what is going on, you'd have to post your full `docker run` command that you use, as well as your `docker-compose` command and `docker-compose.yml` file that defines the service you are wanting to run.
Comment: @Pitt - I'm not sure if you saw my "update" - but it appears that a build, whether explicit or not, does not solve the problem.
Comment: @Pitt I appreciate you helping out here, but let me try and set up a simpler project to help debug this.
Comment: okay! One last thing: I noticed that your question is not clear as to whether you are using `docker run` or `docker-compose run`. so maybe a more adequate test would be to compare the results of `docker start` with `docker-compose up`, and `docker run` with `docker-compose run`?
Comment: @Pitt I am using `docker-compose up`.  If I use `docker-compose run`, it works because it creates a new container with the proper images.

I've updated the post with a link to a sample project to reproduce, along with instructions.  I think I will try reaching out to docker devs for help too.
Answer: the command docker-compose uses the docker-compose.yml file as a configuration file of your containered service. By default it looks for this .yml config file in the directory you run docker-compose.
So it could be that your docker-compose.yml file is not up to date, seeing that one of your volumes is not mounted when you run docker-compose up.
docker run ignores the docker-compose.yml file and just builds the container using the Dockerimage. So there could be configuration difference between the Dockerimage file and the docker-compose.yml files.


Qual a diferença entre os comandos 'git pull' e 'git fetch'?

Question: Eu gostaria de saber qual é a diferença entre os comandos git pull e git fetch no software de versionamento git.
Comment: Tem um [livro muito bom](http://git-scm.com/book/pt-br/), disponível em Português para consulta online. Vale MUITO a pena ler...
Answer: git fetch baixa as referências (refs) com nomes ou tags de um ou mais repositórios (caso você tenha outro remote além do origin configurado), junto com os objetos necessários para completá-los. Basicamente ele atualiza as referências locais com relações às remotas, mas não faz o merge com o branch local.
git pull incorpora mudanças de um repositório remoto para o branch local. É equivalente a git fetch seguido de git merge FETCH_HEAD.
Referências:

git pull
git fetch
Answer: De modo simplório, o git fetch buscas as diferenças em relação ao ramo atual, mas não altera nada nesse branch. Já git pull faz o git fetch e faz o merge das diferenças.
Comment: Isso mesmo, corrigido.
Answer: git fetch faz download dos ultimos commits do branch remoto, mas nao os incorpora com a copia actual do repositorio. Estes commits so estarao disponiveis no branch origin\master, e o branch master continua intacto.
pull equivale a fazer git fetch (download dos ultimos commits) + git merge (incorpora os commits com o branch local)
Ver git pull manpage:

git pull is shorthand for git fetch followed by git merge FETCH_HEAD.
git pull e' um atalho para git fetch seguido de git merge FETCH_HEAD.

Este comportamento por defeito pode ser alterado para executar fetch + rebase , em vez de fetch + merge, com a flag git pull --rebase


Android: NullPointerException at getActionBar

Question: I'm implementing navigation drawer sliding menu .getting java.lang.NullPointerException at the
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setHomeButtonEnabled(true);

In my Application I have tried activity extended Activity and also AppCompatActivity.
Here is my onCreate code
protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();

        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
        navDrawerItems = new ArrayList<NavDrawerItem>();
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
        navMenuIcons.recycle();
        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
        adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
        mDrawerList.setAdapter(adapter);
       //abling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayShowHomeEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,

                R.drawable.menu_left, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        )
        {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();}
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);
        if (savedInstanceState == null) {
            // on first time display view for first nav item
            displayView(0);
        }
    }

Here is LogCat inforamtion
 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tazeen.slidingmenu/com.example.tazeen.slidingmenu.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.tazeen.slidingmenu.MainActivity.onCreate(MainActivity.java:62)
            at android.app.Activity.performCreate(Activity.java:5008)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
            at android.app.ActivityThread.access$600(ActivityThread.java:130)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:4745)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

Comment: Try to Post your Logcat output also.
Comment: possible duplicate of [getActionBar() returns null](http://stackoverflow.com/questions/6867076/getactionbar-returns-null)
Answer: If you are extending from AppCompatActivity you should use, getSupportActionBar()
If you are extending form Activity, You can use getActionBar(),
But in both the cases,
You have make sure to have a ActionBar supported theme assigned for your Activity.
Eg: Theme.AppCompat.Light
or you can programatically do it,
requestWindowFeature(Window.FEATURE_ACTION_BAR);

before
super.onCreate(savedInstanceState);

But it is best to have a style declared and assigned for your activity rather than doing it programatically.
Answer: extends simple Activity instead of ActionBarActivity.and please   always check null before setDisplayShowHomeEnabled() like:
if(getActionBar()!=null){
    getActionBar().setDisplayShowHomeEnabled(true);
        getActionBar().setHomeButtonEnabled(true);
    }

and another solution is to use getSupportActionBar() instead of getActionBar()
and then
if(getSupportActionBar()!=null){
    getSupportActionBar().setDisplayShowHomeEnabled(true);
        getgetSupportActionBarActionBar().setHomeButtonEnabled(true);
    }

enjoy your code:)


A complicated equation system

Question: Are you up for a challange? Nine years ago, I experimented with some variables and came up with an equation system. I figured out there were solutions to it and worked hard to find generalized ways to solve for the different variables. I only used a note pad, pen and an ordinary "high school" calculator with the most basic stuff on it like logaritms, cosine and so on.
This is the system in question: $$z=x^2-y^2=xy=(x-y)^z $$
Can you solve it without plotting graphs on a calculator (in which case it is not much of a challange)? I don't remember exactly how I solved it, becuase it invloed a lot of testing, intution and homemade numerical methods. If you find solutions it will be interesting to see in what form you present them. Becuase they can be expressed in many different ways, I suspect.
This is way over my head to take on myself, but after we have the solutions with as many decimals as we find suitable the question also arises whether we can prove that the variables are transcendental numbers. (I suppose they are.)
Answer: The trick is to solve the relationship for $(x,y)$, then it's easy to compute and check the $z$ from there. You have
$$
x^2-y^2=xy\\
y^2+xy-x^2=0
$$
and now the quadratic formula yields
$$
y_\pm = \frac{-x \pm \sqrt{x^2+4x^2}}{2} = x \left(\frac{-1 \pm \sqrt{5}}{2}\right).
$$
Answer: Exactly! And that was a very neat way to show the relationship.
If x=y=0, z is not equal to 0 for x^2-y^2=xy=(x-y)^z . I think I started with z=0, when xy=1. From there I generalized the case for z and came up with the following relatinship: Let a=(2z-1)/(z-2), z is not equal to 2. Therefore: (z=(2a-1)/(a-2), a is not equal to 2. Then x1=((1+sqrt(5))/2)^a and y1=((1+sqrt(5))/2)^(a-1) If z is an integer we also have: for even z: x2=-((1+sqrt(5))/2)^a y2=-((1+sqrt(5))/2)^(a-1) and for odd z: x2=-((sqrt(5)-1)/2)^a and y2=((sqrt(5)-1)/2)^(a-1)
I am skipping steps here, but returning to the original z=x^2-y^2=xy=(x-y)^z : by now I already knew that ((ln z)(4/z-2))/ln((3-sqrt(5))/2)=3 after some previous manipulation.  From here, I used numerical methods.  I got z1=7.30220780349213621366538204...  and z2=0.565797562941563696922557253... From there:
x1=3.437327511158194756287987239599091116665455... y1=2.124385232360847796318777545089287738785702... x2=0.956807027352594226892051778700936525639314... y2=0.591339263578653552729527217298789716342087...
Due to the nature of the logarithmic equation, I think z must be a positive real number. If only one of x and y is not a real number then xy should not be a real number. But if neither where real numbers, then x-y should not be a real number either. So, I don't think there are any other solutions.

A complicated equation system


QuerySelectorAll using a class and index number

Question: document.querySelectorAll('.fixers > track > tnty')

On the DOM there are many classes named fixers is there a way to include what class number to use something like
document.querySelectorAll('.fixers[2] > track > tnty')

Currently I do this
document.getElementsByClassName('fixers')[2].querySelectorAll('track > tnty')

Is there a more correct way?
Thank you
Answer: You could use the nth-child() pseudo-class to select the second group like so:

const elems = document.querySelectorAll('.fixers:nth-child(2) > .track > .tnty');
console.log(elems);
console.log(elems[0].textContent);

1

2

3

Answer: You can get a selected 'fixers' element using a specific parent
document.querySelectorAll('.special-parent .fixers > track > tnty')

or :nth-child() selector
document.querySelectorAll('.fixers:nth-child(2) > track > tnty')

or using both above mentioned.


What does "Prefetch views unpack data" in APDQC module do?

Question: There is an option in the APDQC (Asynchronous Prefetch Database Query Cache)  https://www.drupal.org/project/apdqc module for:
Prefetch views unpack data
It's unclear what this does. Should this be turned on or left off as default?
Comment: The Views plugin classes have an `unpack_options` method which takes the options for the View/display in the database and applies them on top of the defaults. I don't know the Views code deeply enough for this to be anything other than a guess, but that option probably just allows that data to be cached by APDQC
Answer: Really depends on your workload. In some cases having all of the views data prefetched is faster, in other cases it's slower. If you have 50+ views then it's best to leave it off, if you have just a couple views, turning it on is faster.
Side note: I created the patch for creating this cache in views, now I wish it was prefixed by the view name so prefetch would be easier.


What is the difference between import httplib and from httplib import *?

Question: I would like to know which is the difference between
import httplib and
from httplib import *
By the way i am using python 2.73.
Comment: possible duplication of [Confirming the difference between import * and from xxx import *](http://stackoverflow.com/questions/4436401/confirming-the-difference-between-import-and-from-xxx-import)
Answer: With import httplib, you would have to do
httplib.HTTPConnection(host)

With from httplib import *, you could do
HTTPConnection(host)

It is considered better to specify what you are importing in the second method, as in from httplib import HTTPConnection
Comment: It's preference, but if you use the `from` method, it's best to specify what you are importing instead of using the `*` operator.
Answer: Here's the different, by example:
>>> import httplib
>>> SEE_OTHER
NameError: name 'SEE_OTHER' is not defined
>>> httplib.SEE_OTHER
303

>>> from httplib import *
>>> SEE_OTHER
303
>>> httplib.SEE_OTHER
NameError: name 'httplib' is not defined

The from httplib import * is almost* never what you want, except possibly while experimenting with httplib in the interactive prompt.
Sometimes you want to import a few names out of a library—but in that case, specify the names explicitly:
from httplib import SEE_OTHER, MOVED_PERMANENTLY

Both import the module, but the former creates a single new name, httplib, in your current globals, while the latter instead copies all of the globals from httplib into your current globals.**

* "Almost" because there are a few good use cases even in scripts. For example, the idiomatic way to provide a Python implementation of a module with C accelerators is to end the Python script foo.py with from _foo import *.
** This isn't quite true, because of __all__ and various other details, but close enough for now.


Issues with using glmnet package for MATLAB

Question: I am trying to use the glmnet MATLAB package to train my elastic net model on some huge data. My features are of size 13200, and I have around 6000 samples of these. I directly tried to use lassoglm in MATLAB with these features and corresponding target taking cross validation to just 3 folds and alpha = 0.5. It's already 6 hours and it hasn't finished. I have to do it for several others as well.
Any suggestions what I should do?
Comment: This question appears to be off-topic because it is about just programming ... Better to ask it on stackoverflow and if you want to get an answer ... you need to provide a minimal code to re-produce the problem.
Answer: I am not an expert.
In R, I have got ( after 11 hours!!) : Warning message:
from glmnet Fortran code - Convergence for 10th lambda value not reached after maxit=100000 iterations; solutions for larger lambdas returned.
So you might want to first set maxit very low and then investigate further.
Also I assume your data is in a sparse matrix?
Comment: No it is not sparse
Answer: Not sure about the matlab interface, but in the R version you can control the maximum number of non-zeros using dfmax. Try to set that to something small and see if it works. Also, alpha=0.5 leads to the elastic-net which will increase the number of non-zero variables in the model, try with a larger alpha.


stock prediction python SVR syntax error

Question: I'm trying to do the stock prediction using SVR and here's the code that I'm using:
import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
dates = []
prices = []
def get_data(filename):
    with open (filename,'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader)
        for row in csvFileReader:
            dates.append(int(row[0].split('-')[0]))
            prices.append(float(row[1]))
        return
def predict_prices(dates,prices,x):
    dates = np.reshape(dates,(len(dates),1)
    svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
    svr_lin = SVR(kernel='linear', C=1e3)
    svr_poly = SVR(kernel='poly', C=1e3, degree=2)
    svr_rbf.fit(dates, prices)
    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)

    plt.scatter(dates, prices, color='balck',lable = 'Data')
    plt.plot(dates,svr_rbf.predict(dates),color = 'red',lable = 'rbf' )
    plt.plot(dates,svr_poly.predict(dates),color = 'blue',lable = 'poly' )
    plt.plot(dates,svr_lin.predict(dates),color = 'green',lable = 'lin' )
    plt.xlabel('date')
    plt.ylabel('price')
    plt.legend()
    plt.show()
return svr_rbf.predict(x)[0], svr_poly.predict(x)[0], svr_lin.predict(x)[0]

get_data('data1.csv')
predicted_price = predict_price(dates,prices,29)
print(predicted_price)

The above codes give the following error:
svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
          ^
SyntaxError: invalid syntax

I do not know why there is a syntax error. I also changed C=1e6 then to success.
Please help.
Answer: You are missing a closing ) on line 16. This kind of thing can confuse the Python interpreter, which sometimes indicates the error occurs on the following line (as you experienced).
To fix this, just change:
dates = np.reshape(dates,(len(dates),1)

to:
dates = np.reshape(dates, (len(dates),1))

Comment: Are you sure about this change? The third argument should be a string: https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html
Comment: Whoops, fixed. The second argument should be a tuple
Comment: raise ValueError("'color' kwarg must be an mpl color"

the problem is solved there is no syntax error now thanks a lot but here I m facing a new error. ValueError: 'color' kwarg must be an mpl color spec or sequence of color specs.
For a sequence of values to be color-mapped, use the 'c' kwarg instead.even after changing color to c and writing initials of color-red as 'r' no success. please help.
Comment: @Anisha that sounds like another question -- the StackOverflow community likes folks to post a new question so that others will be able to search for exactly your new question in the future...


Ruby: Undefined local variable or method

Question: I'm trying to store a hash within an array with the keys "name", "number", and "email". I want the email to be a user's last name + last 3 digits of the number + "@btvs.com". I keep getting the error "undefined local variable or method" for number. How can I get this to output correctly? It has no problem grabbing the value from "name", but won't from "number".
data = Array.new()

puts "Name?, eg. Willow Rosenberg"
name = gets.chomp

    data = [
        {
        name: name,
        number: rand(1000..9000) + 1,
        email: name.split(' ').last + number.to_s[1..3] + "@btvs.com"
        }
    ]

puts data

Comment: That's because `name` is set before you start initializing the array/hash. Why not do the same for `number`?
Comment: @JonnyHenly sorry I'm a bit new to this. What should I be setting number to?
Comment: `number = rand(1000..9000) + 1`
Answer: Try
puts "Name?, eg. Willow Rosenberg"
name = gets.chomp
number = rand(1000..9000) + 1
data = [
  {
    name: name,
    number: number,
    email: name.split(' ').last + number.to_s[-3, 3] + "@btvs.com"
  }
]
puts data

Comment: *Try [code dump]* with no explanation, leads to comments like my previous comment.
Comment: Because he said the last three digits of the number.
Comment: @morrime I think you should open another question. but before try on your own and tell us where you find difficulties.
Comment: @morrime Sorry if I came off as sounding rude, that wasn't my intent. If you're having trouble learning Ruby, then you should check out [Codecademy's Ruby Course](https://www.codecademy.com/learn/ruby), it's free, it's hands-on and does a pretty good job of conveying information.
Comment: Why did you change `number.to_s[1..3]` to `number.to_s[-3, 3]`?
Comment: Sometimes people want explanation about one concept, other times they just want the code, see how they could solve their problem.
Comment: I didn't actually use number.to_s[-3, 3]. I kept my original formatting for that, but implemented the correct changes for setting "number" before the array.
Comment: @Ursus I need to loop this so the user is prompted with "Name?" 3 times, and each answer is stored as a new hash within the data array. Each answer should also have a new random number generated for it, and an email. Any ideas?
Comment: @morrime I would add emphasis to Ursus point that you should **try on your own and tell us where you find difficulties**. You should also show that you have done a fair amount of research. Remember that asking a question on Stack Overflow should be your last option.
Comment: @JonnyHenly I'm a beginner and have been googling until my hands bleed for a day and a half. I have been researching and trying things on my own TO NO AVAIL. As a beginner, I cannot open another question for an hour and a half. So let's try not to be rude, shall we?


Stream from S3 a MP4 video file from a Grails controller to a video.js player

Question: I have an issue trying to stream MP4 video files from Amazon S3 through a grails controller.  I would like to host a video file on S3 and stream it (or send it) through a grails controller, that will be accessed by the front end that is a video.js player in a html page.
I need to keep the videos on S3 private, so just making the video public on S3 and using a direct url is not possible.  Any help is appreciated.
Controller:
def video = {
  def s3 = amazonWebService.s3
  def file = s3.getObject(params.bucketName, params.key)

  response.status = 206
  response.contentType = "video/mp4"
  response.outputStream << file.objectContent
  response.outputStream.flush()
  response.outputStream.close()

}
Video (GSP frontend):
<video id="example_video_1" class="video-js vjs-default-skin"
      controls preload="auto" width="640" height="264"
      poster="http://video-js.zencoder.com/oceans-clip.png"
      data-setup='{"example_option":true}'>
        <source src="${createLink(controller:'home', action:'video', params:[bucketName:bucketInstance, key:videoFileInstance])}" type='video/mp4' />
    </video>

Comment: What error are you getting? What problem are you experiencing? Your question doesn't state what the actual issue is, only what you are attempting to do.
Comment: Sorry I should have been more clear.  I am not getting an error, but the video file that I am trying to play in video.js isn't playing.  I am not sure what I am missing.  Any suggestions for setting up a better debug environment would be of help as well.
Answer: You don't need to download the video.

Use the AWS Java SDK, get pre_signed URL for the video, using your bucket and key details. If your video is not of confidential nature, you can also create get a public URL for the video.
Use that pre-signed URL in the place of the SRC.
The video would still not play correctly in all the browsers, because you are having only one format MP4 in your video, which is not supported in all the browsers. You would need to upload the webm format as well to S3 and provide the URL for it in the videojs SRC for that format. For this you can use AWS video encoder, or you can use ffmpeg to do the conversion.

Finally you would be able to play the video in all the major browsers.
Hope this helps.


'str' object has no attribute 'verified'

Question: I am including OTP in my project with twilio. But When verifying phone number it throws following error.
phone.verified = True
AttributeError: 'str' object has no attribute 'verified'

models.py
class User(AbstractBaseUser, PermissionsMixin):
    phone = models.CharField(max_length=15, unique=True)
    is_active = models.BooleanField(default = True)

    is_staff = models.BooleanField(default = False)

    USERNAME_FIELD = 'phone'

    key = models.CharField(max_length=100, unique=True, blank=True)
    verified = models.BooleanField(default=False)
    objects = UserManager()

views.py
@api_view(['GET'])
def send_sms_code(request, format=None):
    time_otp = pyotp.TOTP(request.user.key, interval=10000)
    time_otp = time_otp.now()
    user_phone_number = request.user.phone
    client.messages.create(
                    body="Your verification code is "+time_otp,
                    from_=twilio_phone,
                    to=user_phone_number
                )
    return Response(status=200)

@api_view(['GET'])
def verify_phone(request, sms_code, format=None):
    code = int(sms_code)
    if request.user.authenticate(code):
        phone = request.user.phone
        phone.verified = True
        phone.save()
        return Response(dict(detail = "Phone number verified successfully"),status=201)
    return Response(dict(detail='The provided code did not match or has expired'),status=200)

it sends me a verification code but When I am going to verify it does not work properly. I know where the problem is but How can I solve it? Any help would be appreciated! Thanks beforehand!
Comment: Is verified on the user model or a separate Phone model? If it is the latter, `phone` on the `User` model should be a `ForeignKeyField` to the Phone model rather than a `CharField` and your code should work. If verified is on the `User` model, see the provided answer below.
Answer: Your api view sets phone = request.user.phone which is a string. You then use phone as if it is a User object by accessing the verified property on it. Instead, your view should be:
@api_view(['GET'])
def verify_phone(request, sms_code, format=None):
  ...
  if request.user.authenticate(code):
    user = request.user # set user as a User object.
    user.verified = True
    user.save()
    return Response(...)
  return Response(...)

It looks like you don't even use the phone variable so you don't really need it with the information you gave us.


React Native checkbox of a map select

Question: I am mapping through an array of objects called abilities in React Native, that I retrieve from the backend and trying to select each one of them (abilities) assigned to each item. But selecting one of them, selects them all. How to effectively select a single checkbox in handleConfirm?
    class Example extends Component {
        constructor(props) {
            super(props);
            this.state = {
                checked: false,
            };

            this.handleConfirm = this.handleConfirm.bind(this);

        handleConfirm () {this.setState({ checked: true })}

         render() {
            const {
                checked
                } = this.state;

            return (
                <Container>
                    <Content contentContainerStyle={styles.container}>
                        <ListItem style={styles.listAllItems}>
                            {abilities.map((ability, index) =>

                                <Button
                                    key={index}
                                    iconLeft
                                    style={styles.button}
                             >
                                    <Text>{ability.name + '\n'}</Text>
                                    <Right>
                                        <CheckBox
                                        checked={checked}
                                        onPress={ this.handleConfirm()}/>
                                    </Right>
                                </Button>

                            )}
                        </ListItem>
                    </Content>
                </Container>

Answer: Below things you have missed in your code:
1] As you are mapping through array of object, you need to manage each checkbox state, which is missing in your code(i.e. you have used a single variable for maintaining check-boxes state which is not correct). You need a array for managing checked/unchecked status of each checkbox.
2] Also it has been observed that, you are handling only checked true condition. Actually you need to handle toggle(checked=>unchecked and unchecked=>checked).

I have made some modifications in your code for your issue and above specified changes as well:
class Example extends Component {
    constructor(props) {
        super(props);
        this.state = {
          checked: []
        };
    }

    isItemChecked(abilityName) {
        return this.state.checked.indexOf(abilityName) > -1
    }

    manageToggle = (evt, abilityName) => {
        if (this.isItemChecked(abilityName)) {
          this.setState({
            checked: this.state.checked.filter(i => i !== abilityName)
          })
        } else {
          this.setState({
            checked: [...this.state.checked, abilityName]
          })
        }
    }

    render() {

        return (
            <Container>
                <Content contentContainerStyle={styles.container}>
                    <ListItem style={styles.listAllItems}>
                        {abilities.map((ability, index) =>

                            <Button
                                key={index}
                                iconLeft
                                style={styles.button}
                         >
                                <Text>{ability.name + '\n'}</Text>
                                <Right>
                                    <CheckBox
                                        checked={this.isItemChecked(name)}
                                        onPress={evt => this.manageToggle(evt, ability.name)}/>
                                </Right>
                            </Button>

                        )}
                    </ListItem>
                </Content>
            </Container>

Answer: do this for your onPress in your checkBox
onPress={()=>{ this.handleConfirm()}}

Comment: copy onPress={()=>{ this.handleConfirm()}} and paste it in your code
Comment: did you copy exactly what I said?look you have to use ()=>{ } in your onPress !
Comment: checkbox already has an onPress.

React Native checkbox of a map select


Hypothesis test of mean between groups with dependencies and pairing

Question: I have two groups with small number of n (less than 10) where some observations are replicates for each other, some are paired difference observations, and some are completely independent. For example:
<code>Group I        Group II
A <--paired--> B
C (unpaired)
D <--paired--> E
F <-| replicate of D
</code>
Is there any known way to test the hypothesis that the mean of Group I != mean of Group II?
Comment: What does it mean that F is a replicate of D?
Comment: F and D are not independent measurements but are for example measurements from the same sample.
Comment: How does that differ from A & B (which I also understand to be measurements from the same sample)?
Comment: Consider A & D to be biological replicates and D & F to be technical replicates.
Answer: It sounds like you have an undesigned experiment that presents serious problems for interpretation of the results. First, it is usual to have either paired or unpaired observations and a mixture is awkward (as you apparently know). Second, an important assumption in many significance tests is that the data are a random sample and, given the undesigned appearance of the data, I suspect that may not be the situation in this case. Thus a conventional hypothesis test is not appropriate.
A couple of strategies are worthy of consideration.

Segregate the unpaired and paired observations and analyse them separately. Their results should agree with respect to the size of the effect. 'Agree' here is a bit vague, and you should not expect very close agreement with small samples--the same direction of effect in both sets is probably as much as you can expect unless the effect is very large relative to the relevant variances.
Treat all of the observations as unpaired (use the average of the replicates D and F as a single observation).

It is vital to note that neither approach is reliable, and before making any strong or important conclusion you really will need to either (i) make valid arguments supporting your conclusions that almost need no statistical support from these data or (ii) to repeat the experiment using a better design. Statistical analysis cannot do much to repair 'faulty' data like yours.
Comment: Well, for what it's worth, my employer was the one who "undesigned"  the experiment and left me to pick up the pieces. Is there maybe a Monte Carlo simulation that approximates a conventional t-test that  I could generalize to tolerate poorly designed data?
Comment: +1, nice points. It reminds me of [this quote](http://stats.stackexchange.com/questions/726/famous-statistician-quotes#739).


criar Linked no MySQL entre instâncias diferentes

Question: Olá,
Tenho a instância A (Local) e uma outra instância B, preciso fazer uma consulta onde tenho a tabela A (instância Local) relacionar com a tabela B da (instância B) é possível ?
Answer: A engine MySQL FEDERATED engine até tem uma funcionalidade parecida com a Linked Server do SQL Server, dá uma olhada para ver se te ajuda.
Fora isso, nativamente o MySQL não tem esse tipo de funcionalidade.


How do I finish solving $f(x)f(2y)=f(x+4y)$?

Question: I'm trying to solve this functional equation:
$$f(x)f(2y)=f(x+4y)$$
The first thing I tried was to set $x=y=0$; then I get:
$$f(0)f(0)=f(0)$$
which means that either $f(0)=0$ or we can divide the equation by $f(0)$ and then $f(0)=1$.
Case 1: If $f(0)=0$ then we can try to set $x=0$. Then;
$$f(0)f(2y)=f(4y)$$
$$0=f(4y)$$
Which means that one of the solutions is a constant function $f(x)=0$
Case 2: If $f(0)=1$. This is where I'm stuck.
I tried to set $x=0$, then I get:
$$f(2y)=f(4y)$$
I also tried to set $x=-4y$. Then I get:
$$f(-4y)f(2y)=f(0)=1$$
I think that these two observations could be useful, but I don't know how to continue from here. I have guessed that another solution is $f(x)=1$ but I don't know how to show that there aren't any others as well.
Comment: Are you looking for continuous solutions.
Comment: In your last equalities, replace $ f(2)$ by $f(2y)$
Comment: Yes, I think that is what I'm supposed to find.
Comment: You should always mention what is the domain and codomain of said function (based on the computations you make it seems it is $f: \mathbb{R} \to \mathbb{R}$). Same applies also for domain of the variables in the equation itself, $x,y$ in this case (again it seems those can be any real numbers).
Answer: When solving functional equations, we aren't able to claim continuity and other such properties. We in fact don't need the continuity condition in order to solve the problem.
For the $f(0)=1$ case, we can reuse some of your claims:
(1)$$f(2y)=f(4y)$$
(2)$$f(-4y)f(2y)=1$$
We can substitute 1) into 2) to get that
(3)$$f(-4y)f(4y)=1. $$
We now plug $y=-\frac{x}{2}$ into our original equation to get another identity:
(4)$$f(x)f(-x)=f(-x).$$
We can replace $4y$ with $x$ and combine (3) with (4):
$$f(-x)=f(x)f(-x)=f(4y)f(-4y)=1.$$
We get $f(-x)=1$, and we can flip the sign of the $-x$ to get that
$f(x)=1$ for all x
Answer: Assuming that $ f(0)=1$, you got
for $ y\in \Bbb R $,
$$f(4y)=f(2y)=f(y)=f(\frac y2)$$
$$=...=f(\frac{y}{2^n})$$
for each $ n\ge 0$.
but by continuity of $ f $ at $ 0$,
$$\lim_{n\to +\infty}f(\frac{y}{2^n})=f(0)=1$$
thus
$$(\forall y\in \Bbb R)\;\; f(y)=1$$
Answer: Ryan's answer is showing how to finish the argument you are making. This answer provides alternative way to solve the equation without splitting into the cases in the first place.
Substituting $y/2$ in place of $y$, we get functional equation $f(x)f(y)=f(x+2y)$, which is little more symmetric. If we now swap $x$ and $y$, we get $f(x+2y)=f(y+2x)$. Put $y=-2x$ and observe that $f(-3x)=f(0)$. Finally, substitute $-x/3$ in place of $x$ and get $f(x)=f(0)$, hence $f(x)$ is a constant function. Let $f(x)=a$, putting into the original equation this gives $a^2=a$, so $a=0$ or $a=1$. Thus $f(x)=0$ and $f(x)=1$ are the only solutions.


Linux RHEL cluster

Question: I'm trying to setup a PCS cluster on two nodes running Red-hat, and did successfully, I want to setup syslog server (rsyslog) in Active/Passive mode.
I created the cluster and added the resources, I care about the IPAddr2 resource.
I'm facing an issue which is: the virtual IP is showing it's active on one node when running the pcs status command, but when I send a syslog messages to this virtual IP, it's reflected on both nodes (node1,node2) which cause a duplicates in the logs. that's it, when I run tcpdump on both nodes, they both receive the traffic.
how to configure it to be active only on one node only (active/passive) not on both, and when that node fails the second node should start listening for the logs?
current cluster config:
[root@node1 heartbeat]# pcs status
Cluster name: Syslog
Stack: corosync
Current DC: node2 (version 1.1.20-5.el7-3c4c782f70) - partition with quorum
Last updated: Wed Dec 11 22:10:45 2019
Last change: Wed Dec 11 18:36:32 2019 by root via crm_resource on node1

2 nodes configured
1 resource configured

Online: [ node1 node2 ]

Full list of resources:

 Resource Group: Rsyslog
     rsyslog_vIP    (ocf::heartbeat:IPaddr2):   Started node1

Daemon Status:
  corosync: active/enabled
  pacemaker: active/enabled
  pcsd: active/enabled

I used this command to add the virtual IP:
pcs resource create rsyslog_vIP IPaddr2 ip=10.10.1.32 cidr_netmask=24 op monitor interval=5s --group=Rsyslog

thanks for your support!
Comment: You described you issues, but if you want that someonel help you, you need to show cluster config.
Comment: thank you, post updated to show the cluster config.
Comment: You have only a virtual ip configured, that's right, but you need to check the rsyslog configuration of your nodes, because, the cluster uses rsyslog too and maybe is normal the logs are replicated, use logger command to test.
Answer: The cluster nodes use rsyslog too to replicate the logs, if you want to have a clustered rsyslog, you need to have an specific of rsyslog binding on the virtual ip and use the rsyslog resource agent:
https://github.com/ClusterLabs/resource-agents/blob/master/heartbeat/rsyslog.in

Comment: hi, I've tried this script and placed it in the /usr/lib/ocf/resource.d/heartbeat and renamed it to rsyslogd and give it execute permission, and when I add the rsyslog service as a resource by this command : `pcs resource create rsyslog ocf:heartbeat:rsyslogd configfile="/etc/rsyslog.conf" statusurl="" --group=Rsyslog` , I get the following error : `Error: Agent 'ocf:heartbeat:rsyslogd' is not installed or does not provide valid metadata: Metadata query for ocf:heartbeat:rsyslogd failed: Input/output error, use --force to override` . is there a configuration required to fix it? thank you.
Comment: OCF_ROOT=/usr/lib/ocf /usr/lib/ocf/resource.d/rsyslogd meta-data

Linux RHEL cluster


Prove $\sum_{k=0}^{r}\binom{n}{k}\binom{n}{r-k}\left(-1\right)^{k}=\left(-1\right)^{\frac{r}{2}}\binom{n}{\frac{r}{2}}$ for $r$ even.

Question: How it can be shown that:

$$\sum_{k=0}^{2r}\left(-1\right)^{k}\binom{n}{k}\binom{n}{2r-k}=\left(-1\right)^{r}\binom{n}{r}$$

$$
\begin{align}
\sum_{k=0}^{2r}\left(-1\right)^{k}\binom{n}{k}\binom{n}{2r-k}
&=\left(-1\right)^{n}\sum_{k=0}^{2r}\binom{n}{k}\binom{k-2r-1}{n-2r+k}\tag{1}\\
&=\left(-1\right)^{n}\sum_{k=0}^{2r}\binom{n}{k}\sum_{l}^{}\binom{k}{n-l}\binom{-2r-1}{-2r+k+l}\tag{2}\\
&=\left(-1\right)^{n}\sum_{k=0}^{2r}\sum_{l}^{}\binom{n}{n-l}\binom{l}{n-k}\binom{-2r-1}{-2r+k+l}\tag{3}\\
&=\left(-1\right)^{n}\sum_{l}^{}\binom{n}{l}\binom{l-2r-1}{l-2r+n}\tag{4}\\
&=\sum_{l}^{}\binom{n}{l}\binom{n}{2r-l}\left(-1\right)^{l}\tag{5}
\end{align}
$$

$(1)$: Pascal's rule and negative binomial coefficients
$(2)$: Converse of Vandermonde's convolution
$(3)$: applying the identity $\binom{n}{k}\binom{k}{r}=\binom{n}{r}\binom{n-r}{n-k}$
$(4)$: Vandermonde's convolution
$(5)$: negative binomial coefficients

The final answer depends on the alternating sign Vandermonde convolution.
It's known that:

$$\sum_{k=0}^{r}\binom{n}{k}\binom{n}{r-k}\left(-1\right)^{k}=\left(-1\right)^{\frac{r}{2}}\binom{n}{\frac{r}{2}}\tag{I}$$

For $r$ even.
So setting $2r \mapsto r$ follows the result, but how even $\text{(I)}$ can be proved?

Source : math.wvu.edu
Answer: left hand side is the coefficient of $x^{r}$ from $(1-x)^{n}(1+x)^{n}$.
right hand side is the coefficient of $x^{r}$ from $(1-x^{2})^{n}$.
Answer: $$S=\sum_{k=0}^{2r} (-1)^k {n \choose k} {n \choose 2r-k}$$
$$S=[x^{k+2r-k}] (1-x)^n (1+x)^n= [x^{2r}] (1-x^2)^n= (-1)^r {n \choose r}.$$
Here $[x^j]$ means the co-efficient of $x^j$ in the given expression.
Comment: So can we say $$\left[x^{i}\right]\left[x^{j}\right]\left(...\right)=\left[x^{i+j}\right]\left(...\right)$$?
Comment: Yes you got it right.


What PID is making outbound connections on port 25?

Question: What is the most ready way to log the PID and process name of anything making an outbound connection on port 25? This is on a 2008 x32 server without the windows firewall enabled.
I'm decommissioning and old mail server and unfortunately a lot of the processes were defined by hand pointing to this host. I've got over 90% of the configuration updated but the remainder is a bit of a mystery.
I was thinking about using the following but it'll generate a lot of noise since this is a web server. I'm also not sure if it would work since the windows firewall is disabled.
<code>auditpol /set /subcategory:"Filtering Platform Connection" /success:enable /failure:enable
</code>
Comment: netstat -b says `Displays the executable involved in creating each connection or
listening port. In some cases well-known executables host
multiple independent components, and in these cases the
sequence of components involved in creating the connection
or listening port is displayed. In this case the executable
name is in [] at the bottom, on top is the component it called,
and so forth until TCP/IP was reached. Note that this option
can be time-consuming and will fail unless you have sufficient
permissions.`
Comment: as an alternative you could install netmon 3.4 on it, but I'd do the netstat routine 1st.
Comment: Have a look at the interval part of netstat, you could have it run every x seconds.. possibly pipe it through the windows equivalent of grep.. Also look at -o which will give you the process id, if you started piping itinto a log file filtering on port 25, it shouldn't get too huge one hopes..
Comment: @NickW - That would require running it whist the email is being generated though wouldn't it? I've never used netstat used for prolonged data collection.
Comment: Findstr seems to be the windows equiv :)
Comment: @NickW, why not put that as the answer? Also, netmon, wireshark, etc.
Comment: @Ben, because in all honesty, I don't know if that was of any worth to him :)
Answer: Use one of the following port logging tools:

Port Reporter tool - http://support.microsoft.com/kb/837243
TCPView
FPort v2.0 - TCP/IP Process to Port Mapper
APorts - Active Ports


Define $I_n=\int_0^1\frac{x^n}{\sqrt{x^2+1}}dx$ for every $n\in\mathbb{N}$. Prove that $\lim_{n\to\infty}nI_n=\frac{1}{\sqrt 2}$.

Question:
Question: Define $I_n=\int_0^1\frac{x^n}{\sqrt{x^2+1}}dx$ for every $n\in\mathbb{N}$. Prove that $$\lim_{n\to\infty}nI_n=\frac{1}{\sqrt 2}$$.

My approach: Given that $I_n=\int_0^1\frac{x^n}{\sqrt{x^2+1}}dx, \forall n\in\mathbb{N}.$ Let us make the substitution $x^n=t$, then $$nI_n=\int_0^1\frac{dt}{\sqrt{1+t^{-2/n}}}.$$
Now since $0\le t\le 1\implies \frac{1}{t}\ge 1\implies \left(\frac{1}{t}\right)^{2/n}\ge 1 \implies 1+\left(\frac{1}{t}\right)^{2/n}\ge 2\implies \sqrt{1+\left(\frac{1}{t}\right)^{2/n}}\ge \sqrt 2.$
This implies that $$\frac{1}{\sqrt{1+\left(\frac{1}{t}\right)^{2/n}}}\le\frac{1}{\sqrt 2}\\ \implies \int_0^1 \frac{dt}{\sqrt{1+\left(\frac{1}{t}\right)^{2/n}}}\le \int_0^1\frac{dt}{\sqrt 2}=\frac{1}{\sqrt 2}.$$
So, as you can see, I am trying to solve the question using Sandwich theorem.
Can someone help me to proceed after this?
Also, in $$\lim_{n\to\infty}nI_n=\lim_{n\to\infty}\int_0^1\frac{dt}{\sqrt{1+t^{-2/n}}},$$ the limit and integral interchangeable?
Comment: [This](https://math.stackexchange.com/q/128823/478779) answers your question.
Answer: Actually you are done. You already have: $$nI_n=\int_0^1\frac{dt}{\sqrt{1+t^{-2/n}}}$$ hence $$\begin{align}\lim_{n\to\infty} nI_n &= \lim_{n\to\infty}\int_0^1\frac{dt}{\sqrt{1+t^{-2/n}}} \\ &= \int_0^1 \lim_{n\to\infty} \frac{dt}{\sqrt{1+t^{-2/n}}} \\ &=  \int_0^1\frac{dt}{\sqrt{1+1}} = \frac{1}{\sqrt{2}} \end{align}$$
You can exchange limit and integration due to dominated convergence theorem.
Answer: You can still use Sandwich theorem, if you haven't yet seen dominated convergence theorem :
Let $ n $ be a positive integer.
As you said, using the substitution $ \left\lbrace\begin{aligned}y&=x^{n}\\ \mathrm{d}y &=n x^{n-1}\,\mathrm{d}x\end{aligned}\right. $, we get : $$\int_{0}^{1}{\frac{n x^{n}}{\sqrt{1+x^{2}}}\,\mathrm{d}x}=\int_{0}^{1}{\frac{y^{\frac{1}{n}}}{\sqrt{1+y^{\frac{2}{n}}}}\,\mathrm{d}y}$$
Meaning, we have : \begin{aligned}\left|\frac{1}{\sqrt{2}}-n I_{n}\right|&=\left|\int_{0}^{1}{\left(\frac{1}{\sqrt{2}}-\frac{y^{\frac{1}{n}}}{\sqrt{1+y^{\frac{2}{n}}}}\right)\mathrm{d}y}\right| \\ &=\left|\int_{0}^{1}{\frac{\sqrt{1+y^{\frac{2}{n}}}-\sqrt{2}y^{\frac{1}{n}}}{\sqrt{2\left(1+y^{\frac{2}{n}}\right)}}\,\mathrm{d}y}\right|\\ &=\int_{0}^{1}{\frac{1-y^{\frac{2}{n}}}{\sqrt{2\left(1+y^{\frac{2}{n}}\right)}\left(\sqrt{1+y^{\frac{2}{n}}}+\sqrt{2}y^{\frac{1}{n}}\right)}\,\mathrm{d}y}\end{aligned}
Since $ \left(\forall y\in\left[0,1\right]\right),\ \sqrt{2\left(1+y^{\frac{2}{n}}\right)}\left(\sqrt{1+y^{\frac{2}{n}}}+\sqrt{2}y^{\frac{1}{n}}\right)\geq \sqrt{2}+\sqrt{2}y^{\frac{2}{n}}\geq 1 $, we have : $ \int\limits_{0}^{1}{\frac{1-y^{\frac{2}{n}}}{\sqrt{2\left(1+y^{\frac{2}{n}}\right)}\left(\sqrt{1+y^{\frac{2}{n}}}+\sqrt{2}y^{\frac{1}{n}}\right)}\,\mathrm{d}y}\leq\int\limits_{0}^{1}{\left(1-y^{\frac{2}{n}}\right)\mathrm{d}y} $, and thus : $$ \left|\frac{1}{\sqrt{2}}-n I_{n}\right|\leq\int_{0}^{1}{\left(1-y^{\frac{2}{n}}\right)\mathrm{d}y}=\frac{2}{n+2}\underset{n\to +\infty}{\longrightarrow}0 $$
Hence : $$ \lim_{n\to +\infty}{nI_{n}}=\frac{1}{\sqrt{2}} $$
Comment: Did the $2$ disappear from the denominator? $\sqrt{1+y^{2/n}}$ instead of $\sqrt{2\left(1+y^{2/n}\right)}$
Comment: You're right. I'll fix it. But it won't change much.
Answer: you can use the Binomial series
$${{\left( 1+{{x}^{2}} \right)}^{-1/2}}=\sum\nolimits_{k=0}^{\infty }{\left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right){{x}^{2k}}}$$
$${n{I}_{n}}=n\int_{0}^{1}{{{x}^{n}}{{\left( 1+{{x}^{2}} \right)}^{-1/2}}dx}=n\sum\nolimits_{k=0}^{\infty }{\left\{ \left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right)\int_{0}^{1}{{{x}^{2k+n}}dx} \right\}}=\sum\nolimits_{k=0}^{\infty }{\frac{n\left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right)}{\left( 2k+n+1 \right)}}$$
$$\underset{n\to \infty }{\mathop{\lim }}\,{n{I}_{n}}=\underset{n\to \infty }{\mathop{\lim }}\,\sum\nolimits_{k=0}^{\infty }{\frac{n\left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right)}{\left( 2k+n+1 \right)}}=\sum\nolimits_{k=0}^{\infty }{\underset{n\to \infty }{\mathop{\lim }}\,\frac{n\left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right)}{\left( 2k+n+1 \right)}}=\sum\nolimits_{k=0}^{\infty }{\left( \begin{align}
  & -1/2 \\
 & \ \ k \\
\end{align} \right)}={{\left( 1+1 \right)}^{-1/2}}=\frac{1}{\sqrt{2}}$$
Answer: Since $n/(n+1)\to 1$ the desired limit is equal to the limit of $$(n+1)\int_{0}^{1}\frac{x^n}{\sqrt{1+x^2}}\,dx=\left.\frac{x^{n+1}}{\sqrt{1+x^2}}\right|_{x=0}^{x=1}+\int_{0}^{1}\frac{x^{n+2}}{(1+x^2)^{3/2}}\,dx$$ and this is same as $$\frac{1}{\sqrt{2}}+\int_{0}^{1}\frac{x^{n+2}}{(1+x^2)^{3/2}}\,dx$$ The integral above clearly lies between $$\frac{1}{2\sqrt{2}}\int_{0}^{1}x^{n+2}\,dx=\frac{1}{2\sqrt{2}(n+3)}$$ and $$\int_{0}^{1}x^{n+2}\,dx=\frac{1}{n+3}$$ and thus by Squeeze Theorem tends to $0$. Therefore the desired limit is $1/\sqrt{2}$.
The same technique can be used to prove more generally that $$n\int_{0}^{1}x^nf(x)\,dx\to f(1)$$
Answer: Yet another approach is to use integration by parts to obtain
\begin{equation*}
I_{n} + I_{n-2} = \int_{0}^{1}x^{n-2}\sqrt{1+x^{2}}\,\mathrm{d}x = \frac{\sqrt{2}}{n-1} - \frac{1}{n-1}I_{n}
\end{equation*}
for $n \geq 2$, from which we get
\begin{equation*}
nI_{n} = \sqrt{2} - (n-1)I_{n-2} = \sqrt{2} - (n-2)I_{n-2} - I_{n-2}. \tag*{(1)}
\end{equation*}
Define $S_{n} = nI_{n}$ for each $n\in \mathbb{N}$. You have already shown that the sequence $\{S_{n}\}_{n\geq 2}$ is bounded above by $1/\sqrt{2}$, and note also that
\begin{align}
S_{n+1} - S_{n} &= \int_{0}^{1}\frac{(n+1)x^{n+1}-nx^{n}}{\sqrt{1+x^{2}}}\,\mathrm{d}x \\
&\geq \frac{1}{\sqrt{2}}\int_{0}^{1}\big((n+1)x^{n+1} - nx^{n}\big)\,\mathrm{d}x \\
&= \frac{1}{\sqrt{2}(n+1)(n+2)} > 0
\end{align}
so that the sequence $\{S_{n}\}_{n\geq 2}$ is increasing. Thus by the monotone convergence theorem, $S_{n}$ converges to a limit $L$. It is therefore valid to take the limit as $n \to \infty$ on both sides of $(1)$, noting that $I_{n-2} \to 0$, to find that
\begin{equation*}
L=\sqrt{2} - L
\end{equation*}
or
\begin{equation*}
L = \frac{1}{\sqrt{2}}.
\end{equation*}


TweetSharp - TwitterService send direct message

Question: i am using the latest version of tweetsharp from their site (TweetSharp.Next - Version 2 preview 7)
whenever i try and call SendDirectMessage on the twitter service:
TwitterDirectMessage dm = TwitterService.SendDirectMessage("UserImSendingTo", "My twitter message");

i get an error:
Argument
Value cannot be null.\r\nParameter name: types

What is going on? I'm definitely authenticated as i can do everything else - is there a bug in TweetSharp?
Comment: Looks that way; (or you've not configured it correctl); try filing a bug on their site: http://tweetsharp.codeplex.com/workitem/list/basic
Comment: Thanks - have submitted a bug ticket http://tweetsharp.codeplex.com/workitem/75
Answer: This has been solved by the latest release of tweet sharp


How can I store an Axios response array of object in a React State (with TypeScript)

Question: I'm sorry in advance, this is for a professional project and I can't detail things, so I gotta explain things without telling the true terms.
I'm sending a GET request to an API. This API sends a response in this format :
[0:
 [
   0: { permission: 1
       thing: { title: 'title' id: '1234'}
      }
   1: { permission: 1
       thing: { title: 'title2' id: '5678'}
      }
 ]
]

In my code, I have a state (use hooks) called things, and I wanna store the 'things' Axios send in response. More clearly, I wanna store the 0 and the 1 inside the big 0.
I made an interface like this one :
interface IThing {
id: string;
title: string;
permission: number;
};

in order to type my state like this :
const [things, setThings] = useState<IThing[]>();

Now, here's the function I use to get data from Axios and try to store it in my state (maybe it's important to precise that this function is in a useEffect) :
const getMyThings = async () => {
  try {
    const getThings = await axios.get(
      "url",
      {
        headers: {
          ...
        },
      }
    );

    const result = getThings.data;

    if (things) {
    const newThings = [...things];
    console.log(newProjects);
    newThings.push(result);
    setThings(newThings);
    console.log(projects);
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.log(error.response);
    } else {
      console.log(error);
    }
  }

In this function, the console.log(result) print the axios response.
But once I push it in the state, a console.log() of things always returns undefined.
I also tried with this :
const newThings = [...(things || [])];
    newThings.push(result);
    console.log(newThings);
    setThings(newThings);
    console.log(things);

but the same thing happen : the console.log(newThings) returns the axios response, but the console.log(things) returns undefined.
One thing I saw is that my state is inferred by TypeScript as IThing | undefined, it probably comes from here but I don't know what to do as I'm new with TypeScript.
Thanks in advance for your help!
Comment: `but the console.log(things) returns undefined.` That's expected. Calling `setThings` does not change the value in the local variable `things`, so if it was `undefined` before, it's `undefined` after. Instead, it requests react to re-render the component. That new render will get a new set of local variables. If you'd like to verify that it rerendered with the new array, then put a log statement in the body of the component.
Comment: You must check  `console.log(things)` update in `useEffect` with dependency, because  `setThings(newThings);` is asyncronous
Answer: In the simplest terms, the 'things' in your state can be only updated once the whole function concludes. When you the set the new state, the component re-renders after your function is over.
If you log the 'things' in the main component or outside this function, it will show you the new values but you cannot expect it to update while your function is still running.


Creating MySql log

Question: Helllo, My question is the following: using php, is it possible to create a log of all the interactions with the MySQL database which in general can be accessed by phpMyadmin. Is there a specific query or an example that I can look at?
Thank you for your time.
Answer: Use trigger command. First create a log table for the specific table then insert all the trigger outputs there.
Here's the sample:
CREATE TABLE `sales_category` (
    `salescatid` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    `salescatname` VARCHAR(128) NOT NULL,
    `salescatdesc` VARCHAR(512) NOT NULL,
    UNIQUE INDEX `salescatname` (`salescatname`),
    UNIQUE INDEX `salescatid` (`salescatid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB

2. Create table for log

CREATE TABLE `category_log` (
    `action` ENUM('CREATE','UPDATE','DELETE') NULL DEFAULT NULL,
    `salescatid` INT(10) UNSIGNED NOT NULL,
    `salescatname` VARCHAR(255) NOT NULL,
    `salescatdesc` VARCHAR(255) NOT NULL,
    INDEX `id` (`salescatid`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB;

3. Add triggers

    //FOR ADD

    DELIMITER #
    CREATE TRIGGER ai_category
    AFTER INSERT ON sales_category
    FOR EACH ROW
    BEGIN
        INSERT INTO category_log(action,salescatid,salescatname,salescatdesc)
        VALUES('CREATE',NEW.salescatid,NEW.salescatname,NEW.salescatdesc);
    END;#

    //FOR UPDATE

    DELIMITER #
    CREATE TRIGGER au_category
    AFTER UPDATE ON sales_category
    FOR EACH ROW
    BEGIN
        INSERT INTO category_log(action,salescatid,salescatname,salescatdesc)
        VALUES('UPDATE',NEW.salescatid,NEW.salescatname,NEW.salescatdesc);
    END;#

    //FOR DELETE

    DELIMITER #
    CREATE TRIGGER ad_category
    AFTER DELETE ON sales_category
    FOR EACH ROW
    BEGIN
        INSERT INTO category_log(action,salescatid,salescatname,salescatdesc)
        VALUES('DELETE',OLD.salescatid,OLD.salescatname,OLD.salescatdesc);
    END;#

Is this what you are looking for? This is CRUD process but it is done thru SQL commands. If you what to call this I think you should put this in a function.. I am also a beginner so if there's a bug kindly tell me also. Goodluck.
Answer: There is simple way to capture SQL log. this log called general log. it captures all sql executed by all clients.
to enable general log.
mysql> SET GLOBAL general_log = 'ON';

where is log located?
mysql> SHOW variables like '%general_log%';
+------------------+--------------------+
| Variable_name    | Value              |
+------------------+--------------------+
| general_log      | ON                 |
| general_log_file | /tmp/your_path.log |
+------------------+--------------------+

you want change location?
mysql> SET GLOBAL general_log_file = 'what you want';

to turn off log
mysql> SET GLOBAL general_log = 'OFF';

be careful, general log will grow big, after test done, always turn off the log
Comment: Wow, it's great answer. Better than my answer. I will search and study for that also. :)
Comment: @Jerielle to be frankly with, I also learned new skill from you answer ;-)
Answer: To enable the query log, put this in /etc/my.cnf in the [mysqld] section
log   = /path/to/query.log

remember that this logfile can grow very big on a busy server
update:
as of mysql 5.1.12 you should use
general_log=1

with mysql 5.1.29, the log option is deprecated. to specify the logfile use
general_log_file=/path/to/query.log

instead. See http://dev.mysql.com/doc/refman/5.6/en/query-log.html
Enable Query logging on the database (Note that the string 'table' should be put literally and not substituted by any table name)
SET global general_log = 1;
SET global log_output = 'table';

View the log
select * from mysql.general_log

Disable Query logging on the database
SET global general_log = 0;

Refer: http://www.jovicailic.org/2012/07/how-to-enable-general-query-log-in-mysql-under-linux/

Creating MySql log


Split huge text files using java to Read them

Question: I am working on parsing a log file of size more than 2Gb. The requirement is to print some predefined words along with time stamp to a text/csv file. I have written the below code and when using small piece of log file  its working fine but with 2GB of actual input log file I am getting out of memory error. please help me in resolving this.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.sql.Time;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

    public class MyFileParser{
        private static final String COMMA_STR = ",";
        private static final String NEW_LINE_STR = "\n";

        public static void main(String[] args)  throws IOException{

            String searchString = "" ;
            String line = null;
            boolean searchFlag = false;
            StringBuffer sbr = new StringBuffer();

            FileReader reader = new FileReader("C:\\Users\\Kiran\\Desktop\\mylogs\\File.txt");
            FileWriter writter = new FileWriter("output.csv");
            BufferedReader br = new BufferedReader(reader);

            while( (line = br.readLine())  != null){

                if(line.contains("prompf1") ){
                    searchString= "prompf1";
                    searchFlag = true;
                }

                else if (line.contains("prompf9")){
                    searchString = "prompf9";
                    searchFlag = true;
                }
                    if(searchFlag){
                        String timeStamp = "";
                        int count = 0;
                    char[] charArray =  line.toCharArray();
                    for(int i=0 ; i <= charArray.length ; i++){
            // to remove [] at the begining and ending of time stamp in the file
                        if(charArray[i] == '[' || charArray[i] == ']'){
                            count ++ ;
                        }
                               else
                        timeStamp= timeStamp+  charArray[i];
                        if(count == 2){
                            break ;
                        }

                    }
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = formatter.parse(timeStamp);
                    searchString = date + COMMA_STR+ searchString;
                    sbr.append(searchString);
                    sbr.append(NEW_LINE_STR);
                    System.out.println(searchString);

                }

            }

            writter.write(sbr.toString());
            writter.flush();
            writter.close();

        }

    }

Answer: You are reading all the lines into a StringBuffer and then writing them out in a single operation. That's unnecessary and will cause memory problems if there are many such lines.
What you should do is write each line as soon as you have it, inside the reading loop. Then you won't need to buffer anything and the memory consumption should drop drastically.
Also do you actually have dateTime = timeStamp+  charArray[i]; in your code? Shouldn't that be timeStamp = timeStamp+  charArray[i];? Anyway, it would be more efficient to find the [ and ] with String#indexOf() and get the date string with String#substring().
And there is no need to create a new SimpleDateFormat for each line - create it before the reading loop.
Comment: yes you are right..that line should be timeStamp = timeStamp+  charArray[i];  I will modify code as per your comments. But I am still not sure these changes will handle out of memory error or not... Is there any way to split them into temp files and read ?
Comment: @kiran Splitting the file would help if you needed to read it into memory all at once. But you don't need to do that if you read it line by line and write the lines you choose immediately without adding them into a `StringBuffer`.
Comment: Ok let me test the code with modified changes. I will post update here if I am facing any problem..Thanks again


What query would I use for this

Question: I have a Relationship table that links teachers to students
Teacher   Student
1         1
1         2
2         1
2         3

The Students table then has specific data about the students
Id    Date of birth   First Name
1     1990-10-10      Bill Smith
2     1989-01-03      Adam Smithson

I want to select all the students who are students of teacher 1. Right now i do this way (this is propel ORM syntax).
$relationships = RelationshipQuery::create()->filterByTeacher($teacherid)->find();

foreach($relationships as $relationship){
  $studentId = $relationship->getStudent();

  //use the studentId to get the actual student object
  $student = StudentQuery::create()->findPk($studentId);

  //after I get the student, I add it to an array
  $students[] = $student;
}

The problem with this is that I end up with an array, and not the usual propelCollection that we end up with when we do a normal ->find(). Is there a way to clean up this query a bit (use joins or something like that) so that I end up with a PropelCollection from the start?
Answer: You should define your schema for the relationship like this: http://www.propelorm.org/wiki/Documentation/1.5/Relationships#Many-to-ManyRelationships
The code you're asking for is very easy:
$teacher = TeacherQuery::create()->findOneById($teacherId);
$students = $teacher->getStudents(); //Your students collection

What query would I use for this


How to theme view header Global: Text Area?

Question: I'm trying to stick a flexbox in a view's Header Global: Text area and there's a wrapping paragraph tag that I'm trying to theme away. The views-view.tpl.php only has 'print $header' inside the 'view-header' div so the errant 'p' must be rendered into the $header variable.
I can trim the paragraph tags from the $header variable in template.php with a post render hook, but I'd rather modify a tpl file.
Answer: It seems the
 tag is inserted on the Global: Text Area header, but not on the Global: Unfiltered text. In case it is acceptable for you to use this one, it might fix your issue.
(by the way, in version 8 of Views, the
 tag is not inserted any more for the Global: Text Area header)
Answer: In settings.php add
$conf['theme_debug'] = TRUE;

View the source of the page and you will see the theme files being rendered and possible alternatives.
Comment: Neat trick, but it didn't help in this case. The comments just say that views-view.tpl.php is the template powering the header bit.
Comment: Yes I think that's it. The last time I did this I overwrote the page.tpl.php and custom loaded the lot. I was trying to combine a bunch of views and blocks though so overkill. You could try making the header text format 'php' and just printing the header that you want.


Setting the text-box value as the subject in Mailto functionality.

Question: I have created a custom html helper in MVC for MailTo functionality.
But I got an requirement to set the subject of the mail to the value user have entered in another textbox field.
I am not sure how to achieve this, Can some body please help?
Thanks
Html Helper
public static MvcHtmlString SendMailTo(this HtmlHelper helper, string emailAddress, string subject, string displayText)
    {
        var sb = string.Format("{3}",
            CharEncode("mailto:"), CharEncode(emailAddress),CharEncode("?subject=" +subject), CharEncode(displayText));

        return new MvcHtmlString(sb);
    }

    public static string CharEncode(string value)
    {
        var enc = System.Text.Encoding.Default;
        var retval = "";
        for (var i = 0; i < value.Length; i++)
        {
            retval += "&#" + enc.GetBytes(new[] { Convert.ToChar(value.Substring(i, 1)) })[0] + ";";
        }
        return retval;
    }

View:

                    @Html.LabelFor(m => m.ApplicationId, new { @class = "col-sm-3 control-label" })

                        @Html.TextBoxFor(m => m.ApplicationId,  new {@class = "form-control"})

                    @Html.SendMailTo("firstname.lastname@example.com", "Password Request: ", "Request Password")
                    <button type="submit" class="button">Sign in</button>

Answer: You can not get that value without any jquery code.
You should make an event on keyup ( for example ) on your texbox ( this is the one which is used as an user mail input )
Put your email form in a partial view and update that partial when that event is triggered.
INFO :
A) To render your ParialView use can Html.Partial helper -> Example here
B) To get textbox value you can use following jquery code
    `$('.class of your textbox').val()' //will return a string

C) To update your partial view
   c.1 Place your partial view in a `div element`
   c.2 Make an `ajax` call from `jquery` to an action which returns your partial view filled with data

      Example for c.2:

           *AJAX*

           $.ajax({
              type:"GET",
              data:{
                  mail:$('.class of your textbox').val()
              },
              success: function(response){
                 $(".class of your div").html(response.Html);
              }
              error: function(response){
                 // whatever you want to do
              }
           });

          *Controller Action*

           public JsonResult(string mail)
           {

              var model = new CustomModel(){ Mail=mail };  // custom class to your as model for your partial view

              var html = RenderPartial(...)  // method you can find in the link posted below
              return Json(
              {
                Html=html
              },JsonRequestBehavior.AllowGet)
           }

Link I was writing about few lines above - follow this link
You can call that ajax on whatever event you want for your textbox.
Comment: Many Thanks, Do you have any sample code which I can refer to?
Comment: Instead of adding partial view, can I just add some jquery code to  send the email?
Comment: If you don't want to display destination mail somewhere else besides that textbox before sending, sure. Just make an onclick action for your link/button.  PS: I've added some code
Comment: Thanks for adding the code, Yes this is the only page where I am having this functionality. my worry now is how to validate the form when user click on this link, I want user to enter the applicationid before they click on this link, I tried adding $('#LoginForm').validate(); but this is not validating the form.


Why the faithful $D$-submodule of $F$ which is finitely generated as $D$ module, $M=M^2$?

Question: I am studying the theorem that every Dedekind domain is integrally closed.  Here's the setup.
Let $D$ be a Dedekind domain, $F$ its field of fractions and let $u$ be an element of $F$ that is $D$-integral (there exists a monic polynomial $f(x)=x^n+a_1x^{n-1}+...+a_n$ such that $f(u)=0$).
Then, there exists a faithful $D[u]$ submodule of $F$ that is finitely generated as $D$ module. This submodule is $M=D1+Du+...+Du^{n-1}$.
I now wish to prove that this fractional ideal $M$ satisfies $M^2=M$, but I am having difficulties.
Would you help me, please?
Thank you in advance.
Comment: Maybe $M^2=D1M+DuM+...+Du^n-1M$ is included in $M$ since $M$ is regarded as a $D$-module which contains $1$. Also, $M$ is included in $M^2$ and hence $M=M^2$.
Comment: @Eric Wofsey I need to prove $M=M^2$ because from this it follows that $M=D$ since $M$ is a fractional ideal and hence invertible.
Answer: Just note that $M$ is none other than the ring $D[u]$ itself, since any higher power of $u$ can be reduced to an element of $M$ using $f(u)=0$.  Thus $M$ is closed under multiplication.
Comment: Thank you for your answer! Well, I understand why $M$ is a subring of $D[u]$ but I am not clear why it is the ring $D[u]$ itself. So, if $x$ is any element of $D[u]$ why is it in $M$?


Got a list of items and scores. How do I return a list with the highest item in each subfolder

Question: I got the list of items and their scores. How do I return a list with the highest item in each subfolder
from
[('../dir_a/1.png', 5.14),
 ('../dir_a/2.png', 5.15),
 ('../dir_b/3.png', 4.19),
 ('../dir_b/4.png', 3.81)]

To
[('../dir_a/2.png', 5.15),
 ('../dir_b/3.png', 4.19)]

Comment: This is just a program description. What did you code to solve it, where did your solution go wrong and where is your [mcve]?
Comment: See [ask] and please take the tour - we help you fix up your broken code, SO is no coding service that produces solutions ... generally.
Comment: Thx for the advice and trying to learn better next time...  I was trying to use pathlib.Path(i[0]) and then I still couldn't figure out the way in python to do something like argmax in Numpy. And then I came up to ask. Sorry for making an unpleasant movement.
Answer: import os

result = {}
lst = [('../dir_a/1.png', 5.14), ('../dir_a/2.png', 5.15), ('../dir_b/3.png', 4.19), ('../dir_b/4.png', 3.81)]

for p in lst:
    base_dir =  os.path.basename(os.path.dirname(p[0]))     #Use base dir as key
    if base_dir not in result:
        result[base_dir] = ("", 0)
    if p[1] > result[base_dir][1]:                          #check score
        result[base_dir] = (p)
print(result.values())                                      #Get values

Output:
[('../dir_a/2.png', 5.15), ('../dir_b/3.png', 4.19)]

Comment: thx for ure reply. Learned the os.path way to nail this down
Answer: Here is a way to do it using Pandas:
# Create example data frame
df = pd.DataFrame([('../dir_a/1.png', 5.14),
                   ('../dir_a/2.png', 5.15),
                   ('../dir_b/3.png', 4.19),
                   ('../dir_b/4.png', 3.81)], columns = ['path', 'score'])

# Split the file path by '/' and expand into columns with original data frame
df = pd.concat([df.path.str.split('/', expand=True), df], axis=1)

# Group the rows based on the directory name (column 1) and find the max score
df.groupby(1)['score'].max().reset_index()

       1  score
0  dir_a   5.15
1  dir_b   4.19

Then you can convert the values back into a list if need be.
Comment: Thx for ur answering. Panda is also a good way to do. Learn a lot
Answer: If you only ever need the max, you can put the directory in a dictionary and key off that, then keep the max.
from pathlib import PurePath

max_dict = {}
for path, val in lst:
    parent = PurePath(path).parent
    max_dict[parent] = max(max_dict.get(parent, float('-inf')), val)

Answer: Here is an one-liner :
a = [('../dir_a/1.png', 5.14), ('../dir_a/2.png', 5.15), ('../dir_b/3.png', 4.19), ('../dir_b/4.png', 3.81)]

f = [(next((x[0] for x in a if x[1]==max([v[1] for v in a if v[0].split('/')[1]==k])),k),max([v[1] for v in a if v[0].split('/')[1]==k])) for k in set([kk[0].split('/')[1] for kk in a])]

OUTPUT :
[('../dir_a/2.png', 5.15), ('../dir_b/3.png', 4.19)]


Using Ruler to Measure Irrational Number

Question: If I would draw a right triangle with legs of length 1 centimeter with a ruler then its hypotenuse should be equal to $\sqrt2$ which is an irrational number - therefore its decimal representation, which is the limit of the sequence
 $\lim_{n \to\infty}\sum_{i=0}^\infty{\frac{a_i}{10^i}}$, has infinitely many numbers after the interger part of$ \sqrt2$.
What exactly can the ruler measure when drawing such a triangle, considering the fact that we draw irrational number (which by definition is infinitely long)?
I hope the question is clear.
Thanks.
Comment: Define *ruler*.
Comment: Also, consider how would you measure $1/3$ with a metric or imperial ruler.
Comment: Why do you insist to discuss a number, which cannot be described by a finite sum of digit-multiples of powers of ten in terms of "long"?
Comment: not long, infinitely long.
Answer: If the ruler has marks at 0 cm, 1 cm, 2 cm,... then you will measure that the length of the hypotenuse is between 1 and 2 cm .
If the ruler has marks at 0 mm, 1 mm, 2 mm,... then you will measure that the length of the hypotenuse is between 14 and 15 mm .
So everything depends on where are the marks in the ruler. If it is a special ruler with a mark at $\sqrt2$ cm, then it will measure the exact length of the hypotenuse.
Answer: $\sqrt 2$ is irrational and thus the decimal period is infinite, however let's go back to calculus for a moment. Consider the following logical conundrum:
If I know it is 8ft to the door, and let's say I take a step halfway each time. Then before the first step, I have to cover 4ft first. Then 2ft, then 1ft, 0.5ft, 0.25ft.... etc. Movement should be impossible since there are an infinite number of points between each step. However, in calculus we learned that an infinite series converges to a point or diverges.
$\sqrt 2$ is approximated to be 1.4142, so as this decimal becomes longer, it eventually will converge to simply 1.4. The decimal period is infinite, however as it approaches $\infty$ the measurement becomes too small to comprehend.
Your ruler, undoubtedly contained infinite-many points on it, you just cannot see them.
Comment: The decimal expansion of $\sqrt 2$ never repeats!
Comment: @lhf, actually, the decimal expansion of $\sqrt2$ repeats a lot, just not periodically.


Python números primos | while

Question: Tenho o seguinte problema:
Escreva a função maior_primo que recebe um número inteiro maior ou igual a 2 como parâmetro e devolve o maior número primo menor ou igual ao número passado à função
Note que
maior_primo(100) deve devolver 97
maior_primo(7) deve devolver 7
Dica: escreva uma função éPrimo(k) e faça um laço percorrendo os números até o número dado checando se o número é primo ou não; se for, guarde numa variável. Ao fim do laço, o valor armazenado na variável é o maior primo encontrado.
Minha solução seria:
def éPrimo (k):
    div = 2
    while k % div != 0 and div <= k:
        div = div + 1
        if k % div == 0:
            k = k - 1
        else:
            print (k)

Eu estou muitíssimo convencido de que estou certo, ainda estou em um nível muito iniciante e se alguém puder me dar uma luz encima desses parâmetros básicos seria de grande ajuda.
Comment: Cade a função `maior_primo`? O problema até então me parece nela. Se bem que não entendi o enunciado da pergunta por falta de virgulas e pontuação, tem muito texto misturado, tá dificil de ter certeza do que você fez ou escreveu.
Comment: Sim, Realmente LINQ. Parece ser o mesmo curso. Muito obrigado.
Comment: Relacionada: [Como gerar 200.000 primos o mais rápido possível em Python?](https://pt.stackoverflow.com/q/231555/5878)
Answer: def ehPrimo(x):
    if x >= 2:
        for y in range( 2, x ):
            if not ( x % y ):
                return False
    else:
        return False

    return True

num = int(input("Entre com um numero: "))

for n in range( num, 0, -1 ):
    if ehPrimo(n) :
        print n
        break

Python números primos | while


Quais as principais diferenças entre um computador quântico e um computador convencional?

Question: Dizem que a computação quântica irá revolucionar a computação caso seja implementada de maneira bem sucedida. Por que isso? Quais as principais diferenças entre um computador quântico e um computador convencional que tornariam o primeiro muito mais rápido?
Comment: @mgibson: fatoração NÃO é um problema NP-hard! A complexidade exata ainda é um problema em aberto mas o consenso é de que o problema  da fatoração provavelmente tem complexidade intermediária, acima de P mas abaixo de NP-completo. Além disso até hoje não se sabe de nenhum problema NP completo que seja resolvido em tempo polinomial por um algoritmo quântico e existem evidências de que isso talvez seja impossível. [dê uma olhada na tabela na pag 6 desse pdf](http://cs.virginia.edu/~robins/The_Limits_of_Quantum_Computers.pdf)
Comment: Não sei falar das diferenças, mas um dos maiores *impactos* que a computação quântica traria seria sobre a segurança: não só ela abre novas possibilidades que hoje não existem, como também torna obsoletas várias técnicas das quais os sistemas atuais dependem enormemente, como as empregadas pelo SSL/TLS (seja RSA ou Curvas Elípticas). Alguns problemas até então considerados *NP-Hard* - como a fatoração - poderiam ser resolvidos em tempo polinomial dado um número suficiente de qbits. Um cenário desses demandaria um *upgrade* em larga escala para que a internet continuasse razoavelmente segura.
Comment: Carlos, eu não saberia dizer isso em geral, mas no caso específico da fatoração há o [algoritmo de Shor](http://en.wikipedia.org/wiki/Shor%27s_algorithm). A relação entre as classes NP e BQP é um problema em aberto. @Motta Sim, há bastante pesquisa no assunto [criptografia pós-*quantum*](http://en.wikipedia.org/wiki/Post-quantum_cryptography), incluindo algoritmos "normais" que são resistentes à computação quântica (a propósito, os hashes e a criptografia simétrica já o são, em sua maior parte). Como falei no meu 1º comentário, o problema é de natureza prática: o custo de um *upgrade* massivo.
Comment: Não foi reclassificado não, é só que esse é um erro bem comum que as pessoas fazem mesmo... Quanto ao link, faltou um "www." no começo. ops.
Comment: @mgibsonbr você saberia explicar por que/como com a computação quântica esses problemas NP-hard conseguiriam ser resolvidos em tempo polinomial?
Comment: Mas os algoritmos de criptografia seriam também quânticos ...
Comment: Seria interessante voce pesquisar artigos no google de preferencia artigos em ingles, pra isso que eles servem. São mt bons. Pois aqui voce vera mt acho e nao acho dizem ou n dizem, nos artigos os autores provam o pq isso e aquilo. ctza lendo  um dois ou tres artigos vc ja tera ctza como funciona computaçao quantica
Comment: Fazendo isso você mesmo podera responder essa pergunta citando fontes(links) de texto que você leu.
Comment: @hugomg [Estou vendo](http://en.wikipedia.org/wiki/Integer_factorization#Difficulty_and_complexity)... Na faculdade me disseram que era NP-hard, mas isso faz mais de 10 anos, e de todo modo pode ter sido falha dos meus professores (ou o problema pode ter sido reclassificado nesse meio tempo, não sei). Quanto ao NP-completo, concordo com tudo. P.S. O link que você passou parece quebrado...
Answer: Em um computador convencional, um determinado dado (i.e. um "bit") está sempre em um único estado - 0 ou 1. Em um computador quântico, esse mesmo dado (chamado "qubit") pode estar em qualquer sobreposição desses dois estados, até o momento em que ele é medido (colapsando para um único valor). Isso ocorre segundo as leis da Mecânica Quântica, que inclui coisas como o entrelaçamento (que é descrito como uma das bases da computação quântica, embora eu não saiba dizer qual é exatamente o papel dele).
O que torna um computador quântico mais rápido que um convencional é portanto a sua capacidade de progredir de um estado probabilístico para outro estado probabilístico sem a necessidade de enumerar todas as possibilidades envolvidas. Para entender isso, ajuda conhecer a classe de complexidade BPP:
Bounded-error Probabilistic Polynomial time
Um problema é dito estar na BPP se existe um algoritmo para ele com as seguintes propriedades:

Um componente aleatório (i.e. o algoritmo pode usar dados aleatórios ou tomar decisões aleatórias);
Tempo de execução polinomial em relação ao tamanho da entrada, no pior caso;
A resposta ("sim" ou "não") tem pelo menos 2/3 de chance de estar correta.

Estritamente falando, admitem-se respostas erradas, desde que a chance das mesmas seja inferior à das respostas certas (i.e. o valor 2/3 pode ser substituído por outro).

Todo problema em P está em BPP, entretanto há problemas em BPP que ainda não se sabe se está em P. O número desses problemas vêm diminuindo (ex.: até pouco tempo atrás, não existia algoritmo polinomial para se dizer se um número é ou não primo, apenas um algoritmo probabilístico), o que leva à conjectura que P = BPP, mas ainda existem casos.

Nota: além da classe BPP, há outras situações em que um algoritmo probabilístico é desejável. Por exemplo, não se pode garantidamente resolver um problema NP-Completo em tempo polinomial, mas poderia-se - em um busca exaustiva - empregar probabilidades para reduzir o espaço de busca. Em um computador convencional, isso não traz benefício algum entretanto...

OK, e como um algoritmo probabilístico funciona, já que existe uma grande possibilidade de erro? Simplesmente executando-o várias vezes de modo a reduzir a margem de erro. Se na primeira rodada há 1/3 de chance de erro, após a segunda há (1/3)*(1/3) = 1/9, após a terceira 1/27 e assim por diante. De modo que basta pegar os resultados de várias rodadas e verificar qual deles ocorre com mais frequência, e tomá-lo como o resultado certo.
Combinações
Um único bit pode estar somente em dois estados, 0 ou 1. Dois bits podem estar em quatro, 00, 01, 10 ou 11, três bits em oito, e assim por diante. Isso significa que se você partiu do estado 100 e aplicou alguma operação probabilística, há 1 chance em 8 de se chegar a qualquer um dos estados seguintes. Após várias operações em sequência, o número de possibilidades aumenta enormemente. Isso significa que é necessário executar um número muito grande de rodadas para se chegar a um resultado com um nível aceitável de confiança.
No caso da computação quântica, por outro lado, a própria sobreposição de estados guarda em si as probabilidades a partir das quais se chegou a um determinado estado. Assim, partindo do estado 100 se chega ao estado ??? após a primeira operação, ao estado ??? após a segunda, e assim por diante, até que todas as operações sejam executadas. Somente no final, quando o resultado for lido (i.e. os qubits forem medidos) é que um conjunto de valores concretos - tipo 010 - será obtido.
Explicando de uma outra forma, se no computador convencional se partiu de 100 e chegou a 101, a próxima etapa terá como base o estado 101. Se a primeira etapa foi repetida 20 vezes e em 17 delas se chegou ao 101, então a segunda etapa será executada 17 vezes com o estado 101 como base (e 3 vezes a partir de uma outra base). Digamos que a segunda etapa produziu 011 em 15 dessas repetições.
Já no computador quântico o resultado da primeira etapa será ???, com 85% de chance de ser 101, e o resultado da segunda etapa será ???, com pelo menos 75% de chance de ser 011 (85% * 88,2%). Tudo isso numa única execução! Enquanto o computador convencional teria de executar um alto número de vezes para se chegar ao mesmo resultado com um nível de confiança similar (e mais tantas vezes para se reduzir a margem de erro a um valor aceitável - algo que ambos, convencional e quântico, têm de fazer de qualquer forma).
Respondendo então à pergunta, o que torna o computador quântico tão mais rápido é a possibilidade de, em uma única sequência de operações, se chegar ao mesmo resultado que um computador convencional chegaria se executasse um conjunto muito maior de operações.
É um caso similar ao das placas de aceleração gráfica, onde são realizadas operações envolvendo vetores, matrizes, etc diretamente nos circuitos do hardware, sendo que as mesmas operações para serem executadas na CPU demandaria um conjunto bem maior de operações sobre tipos de dados mais simples (i.e. números), envolvendo loops. Nesse caso a escala da otimização é bem maior, mas em princípio tudo o que um computador quântico faz poderia ser simulado em um computador convencional (a Máquina de Turing Quântica continua sendo teoricamente equivalente à Máquina de Turing).


How To Use Facebook Real Time API To Get The Number Of Likes On My Page?

Question: I am trying to get real time updates of how many page like we have. I have been trying to use Facebooks real time API with no luck. I have looked for tutorials but the don't seem to be up to date. Does any one have any idea of how to get a real time count of Facebook likes from a page?
Thanks
Fran
Answer: You can´t use the Realtime API for that. The Realtime API is for new feed posts on the Page, for example. You can get the likes easily with a basic API call: https://developers.facebook.com/docs/graph-api/reference/v2.2/page
You will only get the current likes, of course. So you would need to refresh it every few seconds.
Comment: I got this from FB graph reference does this not mean you can get the likes?

"likes:
The number of users who like the Page. For Global Brand Pages this is the count for all pages across the brand."
Comment: yes? that´s exactly what i was pointing out in my answer. the link i posted shows that "likes" is a field of the page endpoint.


Propensity score matching with replacement: setting a limit on number of reuses

Question: We are using a propensity score model to built a control group in an observational study. We have tried several options and a 1 to 5 matching ratio with replacement ensures the best covariate balance.
Using replacements leads to high level of reuse. The treated group size in 2200 and the most reused individual in the matched control group is reused 42 times. Here is the distribution of number of uses of each individual in the control group:

I am concerned about this rate because these are survey data where the assignment of the treatment variable is prone to measurement error. Although the question was quite clear, it is possible that the highly reused individuals, people who have high propensity scores but are not treated, just did not understand the question properly, were tired and wanted to stop the survey, etc.
We have tried a reuse limit of 5 but it significantly impacts covariate balances.
We failed to find relevant advises in the literature, where covariate balance and common support are the two main worries.

Should we be worried about the high reuse rate? We know it will increase the variance, but does it also make the matching less reliable?
Are there any guidelines as to how to balance between number of reuse and covariate support, ie. how to chose a ceiling for the number of reuse?
Answer: Sadly I don't have good news. (Also, I'm assuming you're using the reuse.max option in MatchIt, in which case I'm glad that feature came in handy!) The number of reuses has not been discussed in the matching literature at all. Most applications either consider matching with replacement and no limit on reuses or matching without replacement. There are no other guidelines on this matter except generally to balance the precision of the remaining sample and its covariate balance.
Balance and variance are the main issues to be concerned about. You can examine the effective sample size (ESS) of the resulting matched sample to use as a guide for how precise the resulting estimate is. Ideally, you would do a power-analysis to determine how small this value can be before your sample size is too small to reliably detect the effect you believe to be there. If it is impossible to achieve balance with such an ESS, then your sample just doesn't contain enough information to validly estimate the causal effect without additional assumptions (e.g., of the functional form of the outcome model).
You might also consider using different matching methods. Template matching (method = "cardinality", ratio = NA in matchit()) can be a nice alternative if you are intent on retaining the ATT as your estimand. Full matching (method = "full") can be another good method that retains many of the advantages of matching with replacement but doesn't require manually figuring out this tradeoff.
Comment: thank you for the answer, and for your package. Indeed, we used `reuse.max` in `matchit()`. The ESS is still high with reuse. We'll read about the other methods you are suggesting and try them.