问:
I am getting an error when installing youtube-dl via the pip command on macOS High Sierra
Long story short, I am creating a discord bot and I need youtube-dl to do so. When I went to install it on terminal, I used the command

```<code>pip install youtube-dl
</code>```

and I got this

```<code>Collecting youtube-dl
  Using cached youtube_dl-2017.12.2-py2.py3-none-any.whl
Installing collected packages: youtube-dl
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/youtube_dl'
</code>```

I don't really know what to make of this or weather or not it is a bug with the pip command itself in High Sierra. Any help would be appreciated. Thanks!

答:
You're getting permission denied as current user do not have required permission therefore use sudo along with your command as follows:

```<code>sudo pip install youtube-dl
</code>```

or run terminal with root user and run your command.

Body:
Long story short, I am creating a discord bot and I need youtube-dl to do so. When I went to install it on terminal, I used the command

pip install youtube-dl

and I got this

Collecting youtube-dl
  Using cached youtube_dl-2017.12.2-py2.py3-none-any.whl
Installing collected packages: youtube-dl
Exception:
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/youtube_dl'

I don't really know what to make of this or weather or not it is a bug with the pip command itself in High Sierra. Any help would be appreciated. Thanks!

Body:
You're getting permission denied as current user do not have required permission therefore use sudo along with your command as follows:

sudo pip install youtube-dl

or run terminal with root user and run your command.


来源: stackexchange

问:
openMP Alternating direction implicit method
Hi I am trying to parralelize the calculation of this code with openMP. It is calculation of hydrodynamics vorticity with finite difference implicite method. I am using the Alternating direction implicit method to do so.

I would like to speed up its execution. (Here Nx=Ny=100)

The probleme is that using openMp this way slow down the code instead of speeding it up. I have try to specify the shared variable but this not helping much.
Any idea?

All the best

```<code>void ADI(double vort[][Ny], double psi[][Ny], double n[][Ny],
double cls[][Ny],double AAx[], double BBx[], double CCx[], double DDx[],
double AAy[], double BBy[], double CCy[], double DDy[],
double cx[][Ny], double cy[][Ny], double epsx[][Ny], double epsy[][Ny],
double vortx[], double vorty[Ny-2], double dx, double Dxs, double coefMass,
double coefMasCls)
{
    ////////////calcul sur y////////////
    //calcul coef ADI
    int i=0, j=0;

    #pragma omp parallel for private(Dxs,i) shared(psi,vort)
    for (i=0; i<Nx; i++) //Boundary condition sur x
    {
        vort[i][0]=(psi[i][0]-psi[i][1])*2/Dxs;
        vort[i][Ny-1] = (psi[i][Ny-1]-psi[i][Ny-2])*2/Dxs;
    }

    #pragma omp parallel for private(Dxs,j) shared(psi,vort)
    for (j=0; j<Ny; j++) //Boundary condition
    {
        vort[0][j] = (psi[0][j]-psi[1][j])*2/Dxs;
        vort[Nx-1][j] = (psi[Nx-1][j]-psi[Nx-2][j])*2/Dxs;

    }

    for (j=1; j<Ny-1; j++) //interior points
    {
        #pragma omp parallel for private(coefMasCls,coefMasCls,i) shared(psi,vort,n,cls)
        for (i=1; i<Nx-1; i++) //interior points
        {

            vort[i][j] = vort[i][j] - coefMass * (n[i+1][j]-n[i-1][j])- coefMasCls * (cls[i+1][j]-cls[i-1][j]);;

        }
        //i=0;
        //vort[i][j] = vort[i][j] + coefMass*(n[1][j]-n[1][j]);
        //i=Nx-1;
        //vort[i][j] = vort[i][j] + coefMass*(n[Nx-2][j]-n[Nx-2][j]);

    }

    for (i=1; i<Nx-1; i++) //interior points
    {
        for (j=1; j<Ny-1; j++) //interior points
        {

            AAy[j] = -.5 * ( .5 * (1 + epsy[i][j]) * cy[i][j-1] + dx);

            BBy[j] = 1 + dx + .5 * epsy[i][j] * cy[i][j];

            CCy[j] = .5 * ( .5 * ( 1 - epsy[i][j] ) * cy[i][j+1] - dx);

            DDy[j] = .5 * (.5 * ( 1 + epsx[i][j] ) * cx[i-1][j] + dx ) * vort[i-1][j]
            + ( 1 - dx - .5 * epsx[i][j] * cx[i][j] ) * vort[i][j]
            + .5 * (- .5 * ( 1 - epsx[i][j] ) * cx[i+1][j] + dx ) * vort[i+1][j];

            vorty[j] = vort[i][j];
        }

        DDy[1]=DDy[1] - AAy[1] * vort[i][0];  //the AA[0] are not taken into account in the tridiag methode. Include it in the second hand
        DDy[Ny-2]=DDy[Ny-2] - CCy[Ny-2]* vort[i][Ny-1]; //moving boundary condition
        //DDy[Ny-3]= DDy[Ny-3]; //vorticity nul on the free slip boundary condition

        tridiag(AAy, BBy, CCy, DDy, vorty, Ny-1); //ne calcul pas le point en 0 et en Ny-1

        for (j=1; j<Ny-1; j++)
        {
            vort[i][j]=vorty[j];
        }

    }

    ////////////calcul sur x //////////
    //calcul coef ADI

    for (j=1; j<Ny-1; j++)
    {

        for (i=1; i<Nx-1; i++)

        {

            AAx[i] = -.5* ( .5 * ( 1 + epsx[i][j] ) * cx[i-1][j] + dx );
            BBx[i] = 1 + dx + .5 * epsx[i][j] * cx[i][j];
            CCx[i] = .5 * ( .5 * ( 1 - epsx[i][j] ) * cx[i+1][j] - dx) ;

            DDx[i]= .5 * ( .5 * ( 1 + epsy[i][j] ) * cy[i][j-1] + dx ) * vort[i][j-1]
            + ( 1 - dx - .5 * epsy[i][j] * cy[i][j] ) * vort[i][j]
            + .5 * (-.5 * ( 1 - epsy[i][j] ) * cy[i][j+1] + dx ) * vort[i][j+1];

            vortx[i]=vort[i][j];

        }

        DDx[1] = DDx[1] - AAx[1]* vort[0][j];
        DDx[Nx-2] = DDx[Nx-2] - CCx[Nx-2] * vort[Nx-1][j];

        tridiag(AAx, BBx, CCx, DDx, vortx, Nx-1); //ne calcul pas le point en 0 et en Nx-1

        for (i=1; i<Nx-1; i++)
        {
            vort[i][j]=vortx[i];

        }

    }

}
</code>```

答:
The first thing to do is indeed to isolate which loop parallelizations have the most bad impact, but the last loop there looks very much like you would be experiencing cache thrashing. Simplifying the structure a bit:

```<code>double vort[Nx][Ny];
// ...
for (int j=1; j<Ny-1; ++j) {
    #pragma omp parallel for
    for (int i=1; i<Nx-1; ++i) {
        vort[i][j] -= f(i, j);
    }
}
</code>```

Any given thread is going to read and update in turn the values in vort at offsets j+k*Ny, j+(k+1)*Ny, j+(k+2)*Ny etc. depending on how the for loop is chunked across the threads. Each of these accesses is going to pull in a cache-line's worth of data to update 8 bytes. And when the outer loop starts again, chances are none of the data you just accessed is still going to be in cache.

All things being equal, if you can arrange your array accesses so that you're moving in the direction of the smallest stride (for C arrays, that's the last index), your cache behaviour will be much better. For dimension size 100, the arrays are likely not so big that this makes a huge difference. For e.g. Nx, Ny = 1000, it will likely be devastating to access the array the 'wrong way'.

This would give poorer performance in serial code, but I think adding threads to it just makes it that much worse.

That all said, the amount of computation done in each of these inner loops is quite small; there's a good chance you're going to be constrained by memory bandwidth regardless.

Addendum

Just to be explicit, the 'right' loop access would look like:

```<code>for (int i=1; i<Nx-1; ++i) {
    for (int j=1; j<Ny-1; ++j) {
        vort[i][j] -= f(i, j);
    }
}
</code>```

And to parallelize it, you can allow the compiler to better chunk the data across threads by using the collapse directive:

```<code>#pragma omp parallel for collapse(2)
for (int i=1; i<Nx-1; ++i) {
    for (int j=1; j<Ny-1; ++j) {
        vort[i][j] -= f(i, j);
    }
}
</code>```

