问:
handling expo push notifications when app is closed
Expo sdk 37

```<code>componentDidMount() {
this.registerForPushNotificationsAsync();
this._notificationSubscription = Notifications.addListener(this._handleNotification);
}
_handleNotification = notification => {
Vibration.vibrate();
console.log(notification);
console.log(“hello”)
this.setState({ notification: notification });
};

</code>```

When the app is foregrounded the handle function is executed and the console.log is executed but when the app is closed the handle function is not executed at all?
Can anyone help?

答:
Solved it by adding this in app.json file</p>

```<code>{
  "expo": {
    "userInterfaceStyle": "automatic",
    "ios": {
      "userInterfaceStyle": "light"
    },
    "android": {
      "userInterfaceStyle": "dark"
    }
  }
}
</code>```

Body:
Expo sdk 37

componentDidMount() {
this.registerForPushNotificationsAsync();
this._notificationSubscription = Notifications.addListener(this._handleNotification);
}
_handleNotification = notification => {
Vibration.vibrate();
console.log(notification);
console.log(“hello”)
this.setState({ notification: notification });
};

When the app is foregrounded the handle function is executed and the console.log is executed but when the app is closed the handle function is not executed at all?
Can anyone help?

Body:
Solved it by adding this in app.json file

{
  "expo": {
    "userInterfaceStyle": "automatic",
    "ios": {
      "userInterfaceStyle": "light"
    },
    "android": {
      "userInterfaceStyle": "dark"
    }
  }
}


来源: stackexchange

问:
How to extract a String from a TextView (AndroidStudio)?
My application retrieves data from the Firebase Database and displays it in a RecyclerView.
The app already displays the title, the headline and the 3 labels just fine.
Additionally it should check if a title is the String "Test". If it is it should display a certain image.

This is my Adapter

```<code>public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

   Context context;
   ArrayList<NewsCard> newsCards;

   public  MyAdapter(Context c , ArrayList<NewsCard> n){
       context = c;
       newsCards = n;
   }
   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row, parent, false));
   }

   @Override
   public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
       holder.title.setText(newsCards.get(position).getTitle());
       holder.headline.setText(newsCards.get(position).getHeadline());
       holder.label1.setText(newsCards.get(position).getLabel1());
       holder.label2.setText(newsCards.get(position).getLabel2());
       holder.lable3.setText(newsCards.get(position).getLabel3());

   }

   @Override
   public int getItemCount() {

       return newsCards.size();
   }

   class MyViewHolder extends RecyclerView.ViewHolder
   {

       TextView title, headline,label1,label2,lable3;
       ImageView icon;

       public MyViewHolder(@NonNull View itemView) {

           super(itemView);

           title = (TextView) itemView.findViewById(R.id.title);

           headline = (TextView) itemView.findViewById(R.id.headline);
           label1 = (TextView) itemView.findViewById(R.id.lable1);
           label2 = (TextView) itemView.findViewById(R.id.lable2);
           lable3 = (TextView) itemView.findViewById(R.id.lable3);
           icon = (ImageView) itemView.findViewById(R.id.iconT);

           String test = title.getText().toString();
           if (test == "Test"){
               icon.setImageResource(R.drawable.common_google_signin_btn_icon_dark_focused);

           }

       }
   }
}
</code>```

As you can see I tried to extract the String from the TextView but somehow it isn't working even if there are titles with the value "Test".

```<code> @Override
    public int getItemCount() {

        return newsCards.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {

        TextView title, headline,label1,label2,lable3;
        ImageView icon;

        public MyViewHolder(@NonNull View itemView) {

            super(itemView);

            title = (TextView) itemView.findViewById(R.id.title);

            headline = (TextView) itemView.findViewById(R.id.headline);
            label1 = (TextView) itemView.findViewById(R.id.lable1);
            label2 = (TextView) itemView.findViewById(R.id.lable2);
            lable3 = (TextView) itemView.findViewById(R.id.lable3);
            icon = (ImageView) itemView.findViewById(R.id.iconT);

            String test = title.getText().toString();
            if (test == "Test"){
                icon.setImageResource(R.drawable.common_google_signin_btn_icon_dark_focused);

            }

        }
    }
</code>```

I have already checked if the problem is with the RecyclerView itself but I am confident that that's not the reason why it isn't working.

答:
Try to use if (test.equals("Test")) while comparing strings

== tests for reference equality (whether they are the same object).

.equals() tests for value equality (whether they are logically "equal").

ContentLicense: CC BY-SA 4.0

Body:
My application retrieves data from the Firebase Database and displays it in a RecyclerView.
The app already displays the title, the headline and the 3 labels just fine.
Additionally it should check if a title is the String "Test". If it is it should display a certain image.

This is my Adapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

   Context context;
   ArrayList<NewsCard> newsCards;

   public  MyAdapter(Context c , ArrayList<NewsCard> n){
       context = c;
       newsCards = n;
   }
   @NonNull
   @Override
   public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
       return new MyViewHolder(LayoutInflater.from(context).inflate(R.layout.row, parent, false));
   }

   @Override
   public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
       holder.title.setText(newsCards.get(position).getTitle());
       holder.headline.setText(newsCards.get(position).getHeadline());
       holder.label1.setText(newsCards.get(position).getLabel1());
       holder.label2.setText(newsCards.get(position).getLabel2());
       holder.lable3.setText(newsCards.get(position).getLabel3());

   }

   @Override
   public int getItemCount() {

       return newsCards.size();
   }

   class MyViewHolder extends RecyclerView.ViewHolder
   {

       TextView title, headline,label1,label2,lable3;
       ImageView icon;

       public MyViewHolder(@NonNull View itemView) {

           super(itemView);

           title = (TextView) itemView.findViewById(R.id.title);

           headline = (TextView) itemView.findViewById(R.id.headline);
           label1 = (TextView) itemView.findViewById(R.id.lable1);
           label2 = (TextView) itemView.findViewById(R.id.lable2);
           lable3 = (TextView) itemView.findViewById(R.id.lable3);
           icon = (ImageView) itemView.findViewById(R.id.iconT);

           String test = title.getText().toString();
           if (test == "Test"){
               icon.setImageResource(R.drawable.common_google_signin_btn_icon_dark_focused);

           }

       }
   }
}

