问:
MongoDB's $graphLookup trying to get a tree structure
I'm trying to work with the new MongoDB v3.4 $graphLookup aggregation pipeline. I have this simple tree collection, with some nodes and a parent DBRef:

```<code>{ "_id" : ObjectId("59380657bbdbfb36c18a80f2"), "name" : "Root node 1" },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("59380657bbdbfb36c18a80f3"), "name" : "Root node 2" }
</code>```

I would like to get this kind of tree structure:

```<code>- Root node 1
    - Child 1.1
        - Subchild 1.1.1
    - Child 1.2
- Root node 2
</code>```

So, I'm trying to work with the new $graphLookup aggregation pipeline, like this:

```<code>db.getCollection('tree').aggregate([
    { $match: { parent: { $exists: false } } },
    {
        $graphLookup: {
            from: "tree",
            startWith: "$_id",
            connectFromField: "_id",
            connectToField: "parent",
            as: "children"
        }
   },
   { $sort: { name: 1 } }
])
</code>```

But my issue is that I get all child of "Root node 1" in one collection:

```<code>{
    "_id" : ObjectId("59380657bbdbfb36c18a80f2"),
    "name" : "Root node 1",
    "children" : [
        { "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
        { "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
        { "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") }
    ]
},
{
    "_id" : ObjectId("59380657bbdbfb36c18a80f3"),
    "name" : "Root node 2",
    "children" : [ ]
}
</code>```

I have no idea how to lookup children recursively to get "Subchild 1.1.1" in the children collection of "Child 1.1".
I'm looking for any suggestions. Thanks :)

答:
$graphLookup is not producing the hierarchy of dependencies - it performs a recursive search of connected documents, but results are flattened into the single-dimension array. Here is the quote from the documentation:

For each matching document, $graphLookup takes the value of the
  _id and checks every document in the tree collection for
  a matching parent value. For each match, $graphLookup adds the
  matching document in the from collection to an array children. This step continues recursively until no more
  matching documents are found, or until the operation reaches a
  recursion depth specified by the maxDepth parameter.

I.e. it searches for dependent documents recursively, but each found document is added to same children array of the parent document no matter how 'deep' the child is located.

Note - you don't see Child 1.1 with its connected Subchild 1.1.1 because you are filtering out these documents in match stage:

```<code>{ $match: { parent: { $exists: false } } }
</code>```

that selects only documents which don't have a parent - "Root node 1" and "Root node 2". If you will remove this filter, then all other documents with the hierarchy of their dependants will be returned:

```<code>{
    "name" : "Child 1.1",
    "children" : [
        { "name" : "Subchild 1.1.1" }
    ]
},
{
    "name" : "Child 1.2"
    "children" : []
},
{
    "name" : "Root node 1",
    "children" : [
        { "name" : "Subchild 1.1.1" },
        { "name" : "Child 1.2" },
        { "name" : "Child 1.1" }
    ]
},
{
    "name" : "Root node 2",
    "children" : []
},
{
    "name" : "Subchild 1.1.1"
    "children" : []
}
</code>```

If you don't want to mix children from different 'depth' of tree in single children array, then take a look at interesting comment in documentation

Setting the maxDepth field to 0 is equivalent to a non-recursive
  $lookup search stage.

It means that each document will get all its direct children into the children array, and after that lookup will stop without any further recursive search. Output will be

```<code>{
    "name" : "Child 1.1",
    "children" : [
        { "name" : "Subchild 1.1.1" }
    ]
},
{
    "name" : "Child 1.2"
    "children" : []
},
{
    "name" : "Root node 1",
    "children" : [
        { "name" : "Child 1.2" },
        { "name" : "Child 1.1" }
    ]
},
{
    "name" : "Root node 2",
    "children" : []
},
{
    "name" : "Subchild 1.1.1"
    "children" : []
}
</code>```

Body:
I'm trying to work with the new MongoDB v3.4 $graphLookup aggregation pipeline. I have this simple tree collection, with some nodes and a parent DBRef:

