问:
HTML Canvas Full Screen
I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/

At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.

Any ideas?

EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?

```<code>var $j = jQuery.noConflict();

var canvas;
var ctx;
var canvasDiv;
var outerDiv;

var canvasW = $j('body').width();
var canvasH = $j('body').height();

//var canvasW     = 640;
//var canvasH     = 480;

var numMovers   = 550;
var movers      = [];
var friction    = .96;
var radCirc     = Math.PI * 2;

var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0;
var isMouseDown = true;

function init()
{
    canvas = document.getElementById("mainCanvas");

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

function setup()
{
    outerDiv = document.getElementById("outer");
    canvasDiv = document.getElementById("canvasContainer");
    ctx = canvas.getContext("2d");

    var i = numMovers;
    while( i-- )
    {
        var m = new Mover();
        m.x  = canvasW * .5;
        m.y  = canvasH * .5;
        m.vX = Math.cos(i) * Math.random() * 25;
        m.vY = Math.sin(i) * Math.random() * 25;
        m.size = 2;
        movers[i] = m;
    }

    document.onmousedown = onDocMouseDown;
    document.onmouseup   = onDocMouseUp;
    document.onmousemove = onDocMouseMove;
}

function run()
{
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "rgba(8,8,12,.65)";
    ctx.fillRect( 0 , 0 , canvasW , canvasH );
    ctx.globalCompositeOperation = "lighter";

    mouseVX    = mouseX - prevMouseX;
    mouseVY    = mouseY - prevMouseY;
    prevMouseX = mouseX;
    prevMouseY = mouseY;

    var toDist   = canvasW / 1.15;
    var stirDist = canvasW / 8;
    var blowDist = canvasW / 2;

    var Mrnd   = Math.random;
    var Mabs   = Math.abs;
    var Msqrt  = Math.sqrt;
    var Mcos   = Math.cos;
    var Msin   = Math.sin;
    var Matan2 = Math.atan2;
    var Mmax   = Math.max;
    var Mmin   = Math.min;

    var i = numMovers;
    while( i-- )
    {
        var m  = movers[i];
        var x  = m.x;
        var y  = m.y;
        var vX = m.vX;
        var vY = m.vY;

        var dX = x - mouseX;
        var dY = y - mouseY;
        var d = Msqrt( dX * dX + dY * dY );
        var a = Matan2( dY , dX );
        var cosA = Mcos( a );
        var sinA = Msin( a );

        if( isMouseDown )
        {
            if( d < blowDist )
            {
                var blowAcc = ( 1 - ( d / blowDist ) ) * 2;
                vX += cosA * blowAcc + .5 - Mrnd();
                vY += sinA * blowAcc + .5 - Mrnd();
            }
        }

        if( d < toDist )
        {
            var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014;
            vX -= cosA * toAcc;
            vY -= sinA * toAcc;
        }

        if( d < stirDist )
        {
            var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022;
            vX += mouseVX * mAcc;
            vY += mouseVY * mAcc;
        }

        vX *= friction;
        vY *= friction;

        var avgVX = Mabs( vX );
        var avgVY = Mabs( vY );
        var avgV = ( avgVX + avgVY ) * .5;

        if( avgVX < .1 ) vX *= Mrnd() * 3;
        if( avgVY < .1 ) vY *= Mrnd() * 3;

        var sc = avgV * .45;
        sc = Mmax( Mmin( sc , 3.5 ) , .4 );

        var nextX = x + vX;
        var nextY = y + vY;

        if( nextX > canvasW )
        {
            nextX = canvasW;
            vX *= -1;
        }
        else if( nextX < 0 )
        {
            nextX = 0;
            vX *= -1;
        }

        if( nextY > canvasH )
        {
            nextY = canvasH;
            vY *= -1;
        }
        else if( nextY < 0 )
        {
            nextY = 0;
            vY *= -1;
        }

        m.vX = vX;
        m.vY = vY;
        m.x  = nextX;
        m.y  = nextY;

        ctx.fillStyle = m.color;
        ctx.beginPath();
        ctx.arc( nextX , nextY , sc , 0 , radCirc , true );
        ctx.closePath();
        ctx.fill();
    }

    //rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 );
}

function onDocMouseMove( e )
{
    var ev = e ? e : window.event;
    mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;
    mouseY = ev.clientY - outerDiv.offsetTop  - canvasDiv.offsetTop;
}

function onDocMouseDown( e )
{
    isMouseDown = true;
    return false;
}

function onDocMouseUp( e )
{
    isMouseDown = true;
    return false;
}

// ==========================================================================================

function Mover()
{
    this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
    this.y     = 0;
    this.x     = 0;
    this.vX    = 0;
    this.vY    = 0;
    this.size  = 0;
}

// ==========================================================================================

function rect( context , x , y , w , h )
{
    context.beginPath();
    context.rect( x , y , w , h );
    context.closePath();
    context.fill();
}

// ==========================================================================================
</code>```

答:
Because it was not posted yet and is a simple css fix:

```<code>#canvas {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
}
</code>```

Works great if you want to apply a fullscreen canvas background (for example with Granim.js).

Title: HTML Canvas Full Screen

Body:
I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/

At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.

Any ideas?

EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?

var $j = jQuery.noConflict();

var canvas;
var ctx;
var canvasDiv;
var outerDiv;

var canvasW = $j('body').width();
var canvasH = $j('body').height();

//var canvasW     = 640;
//var canvasH     = 480;

var numMovers   = 550;
var movers      = [];
var friction    = .96;
var radCirc     = Math.PI * 2;

var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0;
var isMouseDown = true;

function init()
{
    canvas = document.getElementById("mainCanvas");

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

function setup()
{
    outerDiv = document.getElementById("outer");
    canvasDiv = document.getElementById("canvasContainer");
    ctx = canvas.getContext("2d");

    var i = numMovers;
    while( i-- )
    {
        var m = new Mover();
        m.x  = canvasW * .5;
        m.y  = canvasH * .5;
        m.vX = Math.cos(i) * Math.random() * 25;
        m.vY = Math.sin(i) * Math.random() * 25;
        m.size = 2;
        movers[i] = m;
    }

    document.onmousedown = onDocMouseDown;
    document.onmouseup   = onDocMouseUp;
    document.onmousemove = onDocMouseMove;
}

function run()
{
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "rgba(8,8,12,.65)";
    ctx.fillRect( 0 , 0 , canvasW , canvasH );
    ctx.globalCompositeOperation = "lighter";

    mouseVX    = mouseX - prevMouseX;
    mouseVY    = mouseY - prevMouseY;
    prevMouseX = mouseX;
    prevMouseY = mouseY;

    var toDist   = canvasW / 1.15;
    var stirDist = canvasW / 8;
    var blowDist = canvasW / 2;

    var Mrnd   = Math.random;
    var Mabs   = Math.abs;
    var Msqrt  = Math.sqrt;
    var Mcos   = Math.cos;
    var Msin   = Math.sin;
    var Matan2 = Math.atan2;
    var Mmax   = Math.max;
    var Mmin   = Math.min;

    var i = numMovers;
    while( i-- )
    {
        var m  = movers[i];
        var x  = m.x;
        var y  = m.y;
        var vX = m.vX;
        var vY = m.vY;

        var dX = x - mouseX;
        var dY = y - mouseY;
        var d = Msqrt( dX * dX + dY * dY );
        var a = Matan2( dY , dX );
        var cosA = Mcos( a );
        var sinA = Msin( a );

        if( isMouseDown )
        {
            if( d < blowDist )
            {
                var blowAcc = ( 1 - ( d / blowDist ) ) * 2;
                vX += cosA * blowAcc + .5 - Mrnd();
                vY += sinA * blowAcc + .5 - Mrnd();
            }
        }

        if( d < toDist )
        {
            var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014;
            vX -= cosA * toAcc;
            vY -= sinA * toAcc;
        }

        if( d < stirDist )
        {
            var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022;
            vX += mouseVX * mAcc;
            vY += mouseVY * mAcc;
        }

        vX *= friction;
        vY *= friction;

        var avgVX = Mabs( vX );
        var avgVY = Mabs( vY );
        var avgV = ( avgVX + avgVY ) * .5;

        if( avgVX < .1 ) vX *= Mrnd() * 3;
        if( avgVY < .1 ) vY *= Mrnd() * 3;

        var sc = avgV * .45;
        sc = Mmax( Mmin( sc , 3.5 ) , .4 );

        var nextX = x + vX;
        var nextY = y + vY;

        if( nextX > canvasW )
        {
            nextX = canvasW;
            vX *= -1;
        }
        else if( nextX < 0 )
        {
            nextX = 0;
            vX *= -1;
        }

        if( nextY > canvasH )
        {
            nextY = canvasH;
            vY *= -1;
        }
        else if( nextY < 0 )
        {
            nextY = 0;
            vY *= -1;
        }

        m.vX = vX;
        m.vY = vY;
        m.x  = nextX;
        m.y  = nextY;

        ctx.fillStyle = m.color;
        ctx.beginPath();
        ctx.arc( nextX , nextY , sc , 0 , radCirc , true );
        ctx.closePath();
        ctx.fill();
    }

    //rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 );
}

function onDocMouseMove( e )
{
    var ev = e ? e : window.event;
    mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;
    mouseY = ev.clientY - outerDiv.offsetTop  - canvasDiv.offsetTop;
}

function onDocMouseDown( e )
{
    isMouseDown = true;
    return false;
}

function onDocMouseUp( e )
{
    isMouseDown = true;
    return false;
}

// ==========================================================================================

function Mover()
{
    this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
    this.y     = 0;
    this.x     = 0;
    this.vX    = 0;
    this.vY    = 0;
    this.size  = 0;
}

// ==========================================================================================

function rect( context , x , y , w , h )
{
    context.beginPath();
    context.rect( x , y , w , h );
    context.closePath();
    context.fill();
}

// ==========================================================================================

Body:
Because it was not posted yet and is a simple css fix:

#canvas {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
}

