问:
what is unconditional self loop in promela?
I am working on a project which involves SPIN Model checker.SPIN version 6.4.7 and ispin version 1.1.4 I am getting this error on ispin saying

state 76: unconditional self loop

```<code>    proctype TDMAProtocol(byte id; chan P1, P2, PR)

54  {

55       byte id_j, members_j, r_j;

56     do

57        ::nodeState[id].r == id ->
58           nodeState[id].r =  (nodeState[id].r + 1) % 4;

59
60        atomic {
61  //       printf("-- %d New round %d member %d cmembers %d\n" , id, nodeState[id].r,nodeState[id].members, nodeState[id].cmembers);

62
63           nodeState[id].r =  (nodeState[id].r + 1) % 4;

64           nodeState[id].messageLost[0] = nodeState[id].messageLost[0]+1;

65           nodeState[id].messageLost[1] = nodeState[id].messageLost[1]+1;

66           nodeState[id].messageLost[2] = nodeState[id].messageLost[2]+1;

67           nodeState[id].messageLost[id] = 0;

68  //       nodeState[id].round = 1;
69
70            // Send aloha
71            if
72            ::nodeState[id].state == ALOHA && nodeState[id].p == 0 ->
73
74  //            printf("%d --Sending \n" , id);
75                P1!id,nodeState[id].members,nodeState[id].r;
76                P2!id,nodeState[id].members,nodeState[id].r;
77                 if
78                    ::true ->  nodeState[id].p = 0;
79                    ::true ->  nodeState[id].p = 1;
80                    ::skip
81                fi;
82            ::nodeState[id].state == ALOHA && nodeState[id].p == 1 ->
83                if
84                ::true ->  nodeState[id].p = 0;
85                ::true ->  nodeState[id].p = 1
86                fi;
87  //            printf("%d --Sending with proabality %d\n" , id, nodeState[id].p);
88
89          // send TDMA
90            ::nodeState[id].state != ALOHA ->
91  //          printf("%d --Sending TDM\n" , id)
92
93              P1!id,nodeState[id].members,nodeState[id].r;
94              P2!id,nodeState[id].members,nodeState[id].r
95            ::skip
96
97            fi;
98        }
99
100      :: empty(PR) ->
101           skip
102      :: nempty(PR) ->
103        PR?id_j,members_j,r_j;
104 //     printf("%d Size of channel %d\n", id, len(PR));
105        atomic {
106          if
107           ::nodeState[id].state ==  ALOHA ->
108           nodeState[id].messageLost[id_j] = 0;
109           nodeState[id].members = nodeState[id].members | (1 << id_j);
110           if
111             ::nodeState[id].members == members_j ->
112               nodeState[id].cmembers = nodeState[id].members | (1 << id_j)
113             ::skip
114           fi;
115           if
116             ::nodeState[id].cmembers == members_j ->
117               printf("%d reaches TDMA\n", id);
118               nodeState[id].state = TDMA
119               if
120             ::nodeState[id].leader > members_j ->
121               nodeState[id].leader = members_j
122             ::skip
123               fi;
124               if
125             ::nodeState[id].leader == members_j ->
126               nodeState[id].r = r_j
127             ::skip
128               fi;
129              ::nodeState[id].cmembers != members_j ->
130             skip
131           fi;
132 //         printf("%d --Receiving in ALOHA %d from %d\n" , id,  nodeState[id].members, id_j);
133
134         ::nodeState[id].state !=  ALOHA ->
135 //      printf("%d reaches TDMA\n" , id);
136         nodeState[id].messageLost[id_j] = 0
137
138         fi;
139       }
140       //round
141          // Failure detector
142      :: nodeState[id].state == TDMA &&
143           (nodeState[id].messageLost[0] > 3 || nodeState[id].messageLost[1] > 3 || nodeState[id].messageLost[2] > 3) ->
144           atomic {
145         printf("%d ALOHA from failure Detector\n", id);
146
147         nodeState[id].state = ALOHA;
148         nodeState[id].members = 1 << id;
149         nodeState[id].cmembers = 1 << id;
150         nodeState[id].leader = id
151           }
152 //   :: nodeState[id].round > 0 ->
153 //      nodeState[id].round = (nodeState[id].round + 1) % 2
154      :: nodeState[id].r != id ->
155        // printf("%d in round %d\n" , id, nodeState[id].r);
156         nodeState[id].r =  (nodeState[id].r + 1) % 4
157
158         //nodeState[id].round = (nodeState[id].round + 1) % 2
159      :: skip
160    od;
161 }
</code>```

Error is pointed at line 57.I am not sure what does this mean. when i run my code on terminal it works fine bt with ispin interface it throws this error. Someone came across this error?

答:
after spending many hours wandering around the code. i tried hit and trial and removed last skip statement from the model. Seems like many possible alternative guard statements along with additional skip statement made it an unconditional self loop.
It worked when i removed the last ::skip statement from do loop.

It appears that Spin has some very simple mechanism for detecting unconditional self loops caused by some loop guard being equal to skip or true with no subsequent instruction to be executed, e.g.:

init
{
    do
        :: skip            // or true
    od;
}
```

<p>prints:</p>

<pre class="lang-sh prettyprint-override"><code>~$ spin -search test.pml
error: proctype ':init:' line 4, state 2: has unconditional self-loop

pan: elapsed time 1.76e+07 seconds
pan: rate         0 states/second
</code>```

The routine can be easily circumvented by adding an extra empty statement:

init
{
    do
        :: skip -> skip            // or true -> true
    od;
}
```

<p>prints:</p>

<pre class="lang-sh prettyprint-override"><code>~$ spin -search test.pml

(Spin Version 6.4.3 -- 16 December 2014)
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 12 byte, depth reached 1, errors: 0
        2 states, stored
        1 states, matched
        3 transitions (= stored+matched)
        0 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.000   equivalent memory usage for states (stored*(State-vector + overhead))
    0.292   actual memory usage for states
  128.000   memory used for hash table (-w24)
    0.534   memory used for DFS stack (-m10000)
  128.730   total actual memory usage

unreached in init
    test.pml:6, state 6, "-end-"
    (1 of 6 states)

pan: elapsed time 0 seconds
</code>```

Interestingly, the routine fails to consider other obvious cases in which an unconditional self-loop arises, e.g. when the guard is a number different from 0 and there is no re-entrant block of instructions.

Body:
I am working on a project which involves SPIN Model checker.SPIN version 6.4.7 and ispin version 1.1.4 I am getting this error on ispin saying

state 76: unconditional self loop

    proctype TDMAProtocol(byte id; chan P1, P2, PR)

54  {

55       byte id_j, members_j, r_j;

56     do

57        ::nodeState[id].r == id ->
58           nodeState[id].r =  (nodeState[id].r + 1) % 4;

59
60        atomic {
61  //       printf("-- %d New round %d member %d cmembers %d\n" , id, nodeState[id].r,nodeState[id].members, nodeState[id].cmembers);

62
63           nodeState[id].r =  (nodeState[id].r + 1) % 4;

64           nodeState[id].messageLost[0] = nodeState[id].messageLost[0]+1;

65           nodeState[id].messageLost[1] = nodeState[id].messageLost[1]+1;

66           nodeState[id].messageLost[2] = nodeState[id].messageLost[2]+1;

67           nodeState[id].messageLost[id] = 0;

68  //       nodeState[id].round = 1;
69
70            // Send aloha
71            if
72            ::nodeState[id].state == ALOHA && nodeState[id].p == 0 ->
73
74  //            printf("%d --Sending \n" , id);
75                P1!id,nodeState[id].members,nodeState[id].r;
76                P2!id,nodeState[id].members,nodeState[id].r;
77                 if
78                    ::true ->  nodeState[id].p = 0;
79                    ::true ->  nodeState[id].p = 1;
80                    ::skip
81                fi;
82            ::nodeState[id].state == ALOHA && nodeState[id].p == 1 ->
83                if
84                ::true ->  nodeState[id].p = 0;
85                ::true ->  nodeState[id].p = 1
86                fi;
87  //            printf("%d --Sending with proabality %d\n" , id, nodeState[id].p);
88
89          // send TDMA
90            ::nodeState[id].state != ALOHA ->
91  //          printf("%d --Sending TDM\n" , id)
92
93              P1!id,nodeState[id].members,nodeState[id].r;
94              P2!id,nodeState[id].members,nodeState[id].r
95            ::skip
96
97            fi;
98        }
99
100      :: empty(PR) ->
101           skip
102      :: nempty(PR) ->
103        PR?id_j,members_j,r_j;
104 //     printf("%d Size of channel %d\n", id, len(PR));
105        atomic {
106          if
107           ::nodeState[id].state ==  ALOHA ->
108           nodeState[id].messageLost[id_j] = 0;
109           nodeState[id].members = nodeState[id].members | (1 << id_j);
110           if
111             ::nodeState[id].members == members_j ->
112               nodeState[id].cmembers = nodeState[id].members | (1 << id_j)
113             ::skip
114           fi;
115           if
116             ::nodeState[id].cmembers == members_j ->
117               printf("%d reaches TDMA\n", id);
118               nodeState[id].state = TDMA
119               if
120             ::nodeState[id].leader > members_j ->
121               nodeState[id].leader = members_j
122             ::skip
123               fi;
124               if
125             ::nodeState[id].leader == members_j ->
126               nodeState[id].r = r_j
127             ::skip
128               fi;
129              ::nodeState[id].cmembers != members_j ->
130             skip
131           fi;
132 //         printf("%d --Receiving in ALOHA %d from %d\n" , id,  nodeState[id].members, id_j);
133
134         ::nodeState[id].state !=  ALOHA ->
135 //      printf("%d reaches TDMA\n" , id);
136         nodeState[id].messageLost[id_j] = 0
137
138         fi;
139       }
140       //round
141          // Failure detector
142      :: nodeState[id].state == TDMA &&
143           (nodeState[id].messageLost[0] > 3 || nodeState[id].messageLost[1] > 3 || nodeState[id].messageLost[2] > 3) ->
144           atomic {
145         printf("%d ALOHA from failure Detector\n", id);
146
147         nodeState[id].state = ALOHA;
148         nodeState[id].members = 1 << id;
149         nodeState[id].cmembers = 1 << id;
150         nodeState[id].leader = id
151           }
152 //   :: nodeState[id].round > 0 ->
153 //      nodeState[id].round = (nodeState[id].round + 1) % 2
154      :: nodeState[id].r != id ->
155        // printf("%d in round %d\n" , id, nodeState[id].r);
156         nodeState[id].r =  (nodeState[id].r + 1) % 4
157
158         //nodeState[id].round = (nodeState[id].round + 1) % 2
159      :: skip
160    od;
161 }