{ "_id" : ObjectId("59380657bbdbfb36c18a80f2"), "name" : "Root node 1" },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
{ "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
{ "_id" : ObjectId("59380657bbdbfb36c18a80f3"), "name" : "Root node 2" }

I would like to get this kind of tree structure:

- Root node 1
    - Child 1.1
        - Subchild 1.1.1
    - Child 1.2
- Root node 2

So, I'm trying to work with the new $graphLookup aggregation pipeline, like this:

db.getCollection('tree').aggregate([
    { $match: { parent: { $exists: false } } },
    {
        $graphLookup: {
            from: "tree",
            startWith: "$_id",
            connectFromField: "_id",
            connectToField: "parent",
            as: "children"
        }
   },
   { $sort: { name: 1 } }
])

But my issue is that I get all child of "Root node 1" in one collection:

{
    "_id" : ObjectId("59380657bbdbfb36c18a80f2"),
    "name" : "Root node 1",
    "children" : [
        { "_id" : ObjectId("593806b0bbdbfb36c18a80f7"), "name" : "Subchild 1.1.1", "parent" : ObjectId("5938068abbdbfb36c18a80f5") },
        { "_id" : ObjectId("5938068abbdbfb36c18a80f6"), "name" : "Child 1.2", "parent" : ObjectId("59380657bbdbfb36c18a80f2") },
        { "_id" : ObjectId("5938068abbdbfb36c18a80f5"), "name" : "Child 1.1", "parent" : ObjectId("59380657bbdbfb36c18a80f2") }
    ]
},
{
    "_id" : ObjectId("59380657bbdbfb36c18a80f3"),
    "name" : "Root node 2",
    "children" : [ ]
}

I have no idea how to lookup children recursively to get "Subchild 1.1.1" in the children collection of "Child 1.1".
I'm looking for any suggestions. Thanks :)

Body:
$graphLookup is not producing the hierarchy of dependencies - it performs a recursive search of connected documents, but results are flattened into the single-dimension array. Here is the quote from the documentation:

For each matching document, $graphLookup takes the value of the
  _id and checks every document in the tree collection for
  a matching parent value. For each match, $graphLookup adds the
  matching document in the from collection to an array children. This step continues recursively until no more
  matching documents are found, or until the operation reaches a
  recursion depth specified by the maxDepth parameter.

I.e. it searches for dependent documents recursively, but each found document is added to same children array of the parent document no matter how 'deep' the child is located.

Note - you don't see Child 1.1 with its connected Subchild 1.1.1 because you are filtering out these documents in match stage:

{ $match: { parent: { $exists: false } } }

that selects only documents which don't have a parent - "Root node 1" and "Root node 2". If you will remove this filter, then all other documents with the hierarchy of their dependants will be returned:

{
    "name" : "Child 1.1",
    "children" : [
        { "name" : "Subchild 1.1.1" }
    ]
},
{
    "name" : "Child 1.2"
    "children" : []
},
{
    "name" : "Root node 1",
    "children" : [
        { "name" : "Subchild 1.1.1" },
        { "name" : "Child 1.2" },
        { "name" : "Child 1.1" }
    ]
},
{
    "name" : "Root node 2",
    "children" : []
},
{
    "name" : "Subchild 1.1.1"
    "children" : []
}

If you don't want to mix children from different 'depth' of tree in single children array, then take a look at interesting comment in documentation

Setting the maxDepth field to 0 is equivalent to a non-recursive
  $lookup search stage.

It means that each document will get all its direct children into the children array, and after that lookup will stop without any further recursive search. Output will be

{
    "name" : "Child 1.1",
    "children" : [
        { "name" : "Subchild 1.1.1" }
    ]
},
{
    "name" : "Child 1.2"
    "children" : []
},
{
    "name" : "Root node 1",
    "children" : [
        { "name" : "Child 1.2" },
        { "name" : "Child 1.1" }
    ]
},
{
    "name" : "Root node 2",
    "children" : []
},
{
    "name" : "Subchild 1.1.1"
    "children" : []
}


来源: stackexchange

问:
How to notificate user by e-mail after permission granted
How can I to notificate user by email(do as google-analytics does from web-application), that I granted permissions.
I use this method.
There is my request:

```<code>var request = gapi.client.analytics.management.accountUserLinks.insert(
        {
          'accountId': accountId,
          'resource': {
            'permissions': {
              'local': [
                'EDIT',
                'COLLABORATE',
                'READ_AND_ANALYZE'
              ]
            },
            'userRef': {
              'email': email
            }
          }
        });
</code>```

Thanks.

答:
```<code>MailApp.sendEmail(email,
    "notifications@example.com",
    "Permission granted",
    "You have new permissions granted: Edit, Collaborate, Read&Analyse");
</code>```

Look: How to send structured email markup using Gmail API and Javascript?

ContentLicense: CC BY-SA 3.0

Body:
How can I to notificate user by email(do as google-analytics does from web-application), that I granted permissions.
I use this method.
There is my request:

var request = gapi.client.analytics.management.accountUserLinks.insert(
        {
          'accountId': accountId,
          'resource': {
            'permissions': {
              'local': [
                'EDIT',
                'COLLABORATE',
                'READ_AND_ANALYZE'
              ]
            },
            'userRef': {
              'email': email
            }
          }
        });

Thanks.

Body:
MailApp.sendEmail(email,
    "notifications@example.com",
    "Permission granted",
    "You have new permissions granted: Edit, Collaborate, Read&Analyse");

Look: How to send structured email markup using Gmail API and Javascript?


问:
How to set autofocus in angular or angular 2 not angularjs
I see many posts in how to set autofocus on an input filed in angularjs by creating a directive or HTML autofocus, Is there a quick and easy way to set focus in angular (angular 2, angular 4 etc)</p>

答:
Aniruddha Das' answer works well in some cases.  However, if this is applied to a template-based form with required validation, you may get the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after >it was checked. Previous value: 'false'. Current value: 'true'.

One solution to this is wrapping the focus() call within ngInit() instead of ngAfterViewInit().  So, extending upon Aniduddha's answer:

In your html add the #namedReference to the component:

```<code><input type="text"
    placeholder="Your full name"
    name="name"
    ngModel
    #fullName="ngModel"
    required
    #nameit>
</code>```

Then use onNgInit() to apply auto focus into it:

```<code>@ViewChild('nameit') private elementRef: ElementRef;

ngOnInit() {
    this.elementRef.nativeElement.focus();
}
</code>```

Body:
Aniruddha Das' answer works well in some cases.  However, if this is applied to a template-based form with required validation, you may get the following error:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after >it was checked. Previous value: 'false'. Current value: 'true'.

One solution to this is wrapping the focus() call within ngInit() instead of ngAfterViewInit().  So, extending upon Aniduddha's answer:

In your html add the #namedReference to the component:

<input type="text"
    placeholder="Your full name"
    name="name"
    ngModel
    #fullName="ngModel"
    required
    #nameit>

Then use onNgInit() to apply auto focus into it:

@ViewChild('nameit') private elementRef: ElementRef;

ngOnInit() {
    this.elementRef.nativeElement.focus();
}


问:
Change Variable through Class Operating on DataFrame?
I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:</p>

```<code>import pandas as pd
from __future__ import division
import numpy as np

    df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
 "B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
 "C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.initial_value = self.initial_value + self.B

        return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()

print x
</code>```

答:
This will work:

```<code>def test_values(self):
    self.inital_value += sum(self.B*self.C)
    return self.initial_value
</code>```

Just sum over the product of C and B:

```<code>import pandas as pd
from __future__ import division
import numpy as np

df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
"B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
"C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.inital_value += sum(self.B*self.C)
        return self.initial_value

x = test(A, B, C, initial_value)
print(x.test_values())
</code>```

Body:
I have a variable initial_value, equal to 1000, that I would like to sum to values on Column B. initial_value and Column B will only be summed when Column C is equal to 1 and not 0. Therefore, the resulting initial value after the Class operation should be 1030 (or 1000 + 10 - 30 + 70 + 10). So far I have tried:

import pandas as pd
from __future__ import division
import numpy as np

    df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
 "B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
 "C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.initial_value = self.initial_value + self.B

        return self.initial_value

x = test(A, B, C, initial_value)
x.test_values()

print x

Body:
This will work:

def test_values(self):
    self.inital_value += sum(self.B*self.C)
    return self.initial_value

Just sum over the product of C and B:

import pandas as pd
from __future__ import division
import numpy as np

df = pd.DataFrame({"A":[40,50,60,70,20,30,40,10,10,80,60,40,50],\
"B":[0,10,10,10,-50,10,10,-30,0,70,-20,-20,10], \
"C":[0,0,0,1,0,0,0,1,0,1,0,0,1]})

A = df['A']
B = df['B']
C = df['C']

initial_value = 1000.00

class test:
    def __init__(self, A, B, C, initial_value):
        self.A = A
        self.B = B
        self.C = C
        self.initial_value = initial_value

    def test_values(self):
        self.inital_value += sum(self.B*self.C)
        return self.initial_value

x = test(A, B, C, initial_value)
print(x.test_values())


问:
makefile target dependencies dependent on target name
I have the following rule:

```<code>SPECIAL = file1 file2

%.o : %.cpp a.h
    $(CC) -c $(CFLAGS) $< -o $@
</code>```

I would like that if % is in $(SPECIAL), then b.h is added to the list of dependencies.

Is there a way to do it, without repeating the rule?

答:
You can assign additional dependencies separately. Just add a line at the end:

```<code>$(addsuffix .o,${SPECIAL}): b.h
</code>```

To not have to deal with dependency order, replace $< in the rule with $(filter %.cpp,$^). This way %.cpp does not have to be the first dependency.

Ideally, you want the header dependencies to be generated automatically to avoid specifying them manually.

The most simple automatic dependency generation:

```<code>%.o : %.cpp
    $(CXX) -c -o $@ -MD -MP $(CXXFLAGS) $(filter %.cpp,$^)

ifneq ($(MAKECMDGOALS),clean)
-include $(wildcard *.d)
endif
</code>```

Body:
I have the following rule:

SPECIAL = file1 file2

%.o : %.cpp a.h
    $(CC) -c $(CFLAGS) $< -o $@

I would like that if % is in $(SPECIAL), then b.h is added to the list of dependencies.

Is there a way to do it, without repeating the rule?

Body:
You can assign additional dependencies separately. Just add a line at the end:

$(addsuffix .o,${SPECIAL}): b.h

To not have to deal with dependency order, replace $< in the rule with $(filter %.cpp,$^). This way %.cpp does not have to be the first dependency.

Ideally, you want the header dependencies to be generated automatically to avoid specifying them manually.

The most simple automatic dependency generation:

%.o : %.cpp
    $(CXX) -c -o $@ -MD -MP $(CXXFLAGS) $(filter %.cpp,$^)

ifneq ($(MAKECMDGOALS),clean)
-include $(wildcard *.d)
endif


问:
only one color is displayed in time
I'm developing paint app the problem is when i choose color and paint and then pick different color the whole paint color changes to the new color can any one tell why this is happening and how to solve this ?  and how to add eraser to this?
imageview DrawView here :

```<code>public class DrawView extends ImageView {
    private ArrayList<Point> mTouches;
    int paintColor;
    public int setcolor(int a){
        paintColor=a;
        return paintColor;}
    // Java constructor
    public DrawView(Context context) {
        super(context);
        init();}
    // XML constructor
    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();}
    private void init() {
        mTouches = new ArrayList<Point>();}
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Capture a reference to each touch for drawing
        float touchX = event.getX();
        float touchY = event.getY();
        mTouches.add(new Point(Math.round(touchX), Math.round(touchY)));
        return super.onTouchEvent(event);}
    @Override
    protected void onDraw(Canvas c) {
        // Let the image be drawn first
        super.onDraw(c);
        // Draw your custom points here
        Paint paint = new Paint();
        paint.setColor(paintColor);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        for (Point p : mTouches) {
            c.drawCircle( p.x, p.y,15,paint);}} }
</code>```

in my main:

```<code>im.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                DrawView mcustomImagview = (DrawView) v;
                mcustomImagview.setcolor(color);
                mcustomImagview.invalidate();
                if (v.onTouchEvent(event)) {
// Do something with event.getX(), event.getY() }
                return true;}})
</code>```

答:
Every time onDraw is called, the entire canvas is redraw. As you store only one paintColor in your custom class, only the last selected one is used.

You need to store the color together with the associated Point. Then when you loop throw your mTouches array, you change the color for the color of the current Point.

Btw the Paint object can be updated, so you don't need to create it every time as it's a bad practice to create new objects in onDraw.

EDIT

```<code>public class DrawView extends android.support.v7.widget.AppCompatImageView {
    private ArrayList<ColouredPoint> mTouches;
    // Current used colour
    private int mCurrColour;
    private Paint mPaint;

    public void setColor(int colour) {
        mCurrColour = colour;
    }

    public DrawView(Context context) {
        super(context);
        init();
    }

    // XML constructor
    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mTouches = new ArrayList<>();
        mPaint = new Paint();
        mPaint.setColor(mCurrColour);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(5);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Capture a reference to each touch for drawing
        float touchX = event.getX();
        float touchY = event.getY();
        mTouches.add(new ColouredPoint(Math.round(touchX), Math.round(touchY), mCurrColour));

        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas c) {
        // Let the image be drawn first
        super.onDraw(c);
        // Draw your custom points here
        for (ColouredPoint p : mTouches) {
            mPaint.setColor(p.colour);
            c.drawCircle(p.x, p.y, 15, mPaint);
        }
    }

    /**
     * Class to store the coordinate and the colour of the point.
     */
    private class ColouredPoint {
        int x;
        int y;
        int colour;

        public ColouredPoint(int x, int y, int colour) {
            this.x = x;
            this.y = y;
            this.colour = colour;
        }
    }
}
</code>```

Title: only one color is displayed in time

Body:
I'm developing paint app the problem is when i choose color and paint and then pick different color the whole paint color changes to the new color can any one tell why this is happening and how to solve this ?  and how to add eraser to this?
imageview DrawView here :

public class DrawView extends ImageView {
    private ArrayList<Point> mTouches;
    int paintColor;
    public int setcolor(int a){
        paintColor=a;
        return paintColor;}
    // Java constructor
    public DrawView(Context context) {
        super(context);
        init();}
    // XML constructor
    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();}
    private void init() {
        mTouches = new ArrayList<Point>();}
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Capture a reference to each touch for drawing
        float touchX = event.getX();
        float touchY = event.getY();
        mTouches.add(new Point(Math.round(touchX), Math.round(touchY)));
        return super.onTouchEvent(event);}
    @Override
    protected void onDraw(Canvas c) {
        // Let the image be drawn first
        super.onDraw(c);
        // Draw your custom points here
        Paint paint = new Paint();
        paint.setColor(paintColor);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(5);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeJoin(Paint.Join.ROUND);
        paint.setStrokeCap(Paint.Cap.ROUND);
        for (Point p : mTouches) {
            c.drawCircle( p.x, p.y,15,paint);}} }