Works great if you want to apply a fullscreen canvas background (for example with Granim.js).


来源: stackexchange

问:
Resources inside Loader's loadInBackground()?
As far as I know, I can't hold reference to the activity's context inside a Loader.

Is there a safe way to get resources inside Loader's loadInBackground() method?

答:
See the docs of the constructor of Loader:

Loader (Context context)

Stores away the application context associated with context. Since Loaders can be used across multiple activities it's dangerous to store the context directly; always use getContext() to retrieve the Loader's Context, don't use the constructor argument directly. The Context returned by getContext() is safe to use across Activity instances.

And the implementation:

```
<code>
    public Loader(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * @return an application context retrieved from the Context passed to the constructor.
     */
    public Context getContext() {
        return mContext;
    }

</code>
```

So, within loadInBackground() you are free to get the resources from the context that Loader class retains, because it's an application context.

ContentLicense: CC BY-SA 3.0

Body:
See the docs of the constructor of Loader:

Loader (Context context)

Stores away the application context associated with context. Since Loaders can be used across multiple activities it's dangerous to store the context directly; always use getContext() to retrieve the Loader's Context, don't use the constructor argument directly. The Context returned by getContext() is safe to use across Activity instances.

And the implementation:

    public Loader(Context context) {
        mContext = context.getApplicationContext();
    }

    /**
     * @return an application context retrieved from the Context passed to the constructor.
     */
    public Context getContext() {
        return mContext;
    }

So, within loadInBackground() you are free to get the resources from the context that Loader class retains, because it's an application context.


问:
Downloading Xcode 9 (or 9.1 Beta release)
I downloaded iOS 11 on my device and want to continue testing my projects on my device but it wont work because it says that ios 11.0 may not support the version of Xcode I have (which is 8.3.3). I am assuming this is because I need to use the Xcode 9 (or 9.1 beta release) but I can't seem to find where I can download this at.</p>

答:
According to Apple's developer downloads page:

Your Apple ID must be associated with a paid Apple Developer Program or Apple Developer Enterprise Program to access certain software downloads. You can download Xcode or sign in with a different account

It seems need to login a paid account to get XCode9.My paid account can access the new beta XCode resource but another non-payment account can't.


问:
Change in variable triggers an event
Is triggering an event via a change in variable possible? For example.

This would trigger the event

```<code>Dim t As Integer
Dim Fire As Boolean

Private Sub Test
t = 0
Fire = True
IIf Fire, t=1, t=2
End sub
</code>```

In the event handler

```<code>Select Case t
    Case 0
       'Do something
    Case 1
       'Do something
    Case 2
       'Do something
    Case 3
       'Do something
    ...
</code>```

Google brings up Event handlers, and using class modules but I am unable to wrap my head around it.

答:
Yes this is possible. However, you'll need an Object Oriented approach.
You first need to define a class that raises the events you wish to hook into. Secondly you'll need a class that actually handles the event, since you can not use event handlers in a regular module.
Thirdly, in your regular module you can then just use these classes.

Here's a simple example:
Create a class module named "ClassWithEvent". Place the following code:

```<code>Public Event VariableChange(value As Integer)
Private p_int As Integer
Public Property Get value() As Integer
    value = p_int
End Property
Public Property Let value(value As Integer)
    If p_int <> value Then RaiseEvent VariableChange(value) 'Only raise on actual change.
    p_int = value
End Property
</code>```

Next, create the class that can handle the events raised by this class.
Name this Class Module "ClassHandlesEvent". Place the following code in it:

```<code>Private WithEvents SomeVar As ClassWithEvent
Private Sub SomeVar_VariableChange(value As Integer) 'This is the event handler.
    Select Case value
        Case 1:
            MsgBox "here, 1!"
        Case 2:
            MsgBox "here, 2!"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Get EventVariable() As ClassWithEvent
    Set EventVariable = SomeVar
End Property
Public Property Let EventVariable(value As ClassWithEvent)
    Set SomeVar = value
End Property
</code>```

Next, in a regular module, instantiate your ClassWithEvent and pass this one as a property to the class that handles them.

```<code>Sub test()
    Dim var As ClassHandlesEvent
    Dim tst As ClassWithEvent

    Set var = New ClassHandlesEvent
    Set tst = New ClassWithEvent
    var.EventVariable = tst

    tst.value = 2 'A messagebox saying "Here, 2!" will pop-up
End Sub
</code>```

Title: Change in variable triggers an event

Body:
Is triggering an event via a change in variable possible? For example.

This would trigger the event

Dim t As Integer
Dim Fire As Boolean

Private Sub Test
t = 0
Fire = True
IIf Fire, t=1, t=2
End sub

In the event handler

Select Case t
    Case 0
       'Do something
    Case 1
       'Do something
    Case 2
       'Do something
    Case 3
       'Do something
    ...

Google brings up Event handlers, and using class modules but I am unable to wrap my head around it.

Body:
Yes this is possible. However, you'll need an Object Oriented approach.
You first need to define a class that raises the events you wish to hook into. Secondly you'll need a class that actually handles the event, since you can not use event handlers in a regular module.
Thirdly, in your regular module you can then just use these classes.

Here's a simple example:
Create a class module named "ClassWithEvent". Place the following code:

Public Event VariableChange(value As Integer)
Private p_int As Integer
Public Property Get value() As Integer
    value = p_int
End Property
Public Property Let value(value As Integer)
    If p_int <> value Then RaiseEvent VariableChange(value) 'Only raise on actual change.
    p_int = value
End Property

Next, create the class that can handle the events raised by this class.
Name this Class Module "ClassHandlesEvent". Place the following code in it:

Private WithEvents SomeVar As ClassWithEvent
Private Sub SomeVar_VariableChange(value As Integer) 'This is the event handler.
    Select Case value
        Case 1:
            MsgBox "here, 1!"
        Case 2:
            MsgBox "here, 2!"
        Case Default:
            'Do Nothing
    End Select
End Sub
Public Property Get EventVariable() As ClassWithEvent
    Set EventVariable = SomeVar
End Property
Public Property Let EventVariable(value As ClassWithEvent)
    Set SomeVar = value
End Property

Next, in a regular module, instantiate your ClassWithEvent and pass this one as a property to the class that handles them.

Sub test()
    Dim var As ClassHandlesEvent
    Dim tst As ClassWithEvent

    Set var = New ClassHandlesEvent
    Set tst = New ClassWithEvent
    var.EventVariable = tst

    tst.value = 2 'A messagebox saying "Here, 2!" will pop-up
End Sub


问:
Parcelable get huge infinite items from array up to OOM
I am using Parcelable to communicate between fragments. Everything is working good, but sometimes when Android kills app process to free up the memory and user returns to app, the Parcelable gets huge amount of items from arrays like couple millions items instead of 2-3 and of course it throws OOM.
I suppose something's wrong with CREATOR, but I can't handle it.
The code for parcelable is composed from super class and child class and my interested item class:

base class:

```<code> public abstract class BaseRs implements Parcelable {

private String token;
private String msgAlert;
private String simpleMsg;
private AdsObj adsObj;
private Map<String, String> mapSettings;

//getters & setters

public BaseRs() {
}

protected BaseRs(Parcel in) {
    token = in.readString();
    msgAlert = in.readString();
    simpleMsg = in.readString();
    adsObj = in.readParcelable(AdsObj.class.getClassLoader());
    mapSettings = MapParcelable.readParcelable(in);
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(token);
    dest.writeString(msgAlert);
    dest.writeString(simpleMsg);
    dest.writeParcelable(adsObj, flags);
    MapParcelable.writeToParcel(dest, mapSettings);
 }

}
</code>```

child class

```<code>public class GetSalesItemsRs extends BaseRs {

private SaleCoinItem[] coinPacksArray;

//getters+ setters

protected GetSalesItemsRs(Parcel in) {
    super(in);
    coinPacksArray = in.createTypedArray(SaleCoinItem.CREATOR);
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    super.writeToParcel(dest, flags);
    dest.writeTypedArray(coinPacksArray, flags);
}

@Override
public int describeContents() {
    return 0;
}

public static final Creator<GetSalesItemsRs> CREATOR = new Creator<GetSalesItemsRs>() {
    @Override
    public GetSalesItemsRs createFromParcel(Parcel in) {
        return new GetSalesItemsRs(in);
    }

    @Override
    public GetSalesItemsRs[] newArray(int size) {
        return new GetSalesItemsRs[size];
    }
    };
}
</code>```

and my interested object

```<code>public class SaleCoinItem implements Parcelable {

private int amount;
private double price;
private int sortOrder;

//getters & setters

protected SaleCoinItem(Parcel in) {
    amount = in.readInt();
    price = in.readDouble();
    sortOrder = in.readInt();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(amount);
    dest.writeDouble(price);
    dest.writeInt(sortOrder);
}

@Override
public int describeContents() {
    return 0;
}

public static final Creator<SaleCoinItem> CREATOR = new Creator<SaleCoinItem>() {
    @Override
    public SaleCoinItem createFromParcel(Parcel in) {
        return new SaleCoinItem(in);
    }

    @Override
    public SaleCoinItem[] newArray(int size) {
        return new SaleCoinItem[size];

       }
    };
}
</code>```

The functiona to parcel Map - maybe here is the error ;)