As you can see I tried to extract the String from the TextView but somehow it isn't working even if there are titles with the value "Test".

 @Override
    public int getItemCount() {

        return newsCards.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder
    {

        TextView title, headline,label1,label2,lable3;
        ImageView icon;

        public MyViewHolder(@NonNull View itemView) {

            super(itemView);

            title = (TextView) itemView.findViewById(R.id.title);

            headline = (TextView) itemView.findViewById(R.id.headline);
            label1 = (TextView) itemView.findViewById(R.id.lable1);
            label2 = (TextView) itemView.findViewById(R.id.lable2);
            lable3 = (TextView) itemView.findViewById(R.id.lable3);
            icon = (ImageView) itemView.findViewById(R.id.iconT);

            String test = title.getText().toString();
            if (test == "Test"){
                icon.setImageResource(R.drawable.common_google_signin_btn_icon_dark_focused);

            }

        }
    }

I have already checked if the problem is with the RecyclerView itself but I am confident that that's not the reason why it isn't working.


问:
Gremlin Client Connecting to Gremlin / JanusGraph Server via URL-based Load Balancers
Due to security policies, I have a cluster of JanusGraph servers (running in an internal Kubernetes network) that can be accessed by external Gremlin clients via the below network route:

clients --> global load balancer (URL-based) --> third-party firewall --> internal load balancer --> graph servers

The endpoint exposed by the global load balancer is something like e.g. https://myhost.com/mypath1/mypath2/

This approach works fine for HTTP(S) based requests, as I am able to receive a response from the gremlin server when firing a curl command to the above global load balancer endpoint.

However, I have 2 other gremlin client usage patterns:

using gremlin.sh console

using gremlin-python client (or more generally, WebSocket clients)

Hence my questions are:

In the remote.yaml file used by gremlin.sh client, how do I specify the global load balancer endpoint in the hosts and port parameters?

I have tried a few combinations (e.g. hosts = ['myhost.com']/['myhost.com/mypath1/mypath2'], port = 8182/443) but they all don't work

In gremlin-python client, I am using a WebSocket-based connection. How do I specify the websocket connection string with the above endpoint?

I have tried various connection strings (e.g. ws(s)://myhost.com/mypath1/mypath2/gremlin) but they don't work too

答:
In the remote.yaml file used by gremlin.sh client, how do I specify the global load balancer endpoint in the hosts and port parameters?

For hosts you should just supply the host name (no path) and for port, it should just be 443 assuming that is the port you've exposed on your load balancer. Of course you also need to enable SSL - as an example note the settings provided in the packaged remote-secure.yaml file and see additional configuration options in https://tinkerpop.apache.org/docs/current/reference/#_configuration.

As for your custom path of mypath1/mypath2/gremlin, that is not configurable at this time. It expects that path to be /gremlin. I've created TINKERPOP-2379 in response.

In gremlin-python client, I am using a WebSocket-based connection. How do I specify the websocket connection string with the above endpoint?

I would expect this to work for Python: wss://myhost.com:443/mypath1/mypath2/gremlin


问:
How can I work with Iterables in my JSP pages?
I'm using an API that makes heavy use of Iterables (java.lang.Iterable), but I can't use them directly on my JSP pages because JSTL tags and EL can not process them. Right now, I'm transforming each iterable to a list prior to rendering them.

What would be the cleanest and simplest approach to make it work without previous transformations?
Do newest JSTL-Jasper-EL-taglibs-etc. versions support it? Where can I found that information? I don't find anything about it googling...

I know I can use Iterable.iterator(), but I can't call that method inside the JSP, only in my controller class, and this is very limiting.

答:
You can implement your own JSP tags in Java, so you could write a tag that accepted an Iterable and then use that in the same way as you'd use the JSTL forEach tag.

This documentation has an example on how to create a custom tag that iterates through an arbitrary custom object - your implementation would likely be simpler. The key is in returning EVAL_BODY_AGAIN to allow you to process the body of the tag multiple times.

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags6.html#68297

I haven't tried running this, but it might be something to start with:

```<code>public class IterableForEachTag extends BodyTagSupport {
    private static final long serialVersionUID = 1L;
    private Iterable<?> iterable = null;
    private Iterator<?> iterator = null;
    private String var = null;

    public int doStartTag() throws JspException {
        if (iterator == null) {
            iterator = iterable.iterator();
        }
        if (iterator.hasNext()) {
            Object element = iterator.next();
            pageContext.setAttribute(var, element);
            return (EVAL_BODY_AGAIN);
        } else
            return (SKIP_BODY);
    }

    public int doAfterBody() throws JspException {
        if (bodyContent != null) {
            try {
                JspWriter out = getPreviousOut();
                out.print(bodyContent.getString());
                bodyContent.clearBody();
            } catch (IOException e) {
                throw new JspException(e);
            }
        }
        if (iterator.hasNext()) {
            Object element = iterator.next();
            pageContext.setAttribute(var, element);
            return (EVAL_BODY_AGAIN);
        } else {
            return (SKIP_BODY);
        }
    }

    public void setIterable(Iterable i) {
        iterable = i;
        iterator = null;
    }

    public void setVar(String v) {
        var = v;
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can implement your own JSP tags in Java, so you could write a tag that accepted an Iterable and then use that in the same way as you'd use the JSTL forEach tag.

This documentation has an example on how to create a custom tag that iterates through an arbitrary custom object - your implementation would likely be simpler. The key is in returning EVAL_BODY_AGAIN to allow you to process the body of the tag multiple times.

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags6.html#68297

I haven't tried running this, but it might be something to start with:

public class IterableForEachTag extends BodyTagSupport {
    private static final long serialVersionUID = 1L;
    private Iterable<?> iterable = null;
    private Iterator<?> iterator = null;
    private String var = null;

    public int doStartTag() throws JspException {
        if (iterator == null) {
            iterator = iterable.iterator();
        }
        if (iterator.hasNext()) {
            Object element = iterator.next();
            pageContext.setAttribute(var, element);
            return (EVAL_BODY_AGAIN);
        } else
            return (SKIP_BODY);
    }

    public int doAfterBody() throws JspException {
        if (bodyContent != null) {
            try {
                JspWriter out = getPreviousOut();
                out.print(bodyContent.getString());
                bodyContent.clearBody();
            } catch (IOException e) {
                throw new JspException(e);
            }
        }
        if (iterator.hasNext()) {
            Object element = iterator.next();
            pageContext.setAttribute(var, element);
            return (EVAL_BODY_AGAIN);
        } else {
            return (SKIP_BODY);
        }
    }

    public void setIterable(Iterable i) {
        iterable = i;
        iterator = null;
    }

    public void setVar(String v) {
        var = v;
    }
}


问:
Cytoscape layout to use node attributes as coordinates?
Is there a way to use x,y coordinates stored as attributes of each node to layout a graph using the coordinates that were calculated by another program?

And if not, would it be possible to implement this somehow - how does one get started on this?

Is there a standard way how to provide the node positions to the cytoscape.js web viewer somehow?

Background: it is trivial to use Python networkx to calculate some layouts which are not supported in Cytoscape, and it would also be trivial to store the coordinates as node attributes. All that would then be need is some way for Cytoscape to use those coordinates to find node positions instead of using a layout algorithm.

答:
This is a quite easy thing to do. Many examples on  use this functionlity in the demos, as you can see here:

1: FCose Demo

2: Cose Blicent Demo

3: d3-force Demo

4: Euler Compound Demo

5: Spread Demo

As you can see, there are an abundance of examples for this in the demos, but also in the docs. You can see one here and here:

```<code>// can use reference to eles later
var eles = cy.add([
  { group: 'nodes', data: { id: 'n0' }, position: { x: 100, y: 100 } },
  { group: 'nodes', data: { id: 'n1' }, position: { x: 200, y: 200 } },
  { group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' } }
]);
</code>```

The json used in the .add() function can be created in your js application or directly in Python and added to the graph as some of the examples do.

In general, you should take some time and skim through through the docs. The ability to position nodes via x and y is quite basic and is one of the first pages in the docs.

If you don't understand the description in the docs and the examples I provided, please edit your question and add your current code as a Minimal, Reproducible Example, where you can show your efforts to implement the positioning.

Edit:

As @maxkfranz pointed out, the preset layout plays a big role here. The documentation states this in the Initialisation Chapter:

If you want to specify your node positions yourself in your elements JSON, you can use the preset layout — by default it does not set any positions, leaving your nodes in their current positions (i.e. specified in options.elements at initialisation time).`

Body:
This is a quite easy thing to do. Many examples on  use this functionlity in the demos, as you can see here:

1: FCose Demo

2: Cose Blicent Demo

3: d3-force Demo

4: Euler Compound Demo

5: Spread Demo

As you can see, there are an abundance of examples for this in the demos, but also in the docs. You can see one here and here:

// can use reference to eles later
var eles = cy.add([
  { group: 'nodes', data: { id: 'n0' }, position: { x: 100, y: 100 } },
  { group: 'nodes', data: { id: 'n1' }, position: { x: 200, y: 200 } },
  { group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' } }
]);

The json used in the .add() function can be created in your js application or directly in Python and added to the graph as some of the examples do.

In general, you should take some time and skim through through the docs. The ability to position nodes via x and y is quite basic and is one of the first pages in the docs.

If you don't understand the description in the docs and the examples I provided, please edit your question and add your current code as a Minimal, Reproducible Example, where you can show your efforts to implement the positioning.

Edit:

As @maxkfranz pointed out, the preset layout plays a big role here. The documentation states this in the Initialisation Chapter:

If you want to specify your node positions yourself in your elements JSON, you can use the preset layout — by default it does not set any positions, leaving your nodes in their current positions (i.e. specified in options.elements at initialisation time).`


问:
Django REST Framework: Serializer to update object if it exists (by unique together)
I have model Run. It represents a time period measurement of data:

```<code>class Run(models.Model):
    start_time      = models.DateTimeField(db_index=True)
    end_time        = models.DateTimeField()
    chamber         = models.ForeignKey(Chamber, on_delete=models.CASCADE)

    class Meta:
        unique_together=(('start_time', 'chamber'),)
</code>```

Here is an example of a POST request data blurb for this endpoint:

```<code>{
    "start_time": "2018-11-11T12:00:00Z",
    "end_time": "2018-11-11T12:00:01Z",
    "chamber": "My Test Chamber"
}
</code>```

A Run belongs to a Chamber and has a start_time and end_time

A Run cannot share the same Chamber and start_time. If I get the same start_time and Chamber in my request data blurb, that means the Run is still ongoing and needs to be updated.

When the request comes through the first time, I create a Run object, that works fine. The sensor that is sending the requests will then send the same POST request data blurb, changing only the end_time of the data blurb, as long as a "Run" is ongoing.

The sensor does not send PUT or PATCH, it only sends POST, this may be a problem, but it's unfixable so I have to make do with POST requests.

The behaviour I desire is:

The first time a Run data blurb is sent, create a new Run object

As long as I receive the same Chamber and run_start in a data blurb, (check that this combination exists), update that Run's end_time (a Run is ongoing)

Here is Serializer:

```<code>class RunsCreateSerializer(ModelSerializer):
    class Meta:
        model = Run
        fields = [
            'id',
            'chamber',
            'start_time',
            'end_time'
        ]
</code>```

Here is views.py on API endpoint:

```<code>class RunsCreateAPIView(CreateAPIView):
    queryset = Run.objects.all()
    queryset = queryset.prefetch_related('chamber')
    serializer_class = RunsCreateSerializer
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        try:
            chamber = Chamber.objects.get(chamber_name=request.data["chamber"])
            request.data["chamber"] = chamber.id
        except:
            print("Invalid chamber name")

        serializer = RunsCreateSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)
</code>```

Now, I found I had to modify "create" on the views.py a little, as the sensor sends the Chamber as a string identifier. I then have to check that string against my Chambers table and retrieve the object instance, then modify the request data  to substitute the Chamber string for its ID on my DB. I'm not sure if that is the right approach but it worked for me then.

Now for my attempt at fixing this:

On serializers.py:

```<code>def create(self, validated_data):
    run, created = Run.objects.update_or_create(
                    chamber=validated_data.get('chamber'),
                    start_time=validated_data.get('start_time'),
                    end_time=validated_data.get('end_time'))
    return run

def update(self, run, validated_data):
    run.chamber = validated_data.get('chamber', run.chamber)
    run.start_time = validated_data.get('start_time', run.start_time)
    run.created = validated_data.get('created', run.created)
    run.save()
    return run
</code>```

I thought by doing this on my serializer I would be able to update the object, but it doesn't seem to be reaching that point (tried with a print("Sanity check") on the create and update methods, I don't see my sanity check output, so I know I'm not reaching that point).

I suspect it has to do with me overriding the create method on the view, but I'm not sure.

If you know how to update the object, and possibly have the serializer/view handle a string for Chamber name instead of having to meddle with methods to replace strings for IDs, I would greatly appreciate your help.

答:
As you mentioned that you are getting chamber as a string, so to handle that relationship properly, use chamber = serializer.StringRelatedField() in your serializer. Remove any method which you have overridden in serializer/view. Just add the following in your RunsCreateAPIView.

```<code>def perform_create(self, serializer):
    chamber=serializer.validated_data.get('chamber'),
    start_time=serializer.validated_data.get('start_time')
    end_time=serializer.validated_data.get('end_time')
    Run.objects.update_or_create(
                  chamber=chamber,
                  start_time=start_time,
                  defaults = {"end_time": end_time}
                  )
</code>```

update_or_create will automatically handle the creation or updating based on the value of chamber and start_time.

Body:
I have model Run. It represents a time period measurement of data:

class Run(models.Model):
    start_time      = models.DateTimeField(db_index=True)
    end_time        = models.DateTimeField()
    chamber         = models.ForeignKey(Chamber, on_delete=models.CASCADE)

    class Meta:
        unique_together=(('start_time', 'chamber'),)

Here is an example of a POST request data blurb for this endpoint:

{
    "start_time": "2018-11-11T12:00:00Z",
    "end_time": "2018-11-11T12:00:01Z",
    "chamber": "My Test Chamber"
}

A Run belongs to a Chamber and has a start_time and end_time

A Run cannot share the same Chamber and start_time. If I get the same start_time and Chamber in my request data blurb, that means the Run is still ongoing and needs to be updated.

When the request comes through the first time, I create a Run object, that works fine. The sensor that is sending the requests will then send the same POST request data blurb, changing only the end_time of the data blurb, as long as a "Run" is ongoing.

The sensor does not send PUT or PATCH, it only sends POST, this may be a problem, but it's unfixable so I have to make do with POST requests.

The behaviour I desire is:

The first time a Run data blurb is sent, create a new Run object

As long as I receive the same Chamber and run_start in a data blurb, (check that this combination exists), update that Run's end_time (a Run is ongoing)

Here is Serializer:

class RunsCreateSerializer(ModelSerializer):
    class Meta:
        model = Run
        fields = [
            'id',
            'chamber',
            'start_time',
            'end_time'
        ]

Here is views.py on API endpoint:

class RunsCreateAPIView(CreateAPIView):
    queryset = Run.objects.all()
    queryset = queryset.prefetch_related('chamber')
    serializer_class = RunsCreateSerializer
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        try:
            chamber = Chamber.objects.get(chamber_name=request.data["chamber"])
            request.data["chamber"] = chamber.id
        except:
            print("Invalid chamber name")

        serializer = RunsCreateSerializer(data=request.data)
        print(serializer)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors)

Now, I found I had to modify "create" on the views.py a little, as the sensor sends the Chamber as a string identifier. I then have to check that string against my Chambers table and retrieve the object instance, then modify the request data  to substitute the Chamber string for its ID on my DB. I'm not sure if that is the right approach but it worked for me then.

Now for my attempt at fixing this:

On serializers.py:

def create(self, validated_data):
    run, created = Run.objects.update_or_create(
                    chamber=validated_data.get('chamber'),
                    start_time=validated_data.get('start_time'),
                    end_time=validated_data.get('end_time'))
    return run

def update(self, run, validated_data):
    run.chamber = validated_data.get('chamber', run.chamber)
    run.start_time = validated_data.get('start_time', run.start_time)
    run.created = validated_data.get('created', run.created)
    run.save()
    return run

I thought by doing this on my serializer I would be able to update the object, but it doesn't seem to be reaching that point (tried with a print("Sanity check") on the create and update methods, I don't see my sanity check output, so I know I'm not reaching that point).

I suspect it has to do with me overriding the create method on the view, but I'm not sure.

If you know how to update the object, and possibly have the serializer/view handle a string for Chamber name instead of having to meddle with methods to replace strings for IDs, I would greatly appreciate your help.

Body:
As you mentioned that you are getting chamber as a string, so to handle that relationship properly, use chamber = serializer.StringRelatedField() in your serializer. Remove any method which you have overridden in serializer/view. Just add the following in your RunsCreateAPIView.

def perform_create(self, serializer):
    chamber=serializer.validated_data.get('chamber'),
    start_time=serializer.validated_data.get('start_time')
    end_time=serializer.validated_data.get('end_time')
    Run.objects.update_or_create(
                  chamber=chamber,
                  start_time=start_time,
                  defaults = {"end_time": end_time}
                  )

update_or_create will automatically handle the creation or updating based on the value of chamber and start_time.


问:
Pandas - change in value to negative with a specific condition for particular groups of values
I have an example of a df that looks like this:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       10
4    2     100%    100      100
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

Each row is divided into groups - in this case groups from 1 to 3 - the number of groups is different, but this does not matter.

I would like all elements in df[0] being number and % sign (e.g. 10% or 100%) to change their value in Total column to negative values

An example of such a solution:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10    <--- change the value here
4    2     100%    100      -100   <--- change the value here
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

as far as I can pull this off, I don't know how to change these values. I've tried that way:

df[df[0].str.contains('\d%', regex= True, na=False)]

This way I have all the rows in which the value of df[0] have these requirements - the problem is that I don't know how to change their value in the Total column to negative. I tried that, but it doesn't help and there are errors:

df['Total'] = np.where(df[df[0].str.contains('\d%', regex= True, na=False)], df['Total'] *= -1,  df['Total'])

In addition, I would like to change the value df[0] == SUM  to a negative value but only when all the elements in the same group as SUM were values that met the previous requirements.

Example:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10
4    2     100%    100      -100
5    2     SUM     110      -110   <--- here should be a negative value - they are in the same group
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

if in a given group (in this case group 2) there are values which for df[0] contain only a number and a sign of percentage, then their values for the Total column should be negative. Additionally, if all rows in the group meet this condition (these are numbers with a percentage sign) then for df[0] == SUM the value in Total column should also change the sign.

How to connect it to such a regex? How to make SUM dependence in a given group on previous values in same group?

答:
Use:</p>

```<code>#test number with %
m = df[0].str.contains('\d%', regex= True, na=False)

#multiple if matched condition
df.loc[m, 'Total'] *= -1

#test if all values without last are matched m condition
m1 = m.groupby(df['Group']).transform(lambda x: x[:-1].all())

#multiple last value of group if matched m1 and not matched m
df.loc[m1 & ~m, 'Total'] *= -1
print (df)
   Group      0    1  Total
0      1   Text    5      5
1      1  Text2    5      5
2      1    SUM   10     10
3      2    10%   10    -10
4      2   100%  100   -100
5      2    SUM  110   -110
6      3  Text3    4      4
7      3    SUM    4      4
</code>```

Body:
I have an example of a df that looks like this:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       10
4    2     100%    100      100
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4

Each row is divided into groups - in this case groups from 1 to 3 - the number of groups is different, but this does not matter.

I would like all elements in df[0] being number and % sign (e.g. 10% or 100%) to change their value in Total column to negative values

An example of such a solution:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10    <--- change the value here
4    2     100%    100      -100   <--- change the value here
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4

as far as I can pull this off, I don't know how to change these values. I've tried that way:

df[df[0].str.contains('\d%', regex= True, na=False)]

This way I have all the rows in which the value of df[0] have these requirements - the problem is that I don't know how to change their value in the Total column to negative. I tried that, but it doesn't help and there are errors:

df['Total'] = np.where(df[df[0].str.contains('\d%', regex= True, na=False)], df['Total'] *= -1,  df['Total'])

In addition, I would like to change the value df[0] == SUM  to a negative value but only when all the elements in the same group as SUM were values that met the previous requirements.

Example:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10
4    2     100%    100      -100
5    2     SUM     110      -110   <--- here should be a negative value - they are in the same group
6    3     Text3   4        4
7    3     SUM     4        4

if in a given group (in this case group 2) there are values which for df[0] contain only a number and a sign of percentage, then their values for the Total column should be negative. Additionally, if all rows in the group meet this condition (these are numbers with a percentage sign) then for df[0] == SUM the value in Total column should also change the sign.

How to connect it to such a regex? How to make SUM dependence in a given group on previous values in same group?

Body:
Use:

#test number with %
m = df[0].str.contains('\d%', regex= True, na=False)

#multiple if matched condition
df.loc[m, 'Total'] *= -1

#test if all values without last are matched m condition
m1 = m.groupby(df['Group']).transform(lambda x: x[:-1].all())

#multiple last value of group if matched m1 and not matched m
df.loc[m1 & ~m, 'Total'] *= -1
print (df)
   Group      0    1  Total
0      1   Text    5      5
1      1  Text2    5      5
2      1    SUM   10     10
3      2    10%   10    -10
4      2   100%  100   -100
5      2    SUM  110   -110
6      3  Text3    4      4
7      3    SUM    4      4


问:
ServiceNow to Circuit Integration
Use Case scenario :

In case of Priority 1 incident in ServiceNow, we need to automate the system to start a conference meeting with pre-determined users in Circuit application.

REST API to create conversation is available but not to start conference.

We need to avoid manual intervention and to auto start the conference on creation of Priority 1 incident.

Queries :

1) Kindly advise if there is any way we can achieve this or circuit team will have some development plan to develop API to auto start conference.

2) If we use JS SDK, which have functionality available to create and start conference, so do we need to login every time while starting the conference from ServiceNow.

3) For JS SDK (implicit grant type), how authorization works for end user. How client id generated in circuit will be used for each end user. Can end user user their own circuit credentials to create and start conference.

4) When I use JS SDK to start conference, conference is getting started in my ServiceNow application then I need to pull request is Circuit application. Is there any way we can directly start conference in Circuit application.

答:
There is an undocumented REST API (/remote/call/start) to start a call on the user's webclient or desktop client. Note that this API is undocumented which means there is no guaranteed backwards compatibility, but it will likely remain backwards compatible. The destClientId can be used to start the call on a specific device.
E.g. If the user has the desktop client and web client running you could specify which one. If not provided but the user is logged on to multiple devices, then a prompt will be shown to start the call. Use API /telephony/deviceInfos to get the destClientIds.

    await this.axios.post('/remote/call/start',{
      mediaType: 'audio',  // audio, video or telephony
      destClientId: ...,   // optional. client id of user's device to start call on
      emailAddress: ...,   // email of user to call, only for direct call
      phoneNumber: ...,    // dialabe phone number
      convId: ...          // conversation ID, used for group calls
    });
```

<ol start="2">
<li><p>If the user still has a circuit session (30 days if the user uses Circuit clients with "private computer" checked) and the the access token is still valid according to TTL setting in application registration, then the JS SDK can logon without the user having to enter any credentials, or to accept permissions. logonCheck can be used to automatically login. </p></li>
<li><p>re what you question is here. For implicit, the clientId for the application is hardcoded in the application JS code. But since the client_id is restricted to be used on the registered domains, nobody else can use your client_id. The logon is shown the circuit-sdk github page:</p></li>
</ol>

<pre class="lang-js prettyprint-override"><code>    const client = new Circuit.Client({
      client_id: '<your client_id>',
      domain: '<circuit domain>  // e.g. circuitsandbox.net
    });
    const user = await client.logon();
</code>```

Yes, use API startConference and pass the clientId (aka destClientId) of the client you wish to start the call at. Use getDevices to find the user's clientIds. This is the same as the REST API described in #1 above.

Title: ServiceNow to Circuit Integration

Body:
There is an undocumented REST API (/remote/call/start) to start a call on the user's webclient or desktop client. Note that this API is undocumented which means there is no guaranteed backwards compatibility, but it will likely remain backwards compatible. The destClientId can be used to start the call on a specific device.
E.g. If the user has the desktop client and web client running you could specify which one. If not provided but the user is logged on to multiple devices, then a prompt will be shown to start the call. Use API /telephony/deviceInfos to get the destClientIds.

    await this.axios.post('/remote/call/start',{
      mediaType: 'audio',  // audio, video or telephony
      destClientId: ...,   // optional. client id of user's device to start call on
      emailAddress: ...,   // email of user to call, only for direct call
      phoneNumber: ...,    // dialabe phone number
      convId: ...          // conversation ID, used for group calls
    });

If the user still has a circuit session (30 days if the user uses Circuit clients with "private computer" checked) and the the access token is still valid according to TTL setting in application registration, then the JS SDK can logon without the user having to enter any credentials, or to accept permissions. logonCheck can be used to automatically login.

re what you question is here. For implicit, the clientId for the application is hardcoded in the application JS code. But since the client_id is restricted to be used on the registered domains, nobody else can use your client_id. The logon is shown the circuit-sdk github page:

    const client = new Circuit.Client({
      client_id: '<your client_id>',
      domain: '<circuit domain>  // e.g. circuitsandbox.net
    });
    const user = await client.logon();

Yes, use API startConference and pass the clientId (aka destClientId) of the client you wish to start the call at. Use getDevices to find the user's clientIds. This is the same as the REST API described in #1 above.


问:
how to change the column value based on other column value in data frame?
I am trying to change one column value based on other columns value. Can you please help me how to do this?

Example:

```<code>priority     comb_fld_order       start_bracs     end_bracs
1                                   (
1.1
2.3           1                     (
2.3.1         1                                      )
3.7                                                  )
</code>```

Expected Output:

```<code>priority     comb_fld_order       start_bracs     end_bracs
1
1.1
2.3           1                     (
2.3.1         1                                      )
3.7
</code>```

Means if comb_fld_order is null then we should to remove brackets from start_bracs and end_bracs column.

答:
You can create a boolean mask using Series.eq, then use  Series.where to replace the values based on condition:

```<code>m = df['comb_fld_order'].eq('')
df['start_bracs'] = df['start_bracs'].where(~m, '')
df['end_bracs'] = df['end_bracs'].where(~m, '')
</code>```

Result:

```<code># print(df)

  priority comb_fld_order start_bracs end_bracs
0        1
1      1.1
2      2.3              1           (
3    2.3.1              1                     )
4      3.7
</code>```

Body:
I am trying to change one column value based on other columns value. Can you please help me how to do this?

Example:

priority     comb_fld_order       start_bracs     end_bracs
1                                   (
1.1
2.3           1                     (
2.3.1         1                                      )
3.7                                                  )

Expected Output:

priority     comb_fld_order       start_bracs     end_bracs
1
1.1
2.3           1                     (
2.3.1         1                                      )
3.7

Means if comb_fld_order is null then we should to remove brackets from start_bracs and end_bracs column.

Body:
You can create a boolean mask using Series.eq, then use  Series.where to replace the values based on condition:

m = df['comb_fld_order'].eq('')
df['start_bracs'] = df['start_bracs'].where(~m, '')
df['end_bracs'] = df['end_bracs'].where(~m, '')

Result:

# print(df)

  priority comb_fld_order start_bracs end_bracs
0        1
1      1.1
2      2.3              1           (
3    2.3.1              1                     )
4      3.7


问:
error: dereferencing pointer to incomplete type - C language
A few days ago I made a function, which worked just fine. This is struct defining I used.

```<code>typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;
</code>```

Then I have this function

```<code>void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next;
        }
        printf("Middle is: %d", first->data);
    }
}
</code>```

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine

答:
In  this typedef declaration of a structure

```<code>typedef struct {
    int data;
    struct Node * next;
} Node;
</code>```

the type struct Node is an incomplete type. That is the type name struct Node is introduced but not defined.

Pay attention that the typedef name Node and the type name struct Node name two different entities. The name Node names an unnamed structure while struct Node names a not yet defined structure.

It is obvious that you mean the following

```<code>typedef struct Node {
    int data;
    struct Node * next;
} Node;
</code>```

Body:
A few days ago I made a function, which worked just fine. This is struct defining I used.

typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;

Then I have this function

void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next;
        }
        printf("Middle is: %d", first->data);
    }
}

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine

Body:
In  this typedef declaration of a structure

typedef struct {
    int data;
    struct Node * next;
} Node;

the type struct Node is an incomplete type. That is the type name struct Node is introduced but not defined.

Pay attention that the typedef name Node and the type name struct Node name two different entities. The name Node names an unnamed structure while struct Node names a not yet defined structure.

It is obvious that you mean the following

typedef struct Node {
    int data;
    struct Node * next;
} Node;


问:
How can I have nested horizontal ScrollViews in React Native?
I saw that React Native offers nested vertical scroll-views from React Native Nested ScrollView Can`t Scroll on Android Device