in my main:

im.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                DrawView mcustomImagview = (DrawView) v;
                mcustomImagview.setcolor(color);
                mcustomImagview.invalidate();
                if (v.onTouchEvent(event)) {
// Do something with event.getX(), event.getY() }
                return true;}})

Body:
Every time onDraw is called, the entire canvas is redraw. As you store only one paintColor in your custom class, only the last selected one is used.

You need to store the color together with the associated Point. Then when you loop throw your mTouches array, you change the color for the color of the current Point.

Btw the Paint object can be updated, so you don't need to create it every time as it's a bad practice to create new objects in onDraw.

EDIT

public class DrawView extends android.support.v7.widget.AppCompatImageView {
    private ArrayList<ColouredPoint> mTouches;
    // Current used colour
    private int mCurrColour;
    private Paint mPaint;

    public void setColor(int colour) {
        mCurrColour = colour;
    }

    public DrawView(Context context) {
        super(context);
        init();
    }

    // XML constructor
    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        mTouches = new ArrayList<>();
        mPaint = new Paint();
        mPaint.setColor(mCurrColour);
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(5);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // Capture a reference to each touch for drawing
        float touchX = event.getX();
        float touchY = event.getY();
        mTouches.add(new ColouredPoint(Math.round(touchX), Math.round(touchY), mCurrColour));

        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas c) {
        // Let the image be drawn first
        super.onDraw(c);
        // Draw your custom points here
        for (ColouredPoint p : mTouches) {
            mPaint.setColor(p.colour);
            c.drawCircle(p.x, p.y, 15, mPaint);
        }
    }

    /**
     * Class to store the coordinate and the colour of the point.
     */
    private class ColouredPoint {
        int x;
        int y;
        int colour;

        public ColouredPoint(int x, int y, int colour) {
            this.x = x;
            this.y = y;
            this.colour = colour;
        }
    }
}


问:
Verilog - confusion between || and + operator
In boolean algebra, addition of terms corresponds to an OR gate, while multiplication corresponds to an AND gate.

Suppose I wanted a blower fan of a thermostat that worked as follows:

The fan should turn on if either the heater or air-conditioner are on. Alternatively if the user requests the fan to turn on (by turning on an input fan_on), the fan should turn on even if the heater or air conditioner are off.

Based on these requirements I formulated the logic statement in Verilog code as:

```<code>assign blower_fan = fan_on + heater + aircon;
</code>```

However upon simulation this yields an incorrect solution. However this works:

```<code>assign blower_fan = fan_on || (heater + aircon);
</code>```

as does

```<code>assign blower_fan = fan_on || (heater || aircon);
</code>```

My Question:

What am I misunderstanding about the + operator? Also, I'm confused between the latter two solutions that DO work - why do both of them work and is the last one where I use only the logical OR operator a more correct (or preferred) way of doing what I want to do?

Edit#1: Here is the whole module where I declared inputs and outputs

```<code>module top_module (
    input too_cold,
    input too_hot,
    input mode,
    input fan_on,
    output heater,
    output aircon,
    output fan
);

    assign heater = (mode&&too_cold);
    assign aircon = (!mode&&too_hot);
    assign fan = (fan_on) || (heater || aircon);

endmodule
</code>```

答:
The Verilog + operator is not the an OR operator, it is the addition operator. There are two OR operators in Verilog:

```<code>|   bitwise OR
||  logical OR
</code>```

For vectors, the bitwise operation treats the individual bits of vector operands separately. In contrast, with the logical operators a scalar or vector is considered to be TRUE when it includes at least one 1, and FALSE when every bit is 0. Xs and Zs are considered to be unknown (neither TRUE nor FALSE).

You can also use the | operator as a reduction operator.

For example:

```<code>Expression           Result    Comment
=========================================
   1'b0 |  1'b0      1'b0      bitwise OR
   1'b0 |  1'b1      1'b1      bitwise OR
   1'b1 |  1'b0      1'b1      bitwise OR
   1'b1 |  1'b1      1'b1      bitwise OR

4'b0101 |  4'b1100   4'b1101   bitwise OR

4'b0000 || 4'b0000   1'b0      logical OR
4'b0000 || 4'b1100   1'b1      logical OR
4'b0101 || 4'b0000   1'b1      logical OR
4'b0101 || 4'b1100   1'b1      logical OR

| 4'b0000            1'b0      reduction
| 4'b0101            1'b1      reduction
| 4'b1111            1'b1      reduction
</code>```

If you use the + operator instead of the | operator and assign to one-bit, you are effectively using exclusive-OR instead of OR. Compare these truth tables:

```<code>            OR     XOR    +
A    B      F      F      F
==============================
1'b0 1'b0   1'b0   1'b0   1'b0
1'b0 1'b1   1'b1   1'b1   1'b1
1'b1 1'b0   1'b1   1'b1   1'b1
1'b1 1'b1   1'b1   1'b0   1'b0
</code>```

This expression:

```<code>assign blower_fan = fan_on || (heater + aircon);
</code>```

is going to fail when the fan_on is 1'b0 and both heater and aircon are 1'b1, whereas this one won't:

```<code>assign blower_fan = fan_on | heater | aircon;
</code>```

Body:
In boolean algebra, addition of terms corresponds to an OR gate, while multiplication corresponds to an AND gate.

Suppose I wanted a blower fan of a thermostat that worked as follows:

The fan should turn on if either the heater or air-conditioner are on. Alternatively if the user requests the fan to turn on (by turning on an input fan_on), the fan should turn on even if the heater or air conditioner are off.

Based on these requirements I formulated the logic statement in Verilog code as:

assign blower_fan = fan_on + heater + aircon;

However upon simulation this yields an incorrect solution. However this works:

assign blower_fan = fan_on || (heater + aircon);

as does

assign blower_fan = fan_on || (heater || aircon);

My Question:

What am I misunderstanding about the + operator? Also, I'm confused between the latter two solutions that DO work - why do both of them work and is the last one where I use only the logical OR operator a more correct (or preferred) way of doing what I want to do?

Edit#1: Here is the whole module where I declared inputs and outputs

module top_module (
    input too_cold,
    input too_hot,
    input mode,
    input fan_on,
    output heater,
    output aircon,
    output fan
);

    assign heater = (mode&&too_cold);
    assign aircon = (!mode&&too_hot);
    assign fan = (fan_on) || (heater || aircon);

endmodule

Body:
The Verilog + operator is not the an OR operator, it is the addition operator. There are two OR operators in Verilog:

|   bitwise OR
||  logical OR

For vectors, the bitwise operation treats the individual bits of vector operands separately. In contrast, with the logical operators a scalar or vector is considered to be TRUE when it includes at least one 1, and FALSE when every bit is 0. Xs and Zs are considered to be unknown (neither TRUE nor FALSE).

You can also use the | operator as a reduction operator.

For example:

Expression           Result    Comment
=========================================
   1'b0 |  1'b0      1'b0      bitwise OR
   1'b0 |  1'b1      1'b1      bitwise OR
   1'b1 |  1'b0      1'b1      bitwise OR
   1'b1 |  1'b1      1'b1      bitwise OR

4'b0101 |  4'b1100   4'b1101   bitwise OR

4'b0000 || 4'b0000   1'b0      logical OR
4'b0000 || 4'b1100   1'b1      logical OR
4'b0101 || 4'b0000   1'b1      logical OR
4'b0101 || 4'b1100   1'b1      logical OR

| 4'b0000            1'b0      reduction
| 4'b0101            1'b1      reduction
| 4'b1111            1'b1      reduction

If you use the + operator instead of the | operator and assign to one-bit, you are effectively using exclusive-OR instead of OR. Compare these truth tables:

            OR     XOR    +
A    B      F      F      F
==============================
1'b0 1'b0   1'b0   1'b0   1'b0
1'b0 1'b1   1'b1   1'b1   1'b1
1'b1 1'b0   1'b1   1'b1   1'b1
1'b1 1'b1   1'b1   1'b0   1'b0

This expression:

assign blower_fan = fan_on || (heater + aircon);

is going to fail when the fan_on is 1'b0 and both heater and aircon are 1'b1, whereas this one won't:

assign blower_fan = fan_on | heater | aircon;


问:
What is the most efficient binary to text encoding?
The closest contenders that I could find so far are yEnc (2%) and ASCII85 (25% overhead). There seem to be some issues around yEnc mainly around the fact that it uses an 8-bit character set. Which leads to another thought: is there a binary to text encoding based on the UTF-8 character set?</p>

答:
According to Wikipedia

basE91 produces the shortest plain ASCII output for compressed 8-bit binary input.

OwnerDisplayName: Mark

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 4.0


问:
gem 'gon' - name error in Quotes#index, uninitialized constant ActionView::CompiledTemplates::Gon, Rails 5
I am trying to use the gem 'gon' but run into the above error, stating;

```<code>namer error in Quotes#index

 Showing /Users/jamesbkemp/Code/QuoteEngine/app/views/layouts/application.html.erb where line #5 raised:
</code>```

uninitialized constant ActionView::CompiledTemplates::Gon

Any idea what the issue may be and or any suggestoins on alternative gems to make passing controller variables into javascript easier?

Thanks

application.html.erb, note line 5;