```<code>public class MapParcelable {

public static void writeToParcel(Parcel out, Map<String, String> map) {
    if (map != null) {
        out.writeInt(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            out.writeString(entry.getKey());
            out.writeString(entry.getValue());
        }
    }
}

public static Map<String, String> readParcelable(Parcel parcel) {
    Map<String, String> map = new HashMap<String, String>();
    int size = parcel.readInt();
    for (int i = 0; i < size; i++) {
        String key = parcel.readString();
        String value = parcel.readString();
        map.put(key, value);
    }

    return map;

   }

}
</code>```

I get parcelable obj inside the onCreateView method :

```<code>GetSalesItemsRs mGetSalesItemsRs = getArguments().getParcelable(KEY_PARCEL);
</code>```

答:
I think the problem is that if the Map is null you're not writing the size field to the Parcel, but when you read it you always read the size field, and it might end up reading some random value. So or you change the code to

```<code>if (map != null) {
    out.writeInt(map.size());
    for (Map.Entry<String, String> entry : map.entrySet()) {
        out.writeString(entry.getKey());
        out.writeString(entry.getValue());
    }
}else{
    out.writeInt(0);
}
</code>```

and you will never get a null  value when recreating the class, or you create another boolean field "hasMap" and always write that one

Body:
I am using Parcelable to communicate between fragments. Everything is working good, but sometimes when Android kills app process to free up the memory and user returns to app, the Parcelable gets huge amount of items from arrays like couple millions items instead of 2-3 and of course it throws OOM.
I suppose something's wrong with CREATOR, but I can't handle it.
The code for parcelable is composed from super class and child class and my interested item class:

base class:

 public abstract class BaseRs implements Parcelable {

private String token;
private String msgAlert;
private String simpleMsg;
private AdsObj adsObj;
private Map<String, String> mapSettings;

//getters & setters

public BaseRs() {
}

protected BaseRs(Parcel in) {
    token = in.readString();
    msgAlert = in.readString();
    simpleMsg = in.readString();
    adsObj = in.readParcelable(AdsObj.class.getClassLoader());
    mapSettings = MapParcelable.readParcelable(in);
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(token);
    dest.writeString(msgAlert);
    dest.writeString(simpleMsg);
    dest.writeParcelable(adsObj, flags);
    MapParcelable.writeToParcel(dest, mapSettings);
 }

}

child class

public class GetSalesItemsRs extends BaseRs {

private SaleCoinItem[] coinPacksArray;

//getters+ setters

protected GetSalesItemsRs(Parcel in) {
    super(in);
    coinPacksArray = in.createTypedArray(SaleCoinItem.CREATOR);
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    super.writeToParcel(dest, flags);
    dest.writeTypedArray(coinPacksArray, flags);
}

@Override
public int describeContents() {
    return 0;
}

public static final Creator<GetSalesItemsRs> CREATOR = new Creator<GetSalesItemsRs>() {
    @Override
    public GetSalesItemsRs createFromParcel(Parcel in) {
        return new GetSalesItemsRs(in);
    }

    @Override
    public GetSalesItemsRs[] newArray(int size) {
        return new GetSalesItemsRs[size];
    }
    };
}

and my interested object

public class SaleCoinItem implements Parcelable {

private int amount;
private double price;
private int sortOrder;

//getters & setters

protected SaleCoinItem(Parcel in) {
    amount = in.readInt();
    price = in.readDouble();
    sortOrder = in.readInt();
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(amount);
    dest.writeDouble(price);
    dest.writeInt(sortOrder);
}

@Override
public int describeContents() {
    return 0;
}

public static final Creator<SaleCoinItem> CREATOR = new Creator<SaleCoinItem>() {
    @Override
    public SaleCoinItem createFromParcel(Parcel in) {
        return new SaleCoinItem(in);
    }

    @Override
    public SaleCoinItem[] newArray(int size) {
        return new SaleCoinItem[size];

       }
    };
}

The functiona to parcel Map - maybe here is the error ;)

public class MapParcelable {

public static void writeToParcel(Parcel out, Map<String, String> map) {
    if (map != null) {
        out.writeInt(map.size());
        for (Map.Entry<String, String> entry : map.entrySet()) {
            out.writeString(entry.getKey());
            out.writeString(entry.getValue());
        }
    }
}

public static Map<String, String> readParcelable(Parcel parcel) {
    Map<String, String> map = new HashMap<String, String>();
    int size = parcel.readInt();
    for (int i = 0; i < size; i++) {
        String key = parcel.readString();
        String value = parcel.readString();
        map.put(key, value);
    }

    return map;

   }

}

I get parcelable obj inside the onCreateView method :

GetSalesItemsRs mGetSalesItemsRs = getArguments().getParcelable(KEY_PARCEL);

Body:
I think the problem is that if the Map is null you're not writing the size field to the Parcel, but when you read it you always read the size field, and it might end up reading some random value. So or you change the code to

if (map != null) {
    out.writeInt(map.size());
    for (Map.Entry<String, String> entry : map.entrySet()) {
        out.writeString(entry.getKey());
        out.writeString(entry.getValue());
    }
}else{
    out.writeInt(0);
}

and you will never get a null  value when recreating the class, or you create another boolean field "hasMap" and always write that one


问:
Qml button fix size
I have made list whose delegate is RowLayout consist of Button. The list takes data from cpp.

My problem is the button variable width. The button side changed based on data. I want to keep fix button side and wrap text

答:
To give your Button a fixed width, just set the property with the same name to a fixed value.

The Button has a contentItem that is a Text. You can change the wrapMode there to Text.WordWrap

As the contentItem is of type Item you can't set the wrapMode like this:

```<code>Button {
    width: 100
    text:  'Very very long button description.'
    contentItem.wrapMode: Text.WordWrap // Won't work
}
</code>```

Instead you might use Component.onCompleted like this:

```<code>Button {
    width: 100
    text:  'Very very long button description.'
    Component.onCompleted: contentItem.wrapMode = Text.WordWrap
}
</code>```

Title: Qml button fix size

Body:
To give your Button a fixed width, just set the property with the same name to a fixed value.

The Button has a contentItem that is a Text. You can change the wrapMode there to Text.WordWrap

As the contentItem is of type Item you can't set the wrapMode like this:

Button {
    width: 100
    text:  'Very very long button description.'
    contentItem.wrapMode: Text.WordWrap // Won't work
}

Instead you might use Component.onCompleted like this:

Button {
    width: 100
    text:  'Very very long button description.'
    Component.onCompleted: contentItem.wrapMode = Text.WordWrap
}


问:
AngularJS tests - inject -> module -> inject
I'm trying to test a service documentViewer that depends on some other service authService

```<code>  angular
    .module('someModule')
    .service('documentViewer', DocumentViewer);

  /* @ngInject */
  function DocumentViewer($q, authService) {
    // ...

    this.view = function(doc) {
      //...
    }
  }
</code>```

This  is what my test looks like at the moment

```<code>it('test', inject(function($q) {
  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };

  var auth = {
    refreshProfileData: function() {
      return $q.resolve(0);
    },
  };

  var viewer = createViewer(auth);
}));

function createViewer(auth) {
  var viewer;

  module({
    authService: auth
  });
  inject(function(documentViewer) {
    viewer = documentViewer;
  });

  return viewer;
}
</code>```

The problem is I need to call inject to grab a $q, then use it to create my mocks, register my mocks with module, and then call inject again to grab the unit under test.

This results in

Error: Injector already created, can not register a module! in bower_components/angular-mocks/angular-mocks.js (line 2278)

I've seen lots of answers here on SO saying you can't call module after inject, but they don't offer any alternative to a scenario like the above.

What's the correct approach here?

PS: I'd like to avoid using beforeEach, I want each test to be self-contained.

答:
module is used to define which modules will be loaded with inject and cannot be called after inject, this is chicken-egg situation.

The object accepted by module is used to define mocked services with $provide.value:

If an object literal is passed each key-value pair will be registered on the module via $provide.value, the key being the string name (or token) to associate with the value on the injector.

There can be no more than 1 function like createViewer that calls both module and inject. If this means that this kind of self-contained test is an antipattern, there is nothing that can be done about that. Angular testing works best with usual habits, including beforeEach and local variables.

In order to eliminate the dependency on $q, mocked service can be made a factory.

```<code>it('test', function () {
  var authFactory = function ($q) {
    return {
      refreshProfileData: function() {
        return $q.resolve(0);
      },
    };
  };

  // mocks defined first
  module(function ($provide) {
    $provide.factory('authService': authFactory);
  });

  var viewer;
  inject(function(documentViewer) {
    viewer = documentViewer;
  });
  // no module(...) is allowed after this point

  var $q;
  inject(function(_$q_) {
    $q = _$q_;
  });

  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };
});
</code>```

Body:
I'm trying to test a service documentViewer that depends on some other service authService

  angular
    .module('someModule')
    .service('documentViewer', DocumentViewer);

  /* @ngInject */
  function DocumentViewer($q, authService) {
    // ...

    this.view = function(doc) {
      //...
    }
  }

This  is what my test looks like at the moment

it('test', inject(function($q) {
  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };

  var auth = {
    refreshProfileData: function() {
      return $q.resolve(0);
    },
  };

  var viewer = createViewer(auth);
}));

function createViewer(auth) {
  var viewer;

  module({
    authService: auth
  });
  inject(function(documentViewer) {
    viewer = documentViewer;
  });

  return viewer;
}

The problem is I need to call inject to grab a $q, then use it to create my mocks, register my mocks with module, and then call inject again to grab the unit under test.

This results in

Error: Injector already created, can not register a module! in bower_components/angular-mocks/angular-mocks.js (line 2278)

I've seen lots of answers here on SO saying you can't call module after inject, but they don't offer any alternative to a scenario like the above.