Lastly, in order to avoid false sharing (threads treading on each other's cache lines), it's good to make sure that two adjacent rows of the array don't share data in the same cache line. One could make sure that each row is aligned on to a multiple of the cache-line size in memory, or more simply just add padding to the end of each row.

```<code>double vort[Nx][Ny+8]; // 8 doubles ~ 64 bytes
</code>```

(Assuming a cache-line of 64 bytes, this should suffice.)

ContentLicense: CC BY-SA 3.0

Body:
Hi I am trying to parralelize the calculation of this code with openMP. It is calculation of hydrodynamics vorticity with finite difference implicite method. I am using the Alternating direction implicit method to do so.

I would like to speed up its execution. (Here Nx=Ny=100)

The probleme is that using openMp this way slow down the code instead of speeding it up. I have try to specify the shared variable but this not helping much.
Any idea?

All the best

void ADI(double vort[][Ny], double psi[][Ny], double n[][Ny],
double cls[][Ny],double AAx[], double BBx[], double CCx[], double DDx[],
double AAy[], double BBy[], double CCy[], double DDy[],
double cx[][Ny], double cy[][Ny], double epsx[][Ny], double epsy[][Ny],
double vortx[], double vorty[Ny-2], double dx, double Dxs, double coefMass,
double coefMasCls)
{
    ////////////calcul sur y////////////
    //calcul coef ADI
    int i=0, j=0;

    #pragma omp parallel for private(Dxs,i) shared(psi,vort)
    for (i=0; i<Nx; i++) //Boundary condition sur x
    {
        vort[i][0]=(psi[i][0]-psi[i][1])*2/Dxs;
        vort[i][Ny-1] = (psi[i][Ny-1]-psi[i][Ny-2])*2/Dxs;
    }

    #pragma omp parallel for private(Dxs,j) shared(psi,vort)
    for (j=0; j<Ny; j++) //Boundary condition
    {
        vort[0][j] = (psi[0][j]-psi[1][j])*2/Dxs;
        vort[Nx-1][j] = (psi[Nx-1][j]-psi[Nx-2][j])*2/Dxs;

    }

    for (j=1; j<Ny-1; j++) //interior points
    {
        #pragma omp parallel for private(coefMasCls,coefMasCls,i) shared(psi,vort,n,cls)
        for (i=1; i<Nx-1; i++) //interior points
        {

            vort[i][j] = vort[i][j] - coefMass * (n[i+1][j]-n[i-1][j])- coefMasCls * (cls[i+1][j]-cls[i-1][j]);;

        }
        //i=0;
        //vort[i][j] = vort[i][j] + coefMass*(n[1][j]-n[1][j]);
        //i=Nx-1;
        //vort[i][j] = vort[i][j] + coefMass*(n[Nx-2][j]-n[Nx-2][j]);

    }

    for (i=1; i<Nx-1; i++) //interior points
    {
        for (j=1; j<Ny-1; j++) //interior points
        {

            AAy[j] = -.5 * ( .5 * (1 + epsy[i][j]) * cy[i][j-1] + dx);

            BBy[j] = 1 + dx + .5 * epsy[i][j] * cy[i][j];

            CCy[j] = .5 * ( .5 * ( 1 - epsy[i][j] ) * cy[i][j+1] - dx);

            DDy[j] = .5 * (.5 * ( 1 + epsx[i][j] ) * cx[i-1][j] + dx ) * vort[i-1][j]
            + ( 1 - dx - .5 * epsx[i][j] * cx[i][j] ) * vort[i][j]
            + .5 * (- .5 * ( 1 - epsx[i][j] ) * cx[i+1][j] + dx ) * vort[i+1][j];

            vorty[j] = vort[i][j];
        }

        DDy[1]=DDy[1] - AAy[1] * vort[i][0];  //the AA[0] are not taken into account in the tridiag methode. Include it in the second hand
        DDy[Ny-2]=DDy[Ny-2] - CCy[Ny-2]* vort[i][Ny-1]; //moving boundary condition
        //DDy[Ny-3]= DDy[Ny-3]; //vorticity nul on the free slip boundary condition

        tridiag(AAy, BBy, CCy, DDy, vorty, Ny-1); //ne calcul pas le point en 0 et en Ny-1

        for (j=1; j<Ny-1; j++)
        {
            vort[i][j]=vorty[j];
        }

    }

    ////////////calcul sur x //////////
    //calcul coef ADI

    for (j=1; j<Ny-1; j++)
    {

        for (i=1; i<Nx-1; i++)

        {

            AAx[i] = -.5* ( .5 * ( 1 + epsx[i][j] ) * cx[i-1][j] + dx );
            BBx[i] = 1 + dx + .5 * epsx[i][j] * cx[i][j];
            CCx[i] = .5 * ( .5 * ( 1 - epsx[i][j] ) * cx[i+1][j] - dx) ;

            DDx[i]= .5 * ( .5 * ( 1 + epsy[i][j] ) * cy[i][j-1] + dx ) * vort[i][j-1]
            + ( 1 - dx - .5 * epsy[i][j] * cy[i][j] ) * vort[i][j]
            + .5 * (-.5 * ( 1 - epsy[i][j] ) * cy[i][j+1] + dx ) * vort[i][j+1];

            vortx[i]=vort[i][j];

        }

        DDx[1] = DDx[1] - AAx[1]* vort[0][j];
        DDx[Nx-2] = DDx[Nx-2] - CCx[Nx-2] * vort[Nx-1][j];

        tridiag(AAx, BBx, CCx, DDx, vortx, Nx-1); //ne calcul pas le point en 0 et en Nx-1

        for (i=1; i<Nx-1; i++)
        {
            vort[i][j]=vortx[i];

        }

    }

}

Body:
The first thing to do is indeed to isolate which loop parallelizations have the most bad impact, but the last loop there looks very much like you would be experiencing cache thrashing. Simplifying the structure a bit:

double vort[Nx][Ny];
// ...
for (int j=1; j<Ny-1; ++j) {
    #pragma omp parallel for
    for (int i=1; i<Nx-1; ++i) {
        vort[i][j] -= f(i, j);
    }
}

Any given thread is going to read and update in turn the values in vort at offsets j+k*Ny, j+(k+1)*Ny, j+(k+2)*Ny etc. depending on how the for loop is chunked across the threads. Each of these accesses is going to pull in a cache-line's worth of data to update 8 bytes. And when the outer loop starts again, chances are none of the data you just accessed is still going to be in cache.

All things being equal, if you can arrange your array accesses so that you're moving in the direction of the smallest stride (for C arrays, that's the last index), your cache behaviour will be much better. For dimension size 100, the arrays are likely not so big that this makes a huge difference. For e.g. Nx, Ny = 1000, it will likely be devastating to access the array the 'wrong way'.

This would give poorer performance in serial code, but I think adding threads to it just makes it that much worse.

That all said, the amount of computation done in each of these inner loops is quite small; there's a good chance you're going to be constrained by memory bandwidth regardless.

Addendum

Just to be explicit, the 'right' loop access would look like:

for (int i=1; i<Nx-1; ++i) {
    for (int j=1; j<Ny-1; ++j) {
        vort[i][j] -= f(i, j);
    }
}

And to parallelize it, you can allow the compiler to better chunk the data across threads by using the collapse directive:

#pragma omp parallel for collapse(2)
for (int i=1; i<Nx-1; ++i) {
    for (int j=1; j<Ny-1; ++j) {
        vort[i][j] -= f(i, j);
    }
}

