问:
Error C2280 vector of objects that have unique_ptr members
I believe I know why this is happening, but being new to c++ I'm unsure what the correct way to handle it is (without using raw pointers). From my research what is happening is that when I attempt to push_back a Stage object into a vector a copy is being attempted and since Stage contains unique_ptr members which have deleted copy constructors, the below error is encountered.

Is my understanding correct? If so, what is the best way to resolve this issue in modern c++?

Minimal Reproducible Example

```<code>#include <iostream>
#include <vector>
#include <memory>

class Actor
{
private:
    int prop1 = 1;
    int prop2 = 2;
public:
    Actor() {}
};

class Stage
{
public:
    Stage() {}
    std::vector<std::unique_ptr<Actor>> actors;
};

class App
{
public:
    App() {}
    std::vector<Stage> stages;
};

int main()
{
    auto act1 = std::make_unique<Actor>();

    auto sta1 = Stage();
    sta1.actors.push_back(std::move(act1));

    auto app = App();
    app.stages.push_back(sta1); // Issue occurs when copying Stage object into vector since Stage object contains members of type unique_ptr (or at least that's my best guess from the research I have done)

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

Compiler Error from MSVC

```<code>Error   C2280   'std::unique_ptr<Actor,std::default_delete<_Ty>>::unique_ptr(
const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to
reference a deleted function    SmartPointers
c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xmemory0    945
</code>```

答:
unique_ptr cannot be copied, only moved. That's why it's called unique in the first place.

You used the right approach when pushing to actors so you only need to adapt it to stages.

```<code> app.stages.push_back(std::move(sta1));
</code>```

Body:
I believe I know why this is happening, but being new to c++ I'm unsure what the correct way to handle it is (without using raw pointers). From my research what is happening is that when I attempt to push_back a Stage object into a vector a copy is being attempted and since Stage contains unique_ptr members which have deleted copy constructors, the below error is encountered.

Is my understanding correct? If so, what is the best way to resolve this issue in modern c++?

Minimal Reproducible Example

#include <iostream>
#include <vector>
#include <memory>

class Actor
{
private:
    int prop1 = 1;
    int prop2 = 2;
public:
    Actor() {}
};

class Stage
{
public:
    Stage() {}
    std::vector<std::unique_ptr<Actor>> actors;
};

class App
{
public:
    App() {}
    std::vector<Stage> stages;
};

int main()
{
    auto act1 = std::make_unique<Actor>();

    auto sta1 = Stage();
    sta1.actors.push_back(std::move(act1));

    auto app = App();
    app.stages.push_back(sta1); // Issue occurs when copying Stage object into vector since Stage object contains members of type unique_ptr (or at least that's my best guess from the research I have done)

    std::cin.get();
    return 0;
}

Compiler Error from MSVC

Error   C2280   'std::unique_ptr<Actor,std::default_delete<_Ty>>::unique_ptr(
const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to
reference a deleted function    SmartPointers
c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xmemory0    945

Body:
unique_ptr cannot be copied, only moved. That's why it's called unique in the first place.

You used the right approach when pushing to actors so you only need to adapt it to stages.

 app.stages.push_back(std::move(sta1));


来源: stackexchange

问:
Can the input for "Lasso" in python contain categorical variables?
I want to perform multiple linear regression in python with lasso. I am not sure whether the input observation matrix X can contain categorical variables. I read the instructions from here: lasso in python

But it is simple and not indicate the types allowed for. For example, my code includes:

```<code>model = Lasso(fit_intercept=False, alpha=0.01)
model.fit(X, y)
</code>```

In the code above, X is an observation matrix with size of n-by-p, can one of the p variables be categorical type?

答:
You need to represent the categorical variables using 1s and 0s. If your categorical variables are binary, meaning each belongs to one of two categories, then you replace all category A and B variables into 0s and 1s, respectively. If some have more than two categories, you will need to use dummy variables.

I usually have my data in a Pandas dataframe, in which case I use houses = pd.get_dummies(houses), which creates the dummy variables.

ContentLicense: CC BY-SA 4.0

Body:
I want to perform multiple linear regression in python with lasso. I am not sure whether the input observation matrix X can contain categorical variables. I read the instructions from here: lasso in python

But it is simple and not indicate the types allowed for. For example, my code includes:

model = Lasso(fit_intercept=False, alpha=0.01)
model.fit(X, y)

In the code above, X is an observation matrix with size of n-by-p, can one of the p variables be categorical type?


问:
Skipping NA rows in index column
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3
</code>```

At the moment I'm doing it as:

```<code>i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)
</code>```

but that gives me

```<code>VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5
</code>```

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

答:
You can use an index i holding !is.na(df$VarA) which can be used for subseting df and to generate the sequence.

```<code>i <- !is.na(df$VarA)
df$ID[i] <- seq_len(sum(i))
df
#  VarA ID
#1 TRUE  1
#2   NA NA
#3   NA NA
#4 TRUE  2
#5 TRUE  3
</code>```

Or using which for the index:

```<code>i <- which(df$VarA)
df$ID[i] <- seq_along(i)
</code>```

Data:

```<code>df <- data.frame(VarA = c(TRUE,NA,NA,TRUE,TRUE))
</code>```

Title: Skipping NA rows in index column

Body:
I have a dataframe with a column with values TRUE and NA. I'd like to add an index column to the df that indexes all rows with TRUE but simply skips all rows with NA, without removing them. Like this:

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    2
TRUE    3

At the moment I'm doing it as:

i = 1:nrow(df)
df$ID <- ifelse(df$VarA == TRUE, i, NA)

but that gives me

VarA    ID
TRUE    1
NA      NA
NA      NA
TRUE    4
TRUE    5

which is not what I want. I know this should be super easy with something like na.omit but somehow I just can't figure it out.

Body:
You can use an index i holding !is.na(df$VarA) which can be used for subseting df and to generate the sequence.

i <- !is.na(df$VarA)
df$ID[i] <- seq_len(sum(i))
df
#  VarA ID
#1 TRUE  1
#2   NA NA
#3   NA NA
#4 TRUE  2
#5 TRUE  3

Or using which for the index:

i <- which(df$VarA)
df$ID[i] <- seq_along(i)

Data:

df <- data.frame(VarA = c(TRUE,NA,NA,TRUE,TRUE))


问:
Hibernate Search, filter out object with the highest value
Hi i have a EntityObject like this

```<code>public class Adm{
private String id;
private String version;
private String name;
private String mimetype;
    ...
    ...
    ...

}
</code>```

I would like to add an filter out all objects with the highest version of those objects with the same name. Anyone got any idea how todo this, with a filter or when creating the query?

I use Hibernate Search Version 3.3.0.

//Trind

答:
The way to do filtering in Search is via FullTextFilters. See http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#query-filter
You can pass parameters to the filter when you enable them, eg

```<code>fullTextQuery.enableFullTextFilter("version").setParameter( "max", 1001 );
</code>```

You can pass as many parameters you like and also pass any parameter type you want (you will just have to cast appropriately in the filter implementation). You would probably need another query to determine the max values. Maybe a HQL or Criteria query after all.
Within the Filter you could use a NumericRangeQuery. Of course this all depends on your domain model. You haven't included the Hibernate Search annotations and the Hibernate Search query you are trying to run. Also is the max version something you can determine beforehand and cache?
Hope, this gives you some pointers.

ContentLicense: CC BY-SA 3.0

Body:
Hi i have a EntityObject like this

public class Adm{
private String id;
private String version;
private String name;
private String mimetype;
    ...
    ...
    ...

}

I would like to add an filter out all objects with the highest version of those objects with the same name. Anyone got any idea how todo this, with a filter or when creating the query?

I use Hibernate Search Version 3.3.0.

//Trind

Body:
The way to do filtering in Search is via FullTextFilters. See http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#query-filter
You can pass parameters to the filter when you enable them, eg

fullTextQuery.enableFullTextFilter("version").setParameter( "max", 1001 );

You can pass as many parameters you like and also pass any parameter type you want (you will just have to cast appropriately in the filter implementation). You would probably need another query to determine the max values. Maybe a HQL or Criteria query after all.
Within the Filter you could use a NumericRangeQuery. Of course this all depends on your domain model. You haven't included the Hibernate Search annotations and the Hibernate Search query you are trying to run. Also is the max version something you can determine beforehand and cache?
Hope, this gives you some pointers.


问:
Firebase | How can I change the App Distribution's App Icon
I migrated Fabric project to Firebase. But I can't find any options for an app icon in the App Distribution.

How can I change my app icon?

答:
Sending a new build with a new app icon can be a solution.
Yesterday I sent wrong which belongs to another app and the app icon changed to the new build's app icon.</p>


问:
activeNetworkInfo.type is deprecated in API level 28
I want to use the Connectivity manager which provide the method activeNetworkInfo.type for checking the type of network in Android. This method was deprecated in API level 28. so what is the solution to check network type in API 28. my code is :

```<code>/**
 * Check Wi Fi connectivity
 */
fun isWiFiConnected(context: Context): Boolean {
    val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return connManager.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}
</code>```

My Gradle is like :

```<code>compileSdkVersion 28
buildToolsVersion '28.0.3'
defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
    }
</code>```

答:
I am using this Kotlin func to check internet connection:

Be careful about version checking (Version >= M)

```<code>private fun isInternetConnected():Boolean{

    val connectivityManager = this.getSystemService(android.content.Context.CONNECTIVITY_SERVICE)
            as ConnectivityManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val networkCapabilities = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false

        return when {

            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                    activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                    activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            else -> false
        }
    }
    else {
        return connectivityManager.activeNetworkInfo != null &&
                connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting
    }
}
</code>```

Body:
I want to use the Connectivity manager which provide the method activeNetworkInfo.type for checking the type of network in Android. This method was deprecated in API level 28. so what is the solution to check network type in API 28. my code is :

/**
 * Check Wi Fi connectivity
 */
fun isWiFiConnected(context: Context): Boolean {
    val connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    return connManager.activeNetworkInfo.type == ConnectivityManager.TYPE_WIFI
}

My Gradle is like :

compileSdkVersion 28
buildToolsVersion '28.0.3'
defaultConfig {
        minSdkVersion 21
        targetSdkVersion 28
    }

Body:
I am using this Kotlin func to check internet connection:

Be careful about version checking (Version >= M)

private fun isInternetConnected():Boolean{

    val connectivityManager = this.getSystemService(android.content.Context.CONNECTIVITY_SERVICE)
            as ConnectivityManager

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        val networkCapabilities = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false

        return when {

            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
                    activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
                    activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            else -> false
        }
    }
    else {
        return connectivityManager.activeNetworkInfo != null &&
                connectivityManager.activeNetworkInfo!!.isConnectedOrConnecting
    }
}


问:
asmx service returns xml instead of json
I am trying to set up a asmx service to return json inside the web method. When I view the response inside
a browser instead of returning json I get xml. I have set up my web method to return the json format.
Please find my web service below:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace space_port_lander_real_app
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod(CacheDuration = 60)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {

            //string xmlstring = "<user><name>Hello World</name><password>some pass</password></user>";

            //var name = $(xml).find('name').text();

            //return xmlstring;

            return "hello world";
        }
    }
}
</code>```

The response output looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">hello world</string>
</code>```

I set up my method to return a string. Is there something I'm missing?

答:
If you want a GET method to return JSON, you need to set it otherwise use POST.

```<code>[ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]
</code>```

Check Here

Body:
I am trying to set up a asmx service to return json inside the web method. When I view the response inside
a browser instead of returning json I get xml. I have set up my web method to return the json format.
Please find my web service below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;

namespace space_port_lander_real_app
{
    ///
    /// Summary description for WebService1
    ///
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod(CacheDuration = 60)]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string HelloWorld()
        {

            //string xmlstring = "<user><name>Hello World</name><password>some pass</password></user>";

            //var name = $(xml).find('name').text();

            //return xmlstring;

            return "hello world";
        }
    }
}

The response output looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">hello world</string>

I set up my method to return a string. Is there something I'm missing?

Body:
If you want a GET method to return JSON, you need to set it otherwise use POST.

[ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]

Check Here


问:
MySQL: Add a WHERE in a LEFT JOIN
I have the following table:

SequenceNumber are always a multiple of 10. I would like to get, for a specific cpId, the smallest free sequence number (still in a multiple of 10). For example, for cpId = 1, the smallest available should be 20. For cpId = 2, it should be 10.

I have the following statement to get the smallest available sequenceNumber for all cpId, and I don't know how I can add a WHERE cpId = x inside the statement:

```<code>SELECT MIN(t1.sequenceNumber + 10) AS nextID
FROM LogicalConnection t1
   LEFT JOIN LogicalConnection t2
       ON t1.sequenceNumber + 10 = t2.sequenceNumber
WHERE t2.sequenceNumber IS NULL;
</code>```

DB fiddle: https://www.db-fiddle.com/f/ag67AkFzfwPZEva8bTN7Q3/2#&togetherjs=L9nHb3Uu7O

Thank you for your help!

答:
You can use lead() to get the next number and then some simple logic:

```<code>select cpid,
       (case when min_sn > 10 then 10
             else min(sequenceNumber) + 10
        end)
from (select t.*,
             min(sequenceNumber) over (partition by cpid) as min_sn,
             lead(sequenceNumber) over (partition by cpid order by sequenceNumber) as next_sn
      from t
     ) t
where next_sn is null or next_sn <> sequenceNumber + 10
group by cpid, min_sn;
</code>```

Title: MySQL: Add a WHERE in a LEFT JOIN

Body:
I have the following table:

SequenceNumber are always a multiple of 10. I would like to get, for a specific cpId, the smallest free sequence number (still in a multiple of 10). For example, for cpId = 1, the smallest available should be 20. For cpId = 2, it should be 10.

I have the following statement to get the smallest available sequenceNumber for all cpId, and I don't know how I can add a WHERE cpId = x inside the statement:

SELECT MIN(t1.sequenceNumber + 10) AS nextID
FROM LogicalConnection t1
   LEFT JOIN LogicalConnection t2
       ON t1.sequenceNumber + 10 = t2.sequenceNumber
WHERE t2.sequenceNumber IS NULL;

DB fiddle: https://www.db-fiddle.com/f/ag67AkFzfwPZEva8bTN7Q3/2#&togetherjs=L9nHb3Uu7O

Thank you for your help!

Body:
You can use lead() to get the next number and then some simple logic:

select cpid,
       (case when min_sn > 10 then 10
             else min(sequenceNumber) + 10
        end)
from (select t.*,
             min(sequenceNumber) over (partition by cpid) as min_sn,
             lead(sequenceNumber) over (partition by cpid order by sequenceNumber) as next_sn
      from t
     ) t
where next_sn is null or next_sn <> sequenceNumber + 10
group by cpid, min_sn;


问:
How can I create PBF file from GeoJSON file using NodeJS?
I have a Geojson file which name is countries.geojson.

I can read this file with get method. I want to create PBF files from this GeoJSON file. How can I do that?

```<code>var express = require("express");
const fs = require('fs');
var Pbf = require('pbf');
var protobuf = require('protocol-buffers')
const path = require('path');

var app = express();

app.get("/get/data", (req, res, next) => {
    fs.readFile('data/countries.geojson', (err, data) => {
        if (err) throw err;
        let country = JSON.parse(data);
        res.send(country);
    });
});

app.get("/", (req, res, next) => {
    // Create PBF file
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});
</code>```

答:
Use geobuf library:</p>

```<code>var buffer = geobuf.encode(geojson, new Pbf());
</code>```

Body:
I have a Geojson file which name is countries.geojson.

I can read this file with get method. I want to create PBF files from this GeoJSON file. How can I do that?

var express = require("express");
const fs = require('fs');
var Pbf = require('pbf');
var protobuf = require('protocol-buffers')
const path = require('path');

var app = express();

app.get("/get/data", (req, res, next) => {
    fs.readFile('data/countries.geojson', (err, data) => {
        if (err) throw err;
        let country = JSON.parse(data);
        res.send(country);
    });
});

app.get("/", (req, res, next) => {
    // Create PBF file
});

app.listen(3000, () => {
    console.log("Server running on port 3000");
});

Body:
Use geobuf library:

var buffer = geobuf.encode(geojson, new Pbf());


问:
Where is placed createSwitchNavigator in react-navigation 5.x for migrating from react-navigation 4 to 5.x
I'm migrating a React Native application from react-navigation 4 to 5.x and i can't find which package contains createSwitchNavigation. Specifically i have doubts with the auth token check part.

With react-navigation 4 i had:

const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  signinFlow: createStackNavigator({
    Signup: SignupScreen,
    Signin: SigninScreen,
  }),
  appFlow: createBottomTabNavigator({
    TrackCreate: TrackCreateScreen,
    trackListFlow: createStackNavigator({
      TrackList: TrackListScreen,
      TrackDetail: TrackDetailScreen
    }),
    Account: AccountScreen,
  })
}, {
  initialRouteName: 'ResolveAuth'
});
```

<p>Then i have a file containing ResolveAuthScreen component.</p>

<pre class="lang-js prettyprint-override"><code>import React, { useEffect } from 'react';
import { connect } from 'react-redux';

const ResolveAuthScreen = (props) => {
  useEffect(() => {
    if (!props.token) {
      props.navigation.navigate('loginFlow');
    } else {
      props.navigation.navigate('TrackList');
    }
  }, []);

  return null;
};

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(ResolveAuthScreen);
</code>```

The rest of components are not important for this doubt. I want to know how to replicate the same Switch navigation flow.
I would like to know how can i create something like this:

const Switch = createSwitchNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Switch.Navigator>
        <Switch.Screen name="ResolveAuth" component={ResolveAuthScreen} />
        <Switch.Screen name="signinFlow" component={SignInFlowScreens} />
        <Switch.Screen name="appFlow" component={AppFlowScreens} />
      </Switch.Navigator>
    </NavigationContainer>
  );
}
```

答:
There is no switch navigator on v5. You could try below code</p>

```<code>function App({ token }) {
  const [isLoggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    setLoggedIn(!!token);
  }, [token]);

  return (
    <NavigationContainer>
      {isLoggedIn ? <AppFlowScreens /> : <SignInFlowScreens /> }
    </NavigationContainer>
  );
}

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(App);
</code>```

Body:
I'm migrating a React Native application from react-navigation 4 to 5.x and i can't find which package contains createSwitchNavigation. Specifically i have doubts with the auth token check part.

With react-navigation 4 i had:

const switchNavigator = createSwitchNavigator({
  ResolveAuth: ResolveAuthScreen,
  signinFlow: createStackNavigator({
    Signup: SignupScreen,
    Signin: SigninScreen,
  }),
  appFlow: createBottomTabNavigator({
    TrackCreate: TrackCreateScreen,
    trackListFlow: createStackNavigator({
      TrackList: TrackListScreen,
      TrackDetail: TrackDetailScreen
    }),
    Account: AccountScreen,
  })
}, {
  initialRouteName: 'ResolveAuth'
});

Then i have a file containing ResolveAuthScreen component.

import React, { useEffect } from 'react';
import { connect } from 'react-redux';

const ResolveAuthScreen = (props) => {
  useEffect(() => {
    if (!props.token) {
      props.navigation.navigate('loginFlow');
    } else {
      props.navigation.navigate('TrackList');
    }
  }, []);

  return null;
};

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(ResolveAuthScreen);

The rest of components are not important for this doubt. I want to know how to replicate the same Switch navigation flow.
I would like to know how can i create something like this:

const Switch = createSwitchNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Switch.Navigator>
        <Switch.Screen name="ResolveAuth" component={ResolveAuthScreen} />
        <Switch.Screen name="signinFlow" component={SignInFlowScreens} />
        <Switch.Screen name="appFlow" component={AppFlowScreens} />
      </Switch.Navigator>
    </NavigationContainer>
  );
}

Body:
There is no switch navigator on v5. You could try below code

function App({ token }) {
  const [isLoggedIn, setLoggedIn] = useState(false);

  useEffect(() => {
    setLoggedIn(!!token);
  }, [token]);

  return (
    <NavigationContainer>
      {isLoggedIn ? <AppFlowScreens /> : <SignInFlowScreens /> }
    </NavigationContainer>
  );
}

const mapStateToProps = (state) => {
  return {
    token: state.auth.token,
  };
};

export default connect(mapStateToProps, null)(App);


问:
Parsing an unusual http response with Angular, RxJS in Facade pattern
I have a Back-End API that returns data in the following structure:

```<code>{
    "code": 200,
    "message": "Success",
    "data": // Can basically be anything.. object, array, string, etc...
}
</code>```

The thing is, I'm really confused about how all this is supposed to work with such a nested payload.

Would love a little more guidance regarding how to implement this abomination within my design pattern and how to do it right.

I have the following weapons in my arsenal:

APIResponse - Model

```<code>export default interface APIResponse {
    code: number;
    message: string;
    data?: any;
}
</code>```

NetworkService - Service

```<code>@Injectable({ providedIn: 'root' })
export class NetworkService {
    constructor(private http: HttpClient) { }

    private _formatErrors(error: any) {
        return throwError(error);
    }

    get(environment: string, path: string, params: HttpParams = new HttpParams()): Observable<APIResponse> {
        return this.http.get<APIResponse>(`${environment}${path}`, { params }).pipe(catchError(this._formatErrors));
    }
}
</code>```

PostsAPI

I'm stuck exactly here. How do I convert the APIResponse's data attribute to Post[] Observable?

```<code>@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}
</code>```

PostsFacade

```<code>@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this._postsAPI.getAllPosts().subscribe(response => this.posts$ = response.data.posts); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}
</code>```

HomeComponent - The page that displays the posts

```<code>@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    posts$ = this._postsFacade.posts$;

    // Lifecycle
    constructor(private _postsFacade: PostsFacade) { }
    ngOnInit() {
        console.log(this.posts$); // Returns undefined
    }
}
</code>```

Thanks a lot!

答:
Inside your PostsFacade you should not subscribe to the observable because posts$ will not be of type Observable then.
PostsFacade:

```<code>@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this.posts$ = this._postsAPI.getAllPosts()
    }
}
</code>```

Now to convert the APIResponses data attribute to Post[] use rxjs map operator like follows:
 PostsApi:

```<code>@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`).pipe(map(apiResponse => responseToPosts(apiResponse)));
    }
}
</code>```

With responseToPosts(apiResponse:APIResponse):Post[] a function which converts your apiResponse to Post[]

Body:
I have a Back-End API that returns data in the following structure:

{
    "code": 200,
    "message": "Success",
    "data": // Can basically be anything.. object, array, string, etc...
}

The thing is, I'm really confused about how all this is supposed to work with such a nested payload.

Would love a little more guidance regarding how to implement this abomination within my design pattern and how to do it right.

I have the following weapons in my arsenal:

APIResponse - Model

export default interface APIResponse {
    code: number;
    message: string;
    data?: any;
}

NetworkService - Service

@Injectable({ providedIn: 'root' })
export class NetworkService {
    constructor(private http: HttpClient) { }

    private _formatErrors(error: any) {
        return throwError(error);
    }

    get(environment: string, path: string, params: HttpParams = new HttpParams()): Observable<APIResponse> {
        return this.http.get<APIResponse>(`${environment}${path}`, { params }).pipe(catchError(this._formatErrors));
    }
}

PostsAPI

I'm stuck exactly here. How do I convert the APIResponse's data attribute to Post[] Observable?

@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}

PostsFacade

@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this._postsAPI.getAllPosts().subscribe(response => this.posts$ = response.data.posts); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}

HomeComponent - The page that displays the posts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    posts$ = this._postsFacade.posts$;

    // Lifecycle
    constructor(private _postsFacade: PostsFacade) { }
    ngOnInit() {
        console.log(this.posts$); // Returns undefined
    }
}

Thanks a lot!

Body:
Inside your PostsFacade you should not subscribe to the observable because posts$ will not be of type Observable then.
PostsFacade:

@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this.posts$ = this._postsAPI.getAllPosts()
    }
}

Now to convert the APIResponses data attribute to Post[] use rxjs map operator like follows:
 PostsApi:

@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`).pipe(map(apiResponse => responseToPosts(apiResponse)));
    }
}

With responseToPosts(apiResponse:APIResponse):Post[] a function which converts your apiResponse to Post[]


问:
python proton API on_accepted() - how do I get the details of the msg being accepted, from the event parameter?
There are a dozen "hello world" type examples I see where on_accepted() just counts the number of accepted msgs - where it is something to show that "a message" was accepted. However, I need to know WHICH message was accepted.

def on_accepted(self, event):
    m_id = event.message.id
    self.logger.info( 'Accepted msg {0}'.format( m_id ))
```

This doesn't work because there is no valid message element in event, so I end up with a NoneType doesn't have an id type error.

I looked at the members of the event parameter and I don't see anything which I thought would make sense..

答:
I wasn't able to find any references to how to read the message details, but I was able to find a work around which gave me the same info.

If I specify a tag on the send() call, like this:

event.sender.send(msg, tag = msg_id )

I can then read it in the receiver code like this:

def on_accepted(self, event):
    msg_id  = event.delivery.tag

Problem "solved"

Body:
There are a dozen "hello world" type examples I see where on_accepted() just counts the number of accepted msgs - where it is something to show that "a message" was accepted. However, I need to know WHICH message was accepted.

def on_accepted(self, event):
    m_id = event.message.id
    self.logger.info( 'Accepted msg {0}'.format( m_id ))

This doesn't work because there is no valid message element in event, so I end up with a NoneType doesn't have an id type error.

I looked at the members of the event parameter and I don't see anything which I thought would make sense..


问:
I have set up a small flask webpage but in only runs on localhost while I would like to make it run on my local network python3.7
I have set up a small flask webpage but in only runs on localhost  while I would like to make it run on my local network, how do I do that? </p>

答:
Just my 2 cents on this, I just did some research, there are many suggestions online...

Adding a parameter to your app.run(), by default it runs on localhost, so change it to app.run(host= '0.0.0.0') to run on your machines IP address.

Few other things you could do is to use the flask executable to start up your local server, and then you can use flask run --host=0.0.0.0 to change the default IP which is 127.0.0.1 and open it up to non local connections.

The thing is you should use the app.run() method which is much better than any other methods.

Hope it helps a little, if not good luck :)


问:
TypeError: must be str, not Statement
I am working on a chatbot and the code is -

```<code>from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import numpy as np
import random
import string # to process standard python strings

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

import os
language = 'en'

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            greetinput = random.choice(GREETING_RESPONSES)
            return greetinput

def response(user_response):
    robo_response=''
    user_response = str(user_response)
    robo_response = robo_response+return_response
    return robo_response

flag=True

my_bot = ChatBot(name='PyBot', read_only=True,logic_adapters=['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])
small_talk = ['hi there!',
              'hi!',
              'how do you do?',
              'how are you?',
              'i\'m cool.',
              'fine, you?',
              'always cool.',
              'i\'m ok',
              'glad to hear that.',
              'i\'m fine',
              'glad to hear that.',
              'i feel awesome',
              'excellent, glad to hear that.',
              'not so good',
              'sorry to hear that.',
              'what\'s your name?',
              'i\'m pybot. ask me a math question, please.']

math_talk_1 = ['pythagorean theorem',
           'a squared plus b squared equals c squared.']

math_talk_2 = ['law of cosines',
           'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']

list_trainer = ListTrainer(my_bot)

for item in (small_talk, math_talk_1, math_talk_2):
    list_trainer.train(item)

corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')

openremark = "ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!"

print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print("func call user_response")
                print(user_response)
                print("end")
                user_response = str(user_response)
                print(response(user_response))
    else:
        flag=False

        offremark2 = "Bye! take care"
        print("ROBO: Bye! take care..")
</code>```

