问:
Asynchronously writing to console from stdin and other sources
I try to try to write some kind of renderer for the command line that should be able to print data from stdin and from another data source using asyncio and blessed, which is an improved version of python-blessings.

Here is what I have so far:

```<code>import asyncio
from blessed import Terminal

@asyncio.coroutine
def render(term):
    while True:
        received = yield
        if received:
            print(term.bold + received + term.normal)

async def ping(renderer):
    while True:
        renderer.send('ping')
        await asyncio.sleep(1)

async def input_reader(term, renderer):
    while True:
        with term.cbreak():
            val = term.inkey()
            if val.is_sequence:
               renderer.send("got sequence: {0}.".format((str(val), val.name, val.code)))
            elif val:
               renderer.send("got {0}.".format(val))

async def client():
    term = Terminal()
    renderer = render(term)
    render_task = asyncio.ensure_future(renderer)
    pinger = asyncio.ensure_future(ping(renderer))
    inputter = asyncio.ensure_future(input_reader(term, renderer))
    done, pending = await asyncio.wait(
        [pinger, inputter, renderer],
        return_when=asyncio.FIRST_COMPLETED,
    )
    for task in pending:
        task.cancel()

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(client())
    asyncio.get_event_loop().run_forever()
</code>```

For learning and testing purposes there is just a dump ping that sends 'ping' each second and another routine, that should grab key inputs and also sends them to my renderer.

But ping only appears once in the command line using this code and the input_reader works as expected. When I replace input_reader with a pong similar to ping everything is fine.

This is how it looks when typing 'pong', although if it takes ten seconds to write 'pong':

```<code>$ python async_term.py
ping
got p.
got o.
got n.
got g.
</code>```

答:
It seems like blessed is not built to work correctly with asyncio:  inkey() is a blocking method.  This will block any other couroutine.

You can use a loop with kbhit() and await asyncio.sleep() to yield control to other coroutines - but this is not a clean asyncio solution.

Body:
I try to try to write some kind of renderer for the command line that should be able to print data from stdin and from another data source using asyncio and blessed, which is an improved version of python-blessings.

Here is what I have so far:

import asyncio
from blessed import Terminal

@asyncio.coroutine
def render(term):
    while True:
        received = yield
        if received:
            print(term.bold + received + term.normal)

async def ping(renderer):
    while True:
        renderer.send('ping')
        await asyncio.sleep(1)

async def input_reader(term, renderer):
    while True:
        with term.cbreak():
            val = term.inkey()
            if val.is_sequence:
               renderer.send("got sequence: {0}.".format((str(val), val.name, val.code)))
            elif val:
               renderer.send("got {0}.".format(val))

async def client():
    term = Terminal()
    renderer = render(term)
    render_task = asyncio.ensure_future(renderer)
    pinger = asyncio.ensure_future(ping(renderer))
    inputter = asyncio.ensure_future(input_reader(term, renderer))
    done, pending = await asyncio.wait(
        [pinger, inputter, renderer],
        return_when=asyncio.FIRST_COMPLETED,
    )
    for task in pending:
        task.cancel()

if __name__ == '__main__':
    asyncio.get_event_loop().run_until_complete(client())
    asyncio.get_event_loop().run_forever()

For learning and testing purposes there is just a dump ping that sends 'ping' each second and another routine, that should grab key inputs and also sends them to my renderer.

But ping only appears once in the command line using this code and the input_reader works as expected. When I replace input_reader with a pong similar to ping everything is fine.

This is how it looks when typing 'pong', although if it takes ten seconds to write 'pong':

$ python async_term.py
ping
got p.
got o.
got n.
got g.


来源: stackexchange

问:
How to Write If!=IsNull in Sql StoredProceddure
Here i Wrote a Small StoredProcedure when Id is not available It shows Else
Please Helpme

```<code>Alter procedure Sp_GetEmpById
(@Id int)
As
Begin
if(@Id!==ISNULL){
select Email,Gen,Country from Employee where Emp_Id =@Id
}
Else
print 'The Id Enter By u is Not  Availabe '+@Id
End
</code>```

Here i get Two Error at ISNULL And Then Id Enter By u is Not in Availabe '+@Id
@Id

答:
This will compile, however I am not sure about your requirements:</p>

```<code>create procedure Sp_GetEmpById @Id int
as
begin
if @Id is not NULL
    select Email,Gen,Country from Employee where Emp_Id = @Id
else
    print 'The Id Enter By u is Not  Availabe ' + @Id

end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here i Wrote a Small StoredProcedure when Id is not available It shows Else
Please Helpme

Alter procedure Sp_GetEmpById
(@Id int)
As
Begin
if(@Id!==ISNULL){
select Email,Gen,Country from Employee where Emp_Id =@Id
}
Else
print 'The Id Enter By u is Not  Availabe '+@Id
End

Here i get Two Error at ISNULL And Then Id Enter By u is Not in Availabe '+@Id
@Id

Body:
This will compile, however I am not sure about your requirements:

create procedure Sp_GetEmpById @Id int
as
begin
if @Id is not NULL
    select Email,Gen,Country from Employee where Emp_Id = @Id
else
    print 'The Id Enter By u is Not  Availabe ' + @Id

end


问:
C++: Dynamically loading classes from dlls
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

```<code>//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};
</code>```

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

```<code>//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }
</code>```

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

答: Perhaps you want to look into DLL Delay-Loading (http://www.codeproject.com/KB/DLL/Delay_Loading_Dll.aspx) - this will give you what you want without having to work too hard for it</p>

OwnerDisplayName: Fire Lancer

ContentLicense: CC BY-SA 2.5

Body:
For my current project I want to be able to load some classes from a dll (which is not always the same, and may not even exist when my app is compiled). There may also be several alternative dll's for a given class (eg an implementation for Direct3D9 and one for OpenGL), but only one of the dlls will be loaded/used at any one time.

I have a set of base classes that define the interface plus some basic methods/members (ie the ones for refrence counting) of the classes I want to load, which the dll projects then derive from when creating there classes.

//in namespace base
class Sprite : public RefCounted//void AddRef(), void Release() and unsigned refCnt
{
public:
    virtual base::Texture *GetTexture()=0;
    virtual unsigned GetWidth()=0;
    virtual unsigned GetHeight()=0;
    virtual float GetCentreX()=0;
    virtual float GetCentreY()=0;
    virtual void SetCentre(float x, float y)=0;

    virtual void Draw(float x, float y)=0;
    virtual void Draw(float x, float y, float angle)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY)=0;
    virtual void Draw(float x, float y, float scaleX, flota scaleY, float angle)=0;
};

The thing is I'm not sure how to do it all so that the executable and other dlls can load and use these classes since ive only ever used dlls where there was only one dll and I could have the Visual Studio linker sort it all out using the .lib file I get when compileing dll's.

I dont mind using factory methods for instancing the classes, many of them do already by design (Ie a sprite class is created by the main Graphics class, eg Graphics->CreateSpriteFromTexture(base::Texture*)

EDIT:
When I needed to write some c++ dlls for use in python I used a library called pyCxx. The resulting dll basicly only exported one method, which created an instance of the "Module" class, which could then contain factory methods to create other classes etc.

The resulting dll could be imported in python just with "import [dllname]".

//dll compiled as cpputill.pyd
extern "C" void initcpputill()//only exported method
{
    static CppUtill* cpputill = new CppUtill;
}

class CppUtill : public Py::ExtensionModule<CppUtill>
{
public:
    CppUtill()
    : Py::ExtensionModule<CppUtill>("cpputill")
    {
        ExampleClass::init_type();

        add_varargs_method("ExampleClass",&CppUtill::ExampleClassFactory, "ExampleClass(), create instance of ExampleClass");
        add_varargs_method("HelloWorld",  &CppUtill::HelloWorld,  "HelloWorld(), print Hello World to console");

        initialize("C Plus Plus module");
    }
...
class ExampleClass
...
    static void init_type()
    {
        behaviors().name("ExampleClass");
        behaviors().doc ("example class");
        behaviors().supportGetattr();
        add_varargs_method("Random", &ExampleClass::Random, "Random(), get float in range 0<=x<1");
    }

How exactly does that work, and could I use it in a purely c++ enviroment to solve my problem here?

LastEditorDisplayName: Fire Lancer

OwnerDisplayName: Paul Betts


问:
Hibernate: Multiple FK relationships
I'm kinda stuck defining a Hibernate Entity:

Assuming I have the following two tables in a database:

(A)

fromCompany

toCompany

viaCompany

(B)

companyID (PK)

description

where the elements of (A) point to the primary key of (B); so there are 3 one-to-one relationships between the FKs and the PK.
I assume 3 OneToOne statements with different mappedBy conditions are not the way to go, mh? Has been a long day - I probably just don't get it ;)

Thanks for your help!

答:
The easiest way  to implement Class A with 3 ManyToOne Relationships pointing to ClassB

```<code>@Entity
class ClassA {