Error is pointed at line 57.I am not sure what does this mean. when i run my code on terminal it works fine bt with ispin interface it throws this error. Someone came across this error?

Body:
after spending many hours wandering around the code. i tried hit and trial and removed last skip statement from the model. Seems like many possible alternative guard statements along with additional skip statement made it an unconditional self loop.
It worked when i removed the last ::skip statement from do loop.

It appears that Spin has some very simple mechanism for detecting unconditional self loops caused by some loop guard being equal to skip or true with no subsequent instruction to be executed, e.g.:

init
{
    do
        :: skip            // or true
    od;
}

prints:

~$ spin -search test.pml
error: proctype ':init:' line 4, state 2: has unconditional self-loop

pan: elapsed time 1.76e+07 seconds
pan: rate         0 states/second

The routine can be easily circumvented by adding an extra empty statement:

init
{
    do
        :: skip -> skip            // or true -> true
    od;
}

prints:

~$ spin -search test.pml

(Spin Version 6.4.3 -- 16 December 2014)
    + Partial Order Reduction

Full statespace search for:
    never claim             - (none specified)
    assertion violations    +
    cycle checks            - (disabled by -DSAFETY)
    invalid end states      +

State-vector 12 byte, depth reached 1, errors: 0
        2 states, stored
        1 states, matched
        3 transitions (= stored+matched)
        0 atomic steps
hash conflicts:         0 (resolved)

Stats on memory usage (in Megabytes):
    0.000   equivalent memory usage for states (stored*(State-vector + overhead))
    0.292   actual memory usage for states
  128.000   memory used for hash table (-w24)
    0.534   memory used for DFS stack (-m10000)
  128.730   total actual memory usage

unreached in init
    test.pml:6, state 6, "-end-"
    (1 of 6 states)

pan: elapsed time 0 seconds

Interestingly, the routine fails to consider other obvious cases in which an unconditional self-loop arises, e.g. when the guard is a number different from 0 and there is no re-entrant block of instructions.


来源: stackexchange

问:
How to serve <use> SVG-symbols with Webpack and Vue.js?
I use Webpack in conjunction with Vue.js.
In the map.svg file I store all the SVG icons in the form like this:

```<code><symbol id="someID"><path></symbol>
<symbol id="otherID"><path></symbol>
</code>```

In the code I use a construct like this with SVG4Everybody-plugin:

```<code><svg><use xlink:href="map.svg#someID"></svg>
</code>```

But this does not work, because Webpack does not distribute SVG sprites. What to do in this situation? Thanks!

Webpack 3.6.0
Vue 2.5.2

答:
You must add the SVG sprite to HTML using the <object>

```<code><object type="image/svg+xml" data="map.svg">
   Your browser does not support SVG
</object>
</code>```

Your browser does not support SVG - failback for old browsers

After adding a sprite to the HTML, you can use the icons from the sprite:

```<code><svg viewBox="0 0 24 24">
  <use xlink:href="map.svg#someID">
 </svg>
</code>```

Use the viewBox options to match the size of the icons.

ContentLicense: CC BY-SA 3.0

Body:
I use Webpack in conjunction with Vue.js.
In the map.svg file I store all the SVG icons in the form like this:

<symbol id="someID"><path></symbol>
<symbol id="otherID"><path></symbol>

In the code I use a construct like this with SVG4Everybody-plugin:

<svg><use xlink:href="map.svg#someID"></svg>

But this does not work, because Webpack does not distribute SVG sprites. What to do in this situation? Thanks!

Webpack 3.6.0
Vue 2.5.2

Body:
You must add the SVG sprite to HTML using the <object>

<object type="image/svg+xml" data="map.svg">
   Your browser does not support SVG
</object>

Your browser does not support SVG - failback for old browsers

After adding a sprite to the HTML, you can use the icons from the sprite:

<svg viewBox="0 0 24 24">
  <use xlink:href="map.svg#someID">
 </svg>

Use the viewBox options to match the size of the icons.


答:
The problem with you original query is that you're summing all elements, because GROUP BY id, nts is executed in outer query. Combining a CTE with LATERAL JOIN would do the trick:

```<code>WITH tmp AS (
    SELECT
        id,
        date_trunc('hour', ts + '1 hour') nts,
        sum(elem) AS counts
    FROM
        ts2
        LEFT JOIN LATERAL unnest(counts) WITH ORDINALITY x(elem, rn) ON TRUE
    GROUP BY
        id, nts, rn
)
SELECT id, nts, array_agg(counts) FROM tmp GROUP BY id, nts
</code>```

Title: Summing arrays in conjunction with GROUP BY

Body:
I've got some periodic counter data (like once a second) from different objects that I wish to combine into an hourly total.

If I do it with separate column names, it's pretty straightforward:

CREATE TABLE ts1 (
        id      INTEGER,
        ts      TIMESTAMP,
        count0  integer,
        count1  integer,
        count2  integer
);

INSERT INTO ts1 VALUES
        (1, '2017-12-07 10:37:48', 10, 20, 50),
        (2, '2017-12-07 10:37:48', 13, 7, 88),
        (1, '2017-12-07 10:37:49', 12, 23, 34),
        (2, '2017-12-07 10:37:49', 11, 13, 46),
        (1, '2017-12-07 10:37:50', 8, 33, 80),
        (2, '2017-12-07 10:37:50', 9, 3, 47),
        (1, '2017-12-07 10:37:51', 17, 99, 7),
        (2, '2017-12-07 10:37:51', 9, 23, 96);

SELECT id, date_trunc('hour', ts + '1 hour') nts,
           sum(count0), sum(count1), sum(count2)
    FROM ts1 GROUP BY id, nts;

id |         nts         | sum | sum | sum
----+---------------------+-----+-----+-----
  1 | 2017-12-07 11:00:00 |  47 | 175 | 171
  2 | 2017-12-07 11:00:00 |  42 |  46 | 277
(2 rows)