What's the correct approach here?

PS: I'd like to avoid using beforeEach, I want each test to be self-contained.

Body:
module is used to define which modules will be loaded with inject and cannot be called after inject, this is chicken-egg situation.

The object accepted by module is used to define mocked services with $provide.value:

If an object literal is passed each key-value pair will be registered on the module via $provide.value, the key being the string name (or token) to associate with the value on the injector.

There can be no more than 1 function like createViewer that calls both module and inject. If this means that this kind of self-contained test is an antipattern, there is nothing that can be done about that. Angular testing works best with usual habits, including beforeEach and local variables.

In order to eliminate the dependency on $q, mocked service can be made a factory.

it('test', function () {
  var authFactory = function ($q) {
    return {
      refreshProfileData: function() {
        return $q.resolve(0);
      },
    };
  };

  // mocks defined first
  module(function ($provide) {
    $provide.factory('authService': authFactory);
  });

  var viewer;
  inject(function(documentViewer) {
    viewer = documentViewer;
  });
  // no module(...) is allowed after this point

  var $q;
  inject(function(_$q_) {
    $q = _$q_;
  });

  var doc = {
    view: function() {
      return $q.resolve(0);
    }
  };
});


问:
How to view file diff in git before commit
This often happens to me:

I'm working on a couple related changes at the same time over the course of a day or two, and when it's time to commit, I end up forgetting what changed in a specific file. (This is just a personal git repo, so I'm ok with having more than one update in a commit.)

Is there any way to preview the changes between my local file, which is about to be checked in, and the last commit for that file?

Something like:

```<code>git diff --changed /myfile.txt
</code>```

And it would print out something like:

```<code>line 23
  (last commit): var = 2+2
  (current):     var = myfunction() + 2

line 149
  (last commit): return var
  (current):     return var / 7
</code>```

This way, I could quickly see what I had done in that file since it was last checked in.

答: On macOS, go to the git root directory and enter git diff *

Body:
This often happens to me:

I'm working on a couple related changes at the same time over the course of a day or two, and when it's time to commit, I end up forgetting what changed in a specific file. (This is just a personal git repo, so I'm ok with having more than one update in a commit.)

Is there any way to preview the changes between my local file, which is about to be checked in, and the last commit for that file?

Something like:

git diff --changed /myfile.txt

And it would print out something like:

line 23
  (last commit): var = 2+2
  (current):     var = myfunction() + 2

line 149
  (last commit): return var
  (current):     return var / 7

This way, I could quickly see what I had done in that file since it was last checked in.


答:
Should you want to add a new column (say 'count_column') containing the groups' counts into the dataframe:

```<code>df.count_column=df.groupby(['col5','col2']).col5.transform('count')
</code>```

(I picked 'col5' as it contains no nan)

ContentLicense: CC BY-SA 4.0

Title: Pandas DataFrame Groupby two columns and get counts

Body:
I have a pandas dataframe in the following format:

df = pd.DataFrame([
    [1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3],
    list('AAABBBBABCBDDD'),
    [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8],
    ['x/y/z','x/y','x/y/z/n','x/u','x','x/u/v','x/y/z','x','x/u/v/b','-','x/y','x/y/z','x','x/u/v/w'],
    ['1','3','3','2','4','2','5','3','6','3','5','1','1','1']
]).T
df.columns = ['col1','col2','col3','col4','col5']

df:

   col1 col2 col3     col4 col5
0   1.1    A  1.1    x/y/z    1
1   1.1    A  1.7      x/y    3
2   1.1    A  2.5  x/y/z/n    3
3   2.6    B  2.6      x/u    2
4   2.5    B  3.3        x    4
5   3.4    B  3.8    x/u/v    2
6   2.6    B    4    x/y/z    5
7   2.6    A  4.2        x    3
8   3.4    B  4.3  x/u/v/b    6
9   3.4    C  4.5        -    3
10  2.6    B  4.6      x/y    5
11  1.1    D  4.7    x/y/z    1
12  1.1    D  4.7        x    1
13  3.3    D  4.8  x/u/v/w    1

I want to get the count by each row like following. Expected Output:

col5 col2 count
1    A      1
     D      3
2    B      2
etc...

How to get my expected output? And I want to find largest count for each 'col2' value?

Body:
Should you want to add a new column (say 'count_column') containing the groups' counts into the dataframe:

df.count_column=df.groupby(['col5','col2']).col5.transform('count')

(I picked 'col5' as it contains no nan)


问:
Specify subclass mapping for Single Table Inheritance
The documentation for inheritance explains how to easily implement STI given that you can choose the values for the type column.

However, I have a legacy DB, and these values already exist. Let's say those are PRIORITY, ECONOMY, and FLEXI, how do I specify how to map these values to subclasses?

```<code>class PriorityPassenger < Passenger
  # map to PRIORITY
end
</code>```

答:
This should work (untested):</p>

```<code>ActiveRecord::Inheritance::ClassMethods.prepend(Module.new do
  def find_sti_class(type_name)
    case type_name
    when 'PRIORITY' then PriorityPassenger
    ...
    else super(type_name)
    end
  end
end)
</code>```

Body:
The documentation for inheritance explains how to easily implement STI given that you can choose the values for the type column.

However, I have a legacy DB, and these values already exist. Let's say those are PRIORITY, ECONOMY, and FLEXI, how do I specify how to map these values to subclasses?

class PriorityPassenger < Passenger
  # map to PRIORITY
end

Body:
This should work (untested):

ActiveRecord::Inheritance::ClassMethods.prepend(Module.new do
  def find_sti_class(type_name)
    case type_name
    when 'PRIORITY' then PriorityPassenger
    ...
    else super(type_name)
    end
  end
end)


问:
Memory Consistency || Thread interference || Php
I have a question regarding Memcache and session lock for user session.
I want to lock or do something that will prevent Thread Interference for user session...

We have a situation like so:

If server is at max, user is redirected to "free" server, but a this point some of data are wrong...

So does anybody has any sugestions :?

答:
All your Memcached servers must be listed in your app/etc/local.xml file and be the same for each server, that way they will share the session data.

Alternatively - or additionally - a better load balancing policy would be "consistent hashing".  Users would be spread evenly over the available servers and each user would be handled by the same server, and hence, same session.

ContentLicense: CC BY-SA 2.5


问:
Can't center divs HTML CSS
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page">
  <div id="pageName" }>
    <p>Colour</p>
  </div>
  <div id="bg_01">
  </div>

  <div id="bg_02">
  </div>

  <div id="bg_03">
  </div>

  <div id="bg_04">
  </div>

  <div id="bg_05">
  </div>
</div></code>```

答:
Take away Float: left from your objects and give them display: inline-block.

Also give text-align: center to your parent div

```<code>p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  display: inline-block;
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_02 {
  display: inline-block;
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_03 {
  display: inline-block;
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_04 {
  display: inline-block;
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_05 {
  display: inline-block;
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}
</code>```

Title: Can't center divs HTML CSS

Body:
i'm having a small issue getting my divs to sit inline with each other and in the center of the parent div. So I have one parent "page" then 6 other divs inside of that the "pageName" which sits above "bg_01", "bg_02", "bg_03", "bg_04", "bg_05", "bg_06" which all sit inline with each other. However it works when the window is quite small however i'm trying to get it to work when the window is any size, can anyone see where I'm going wrong?

Thanks again guys.

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_02 {
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_03 {
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_04 {
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

#bg_05 {
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
  float: left;
}

Colour

Body:
Take away Float: left from your objects and give them display: inline-block.

Also give text-align: center to your parent div

p {
  margin: 0;
}

#page {
  border: 2px solid #e1dfe1;
  border-radius: 5px;
  background-color: #fff;
  width: 100%;
  height: 200px;
  margin-top: 50px;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-align: center;
}

#pageName {
  background-color: #f5f0f5;
  border-bottom: 2px solid #e1dfe1;
}

#pageName p {
  padding-top: 15px;
  padding-bottom: 15px;
  padding-left: 15px;
  color: #565656;
  font-weight: bold;
}

#bg_01 {
  display: inline-block;
  background-color: #80b3ff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_02 {
  display: inline-block;
  background-color: #afe9af;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_03 {
  display: inline-block;
  background-color: #ffb380;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_04 {
  display: inline-block;
  background-color: #ffaaaa;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}

#bg_05 {
  display: inline-block;
  background-color: #eeaaff;
  width: 80px;
  height: 80px;
  border: 3px solid #666;
  border-radius: 20px;
  margin: 4%;
}


问:
how to start QTimer so that the GUI does not hangs-RestartStoppedProcess()-code
I have made new QTimer object in my class's ctor. When the application starts the timer also starts with the specified time. This timer keeps a track of all the process IDs and if finds that a particular process-id is not active(killed from task manager) then it restarts that particular process. Now the issue is my application lags a-bit due to this QTimer object and only after the timeout, the application becomes smooth. But after 5 seconds the timer starts again and the application starts lagging again. What is the best alternative to start a QTimer object apart from ctor of a class?</p>

```<code>qTimer = new QTimer(0);

connect(qTimer, SIGNAL(timeout()), this, SLOT(RestartStoppedProcess()), Qt::DirectConnection);
connect(qTimer, SIGNAL(destroyed()), qTimer, SLOT(deleteLater()), Qt::DirectConnection);

qTimer->setTimerType(Qt::VeryCoarseTimer);
qTimer->start(5000);

void ProcessMonitor::RestartStoppedProcess()
{
    try
    {
        QProcess *objMonitorProcess = new QProcess(this);
        connect(objMonitorProcess, SIGNAL(finished(int,QProcess::ExitStatus)), objMonitorProcess, SLOT(deleteLater()));
        for(int i = 0; i < ui->twShowProcess->rowCount(); i++)
        {
#ifdef Q_WS_LIN
            //            objMonitorProcess->start("pidof", QStringList() << (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
            objMonitorProcess->start("pidof "+ (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
#elif Q_WS_WIN
            QString cmd("wmic process where ");
            QString qszFilters("\"processid=\'");
            QString qszSubFilters = qszFilters.append(ui->twShowProcess->item(i, 1)->text().append("\'").append("\"").append(" get name"));
            cmd.append(qszSubFilters);
            objMonitorProcess->start(cmd.toStdString().c_str(), QIODevice::ReadOnly);
#else
            QString qszProcessName = ui->twShowProcess->item(i, 0)->text().split(".").takeFirst();
            objMonitorProcess->start("pgrep", QStringList() << qszProcessName, QIODevice::ReadOnly);
#endif
            if((objMonitorProcess->waitForStarted(4000) == true) && (objMonitorProcess->state() == QProcess::Running))
            {
                if(objMonitorProcess->waitForFinished(3000) == false)
                    continue;
                else
                {
                    QString qszProcessStatus = ui->twShowProcess->item(i, 3)->text();
                    if(qszProcessStatus.compare("Running") == 0)
                    {
                        QString qszStandardOutput, qszStandardError;
                        qszStandardOutput.clear(); qszStandardError.clear();
                        qszStandardOutput = QString(objMonitorProcess->readAllStandardOutput());
                        qszStandardError = QString(objMonitorProcess->readAllStandardError());
                        if(qszStandardError.simplified().compare("No Instance(s) Available.", Qt::CaseInsensitive) == 0 && qszStandardOutput.simplified().isEmpty() == true)
                        {
                            ui->twShowProcess->selectRow(i);
                            if(ui->twShowProcess->selectedItems().at(0)->text().compare("LTtagdb.exe", Qt::CaseInsensitive) == 0 ||
                                    ui->twShowProcess->selectedItems().at(0)->text().compare("LTmessagebroker.exe", Qt::CaseInsensitive) == 0)
                                this->StopAllApplicationsForcefully();
                            else
                                this->on_actionStop_triggered();

                            if(this->ptrobjContextMenu->isVisible())
                                this->ptrobjContextMenu->close();

                            ui->twShowProcess->clearSelection();

                            if(mobj_ProcessLogMap.mobj_ProcessAndLogMapping.contains(ui->twShowProcess->item(i, 8)->text()) == true)
                            {
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.remove(ui->twShowProcess->item(i, 8)->text());
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                            }
                            else
                                this->mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                        }

                        if(ui->twShowProcess->item(i, 0)->text() == "LThistdb.exe")
                        {
                            if(IsServiceRunning(QString("LThistdb.exe")) == false)
                                this->on_actionStopPostgreSQL_DB_Server_triggered();
                        }
                        qszStandardOutput.clear();
                    }
                }
            }
            else
                break;
#ifdef Q_WS_WIN
            cmd.clear();
            qszFilters.clear();
            qszSubFilters.clear();
#endif
        }
    }
    catch(QProcess::ProcessError pError)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Crashed", "Process error returned code: " + QString::number(pError));
    }
    catch(...)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Unknown Crash", "Unknown crash exit-child process may not be running correctly!");
    }
}
</code>```

答:
The problem is likely due to the amount of work being done by RestartStoppedProcess.

As the documentation for QTimer states, when discussing the called slot:

It should be written in such a way that it always returns quickly (typically after processing one data item) so that Qt can deliver events to the user interface and stop the timer as soon as it has done all its work.

As you've witnessed with your application, a heavy workload with a QTimer on the main thread can cause lag in the Gui. The Qt documentation goes on to state:

This is the traditional way of implementing heavy work in GUI applications, but as multithreading is nowadays becoming available on more and more platforms, we expect that zero-millisecond QTimer objects will gradually be replaced by QThreads.

With this in mind, I suggest refactoring your code so that RestartStoppedProcess functions in a separate thread. There's a great tutorial on "How to Really Truly Use QThread" here.

Body:
I have made new QTimer object in my class's ctor. When the application starts the timer also starts with the specified time. This timer keeps a track of all the process IDs and if finds that a particular process-id is not active(killed from task manager) then it restarts that particular process. Now the issue is my application lags a-bit due to this QTimer object and only after the timeout, the application becomes smooth. But after 5 seconds the timer starts again and the application starts lagging again. What is the best alternative to start a QTimer object apart from ctor of a class?

qTimer = new QTimer(0);

connect(qTimer, SIGNAL(timeout()), this, SLOT(RestartStoppedProcess()), Qt::DirectConnection);
connect(qTimer, SIGNAL(destroyed()), qTimer, SLOT(deleteLater()), Qt::DirectConnection);

qTimer->setTimerType(Qt::VeryCoarseTimer);
qTimer->start(5000);

void ProcessMonitor::RestartStoppedProcess()
{
    try
    {
        QProcess *objMonitorProcess = new QProcess(this);
        connect(objMonitorProcess, SIGNAL(finished(int,QProcess::ExitStatus)), objMonitorProcess, SLOT(deleteLater()));
        for(int i = 0; i < ui->twShowProcess->rowCount(); i++)
        {
#ifdef Q_WS_LIN
            //            objMonitorProcess->start("pidof", QStringList() << (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
            objMonitorProcess->start("pidof "+ (ui->twShowProcess->item(i, 0)->text()), QIODevice::ReadOnly);
#elif Q_WS_WIN
            QString cmd("wmic process where ");
            QString qszFilters("\"processid=\'");
            QString qszSubFilters = qszFilters.append(ui->twShowProcess->item(i, 1)->text().append("\'").append("\"").append(" get name"));
            cmd.append(qszSubFilters);
            objMonitorProcess->start(cmd.toStdString().c_str(), QIODevice::ReadOnly);
#else
            QString qszProcessName = ui->twShowProcess->item(i, 0)->text().split(".").takeFirst();
            objMonitorProcess->start("pgrep", QStringList() << qszProcessName, QIODevice::ReadOnly);
#endif
            if((objMonitorProcess->waitForStarted(4000) == true) && (objMonitorProcess->state() == QProcess::Running))
            {
                if(objMonitorProcess->waitForFinished(3000) == false)
                    continue;
                else
                {
                    QString qszProcessStatus = ui->twShowProcess->item(i, 3)->text();
                    if(qszProcessStatus.compare("Running") == 0)
                    {
                        QString qszStandardOutput, qszStandardError;
                        qszStandardOutput.clear(); qszStandardError.clear();
                        qszStandardOutput = QString(objMonitorProcess->readAllStandardOutput());
                        qszStandardError = QString(objMonitorProcess->readAllStandardError());
                        if(qszStandardError.simplified().compare("No Instance(s) Available.", Qt::CaseInsensitive) == 0 && qszStandardOutput.simplified().isEmpty() == true)
                        {
                            ui->twShowProcess->selectRow(i);
                            if(ui->twShowProcess->selectedItems().at(0)->text().compare("LTtagdb.exe", Qt::CaseInsensitive) == 0 ||
                                    ui->twShowProcess->selectedItems().at(0)->text().compare("LTmessagebroker.exe", Qt::CaseInsensitive) == 0)
                                this->StopAllApplicationsForcefully();
                            else
                                this->on_actionStop_triggered();

                            if(this->ptrobjContextMenu->isVisible())
                                this->ptrobjContextMenu->close();

                            ui->twShowProcess->clearSelection();

                            if(mobj_ProcessLogMap.mobj_ProcessAndLogMapping.contains(ui->twShowProcess->item(i, 8)->text()) == true)
                            {
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.remove(ui->twShowProcess->item(i, 8)->text());
                                mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                            }
                            else
                                this->mobj_ProcessLogMap.mobj_ProcessAndLogMapping.insert(ui->twShowProcess->item(i, 8)->text(), QString(""));
                        }

                        if(ui->twShowProcess->item(i, 0)->text() == "LThistdb.exe")
                        {
                            if(IsServiceRunning(QString("LThistdb.exe")) == false)
                                this->on_actionStopPostgreSQL_DB_Server_triggered();
                        }
                        qszStandardOutput.clear();
                    }
                }
            }
            else
                break;
#ifdef Q_WS_WIN
            cmd.clear();
            qszFilters.clear();
            qszSubFilters.clear();
#endif
        }
    }
    catch(QProcess::ProcessError pError)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Crashed", "Process error returned code: " + QString::number(pError));
    }
    catch(...)
    {
        QMessageBox objCrashExit;
        objCrashExit.information(this, "Unknown Crash", "Unknown crash exit-child process may not be running correctly!");
    }
}


问:
Giving border to
 of table in a table
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

```<code><table>

    <tr>
        <td>A</td>
    </tr>

    <tr>
        <td>
           <table class="t_border">
              <tr>
                 <td>B</td>
              </tr>
        </td>
    </tr>
</tbody>
</code>```

答:
You can't add a border to a
. You would have to add it to the s. Also your t_border table isn't be being closed
 and your outer table should be closed with
 instead of
.

Title: Giving border to <tr> of table in a table

Body:
How do i give a border to the
(t_border).
The inner table shouldnt inherit the style from the outer one

        A

                 B

Body: You can't add a border to a <tr>. You would have to add it to the <td>s. Also your t_border table isn't be being closed </table> and your outer table should be closed with </table> instead of </tbody>.


答: Just giving the border to the tr won't really have an effect. It would be better to give the td's a border top or bottom of what you want it to actually show up. For example, border-bottom:2px solid black;  </p>


问:
Spring, hibernate entity fields depending on profile
i have something like this:

```<code>@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}
</code>```

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

```<code>   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;
</code>```

is something like that possible?

答:
You could do this by creating a custom Hibernate UserType and registering it on your beginTime field via the Hibernate @Type annotation.

In your new UserType, you could then get the current profile from the Spring Environment to determine the target column name. You'll have to statically register the Environment in your application somehow first, as your UserType will have been instantiated by Hibernate and won't know about your Spring application context. All doable though!

Body:
i have something like this:

@Entity
@Table(name = "schedules")
public class ScheduleDO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Long id;

@Column(name = "begin_time", columnDefinition = "TIMESTAMP WITH TIME ZONE",
nullable = false)
private OffsetDateTime beginTime;
}

And i want to be able to change the "beginTime" variable anotation based on active profile. Something like this:

   @Profile("dev")
   @Column(name = "begin_time_dev", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   @Profile("test")
   @Column(name = "begin_time_test", columnDefinition = "TIMESTAMP WITH TIME ZONE",
   nullable = false)
   private OffsetDateTime beginTime;

is something like that possible?


问:
Dynamically add element to map after pattern matching match case
I have a method as follows:

```<code>  protected def extract(implicit params:Params) =
    Map(
  "address" -> params.address,
  "city" -> reconcileCity,
  "region" -> params.region,
)collect {
    case (k, v) if v.isDefined => k -> v.get
  }
</code>```

I want to substitute value of city from another method as follows :

```<code>  protected def reconcileCity(implicit params:Params)
  params.city match {
  case Some("madras") => "Chennai"
  case Some("bangalore") => "Bengaluru"
  case Some("gurgaon") => "Gurugram"
  case _ => params.city.mkString
}
</code>```

But I am getting error like :

```<code>  Error:(177, 24) value isDefined is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
  Error:(177, 44) value get is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
</code>```

Please help.

答:
Agreed on @Alexey's answer that isDefined and get are methods that can be applied to Option class. Alexay suggested to change all the returning values to Some but I suggest to change only the returned value to Some as

```<code>  protected def extract(implicit params:Params) =
    Map(
      "address" -> params.address,
      "city" -> Some(reconcileCity),
      "region" -> params.region
    )collect {
      case (k, v) if v.isDefined => k -> v.get
    }

  protected def reconcileCity(implicit params:Params) = params.city.get match {
    case "madras" | "Madras" => "Chennai"
    case "bangalore" | "Banglore" => "Bengaluru"
    case "gurgaon" | "GurGaon" => "Gurugram"
    case _ => params.city.mkString
  }
</code>```

Body:
I have a method as follows:

  protected def extract(implicit params:Params) =
    Map(
  "address" -> params.address,
  "city" -> reconcileCity,
  "region" -> params.region,
)collect {
    case (k, v) if v.isDefined => k -> v.get
  }

I want to substitute value of city from another method as follows :

  protected def reconcileCity(implicit params:Params)
  params.city match {
  case Some("madras") => "Chennai"
  case Some("bangalore") => "Bengaluru"
  case Some("gurgaon") => "Gurugram"
  case _ => params.city.mkString
}

But I am getting error like :

  Error:(177, 24) value isDefined is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get
  Error:(177, 44) value get is not a member of java.io.Serializable
  case (k, v) if v.isDefined => k -> v.get

Please help.

Body:
Agreed on @Alexey's answer that isDefined and get are methods that can be applied to Option class. Alexay suggested to change all the returning values to Some but I suggest to change only the returned value to Some as

  protected def extract(implicit params:Params) =
    Map(
      "address" -> params.address,
      "city" -> Some(reconcileCity),
      "region" -> params.region
    )collect {
      case (k, v) if v.isDefined => k -> v.get
    }

  protected def reconcileCity(implicit params:Params) = params.city.get match {
    case "madras" | "Madras" => "Chennai"
    case "bangalore" | "Banglore" => "Bengaluru"
    case "gurgaon" | "GurGaon" => "Gurugram"
    case _ => params.city.mkString
  }


问:
Vectorize Pandas Dataframe into Numpy Array
I have a problem where I need to convert a pandas dataframe into an array of list of lists.

Sample:

```<code>import pandas as pd
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])
</code>```

I know there is the as_matrix() function which returns below:

```<code>df.as_matrix():
# result:array([[1, 2, 3],
                [2, 2, 4],
                [3, 2, 4]])