    //@ID
    //private id;

    @ManyToOne
    private ClassB from;

    @ManyToOne
    private ClassB toCompany;

    @ManyToOne
    private ClassB viaCompany;
}
</code>```

would not work, because every entity needs an Id. – You could try to overcome this problem by using a combinded Id (consisting of the three associations), but I guess it results in a lot of trouble to implement a ID consisting of associations to other entities.

@see Hibernate/persistence without @Id

The other way provided by Hibernate are so called Ternary Associations. – In this case you model the complete table A in form of an ternary m:n relationship. – But this is a very complicated task too.

@see http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html#collections-ternary

Title: Hibernate: Multiple FK relationships

Body:
The easiest way  to implement Class A with 3 ManyToOne Relationships pointing to ClassB

@Entity
class ClassA {

    //@ID
    //private id;

    @ManyToOne
    private ClassB from;

    @ManyToOne
    private ClassB toCompany;

    @ManyToOne
    private ClassB viaCompany;
}

would not work, because every entity needs an Id. – You could try to overcome this problem by using a combinded Id (consisting of the three associations), but I guess it results in a lot of trouble to implement a ID consisting of associations to other entities.

@see Hibernate/persistence without @Id

The other way provided by Hibernate are so called Ternary Associations. – In this case you model the complete table A in form of an ternary m:n relationship. – But this is a very complicated task too.

@see http://docs.jboss.org/hibernate/core/3.5/reference/en/html/collections.html#collections-ternary


问:
Maximum number of threads per process in Linux?
What is the maximum number of threads that can be created by a process under Linux?

How (if possible) can this value be modified?

答:
For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.


问:
Android Studio, pass to next page if one out of two text fields are filled
So I  basically want to know how would I  allow the user to proceed to the next page when they hit pay if either txtCode or StreetCode is filled, only one of these two needs to be filled in order to pass to the next page but how would i get that to work as currently they both must filled to pass to the next page.</p>

```<code>    btnPay = (Button)findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
             txtReg = (EditText)findViewById(R.id.txtReg);
             txtCode = (EditText)findViewById(R.id.txtCode);
             txtStreetName = (EditText)findViewById(R.id.txtStreetName);

             dlCostTime = (Spinner)findViewById(R.id.dlCostTime);

            if( txtReg.getText().toString().trim().equals(""))
            {
                txtReg.setError("required!");
            }
            if( txtCode.getText().toString().trim().equals(""))
            {
                txtCode.setError("required!");
            }
            if( txtStreetName.getText().toString().trim().equals(""))
            {
                txtStreetName.setError("required!");
            }

            else{
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });

            }
</code>```

答:
Replace this code

```<code>if( txtReg.getText().toString().trim().equals(""))
{
    txtReg.setError("required!");
}
if( txtCode.getText().toString().trim().equals(""))
{
    txtCode.setError("required!");
}
if( txtStreetName.getText().toString().trim().equals(""))
{
    txtStreetName.setError("required!");
}

else{
    final Button btnPay = (Button) findViewById(R.id.btnPay);

    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
            UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
        }
    });

}
</code>```

with this

```<code>if( txtReg.getText().toString().trim().equals("")){
    txtReg.setError("required!");
}else{

    if((txtCode.getText().toString().trim().equals("") && !txtStreetName.getText().toString().trim().equals("")) ||
            (!txtCode.getText().toString().trim().equals("") && txtStreetName.getText().toString().trim().equals(""))){
        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
    }else{
        //show message enter either code or street name not both
}
</code>```

Body:
So I  basically want to know how would I  allow the user to proceed to the next page when they hit pay if either txtCode or StreetCode is filled, only one of these two needs to be filled in order to pass to the next page but how would i get that to work as currently they both must filled to pass to the next page.

    btnPay = (Button)findViewById(R.id.btnPay);/** REFERENCE THE PAY BUTTON*/
    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {/** SETS ONCLICKLISTENER TO LISTEN FOR BUTTON CLICK*/
            /** REFERENCES ALL VARIABLE TO FIELDS IN LAYOUT */
             txtReg = (EditText)findViewById(R.id.txtReg);
             txtCode = (EditText)findViewById(R.id.txtCode);
             txtStreetName = (EditText)findViewById(R.id.txtStreetName);

             dlCostTime = (Spinner)findViewById(R.id.dlCostTime);

            if( txtReg.getText().toString().trim().equals(""))
            {
                txtReg.setError("required!");
            }
            if( txtCode.getText().toString().trim().equals(""))
            {
                txtCode.setError("required!");
            }
            if( txtStreetName.getText().toString().trim().equals(""))
            {
                txtStreetName.setError("required!");
            }

            else{
                final Button btnPay = (Button) findViewById(R.id.btnPay);

                btnPay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
                        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
                    }
                });

            }

Body:
Replace this code

if( txtReg.getText().toString().trim().equals(""))
{
    txtReg.setError("required!");
}
if( txtCode.getText().toString().trim().equals(""))
{
    txtCode.setError("required!");
}
if( txtStreetName.getText().toString().trim().equals(""))
{
    txtStreetName.setError("required!");
}

else{
    final Button btnPay = (Button) findViewById(R.id.btnPay);

    btnPay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
            UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
        }
    });

}

with this

if( txtReg.getText().toString().trim().equals("")){
    txtReg.setError("required!");
}else{

    if((txtCode.getText().toString().trim().equals("") && !txtStreetName.getText().toString().trim().equals("")) ||
            (!txtCode.getText().toString().trim().equals("") && txtStreetName.getText().toString().trim().equals(""))){
        Intent payIntent = new Intent(UserAreaActivity.this, PaymentActivity.class);// creates intent to open payment details
        UserAreaActivity.this.startActivity(payIntent);//Performs intent to open payment page
    }else{
        //show message enter either code or street name not both
}


问:
How to make heatmap square in Seaborn FacetGrid
I'm using Seaborn's FacetGrid class to plot a set of matrices using the heatmap function, also from Seaborn. However, I cannot adjust the aspect ratio of these subplots. Here is an example:

```<code>import seaborn as sns
import numpy as np
import pandas as pd

# Generate a set of sample data
np.random.seed(0)
indices = pd.MultiIndex.from_product((range(5), range(5), range(5)), names=('label0', 'label1', 'label2'))
data = pd.DataFrame(np.random.uniform(0, 100, size=len(indices)), index=indices, columns=('value',)).reset_index()

def draw_heatmap(*args, **kwargs):
    data = kwargs.pop('data')
    d = data.pivot(index=args[1], columns=args[0], values=args[2])
    sns.heatmap(d, **kwargs)

fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False)
</code>```

That produces this image:

Notice how the elements of the matrix plots are rectangular, rather than square. If I were making one plot (without the FacetGrid), I could pass the option square=True to sns.heatmap to make the plot square. However, if I put that in the arguments to map_dataframe, I get this result:

```<code>fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False, square=True)
</code>```

It looks like the axes are too big for the data, even though the default aspect ratio for the FacetGrid is 1. (And explicitly setting aspect=1 when constructing the FacetGrid doesn't help.)

Is there any way to fix this?

答:
When you set aspect argument of FacetGrid not only axis limits but the sizes and positions of axis labels and titles are also took into consideration to calculate proper axis geometry. Therefore heatmaps are rectangles.

To adjust quadratic heatmap and axis you may set corrected axis bounding box position manually with function set_bbox.

Another way is a little bit tricky. Function ax.set_aspect with the second argument box_forced would try to adjust heatmap and axis.
However to completely remove remain gray borders you may hide it by setting axis background color according to figure face color like here:

```<code>import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pylab as plt

# Generate a set of sample data
np.random.seed(0)
indices = pd.MultiIndex.from_product((range(5), range(5), range(5)),
 names=('label0', 'label1', 'label2'))