The problem is that different objects have different numbers of counts (though each particular object's rows -- ones sharing the same ID -- all have the same number of counts). Hence I want to use an array.

The corresponding table looks like this:

CREATE TABLE ts2 (
        id      INTEGER,
        ts      TIMESTAMP,
        counts  INTEGER[]
);

INSERT INTO ts2 VALUES
        (1, '2017-12-07 10:37:48', ARRAY[10, 20, 50]),
        (2, '2017-12-07 10:37:48', ARRAY[13, 7, 88]),
        (1, '2017-12-07 10:37:49', ARRAY[12, 23, 34]),
        (2, '2017-12-07 10:37:49', ARRAY[11, 13, 46]),
        (1, '2017-12-07 10:37:50', ARRAY[8, 33, 80]),
        (2, '2017-12-07 10:37:50', ARRAY[9, 3, 47]),
        (1, '2017-12-07 10:37:51', ARRAY[17, 99, 7]),
        (2, '2017-12-07 10:37:51', ARRAY[9, 23, 96]);

I have looked at this answer https://stackoverflow.com/a/24997565/1076479 and I get the general gist of it, but I cannot figure out how to get the correct rows summed together when I try to combine it with the grouping by id and timestamp.

For example, with this I get all the rows, not just the ones with matching id and timestamp:

SELECT id, date_trunc('hour', ts + '1 hour') nts, ARRAY(
        SELECT sum(elem) FROM ts2 t, unnest(t.counts)
            WITH ORDINALITY x(elem, rn) GROUP BY rn ORDER BY rn
        ) FROM ts2 GROUP BY id, nts;

 id |         nts         |    array
----+---------------------+--------------
  1 | 2017-12-07 11:00:00 | {89,221,448}
  2 | 2017-12-07 11:00:00 | {89,221,448}
(2 rows)

FWIW, I'm using postgresql 9.6

Body:
The problem with you original query is that you're summing all elements, because GROUP BY id, nts is executed in outer query. Combining a CTE with LATERAL JOIN would do the trick:

WITH tmp AS (
    SELECT
        id,
        date_trunc('hour', ts + '1 hour') nts,
        sum(elem) AS counts
    FROM
        ts2
        LEFT JOIN LATERAL unnest(counts) WITH ORDINALITY x(elem, rn) ON TRUE
    GROUP BY
        id, nts, rn
)
SELECT id, nts, array_agg(counts) FROM tmp GROUP BY id, nts


问:
Does ArrayList.java compile without warnings?
Using http://www.docjar.com/html/api/java/util/ArrayList.java.html as reference

```
  111       private transient Object[] elementData;

  381       public E get(int index) {
  382           rangeCheck(index);
  383
  384           return elementData(index);
  385       }
```

On compilation does this result in a warning like "ArrayList.java uses unchecked or unsafe operations."?

答:
elementData(index) is a method call whose return type is E (not to be confused with elementData[index] whose type is Object), and that method casts elementData[index] to E and suppresses the warnings:

```<code>@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}
</code>```

Therefore the code you asked about produces no warnings.

Body:
Using http://www.docjar.com/html/api/java/util/ArrayList.java.html as reference

  111       private transient Object[] elementData;

  381       public E get(int index) {
  382           rangeCheck(index);
  383
  384           return elementData(index);
  385       }

On compilation does this result in a warning like "ArrayList.java uses unchecked or unsafe operations."?

Body:
elementData(index) is a method call whose return type is E (not to be confused with elementData[index] whose type is Object), and that method casts elementData[index] to E and suppresses the warnings:

@SuppressWarnings("unchecked")
E elementData(int index) {
    return (E) elementData[index];
}

Therefore the code you asked about produces no warnings.


问:
Replace None with NaN in pandas dataframe
I have table x:

```<code>        website
0   http://www.google.com/
1   http://www.yahoo.com
2   None
</code>```

I want to replace python None with pandas NaN. I tried:

```<code>x.replace(to_replace=None, value=np.nan)
</code>```

But I got:

```<code>TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'
</code>```

How should I go about it?

答:
The following line replaces None with NaN:

```<code>df['column'].replace('None', np.nan, inplace=True)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have table x:

        website
0   http://www.google.com/
1   http://www.yahoo.com
2   None

I want to replace python None with pandas NaN. I tried:

x.replace(to_replace=None, value=np.nan)

But I got:

TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'

How should I go about it?

Body:
The following line replaces None with NaN:

df['column'].replace('None', np.nan, inplace=True)


问:
NestedScrollView with webView only scrolling NestedScrollView
Below is my code to handle the correct behaviour of my apps actionBar/toolbar/tabBar and nestedScrollView with a ViewPager (webView) inside it. The ViewPager is basically a normal webView.

Everything works fine except my ViewPager can't be scrolled vertically. Only the NestedScrollView is being scrolled. I want the same behaviour as the Facebook app, if you scroll the newsfeed (webView) the tabBar moves the toolbar out of vision vertically.

```<code><android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.activity.FragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    app:theme="@style/M.Toolbar"
                    app:popupTheme="@style/M.Toolbar.PopupTheme"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_scrollFlags="scroll|enterAlways"
                    >
                </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"
            android:visibility="gone"
            android:background="@color/background"
            app:background="@color/background"
            />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="@android:color/transparent"
        android:fillViewport="true"
        >

    <com.m.ui.util.EdgeScrollViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:visibility="visible"
        >

    </com.m.ui.util.EdgeScrollViewPager>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

So in order to be able to scroll my viewPager (webView) I added a new class which extends webView:

public class TouchyWebView extends WebView {

```<code>    public TouchyWebView(Context context) {
        super(context);
    }

    public TouchyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TouchyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        requestDisallowInterceptTouchEvent(true);
        return super.onTouchEvent(event);
    }
}
</code>```

This solves the problem with the viewPager (webView) which becomes scrollable. BUT, the NestedScrollView becomes static and refuses to scroll the tabBar/toolbar vertically. So I am stuck with either scrolling the webView OR the tabBar-toolbar. How do I make both viewPager(webView) and NestedScrollView (tabBar/toolbar) scrollable at the same time ?

My webView

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <com.m.ui.base.TouchyWebView
        android:id="@+id/web_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:visibility="visible" />

    <LinearLayout
        android:id="@+id/web_loadingview"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:layout_gravity="center">

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:visibility="visible"
            android:layout_gravity="center"/>
    </LinearLayout>

</FrameLayout>
</code>```

Regards

答:
I had a similar problem and solved it with setFillViewport (true)
A piece of my code

```<code> NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
    scrollView.setFillViewport (true);
</code>```

And inside the fragment I had a listView where I sat android:nestedScrollingEnabled="true" .. Fixed the scrolling issue

Body:
Below is my code to handle the correct behaviour of my apps actionBar/toolbar/tabBar and nestedScrollView with a ViewPager (webView) inside it. The ViewPager is basically a normal webView.

Everything works fine except my ViewPager can't be scrolled vertically. Only the NestedScrollView is being scrolled. I want the same behaviour as the Facebook app, if you scroll the newsfeed (webView) the tabBar moves the toolbar out of vision vertically.

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ui.activity.FragmentContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    app:theme="@style/M.Toolbar"
                    app:popupTheme="@style/M.Toolbar.PopupTheme"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_scrollFlags="scroll|enterAlways"
                    >
                </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="scrollable"
            android:visibility="gone"
            android:background="@color/background"
            app:background="@color/background"
            />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.widget.NestedScrollView
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="@android:color/transparent"
        android:fillViewport="true"
        >

    <com.m.ui.util.EdgeScrollViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:visibility="visible"
        >

    </com.m.ui.util.EdgeScrollViewPager>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

So in order to be able to scroll my viewPager (webView) I added a new class which extends webView:

public class TouchyWebView extends WebView {

    public TouchyWebView(Context context) {
        super(context);
    }

    public TouchyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TouchyWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        requestDisallowInterceptTouchEvent(true);
        return super.onTouchEvent(event);
    }
}

This solves the problem with the viewPager (webView) which becomes scrollable. BUT, the NestedScrollView becomes static and refuses to scroll the tabBar/toolbar vertically. So I am stuck with either scrolling the webView OR the tabBar-toolbar. How do I make both viewPager(webView) and NestedScrollView (tabBar/toolbar) scrollable at the same time ?

My webView

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white">

    <com.m.ui.base.TouchyWebView
        android:id="@+id/web_webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        android:visibility="visible" />

    <LinearLayout
        android:id="@+id/web_loadingview"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        android:layout_gravity="center">

        <ProgressBar
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:indeterminate="true"
            android:visibility="visible"
            android:layout_gravity="center"/>
    </LinearLayout>

</FrameLayout>

Regards

Body:
I had a similar problem and solved it with setFillViewport (true)
A piece of my code

 NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nest_scrollview);
    scrollView.setFillViewport (true);

And inside the fragment I had a listView where I sat android:nestedScrollingEnabled="true" .. Fixed the scrolling issue


问:
Attempt to invoke virtual method 'void com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])' on a null object reference
I tried to make a Facebook connection, but it seems I made a mistake, and now my Facebook button crashes.

```<code>public class FacebookConnect extends AppCompatActivity {

    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    public String TAG;

    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Profile profile = Profile.getCurrentProfile();
            nextActivity(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            System.out.println("test");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        callbackManager = CallbackManager.Factory.create();
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
                                                       AccessToken currentAccessToken) {
            }
        };
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                nextActivity(currentProfile);
            }
        };
        accessTokenTracker.startTracking();
        profileTracker.startTracking();
        LoginButton loginButton = (LoginButton)findViewById(R.id.facebookSignupButton);
        loginButton.setReadPermissions("user_friends");
        loginButton.registerCallback(callbackManager, callback);
        new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Profile profile = Profile.getCurrentProfile();
                nextActivity(profile);
                Toast.makeText(getApplicationContext(), "Log in", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        };
    }
    @Override
    protected void onResume(){
        super.onResume();
        Profile profile = Profile.getCurrentProfile();
        nextActivity(profile);
    }

    protected void onPause(){
        super.onPause();
    }

    protected void onStop(){
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void nextActivity(Profile profile){
        if (profile != null){
            Intent main = new Intent(this, NavigationActivity.class);
            main.putExtra("name", profile.getFirstName());
            main.putExtra("surname", profile.getLastName());
            main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
            Log.d(TAG, "Connected");
            startActivity(main);
        }
    }
}
</code>```

Do you know how to solve it ?

This is actually the error when I clicked on, I have the same problem when I tried make a google connection too.

12-07 19:54:48.717 3772-3772/com.climb.eip.climb E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.climb.eip.climb, PID: 3772
                                                                         java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.climb.eip.climb/com.climb.eip.climb.utils.FacebookConnect}:
  java.lang.NullPointerException: Attempt to invoke virtual method 'void
  com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])'
  on a null object reference
                                                                             at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                             at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void
  com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])'
  on a null object reference
                                                                             at
  com.climb.eip.climb.utils.FacebookConnect.onCreate(FacebookConnect.java:76)
                                                                             at android.app.Activity.performCreate(Activity.java:6662)
                                                                             at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                             at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

答:
where is ?

```<code>setContentView(R.layout.your_layout);
</code>```

in onCreate()

So add this line with your layout name in onCreate() after

```<code>super.onCreate(savedInstanceState);
</code>```

Body:
I tried to make a Facebook connection, but it seems I made a mistake, and now my Facebook button crashes.

public class FacebookConnect extends AppCompatActivity {

    private CallbackManager callbackManager;
    private AccessTokenTracker accessTokenTracker;
    private ProfileTracker profileTracker;
    public String TAG;

    private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Profile profile = Profile.getCurrentProfile();
            nextActivity(profile);
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onError(FacebookException error) {
            System.out.println("test");
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        callbackManager = CallbackManager.Factory.create();
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
                                                       AccessToken currentAccessToken) {
            }
        };
        profileTracker = new ProfileTracker() {
            @Override
            protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
                nextActivity(currentProfile);
            }
        };
        accessTokenTracker.startTracking();
        profileTracker.startTracking();
        LoginButton loginButton = (LoginButton)findViewById(R.id.facebookSignupButton);
        loginButton.setReadPermissions("user_friends");
        loginButton.registerCallback(callbackManager, callback);
        new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Profile profile = Profile.getCurrentProfile();
                nextActivity(profile);
                Toast.makeText(getApplicationContext(), "Log in", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onError(FacebookException error) {

            }
        };
    }
    @Override
    protected void onResume(){
        super.onResume();
        Profile profile = Profile.getCurrentProfile();
        nextActivity(profile);
    }

    protected void onPause(){
        super.onPause();
    }

    protected void onStop(){
        super.onStop();
        accessTokenTracker.stopTracking();
        profileTracker.stopTracking();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void nextActivity(Profile profile){
        if (profile != null){
            Intent main = new Intent(this, NavigationActivity.class);
            main.putExtra("name", profile.getFirstName());
            main.putExtra("surname", profile.getLastName());
            main.putExtra("imageUrl", profile.getProfilePictureUri(200,200).toString());
            Log.d(TAG, "Connected");
            startActivity(main);
        }
    }
}

Do you know how to solve it ?

This is actually the error when I clicked on, I have the same problem when I tried make a google connection too.

12-07 19:54:48.717 3772-3772/com.climb.eip.climb E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.climb.eip.climb, PID: 3772
                                                                         java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.climb.eip.climb/com.climb.eip.climb.utils.FacebookConnect}:
  java.lang.NullPointerException: Attempt to invoke virtual method 'void
  com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])'
  on a null object reference
                                                                             at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                             at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
                                                                          Caused by: java.lang.NullPointerException: Attempt to invoke virtual
  method 'void
  com.facebook.login.widget.LoginButton.setReadPermissions(java.lang.String[])'
  on a null object reference
                                                                             at
  com.climb.eip.climb.utils.FacebookConnect.onCreate(FacebookConnect.java:76)
                                                                             at android.app.Activity.performCreate(Activity.java:6662)
                                                                             at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                             at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                             at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                             at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                             at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

Body:
where is ?

setContentView(R.layout.your_layout);

in onCreate()

So add this line with your layout name in onCreate() after

super.onCreate(savedInstanceState);


问:
Golang map containing both string and integer
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

```<code>{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

instead of

```<code>{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
</code>```

I am using:

```<code>var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)
</code>```

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

答:
If you cannot describe your data with a properly typed struct then consider using a map with values of type interface{} (essentially any type):

```<code>output_map := map[string]map[string]interface{}{}
</code>```

For example:

```<code>output_map := map[string]map[string]interface{}{
  "age": {
    "$gt": 18,
  },
  "location": {
    "eq": "London",
  },
}
bytes, err := json.MarshalIndent(&output_map, "", "  ")
if err != nil {
  panic(err)
}
// {
//   "age": {
//     "$gt": 18
//   },
//   "location": {
//     "eq": "London"
//   }
// }
</code>```

Of course, using the interface{} type is not a best-practice; however, it's sometimes the only way to accomplish certain things.

Body:
I am trying to create a JSON string from a map using JSON.Marshal() in golang. However, the int values are being displayed as strings surrounded by double quotes.

My code is outputting:

{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

instead of

{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}

I am using:

var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)

My understanding is that JSON.Marshal() will print the integers correctly if they are supplied but my map won't contain integers. I could change my map to map[string]map[string]int{} but then it wouldn't contain the string values for 'name' and 'location'.

The ultimate problem is that I need the map to contain both int and string values. Some sort of map[string]map[string]{}.

How can I achieve this? Thank you in advance.

Harry

Body:
If you cannot describe your data with a properly typed struct then consider using a map with values of type interface{} (essentially any type):

output_map := map[string]map[string]interface{}{}

For example:

output_map := map[string]map[string]interface{}{
  "age": {
    "$gt": 18,
  },
  "location": {
    "eq": "London",
  },
}
bytes, err := json.MarshalIndent(&output_map, "", "  ")
if err != nil {
  panic(err)
}
// {
//   "age": {
//     "$gt": 18
//   },
//   "location": {
//     "eq": "London"
//   }
// }

Of course, using the interface{} type is not a best-practice; however, it's sometimes the only way to accomplish certain things.


问:
Should I use the  element?
I've stumbled about the  element on w3schools but as far as caniuse.com told me, the element isn't supported by IE, Opera Mini and the UC Browser for Android.

Would I be better by going with a  element or should I stick with a
?

答:
caniuse.com told me, the element isn't supported by IE, Opera Mini and the UC Browser for Android

That isn't what it says.

It says "Partial support" and:

Partial support refers to missing the default styling, as technically the elements are considered "unknown". This is easily taken care of by manually setting the default display value for each tag

So if main has the appropriate semantics, then use it. Just make sure to explicitly set display: block.

If the browser doesn't expose the semantics of using main then it will have no semantics, which is the same as a div.

Title: Should I use the <main> element?


问:
How can I convert a string, such as "iso-8859-1", to it's String.Encoding counterpart?
After sending a HTTP request from Swift, I get a field in the response called textEncodingName.

I want to convert the data object I also received into a string containing its contents, and to do this, I'm using String(data: data!, encoding: .utf8). This works most of the time, because most websites are UTF-8 encoded. But with, for example, https://www.google.co.uk, the response.textEncodingName == "iso-8859-1".

I guess other websites would use even more obscure encodings, so my question is this: how can I find the right encoding to convert my data object to the correct string.

答:
In swift you can use:</p>

```<code>func getTextFrom(_ url: URL) -> String?  {
    guard let data = try? Data(contentsOf: url) else {
        return nil
    }
    return String(data: data, encoding: .utf8) ??
        String(data: data, encoding: .isoLatin1)
}
</code>```

Body:
In swift you can use:

func getTextFrom(_ url: URL) -> String?  {
    guard let data = try? Data(contentsOf: url) else {
        return nil
    }
    return String(data: data, encoding: .utf8) ??
        String(data: data, encoding: .isoLatin1)
}


问:
IONIC 3 new local storage
I want to create a new localstorage in my ionic app (IONIC 3), but I've looked many ways to do that. I currently have this:

database.ts (my provider)

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Storage } from '@ionic/storage';