The problem is that it doesn't seem to work on nested Horizontal ScrollViews on Android. See this code for an example:

https://snack.expo.io/@harrytravelchime/broken-horizontal-scroll

```<code>import React from 'react';
import _ from 'lodash';
import { View, ScrollView, StyleSheet, Text, SafeAreaView } from 'react-native';

export default class App extends React.PureComponent {
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView
          style={{ height: '100%', width: '100%' }}
          horizontal
          nestedScrollEnabled
        >
          <View style={{ flexDirection: 'row' }}>
            <ScrollView
              style={{ width: 200, height: '100%' }}
              horizontal
              nestedScrollEnabled
            >
              <View style={{ flexDirection: 'row' }}>
                {_.times(200, n => (
                  <View key={1000 + n} style={{ marginRight: 10 }}>
                    <Text>{1000 + n}</Text>
                  </View>
                ))}
              </View>
            </ScrollView>
            {_.times(200, n => (
              <View key={n} style={{ marginRight: 10 }}>
                <Text>{n}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
    paddingVertical: 50,
  },
});
</code>```

On the other hand, the same code except with vertical scrolling totally works:
https://snack.expo.io/@harrytravelchime/working-vertical-scroll

Is there a way to make nested horizontal scrolling work?

答:
There is one more easier solution if you are using react-native-gesture-handler