data = pd.DataFrame(np.random.uniform(0, 100, size=len(indices)),
 index=indices, columns=('value',)).reset_index()

def draw_heatmap(*args, **kwargs):
    data = kwargs.pop('data')
    d = data.pivot(index=args[1], columns=args[0], values=args[2])
    sns.heatmap(d, **kwargs)

fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False, square = True)
# get figure background color
facecolor=plt.gcf().get_facecolor()
for ax in fg.axes.flat:
    # set aspect of all axis
    ax.set_aspect('equal','box-forced')
    # set background color of axis instance
    ax.set_axis_bgcolor(facecolor)
plt.show()
</code>```

Result:

Body:
I'm using Seaborn's FacetGrid class to plot a set of matrices using the heatmap function, also from Seaborn. However, I cannot adjust the aspect ratio of these subplots. Here is an example:

import seaborn as sns
import numpy as np
import pandas as pd

# Generate a set of sample data
np.random.seed(0)
indices = pd.MultiIndex.from_product((range(5), range(5), range(5)), names=('label0', 'label1', 'label2'))
data = pd.DataFrame(np.random.uniform(0, 100, size=len(indices)), index=indices, columns=('value',)).reset_index()

def draw_heatmap(*args, **kwargs):
    data = kwargs.pop('data')
    d = data.pivot(index=args[1], columns=args[0], values=args[2])
    sns.heatmap(d, **kwargs)

fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False)

That produces this image:

Notice how the elements of the matrix plots are rectangular, rather than square. If I were making one plot (without the FacetGrid), I could pass the option square=True to sns.heatmap to make the plot square. However, if I put that in the arguments to map_dataframe, I get this result:

fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False, square=True)

It looks like the axes are too big for the data, even though the default aspect ratio for the FacetGrid is 1. (And explicitly setting aspect=1 when constructing the FacetGrid doesn't help.)

Is there any way to fix this?

Body:
When you set aspect argument of FacetGrid not only axis limits but the sizes and positions of axis labels and titles are also took into consideration to calculate proper axis geometry. Therefore heatmaps are rectangles.

To adjust quadratic heatmap and axis you may set corrected axis bounding box position manually with function set_bbox.

Another way is a little bit tricky. Function ax.set_aspect with the second argument box_forced would try to adjust heatmap and axis.
However to completely remove remain gray borders you may hide it by setting axis background color according to figure face color like here:

import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pylab as plt

# Generate a set of sample data
np.random.seed(0)
indices = pd.MultiIndex.from_product((range(5), range(5), range(5)),
 names=('label0', 'label1', 'label2'))
data = pd.DataFrame(np.random.uniform(0, 100, size=len(indices)),
 index=indices, columns=('value',)).reset_index()

def draw_heatmap(*args, **kwargs):
    data = kwargs.pop('data')
    d = data.pivot(index=args[1], columns=args[0], values=args[2])
    sns.heatmap(d, **kwargs)

fg = sns.FacetGrid(data, col='label0')
fg.map_dataframe(draw_heatmap, 'label1', 'label2', 'value', cbar=False, square = True)
# get figure background color
facecolor=plt.gcf().get_facecolor()
for ax in fg.axes.flat:
    # set aspect of all axis
    ax.set_aspect('equal','box-forced')
    # set background color of axis instance
    ax.set_axis_bgcolor(facecolor)
plt.show()

Result:


问:
RA vs DEC (equatorial coordinate system) 2d plot with matplotlib
I would like to plot some 2d maps showing astronomical sources positions on the sky.

Namely:

I have some data ASCII tables with equatorial coordinates of the sources (RA - right ascension, DEC - declination).
An example:

Here RA measured in hours (h), minutes (m), and seconds (s); DEC - in degrees (°), minutes ('), and seconds (").

Right now I'm plotting maps with TOPCAT and it looks like this:

And everything is fine except that the work with the TOPCAT cannot be scripted. But it is crucial since I have an awful amount of data.

I decided to use matplotlib (with astropy), but found out that it is a difficult question to set the axes in HH:MM:SS and °:':" as in the plot above.

And astropy tutorial says:

The axis object, ax, knows to expect angular coordinate values. An
  important fact is that it expects the values to be in radians, and it
  expects the azimuthal angle values to be between (-180º,180º). This is
  (currently) not customizable, so we have to coerce our RA data to
  conform to these rules!

But "currently" in the tutorial is 2013, maybe it's fixed already?

So the question is: can I plot my RA/DEC data and set the axes as HH:MM:SS and °:':" with matplotlib?
P.S.: Without adding FITS files.

答:
You can use whatever you want as the axes ticks labels using xticks() and yticks() functions. For example, function call xticks([1, 2, 3], ["a", "b", "c"]) will give you ticks labeled as a, b and c at positions of 1, 2 and 3 along the x-axis. So a (somewhat dirty) solution for your problem looks something like this:

Plot your coordinates in degrees

Configure axes using xticks() and yticks() functions to show hh:mm:ss and °:':" values:

```<code># Set up RA coordinates along x-axis
ticksLocationsRA = linspace(minRA, maxRA, numberOfTicks)
ticksLabelsRA = degrees_to_hhmmss(ticksLocatoinsRA)
xticks(ticksLocationsRA, ticksLabelsRA)

# The same with DEC coodinates
ticksLocationsDEC = linspace(minDEC, maxDEC, numberOfTicks)
ticksLabelsDEC = degrees_to_ddmmss(ticksLocatoinsDEC)
yticks(ticksLocationsDEC, ticksLabelsDEC)
</code>```

You only need to write a functions degrees_to_hhmmss() and degrees_to_ddmmss() to convert decimal degrees to strings like HH:MM:SS and °:':" (note, that you can use LaTex notation inside of matplotlib)

Body:
You can use whatever you want as the axes ticks labels using xticks() and yticks() functions. For example, function call xticks([1, 2, 3], ["a", "b", "c"]) will give you ticks labeled as a, b and c at positions of 1, 2 and 3 along the x-axis. So a (somewhat dirty) solution for your problem looks something like this:

Plot your coordinates in degrees

Configure axes using xticks() and yticks() functions to show hh:mm:ss and °:':" values:

# Set up RA coordinates along x-axis
ticksLocationsRA = linspace(minRA, maxRA, numberOfTicks)
ticksLabelsRA = degrees_to_hhmmss(ticksLocatoinsRA)
xticks(ticksLocationsRA, ticksLabelsRA)

# The same with DEC coodinates
ticksLocationsDEC = linspace(minDEC, maxDEC, numberOfTicks)
ticksLabelsDEC = degrees_to_ddmmss(ticksLocatoinsDEC)
yticks(ticksLocationsDEC, ticksLabelsDEC)

You only need to write a functions degrees_to_hhmmss() and degrees_to_ddmmss() to convert decimal degrees to strings like HH:MM:SS and °:':" (note, that you can use LaTex notation inside of matplotlib)


问:
How to make data inside a particular item show while using ng-repeat in angularjs?
I'm trying to make a quiz application with angular js.
When a user selects the correct answer i want to show an icon inside that item.
Problem is that icon is beign applied to every item in the list.
How can i fix this.?

here's the code

```<code>   <md-radio-group ng-model="test.selected" ng-change="test.onChange(test.selected)">
   <md-radio-button ng-repeat="item in test.items" value="{{item}}" class="md-accent" ng-click="test.validate($index)">
   {{item}}
   <md-icon class="material-icons md-secondary right" ng-show="test.isCorrect">done</md-icon>
   <md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect">clear</md-icon>
   </md-radio-button>
   </md-radio-group>