On run command it is not working fine -

```<code>ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!
hi
ROBO: hi there
gaurav
ROBO: func call user_response
gaurav
end
user_response
gaurav
type
<class 'str'>
end
dummy check
you are busy
dummy end
user_response
gaurav
Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement
</code>```

It is working fine for greeting and BYE message but when it has to work with CHATTERBOT and CHATTERBOT_CORPUS it is giving an error.

```<code>Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement
</code>```

TypeError: must be str, not Statement

I even tried with making user_response string first and also with for loop so that it work for each singular element but it turn up the same message. I am not able to resolve the error and didnt get any answer for the same or similar question.

答:
What is return_response ? It doesn't look like it's defined.

Maybe replace this :

```<code>robo_response = robo_response+return_response
</code>```

by this :

```<code>robo_response = robo_response+user_response
</code>```

Title: TypeError: must be str, not Statement

Body:
I am working on a chatbot and the code is -

from chatterbot import ChatBot
from chatterbot.trainers import ListTrainer
from chatterbot.trainers import ChatterBotCorpusTrainer
import nltk
import numpy as np
import random
import string # to process standard python strings

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

import os
language = 'en'

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]

def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            greetinput = random.choice(GREETING_RESPONSES)
            return greetinput

def response(user_response):
    robo_response=''
    user_response = str(user_response)
    robo_response = robo_response+return_response
    return robo_response

flag=True

my_bot = ChatBot(name='PyBot', read_only=True,logic_adapters=['chatterbot.logic.MathematicalEvaluation','chatterbot.logic.BestMatch'])
small_talk = ['hi there!',
              'hi!',
              'how do you do?',
              'how are you?',
              'i\'m cool.',
              'fine, you?',
              'always cool.',
              'i\'m ok',
              'glad to hear that.',
              'i\'m fine',
              'glad to hear that.',
              'i feel awesome',
              'excellent, glad to hear that.',
              'not so good',
              'sorry to hear that.',
              'what\'s your name?',
              'i\'m pybot. ask me a math question, please.']

math_talk_1 = ['pythagorean theorem',
           'a squared plus b squared equals c squared.']

math_talk_2 = ['law of cosines',
           'c**2 = a**2 + b**2 - 2 * a * b * cos(gamma)']

list_trainer = ListTrainer(my_bot)

for item in (small_talk, math_talk_1, math_talk_2):
    list_trainer.train(item)

corpus_trainer = ChatterBotCorpusTrainer(my_bot)
corpus_trainer.train('chatterbot.corpus.english')

openremark = "ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!"

print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print("func call user_response")
                print(user_response)
                print("end")
                user_response = str(user_response)
                print(response(user_response))
    else:
        flag=False

        offremark2 = "Bye! take care"
        print("ROBO: Bye! take care..")

On run command it is not working fine -

ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!
hi
ROBO: hi there
gaurav
ROBO: func call user_response
gaurav
end
user_response
gaurav
type
<class 'str'>
end
dummy check
you are busy
dummy end
user_response
gaurav
Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement

It is working fine for greeting and BYE message but when it has to work with CHATTERBOT and CHATTERBOT_CORPUS it is giving an error.

Traceback (most recent call last):
  File "chatbot-new-1.py", line 118, in <module>
    print(response(user_response))
  File "chatbot-new-1.py", line 46, in response
    robo_response = robo_response+return_response
TypeError: must be str, not Statement

TypeError: must be str, not Statement

I even tried with making user_response string first and also with for loop so that it work for each singular element but it turn up the same message. I am not able to resolve the error and didnt get any answer for the same or similar question.

Body:
What is return_response ? It doesn't look like it's defined.

Maybe replace this :

robo_response = robo_response+return_response

by this :

robo_response = robo_response+user_response


问:
Why does pressing Enter on a button not cause :active state in Chrome?
Check the following snippet in current Chrome (80):