```<code>import { ScrollView } from 'react-native'
import { ScrollView as GestureHandlerScrollView } from 'react-native-gesture-handler'

<ScrollView horizontal>
    <GestureHandlerScrollView horizontal />
</ScrollVIew>
</code>```

I got this answer from react-native github issue

Body:
I saw that React Native offers nested vertical scroll-views from React Native Nested ScrollView Can`t Scroll on Android Device

The problem is that it doesn't seem to work on nested Horizontal ScrollViews on Android. See this code for an example:

https://snack.expo.io/@harrytravelchime/broken-horizontal-scroll

import React from 'react';
import _ from 'lodash';
import { View, ScrollView, StyleSheet, Text, SafeAreaView } from 'react-native';

export default class App extends React.PureComponent {
  render() {
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView
          style={{ height: '100%', width: '100%' }}
          horizontal
          nestedScrollEnabled
        >
          <View style={{ flexDirection: 'row' }}>
            <ScrollView
              style={{ width: 200, height: '100%' }}
              horizontal
              nestedScrollEnabled
            >
              <View style={{ flexDirection: 'row' }}>
                {_.times(200, n => (
                  <View key={1000 + n} style={{ marginRight: 10 }}>
                    <Text>{1000 + n}</Text>
                  </View>
                ))}
              </View>
            </ScrollView>
            {_.times(200, n => (
              <View key={n} style={{ marginRight: 10 }}>
                <Text>{n}</Text>
              </View>
            ))}
          </View>
        </ScrollView>
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'stretch',
    paddingVertical: 50,
  },
});

On the other hand, the same code except with vertical scrolling totally works:
https://snack.expo.io/@harrytravelchime/working-vertical-scroll

Is there a way to make nested horizontal scrolling work?

Body:
There is one more easier solution if you are using react-native-gesture-handler

import { ScrollView } from 'react-native'
import { ScrollView as GestureHandlerScrollView } from 'react-native-gesture-handler'

<ScrollView horizontal>
    <GestureHandlerScrollView horizontal />
</ScrollVIew>

I got this answer from react-native github issue


问:
Deploying react app to heroku giving H10 error code
I've created a react app using create-react-app.It is working well in my local server.But when I tried to deploy it to heroku it is crashing.I don't know why it is crashing.

In heroku logs --tail its showing error code=H10 desc=App crashed.I searched about this issue and nothing helpful for me.

My question is similar to this question : React app runs locally, crashes when on Heroku error code=H10

But I'm unable to understand the solution they given.

My package.json file is as follows:

```<code>{
  "name": "lets-chat",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/free-regular-svg-icons": "^5.13.0",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "dotenv": "^8.2.0",
    "firebase": "^7.14.0",
    "moment": "^2.24.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

I don't know what's wrong in this file.Should I make any changes in this file to get my problem solved?

heroku logs --tail gave the report as follows:

答:
I also had same issue. I could figure out it is something to do with react version.
I changed the version and it worked. Update your version in package.json and see if it works.</p>

```<code>"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0"
</code>```

Body:
I've created a react app using create-react-app.It is working well in my local server.But when I tried to deploy it to heroku it is crashing.I don't know why it is crashing.

In heroku logs --tail its showing error code=H10 desc=App crashed.I searched about this issue and nothing helpful for me.

My question is similar to this question : React app runs locally, crashes when on Heroku error code=H10

But I'm unable to understand the solution they given.

My package.json file is as follows:

{
  "name": "lets-chat",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-brands-svg-icons": "^5.13.0",
    "@fortawesome/free-regular-svg-icons": "^5.13.0",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "dotenv": "^8.2.0",
    "firebase": "^7.14.0",
    "moment": "^2.24.0",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

I don't know what's wrong in this file.Should I make any changes in this file to get my problem solved?

heroku logs --tail gave the report as follows:

Body:
I also had same issue. I could figure out it is something to do with react version.
I changed the version and it worked. Update your version in package.json and see if it works.

"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.2.0"


问:
String validation in basic chess model
I get a string which size is 16 (location of chess pieces on the mini-chess-board). This string may contain only symbols:

K (king)

P (pawn)

N(knight)

R(rook)

B(bishop)

Q (queen)

and whitespaces (free field).

How can i validate this string with regex to check if string size is really 16, symbols are only of these and also it should necessarily contain one K symbol (because one King should be)

I tried [KQBNRP ]{16} but now cant check for a K symbol

Thank you

答:
As you know exactly which chars are allowed, you could use a single positive lookahead assertion for a single occurrence of K

Then match any of the listed 16 times using your pattern [KQBNRP ]{16}

```<code>^(?=[QBNRP ]*K[QBNRP ]*$)[KQBNRP ]{16}$
</code>```

Regex demo

Explanation

^ Start of string

(?= Positive lookahead, assert that form the current position what is on the right is

[QBNRP ]*K[QBNRP ]*$ Match a K between what is in the character class except for the K

) Close the group

[KQBNRP ]{16} Match 16 times any of the listed

$ End of string

Title: String validation in basic chess model

Body:
As you know exactly which chars are allowed, you could use a single positive lookahead assertion for a single occurrence of K

Then match any of the listed 16 times using your pattern [KQBNRP ]{16}

^(?=[QBNRP ]*K[QBNRP ]*$)[KQBNRP ]{16}$

Regex demo

Explanation

^ Start of string

(?= Positive lookahead, assert that form the current position what is on the right is

[QBNRP ]*K[QBNRP ]*$ Match a K between what is in the character class except for the K

) Close the group

[KQBNRP ]{16} Match 16 times any of the listed

$ End of string


问:
Why is there a warp-level synchronization primitive in CUDA?
I have two questions regarding __syncwarp() in CUDA:

If I understand correctly, a warp in CUDA is executed in an SIMD fasion. Does that not imply that all threads in a warp are always synchronized? If so, what exactly does __syncwarp() do, and why is it necessary?

Say we have a kernel launched with a block size of 1024, where the threads within a block are divided into groups of 32 threads each. Each thread communicates with other threads in it's group via shared memory, but does not communicate with any thread outside it's group. In such a kernel, I can see how a more granular synchronization than __syncthreads() may be useful, but since the warps the block is split into may not match with the groups, how would one guarantee correctness when using __syncwarp()?

答:
If I understand correctly, a warp in CUDA is executed in an SIMD fasion. Does that not imply that all threads in a warp are always synchronized?

No. There can be warp level execution divergence (usually branching, but can be other things like warp shuffles, voting, and predicated execution), handled by instruction replay or execution masking. Note that in "modern" CUDA, implicit warp synchronous programming is no longer safe, thus warp level synchronization is not just desirable, it is mandatory.

If so, what exactly does __syncwarp() do, and why is it necessary?

Because there can be warp level execution divergence, and this is how synchronization within a divergent warp is achieved.

Say we have a kernel launched with a block size of 1024, where the threads within a block are divided into groups of 32 threads each. Each thread communicates with other threads in it's group via shared memory, but does not communicate with any thread outside it's group. In such a kernel, I can see how a more granular synchronization than __syncthreads() may be useful, but since the warps the block is split into may not match with the groups, how would one guarantee correctness when using __syncwarp()?

By ensuring that the split is always performed explicitly using calculated warp boundaries (or a suitable thread mask).


问:
Transform dataframe in specific way
I have a dataframe:

```<code>ID Name Value
1  A    5%
2  B    7%
3  C    mean - 14.1, variance - 1.16
4  D    mean - 7.15, variance - 1.62
5  E    mean - 8.32, variance - 2.56
</code>```

I want to transform that dataframe, so it looks like this:

```<code>ID Name Type        Value
1  A    value        5
2  B    value        7
3  C    mean        14.1
3  C    variance    1.16
4  D    mean        7.15
4  D    variance    1.62
5  E    mean        8.32
5  E    variance    2.56
</code>```

So as you see, i added a column type with type of value of the row. When it has value with percent it has type value, and when it has value mean and variance, it must be separated into two rows with type mean and type variance. How could i do that?

Data in dput format.

```<code>df1 <-
structure(list(ID = 1:5, Name = c("A", "B", "C", "D", "E"),
Value = c("5%", "7%", "mean - 14.1, variance - 1.16",
"mean - 7.15, variance - 1.62", "mean - 8.32, variance - 2.56")),
class = "data.frame", row.names = c(NA, -5L))
</code>```

答:
We can bring the data into separate rows splitting on comma (,), separate the columns into two columns on '-' and get the data in numeric form.

```<code>library(dplyr)
library(tidyr)

df1 %>%
  separate_rows(Value, sep = ',') %>%
  separate(Value, c('Type', 'Value'), sep = '\\s+-\\s+', fill = "left") %>%
  mutate(Type = replace(Type, is.na(Type), 'value'),
         Value = readr::parse_number(Value)))

#  ID Name      Type Value
#1  1    A     value  5.00
#2  2    B     value  7.00
#3  3    C      mean 14.10
#4  3    C  variance  1.16
#5  4    D      mean  7.15
#6  4    D  variance  1.62
#7  5    E      mean  8.32
#8  5    E  variance  2.56
</code>```

Title: Transform dataframe in specific way

Body:
I have a dataframe:

ID Name Value
1  A    5%
2  B    7%
3  C    mean - 14.1, variance - 1.16
4  D    mean - 7.15, variance - 1.62
5  E    mean - 8.32, variance - 2.56

I want to transform that dataframe, so it looks like this:

ID Name Type        Value
1  A    value        5
2  B    value        7
3  C    mean        14.1
3  C    variance    1.16
4  D    mean        7.15
4  D    variance    1.62
5  E    mean        8.32
5  E    variance    2.56

So as you see, i added a column type with type of value of the row. When it has value with percent it has type value, and when it has value mean and variance, it must be separated into two rows with type mean and type variance. How could i do that?

Data in dput format.

df1 <-
structure(list(ID = 1:5, Name = c("A", "B", "C", "D", "E"),
Value = c("5%", "7%", "mean - 14.1, variance - 1.16",
"mean - 7.15, variance - 1.62", "mean - 8.32, variance - 2.56")),
class = "data.frame", row.names = c(NA, -5L))

Body:
We can bring the data into separate rows splitting on comma (,), separate the columns into two columns on '-' and get the data in numeric form.

library(dplyr)
library(tidyr)

df1 %>%
  separate_rows(Value, sep = ',') %>%
  separate(Value, c('Type', 'Value'), sep = '\\s+-\\s+', fill = "left") %>%
  mutate(Type = replace(Type, is.na(Type), 'value'),
         Value = readr::parse_number(Value)))

#  ID Name      Type Value
#1  1    A     value  5.00
#2  2    B     value  7.00
#3  3    C      mean 14.10
#4  3    C  variance  1.16
#5  4    D      mean  7.15
#6  4    D  variance  1.62
#7  5    E      mean  8.32
#8  5    E  variance  2.56


问:
categoryChoiceTree in prestashop module configuration page
I'm developing a prestashop module and I'm trying to show a category tree in my backoffice configuration page.

I'm trying to follow this instructions below but  I don't know exactly where to add this code.

It should be inside main module's php? or inside a separate .php file and call it from the main one (don't know how to do it either).