</code>```

Here's a plunker demo plunkr

答:
I made some changes in your plunker,

Changed link

```<code>(function(){
    angular.module('app')
            .controller('testCtrl', ['$scope', function($scope){
                var vm = this;
                vm.items = ['Dignity','Pretty','Cheap','Expensive'];
                vm.right = 0;
                vm.onChange = function(selected){
                        console.log(selected);
                    }
                vm.validate = function(index){
                    console.log(index);
                    if(index === vm.right){
                        vm.isCorrect = vm.items[index];
                        vm.isNotCorrect = "";
                    }
                    else{
                        vm.isNotCorrect = vm.items[index];
                        vm.isCorrect = "";
                    }
                }
            }])
})();
</code>```

and in view

```<code><md-icon class="material-icons md-secondary right" ng-show="test.isCorrect==item">done</md-icon>
<md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect==item">clear</md-icon>
</code>```

Body:
I'm trying to make a quiz application with angular js.
When a user selects the correct answer i want to show an icon inside that item.
Problem is that icon is beign applied to every item in the list.
How can i fix this.?

here's the code

   <md-radio-group ng-model="test.selected" ng-change="test.onChange(test.selected)">
   <md-radio-button ng-repeat="item in test.items" value="{{item}}" class="md-accent" ng-click="test.validate($index)">
   {{item}}
   <md-icon class="material-icons md-secondary right" ng-show="test.isCorrect">done</md-icon>
   <md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect">clear</md-icon>
   </md-radio-button>
   </md-radio-group>

Here's a plunker demo plunkr

Body:
I made some changes in your plunker,

Changed link

(function(){
    angular.module('app')
            .controller('testCtrl', ['$scope', function($scope){
                var vm = this;
                vm.items = ['Dignity','Pretty','Cheap','Expensive'];
                vm.right = 0;
                vm.onChange = function(selected){
                        console.log(selected);
                    }
                vm.validate = function(index){
                    console.log(index);
                    if(index === vm.right){
                        vm.isCorrect = vm.items[index];
                        vm.isNotCorrect = "";
                    }
                    else{
                        vm.isNotCorrect = vm.items[index];
                        vm.isCorrect = "";
                    }
                }
            }])
})();

and in view

<md-icon class="material-icons md-secondary right" ng-show="test.isCorrect==item">done</md-icon>
<md-icon class="material-icons md-secondary wrong" ng-show="test.isNotCorrect==item">clear</md-icon>


问:
How can I get vc++ and g++ to behave the same regarding typename for dependent qualified types?
Is there a switch I can supply to cl.exe that will enable a warning or error when a typename is missing from a qualified dependent type?

I'm working in an environment where developers tend to work one one platform, either Windows or Linux, and the code is ultimately built on both platforms nightly.  We've encountered a problem with people forgetting to use typename on qualified dependent types on Windows, where Visual C++ 2008 will automatically insert a missing typename if possible.  When they check in the code like this, it breaks the build on Linux, where g++ requires the typename.  It would be desirable to tweak the Makefile such that we can expect the same typename behaviour on Windows and Linux to mitigate the likelihood of the build breaking.  I prefer the g++ behaviour, but anything that would help the two platforms behave the same would be much appreciated.

See also Why do I need to use typedef typename in g++ but not VS?

答:
My workplace solved all problems of this kind by introducing a continuous integration server. In our case we were quite satisfied with TeamCity. It is very customizable, and with some bash scripting I am sure you can present gcc errors nicely within TeamCity. I customized our server to the point where I was also getting Doxygen errors presented nicely and we reduced the number of errors from an initial 11000 to 0, over a couple of months.

Good luck!


问:
How to find sum of files for all directories and sub directories (separately) and them sort them by size
Could you please advise me how to find the sum of all files in directories and sub directories?
I try to make this script but is not working.</p>

```<code>find . -xdev -type d  | while read l;do ls -l "$l" |
  awk '{sum+=$5}END{print sum/1024/1024 "" $l }';done | sort -k 1
</code>```

答: The awk command is in the wrong place.  It should come after the while loop.</p>

Body:
Could you please advise me how to find the sum of all files in directories and sub directories?
I try to make this script but is not working.

find . -xdev -type d  | while read l;do ls -l "$l" |
  awk '{sum+=$5}END{print sum/1024/1024 "" $l }';done | sort -k 1


问:
An issue with limiting a while loop
My table auto increments the value KundeID and on the form that confirms the input of data I want to show the person inputting it what their ID is when they're done. I'm using this code currently and while I get the correct ID, it loops forever, but I only want it to tell the ID once. What can I do to fix this?

```<code>$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
while   ($result=mysqli_query($kobling,$sq)) {
    $row=mysqli_fetch_array($result);
    echo "Ditt kundenummer er ".$row["max_ID"]."<br>";
}
</code>```

答:
As you mention table auto increments the value KundeID and you want maximum or latest Id, Right ?

So no need to use while loop you can directly get value using query
your code should be like this:

```<code> $sq="select KundeID from kunder order by KundeID desc limit 1";

 $result=mysqli_query($kobling,$sq);

 $row=mysqli_fetch_array($result);

 echo "Ditt kundenummer er ".$row["KundeID"]. "<br>";
</code>```

This may help you.

Title: An issue with limiting a while loop

Body:
My table auto increments the value KundeID and on the form that confirms the input of data I want to show the person inputting it what their ID is when they're done. I'm using this code currently and while I get the correct ID, it loops forever, but I only want it to tell the ID once. What can I do to fix this?

$sq="SELECT MAX(KundeID) AS max_ID FROM kunder";
while   ($result=mysqli_query($kobling,$sq)) {
    $row=mysqli_fetch_array($result);
    echo "Ditt kundenummer er ".$row["max_ID"]."
";
}

Body:
As you mention table auto increments the value KundeID and you want maximum or latest Id, Right ?

So no need to use while loop you can directly get value using query
your code should be like this:

 $sq="select KundeID from kunder order by KundeID desc limit 1";

 $result=mysqli_query($kobling,$sq);

 $row=mysqli_fetch_array($result);

 echo "Ditt kundenummer er ".$row["KundeID"]. "<br>";

This may help you.


问:
How would browser cookies look from TCP server point of view?
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

```<code>function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}
</code>```

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?

答: It comes through as part of the HTTP request header (look at the spec or http://en.wikipedia.org/wiki/HTTP_cookie for a quick overview).  HTTP just looks like normal payload data as far a TCP is concerned.  I would drag out a packet sniffer and capture some traffic.</p>

Body:
So imagine we have TCP server recieving all browser requests. How a cookie generated by some JavaScript function like:

function writeCookie()
{

var the_cookie = "users_resolution="+ screen.width +"x"+ screen.height;

document.cookie=the_cookie

location = location.href;
}

Will loock  if some browser like chrome will come to such server? what will full page requesl look like?


问:
Ubuntu 14.04 Apache2 404 Page Not Found
I've setted up an Ubuntu 14.04 with php5, Apache2, mysql / mysql-php.
Now I am tring to visit mydomain.com/admin but its response the following error
The requested URL /admin was not found on this server.

Here is my mydomain.com.conf file

```<code><VirtualHost *:80>
    <Directory /var/www/mydomain>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    ServerName mydomain.com
    ServerAlias www.mydomain.com
    DocumentRoot /var/www/mydomain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
</code>```

mod_rewrite is already enabled

答: You can't access the domain because you haven't properly configured a live domain. Go to http://localhost:80/admin to access your information. I would try setting the server name equal to your public IP address and set the server alias equal to localhost. Then you'll be able to access the server from over the web by entering your public IP address into the URL of your HTTP client. </p>

Title: Ubuntu 14.04 Apache2 404 Page Not Found

Body:
I've setted up an Ubuntu 14.04 with php5, Apache2, mysql / mysql-php.
Now I am tring to visit mydomain.com/admin but its response the following error
The requested URL /admin was not found on this server.

Here is my mydomain.com.conf file

<VirtualHost *:80>
    <Directory /var/www/mydomain>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>
    ServerName mydomain.com
    ServerAlias www.mydomain.com
    DocumentRoot /var/www/mydomain
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

mod_rewrite is already enabled


问:
run a specific line from a csv file depending on user input
How do you run a specific line from a csv file depending on user input.
My code asks the user to input the problem with their phone, if the user inputs water has spilled the keyword water or spilled will be identified and a   solution stored in the csv will be printed. However i stored many solutions there for different keywords.</p>

答:
If your problems/solutions are written in the file this way:

```<code>Problems1\nSolution1\nProblems2\nSolution2
</code>```

which gives:

```<code>Problems1
Solution1
Problems2
Solution2
</code>```

you can try this code:

```<code>problem = input ('What is your problem ? ')

with open ('keywords.txt', 'r') as myfile:
    text = myfile.read()

list_of_problems_and_solutions = text.split('\n')

for i in range (0, len(list_of_problems_and_solutions )-1, 2):
    if problem in list_of_problems_and_solutions [i]
    print (list_of_problems_and_solutions [i + 1])