</code>```

However, I require something in this format

```<code>  [array([[1], [2], [3]]),
   array([[2], [2], [4]],
   array([[3], [2], [4]])]
</code>```

IE. I need a list of arrays containing list of lists where the inner most list contains a single element and the outer most list in the array represents the row of the dataframe. The effect of this is that it basically vectorizes each row of the dataframe into a vector of dimension 3.

This is useful especially when I need to do matrix / vector operations in numpy and currently the data source I have is in .csv format and I am struggling to find a way to convert a dataframe into a vector.

答:
First convert your DataFrame to a matrix. Then add a dimension and convert it to a list.

Try:

```<code>df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])
my_matrix = df.as_matrix()
my_list_of_arrays_of_list_lists = list(np.expand_dims(my_matrix, axis=2))
</code>```

my_list_of_arrays_of_list_lists represents what you are looking for and gives you:

```<code>Out[42]: [array([[1],[2],[3]]),
          array([[2],[2],[4]]),
          array([[3],[2],[4]])]
</code>```

Body:
I have a problem where I need to convert a pandas dataframe into an array of list of lists.

Sample:

import pandas as pd
df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])

I know there is the as_matrix() function which returns below:

df.as_matrix():
# result:array([[1, 2, 3],
                [2, 2, 4],
                [3, 2, 4]])

However, I require something in this format

  [array([[1], [2], [3]]),
   array([[2], [2], [4]],
   array([[3], [2], [4]])]

IE. I need a list of arrays containing list of lists where the inner most list contains a single element and the outer most list in the array represents the row of the dataframe. The effect of this is that it basically vectorizes each row of the dataframe into a vector of dimension 3.

This is useful especially when I need to do matrix / vector operations in numpy and currently the data source I have is in .csv format and I am struggling to find a way to convert a dataframe into a vector.

Body:
First convert your DataFrame to a matrix. Then add a dimension and convert it to a list.

Try:

df = pd.DataFrame([[1,2,3],[2,2,4],[3,2,4]])
my_matrix = df.as_matrix()
my_list_of_arrays_of_list_lists = list(np.expand_dims(my_matrix, axis=2))

my_list_of_arrays_of_list_lists represents what you are looking for and gives you:

Out[42]: [array([[1],[2],[3]]),
          array([[2],[2],[4]]),
          array([[3],[2],[4]])]


问:
thumbnail over the youtubeVideoplayer in xml of android studio?
How to put thumbnail over the youtubeVideoplayer in Layout-xml file of android studio 2.3.2, As I am able to play the youtube video in my app but I want to show the thumbnail of that video before playing video so that it look nice.</p>

答:
you need to get the video's thumbnail seperately

You can get a thumbnail of your YouTube video using this link by replacing VIDEO_ID with your own video's ID.

Show this thumbnail before user plays the video


问:
Deleting duplicate data in one of three column in Excel
I tried to use some functions that I found whilst searching to solve my problem, they are slightly modified it to remove duplicate data in a field.
File

Rather than a count of 4, I would like the count of 2 from column J. The information below are my attempts for 4 different sections on the attached document as I always thought the next one would give me the result that I wanted.

H  ====I==========J

  P13C   Body Exterior   4943

P13C   Body Exterior   4943

P13C   Body Exterior   5122

P13C   Body Exterior   5122

=IFERROR(INDEX($K$7:$K$142,MATCH(0,COUNTIFS($H$7:$H$142,B14,$K$7:$K$142,$E$14),0)),"")

as does this

=IFERROR(INDEX($J$7:$J$142,MATCH(,IF(H$7:H$142="P13C",COUNTIF(I7:I142,$J$7:$J$142)),)),"")

and this

=IFERROR(INDEX($K$7:$K$142,MATCH(0,COUNTIF($H$7:$H$142,$K$7:$K$142),0)),"")

This, gives me a 0

=IF($J$7:$J$142>1,IF($K$7:$K$142="20",SUM(IF(FREQUENCY($H$7:$H$142,$H$7:$H$142)>1,1))))

This gives me a DIV error

=SUMPRODUCT(((H7:H142="P13C")*(I7:I142="Body Exterior"))/(COUNTIFS(J7:J142, J7:J142, H7:H142, "P13C", I7:I142,"Body Exterior")+((H7:H142<>"P13C")+(I7:I142="Body Exterior"))))

There are duplicates in $J$7:$J$142, but I only want the one count.

答:
Sort the column J in smallest to largest order

concatenate all three values by using '&' on next column K ---> H&I&J

then use IF and COUNTIF formula on next column L,

Column L:

```<code>=IF(K1=K2,COUNTIF(K1,K1:K142),"")
</code>```

this a easy method to get count 1 for J column

Body:
Sort the column J in smallest to largest order

concatenate all three values by using '&' on next column K ---> H&I&J

then use IF and COUNTIF formula on next column L,

Column L:

=IF(K1=K2,COUNTIF(K1,K1:K142),"")

this a easy method to get count 1 for J column


问:
how to compare a password in symfony2 with fosuserbundle?
this is my fuction code but iam get this error  Call to a member function get() on null. so help me please</p>

```<code>public function verificarSenhaDefaultAction() {
        $a = "12345678";
        $default = $this->get('security.password_encoder')->encodePassword($this->getUser(), $a);

        if ($this->getUser()->getPassword() == $default):
            return TRUE;
        else:
            Return FALSE;
        endif;
    }