As much time I'm spending trying to figure out, how to implement the code in the link above, the more I think I'm losing my time.
I see that "use" files, and this JS, " /admin-dev/themes/new-theme/js/components/form/choice-tree.js " are not in any prestashop folders.

答:
The only way that I found to "paint" the categorytree in my configuration page is adding this code to the inputs form array:

Can anyone tell me how to retrieve users selection data to my database?
It does not work as any other form field.

```<code>array(
                            'type' => 'categories',
                            'label' => $this->l('Destination Category'),
                            'desc' => $this->l('Select ONE Category'),
                            'name' => 'CATEGORY_CATEGORY_TO',
                            'tree' => [
                                // 'selected_categories' => [],
                                'disabled_categories' => null,
                                'use_search' => false,
                                'use_checkbox' => false,
                                'id' => 'id_category_tree',
                            ],
                            'required' => true
                        ),
</code>```

Body:
The only way that I found to "paint" the categorytree in my configuration page is adding this code to the inputs form array:

Can anyone tell me how to retrieve users selection data to my database?
It does not work as any other form field.

array(
                            'type' => 'categories',
                            'label' => $this->l('Destination Category'),
                            'desc' => $this->l('Select ONE Category'),
                            'name' => 'CATEGORY_CATEGORY_TO',
                            'tree' => [
                                // 'selected_categories' => [],
                                'disabled_categories' => null,
                                'use_search' => false,
                                'use_checkbox' => false,
                                'id' => 'id_category_tree',
                            ],
                            'required' => true
                        ),