>>> What is your problem ? Problems1
Solution1
</code>```

The list_of_problems_and_solutions will be someting like ['Problems1', 'Solution1', 'Problems2', 'Solution2' ]
The for i in range (0, len(list_of_problems_and_solutions )-1, 2): function will go through the list from index 0 to the end, with a step of 2.
As you see, when I type Problems1 as my problem, Python returns Solution1. You only have to replace with your keywords/solutions

Body:
If your problems/solutions are written in the file this way:

Problems1\nSolution1\nProblems2\nSolution2

which gives:

Problems1
Solution1
Problems2
Solution2

you can try this code:

problem = input ('What is your problem ? ')

with open ('keywords.txt', 'r') as myfile:
    text = myfile.read()

list_of_problems_and_solutions = text.split('\n')

for i in range (0, len(list_of_problems_and_solutions )-1, 2):
    if problem in list_of_problems_and_solutions [i]
    print (list_of_problems_and_solutions [i + 1])

>>> What is your problem ? Problems1
Solution1

The list_of_problems_and_solutions will be someting like ['Problems1', 'Solution1', 'Problems2', 'Solution2' ]
The for i in range (0, len(list_of_problems_and_solutions )-1, 2): function will go through the list from index 0 to the end, with a step of 2.
As you see, when I type Problems1 as my problem, Python returns Solution1. You only have to replace with your keywords/solutions


问:
How can I replace a window's URL hash with another response?
I am trying to change a hashed URL (document.location.hash) with the replace method, but it doesn't work.

```<code>$(function(){
 var anchor = document.location.hash;
 //this returns me a string value like '#categories'

  $('span').click(function(){

     $(window).attr('url').replace(anchor,'#food');
     //try to change current url.hash '#categories'
     //with another string, I stucked here.
  });

});
</code>```

I dont want to change/refresh page, I just want to replace URL without any responses.

Note: I don't want to solve this with a href="#food" solution.

答:
You may prefer the answer of this question.

The difference being that with history.replaceState() you don't scroll to the anchor, only replace it in the navigation bar. It's supported by all major browsers, source.

```<code>history.replaceState(undefined, undefined, "#hash_value")
</code>```

Body:
I am trying to change a hashed URL (document.location.hash) with the replace method, but it doesn't work.

$(function(){
 var anchor = document.location.hash;
 //this returns me a string value like '#categories'

  $('span').click(function(){

     $(window).attr('url').replace(anchor,'#food');
     //try to change current url.hash '#categories'
     //with another string, I stucked here.
  });

});

I dont want to change/refresh page, I just want to replace URL without any responses.

Note: I don't want to solve this with a href="#food" solution.

Body:
You may prefer the answer of this question.

The difference being that with history.replaceState() you don't scroll to the anchor, only replace it in the navigation bar. It's supported by all major browsers, source.

history.replaceState(undefined, undefined, "#hash_value")


问:
Anaconda Python install imutils in Windows10
I am using Anaconda2 Python2.7 with Windows 10 . How can I install the package imutils?

When I type: conda install imutils

It returns

```<code>Error:  Package missing in current win-64 channels:
  - imutils
</code>```

And then I search it

```<code>anaconda search -t conda imutils
</code>```

It seems that there is only the OSX version, but not the windows version.

Are there any methods that can install imutils in Anaconda Windows 10?

答:
I am using Anaconda3 Python3.6 with Windows 7, but the command seems the same: pip install imutils

```<code>c:\>pip install imutils
Collecting imutils
  Downloading imutils-0.4.0.tar.gz
Building wheels for collected packages: imutils
  Running setup.py bdist_wheel for imutils ... done
  Stored in directory: C:\Users\username\AppData\Local\pip\Cache\wheels\09\42\86\
d9e60e31cc4bec207af96ac3cda32b2ce6475a8883ec0d6b99
Successfully built imutils
Installing collected packages: imutils
Successfully installed imutils-0.4.0

c:\>anaconda search -t conda imutils
Using Anaconda API: https://api.anaconda.org
Run 'anaconda show <USER/PACKAGE>' to get more details:
Packages:
     Name                      |  Version | Package Types   | Platforms
     ------------------------- |   ------ | --------------- | ---------------
     STScI/imutils             | 0.0.0.git | conda           | osx-64
                                          : imutils
     mlgill/imutils            |    0.3.6 | conda           | linux-64, osx-64
     thecampfire/imutils       |    0.3.1 | conda           | osx-64
</code>```

For those who's using Python 2.7, write the same command with path to pip2.7.exe file c:\Python27\Scripts\pip2.7.exe install imutils

```<code>c:\>c:\Python27\Scripts\pip2.7.exe install imutils
Collecting imutils
  Using cached imutils-0.4.0.tar.gz
Installing collected packages: imutils
  Running setup.py install for imutils ... done
Successfully installed imutils-0.4.0

c:\>c:\Python27\Scripts\pip2.7.exe show imutils
Name: imutils
Version: 0.4.0
Summary: A series of convenience functions to make basic image processing
functions such as translation, rotation, resizing, skeletonization, displaying
Matplotlib images, sorting contours, detecting edges, and much more easier
with OpenCV and both Python 2.7 and Python 3.
Home-page: https://github.com/jrosebr1/imutils
Author: Adrian Rosebrock
Author-email: adrian@pyimagesearch.com
License: UNKNOWN
Location: c:\python27\lib\site-packages
Requires:
</code>```

Body:
I am using Anaconda2 Python2.7 with Windows 10 . How can I install the package imutils?

When I type: conda install imutils

It returns

Error:  Package missing in current win-64 channels:
  - imutils

And then I search it

anaconda search -t conda imutils

It seems that there is only the OSX version, but not the windows version.

Are there any methods that can install imutils in Anaconda Windows 10?

Body:
I am using Anaconda3 Python3.6 with Windows 7, but the command seems the same: pip install imutils

c:\>pip install imutils
Collecting imutils
  Downloading imutils-0.4.0.tar.gz
Building wheels for collected packages: imutils
  Running setup.py bdist_wheel for imutils ... done
  Stored in directory: C:\Users\username\AppData\Local\pip\Cache\wheels\09\42\86\
d9e60e31cc4bec207af96ac3cda32b2ce6475a8883ec0d6b99
Successfully built imutils
Installing collected packages: imutils
Successfully installed imutils-0.4.0

c:\>anaconda search -t conda imutils
Using Anaconda API: https://api.anaconda.org
Run 'anaconda show <USER/PACKAGE>' to get more details:
Packages:
     Name                      |  Version | Package Types   | Platforms
     ------------------------- |   ------ | --------------- | ---------------
     STScI/imutils             | 0.0.0.git | conda           | osx-64
                                          : imutils
     mlgill/imutils            |    0.3.6 | conda           | linux-64, osx-64
     thecampfire/imutils       |    0.3.1 | conda           | osx-64

For those who's using Python 2.7, write the same command with path to pip2.7.exe file c:\Python27\Scripts\pip2.7.exe install imutils

c:\>c:\Python27\Scripts\pip2.7.exe install imutils
Collecting imutils
  Using cached imutils-0.4.0.tar.gz
Installing collected packages: imutils
  Running setup.py install for imutils ... done
Successfully installed imutils-0.4.0

c:\>c:\Python27\Scripts\pip2.7.exe show imutils
Name: imutils
Version: 0.4.0
Summary: A series of convenience functions to make basic image processing
functions such as translation, rotation, resizing, skeletonization, displaying
Matplotlib images, sorting contours, detecting edges, and much more easier
with OpenCV and both Python 2.7 and Python 3.
Home-page: https://github.com/jrosebr1/imutils
Author: Adrian Rosebrock
Author-email: adrian@pyimagesearch.com
License: UNKNOWN
Location: c:\python27\lib\site-packages
Requires:


问:
DOS batch: force echo of single statement?
In my DOS batch file, I use the "@" symbol to suppress the echo of that statement before execution when echo is ON.

How should I force the echo of a statement when echo is OFF (I'm hoping for another single character, but all answers welcome)?

答:
Here is a not as powerful solution as @ : surround the commands you want to echo by "echo on" then "echo off".</p>

```<code>@echo on
your commands
@echo off
</code>```

Body:
Here is a not as powerful solution as @ : surround the commands you want to echo by "echo on" then "echo off".

@echo on
your commands
@echo off


问:
Mail multipart/alternative vs multipart/mixed
When creating email messages you are supposed to set the Content-Type to multipart/alternative when sending HTML and TEXT or multipart/mixed when sending TEXT and attachments.

So what do you do if you want to send HTML, Text, and attachments? Use both?

答:
I hit this issue. This architecture (from Lain's answer) worked for me.
Here is the solution in Python.

mixed

alternative

text

related

html

inline image

inline image

attachment

attachment

Here is the main email creation function:

```<code>def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}
</code>```

Here is the full code for sending an email containing html/text/attachment:

```<code>import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    SendMessageInternal(service, "me", message1)

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        return "error"

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def main():
    to = "to@address.com"
    sender = "from@address.com"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    attachment = "/path/to/file.pdf"
    SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)