</code>```

答:
You need to call get function from the container like this:</p>

```<code>$this->container->get('security.password_encoder')->encodePassword($this->getUser(), $a);
</code>```

Body:
this is my fuction code but iam get this error  Call to a member function get() on null. so help me please

public function verificarSenhaDefaultAction() {
        $a = "12345678";
        $default = $this->get('security.password_encoder')->encodePassword($this->getUser(), $a);

        if ($this->getUser()->getPassword() == $default):
            return TRUE;
        else:
            Return FALSE;
        endif;
    }

Body:
You need to call get function from the container like this:

$this->container->get('security.password_encoder')->encodePassword($this->getUser(), $a);


问:
How to plotted graph save as a JPEG image in C#
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

```<code> private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }
</code>```

This is my part of .csv file data as follows;

```<code>Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE
</code>```

答:
Have you tried using SaveImage method on chart control?

```<code>  public class Chart : Control, ISupportInitialize, IDisposable
  {

   /// <summary>Saves an image to the specified file.</summary>
   /// <param name="imageFileName">The name of the file in which image is saved to.</param>
   /// <param name="format">The image format.</param>
   public void SaveImage(string imageFileName, ImageFormat format)
</code>```

Sample usage

```<code>speedChart.SaveImage("speedChart", ImageFormat.Jpeg);
</code>```

Body:
I want to save  my plotted graph as a JPEG image by clicking save button.Please give me to help for solving this.this is my plotted grapg look like.

This is code that I used to plotted the graph.

 private void Output_Load(object sender, EventArgs e)
        {

            List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV

            // Loops through each lines in the CSV
            foreach (string line in System.IO.File.ReadAllLines(pathToCsv).Skip(1)) // .Skip(1) is for skipping header
            {
                // here line stands for each line in the csv file

                string[] InCsvLine = line.Split(',');

                // creating an object of type Graph based on the each csv line

                Graph Inst1 = new Graph();

                Inst1.AvI = double.Parse(InCsvLine[1]);
                Inst1.AvE = double.Parse(InCsvLine[2]);

                chart1.Series["Speed"].YAxisType = AxisType.Primary;
                chart1.Series["Speed"].Points.AddXY(Inst1.Date.AvI, Inst1.AvE);
                chart1.Series["Speed"].ChartType = SeriesChartType.FastLine;

            }
        }

This is my part of .csv file data as follows;

Name,AvI,AvE,Test
Amal,3.28000,100,TRUE
Kamal,3.30000,150,FALSE
Ann,3.32000,200,FALSE
Jery,3.34000,220,FALSE
TaW,3.39000,130,FALSE
Nane,3.40000,125,TRUE
Petter,3.42000,300,TRUE
Sam,3.46000,265,TRUE
Daniyel,3.50000,245,TRUE
Don,3.62000,146,FALSE
Zip,3.64000,201,FALSE
Sera,3.68000,300,FALSE
Perera,3.70000,200,TRUE
Dam,3.90000,170,TRUE

Body:
Have you tried using SaveImage method on chart control?

  public class Chart : Control, ISupportInitialize, IDisposable
  {

   /// <summary>Saves an image to the specified file.</summary>
   /// <param name="imageFileName">The name of the file in which image is saved to.</param>
   /// <param name="format">The image format.</param>
   public void SaveImage(string imageFileName, ImageFormat format)

Sample usage

speedChart.SaveImage("speedChart", ImageFormat.Jpeg);


问:
ERROR(UNITY 4.6):"Couldn't read a file://file"
I have installed unity 4.6 but as soon as it finished and I tried to run it, it gives an error, "Couldn't read a file://file" (see the screenshot) and I am not able to run it on my PC. I've also tried to install a different version but they all are giving me the same error message.

答:
Try to delete all Unity files from your computer, than instal Unity 5 from [https://store.unity.com/?_ga=2.113035399.2020539281.1496751500-317263663.1476714068][1]
If you are gonna use Unity 5, if you will not still you can try for is it because your computer or just a temporary bug.

Than install Unity as administrator, read installation process carefull and start as administrator.

I hope that will solve your problem, have a nice day :)


问:
How to inject different service based on certain build environment in Angular2?
I have HeroMockService that will return mocked data and HeroService that will call back end service to retrieve heroes from database.

Assuming Angular2 has build environment, I'm planning to inject HeroMockService to AppComponent if current build environment is "dev-mock".  If current build environment is "dev-rest", HeroService should be injected to AppComponent instead.

I would like to know how can I achieve this?

答:
See below my solution is based on @peeskillet one.

Create an interface that both the mock and real service implement, for your example IHeroService.

```<code>export interface IHeroService {
    getHeroes();
}

export class HeroService implements IHeroService {
    getHeroes() {
    //Implementation goes here
    }
}

export class HeroMockService implements IHeroService {
    getHeroes() {
    //Mock implementation goes here
}
</code>```

Assuming you've created the Angular app using Angular-CLI, in your environment.ts file add the appropriate implementation, e.g.:

```<code>import { HeroService } from '../app/hero.service';

export const environment = {
  production: false,
  heroService: HeroService
};
</code>```

For every different environment.(prod|whatever).ts you have to define a heroService pointing to the implementation and add the import.

Now, say you want to import the service in the AppModule class (you can do it on the component where you need the service as well)

```<code>@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    FormsModule,
    HttpModule,
    AlertModule.forRoot()
  ],
  providers: [
    {
      provide: 'IHeroService',
      useClass: environment.heroService
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

The important part is the provider:

```<code>  providers: [
    {
      provide: 'IHeroService',
      useClass: environment.heroService
    }
</code>```

Now wherever you want to use the service you have to do the following:

```<code>import { IHeroService } from './../hero.service';

export class HeroComponent {

constructor(@Inject('IHeroService') private heroService: IHeroService) {}
</code>```

Sources:
Is it possible to inject interface with angular2?
https://medium.com/beautiful-angular/angular-2-and-environment-variables-59c57ba643be
http://tattoocoder.com/angular-cli-using-the-environment-option/

Body:
See below my solution is based on @peeskillet one.

Create an interface that both the mock and real service implement, for your example IHeroService.

export interface IHeroService {
    getHeroes();
}

export class HeroService implements IHeroService {
    getHeroes() {
    //Implementation goes here
    }
}

export class HeroMockService implements IHeroService {
    getHeroes() {
    //Mock implementation goes here
}

Assuming you've created the Angular app using Angular-CLI, in your environment.ts file add the appropriate implementation, e.g.:

import { HeroService } from '../app/hero.service';

export const environment = {
  production: false,
  heroService: HeroService
};

For every different environment.(prod|whatever).ts you have to define a heroService pointing to the implementation and add the import.

Now, say you want to import the service in the AppModule class (you can do it on the component where you need the service as well)

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    FormsModule,
    HttpModule,
    AlertModule.forRoot()
  ],
  providers: [
    {
      provide: 'IHeroService',
      useClass: environment.heroService
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

The important part is the provider:

  providers: [
    {
      provide: 'IHeroService',
      useClass: environment.heroService
    }

Now wherever you want to use the service you have to do the following:

import { IHeroService } from './../hero.service';

export class HeroComponent {

constructor(@Inject('IHeroService') private heroService: IHeroService) {}

Sources:
Is it possible to inject interface with angular2?
https://medium.com/beautiful-angular/angular-2-and-environment-variables-59c57ba643be
http://tattoocoder.com/angular-cli-using-the-environment-option/


问:
Why does C# disallow readonly local variables?
Having a friendly debate with a co-worker about this.  We have some thoughts about this, but wondering what the SO crowd thinks about this?</p>

答:
Addressing Jared's answer, it would probably just have to be a compile-time feature - the compiler would prohibit you from writing to the variable after the initial declaration (which would have to include an assignment).

Can I see value in this? Potentially - but not a lot, to be honest. If you can't easily tell whether or not a variable is going to be assigned elsewhere in the method, then your method is too long.

For what it's worth, Java has this feature (using the final modifier) and I've very rarely seen it used other than in cases where it has to be used to allow the variable to be captured by an anonymous inner class - and where it is used, it gives me an impression of clutter rather than useful information.

OwnerDisplayName: Brian Genisio

OwnerDisplayName: Jon Skeet


问:
What is the role of Logstash Shipper and Logstash Indexer in ELK stack?
I have been studying online about ELK stack for my new project.

Although most of the tech blogs are about how to set ELK up.

Although I need more information to begin with.

What is Logstash ? Further, Logstash Shipper and Indexer.

What is Elasticsearch's role ?

Any leads will be appreciated too if not a proper answer.

答:
I will try to explain the elk stack to you with an example.

Applications generate logs which all have the same format ( timestamp | loglevel | message ) on any machine in our cluster and write those logs to some file.

Filebeat (a logshipper from elk) tracks that file, gathers any updates to the file periodically and forwards them to logstash over the network. Unlike logstash Filebeat is a lightweight application that uses very little resources so I don't mind running it on every machine in the cluster. It notices when logstash is down and waits with tranferring data until logstash is running again (no logs are lost).

Logstash receives messages from all log shippers through the network and applies filters to the messages. In our case it splits up each entry into timestamp, loglevel and message. These are separate fields and can later be searched easily. Any messages that do not conform to that format will get a field: invalid logformat. These messages with fields are now forwarded to elastic search in a speed that elastic search can handle.

Elastic search stores all messages and indexes ( prepares for quick search) all the fields im the messages. It is our database.

We then use Kibana (also from elk) as a gui for accessing the logs. In kibana I can do something like: show me all logs from between 3-5 pm today with loglevel error whose message contains MyClass. Kibana will ask elasticsearch for the results and display them


问:
How can i generate child model in mongoose
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));
</code>```

An example for a child is TwitterBrick.
for now it is:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));
</code>```

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven

答:
Just add the Brick model as an attribute (composition).
It will compensate for that.
Or just rely on exisiting mongoose plugins for that https://github.com/briankircho/mongoose-schema-extend
check this one out.</p>

Body:
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));

An example for a child is TwitterBrick.
for now it is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven


问:
BrowserStack + Nightwatch.js How to set up proxy which is password protected (ERROR: httpProxy was not of the form host[:port]
BrowserStack + Nightwatch.js How to set up proxy which is password protected

```<code>  common_capabilities: {
    'browserstack.user': 'user',
    'browserstack.key': 'key',
    'browserstack.debug': true,
},
test_settings: {
    default: {
        desiredCapabilities: {
            'os': 'OS X',
            'os_version': 'Sierra',
            'browser': 'Firefox',
            'browser_version': '53.0',
            'resolution': '1280x960',
            "acceptSslCerts": 'false',
            'proxy': {
                'httpProxy': 'user:password@server:80',
                'protocol': 'http',
                'proxyType': 'manual',
                //'httpProxy': 'server:80',
                //'user': 'user',
                //'pass': 'password'
            }
        },
</code>```

I have en ERROR:

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?

message: 'Could not start Browser / Emulator

Reason:  httpProxy was not of the form host[:port]

答:
I found the better solution, using nightwatch-browserstack
and customize local.runner.js:</p>

```<code>#!/usr/bin/env node
process.env.NODE_ENV = 'testing';

const access = require('../conf/browserStackAccess.js').access; //{'USERNAME':'', 'ACCESS_KEY': ''}

const bsLocalOptions = {
  'key': access.ACCESS_KEY,
  'local-proxy-host': PROXY_HOST,
  'local-proxy-port': PROXY_PORT,
  'local-proxy-user': PROXY_USER,
  'local-proxy-pass': ROXY_PASS,
  'local-identifier': LOCAL_ID //'Test123'
}

var Nightwatch = require('nightwatch');
var browserstack = require('browserstack-local');
var bs_local;

try {

  process.mainModule.filename = "./node_modules/nightwatch/bin/nightwatch"
  // Code to start browserstack local before start of test
  console.log("Connecting local");

  Nightwatch.bs_local = bs_local = new browserstack.Local();

  bs_local.start(bsLocalOptions, function (error) {
    if (error) throw error;

    console.log('Connected. Now testing...');
    Nightwatch.cli(function (argv) {
      Nightwatch.CliRunner(argv)
        .setup(null, function () {
          // Code to stop browserstack local after end of parallel test
          bs_local.stop(function () { });
        })
        .runTests(function () {
          // Code to stop browserstack local after end of single test
          bs_local.stop(function () { });
        });
    });
  });
} catch (ex) {
  console.log('There was an error while starting the test runner:\n\n');
  process.stderr.write(ex.stack + '\n');
  process.exit(2);
}
</code>```

Body:
BrowserStack + Nightwatch.js How to set up proxy which is password protected

  common_capabilities: {
    'browserstack.user': 'user',
    'browserstack.key': 'key',
    'browserstack.debug': true,
},
test_settings: {
    default: {
        desiredCapabilities: {
            'os': 'OS X',
            'os_version': 'Sierra',
            'browser': 'Firefox',
            'browser_version': '53.0',
            'resolution': '1280x960',
            "acceptSslCerts": 'false',
            'proxy': {
                'httpProxy': 'user:password@server:80',
                'protocol': 'http',
                'proxyType': 'manual',
                //'httpProxy': 'server:80',
                //'user': 'user',
                //'pass': 'password'
            }
        },

I have en ERROR:

Error retrieving a new session from the selenium server

Connection refused! Is selenium server started?

message: 'Could not start Browser / Emulator

Reason:  httpProxy was not of the form host[:port]

Body:
I found the better solution, using nightwatch-browserstack
and customize local.runner.js:

#!/usr/bin/env node
process.env.NODE_ENV = 'testing';

const access = require('../conf/browserStackAccess.js').access; //{'USERNAME':'', 'ACCESS_KEY': ''}

const bsLocalOptions = {
  'key': access.ACCESS_KEY,
  'local-proxy-host': PROXY_HOST,
  'local-proxy-port': PROXY_PORT,
  'local-proxy-user': PROXY_USER,
  'local-proxy-pass': ROXY_PASS,
  'local-identifier': LOCAL_ID //'Test123'
}

var Nightwatch = require('nightwatch');
var browserstack = require('browserstack-local');
var bs_local;

try {

  process.mainModule.filename = "./node_modules/nightwatch/bin/nightwatch"
  // Code to start browserstack local before start of test
  console.log("Connecting local");

  Nightwatch.bs_local = bs_local = new browserstack.Local();

  bs_local.start(bsLocalOptions, function (error) {
    if (error) throw error;

    console.log('Connected. Now testing...');
    Nightwatch.cli(function (argv) {
      Nightwatch.CliRunner(argv)
        .setup(null, function () {
          // Code to stop browserstack local after end of parallel test
          bs_local.stop(function () { });
        })
        .runTests(function () {
          // Code to stop browserstack local after end of single test
          bs_local.stop(function () { });
        });
    });
  });
} catch (ex) {
  console.log('There was an error while starting the test runner:\n\n');
  process.stderr.write(ex.stack + '\n');
  process.exit(2);
}


问:
How to handle new fields with jquery that have array
I have for example 3 fields that user can input a number a,b,c

So field C will check if number entered in field C is  b.

In the form i have a button that create an additional line with
another a,b,c; so i don't know how to control same operation like before...

FIDDLE

```<code>$(".c").change(function() {

  if ($('.c').val() > $('.a').val() || $('.c').val() < $('.b').val()) {
    $('.c').css("backgroundColor", "#ff0000");
  } else {
    $('.c').css("backgroundColor", "#00FF00");
  }
});

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

  var tr = '<tr>' + '<td>Cota1</td>' +
    '<td><input type="text" name="tol_cota1[]" class="form-control a"></td>' +
    '<td><input type="text" name="tolb_cota1[]" class="form-control b"></td>' +
    '<td><input type="text" name="medido_cota1[]" class="form-control c"></td>' +
    '<td><input type="button"  class="btn btn-danger remove" value="Remove Line"></td>' + '</tr>';

  $('.details').append(tr);

});

// delete row
$('.details').delegate('.remove', 'click', function() {
  var con = confirm("Are you sure you want to remove the line?");
  if (con) {
    $(this).parent().parent().remove();
  }
});
</code>```

答:
the best way would be using the closest function</p>

```<code>$(".c").change(function(){

        if($(this).val() > $(this).closest('.a').val() || $(this).closest('.c').val() < $('.b').val())
                {
         $(this).closest('.c').css( "backgroundColor", "#ff0000" );
                }else{
                $(this).closest('.c').css( "backgroundColor", "#00FF00" );
                }
        });
</code>```

Body:
I have for example 3 fields that user can input a number a,b,c

So field C will check if number entered in field C is  b.

In the form i have a button that create an additional line with
another a,b,c; so i don't know how to control same operation like before...

FIDDLE

$(".c").change(function() {

  if ($('.c').val() > $('.a').val() || $('.c').val() < $('.b').val()) {
    $('.c').css("backgroundColor", "#ff0000");
  } else {
    $('.c').css("backgroundColor", "#00FF00");
  }
});

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

  var tr = '
' + 'Cota1	' +
    '<input type="text" name="tol_cota1[]" class="form-control a">	' +
    '<input type="text" name="tolb_cota1[]" class="form-control b">	' +
    '<input type="text" name="medido_cota1[]" class="form-control c">	' +
    '<input type="button"  class="btn btn-danger remove" value="Remove Line">	' + '
';

  $('.details').append(tr);

});

// delete row
$('.details').delegate('.remove', 'click', function() {
  var con = confirm("Are you sure you want to remove the line?");
  if (con) {
    $(this).parent().parent().remove();
  }
});

Body:
the best way would be using the closest function

$(".c").change(function(){

        if($(this).val() > $(this).closest('.a').val() || $(this).closest('.c').val() < $('.b').val())
                {
         $(this).closest('.c').css( "backgroundColor", "#ff0000" );
                }else{
                $(this).closest('.c').css( "backgroundColor", "#00FF00" );
                }
        });


问:
zxing - export PNG barcode with encoded value
Using zxing, I managed to save a Code39 barcode as PNG but it does display only the bars, no numbers. How could I have the barcode and number in a single PNG?

KI

答:
You cannot add the numbers using zxing. You could do something like adding the text yourself to the image, but this might not work flawlessly in all cases without fiddling.

```<code>public static void main(String[] args) throws Exception {
    final BufferedImage image = ...

    Graphics g = image.getGraphics();
    g.setFont(g.getFont().deriveFont(20f)); // select compatible font
    g.drawString("numbers", 100, 100); // center on your image using image size
    g.dispose();

    ImageIO.write(image, "png", new File("barcode.png"));
}
</code>```

Alternatively, you could organize all this in a JPanel and then render the panel to image. This would allow you to benefit from layout orientations and fittings.
Using something like this.

Body:
You cannot add the numbers using zxing. You could do something like adding the text yourself to the image, but this might not work flawlessly in all cases without fiddling.

public static void main(String[] args) throws Exception {
    final BufferedImage image = ...

    Graphics g = image.getGraphics();
    g.setFont(g.getFont().deriveFont(20f)); // select compatible font
    g.drawString("numbers", 100, 100); // center on your image using image size
    g.dispose();

    ImageIO.write(image, "png", new File("barcode.png"));
}

Alternatively, you could organize all this in a JPanel and then render the panel to image. This would allow you to benefit from layout orientations and fittings.
Using something like this.