Lastly, in order to avoid false sharing (threads treading on each other's cache lines), it's good to make sure that two adjacent rows of the array don't share data in the same cache line. One could make sure that each row is aligned on to a multiple of the cache-line size in memory, or more simply just add padding to the end of each row.

double vort[Nx][Ny+8]; // 8 doubles ~ 64 bytes

(Assuming a cache-line of 64 bytes, this should suffice.)


问:
One single tkinter program wont open on double click. I get no error message
My code for an alarm in tkinter won't open on double click. It runs in idle just fine and all my other tkinter programs open on double click too. What in the code is causing this?

```<code>from tkinter import *
import datetime
import time
from time import strftime
import winsound

master = Tk()
master.geometry('300x300')
master.title('Alarm Time')

label = Label(master, text = 'What time would you like to wake up?')
label.pack()

EnteredAlarm = Entry(master)
EnteredAlarm.pack(ipady=8)

def callback():
    Alarm = EnteredAlarm.get()
    while True:
        Time = strftime('%H:%M')

        if str(Time) == str(Alarm):
            print('Wake up Mister West')
            winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME)
            break

        else:
            print('Zzz...')
            time.sleep(5)

b = Button(master, text="OK", command=callback)
b.pack()
</code>```

The code doesn't return any errors, all that happens is cmd opens for half a second then closes. Any help is appreciated, thanks in advance.

答:
You need to add master.mainloop() at the end of your program, as the last logical line.

This forces the program to continually update everything.

Body:
My code for an alarm in tkinter won't open on double click. It runs in idle just fine and all my other tkinter programs open on double click too. What in the code is causing this?

from tkinter import *
import datetime
import time
from time import strftime
import winsound

master = Tk()
master.geometry('300x300')
master.title('Alarm Time')

label = Label(master, text = 'What time would you like to wake up?')
label.pack()

EnteredAlarm = Entry(master)
EnteredAlarm.pack(ipady=8)

def callback():
    Alarm = EnteredAlarm.get()
    while True:
        Time = strftime('%H:%M')

        if str(Time) == str(Alarm):
            print('Wake up Mister West')
            winsound.PlaySound('Alarm.wav', winsound.SND_FILENAME)
            break

        else:
            print('Zzz...')
            time.sleep(5)

b = Button(master, text="OK", command=callback)
b.pack()

The code doesn't return any errors, all that happens is cmd opens for half a second then closes. Any help is appreciated, thanks in advance.


问:
Trying to divide two results from sql queries

```<code>$result="SELECT count(*) as c FROM results";

$result5=mysqli_query($connection, "SELECT SUM(HomeTeamTries + AwayTeamTries) as ts
FROM results");

$result6=mysqli_query($connection, "SELECT SUM($result / $result5) as at FROM results");
</code>```

The first and 5th query give me numbers from a database and these number are 270(1st) and 1110(5th) I want to know how to divide these results to give me an average of the 2 numbers which should be 4.11

I have tries using select sum statements to divide these results but ive had no joy any help is appreciated

答:
You can divide the sum and count terms:

```<code>SELECT COUNT(*) AS c,
       SUM(HomeTeamTries + AwayTeamTries) AS ts,
       SUM(HomeTeamTries + AwayTeamTries) / COUNT(*) AS ratio
FROM   results;
</code>```

Body:
$result="SELECT count(*) as c FROM results";

$result5=mysqli_query($connection, "SELECT SUM(HomeTeamTries + AwayTeamTries) as ts
FROM results");

$result6=mysqli_query($connection, "SELECT SUM($result / $result5) as at FROM results");

The first and 5th query give me numbers from a database and these number are 270(1st) and 1110(5th) I want to know how to divide these results to give me an average of the 2 numbers which should be 4.11

I have tries using select sum statements to divide these results but ive had no joy any help is appreciated

Body:
You can divide the sum and count terms:

SELECT COUNT(*) AS c,
       SUM(HomeTeamTries + AwayTeamTries) AS ts,
       SUM(HomeTeamTries + AwayTeamTries) / COUNT(*) AS ratio
FROM   results;


问:
Placing a UIButton in the same space as UITabBar (When hidden)
I have a UITabBarController based application that I am developing. In one of my screen designs, I need to hide the tab bar (Which I do with UIView's setHidden method) I then placed a UIView where the tabBar would normally be and added a UIButton to the UIView. However when tapping the button I do not get any response. The button does not receive any touch events.

I've looked at some SO questions and answers for the solution. However most of them require subclassing. I've tried subclassing and overriding the HitTest event, however even that method is not called in my UIButton subclass.

I'm developing on iOS 7.1.

Can anyone shed some light on this and how to get the button to respond to touch events?

EDIT

My self and @Geet have looked at this issue a little more closely. It seems anything placed in the same space as the UITabBar does not receive touch events. As a test I created a new project with very little code that replicates my original projects setup.

In the sample app, we have one UIViewController embedded in a UITabBarController as the first tab. That UIViewController is then embedded in a UINavigationController. From there, we push a second UIViewController onto the stack.

Tapping the "Hide Tabbar" button at the top does just that. Hides the tabBar. Which exposes the green UIView that has been placed there in the storyboard, with a UIButton that is connected to the ViewControllers implementation file. This button does not receive any touch events at all. As soon as I move the button above the space where the TabBar would normally occupy, the button works. Move it back down towards the bottom of the screen - button no longer works.

It seems Apple has barred all touch events under the UITabBar. I wonder if there is a way around this?

I have tried:

```<code>self.tabbar.userInteractionENabled = NO;
</code>```

Which did not help either.

Maybe there is a method that we are able to override the in a subclass of UITabbarController that will allow touches in this spec when the UITabBar is hidden?

If anyone wants to play around with the sample project - its here on my gitHub:

https://github.com/TanderZA/UIButton-in-UITabbar-Space

答:
I recently encountered this problem where we were hiding the UITabBar using isHidden but a UIView in one of the child view controllers underneath the UITabBar would not receive hit events. It received events everywhere but where the UITabBar used to be visible and located.

Rotating the phone back and forth would make the problem go away.  The solution I eventually found is after setting isHidden to true you need to call setNeedsLayout on the UITabBarController view:

```<code>self.tabBarController.tabBar.isHidden = true;
self.tabBarController.view.setNeedsLayout();
</code>```

Body:
I have a UITabBarController based application that I am developing. In one of my screen designs, I need to hide the tab bar (Which I do with UIView's setHidden method) I then placed a UIView where the tabBar would normally be and added a UIButton to the UIView. However when tapping the button I do not get any response. The button does not receive any touch events.

I've looked at some SO questions and answers for the solution. However most of them require subclassing. I've tried subclassing and overriding the HitTest event, however even that method is not called in my UIButton subclass.

I'm developing on iOS 7.1.

Can anyone shed some light on this and how to get the button to respond to touch events?

EDIT

My self and @Geet have looked at this issue a little more closely. It seems anything placed in the same space as the UITabBar does not receive touch events. As a test I created a new project with very little code that replicates my original projects setup.

In the sample app, we have one UIViewController embedded in a UITabBarController as the first tab. That UIViewController is then embedded in a UINavigationController. From there, we push a second UIViewController onto the stack.

Tapping the "Hide Tabbar" button at the top does just that. Hides the tabBar. Which exposes the green UIView that has been placed there in the storyboard, with a UIButton that is connected to the ViewControllers implementation file. This button does not receive any touch events at all. As soon as I move the button above the space where the TabBar would normally occupy, the button works. Move it back down towards the bottom of the screen - button no longer works.

It seems Apple has barred all touch events under the UITabBar. I wonder if there is a way around this?

I have tried:

self.tabbar.userInteractionENabled = NO;

Which did not help either.

Maybe there is a method that we are able to override the in a subclass of UITabbarController that will allow touches in this spec when the UITabBar is hidden?

If anyone wants to play around with the sample project - its here on my gitHub:

https://github.com/TanderZA/UIButton-in-UITabbar-Space

Body:
I recently encountered this problem where we were hiding the UITabBar using isHidden but a UIView in one of the child view controllers underneath the UITabBar would not receive hit events. It received events everywhere but where the UITabBar used to be visible and located.

Rotating the phone back and forth would make the problem go away.  The solution I eventually found is after setting isHidden to true you need to call setNeedsLayout on the UITabBarController view:

self.tabBarController.tabBar.isHidden = true;
self.tabBarController.view.setNeedsLayout();


问:
is it possible to switch from Relative layout to Linear layout without displacing the objects?
I started my application with relative layout. I completed the entire registration form. i wanted to change the radio buttons to spinner. While replacing the radio buttons with spinner my entire form objects gets displaced. Is there a way to change relative layout to linear layout without affecting the objects?</p>

答: You can add the XML Relativelayout and the result you expect. Sorry i cant comment</p>

ContentLicense: CC BY-SA 4.0


问:
How to write a POST method result into a file put contents content?
I would like to have the the result of an HTML form POST call into the content of another PHP file.
The goal is to have a redirection page generated dynamically  based on the HTML form values.

```<code>$redirectionLink = $_POST["redirectionLink"];
$redirectionFileContent =
`
<?php
header("Location:.".'$redirectionLink ');
?>
`;

$otherFileLocation= 'c:\xampp\htdocs\li\something.php';
file_put_contents($otherFileLocation,$redirectionFileContent);
</code>```

I receive the following output when I run the code above:

```<code>Notice: Array to string conversion in C:\xampp\htdocs\shortlink\process.php on line 25
</code>```

I don't know how it would be better. Maybe store it in a variable or write into it as a post call

I'm open to suggestions.

Thank you for your help in advance.

答:
This might solve the problem    </p>

```<code>header('Location:.$_POST["longlink"]');
</code>```

Body:
I would like to have the the result of an HTML form POST call into the content of another PHP file.
The goal is to have a redirection page generated dynamically  based on the HTML form values.

$redirectionLink = $_POST["redirectionLink"];
$redirectionFileContent =
`
<?php
header("Location:.".'$redirectionLink ');
?>
`;

$otherFileLocation= 'c:\xampp\htdocs\li\something.php';
file_put_contents($otherFileLocation,$redirectionFileContent);

I receive the following output when I run the code above:

Notice: Array to string conversion in C:\xampp\htdocs\shortlink\process.php on line 25

I don't know how it would be better. Maybe store it in a variable or write into it as a post call

I'm open to suggestions.

Thank you for your help in advance.

Body:
This might solve the problem

header('Location:.$_POST["longlink"]');


问:
WebSocket URL variable is not defined
I have this JS code, that're trying connecting to a WebSocket, but I have a problem with the URL variable.

var tipoChat = 1;
var escolherWebSocket = 1;
var unidade = prompt('Qual o IP do Provador?');
var loja = prompt('Qual o codigo da Loja?');
var url;
ws = new WebSocket(url);

// tipoChat 1 Produto
// tipoChat 2 Vendedor
// tipoChat 3 Atendente

function chatProduto() {
    tipoChat = 1;

    $("#btnProduto").addClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").removeClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function chatVendedor() {
    tipoChat = 2;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").addClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat2");
     $("#provador-produto").removeClass("show-chat1");

}

function chatAtendente() {
    tipoChat = 3;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").addClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function conectar() {
    $('#btnConectar').hide();
    $('#btnDesconectar').show();

                ws.onopen = function () {

                    $('#messages').prepend('Connected
');
                    $('#cmdSend').click(function () {

                        ws.send($('#txtMessage').val());

                        $('#txtMessage').val('');

                    });

}
}

switch (tipoChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}```
</div>
</div>
</p>

<p>And This is my error on console:</p>

<p><strong>Uncaught DOMException: Failed to construct 'WebSocket': The URL 'undefined' is invalid.</strong></p>

<p>Someone can say say why the Switch is not setting the Url variable?
It works only when I assign a value on console.</p>

<p><strong>EDIT</strong>:<br>
For some reason, when I call URL variable on console, the result is undefined, even I initializing WebSocket after switch. I really don't know why URL variable is not being defined </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var typeChat = 1;
var escolherWebSocket = 1;
var url;

switch (typeChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

ws = new WebSocket(url);</code>```

答:
Just initialize the 'url' variable in the top. Because you are creating a websocket with the 'url' variable without initializing it first. So 'url' variable is undefined at the moment.

Or you create socket where you are assigning to 'url' variable i.e. inside the switch block cases.

Title: WebSocket URL variable is not defined

Body:
I have this JS code, that're trying connecting to a WebSocket, but I have a problem with the URL variable.

var tipoChat = 1;
var escolherWebSocket = 1;
var unidade = prompt('Qual o IP do Provador?');
var loja = prompt('Qual o codigo da Loja?');
var url;
ws = new WebSocket(url);

// tipoChat 1 Produto
// tipoChat 2 Vendedor
// tipoChat 3 Atendente

function chatProduto() {
    tipoChat = 1;

    $("#btnProduto").addClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").removeClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function chatVendedor() {
    tipoChat = 2;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").removeClass("btn-menuStyle-active");
    $("#btnVendedor").addClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat2");
     $("#provador-produto").removeClass("show-chat1");

}

function chatAtendente() {
    tipoChat = 3;

    $("#btnProduto").removeClass("btn-menuStyle-active");
    $("#btnAtendente").addClass("btn-menuStyle-active");
    $("#btnVendedor").removeClass("btn-menuStyle-active");

     $("#provador-produto").addClass("show-chat1");
     $("#provador-produto").removeClass("show-chat2");

}

function conectar() {
    $('#btnConectar').hide();
    $('#btnDesconectar').show();

                ws.onopen = function () {

                    $('#messages').prepend('Connected
');
                    $('#cmdSend').click(function () {

                        ws.send($('#txtMessage').val());

                        $('#txtMessage').val('');

                    });

}
}

switch (tipoChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

And This is my error on console:

Uncaught DOMException: Failed to construct 'WebSocket': The URL 'undefined' is invalid.

Someone can say say why the Switch is not setting the Url variable?
It works only when I assign a value on console.

EDIT:

For some reason, when I call URL variable on console, the result is undefined, even I initializing WebSocket after switch. I really don't know why URL variable is not being defined

var typeChat = 1;
var escolherWebSocket = 1;
var url;

switch (typeChat) {

    case "1": // Chat Produto

        switch (escolherWebSocket) {

            case "1": //CBYK
                var url = 'ws://example0';
                break;

            case "2": //Centauro
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "2": // Chat Vendedor

        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';
                break;

            case "2":
                var url = 'ws://example0';
                break;

            default:
                alert("Código de Socket Inválido");
        }

    case "3": //Chat atendente
        switch (escolherWebSocket) {
            case "1":
                var url = 'ws://example0';

                break;

            case "2":
                var url = 'ws://example1';
                break;

            default:
                alert("Código de Socket Inválido");
}}

ws = new WebSocket(url);


问:
How to store a password without a database (PHP)?
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

```<code>$password = "something"
</code>```

Or encrypt it and store it in a text file?

Any advice is appreciated.

答: If it is not going to be in a database, I'd be inclined to store it in a text file that is outside of the servers webroot.  If you store it in the php script, and something happens to the server configuration, it is possible the php script could be served up in plain text, rather than being parsed through php, so the password would be visible.  Granted, under normal circumstances, this would not be very likely to happen, but it is a possible risk.  Encrypting it may help, but you'll also have to have the decryption key stored someplace, so it would only be a slight inconvenience for someone to decrypt it.  It might be better to store the password in hashed format (e.g. MD5 or SHA-1), hash the password the user enters using the same method, and then compare the hashes.</p>

ContentLicense: CC BY-SA 2.5

Body:
I would like to have a page that requires a password to login, but without a dataabase.

I was thinking of having it hard coded in the page, ie:

$password = "something"

Or encrypt it and store it in a text file?

Any advice is appreciated.


问:
One hot encoding of string categorical features
I'm trying to perform a one hot encoding of a trivial dataset.

```<code>data = [['a', 'dog', 'red']
        ['b', 'cat', 'green']]
</code>```

What's the best way to preprocess this data using Scikit-Learn?

On first instinct, you'd look towards Scikit-Learn's OneHotEncoder. But the one hot encoder doesn't support strings as features; it only discretizes integers.

So then you would use a LabelEncoder, which would encode the strings into integers. But then you have to apply the label encoder into each of the columns and store each one of these label encoders (as well as the columns they were applied on). And this feels extremely clunky.

So, what's the best way to do it in Scikit-Learn?

Please don't suggest pandas.get_dummies. That's what I generally use nowadays for one hot encodings. However, its limited in the fact that you can't encode your training / test set separately.

答:
If you are on sklearn>0.20.dev0

```<code>In [11]: from sklearn.preprocessing import OneHotEncoder
    ...: cat = OneHotEncoder()
    ...: X = np.array([['a', 'b', 'a', 'c'], [0, 1, 0, 1]], dtype=object).T
    ...: cat.fit_transform(X).toarray()
    ...:
Out[11]: array([[1., 0., 0., 1., 0.],
           [0., 1., 0., 0., 1.],
           [1., 0., 0., 1., 0.],
           [0., 0., 1., 0., 1.]])
</code>```

If you are on sklearn==0.20.dev0

```<code>In [30]: cat = CategoricalEncoder()

In [31]: X = np.array([['a', 'b', 'a', 'c'], [0, 1, 0, 1]], dtype=object).T

In [32]: cat.fit_transform(X).toarray()
Out[32]:
array([[ 1.,  0., 0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  1.]])
</code>```

Another way to do it is to use category_encoders.

Here is an example:

```<code>% pip install category_encoders
import category_encoders as ce
le =  ce.OneHotEncoder(return_df=False, impute_missing=False, handle_unknown="ignore")
X = np.array([['a', 'dog', 'red'], ['b', 'cat', 'green']])
le.fit_transform(X)
array([[1, 0, 1, 0, 1, 0],
       [0, 1, 0, 1, 0, 1]])
</code>```

Body:
I'm trying to perform a one hot encoding of a trivial dataset.

data = [['a', 'dog', 'red']
        ['b', 'cat', 'green']]

What's the best way to preprocess this data using Scikit-Learn?

On first instinct, you'd look towards Scikit-Learn's OneHotEncoder. But the one hot encoder doesn't support strings as features; it only discretizes integers.

So then you would use a LabelEncoder, which would encode the strings into integers. But then you have to apply the label encoder into each of the columns and store each one of these label encoders (as well as the columns they were applied on). And this feels extremely clunky.

So, what's the best way to do it in Scikit-Learn?

Please don't suggest pandas.get_dummies. That's what I generally use nowadays for one hot encodings. However, its limited in the fact that you can't encode your training / test set separately.

Body:
If you are on sklearn>0.20.dev0

In [11]: from sklearn.preprocessing import OneHotEncoder
    ...: cat = OneHotEncoder()
    ...: X = np.array([['a', 'b', 'a', 'c'], [0, 1, 0, 1]], dtype=object).T
    ...: cat.fit_transform(X).toarray()
    ...:
Out[11]: array([[1., 0., 0., 1., 0.],
           [0., 1., 0., 0., 1.],
           [1., 0., 0., 1., 0.],
           [0., 0., 1., 0., 1.]])

If you are on sklearn==0.20.dev0

In [30]: cat = CategoricalEncoder()

In [31]: X = np.array([['a', 'b', 'a', 'c'], [0, 1, 0, 1]], dtype=object).T

In [32]: cat.fit_transform(X).toarray()
Out[32]:
array([[ 1.,  0., 0.,  1.,  0.],
       [ 0.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  0.,  1.,  0.],
       [ 0.,  0.,  1.,  0.,  1.]])

Another way to do it is to use category_encoders.

Here is an example:

% pip install category_encoders
import category_encoders as ce
le =  ce.OneHotEncoder(return_df=False, impute_missing=False, handle_unknown="ignore")
X = np.array([['a', 'dog', 'red'], ['b', 'cat', 'green']])
le.fit_transform(X)
array([[1, 0, 1, 0, 1, 0],
       [0, 1, 0, 1, 0, 1]])


问:
Add a CSS framework to Angular vendor bundle

Here is my situation :

Web site powered by Angular 4

Initialised with Angular Starter Kit

Using Semantic UI as CSS framework

Here is my issue :

Adding Semantic UI to webpack has no effect.

Here is what I tried :

(I followed the official Angular documentation for webpack)

Add semantic-ui to package.json from terminal

```<code>npm install semantic-ui-css --save
</code>```

Add vendor bundle to the entry property in webpack.common.js

```<code>[...]
entry: {

  'polyfills': './src/polyfills.browser.ts',
  'main':      AOT ? './src/main.browser.aot.ts' :
              './src/main.browser.ts',
  'vendor':   './src/vendor.ts'

},
[...]
</code>```

Create the src/vendor.ts file and set its content to :

```<code>// Angular
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

// My CSS framework
import 'semantic-ui-css';
</code>```

What I got :

Webpack build without error, the vendor bundle is created :

vendor.bundle.js   3.74 MB       2  [emitted]  [big]  vendor

And webpack inject the bundle script in the HTML page :

```<code><script type="text/javascript" src="polyfills.bundle.js"></script><script type="text/javascript" src="vendor.bundle.js"></script><script type="text/javascript" src="main.bundle.js" async></script></body>
</code>```

But the visual doesn't change (but should I check it with CDN) and I don't see the vendor.bundle.js file in the dist folder.

I probably miss something, what is it ?

答:
Below statement only imports semantic.js as package.json is pointing
  to that file.

```<code>import 'semantic-ui-css';
</code>```

To import CSS, you can add the below:

```<code>// To import CSS
import 'semantic-ui-css/semantic.css';
</code>```

OR in src/styles/styles.scss

```<code>@import '../../node_modules/semantic-ui-css/semantic.css';
</code>```

Body:
Here is my situation :

Web site powered by Angular 4

Initialised with Angular Starter Kit

Using Semantic UI as CSS framework

Here is my issue :

Adding Semantic UI to webpack has no effect.

Here is what I tried :

(I followed the official Angular documentation for webpack)

Add semantic-ui to package.json from terminal

npm install semantic-ui-css --save

Add vendor bundle to the entry property in webpack.common.js

[...]
entry: {

  'polyfills': './src/polyfills.browser.ts',
  'main':      AOT ? './src/main.browser.aot.ts' :
              './src/main.browser.ts',
  'vendor':   './src/vendor.ts'

},
[...]

Create the src/vendor.ts file and set its content to :

// Angular
import '@angular/platform-browser';
import '@angular/platform-browser-dynamic';
import '@angular/core';
import '@angular/common';
import '@angular/http';
import '@angular/router';

// My CSS framework
import 'semantic-ui-css';

What I got :

Webpack build without error, the vendor bundle is created :

vendor.bundle.js   3.74 MB       2  [emitted]  [big]  vendor

And webpack inject the bundle script in the HTML page :

But the visual doesn't change (but should I check it with CDN) and I don't see the vendor.bundle.js file in the dist folder.

I probably miss something, what is it ?

Body:
Below statement only imports semantic.js as package.json is pointing
  to that file.

import 'semantic-ui-css';

To import CSS, you can add the below:

// To import CSS
import 'semantic-ui-css/semantic.css';

OR in src/styles/styles.scss

@import '../../node_modules/semantic-ui-css/semantic.css';


答:
You can chain together aggregates in your SQL string you're sending, i.e.

```<code>SELECT CAST(SUM(HomeTeamTries + AwayTeamTries) AS NUMERIC(10,2))/COUNT(*) FROM results
</code>```

I added in the cast to numeric so that you end up with numeric division instead of int division.

Title: Trying to divide two results from sql queries

Body:
You can chain together aggregates in your SQL string you're sending, i.e.

SELECT CAST(SUM(HomeTeamTries + AwayTeamTries) AS NUMERIC(10,2))/COUNT(*) FROM results

I added in the cast to numeric so that you end up with numeric division instead of int division.


问:
CKEditor 4.5 drag and drop image upload - how to return new dimensions in json response?
I have drag and drop image uploads working using CKEditor 4.5.1. Very nice feature! On the server side I am resizing large images. My JSON response returns the resized image url (set by 'url' in the response) and that is the image that is shown in the CKEditor window after the successful file upload. But the img tag inserted has the height and width attributes set with the values from the original image, not my resized image. Is there a way to return the new height and width values? Or does anyone have an idea of how to hack around this?

And more generally, is there any resource which describes all possible values in the JSON response? I saw it mentioned somewhere that it wasn't documented yet but hopefully someone might know and take the time to share.

答:
@Michael , thanks for answer. I yet tested and can say that fileUploadResponse is not required.

Responce data can be reach from instanceReady like this (if present in responce from server ofcource)

```<code>__ckeditor.on( 'instanceReady', function() {
    __ckeditor.widgets.registered.uploadimage.onUploaded = function( upload ) {
        console.log(upload);
        this.replaceWith( '<img src="' + upload.url + '" ' +
            'width="' + upload.responseData.width + '" ' +
            'height="' + upload.responseData.height + '">' );
    }
} );
</code>```

Body:
@Michael , thanks for answer. I yet tested and can say that fileUploadResponse is not required.

Responce data can be reach from instanceReady like this (if present in responce from server ofcource)

__ckeditor.on( 'instanceReady', function() {
    __ckeditor.widgets.registered.uploadimage.onUploaded = function( upload ) {
        console.log(upload);
        this.replaceWith( '<img src="' + upload.url + '" ' +
            'width="' + upload.responseData.width + '" ' +
            'height="' + upload.responseData.height + '">' );
    }
} );


答:
You can do either of those.  Just be sure to store a hash of the password, not the real one for security.  Here's and extremely simple example.

```<code><?
    if(md5($_REQUEST['password']) == 'md5ofyourpasswordHERE'){
         //do your logged in page stuff here.
    } else {
         //kick them out or tell them to resupply password.
    }
?>
</code>```

You can also check the username, if that's important to you.

Hope that helps!

Title: How to store a password without a database (PHP)?

Body:
You can do either of those.  Just be sure to store a hash of the password, not the real one for security.  Here's and extremely simple example.

<?
    if(md5($_REQUEST['password']) == 'md5ofyourpasswordHERE'){
         //do your logged in page stuff here.
    } else {
         //kick them out or tell them to resupply password.
    }
?>

You can also check the username, if that's important to you.

Hope that helps!


问:
Cannot resolve symbol 'AuthUI'
I am adding firebase google and Gmail sign in but when I pasted my code in
onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) method i got this error

Cannot resolve symbol 'AuthUI'

on AuthUI word and all AuthUI words got red in
onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) method.

Code of MainActivity

```<code>package com.google.firebase.udacity.friendlychat;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public static final String ANONYMOUS = "anonymous";
    public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
    public static final int RC_SIGN_IN=1;

    private ListView mMessageListView;
    private MessageAdapter mMessageAdapter;
    private ProgressBar mProgressBar;
    private ImageButton mPhotoPickerButton;
    private EditText mMessageEditText;
    private Button mSendButton;

    private String mUsername;

    private FirebaseDatabase database;
    private DatabaseReference databaserefrence;
    private ChildEventListener databaselistener;

   private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener auhtlistener;

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

        mUsername = ANONYMOUS;

        database = FirebaseDatabase.getInstance();
        databaserefrence= database.getReference().child("messages");

        auth= FirebaseAuth.getInstance();

        // Initialize references to views
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mMessageListView = (ListView) findViewById(R.id.messageListView);
        mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
        mMessageEditText = (EditText) findViewById(R.id.messageEditText);
        mSendButton = (Button) findViewById(R.id.sendButton);

        // Initialize message ListView and its adapter
        List<FriendlyMessage> friendlyMessages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
        mMessageListView.setAdapter(mMessageAdapter);

        // Initialize progress bar
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);

        // ImagePickerButton shows an image picker to upload a image for a message
        mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Fire an intent to show an image picker
            }
        });

        // Enable Send button when there's text to send
        mMessageEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().length() > 0) {
                    mSendButton.setEnabled(true);
                } else {
                    mSendButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

        // Send button sends a message and clears the EditText
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Send messages on click
                FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
                databaserefrence.push().setValue(friendlyMessage);
                // Clear input box
                mMessageEditText.setText("");
            }
        });

        databaselistener= new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s)
            {
                mMessageAdapter.add(dataSnapshot.getValue(FriendlyMessage.class));
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        databaserefrence.addChildEventListener(databaselistener);

        auhtlistener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)
            {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if(user!=null)
                {

                }
                else
                {
                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setAvailableProviders(
                                            Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
                                    .build(),
                            RC_SIGN_IN);
                }
            }
        };
        auth.addAuthStateListener(auhtlistener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}
</code>```

Code of FriendlyMessage.java

```<code>package com.google.firebase.udacity.friendlychat;

public class FriendlyMessage {

    private String text;
    private String name;
    private String photoUrl;

    public FriendlyMessage()
    {

    }

    public FriendlyMessage(String text, String name, String photoUrl) {
        this.text = text;
        this.name = name;
        this.photoUrl = photoUrl;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhotoUrl() {
        return photoUrl;
    }

    public void setPhotoUrl(String photoUrl) {
        this.photoUrl = photoUrl;
    }
}
</code>```

Code for message adapter class

```<code>package com.google.firebase.udacity.friendlychat;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

public class MessageAdapter extends ArrayAdapter<FriendlyMessage> {
    public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
        }

        ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
        TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
        TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);

        FriendlyMessage message = getItem(position);

        boolean isPhoto = message.getPhotoUrl() != null;
        if (isPhoto) {
            messageTextView.setVisibility(View.GONE);
            photoImageView.setVisibility(View.VISIBLE);
            Glide.with(photoImageView.getContext())
                    .load(message.getPhotoUrl())
                    .into(photoImageView);
        } else {
            messageTextView.setVisibility(View.VISIBLE);
            photoImageView.setVisibility(View.GONE);
            messageTextView.setText(message.getText());
        }
        authorTextView.setText(message.getName());

        return convertView;
    }
}
</code>```

Code of build.gradle(project:friendlyChat)

```<code>buildscript {
    repositories {
        jcenter()
        mavenLocal()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2' //alrae

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0' //already
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Code for build.gradle(Module:app)

```<code>apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.google.firebase.udacity.friendlychat"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // Displaying images
    // already
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.google.firebase:firebase-database:11.0.4'
    compile 'com.google.firebase:firebase-auth:11.0.4'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
You should add this in your build.gradle section .</p>

```<code>compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.firebaseui:firebase-ui-auth:0.6.1'
    compile 'com.google.firebase:firebase-storage:9.6.1'
    compile 'com.google.firebase:firebase-messaging:9.6.1'
    compile 'com.google.firebase:firebase-config:9.6.1'
</code>```

Title: Cannot resolve symbol 'AuthUI'

Body:
I am adding firebase google and Gmail sign in but when I pasted my code in
onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) method i got this error

Cannot resolve symbol 'AuthUI'

on AuthUI word and all AuthUI words got red in
onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) method.

Code of MainActivity

package com.google.firebase.udacity.friendlychat;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    public static final String ANONYMOUS = "anonymous";
    public static final int DEFAULT_MSG_LENGTH_LIMIT = 1000;
    public static final int RC_SIGN_IN=1;

    private ListView mMessageListView;
    private MessageAdapter mMessageAdapter;
    private ProgressBar mProgressBar;
    private ImageButton mPhotoPickerButton;
    private EditText mMessageEditText;
    private Button mSendButton;

    private String mUsername;

    private FirebaseDatabase database;
    private DatabaseReference databaserefrence;
    private ChildEventListener databaselistener;

   private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener auhtlistener;

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

        mUsername = ANONYMOUS;

        database = FirebaseDatabase.getInstance();
        databaserefrence= database.getReference().child("messages");

        auth= FirebaseAuth.getInstance();

        // Initialize references to views
        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
        mMessageListView = (ListView) findViewById(R.id.messageListView);
        mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
        mMessageEditText = (EditText) findViewById(R.id.messageEditText);
        mSendButton = (Button) findViewById(R.id.sendButton);

        // Initialize message ListView and its adapter
        List<FriendlyMessage> friendlyMessages = new ArrayList<>();
        mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
        mMessageListView.setAdapter(mMessageAdapter);

        // Initialize progress bar
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);

        // ImagePickerButton shows an image picker to upload a image for a message
        mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Fire an intent to show an image picker
            }
        });

        // Enable Send button when there's text to send
        mMessageEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().length() > 0) {
                    mSendButton.setEnabled(true);
                } else {
                    mSendButton.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(DEFAULT_MSG_LENGTH_LIMIT)});

        // Send button sends a message and clears the EditText
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // TODO: Send messages on click
                FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(), mUsername, null);
                databaserefrence.push().setValue(friendlyMessage);
                // Clear input box
                mMessageEditText.setText("");
            }
        });

        databaselistener= new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s)
            {
                mMessageAdapter.add(dataSnapshot.getValue(FriendlyMessage.class));
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        databaserefrence.addChildEventListener(databaselistener);

        auhtlistener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)
            {
                FirebaseUser user = firebaseAuth.getCurrentUser();

                if(user!=null)
                {

                }
                else
                {
                    startActivityForResult(
                            AuthUI.getInstance()
                                    .createSignInIntentBuilder()
                                    .setAvailableProviders(
                                            Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.PHONE_VERIFICATION_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.FACEBOOK_PROVIDER).build(),
                                                    new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
                                    .build(),
                            RC_SIGN_IN);
                }
            }
        };
        auth.addAuthStateListener(auhtlistener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }
}