if __name__ == '__main__':
    main()
</code>```

Body:
I hit this issue. This architecture (from Lain's answer) worked for me.
Here is the solution in Python.

mixed

alternative

text

related

html

inline image

inline image

attachment

attachment

Here is the main email creation function:

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

Here is the full code for sending an email containing html/text/attachment:

import httplib2
import os
import oauth2client
from oauth2client import client, tools
import base64
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from apiclient import errors, discovery
import mimetypes
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase

SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE1 = 'client_secret.json'
location = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
CLIENT_SECRET_FILE = os.path.join(location, CLIENT_SECRET_FILE1)
APPLICATION_NAME = 'Gmail API Python Send Email'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'gmail-python-email-send.json')
    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        credentials = tools.run_flow(flow, store)
        print 'Storing credentials to ' + credential_path
    return credentials

def SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachmentFile):
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)
    message1 = create_message_with_attachment(sender, to, subject, msgHtml, msgPlain, attachmentFile)
    SendMessageInternal(service, "me", message1)

def SendMessageInternal(service, user_id, message):
    try:
        message = (service.users().messages().send(userId=user_id, body=message).execute())
        print 'Message Id: %s' % message['id']
        return message
    except errors.HttpError, error:
        print 'An error occurred: %s' % error
        return "error"

def create_message_with_attachment(
    sender, to, subject, msgHtml, msgPlain, attachmentFile):
    """Create a message for an email.

    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
      file: The path to the file to be attached.

    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEMultipart('mixed')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject

    message_alternative = MIMEMultipart('alternative')
    message_related = MIMEMultipart('related')

    message_related.attach(MIMEText(msgHtml, 'html'))
    message_alternative.attach(MIMEText(msgPlain, 'plain'))
    message_alternative.attach(message_related)

    message.attach(message_alternative)

    print "create_message_with_attachment: file:", attachmentFile
    content_type, encoding = mimetypes.guess_type(attachmentFile)

    if content_type is None or encoding is not None:
        content_type = 'application/octet-stream'
    main_type, sub_type = content_type.split('/', 1)
    if main_type == 'text':
        fp = open(attachmentFile, 'rb')
        msg = MIMEText(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'image':
        fp = open(attachmentFile, 'rb')
        msg = MIMEImage(fp.read(), _subtype=sub_type)
        fp.close()
    elif main_type == 'audio':
        fp = open(attachmentFile, 'rb')
        msg = MIMEAudio(fp.read(), _subtype=sub_type)
        fp.close()
    else:
        fp = open(attachmentFile, 'rb')
        msg = MIMEBase(main_type, sub_type)
        msg.set_payload(fp.read())
        fp.close()
    filename = os.path.basename(attachmentFile)
    msg.add_header('Content-Disposition', 'attachment', filename=filename)
    message.attach(msg)

    return {'raw': base64.urlsafe_b64encode(message.as_string())}

def main():
    to = "to@address.com"
    sender = "from@address.com"
    subject = "subject"
    msgHtml = "Hi<br/>Html Email"
    msgPlain = "Hi\nPlain Email"
    attachment = "/path/to/file.pdf"
    SendMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachment)

if __name__ == '__main__':
    main()


问:
Why is this program not waiting for input from user?
I currently have the following code wrote:

```<code>import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");

    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

    if(person == "yes" && pInput <= 12 || pInput >= 65){
        otherPrice = otherPrice - discount;
        System.out.println("Your ticket price is: " + otherPrice);

    }

    else if(person == "yes" && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}