问:
JSON Invalid UTF-8 middle byte
This error happens when the (Jackson, this case) JSON engine tries to parse some JSON that is not encoded in UTF-8.

How to tell the engine that it should expect something different from UTF-8, such as UTF-16?

```<code>HttpHeaders requestHeaders = createSomeHeader();
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
String url = "someurl"
ResponseEntity<MyObject[]> arrayResponseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyObject[].class);
</code>```

error log:

```<code>Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]; nested exception is org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:138)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:74)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:622)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:608)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:449)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:404)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:380)
... 4 more
Caused by: org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2132)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2139)
at org.codehaus.jackson.impl.Utf8StreamParser._decodeUtf8_3fast(Utf8StreamParser.java:1962)
</code>```

答:
client text protocol

```<code>POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405

{
  "fwoid": 1,
  "list": [
    {
      "bomIndex": "10001",
      "desc": "带GH 1.25 13pin 公座带针 白色",
      "pn": "084.0001.0036",
      "preUse": 1,
      "type": "追觅 除螨仪-开关PCB组件"
    },
     {
      "bomIndex": "10002",
      "desc": "紫米音箱-商品码标签",
      "pn": "Z.08.013.0051",
      "preUse": 1,
      "type": "E060A0302301"
    }
  ]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40

{"code":"0","message":"BOM保存成功"}
</code>```

a springboot Controller code as below：

```<code>@PostMapping("/bom/create")
@ApiOperation(value = "保存BOM")
@BusinessOperation(module = "BOM",methods = "解析BOM")
public JsonResult save(@RequestBody BOMSaveQuery query)
{
    return bomService.saveBomList(query);
}
</code>```

when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error

```<code>ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}
</code>```

add a jvm arguement works for me.
java -Dfile.encoding=UTF-8

Title: JSON Invalid UTF-8 middle byte

Body:
This error happens when the (Jackson, this case) JSON engine tries to parse some JSON that is not encoded in UTF-8.

How to tell the engine that it should expect something different from UTF-8, such as UTF-16?

HttpHeaders requestHeaders = createSomeHeader();
RestTemplate restTemplate = new RestTemplate();
HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
String url = "someurl"
ResponseEntity<MyObject[]> arrayResponseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyObject[].class);

error log:

Caused by: org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]; nested exception is org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]
at org.springframework.http.converter.json.MappingJacksonHttpMessageConverter.readInternal(MappingJacksonHttpMessageConverter.java:138)
at org.springframework.http.converter.AbstractHttpMessageConverter.read(AbstractHttpMessageConverter.java:154)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:74)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:622)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:608)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:449)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:404)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:380)
... 4 more
Caused by: org.codehaus.jackson.JsonParseException: Invalid UTF-8 middle byte 0x20
at [Source: org.apache.http.conn.EofSensorInputStream@44d397b0; line: 92, column: 42]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2132)
at org.codehaus.jackson.impl.Utf8StreamParser._reportInvalidOther(Utf8StreamParser.java:2139)
at org.codehaus.jackson.impl.Utf8StreamParser._decodeUtf8_3fast(Utf8StreamParser.java:1962)

Body:
client text protocol