```<code>    <!DOCTYPE html>
<html>
  <head>
    <title>QuoteEngine</title>
    <%= Gon::Base.render_data %>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>

    <%= render "layouts/navbar" %>

        <% flash.each do |key, value| %>
       <div class="alert  alert-info alert-<%= key %>"><%= value %></div>
    <% end %>

        <%= yield %>

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

quotes_controller.rb

```<code>class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  # before_action :owners_only, only: [ :show, :edit, :index, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = Quote.new(quote_params)
    @quote = current_user.quotes.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    # @quote = Quote.find(params[:id])
    @quote = current_user.quotes.find(params[:id])
    gon.gon_quote_id = @quote.id
  end

  def index
    @quotes = current_user.quotes.all
  end

  def edit
    @quote = current_user.quotes.find(params[:id])
  end

  def update
    @quote = current_user.quotes.find(params[:id])
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote = current_user.quotes.find(params[:id])
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end
end
</code>```

_quote.rb partial;

```<code>    <% @quote = local_assigns[:quote] %>
<section id="quotes">
    <div class="container">
    <div class="row">
        <div class="col-md-4 text-center">
        <div class="panel panel-success panel-quote link-panel">
          <div class="panel-heading">
            <strong>GLA</strong>
            </div>
          <div class="panel-body text-center">
             <p><strong>Quote ID; <%= @quote.id %></strong></p>
          </div>

          <table class="table table-bordered">
            <tr>
              <td>Company name</td>
              <td><%= @quote.co_name %></td>
            </tr>
            <tr>
              <td>Company number</td>
              <td><%= @quote.co_number %></td>
            </tr>
            <tr>
              <td>Office postcode</td>
              <td><%= @quote.postcode %></td>
            </tr>
            <tr>
              <td>Industry</td>
              <td><%= @quote.industry %></td>
            </tr>
            <tr>
              <td>Previous cover</td>
              <td><%= @quote.prev_cover %></td>
            </tr>
            <tr>
              <td>Lives overseas</td>
              <td><%= @quote.lives_overseas %></td>
            </tr>
            <tr>
              <td>Scheme start date</td>
              <td><%= @quote.scheme_start_date %></td>
            </tr>
            <tr>
              <td>Payment frequency</td>
              <td><%= @quote.payment_frequency %></td>
            </tr>
            <tr>
              <td>Commission level</td>
              <td><%= @quote.commission_level %></td>
            </tr>
          </table>
        </div>
      </div>
    </div>
  </div>
</section>
</code>```

index.html.erb

```<code><% @quotes.each do |quote| %>
  <%= render :partial => "quote", locals: {quote: quote} %>
<% end %>
</code>```

答:
I would like to help with your case since I'm also using gon in rails 5 and it's working

after run bundle install,

open app/views/layouts/application.html.erb
and put under tag body <%= Gon::Base.render_data %>

do some test with open your your controller and create gon data (for example below I gave you with 10 users data

```<code>gon.users = User.limit(10)
</code>```

open your coffee and test with log

```<code>alert gon.users
</code>```

and don't forget to restart your rails server command

Body:
I am trying to use the gem 'gon' but run into the above error, stating;

namer error in Quotes#index

 Showing /Users/jamesbkemp/Code/QuoteEngine/app/views/layouts/application.html.erb where line #5 raised:

uninitialized constant ActionView::CompiledTemplates::Gon

Any idea what the issue may be and or any suggestoins on alternative gems to make passing controller variables into javascript easier?

Thanks

application.html.erb, note line 5;

    <!DOCTYPE html>

    <title>QuoteEngine</title>
    <%= Gon::Base.render_data %>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

    <%= render "layouts/navbar" %>

        <% flash.each do |key, value| %>
       <div class="alert  alert-info alert-<%= key %>"><%= value %>

    <% end %>

        <%= yield %>

quotes_controller.rb

class QuotesController < ApplicationController
  before_action :authenticate_user!, only: [ :new, :create, :edit, :update, :destroy ]
  # before_action :owners_only, only: [ :show, :edit, :index, :update, :destroy ]

  def new
    @quote = Quote.new
  end

  def create
    # @quote = Quote.new(quote_params)
    @quote = current_user.quotes.new(quote_params)
    if @quote.save
        redirect_to quote_url(@quote), notice: 'Quote request created'
    else
      render :new
    end
  end

  def show
    # @quote = Quote.find(params[:id])
    @quote = current_user.quotes.find(params[:id])
    gon.gon_quote_id = @quote.id
  end

  def index
    @quotes = current_user.quotes.all
  end

  def edit
    @quote = current_user.quotes.find(params[:id])
  end

  def update
    @quote = current_user.quotes.find(params[:id])
    if @quote.update_attributes(quote_params)
      redirect_to quote_path(@quote)
    else
      render :edit
    end
  end

  def destroy
    @quote = current_user.quotes.find(params[:id])
    @quote.destroy
    redirect_to quotes_path
  end

private

  def quote_params
    params.require(:quote).permit(:gla, :prev_cover, :co_name, :co_number, :postcode, :industry, :lives_overseas,
                                  :scheme_start_date, :payment_frequency, :commission_level)
  end
end

_quote.rb partial;

    <% @quote = local_assigns[:quote] %>

            GLA

Quote ID; <%= @quote.id %>

              Company name
              <%= @quote.co_name %>

              Company number
              <%= @quote.co_number %>

              Office postcode
              <%= @quote.postcode %>

              Industry
              <%= @quote.industry %>

              Previous cover
              <%= @quote.prev_cover %>

              Lives overseas
              <%= @quote.lives_overseas %>

              Scheme start date
              <%= @quote.scheme_start_date %>

              Payment frequency
              <%= @quote.payment_frequency %>

              Commission level
              <%= @quote.commission_level %>

index.html.erb

<% @quotes.each do |quote| %>
  <%= render :partial => "quote", locals: {quote: quote} %>
<% end %>

Body:
I would like to help with your case since I'm also using gon in rails 5 and it's working

after run bundle install,

open app/views/layouts/application.html.erb
and put under tag body <%= Gon::Base.render_data %>

do some test with open your your controller and create gon data (for example below I gave you with 10 users data

gon.users = User.limit(10)

open your coffee and test with log

alert gon.users

and don't forget to restart your rails server command


问:
How to serialize and deserialize FormCollection?
I'm trying to serialize a FormCollection object, and based on what I have researched, it inherits NameObjectCollectionBase so it also inherits GetObjectData and ISerializable. Wouldn't this mean it is serializable?

https://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection(v=vs.118).aspx

Here's a snippet of what I'm trying:

```<code>BinaryFormatter formatter = new BinaryFormatter();

//Serialize
using (MemoryStream stream = new MemoryStream())
{
  formatter.Serialize(stream, data);
  string test = Convert.ToBase64String(stream.ToArray());
  Session["test"] = test;
};

//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String((string)Session["test"])))
{
  data = (FormCollection) formatter.Deserialize(stream);
}
</code>```

I, unfortunately, got this error:

```<code>System.Runtime.Serialization.SerializationException: Type 'System.Web.Mvc.FormCollection' in Assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral... is not marked as serializable.
</code>```

Because this is a sealed class, I cannot extend it and add the [Serializable] Attribute.

My questions is:

Why I can't serialize FormCollection like this?

And how I can serialize/deserialize a FormCollection object?

答:
It cannot be serialized like this because it lacks [Serializable] attribute. That means developers of this class had no intention to make it serializable (with BinaryFormatter). The fact it's parent class implements ISerializable and marked with [Serializable] does not change anything - child class might have it's own internal details which will be lost during serialization if it was allowed to serialize any descendant of serializable class.

If you want to use BinaryFormatter (which might or might not be the best way) - you can do it like this:

```<code>BinaryFormatter formatter = new BinaryFormatter();
//Serialize
string serialized;
using (MemoryStream stream = new MemoryStream())
{
    // pass FormCollection to constructor of new NameValueCollection
    // that way we kind of convert it to NameValueCollection which is serializable
    // of course we lost any FormCollection-specific details (if there were any)
    formatter.Serialize(stream, new NameValueCollection(data));
    serialized = Convert.ToBase64String(stream.ToArray());
};