@Injectable()
export class DatabaseProvider {

  localData: Storage;

  constructor(public http: HttpClient) {

    this.localData = new Storage(localStorage);
  }

}
</code>```

but the IDE told me that it's a mistake in the line "this.localData = new Storage(localStorage);" maybe it requires a special import. I have installed the "@ionic/storage": "2.1.3".

Thanks for your help!

答:
You do not need to provide an argument to storage constructor unless you want to specify settings like the perferred db.
Here is an example of using Storage in a provider-

LocalNotes.ts

```<code>import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';

@Injectable()
export class LocalNotes {
  local:any;

  constructor() {
    this.local = new Storage();
  }

  getNotes() {
    return new Promise((resolve, reject)=> {
      this.local.get('userNotes')
        .then((answer)=> {
          resolve(answer);
        })
        .catch((err) => {
          reject(err);
          });
      });
  }

  setNotes(notes:string[]) {
    this.local.set('userNotes', notes);
  }
}
</code>```

Title: IONIC 3 new local storage

Body:
I want to create a new localstorage in my ionic app (IONIC 3), but I've looked many ways to do that. I currently have this:

database.ts (my provider)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

import { Storage } from '@ionic/storage';

@Injectable()
export class DatabaseProvider {

  localData: Storage;

  constructor(public http: HttpClient) {

    this.localData = new Storage(localStorage);
  }

}

but the IDE told me that it's a mistake in the line "this.localData = new Storage(localStorage);" maybe it requires a special import. I have installed the "@ionic/storage": "2.1.3".

Thanks for your help!

Body:
You do not need to provide an argument to storage constructor unless you want to specify settings like the perferred db.
Here is an example of using Storage in a provider-

LocalNotes.ts

import {Injectable} from '@angular/core';
import {Storage} from '@ionic/storage';

@Injectable()
export class LocalNotes {
  local:any;

  constructor() {
    this.local = new Storage();
  }

  getNotes() {
    return new Promise((resolve, reject)=> {
      this.local.get('userNotes')
        .then((answer)=> {
          resolve(answer);
        })
        .catch((err) => {
          reject(err);
          });
      });
  }

  setNotes(notes:string[]) {
    this.local.set('userNotes', notes);
  }
}


问:
Mage::app()->getLayout()->getBlock('content'); returns false Magento 1.9
I am trying to add a block dynamically after the content, the block should load in every category and every product page and base on the category title or page title load some data from database and show.

I use controller_action_layout_load_before, and inside the method in observer class,

```<code>Mage::app()->getLayout()->getBlock('content');
</code>```

returns false instead of an object.
I have to implement it for a client as a Magento module, I have no access to their template, I am using Magento 1.9 rwd/default

答:
I think that using controller_action_layout_load_before is not good; it is too early because the XML layout is not built yet.

Try to use event controller_action_layout_generate_xml_before.

Or maybe adding your own XML layout could be better solution. See http://alanstorm.com/adding-additional-layout-xml-updates-via-modules/

Body:
I am trying to add a block dynamically after the content, the block should load in every category and every product page and base on the category title or page title load some data from database and show.

I use controller_action_layout_load_before, and inside the method in observer class,

Mage::app()->getLayout()->getBlock('content');

returns false instead of an object.
I have to implement it for a client as a Magento module, I have no access to their template, I am using Magento 1.9 rwd/default


问:
C++ cross-compiler from Windows to Linux
Are there any user friendly tools out there to cross-compile from Windows to Linux?</p>

答: I don't believe there are any compilers that allow you to compile on Windows and then take the resulting binary and run it on a Linux machine.  Your best bet is to set up two development environments, one on Windows and one on Linux.  Do most of your development and debugging in the Windows environment if that's what suits you, then frequently compile and test under Linux to be sure your code is truly cross-platform.  You'll also want to use a cross-platform build system and testing framework.  I recommend using cmake and Google Test, respectively.</p>

ContentLicense: CC BY-SA 2.5


问:
Multiple Constrain Knapsack
I'm trying to solve the following problem:

INPUT:

An array of items, each item has 3 different weights (integers), a value and the amount available of this type of item.

A maximum for each type of weight

OUTPUT:

An array that tells how many of each item to take in order to achieve the maximum value. The sum of each of the weights of every item must not exceed the maximum allowed and you may not take more of an item of what is available.

Example output: {3,0,2,1} means 3 of item1, 0 of item2, 2 of item3, and 1 of item4.

Example scenario:

In case I wasn't very clear with the explanation, imagine it's about putting food on a backpack. Each type of food has a weight, a volume, a number of calories and a value and there's a certain amount of each type of food available. The objective would be to maximize the value of the food in the backpack without exceeding a certain maximum amount of weight, volume and calories.

On this scenario the INPUT could be:

```<code>Array<Food>:
</code>```

Burger (Weight 2, Volume 2, Calories 5, Value 5$, number of Burgers 3)

Pizza (Weight 3, Volume 7, Calories 6, Value 8$, number of Pizzas 2)

Hot Dog (Weight 1, Volume 1, Calories 3, Value 2$, number of Hot Dogs 6)

int MaxWeight = 10; int MaxVolume = 15; int MaxCalories = 10;

My Attempt

Since the data set is quite small (say 7 types of items and there's no more than 15 pieces of each item available), I thought of a brute force search:

Keep track of the best set found so far (Most value and doesn't
exceed any limits), call best set B

Have a recursive function R(s) which takes a set (array of how many of each item) as input, if the input is invalid, it returns. If the input is valid it first updates B (in case s better than B) and then calls R(s + p_i) for every product p_i

The idea is to first call R(s) with s = empty set (0 for every product) and every possible branch will be created while the branches that exceed the weights are ignored.

This obviously didn't work cause the amount of branches that have to be checked is huge even for only as few as 7 items

Any help is much appreciated!

答:
You have to consider each type of weight in your DP method. I'll write the implementation in C++:

```<code>vector<Food> Array;
int memo[MAX_ITEM][MAX_WEIGHT1][MAX_WEIGHT2][MAX_WEIGHT3];
int f(int ind, int weight1, int weight2, int weight3){
    if(weight1<0 || weight2<0 || weight3<0) return -INF;
    if(ind == Array.size()) return 0;
    int &ret= memo[ind][weight1][weight2][weight3];
    if(ret>0) return ret;
    int res = 0;
    for(int i=0;i<=Array[ind].maxOfType;i++)
        res = max(res, i * Array[ind].value + f(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3));
    return ret = res;
}
</code>```

The DP function is recursive and we use memoization to optimize it. It returns the maximum value we can get. you can call it by:

```<code>f(0,MaxWeight1, MaxWeight2, MaxWeight3);
</code>```

After that we have to track and see which items leads to maximum value. The Next method will print what you want:

```<code>void printResult(int ind, int weight1, int weight2, int weight3){
        if(ind == Array.size()) return;
        int maxi = memo[ind][weight1][weight2][weight3];
        for(int i=0;i<=Array[ind].maxOfType;i++){
            int cur = i * Array[ind].value + f(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3);
            if(cur == maxi){
                cout<<i<<", ";
                printResult(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3);
                break;
            }
        }
}
</code>```

All codes are tested and works well.

Title: Multiple Constrain Knapsack

Body:
I'm trying to solve the following problem:

INPUT:

An array of items, each item has 3 different weights (integers), a value and the amount available of this type of item.

A maximum for each type of weight

OUTPUT:

An array that tells how many of each item to take in order to achieve the maximum value. The sum of each of the weights of every item must not exceed the maximum allowed and you may not take more of an item of what is available.

Example output: {3,0,2,1} means 3 of item1, 0 of item2, 2 of item3, and 1 of item4.

Example scenario:

In case I wasn't very clear with the explanation, imagine it's about putting food on a backpack. Each type of food has a weight, a volume, a number of calories and a value and there's a certain amount of each type of food available. The objective would be to maximize the value of the food in the backpack without exceeding a certain maximum amount of weight, volume and calories.

On this scenario the INPUT could be:

Array<Food>:

Burger (Weight 2, Volume 2, Calories 5, Value 5$, number of Burgers 3)

Pizza (Weight 3, Volume 7, Calories 6, Value 8$, number of Pizzas 2)

Hot Dog (Weight 1, Volume 1, Calories 3, Value 2$, number of Hot Dogs 6)

int MaxWeight = 10; int MaxVolume = 15; int MaxCalories = 10;

My Attempt

Since the data set is quite small (say 7 types of items and there's no more than 15 pieces of each item available), I thought of a brute force search:

Keep track of the best set found so far (Most value and doesn't
exceed any limits), call best set B

Have a recursive function R(s) which takes a set (array of how many of each item) as input, if the input is invalid, it returns. If the input is valid it first updates B (in case s better than B) and then calls R(s + p_i) for every product p_i

The idea is to first call R(s) with s = empty set (0 for every product) and every possible branch will be created while the branches that exceed the weights are ignored.

This obviously didn't work cause the amount of branches that have to be checked is huge even for only as few as 7 items

Any help is much appreciated!

Body:
You have to consider each type of weight in your DP method. I'll write the implementation in C++:

vector<Food> Array;
int memo[MAX_ITEM][MAX_WEIGHT1][MAX_WEIGHT2][MAX_WEIGHT3];
int f(int ind, int weight1, int weight2, int weight3){
    if(weight1<0 || weight2<0 || weight3<0) return -INF;
    if(ind == Array.size()) return 0;
    int &ret= memo[ind][weight1][weight2][weight3];
    if(ret>0) return ret;
    int res = 0;
    for(int i=0;i<=Array[ind].maxOfType;i++)
        res = max(res, i * Array[ind].value + f(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3));
    return ret = res;
}

The DP function is recursive and we use memoization to optimize it. It returns the maximum value we can get. you can call it by:

f(0,MaxWeight1, MaxWeight2, MaxWeight3);

After that we have to track and see which items leads to maximum value. The Next method will print what you want:

void printResult(int ind, int weight1, int weight2, int weight3){
        if(ind == Array.size()) return;
        int maxi = memo[ind][weight1][weight2][weight3];
        for(int i=0;i<=Array[ind].maxOfType;i++){
            int cur = i * Array[ind].value + f(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3);
            if(cur == maxi){
                cout<<i<<", ";
                printResult(ind+1, weight1-i*Array[ind].weight1, weight2-i*Array[ind].weight2, weight3-i*Array[ind].weight3);
                break;
            }
        }
}

All codes are tested and works well.


问:
Include header files without ".h" format
I know that to include headers you must type #include .

Is there a way to include the header as #include , like we do with iostream or cstdlib?

答:
Just rename header.h to header. The files iostream, cstdlib, etc are files with exactly those names that don't have any extension. For example, here is a screenshot of Visual Studio's iostream file in Windows Explorer:

Usually when you create your own header file it has the extension .h (or sometimes .hpp), but nothing in the C++ standard forces them to have any specific extension. You can include a file with any you want as long as its contents is valid C++. Some libraries like the C++ standard library or Qt don't have any extension on their header files just to make your code look nice. Most IDEs automatically add a .h extension when you create a header file because .h is the extension that header files usually have, but that's just a convention, you can give them any extension you want.


问:
clean() method in model and field validation
I have a problem with a model's clean() method and basic field validation. here's my model and the clean() method.

```<code>class Trial(models.Model):

    trial_start = DurationField()
    movement_start = DurationField()
    trial_stop = DurationField()

    def clean(self):
        from django.core.exceptions import ValidationError
        if not (self.movement_start >= self.trial_start):
            raise ValidationError('movement start must be >= trial start')
        if not (self.trial_stop >= self.movement_start):
            raise ValidationError('trial stop must be >= movement start')
        if not (self.trial_stop > self.trial_start):
            raise ValidationError('trial stop must be > trial start')