POST http://127.0.0.1/bom/create HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.25.0
Accept: */*
Postman-Token: 50ecfbfe-741f-4a2b-a3d3-cdf162ada27f
Host: 127.0.0.1
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 405

{
  "fwoid": 1,
  "list": [
    {
      "bomIndex": "10001",
      "desc": "带GH 1.25 13pin 公座带针 白色",
      "pn": "084.0001.0036",
      "preUse": 1,
      "type": "追觅 除螨仪-开关PCB组件"
    },
     {
      "bomIndex": "10002",
      "desc": "紫米音箱-商品码标签",
      "pn": "Z.08.013.0051",
      "preUse": 1,
      "type": "E060A0302301"
    }
  ]
}
HTTP/1.1 200 OK
Connection: keep-alive
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Date: Mon, 01 Jun 2020 11:23:42 GMT
Content-Length: 40

{"code":"0","message":"BOM保存成功"}

a springboot Controller code as below：

@PostMapping("/bom/create")
@ApiOperation(value = "保存BOM")
@BusinessOperation(module = "BOM",methods = "解析BOM")
public JsonResult save(@RequestBody BOMSaveQuery query)
{
    return bomService.saveBomList(query);
}

when i debug on loopback interface,it works ok. while deploy on internet server via bat command, i got an error

ServletInvocableHandlerMethod - Could not resolve parameter [0] in public XXXController.save(com.h2.mes.query.BOMSaveQuery): JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Invalid UTF-8 middle byte 0x3f; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Invalid UTF-8 middle byte 0x3f
 at [Source: (PushbackInputStream); line: 9, column: 32] (through reference chain: com.h2.mes.query.BOMSaveQuery["list"]->java.util.ArrayList[0]->com.h2.mes.vo.BOMVO["type"])]
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - Completed 400 BAD_REQUEST
2020-06-01 15:37:50.251 MES [XNIO-1 task-13] DEBUG o.s.web.servlet.DispatcherServlet - "ERROR" dispatch for POST "/error", parameters={}

add a jvm arguement works for me.
java -Dfile.encoding=UTF-8


问:
How to get the value of selected checkbox with specific name using jquery
i have this check box with different name but all the name start with checkUser

```<code><input type="checkbox" value="60176694447" name="checkUser52106">
<input type="checkbox" value="60176694448" name="checkUser52107">
<input type="checkbox" value="60176694449" name="checkUser52108">
</code>```

A quick google bring me this function from sitepoint

```<code>$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
  val[i] = $(this).val();
});
});
});
</code>```

Right now i want to get all the value of selected checkbox with name start with checkUser. How to achieve this?

答:
Use the attribute startsWith selector:

```<code>$(':checkbox[name^="checkUser"]:checked').each(function(i){
    val[i] = $(this).val();
});
</code>```

You can use .map instead for a shorter solution:

```<code>var val = $(':checkbox[name^="checkUser"]:checked').map(function(){
    return this.value;
}).get();
</code>```

Body:
i have this check box with different name but all the name start with checkUser

<input type="checkbox" value="60176694447" name="checkUser52106">
<input type="checkbox" value="60176694448" name="checkUser52107">
<input type="checkbox" value="60176694449" name="checkUser52108">

A quick google bring me this function from sitepoint

$(function(){
$('#btnClick').click(function(){
var val = [];
$(':checkbox:checked').each(function(i){
  val[i] = $(this).val();
});
});
});

Right now i want to get all the value of selected checkbox with name start with checkUser. How to achieve this?

Body:
Use the attribute startsWith selector:

$(':checkbox[name^="checkUser"]:checked').each(function(i){
    val[i] = $(this).val();
});

You can use .map instead for a shorter solution:

var val = $(':checkbox[name^="checkUser"]:checked').map(function(){
    return this.value;
}).get();


问:
How to get result of promise from angular service with Ionic storage, instead of Promise<any> in response
I'm using Ionic Storage for local storage purpose.
To work with storage I've created service, where I've getter and setter storage methods.

I want to check on load of application that, if any value is available on storage or not, if value is not available in storage than only want to make actual data call and will set to storage, but next time on wards want to read from storage rather than making actual get call for data.

Now problem is when my component gets load, I'm calling service's storage.get method which takes time and because of that component's property is not getting seted with actual storage's correct value.

Also, method used to return string value form service is not allowing to write method without final return statement as mentioned in code below [right now I've added two return statement from Promise, which doesn't seems correct design to me, but without it i'm getting compilation error], and both return statements gets executed at different interval of time due to time taken by Promise to get response from storage, which yields overtiring of actual response from storage.

I'm not sure how to manage such scenario from promise, as Ionic storage by default returns Promise.

```<code> getDefaultLanguage(): string {

     this.storage.get('defaultLanguage').then((res) => {
       return this.defaultLanguage = res || 'en';
     });
     return this.defaultLanguage;
   }
</code>```

Please let me know how I can hold execution in component until I get response from above service call with Promise, so core component's logic can work properly, also wanted correct way to implement service layer where I want result as string from Promise instead of promise<any>.

答:
Thanks @Nenroz and @mwilson for both of your answers.

It helps me understands how Promise actually works, I was rather looking for single service method which directly returns me string value from Promise and also wanted to wait for further code execution until than.

As, front-end framework react to change itself, so instead of actual ask for this question to wait till getting value from Promise,
I'd find a way to manage to hold UI until Promise get resolves as below. (without awaiting further code execution)

added method InitStorage() in app.component.ts's constructor

```<code> InitStorage() {
     const defLanguage = this.storageService.getDefaultLanguage();
 }
</code>```

StorageService.ts's method as below to return Promise<string>

```<code> getDefaultLanguage(): Promise<string> {
     return this.storage.get('defaultLanguage');
 }
</code>```

Now to wait till getting value from above method and stop further code execution until promise gets resolved, added its implementation in ngOnInit in page.ts

```<code> ngOnInit() {
      this.defaultLanguage = this.storageService.defaultLanguage;
 }
</code>```

and added its value in page.html file, so once value is available in variable html can refreshed/set by framework, previously I was not able to bind its value in HTML (previously Value was getting sated after Page was getting loaded, and UI was not getting updated)

```<code> <ion-radio-group [value]="defaultLanguage" />
</code>```

I'm not sure if this correct architecture of service and Promise in Angular, but this is how I managed to get Storage value in service and able to update UI with correct storage value when sated in variable.

Looking forward to any further suggestion for architectural improvement and thanks for all valuable suggestions.

Body:
I'm using Ionic Storage for local storage purpose.
To work with storage I've created service, where I've getter and setter storage methods.

I want to check on load of application that, if any value is available on storage or not, if value is not available in storage than only want to make actual data call and will set to storage, but next time on wards want to read from storage rather than making actual get call for data.

Now problem is when my component gets load, I'm calling service's storage.get method which takes time and because of that component's property is not getting seted with actual storage's correct value.

Also, method used to return string value form service is not allowing to write method without final return statement as mentioned in code below [right now I've added two return statement from Promise, which doesn't seems correct design to me, but without it i'm getting compilation error], and both return statements gets executed at different interval of time due to time taken by Promise to get response from storage, which yields overtiring of actual response from storage.

I'm not sure how to manage such scenario from promise, as Ionic storage by default returns Promise.

 getDefaultLanguage(): string {

     this.storage.get('defaultLanguage').then((res) => {
       return this.defaultLanguage = res || 'en';
     });
     return this.defaultLanguage;
   }

Please let me know how I can hold execution in component until I get response from above service call with Promise, so core component's logic can work properly, also wanted correct way to implement service layer where I want result as string from Promise instead of promise<any>.

Body:
Thanks @Nenroz and @mwilson for both of your answers.

It helps me understands how Promise actually works, I was rather looking for single service method which directly returns me string value from Promise and also wanted to wait for further code execution until than.

As, front-end framework react to change itself, so instead of actual ask for this question to wait till getting value from Promise,
I'd find a way to manage to hold UI until Promise get resolves as below. (without awaiting further code execution)

added method InitStorage() in app.component.ts's constructor

 InitStorage() {
     const defLanguage = this.storageService.getDefaultLanguage();
 }

StorageService.ts's method as below to return Promise<string>

 getDefaultLanguage(): Promise<string> {
     return this.storage.get('defaultLanguage');
 }

Now to wait till getting value from above method and stop further code execution until promise gets resolved, added its implementation in ngOnInit in page.ts

 ngOnInit() {
      this.defaultLanguage = this.storageService.defaultLanguage;
 }

and added its value in page.html file, so once value is available in variable html can refreshed/set by framework, previously I was not able to bind its value in HTML (previously Value was getting sated after Page was getting loaded, and UI was not getting updated)

 <ion-radio-group [value]="defaultLanguage" />

I'm not sure if this correct architecture of service and Promise in Angular, but this is how I managed to get Storage value in service and able to update UI with correct storage value when sated in variable.

Looking forward to any further suggestion for architectural improvement and thanks for all valuable suggestions.


问:
vscode built-in commands : "vscode.executeDocumentSymbolProvider" command not returning all symbols in the document
I'm writing an extension for vscode in typescript.

At some point I need to find all symbols declared in a document (the document contains typescript code).

I'm using the built-in command "vscode.executeDocumentSymbolProvider" for that. But it returns only types and variables, ie, symbols declared with the keywords class, interface, const, let...etc. It doesn't return for example a parameter of a function. Is there a reason for that ?
I thought even parameters were symbols since a parameter can, for example, shadow a varaible declared in an outer scope.
Also, Is there another way to find all the symbols ?

答:
Since I figured it out I'll post an answer in case someone needs it in the future.

The command "vscode.executeDocumentSymbolProvider" does in fact return all the symbols. It's just that they are nested inside each others (tree like structure). See the "children" property of "vscode.DocumentSymbol" class.


问:
Is it a bad practice to catch the Throwable?
Is it a bad practice to catch Throwable?For example my code  something like this.But in sonar its showing as bug .How can we resolve this

code

```<code>try {
            return restTemplate.getForObject(urlSearchID, AccessIDSearchResponse.class);

        } catch (HttpServerErrorException hse) {
            AccesIdExceptionUtility.recoverFromHttpServerExc(hse);
        } catch (HttpClientErrorException hce) {
            AccesIdExceptionUtility.recoverFromHttpClientExc(hce);
        } catch (ClientException ce) {
            AccesIdExceptionUtility.recoverFromClientExc(ce);
        } catch (Exception e) {
            AccesIdExceptionUtility.recoverFromException(e);
        }
        catch (Throwable ex) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, ex.getMessage(), agentSearchUrl);
        }
        return null;
</code>```

答:
Yes, as a general rule, it's a bad idea.

You are catching Errors as well as Exceptions.  You almost certainly are not handling them correctly.  For example, you're mishandling ThreadDeath according to my reading of the documentation.  And your chances of doing anything useful on VirtualMachineError are slim to none.

Since recovery is unlikely, the effect is that you'll obfuscate the original problem, making your debugging life harder.

Body:
Is it a bad practice to catch Throwable?For example my code  something like this.But in sonar its showing as bug .How can we resolve this

code

try {
            return restTemplate.getForObject(urlSearchID, AccessIDSearchResponse.class);

        } catch (HttpServerErrorException hse) {
            AccesIdExceptionUtility.recoverFromHttpServerExc(hse);
        } catch (HttpClientErrorException hce) {
            AccesIdExceptionUtility.recoverFromHttpClientExc(hce);
        } catch (ClientException ce) {
            AccesIdExceptionUtility.recoverFromClientExc(ce);
        } catch (Exception e) {
            AccesIdExceptionUtility.recoverFromException(e);
        }
        catch (Throwable ex) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, ex.getMessage(), agentSearchUrl);
        }
        return null;


答:
error: dereferencing pointer to incomplete type

This means that the compiler couldn't find a definition of the struct within the translation unit where you made that access - it could only find a declaration. struct Node * next; is as it turns out, a pointer to a type that wasn't previously defined at the point where you declared it. Because it only becomes defined when the compiler reaches the }; of the struct.

For a self-referencing struct, you need to forward-declare the type in order to use it as a struct member. Depending on your coding style that either means:

```<code>typedef struct Node Node;

struct Node {
    int data;
    struct Node* next;  // also possible: Node* next;
};
</code>```

or

```<code>typedef struct Node {
    int data;
    struct Node* next;
} Node;
</code>```

(The type Node and the struct tag Node actually live in separate namespaces, but this is one of those things one need not ponder about - just do.)

Title: error: dereferencing pointer to incomplete type - C language

Body:
A few days ago I made a function, which worked just fine. This is struct defining I used.

typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;

Then I have this function

void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next;
        }
        printf("Middle is: %d", first->data);
    }
}

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine

Body:
error: dereferencing pointer to incomplete type

This means that the compiler couldn't find a definition of the struct within the translation unit where you made that access - it could only find a declaration. struct Node * next; is as it turns out, a pointer to a type that wasn't previously defined at the point where you declared it. Because it only becomes defined when the compiler reaches the }; of the struct.

For a self-referencing struct, you need to forward-declare the type in order to use it as a struct member. Depending on your coding style that either means:

typedef struct Node Node;

struct Node {
    int data;
    struct Node* next;  // also possible: Node* next;
};

or

typedef struct Node {
    int data;
    struct Node* next;
} Node;

(The type Node and the struct tag Node actually live in separate namespaces, but this is one of those things one need not ponder about - just do.)


问:
Netbeans 10.0  for simple Hello world program
Hi, I just installed Netbeans 10.0 and I can't run my Java project because apparently my main is missing but the class main is there!

I tried to right click the project and create a new main class but it didn't help.

the error

答:
Just find out how to fix the problem but i'm not sure if it's a real solution.
-Download JDK 10
-Open Netbeans >Tools>Java platform>add platform and select the JDK 10 folder
-Then disable the compile on save options in your project by doing right click on the project>proprieties>compiling and turn off the compile on save options

Always remember to set JDK 10 on your project by right click on your project>Proprieties>Libraries>And select JDK 10!

Title: Netbeans 10.0 <main classes not found> for simple Hello world program


问:
Python read next()
next() in python does not work. What is an alternative to reading next line in Python? Here is a sample:

```<code>filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

while 1:
    lines = f.readlines()
    if not lines:
        break
    for line in lines:
        print line
        if (line[:5] == "anim "):
            print 'next() '
            ne = f.next()
            print ' ne ',ne,'\n'
            break

f.close()
</code>```

Running this on a file does not show 'ne '.

答:
You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

```<code>filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()
</code>```

Title: Python read next()

Body:
next() in python does not work. What is an alternative to reading next line in Python? Here is a sample:

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

while 1:
    lines = f.readlines()
    if not lines:
        break
    for line in lines:
        print line
        if (line[:5] == "anim "):
            print 'next() '
            ne = f.next()
            print ' ne ',ne,'\n'
            break

f.close()

Running this on a file does not show 'ne '.

Body:
You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()


问:
finding semantic similarity between 2 statements
I am currently working with small application in python and my application has search functionality (currently using difflib) but I want to create Semantic Search which can give top 5 or 10 results from my database, based on user inputted text. It is same as google search engine works. I found some solutions Here.

But the problem is, below two statements from one of solution are semantically incorrect. And I don't care about this. because they are making things too hard which I don't want And also solution will be some pretrained neural network model or library from which I can implement easily.

Pete and Rob have found a dog near the station.

Pete and Rob have never found a dog near the station

And also I found some solutions which are showing using gensim and Glove embeddings and finding similarity between words and not sentences.

What I wanted ?

Suppose my db has statement display classes and user inputs show, showed, displayed, displayed class, show types etc are same. And if above 2 statements are given as same then also I don't care. displayed and displayed class already showing in difflib.

Points to be noted

Find from fixed set of statements but user inputted statements can differ

Must work for statements

答:
You can use wordnet for finding synonyms and then use these synonyms for finding similar statements.

import nltk
from nltk.corpus import wordnet as wn

nltk.download('wordnet')

def get_syn_list(gword):
  syn_list = []
  try:
    syn_list.extend(wn.synsets(gword,pos=wn.NOUN))
    syn_list.extend(wn.synsets(gword,pos=wn.VERB))
    syn_list.extend(wn.synsets(gword,pos=wn.ADJ))
    syn_list.extend(wn.synsets(gword,pos=wn.ADV))
  except :
    print("Something Wrong Happened")
  syn_words = []
  for i in syn_list:
    syn_words.append(i.lemmas()[0].name())
  return syn_words
```

<p>Now use <code>split</code> and split your statements in db. like this</p>

<pre class="lang-py prettyprint-override"><code>stat = ["display classes"]

syn_dict = {}
for i in stat:
   tmp = []
   for x in i.split(" "):
       tmp.extend(get_syn_list(x))
   syn_dict[i] = set(tmp)
</code>```

Now you have synonyms just compare them with inputted text. And use lemmatizer before comparing words so that displayed become display.

Body:
You can use wordnet for finding synonyms and then use these synonyms for finding similar statements.

import nltk
from nltk.corpus import wordnet as wn

nltk.download('wordnet')

def get_syn_list(gword):
  syn_list = []
  try:
    syn_list.extend(wn.synsets(gword,pos=wn.NOUN))
    syn_list.extend(wn.synsets(gword,pos=wn.VERB))
    syn_list.extend(wn.synsets(gword,pos=wn.ADJ))
    syn_list.extend(wn.synsets(gword,pos=wn.ADV))
  except :
    print("Something Wrong Happened")
  syn_words = []
  for i in syn_list:
    syn_words.append(i.lemmas()[0].name())
  return syn_words

Now use split and split your statements in db. like this

stat = ["display classes"]

syn_dict = {}
for i in stat:
   tmp = []
   for x in i.split(" "):
       tmp.extend(get_syn_list(x))
   syn_dict[i] = set(tmp)

Now you have synonyms just compare them with inputted text. And use lemmatizer before comparing words so that displayed become display.


问:
Mirror repository from Azure repos on GitLab
I need to mirror a repository in Azure Repos with a repository in GitLab (pull), on Gitlab it asks me to insert the repository URL (which I have) and it asks me for a password, I've tried with my outlook password and some credentials I created on Azure Repos, but none are working. Is there another password?

I had no problem mirroring from GitHub, but I haven't been able to do the same with Azure Repos, and I'd like to have everything on GitLab.

I'm trying this:
https://docs.gitlab.com/ee/workflow/repository_mirroring.html

Thanks!

答:
To add on previous solution. I was able to mirror without creating a token

For pull Request:

```<code>https://<username>@gitlab.com/group.project.git
</code>```

Username: your gitlab username
Password: your gitlab password

Try pulling the repo locally using this command

```<code>git clone https://<username>:<password>@gitlab.com/group/project.git
</code>```

If git clone works, then mirroring should work as well

Note :
that having an "@" in your password fails the git command. this is usual suspect

Body:
To add on previous solution. I was able to mirror without creating a token

For pull Request:

https://<username>@gitlab.com/group.project.git

Username: your gitlab username
Password: your gitlab password

Try pulling the repo locally using this command

git clone https://<username>:<password>@gitlab.com/group/project.git

If git clone works, then mirroring should work as well

Note :
that having an "@" in your password fails the git command. this is usual suspect