//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(serialized))) {
    // deserialize as NameValueCollection then create new
    // FormCollection from that
    data = new FormCollection((NameValueCollection) formatter.Deserialize(stream));
}
</code>```

Body:
I'm trying to serialize a FormCollection object, and based on what I have researched, it inherits NameObjectCollectionBase so it also inherits GetObjectData and ISerializable. Wouldn't this mean it is serializable?

https://msdn.microsoft.com/en-us/library/system.web.mvc.formcollection(v=vs.118).aspx

Here's a snippet of what I'm trying:

BinaryFormatter formatter = new BinaryFormatter();

//Serialize
using (MemoryStream stream = new MemoryStream())
{
  formatter.Serialize(stream, data);
  string test = Convert.ToBase64String(stream.ToArray());
  Session["test"] = test;
};

//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String((string)Session["test"])))
{
  data = (FormCollection) formatter.Deserialize(stream);
}

I, unfortunately, got this error:

System.Runtime.Serialization.SerializationException: Type 'System.Web.Mvc.FormCollection' in Assembly 'System.Web.Mvc, Version=5.2.3.0, Culture=neutral... is not marked as serializable.

Because this is a sealed class, I cannot extend it and add the [Serializable] Attribute.

My questions is:

Why I can't serialize FormCollection like this?

And how I can serialize/deserialize a FormCollection object?

Body:
It cannot be serialized like this because it lacks [Serializable] attribute. That means developers of this class had no intention to make it serializable (with BinaryFormatter). The fact it's parent class implements ISerializable and marked with [Serializable] does not change anything - child class might have it's own internal details which will be lost during serialization if it was allowed to serialize any descendant of serializable class.

If you want to use BinaryFormatter (which might or might not be the best way) - you can do it like this:

BinaryFormatter formatter = new BinaryFormatter();
//Serialize
string serialized;
using (MemoryStream stream = new MemoryStream())
{
    // pass FormCollection to constructor of new NameValueCollection
    // that way we kind of convert it to NameValueCollection which is serializable
    // of course we lost any FormCollection-specific details (if there were any)
    formatter.Serialize(stream, new NameValueCollection(data));
    serialized = Convert.ToBase64String(stream.ToArray());
};

//Deserialize
using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(serialized))) {
    // deserialize as NameValueCollection then create new
    // FormCollection from that
    data = new FormCollection((NameValueCollection) formatter.Deserialize(stream));
}


问:
locking only when modifying vs entire method
When should locks be used? Only when modifying data or when accessing it as well?

```<code>public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}
</code>```

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.

答:
You have to lock when reading too, or you can get unreliable data, or even an exception if a concurrent modification physically changes the target data structure.

In the case above, you need to make sure that multiple threads don't try to add the value at the same time, so you need at least a read lock while checking whether it is already present.  Otherwise multiple threads could decide to add, find the value is not present (since this check is not locked), and then all try to add in turn (after getting the lock)

You could use a ReaderWriterLockSlim if you have many reads and only a few writes.  In the code above you would acquire the read lock to do the check and upgrade to a write lock once you decide you need to add it.  In most cases, only a read lock (which allows your reader threads to still run in parallel) would be needed.

There is a summary of the available .Net 4 locking primitives here.  Definitely you should understand this before you get too deep into multithreaded code. Picking the correct locking mechanism can make a huge performance difference.

You are correct that you have been lucky so far - that's a frequent feature of concurrency bugs.  They are often hard to reproduce without targeted load testing, meaning correct design (and exhaustive testing, of course) is vital to avoid embarrassing and confusing production bugs.

Body:
When should locks be used? Only when modifying data or when accessing it as well?

public class Test {
    static Dictionary<string, object> someList = new Dictionary<string, object>();

    static object syncLock = new object();

    public static object GetValue(string name) {
        if (someList.ContainsKey(name)) {
            return someList[name];
        } else {
            lock(syncLock) {
                object someValue = GetValueFromSomeWhere(name);
                someList.Add(name, someValue);
            }
        }
    }
}

Should there be a lock around the the entire block or is it ok to just add it to the actual modification? My understanding is that there still could be some race condition where one call might not have found it and started to add it while another call right after might have also run into the same situation - but I'm not sure. Locking is still so confusing. I haven't run into any issues with the above similar code but I could just be lucky so far. Any help above would be appriciated as well as any good resources for how/when to lock objects.


问:
Cannot see any output on console on using onclick property?
When I type anything and then click on submit button it doesn't show anything in my console what am I missing.</p>

```<code><body>

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

<script type="text/javascript">

function showdata() {
    var film = document.getElementById('term').value;
    console.log(film);
}
</script>
</body>
</code>```

答:
When I run that code I get this error displayed in the console:

Uncaught SyntaxError: Unexpected token <

… because you swapped the position of the </script> and  tags.

Since you say you see nothing, the problem is most likely because you run the code when the submit button is clicked.

The JS will run then the form will submit and a new page will load.

Unless you configure your console to Preserve log, this will clear the console and erase any messages displayed there.

Change the configuration.

Body:
When I type anything and then click on submit button it doesn't show anything in my console what am I missing.

<form name="fetch-movie-title" id="fetch">
     <input type="text" placeholder="Enter a movie title" id="term" />
     <input type="submit" onclick="showdata()" id="search" value="Find me a poster" />
</form>

Body:
When I run that code I get this error displayed in the console:

Uncaught SyntaxError: Unexpected token <

… because you swapped the position of the </script> and </body> tags.

Since you say you see nothing, the problem is most likely because you run the code when the submit button is clicked.

The JS will run then the form will submit and a new page will load.

Unless you configure your console to Preserve log, this will clear the console and erase any messages displayed there.

Change the configuration.


答:
if the body tag is inside the script tag you will be getting a parser error so the function won't be defined when the click happens.

Alternatively, you aren't preventing the form submission so the page might be reloading before you get a chance to see the output.

Title: Cannot see any output on console on using onclick property?


问:
laravel display data on a page based on id
I have a page that shows links with name of businesses that are retrieved in database like this:

Controller:

```<code>public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}
</code>```

View:

```<code>@extends('master') @section('title', 'Live Oldham') @section('content')
@section('content')
            @foreach ($business as $businesses)
        <a target="_blank" href="{{ url('business/' . $businesses->name) }}"> {{($businesses->name) }}
        </a> @endforeach
@endsection
</code>```

Route:

```<code>Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');
</code>```

I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.

Controller:

```<code>function displayBusiness() {
    $business = Business::all();
    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}
</code>```

View:

```<code>@foreach ($business as $businesses)
    <p>{{$businesses->name}}</p>
    <p>{{$businesses->email}}</p>
@endforeach
@foreach ($address as $addresses)
    <p>{{$addresses->firstline_address}}</p>
    <p>{{$addresses->secondline_address}}</p>
    <p>{{$addresses->town}}</p>
    <p>{{$addresses->city}}</p>
    <p>{{$addresses->postcode}}</p>
    <p>{{$addresses->telephone}}</p>
@endforeach
</code>```

Route:

```<code>Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');
</code>```

Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.

Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.

Thanks!

答:
I do not know if I understood the question, but that may be the beginning of a solution ...

First view :

```<code>@extends('master') @section('title', 'Live Oldham')
@section('content')
            @foreach ($business as $businesses)
        <a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
        </a> @endforeach
@endsection
</code>```

Second Controller :

```<code>function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    return view('displayBusiness', compact('business', 'address'));
}
</code>```

Second View :

```<code>    <p>{{$business->name}}</p>
    <p>{{$business->email}}</p>
    <p>{{$address->firstline_address}}</p>
    <p>{{$address->secondline_address}}</p>
    <p>{{$address->town}}</p>
    <p>{{$address->city}}</p>
    <p>{{$address->postcode}}</p>
    <p>{{$address->telephone}}</p>
</code>```

Second Route :

```<code>Route::get('business/{id}', 'BusinessController@displayBusiness')->name('displayBusiness');
</code>```

Body:
I have a page that shows links with name of businesses that are retrieved in database like this:

Controller:

public function viewBusiness() {
// Return our "website" object
$business = Business::all();
// Pass the contents of the "html" property to the view
return view('viewBusiness', ['business' => $business]);
}

View:

@extends('master') @section('title', 'Live Oldham') @section('content')
@section('content')
            @foreach ($business as $businesses)
        name) }}"> {{($businesses->name) }}
         @endforeach
@endsection

Route:

Route::get('business/list', 'BusinessController@viewBusiness')->name('viewBusiness');

I then have added a function where user click on a link and it is taken to a page which displays all data for that specific business, however it diplays all data but for all businesses.

Controller:

function displayBusiness() {
    $business = Business::all();
    $address = Address::all();
    return view('displayBusiness', ['business' => $business, 'address' => $address]);
}

View:

@foreach ($business as $businesses)

{{$businesses->name}}

{{$businesses->email}}

@endforeach
@foreach ($address as $addresses)

{{$addresses->firstline_address}}

{{$addresses->secondline_address}}

{{$addresses->town}}

{{$addresses->city}}

{{$addresses->postcode}}

{{$addresses->telephone}}

@endforeach

Route:

Route::get('business/{name}', 'BusinessController@displayBusiness')->name('displayBusiness');

Now here's the question, how can this code be modified so only a business that match either bussiness->name or business->id is displayed. (I guess name is taken when user clicks on a name.

Another question is how to restrict the url so that if localhost/business/{name} is not equal to any business->name in the database returns error? at the moment it shows the page no matter what you enter.

Thanks!

Body:
I do not know if I understood the question, but that may be the beginning of a solution ...

First view :

@extends('master') @section('title', 'Live Oldham')
@section('content')
            @foreach ($business as $businesses)
        <a target="_blank" href="{{ url('business/' . $businesses->id) }}"> {{($businesses->name) }}
        </a> @endforeach
@endsection

Second Controller :

function displayBusiness($id) {
    $business = Business::find($id);
    $address = Address::find($id);
    return view('displayBusiness', compact('business', 'address'));
}

Second View :

    <p>{{$business->name}}</p>
    <p>{{$business->email}}</p>
    <p>{{$address->firstline_address}}</p>
    <p>{{$address->secondline_address}}</p>
    <p>{{$address->town}}</p>
    <p>{{$address->city}}</p>
    <p>{{$address->postcode}}</p>
    <p>{{$address->telephone}}</p>

Second Route :

Route::get('business/{id}', 'BusinessController@displayBusiness')->name('displayBusiness');


问:
Nodes inconsistency between 2D and 3D elements in GMSH
I am trying to produce a tetrahedral mesh of a cube. The problem I encounter is that a few nodes that are used to generate the triangular faces are then not used to generate any of the tetrahedral elements. Is there a way to avoid this?
This is the code.

```<code>    cl__1 = 0.01;
    Point(1) = {0, 0, 0, cl__1};
    Point(2) = {1, 0, 0, cl__1};
    Point(3) = {1, 1, 0, cl__1};
    Point(4) = {0, 1, 0, cl__1};
    Line(1) = {1, 2};
    Line(2) = {2, 3};
    Line(3) = {3, 4};
    Line(4) = {4, 1};
    Line Loop(5) = {4, 1, 2, 3};
    Plane Surface(6) = {5};
    Extrude {0, 0, 1} {
      Surface{6};
    }
    Coherence;
    Transfinite Line {1, 2, 3, 4, 9, 10, 11, 8, 18, 22, 13, 14} = 2 Using Progression 1;
    Transfinite Surface {19};
    Transfinite Surface {23};
    Transfinite Surface {27};
    Transfinite Surface {15};
    Transfinite Surface {28};
    Transfinite Surface {6};
    Transfinite Volume{1} = {1, 2, 3, 4, 6, 10, 14, 5};
    Physical Surface("top") = {28};
    Physical Surface("bottom") = {6};
    Physical Surface("x_min") = {15};
    Physical Surface("x_max") = {23};
    Physical Surface("y_min") = {19};
    Physical Surface("y_max") = {27};
    Physical Volume("bottom_volume") = {1};