</code>```

My clean() method checks whether certain values are in the correct range. If the user forget to fill out a field, e.g. movement_start, then I get an error:

can't compare datetime.timedelta to NoneType

I'm surprised that I get this error, since the original clean() function should be catching that missing entry (after all movement_start is a required field). So how can I the basic checking for missing values, and my custom check whether values are in certain ranges? Can this be done with model's clean() method, or do I need to use Forms?

EDIT1 to make it more clear: trial_start, movement_start and trial_stop are all required fields. I need to write a clean() method which first checks that all three fields have been filled out, and then, check whether the values are in a certain range.

The following code for example DOES NOT work, since trial_start might be empty. I want to avoid having to check for the existence of each field - django should do that for me.

```<code>class TrialForm(ModelForm):

    class Meta:
        model = Trial

    def clean_movement_start(self):
        movement_start = self.cleaned_data["movement_start"]
        trial_start = self.cleaned_data["trial_start"]
        if not (movement_start >= trial_start):
            raise forms.ValidationError('movement start must be >= trial start')
        return self.cleaned_data["movement_start"]
</code>```

EDIT2  The reason that I wanted to add this check to the model's clean() method is that objects that are created on the python shell, will automatically be checked for correct values. A form will be fine for views, but I need the value check also for the shell.

答:
I know this is late, but to answer why this might be happening for people who end up here: There's no "original clean". The clean method is a hook for custom validation, so you are the one who provides its code. Not sure how OP was using the clean hook, but: After defining it you should be calling full_clean() over your models so that Django runs model validation in its entirety. See the details in the docs for the order in which it calls the different validation methods and such https://docs.djangoproject.com/en/1.11/ref/models/instances/#validating-objects (perhaps important to note: full_clean() isn't automatically called by a model's save() which is part of why when you use the shell and save straight away you'll be skipping the validation)

(note ModelForms also have various validation steps and will call a model's full_clean: https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#validation-on-a-modelform )

Body:
I have a problem with a model's clean() method and basic field validation. here's my model and the clean() method.

class Trial(models.Model):

    trial_start = DurationField()
    movement_start = DurationField()
    trial_stop = DurationField()

    def clean(self):
        from django.core.exceptions import ValidationError
        if not (self.movement_start >= self.trial_start):
            raise ValidationError('movement start must be >= trial start')
        if not (self.trial_stop >= self.movement_start):
            raise ValidationError('trial stop must be >= movement start')
        if not (self.trial_stop > self.trial_start):
            raise ValidationError('trial stop must be > trial start')

My clean() method checks whether certain values are in the correct range. If the user forget to fill out a field, e.g. movement_start, then I get an error:

can't compare datetime.timedelta to NoneType

I'm surprised that I get this error, since the original clean() function should be catching that missing entry (after all movement_start is a required field). So how can I the basic checking for missing values, and my custom check whether values are in certain ranges? Can this be done with model's clean() method, or do I need to use Forms?

EDIT1 to make it more clear: trial_start, movement_start and trial_stop are all required fields. I need to write a clean() method which first checks that all three fields have been filled out, and then, check whether the values are in a certain range.

The following code for example DOES NOT work, since trial_start might be empty. I want to avoid having to check for the existence of each field - django should do that for me.

class TrialForm(ModelForm):

    class Meta:
        model = Trial

    def clean_movement_start(self):
        movement_start = self.cleaned_data["movement_start"]
        trial_start = self.cleaned_data["trial_start"]
        if not (movement_start >= trial_start):
            raise forms.ValidationError('movement start must be >= trial start')
        return self.cleaned_data["movement_start"]

EDIT2  The reason that I wanted to add this check to the model's clean() method is that objects that are created on the python shell, will automatically be checked for correct values. A form will be fine for views, but I need the value check also for the shell.


问:
java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource in IntelliJ while it works fine in Eclipse
I made a simple Java EE app, and I have a problem with connection to database.
In eclipse everything works fine, but when I try the same in Intellij errors occur.

```<code>package db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class DbUtil {
private static DbUtil dbUtil;
private ComboPooledDataSource connectionPool;

private DbUtil() throws PropertyVetoException {
    connectionPool = new ComboPooledDataSource();
    connectionPool.setDriverClass("com.mysql.jdbc.Driver");
    connectionPool.setJdbcUrl("jdbc:mysql://localhost:3306/world");
    connectionPool.setUser("root");
    connectionPool.setPassword("root");

    connectionPool.setInitialPoolSize(5);
    connectionPool.setMinPoolSize(5);
    connectionPool.setMaxPoolSize(20);
    connectionPool.setAcquireIncrement(5);
    connectionPool.setMaxIdleTime(3600);
}

public Connection getConnection() throws SQLException {
    return connectionPool.getConnection();
}

public void close() {
    connectionPool.close();
}

public static DbUtil getInstance() {
    if (dbUtil == null) {
        try {
            dbUtil = new DbUtil();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
    return dbUtil;
}
  }
</code>```

In project structure - > libraries I have:
image

And the errors are:

```<code>java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/ComboPooledDataSource
java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource
</code>```

答:
Just add this dependencies to pom file</p>

```<code>    <dependency>
        <groupId>com.google.code.maven-play-plugin.com.mchange</groupId>
        <artifactId>c3p0-oracle-thin-extras</artifactId>
        <version>0.9.5</version>
    </dependency>

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>mchange-commons-java</artifactId>
        <version>0.2.11</version>
    </dependency>

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
</code>```

Body:
I made a simple Java EE app, and I have a problem with connection to database.
In eclipse everything works fine, but when I try the same in Intellij errors occur.

package db;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

public class DbUtil {
private static DbUtil dbUtil;
private ComboPooledDataSource connectionPool;

private DbUtil() throws PropertyVetoException {
    connectionPool = new ComboPooledDataSource();
    connectionPool.setDriverClass("com.mysql.jdbc.Driver");
    connectionPool.setJdbcUrl("jdbc:mysql://localhost:3306/world");
    connectionPool.setUser("root");
    connectionPool.setPassword("root");

    connectionPool.setInitialPoolSize(5);
    connectionPool.setMinPoolSize(5);
    connectionPool.setMaxPoolSize(20);
    connectionPool.setAcquireIncrement(5);
    connectionPool.setMaxIdleTime(3600);
}

public Connection getConnection() throws SQLException {
    return connectionPool.getConnection();
}

public void close() {
    connectionPool.close();
}

public static DbUtil getInstance() {
    if (dbUtil == null) {
        try {
            dbUtil = new DbUtil();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }
    return dbUtil;
}
  }

In project structure - > libraries I have:
image

And the errors are:

java.lang.NoClassDefFoundError: com/mchange/v2/c3p0/ComboPooledDataSource
java.lang.ClassNotFoundException: com.mchange.v2.c3p0.ComboPooledDataSource

Body:
Just add this dependencies to pom file

    <dependency>
        <groupId>com.google.code.maven-play-plugin.com.mchange</groupId>
        <artifactId>c3p0-oracle-thin-extras</artifactId>
        <version>0.9.5</version>
    </dependency>

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>mchange-commons-java</artifactId>
        <version>0.2.11</version>
    </dependency>

    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>


问:
Angular prerendering times out with setInterval()
I have a Visual Studio 2017 .NET Core 2.0 project with Angular template. Angular prerendering times out when I uncomment either of the "this.SetUpRefreshInterval()" lines below. The app returns error "NodeInvocationException: Prerendering timed out after 30000ms because the boot function in 'ClientApp/dist/main-server' returned a promise that did not resolve or reject. Make sure that your boot function always resolves or rejects its promise." Any ideas?

Here's the component code:

```<code>import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-currentdatetime',
templateUrl: './currentdatetime.component.html',
styleUrls: ['./currentdatetime.component.css']
})
export class CurrentDateTimeComponent implements OnInit {
    private currentDateTime: Date;