foo.addEventListener('click', () => {
  console.log('button activated');
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>button:active {
  background-color: yellow;
}</code>```

<button type="button" id="foo">Activate me using Click, Enter, Space</button>```

Chrome applies the button:active styles when the button is clicked (right or left) or activated using Space, but not when activated using Enter.

Firefox only applies the button:active styles when clicking (left mouse button only) the button.

Does anyone know

how this is supposed to work, and

how do I get the button to show button:active no matter which of
the activation methods are used?

I'd highly prefer a solution based on CSS. Adding/removing a class using key listeners would be a very ugly solution and is not in the scope of this question.

Edit

There has to be, or at least there should be, a standard way to give the user activating a button using Enter visual feedback on their action. Is this behaviour not specified somewhere? If it were, I could raise it as an issue on Mozilla bug tracker and also on Chromium issue tracker.

答:
The specification seems quite clear about this:

The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it. On systems with more than one mouse button, :active applies only to the primary or primary activation button (typically the "left" mouse button), and any aliases thereof.

https://drafts.csswg.org/selectors-3/#sel-active

So it does not explicitly mention activating an element using the keyboard, but it does state

[...] while an element is being activated by the user [...]

Since a button is clearly being activated by the user when he issues Enter or Space, both Firefox and Chrome seem in clear violation of the spec here.

On top of that, Chrome also applies :active when rightclicking the button (which is explicitly stated in the spec should not be the case).

Will file an issue in the CSSWG tracker for making this part of the spec more explicit. Here it is: https://github.com/w3c/csswg-drafts/issues/4787

Body:
Check the following snippet in current Chrome (80):

foo.addEventListener('click', () => {
  console.log('button activated');
})

button:active {
  background-color: yellow;
}

<button type="button" id="foo">Activate me using Click, Enter, Space</button>

Chrome applies the button:active styles when the button is clicked (right or left) or activated using Space, but not when activated using Enter.

Firefox only applies the button:active styles when clicking (left mouse button only) the button.

Does anyone know

how this is supposed to work, and

how do I get the button to show button:active no matter which of
the activation methods are used?

I'd highly prefer a solution based on CSS. Adding/removing a class using key listeners would be a very ugly solution and is not in the scope of this question.

Edit

There has to be, or at least there should be, a standard way to give the user activating a button using Enter visual feedback on their action. Is this behaviour not specified somewhere? If it were, I could raise it as an issue on Mozilla bug tracker and also on Chromium issue tracker.


问:
Run jQuery function when a certain number of checkboxes are selected
I am trying to achieve the following with jQuery:

Select max 3 check boxes out of 20, when three check boxes are selected run jQuery function.

答:
If I understand correctly you want to run a function if three boxes are checked? To do that use</p>

```<code>$(":checkbox").click(function(){

if($(":checkbox:checked").length==3))
  //run function here
});
</code>```

Body:
If I understand correctly you want to run a function if three boxes are checked? To do that use

$(":checkbox").click(function(){

if($(":checkbox:checked").length==3))
  //run function here
});


问:
Exclude Specific Areas from Crawler
I wanted to exclude some specific Areas from being crawled by google etc. because this is the legal/privacy and will get penalty because of long unrelated text. So I found a solution with iframe. I think the best way is to create a specific route for my desired element with htmlRoute or renderRoute and Disallow: /ROUTE/ in robots.txt. Or is there any other recommended way to solve this ? Maybe even more elegant ?

Here is my example of that code I tried  but unfortunately this isn't working anymore:

```<code><footer class="page-footer">
  <div class="footer-copyright">
    <div class="footer-container">

      {%- if data.global.legal -%}
        © {{ data.global.creation_date }} {{ data.global.copyright }}
      {%- endif -%}

      {%- if data.global.privacy -%}
        <a class="grey-text text-lighten-4 right modal-trigger" href="#modal-1">privacy</a>
        <div id="modal-1" class="modal">
          <div class="modal-content text-darken-4">

            <!--googleoff: index-->

            <h4>Privacy</h4>
            {{ apos.area(data.global, 'privacy', {
              edit: false,
              widgets: { 'apostrophe-rich-text': { } }
            }) }}

            <!--googleon: index-->

          </div>
        </div>
      {%- endif -%}

      {%- if data.global.legal -%}
        <a class="grey-text text-lighten-4 right modal-trigger" href="#modal-2">Legal</a>
        <div id="modal-2" class="modal">
          <div class="modal-content text-darken-4">

            <!--googleoff: index-->

            <h4>Legal Info</h4>
            {{ apos.area(data.global, 'legal', {
              edit: false,
              widgets: { 'apostrophe-rich-text': { } }
            }) }}

            <!--googleon: index-->

          </div>
        </div>
      {%- endif -%}

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

I've picked some example renderRoute function from apostrophe core modules and implemented this to my apostrophe global now my apostrophe global looks like that:

```<code>...
{
  name: 'legal',
  label: 'Legal Info',
  help: 'Your adress, phone and other info here',
  type: 'area',
  options: {
    widgets: {
      'apostrophe-rich-text': {
        toolbar: [
          'Styles',
          'Bold',
          'Italic',
          'Blockquote',
          'BulletedList',
          'Link'
        ],
        controls: {
          movable: false,
          cloneable: false,
          removable: true,
          position: 'top-right'
        }
       }
     }
   }
},
construct: function(self, options) {
  self.renderRoute('post', 'iframe', function(req, res, next) {
    return next(null, {
      template: 'legal'
    });
  });
}
</code>```

But i still don't get an route like iframe when i open the legal modal. I think I made something wrong or didn't understood this function fully. I would be really thankful if you could clarify this. Maybe it's just a quick look for you...

答:
googleoff is not for the public google crawler. It is strictly for google's old "search appliance" which was for intranet use and has been discontinued.

Your iframe tactic can work. The simplest way to get there would be to put the content in the global preferences by adding an area to the schema of apostrophe-global, like this:

```<code>// in lib/modules/apostrophe-global/index.js

module.exports = {
  addFields: [
    {
      name: 'legal',
      type: 'singleton',
      widgetType: 'apostrophe-rich-text',
      options: {
        toolbar: [ 'Bold', 'Italic', 'Link' ]
      }
    }
  ]
};
</code>```

Then you can use renderRoute as you suggested, and render a template that outputs that area from the global doc.

Title: Exclude Specific Areas from Crawler

Body:
I wanted to exclude some specific Areas from being crawled by google etc. because this is the legal/privacy and will get penalty because of long unrelated text. So I found a solution with iframe. I think the best way is to create a specific route for my desired element with htmlRoute or renderRoute and Disallow: /ROUTE/ in robots.txt. Or is there any other recommended way to solve this ? Maybe even more elegant ?

Here is my example of that code I tried  but unfortunately this isn't working anymore:

      {%- if data.global.legal -%}
        © {{ data.global.creation_date }} {{ data.global.copyright }}
      {%- endif -%}

      {%- if data.global.privacy -%}
        privacy

Privacy

            {{ apos.area(data.global, 'privacy', {
              edit: false,
              widgets: { 'apostrophe-rich-text': { } }
            }) }}

      {%- endif -%}

      {%- if data.global.legal -%}
        Legal

Legal Info

            {{ apos.area(data.global, 'legal', {
              edit: false,
              widgets: { 'apostrophe-rich-text': { } }
            }) }}

      {%- endif -%}

I've picked some example renderRoute function from apostrophe core modules and implemented this to my apostrophe global now my apostrophe global looks like that:

...
{
  name: 'legal',
  label: 'Legal Info',
  help: 'Your adress, phone and other info here',
  type: 'area',
  options: {
    widgets: {
      'apostrophe-rich-text': {
        toolbar: [
          'Styles',
          'Bold',
          'Italic',
          'Blockquote',
          'BulletedList',
          'Link'
        ],
        controls: {
          movable: false,
          cloneable: false,
          removable: true,
          position: 'top-right'
        }
       }
     }
   }
},
construct: function(self, options) {
  self.renderRoute('post', 'iframe', function(req, res, next) {
    return next(null, {
      template: 'legal'
    });
  });
}

But i still don't get an route like iframe when i open the legal modal. I think I made something wrong or didn't understood this function fully. I would be really thankful if you could clarify this. Maybe it's just a quick look for you...

Body:
googleoff is not for the public google crawler. It is strictly for google's old "search appliance" which was for intranet use and has been discontinued.

Your iframe tactic can work. The simplest way to get there would be to put the content in the global preferences by adding an area to the schema of apostrophe-global, like this:

// in lib/modules/apostrophe-global/index.js

module.exports = {
  addFields: [
    {
      name: 'legal',
      type: 'singleton',
      widgetType: 'apostrophe-rich-text',
      options: {
        toolbar: [ 'Bold', 'Italic', 'Link' ]
      }
    }
  ]
};

Then you can use renderRoute as you suggested, and render a template that outputs that area from the global doc.


问:
speed up a python wrapper for a scipy function
I need to create a fast python implementation of a simple wrapper for a scipy.stats function. This function only take vectors and not matrices. Wrappers below are two implementations, but both have similar run times.
Is it possible to speed any of these up, without moving the implementation to C/C++ domain.

```<code>import numpy as np
from scipy.stats import kendalltau

def wrap1(X, y):
    corr = []
    p_value = []
    X = np.array(X).transpose()
    y = np.ravel(y)
    for col in X:
        ktau = kendalltau(col, y, nan_policy='raise')
        corr.append(ktau[0])
        p_value.append(ktau[1])
    return corr, p_value

##########Version2

def wrap2(X, y):
        X = np.array(X).transpose()
        y = np.tile(np.ravel(y), (X.shape[0], 1))
        corr, p_value = zip(*[kendalltau(a, b, nan_policy='raise')
                              for a, b in zip(X, y)])
        return corr, p_value
</code>```

Sample run:

```<code>t1 = np.arange(30).reshape(10,3)
t2 = np.arange(10).reshape(10,)
wrap1(t1,t2)
wrap2(t1,t2)
</code>```

Thanks a lot

答:
1) In your wrap1 function, preallocate the arrays of corr and p_value, and fill them in instead of appending to lists.

2) replace np.array(X) with np.asarray(X) --- this will avoid making a copy of X if it's already an array.

That's probably all you can do easily if staying at the python level.

If that's not enough, you can try profiling the kendalltau function. There is quite a bit going on, and if you see a significant fraction of time spent in e.g. checking your arrays for nan values and you are sure your inputs do not have those, you can copy-paste relevant parts of the scipy implementation into your code.

Body:
I need to create a fast python implementation of a simple wrapper for a scipy.stats function. This function only take vectors and not matrices. Wrappers below are two implementations, but both have similar run times.
Is it possible to speed any of these up, without moving the implementation to C/C++ domain.

import numpy as np
from scipy.stats import kendalltau

def wrap1(X, y):
    corr = []
    p_value = []
    X = np.array(X).transpose()
    y = np.ravel(y)
    for col in X:
        ktau = kendalltau(col, y, nan_policy='raise')
        corr.append(ktau[0])
        p_value.append(ktau[1])
    return corr, p_value

##########Version2

def wrap2(X, y):
        X = np.array(X).transpose()
        y = np.tile(np.ravel(y), (X.shape[0], 1))
        corr, p_value = zip(*[kendalltau(a, b, nan_policy='raise')
                              for a, b in zip(X, y)])
        return corr, p_value

Sample run:

t1 = np.arange(30).reshape(10,3)
t2 = np.arange(10).reshape(10,)
wrap1(t1,t2)
wrap2(t1,t2)

Thanks a lot


问:
How to not use ObjectId() in node mongo native
As _id's get passed back and forth through REST API calls and other things that make it necessary for them to handled as strings, it can be annoying and error producing to have to wrap them as ObjectIds when querying or using as foreign keys in mongodb docs.

I would rather use uuid strings (using the npm uuid package).

Is there any way to change node mongodb to use string based id's by default when inserting a new object, and possibly also use the uuid generator function I specify?

答:
The _id field of MongoDB can have any value you want as long as you can guarantee that it is unique for the collection. When your data already has a natural key, there is no reason not to use this in place of the auto-generated ObjectIDs.

By not using ObjectIDs, you also miss out on another convenience feature: An ObjectID also includes an unix timestamp when it was generated, and many drivers provide a funtion to extract it and convert it to a date. This can sometimes make a separate create-date field redundant.

But still you can use other field as primary key if you are facing issues. Just ensure you create a unique index on the field. You can generate the field when inserting your data.

```<code>db.collection.createIndex( <key and index type specification>, { unique: true } )
</code>```

One example:

```<code>db.employees.createIndex( { "uuid": 1 }, { unique: true } )
</code>```

Body:
The _id field of MongoDB can have any value you want as long as you can guarantee that it is unique for the collection. When your data already has a natural key, there is no reason not to use this in place of the auto-generated ObjectIDs.

By not using ObjectIDs, you also miss out on another convenience feature: An ObjectID also includes an unix timestamp when it was generated, and many drivers provide a funtion to extract it and convert it to a date. This can sometimes make a separate create-date field redundant.

But still you can use other field as primary key if you are facing issues. Just ensure you create a unique index on the field. You can generate the field when inserting your data.

db.collection.createIndex( <key and index type specification>, { unique: true } )

One example:

db.employees.createIndex( { "uuid": 1 }, { unique: true } )


问:
Odd behaviour with dotnet core authentication system using JWT tokens
I have been testing my Web API authentication system for a while and have come across something really odd.

This are the steps I follow:

1 - I register an user and the system provides a JWT token

2 - I try to call API actions with the token and everything works as expected

3 - Now, I delete my database and rebuild it again with Add-Migration command

4 - There's no users in my database, but If I call an API action using the previous generated token (from point 1), it is accepted as a correctly authorized one. Remember, my database is clean. No users, no tokens, etc. registered.

Could anyone guess what is happening here?

答:
Token owner has access to your API till token is not expired. This is default behavior of JWT token implementation. You don't need to check the database for user and his privileges. Everything inside token. So this is like a cache. But if you want immediately change user rights and access params you have 3 ways:

Decrease of token's lifetime;

Write middleware and check user in database when performing parsing token data;

logout user from portal to force new login with new token;

Mostly business rules allow some delay for users in access updates or force them to re login.


问:
Linked list in C with OMP : memory issues
I've adapted a very nice omp-parallelized code to perform numerical integration I found here.
However, some massif profiling revealed that there is some serious memory-leaking going on...
I guess this is related to how popping elements from the stack is handeled, where the top element on the stack is returned but not removed from the stack.

So I figured, I could easily add this missing feature as I've done this before in serial code.
But I'm obiously doing something wrong because I'm getting an "invalid pointer error" after a couple of "frees" ...

Since I'm completely new to OMP I figured, I could ask you guys for help.
I'm really sorry, that I wasn't able to cut done my "example" more.
But I think, that it's important to see how the author implemented the linked list and which datastructures.

I guess most of the code below may be skipped, it looks fine to me.
The problem arises when I try to "free" the data associated with the top element of the stack in the function "pop_stack" at the very end.

Popping elements in serial seems to work fine - inside the parallel section it doesn't.
Can you spot the mistake(s) ?

Note: This is incomplete code. It won't compile.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <math.h>

int num_threads;
#define INITIAL_STACK_SIZE 128

/* the stack structure */
struct stack_s{
  int el_count;            /* count of elements on stack */
  int el_size;             /* size of an element */
  int mem_reserve;         /* allocated memory for stack */
  void* elements;          /* pointer to begin of stack */
};

struct myparams { double c1; double c1;};

typedef struct _work_t{
  double a;
  double b;
  double rec; /* max recursion depth */
  struct myparams * p;
} work_t;
typedef struct stack_s* stack_t;

void create_stack(stack_t* stack, int element_size);
int empty_stack(stack_t stack);
void push_stack(stack_t stack, void* element);
void pop_stack(stack_t stack, void* element);

double do_something(
  double (*f)(double,struct myparams*), /* function to be called  */
  double a,
  double b,
  int rec,   /*max. recursion depth*/
  struct myparams* p);

static double myfun(double x,struct myparams* p){ return  exp(-x*x)/p->a+log(x*pow(p->b,2.0));}

int main(int argc,char** argv)
{
  num_threads=omp_get_num_threads();
  double a=somevalue;
  double b=somevalue;

  struct myparams pinit;
  pinit.c1=someval;
  pinit.c2=someval;
  double answer=0;

  #pragma omp parallel
  {
    answer = do_something(myfun, xmin, xmax, 100, &pinit);
  } /* omp parallel */

  return 0;
}

double do_something(
  double (*f)(double,struct myparams*), /* function to be called  */
  double a,
  double b,
  int rec,
  struct myparams* p)
{
  stack_t stack;
  work_t work;

  int ready, idle, busy;

  /* prepare stack */
  work.a = a;
  work.b = b;
  work.rec=rec;
  work.p=p;

  create_stack(&stack, sizeof(work_t));
  push_stack(stack, &work);

  double result = 0.0;

  busy = 0;

#pragma omp parallel default(none) \
    shared(stack, result,f,busy) \
    private(work, idle, ready)
  {

    ready = 0;
    idle = 1;

    while(!ready )
    {

#pragma omp critical (stack)
      {
        if (!empty_stack(stack)){
          /* we have new work */
          pop_stack(stack, &work);

          if (idle){
            /* say others i'm busy */
            busy += 1;
            idle = 0;
          }

        }else{
          /* no new work on stack */
          if (!idle){
            busy -= 1;
            idle = 1;
          }

          /* nobody has anything to do; let us leave the loop */
          if (busy == 0)
            ready = 1;

        }
      } /* end critical(stack) */

      if (idle)
        continue;

      /* do some calculations using values saved in work and as well as the function f
         along with the function parameters saved in myparams
         -> estimate an error  & save it to 'delta' */

      if(rec <= 0 || fabs(delta) <= global_tolerance)
      {
        //error acceptable
#pragma omp critical (result)
        result += somevalue_computed_above;
      }
      else // error not acceptable
      {
        //push 2 new work-elements to stack
        //prepare 1st new elem.
        work.a = some_new_a;
        work.b = some_new_b;
        work.rec=rec-1;

  #pragma omp critical (stack)
        {
          push_stack(stack, &work);
          //prepare 2nd new element
          work.a = some_new_a2;
          work.b = some_new_b2;
          work.rec=rec-1;
          push_stack(stack, &work);

        }
      }
    } /* while */
  } /* end omp parallel */

  return result;
}

/******************************************
 * create new stack
 ******************************************/
void
create_stack(
             stack_t* stack,     /* stack to create */
             int element_size)   /* size of a stack element */
{
  int initial_size = INITIAL_STACK_SIZE;

  /* allocate memory for new stack struct */
  (*stack) = (stack_t) malloc(sizeof(struct stack_s));
  if (!(*stack)){
    fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
    exit(1);
  }

  /* allocate memory for stack elements */
  (*stack)->elements = (void*) malloc(element_size * initial_size);
  (*stack)->mem_reserve = initial_size;
  if (!(*stack)->elements){
    fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
    exit(1);
  }

  (*stack)->el_size = element_size;
  (*stack)->el_count = 0;

}

/*****************************************
 * check if the stack is empty
 *****************************************/
int
empty_stack
(stack_t stack)
{
  return stack->el_count <= 0;
}

/*****************************************
 * push a element on stack
 *****************************************/
void
push_stack(
           stack_t stack,    /* target stack */
           void* element)    /* element to push */
{
  int i, new_reserve;
  int log2_count;

  /* check if we need more memory for stack */
  if (stack->el_count >= stack->mem_reserve){

      /* calculate new size for the stack
         it should be a power of two */
      for (i = stack->el_count, log2_count = 0;
           i > 0;
           i>>1, log2_count++);
      new_reserve = 1 << log2_count;

      /* reallocate memory for phase thread tables
         and nullify new values */
      stack->elements = (void *) realloc(stack->elements,
                      stack->el_size * new_reserve);
      if (!stack->elements){
        fprintf(stderr, "error: can't reallocate stack.. Aborting\n");
        exit(1);
      }

      stack->mem_reserve = new_reserve;
  }

  /* now push the element on top of the stack */
  memcpy((char*)stack->elements + stack->el_count*stack->el_size,
            element, stack->el_size);
  stack->el_count++;

}

/*****************************************
 * pop an element from stack
 * THIS IS WHERE I SUSPECT A MISTAKE !
 *****************************************/
void pop_stack(
          stack_t stack,    /* target stack */
          void* element)    /* where poped el. should be stored */
{
  if (stack->el_count <= 0){
    fprintf(stderr, "error: trying to pop from empty stack.\n");
    exit(2);
  }

  stack->el_count--;
  memcpy(element,
         (char*)stack->elements + stack->el_count*stack->el_size,
         stack->el_size);

  // try to remove last element from stack
  // in original code there was no cleanup
  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2

}
</code>```

答:
So it looks like pop_stack() is only called inside some stack related critical region, so we can stop worrying about data races.

You identify this part of the code:

```<code>/*****************************************
 * pop an element from stack
 * THIS IS WHERE I SUSPECT A MISTAKE !
 *****************************************/
void pop_stack(
          stack_t stack,    /* target stack */
          void* element)    /* where poped el. should be stored */
{
  if (stack->el_count <= 0){
    fprintf(stderr, "error: trying to pop from empty stack.\n");
    exit(2);
  }

  stack->el_count--;
  memcpy(element,
         (char*)stack->elements + stack->el_count*stack->el_size,
         stack->el_size);

  // try to remove last element from stack
  // in original code there was no cleanup
  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2
}
</code>```

as the possible seat of the problem.  So the push_stack() clearly copies stack->el_size bytes of the element to the stack, and pop_stack() copies them back again.  That all looks wonderful.  The last part of pop_stack() is, however, a bit of a puzzle...

```<code>  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2
</code>```

stack->elements is a void* pointer to the first byte of the first element, so adding stack->el_count to that does not give you the address of the element that has just been popped, except when stack->el_count == 0 !!  So tmp is set to a nonsense value, and tmp->a is also, therefore, nonsense.  As for the free(tmp)... only when el_count == 0 (now) will the free() not fail, but it will destroy the stack.

Looking at the way the stack works does not suggest to me that the pop_stack() needs to do any "cleanup".  If you think it does, then you need to reconsider what that really needs to be.  It's possible that you are using the stack as a stack of pointers to "stuff"... but in any case, there's a little more work to be done.

Body:
I've adapted a very nice omp-parallelized code to perform numerical integration I found here.
However, some massif profiling revealed that there is some serious memory-leaking going on...
I guess this is related to how popping elements from the stack is handeled, where the top element on the stack is returned but not removed from the stack.

So I figured, I could easily add this missing feature as I've done this before in serial code.
But I'm obiously doing something wrong because I'm getting an "invalid pointer error" after a couple of "frees" ...

Since I'm completely new to OMP I figured, I could ask you guys for help.
I'm really sorry, that I wasn't able to cut done my "example" more.
But I think, that it's important to see how the author implemented the linked list and which datastructures.

I guess most of the code below may be skipped, it looks fine to me.
The problem arises when I try to "free" the data associated with the top element of the stack in the function "pop_stack" at the very end.

Popping elements in serial seems to work fine - inside the parallel section it doesn't.
Can you spot the mistake(s) ?

Note: This is incomplete code. It won't compile.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <omp.h>
#include <math.h>

int num_threads;
#define INITIAL_STACK_SIZE 128

/* the stack structure */
struct stack_s{
  int el_count;            /* count of elements on stack */
  int el_size;             /* size of an element */
  int mem_reserve;         /* allocated memory for stack */
  void* elements;          /* pointer to begin of stack */
};

struct myparams { double c1; double c1;};

typedef struct _work_t{
  double a;
  double b;
  double rec; /* max recursion depth */
  struct myparams * p;
} work_t;
typedef struct stack_s* stack_t;

void create_stack(stack_t* stack, int element_size);
int empty_stack(stack_t stack);
void push_stack(stack_t stack, void* element);
void pop_stack(stack_t stack, void* element);

double do_something(
  double (*f)(double,struct myparams*), /* function to be called  */
  double a,
  double b,
  int rec,   /*max. recursion depth*/
  struct myparams* p);

static double myfun(double x,struct myparams* p){ return  exp(-x*x)/p->a+log(x*pow(p->b,2.0));}

int main(int argc,char** argv)
{
  num_threads=omp_get_num_threads();
  double a=somevalue;
  double b=somevalue;

  struct myparams pinit;
  pinit.c1=someval;
  pinit.c2=someval;
  double answer=0;

  #pragma omp parallel
  {
    answer = do_something(myfun, xmin, xmax, 100, &pinit);
  } /* omp parallel */

  return 0;
}

double do_something(
  double (*f)(double,struct myparams*), /* function to be called  */
  double a,
  double b,
  int rec,
  struct myparams* p)
{
  stack_t stack;
  work_t work;

  int ready, idle, busy;

  /* prepare stack */
  work.a = a;
  work.b = b;
  work.rec=rec;
  work.p=p;

  create_stack(&stack, sizeof(work_t));
  push_stack(stack, &work);

  double result = 0.0;

  busy = 0;

#pragma omp parallel default(none) \
    shared(stack, result,f,busy) \
    private(work, idle, ready)
  {

    ready = 0;
    idle = 1;

    while(!ready )
    {

#pragma omp critical (stack)
      {
        if (!empty_stack(stack)){
          /* we have new work */
          pop_stack(stack, &work);

          if (idle){
            /* say others i'm busy */
            busy += 1;
            idle = 0;
          }

        }else{
          /* no new work on stack */
          if (!idle){
            busy -= 1;
            idle = 1;
          }

          /* nobody has anything to do; let us leave the loop */
          if (busy == 0)
            ready = 1;

        }
      } /* end critical(stack) */

      if (idle)
        continue;

      /* do some calculations using values saved in work and as well as the function f
         along with the function parameters saved in myparams
         -> estimate an error  & save it to 'delta' */

      if(rec <= 0 || fabs(delta) <= global_tolerance)
      {
        //error acceptable
#pragma omp critical (result)
        result += somevalue_computed_above;
      }
      else // error not acceptable
      {
        //push 2 new work-elements to stack
        //prepare 1st new elem.
        work.a = some_new_a;
        work.b = some_new_b;
        work.rec=rec-1;

  #pragma omp critical (stack)
        {
          push_stack(stack, &work);
          //prepare 2nd new element
          work.a = some_new_a2;
          work.b = some_new_b2;
          work.rec=rec-1;
          push_stack(stack, &work);

        }
      }
    } /* while */
  } /* end omp parallel */

  return result;
}

/******************************************
 * create new stack
 ******************************************/
void
create_stack(
             stack_t* stack,     /* stack to create */
             int element_size)   /* size of a stack element */
{
  int initial_size = INITIAL_STACK_SIZE;

  /* allocate memory for new stack struct */
  (*stack) = (stack_t) malloc(sizeof(struct stack_s));
  if (!(*stack)){
    fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
    exit(1);
  }

  /* allocate memory for stack elements */
  (*stack)->elements = (void*) malloc(element_size * initial_size);
  (*stack)->mem_reserve = initial_size;
  if (!(*stack)->elements){
    fprintf(stderr, "error: could not allocate memory for stack.. Abort.\n");
    exit(1);
  }

  (*stack)->el_size = element_size;
  (*stack)->el_count = 0;

}

/*****************************************
 * check if the stack is empty
 *****************************************/
int
empty_stack
(stack_t stack)
{
  return stack->el_count <= 0;
}

/*****************************************
 * push a element on stack
 *****************************************/
void
push_stack(
           stack_t stack,    /* target stack */
           void* element)    /* element to push */
{
  int i, new_reserve;
  int log2_count;

  /* check if we need more memory for stack */
  if (stack->el_count >= stack->mem_reserve){

      /* calculate new size for the stack
         it should be a power of two */
      for (i = stack->el_count, log2_count = 0;
           i > 0;
           i>>1, log2_count++);
      new_reserve = 1 << log2_count;

      /* reallocate memory for phase thread tables
         and nullify new values */
      stack->elements = (void *) realloc(stack->elements,
                      stack->el_size * new_reserve);
      if (!stack->elements){
        fprintf(stderr, "error: can't reallocate stack.. Aborting\n");
        exit(1);
      }

      stack->mem_reserve = new_reserve;
  }

  /* now push the element on top of the stack */
  memcpy((char*)stack->elements + stack->el_count*stack->el_size,
            element, stack->el_size);
  stack->el_count++;

}

/*****************************************
 * pop an element from stack
 * THIS IS WHERE I SUSPECT A MISTAKE !
 *****************************************/
void pop_stack(
          stack_t stack,    /* target stack */
          void* element)    /* where poped el. should be stored */
{
  if (stack->el_count <= 0){
    fprintf(stderr, "error: trying to pop from empty stack.\n");
    exit(2);
  }

  stack->el_count--;
  memcpy(element,
         (char*)stack->elements + stack->el_count*stack->el_size,
         stack->el_size);

  // try to remove last element from stack
  // in original code there was no cleanup
  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2

}

Body:
So it looks like pop_stack() is only called inside some stack related critical region, so we can stop worrying about data races.

You identify this part of the code:

/*****************************************
 * pop an element from stack
 * THIS IS WHERE I SUSPECT A MISTAKE !
 *****************************************/
void pop_stack(
          stack_t stack,    /* target stack */
          void* element)    /* where poped el. should be stored */
{
  if (stack->el_count <= 0){
    fprintf(stderr, "error: trying to pop from empty stack.\n");
    exit(2);
  }

  stack->el_count--;
  memcpy(element,
         (char*)stack->elements + stack->el_count*stack->el_size,
         stack->el_size);

  // try to remove last element from stack
  // in original code there was no cleanup
  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2
}

as the possible seat of the problem.  So the push_stack() clearly copies stack->el_size bytes of the element to the stack, and pop_stack() copies them back again.  That all looks wonderful.  The last part of pop_stack() is, however, a bit of a puzzle...

  struct _work_t *tmp = (struct _work_t*) stack->elements+stack->el_count;
  printf("ncount:%d, foo:%f\n",stack->el_count+1,tmp->a);
  free(tmp); //Works as long as el_count == 1 but fails if it becomes 2

stack->elements is a void* pointer to the first byte of the first element, so adding stack->el_count to that does not give you the address of the element that has just been popped, except when stack->el_count == 0 !!  So tmp is set to a nonsense value, and tmp->a is also, therefore, nonsense.  As for the free(tmp)... only when el_count == 0 (now) will the free() not fail, but it will destroy the stack.

Looking at the way the stack works does not suggest to me that the pop_stack() needs to do any "cleanup".  If you think it does, then you need to reconsider what that really needs to be.  It's possible that you are using the stack as a stack of pointers to "stuff"... but in any case, there's a little more work to be done.


问:
java.util.zip.ZipException: invalid code lengths set with SentenceModel
I'm using OpenNLP for syntactic analysis. I wrote these lines to load the
 Sentence detector model:

```<code>    InputStream is = getClass().getClassLoader().getResourceAsStream("models/en-sent.bin") ;
    SentenceModel sModel = new SentenceModel(is);
</code>```

the above line throws the exception: java.util.zip.ZipException: invalid code
 lengths set.

The "models/en-sent.bin" is located under "src/main/resources/models/en-
 token.bin".

When I try to print the file path using:

```<code>   System.out.println(getClass().getClassLoader().getResource("models/en-sent.bin"));
</code>```

The path shows as : "file:/C:/Users/aaa/workspace/qa/target/classes/models/en-sent.bin".
if I load the model using:

```<code>    InputStream is =  new FileInputStream("src/main/resources/models/en-sent.bin") ;
    SentenceModel sModel = new SentenceModel(is);
</code>```

It works fine, but this method will not work when I build the file into a runnable jar. Any help why this Exception is thrown?

The full stack exception is here:

```<code>java.util.zip.ZipException: invalid code lengths set
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.util.zip.ZipInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at opennlp.tools.util.model.PropertiesSerializer.create(PropertiesSerializer.java:31)
at opennlp.tools.util.model.PropertiesSerializer.create(PropertiesSerializer.java:27)
at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:224)
at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:173)
at opennlp.tools.sentdetect.SentenceModel.<init>(SentenceModel.java:91)
at com.elsevier.sherpath.syntactic_analysis.QuestionNLPAnalysis.<init>(QuestionNLPAnalysis.java:88)
at com.elsevier.sherpath.main.QuestionProcessing.syntacticAnalysis(QuestionProcessing.java:255)
at com.elsevier.sherpath.main.BatchProcess.main(BatchProcess.java:23)
</code>```

Thanks

答:
We can also use this Plugin:

```<code> <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
            <configuration>
                <nonFilteredFileExtensions>
                    <nonFilteredFileExtension>bin</nonFilteredFileExtension>
                </nonFilteredFileExtensions>
            </configuration>
        </plugin>
</code>```

Body:
I'm using OpenNLP for syntactic analysis. I wrote these lines to load the
 Sentence detector model:

    InputStream is = getClass().getClassLoader().getResourceAsStream("models/en-sent.bin") ;
    SentenceModel sModel = new SentenceModel(is);

the above line throws the exception: java.util.zip.ZipException: invalid code
 lengths set.

The "models/en-sent.bin" is located under "src/main/resources/models/en-
 token.bin".

When I try to print the file path using:

   System.out.println(getClass().getClassLoader().getResource("models/en-sent.bin"));

The path shows as : "file:/C:/Users/aaa/workspace/qa/target/classes/models/en-sent.bin".
if I load the model using:

    InputStream is =  new FileInputStream("src/main/resources/models/en-sent.bin") ;
    SentenceModel sModel = new SentenceModel(is);

It works fine, but this method will not work when I build the file into a runnable jar. Any help why this Exception is thrown?

The full stack exception is here:

java.util.zip.ZipException: invalid code lengths set
at java.util.zip.InflaterInputStream.read(Unknown Source)
at java.util.zip.ZipInputStream.read(Unknown Source)
at java.io.FilterInputStream.read(Unknown Source)
at java.util.Properties$LineReader.readLine(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at opennlp.tools.util.model.PropertiesSerializer.create(PropertiesSerializer.java:31)
at opennlp.tools.util.model.PropertiesSerializer.create(PropertiesSerializer.java:27)
at opennlp.tools.util.model.BaseModel.loadModel(BaseModel.java:224)
at opennlp.tools.util.model.BaseModel.<init>(BaseModel.java:173)
at opennlp.tools.sentdetect.SentenceModel.<init>(SentenceModel.java:91)
at com.elsevier.sherpath.syntactic_analysis.QuestionNLPAnalysis.<init>(QuestionNLPAnalysis.java:88)
at com.elsevier.sherpath.main.QuestionProcessing.syntacticAnalysis(QuestionProcessing.java:255)
at com.elsevier.sherpath.main.BatchProcess.main(BatchProcess.java:23)

Thanks

Body:
We can also use this Plugin:

 <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.1.0</version>
            <configuration>
                <nonFilteredFileExtensions>
                    <nonFilteredFileExtension>bin</nonFilteredFileExtension>
                </nonFilteredFileExtensions>
            </configuration>
        </plugin>


问:
How to fetch the input elements value by class name in jquery
I want to fetch input elements value, they have class "features". I can access all of them

alert($('.features').length);

Correct me if I am wrong, $('.features') is an array of html input elements.But I tried

Array.isArray($('.features')) // returned false

I want to access the value of each element . How to achieve this
I tried to do one and below is the code snippet

function maintest() {

 for(i = 0 ; i < 5 ; i ++ ) {
  $("<input>").attr({"class":"features"}).appendTo("#mainDiv").val("input"+i);
  $("

").appendTo("#mainDiv");
 }

  $("<button> Click me! </button>").click(function() {
  let inputArray = [];
  inputArray = $('.features');
  alert(inputArray.length);
    //alert( inputArray[0].val());
    //what must be put here to see the data value
  }).appendTo("#mainDiv");
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body></code>```

答:
In javascript, setting a variable to a value overwrites the previous value.  It doesn't enforce the type, so these lines:

```<code>let inputArray = [];
inputArray = $('.features');
</code>```

is the same as

```<code>let inputArray = $('.features');
</code>```

$() returns a jquery collection, not a javascript array; there are, of course, similarities, but it's not an "array".

To get the values out you can loop through the collection or you can use .map to extract values, eg:

```<code>var valuesArray = $('.features').map(function() {
                      return $(this).val();
                  }).toArray();
</code>```

function maintest() {

  for (i = 0; i < 5; i++) {
    $("<input>").attr({ "class": "features" })
        .appendTo("#mainDiv")
        .val("input" + i);
    $("

").appendTo("#mainDiv");
  }

  $("<button> Click me! </button>").click(function() {
    let inputArray = $('.features');
    var values = inputArray.map(function() {
      return $(this).val();
    }).toArray();
    console.log(values);
  }).appendTo("#mainDiv");
}

$(() => maintest());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mainDiv"></div></code>```

Body:
In javascript, setting a variable to a value overwrites the previous value.  It doesn't enforce the type, so these lines:

let inputArray = [];
inputArray = $('.features');

is the same as

let inputArray = $('.features');

$() returns a jquery collection, not a javascript array; there are, of course, similarities, but it's not an "array".

To get the values out you can loop through the collection or you can use .map to extract values, eg:

var valuesArray = $('.features').map(function() {
                      return $(this).val();
                  }).toArray();

function maintest() {

  for (i = 0; i < 5; i++) {
    $("<input>").attr({ "class": "features" })
        .appendTo("#mainDiv")
        .val("input" + i);
    $("<br/><br/>").appendTo("#mainDiv");
  }

  $("<button> Click me! </button>").click(function() {
    let inputArray = $('.features');
    var values = inputArray.map(function() {
      return $(this).val();
    }).toArray();
    console.log(values);
  }).appendTo("#mainDiv");
}

$(() => maintest());

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mainDiv"></div>


答:
You have to join both tables on cpId column and group the rows with similar cpId.
Where can be used to filter rows.
Below query gives you the cpId and their corresponding next available minimum sequence number.</p>

```<code>SELECT t1.cpId, MIN(t1.sequenceNumber + 10) AS nextID
FROM LogicalConnection t1
LEFT JOIN LogicalConnection t2
       ON t1.sequenceNumber + 10 = t2.sequenceNumber
       and t1.cpId = t2.cpId
group by (t1.cpId)
</code>```

Title: MySQL: Add a WHERE in a LEFT JOIN

Body:
I have the following table:

SequenceNumber are always a multiple of 10. I would like to get, for a specific cpId, the smallest free sequence number (still in a multiple of 10). For example, for cpId = 1, the smallest available should be 20. For cpId = 2, it should be 10.

I have the following statement to get the smallest available sequenceNumber for all cpId, and I don't know how I can add a WHERE cpId = x inside the statement:

SELECT MIN(t1.sequenceNumber + 10) AS nextID
FROM LogicalConnection t1
   LEFT JOIN LogicalConnection t2
       ON t1.sequenceNumber + 10 = t2.sequenceNumber
WHERE t2.sequenceNumber IS NULL;

DB fiddle: https://www.db-fiddle.com/f/ag67AkFzfwPZEva8bTN7Q3/2#&togetherjs=L9nHb3Uu7O

Thank you for your help!

Body:
You have to join both tables on cpId column and group the rows with similar cpId.
Where can be used to filter rows.
Below query gives you the cpId and their corresponding next available minimum sequence number.

SELECT t1.cpId, MIN(t1.sequenceNumber + 10) AS nextID
FROM LogicalConnection t1
LEFT JOIN LogicalConnection t2
       ON t1.sequenceNumber + 10 = t2.sequenceNumber
       and t1.cpId = t2.cpId
group by (t1.cpId)


问:
How do I make my Angular 8 application use the whole viewport?
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

```<code><body>
  <app-nav-menu></app-nav-menu>
  <div class="container" id="main-container">
    <router-outlet></router-outlet>
  </div>
</body>
</code>```

styles.css

```<code>body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}
</code>```

答:
The body tag in your html page has a default padding.

So, you need to remove that padding by adding the following code.

"style.css"

```<code>body {
   width: 100%;
   height: 100vh; /* This take the whole viewport height */

   margin: 0;
   padding: 0; /* Remove the default padding */
}
</code>```

Body:
I am developing a single-page application consisting of a navbar and a router-outlet which displays the component selected in the navbar. The primary component which loads by default is a Leaflet map which I would like to fill the entire page aside from the navbar. Currently I cannot even get the main component to fill the whole page, as it insists on including white space on the sides. I've set the container to have a high-res background image so I can see how much space it is actually filling.

The main page with all its unnecessary whitespace

The code:

app.component.html

  <app-nav-menu></app-nav-menu>

    <router-outlet></router-outlet>

styles.css

body {
height: 98vh;
width: 98vw;
}

html, body, .container {
    height: 100%;
    overflow: hidden;
    width: 100%;
}

#main-container {
  background-image: url("src/assets/chicago-wallpaper.jpg");
  width: 98vw;
  height: 94vh;
}

Body:
The body tag in your html page has a default padding.

So, you need to remove that padding by adding the following code.

"style.css"

body {
   width: 100%;
   height: 100vh; /* This take the whole viewport height */

   margin: 0;
   padding: 0; /* Remove the default padding */
}