</code>```

Thanks
Jian

答:
The result of that input gives these nodes:

```<code>$Nodes
8
1 0 0 0
2 1 0 0
3 1 1 0
4 0 1 0
5 0 1 1
6 0 0 1
7 1 0 1
8 1 1 1
$EndNodes
</code>```

with these nodes you can define all the triangular faces and the tetrahedral elements that define that mesh (there is no inconsistency in my opinion).

Body:
I am trying to produce a tetrahedral mesh of a cube. The problem I encounter is that a few nodes that are used to generate the triangular faces are then not used to generate any of the tetrahedral elements. Is there a way to avoid this?
This is the code.

    cl__1 = 0.01;
    Point(1) = {0, 0, 0, cl__1};
    Point(2) = {1, 0, 0, cl__1};
    Point(3) = {1, 1, 0, cl__1};
    Point(4) = {0, 1, 0, cl__1};
    Line(1) = {1, 2};
    Line(2) = {2, 3};
    Line(3) = {3, 4};
    Line(4) = {4, 1};
    Line Loop(5) = {4, 1, 2, 3};
    Plane Surface(6) = {5};
    Extrude {0, 0, 1} {
      Surface{6};
    }
    Coherence;
    Transfinite Line {1, 2, 3, 4, 9, 10, 11, 8, 18, 22, 13, 14} = 2 Using Progression 1;
    Transfinite Surface {19};
    Transfinite Surface {23};
    Transfinite Surface {27};
    Transfinite Surface {15};
    Transfinite Surface {28};
    Transfinite Surface {6};
    Transfinite Volume{1} = {1, 2, 3, 4, 6, 10, 14, 5};
    Physical Surface("top") = {28};
    Physical Surface("bottom") = {6};
    Physical Surface("x_min") = {15};
    Physical Surface("x_max") = {23};
    Physical Surface("y_min") = {19};
    Physical Surface("y_max") = {27};
    Physical Volume("bottom_volume") = {1};

Thanks
Jian

Body:
The result of that input gives these nodes:

$Nodes
8
1 0 0 0
2 1 0 0
3 1 1 0
4 0 1 0
5 0 1 1
6 0 0 1
7 1 0 1
8 1 1 1
$EndNodes

with these nodes you can define all the triangular faces and the tetrahedral elements that define that mesh (there is no inconsistency in my opinion).


问:
How to compare two UIImage objects
I am developing one application.In that i am using the imageviews.SO before changeing the UIImageview image I need to take that image in UIimage obejct and compare with another UIImage object for finding both are sam or not. So please tell me how to do that one.

答:
Converting the images to JPG / PNG, or relying on accessibility identifiers is either an expensive operation, or fragile & prone to failure.

Here, I follow the suggestion provided by Apple at the following link:

The isEqual(:) method is the only reliable way to determine whether
  two images contain the same image data. The image objects you create
  may be different from each other, even when you initialize them with
  the same cached image data. The only way to determine their equality
  is to use the isEqual(:) method, which compares the actual image
  data. Listing 1 illustrates the correct and incorrect ways to compare
  images.

To simplify things, I create the following extension for doing comparisons, so that I can avoid the issue of converting the first image:

```<code>import UIKit

extension UIImage {
    func isEqual(to image: UIImage) -> Bool {
        return isEqual(image)
    }
}
</code>```

With this, I can now setup an example to compare it on a pair of images:

```<code>let imageA = UIImage(named: "a")!
let imageB = UIImage(named: "b")!
let imageC = UIImage(named: "a")!

print(imageA.isEqual(to: imageA)) // true
print(imageA.isEqual(to: imageC)) // true
print(imageA.isEqual(to: imageB)) // false
</code>```

Title: How to compare two UIImage objects

Body:
Converting the images to JPG / PNG, or relying on accessibility identifiers is either an expensive operation, or fragile & prone to failure.

Here, I follow the suggestion provided by Apple at the following link:

The isEqual(:) method is the only reliable way to determine whether
  two images contain the same image data. The image objects you create
  may be different from each other, even when you initialize them with
  the same cached image data. The only way to determine their equality
  is to use the isEqual(:) method, which compares the actual image
  data. Listing 1 illustrates the correct and incorrect ways to compare
  images.

To simplify things, I create the following extension for doing comparisons, so that I can avoid the issue of converting the first image:

import UIKit

extension UIImage {
    func isEqual(to image: UIImage) -> Bool {
        return isEqual(image)
    }
}

With this, I can now setup an example to compare it on a pair of images:

let imageA = UIImage(named: "a")!
let imageB = UIImage(named: "b")!
let imageC = UIImage(named: "a")!

print(imageA.isEqual(to: imageA)) // true
print(imageA.isEqual(to: imageC)) // true
print(imageA.isEqual(to: imageB)) // false


问:
MS-SQL 2000: Turn off logging during stored procedure
Here's my scenario:

I have a simple stored procedure that removes a specific set of rows from a table (we'll say about 30k rows), and then inserts about the same amount of rows.  This generally should only take a few seconds; however, the table has a trigger on it that watches for inserts/deletes, and tries to mimic what happened to a linked table on another server.

This process in turn is unbareably slow due to the trigger, and the table is also locked during this process.  So here are my two questions:

I'm guessing a decent part of the slowdown is due to the transaction log.  Is there a way for me to specify in my stored procedure that I do not want what's in the procedure to be logged?

Is there a way for me to do my 'DELETE FROM' and 'INSERT INTO' commands without me locking the table during the entire process?

Thanks!

edit - Thanks for the answers; I figured it was the case (not being able to do either of the above), but wanted to make sure.  The trigger was created a long time ago, and doesn't look very effecient, so it looks like my next step will be to go in to that and find out what's needed and how it can be improved.  Thanks!

答:
It doesn't help with your trigger, but the solution to the locking issue is to perform the transactions in smaller batches.

Instead of

```<code>DELETE FROM Table WHERE <Condition>
</code>```

Do something like

```<code>WHILE EXISTS ( SELECT * FROM table WHERE <condition to delete>)
BEGIN
  SET ROWCOUNT 1000
  DELETE FROM Table WHERE <Condition>
  SET ROWCOUNT 0