    constructor() {
        this.refreshDate();
        //this.setUpRefreshInterval();
    }

    get currentDateFormatted(): String {
        return this.currentDateTime.toLocaleDateString();
    };

    get currentTimeFormatted(): String {
        return this.currentDateTime.toLocaleTimeString();
    };

    ngOnInit(): void {
        //this.setUpRefreshInterval();
    }

    private setUpRefreshInterval(): void {
        setInterval(() => {
            this.refreshDate();
        }, 1000);
    }

    private refreshDate(): void {
        this.currentDateTime = new Date();
    }
}
</code>```

I also tried using Observable.timer and got the same result:

```<code>    private setUpRefreshInterval(): void {
        let timer = Observable.timer(0, 1000);
        timer.subscribe(t => this.currentDateTime = new Date());
    }
</code>```

As a workaround, I used Krishnanunni's suggestion and made this change, which works:

```<code>import { Component, OnInit, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';

constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.refreshDate();
}

ngOnInit(): void {
    // setting up the refresh interval caused a timeout in prerendering, so only set up interval if rendering in browser
    if (isPlatformBrowser(this.platformId)) {
        this.setUpRefreshInterval();
    }
}
</code>```

答: Wrap the interval code in isPlatformBrowser condition so that it is not pre-rendered</p>

Body:
I have a Visual Studio 2017 .NET Core 2.0 project with Angular template. Angular prerendering times out when I uncomment either of the "this.SetUpRefreshInterval()" lines below. The app returns error "NodeInvocationException: Prerendering timed out after 30000ms because the boot function in 'ClientApp/dist/main-server' returned a promise that did not resolve or reject. Make sure that your boot function always resolves or rejects its promise." Any ideas?

Here's the component code:

import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-currentdatetime',
templateUrl: './currentdatetime.component.html',
styleUrls: ['./currentdatetime.component.css']
})
export class CurrentDateTimeComponent implements OnInit {
    private currentDateTime: Date;

    constructor() {
        this.refreshDate();
        //this.setUpRefreshInterval();
    }

    get currentDateFormatted(): String {
        return this.currentDateTime.toLocaleDateString();
    };

    get currentTimeFormatted(): String {
        return this.currentDateTime.toLocaleTimeString();
    };

    ngOnInit(): void {
        //this.setUpRefreshInterval();
    }

    private setUpRefreshInterval(): void {
        setInterval(() => {
            this.refreshDate();
        }, 1000);
    }

    private refreshDate(): void {
        this.currentDateTime = new Date();
    }
}

I also tried using Observable.timer and got the same result:

    private setUpRefreshInterval(): void {
        let timer = Observable.timer(0, 1000);
        timer.subscribe(t => this.currentDateTime = new Date());
    }

As a workaround, I used Krishnanunni's suggestion and made this change, which works:

import { Component, OnInit, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID } from '@angular/core';

constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    this.refreshDate();
}

ngOnInit(): void {
    // setting up the refresh interval caused a timeout in prerendering, so only set up interval if rendering in browser
    if (isPlatformBrowser(this.platformId)) {
        this.setUpRefreshInterval();
    }
}


问:
How do I fix the pop_front and pop_back functions?
I am making a double linked list in C++ and I am getting an exception when I run the code. The exception is Exception Thrown: Write access violation. This->head was nullptr.

I am confused by what this means and the program crashes after this error.

Here is my code:

```<code>#include <iostream>
#include "My_list.h"