Code of FriendlyMessage.java

package com.google.firebase.udacity.friendlychat;

public class FriendlyMessage {

    private String text;
    private String name;
    private String photoUrl;

    public FriendlyMessage()
    {

    }

    public FriendlyMessage(String text, String name, String photoUrl) {
        this.text = text;
        this.name = name;
        this.photoUrl = photoUrl;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhotoUrl() {
        return photoUrl;
    }

    public void setPhotoUrl(String photoUrl) {
        this.photoUrl = photoUrl;
    }
}

Code for message adapter class

package com.google.firebase.udacity.friendlychat;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

public class MessageAdapter extends ArrayAdapter<FriendlyMessage> {
    public MessageAdapter(Context context, int resource, List<FriendlyMessage> objects) {
        super(context, resource, objects);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
        }

        ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
        TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
        TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);

        FriendlyMessage message = getItem(position);

        boolean isPhoto = message.getPhotoUrl() != null;
        if (isPhoto) {
            messageTextView.setVisibility(View.GONE);
            photoImageView.setVisibility(View.VISIBLE);
            Glide.with(photoImageView.getContext())
                    .load(message.getPhotoUrl())
                    .into(photoImageView);
        } else {
            messageTextView.setVisibility(View.VISIBLE);
            photoImageView.setVisibility(View.GONE);
            messageTextView.setText(message.getText());
        }
        authorTextView.setText(message.getName());