</code>```

The program runs up to the point in which I ask for the person to input wither or not they have a coupon.

```<code>System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();
</code>```

At this point, the program does not wait for an input and completes the if statement based on age input which it does wait for a reply from the user.

The output intended is for the user to input age, say yes or no to the coupon question and for the program to continue its run depending on those answers.

What I have tried:

closing the scanner - keyboard.close();

create a new scanner after closing the first instance of scanner.

Guidance is highly appreciated.

答:
I think your nextLine reads the new line feed after your

```<code>keyboard.nextInt();
</code>```

Try putting a

```<code>keyboard.nextLine();
</code>```

just after

```<code>keyboard.nextInt();
</code>```

to reset the Scanner.

Body:
I currently have the following code wrote:

import java.util.Scanner;

public class TicketPriceWithDiscount {

public static void main(String[] args) {

    TicketPriceWithDiscount obj = new TicketPriceWithDiscount();

}

  public TicketPriceWithDiscount(){

    double regPrice = 9.25;
    double otherPrice = 5.25; // ages under 12 or over 65
    double discount = 2.00;
    String person;
    int pInput;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("What is your age?");

    pInput = keyboard.nextInt();

    System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

    if(person == "yes" && pInput <= 12 || pInput >= 65){
        otherPrice = otherPrice - discount;
        System.out.println("Your ticket price is: " + otherPrice);

    }

    else if(person == "yes" && pInput >= 12 && pInput <= 65){
        regPrice = regPrice - discount;
        System.out.println("Your ticket price is: " + regPrice);
    }

    else if(pInput <= 12 || pInput >= 65){
        System.out.println("Your ticket price is: " + otherPrice);
    }

    else if(pInput >= 12 || pInput <= 65) {
        System.out.println("Your ticket price is: " + regPrice);
    }

}

}

The program runs up to the point in which I ask for the person to input wither or not they have a coupon.

System.out.println("Do you have a coupon? Yes or no will do.");

    person = keyboard.nextLine();

At this point, the program does not wait for an input and completes the if statement based on age input which it does wait for a reply from the user.

The output intended is for the user to input age, say yes or no to the coupon question and for the program to continue its run depending on those answers.

What I have tried:

closing the scanner - keyboard.close();

create a new scanner after closing the first instance of scanner.

Guidance is highly appreciated.

Body:
I think your nextLine reads the new line feed after your

keyboard.nextInt();

Try putting a

keyboard.nextLine();

just after

keyboard.nextInt();

to reset the Scanner.


问:
initialize of dictionary in c# return overflow error
I create a dictionary as you can see :

```<code>public Dictionary<string, string> TipList
{
    get { return TipList; }
    set { TipList = value; }
}
</code>```

I fetch some data from a service and I want to put these data into my dictionary as you can see here :

```<code>Dictionary<string, string> dict = new Dictionary<string, string>();
try
{
    using (var response = (HttpWebResponse)request.GetResponse())
    {

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(objText).ToDictionary(x => x.Keys, x => x.Values);
            object o;
            object o1;
            foreach (var item in list)
            {
                o = item.Value.ElementAt(0);
                o1 = item.Value.ElementAt(1);
                dict.Add(o.ToString(), o1.ToString());
            }
            GlobalVariable.TipListCache.Add(NewCarReceiption.CSystem.Value, dict);
            NewCarReceiption.TipList = dict.Where(i=>i.Key!=null & i.Value!=null).ToDictionary(x => x.Key, x => x.Value);
        }
    }
}
</code>```

But after running my code when the above function is trying to put their data into my dictionary .my application returns this error :

答:
You are setting the same property over and over again, going into an infinite loop.

If you don't need any additional logic in your getter and setter, you might just leave it auto-implemented:

```<code>public Dictionary<string, string> TipList
{
   get;
   set;
}
</code>```

If you do need more logic in your getter and setter, you have to add a backing field yourself:

```<code>private Dictionary<string, string> tipList;
public Dictionary<string, string> TipList
{
    get
    {
        DoSomethingBeforeGet();
        return this.tipList;
    }
    set
    {
        DoSomethingBeforeSet();
        this.tipList = value;
        DoSomethingAfterSet();
    }
}
</code>```

Body:
I create a dictionary as you can see :

public Dictionary<string, string> TipList
{
    get { return TipList; }
    set { TipList = value; }
}

I fetch some data from a service and I want to put these data into my dictionary as you can see here :

Dictionary<string, string> dict = new Dictionary<string, string>();
try
{
    using (var response = (HttpWebResponse)request.GetResponse())
    {

        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            var objText = reader.ReadToEnd();
            var list = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(objText).ToDictionary(x => x.Keys, x => x.Values);
            object o;
            object o1;
            foreach (var item in list)
            {
                o = item.Value.ElementAt(0);
                o1 = item.Value.ElementAt(1);
                dict.Add(o.ToString(), o1.ToString());
            }
            GlobalVariable.TipListCache.Add(NewCarReceiption.CSystem.Value, dict);
            NewCarReceiption.TipList = dict.Where(i=>i.Key!=null & i.Value!=null).ToDictionary(x => x.Key, x => x.Value);
        }
    }
}

But after running my code when the above function is trying to put their data into my dictionary .my application returns this error :

Body:
You are setting the same property over and over again, going into an infinite loop.

If you don't need any additional logic in your getter and setter, you might just leave it auto-implemented:

public Dictionary<string, string> TipList
{
   get;
   set;
}

If you do need more logic in your getter and setter, you have to add a backing field yourself:

private Dictionary<string, string> tipList;
public Dictionary<string, string> TipList
{
    get
    {
        DoSomethingBeforeGet();
        return this.tipList;
    }
    set
    {
        DoSomethingBeforeSet();
        this.tipList = value;
        DoSomethingAfterSet();
    }
}


答:
Your setter is calling the TipList property's setter (itself) which is calling its setter and so on - resulting in the exception.

Initialize it like this:

```<code>private Dictionary<string, string> _tipList;
public Dictionary<string, string> TipList
{
    get { return _tipList; }
    set { _tipList = value; }
}
</code>```

Or best, if you do not need any behavior other than the default, with the auto-implemented property:

```<code>public Dictionary<string, string> TipList { get; set; }
</code>```

and since C# 6.0 you can also initialize it like this ( with Auto-property initializers):

```<code>public Dictionary<string, string> TipList { get; set; } = new Dictionary<string, string>();
</code>```

Title: initialize of dictionary in c# return overflow error

Body:
Your setter is calling the TipList property's setter (itself) which is calling its setter and so on - resulting in the exception.

Initialize it like this:

private Dictionary<string, string> _tipList;
public Dictionary<string, string> TipList
{
    get { return _tipList; }
    set { _tipList = value; }
}

Or best, if you do not need any behavior other than the default, with the auto-implemented property:

public Dictionary<string, string> TipList { get; set; }

and since C# 6.0 you can also initialize it like this ( with Auto-property initializers):

public Dictionary<string, string> TipList { get; set; } = new Dictionary<string, string>();


问:
Remove the left and right margins of a UIPopoverPresentationController?
I wanted to know if there was a way to remove the left and right margins of a UIPopoverPresentationController:

I try with:

```<code>suggestionsTableViewController.popoverPresentationController?.popoverLayoutMargins = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
</code>```

But nothing changes.

I also try with UIPopoverBackgroundView:

```<code>suggestionsTableViewController.popoverPresentationController?.popoverBackgroundViewClass = HUBBPopoverBackgroundView.self
</code>```

This is the code of my UIPopoverBackgroundView:

```<code>  class HUBBPopoverBackgroundView: UIPopoverBackgroundView {

  override func layoutSubviews() {
    super.layoutSubviews()
  }

  public override static func contentViewInsets() -> UIEdgeInsets {
    return UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
  }

  public override static func arrowBase() -> CGFloat {
    return 2.0
  }

  public override static func arrowHeight() -> CGFloat {
    return 2.0
  }

  override var arrowOffset: CGFloat {
    get {
      return self.arrowOffset
    }
    set {
      self.arrowOffset = newValue
    }
  }

  override var arrowDirection: UIPopoverArrowDirection {
    get {
      return self.arrowDirection
    }
    set {
      self.arrowDirection = newValue
    }
  }
}
</code>```

Can you help me??

Thank you.

答:
Unfortunately, popoverLayoutMargins does nothing nowadays; it used to work, but it stopped. You can dictate the width of a popover by using its preferredContentSize, but you cannot dictate its exact placement.

If you want that kind of control, don't use a popover; use a custom presented controller instead. Using a UIPresentationController subclass, you can take complete control of the placement of the presented view controller.

Body:
I wanted to know if there was a way to remove the left and right margins of a UIPopoverPresentationController:

I try with:

suggestionsTableViewController.popoverPresentationController?.popoverLayoutMargins = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)

But nothing changes.

I also try with UIPopoverBackgroundView:

suggestionsTableViewController.popoverPresentationController?.popoverBackgroundViewClass = HUBBPopoverBackgroundView.self

This is the code of my UIPopoverBackgroundView:

  class HUBBPopoverBackgroundView: UIPopoverBackgroundView {

  override func layoutSubviews() {
    super.layoutSubviews()
  }

  public override static func contentViewInsets() -> UIEdgeInsets {
    return UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10)
  }

  public override static func arrowBase() -> CGFloat {
    return 2.0
  }

  public override static func arrowHeight() -> CGFloat {
    return 2.0
  }

  override var arrowOffset: CGFloat {
    get {
      return self.arrowOffset
    }
    set {
      self.arrowOffset = newValue
    }
  }

  override var arrowDirection: UIPopoverArrowDirection {
    get {
      return self.arrowDirection
    }
    set {
      self.arrowDirection = newValue
    }
  }
}

Can you help me??

Thank you.


问:
In laravel SPA, I use the DataTables , when I use laravel's vue component，vue also require jquery, so the DataTables can't be load correctly
In laravel SPA, When I use the DataTables which depends on jQuery,  when I use laravel's vue component，vue also require jquery, so the DataTables can't be load correctly， because  loading jquery twice. what should I do?

index.blade.php

```<code><!DOCTYPE html>
    <html lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <!-- Meta, title, CSS, favicons, etc. -->
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>控制台 | {{ config('webbackend.title') }}</title>

        <!-- Bootstrap -->
        <link href="/assets/admin/gentelella/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

        <!-- ...some css... -->

        <!-- Datatables -->
        <link href="/assets/admin/gentelella/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">

        <!-- Custom Theme Style -->
        <link href="/assets/admin/gentelella/build/css/custom.min.css" rel="stylesheet">
    </head>

    <body class="nav-md">

        <div id="app"></div>

        <!-- load jQuery first-->
        <script src="/assets/admin/gentelella/vendors/jquery/dist/jquery.min.js"></script>
        <!-- here is some plugins, they maybe dependent on jquery,so I can't delete previous line -->
        <!-- FastClick -->
        <script src="/assets/admin/gentelella/vendors/fastclick/lib/fastclick.js"></script>
        <!-- NProgress -->
        <script src="/assets/admin/gentelella/vendors/nprogress/nprogress.js"></script>

        <!-- Datatables -->
        <script src="/assets/admin/gentelella/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-buttons/js/dataTables.buttons.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-buttons/js/buttons.flash.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-buttons/js/buttons.html5.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-buttons/js/buttons.print.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-keytable/js/dataTables.keyTable.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-responsive/js/dataTables.responsive.min.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js"></script>
        <script src="/assets/admin/gentelella/vendors/datatables.net-scroller/js/dataTables.scroller.min.js"></script>

        <!-- main.js loaded jQuery already -->
        <script src="{{ asset('js/main.js') }}"></script>

        <!-- Custom Theme Scripts -->
        {{--<script src="/assets/admin/gentelella/build/js/custom.min.js"></script>--}}

    </body>
    </html>