template<typename T>
My_list<T>::My_list()
{
    head = nullptr;
    tail = nullptr;
    size = 0;
    empty = true;
}

template<typename T>
My_list<T>::~My_list()
{
    while (head)
    {
        My_node<T>* next_node = head->next;
        delete head;
        size--;
        head = next_node;
    }
}

template<typename T>
My_list<T>::My_list(const My_list<T>& copy_list)
{
    size = copy_list.size;
    head = copy_list.head;
    tail = copy_list.tail;
    while (copy_list.head)
    {
        My_node<T>* next = copy_list->head->next;
        head->next = copy_list->next;
        size++;
        head = next;
    }
}

template<typename T>
My_list<T>::My_list(const My_list&& new_list)
{
    //add
}

template<typename T>
void My_list<T>::push_front(T data)
{
    My_node<T>* new_node = new My_node<T>(data);
    new_node->next = nullptr;
    new_node.previous = nullptr;

    if (is_empty())
    {
        head = new_node;
        tail = head;
        size++;
        empty = false;

    }
    else
    {
        head->previous = new_node;
        new_node->next = head;
        head = new_node;
        size++;
        empty = false;
    }
}

template<typename T>
void My_list<T>::push_back(T data)
{
    My_node<T>* new_node = new My_node<T>(data);
    new_node->previous = nullptr;
    new_node->next = nullptr;

    if (is_empty())
    {
        head = new_node;
        tail = head;
        size++;
        empty = false;
    }
    else
    {
        tail->next = new_node;
        new_node->previous = tail;
        tail = new_node;
        size++;
        empty = false;
    }
}
template<typename T>
T My_list<T>::pop_front()
{
    if (!is_empty())
    {
        My_node<T>* temp = head;
        head = head->next;
        head->previous = nullptr;
        size--;
        return temp->get_data();
    }
    else
        cout << "The list is empty and cannot pop anything from it" << endl;
}

template<typename T>
T My_list<T>::pop_back()
{
    if (!is_empty())
    {
        My_node<T>* temp = tail;
        tail = tail->previous;
        tail->next = nullptr;
        size--;
        return temp->get_data();
    }
}

template<typename T>
T My_list<T>::front()
{
    return head->get_data();
}

template<typename T>
T My_list<T>::back()
{
    return tail->get_data();
}

template <typename T>
bool My_list<T>::is_empty()
{
    if (empty)
    {
        return true;
    }
    else
        return false;
}
</code>```

the main file:

```<code>#include <iostream>
#include "My_list.h"
#include "My_node.h"
#include "My_node.cpp"
#include "My_list.cpp"
using namespace std;