        return convertView;
    }
}

Code of build.gradle(project:friendlyChat)

buildscript {
    repositories {
        jcenter()
        mavenLocal()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2' //alrae

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0' //already
    }
}

allprojects {
    repositories {
        jcenter()
        mavenLocal()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Code for build.gradle(Module:app)

apply plugin: 'com.android.application'

repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.google.firebase.udacity.friendlychat"
        minSdkVersion 16
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // Displaying images
    // already
    compile 'com.android.support:design:24.2.1'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.google.firebase:firebase-database:11.0.4'
    compile 'com.google.firebase:firebase-auth:11.0.4'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Body:
You should add this in your build.gradle section .

compile 'com.github.bumptech.glide:glide:3.6.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-database:9.6.1'
    compile 'com.google.firebase:firebase-auth:9.6.1'
    compile 'com.firebaseui:firebase-ui-auth:0.6.1'
    compile 'com.google.firebase:firebase-storage:9.6.1'
    compile 'com.google.firebase:firebase-messaging:9.6.1'
    compile 'com.google.firebase:firebase-config:9.6.1'


问:
How to refer to variable instead of column with dplyr
When using dplyr:filter, I often compute a local variable that holds the viable choices:

```<code>df <- as_tibble(data.frame(id=c("a","b"), val=1:6))
ids <- c("b","c")
filter(df, id %in% ids)
# giving id %in% c("b","c")
</code>```

However, if the dataset by chance has a column with the same name, this fails to achieve the intended purpose:

```<code>df$ids <- "a"
filter(df, id %in% ids)
# giving id %in% "a"
</code>```

How should I explicitly refer to the ids variable instead of the ids column?

答:
Unquote with !! to tell filter to look in the calling environment instead of the data frame:

library(tidyverse)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
ids <- c("b", "c")

df %>% filter(id %in% ids)
#> # A tibble: 3 x 2
#>      id   val
#>   <chr> <int>
#> 1     b     2
#> 2     b     4
#> 3     b     6

df <- df %>% mutate(ids = "a")

df %>% filter(id %in% ids)
#> # A tibble: 3 x 3
#>      id   val   ids
#>   <chr> <int> <chr>
#> 1     a     1     a
#> 2     a     3     a
#> 3     a     5     a

df %>% filter(id %in% !!ids)
#> # A tibble: 3 x 3
#>      id   val   ids
#>   <chr> <int> <chr>
#> 1     b     2     a
#> 2     b     4     a
#> 3     b     6     a
```

Of course, the better way to avoid such issues is to not put identically-named vectors in your global environment.

Body:
When using dplyr:filter, I often compute a local variable that holds the viable choices:

df <- as_tibble(data.frame(id=c("a","b"), val=1:6))
ids <- c("b","c")
filter(df, id %in% ids)
# giving id %in% c("b","c")

However, if the dataset by chance has a column with the same name, this fails to achieve the intended purpose:

df$ids <- "a"
filter(df, id %in% ids)
# giving id %in% "a"

How should I explicitly refer to the ids variable instead of the ids column?

Body:
Unquote with !! to tell filter to look in the calling environment instead of the data frame:

library(tidyverse)

df <- data_frame(id = rep(c("a","b"), 3), val = 1:6)
ids <- c("b", "c")

df %>% filter(id %in% ids)
#> # A tibble: 3 x 2
#>      id   val
#>   <chr> <int>
#> 1     b     2
#> 2     b     4
#> 3     b     6

df <- df %>% mutate(ids = "a")

df %>% filter(id %in% ids)
#> # A tibble: 3 x 3
#>      id   val   ids
#>   <chr> <int> <chr>
#> 1     a     1     a
#> 2     a     3     a
#> 3     a     5     a

df %>% filter(id %in% !!ids)
#> # A tibble: 3 x 3
#>      id   val   ids
#>   <chr> <int> <chr>
#> 1     b     2     a
#> 2     b     4     a
#> 3     b     6     a

Of course, the better way to avoid such issues is to not put identically-named vectors in your global environment.


问:
Is there a way to turn off xemacs auto backup files in a specific directory only?
XEmacs always creates a file named foo.txt~ when you edit foo.txt. This can be really useful but not really when you are using source control on your files.

I know you can use (setq make-backup-files nil) to turn it off altogether but was wondering if there was a way to turn it off only in particular directories.

答: The version control package will detect if you're in a CVS, RCS, or SCCS repository and disable backups. If you're using another VC backend like hg, git, or svn, you may need to install additional packages to enable emacs to detect their repositories.</p>


问:
Does any one have YMODEM package for Python.?
I'm trying to find the package modem 1.0 listed in PyPi and hence want to use ymodem from it. The package description in this link http://pypi.python.org/pypi/modem only gives the description and not the download link unlike in this link http://pypi.python.org/pypi/xmodem/0.2.4 .

Does anyone know the location to download modem or ymodem package for Python?

Kindly help me.

Regards,

Manjunath Bhat

答:
This is very old but I thought I'd answer it, since I had this problem recently.

If you are using linux, you can do this, which I found in the following link: https://superuser.com/questions/604055/using-rz-and-sz-under-linux-shell

write a file called ysend with the following code:

```<code>#!/bin/sh

DEV=/dev/ttyUSB0

stty -F $DEV 115200
sb $1 > $DEV < $DEV
</code>```

where DEV is your serial interface and the number is your baud rate. The sb command uses the YMODEM protocol.

you may then call this file from python with the following code:

```<code>import subprocess
subprocess.call(["sudo","bash","ysend",filename])
</code>```

where filename is the file you want to send.

This solved all my problems after hours of searching for a ymodem implementation. Change sb to sz to use zmodem instead

Body:
This is very old but I thought I'd answer it, since I had this problem recently.

If you are using linux, you can do this, which I found in the following link: https://superuser.com/questions/604055/using-rz-and-sz-under-linux-shell

write a file called ysend with the following code:

#!/bin/sh

DEV=/dev/ttyUSB0

stty -F $DEV 115200
sb $1 > $DEV < $DEV

where DEV is your serial interface and the number is your baud rate. The sb command uses the YMODEM protocol.

you may then call this file from python with the following code:

import subprocess
subprocess.call(["sudo","bash","ysend",filename])

where filename is the file you want to send.

This solved all my problems after hours of searching for a ymodem implementation. Change sb to sz to use zmodem instead


答:
Use divide to get the results</p>

```<code>select SUM(HomeTeamTries + AwayTeamTries)/count(*) as average FROM results
</code>```

Body:
$result="SELECT count(*) as c FROM results";

$result5=mysqli_query($connection, "SELECT SUM(HomeTeamTries + AwayTeamTries) as ts
FROM results");

$result6=mysqli_query($connection, "SELECT SUM($result / $result5) as at FROM results");

The first and 5th query give me numbers from a database and these number are 270(1st) and 1110(5th) I want to know how to divide these results to give me an average of the 2 numbers which should be 4.11

I have tries using select sum statements to divide these results but ive had no joy any help is appreciated

Body:
Use divide to get the results

select SUM(HomeTeamTries + AwayTeamTries)/count(*) as average FROM results


问:
Communicating between different docker services in docker-compose
I just started working with docker-compose and am currently struggling with communication between the different services.

I have 2 services, alice and bob. I want these to be able to send http requests to each other. As far as I understood, services should be able to reach each other by using the servicename as hostname.

Unfortunately, alice in my example is not able to reach bob on http://bob:5557, and bob is not able to reach alice on http://alice:5556.

What am I not understanding correctly? Is it even possible to make http requests between services?

This is my docker-compose.yml file:

```<code>version: '3'
services:
  alice:
    build: blockchain
    ports:
    - "5556:5000"
    environment:
      NAME: Alice
  bob:
    build: blockchain
    ports:
    - "5557:5000"
    environment:
      NAME: Bob
</code>```

答:
The Alice and Bob that you named in the docker-compose were docker name (docker run --name) not the hostname of the dockers; I would request you to defined "hostname" key in the docker-compose file to define hostname of the dockers; See example below:

```<code>   version: "3.0"
   services:
       lab1:
           image: ubuntu:version0
           container_name: lab1
           entrypoint: /bin/bash
           stdin_open: true
           hostname: lab1

       lab2:
          image: ubuntu:version0
          container_name: lab2
          entrypoint: /bin/bash
          stdin_open: true
          hostname: lab2
</code>```

Once you defined 'hostname' in the docker-compose file then try to ping the containers using hostname; it should succeed first.

Coming next to making use of port; You binded Alice port 5000 to host port 5556 and Bob port 5000 to host port 5557; From host to reach to the specific docker port you need to use the port 5556 or 5557 to reach Alice or Bob containers respectively whereas if you want to reach the port of the container inside container itself then you need to use the actual port that was used by the containers to communicate; that is port 5556 or 5557 to reach Alice or Bob respectively from containers.

Body:
I just started working with docker-compose and am currently struggling with communication between the different services.

I have 2 services, alice and bob. I want these to be able to send http requests to each other. As far as I understood, services should be able to reach each other by using the servicename as hostname.

Unfortunately, alice in my example is not able to reach bob on http://bob:5557, and bob is not able to reach alice on http://alice:5556.

What am I not understanding correctly? Is it even possible to make http requests between services?

This is my docker-compose.yml file:

version: '3'
services:
  alice:
    build: blockchain
    ports:
    - "5556:5000"
    environment:
      NAME: Alice
  bob:
    build: blockchain
    ports:
    - "5557:5000"
    environment:
      NAME: Bob

Body:
The Alice and Bob that you named in the docker-compose were docker name (docker run --name) not the hostname of the dockers; I would request you to defined "hostname" key in the docker-compose file to define hostname of the dockers; See example below:

   version: "3.0"
   services:
       lab1:
           image: ubuntu:version0
           container_name: lab1
           entrypoint: /bin/bash
           stdin_open: true
           hostname: lab1

       lab2:
          image: ubuntu:version0
          container_name: lab2
          entrypoint: /bin/bash
          stdin_open: true
          hostname: lab2

Once you defined 'hostname' in the docker-compose file then try to ping the containers using hostname; it should succeed first.

Coming next to making use of port; You binded Alice port 5000 to host port 5556 and Bob port 5000 to host port 5557; From host to reach to the specific docker port you need to use the port 5556 or 5557 to reach Alice or Bob containers respectively whereas if you want to reach the port of the container inside container itself then you need to use the actual port that was used by the containers to communicate; that is port 5556 or 5557 to reach Alice or Bob respectively from containers.


问:
Flexbox shrinking and not wrapping
I am trying to get two side-by-side divs to wrap using flexbox. It worked just fine for awhile whenever I just had the divs and a background color, but when I started adding more items it stopped working. The divs start shrinking and never wrap. I have tried flex-shrinking: 0; and other techniques I have found on other sites. Anyways here is the code:

.page4 {
  height: 100%;
  width: 100%;
  margin: auto;
}

h2 {
  text-align: center;
  margin: 0 auto;
  width: 65%;
}

.flex-content {
  margin: auto;
  display: flex;
  flex-shrink: 0;
  width: 80%;
  height: 500px;
  margin-top: 30%;
}

.left {
  align-items: center;
  display: block;
  float: left;
  padding-right: 5px;
  background-color: blue;
  width: 45%;
  height: 500px;
}

.background {
  background-image: url('../pictures/weenies/longpaper.png');
}

.right {
  align-items: center;
  display: block;
  float: right;
  background-color: red;
  width: 45%;
  height: 500px;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

#logopg4 {
  height: 300px;
  width: 300px;
}

.logopg4 {
  text-align: center;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page4">
  <div class="flex-content wrap">
    <div class="left">
      <div class="subs">
        <h2>Subs N'</h2>
        <h2>Sandwiches</h2>
        <div class="subsNSandwiches background">

        </div>
      </div>
      <div class="hen">
        <h2>Hen House</h2>
        <div class="henpaper background">

        </div>
      </div>
      <div class="deezerts">
        <h2>DEEZERTS</h2>
        <div class="deezertspaper background">

        </div>
      </div>
    </div>
    <div class="right">
      <div class="logopg4">
        <img src="./pictures/subs/logo2.png" id="logopg4" />
      </div>
      <div class="rabbit">
        <h2>Rabbit Fixin's</h2>
        <div class="rabbitFixins background">

        </div>
      </div>
      <div class="xtraFixins">
        <h2>Xtra Fixin's</h2>
        <div class="xtrapaper background">

        </div>
      </div>
    </div>
  </div>
</div></code>```

I have omitted some of the other code from the HTML file. Any insight to this issue would be greatly appreciated.

答:
You defined the width for your flex items (.left and .right) at 45%, so they will always remain 45% wide and therefore never wrap.

You can add a min-width  to avoid that - see my example below, where I added min-width: 400px to these two elements.

.page4 {
  height: 100%;
  width: 100%;
  margin: auto;
}

h2 {
  text-align: center;
  margin: 0 auto;
  width: 65%;
}

.flex-content {
  margin: auto;
  display: flex;
  flex-shrink: 0;
  width: 80%;
  height: 500px;
  margin-top: 30%;
}

.left {
  align-items: center;
  display: block;
  float: left;
  padding-right: 5px;
  background-color: blue;
  width: 45%;
  min-width: 400px;
  height: 500px;
}

.background {
  background-image: url('../pictures/weenies/longpaper.png');
}

.right {
  align-items: center;
  display: block;
  float: right;
  background-color: red;
  width: 45%;
  min-width: 400px;
  height: 500px;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

#logopg4 {
  height: 300px;
  width: 300px;
}

.logopg4 {
  text-align: center;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page4">
  <div class="flex-content wrap">
    <div class="left">
      <div class="subs">
        <h2>Subs N'</h2>
        <h2>Sandwiches</h2>
        <div class="subsNSandwiches background">

        </div>
      </div>
      <div class="hen">
        <h2>Hen House</h2>
        <div class="henpaper background">

        </div>
      </div>
      <div class="deezerts">
        <h2>DEEZERTS</h2>
        <div class="deezertspaper background">

        </div>
      </div>
    </div>
    <div class="right">
      <div class="logopg4">
        <img src="./pictures/subs/logo2.png" id="logopg4" />
      </div>
      <div class="rabbit">
        <h2>Rabbit Fixin's</h2>
        <div class="rabbitFixins background">

        </div>
      </div>
      <div class="xtraFixins">
        <h2>Xtra Fixin's</h2>
        <div class="xtrapaper background">

        </div>
      </div>
    </div>
  </div>
</div></code>```

Title: Flexbox shrinking and not wrapping

Body:
I am trying to get two side-by-side divs to wrap using flexbox. It worked just fine for awhile whenever I just had the divs and a background color, but when I started adding more items it stopped working. The divs start shrinking and never wrap. I have tried flex-shrinking: 0; and other techniques I have found on other sites. Anyways here is the code:

.page4 {
  height: 100%;
  width: 100%;
  margin: auto;
}

h2 {
  text-align: center;
  margin: 0 auto;
  width: 65%;
}

.flex-content {
  margin: auto;
  display: flex;
  flex-shrink: 0;
  width: 80%;
  height: 500px;
  margin-top: 30%;
}

.left {
  align-items: center;
  display: block;
  float: left;
  padding-right: 5px;
  background-color: blue;
  width: 45%;
  height: 500px;
}

.background {
  background-image: url('../pictures/weenies/longpaper.png');
}

.right {
  align-items: center;
  display: block;
  float: right;
  background-color: red;
  width: 45%;
  height: 500px;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

#logopg4 {
  height: 300px;
  width: 300px;
}

.logopg4 {
  text-align: center;
  display: block;
}

Subs N'

Sandwiches

Hen House

DEEZERTS

Rabbit Fixin's

Xtra Fixin's

I have omitted some of the other code from the HTML file. Any insight to this issue would be greatly appreciated.

Body:
You defined the width for your flex items (.left and .right) at 45%, so they will always remain 45% wide and therefore never wrap.

You can add a min-width  to avoid that - see my example below, where I added min-width: 400px to these two elements.

.page4 {
  height: 100%;
  width: 100%;
  margin: auto;
}

h2 {
  text-align: center;
  margin: 0 auto;
  width: 65%;
}

.flex-content {
  margin: auto;
  display: flex;
  flex-shrink: 0;
  width: 80%;
  height: 500px;
  margin-top: 30%;
}

.left {
  align-items: center;
  display: block;
  float: left;
  padding-right: 5px;
  background-color: blue;
  width: 45%;
  min-width: 400px;
  height: 500px;
}

.background {
  background-image: url('../pictures/weenies/longpaper.png');
}

.right {
  align-items: center;
  display: block;
  float: right;
  background-color: red;
  width: 45%;
  min-width: 400px;
  height: 500px;
}

.wrap {
  -webkit-flex-wrap: wrap;
  flex-wrap: wrap;
}

#logopg4 {
  height: 300px;
  width: 300px;
}

.logopg4 {
  text-align: center;
  display: block;
}

<div class="page4">
  <div class="flex-content wrap">
    <div class="left">
      <div class="subs">
        <h2>Subs N'</h2>
        <h2>Sandwiches</h2>
        <div class="subsNSandwiches background">

        </div>
      </div>
      <div class="hen">
        <h2>Hen House</h2>
        <div class="henpaper background">

        </div>
      </div>
      <div class="deezerts">
        <h2>DEEZERTS</h2>
        <div class="deezertspaper background">

        </div>
      </div>
    </div>
    <div class="right">
      <div class="logopg4">
        <img src="./pictures/subs/logo2.png" id="logopg4" />
      </div>
      <div class="rabbit">
        <h2>Rabbit Fixin's</h2>
        <div class="rabbitFixins background">

        </div>
      </div>
      <div class="xtraFixins">
        <h2>Xtra Fixin's</h2>
        <div class="xtrapaper background">

        </div>
      </div>
    </div>
  </div>
</div>


问:
Laravel delete all belongsToMany relations in belongsToMany relation
I have a Tournament model which contains a belongsToMany relationship with a Session model:

```<code>class Tournament extends Model{

    public function sessions(){
        return $this->belongsToMany(Session::class, 'tournament_has_sessions');
    }
}
</code>```

Then my sessions model contains a belongsToMany relationship with the User model:

```<code>class Session extends Model{

    public function users(){
        return $this->belongsToMany(User::class, 'session_has_users');
    }

}
</code>```

Now when I delete a Tournament, I want to delete all sessions and all information in the session_has_users table with it.

I have tried:

```<code>$tournament->sessions()->with('users')->delete(); -- < This
$tournament->sessions()->delete();
$tournament->users()->detach();
$tournament->delete();
</code>```

But it does't work. The data in the session_has_users table persists

I realize i could do something like this:

```<code>DB::table('session_has_users')->whereIn('session_id', $this->sessions()->pluck('id'))->delete();
</code>```

But is there a more efficient/handy (or even alternative if not more efficient) way to accomplish this?

答:
Using RDBMS Referential Actions on the Foreign Key

In the database schema, you should define the foreign key with the ON DELETE CASCADE action.  This will automatically delete the related records when the referenced id is deleted.

(See dbudimir's answer for the example lines from a Laravel migration file)

Using Eloquent to Detach All Related Models

If you aren't using foreign keys or your database lacks the support for referential actions, you can use this:

```<code>$tourament->sessions()->sync([]);
</code>```

The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

Providing an empty array should then remove all the relations.

Body:
I have a Tournament model which contains a belongsToMany relationship with a Session model:

class Tournament extends Model{

    public function sessions(){
        return $this->belongsToMany(Session::class, 'tournament_has_sessions');
    }
}

Then my sessions model contains a belongsToMany relationship with the User model:

class Session extends Model{

    public function users(){
        return $this->belongsToMany(User::class, 'session_has_users');
    }

}

Now when I delete a Tournament, I want to delete all sessions and all information in the session_has_users table with it.

I have tried:

$tournament->sessions()->with('users')->delete(); -- < This
$tournament->sessions()->delete();
$tournament->users()->detach();
$tournament->delete();

But it does't work. The data in the session_has_users table persists

I realize i could do something like this:

DB::table('session_has_users')->whereIn('session_id', $this->sessions()->pluck('id'))->delete();

But is there a more efficient/handy (or even alternative if not more efficient) way to accomplish this?

Body:
Using RDBMS Referential Actions on the Foreign Key

In the database schema, you should define the foreign key with the ON DELETE CASCADE action.  This will automatically delete the related records when the referenced id is deleted.

(See dbudimir's answer for the example lines from a Laravel migration file)

Using Eloquent to Detach All Related Models

If you aren't using foreign keys or your database lacks the support for referential actions, you can use this:

$tourament->sessions()->sync([]);

The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table:

https://laravel.com/docs/5.5/eloquent-relationships#updating-many-to-many-relationships

Providing an empty array should then remove all the relations.