</code>```

bootstrap.js

```<code>/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');
</code>```

答:
Verify if jQuery is loaded before VueJs.

Can pass some snippet of main.js? Please.

Body:
In laravel SPA, When I use the DataTables which depends on jQuery,  when I use laravel's vue component，vue also require jquery, so the DataTables can't be load correctly， because  loading jquery twice. what should I do?

index.blade.php

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>控制台 | {{ config('webbackend.title') }}</title>

        <link href="/assets/admin/gentelella/vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

        <link href="/assets/admin/gentelella/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-buttons-bs/css/buttons.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-fixedheader-bs/css/fixedHeader.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-responsive-bs/css/responsive.bootstrap.min.css" rel="stylesheet">
        <link href="/assets/admin/gentelella/vendors/datatables.net-scroller-bs/css/scroller.bootstrap.min.css" rel="stylesheet">

        <link href="/assets/admin/gentelella/build/css/custom.min.css" rel="stylesheet">

        {{----}}

bootstrap.js

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

window.$ = window.jQuery = require('jquery');

require('bootstrap-sass');


问:
Aggregating in R with multiple conditions
I am trying to summarize a data set in R. I am a beginner in R. The code below works, but has many steps. Is there an easier way to accomplish this? I'd like to accomplish the following:

1) group by Client_ID

2) count all ClaimNumbers (whether associated with DS or not)

3) count only claim numbers with DS
4) sum retail and WS only for DS

5) Also, I would like to just count a claim once. In the data, a single claim  number will be repeated for each service year and service.

```<code> # example

 ds <- read.table(text = "
 Client_ID ClaimNumber ServiceYr Service Retail WS
A00002         WC1      2012      DS    100 25
A00002         WC1      2013      DS    100 25
A00002         WC1      2014      BR     50 10
A00002         WC2      2014      BR     50 10
A00002         WC3      2014      BR     50 10
A00003         WC4      2014      BR     50 10
A00003         WC4      2015      BR     50 10
A00003         WC5      2015      BR     50 10
A00003         WC5      2016      BR     50 10
A00003         WC6      2016      DS    100 25",
               sep="",header=TRUE)

 # group by client ID and claim number to get one row per claim number
 total_claims <- sqldf("select Client_ID,ClaimNumber from ds group
                  by Client_ID,ClaimNumber")

 # For DS claims only - group by client ID and claim number
 # to get one row per claim number
 ds_claims <- sqldf("select Client_ID,ClaimNumber, sum(Retail) as Retail,
   sum(WS) as WS from ds where Service='DS' group by Client_ID,ClaimNumber")

 # count the total number of claims by client
 total_counts <-      aggregate(total_claims[,2],b=list(total_claims$Client_ID),FUN=length)

 # fix column headers
 colnames(total_counts)[1:2] <- c("Client_ID","ClaimCount")

 # count the number of DS claims by client
 ds_claim_counts <- aggregate(ds_claims[,2],b=list(ds_claims$Client_ID),FUN=length)

 # fix column headers
 colnames(ds_claim_counts)[1:2] <- c("Client_ID","ClaimCount")

 # merge to get both total counts and ds counts on the same table
 total <- merge(total_counts,ds_claim_counts, by="Client_ID",all.x=TRUE)

 # merge to add ds retail and ws amounts to total table
 total <- merge(total,ds_claims[,c(1,3,4)], by="Client_ID",all.x=TRUE)

 # fix column headers
 colnames(total)[2:3] <- c("Total_CC","DS_CC")
</code>```

答:
Here are some alternatives which give the same answer as the code in the question:

1) sqldf

```<code>library(sqldf)

sqldf("select Client_ID,
              count(distinct ClaimNumber) Total_CC,
              count(distinct case when
                               Service = 'DS' then ClaimNumber
                               else NULL
                             end) DS_CC,
              sum(Retail * (Service = 'DS')) Retail,
              sum(WS * (Service = 'DS')) WS
       from ds
       group by Client_ID")
</code>```

giving:

```<code>  Client_ID Total_CC DS_CC Retail WS
1    A00002        3     1    200 50
2    A00003        3     1    100 25
</code>```

2) data.table

```<code>library(data.table)

DT <- as.data.table(ds)
DT[, list(Total_CC = length(unique(ClaimNumber)),
          DS_CC = length(unique(ClaimNumber[Service == "DS"])),
          Retail = sum(Retail * (Service == "DS")),
          WS = sum(WS * (Service == "DS"))), by = Client_ID]
</code>```

giving:

```<code>   Client_ID Total_CC DS_CC Retail WS
1:    A00002        3     1    200 50
2:    A00003        3     1    100 25
</code>```

3) dplyr

```<code>library(dplyr)

ds %>%
   group_by(Client_ID) %>%
   summarize(Total_CC = length(unique(ClaimNumber)),
          DS_CC = length(unique(ClaimNumber[Service == "DS"])),
          Retail = sum(Retail * (Service == "DS")),
          WS = sum(WS * (Service == "DS"))) %>%
   ungroup
</code>```

giving:

```<code># A tibble: 2 × 5
  Client_ID Total_CC DS_CC Retail    WS
     <fctr>    <int> <int>  <int> <int>
1    A00002        3     1    200    50
2    A00003        3     1    100    25
</code>```

Body:
I am trying to summarize a data set in R. I am a beginner in R. The code below works, but has many steps. Is there an easier way to accomplish this? I'd like to accomplish the following:

1) group by Client_ID

2) count all ClaimNumbers (whether associated with DS or not)

3) count only claim numbers with DS
4) sum retail and WS only for DS

5) Also, I would like to just count a claim once. In the data, a single claim  number will be repeated for each service year and service.

 # example

 ds <- read.table(text = "
 Client_ID ClaimNumber ServiceYr Service Retail WS
A00002         WC1      2012      DS    100 25
A00002         WC1      2013      DS    100 25
A00002         WC1      2014      BR     50 10
A00002         WC2      2014      BR     50 10
A00002         WC3      2014      BR     50 10
A00003         WC4      2014      BR     50 10
A00003         WC4      2015      BR     50 10
A00003         WC5      2015      BR     50 10
A00003         WC5      2016      BR     50 10
A00003         WC6      2016      DS    100 25",
               sep="",header=TRUE)

 # group by client ID and claim number to get one row per claim number
 total_claims <- sqldf("select Client_ID,ClaimNumber from ds group
                  by Client_ID,ClaimNumber")

 # For DS claims only - group by client ID and claim number
 # to get one row per claim number
 ds_claims <- sqldf("select Client_ID,ClaimNumber, sum(Retail) as Retail,
   sum(WS) as WS from ds where Service='DS' group by Client_ID,ClaimNumber")

 # count the total number of claims by client
 total_counts <-      aggregate(total_claims[,2],b=list(total_claims$Client_ID),FUN=length)

 # fix column headers
 colnames(total_counts)[1:2] <- c("Client_ID","ClaimCount")

 # count the number of DS claims by client
 ds_claim_counts <- aggregate(ds_claims[,2],b=list(ds_claims$Client_ID),FUN=length)

 # fix column headers
 colnames(ds_claim_counts)[1:2] <- c("Client_ID","ClaimCount")

 # merge to get both total counts and ds counts on the same table
 total <- merge(total_counts,ds_claim_counts, by="Client_ID",all.x=TRUE)

 # merge to add ds retail and ws amounts to total table
 total <- merge(total,ds_claims[,c(1,3,4)], by="Client_ID",all.x=TRUE)

 # fix column headers
 colnames(total)[2:3] <- c("Total_CC","DS_CC")

Body:
Here are some alternatives which give the same answer as the code in the question:

1) sqldf

library(sqldf)

sqldf("select Client_ID,
              count(distinct ClaimNumber) Total_CC,
              count(distinct case when
                               Service = 'DS' then ClaimNumber
                               else NULL
                             end) DS_CC,
              sum(Retail * (Service = 'DS')) Retail,
              sum(WS * (Service = 'DS')) WS
       from ds
       group by Client_ID")

giving:

  Client_ID Total_CC DS_CC Retail WS
1    A00002        3     1    200 50
2    A00003        3     1    100 25

2) data.table

library(data.table)

DT <- as.data.table(ds)
DT[, list(Total_CC = length(unique(ClaimNumber)),
          DS_CC = length(unique(ClaimNumber[Service == "DS"])),
          Retail = sum(Retail * (Service == "DS")),
          WS = sum(WS * (Service == "DS"))), by = Client_ID]

giving:

   Client_ID Total_CC DS_CC Retail WS
1:    A00002        3     1    200 50
2:    A00003        3     1    100 25

3) dplyr

library(dplyr)

ds %>%
   group_by(Client_ID) %>%
   summarize(Total_CC = length(unique(ClaimNumber)),
          DS_CC = length(unique(ClaimNumber[Service == "DS"])),
          Retail = sum(Retail * (Service == "DS")),
          WS = sum(WS * (Service == "DS"))) %>%
   ungroup

giving:

# A tibble: 2 × 5
  Client_ID Total_CC DS_CC Retail    WS
     <fctr>    <int> <int>  <int> <int>
1    A00002        3     1    200    50
2    A00003        3     1    100    25

ContentLicense: CC BY-SA 4.0