int main()
{
    //list<int> list1;

    //list1.push_back(12);

    //cout << list1.front() << endl;
    My_list<int> list;
    list.push_back(22);

    cout << list.front() << endl;

    cout << "BEFORE POP" << endl;
    cout << list.pop_front() << endl;
    cout << "we did it!" << endl;

    cin.get();
    return 0;
}
</code>```

I realize there may be other things wrong with the code that I haven't gotten to fixing yet. i just want to get the basic pop, push functions working and then can fix the other problems. Perhaps the issue is with one of my other functions like the copy constructor? If you notice anything else worth fixing that would be great!

Thanks.

答:
pop_front and pop_back use is_empty() but never update empty. So once an element is added, those methods never think the list is empty, thus the de-referencing of the null pointer.

You need to modify pop_front and pop_back to check if the list will be empty after the item removal, and if so, set empty to true.

An alternate solution would be to change is_empty() to look at head and tail to determine if the list is empty. This way would remove the need to have the empty member.

Body:
I am making a double linked list in C++ and I am getting an exception when I run the code. The exception is Exception Thrown: Write access violation. This->head was nullptr.

I am confused by what this means and the program crashes after this error.

Here is my code:

#include <iostream>
#include "My_list.h"

template<typename T>
My_list<T>::My_list()
{
    head = nullptr;
    tail = nullptr;
    size = 0;
    empty = true;
}

template<typename T>
My_list<T>::~My_list()
{
    while (head)
    {
        My_node<T>* next_node = head->next;
        delete head;
        size--;
        head = next_node;
    }
}

template<typename T>
My_list<T>::My_list(const My_list<T>& copy_list)
{
    size = copy_list.size;
    head = copy_list.head;
    tail = copy_list.tail;
    while (copy_list.head)
    {
        My_node<T>* next = copy_list->head->next;
        head->next = copy_list->next;
        size++;
        head = next;
    }
}

template<typename T>
My_list<T>::My_list(const My_list&& new_list)
{
    //add
}

template<typename T>
void My_list<T>::push_front(T data)
{
    My_node<T>* new_node = new My_node<T>(data);
    new_node->next = nullptr;
    new_node.previous = nullptr;

    if (is_empty())
    {
        head = new_node;
        tail = head;
        size++;
        empty = false;

    }
    else
    {
        head->previous = new_node;
        new_node->next = head;
        head = new_node;
        size++;
        empty = false;
    }
}

template<typename T>
void My_list<T>::push_back(T data)
{
    My_node<T>* new_node = new My_node<T>(data);
    new_node->previous = nullptr;
    new_node->next = nullptr;

    if (is_empty())
    {
        head = new_node;
        tail = head;
        size++;
        empty = false;
    }
    else
    {
        tail->next = new_node;
        new_node->previous = tail;
        tail = new_node;
        size++;
        empty = false;
    }
}
template<typename T>
T My_list<T>::pop_front()
{
    if (!is_empty())
    {
        My_node<T>* temp = head;
        head = head->next;
        head->previous = nullptr;
        size--;
        return temp->get_data();
    }
    else
        cout << "The list is empty and cannot pop anything from it" << endl;
}

template<typename T>
T My_list<T>::pop_back()
{
    if (!is_empty())
    {
        My_node<T>* temp = tail;
        tail = tail->previous;
        tail->next = nullptr;
        size--;
        return temp->get_data();
    }
}

template<typename T>
T My_list<T>::front()
{
    return head->get_data();
}

template<typename T>
T My_list<T>::back()
{
    return tail->get_data();
}

template <typename T>
bool My_list<T>::is_empty()
{
    if (empty)
    {
        return true;
    }
    else
        return false;
}

the main file:

#include <iostream>
#include "My_list.h"
#include "My_node.h"
#include "My_node.cpp"
#include "My_list.cpp"
using namespace std;

int main()
{
    //list<int> list1;

    //list1.push_back(12);

    //cout << list1.front() << endl;
    My_list<int> list;
    list.push_back(22);

    cout << list.front() << endl;

    cout << "BEFORE POP" << endl;
    cout << list.pop_front() << endl;
    cout << "we did it!" << endl;

    cin.get();
    return 0;
}

I realize there may be other things wrong with the code that I haven't gotten to fixing yet. i just want to get the basic pop, push functions working and then can fix the other problems. Perhaps the issue is with one of my other functions like the copy constructor? If you notice anything else worth fixing that would be great!

Thanks.


问:
Specified key was too long - max key length is 767 bytes
When I executed the following command:

```<code>create table assessment (
    id integer not null auto_increment unique,
    assignment_weight_type tinyint not null,
    description varchar(255),
    end_date datetime not null,
    from_grade tinyint not null,
    f_id tinyint not null,
    name varchar(255) not null,
    start_date datetime not null,
    status tinyint not null,
    weight smallint,
    school_id integer not null,
    school_year_id integer not null,
    s_id integer, primary key (id),
    unique (name, school_id, school_year_id, from_grade, f_id)
) ENGINE=InnoDB;
</code>```

I got this error message:

```<code>Specified key was too long; max key length is 767 bytes
</code>```

I am using a charset of utf8mb4. So why did I get the error message?

答:
I was also getting same issue,i SET value for these variable in mysql as below and its fixed the issue.

1.global.innodb_large_prefix = 1

2.innodb_file_format=Barracuda

3.innodb_file_format_max=Barracuda

Body:
When I executed the following command:

create table assessment (
    id integer not null auto_increment unique,
    assignment_weight_type tinyint not null,
    description varchar(255),
    end_date datetime not null,
    from_grade tinyint not null,
    f_id tinyint not null,
    name varchar(255) not null,
    start_date datetime not null,
    status tinyint not null,
    weight smallint,
    school_id integer not null,
    school_year_id integer not null,
    s_id integer, primary key (id),
    unique (name, school_id, school_year_id, from_grade, f_id)
) ENGINE=InnoDB;

I got this error message:

Specified key was too long; max key length is 767 bytes

I am using a charset of utf8mb4. So why did I get the error message?


问:
How to project the shapefile with GDAL ogr2ogr
The GDAL ogr2ogr project the shape file with EPSG:28991 and create .prj file near Amersfoort. But the actual place of shp file should be in amsterdam.

How to reproject the shape file to locate it on amsterdam with the help of xmin ymin xmax, ymax.enter image description here

答: Regarding the GDAL OGR, no problem in the tool itself. The prj file created contains the EPSG projection that you have assigned to the shapefile. The problem in such cases is, that the map and the shapefile layer are not on the same coordinates system which causes the shifting. To solve this problem make sure that the PRJ file generated contains the targeted coordinates system and what's more important is to assure that the map coordinates is exactly the same.</p>


问:
If the type of objects in a collection is known, should I specify the type of the iterating variable when using fast enumeration?
For example, say I have an NSArray that contains a bunch of NSString objects:

```<code>NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];
</code>```

What are the pros and cons of doing this:

```<code>for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}
</code>```

versus:

```<code>for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}
</code>```

答: You can't make iterator universal by specifying it's type as id if you've already passed a class specific message to it. If you want to make it "almost" universal you can specify as iterator's type the top-most class in hierarchy having all messages you plan to use. For your case this class is NSString

Body:
For example, say I have an NSArray that contains a bunch of NSString objects:

NSArray *games = [NSArray arrayWithObjects:@"Space Invaders", @"Dig Dug", @"Galaga", nil];

What are the pros and cons of doing this:

for (id object in games) {
    NSLog(@"The name of the game is: %@", object);
    NSLog(@"The name is %d characters long.", [object length]);
    // Do some other stuff...
}

versus:

for (NSString *name in games) {
    NSLog(@"The name of the game is: %@", name);
    NSLog(@"The name is %d characters long.", [name length]);
    // Do some other stuff...
}


问:
Unable to create Kubernetes Cluster on IBM Bluemix
I have been trying to create a Kubernetes Cluster with my Bluemix account owner but always getting the following error upon creation:

IBM Cloud Infrastructure exception: Your account is currently prohibited from order 'Computing Instances'.

Any idea what the issue is?  There seems to be no direct way to getting support from Public Bluemix to address this issue.  We opened a ticket but it has not been addressed.

答:
You should contact IBM Bluemix Support for this kind of question.  Before you login to the Bluemix Console, there is a Support link.

From the look of the exception.  It seen like you are trying to create a "second" kubernetes cluster.  If this is what you are trying to do, you will need a SoftLayer account; or your ID in your SoftLayer account is not setup properly.


问:
How to resolve iOS 11 Safari getUserMedia "Invalid constraint" issue
I'm attempting to run the following code in Safari in iOS 11.  It should prompt the user to give access to their devices camera and then display it in my <video autoplay id="video"></video> element.  However, when running in iOS 11, it results in an OverconstrainedError to be thrown:

```<code>{message: "Invalid constraint", constraint: ""}
</code>```

The code runs fine in Android and successfully opens the camera.

I've attempted multiple valid configurations with no luck.

I know iOS 11 just came out so it may be a bug, but any thoughts?  Has anyone else run into this?

Code:

```<code>var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
     navigator.mediaDevices.getUserMedia({video: true})
         .then(function(stream) {
             video.src = window.URL.createObjectURL(stream);
             video.play();
         })
         .catch(function(err) {
             console.log(err);
         });
}
</code>```

Edit 1

I've run navigator.mediaDevices.getSupportedConstraints() and it returns the following:

```<code>{
    aspectRatio: true,
    deviceid: true,
    echoCancellation: false,
    facingMode: true,
    frameRate: true,
    groupId: true,
    height: true,
    sampleRate: false,
    sampleSize: false,
    volume: true,
    width: true
}
</code>```

I've tried configurations omitting the video property, but had no luck.

答:
It appears to have been a bug that was corrected, because I just tried it again and the error message no longer appears.

Note that while the error message went away, I did have to make one more change for it to work, which was adding video.srcObject = stream; in the then callback.

Body:
I'm attempting to run the following code in Safari in iOS 11.  It should prompt the user to give access to their devices camera and then display it in my <video autoplay id="video"></video> element.  However, when running in iOS 11, it results in an OverconstrainedError to be thrown:

{message: "Invalid constraint", constraint: ""}

The code runs fine in Android and successfully opens the camera.

I've attempted multiple valid configurations with no luck.

I know iOS 11 just came out so it may be a bug, but any thoughts?  Has anyone else run into this?

Code:

var video = document.getElementById('video');
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
     navigator.mediaDevices.getUserMedia({video: true})
         .then(function(stream) {
             video.src = window.URL.createObjectURL(stream);
             video.play();
         })
         .catch(function(err) {
             console.log(err);
         });
}

Edit 1

I've run navigator.mediaDevices.getSupportedConstraints() and it returns the following:

{
    aspectRatio: true,
    deviceid: true,
    echoCancellation: false,
    facingMode: true,
    frameRate: true,
    groupId: true,
    height: true,
    sampleRate: false,
    sampleSize: false,
    volume: true,
    width: true
}

I've tried configurations omitting the video property, but had no luck.


问:
ASP.net create infinite loop on application start to do work
I need to do some work on periodic basis, like check some data in DB and make some calculations if needed and store them back to DB.

The question is how bad is it to start infinite look with some "sleep and do work" in separate thread on application start which would perform all required task periodically until pool shutdown?

What are the downsides? it feels for me like it may affect asp.net processing performance due to reusable/releasable concept of MVC resources, but I can't find any proof.

Would appreciate any links or hints, Thanks!

P.S. I realize that best place to do something like this is windows service but it introduce some difficulties with deployment on client environment and I am checking out for any other options if any.

答:
I would suggest you construct a simple Console App to do what you would like and then set a Scheduled Task to run the console app.

This is the method I have used to do maintenance utilities such as the one you are describing.

Otherwise, in an Asp.net app, the worker process could be reset, the host might have an Idle Timeout triggered. And generally I think it would be the wrong approach when a very simple console app will use the language you prefer and accomplish the same task.