END
</code>```

OwnerDisplayName: John

LastEditorDisplayName: CodeSlave

Body:
It doesn't help with your trigger, but the solution to the locking issue is to perform the transactions in smaller batches.

Instead of

DELETE FROM Table WHERE <Condition>

Do something like

WHILE EXISTS ( SELECT * FROM table WHERE <condition to delete>)
BEGIN
  SET ROWCOUNT 1000
  DELETE FROM Table WHERE <Condition>
  SET ROWCOUNT 0
END

OwnerDisplayName: BradC


问:
why does java Charset need extra import?
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

```<code>import java.nio.*;

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}
</code>```

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?

答:
You import packages, not libraries.  A library might contain multiple packages, but that doesn't mean that you can get away from importing them individually.

Also, the Charset class belongs to the java.nio.charset package, while you've imported the java.nio.file package.  There is no relation between the two - one isn't a parent of the other.

Body:
I am teaching myself a little about Files and I/O in Java, based on this tutorial: Oracle Tutorial

Now, after writing some examples to understand input and output, I got a question regarding the import of certain libraries.

I created the following example program, and I ask myself why the program says:

Cannot find symbol - class Charset

import java.nio.*;

public class test
{

public static void main(String[] args)
{
    Charset charset = Charset.forName("US-ASCII");
}

}

I know that the solution is to import the following
    import java.nio.charset.*;

But why do I have to import it, if I already got the parent library?


问:
How to install wkhtmltopdf patched qt without compiling?
I'm using google cloud instance for host Odoo, somo reports print to pdf ok, but other with custom paperformat get the following error:

"The switch --header-spacing, is not support using unpatched qt, and will be ignored.The switch --header-html, is not support using unpatched qt, and will be ignored.The switch --footer-html, is not support using unpatched qt, and will be ignored.QXcbConnection: Could not connect to display"

I google it, and to solve I need to compile wkhtmltopdf like this:
http://www.grobak.net/id/blog/how-fix-wkhtmltopdf-failed-error-code-6 but this proccess need 3 hs and I'm building a script to install google instances on the run with odoo dependencies.

the .deb package have a dependency broken

Anyone know other solution?

答:
After trying many ways I finally made it work.

First I removed all my previous installation by

sudo apt-get remove --purge wkhtmltopdf

sudo apt-get autoremove

Then I opened wkhtmltopdf.org and navigated into their Downloads > Archive. In Archive section I downloaded 0.12.1 .deb version by

wget <copy the link from website for the.deb file and paste it in terminal here>.

sudo dpkg -i <package name>

sudo cp /usr/local/bin/wkhtmltopdf /usr/bin

This is because odoo looks for wkhtmltopdf in /usr/bin directory otherwise gives IOError. I also set my webkit_path parameter in Odoo System Parameters to /usr/bin.

Thats it. Hope this helps


问:
npm global package installing issue
I have faced an issue when I have tried to install Vue CLI.

windows 10,
node ~ 6.10.3
npm ~ 3.10.10

```<code>npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.111430805                                                                            1' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.311380074                                                                            4' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
</code>```

Please help me how I fixed the issues and install the vue cli

答: I removed my old node js and installed the current version 8.0.0 and my issue is solved. </p>

Title: npm global package installing issue

Body:
I have faced an issue when I have tried to install Vue CLI.

windows 10,
node ~ 6.10.3
npm ~ 3.10.10

npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.111430805                                                                            1' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.311380074                                                                            4' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

Please help me how I fixed the issues and install the vue cli


问:
Should I inject "child" dependencies into my client?
I have two services: service A and service B.

Service A depends on service B, therefore I inject service B into service A.

Now I need to use service A in my controller. I just need to call a method in service A, not in service B.

What is the best practice in dependency injection?

Should I just inject service A into my controller, because I only need to call a method in service A and not in service B?

Or should I inject both service A and service B into my controller, because I need to be explicit and advertise all the dependencies of my controller?

答:
There is no one-size-fits-all solution.

However, if you're using a dependency resolver, (A DI-container) you should ask that resolver for the instance you need. The resolver should then also resolve its dependencies.

If not, I'd be inclined to inject both A and B.


问:
Apache Commons Daemon "Failed creating Java" error
I'm trying to start a Windows service using the Apache Commons Daemon. It works on Windows XP, but I'm trying to run it on Windows 7 x64. It fails to start and I get the following error in the logs:

```<code>[2010-12-13 17:21:19] [info] Commons Daemon procrun (1.0.3.0) started
[2010-12-13 17:21:19] [info] Running 'NodeService' Service...
[2010-12-13 17:21:19] [info] Starting service...
[2010-12-13 17:21:19] [error] Failed creating java
[2010-12-13 17:21:19] [error] ServiceStart returned 1
[2010-12-13 17:21:19] [info] Run service finished.
[2010-12-13 17:21:19] [info] Commons Daemon procrun finished
</code>```

I've set the JAVA_HOME and added the Java bin to PATH, just to be sure. I'm not sure why it's not starting, or if it has to do with the x64 operating system. It was designed for a 32-bit system originally.

答: Fixed the issue. The 32-bit version of the JRE must be installed since it looks for that registry info. I had the 64-bit version.</p>

Body:
I'm trying to start a Windows service using the Apache Commons Daemon. It works on Windows XP, but I'm trying to run it on Windows 7 x64. It fails to start and I get the following error in the logs:

[2010-12-13 17:21:19] [info] Commons Daemon procrun (1.0.3.0) started
[2010-12-13 17:21:19] [info] Running 'NodeService' Service...
[2010-12-13 17:21:19] [info] Starting service...
[2010-12-13 17:21:19] [error] Failed creating java
[2010-12-13 17:21:19] [error] ServiceStart returned 1
[2010-12-13 17:21:19] [info] Run service finished.
[2010-12-13 17:21:19] [info] Commons Daemon procrun finished

I've set the JAVA_HOME and added the Java bin to PATH, just to be sure. I'm not sure why it's not starting, or if it has to do with the x64 operating system. It was designed for a 32-bit system originally.


问:
Mvc 5 pagination using view model
Hi i am newbie to Mvc i have a json service which returns a list of walletstatementlogs based on fromdate and todate. I have a controller TopUpReqLogController every time when i hit the action index of the controller it will go to service and fetch the data and returns to view as Ipagedlist and genrates pagelinks. How do i prevent servicecall everytime in TopUpReqLogController index action i just want to load service data once and pass it to index and display data in pages using int ? page please suggest</p>

```<code> public class WalletTopUpRequest
    {

        public string SlNo { get; set; }
        public string Sequence { get; set; }
        public string Merchant { get; set; }
        public string CustomerCode { get; set; }
        public string CustomerName { get; set; }
        public string BankName { get; set; }
        public string TransactionDate { get; set; }
        public string Reference { get; set; }
        public string Amount { get; set; }
        public string ApprovalStatus { get; set; }
        public string ApproveUser { get; set; }
        public string ApprovalDate { get; set; }
        public string RemarKs { get; set; }
    }

public ViewResult Index(int? page)
        {
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            List<WalletTopUpRequest> wallettoprq = new List<WalletTopUpRequest>();
            if (page == null)
            {
                AgentBusiness business = new AgentBusiness();
                var result = business.Topuprequestlog("99910011010", "99810001110", "jBurFDoD1UpNPzWd/BlK4hVpV8GF+0eQT+AfNxEHHDKMB25AHf6CVA==", "25052017000000", "01062017000000");
                wallettoprq = result.wallettopuprequest.ToList();
                var viewmodel = wallettoprq.ToPagedList(pageNumber, pageSize);
                return View(viewmodel);
            }

            return View(wallettoprq.ToPagedList(pageNumber, pageSize));
        }

@using PagedList;
@using PagedList.Mvc;
@model  IPagedList<HaalMeer.MVC.Client.Models.WalletTopUpRequest>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<html>
<head>
</head>
<body>
   <div id="page-wrapper">
        <div class="page-title-container">
            @*<div class="container-fluid">*@
                <div class="page-title pull-left">
                    <h2 class="entry-title">Topup Request Log</h2>
                </div>
                <ul class="breadcrumbs pull-right">
                    <li><a href="#">Home</a></li>
                    <li class="active">Topup Request Log</li>
                </ul>
            </div>
        </div>
        <section id="content" class="gray-area">
            <div class="container">
                <div class="row">
                    <div class="col-md-3">
                    </div>
                    @using (Html.BeginForm("Index", "TopUpReqLog", FormMethod.Get))
                    {
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>From Date</label>
                            <div class="datepicker-wrap blue">
                                @*<input type="text" name="date_from" class="input-text full-width" placeholder="mm/dd/yy" style="background-color: #fff" />*@
                                @Html.TextBox("Fromdate", ViewBag.fromdate as string, new { @class = "input-text full-width", @placeholder = "mm/dd/yyy",@style = "background-color: #fff" }) <br />

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

                    <div class="col-md-3">
                        <div class="form-group">
                            <label>To Date</label>
                            <div class="datepicker-wrap blue">
                                @*<input type="text" name="date_from" class="input-text full-width" placeholder="mm/dd/yy" style="background-color: #fff" />*@
                                @Html.TextBox("Todate", ViewBag.todate as string, new { @class = "input-text full-width", @placeholder = "mm/dd/yyy", @style = "background-color: #fff" }) <br />

                            </div>
                        </div>
                        <button type="submit">Submit</button>
                    </div>
                    }

                    <div class="col-md-3">
                    </div>

                </div>
                <div class="row">
                    <div class="col-md-12 col-sm-12">
                        <div class="table-responsive">

                            <table class="table">
                                <tr class="info" style="text-align: center; font-weight: bold; color: #000">
                                    <td class="col-md-1">Sl</td>
                                    <td class="col-md-2">Date</td>
                                    <td class="col-md-1">Bank Ref.</td>
                                    <td class="col-md-1">Bank Name</td>
                                    <td class="col-md-2">Remarks</td>
                                    <td class="col-md-1">Amount</td>
                                    <td class="col-md-1">Status</td>
                                    <td class="col-md-2">Action Date</td>
                                </tr>

                                        @foreach (var item in Model)
                                        {
                                        <tr>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.SlNo)</td>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.TransactionDate)</td>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.Reference)</td>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.BankName)</td>
                                            <td class="hmleft">@Html.DisplayFor(modelItem => item.RemarKs)</td>
                                            <td class="hmright">@Html.DisplayFor(modelItem => item.Amount) </td>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.ApprovalStatus)</td>
                                            <td class="hmcenter">@Html.DisplayFor(modelItem => item.ApprovalDate)</td>
                                        </tr>

                                         }

                            </table>
                            <br/>

                            Page @(Model.PageCount<Model.PageNumber? 0 : Model.PageNumber) of @Model.PageCount

                            @Html.PagedListPager(Model, page => Url.Action("Index",new { page
                                            }))

                   @*<div class="form-group">
                    <ul class="pagination">
                        <li><a href="#">1</a></li>
                        <li class="active"><a href="#">2</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#">5</a></li>
                        <li><a href="#">3</a></li>
                        <li><a href="#">4</a></li>
                        <li><a href="#">5</a></li>
                    </ul>
                </div>*@

                        </div>
                    </div>

                </div>

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

答:
Below example shows the paging to be done at server side and Client Side :
Here is my Model :

```<code> public partial class Employee
    {
        public int Id { get; set; }
        public string FName { get; set; }
        public string Lname { get; set; }
    }
</code>```

Action:

```<code> public ActionResult Index(int? Page)
    {
        return View();
    }

     /// returns Partial View
    public ActionResult _PartialIndex(int? Page)
    {
        return PartialView(db.Employees.ToList().ToPagedList(Page ?? 1, 10));
    }
</code>```

Views :

1.Index View :Index.cshtml

```<code>@{
    ViewBag.Title = "Index";
}

<script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
<script>

    $(document).ready(function () {
        $('#loading').show();
        debugger;
        var Page = '';
        $.ajax({
            url: '/Employees/_PartialIndex',
            contentType: "application/json; charset=utf-8",
            type: 'get',
            datatype: 'html'
        }).success(function (result) {
            $('#main').html(result);
            $('#loading').hide();
        });
    });
</script>
<h2>Index</h2>
<div class="col-md-8 col-md-offset-2">
    <center>
        <div id="loading" style="display:none; z-index:200; position:absolute; top:50%; left:45%;">
            <img src="~/Content/loading.gif" />
        </div>
    </center>
    <div id="main">

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

2.Partial View :_PartialIndex.cshtml

```<code>@using PagedList.Mvc
@using PagedList;
@model IPagedList<samplePaging.Models.Employee>
@{
    ViewBag.Title = "Index";
}

<h2>Employee List</h2>

<table class="table">
    <tr>
        <th>
            First Name
        </th>
        <th>
          Last Name
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Lname)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>
<center>
    @Html.PagedListPager(Model, page => Url.Action("_PartialIndex", new {  page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions() { DisplayPageCountAndCurrentLocation = true }, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "main", LoadingElementId = "loading" }))
</center>
</code>```

If you want to do the paging at client side then follow below steps:

Action:

```<code>  public ActionResult JsonIndex(int? Page)
        {
            return Json(db.Employees.ToList(), JsonRequestBehavior.AllowGet);
        }
</code>```

View:

```<code>@{
    ViewBag.Title = "Index2";
}

<h2>Index2</h2>

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script>

    $(document).ready(function () {
        //Call EmpDetails jsonResult Method
        $.getJSON("/Employees/JsonIndex",
        function (json) {
            var tr;

        //Append each row to html table
        for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + json[i].FName + "</td>");
                tr.append("<td>" + json[i].LName + "</td>");

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

        }
        $('#EmpInfo').DataTable();
        });

    });

</script>
<hr />
<div class="form-horizontal">
    <table id="EmpInfo" class="table table-bordered  table-hover">
        <thead>
            <tr>
                <th>Fname</th>
                <th>LName</th>

            </tr>
        </thead>
        <tbody></tbody>
    </table>

</div>
</code>```

Hope this help you !

Title: Mvc 5 pagination using view model

Body:
Hi i am newbie to Mvc i have a json service which returns a list of walletstatementlogs based on fromdate and todate. I have a controller TopUpReqLogController every time when i hit the action index of the controller it will go to service and fetch the data and returns to view as Ipagedlist and genrates pagelinks. How do i prevent servicecall everytime in TopUpReqLogController index action i just want to load service data once and pass it to index and display data in pages using int ? page please suggest

 public class WalletTopUpRequest
    {

        public string SlNo { get; set; }
        public string Sequence { get; set; }
        public string Merchant { get; set; }
        public string CustomerCode { get; set; }
        public string CustomerName { get; set; }
        public string BankName { get; set; }
        public string TransactionDate { get; set; }
        public string Reference { get; set; }
        public string Amount { get; set; }
        public string ApprovalStatus { get; set; }
        public string ApproveUser { get; set; }
        public string ApprovalDate { get; set; }
        public string RemarKs { get; set; }
    }

public ViewResult Index(int? page)
        {
            int pageSize = 3;
            int pageNumber = (page ?? 1);
            List<WalletTopUpRequest> wallettoprq = new List<WalletTopUpRequest>();
            if (page == null)
            {
                AgentBusiness business = new AgentBusiness();
                var result = business.Topuprequestlog("99910011010", "99810001110", "jBurFDoD1UpNPzWd/BlK4hVpV8GF+0eQT+AfNxEHHDKMB25AHf6CVA==", "25052017000000", "01062017000000");
                wallettoprq = result.wallettopuprequest.ToList();
                var viewmodel = wallettoprq.ToPagedList(pageNumber, pageSize);
                return View(viewmodel);
            }

            return View(wallettoprq.ToPagedList(pageNumber, pageSize));
        }

@using PagedList;
@using PagedList.Mvc;
@model  IPagedList<HaalMeer.MVC.Client.Models.WalletTopUpRequest>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}

            @*
*@

Topup Request Log

Home

Topup Request Log

                    @using (Html.BeginForm("Index", "TopUpReqLog", FormMethod.Get))
                    {

                            From Date

                                @*<input type="text" name="date_from" class="input-text full-width" placeholder="mm/dd/yy" style="background-color: #fff" />*@
                                @Html.TextBox("Fromdate", ViewBag.fromdate as string, new { @class = "input-text full-width", @placeholder = "mm/dd/yyy",@style = "background-color: #fff" })

                            To Date

                                @*<input type="text" name="date_from" class="input-text full-width" placeholder="mm/dd/yy" style="background-color: #fff" />*@
                                @Html.TextBox("Todate", ViewBag.todate as string, new { @class = "input-text full-width", @placeholder = "mm/dd/yyy", @style = "background-color: #fff" })

                        <button type="submit">Submit</button>

                    }

                                    Sl
                                    Date
                                    Bank Ref.
                                    Bank Name
                                    Remarks
                                    Amount
                                    Status
                                    Action Date

                                        @foreach (var item in Model)
                                        {

                                            @Html.DisplayFor(modelItem => item.SlNo)
                                            @Html.DisplayFor(modelItem => item.TransactionDate)
                                            @Html.DisplayFor(modelItem => item.Reference)
                                            @Html.DisplayFor(modelItem => item.BankName)
                                            @Html.DisplayFor(modelItem => item.RemarKs)
                                            @Html.DisplayFor(modelItem => item.Amount)
                                            @Html.DisplayFor(modelItem => item.ApprovalStatus)
                                            @Html.DisplayFor(modelItem => item.ApprovalDate)

                                         }

                            Page @(Model.PageCount<Model.PageNumber? 0 : Model.PageNumber) of @Model.PageCount

                            @Html.PagedListPager(Model, page => Url.Action("Index",new { page
                                            }))

                   @*

1

2

3

4

5

3

4

5

*@

Body:
Below example shows the paging to be done at server side and Client Side :
Here is my Model :

 public partial class Employee
    {
        public int Id { get; set; }
        public string FName { get; set; }
        public string Lname { get; set; }
    }

Action:

 public ActionResult Index(int? Page)
    {
        return View();
    }

     /// returns Partial View
    public ActionResult _PartialIndex(int? Page)
    {
        return PartialView(db.Employees.ToList().ToPagedList(Page ?? 1, 10));
    }

Views :

1.Index View :Index.cshtml

@{
    ViewBag.Title = "Index";
}

<script src="https://cdn.jsdelivr.net/jquery.ajax.unobtrusive/3.2.4/jquery.unobtrusive-ajax.min.js"></script>
<script>

    $(document).ready(function () {
        $('#loading').show();
        debugger;
        var Page = '';
        $.ajax({
            url: '/Employees/_PartialIndex',
            contentType: "application/json; charset=utf-8",
            type: 'get',
            datatype: 'html'
        }).success(function (result) {
            $('#main').html(result);
            $('#loading').hide();
        });
    });
</script>
<h2>Index</h2>
<div class="col-md-8 col-md-offset-2">
    <center>
        <div id="loading" style="display:none; z-index:200; position:absolute; top:50%; left:45%;">
            <img src="~/Content/loading.gif" />
        </div>
    </center>
    <div id="main">

    </div>
</div>

2.Partial View :_PartialIndex.cshtml

@using PagedList.Mvc
@using PagedList;
@model IPagedList<samplePaging.Models.Employee>
@{
    ViewBag.Title = "Index";
}

<h2>Employee List</h2>

<table class="table">
    <tr>
        <th>
            First Name
        </th>
        <th>
          Last Name
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.FName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Lname)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>
<center>
    @Html.PagedListPager(Model, page => Url.Action("_PartialIndex", new {  page }), PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions() { DisplayPageCountAndCurrentLocation = true }, new AjaxOptions() { HttpMethod = "GET", UpdateTargetId = "main", LoadingElementId = "loading" }))
</center>

If you want to do the paging at client side then follow below steps:

Action:

  public ActionResult JsonIndex(int? Page)
        {
            return Json(db.Employees.ToList(), JsonRequestBehavior.AllowGet);
        }

View:

@{
    ViewBag.Title = "Index2";
}

<h2>Index2</h2>

<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css">
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script>
<script>

    $(document).ready(function () {
        //Call EmpDetails jsonResult Method
        $.getJSON("/Employees/JsonIndex",
        function (json) {
            var tr;

        //Append each row to html table
        for (var i = 0; i < json.length; i++) {
                tr = $('<tr/>');
                tr.append("<td>" + json[i].FName + "</td>");
                tr.append("<td>" + json[i].LName + "</td>");

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

        }
        $('#EmpInfo').DataTable();
        });

    });

</script>
<hr />
<div class="form-horizontal">
    <table id="EmpInfo" class="table table-bordered  table-hover">
        <thead>
            <tr>
                <th>Fname</th>
                <th>LName</th>

            </tr>
        </thead>
        <tbody></tbody>
    </table>

</div>

Hope this help you !